context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.Serialization;
namespace XenAPI
{
public partial class HTTP
{
[Serializable]
public class TooManyRedirectsException : Exception
{
private readonly int redirect;
private readonly Uri uri;
public TooManyRedirectsException(int redirect, Uri uri)
{
this.redirect = redirect;
this.uri = uri;
}
public TooManyRedirectsException() : base() { }
public TooManyRedirectsException(string message) : base(message) { }
public TooManyRedirectsException(string message, Exception exception) : base(message, exception) { }
protected TooManyRedirectsException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
redirect = info.GetInt32("redirect");
uri = (Uri)info.GetValue("uri", typeof(Uri));
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
info.AddValue("redirect", redirect);
info.AddValue("uri", uri, typeof(Uri));
base.GetObjectData(info, context);
}
}
[Serializable]
public class BadServerResponseException : Exception
{
public BadServerResponseException() : base() { }
public BadServerResponseException(string message) : base(message) { }
public BadServerResponseException(string message, Exception exception) : base(message, exception) { }
protected BadServerResponseException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
[Serializable]
public class CancelledException : Exception
{
public CancelledException() : base() { }
public CancelledException(string message) : base(message) { }
public CancelledException(string message, Exception exception) : base(message, exception) { }
protected CancelledException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
public delegate bool FuncBool();
public delegate void UpdateProgressDelegate(int percent);
public delegate void DataCopiedDelegate(long bytes);
// Size of byte buffer used for GETs and PUTs
// (not the socket rx buffer)
public const int BUFFER_SIZE = 32 * 1024;
public const int MAX_REDIRECTS = 10;
public const int DEFAULT_HTTPS_PORT = 443;
#region Helper functions
private static void WriteLine(String txt, Stream stream)
{
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(String.Format("{0}\r\n", txt));
stream.Write(bytes, 0, bytes.Length);
}
private static void WriteLine(Stream stream)
{
WriteLine("", stream);
}
private static string ReadLine(Stream stream)
{
System.Text.StringBuilder result = new StringBuilder();
while (true)
{
int b = stream.ReadByte();
if (b == -1)
throw new EndOfStreamException();
char c = Convert.ToChar(b);
result.Append(c);
if (c == '\n')
return result.ToString();
}
}
/// <summary>
/// Read HTTP headers, doing any redirects as necessary
/// </summary>
/// <param name="stream"></param>
/// <returns>True if a redirect has occurred - headers will need to be resent.</returns>
private static bool ReadHttpHeaders(ref Stream stream, IWebProxy proxy, bool nodelay, int timeout_ms)
{
string response = ReadLine(stream);
int code = getResultCode(response);
switch (code)
{
case 200:
break;
case 302:
string url = "";
while (true)
{
response = ReadLine(stream);
if (response.StartsWith("Location: "))
url = response.Substring(10);
if (response.Equals("\r\n") || response.Equals("\n") || response.Equals(""))
break;
}
Uri redirect = new Uri(url.Trim());
stream.Close();
stream = ConnectStream(redirect, proxy, nodelay, timeout_ms);
return true; // headers need to be sent again
default:
if (response.EndsWith("\r\n"))
response = response.Substring(0, response.Length - 2);
else if (response.EndsWith("\n"))
response = response.Substring(0, response.Length - 1);
stream.Close();
throw new BadServerResponseException(string.Format("Received error code {0} from the server", response));
}
while (true)
{
string line = ReadLine(stream);
if (System.Text.RegularExpressions.Regex.Match(line, "^\\s*$").Success)
break;
}
return false;
}
public static int getResultCode(string line)
{
string[] bits = line.Split(new char[] { ' ' });
return (bits.Length < 2 ? 0 : Int32.Parse(bits[1]));
}
public static bool UseSSL(Uri uri)
{
return uri.Scheme == "https" || uri.Port == DEFAULT_HTTPS_PORT;
}
private static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
public static long CopyStream(Stream inStream, Stream outStream,
DataCopiedDelegate progressDelegate, FuncBool cancellingDelegate)
{
long bytesWritten = 0;
byte[] buffer = new byte[BUFFER_SIZE];
DateTime lastUpdate = DateTime.Now;
while (cancellingDelegate == null || !cancellingDelegate())
{
int bytesRead = inStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
outStream.Write(buffer, 0, bytesRead);
bytesWritten += bytesRead;
if (progressDelegate != null &&
DateTime.Now - lastUpdate > TimeSpan.FromMilliseconds(500))
{
progressDelegate(bytesWritten);
lastUpdate = DateTime.Now;
}
}
if (cancellingDelegate != null && cancellingDelegate())
throw new CancelledException();
if (progressDelegate != null)
progressDelegate(bytesWritten);
return bytesWritten;
}
/// <summary>
/// Build a URI from a hostname, a path, and some query arguments
/// </summary>
/// <param name="args">An even-length array, alternating argument names and values</param>
/// <returns></returns>
public static Uri BuildUri(string hostname, string path, params object[] args)
{
// The last argument may be an object[] in its own right, in which case we need
// to flatten the array.
List<object> flatargs = new List<object>();
foreach (object arg in args)
{
if (arg is IEnumerable<object>)
flatargs.AddRange((IEnumerable<object>)arg);
else
flatargs.Add(arg);
}
UriBuilder uri = new UriBuilder();
uri.Scheme = "https";
uri.Port = DEFAULT_HTTPS_PORT;
uri.Host = hostname;
uri.Path = path;
StringBuilder query = new StringBuilder();
for (int i = 0; i < flatargs.Count - 1; i += 2)
{
string kv;
// If the argument is null, don't include it in the URL
if (flatargs[i + 1] == null)
continue;
// bools are special because some xapi calls use presence/absence and some
// use "b=true" (not "True") and "b=false". But all accept "b=true" or absent.
if (flatargs[i + 1] is bool)
{
if (!((bool)flatargs[i + 1]))
continue;
kv = flatargs[i] + "=true";
}
else
kv = flatargs[i] + "=" + Uri.EscapeDataString(flatargs[i + 1].ToString());
if (query.Length != 0)
query.Append('&');
query.Append(kv);
}
uri.Query = query.ToString();
return uri.Uri;
}
#endregion
private static NetworkStream ConnectSocket(Uri uri, bool nodelay, int timeout_ms)
{
AddressFamily addressFamily = uri.HostNameType == UriHostNameType.IPv6
? AddressFamily.InterNetworkV6
: AddressFamily.InterNetwork;
Socket socket =
new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.NoDelay = nodelay;
//socket.ReceiveBufferSize = 64 * 1024;
socket.ReceiveTimeout = timeout_ms;
socket.SendTimeout = timeout_ms;
socket.Connect(uri.Host, uri.Port);
return new NetworkStream(socket, true);
}
/// <summary>
/// This function will connect a stream to a uri (host and port),
/// negotiating proxies and SSL
/// </summary>
/// <param name="uri"></param>
/// <param name="timeout_ms">Timeout, in ms. 0 for no timeout.</param>
/// <returns></returns>
public static Stream ConnectStream(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms)
{
IMockWebProxy mockProxy = proxy != null ? proxy as IMockWebProxy : null;
if (mockProxy != null)
return mockProxy.GetStream(uri);
Stream stream;
bool useProxy = proxy != null && !proxy.IsBypassed(uri);
if (useProxy)
{
Uri proxyURI = proxy.GetProxy(uri);
stream = ConnectSocket(proxyURI, nodelay, timeout_ms);
}
else
{
stream = ConnectSocket(uri, nodelay, timeout_ms);
}
try
{
if (useProxy)
{
string line = String.Format("CONNECT {0}:{1} HTTP/1.0", uri.Host, uri.Port);
WriteLine(line, stream);
WriteLine(stream);
ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms);
}
if (UseSSL(uri))
{
SslStream sslStream = new SslStream(stream, false,
new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
sslStream.AuthenticateAsClient("", null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, true);
stream = sslStream;
}
return stream;
}
catch
{
stream.Close();
throw;
}
}
private static Stream DO_HTTP(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms, params string[] headers)
{
Stream stream = ConnectStream(uri, proxy, nodelay, timeout_ms);
int redirects = 0;
do
{
if (redirects > MAX_REDIRECTS)
throw new TooManyRedirectsException(redirects, uri);
redirects++;
foreach (string header in headers)
WriteLine(header, stream);
WriteLine(stream);
stream.Flush();
}
while (ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms));
return stream;
}
//
// The following functions do all the HTTP headers related stuff
// returning the stream ready for use
//
public static Stream CONNECT(Uri uri, IWebProxy proxy, String session, int timeout_ms)
{
return DO_HTTP(uri, proxy, true, timeout_ms,
string.Format("CONNECT {0} HTTP/1.0", uri.PathAndQuery),
string.Format("Host: {0}", uri.Host),
string.Format("Cookie: session_id={0}", session));
}
public static Stream PUT(Uri uri, IWebProxy proxy, long ContentLength, int timeout_ms)
{
return DO_HTTP(uri, proxy, false, timeout_ms,
string.Format("PUT {0} HTTP/1.0", uri.PathAndQuery),
string.Format("Host: {0}", uri.Host),
string.Format("Content-Length: {0}", ContentLength));
}
public static Stream GET(Uri uri, IWebProxy proxy, int timeout_ms)
{
return DO_HTTP(uri, proxy, false, timeout_ms,
string.Format("GET {0} HTTP/1.0", uri.PathAndQuery),
string.Format("Host: {0}", uri.Host));
}
/// <summary>
/// A general HTTP PUT method, with delegates for progress and cancelling. May throw various exceptions.
/// </summary>
/// <param name="progressDelegate">Delegate called periodically (500ms) with percent complete</param>
/// <param name="cancellingDelegate">Delegate called periodically to see if need to cancel</param>
/// <param name="uri">URI to PUT to</param>
/// <param name="proxy">A proxy to handle the HTTP connection</param>
/// <param name="path">Path to file to put</param>
/// <param name="timeout_ms">Timeout for the connection in ms. 0 for no timeout.</param>
public static void Put(UpdateProgressDelegate progressDelegate, FuncBool cancellingDelegate,
Uri uri, IWebProxy proxy, string path, int timeout_ms)
{
using (Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read),
requestStream = PUT(uri, proxy, fileStream.Length, timeout_ms))
{
long len = fileStream.Length;
DataCopiedDelegate dataCopiedDelegate = delegate(long bytes)
{
if (progressDelegate != null && len > 0)
progressDelegate((int)((bytes * 100) / len));
};
CopyStream(fileStream, requestStream, dataCopiedDelegate, cancellingDelegate);
}
}
/// <summary>
/// A general HTTP GET method, with delegates for progress and cancelling. May throw various exceptions.
/// </summary>
/// <param name="dataRxDelegate">Delegate called periodically (500 ms) with the number of bytes transferred</param>
/// <param name="cancellingDelegate">Delegate called periodically to see if need to cancel</param>
/// <param name="uri">URI to GET from</param>
/// <param name="proxy">A proxy to handle the HTTP connection</param>
/// <param name="path">Path to file to receive the data</param>
/// <param name="timeout_ms">Timeout for the connection in ms. 0 for no timeout.</param>
public static void Get(DataCopiedDelegate dataCopiedDelegate, FuncBool cancellingDelegate,
Uri uri, IWebProxy proxy, string path, int timeout_ms)
{
string tmpFile = Path.GetTempFileName();
try
{
using (Stream fileStream = new FileStream(tmpFile, FileMode.Create, FileAccess.Write, FileShare.None),
downloadStream = GET(uri, proxy, timeout_ms))
{
CopyStream(downloadStream, fileStream, dataCopiedDelegate, cancellingDelegate);
fileStream.Flush();
}
File.Delete(path);
File.Move(tmpFile, path);
}
finally
{
File.Delete(tmpFile);
}
}
}
}
| |
// 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Reflection;
using System.Collections.Generic;
using NUnit.Framework;
// Do not warn about missing documentation.
#pragma warning disable 1591
namespace FalkenTests
{
public class FalkenJoystickContainer : Falken.AttributeContainer
{
public Falken.Joystick joystick =
new Falken.Joystick("joystick",
Falken.AxesMode.DirectionXZ,
Falken.ControlledEntity.Player,
Falken.ControlFrame.Player);
}
public class JoystickAttributeTest
{
private FalkenInternal.falken.AttributeContainer _falkenContainer;
[SetUp]
public void Setup()
{
_falkenContainer = new FalkenInternal.falken.AttributeContainer();
}
[Test]
public void FalkenInternalAxesModeConversion()
{
Falken.AxesMode Mode = Falken.AxesMode.Invalid;
Assert.AreEqual(Falken.Joystick.ToInternalAxesMode(Mode),
FalkenInternal.falken.AxesMode.kAxesModeInvalid);
Mode = Falken.AxesMode.DeltaPitchYaw;
Assert.AreEqual(Falken.Joystick.ToInternalAxesMode(Mode),
FalkenInternal.falken.AxesMode.kAxesModeDeltaPitchYaw);
Mode = Falken.AxesMode.DirectionXZ;
Assert.AreEqual(Falken.Joystick.ToInternalAxesMode(Mode),
FalkenInternal.falken.AxesMode.kAxesModeDirectionXZ);
}
[Test]
public void FalkenInternalControlledEntityConversion()
{
Falken.ControlledEntity Entity =
Falken.ControlledEntity.Player;
Assert.AreEqual(Falken.Joystick.ToInternalControlledEntity(Entity),
FalkenInternal.falken.ControlledEntity.kControlledEntityPlayer);
Entity =
Falken.ControlledEntity.Camera;
Assert.AreEqual(Falken.Joystick.ToInternalControlledEntity(Entity),
FalkenInternal.falken.ControlledEntity.kControlledEntityCamera);
}
[Test]
public void FalkenInternalControlFrameConversion()
{
Falken.ControlFrame Frame =
Falken.ControlFrame.Player;
Assert.AreEqual(Falken.Joystick.ToInternalControlFrame(Frame),
FalkenInternal.falken.ControlFrame.kControlFramePlayer);
Frame = Falken.ControlFrame.Camera;
Assert.AreEqual(Falken.Joystick.ToInternalControlFrame(Frame),
FalkenInternal.falken.ControlFrame.kControlFrameCamera);
Frame = Falken.ControlFrame.World;
Assert.AreEqual(Falken.Joystick.ToInternalControlFrame(Frame),
FalkenInternal.falken.ControlFrame.kControlFrameWorld);
}
[Test]
public void CreateJoystickAttributeAxesModeDirectionXZ()
{
Falken.Joystick joystick = new Falken.Joystick("Stick1",
Falken.AxesMode. DirectionXZ,
Falken.ControlledEntity.Player,
Falken.ControlFrame.Player);
Assert.AreEqual(Falken.AxesMode.DirectionXZ, joystick.AxesMode);
Assert.AreEqual(Falken.ControlledEntity.Player, joystick.ControlledEntity);
Assert.AreEqual(Falken.ControlFrame.Player, joystick.ControlFrame);
}
[Test]
public void CreateJoystickAttributeAxesModeDeltaPitchYaw()
{
Falken.Joystick joystick = new Falken.Joystick("Stick2",
Falken.AxesMode.DeltaPitchYaw,
Falken.ControlledEntity.Camera,
Falken.ControlFrame.World);
Assert.AreEqual(Falken.AxesMode.DeltaPitchYaw, joystick.AxesMode);
Assert.AreEqual(Falken.ControlledEntity.Camera, joystick.ControlledEntity);
Assert.AreEqual(Falken.ControlFrame.World, joystick.ControlFrame);
}
[Test]
public void BindDynamicJoystick()
{
Falken.AttributeContainer container = new Falken.AttributeContainer();
Falken.Joystick joystick = new Falken.Joystick("joystick",
Falken.AxesMode.DirectionXZ,
Falken.ControlledEntity.Player,
Falken.ControlFrame.Player);
container["joystick"] = joystick;
container.BindAttributes(_falkenContainer);
Assert.AreEqual(1, container.Values.Count);
Assert.IsTrue(container.ContainsKey("joystick"));
Assert.AreEqual("joystick", joystick.Name);
Assert.AreEqual(Falken.AxesMode.DirectionXZ, joystick.AxesMode);
Assert.AreEqual(Falken.ControlledEntity.Player, joystick.ControlledEntity);
Assert.AreEqual(Falken.ControlFrame.Player, joystick.ControlFrame);
}
[Test]
public void BindJoystickContainer()
{
FalkenJoystickContainer JoystickContainer =
new FalkenJoystickContainer();
JoystickContainer.BindAttributes(_falkenContainer);
Assert.IsTrue(JoystickContainer.Bound);
Assert.IsTrue(JoystickContainer["joystick"] is Falken.Joystick);
Falken.Joystick joystick = (Falken.Joystick)JoystickContainer["joystick"];
joystick.X = 0.5f;
Assert.AreEqual(0.5f, joystick.X);
joystick.Y = 0.5f;
Assert.AreEqual(0.5f, joystick.Y);
using (var ignoreErrorMessages = new IgnoreErrorMessages())
{
Assert.That(() => joystick.Y = -1.5f, Throws.Exception.TypeOf<ApplicationException>());
}
}
[Test]
public void JoystickXAxisClampingTest()
{
FalkenJoystickContainer JoystickContainer =
new FalkenJoystickContainer();
JoystickContainer.BindAttributes(_falkenContainer);
Falken.Joystick joystick = (Falken.Joystick)JoystickContainer["joystick"];
var recovered_logs = new List<String>();
System.EventHandler<Falken.Log.MessageArgs> handler = (
object source, Falken.Log.MessageArgs args) =>
{
recovered_logs.Add(args.Message);
};
Falken.Log.OnMessage += handler;
var expected_logs = new List<String>() {
"Unable to set value of attribute 'x_axis' to -2 as it is out" +
" of the specified range -1 to 1.",
"Unable to set value of attribute 'x_axis' to 2 as it is out" +
" of the specified range -1 to 1." };
// default clamping value (off)
Assert.IsFalse(joystick.EnableClamping);
joystick.X = 0.0f;
Assert.AreEqual(0.0, joystick.X);
using (var ignoreErrorMessages = new IgnoreErrorMessages())
{
Assert.That(() => joystick.X = -2.0f,
Throws.TypeOf<ApplicationException>());
Assert.That(() => joystick.X = 2.0f,
Throws.TypeOf<ApplicationException>());
}
Assert.That(recovered_logs, Is.EquivalentTo(expected_logs));
// with clamping on
recovered_logs.Clear();
joystick.EnableClamping = true;
Assert.IsTrue(joystick.EnableClamping);
joystick.X = 0.0f;
Assert.AreEqual(0.0f, joystick.X);
joystick.X = -2.0f;
Assert.AreEqual(-1.0f, joystick.X);
joystick.X = 2.0f;
Assert.AreEqual(1.0f, joystick.X);
Assert.AreEqual(0, recovered_logs.Count);
// with clamping off
recovered_logs.Clear();
joystick.EnableClamping = false;
Assert.IsFalse(joystick.EnableClamping);
joystick.X = 0.0f;
Assert.AreEqual(0.0f, joystick.X);
using (var ignoreErrorMessages = new IgnoreErrorMessages())
{
Assert.That(() => joystick.X = -2.0f,
Throws.TypeOf<ApplicationException>());
Assert.That(() => joystick.X = 2.0f,
Throws.TypeOf<ApplicationException>());
}
Assert.That(recovered_logs, Is.EquivalentTo(expected_logs));
}
[Test]
public void JoystickYAxisClampingTest()
{
FalkenJoystickContainer JoystickContainer =
new FalkenJoystickContainer();
JoystickContainer.BindAttributes(_falkenContainer);
Falken.Joystick joystick = (Falken.Joystick)JoystickContainer["joystick"];
var recovered_logs = new List<String>();
System.EventHandler<Falken.Log.MessageArgs> handler = (
object source, Falken.Log.MessageArgs args) =>
{
recovered_logs.Add(args.Message);
};
Falken.Log.OnMessage += handler;
var expected_logs = new List<String>() {
"Unable to set value of attribute 'y_axis' to -2 as it is out" +
" of the specified range -1 to 1.",
"Unable to set value of attribute 'y_axis' to 2 as it is out" +
" of the specified range -1 to 1." };
// default clamping value (off)
Assert.IsFalse(joystick.EnableClamping);
joystick.Y = 0.0f;
Assert.AreEqual(0.0, joystick.Y);
using (var ignoreErrorMessages = new IgnoreErrorMessages())
{
Assert.That(() => joystick.Y = -2.0f,
Throws.TypeOf<ApplicationException>());
Assert.That(() => joystick.Y = 2.0f,
Throws.TypeOf<ApplicationException>());
}
Assert.That(recovered_logs, Is.EquivalentTo(expected_logs));
// with clamping on
recovered_logs.Clear();
joystick.EnableClamping = true;
Assert.IsTrue(joystick.EnableClamping);
joystick.Y = 0.0f;
Assert.AreEqual(0.0f, joystick.Y);
joystick.Y = -2.0f;
Assert.AreEqual(-1.0f, joystick.Y);
joystick.Y = 2.0f;
Assert.AreEqual(1.0f, joystick.Y);
Assert.AreEqual(0, recovered_logs.Count);
// with clamping off
recovered_logs.Clear();
joystick.EnableClamping = false;
Assert.IsFalse(joystick.EnableClamping);
joystick.Y = 0.0f;
Assert.AreEqual(0.0f, joystick.Y);
using (var ignoreErrorMessages = new IgnoreErrorMessages())
{
Assert.That(() => joystick.Y = -2.0f,
Throws.TypeOf<ApplicationException>());
Assert.That(() => joystick.Y = 2.0f,
Throws.TypeOf<ApplicationException>());
}
Assert.That(recovered_logs, Is.EquivalentTo(expected_logs));
}
[Test]
public void GetandSetUnboundJoystickAttribute()
{
Falken.Joystick joystick = new Falken.Joystick("Stick2", Falken.AxesMode.DeltaPitchYaw,
Falken.ControlledEntity.Camera,
Falken.ControlFrame.World);
using (var ignoreErrorMessages = new IgnoreErrorMessages())
{
Assert.That(() => joystick.Y = -0.5f,
Throws.Exception.TypeOf<Falken.AttributeNotBoundException>());
float x = 0;
Assert.That(() => x = joystick.X,
Throws.Exception.TypeOf<Falken.AttributeNotBoundException>());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ChatSharp
{
public partial class IrcClient
{
/// <summary>
/// Changes your nick.
/// </summary>
public void Nick(string newNick)
{
SendRawMessage("NICK {0}", newNick);
User.Nick = newNick;
}
/// <summary>
/// Sends a message to one or more destinations (channels or users).
/// </summary>
public void SendMessage(string message, params string[] destinations)
{
const string illegalCharacters = "\r\n\0";
if (destinations == null || !destinations.Any()) throw new InvalidOperationException("Message must have at least one target.");
if (illegalCharacters.Any(message.Contains)) throw new ArgumentException("Illegal characters are present in message.", "message");
string to = string.Join(",", destinations);
SendRawMessage("PRIVMSG {0} :{1}{2}", to, PrivmsgPrefix, message);
}
/// <summary>
/// Sends a CTCP action (i.e. "* SirCmpwn waves hello") to one or more destinations.
/// </summary>
public void SendAction(string message, params string[] destinations)
{
const string illegalCharacters = "\r\n\0";
if (destinations == null || !destinations.Any()) throw new InvalidOperationException("Message must have at least one target.");
if (illegalCharacters.Any(message.Contains)) throw new ArgumentException("Illegal characters are present in message.", "message");
string to = string.Join(",", destinations);
SendRawMessage("PRIVMSG {0} :\x0001ACTION {1}{2}\x0001", to, PrivmsgPrefix, message);
}
/// <summary>
/// Sends a NOTICE to one or more destinations (channels or users).
/// </summary>
public void SendNotice(string message, params string[] destinations)
{
const string illegalCharacters = "\r\n\0";
if (destinations == null || !destinations.Any()) throw new InvalidOperationException("Message must have at least one target.");
if (illegalCharacters.Any(message.Contains)) throw new ArgumentException("Illegal characters are present in message.", "message");
string to = string.Join(",", destinations);
SendRawMessage("NOTICE {0} :{1}{2}", to, PrivmsgPrefix, message);
}
/// <summary>
/// Leaves the specified channel.
/// </summary>
public void PartChannel(string channel)
{
if (!Channels.Contains(channel))
throw new InvalidOperationException("Client is not present in channel.");
SendRawMessage("PART {0}", channel);
}
/// <summary>
/// Leaves the specified channel, giving a reason for your departure.
/// </summary>
public void PartChannel(string channel, string reason)
{
if (!Channels.Contains(channel))
throw new InvalidOperationException("Client is not present in channel.");
SendRawMessage("PART {0} :{1}", channel, reason);
}
/// <summary>
/// Joins the specified channel.
/// </summary>
public void JoinChannel(string channel, string key = null)
{
if (Channels.Contains(channel))
throw new InvalidOperationException("Client is already present in channel.");
string joinCmd = string.Format("JOIN {0}", channel);
if (!string.IsNullOrEmpty(key))
joinCmd += string.Format(" {0}", key);
SendRawMessage(joinCmd, channel);
// account-notify capability
var flags = WhoxField.Nick | WhoxField.Hostname | WhoxField.AccountName | WhoxField.Username;
if (Capabilities.IsEnabled("account-notify"))
Who(channel, WhoxFlag.None, flags, (whoList) =>
{
if (whoList.Count > 0)
{
foreach (var whoQuery in whoList)
{
var user = Users.GetOrAdd(whoQuery.User.Hostmask);
user.Account = whoQuery.User.Account;
}
}
});
}
/// <summary>
/// Sets the topic for the specified channel.
/// </summary>
public void SetTopic(string channel, string topic)
{
if (!Channels.Contains(channel))
throw new InvalidOperationException("Client is not present in channel.");
SendRawMessage("TOPIC {0} :{1}", channel, topic);
}
/// <summary>
/// Retrieves the topic for the specified channel.
/// </summary>
public void GetTopic(string channel)
{
SendRawMessage("TOPIC {0}", channel);
}
/// <summary>
/// Kicks the specified user from the specified channel.
/// </summary>
public void KickUser(string channel, string user)
{
SendRawMessage("KICK {0} {1} :{1}", channel, user);
}
/// <summary>
/// Kicks the specified user from the specified channel.
/// </summary>
public void KickUser(string channel, string user, string reason)
{
SendRawMessage("KICK {0} {1} :{2}", channel, user, reason);
}
/// <summary>
/// Invites the specified user to the specified channel.
/// </summary>
public void InviteUser(string channel, string user)
{
SendRawMessage("INVITE {1} {0}", channel, user);
}
/// <summary>
/// Sends a WHOIS query asking for information on the given nick.
/// </summary>
public void WhoIs(string nick)
{
WhoIs(nick, null);
}
/// <summary>
/// Sends a WHOIS query asking for information on the given nick, and a callback
/// to run when we have received the response.
/// </summary>
public void WhoIs(string nick, Action<WhoIs> callback)
{
var whois = new WhoIs();
RequestManager.QueueOperation("WHOIS " + nick, new RequestOperation(whois, ro =>
{
if (callback != null)
callback((WhoIs)ro.State);
}));
SendRawMessage("WHOIS {0}", nick);
}
/// <summary>
/// Sends an extended WHO query asking for specific information about a single user
/// or the users in a channel, and runs a callback when we have received the response.
/// </summary>
public void Who(string target, WhoxFlag flags, WhoxField fields, Action<List<ExtendedWho>> callback)
{
if (ServerInfo.ExtendedWho)
{
var whox = new List<ExtendedWho>();
// Generate random querytype for WHO query
int queryType = RandomNumber.Next(0, 999);
// Add the querytype field if it wasn't defined
var _fields = fields;
if ((fields & WhoxField.QueryType) == 0)
_fields |= WhoxField.QueryType;
string whoQuery = string.Format("WHO {0} {1}%{2},{3}", target, flags.AsString(), _fields.AsString(), queryType);
string queryKey = string.Format("WHO {0} {1} {2:D}", target, queryType, _fields);
RequestManager.QueueOperation(queryKey, new RequestOperation(whox, ro =>
{
callback?.Invoke((List<ExtendedWho>)ro.State);
}));
SendRawMessage(whoQuery);
}
else
{
var whox = new List<ExtendedWho>();
string whoQuery = string.Format("WHO {0}", target);
RequestManager.QueueOperation(whoQuery, new RequestOperation(whox, ro =>
{
callback?.Invoke((List<ExtendedWho>)ro.State);
}));
SendRawMessage(whoQuery);
}
}
/// <summary>
/// Requests the mode of a channel from the server.
/// </summary>
public void GetMode(string channel)
{
GetMode(channel, null);
}
/// <summary>
/// Requests the mode of a channel from the server, and passes it to a callback later.
/// </summary>
public void GetMode(string channel, Action<IrcChannel> callback)
{
RequestManager.QueueOperation("MODE " + channel, new RequestOperation(channel, ro =>
{
var c = Channels[(string)ro.State];
if (callback != null)
callback(c);
}));
SendRawMessage("MODE {0}", channel);
}
/// <summary>
/// Sets the mode of a target.
/// </summary>
public void ChangeMode(string target, string change)
{
SendRawMessage("MODE {0} {1}", target, change);
}
/// <summary>
/// Gets a collection of masks from a channel by a mode. This can be used, for example,
/// to get a list of bans.
/// </summary>
public void GetModeList(string channel, char mode, Action<MaskCollection> callback)
{
RequestManager.QueueOperation("GETMODE " + mode + " " + channel, new RequestOperation(new MaskCollection(), ro =>
{
var c = (MaskCollection)ro.State;
if (callback != null)
callback(c);
}));
SendRawMessage("MODE {0} {1}", channel, mode);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (C) LogicKing.com, Inc.
//-----------------------------------------------------------------------------
// Cut scene functional
new ActionMap(CutSceneActionMap);
CutSceneActionMap.bindCmd(keyboard, "space", " $currentPlayingScene.stop(); ", "");
datablock MissionMarkerData(CutSceneData)
{
category = "Misc";
shapeFile = "core/art/shapes/octahedron.dts";
};
function CutScene::create()
{
%scene = new MissionMarker() {
dataBlock = CutSceneData;
class = "CutScene";
};
return %scene;
}
function CutSceneData::onAdd(%this, %obj)
{
%obj.soundsCount = %obj.soundsCount $= "" ? 0 : %obj.soundsCount;
%obj.chunksCount = %obj.chunksCount $= "" ? 0 : %obj.chunksCount;
%obj.pathsCount = %obj.pathsCount $= "" ? 0 : %obj.pathsCount;
%obj.prepareSounds();
}
function CutSceneData::onRemove(%this, %obj)
{
%obj.clearSounds();
}
function CutScene::play(%this)
{
%this.player = LocalClientConnection.getControlObject();
%this.currentCameraPath = 0;
%this.createCamera();
%this.playCamera();
%this.processChunks();
%this.playSounds();
if(!LogickingEditor.isActive)
%this.signal("onPlay");
$currentPlayingScene = %this;
CutSceneActionMap.push();
}
function CutScene::createCamera(%this)
{
%this.camera = new PathCamera() {
dataBlock = CutSceneCam;
};
MissionCleanup.add( %this.camera );
%this.camera.scene = %this;
}
function CutScene::destroyCamera(%this)
{
%this.camera.delete();
%this.camera = "";
}
function CutScene::playCamera(%this)
{
%path = %this.getCameraPath();
%marker = %this.getCameraPosition();
if(isObject(%path) && %path.getCount() > 0)
{
%node = %path.getObject(0);
%this.camera.setTransform(%node.getTransform());
%this.camera.reset(0);
%this.camera.followPath(%path);
%this.camera.onEndPath = %this @ ".onEndPath(true); ";
}
else if(isObject(%marker))
{
%this.camera.pushNode(%marker);
%this.camera.popFront();
}
else
{
%this.stop(true);
}
}
function CutScene::prepareSounds(%this)
{
%this.clearSounds();
%count = %this.soundsCount;
if(%count $= "" || %count == 0) return;
if(!isObject(%this.description))
{
%this.description = new SFXDescription()
{
volume = 1.0;
isLooping = false;
is3D = false;
channel = $SimAudioType;
};
MissionCleanup.add(%this.description);
}
for(%i = 0; %i < %count; %i++)
{
%filePath = %this.sounds[%i, 0];
if(%filePath $= "") continue;
if(isObject(cutSceneSFXProfile))
cutSceneSFXProfile.delete();
%sfxProfile = new SFXProfile(cutSceneSFXProfile) {
filename = %filePath;
description = %this.description;
preload = true;
};
if(!isObject(%sfxProfile))
{
echo("Warning! ", %filePath, ". Unable to create profile for sound");
continue;
}
else
MissionCleanup.add(%sfxProfile);
%this.sfxSource[%i] = sfxCreateSource(%sfxProfile, 0, 0, 0);
}
}
function CutScene::clearSounds(%this)
{
%count = %this.soundsCount;
if(%count $= "" || %count == 0) return;
for(%i = 0; %i < %count; %i++)
{
%sfxSource = %this.sfxSource[%i];
if(isObject(%sfxSource))
{
%sfxSource.stop();
%sfxSource.delete();
%this.sfxSource[%i] = "";
}
}
}
function CutScene::stopSounds(%this)
{
%count = %this.soundsCount;
if(%count $= "" || %count == 0) return;
for(%i = 0; %i < %count; %i++)
{
%sfxSource = %this.sfxSource[%i];
if(isObject(%sfxSource))
{
%sfxSource.stop();
}
}
}
function CutScene::playSounds(%this)
{
%count = %this.soundsCount;
if(%count $= "" || %count == 0) return;
for(%i = 0; %i < %count; %i++)
{
if(isObject(%this.sfxSource[%i]))
{
if(%this.sounds[%i, 1] !$= "" && %this.sounds[%i, 1] > 0)
%this.schedule(%this.sounds[%i, 1], "playSound", %i);
else
%this.playSound(%i);
}
}
}
function CutScene::playSound(%this, %idx)
{
%sfxSource = %this.sfxSource[%idx];
if(isObject(%sfxSource))
%sfxSource.play();
}
function CutScene::processChunks(%this)
{
%count = %this.chunksCount;
if(%count $= "" || %count == 0) return;
for(%i = 0; %i < %count; %i++)
{
%code = %this.chunks[%i, 0];
%timeShift = %this.chunks[%i, 1];
if(%code !$= "")
{
if(%timeShift $= "" || %timeShift == 0)
%this.doChunk(%code);
else
%this.schedule(%timeShift, "doChunk", %code);
}
}
}
function CutScene::doChunk(%this, %chunk)
{
Helpers::evalWithThisObj(%chunk, %this);
}
function CutScene::getCurrentPath(%this)
{
%path = %this.getFieldValue("paths" @ %this.currentCameraPath @ "_0");
return %path;
}
function CutScene::getCameraPath(%this)
{
while((%this.getCurrentPath().isEnabled() == 0) && %this.currentCameraPath < %this.pathsCount)
{
%this.currentCameraPath++;
}
return %this.getCurrentPath();
}
function CutScene::getCameraPosition(%this)
{
return %this.getId() @ "/" @ %this.getName() @ "CameraPosition";
}
function CutScene::onEndPath(%this)
{
if(%this.pathsCount !$= "" && %this.currentCameraPath < %this.pathsCount)
{
%this.currentCameraPath++;
%this.playCamera();
}
else
%this.stop(true);
}
function CutScene::stop(%this, %onEndCamera)
{
$currentPlayingScene = "";
CutSceneActionMap.pop();
if(!LogickingEditor.isActive)
%this.signal("onStop");
if(%onEndCamera $= "")
{
%this.camera.onEndPath = "";
%this.camera.stop();
}
else
LocalClientConnection.setControlObject(%this.player);
%this.camera = "";
%this.player = "";
%this.stopSounds();
}
function askPlayScene(%scene)
{
MessageBoxYesNo( "Play current scene?", "Do you really want to play current cutScene? This may cause some changes im mission file.", " doPlayScene(" @ %scene @ "); ");
}
function doPlayScene(%scene)
{
LogickingEditor.closeAllWindows();
LogickingEditorFieldEditor.currentScene = %scene;
%scene.play();
}
ActivatePackage(TemplateFunctions);
registerTemplate("CutScene", "CutScenes", " CutScene::create(); ");
setTemplateCommand("CutScene", "Play scene", "Play current cut scene", " askPlayScene(%this); ");
// actions
setTemplateAction("CutScene", "play", " play scene");
setTemplateAction("CutScene", "stop", " stop's scene");
// events
setTemplateEvent("CutScene", "onPlay", "echo(\"onPlay\");");
setTemplateEvent("CutScene", "onStop", "echo(\"onStop\");");
// param groups
setTemplateParamsGroup("CutScene", "Chunks", "code|Code|Time shift", "chunks");
setTemplateParamsGroup("CutScene", "Sounds", "sound|File path|Time shift", "sounds", $soundFilesMask);
setTemplateParamsGroup("CutScene", "Paths", "objectLink|Paths", "paths", "Path");
DeactivatePackage(TemplateFunctions);
| |
using System;
using System.Collections.Generic;
namespace ICSimulator
{
/* a Priority Packet Pool is an abstract packet container that
* implements a priority/reordering/scheduling. Intended for use
* with injection queues, and possibly in-network buffers, that are
* nominally FIFO but could potentially reorder.
*/
public interface IPrioPktPool
{
void addPacket(Packet pkt);
void setNodeId(int id);
Packet next();
int Count { get; }
int FlitCount { get; }
Flit peekFlit();
void takeFlit();
bool FlitInterface { get; }
}
/* simple single-FIFO packet pool. */
public class FIFOPrioPktPool : IPrioPktPool
{
Queue<Packet> queue;
int flitCount = 0;
public FIFOPrioPktPool()
{
queue = new Queue<Packet>();
}
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
queue.Enqueue(pkt);
}
public Packet next()
{
if (queue.Count > 0)
{
Packet p = queue.Dequeue();
flitCount -= p.nrOfFlits;
return p;
}
else
return null;
}
public void setNodeId(int id)
{
}
public int Count { get { return queue.Count; } }
public int FlitCount { get { return flitCount; } }
public bool FlitInterface { get { return false; } }
public Flit peekFlit() { return null; }
public void takeFlit() { }
}
/* multi-queue priority packet pool, based on Packet's notion of
* queues (Packet.numQueues and Packet.getQueue() ): currently
* Packet implements these based on the cache-coherence protocol,
* so that control, data, and writeback packets have separate queues.
*/
public class MultiQPrioPktPool : IPrioPktPool
{
Queue<Packet>[] queues;
int nqueues;
int queue_next;
int flitCount = 0;
public MultiQPrioPktPool()
{
nqueues = Packet.numQueues;
queues = new Queue<Packet>[nqueues];
for (int i = 0; i < nqueues; i++)
queues[i] = new Queue<Packet>();
queue_next = nqueues - 1;
}
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
queues[pkt.getQueue()].Enqueue(pkt);
}
void advanceRR()
{
int tries = nqueues;
do
queue_next = (queue_next + 1) % nqueues;
while (tries-- > 0 && queues[queue_next].Count == 0);
}
public Packet next()
{
advanceRR();
if (queues[queue_next].Count > 0)
{
Packet p = queues[queue_next].Dequeue();
flitCount -= p.nrOfFlits;
return p;
}
else
return null;
}
public void setNodeId(int id)
{
}
public int Count
{
get
{
int sum = 0;
for (int i = 0; i < nqueues; i++)
sum += queues[i].Count;
return sum;
}
}
public int FlitCount { get { return flitCount; } }
public bool FlitInterface { get { return false; } }
public Flit peekFlit() { return null; }
public void takeFlit() { }
}
/**
* @brief Same as the multiqpriopktpool with throttling on request packet
* enabled.
**/
public class MultiQThrottlePktPool : IPrioPktPool
{
Queue<Packet>[] queues;
int nqueues;
int queue_next;
int node_id=-1;
int flitCount = 0;
public static IPrioPktPool construct()
{
if (Config.cluster_prios_injq)
return new ReallyNiftyPrioritizingPacketPool();
else
return new MultiQThrottlePktPool();
}
private MultiQThrottlePktPool()
{
nqueues = Packet.numQueues;
queues = new Queue<Packet>[nqueues];
for (int i = 0; i < nqueues; i++)
queues[i] = new Queue<Packet>();
queue_next = nqueues - 1;
}
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
queues[pkt.getQueue()].Enqueue(pkt);
}
void advanceRR()
{
int tries = nqueues;
do
queue_next = (queue_next + 1) % nqueues;
while (tries-- > 0 && queues[queue_next].Count == 0 );
}
public Packet next()
{
if(node_id==-1)
throw new Exception("Haven't configured the packet pool");
advanceRR();
if (queues[queue_next].Count > 0 &&
(queue_next != 0 || Simulator.controller.tryInject(node_id)) )
{
Packet p = queues[queue_next].Dequeue();
flitCount -= p.nrOfFlits;
return p;
}
else
return null;
}
public void setNodeId(int id)
{
node_id=id;
}
public int Count
{
get
{
int sum = 0;
for (int i = 0; i < nqueues; i++)
sum += queues[i].Count;
return sum;
}
}
public int FlitCount { get { return flitCount; } }
public bool FlitInterface { get { return false; } }
public Flit peekFlit() { return null; }
public void takeFlit() { }
}
/** @brief the Really Nifty Prioritizing Packet Pool respects full
* priorities (i.e., by using a min-heap) and also optionally respects
* throttling.
*/
public class ReallyNiftyPrioritizingPacketPool : IPrioPktPool
{
class HeapNode : IComparable
{
public Packet pkt;
public HeapNode(Packet p) { pkt = p; }
public int CompareTo(object o)
{
if (o is HeapNode)
return Simulator.controller.rankFlits(pkt.flits[0], (o as HeapNode).pkt.flits[0]);
else
throw new ArgumentException("bad comparison");
}
}
MinHeap<HeapNode>[] heaps;
int nheaps;
int heap_next;
int flitCount = 0;
int node_id = -1;
public ReallyNiftyPrioritizingPacketPool()
{
nheaps = Packet.numQueues;
heaps = new MinHeap<HeapNode>[nheaps];
for (int i = 0; i < nheaps; i++)
heaps[i] = new MinHeap<HeapNode>();
heap_next = nheaps - 1;
}
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
HeapNode h = new HeapNode(pkt);
heaps[pkt.getQueue()].Enqueue(h);
}
void advanceRR()
{
int tries = nheaps;
do
heap_next = (heap_next + 1) % nheaps;
// keep incrementing while we're at an empty queue or at req-queue and throttling
while (tries-- > 0 &&
((heaps[heap_next].Count == 0) ||
(heap_next == 0 && !Simulator.controller.tryInject(node_id))));
}
public Packet next()
{
advanceRR();
//only queues for non-control packets go proceed without any
//throttling constraint
if (heaps[heap_next].Count > 0 &&
(heap_next!=0 || Simulator.controller.tryInject(node_id)) )
{
HeapNode h = heaps[heap_next].Dequeue();
Packet p = h.pkt;
flitCount -= p.nrOfFlits;
return p;
}
else
return null;
}
public void setNodeId(int id)
{
node_id = id;
}
public int Count
{
get
{
int sum = 0;
for (int i = 0; i < nheaps; i++)
sum += heaps[i].Count;
return sum;
}
}
public int FlitCount { get { return flitCount; } }
public bool FlitInterface { get { return false; } }
public Flit peekFlit() { return null; }
public void takeFlit() { }
}
}
| |
/*
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 *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.Diagnostics;
namespace Microsoft.Research.DryadLinq
{
// This class implements an expression matcher. This is useful for
// many interesting static analysis. Again, it would be nice if this
// is a functionality provided by C# and LINQ. But unfortunately it
// is not.
internal class ExpressionMatcher
{
public static bool Match(Expression e1, Expression e2)
{
return Match(e1, e2, Substitution.Empty);
}
// return true if e1 subsumes e2 in terms of member access
internal static bool MemberAccessSubsumes(Expression e1, Expression e2)
{
if (Match(e1, e2)) return true;
Expression e = e2;
while (e is MemberExpression)
{
e = ((MemberExpression)e).Expression;
if (Match(e1, e)) return true;
}
return false;
}
internal static bool Match(Expression e1, Expression e2, Substitution subst)
{
if (!e1.Type.Equals(e2.Type)) return false;
if (e1 is BinaryExpression)
{
return ((e2 is BinaryExpression) &&
MatchBinary((BinaryExpression)e1, (BinaryExpression)e2, subst));
}
else if (e1 is ConditionalExpression)
{
return ((e2 is ConditionalExpression) &&
MatchConditional((ConditionalExpression)e1, (ConditionalExpression)e2, subst));
}
else if (e1 is ConstantExpression)
{
return ((e2 is ConstantExpression) &&
MatchConstant((ConstantExpression)e1, (ConstantExpression)e2, subst));
}
else if (e1 is InvocationExpression)
{
return ((e2 is InvocationExpression) &&
MatchInvocation((InvocationExpression)e1, (InvocationExpression)e2, subst));
}
else if (e1 is LambdaExpression)
{
return ((e2 is LambdaExpression) &&
MatchLambda((LambdaExpression)e1, (LambdaExpression)e2, subst));
}
else if (e1 is MemberExpression)
{
return ((e2 is MemberExpression) &&
MatchMember((MemberExpression)e1, (MemberExpression)e2, subst));
}
else if (e1 is MethodCallExpression)
{
return ((e2 is MethodCallExpression) &&
MatchMethodCall((MethodCallExpression)e1, (MethodCallExpression)e2, subst));
}
else if (e1 is NewExpression)
{
return ((e2 is NewExpression) &&
MatchNew((NewExpression)e1, (NewExpression)e2, subst));
}
else if (e1 is NewArrayExpression)
{
return ((e2 is NewArrayExpression) &&
MatchNewArray((NewArrayExpression)e1, (NewArrayExpression)e2, subst));
}
else if (e1 is MemberInitExpression)
{
return ((e2 is MemberInitExpression) &&
MatchMemberInit((MemberInitExpression)e1, (MemberInitExpression)e2, subst));
}
else if (e1 is ListInitExpression)
{
return ((e2 is ListInitExpression) &&
MatchListInit((ListInitExpression)e1, (ListInitExpression)e2, subst));
}
else if (e1 is ParameterExpression)
{
return ((e2 is ParameterExpression) &&
MatchParameter((ParameterExpression)e1, (ParameterExpression)e2, subst));
}
else if (e1 is TypeBinaryExpression)
{
return ((e2 is TypeBinaryExpression) &&
MatchTypeBinary((TypeBinaryExpression)e1, (TypeBinaryExpression)e2, subst));
}
else if (e1 is UnaryExpression)
{
return ((e2 is UnaryExpression) &&
MatchUnary((UnaryExpression)e1, (UnaryExpression)e2, subst));
}
throw new DryadLinqException(DryadLinqErrorCode.ExpressionTypeNotHandled,
String.Format(SR.ExpressionTypeNotHandled,
"ExpressionMatcher", e1.NodeType));
}
private static bool MatchInvocation(InvocationExpression e1,
InvocationExpression e2,
Substitution subst)
{
ReadOnlyCollection<Expression> args1 = e1.Arguments;
ReadOnlyCollection<Expression> args2 = e2.Arguments;
if (!Match(e1.Expression, e2.Expression, subst) || args1.Count != args2.Count)
{
return false;
}
for (int i = 0; i < args1.Count; i++)
{
if (!Match(args1[i], args2[i], subst))
{
return false;
}
}
return true;
}
private static bool MatchBinary(BinaryExpression e1,
BinaryExpression e2,
Substitution subst)
{
return (e1.NodeType == e2.NodeType &&
Match(e1.Left, e2.Left, subst) &&
Match(e1.Right, e2.Right, subst));
}
private static bool MatchConditional(ConditionalExpression e1,
ConditionalExpression e2,
Substitution subst)
{
return (Match(e1.Test, e2.Test, subst) &&
Match(e1.IfTrue, e2.IfTrue, subst) &&
Match(e1.IfFalse, e2.IfFalse, subst));
}
private static bool MatchConstant(ConstantExpression e1,
ConstantExpression e2,
Substitution subst)
{
if (e1.Value == null)
{
return (e2.Value == null);
}
else
{
return e1.Value.Equals(e2.Value);
}
}
private static bool MatchLambda(LambdaExpression e1,
LambdaExpression e2,
Substitution subst)
{
if (e1.Parameters.Count != e2.Parameters.Count)
{
return false;
}
Substitution subst1 = subst;
for (int i = 0, n = e1.Parameters.Count; i < n; i++)
{
if (!e1.Parameters[i].Equals(e2.Parameters[i]))
{
subst1 = subst1.Cons(e1.Parameters[i], e2.Parameters[i]);
}
}
return Match(e1.Body, e2.Body, subst1);
}
private static bool MatchMember(MemberExpression e1,
MemberExpression e2,
Substitution subst)
{
if (e1.Expression == null)
{
if (e2.Expression != null) return false;
}
else
{
if (e2.Expression == null ||
!Match(e1.Expression, e2.Expression, subst))
{
return false;
}
}
return e1.Member.Equals(e2.Member);
}
private static bool MatchMethodCall(MethodCallExpression e1,
MethodCallExpression e2,
Substitution subst)
{
if (e1.Method != e2.Method) return false;
if (e1.Object == null || e2.Object == null)
{
if (e1.Object != e2.Object) return false;
}
else if (!Match(e1.Object, e2.Object, subst) ||
e1.Arguments.Count != e2.Arguments.Count)
{
return false;
}
for (int i = 0, n = e1.Arguments.Count; i < n; i++)
{
if (!Match(e1.Arguments[i], e2.Arguments[i], subst))
{
return false;
}
}
return true;
}
private static bool MatchNew(NewExpression e1, NewExpression e2, Substitution subst)
{
if (e1.Arguments.Count != e2.Arguments.Count)
{
return false;
}
for (int i = 0, n = e1.Arguments.Count; i < n; i++)
{
if (!Match(e1.Arguments[i], e2.Arguments[i], subst))
{
return false;
}
}
return true;
}
public static bool MatchNewArray(NewArrayExpression e1,
NewArrayExpression e2,
Substitution subst)
{
if (e1.NodeType != e2.NodeType ||
e1.Expressions.Count != e2.Expressions.Count)
{
return false;
}
for (int i = 0, n = e1.Expressions.Count; i < n; i++)
{
if (!Match(e1.Expressions[i], e2.Expressions[i], subst))
{
return false;
}
}
return true;
}
public static bool MatchMemberInit(MemberInitExpression e1,
MemberInitExpression e2,
Substitution subst)
{
if (!Match(e1.NewExpression, e2.NewExpression, subst) ||
e1.Bindings.Count != e2.Bindings.Count)
{
return false;
}
for (int i = 0, n = e1.Bindings.Count; i < n; i++)
{
if (!MatchMemberBinding(e1.Bindings[i], e2.Bindings[i], subst))
{
return false;
}
}
return true;
}
public static bool MatchListInit(ListInitExpression e1,
ListInitExpression e2,
Substitution subst)
{
if (!Match(e1.NewExpression, e2.NewExpression, subst))
{
return false;
}
if (e1.Initializers.Count != e2.Initializers.Count)
{
return false;
}
for (int i = 0, n = e1.Initializers.Count; i < n; i++)
{
ElementInit init1 = e1.Initializers[i];
ElementInit init2 = e2.Initializers[i];
if (!MatchElementInit(init1, init2, subst))
{
return false;
}
}
return true;
}
public static bool MatchParameter(ParameterExpression e1,
ParameterExpression e2,
Substitution subst)
{
if (e1.Equals(e2)) return true;
ParameterExpression e = subst.Find(e1);
return (e != null && e.Equals(e2));
}
public static bool MatchTypeBinary(TypeBinaryExpression e1,
TypeBinaryExpression e2,
Substitution subst)
{
return (e1.NodeType == ExpressionType.TypeIs &&
e2.NodeType == ExpressionType.TypeIs &&
e1.TypeOperand.Equals(e2.TypeOperand) &&
Match(e1.Expression, e2.Expression, subst));
}
public static bool MatchUnary(UnaryExpression e1, UnaryExpression e2, Substitution subst)
{
return (e1.NodeType == e2.NodeType &&
Match(e1.Operand, e2.Operand, subst));
}
private static bool MatchMemberBinding(MemberBinding b1, MemberBinding b2, Substitution subst)
{
if (b1.BindingType != b2.BindingType ||
!b1.Member.Equals(b2.Member))
{
return false;
}
if (b1 is MemberAssignment)
{
return Match(((MemberAssignment)b1).Expression,
((MemberAssignment)b2).Expression,
subst);
}
else if (b1 is MemberMemberBinding)
{
MemberMemberBinding mmb1 = (MemberMemberBinding)b1;
MemberMemberBinding mmb2 = (MemberMemberBinding)b2;
if (mmb1.Bindings.Count != mmb2.Bindings.Count)
{
return false;
}
for (int i = 0, n = mmb1.Bindings.Count; i < n; i++)
{
if (!MatchMemberBinding(mmb1.Bindings[i], mmb2.Bindings[i], subst))
{
return false;
}
}
return true;
}
else
{
MemberListBinding mlb1 = (MemberListBinding)b1;
MemberListBinding mlb2 = (MemberListBinding)b2;
if (mlb1.Initializers.Count != mlb2.Initializers.Count)
{
return false;
}
for (int i = 0, n = mlb1.Initializers.Count; i < n; i++)
{
if (!MatchElementInit(mlb1.Initializers[i], mlb2.Initializers[i], subst))
{
return false;
}
}
return true;
}
}
private static bool MatchElementInit(ElementInit init1,
ElementInit init2,
Substitution subst)
{
if (init1.AddMethod != init2.AddMethod ||
init1.Arguments.Count != init2.Arguments.Count)
{
return false;
}
for (int i = 0; i < init1.Arguments.Count; i++)
{
if (!Match(init1.Arguments[i], init2.Arguments[i], subst))
{
return false;
}
}
return true;
}
}
internal class Substitution
{
private ParameterExpression x;
private ParameterExpression y;
private Substitution next;
public static Substitution Empty = new Substitution(null, null, null);
private Substitution(ParameterExpression x, ParameterExpression y, Substitution s)
{
this.x = x;
this.y = y;
this.next = s;
}
public Substitution Cons(ParameterExpression a, ParameterExpression b)
{
return new Substitution(a, b, this);
}
public ParameterExpression Find(ParameterExpression a)
{
Substitution curSubst = this;
while (curSubst != Empty)
{
if (curSubst.x.Equals(a)) return y;
curSubst = curSubst.next;
}
return null;
}
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/type/interval.proto
// </auto-generated>
#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.Type {
/// <summary>Holder for reflection information generated from google/type/interval.proto</summary>
public static partial class IntervalReflection {
#region Descriptor
/// <summary>File descriptor for google/type/interval.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static IntervalReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chpnb29nbGUvdHlwZS9pbnRlcnZhbC5wcm90bxILZ29vZ2xlLnR5cGUaH2dv",
"b2dsZS9wcm90b2J1Zi90aW1lc3RhbXAucHJvdG8iaAoISW50ZXJ2YWwSLgoK",
"c3RhcnRfdGltZRgBIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXAS",
"LAoIZW5kX3RpbWUYAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1w",
"QmkKD2NvbS5nb29nbGUudHlwZUINSW50ZXJ2YWxQcm90b1ABWjxnb29nbGUu",
"Z29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL3R5cGUvaW50ZXJ2YWw7",
"aW50ZXJ2YWz4AQGiAgNHVFBiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.Interval), global::Google.Type.Interval.Parser, new[]{ "StartTime", "EndTime" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Represents a time interval, encoded as a Timestamp start (inclusive) and a
/// Timestamp end (exclusive).
///
/// The start must be less than or equal to the end.
/// When the start equals the end, the interval is empty (matches no time).
/// When both start and end are unspecified, the interval matches any time.
/// </summary>
public sealed partial class Interval : pb::IMessage<Interval>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Interval> _parser = new pb::MessageParser<Interval>(() => new Interval());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<Interval> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Type.IntervalReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Interval() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Interval(Interval other) : this() {
startTime_ = other.startTime_ != null ? other.startTime_.Clone() : null;
endTime_ = other.endTime_ != null ? other.endTime_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Interval Clone() {
return new Interval(this);
}
/// <summary>Field number for the "start_time" field.</summary>
public const int StartTimeFieldNumber = 1;
private global::Google.Protobuf.WellKnownTypes.Timestamp startTime_;
/// <summary>
/// Optional. Inclusive start of the interval.
///
/// If specified, a Timestamp matching this interval will have to be the same
/// or after the start.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Protobuf.WellKnownTypes.Timestamp StartTime {
get { return startTime_; }
set {
startTime_ = value;
}
}
/// <summary>Field number for the "end_time" field.</summary>
public const int EndTimeFieldNumber = 2;
private global::Google.Protobuf.WellKnownTypes.Timestamp endTime_;
/// <summary>
/// Optional. Exclusive end of the interval.
///
/// If specified, a Timestamp matching this interval will have to be before the
/// end.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Protobuf.WellKnownTypes.Timestamp EndTime {
get { return endTime_; }
set {
endTime_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as Interval);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(Interval other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(StartTime, other.StartTime)) return false;
if (!object.Equals(EndTime, other.EndTime)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (startTime_ != null) hash ^= StartTime.GetHashCode();
if (endTime_ != null) hash ^= EndTime.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (startTime_ != null) {
output.WriteRawTag(10);
output.WriteMessage(StartTime);
}
if (endTime_ != null) {
output.WriteRawTag(18);
output.WriteMessage(EndTime);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (startTime_ != null) {
output.WriteRawTag(10);
output.WriteMessage(StartTime);
}
if (endTime_ != null) {
output.WriteRawTag(18);
output.WriteMessage(EndTime);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (startTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartTime);
}
if (endTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndTime);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(Interval other) {
if (other == null) {
return;
}
if (other.startTime_ != null) {
if (startTime_ == null) {
StartTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
StartTime.MergeFrom(other.StartTime);
}
if (other.endTime_ != null) {
if (endTime_ == null) {
EndTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
EndTime.MergeFrom(other.EndTime);
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
if (startTime_ == null) {
StartTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(StartTime);
break;
}
case 18: {
if (endTime_ == null) {
EndTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(EndTime);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
if (startTime_ == null) {
StartTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(StartTime);
break;
}
case 18: {
if (endTime_ == null) {
EndTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(EndTime);
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.ExceptionServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading;
namespace System.Net.Mail
{
internal partial class SmtpConnection
{
private static readonly ContextCallback s_AuthenticateCallback = new ContextCallback(AuthenticateCallback);
private BufferBuilder _bufferBuilder = new BufferBuilder();
private bool _isConnected;
private bool _isClosed;
private bool _isStreamOpen;
private EventHandler _onCloseHandler;
internal SmtpTransport _parent;
private SmtpClient _client;
private NetworkStream _networkStream;
internal TcpClient _tcpClient;
internal string _host = null;
internal int _port = 0;
private SmtpReplyReaderFactory _responseReader;
private ICredentialsByHost _credentials;
private int _timeout = 100000;
private string[] _extensions;
private ChannelBinding _channelBindingToken = null;
private bool _enableSsl;
private X509CertificateCollection _clientCertificates;
internal SmtpConnection(SmtpTransport parent, SmtpClient client, ICredentialsByHost credentials, ISmtpAuthenticationModule[] authenticationModules)
{
_client = client;
_credentials = credentials;
_authenticationModules = authenticationModules;
_parent = parent;
_tcpClient = new TcpClient();
_onCloseHandler = new EventHandler(OnClose);
}
internal BufferBuilder BufferBuilder => _bufferBuilder;
internal bool IsConnected => _isConnected;
internal bool IsStreamOpen => _isStreamOpen;
internal SmtpReplyReaderFactory Reader => _responseReader;
internal bool EnableSsl
{
get
{
return _enableSsl;
}
set
{
_enableSsl = value;
}
}
internal int Timeout
{
get
{
return _timeout;
}
set
{
_timeout = value;
}
}
internal X509CertificateCollection ClientCertificates
{
get
{
return _clientCertificates;
}
set
{
_clientCertificates = value;
}
}
internal void InitializeConnection(string host, int port)
{
_tcpClient.Connect(host, port);
_networkStream = _tcpClient.GetStream();
}
internal IAsyncResult BeginInitializeConnection(string host, int port, AsyncCallback callback, object state)
{
return _tcpClient.BeginConnect(host, port, callback, state);
}
internal void EndInitializeConnection(IAsyncResult result)
{
_tcpClient.EndConnect(result);
_networkStream = _tcpClient.GetStream();
}
internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port)
{
ConnectAndHandshakeAsyncResult result = new ConnectAndHandshakeAsyncResult(this, host, port, outerResult, callback, state);
result.GetConnection();
return result;
}
internal IAsyncResult BeginFlush(AsyncCallback callback, object state)
{
return _networkStream.BeginWrite(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length, callback, state);
}
internal void EndFlush(IAsyncResult result)
{
_networkStream.EndWrite(result);
_bufferBuilder.Reset();
}
internal void Flush()
{
_networkStream.Write(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length);
_bufferBuilder.Reset();
}
internal void ReleaseConnection()
{
if (!_isClosed)
{
lock (this)
{
if (!_isClosed && _tcpClient != null)
{
//free cbt buffer
if (_channelBindingToken != null)
{
_channelBindingToken.Close();
}
_networkStream.Close();
_tcpClient.Dispose();
}
_isClosed = true;
}
}
_isConnected = false;
}
internal void Abort()
{
if (!_isClosed)
{
lock (this)
{
if (!_isClosed && _tcpClient != null)
{
//free CBT buffer
if (_channelBindingToken != null)
{
_channelBindingToken.Close();
}
// must destroy manually since sending a QUIT here might not be
// interpreted correctly by the server if it's in the middle of a
// DATA command or some similar situation. This may send a RST
// but this is ok in this situation. Do not reuse this connection
_tcpClient.LingerState = new LingerOption(true, 0);
_networkStream.Close();
_tcpClient.Dispose();
}
_isClosed = true;
}
}
_isConnected = false;
}
internal void GetConnection(string host, int port)
{
if (_isConnected)
{
throw new InvalidOperationException(SR.SmtpAlreadyConnected);
}
InitializeConnection(host, port);
_responseReader = new SmtpReplyReaderFactory(_networkStream);
LineInfo info = _responseReader.GetNextReplyReader().ReadLine();
switch (info.StatusCode)
{
case SmtpStatusCode.ServiceReady:
break;
default:
throw new SmtpException(info.StatusCode, info.Line, true);
}
try
{
_extensions = EHelloCommand.Send(this, _client.clientDomain);
ParseExtensions(_extensions);
}
catch (SmtpException e)
{
if ((e.StatusCode != SmtpStatusCode.CommandUnrecognized)
&& (e.StatusCode != SmtpStatusCode.CommandNotImplemented))
{
throw;
}
HelloCommand.Send(this, _client.clientDomain);
//if ehello isn't supported, assume basic login
_supportedAuth = SupportedAuth.Login;
}
if (_enableSsl)
{
if (!_serverSupportsStartTls)
{
// Either TLS is already established or server does not support TLS
if (!(_networkStream is TlsStream))
{
throw new SmtpException(SR.MailServerDoesNotSupportStartTls);
}
}
StartTlsCommand.Send(this);
TlsStream tlsStream = new TlsStream(_networkStream, _tcpClient.Client, host, _clientCertificates);
tlsStream.AuthenticateAsClient();
_networkStream = tlsStream;
_responseReader = new SmtpReplyReaderFactory(_networkStream);
// According to RFC 3207: The client SHOULD send an EHLO command
// as the first command after a successful TLS negotiation.
_extensions = EHelloCommand.Send(this, _client.clientDomain);
ParseExtensions(_extensions);
}
// if no credentials were supplied, try anonymous
// servers don't appear to anounce that they support anonymous login.
if (_credentials != null)
{
for (int i = 0; i < _authenticationModules.Length; i++)
{
//only authenticate if the auth protocol is supported - chadmu
if (!AuthSupported(_authenticationModules[i]))
{
continue;
}
NetworkCredential credential = _credentials.GetCredential(host, port, _authenticationModules[i].AuthenticationType);
if (credential == null)
continue;
Authorization auth = SetContextAndTryAuthenticate(_authenticationModules[i], credential, null);
if (auth != null && auth.Message != null)
{
info = AuthCommand.Send(this, _authenticationModules[i].AuthenticationType, auth.Message);
if (info.StatusCode == SmtpStatusCode.CommandParameterNotImplemented)
{
continue;
}
while ((int)info.StatusCode == 334)
{
auth = _authenticationModules[i].Authenticate(info.Line, null, this, _client.TargetName, _channelBindingToken);
if (auth == null)
{
throw new SmtpException(SR.SmtpAuthenticationFailed);
}
info = AuthCommand.Send(this, auth.Message);
if ((int)info.StatusCode == 235)
{
_authenticationModules[i].CloseContext(this);
_isConnected = true;
return;
}
}
}
}
}
_isConnected = true;
}
private Authorization SetContextAndTryAuthenticate(ISmtpAuthenticationModule module, NetworkCredential credential, ContextAwareResult context)
{
// We may need to restore user thread token here
if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
{
#if DEBUG
if (context != null && !context.IdentityRequested)
{
NetEventSource.Fail(this, "Authentication required when it wasn't expected. (Maybe Credentials was changed on another thread?)");
}
#endif
try
{
ExecutionContext x = context == null ? null : context.ContextCopy;
if (x != null)
{
AuthenticateCallbackContext authenticationContext =
new AuthenticateCallbackContext(this, module, credential, _client.TargetName, _channelBindingToken);
ExecutionContext.Run(x, s_AuthenticateCallback, authenticationContext);
return authenticationContext._result;
}
else
{
return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken);
}
}
catch
{
// Prevent the impersonation from leaking to upstack exception filters.
throw;
}
}
return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken);
}
private static void AuthenticateCallback(object state)
{
AuthenticateCallbackContext context = (AuthenticateCallbackContext)state;
context._result = context._module.Authenticate(null, context._credential, context._thisPtr, context._spn, context._token);
}
private class AuthenticateCallbackContext
{
internal AuthenticateCallbackContext(SmtpConnection thisPtr, ISmtpAuthenticationModule module, NetworkCredential credential, string spn, ChannelBinding Token)
{
_thisPtr = thisPtr;
_module = module;
_credential = credential;
_spn = spn;
_token = Token;
_result = null;
}
internal readonly SmtpConnection _thisPtr;
internal readonly ISmtpAuthenticationModule _module;
internal readonly NetworkCredential _credential;
internal readonly string _spn;
internal readonly ChannelBinding _token;
internal Authorization _result;
}
internal void EndGetConnection(IAsyncResult result)
{
ConnectAndHandshakeAsyncResult.End(result);
}
internal Stream GetClosableStream()
{
ClosableStream cs = new ClosableStream(_networkStream, _onCloseHandler);
_isStreamOpen = true;
return cs;
}
private void OnClose(object sender, EventArgs args)
{
_isStreamOpen = false;
DataStopCommand.Send(this);
}
private class ConnectAndHandshakeAsyncResult : LazyAsyncResult
{
private string _authResponse;
private SmtpConnection _connection;
private int _currentModule = -1;
private int _port;
private static AsyncCallback s_handshakeCallback = new AsyncCallback(HandshakeCallback);
private static AsyncCallback s_sendEHelloCallback = new AsyncCallback(SendEHelloCallback);
private static AsyncCallback s_sendHelloCallback = new AsyncCallback(SendHelloCallback);
private static AsyncCallback s_authenticateCallback = new AsyncCallback(AuthenticateCallback);
private static AsyncCallback s_authenticateContinueCallback = new AsyncCallback(AuthenticateContinueCallback);
private string _host;
private readonly ContextAwareResult _outerResult;
internal ConnectAndHandshakeAsyncResult(SmtpConnection connection, string host, int port, ContextAwareResult outerResult, AsyncCallback callback, object state) :
base(null, state, callback)
{
_connection = connection;
_host = host;
_port = port;
_outerResult = outerResult;
}
internal static void End(IAsyncResult result)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result;
object connectResult = thisPtr.InternalWaitForCompletion();
if (connectResult is Exception e)
{
ExceptionDispatchInfo.Throw(e);
}
}
internal void GetConnection()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (_connection._isConnected)
{
throw new InvalidOperationException(SR.SmtpAlreadyConnected);
}
InitializeConnection();
}
private void InitializeConnection()
{
IAsyncResult result = _connection.BeginInitializeConnection(_host, _port, InitializeConnectionCallback, this);
if (result.CompletedSynchronously)
{
_connection.EndInitializeConnection(result);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Connect returned");
try
{
Handshake();
}
catch (Exception e)
{
InvokeCallback(e);
}
}
}
private static void InitializeConnectionCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
thisPtr._connection.EndInitializeConnection(result);
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Connect returned {thisPtr}");
try
{
thisPtr.Handshake();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private void Handshake()
{
_connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream);
SmtpReplyReader reader = _connection.Reader.GetNextReplyReader();
IAsyncResult result = reader.BeginReadLine(s_handshakeCallback, this);
if (!result.CompletedSynchronously)
{
return;
}
LineInfo info = reader.EndReadLine(result);
if (info.StatusCode != SmtpStatusCode.ServiceReady)
{
throw new SmtpException(info.StatusCode, info.Line, true);
}
try
{
if (!SendEHello())
{
return;
}
}
catch
{
if (!SendHello())
{
return;
}
}
}
private static void HandshakeCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
try
{
LineInfo info = thisPtr._connection.Reader.CurrentReader.EndReadLine(result);
if (info.StatusCode != SmtpStatusCode.ServiceReady)
{
thisPtr.InvokeCallback(new SmtpException(info.StatusCode, info.Line, true));
return;
}
if (!thisPtr.SendEHello())
{
return;
}
}
catch (SmtpException)
{
if (!thisPtr.SendHello())
{
return;
}
}
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private bool SendEHello()
{
IAsyncResult result = EHelloCommand.BeginSend(_connection, _connection._client.clientDomain, s_sendEHelloCallback, this);
if (result.CompletedSynchronously)
{
_connection._extensions = EHelloCommand.EndSend(result);
_connection.ParseExtensions(_connection._extensions);
// If we already have a TlsStream, this is the second EHLO cmd
// that we sent after TLS handshake compelted. So skip TLS and
// continue with Authenticate.
if (_connection._networkStream is TlsStream)
{
Authenticate();
return true;
}
if (_connection.EnableSsl)
{
if (!_connection._serverSupportsStartTls)
{
// Either TLS is already established or server does not support TLS
if (!(_connection._networkStream is TlsStream))
{
throw new SmtpException(SR.Format(SR.MailServerDoesNotSupportStartTls));
}
}
SendStartTls();
}
else
{
Authenticate();
}
return true;
}
return false;
}
private static void SendEHelloCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
try
{
thisPtr._connection._extensions = EHelloCommand.EndSend(result);
thisPtr._connection.ParseExtensions(thisPtr._connection._extensions);
// If we already have a SSlStream, this is the second EHLO cmd
// that we sent after TLS handshake compelted. So skip TLS and
// continue with Authenticate.
if (thisPtr._connection._networkStream is TlsStream)
{
thisPtr.Authenticate();
return;
}
}
catch (SmtpException e)
{
if ((e.StatusCode != SmtpStatusCode.CommandUnrecognized)
&& (e.StatusCode != SmtpStatusCode.CommandNotImplemented))
{
throw;
}
if (!thisPtr.SendHello())
{
return;
}
}
if (thisPtr._connection.EnableSsl)
{
if (!thisPtr._connection._serverSupportsStartTls)
{
// Either TLS is already established or server does not support TLS
if (!(thisPtr._connection._networkStream is TlsStream))
{
throw new SmtpException(SR.MailServerDoesNotSupportStartTls);
}
}
thisPtr.SendStartTls();
}
else
{
thisPtr.Authenticate();
}
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private bool SendHello()
{
IAsyncResult result = HelloCommand.BeginSend(_connection, _connection._client.clientDomain, s_sendHelloCallback, this);
//if ehello isn't supported, assume basic auth
if (result.CompletedSynchronously)
{
_connection._supportedAuth = SupportedAuth.Login;
HelloCommand.EndSend(result);
Authenticate();
return true;
}
return false;
}
private static void SendHelloCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
HelloCommand.EndSend(result);
thisPtr.Authenticate();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private bool SendStartTls()
{
IAsyncResult result = StartTlsCommand.BeginSend(_connection, SendStartTlsCallback, this);
if (result.CompletedSynchronously)
{
StartTlsCommand.EndSend(result);
TlsStreamAuthenticate();
return true;
}
return false;
}
private static void SendStartTlsCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
StartTlsCommand.EndSend(result);
thisPtr.TlsStreamAuthenticate();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private bool TlsStreamAuthenticate()
{
_connection._networkStream = new TlsStream(_connection._networkStream, _connection._tcpClient.Client, _host, _connection._clientCertificates);
IAsyncResult result = (_connection._networkStream as TlsStream).BeginAuthenticateAsClient(TlsStreamAuthenticateCallback, this);
if (result.CompletedSynchronously)
{
(_connection._networkStream as TlsStream).EndAuthenticateAsClient(result);
_connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream);
SendEHello();
return true;
}
return false;
}
private static void TlsStreamAuthenticateCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
(thisPtr._connection._networkStream as TlsStream).EndAuthenticateAsClient(result);
thisPtr._connection._responseReader = new SmtpReplyReaderFactory(thisPtr._connection._networkStream);
thisPtr.SendEHello();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private void Authenticate()
{
//if no credentials were supplied, try anonymous
//servers don't appear to anounce that they support anonymous login.
if (_connection._credentials != null)
{
while (++_currentModule < _connection._authenticationModules.Length)
{
//only authenticate if the auth protocol is supported
ISmtpAuthenticationModule module = _connection._authenticationModules[_currentModule];
if (!_connection.AuthSupported(module))
{
continue;
}
NetworkCredential credential = _connection._credentials.GetCredential(_host, _port, module.AuthenticationType);
if (credential == null)
continue;
Authorization auth = _connection.SetContextAndTryAuthenticate(module, credential, _outerResult);
if (auth != null && auth.Message != null)
{
IAsyncResult result = AuthCommand.BeginSend(_connection, _connection._authenticationModules[_currentModule].AuthenticationType, auth.Message, s_authenticateCallback, this);
if (!result.CompletedSynchronously)
{
return;
}
LineInfo info = AuthCommand.EndSend(result);
if ((int)info.StatusCode == 334)
{
_authResponse = info.Line;
if (!AuthenticateContinue())
{
return;
}
}
else if ((int)info.StatusCode == 235)
{
module.CloseContext(_connection);
_connection._isConnected = true;
break;
}
}
}
}
_connection._isConnected = true;
InvokeCallback();
}
private static void AuthenticateCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
LineInfo info = AuthCommand.EndSend(result);
if ((int)info.StatusCode == 334)
{
thisPtr._authResponse = info.Line;
if (!thisPtr.AuthenticateContinue())
{
return;
}
}
else if ((int)info.StatusCode == 235)
{
thisPtr._connection._authenticationModules[thisPtr._currentModule].CloseContext(thisPtr._connection);
thisPtr._connection._isConnected = true;
thisPtr.InvokeCallback();
return;
}
thisPtr.Authenticate();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
private bool AuthenticateContinue()
{
for (;;)
{
// We don't need credential on the continued auth assuming they were captured on the first call.
// That should always work, otherwise what if a new credential has been returned?
Authorization auth = _connection._authenticationModules[_currentModule].Authenticate(_authResponse, null, _connection, _connection._client.TargetName, _connection._channelBindingToken);
if (auth == null)
{
throw new SmtpException(SR.Format(SR.SmtpAuthenticationFailed));
}
IAsyncResult result = AuthCommand.BeginSend(_connection, auth.Message, s_authenticateContinueCallback, this);
if (!result.CompletedSynchronously)
{
return false;
}
LineInfo info = AuthCommand.EndSend(result);
if ((int)info.StatusCode == 235)
{
_connection._authenticationModules[_currentModule].CloseContext(_connection);
_connection._isConnected = true;
InvokeCallback();
return false;
}
else if ((int)info.StatusCode != 334)
{
return true;
}
_authResponse = info.Line;
}
}
private static void AuthenticateContinueCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
try
{
LineInfo info = AuthCommand.EndSend(result);
if ((int)info.StatusCode == 235)
{
thisPtr._connection._authenticationModules[thisPtr._currentModule].CloseContext(thisPtr._connection);
thisPtr._connection._isConnected = true;
thisPtr.InvokeCallback();
return;
}
else if ((int)info.StatusCode == 334)
{
thisPtr._authResponse = info.Line;
if (!thisPtr.AuthenticateContinue())
{
return;
}
}
thisPtr.Authenticate();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
namespace System.Runtime.Serialization
{
#if uapaot
public class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext
#else
internal class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext
#endif
{
private bool _preserveObjectReferences;
private SerializationMode _mode;
private ISerializationSurrogateProvider _serializationSurrogateProvider;
internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
: base(serializer, rootTypeDataContract, dataContractResolver)
{
_mode = SerializationMode.SharedContract;
_preserveObjectReferences = serializer.PreserveObjectReferences;
_serializationSurrogateProvider = serializer.SerializationSurrogateProvider;
}
internal XmlObjectSerializerReadContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
: base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
{
}
internal override SerializationMode Mode
{
get { return _mode; }
}
internal override object InternalDeserialize(XmlReaderDelegator xmlReader, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, string name, string ns)
{
if (_mode == SerializationMode.SharedContract)
{
if (_serializationSurrogateProvider == null)
return base.InternalDeserialize(xmlReader, declaredTypeID, declaredTypeHandle, name, ns);
else
return InternalDeserializeWithSurrogate(xmlReader, Type.GetTypeFromHandle(declaredTypeHandle), null /*surrogateDataContract*/, name, ns);
}
else
{
return InternalDeserializeInSharedTypeMode(xmlReader, declaredTypeID, Type.GetTypeFromHandle(declaredTypeHandle), name, ns);
}
}
internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns)
{
if (_mode == SerializationMode.SharedContract)
{
if (_serializationSurrogateProvider == null)
return base.InternalDeserialize(xmlReader, declaredType, name, ns);
else
return InternalDeserializeWithSurrogate(xmlReader, declaredType, null /*surrogateDataContract*/, name, ns);
}
else
{
return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
}
}
internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns)
{
if (_mode == SerializationMode.SharedContract)
{
if (_serializationSurrogateProvider == null)
return base.InternalDeserialize(xmlReader, declaredType, dataContract, name, ns);
else
return InternalDeserializeWithSurrogate(xmlReader, declaredType, dataContract, name, ns);
}
else
{
return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
}
}
private object InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string name, string ns)
{
object retObj = null;
if (TryHandleNullOrRef(xmlReader, declaredType, name, ns, ref retObj))
return retObj;
DataContract dataContract;
string assemblyName = attributes.ClrAssembly;
string typeName = attributes.ClrType;
if (assemblyName != null && typeName != null)
{
Assembly assembly;
Type type;
dataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type);
if (dataContract == null)
{
if (assembly == null)
throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.AssemblyNotFound, assemblyName));
if (type == null)
throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ClrTypeNotFound, assembly.FullName, typeName));
}
//Array covariance is not supported in XSD. If declared type is array, data is sent in format of base array
if (declaredType != null && declaredType.IsArray)
dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
}
else
{
if (assemblyName != null)
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
else if (typeName != null)
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
else if (declaredType == null)
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
}
return ReadDataContractValue(dataContract, xmlReader);
}
private object InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, string name, string ns)
{
DataContract dataContract = surrogateDataContract ??
GetDataContract(DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, declaredType));
if (this.IsGetOnlyCollection && dataContract.UnderlyingType != declaredType)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(declaredType))));
}
ReadAttributes(xmlReader);
string objectId = GetObjectId();
object oldObj = InternalDeserialize(xmlReader, name, ns, ref dataContract);
object obj = DataContractSurrogateCaller.GetDeserializedObject(_serializationSurrogateProvider, oldObj, dataContract.UnderlyingType, declaredType);
ReplaceDeserializedObject(objectId, oldObj, obj);
return obj;
}
private Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly)
{
// The method is used only when _mode == SerializationMode.SharedType.
// _mode is set to SerializationMode.SharedType only when the context is for NetDataContractSerializer.
throw new PlatformNotSupportedException(SR.PlatformNotSupported_NetDataContractSerializer);
}
private DataContract ResolveDataContractInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly, out Type type)
{
type = ResolveDataContractTypeInSharedTypeMode(assemblyName, typeName, out assembly);
if (type != null)
{
return GetDataContract(type);
}
return null;
}
protected override DataContract ResolveDataContractFromTypeName()
{
if (_mode == SerializationMode.SharedContract)
{
return base.ResolveDataContractFromTypeName();
}
else
{
if (attributes.ClrAssembly != null && attributes.ClrType != null)
{
Assembly assembly;
Type type;
return ResolveDataContractInSharedTypeMode(attributes.ClrAssembly, attributes.ClrType, out assembly, out type);
}
}
return null;
}
internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable)
{
if (_serializationSurrogateProvider != null)
{
while (memberType.IsArray)
memberType = memberType.GetElementType();
memberType = DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, memberType);
if (!DataContract.IsTypeSerializable(memberType))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TypeNotSerializable, memberType)));
return;
}
base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable);
}
internal override Type GetSurrogatedType(Type type)
{
if (_serializationSurrogateProvider == null)
{
return base.GetSurrogatedType(type);
}
else
{
type = DataContract.UnwrapNullableType(type);
Type surrogateType = DataContractSerializer.GetSurrogatedType(_serializationSurrogateProvider, type);
if (this.IsGetOnlyCollection && surrogateType != type)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser,
DataContract.GetClrTypeFullName(type))));
}
else
{
return surrogateType;
}
}
}
#if USE_REFEMIT
public override int GetArraySize()
#else
internal override int GetArraySize()
#endif
{
return _preserveObjectReferences ? attributes.ArraySZSize : -1;
}
}
}
| |
/*
* Copyright 2011 The Poderosa Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* $Id: OpenSSHPrivateKeyLoader.cs,v 1.1 2011/11/03 16:27:38 kzmi Exp $
*/
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using Granados.Crypto;
using Granados.PKI;
using Granados.Util;
namespace Granados.Poderosa.KeyFormat {
/// <summary>
/// OpenSSH SSH2 private key loader
/// </summary>
internal class OpenSSHPrivateKeyLoader : ISSH2PrivateKeyLoader {
private readonly string keyFilePath;
private readonly byte[] keyFile;
private enum KeyType {
RSA,
DSA,
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="keyFile">key file data</param>
/// <param name="keyFilePath">Path of a key file</param>
public OpenSSHPrivateKeyLoader(byte[] keyFile, string keyFilePath) {
this.keyFilePath = keyFilePath;
this.keyFile = keyFile;
}
/// <summary>
/// Read OpenSSH SSH2 private key parameters.
/// </summary>
/// <param name="passphrase">passphrase for decrypt the key file</param>
/// <param name="keyPair">key pair</param>
/// <param name="comment">comment or empty if it didn't exist</param>
public void Load(string passphrase, out KeyPair keyPair, out string comment) {
if (keyFile == null)
throw new SSHException("A key file is not loaded yet");
KeyType keyType;
String base64Text;
bool encrypted = false;
CipherAlgorithm? encryption = null;
byte[] iv = null;
int keySize = 0;
int ivSize = 0;
using (StreamReader sreader = GetStreamReader()) {
string line = sreader.ReadLine();
if (line == null)
throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected eof)");
if (line == PrivateKeyFileHeader.SSH2_OPENSSH_HEADER_RSA)
keyType = KeyType.RSA;
else if (line == PrivateKeyFileHeader.SSH2_OPENSSH_HEADER_DSA)
keyType = KeyType.DSA;
else
throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected key type)");
string footer = line.Replace("BEGIN", "END");
StringBuilder buf = new StringBuilder();
comment = String.Empty;
while (true) {
line = sreader.ReadLine();
if (line == null)
throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected eof)");
if (line == footer)
break;
if (line.IndexOf(':') >= 0) {
if (line.StartsWith("Proc-Type:")) {
string[] w = line.Substring("Proc-Type:".Length).Trim().Split(',');
if (w.Length < 1)
throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid Proc-Type)");
if (w[0] != "4")
throw new SSHException(Strings.GetString("UnsupportedPrivateKeyFormat")
+ " (" + Strings.GetString("Reason_UnsupportedProcType") + ")");
if (w.Length >= 2 && w[1] == "ENCRYPTED")
encrypted = true;
}
else if (line.StartsWith("DEK-Info:")) {
string[] w = line.Substring("DEK-Info:".Length).Trim().Split(',');
if (w.Length < 2)
throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid DEK-Info)");
switch (w[0]) {
case "DES-EDE3-CBC":
encryption = CipherAlgorithm.TripleDES;
ivSize = 8;
keySize = 24;
break;
case "AES-128-CBC":
encryption = CipherAlgorithm.AES128;
ivSize = 16;
keySize = 16;
break;
default:
throw new SSHException(Strings.GetString("UnsupportedPrivateKeyFormat")
+ " (" + Strings.GetString("Reason_UnsupportedEncryptionType") + ")");
}
iv = HexToByteArray(w[1]);
if (iv == null || iv.Length != ivSize)
throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid IV)");
}
}
else
buf.Append(line);
}
base64Text = buf.ToString();
}
byte[] keydata = Base64.Decode(Encoding.ASCII.GetBytes(base64Text));
if (encrypted) {
if (!encryption.HasValue || iv == null)
throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing encryption type or IV)");
byte[] key = OpenSSHPassphraseToKey(passphrase, iv, keySize);
Cipher cipher = CipherFactory.CreateCipher(SSHProtocol.SSH2, encryption.Value, key, iv);
if (keydata.Length % cipher.BlockSize != 0)
throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid key data size)");
cipher.Decrypt(keydata, 0, keydata.Length, keydata, 0);
}
using (MemoryStream keyDataStream = new MemoryStream(keydata, false)) {
BERReader reader = new BERReader(keyDataStream);
if (!reader.ReadSequence())
throw new SSHException(Strings.GetString("WrongPassphrase"));
if (keyType == KeyType.RSA) {
/* from OpenSSL rsa_asn1.c
*
* ASN1_SIMPLE(RSA, version, LONG),
* ASN1_SIMPLE(RSA, n, BIGNUM),
* ASN1_SIMPLE(RSA, e, BIGNUM),
* ASN1_SIMPLE(RSA, d, BIGNUM),
* ASN1_SIMPLE(RSA, p, BIGNUM),
* ASN1_SIMPLE(RSA, q, BIGNUM),
* ASN1_SIMPLE(RSA, dmp1, BIGNUM),
* ASN1_SIMPLE(RSA, dmq1, BIGNUM),
* ASN1_SIMPLE(RSA, iqmp, BIGNUM)
*/
BigInteger v, n, e, d, p, q, dmp1, dmq1, iqmp;
if (!reader.ReadInteger(out v) ||
!reader.ReadInteger(out n) ||
!reader.ReadInteger(out e) ||
!reader.ReadInteger(out d) ||
!reader.ReadInteger(out p) ||
!reader.ReadInteger(out q) ||
!reader.ReadInteger(out dmp1) ||
!reader.ReadInteger(out dmq1) ||
!reader.ReadInteger(out iqmp)) {
throw new SSHException(Strings.GetString("WrongPassphrase"));
}
BigInteger u = p.modInverse(q); // inverse of p mod q
keyPair = new RSAKeyPair(e, d, n, u, p, q);
}
else if (keyType == KeyType.DSA) {
/* from OpenSSL dsa_asn1.c
*
* ASN1_SIMPLE(DSA, version, LONG),
* ASN1_SIMPLE(DSA, p, BIGNUM),
* ASN1_SIMPLE(DSA, q, BIGNUM),
* ASN1_SIMPLE(DSA, g, BIGNUM),
* ASN1_SIMPLE(DSA, pub_key, BIGNUM),
* ASN1_SIMPLE(DSA, priv_key, BIGNUM)
*/
BigInteger v, p, q, g, y, x;
if (!reader.ReadInteger(out v) ||
!reader.ReadInteger(out p) ||
!reader.ReadInteger(out q) ||
!reader.ReadInteger(out g) ||
!reader.ReadInteger(out y) ||
!reader.ReadInteger(out x)) {
throw new SSHException(Strings.GetString("WrongPassphrase"));
}
keyPair = new DSAKeyPair(p, g, q, y, x);
}
else {
throw new SSHException("Unknown file type. This should not happen.");
}
}
}
private static byte[] OpenSSHPassphraseToKey(string passphrase, byte[] iv, int length) {
const int HASH_SIZE = 16;
const int SALT_SIZE = 8;
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] pp = Encoding.UTF8.GetBytes(passphrase);
byte[] buf = new byte[((length + HASH_SIZE - 1) / HASH_SIZE) * HASH_SIZE];
int offset = 0;
while (offset < length) {
if (offset > 0)
md5.TransformBlock(buf, 0, offset, null, 0);
md5.TransformBlock(pp, 0, pp.Length, null, 0);
md5.TransformFinalBlock(iv, 0, SALT_SIZE);
Buffer.BlockCopy(md5.Hash, 0, buf, offset, HASH_SIZE);
offset += HASH_SIZE;
md5.Initialize();
}
md5.Clear();
byte[] key = new byte[length];
Buffer.BlockCopy(buf, 0, key, 0, length);
return key;
}
private static byte[] HexToByteArray(string text) {
if (text.Length % 2 != 0)
return null;
int len = text.Length / 2;
byte[] buf = new byte[len];
for (int i = 0; i < len; i++) {
byte b;
if (!Byte.TryParse(text.Substring(i * 2, 2),
NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo, out b)) {
return null;
}
buf[i] = b;
}
return buf;
}
private StreamReader GetStreamReader() {
MemoryStream mem = new MemoryStream(keyFile, false);
return new StreamReader(mem, Encoding.ASCII);
}
}
}
| |
#region License
/*
* HttpListenerWebSocketContext.cs
*
* The MIT License
*
* Copyright (c) 2012-2016 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Security.Principal;
namespace CustomWebSocketSharp.Net.WebSockets
{
/// <summary>
/// Provides the properties used to access the information in
/// a WebSocket handshake request received by the <see cref="HttpListener"/>.
/// </summary>
public class HttpListenerWebSocketContext : WebSocketContext
{
#region Private Fields
private HttpListenerContext _context;
private WebSocket _websocket;
#endregion
#region Internal Constructors
internal HttpListenerWebSocketContext (HttpListenerContext context, string protocol)
{
_context = context;
_websocket = new WebSocket (this, protocol);
}
#endregion
#region Internal Properties
internal Logger Log {
get {
return _context.Listener.Log;
}
}
internal Stream Stream {
get {
return _context.Connection.Stream;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the HTTP cookies included in the request.
/// </summary>
/// <value>
/// A <see cref="CustomWebSocketSharp.Net.CookieCollection"/> that contains the cookies.
/// </value>
public override CookieCollection CookieCollection {
get {
return _context.Request.Cookies;
}
}
/// <summary>
/// Gets the HTTP headers included in the request.
/// </summary>
/// <value>
/// A <see cref="NameValueCollection"/> that contains the headers.
/// </value>
public override NameValueCollection Headers {
get {
return _context.Request.Headers;
}
}
/// <summary>
/// Gets the value of the Host header included in the request.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the Host header.
/// </value>
public override string Host {
get {
return _context.Request.Headers["Host"];
}
}
/// <summary>
/// Gets a value indicating whether the client is authenticated.
/// </summary>
/// <value>
/// <c>true</c> if the client is authenticated; otherwise, <c>false</c>.
/// </value>
public override bool IsAuthenticated {
get {
return _context.User != null;
}
}
/// <summary>
/// Gets a value indicating whether the client connected from the local computer.
/// </summary>
/// <value>
/// <c>true</c> if the client connected from the local computer; otherwise, <c>false</c>.
/// </value>
public override bool IsLocal {
get {
return _context.Request.IsLocal;
}
}
/// <summary>
/// Gets a value indicating whether the WebSocket connection is secured.
/// </summary>
/// <value>
/// <c>true</c> if the connection is secured; otherwise, <c>false</c>.
/// </value>
public override bool IsSecureConnection {
get {
return _context.Connection.IsSecure;
}
}
/// <summary>
/// Gets a value indicating whether the request is a WebSocket handshake request.
/// </summary>
/// <value>
/// <c>true</c> if the request is a WebSocket handshake request; otherwise, <c>false</c>.
/// </value>
public override bool IsWebSocketRequest {
get {
return _context.Request.IsWebSocketRequest;
}
}
/// <summary>
/// Gets the value of the Origin header included in the request.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the Origin header.
/// </value>
public override string Origin {
get {
return _context.Request.Headers["Origin"];
}
}
/// <summary>
/// Gets the query string included in the request.
/// </summary>
/// <value>
/// A <see cref="NameValueCollection"/> that contains the query string parameters.
/// </value>
public override NameValueCollection QueryString {
get {
return _context.Request.QueryString;
}
}
/// <summary>
/// Gets the URI requested by the client.
/// </summary>
/// <value>
/// A <see cref="Uri"/> that represents the requested URI.
/// </value>
public override Uri RequestUri {
get {
return _context.Request.Url;
}
}
/// <summary>
/// Gets the value of the Sec-WebSocket-Key header included in the request.
/// </summary>
/// <remarks>
/// This property provides a part of the information used by the server to prove that
/// it received a valid WebSocket handshake request.
/// </remarks>
/// <value>
/// A <see cref="string"/> that represents the value of the Sec-WebSocket-Key header.
/// </value>
public override string SecWebSocketKey {
get {
return _context.Request.Headers["Sec-WebSocket-Key"];
}
}
/// <summary>
/// Gets the values of the Sec-WebSocket-Protocol header included in the request.
/// </summary>
/// <remarks>
/// This property represents the subprotocols requested by the client.
/// </remarks>
/// <value>
/// An <see cref="T:System.Collections.Generic.IEnumerable{string}"/> instance that provides
/// an enumerator which supports the iteration over the values of the Sec-WebSocket-Protocol
/// header.
/// </value>
public override IEnumerable<string> SecWebSocketProtocols {
get {
var protocols = _context.Request.Headers["Sec-WebSocket-Protocol"];
if (protocols != null) {
foreach (var protocol in protocols.Split (','))
yield return protocol.Trim ();
}
}
}
/// <summary>
/// Gets the value of the Sec-WebSocket-Version header included in the request.
/// </summary>
/// <remarks>
/// This property represents the WebSocket protocol version.
/// </remarks>
/// <value>
/// A <see cref="string"/> that represents the value of the Sec-WebSocket-Version header.
/// </value>
public override string SecWebSocketVersion {
get {
return _context.Request.Headers["Sec-WebSocket-Version"];
}
}
/// <summary>
/// Gets the server endpoint as an IP address and a port number.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the server endpoint.
/// </value>
public override System.Net.IPEndPoint ServerEndPoint {
get {
return _context.Connection.LocalEndPoint;
}
}
/// <summary>
/// Gets the client information (identity, authentication, and security roles).
/// </summary>
/// <value>
/// A <see cref="IPrincipal"/> instance that represents the client information.
/// </value>
public override IPrincipal User {
get {
return _context.User;
}
}
/// <summary>
/// Gets the client endpoint as an IP address and a port number.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the client endpoint.
/// </value>
public override System.Net.IPEndPoint UserEndPoint {
get {
return _context.Connection.RemoteEndPoint;
}
}
/// <summary>
/// Gets the <see cref="CustomWebSocketSharp.WebSocket"/> instance used for
/// two-way communication between client and server.
/// </summary>
/// <value>
/// A <see cref="CustomWebSocketSharp.WebSocket"/>.
/// </value>
public override WebSocket WebSocket {
get {
return _websocket;
}
}
#endregion
#region Internal Methods
internal void Close ()
{
_context.Connection.Close (true);
}
internal void Close (HttpStatusCode code)
{
_context.Response.Close (code);
}
#endregion
#region Public Methods
/// <summary>
/// Returns a <see cref="string"/> that represents
/// the current <see cref="HttpListenerWebSocketContext"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents
/// the current <see cref="HttpListenerWebSocketContext"/>.
/// </returns>
public override string ToString ()
{
return _context.Request.ToString ();
}
#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.Data
{
using System.Collections.ObjectModel;
/// <summary>
/// Represents the set of actions available for a rule.
/// </summary>
public sealed class RuleActions : ComplexProperty
{
/// <summary>
/// SMS recipient address type.
/// </summary>
private const string MobileType = "MOBILE";
/// <summary>
/// The AssignCategories action.
/// </summary>
private StringList assignCategories;
/// <summary>
/// The CopyToFolder action.
/// </summary>
private FolderId copyToFolder;
/// <summary>
/// The Delete action.
/// </summary>
private bool delete;
/// <summary>
/// The ForwardAsAttachmentToRecipients action.
/// </summary>
private EmailAddressCollection forwardAsAttachmentToRecipients;
/// <summary>
/// The ForwardToRecipients action.
/// </summary>
private EmailAddressCollection forwardToRecipients;
/// <summary>
/// The MarkImportance action.
/// </summary>
private Importance? markImportance;
/// <summary>
/// The MarkAsRead action.
/// </summary>
private bool markAsRead;
/// <summary>
/// The MoveToFolder action.
/// </summary>
private FolderId moveToFolder;
/// <summary>
/// The PermanentDelete action.
/// </summary>
private bool permanentDelete;
/// <summary>
/// The RedirectToRecipients action.
/// </summary>
private EmailAddressCollection redirectToRecipients;
/// <summary>
/// The SendSMSAlertToRecipients action.
/// </summary>
private Collection<MobilePhone> sendSMSAlertToRecipients;
/// <summary>
/// The ServerReplyWithMessage action.
/// </summary>
private ItemId serverReplyWithMessage;
/// <summary>
/// The StopProcessingRules action.
/// </summary>
private bool stopProcessingRules;
/// <summary>
/// Initializes a new instance of the <see cref="RulePredicates"/> class.
/// </summary>
internal RuleActions()
: base()
{
this.assignCategories = new StringList();
this.forwardAsAttachmentToRecipients = new EmailAddressCollection(XmlElementNames.Address);
this.forwardToRecipients = new EmailAddressCollection(XmlElementNames.Address);
this.redirectToRecipients = new EmailAddressCollection(XmlElementNames.Address);
this.sendSMSAlertToRecipients = new Collection<MobilePhone>();
}
/// <summary>
/// Gets the categories that should be stamped on incoming messages.
/// To disable stamping incoming messages with categories, set
/// AssignCategories to null.
/// </summary>
public StringList AssignCategories
{
get
{
return this.assignCategories;
}
}
/// <summary>
/// Gets or sets the Id of the folder incoming messages should be copied to.
/// To disable copying incoming messages to a folder, set CopyToFolder to null.
/// </summary>
public FolderId CopyToFolder
{
get
{
return this.copyToFolder;
}
set
{
this.SetFieldValue<FolderId>(ref this.copyToFolder, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether incoming messages should be
/// automatically moved to the Deleted Items folder.
/// </summary>
public bool Delete
{
get
{
return this.delete;
}
set
{
this.SetFieldValue<bool>(ref this.delete, value);
}
}
/// <summary>
/// Gets the e-mail addresses to which incoming messages should be
/// forwarded as attachments. To disable forwarding incoming messages
/// as attachments, empty the ForwardAsAttachmentToRecipients list.
/// </summary>
public EmailAddressCollection ForwardAsAttachmentToRecipients
{
get
{
return this.forwardAsAttachmentToRecipients;
}
}
/// <summary>
/// Gets the e-mail addresses to which incoming messages should be forwarded.
/// To disable forwarding incoming messages, empty the ForwardToRecipients list.
/// </summary>
public EmailAddressCollection ForwardToRecipients
{
get
{
return this.forwardToRecipients;
}
}
/// <summary>
/// Gets or sets the importance that should be stamped on incoming
/// messages. To disable the stamping of incoming messages with an
/// importance, set MarkImportance to null.
/// </summary>
public Importance? MarkImportance
{
get
{
return this.markImportance;
}
set
{
this.SetFieldValue<Importance?>(ref this.markImportance, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether incoming messages should be
/// marked as read.
/// </summary>
public bool MarkAsRead
{
get
{
return this.markAsRead;
}
set
{
this.SetFieldValue<bool>(ref this.markAsRead, value);
}
}
/// <summary>
/// Gets or sets the Id of the folder to which incoming messages should be
/// moved. To disable the moving of incoming messages to a folder, set
/// CopyToFolder to null.
/// </summary>
public FolderId MoveToFolder
{
get
{
return this.moveToFolder;
}
set
{
this.SetFieldValue<FolderId>(ref this.moveToFolder, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether incoming messages should be
/// permanently deleted. When a message is permanently deleted, it is never
/// saved into the recipient's mailbox. To delete a message after it has
/// been saved into the recipient's mailbox, use the Delete action.
/// </summary>
public bool PermanentDelete
{
get
{
return this.permanentDelete;
}
set
{
this.SetFieldValue<bool>(ref this.permanentDelete, value);
}
}
/// <summary>
/// Gets the e-mail addresses to which incoming messages should be
/// redirecteded. To disable redirection of incoming messages, empty
/// the RedirectToRecipients list. Unlike forwarded mail, redirected mail
/// maintains the original sender and recipients.
/// </summary>
public EmailAddressCollection RedirectToRecipients
{
get
{
return this.redirectToRecipients;
}
}
/// <summary>
/// Gets the phone numbers to which an SMS alert should be sent. To disable
/// sending SMS alerts for incoming messages, empty the
/// SendSMSAlertToRecipients list.
/// </summary>
public Collection<MobilePhone> SendSMSAlertToRecipients
{
get
{
return this.sendSMSAlertToRecipients;
}
}
/// <summary>
/// Gets or sets the Id of the template message that should be sent
/// as a reply to incoming messages. To disable automatic replies, set
/// ServerReplyWithMessage to null.
/// </summary>
public ItemId ServerReplyWithMessage
{
get
{
return this.serverReplyWithMessage;
}
set
{
this.SetFieldValue<ItemId>(ref this.serverReplyWithMessage, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether subsequent rules should be
/// evaluated.
/// </summary>
public bool StopProcessingRules
{
get
{
return this.stopProcessingRules;
}
set
{
this.SetFieldValue<bool>(ref this.stopProcessingRules, value);
}
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>True if element was read.</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
switch (reader.LocalName)
{
case XmlElementNames.AssignCategories:
this.assignCategories.LoadFromXml(reader, reader.LocalName);
return true;
case XmlElementNames.CopyToFolder:
reader.ReadStartElement(XmlNamespace.NotSpecified, XmlElementNames.FolderId);
this.copyToFolder = new FolderId();
this.copyToFolder.LoadFromXml(reader, XmlElementNames.FolderId);
reader.ReadEndElement(XmlNamespace.NotSpecified, XmlElementNames.CopyToFolder);
return true;
case XmlElementNames.Delete:
this.delete = reader.ReadElementValue<bool>();
return true;
case XmlElementNames.ForwardAsAttachmentToRecipients:
this.forwardAsAttachmentToRecipients.LoadFromXml(reader, reader.LocalName);
return true;
case XmlElementNames.ForwardToRecipients:
this.forwardToRecipients.LoadFromXml(reader, reader.LocalName);
return true;
case XmlElementNames.MarkImportance:
this.markImportance = reader.ReadElementValue<Importance>();
return true;
case XmlElementNames.MarkAsRead:
this.markAsRead = reader.ReadElementValue<bool>();
return true;
case XmlElementNames.MoveToFolder:
reader.ReadStartElement(XmlNamespace.NotSpecified, XmlElementNames.FolderId);
this.moveToFolder = new FolderId();
this.moveToFolder.LoadFromXml(reader, XmlElementNames.FolderId);
reader.ReadEndElement(XmlNamespace.NotSpecified, XmlElementNames.MoveToFolder);
return true;
case XmlElementNames.PermanentDelete:
this.permanentDelete = reader.ReadElementValue<bool>();
return true;
case XmlElementNames.RedirectToRecipients:
this.redirectToRecipients.LoadFromXml(reader, reader.LocalName);
return true;
case XmlElementNames.SendSMSAlertToRecipients:
EmailAddressCollection smsRecipientCollection = new EmailAddressCollection(XmlElementNames.Address);
smsRecipientCollection.LoadFromXml(reader, reader.LocalName);
this.sendSMSAlertToRecipients = ConvertSMSRecipientsFromEmailAddressCollectionToMobilePhoneCollection(smsRecipientCollection);
return true;
case XmlElementNames.ServerReplyWithMessage:
this.serverReplyWithMessage = new ItemId();
this.serverReplyWithMessage.LoadFromXml(reader, reader.LocalName);
return true;
case XmlElementNames.StopProcessingRules:
this.stopProcessingRules = reader.ReadElementValue<bool>();
return true;
default:
return false;
}
}
/// <summary>
/// Writes elements to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
if (this.AssignCategories.Count > 0)
{
this.AssignCategories.WriteToXml(writer, XmlElementNames.AssignCategories);
}
if (this.CopyToFolder != null)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.CopyToFolder);
this.CopyToFolder.WriteToXml(writer);
writer.WriteEndElement();
}
if (this.Delete != false)
{
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.Delete,
this.Delete);
}
if (this.ForwardAsAttachmentToRecipients.Count > 0)
{
this.ForwardAsAttachmentToRecipients.WriteToXml(writer, XmlElementNames.ForwardAsAttachmentToRecipients);
}
if (this.ForwardToRecipients.Count > 0)
{
this.ForwardToRecipients.WriteToXml(writer, XmlElementNames.ForwardToRecipients);
}
if (this.MarkImportance.HasValue)
{
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.MarkImportance,
this.MarkImportance.Value);
}
if (this.MarkAsRead != false)
{
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.MarkAsRead,
this.MarkAsRead);
}
if (this.MoveToFolder != null)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MoveToFolder);
this.MoveToFolder.WriteToXml(writer);
writer.WriteEndElement();
}
if (this.PermanentDelete != false)
{
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.PermanentDelete,
this.PermanentDelete);
}
if (this.RedirectToRecipients.Count > 0)
{
this.RedirectToRecipients.WriteToXml(writer, XmlElementNames.RedirectToRecipients);
}
if (this.SendSMSAlertToRecipients.Count > 0)
{
EmailAddressCollection emailCollection = ConvertSMSRecipientsFromMobilePhoneCollectionToEmailAddressCollection(this.SendSMSAlertToRecipients);
emailCollection.WriteToXml(writer, XmlElementNames.SendSMSAlertToRecipients);
}
if (this.ServerReplyWithMessage != null)
{
this.ServerReplyWithMessage.WriteToXml(writer, XmlElementNames.ServerReplyWithMessage);
}
if (this.StopProcessingRules != false)
{
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.StopProcessingRules,
this.StopProcessingRules);
}
}
/// <summary>
/// Validates this instance.
/// </summary>
internal override void InternalValidate()
{
base.InternalValidate();
EwsUtilities.ValidateParam(this.forwardAsAttachmentToRecipients, "ForwardAsAttachmentToRecipients");
EwsUtilities.ValidateParam(this.forwardToRecipients, "ForwardToRecipients");
EwsUtilities.ValidateParam(this.redirectToRecipients, "RedirectToRecipients");
foreach (MobilePhone sendSMSAlertToRecipient in this.sendSMSAlertToRecipients)
{
EwsUtilities.ValidateParam(sendSMSAlertToRecipient, "SendSMSAlertToRecipient");
}
}
/// <summary>
/// Convert the SMS recipient list from EmailAddressCollection type to MobilePhone collection type.
/// </summary>
/// <param name="emailCollection">Recipient list in EmailAddressCollection type.</param>
/// <returns>A MobilePhone collection object containing all SMS recipient in MobilePhone type. </returns>
private static Collection<MobilePhone> ConvertSMSRecipientsFromEmailAddressCollectionToMobilePhoneCollection(EmailAddressCollection emailCollection)
{
Collection<MobilePhone> mobilePhoneCollection = new Collection<MobilePhone>();
foreach (EmailAddress emailAddress in emailCollection)
{
mobilePhoneCollection.Add(new MobilePhone(emailAddress.Name, emailAddress.Address));
}
return mobilePhoneCollection;
}
/// <summary>
/// Convert the SMS recipient list from MobilePhone collection type to EmailAddressCollection type.
/// </summary>
/// <param name="recipientCollection">Recipient list in a MobilePhone collection type.</param>
/// <returns>An EmailAddressCollection object containing recipients with "MOBILE" address type. </returns>
private static EmailAddressCollection ConvertSMSRecipientsFromMobilePhoneCollectionToEmailAddressCollection(Collection<MobilePhone> recipientCollection)
{
EmailAddressCollection emailCollection = new EmailAddressCollection(XmlElementNames.Address);
foreach (MobilePhone recipient in recipientCollection)
{
EmailAddress emailAddress = new EmailAddress(
recipient.Name,
recipient.PhoneNumber,
RuleActions.MobileType);
emailCollection.Add(emailAddress);
}
return emailCollection;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
namespace System.Diagnostics.Tests
{
public class ProcessTests : ProcessTestBase
{
private class FinalizingProcess : Process
{
public static volatile bool WasFinalized;
public static void CreateAndRelease()
{
new FinalizingProcess();
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
WasFinalized = true;
}
base.Dispose(disposing);
}
}
private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
{
_process.PriorityClass = exPriorityClass;
_process.Refresh();
Assert.Equal(priority, _process.BasePriority);
}
private void AssertNonZeroWindowsZeroUnix(long value)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.NotEqual(0, value);
}
else
{
Assert.Equal(0, value);
}
}
[Fact, PlatformSpecific(PlatformID.Windows)]
public void TestBasePriorityOnWindows()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
// We are not checking for RealTime case here, as RealTime priority process can
// preempt the threads of all other processes, including operating system processes
// performing important tasks, which may cause the machine to be unresponsive.
//SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix
public void TestBasePriorityOnUnix()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
SetAndCheckBasePriority(ProcessPriorityClass.High, -11);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[InlineData(null)]
public void TestEnableRaiseEvents(bool? enable)
{
bool exitedInvoked = false;
Process p = CreateProcessLong();
if (enable.HasValue)
{
p.EnableRaisingEvents = enable.Value;
}
p.Exited += delegate { exitedInvoked = true; };
StartSleepKillWait(p);
if (enable.GetValueOrDefault())
{
// There's no guarantee that the Exited callback will be invoked by
// the time Process.WaitForExit completes, though it's extremely likely.
// There could be a race condition where WaitForExit is returning from
// its wait and sees that the callback is already running asynchronously,
// at which point it returns to the caller even if the callback hasn't
// entirely completed. As such, we spin until the value is set.
Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS));
}
else
{
Assert.False(exitedInvoked);
}
}
[Fact]
public void TestExitCode()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
{
Process p = CreateProcessLong();
StartSleepKillWait(p);
Assert.NotEqual(0, p.ExitCode);
}
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public void TestUseShellExecute_Unix_Succeeds()
{
using (var p = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = "exit", Arguments = "42" }))
{
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(42, p.ExitCode);
}
}
[Fact]
public void TestExitTime()
{
DateTime timeBeforeProcessStart = DateTime.UtcNow;
Process p = CreateProcessLong();
p.Start();
Assert.Throws<InvalidOperationException>(() => p.ExitTime);
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart, "TestExitTime is incorrect.");
}
[Fact]
public void TestId()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle));
}
else
{
IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunner).Select(p => p.Id);
Assert.Contains(_process.Id, testProcessIds);
}
}
[Fact]
public void TestHasExited()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.HasExited, "TestHasExited001 failed");
}
{
Process p = CreateProcessLong();
p.Start();
try
{
Assert.False(p.HasExited, "TestHasExited002 failed");
}
finally
{
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
Assert.True(p.HasExited, "TestHasExited003 failed");
}
}
[Fact]
public void TestMachineName()
{
// Checking that the MachineName returns some value.
Assert.NotNull(_process.MachineName);
}
[Fact, PlatformSpecific(~PlatformID.OSX)]
public void TestMainModuleOnNonOSX()
{
string fileName = "corerun";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
fileName = "CoreRun.exe";
Process p = Process.GetCurrentProcess();
Assert.True(p.Modules.Count > 0);
Assert.Equal(fileName, p.MainModule.ModuleName);
Assert.EndsWith(fileName, p.MainModule.FileName);
Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", fileName), p.MainModule.ToString());
}
[Fact]
public void TestMaxWorkingSet()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MaxWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MaxWorkingSet = (IntPtr)((int)curValue + 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)max;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MaxWorkingSet);
}
finally
{
_process.MaxWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
public void TestMinWorkingSet()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MinWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MinWorkingSet = (IntPtr)((int)curValue - 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)min;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MinWorkingSet);
}
finally
{
_process.MinWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
public void TestModules()
{
ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules;
foreach (ProcessModule pModule in moduleCollection)
{
// Validated that we can get a value for each of the following.
Assert.NotNull(pModule);
Assert.NotEqual(IntPtr.Zero, pModule.BaseAddress);
Assert.NotNull(pModule.FileName);
Assert.NotNull(pModule.ModuleName);
// Just make sure these don't throw
IntPtr addr = pModule.EntryPointAddress;
int memSize = pModule.ModuleMemorySize;
}
}
[Fact]
public void TestNonpagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64);
}
[Fact]
public void TestPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64);
}
[Fact]
public void TestPagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64);
}
[Fact]
public void TestPeakPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64);
}
[Fact]
public void TestPeakVirtualMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64);
}
[Fact]
public void TestPeakWorkingSet64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64);
}
[Fact]
public void TestPrivateMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64);
}
[Fact]
public void TestVirtualMemorySize64()
{
Assert.True(_process.VirtualMemorySize64 > 0);
}
[Fact]
public void TestWorkingSet64()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
Assert.True(_process.WorkingSet64 >= 0);
return;
}
Assert.True(_process.WorkingSet64 > 0);
}
[Fact]
public void TestProcessorTime()
{
Assert.True(_process.UserProcessorTime.TotalSeconds >= 0);
Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0);
double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
double processorTimeAtHalfSpin = 0;
// Perform loop to occupy cpu, takes less than a second.
int i = int.MaxValue / 16;
while (i > 0)
{
i--;
if (i == int.MaxValue / 32)
processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
}
Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds);
}
[ActiveIssue(5805)]
[Fact]
public void TestProcessStartTime()
{
DateTime systemBootTime = DateTime.UtcNow - TimeSpan.FromMilliseconds(Environment.TickCount);
Process p = CreateProcessLong();
Assert.Throws<InvalidOperationException>(() => p.StartTime);
try
{
p.Start();
// Time in unix, is measured in jiffies, which is incremented by one for every timer interrupt since the boot time.
// Thus, because there are HZ timer interrupts in a second, there are HZ jiffies in a second. Hence 1\HZ, will
// be the resolution of system timer. The lowest value of HZ on unix is 100, hence the timer resolution is 10 ms.
// On Windows, timer resolution is 15 ms from MSDN DateTime.Now. Hence, allowing error in 15ms [max(10,15)].
long intervalTicks = new TimeSpan(0, 0, 0, 0, 15).Ticks;
long beforeTicks = systemBootTime.Ticks;
try
{
// Ensure the process has started, p.id throws InvalidOperationException, if the process has not yet started.
Assert.Equal(p.Id, Process.GetProcessById(p.Id).Id);
long startTicks = p.StartTime.ToUniversalTime().Ticks;
long afterTicks = DateTime.UtcNow.Ticks + intervalTicks;
Assert.InRange(startTicks, beforeTicks, afterTicks);
}
catch (InvalidOperationException)
{
Assert.True(p.StartTime.ToUniversalTime().Ticks > beforeTicks);
}
}
finally
{
if (!p.HasExited)
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
}
[Fact]
[PlatformSpecific(~PlatformID.OSX)] // getting/setting affinity not supported on OSX
public void TestProcessorAffinity()
{
IntPtr curProcessorAffinity = _process.ProcessorAffinity;
try
{
_process.ProcessorAffinity = new IntPtr(0x1);
Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity);
}
finally
{
_process.ProcessorAffinity = curProcessorAffinity;
Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity);
}
}
[Fact]
public void TestPriorityBoostEnabled()
{
bool isPriorityBoostEnabled = _process.PriorityBoostEnabled;
try
{
_process.PriorityBoostEnabled = true;
Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed");
_process.PriorityBoostEnabled = false;
Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed");
}
finally
{
_process.PriorityBoostEnabled = isPriorityBoostEnabled;
}
}
[Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix
public void TestPriorityClassUnix()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact, PlatformSpecific(PlatformID.Windows)]
public void TestPriorityClassWindows()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact]
public void TestInvalidPriorityClass()
{
Process p = new Process();
Assert.Throws<ArgumentException>(() => { p.PriorityClass = ProcessPriorityClass.Normal | ProcessPriorityClass.Idle; });
}
[Fact]
public void TestProcessName()
{
Assert.Equal(_process.ProcessName, HostRunner, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void TestSafeHandle()
{
Assert.False(_process.SafeHandle.IsInvalid);
}
[Fact]
public void TestSessionId()
{
uint sessionId;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId);
}
else
{
sessionId = (uint)Interop.getsid(_process.Id);
}
Assert.Equal(sessionId, (uint)_process.SessionId);
}
[Fact]
public void TestGetCurrentProcess()
{
Process current = Process.GetCurrentProcess();
Assert.NotNull(current);
int currentProcessId = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
Interop.GetCurrentProcessId() :
Interop.getpid();
Assert.Equal(currentProcessId, current.Id);
}
[Fact]
public void TestGetProcessById()
{
Process p = Process.GetProcessById(_process.Id);
Assert.Equal(_process.Id, p.Id);
Assert.Equal(_process.ProcessName, p.ProcessName);
}
[Fact]
public void TestGetProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
// Get all the processes running on the machine, and check if the current process is one of them.
var foundCurrentProcess = (from p in Process.GetProcesses()
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses001 failed");
foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName)
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses002 failed");
}
[Fact]
public void TestGetProcessesByName()
{
// Get the current process using its name
Process currentProcess = Process.GetCurrentProcess();
Assert.True(Process.GetProcessesByName(currentProcess.ProcessName).Count() > 0, "TestGetProcessesByName001 failed");
Assert.True(Process.GetProcessesByName(currentProcess.ProcessName, currentProcess.MachineName).Count() > 0, "TestGetProcessesByName001 failed");
}
public static IEnumerable<object[]> GetTestProcess()
{
Process currentProcess = Process.GetCurrentProcess();
yield return new object[] { currentProcess, Process.GetProcessById(currentProcess.Id, "127.0.0.1") };
yield return new object[] { currentProcess, Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProcess.Id).Single() };
}
[Theory, PlatformSpecific(PlatformID.Windows)]
[MemberData("GetTestProcess")]
public void TestProcessOnRemoteMachineWindows(Process currentProcess, Process remoteProcess)
{
Assert.Equal(currentProcess.Id, remoteProcess.Id);
Assert.Equal(currentProcess.BasePriority, remoteProcess.BasePriority);
Assert.Equal(currentProcess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents);
Assert.Equal("127.0.0.1", remoteProcess.MachineName);
// This property throws exception only on remote processes.
Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule);
}
[Fact, PlatformSpecific(PlatformID.AnyUnix)]
public void TestProcessOnRemoteMachineUnix()
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1"));
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1"));
}
[Fact]
public void TestStartInfo()
{
{
Process process = CreateProcessLong();
process.Start();
Assert.Equal(HostRunner, process.StartInfo.FileName);
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = CreateProcessLong();
process.Start();
Assert.Throws<System.InvalidOperationException>(() => (process.StartInfo = new ProcessStartInfo()));
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = new Process();
process.StartInfo = new ProcessStartInfo(TestConsoleApp);
Assert.Equal(TestConsoleApp, process.StartInfo.FileName);
}
{
Process process = new Process();
Assert.Throws<ArgumentNullException>(() => process.StartInfo = null);
}
{
Process process = Process.GetCurrentProcess();
Assert.Throws<System.InvalidOperationException>(() => process.StartInfo);
}
}
[Theory]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData("\"abc\"\t\td\te", @"abc,d,e")]
[InlineData(@"a\\b d""e f""g h", @"a\\b,de fg,h")]
[InlineData(@"\ \\ \\\", @"\,\\,\\\")]
[InlineData(@"a\\\""b c d", @"a\""b,c,d")]
[InlineData(@"a\\\\""b c"" d e", @"a\\b c,d,e")]
[InlineData(@"a""b c""d e""f g""h i""j k""l", @"ab cd,ef gh,ij kl")]
[InlineData(@"a b c""def", @"a,b,cdef")]
[InlineData(@"""\a\"" \\""\\\ b c", @"\a"" \\\\,b,c")]
public void TestArgumentParsing(string inputArguments, string expectedArgv)
{
using (var handle = RemoteInvokeRaw((Func<string, string, string, int>)ConcatThreeArguments,
inputArguments,
start: true,
psi: new ProcessStartInfo { RedirectStandardOutput = true }))
{
Assert.Equal(expectedArgv, handle.Process.StandardOutput.ReadToEnd());
}
}
private static int ConcatThreeArguments(string one, string two, string three)
{
Console.Write(string.Join(",", one, two, three));
return SuccessExitCode;
}
// [Fact] // uncomment for diagnostic purposes to list processes to console
public void TestDiagnosticsWithConsoleWriteLine()
{
foreach (var p in Process.GetProcesses().OrderBy(p => p.Id))
{
Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count);
p.Dispose();
}
}
[Fact]
public void CanBeFinalized()
{
FinalizingProcess.CreateAndRelease();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(FinalizingProcess.WasFinalized);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// FileIOPermission.cs
//
// <OWNER>[....]</OWNER>
//
namespace System.Security.Permissions {
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if FEATURE_CAS_POLICY
using SecurityElement = System.Security.SecurityElement;
#endif // FEATURE_CAS_POLICY
using System.Security.AccessControl;
using System.Security.Util;
using System.IO;
using System.Collections;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum FileIOPermissionAccess
{
NoAccess = 0x00,
Read = 0x01,
Write = 0x02,
Append = 0x04,
PathDiscovery = 0x08,
AllAccess = 0x0F,
}
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
sealed public class FileIOPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
{
private FileIOAccess m_read;
private FileIOAccess m_write;
private FileIOAccess m_append;
private FileIOAccess m_pathDiscovery;
[OptionalField(VersionAdded = 2)]
private FileIOAccess m_viewAcl;
[OptionalField(VersionAdded = 2)]
private FileIOAccess m_changeAcl;
private bool m_unrestricted;
public FileIOPermission(PermissionState state)
{
if (state == PermissionState.Unrestricted)
{
m_unrestricted = true;
}
else if (state == PermissionState.None)
{
m_unrestricted = false;
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileIOPermission( FileIOPermissionAccess access, String path )
{
VerifyAccess( access );
String[] pathList = new String[] { path };
AddPathList( access, pathList, false, true, false );
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileIOPermission( FileIOPermissionAccess access, String[] pathList )
{
VerifyAccess( access );
AddPathList( access, pathList, false, true, false );
}
#if FEATURE_MACL
[System.Security.SecuritySafeCritical] // auto-generated
public FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String path )
{
VerifyAccess( access );
String[] pathList = new String[] { path };
AddPathList( access, control, pathList, false, true, false );
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String[] pathList )
: this( access, control, pathList, true, true )
{
}
#endif
[System.Security.SecurityCritical] // auto-generated
internal FileIOPermission( FileIOPermissionAccess access, String[] pathList, bool checkForDuplicates, bool needFullPath )
{
VerifyAccess( access );
AddPathList( access, pathList, checkForDuplicates, needFullPath, true );
}
#if FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
internal FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates, bool needFullPath )
{
VerifyAccess( access );
AddPathList( access, control, pathList, checkForDuplicates, needFullPath, true );
}
#endif
public void SetPathList( FileIOPermissionAccess access, String path )
{
String[] pathList;
if(path == null)
pathList = new String[] {};
else
pathList = new String[] { path };
SetPathList( access, pathList, false );
}
public void SetPathList( FileIOPermissionAccess access, String[] pathList )
{
SetPathList( access, pathList, true );
}
internal void SetPathList( FileIOPermissionAccess access,
String[] pathList, bool checkForDuplicates )
{
SetPathList( access, AccessControlActions.None, pathList, checkForDuplicates );
}
[System.Security.SecuritySafeCritical] // auto-generated
internal void SetPathList( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates )
{
VerifyAccess( access );
if ((access & FileIOPermissionAccess.Read) != 0)
m_read = null;
if ((access & FileIOPermissionAccess.Write) != 0)
m_write = null;
if ((access & FileIOPermissionAccess.Append) != 0)
m_append = null;
if ((access & FileIOPermissionAccess.PathDiscovery) != 0)
m_pathDiscovery = null;
#if FEATURE_MACL
if ((control & AccessControlActions.View) != 0)
m_viewAcl = null;
if ((control & AccessControlActions.Change) != 0)
m_changeAcl = null;
#else
m_viewAcl = null;
m_changeAcl = null;
#endif
m_unrestricted = false;
#if FEATURE_MACL
AddPathList( access, control, pathList, checkForDuplicates, true, true );
#else
AddPathList( access, pathList, checkForDuplicates, true, true );
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
public void AddPathList( FileIOPermissionAccess access, String path )
{
String[] pathList;
if(path == null)
pathList = new String[] {};
else
pathList = new String[] { path };
AddPathList( access, pathList, false, true, false );
}
[System.Security.SecuritySafeCritical] // auto-generated
public void AddPathList( FileIOPermissionAccess access, String[] pathList )
{
AddPathList( access, pathList, true, true, true );
}
[System.Security.SecurityCritical] // auto-generated
internal void AddPathList( FileIOPermissionAccess access, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList )
{
AddPathList( access, AccessControlActions.None, pathListOrig, checkForDuplicates, needFullPath, copyPathList );
}
[System.Security.SecurityCritical] // auto-generated
internal void AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList)
{
if (pathListOrig == null)
{
throw new ArgumentNullException( "pathList" );
}
if (pathListOrig.Length == 0)
{
throw new ArgumentException( Environment.GetResourceString("Argument_EmptyPath" ));
}
Contract.EndContractBlock();
// @
VerifyAccess(access);
if (m_unrestricted)
return;
String[] pathList = pathListOrig;
if(copyPathList)
{
// Make a copy of pathList (in case its value changes after we check for illegal chars)
pathList = new String[pathListOrig.Length];
Array.Copy(pathListOrig, pathList, pathListOrig.Length);
}
CheckIllegalCharacters( pathList );
ArrayList pathArrayList = StringExpressionSet.CreateListFromExpressions(pathList, needFullPath);
if ((access & FileIOPermissionAccess.Read) != 0)
{
if (m_read == null)
{
m_read = new FileIOAccess();
}
m_read.AddExpressions( pathArrayList, checkForDuplicates);
}
if ((access & FileIOPermissionAccess.Write) != 0)
{
if (m_write == null)
{
m_write = new FileIOAccess();
}
m_write.AddExpressions( pathArrayList, checkForDuplicates);
}
if ((access & FileIOPermissionAccess.Append) != 0)
{
if (m_append == null)
{
m_append = new FileIOAccess();
}
m_append.AddExpressions( pathArrayList, checkForDuplicates);
}
if ((access & FileIOPermissionAccess.PathDiscovery) != 0)
{
if (m_pathDiscovery == null)
{
m_pathDiscovery = new FileIOAccess( true );
}
m_pathDiscovery.AddExpressions( pathArrayList, checkForDuplicates);
}
#if FEATURE_MACL
if ((control & AccessControlActions.View) != 0)
{
if (m_viewAcl == null)
{
m_viewAcl = new FileIOAccess();
}
m_viewAcl.AddExpressions( pathArrayList, checkForDuplicates);
}
if ((control & AccessControlActions.Change) != 0)
{
if (m_changeAcl == null)
{
m_changeAcl = new FileIOAccess();
}
m_changeAcl.AddExpressions( pathArrayList, checkForDuplicates);
}
#endif
}
[SecuritySafeCritical]
public String[] GetPathList( FileIOPermissionAccess access )
{
VerifyAccess( access );
ExclusiveAccess( access );
if (AccessIsSet( access, FileIOPermissionAccess.Read ))
{
if (m_read == null)
{
return null;
}
return m_read.ToStringArray();
}
if (AccessIsSet( access, FileIOPermissionAccess.Write ))
{
if (m_write == null)
{
return null;
}
return m_write.ToStringArray();
}
if (AccessIsSet( access, FileIOPermissionAccess.Append ))
{
if (m_append == null)
{
return null;
}
return m_append.ToStringArray();
}
if (AccessIsSet( access, FileIOPermissionAccess.PathDiscovery ))
{
if (m_pathDiscovery == null)
{
return null;
}
return m_pathDiscovery.ToStringArray();
}
// not reached
return null;
}
public FileIOPermissionAccess AllLocalFiles
{
get
{
if (m_unrestricted)
return FileIOPermissionAccess.AllAccess;
FileIOPermissionAccess access = FileIOPermissionAccess.NoAccess;
if (m_read != null && m_read.AllLocalFiles)
{
access |= FileIOPermissionAccess.Read;
}
if (m_write != null && m_write.AllLocalFiles)
{
access |= FileIOPermissionAccess.Write;
}
if (m_append != null && m_append.AllLocalFiles)
{
access |= FileIOPermissionAccess.Append;
}
if (m_pathDiscovery != null && m_pathDiscovery.AllLocalFiles)
{
access |= FileIOPermissionAccess.PathDiscovery;
}
return access;
}
set
{
if ((value & FileIOPermissionAccess.Read) != 0)
{
if (m_read == null)
m_read = new FileIOAccess();
m_read.AllLocalFiles = true;
}
else
{
if (m_read != null)
m_read.AllLocalFiles = false;
}
if ((value & FileIOPermissionAccess.Write) != 0)
{
if (m_write == null)
m_write = new FileIOAccess();
m_write.AllLocalFiles = true;
}
else
{
if (m_write != null)
m_write.AllLocalFiles = false;
}
if ((value & FileIOPermissionAccess.Append) != 0)
{
if (m_append == null)
m_append = new FileIOAccess();
m_append.AllLocalFiles = true;
}
else
{
if (m_append != null)
m_append.AllLocalFiles = false;
}
if ((value & FileIOPermissionAccess.PathDiscovery) != 0)
{
if (m_pathDiscovery == null)
m_pathDiscovery = new FileIOAccess( true );
m_pathDiscovery.AllLocalFiles = true;
}
else
{
if (m_pathDiscovery != null)
m_pathDiscovery.AllLocalFiles = false;
}
}
}
public FileIOPermissionAccess AllFiles
{
get
{
if (m_unrestricted)
return FileIOPermissionAccess.AllAccess;
FileIOPermissionAccess access = FileIOPermissionAccess.NoAccess;
if (m_read != null && m_read.AllFiles)
{
access |= FileIOPermissionAccess.Read;
}
if (m_write != null && m_write.AllFiles)
{
access |= FileIOPermissionAccess.Write;
}
if (m_append != null && m_append.AllFiles)
{
access |= FileIOPermissionAccess.Append;
}
if (m_pathDiscovery != null && m_pathDiscovery.AllFiles)
{
access |= FileIOPermissionAccess.PathDiscovery;
}
return access;
}
set
{
if (value == FileIOPermissionAccess.AllAccess)
{
m_unrestricted = true;
return;
}
if ((value & FileIOPermissionAccess.Read) != 0)
{
if (m_read == null)
m_read = new FileIOAccess();
m_read.AllFiles = true;
}
else
{
if (m_read != null)
m_read.AllFiles = false;
}
if ((value & FileIOPermissionAccess.Write) != 0)
{
if (m_write == null)
m_write = new FileIOAccess();
m_write.AllFiles = true;
}
else
{
if (m_write != null)
m_write.AllFiles = false;
}
if ((value & FileIOPermissionAccess.Append) != 0)
{
if (m_append == null)
m_append = new FileIOAccess();
m_append.AllFiles = true;
}
else
{
if (m_append != null)
m_append.AllFiles = false;
}
if ((value & FileIOPermissionAccess.PathDiscovery) != 0)
{
if (m_pathDiscovery == null)
m_pathDiscovery = new FileIOAccess( true );
m_pathDiscovery.AllFiles = true;
}
else
{
if (m_pathDiscovery != null)
m_pathDiscovery.AllFiles = false;
}
}
}
[Pure]
private static void VerifyAccess( FileIOPermissionAccess access )
{
if ((access & ~FileIOPermissionAccess.AllAccess) != 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access));
}
[Pure]
private static void ExclusiveAccess( FileIOPermissionAccess access )
{
if (access == FileIOPermissionAccess.NoAccess)
{
throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
}
if (((int) access & ((int)access-1)) != 0)
{
throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
}
}
private static void CheckIllegalCharacters( String[] str )
{
for (int i = 0; i < str.Length; ++i)
{
Path.CheckInvalidPathChars(str[i], true);
}
}
private static bool AccessIsSet( FileIOPermissionAccess access, FileIOPermissionAccess question )
{
return (access & question) != 0;
}
private bool IsEmpty()
{
return (!m_unrestricted &&
(this.m_read == null || this.m_read.IsEmpty()) &&
(this.m_write == null || this.m_write.IsEmpty()) &&
(this.m_append == null || this.m_append.IsEmpty()) &&
(this.m_pathDiscovery == null || this.m_pathDiscovery.IsEmpty()) &&
(this.m_viewAcl == null || this.m_viewAcl.IsEmpty()) &&
(this.m_changeAcl == null || this.m_changeAcl.IsEmpty()));
}
//------------------------------------------------------
//
// CODEACCESSPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public bool IsUnrestricted()
{
return m_unrestricted;
}
//------------------------------------------------------
//
// IPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
{
return this.IsEmpty();
}
FileIOPermission operand = target as FileIOPermission;
if (operand == null)
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
if (operand.IsUnrestricted())
return true;
else if (this.IsUnrestricted())
return false;
else
return ((this.m_read == null || this.m_read.IsSubsetOf( operand.m_read )) &&
(this.m_write == null || this.m_write.IsSubsetOf( operand.m_write )) &&
(this.m_append == null || this.m_append.IsSubsetOf( operand.m_append )) &&
(this.m_pathDiscovery == null || this.m_pathDiscovery.IsSubsetOf( operand.m_pathDiscovery )) &&
(this.m_viewAcl == null || this.m_viewAcl.IsSubsetOf( operand.m_viewAcl )) &&
(this.m_changeAcl == null || this.m_changeAcl.IsSubsetOf( operand.m_changeAcl )));
}
public override IPermission Intersect(IPermission target)
{
if (target == null)
{
return null;
}
FileIOPermission operand = target as FileIOPermission;
if (operand == null)
{
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
}
else if (this.IsUnrestricted())
{
return target.Copy();
}
if (operand.IsUnrestricted())
{
return this.Copy();
}
FileIOAccess intersectRead = this.m_read == null ? null : this.m_read.Intersect( operand.m_read );
FileIOAccess intersectWrite = this.m_write == null ? null : this.m_write.Intersect( operand.m_write );
FileIOAccess intersectAppend = this.m_append == null ? null : this.m_append.Intersect( operand.m_append );
FileIOAccess intersectPathDiscovery = this.m_pathDiscovery == null ? null : this.m_pathDiscovery.Intersect( operand.m_pathDiscovery );
FileIOAccess intersectViewAcl = this.m_viewAcl == null ? null : this.m_viewAcl.Intersect( operand.m_viewAcl );
FileIOAccess intersectChangeAcl = this.m_changeAcl == null ? null : this.m_changeAcl.Intersect( operand.m_changeAcl );
if ((intersectRead == null || intersectRead.IsEmpty()) &&
(intersectWrite == null || intersectWrite.IsEmpty()) &&
(intersectAppend == null || intersectAppend.IsEmpty()) &&
(intersectPathDiscovery == null || intersectPathDiscovery.IsEmpty()) &&
(intersectViewAcl == null || intersectViewAcl.IsEmpty()) &&
(intersectChangeAcl == null || intersectChangeAcl.IsEmpty()))
{
return null;
}
FileIOPermission intersectPermission = new FileIOPermission(PermissionState.None);
intersectPermission.m_unrestricted = false;
intersectPermission.m_read = intersectRead;
intersectPermission.m_write = intersectWrite;
intersectPermission.m_append = intersectAppend;
intersectPermission.m_pathDiscovery = intersectPathDiscovery;
intersectPermission.m_viewAcl = intersectViewAcl;
intersectPermission.m_changeAcl = intersectChangeAcl;
return intersectPermission;
}
public override IPermission Union(IPermission other)
{
if (other == null)
{
return this.Copy();
}
FileIOPermission operand = other as FileIOPermission;
if (operand == null)
{
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
}
if (this.IsUnrestricted() || operand.IsUnrestricted())
{
return new FileIOPermission( PermissionState.Unrestricted );
}
FileIOAccess unionRead = this.m_read == null ? operand.m_read : this.m_read.Union( operand.m_read );
FileIOAccess unionWrite = this.m_write == null ? operand.m_write : this.m_write.Union( operand.m_write );
FileIOAccess unionAppend = this.m_append == null ? operand.m_append : this.m_append.Union( operand.m_append );
FileIOAccess unionPathDiscovery = this.m_pathDiscovery == null ? operand.m_pathDiscovery : this.m_pathDiscovery.Union( operand.m_pathDiscovery );
FileIOAccess unionViewAcl = this.m_viewAcl == null ? operand.m_viewAcl : this.m_viewAcl.Union( operand.m_viewAcl );
FileIOAccess unionChangeAcl = this.m_changeAcl == null ? operand.m_changeAcl : this.m_changeAcl.Union( operand.m_changeAcl );
if ((unionRead == null || unionRead.IsEmpty()) &&
(unionWrite == null || unionWrite.IsEmpty()) &&
(unionAppend == null || unionAppend.IsEmpty()) &&
(unionPathDiscovery == null || unionPathDiscovery.IsEmpty()) &&
(unionViewAcl == null || unionViewAcl.IsEmpty()) &&
(unionChangeAcl == null || unionChangeAcl.IsEmpty()))
{
return null;
}
FileIOPermission unionPermission = new FileIOPermission(PermissionState.None);
unionPermission.m_unrestricted = false;
unionPermission.m_read = unionRead;
unionPermission.m_write = unionWrite;
unionPermission.m_append = unionAppend;
unionPermission.m_pathDiscovery = unionPathDiscovery;
unionPermission.m_viewAcl = unionViewAcl;
unionPermission.m_changeAcl = unionChangeAcl;
return unionPermission;
}
public override IPermission Copy()
{
FileIOPermission copy = new FileIOPermission(PermissionState.None);
if (this.m_unrestricted)
{
copy.m_unrestricted = true;
}
else
{
copy.m_unrestricted = false;
if (this.m_read != null)
{
copy.m_read = this.m_read.Copy();
}
if (this.m_write != null)
{
copy.m_write = this.m_write.Copy();
}
if (this.m_append != null)
{
copy.m_append = this.m_append.Copy();
}
if (this.m_pathDiscovery != null)
{
copy.m_pathDiscovery = this.m_pathDiscovery.Copy();
}
if (this.m_viewAcl != null)
{
copy.m_viewAcl = this.m_viewAcl.Copy();
}
if (this.m_changeAcl != null)
{
copy.m_changeAcl = this.m_changeAcl.Copy();
}
}
return copy;
}
#if FEATURE_CAS_POLICY
public override SecurityElement ToXml()
{
SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.FileIOPermission" );
if (!IsUnrestricted())
{
if (this.m_read != null && !this.m_read.IsEmpty())
{
esd.AddAttribute( "Read", SecurityElement.Escape( m_read.ToString() ) );
}
if (this.m_write != null && !this.m_write.IsEmpty())
{
esd.AddAttribute( "Write", SecurityElement.Escape( m_write.ToString() ) );
}
if (this.m_append != null && !this.m_append.IsEmpty())
{
esd.AddAttribute( "Append", SecurityElement.Escape( m_append.ToString() ) );
}
if (this.m_pathDiscovery != null && !this.m_pathDiscovery.IsEmpty())
{
esd.AddAttribute( "PathDiscovery", SecurityElement.Escape( m_pathDiscovery.ToString() ) );
}
if (this.m_viewAcl != null && !this.m_viewAcl.IsEmpty())
{
esd.AddAttribute( "ViewAcl", SecurityElement.Escape( m_viewAcl.ToString() ) );
}
if (this.m_changeAcl != null && !this.m_changeAcl.IsEmpty())
{
esd.AddAttribute( "ChangeAcl", SecurityElement.Escape( m_changeAcl.ToString() ) );
}
}
else
{
esd.AddAttribute( "Unrestricted", "true" );
}
return esd;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void FromXml(SecurityElement esd)
{
CodeAccessPermission.ValidateElement( esd, this );
String et;
if (XMLUtil.IsUnrestricted(esd))
{
m_unrestricted = true;
return;
}
m_unrestricted = false;
et = esd.Attribute( "Read" );
if (et != null)
{
m_read = new FileIOAccess( et );
}
else
{
m_read = null;
}
et = esd.Attribute( "Write" );
if (et != null)
{
m_write = new FileIOAccess( et );
}
else
{
m_write = null;
}
et = esd.Attribute( "Append" );
if (et != null)
{
m_append = new FileIOAccess( et );
}
else
{
m_append = null;
}
et = esd.Attribute( "PathDiscovery" );
if (et != null)
{
m_pathDiscovery = new FileIOAccess( et );
m_pathDiscovery.PathDiscovery = true;
}
else
{
m_pathDiscovery = null;
}
et = esd.Attribute( "ViewAcl" );
if (et != null)
{
m_viewAcl = new FileIOAccess( et );
}
else
{
m_viewAcl = null;
}
et = esd.Attribute( "ChangeAcl" );
if (et != null)
{
m_changeAcl = new FileIOAccess( et );
}
else
{
m_changeAcl = null;
}
}
#endif // FEATURE_CAS_POLICY
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
return FileIOPermission.GetTokenIndex();
}
internal static int GetTokenIndex()
{
return BuiltInPermissionIndex.FileIOPermissionIndex;
}
[System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals(Object obj)
{
FileIOPermission perm = obj as FileIOPermission;
if(perm == null)
return false;
if(m_unrestricted && perm.m_unrestricted)
return true;
if(m_unrestricted != perm.m_unrestricted)
return false;
if(m_read == null)
{
if(perm.m_read != null && !perm.m_read.IsEmpty())
return false;
}
else if(!m_read.Equals(perm.m_read))
return false;
if(m_write == null)
{
if(perm.m_write != null && !perm.m_write.IsEmpty())
return false;
}
else if(!m_write.Equals(perm.m_write))
return false;
if(m_append == null)
{
if(perm.m_append != null && !perm.m_append.IsEmpty())
return false;
}
else if(!m_append.Equals(perm.m_append))
return false;
if(m_pathDiscovery == null)
{
if(perm.m_pathDiscovery != null && !perm.m_pathDiscovery.IsEmpty())
return false;
}
else if(!m_pathDiscovery.Equals(perm.m_pathDiscovery))
return false;
if(m_viewAcl == null)
{
if(perm.m_viewAcl != null && !perm.m_viewAcl.IsEmpty())
return false;
}
else if(!m_viewAcl.Equals(perm.m_viewAcl))
return false;
if(m_changeAcl == null)
{
if(perm.m_changeAcl != null && !perm.m_changeAcl.IsEmpty())
return false;
}
else if(!m_changeAcl.Equals(perm.m_changeAcl))
return false;
return true;
}
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetHashCode()
{
// This implementation is only to silence a compiler warning.
return base.GetHashCode();
}
}
[Serializable]
internal sealed class FileIOAccess
{
#if !FEATURE_CASE_SENSITIVE_FILESYSTEM
private bool m_ignoreCase = true;
#else
private bool m_ignoreCase = false;
#endif // !FEATURE_CASE_SENSITIVE_FILESYSTEM
private StringExpressionSet m_set;
private bool m_allFiles;
private bool m_allLocalFiles;
private bool m_pathDiscovery;
private const String m_strAllFiles = "*AllFiles*";
private const String m_strAllLocalFiles = "*AllLocalFiles*";
public FileIOAccess()
{
m_set = new StringExpressionSet( m_ignoreCase, true );
m_allFiles = false;
m_allLocalFiles = false;
m_pathDiscovery = false;
}
public FileIOAccess( bool pathDiscovery )
{
m_set = new StringExpressionSet( m_ignoreCase, true );
m_allFiles = false;
m_allLocalFiles = false;
m_pathDiscovery = pathDiscovery;
}
[System.Security.SecurityCritical] // auto-generated
public FileIOAccess( String value )
{
if (value == null)
{
m_set = new StringExpressionSet( m_ignoreCase, true );
m_allFiles = false;
m_allLocalFiles = false;
}
else if (value.Length >= m_strAllFiles.Length && String.Compare( m_strAllFiles, value, StringComparison.Ordinal) == 0)
{
m_set = new StringExpressionSet( m_ignoreCase, true );
m_allFiles = true;
m_allLocalFiles = false;
}
else if (value.Length >= m_strAllLocalFiles.Length && String.Compare( m_strAllLocalFiles, 0, value, 0, m_strAllLocalFiles.Length, StringComparison.Ordinal) == 0)
{
m_set = new StringExpressionSet( m_ignoreCase, value.Substring( m_strAllLocalFiles.Length ), true );
m_allFiles = false;
m_allLocalFiles = true;
}
else
{
m_set = new StringExpressionSet( m_ignoreCase, value, true );
m_allFiles = false;
m_allLocalFiles = false;
}
m_pathDiscovery = false;
}
public FileIOAccess( bool allFiles, bool allLocalFiles, bool pathDiscovery )
{
m_set = new StringExpressionSet( m_ignoreCase, true );
m_allFiles = allFiles;
m_allLocalFiles = allLocalFiles;
m_pathDiscovery = pathDiscovery;
}
public FileIOAccess( StringExpressionSet set, bool allFiles, bool allLocalFiles, bool pathDiscovery )
{
m_set = set;
m_set.SetThrowOnRelative( true );
m_allFiles = allFiles;
m_allLocalFiles = allLocalFiles;
m_pathDiscovery = pathDiscovery;
}
private FileIOAccess( FileIOAccess operand )
{
m_set = operand.m_set.Copy();
m_allFiles = operand.m_allFiles;
m_allLocalFiles = operand.m_allLocalFiles;
m_pathDiscovery = operand.m_pathDiscovery;
}
[System.Security.SecurityCritical] // auto-generated
public void AddExpressions(ArrayList values, bool checkForDuplicates)
{
m_allFiles = false;
m_set.AddExpressions(values, checkForDuplicates);
}
public bool AllFiles
{
get
{
return m_allFiles;
}
set
{
m_allFiles = value;
}
}
public bool AllLocalFiles
{
get
{
return m_allLocalFiles;
}
set
{
m_allLocalFiles = value;
}
}
public bool PathDiscovery
{
set
{
m_pathDiscovery = value;
}
}
public bool IsEmpty()
{
return !m_allFiles && !m_allLocalFiles && (m_set == null || m_set.IsEmpty());
}
public FileIOAccess Copy()
{
return new FileIOAccess( this );
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileIOAccess Union( FileIOAccess operand )
{
if (operand == null)
{
return this.IsEmpty() ? null : this.Copy();
}
Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if (this.m_allFiles || operand.m_allFiles)
{
return new FileIOAccess( true, false, this.m_pathDiscovery );
}
return new FileIOAccess( this.m_set.Union( operand.m_set ), false, this.m_allLocalFiles || operand.m_allLocalFiles, this.m_pathDiscovery );
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public FileIOAccess Intersect( FileIOAccess operand )
{
if (operand == null)
{
return null;
}
Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if (this.m_allFiles)
{
if (operand.m_allFiles)
{
return new FileIOAccess( true, false, this.m_pathDiscovery );
}
else
{
return new FileIOAccess( operand.m_set.Copy(), false, operand.m_allLocalFiles, this.m_pathDiscovery );
}
}
else if (operand.m_allFiles)
{
return new FileIOAccess( this.m_set.Copy(), false, this.m_allLocalFiles, this.m_pathDiscovery );
}
StringExpressionSet intersectionSet = new StringExpressionSet( m_ignoreCase, true );
if (this.m_allLocalFiles)
{
String[] expressions = operand.m_set.UnsafeToStringArray();
if (expressions != null)
{
for (int i = 0; i < expressions.Length; ++i)
{
String root = GetRoot( expressions[i] );
if (root != null && IsLocalDrive( GetRoot( root ) ) )
{
intersectionSet.AddExpressions( new String[] { expressions[i] }, true, false );
}
}
}
}
if (operand.m_allLocalFiles)
{
String[] expressions = this.m_set.UnsafeToStringArray();
if (expressions != null)
{
for (int i = 0; i < expressions.Length; ++i)
{
String root = GetRoot( expressions[i] );
if (root != null && IsLocalDrive(GetRoot(root)))
{
intersectionSet.AddExpressions( new String[] { expressions[i] }, true, false );
}
}
}
}
String[] regularIntersection = this.m_set.Intersect( operand.m_set ).UnsafeToStringArray();
if (regularIntersection != null)
intersectionSet.AddExpressions( regularIntersection, !intersectionSet.IsEmpty(), false );
return new FileIOAccess( intersectionSet, false, this.m_allLocalFiles && operand.m_allLocalFiles, this.m_pathDiscovery );
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public bool IsSubsetOf( FileIOAccess operand )
{
if (operand == null)
{
return this.IsEmpty();
}
if (operand.m_allFiles)
{
return true;
}
Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if (!((m_pathDiscovery && this.m_set.IsSubsetOfPathDiscovery( operand.m_set )) || this.m_set.IsSubsetOf( operand.m_set )))
{
if (operand.m_allLocalFiles)
{
String[] expressions = m_set.UnsafeToStringArray();
for (int i = 0; i < expressions.Length; ++i)
{
String root = GetRoot( expressions[i] );
if (root == null || !IsLocalDrive(GetRoot(root)))
{
return false;
}
}
}
else
{
return false;
}
}
return true;
}
private static String GetRoot( String path )
{
#if !PLATFORM_UNIX
String str = path.Substring( 0, 3 );
if (str.EndsWith( ":\\", StringComparison.Ordinal))
#else
String str = path.Substring( 0, 1 );
if(str == "/")
#endif // !PLATFORM_UNIX
{
return str;
}
else
{
return null;
}
}
[SecuritySafeCritical]
public override String ToString()
{
// SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so
// we're only exposing out the same paths that we took as input.
if (m_allFiles)
{
return m_strAllFiles;
}
else
{
if (m_allLocalFiles)
{
String retstr = m_strAllLocalFiles;
String tempStr = m_set.UnsafeToString();
if (tempStr != null && tempStr.Length > 0)
retstr += ";" + tempStr;
return retstr;
}
else
{
return m_set.UnsafeToString();
}
}
}
[SecuritySafeCritical]
public String[] ToStringArray()
{
// SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so
// we're only exposing out the same paths that we took as input.
return m_set.UnsafeToStringArray();
}
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern bool IsLocalDrive(String path);
[System.Security.SecuritySafeCritical] // auto-generated
public override bool Equals(Object obj)
{
FileIOAccess operand = obj as FileIOAccess;
if(operand == null)
return (IsEmpty() && obj == null);
Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if(m_pathDiscovery)
{
if(this.m_allFiles && operand.m_allFiles)
return true;
if(this.m_allLocalFiles == operand.m_allLocalFiles &&
m_set.IsSubsetOf(operand.m_set) &&
operand.m_set.IsSubsetOf(m_set)) // Watch Out: This calls StringExpressionSet.IsSubsetOf, unlike below
return true;
return false;
}
else
{
if(!this.IsSubsetOf(operand)) // Watch Out: This calls FileIOAccess.IsSubsetOf, unlike above
return false;
if(!operand.IsSubsetOf(this))
return false;
return true;
}
}
public override int GetHashCode()
{
// This implementation is only to silence a compiler warning.
return base.GetHashCode();
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
#if FEATURE_NUMERICS
using System.Numerics;
#else
using Microsoft.Scripting.Math;
using Complex = Microsoft.Scripting.Math.Complex64;
#endif
[assembly: PythonModule("copyreg", typeof(IronPython.Modules.PythonCopyReg))]
namespace IronPython.Modules {
[Documentation("Provides global reduction-function registration for pickling and copying objects.")]
public static class PythonCopyReg {
private static readonly object _dispatchTableKey = new object();
private static readonly object _extensionRegistryKey = new object();
private static readonly object _invertedRegistryKey = new object();
private static readonly object _extensionCacheKey = new object();
internal static PythonDictionary GetDispatchTable(CodeContext/*!*/ context) {
EnsureModuleInitialized(context);
return (PythonDictionary)PythonContext.GetContext(context).GetModuleState(_dispatchTableKey);
}
internal static PythonDictionary GetExtensionRegistry(CodeContext/*!*/ context) {
EnsureModuleInitialized(context);
return (PythonDictionary)PythonContext.GetContext(context).GetModuleState(_extensionRegistryKey);
}
internal static PythonDictionary GetInvertedRegistry(CodeContext/*!*/ context) {
EnsureModuleInitialized(context);
return (PythonDictionary)PythonContext.GetContext(context).GetModuleState(_invertedRegistryKey);
}
internal static PythonDictionary GetExtensionCache(CodeContext/*!*/ context) {
EnsureModuleInitialized(context);
return (PythonDictionary)PythonContext.GetContext(context).GetModuleState(_extensionCacheKey);
}
#region Public API
[Documentation("pickle(type, function[, constructor]) -> None\n\n"
+ "Associate function with type, indicating that function should be used to\n"
+ "\"reduce\" objects of the given type when pickling. function should behave as\n"
+ "specified by the \"Extended __reduce__ API\" section of PEP 307.\n"
+ "\n"
+ "Reduction functions registered by calling pickle() can be retrieved later\n"
+ "through copyreg.dispatch_table[type].\n"
+ "\n"
+ "Note that calling pickle() will overwrite any previous association for the\n"
+ "given type.\n"
+ "\n"
+ "The constructor argument is ignored, and exists only for backwards\n"
+ "compatibility."
)]
public static void pickle(CodeContext/*!*/ context, object type, object function, [DefaultParameterValue(null)] object ctor) {
EnsureCallable(context, function, "reduction functions must be callable");
if (ctor != null) constructor(context, ctor);
GetDispatchTable(context)[type] = function;
}
[Documentation("constructor(object) -> None\n\n"
+ "Raise TypeError if object isn't callable. This function exists only for\n"
+ "backwards compatibility; for details, see\n"
+ "http://mail.python.org/pipermail/python-dev/2006-June/066831.html."
)]
public static void constructor(CodeContext/*!*/ context, object callable) {
EnsureCallable(context, callable, "constructors must be callable");
}
/// <summary>
/// Throw TypeError with a specified message if object isn't callable.
/// </summary>
private static void EnsureCallable(CodeContext/*!*/ context, object @object, string message) {
if (!PythonOps.IsCallable(context, @object)) {
throw PythonOps.TypeError(message);
}
}
[Documentation("pickle_complex(complex_number) -> (<type 'complex'>, (real, imag))\n\n"
+ "Reduction function for pickling complex numbers.")]
public static PythonTuple pickle_complex(CodeContext context, object complex) {
return PythonTuple.MakeTuple(
DynamicHelpers.GetPythonTypeFromType(typeof(Complex)),
PythonTuple.MakeTuple(
PythonOps.GetBoundAttr(context, complex, "real"),
PythonOps.GetBoundAttr(context, complex, "imag")
)
);
}
public static void clear_extension_cache(CodeContext/*!*/ context) {
GetExtensionCache(context).clear();
}
[Documentation("Register an extension code.")]
public static void add_extension(CodeContext/*!*/ context, object moduleName, object objectName, object value) {
PythonTuple key = PythonTuple.MakeTuple(moduleName, objectName);
int code = GetCode(context, value);
bool keyExists = GetExtensionRegistry(context).__contains__(key);
bool codeExists = GetInvertedRegistry(context).__contains__(code);
if (!keyExists && !codeExists) {
GetExtensionRegistry(context)[key] = code;
GetInvertedRegistry(context)[code] = key;
} else if (keyExists && codeExists &&
PythonOps.EqualRetBool(context, GetExtensionRegistry(context)[key], code) &&
PythonOps.EqualRetBool(context, GetInvertedRegistry(context)[code], key)
) {
// nop
} else {
if (keyExists) {
throw PythonOps.ValueError("key {0} is already registered with code {1}", PythonOps.Repr(context, key), PythonOps.Repr(context, GetExtensionRegistry(context)[key]));
} else { // codeExists
throw PythonOps.ValueError("code {0} is already in use for key {1}", PythonOps.Repr(context, code), PythonOps.Repr(context, GetInvertedRegistry(context)[code]));
}
}
}
[Documentation("Unregister an extension code. (only for testing)")]
public static void remove_extension(CodeContext/*!*/ context, object moduleName, object objectName, object value) {
PythonTuple key = PythonTuple.MakeTuple(moduleName, objectName);
int code = GetCode(context, value);
object existingKey;
object existingCode;
if (((IDictionary<object, object>)GetExtensionRegistry(context)).TryGetValue(key, out existingCode) &&
((IDictionary<object, object>)GetInvertedRegistry(context)).TryGetValue(code, out existingKey) &&
PythonOps.EqualRetBool(context, existingCode, code) &&
PythonOps.EqualRetBool(context, existingKey, key)
) {
GetExtensionRegistry(context).__delitem__(key);
GetInvertedRegistry(context).__delitem__(code);
} else {
throw PythonOps.ValueError("key {0} is not registered with code {1}", PythonOps.Repr(context, key), PythonOps.Repr(context, code));
}
}
[Documentation("__newobj__(cls, *args) -> cls.__new__(cls, *args)\n\n"
+ "Helper function for unpickling. Creates a new object of a given class.\n"
+ "See PEP 307 section \"The __newobj__ unpickling function\" for details."
)]
public static object __newobj__(CodeContext/*!*/ context, object cls, params object[] args) {
object[] newArgs = new object[1 + args.Length];
newArgs[0] = cls;
for (int i = 0; i < args.Length; i++) newArgs[i + 1] = args[i];
return PythonOps.Invoke(context, cls, "__new__", newArgs);
}
[Documentation("_reconstructor(basetype, objtype, basestate) -> object\n\n"
+ "Helper function for unpickling. Creates and initializes a new object of a given\n"
+ "class. See PEP 307 section \"Case 2: pickling new-style class instances using\n"
+ "protocols 0 or 1\" for details."
)]
public static object _reconstructor(CodeContext/*!*/ context, object objType, object baseType, object baseState) {
object obj;
if (baseState == null) {
obj = PythonOps.Invoke(context, baseType, "__new__", objType);
PythonOps.Invoke(context, baseType, "__init__", obj);
} else {
obj = PythonOps.Invoke(context, baseType, "__new__", objType, baseState);
PythonOps.Invoke(context, baseType, "__init__", obj, baseState);
}
return obj;
}
#endregion
#region Private implementation
/// <summary>
/// Convert object to ushort, throwing ValueError on overflow.
/// </summary>
private static int GetCode(CodeContext/*!*/ context, object value) {
try {
int intValue = PythonContext.GetContext(context).ConvertToInt32(value);
if (intValue > 0) return intValue;
// fall through and throw below
} catch (OverflowException) {
// throw below
}
throw PythonOps.ValueError("code out of range");
}
#endregion
private static void EnsureModuleInitialized(CodeContext context) {
if (!PythonContext.GetContext(context).HasModuleState(_dispatchTableKey)) {
Importer.ImportBuiltin(context, "copyreg");
}
}
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
context.NewObject = (BuiltinFunction)dict["__newobj__"];
context.PythonReconstructor = (BuiltinFunction)dict["_reconstructor"];
PythonDictionary dispatchTable = new PythonDictionary();
dispatchTable[TypeCache.Complex] = dict["pickle_complex"];
context.SetModuleState(_dispatchTableKey, dict["dispatch_table"] = dispatchTable);
context.SetModuleState(_extensionRegistryKey, dict["_extension_registry"] = new PythonDictionary());
context.SetModuleState(_invertedRegistryKey, dict["_inverted_registry"] = new PythonDictionary());
context.SetModuleState(_extensionCacheKey, dict["_extension_cache"] = new PythonDictionary());
}
}
}
| |
//
// ConditionType.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.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.
//
using System;
using System.Xml;
using Mono.Addins.Description;
using System.Collections;
using System.Collections.Generic;
namespace Mono.Addins
{
/// <summary>
/// A condition evaluator.
/// </summary>
/// <remarks>
/// Add-ins may use conditions to register nodes in an extension point which
/// are only visible under some contexts. For example, an add-in registering
/// a custom menu option to the main menu of a sample text editor might want
/// to make that option visible only for some kind of files. To allow add-ins
/// to do this kind of check, the host application needs to define a new condition.
/// </remarks>
public abstract class ConditionType
{
internal event EventHandler Changed;
string id;
/// <summary>
/// Evaluates the condition.
/// </summary>
/// <param name="conditionNode">
/// Condition node information.
/// </param>
/// <returns>
/// 'true' if the condition is satisfied.
/// </returns>
public abstract bool Evaluate (NodeElement conditionNode);
/// <summary>
/// Notifies that the condition has changed, and that it has to be re-evaluated.
/// </summary>
/// This method must be called when there is a change in the state that determines
/// the result of the evaluation. When this method is called, all node conditions
/// depending on it are reevaluated and the corresponding events for adding or
/// removing extension nodes are fired.
/// <remarks>
/// </remarks>
public void NotifyChanged ()
{
if (Changed != null)
Changed (this, EventArgs.Empty);
}
internal string Id {
get { return id; }
set { id = value; }
}
}
internal class BaseCondition
{
BaseCondition parent;
internal BaseCondition (BaseCondition parent)
{
this.parent = parent;
}
public virtual bool Evaluate (ExtensionContext ctx)
{
return parent == null || parent.Evaluate (ctx);
}
internal virtual void GetConditionTypes (List<string> listToFill)
{
}
}
internal class NullCondition: BaseCondition
{
public NullCondition (): base (null)
{
}
public override bool Evaluate (ExtensionContext ctx)
{
return false;
}
}
class OrCondition: BaseCondition
{
BaseCondition[] conditions;
public OrCondition (BaseCondition[] conditions, BaseCondition parent): base (parent)
{
this.conditions = conditions;
}
public override bool Evaluate (ExtensionContext ctx)
{
if (!base.Evaluate (ctx))
return false;
foreach (BaseCondition cond in conditions)
if (cond.Evaluate (ctx))
return true;
return false;
}
internal override void GetConditionTypes (List<string> listToFill)
{
foreach (BaseCondition cond in conditions)
cond.GetConditionTypes (listToFill);
}
}
class AndCondition: BaseCondition
{
BaseCondition[] conditions;
public AndCondition (BaseCondition[] conditions, BaseCondition parent): base (parent)
{
this.conditions = conditions;
}
public override bool Evaluate (ExtensionContext ctx)
{
if (!base.Evaluate (ctx))
return false;
foreach (BaseCondition cond in conditions)
if (!cond.Evaluate (ctx))
return false;
return true;
}
internal override void GetConditionTypes (List<string> listToFill)
{
foreach (BaseCondition cond in conditions)
cond.GetConditionTypes (listToFill);
}
}
class NotCondition: BaseCondition
{
BaseCondition baseCond;
public NotCondition (BaseCondition baseCond, BaseCondition parent): base (parent)
{
this.baseCond = baseCond;
}
public override bool Evaluate (ExtensionContext ctx)
{
return !baseCond.Evaluate (ctx);
}
internal override void GetConditionTypes (List<string> listToFill)
{
baseCond.GetConditionTypes (listToFill);
}
}
internal sealed class Condition: BaseCondition
{
ExtensionNodeDescription node;
string typeId;
AddinEngine addinEngine;
string addin;
internal const string SourceAddinAttribute = "__sourceAddin";
internal Condition (AddinEngine addinEngine, ExtensionNodeDescription element, BaseCondition parent): base (parent)
{
this.addinEngine = addinEngine;
typeId = element.GetAttribute ("id");
addin = element.GetAttribute (SourceAddinAttribute);
node = element;
}
public override bool Evaluate (ExtensionContext ctx)
{
if (!base.Evaluate (ctx))
return false;
if (!string.IsNullOrEmpty (addin)) {
// Make sure the add-in that implements the condition is loaded
addinEngine.LoadAddin (null, addin, true);
addin = null; // Don't try again
}
ConditionType type = ctx.GetCondition (typeId);
if (type == null) {
var parts = string.Join(", ", Array.ConvertAll(node.Attributes, attr => attr.Name + "=" + attr.Value));
addinEngine.ReportError ("Condition '" + typeId + "' not found in current extension context. [" + parts + "]", node.ParentAddinDescription.AddinId, null, false);
return false;
}
try {
return type.Evaluate (node);
}
catch (Exception ex) {
addinEngine.ReportError ("Error while evaluating condition '" + typeId + "'", node.ParentAddinDescription.AddinId, ex, false);
return false;
}
}
internal override void GetConditionTypes (List<string> listToFill)
{
listToFill.Add (typeId);
}
}
}
| |
// 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 Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed partial class ExpressionBinder
{
// ----------------------------------------------------------------------------
// BindExplicitConversion
// ----------------------------------------------------------------------------
private sealed class ExplicitConversion
{
private readonly ExpressionBinder _binder;
private Expr _exprSrc;
private readonly CType _typeSrc;
private readonly CType _typeDest;
// This is for lambda error reporting. The reason we have this is because we
// store errors for lambda conversions, and then we don't bind the conversion
// again to report errors. Consider the following case:
//
// int? x = () => null;
//
// When we try to convert the lambda to the nullable type int?, we first
// attempt the conversion to int. If that fails, then we know there is no
// conversion to int?, since int is a predef type. We then look for UserDefined
// conversions, and fail. When we report the errors, we ask the lambda for its
// conversion errors. But since we attempted its conversion to int and not int?,
// we report the wrong error. This field is to keep track of the right type
// to report the error on, so that when the lambda conversion fails, it reports
// errors on the correct type.
private Expr _exprDest;
private readonly bool _needsExprDest;
private readonly CONVERTTYPE _flags;
// ----------------------------------------------------------------------------
// BindExplicitConversion
// ----------------------------------------------------------------------------
public ExplicitConversion(ExpressionBinder binder, Expr exprSrc, CType typeSrc, CType typeDest, bool needsExprDest, CONVERTTYPE flags)
{
_binder = binder;
_exprSrc = exprSrc;
_typeSrc = typeSrc;
_typeDest = typeDest;
_needsExprDest = needsExprDest;
_flags = flags;
_exprDest = null;
}
public Expr ExprDest { get { return _exprDest; } }
/*
* BindExplicitConversion
*
* This is a complex routine with complex parameter. Generally, this should
* be called through one of the helper methods that insulates you
* from the complexity of the interface. This routine handles all the logic
* associated with explicit conversions.
*
* Note that this function calls BindImplicitConversion first, so the main
* logic is only concerned with conversions that can be made explicitly, but
* not implicitly.
*/
public bool Bind()
{
// To test for a standard conversion, call canConvert(exprSrc, typeDest, STANDARDANDCONVERTTYPE.NOUDC) and
// canConvert(typeDest, typeSrc, STANDARDANDCONVERTTYPE.NOUDC).
Debug.Assert((_flags & CONVERTTYPE.STANDARD) == 0);
// 13.2 Explicit conversions
//
// The following conversions are classified as explicit conversions:
//
// * All implicit conversions
// * Explicit numeric conversions
// * Explicit enumeration conversions
// * Explicit reference conversions
// * Explicit interface conversions
// * Unboxing conversions
// * Explicit type parameter conversions
// * User-defined explicit conversions
// * Explicit nullable conversions
// * Lifted user-defined explicit conversions
//
// Explicit conversions can occur in cast expressions (14.6.6).
//
// The explicit conversions that are not implicit conversions are conversions that cannot be
// proven always to succeed, conversions that are known possibly to lose information, and
// conversions across domains of types sufficiently different to merit explicit notation.
// The set of explicit conversions includes all implicit conversions.
// Don't try user-defined conversions now because we'll try them again later.
if (_binder.BindImplicitConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.ISEXPLICIT))
{
return true;
}
if (_typeSrc == null || _typeDest == null || _typeDest is MethodGroupType)
{
return false;
}
if (_typeDest is NullableType)
{
// This is handled completely by BindImplicitConversion.
return false;
}
if (_typeSrc is NullableType)
{
return bindExplicitConversionFromNub();
}
if (bindExplicitConversionFromArrayToIList())
{
return true;
}
// if we were casting an integral constant to another constant type,
// then, if the constant were in range, then the above call would have succeeded.
// But it failed, and so we know that the constant is not in range
switch (_typeDest.TypeKind)
{
default:
Debug.Fail($"Bad type kind: {_typeDest.TypeKind}");
return false;
case TypeKind.TK_VoidType:
return false; // Can't convert to a method group or anon method.
case TypeKind.TK_NullType:
return false; // Can never convert TO the null type.
case TypeKind.TK_ArrayType:
if (bindExplicitConversionToArray((ArrayType)_typeDest))
{
return true;
}
break;
case TypeKind.TK_PointerType:
if (bindExplicitConversionToPointer())
{
return true;
}
break;
case TypeKind.TK_AggregateType:
{
AggCastResult result = bindExplicitConversionToAggregate(_typeDest as AggregateType);
if (result == AggCastResult.Success)
{
return true;
}
if (result == AggCastResult.Abort)
{
return false;
}
break;
}
}
// No built-in conversion was found. Maybe a user-defined conversion?
if (0 == (_flags & CONVERTTYPE.NOUDC))
{
return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false);
}
return false;
}
private bool bindExplicitConversionFromNub()
{
Debug.Assert(_typeSrc != null);
Debug.Assert(_typeDest != null);
// If S and T are value types and there is a builtin conversion from S => T then there is an
// explicit conversion from S? => T that throws on null.
if (_typeDest.IsValueType && _binder.BindExplicitConversion(null, _typeSrc.StripNubs(), _typeDest, _flags | CONVERTTYPE.NOUDC))
{
if (_needsExprDest)
{
Expr valueSrc = _exprSrc;
if (valueSrc.Type is NullableType)
{
valueSrc = _binder.BindNubValue(valueSrc);
}
Debug.Assert(valueSrc.Type == _typeSrc.StripNubs());
if (!_binder.BindExplicitConversion(valueSrc, valueSrc.Type, _typeDest, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.NOUDC))
{
Debug.Fail("BindExplicitConversion failed unexpectedly");
return false;
}
if (_exprDest is ExprUserDefinedConversion udc)
{
udc.Argument = _exprSrc;
}
}
return true;
}
if ((_flags & CONVERTTYPE.NOUDC) == 0)
{
return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false);
}
return false;
}
private bool bindExplicitConversionFromArrayToIList()
{
// 13.2.2
//
// The explicit reference conversions are:
//
// * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and
// their base interfaces, provided there is an explicit reference conversion from S to T.
Debug.Assert(_typeSrc != null);
Debug.Assert(_typeDest != null);
if (!(_typeSrc is ArrayType arrSrc) || !arrSrc.IsSZArray || !(_typeDest is AggregateType aggDest)
|| !aggDest.IsInterfaceType || aggDest.TypeArgsAll.Count != 1)
{
return false;
}
AggregateSymbol aggIList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_ILIST);
AggregateSymbol aggIReadOnlyList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_IREADONLYLIST);
if ((aggIList == null ||
!SymbolLoader.IsBaseAggregate(aggIList, aggDest.OwningAggregate)) &&
(aggIReadOnlyList == null ||
!SymbolLoader.IsBaseAggregate(aggIReadOnlyList, aggDest.OwningAggregate)))
{
return false;
}
CType typeArr = arrSrc.ElementType;
CType typeLst = aggDest.TypeArgsAll[0];
if (!CConversions.FExpRefConv(GetSymbolLoader(), typeArr, typeLst))
{
return false;
}
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK);
return true;
}
private bool bindExplicitConversionFromIListToArray(ArrayType arrayDest)
{
// 13.2.2
//
// The explicit reference conversions are:
//
// * From System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and their base interfaces
// to a one-dimensional array-type S[], provided there is an implicit or explicit reference conversion from
// S[] to System.Collections.Generic.IList<T> or System.Collections.Generic.IReadOnlyList<T>. This is precisely when either S and T
// are the same type or there is an implicit or explicit reference conversion from S to T.
if (!arrayDest.IsSZArray || !(_typeSrc is AggregateType aggSrc) || !aggSrc.IsInterfaceType || aggSrc.TypeArgsAll.Count != 1)
{
return false;
}
AggregateSymbol aggIList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_ILIST);
AggregateSymbol aggIReadOnlyList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_IREADONLYLIST);
if ((aggIList == null ||
!SymbolLoader.IsBaseAggregate(aggIList, aggSrc.OwningAggregate)) &&
(aggIReadOnlyList == null ||
!SymbolLoader.IsBaseAggregate(aggIReadOnlyList, aggSrc.OwningAggregate)))
{
return false;
}
CType typeArr = arrayDest.ElementType;
CType typeLst = aggSrc.TypeArgsAll[0];
Debug.Assert(!(typeArr is MethodGroupType));
if (typeArr != typeLst && !CConversions.FExpRefConv(GetSymbolLoader(), typeArr, typeLst))
{
return false;
}
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK);
return true;
}
private bool bindExplicitConversionFromArrayToArray(ArrayType arraySrc, ArrayType arrayDest)
{
// 13.2.2
//
// The explicit reference conversions are:
//
// * From an array-type S with an element type SE to an array-type T with an element type
// TE, provided all of the following are true:
//
// * S and T differ only in element type. (In other words, S and T have the same number
// of dimensions.)
//
// * An explicit reference conversion exists from SE to TE.
if (arraySrc.Rank != arrayDest.Rank || arraySrc.IsSZArray != arrayDest.IsSZArray)
{
return false; // Ranks do not match.
}
if (CConversions.FExpRefConv(GetSymbolLoader(), arraySrc.ElementType, arrayDest.ElementType))
{
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK);
return true;
}
return false;
}
private bool bindExplicitConversionToArray(ArrayType arrayDest)
{
Debug.Assert(_typeSrc != null);
Debug.Assert(arrayDest != null);
if (_typeSrc is ArrayType arrSrc)
{
return bindExplicitConversionFromArrayToArray(arrSrc, arrayDest);
}
if (bindExplicitConversionFromIListToArray(arrayDest))
{
return true;
}
// 13.2.2
//
// The explicit reference conversions are:
//
// * From System.Array and the interfaces it implements, to any array-type.
if (_binder.canConvert(_binder.GetPredefindType(PredefinedType.PT_ARRAY), _typeSrc, CONVERTTYPE.NOUDC))
{
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK);
return true;
}
return false;
}
private bool bindExplicitConversionToPointer()
{
// 27.4 Pointer conversions
//
// in an unsafe context, the set of available explicit conversions (13.2) is extended to
// include the following explicit pointer conversions:
//
// * From any pointer-type to any other pointer-type.
// * From sbyte, byte, short, ushort, int, uint, long, or ulong to any pointer-type.
if (_typeSrc is PointerType || _typeSrc.FundamentalType <= FUNDTYPE.FT_LASTINTEGRAL && _typeSrc.IsNumericType)
{
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest);
return true;
}
return false;
}
// 13.2.2 Explicit enumeration conversions
//
// The explicit enumeration conversions are:
//
// * From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or
// decimal to any enum-type.
//
// * From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, char,
// float, double, or decimal.
//
// * From any enum-type to any other enum-type.
//
// * An explicit enumeration conversion between two types is processed by treating any
// participating enum-type as the underlying type of that enum-type, and then performing
// an implicit or explicit numeric conversion between the resulting types.
private AggCastResult bindExplicitConversionFromEnumToAggregate(AggregateType aggTypeDest)
{
Debug.Assert(_typeSrc != null);
Debug.Assert(aggTypeDest != null);
if (!_typeSrc.IsEnumType)
{
return AggCastResult.Failure;
}
AggregateSymbol aggDest = aggTypeDest.OwningAggregate;
if (aggDest.isPredefAgg(PredefinedType.PT_DECIMAL))
{
return bindExplicitConversionFromEnumToDecimal(aggTypeDest);
}
if (!aggDest.getThisType().IsNumericType &&
!aggDest.IsEnum() &&
!(aggDest.IsPredefined() && aggDest.GetPredefType() == PredefinedType.PT_CHAR))
{
return AggCastResult.Failure;
}
if (_exprSrc.GetConst() != null)
{
ConstCastResult result = _binder.bindConstantCast(_exprSrc, _typeDest, _needsExprDest, out _exprDest, true);
if (result == ConstCastResult.Success)
{
return AggCastResult.Success;
}
else if (result == ConstCastResult.CheckFailure)
{
return AggCastResult.Abort;
}
}
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest);
return AggCastResult.Success;
}
private AggCastResult bindExplicitConversionFromDecimalToEnum(AggregateType aggTypeDest)
{
Debug.Assert(_typeSrc != null);
Debug.Assert(_typeSrc.IsPredefType(PredefinedType.PT_DECIMAL));
Debug.Assert(aggTypeDest.IsEnumType);
// There is an explicit conversion from decimal to all integral types.
if (_exprSrc.GetConst() != null)
{
// Fold the constant cast if possible.
ConstCastResult result = _binder.bindConstantCast(_exprSrc, _typeDest, _needsExprDest, out _exprDest, true);
if (result == ConstCastResult.Success)
{
return AggCastResult.Success; // else, don't fold and use a regular cast, below.
}
if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW))
{
return AggCastResult.Abort;
}
}
// All casts from decimal to integer types are bound as user-defined conversions.
bool bIsConversionOK = true;
if (_needsExprDest)
{
// According the language, this is a standard conversion, but it is implemented
// through a user-defined conversion. Because it's a standard conversion, we don't
// test the CONVERTTYPE.NOUDC flag here.
CType underlyingType = aggTypeDest.UnderlyingEnumType;
bIsConversionOK = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, underlyingType, _needsExprDest, out _exprDest, false);
if (bIsConversionOK)
{
// upcast to the Enum type
_binder.bindSimpleCast(_exprDest, _typeDest, out _exprDest);
}
}
return bIsConversionOK ? AggCastResult.Success : AggCastResult.Failure;
}
private AggCastResult bindExplicitConversionFromEnumToDecimal(AggregateType aggTypeDest)
{
Debug.Assert(_typeSrc != null);
Debug.Assert(aggTypeDest != null);
Debug.Assert(aggTypeDest.IsPredefType(PredefinedType.PT_DECIMAL));
Debug.Assert(_typeSrc.IsEnumType);
AggregateType underlyingType = _typeSrc.UnderlyingEnumType;
// Need to first cast the source expr to its underlying type.
Expr exprCast;
if (_exprSrc == null)
{
exprCast = null;
}
else
{
_binder.bindSimpleCast(_exprSrc, underlyingType, out exprCast);
}
// There is always an implicit conversion from any integral type to decimal.
if (exprCast.GetConst() != null)
{
// Fold the constant cast if possible.
ConstCastResult result = _binder.bindConstantCast(exprCast, _typeDest, _needsExprDest, out _exprDest, true);
if (result == ConstCastResult.Success)
{
return AggCastResult.Success; // else, don't fold and use a regular cast, below.
}
if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW))
{
return AggCastResult.Abort;
}
}
// Conversions from integral types to decimal are always bound as a user-defined conversion.
if (_needsExprDest)
{
// According the language, this is a standard conversion, but it is implemented
// through a user-defined conversion. Because it's a standard conversion, we don't
// test the CONVERTTYPE.NOUDC flag here.
bool ok = _binder.bindUserDefinedConversion(exprCast, underlyingType, aggTypeDest, _needsExprDest, out _exprDest, false);
Debug.Assert(ok);
}
return AggCastResult.Success;
}
private AggCastResult bindExplicitConversionToEnum(AggregateType aggTypeDest)
{
Debug.Assert(_typeSrc != null);
Debug.Assert(aggTypeDest != null);
AggregateSymbol aggDest = aggTypeDest.OwningAggregate;
if (!aggDest.IsEnum())
{
return AggCastResult.Failure;
}
if (_typeSrc.IsPredefType(PredefinedType.PT_DECIMAL))
{
return bindExplicitConversionFromDecimalToEnum(aggTypeDest);
}
if (_typeSrc.IsNumericType || _typeSrc.IsPredefined && _typeSrc.PredefinedType == PredefinedType.PT_CHAR)
{
// Transform constant to constant.
if (_exprSrc.GetConst() != null)
{
ConstCastResult result = _binder.bindConstantCast(_exprSrc, _typeDest, _needsExprDest, out _exprDest, true);
if (result == ConstCastResult.Success)
{
return AggCastResult.Success;
}
if (result == ConstCastResult.CheckFailure)
{
return AggCastResult.Abort;
}
}
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest);
return AggCastResult.Success;
}
else if (_typeSrc.IsPredefined &&
(_typeSrc.IsPredefType(PredefinedType.PT_OBJECT) || _typeSrc.IsPredefType(PredefinedType.PT_VALUE) || _typeSrc.IsPredefType(PredefinedType.PT_ENUM)))
{
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, EXPRFLAG.EXF_UNBOX);
return AggCastResult.Success;
}
return AggCastResult.Failure;
}
private AggCastResult bindExplicitConversionBetweenSimpleTypes(AggregateType aggTypeDest)
{
// 13.2.1
//
// Because the explicit conversions include all implicit and explicit numeric conversions,
// it is always possible to convert from any numeric-type to any other numeric-type using
// a cast expression (14.6.6).
Debug.Assert(_typeSrc != null);
Debug.Assert(aggTypeDest != null);
if (!_typeSrc.IsSimpleType || !aggTypeDest.IsSimpleType)
{
return AggCastResult.Failure;
}
AggregateSymbol aggDest = aggTypeDest.OwningAggregate;
Debug.Assert(_typeSrc.IsPredefined && aggDest.IsPredefined());
PredefinedType ptSrc = _typeSrc.PredefinedType;
PredefinedType ptDest = aggDest.GetPredefType();
Debug.Assert((int)ptSrc < NUM_SIMPLE_TYPES && (int)ptDest < NUM_SIMPLE_TYPES);
ConvKind convertKind = GetConvKind(ptSrc, ptDest);
// Identity and implicit conversions should already have been handled.
Debug.Assert(convertKind != ConvKind.Implicit);
Debug.Assert(convertKind != ConvKind.Identity);
if (convertKind != ConvKind.Explicit)
{
return AggCastResult.Failure;
}
if (_exprSrc.GetConst() != null)
{
// Fold the constant cast if possible.
ConstCastResult result = _binder.bindConstantCast(_exprSrc, _typeDest, _needsExprDest, out _exprDest, true);
if (result == ConstCastResult.Success)
{
return AggCastResult.Success; // else, don't fold and use a regular cast, below.
}
if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW))
{
return AggCastResult.Abort;
}
}
bool bConversionOk = true;
if (_needsExprDest)
{
// Explicit conversions involving decimals are bound as user-defined conversions.
if (isUserDefinedConversion(ptSrc, ptDest))
{
// According the language, this is a standard conversion, but it is implemented
// through a user-defined conversion. Because it's a standard conversion, we don't
// test the CONVERTTYPE.NOUDC flag here.
bConversionOk = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, aggTypeDest, _needsExprDest, out _exprDest, false);
}
else
{
_binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, (_flags & CONVERTTYPE.CHECKOVERFLOW) != 0 ? EXPRFLAG.EXF_CHECKOVERFLOW : 0);
}
}
return bConversionOk ? AggCastResult.Success : AggCastResult.Failure;
}
private AggCastResult bindExplicitConversionBetweenAggregates(AggregateType aggTypeDest)
{
// 13.2.3
//
// The explicit reference conversions are:
//
// * From object to any reference-type.
// * From any class-type S to any class-type T, provided S is a base class of T.
// * From any class-type S to any interface-type T, provided S is not sealed and
// provided S does not implement T.
// * From any interface-type S to any class-type T, provided T is not sealed or provided
// T implements S.
// * From any interface-type S to any interface-type T, provided S is not derived from T.
Debug.Assert(_typeSrc != null);
Debug.Assert(aggTypeDest != null);
if (!(_typeSrc is AggregateType atSrc))
{
return AggCastResult.Failure;
}
AggregateSymbol aggSrc = atSrc.OwningAggregate;
AggregateSymbol aggDest = aggTypeDest.OwningAggregate;
if (GetSymbolLoader().HasBaseConversion(aggTypeDest, atSrc))
{
if (_needsExprDest)
{
_binder.bindSimpleCast(
_exprSrc, _typeDest, out _exprDest,
aggDest.IsValueType() && aggSrc.getThisType().FundamentalType == FUNDTYPE.FT_REF
? EXPRFLAG.EXF_UNBOX
: EXPRFLAG.EXF_REFCHECK | (_exprSrc?.Flags & EXPRFLAG.EXF_CANTBENULL ?? 0));
}
return AggCastResult.Success;
}
if ((aggSrc.IsClass() && !aggSrc.IsSealed() && aggDest.IsInterface()) ||
(aggSrc.IsInterface() && aggDest.IsClass() && !aggDest.IsSealed()) ||
(aggSrc.IsInterface() && aggDest.IsInterface()) ||
CConversions.HasGenericDelegateExplicitReferenceConversion(GetSymbolLoader(), _typeSrc, aggTypeDest))
{
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK | (_exprSrc?.Flags & EXPRFLAG.EXF_CANTBENULL ?? 0));
return AggCastResult.Success;
}
return AggCastResult.Failure;
}
private AggCastResult bindExplicitConversionFromPointerToInt(AggregateType aggTypeDest)
{
// 27.4 Pointer conversions
// in an unsafe context, the set of available explicit conversions (13.2) is extended to include
// the following explicit pointer conversions:
//
// * From any pointer-type to sbyte, byte, short, ushort, int, uint, long, or ulong.
if (!(_typeSrc is PointerType) || aggTypeDest.FundamentalType > FUNDTYPE.FT_LASTINTEGRAL || !aggTypeDest.IsNumericType)
{
return AggCastResult.Failure;
}
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest);
return AggCastResult.Success;
}
private AggCastResult bindExplicitConversionToAggregate(AggregateType aggTypeDest)
{
Debug.Assert(_typeSrc != null);
Debug.Assert(aggTypeDest != null);
AggCastResult result = bindExplicitConversionFromEnumToAggregate(aggTypeDest);
if (result != AggCastResult.Failure)
{
return result;
}
result = bindExplicitConversionToEnum(aggTypeDest);
if (result != AggCastResult.Failure)
{
return result;
}
result = bindExplicitConversionBetweenSimpleTypes(aggTypeDest);
if (result != AggCastResult.Failure)
{
return result;
}
result = bindExplicitConversionBetweenAggregates(aggTypeDest);
if (result != AggCastResult.Failure)
{
return result;
}
result = bindExplicitConversionFromPointerToInt(aggTypeDest);
if (result != AggCastResult.Failure)
{
return result;
}
if (_typeSrc is VoidType)
{
// No conversion is allowed to or from a void type (user defined or otherwise)
// This is most likely the result of a failed anonymous method or member group conversion
return AggCastResult.Abort;
}
return AggCastResult.Failure;
}
private SymbolLoader GetSymbolLoader()
{
return _binder.GetSymbolLoader();
}
private ExprFactory GetExprFactory()
{
return _binder.GetExprFactory();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Threading;
using Common.Logging;
using NUnit.Framework;
using Quartz.Impl;
using Quartz.Impl.Calendar;
using Quartz.Impl.Triggers;
using Quartz.Job;
using Quartz.Spi;
namespace Quartz.Tests.Integration.Impl.AdoJobStore
{
[Category("integration")]
[TestFixture]
public class AdoJobStoreSmokeTest
{
private static readonly Dictionary<string, string> dbConnectionStrings = new Dictionary<string, string>();
private bool clearJobs = true;
private bool scheduleJobs = true;
private bool clustered = true;
private ILoggerFactoryAdapter oldAdapter;
static AdoJobStoreSmokeTest()
{
dbConnectionStrings["Oracle"] = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=xe)));User Id=quartznet;Password=quartznet;";
dbConnectionStrings["SQLServer"] = "Server=(local);Database=quartz;Trusted_Connection=True;";
dbConnectionStrings["SQLServerCe"] = @"Data Source=C:\quartznet.sdf;Persist Security Info=False;";
dbConnectionStrings["MySQL"] = "Server = localhost; Database = quartz; Uid = quartznet; Pwd = quartznet";
dbConnectionStrings["PostgreSQL"] = "Server=127.0.0.1;Port=5432;Userid=quartznet;Password=quartznet;Protocol=3;SSL=false;Pooling=true;MinPoolSize=1;MaxPoolSize=20;Encoding=UTF8;Timeout=15;SslMode=Disable;Database=quartznet";
dbConnectionStrings["SQLite"] = "Data Source=test.db;Version=3;";
dbConnectionStrings["Firebird"] = "User=SYSDBA;Password=masterkey;Database=c:\\quartznet;DataSource=localhost;Port=3050;Dialect=3; Charset=NONE;Role=;Connection lifetime=15;Pooling=true;MinPoolSize=0;MaxPoolSize=50;Packet Size=8192;ServerType=0;";
}
[TestFixtureSetUp]
public void FixtureSetUp()
{
// set Adapter to report problems
oldAdapter = LogManager.Adapter;
LogManager.Adapter = new FailFastLoggerFactoryAdapter();
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
// default back to old
LogManager.Adapter = oldAdapter;
}
[Test]
public void TestFirebird()
{
RunAdoJobStoreTest("Firebird-201", "Firebird");
}
[Test]
public void TestPostgreSQL10()
{
// we don't support Npgsql-10 anymore
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.PostgreSQLDelegate, Quartz";
try
{
RunAdoJobStoreTest("Npgsql-10", "PostgreSQL", properties);
Assert.Fail("No error from using Npgsql-10");
}
catch (SchedulerException ex)
{
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("Npgsql-10 provider is no longer supported.", ex.InnerException.Message);
}
}
[Test]
public void TestPostgreSQL20()
{
NameValueCollection properties = new NameValueCollection();
RunAdoJobStoreTest("Npgsql-20", "PostgreSQL", properties);
}
[Test]
public void TestSqlServer11()
{
// we don't support SQL Server 1.1
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
try
{
RunAdoJobStoreTest("SqlServer-11", "SQLServer", properties);
Assert.Fail("No error from using SqlServer-11");
}
catch (SchedulerException ex)
{
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("SqlServer-11 provider is no longer supported.", ex.InnerException.Message);
}
}
[Test]
public void TestSqlServer20()
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
RunAdoJobStoreTest("SqlServer-20", "SQLServer", properties);
}
[Test]
public void TestSqlServerCe351()
{
bool previousClustered = clustered;
clustered = false;
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
try
{
RunAdoJobStoreTest("SqlServerCe-351", "SQLServerCe", properties);
}
finally
{
clustered = previousClustered;
}
}
[Test]
public void TestSqlServerCe352()
{
bool previousClustered = clustered;
clustered = false;
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
try
{
RunAdoJobStoreTest("SqlServerCe-352", "SQLServerCe", properties);
}
finally
{
clustered = previousClustered;
}
}
[Test]
public void TestSqlServerCe400()
{
bool previousClustered = clustered;
clustered = false;
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
try
{
RunAdoJobStoreTest("SqlServerCe-400", "SQLServerCe", properties);
}
finally
{
clustered = previousClustered;
}
}
[Test]
public void TestOracleODP20()
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.OracleDelegate, Quartz";
RunAdoJobStoreTest("OracleODP-20", "Oracle", properties);
}
[Test]
public void TestMySql50()
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.MySQLDelegate, Quartz";
RunAdoJobStoreTest("MySql-50", "MySQL", properties);
}
[Test]
public void TestMySql51()
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.MySQLDelegate, Quartz";
RunAdoJobStoreTest("MySql-51", "MySQL", properties);
}
[Test]
public void TestMySql10()
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.MySQLDelegate, Quartz";
RunAdoJobStoreTest("MySql-10", "MySQL", properties);
}
[Test]
public void TestMySql109()
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.MySQLDelegate, Quartz";
RunAdoJobStoreTest("MySql-109", "MySQL", properties);
}
[Test]
public void TestSQLite10()
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SQLiteDelegate, Quartz";
RunAdoJobStoreTest("SQLite-10", "SQLite", properties);
}
[Test]
public void TestSQLite10Clustered()
{
clustered = true;
try
{
TestSQLite10();
}
finally
{
clustered = false;
}
}
private void RunAdoJobStoreTest(string dbProvider, string connectionStringId)
{
RunAdoJobStoreTest(dbProvider, connectionStringId, null);
}
private void RunAdoJobStoreTest(string dbProvider, string connectionStringId,
NameValueCollection extraProperties)
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "TestScheduler";
properties["quartz.scheduler.instanceId"] = "instance_one";
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "10";
properties["quartz.threadPool.threadPriority"] = "Normal";
properties["quartz.jobStore.misfireThreshold"] = "60000";
properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz";
properties["quartz.jobStore.useProperties"] = "false";
properties["quartz.jobStore.dataSource"] = "default";
properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
properties["quartz.jobStore.clustered"] = clustered.ToString();
properties["quartz.jobStore.clusterCheckinInterval"] = 1000.ToString();
if (extraProperties != null)
{
foreach (string key in extraProperties.Keys)
{
properties[key] = extraProperties[key];
}
}
if (connectionStringId == "SQLite")
{
// if running SQLite we need this, SQL Server is sniffed automatically
properties["quartz.jobStore.lockHandler.type"] = "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz";
}
string connectionString;
if (!dbConnectionStrings.TryGetValue(connectionStringId, out connectionString))
{
throw new Exception("Unknown connection string id: " + connectionStringId);
}
properties["quartz.dataSource.default.connectionString"] = connectionString;
properties["quartz.dataSource.default.provider"] = dbProvider;
// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = sf.GetScheduler();
SmokeTestPerformer performer = new SmokeTestPerformer();
performer.Test(sched, clearJobs, scheduleJobs);
Assert.IsEmpty(FailFastLoggerFactoryAdapter.Errors, "Found error from logging output");
}
[Test]
[Explicit]
public void TestSqlServerStress()
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "TestScheduler";
properties["quartz.scheduler.instanceId"] = "instance_one";
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "10";
properties["quartz.threadPool.threadPriority"] = "Normal";
properties["quartz.jobStore.misfireThreshold"] = "60000";
properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz";
properties["quartz.jobStore.useProperties"] = "false";
properties["quartz.jobStore.dataSource"] = "default";
properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
properties["quartz.jobStore.clustered"] = clustered.ToString();
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
RunAdoJobStoreTest("SqlServer-20", "SQLServer", properties);
string connectionString;
if (!dbConnectionStrings.TryGetValue("SQLServer", out connectionString))
{
throw new Exception("Unknown connection string id: " + "SQLServer");
}
properties["quartz.dataSource.default.connectionString"] = connectionString;
properties["quartz.dataSource.default.provider"] = "SqlServer-20";
// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = sf.GetScheduler();
try
{
sched.Clear();
if (scheduleJobs)
{
ICalendar cronCalendar = new CronCalendar("0/5 * * * * ?");
ICalendar holidayCalendar = new HolidayCalendar();
for (int i = 0; i < 100000; ++i)
{
ITrigger trigger = new SimpleTriggerImpl("calendarsTrigger", "test", SimpleTriggerImpl.RepeatIndefinitely, TimeSpan.FromSeconds(1));
JobDetailImpl jd = new JobDetailImpl("testJob", "test", typeof(NoOpJob));
sched.ScheduleJob(jd, trigger);
}
}
sched.Start();
Thread.Sleep(TimeSpan.FromSeconds(30));
}
finally
{
sched.Shutdown(false);
}
}
[Test]
[Explicit]
public void StressTest()
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "TestScheduler";
properties["quartz.scheduler.instanceId"] = "instance_one";
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "10";
properties["quartz.threadPool.threadPriority"] = "Normal";
properties["quartz.jobStore.misfireThreshold"] = "60000";
properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz";
properties["quartz.jobStore.useProperties"] = "false";
properties["quartz.jobStore.dataSource"] = "default";
properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
properties["quartz.jobStore.clustered"] = "false";
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
string connectionString = "Server=(local);Database=quartz;Trusted_Connection=True;";
properties["quartz.dataSource.default.connectionString"] = connectionString;
properties["quartz.dataSource.default.provider"] = "SqlServer-20";
// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = sf.GetScheduler();
try
{
sched.Clear();
JobDetailImpl lonelyJob = new JobDetailImpl("lonelyJob", "lonelyGroup", typeof(SimpleRecoveryJob));
lonelyJob.Durable = true;
lonelyJob.RequestsRecovery = true;
sched.AddJob(lonelyJob, false);
sched.AddJob(lonelyJob, true);
string schedId = sched.SchedulerInstanceId;
JobDetailImpl job = new JobDetailImpl("job_to_use", schedId, typeof(SimpleRecoveryJob));
for (int i = 0; i < 100000; ++i)
{
IOperableTrigger trigger = new SimpleTriggerImpl("stressing_simple", SimpleTriggerImpl.RepeatIndefinitely, TimeSpan.FromSeconds(1));
trigger.StartTimeUtc = DateTime.Now.AddMilliseconds(i);
sched.ScheduleJob(job, trigger);
}
for (int i = 0; i < 100000; ++i)
{
IOperableTrigger ct = new CronTriggerImpl("stressing_cron", "0/1 * * * * ?");
ct.StartTimeUtc = DateTime.Now.AddMilliseconds(i);
sched.ScheduleJob(job, ct);
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
sched.Start();
Thread.Sleep(TimeSpan.FromMinutes(3));
stopwatch.Stop();
Console.WriteLine("Took: " + stopwatch.Elapsed);
}
finally
{
sched.Shutdown(false);
}
}
}
internal class DummyTriggerListener : ITriggerListener
{
public string Name
{
get { return GetType().FullName; }
}
public void TriggerFired(ITrigger trigger, IJobExecutionContext context)
{
}
public bool VetoJobExecution(ITrigger trigger, IJobExecutionContext context)
{
return false;
}
public void TriggerMisfired(ITrigger trigger)
{
}
public void TriggerComplete(ITrigger trigger, IJobExecutionContext context,
SchedulerInstruction triggerInstructionCode)
{
}
}
internal class DummyJobListener : IJobListener
{
public string Name
{
get { return GetType().FullName; }
}
public void JobToBeExecuted(IJobExecutionContext context)
{
}
public void JobExecutionVetoed(IJobExecutionContext context)
{
}
public void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)
{
}
}
public class SimpleRecoveryJob : IJob
{
private const string Count = "count";
/// <summary>
/// Called by the <see cref="IScheduler" /> when a
/// <see cref="ITrigger" /> fires that is associated with
/// the <see cref="IJob" />.
/// </summary>
public virtual void Execute(IJobExecutionContext context)
{
// delay for ten seconds
try
{
Thread.Sleep(TimeSpan.FromSeconds(10));
}
catch (ThreadInterruptedException)
{
}
JobDataMap data = context.JobDetail.JobDataMap;
int count;
if (data.ContainsKey(Count))
{
count = data.GetInt(Count);
}
else
{
count = 0;
}
count++;
data.Put(Count, count);
}
}
[DisallowConcurrentExecution]
[PersistJobDataAfterExecution]
public class SimpleRecoveryStatefulJob : SimpleRecoveryJob
{
}
}
| |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/* TextPrinter.cs --
* Ars Magna project, http://arsmagna.ru
* -------------------------------------------------------
*/
#region Using directives
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Printing;
using CodeJam;
using JetBrains.Annotations;
#endregion
namespace AM.Drawing.Printing
{
/// <summary>
///
/// </summary>
[PublicAPI]
[System.ComponentModel.DesignerCategory("Code")]
public abstract class TextPrinter
: Component
{
#region Events
/// <summary>
///
/// </summary>
public event PrintEventHandler BeginPrint;
/// <summary>
///
/// </summary>
public event PrintEventHandler EndPrint;
/// <summary>
///
/// </summary>
public event PrintPageEventHandler PrintPage;
/// <summary>
///
/// </summary>
public event QueryPageSettingsEventHandler QueryPageSettings;
#endregion
#region Properties
/// <summary>
/// Gets or sets the borders.
/// </summary>
public RectangleF Borders { get; set; }
/// <summary>
/// Gets or sets the name of the document.
/// </summary>
[NotNull]
public string DocumentName { get; set; }
/// <summary>
/// Gets the page number.
/// </summary>
public int PageNumber
{
get; protected set;
}
/// <summary>
/// Gets or sets the page settings.
/// </summary>
public PageSettings PageSettings { get; set; }
/// <summary>
/// Gets or sets the print controller.
/// </summary>
public PrintController PrintController { get; set; }
/// <summary>
/// Gets or sets the printer settings.
/// </summary>
public PrinterSettings PrinterSettings { get; set; }
/// <summary>
/// Gets or sets the color of the text.
/// </summary>
public Color TextColor { get; set; }
/// <summary>
/// Gets or sets the font.
/// </summary>
[NotNull]
public Font TextFont { get; set; }
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the
/// <see cref="TextPrinter"/> class.
/// </summary>
protected TextPrinter()
{
Borders = new RectangleF(10f, 10f, 10f, 10f);
DocumentName = "Text document";
TextColor = Color.Black;
TextFont = new Font(FontFamily.GenericSerif, 12f);
}
#endregion
#region Private members
/// <summary>
/// Called when [begin print].
/// </summary>
protected virtual void OnBeginPrint
(
object sender,
PrintEventArgs e
)
{
PrintEventHandler handler = BeginPrint;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Called when [end print].
/// </summary>
protected virtual void OnEndPrint
(
object sender,
PrintEventArgs e
)
{
PrintEventHandler handler = EndPrint;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Called when [print page].
/// </summary>
protected virtual void OnPrintPage
(
object sender,
PrintPageEventArgs ea
)
{
PrintPageEventHandler handler = PrintPage;
if (handler != null)
{
handler(this, ea);
}
}
/// <summary>
/// Called when [query page settings].
/// </summary>
protected virtual void OnQueryPageSettings
(
object sender,
QueryPageSettingsEventArgs e
)
{
++PageNumber;
QueryPageSettingsEventHandler handler = QueryPageSettings;
if (handler != null)
{
handler(this, e);
}
}
#endregion
#region Public methods
/// <summary>
/// Prints the specified text.
/// </summary>
public virtual bool Print(string text)
{
Code.NotNull(text, "text");
using (PrintDocument document = new PrintDocument())
{
document.DocumentName = DocumentName;
document.OriginAtMargins = false; // ???
if (PageSettings != null)
{
document.DefaultPageSettings = PageSettings;
}
if (PrintController != null)
{
document.PrintController = PrintController;
}
if (PrinterSettings != null)
{
document.PrinterSettings = PrinterSettings;
}
document.BeginPrint += OnBeginPrint;
document.EndPrint += OnEndPrint;
document.PrintPage += OnPrintPage;
document.QueryPageSettings += OnQueryPageSettings;
PageNumber = 1;
document.Print();
return true;
}
}
#endregion
}
}
| |
// 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 applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for LocalNetworkGatewaysOperations.
/// </summary>
public static partial class LocalNetworkGatewaysOperationsExtensions
{
/// <summary>
/// Creates or updates a local network gateway in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update local network gateway
/// operation.
/// </param>
public static LocalNetworkGateway CreateOrUpdate(this ILocalNetworkGatewaysOperations operations, string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, localNetworkGatewayName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a local network gateway in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update local network gateway
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LocalNetworkGateway> CreateOrUpdateAsync(this ILocalNetworkGatewaysOperations operations, string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, localNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the specified local network gateway in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
public static LocalNetworkGateway Get(this ILocalNetworkGatewaysOperations operations, string resourceGroupName, string localNetworkGatewayName)
{
return operations.GetAsync(resourceGroupName, localNetworkGatewayName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified local network gateway in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LocalNetworkGateway> GetAsync(this ILocalNetworkGatewaysOperations operations, string resourceGroupName, string localNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, localNetworkGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified local network gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
public static void Delete(this ILocalNetworkGatewaysOperations operations, string resourceGroupName, string localNetworkGatewayName)
{
operations.DeleteAsync(resourceGroupName, localNetworkGatewayName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified local network gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ILocalNetworkGatewaysOperations operations, string resourceGroupName, string localNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, localNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets all the local network gateways in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<LocalNetworkGateway> List(this ILocalNetworkGatewaysOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the local network gateways in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LocalNetworkGateway>> ListAsync(this ILocalNetworkGatewaysOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a local network gateway in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update local network gateway
/// operation.
/// </param>
public static LocalNetworkGateway BeginCreateOrUpdate(this ILocalNetworkGatewaysOperations operations, string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, localNetworkGatewayName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a local network gateway in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update local network gateway
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LocalNetworkGateway> BeginCreateOrUpdateAsync(this ILocalNetworkGatewaysOperations operations, string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, localNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified local network gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
public static void BeginDelete(this ILocalNetworkGatewaysOperations operations, string resourceGroupName, string localNetworkGatewayName)
{
operations.BeginDeleteAsync(resourceGroupName, localNetworkGatewayName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified local network gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this ILocalNetworkGatewaysOperations operations, string resourceGroupName, string localNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, localNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets all the local network gateways in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<LocalNetworkGateway> ListNext(this ILocalNetworkGatewaysOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the local network gateways in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LocalNetworkGateway>> ListNextAsync(this ILocalNetworkGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using Projeny.Internal;
namespace Projeny.Internal
{
public enum DragListTypes
{
Package,
Release,
AssetItem,
PluginItem,
VsSolution,
Count
}
public class DragListEntry
{
public string Name;
public object Model;
public int Index;
public DragList ListOwner;
public DragListTypes ListType;
public bool IsSelected;
}
public class DragList
{
public event Action SortMethodChanged = delegate {};
public event Action SortDescendingChanged = delegate {};
static readonly string DragId = "DragListData";
readonly List<DragListEntry> _entries = new List<DragListEntry>();
readonly PmView _manager;
readonly Model _model;
readonly DragListTypes _listType;
readonly PmSettings _pmSettings;
readonly PmSettings.DragListSettings _settings;
readonly List<string> _sortMethodCaptions = new List<string>();
public DragList(
PmView manager, DragListTypes listType, Model model, PmSettings pmSettings)
{
_model = model;
_manager = manager;
_listType = listType;
_settings = pmSettings.DragList;
_pmSettings = pmSettings;
}
public bool ShowSortPane
{
get;
set;
}
public List<string> SortMethodCaptions
{
set
{
Assert.That(_sortMethodCaptions.IsEmpty());
_sortMethodCaptions.AddRange(value);
}
}
public int SortMethod
{
get
{
return _model.SortMethod;
}
set
{
if (_model.SortMethod != value)
{
_model.SortMethod = value;
SortMethodChanged();
}
}
}
public bool SortDescending
{
get
{
return _model.SortDescending;
}
set
{
if (_model.SortDescending != value)
{
_model.SortDescending = value;
SortDescendingChanged();
}
}
}
public DragListTypes ListType
{
get
{
return _listType;
}
}
public string SearchFilter
{
get
{
return _model.SearchFilter;
}
set
{
Assert.IsNotNull(value);
_model.SearchFilter = value;
}
}
public IEnumerable<DragListEntry> Values
{
get
{
return _entries;
}
}
public IEnumerable<string> DisplayValues
{
get
{
return _entries.Select(x => x.Name);
}
}
public void ClearSelected()
{
foreach (var entry in _entries)
{
entry.IsSelected = false;
}
}
public void SelectAll()
{
foreach (var entry in _entries)
{
entry.IsSelected = true;
}
}
public void Remove(DragListEntry entry)
{
_entries.RemoveWithConfirm(entry);
UpdateIndices();
}
public void SetItems(List<ItemDescriptor> newItems)
{
var oldEntries = _entries.ToDictionary(x => x.Model, x => x);
_entries.Clear();
for (int i = 0; i < newItems.Count; i++)
{
var item = newItems[i];
var entry = new DragListEntry()
{
Name = item.Caption,
Model = item.Model,
ListOwner = this,
ListType = _listType,
Index = i,
};
var oldEntry = oldEntries.TryGetValue(item.Model);
if (oldEntry != null)
{
entry.IsSelected = oldEntry.IsSelected;
}
_entries.Add(entry);
}
}
public DragListEntry GetAtIndex(int index)
{
return _entries[index];
}
public void Remove(string name)
{
Remove(_entries.Where(x => x.Name == name).Single());
}
public void Clear()
{
_entries.Clear();
}
public void UpdateIndices()
{
for (int i = 0; i < _entries.Count; i++)
{
_entries[i].Index = i;
}
}
void ClickSelect(DragListEntry newEntry)
{
if (newEntry.IsSelected)
{
if (Event.current.control)
{
newEntry.IsSelected = false;
}
return;
}
if (!Event.current.control && !Event.current.shift)
{
_manager.ClearSelected();
}
// The selection entry list should all be from the same list
_manager.ClearOtherListSelected(_listType);
var selected = GetSelected();
if (Event.current.shift && !selected.IsEmpty())
{
var closestEntry = selected
.Select(x => new { Distance = Mathf.Abs(x.Index - newEntry.Index), Entry = x })
.OrderBy(x => x.Distance)
.Select(x => x.Entry).First();
int startIndex;
int endIndex;
if (closestEntry.Index > newEntry.Index)
{
startIndex = newEntry.Index + 1;
endIndex = closestEntry.Index - 1;
}
else
{
startIndex = closestEntry.Index + 1;
endIndex = newEntry.Index - 1;
}
for (int i = startIndex; i <= endIndex; i++)
{
var inBetweenEntry = closestEntry.ListOwner.GetAtIndex(i);
inBetweenEntry.IsSelected = true;
}
}
newEntry.IsSelected = true;
}
public List<DragListEntry> GetSelected()
{
return _entries.Where(x => x.IsSelected).ToList();
}
void DrawSearchPane(Rect rect)
{
Assert.That(ShowSortPane);
var startX = rect.xMin;
var endX = rect.xMax;
var startY = rect.yMin;
var endY = rect.yMax;
var skin = _pmSettings.ReleasesPane;
ImguiUtil.DrawColoredQuad(rect, skin.IconRowBackgroundColor);
endX = rect.xMax - 2 * skin.ButtonWidth;
var searchBarRect = Rect.MinMaxRect(startX, startY, endX, endY);
if (GUI.enabled && searchBarRect.Contains(Event.current.mousePosition))
{
ImguiUtil.DrawColoredQuad(searchBarRect, skin.MouseOverBackgroundColor);
}
GUI.Label(new Rect(startX + skin.SearchIconOffset.x, startY + skin.SearchIconOffset.y, skin.SearchIconSize.x, skin.SearchIconSize.y), skin.SearchIcon);
this.SearchFilter = GUI.TextField(
searchBarRect, this.SearchFilter, skin.SearchTextStyle);
startX = endX;
endX = startX + skin.ButtonWidth;
Rect buttonRect;
buttonRect = Rect.MinMaxRect(startX, startY, endX, endY);
if (buttonRect.Contains(Event.current.mousePosition))
{
ImguiUtil.DrawColoredQuad(buttonRect, skin.MouseOverBackgroundColor);
if (Event.current.type == EventType.MouseDown)
{
SortDescending = !SortDescending;
this.UpdateIndices();
}
}
GUI.DrawTexture(buttonRect, SortDescending ? skin.SortDirUpIcon : skin.SortDirDownIcon);
startX = endX;
endX = startX + skin.ButtonWidth;
buttonRect = Rect.MinMaxRect(startX, startY, endX, endY);
if (buttonRect.Contains(Event.current.mousePosition))
{
ImguiUtil.DrawColoredQuad(buttonRect, skin.MouseOverBackgroundColor);
if (Event.current.type == EventType.MouseDown && !_sortMethodCaptions.IsEmpty())
{
var startPos = new Vector2(buttonRect.xMin, buttonRect.yMax);
ImguiUtil.OpenContextMenu(startPos, CreateSortMethodContextMenuItems());
}
}
GUI.DrawTexture(buttonRect, skin.SortIcon);
}
List<ContextMenuItem> CreateSortMethodContextMenuItems()
{
var result = new List<ContextMenuItem>();
for (int i = 0; i < _sortMethodCaptions.Count; i++)
{
var closedI = i;
result.Add(new ContextMenuItem(
true, _sortMethodCaptions[i], _model.SortMethod == i, () => SortMethod = closedI));
}
return result;
}
public void Draw(Rect fullRect)
{
Rect listRect;
if (ShowSortPane)
{
var releaseSkin = _pmSettings.ReleasesPane;
var searchRect = new Rect(fullRect.xMin, fullRect.yMin, fullRect.width, releaseSkin.IconRowHeight);
DrawSearchPane(searchRect);
listRect = Rect.MinMaxRect(
fullRect.xMin, fullRect.yMin + releaseSkin.IconRowHeight, fullRect.xMax, fullRect.yMax);
}
else
{
listRect = fullRect;
}
var searchFilter = _model.SearchFilter.Trim().ToLowerInvariant();
var visibleEntries = _entries.Where(x => x.Name.ToLowerInvariant().Contains(searchFilter)).ToList();
var viewRect = new Rect(0, 0, listRect.width - 30.0f, visibleEntries.Count * _settings.ItemHeight);
var isListUnderMouse = listRect.Contains(Event.current.mousePosition);
ImguiUtil.DrawColoredQuad(listRect, GetListBackgroundColor(isListUnderMouse));
switch (Event.current.type)
{
case EventType.MouseUp:
{
// Clear our drag info in DragAndDrop so that we know that we are not dragging
DragAndDrop.PrepareStartDrag();
break;
}
case EventType.DragPerform:
// Drag has completed
{
if (isListUnderMouse)
{
DragAndDrop.AcceptDrag();
var receivedDragData = DragAndDrop.GetGenericData(DragId) as DragData;
if (receivedDragData != null)
{
DragAndDrop.PrepareStartDrag();
_manager.OnDragDrop(receivedDragData, this);
}
}
break;
}
case EventType.MouseDrag:
{
if (isListUnderMouse)
{
var existingDragData = DragAndDrop.GetGenericData(DragId) as DragData;
if (existingDragData != null)
{
DragAndDrop.StartDrag("Dragging List Element");
Event.current.Use();
}
}
break;
}
case EventType.DragUpdated:
{
if (isListUnderMouse)
{
var existingDragData = DragAndDrop.GetGenericData(DragId) as DragData;
if (existingDragData != null && (_manager != null && _manager.IsDragAllowed(existingDragData, this)))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
Event.current.Use();
}
else
{
DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
}
}
break;
}
case EventType.ContextClick:
{
if (isListUnderMouse)
{
_manager.OpenContextMenu(this);
Event.current.Use();
}
break;
}
}
bool clickedItem = false;
float yPos = 0;
_model.ScrollPos = GUI.BeginScrollView(listRect, _model.ScrollPos, viewRect);
{
foreach (var entry in visibleEntries)
{
var labelRect = new Rect(0, yPos, listRect.width, _settings.ItemHeight);
bool isItemUnderMouse = labelRect.Contains(Event.current.mousePosition);
Color itemColor;
if (entry.IsSelected)
{
itemColor = _settings.Theme.ListItemSelectedColor;
}
else
{
itemColor = GUI.enabled && isItemUnderMouse ? _settings.Theme.ListItemHoverColor : _settings.Theme.ListItemColor;
}
ImguiUtil.DrawColoredQuad(labelRect, itemColor);
switch (Event.current.type)
{
case EventType.MouseUp:
{
if (isItemUnderMouse && Event.current.button == 0)
{
if (!Event.current.shift && !Event.current.control)
{
_manager.ClearSelected();
ClickSelect(entry);
}
}
break;
}
case EventType.MouseDown:
{
if (isItemUnderMouse)
{
// Unfocus on text field
GUI.FocusControl(null);
clickedItem = true;
ClickSelect(entry);
if (Event.current.button == 0)
{
DragAndDrop.PrepareStartDrag();
var dragData = new DragData()
{
Entries = GetSelected(),
SourceList = this,
};
DragAndDrop.SetGenericData(DragId, dragData);
DragAndDrop.objectReferences = new UnityEngine.Object[0];
}
Event.current.Use();
}
break;
}
}
GUI.Label(labelRect, entry.Name, _settings.ItemTextStyle);
yPos += _settings.ItemHeight;
}
}
GUI.EndScrollView();
if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && !clickedItem && isListUnderMouse)
{
// Unfocus on text field
GUI.FocusControl(null);
_manager.ClearSelected();
}
}
Color GetListBackgroundColor(bool isHover)
{
if (!GUI.enabled)
{
return _settings.Theme.ListColor;
}
if (_model.SearchFilter.Trim().Count() > 0)
{
return isHover ? _settings.Theme.FilteredListHoverColor : _settings.Theme.FilteredListColor;
}
return isHover ? _settings.Theme.ListHoverColor : _settings.Theme.ListColor;
}
public class DragData
{
public List<DragListEntry> Entries;
public DragList SourceList;
}
// View data that needs to be saved and restored
[Serializable]
public class Model
{
public Vector2 ScrollPos;
public string SearchFilter = "";
public int SortMethod;
public bool SortDescending;
}
public class ItemDescriptor
{
public string Caption;
public object Model;
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: RtfControlWord.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Rtf control words enumeration.
//
//---------------------------------------------------------------------------
namespace System.Windows.Documents
{
/// <summary>
/// Rtf control words that enumerate all Rtf control word.
/// </summary>
internal enum RtfControlWord
{
Ctrl_Unknown = -1,
Ctrl_AB = 0,
Ctrl_ABSH,
Ctrl_ABSLOCK,
Ctrl_ABSNOOVRLP,
Ctrl_ABSW,
Ctrl_ACAPS,
Ctrl_ACCCOMMA,
Ctrl_ACCDOT,
Ctrl_ACCNONE,
Ctrl_ACF,
Ctrl_ADDITIVE,
Ctrl_ADJUSTRIGHT,
Ctrl_ADN,
Ctrl_AENDDOC,
Ctrl_AENDNOTES,
Ctrl_AEXPND,
Ctrl_AF,
Ctrl_AFFIXED,
Ctrl_AFS,
Ctrl_AFTNBJ,
Ctrl_AFTNCN,
Ctrl_AFTNNALC,
Ctrl_AFTNNAR,
Ctrl_AFTNNAUC,
Ctrl_AFTNNCHI,
Ctrl_AFTNNCHOSUNG,
Ctrl_AFTNNCNUM,
Ctrl_AFTNNDBAR,
Ctrl_AFTNNDBNUM,
Ctrl_AFTNNDBNUMD,
Ctrl_AFTNNDBNUMK,
Ctrl_AFTNNDBNUMT,
Ctrl_AFTNNGANADA,
Ctrl_AFTNNGBNUM,
Ctrl_AFTNNGBNUMD,
Ctrl_AFTNNGBNUMK,
Ctrl_AFTNNGBNUML,
Ctrl_AFTNNRLC,
Ctrl_AFTNNRUC,
Ctrl_AFTNNZODIAC,
Ctrl_AFTNNZODIACD,
Ctrl_AFTNNZODIACL,
Ctrl_AFTNRESTART,
Ctrl_AFTNRSTCONT,
Ctrl_AFTNSEP,
Ctrl_AFTNSEPC,
Ctrl_AFTNSTART,
Ctrl_AFTNTJ,
Ctrl_AI,
Ctrl_ALANG,
Ctrl_ALLPROT,
Ctrl_ALNTBLIND,
Ctrl_ALT,
Ctrl_ANIMTEXT,
Ctrl_ANNOTATION,
Ctrl_ANNOTPROT,
Ctrl_ANSI,
Ctrl_ANSICPG,
Ctrl_AOUTL,
Ctrl_ASCAPS,
Ctrl_ASHAD,
Ctrl_ASPALPHA,
Ctrl_ASPNUM,
Ctrl_ASTRIKE,
Ctrl_ATNAUTHOR,
Ctrl_ATNICN,
Ctrl_ATNID,
Ctrl_ATNREF,
Ctrl_ATNTIME,
Ctrl_ATRFEND,
Ctrl_ATRFSTART,
Ctrl_AUL,
Ctrl_AULD,
Ctrl_AULDB,
Ctrl_AULNONE,
Ctrl_AULW,
Ctrl_AUP,
Ctrl_AUTHOR,
Ctrl_B,
Ctrl_BACKGROUND,
Ctrl_BDBFHDR,
Ctrl_BDRRLSWSIX,
Ctrl_BGBDIAG,
Ctrl_BGCROSS,
Ctrl_BGDCROSS,
Ctrl_BGDKBDIAG,
Ctrl_BGDKCROSS,
Ctrl_BGDKDCROSS,
Ctrl_BGDKFDIAG,
Ctrl_BGDKHORIZ,
Ctrl_BGDKVERT,
Ctrl_BGFDIAG,
Ctrl_BGHORIZ,
Ctrl_BGVERT,
Ctrl_BIN,
Ctrl_BINFSXN,
Ctrl_BINSXN,
Ctrl_BKMKCOLF,
Ctrl_BKMKCOLL,
Ctrl_BKMKEND,
Ctrl_BKMKPUB,
Ctrl_BKMKSTART,
Ctrl_BLIPTAG,
Ctrl_BLIPUID,
Ctrl_BLIPUPI,
Ctrl_BLUE,
Ctrl_BOX,
Ctrl_BRDRART,
Ctrl_BRDRB,
Ctrl_BRDRBAR,
Ctrl_BRDRBTW,
Ctrl_BRDRCF,
Ctrl_BRDRDASH,
Ctrl_BRDRDASHD,
Ctrl_BRDRDASHDD,
Ctrl_BRDRDASHDOTSTR,
Ctrl_BRDRDASHSM,
Ctrl_BRDRDB,
Ctrl_BRDRDOT,
Ctrl_BRDREMBOSS,
Ctrl_BRDRENGRAVE,
Ctrl_BRDRFRAME,
Ctrl_BRDRHAIR,
Ctrl_BRDRINSET,
Ctrl_BRDRL,
Ctrl_BRDROUTSET,
Ctrl_BRDRNIL, // BORDER: no border specified
Ctrl_BRDRNONE, // BORDER: no border
Ctrl_BRDRTBL, // BORDER: no borders on table cells
Ctrl_BRDRR,
Ctrl_BRDRS, // BORDER: single thickness border
Ctrl_BRDRSH,
Ctrl_BRDRT,
Ctrl_BRDRTH,
Ctrl_BRDRTHTNLG,
Ctrl_BRDRTHTNMG,
Ctrl_BRDRTHTNSG,
Ctrl_BRDRTNTHLG,
Ctrl_BRDRTNTHMG,
Ctrl_BRDRTNTHSG,
Ctrl_BRDRTNTHTNLG,
Ctrl_BRDRTNTHTNMG,
Ctrl_BRDRTNTHTNSG,
Ctrl_BRDRTRIPLE,
Ctrl_BRDRW, // BORDER: width in twips of border line
Ctrl_BRDRWAVY, // BORDER: wavy border
Ctrl_BRDRWAVYDB, // BORDER: double wavy border
Ctrl_BRKFRM,
Ctrl_BRSP,
Ctrl_BULLET,
Ctrl_BUPTIM,
Ctrl_BXE,
Ctrl_CAPS,
Ctrl_CATEGORY,
Ctrl_CB,
Ctrl_CBPAT,
Ctrl_CCHS,
Ctrl_CELL,
Ctrl_CELLX, // TABLE: CELL: defines right boundary of cell, including half spacing (twips)
Ctrl_CF,
Ctrl_CFPAT,
Ctrl_CGRID,
Ctrl_CHARSCALEX,
Ctrl_CHATN,
Ctrl_CHBGBDIAG,
Ctrl_CHBGCROSS,
Ctrl_CHBGDCROSS,
Ctrl_CHBGDKBDIAG,
Ctrl_CHBGDKCROSS,
Ctrl_CHBGDKDCROSS,
Ctrl_CHBGDKFDIAG,
Ctrl_CHBGDKHORIZ,
Ctrl_CHBGDKVERT,
Ctrl_CHBGFDIAG,
Ctrl_CHBGHORIZ,
Ctrl_CHBGVERT,
Ctrl_CHBRDR,
Ctrl_CHCBPAT,
Ctrl_CHCFPAT,
Ctrl_CHDATE,
Ctrl_CHDPA,
Ctrl_CHDPL,
Ctrl_CHFTN,
Ctrl_CHFTNSEP,
Ctrl_CHFTNSEPC,
Ctrl_CHPGN,
Ctrl_CHSHDNG,
Ctrl_CHTIME,
Ctrl_CLBGBDIAG,
Ctrl_CLBGCROSS,
Ctrl_CLBGDCROSS,
Ctrl_CLBGDKBDIAG,
Ctrl_CLBGDKCROSS,
Ctrl_CLBGDKDCROSS,
Ctrl_CLBGDKFDIAG,
Ctrl_CLBGDKHOR,
Ctrl_CLBGDKVERT,
Ctrl_CLBGFDIAG,
Ctrl_CLBGHORIZ,
Ctrl_CLBGVERT,
Ctrl_CLBRDRB, // TABLE: CELL: table cell border bottom.
Ctrl_CLBRDRL, // TABLE: CELL: table cell border left.
Ctrl_CLBRDRR, // TABLE: CELL: table cell border right.
Ctrl_CLBRDRT, // TABLE: CELL: table cell border top.
Ctrl_CLCBPAT,
Ctrl_CLCFPAT,
Ctrl_CLDGLL,
Ctrl_CLDGLU,
Ctrl_CLFITTEXT,
Ctrl_CLFTSWIDTH,
Ctrl_CLMGF,
Ctrl_CLMRG,
Ctrl_CLOWRAP,
Ctrl_CLPADB,
Ctrl_CLPADFB,
Ctrl_CLPADFL,
Ctrl_CLPADFR,
Ctrl_CLPADFT,
Ctrl_CLPADL,
Ctrl_CLPADR,
Ctrl_CLPADT,
Ctrl_CLSHDNG,
Ctrl_CLSHDRAWNIL, // TABLE: no shading
Ctrl_CLTXBTLR,
Ctrl_CLTXLRTB, // TABLE: CELL: text flows left-right-top-bottom
Ctrl_CLTXLRTBV,
Ctrl_CLTXTBRL,
Ctrl_CLTXTBRLV,
Ctrl_CLVERTALB, // TABLE: CELL: cell contents vertically aligned bottom.
Ctrl_CLVERTALC, // TABLE: CELL: cell contents vertically aligned center.
Ctrl_CLVERTALT, // TABLE: CELL: cell contents vertically aligned top.
Ctrl_CLVMGF,
Ctrl_CLVMRG,
Ctrl_CLWWIDTH,
Ctrl_COLLAPSED,
Ctrl_COLNO,
Ctrl_COLORTBL,
Ctrl_COLS,
Ctrl_COLSR,
Ctrl_COLSX,
Ctrl_COLUMN,
Ctrl_COLW,
Ctrl_COMMENT,
Ctrl_COMPANY,
Ctrl_CPG,
Ctrl_CRAUTH,
Ctrl_CRDATE,
Ctrl_CREATIM,
Ctrl_CS,
Ctrl_CTRL,
Ctrl_CTS,
Ctrl_CUFI,
Ctrl_CULI,
Ctrl_CURI,
Ctrl_CVMME,
Ctrl_DATAFIELD,
Ctrl_DATE,
Ctrl_DBCH,
Ctrl_DEFF,
Ctrl_DEFFORMAT,
Ctrl_DEFLANG,
Ctrl_DEFLANGA,
Ctrl_DEFLANGFE,
Ctrl_DEFSHP,
Ctrl_DEFTAB,
Ctrl_DELETED,
Ctrl_DFRAUTH,
Ctrl_DFRDATE,
Ctrl_DFRMTXTX,
Ctrl_DFRMTXTY,
Ctrl_DFRSTART,
Ctrl_DFRSTOP,
Ctrl_DFRXST,
Ctrl_DGHORIGIN,
Ctrl_DGHSHOW,
Ctrl_DGHSPACE,
Ctrl_DGMARGIN,
Ctrl_DGSNAP,
Ctrl_DGVORIGIN,
Ctrl_DGVSHOW,
Ctrl_DGVSPACE,
Ctrl_DIBITMAP,
Ctrl_DN,
Ctrl_DNTBLNSBDB,
Ctrl_DO,
Ctrl_DOBXCOLUMN,
Ctrl_DOBXMARGIN,
Ctrl_DOBXPAGE,
Ctrl_DOBYMARGIN,
Ctrl_DOBYPAGE,
Ctrl_DOBYPARA,
Ctrl_DOCCOMM,
Ctrl_DOCTEMP,
Ctrl_DOCTYPE,
Ctrl_DOCVAR,
Ctrl_DODHGT,
Ctrl_DOLOCK,
Ctrl_DPAENDHOL,
Ctrl_DPAENDL,
Ctrl_DPAENDSOL,
Ctrl_DPAENDW,
Ctrl_DPARC,
Ctrl_DPARCFLIPX,
Ctrl_DPARCFLIPY,
Ctrl_DPASTARTHOL,
Ctrl_DPASTARTL,
Ctrl_DPASTARTSOL,
Ctrl_DPASTARTW,
Ctrl_DPCALLOUT,
Ctrl_DPCOA,
Ctrl_DPCOACCENT,
Ctrl_DPCOBESTFIT,
Ctrl_DPCOBORDER,
Ctrl_DPCODABS,
Ctrl_DPCODBOTTOM,
Ctrl_DPCODCENTER,
Ctrl_DPCODESCENT,
Ctrl_DPCODTOP,
Ctrl_DPCOLENGTH,
Ctrl_DPCOMINUSX,
Ctrl_DPCOMINUSY,
Ctrl_DPCOOFFSET,
Ctrl_DPCOSMARTA,
Ctrl_DPCOTDOUBLE,
Ctrl_DPCOTRIGHT,
Ctrl_DPCOTSINGLE,
Ctrl_DPCOTTRIPLE,
Ctrl_DPCOUNT,
Ctrl_DPELLIPSE,
Ctrl_DPENDGROUP,
Ctrl_DPFILLBGCB,
Ctrl_DPFILLBGCG,
Ctrl_DPFILLBGCR,
Ctrl_DPFILLBGGRAY,
Ctrl_DPFILLBGPAL,
Ctrl_DPFILLFGCB,
Ctrl_DPFILLFGCG,
Ctrl_DPFILLFGCR,
Ctrl_DPFILLFGGRAY,
Ctrl_DPFILLFGPAL,
Ctrl_DPFILLPAT,
Ctrl_DPGROUP,
Ctrl_DPLINE,
Ctrl_DPLINECOB,
Ctrl_DPLINECOG,
Ctrl_DPLINECOR,
Ctrl_DPLINEDADO,
Ctrl_DPLINEDADODO,
Ctrl_DPLINEDASH,
Ctrl_DPLINEDOT,
Ctrl_DPLINEGRAY,
Ctrl_DPLINEHOLLOW,
Ctrl_DPLINEPAL,
Ctrl_DPLINESOLID,
Ctrl_DPLINEW,
Ctrl_DPPOLYCOUNT,
Ctrl_DPPOLYGON,
Ctrl_DPPOLYLINE,
Ctrl_DPPTX,
Ctrl_DPPTY,
Ctrl_DPRECT,
Ctrl_DPROUNDR,
Ctrl_DPSHADOW,
Ctrl_DPSHADX,
Ctrl_DPSHADY,
Ctrl_DPTXBTLR,
Ctrl_DPTXBX,
Ctrl_DPTXBXMAR,
Ctrl_DPTXBXTEXT,
Ctrl_DPTXLRTB,
Ctrl_DPTXLRTBV,
Ctrl_DPTXTBRL,
Ctrl_DPTXTBRLV,
Ctrl_DPX,
Ctrl_DPXSIZE,
Ctrl_DPY,
Ctrl_DPYSIZE,
Ctrl_DROPCAPLI,
Ctrl_DROPCAPT,
Ctrl_DS,
Ctrl_DXFRTEXT,
Ctrl_DY,
Ctrl_EDMINS,
Ctrl_EMBO,
Ctrl_EMDASH,
Ctrl_EMFBLIP,
Ctrl_EMSPACE,
Ctrl_ENDASH,
Ctrl_ENDDOC,
Ctrl_ENDNHERE,
Ctrl_ENDNOTES,
Ctrl_ENSPACE,
Ctrl_EXPND,
Ctrl_EXPNDTW,
Ctrl_EXPSHRTN,
Ctrl_F,
Ctrl_FAAUTO,
Ctrl_FACENTER,
Ctrl_FACINGP,
Ctrl_FAHANG,
Ctrl_FALT,
Ctrl_FAROMAN,
Ctrl_FAVAR,
Ctrl_FBIAS,
Ctrl_FBIDI,
Ctrl_FCHARS,
Ctrl_FCHARSET,
Ctrl_FDECOR,
Ctrl_FET,
Ctrl_FETCH,
Ctrl_FFDEFRES,
Ctrl_FFDEFTEXT,
Ctrl_FFENTRYMCR,
Ctrl_FFEXITMCR,
Ctrl_FFFORMAT,
Ctrl_FFHASLISTBOX,
Ctrl_FFHELPTEXT,
Ctrl_FFHPS,
Ctrl_FFL,
Ctrl_FFMAXLEN,
Ctrl_FFNAME,
Ctrl_FFOWNHELP,
Ctrl_FFOWNSTAT,
Ctrl_FFPROT,
Ctrl_FFRECALC,
Ctrl_FFRES,
Ctrl_FFSIZE,
Ctrl_FFSTATTEXT,
Ctrl_FFTYPE,
Ctrl_FFTYPETXT,
Ctrl_FI,
Ctrl_FID,
Ctrl_FIELD,
Ctrl_FILE,
Ctrl_FILETBL,
Ctrl_FITTEXT,
Ctrl_FLDALT,
Ctrl_FLDDIRTY,
Ctrl_FLDEDIT,
Ctrl_FLDINST,
Ctrl_FLDLOCK,
Ctrl_FLDPRIV,
Ctrl_FLDRSLT,
Ctrl_FLDTYPE,
Ctrl_FMODERN,
Ctrl_FN,
Ctrl_FNAME,
Ctrl_FNETWORK,
Ctrl_FNIL,
Ctrl_FONTEMB,
Ctrl_FONTFILE,
Ctrl_FONTTBL,
Ctrl_FOOTER,
Ctrl_FOOTERF,
Ctrl_FOOTERL,
Ctrl_FOOTERR,
Ctrl_FOOTERY,
Ctrl_FOOTNOTE,
Ctrl_FORMDISP,
Ctrl_FORMFIELD,
Ctrl_FORMPROT,
Ctrl_FORMSHADE,
Ctrl_FOSNUM,
Ctrl_FPRQ,
Ctrl_FRACWIDTH,
Ctrl_FRELATIVE,
Ctrl_FRMTXBTLR,
Ctrl_FRMTXLRTB,
Ctrl_FRMTXLRTBV,
Ctrl_FRMTXTBRL,
Ctrl_FRMTXTBRLV,
Ctrl_FROMAN,
Ctrl_FROMHTML,
Ctrl_FROMTEXT,
Ctrl_FS,
Ctrl_FSCRIPT,
Ctrl_FSWISS,
Ctrl_FTNALT,
Ctrl_FTNBJ,
Ctrl_FTNCN,
Ctrl_FTNIL,
Ctrl_FTNLYTWNINE,
Ctrl_FTNNALC,
Ctrl_FTNNAR,
Ctrl_FTNNAUC,
Ctrl_FTNNCHI,
Ctrl_FTNNCHOSUNG,
Ctrl_FTNNCNUM,
Ctrl_FTNNDBAR,
Ctrl_FTNNDBNUM,
Ctrl_FTNNDBNUMD,
Ctrl_FTNNDBNUMK,
Ctrl_FTNNDBNUMT,
Ctrl_FTNNGANADA,
Ctrl_FTNNGBNUM,
Ctrl_FTNNGBNUMD,
Ctrl_FTNNGBNUMK,
Ctrl_FTNNGBNUML,
Ctrl_FTNNRLC,
Ctrl_FTNNRUC,
Ctrl_FTNNZODIAC,
Ctrl_FTNNZODIACD,
Ctrl_FTNNZODIACL,
Ctrl_FTNRESTART,
Ctrl_FTNRSTCONT,
Ctrl_FTNRSTPG,
Ctrl_FTNSEP,
Ctrl_FTNSEPC,
Ctrl_FTNSTART,
Ctrl_FTNTJ,
Ctrl_FTTRUETYPE,
Ctrl_FVALIDDOS,
Ctrl_FVALIDHPFS,
Ctrl_FVALIDMAC,
Ctrl_FVALIDNTFS,
Ctrl_G,
Ctrl_GCW,
Ctrl_GREEN,
Ctrl_GRIDTBL,
Ctrl_GUTTER,
Ctrl_GUTTERPRL,
Ctrl_GUTTERSXN,
Ctrl_HEADER,
Ctrl_HEADERF,
Ctrl_HEADERL,
Ctrl_HEADERR,
Ctrl_HEADERY,
Ctrl_HICH,
Ctrl_HIGHLIGHT,
Ctrl_HLFR,
Ctrl_HLINKBASE,
Ctrl_HLLOC,
Ctrl_HLSRC,
Ctrl_HORZDOC,
Ctrl_HORZSECT,
Ctrl_HR,
Ctrl_HTMAUTSP,
Ctrl_HTMLBASE,
Ctrl_HTMLRTF,
Ctrl_HTMLTAG,
Ctrl_HYPHAUTO,
Ctrl_HYPHCAPS,
Ctrl_HYPHCONSEC,
Ctrl_HYPHHOTZ,
Ctrl_HYPHPAR,
Ctrl_I,
Ctrl_ID,
Ctrl_ILVL,
Ctrl_IMPR,
Ctrl_INFO,
Ctrl_INTBL,
Ctrl_ITAP,
Ctrl_IXE,
Ctrl_JCOMPRESS,
Ctrl_JEXPAND,
Ctrl_JPEGBLIP,
Ctrl_JSKSU,
Ctrl_KEEP,
Ctrl_KEEPN,
Ctrl_KERNING,
Ctrl_KEYCODE,
Ctrl_KEYWORDS,
Ctrl_KSULANG,
Ctrl_LANDSCAPE,
Ctrl_LANG,
Ctrl_LANGFE,
Ctrl_LANGFENP,
Ctrl_LANGNP,
Ctrl_LBR,
Ctrl_LCHARS,
Ctrl_LDBLQUOTE,
Ctrl_LEVEL,
Ctrl_LEVELFOLLOW,
Ctrl_LEVELINDENT,
Ctrl_LEVELJC,
Ctrl_LEVELJCN,
Ctrl_LEVELLEGAL,
Ctrl_LEVELNFC,
Ctrl_LEVELNFCN,
Ctrl_LEVELNORESTART,
Ctrl_LEVELNUMBERS,
Ctrl_LEVELOLD,
Ctrl_LEVELPREV,
Ctrl_LEVELPREVSPACE,
Ctrl_LEVELSPACE,
Ctrl_LEVELSTARTAT,
Ctrl_LEVELTEMPLATEID,
Ctrl_LEVELTEXT,
Ctrl_LFOLEVEL,
Ctrl_LI,
Ctrl_LINE,
Ctrl_LINEBETCOL,
Ctrl_LINECONT,
Ctrl_LINEMOD,
Ctrl_LINEPPAGE,
Ctrl_LINERESTART,
Ctrl_LINESTART,
Ctrl_LINESTARTS,
Ctrl_LINEX,
Ctrl_LINKSELF,
Ctrl_LINKSTYLES,
Ctrl_LINKVAL,
Ctrl_LIN,
Ctrl_LISA,
Ctrl_LISB,
Ctrl_LIST,
Ctrl_LISTHYBRID,
Ctrl_LISTID,
Ctrl_LISTLEVEL,
Ctrl_LISTNAME,
Ctrl_LISTOVERRIDE,
Ctrl_LISTOVERRIDECOUNT,
Ctrl_LISTOVERRIDEFORMAT,
Ctrl_LISTOVERRIDESTART,
Ctrl_LISTPICTURE,
Ctrl_LISTRESTARTHDN,
Ctrl_LISTSIMPLE,
Ctrl_LISTTABLE,
Ctrl_LISTOVERRIDETABLE,
Ctrl_LISTTEMPLATEID,
Ctrl_LISTTEXT,
Ctrl_LNBRKRULE,
Ctrl_LNDSCPSXN,
Ctrl_LNONGRID,
Ctrl_LOCH,
Ctrl_LQUOTE,
Ctrl_LS,
Ctrl_LTRCH,
Ctrl_LTRDOC,
Ctrl_LTRMARK,
Ctrl_LTRPAR,
Ctrl_LTRROW,
Ctrl_LTRSECT,
Ctrl_LYTCALCTBLWD,
Ctrl_LYTEXCTTP,
Ctrl_LYTPRTMET,
Ctrl_LYTTBLRTGR,
Ctrl_MAC,
Ctrl_MACPICT,
Ctrl_MAKEBACKUP,
Ctrl_MANAGER,
Ctrl_MARGB,
Ctrl_MARGBSXN,
Ctrl_MARGL,
Ctrl_MARGLSXN,
Ctrl_MARGMIRROR,
Ctrl_MARGR,
Ctrl_MARGRSXN,
Ctrl_MARGT,
Ctrl_MARGTSXN,
Ctrl_MHTMLTAG,
Ctrl_MIN,
Ctrl_MO,
Ctrl_MSMCAP,
Ctrl_NESTCELL,
Ctrl_NESTROW,
Ctrl_NESTTABLEPROPS,
Ctrl_NEXTFILE,
Ctrl_NOCOLBAL,
Ctrl_NOCWRAP,
Ctrl_NOEXTRASPRL,
Ctrl_NOFCHARS,
Ctrl_NOFCHARSWS,
Ctrl_NOFPAGES,
Ctrl_NOFWORDS,
Ctrl_NOLEAD,
Ctrl_NOLINE,
Ctrl_NOLNHTADJTBL,
Ctrl_NONESTTABLES,
Ctrl_NONSHPPICT,
Ctrl_NOOVERFLOW,
Ctrl_NOPROOF,
Ctrl_NOSECTEXPAND,
Ctrl_NOSNAPLINEGRID,
Ctrl_NOSPACEFORUL,
Ctrl_NOSUPERSUB,
Ctrl_NOTABIND,
Ctrl_NOULTRLSPC,
Ctrl_NOWIDCTLPAR,
Ctrl_NOWRAP,
Ctrl_NOWWRAP,
Ctrl_NOXLATTOYEN,
Ctrl_OBJALIAS,
Ctrl_OBJALIGN,
Ctrl_OBJATTPH,
Ctrl_OBJAUTLINK,
Ctrl_OBJCLASS,
Ctrl_OBJCROPB,
Ctrl_OBJCROPL,
Ctrl_OBJCROPR,
Ctrl_OBJCROPT,
Ctrl_OBJDATA,
Ctrl_OBJECT,
Ctrl_OBJEMB,
Ctrl_OBJH,
Ctrl_OBJHTML,
Ctrl_OBJICEMB,
Ctrl_OBJLINK,
Ctrl_OBJLOCK,
Ctrl_OBJNAME,
Ctrl_OBJOCX,
Ctrl_OBJPUB,
Ctrl_OBJSCALEX,
Ctrl_OBJSCALEY,
Ctrl_OBJSECT,
Ctrl_OBJSETSIZE,
Ctrl_OBJSUB,
Ctrl_OBJTIME,
Ctrl_OBJTRANSY,
Ctrl_OBJUPDATE,
Ctrl_OBJW,
Ctrl_OLDAS,
Ctrl_OLDLINEWRAP,
Ctrl_OPERATOR,
Ctrl_OTBLRUL,
Ctrl_OUTL,
Ctrl_OUTLINELEVEL,
Ctrl_OVERLAY,
Ctrl_PAGE,
Ctrl_PAGEBB,
Ctrl_PANOSE,
Ctrl_PAPERH,
Ctrl_PAPERW,
Ctrl_PAR,
Ctrl_PARD,
Ctrl_PC,
Ctrl_PCA,
Ctrl_PGBRDRB,
Ctrl_PGBRDRFOOT,
Ctrl_PGBRDRHEAD,
Ctrl_PGBRDRL,
Ctrl_PGBRDROPT,
Ctrl_PGBRDRR,
Ctrl_PGBRDRSNAP,
Ctrl_PGBRDRT,
Ctrl_PGHSXN,
Ctrl_PGNBIDIA,
Ctrl_PGNBIDIB,
Ctrl_PGNCHOSUNG,
Ctrl_PGNCNUM,
Ctrl_PGNCONT,
Ctrl_PGNDBNUM,
Ctrl_PGNDBNUMD,
Ctrl_PGNDBNUMK,
Ctrl_PGNDBNUMT,
Ctrl_PGNDEC,
Ctrl_PGNDECD,
Ctrl_PGNGANADA,
Ctrl_PGNGBNUM,
Ctrl_PGNGBNUMD,
Ctrl_PGNGBNUMK,
Ctrl_PGNGBNUML,
Ctrl_PGNHN,
Ctrl_PGNHNSC,
Ctrl_PGNHNSH,
Ctrl_PGNHNSM,
Ctrl_PGNHNSN,
Ctrl_PGNHNSP,
Ctrl_PGNLCLTR,
Ctrl_PGNLCRM,
Ctrl_PGNRESTART,
Ctrl_PGNSTART,
Ctrl_PGNSTARTS,
Ctrl_PGNUCLTR,
Ctrl_PGNUCRM,
Ctrl_PGNX,
Ctrl_PGNY,
Ctrl_PGNZODIAC,
Ctrl_PGNZODIACD,
Ctrl_PGNZODIACL,
Ctrl_PGWSXN,
Ctrl_PHCOL,
Ctrl_PHMRG,
Ctrl_PHPG,
Ctrl_PICBMP,
Ctrl_PICBPP,
Ctrl_PICCROPB,
Ctrl_PICCROPL,
Ctrl_PICCROPR,
Ctrl_PICCROPT,
Ctrl_PICH,
Ctrl_PICHGOAL,
Ctrl_PICPROP,
Ctrl_PICSCALED,
Ctrl_PICSCALEX,
Ctrl_PICSCALEY,
Ctrl_PICT,
Ctrl_PICW,
Ctrl_PICWGOAL,
Ctrl_PLAIN,
Ctrl_PMMETAFILE,
Ctrl_PN,
Ctrl_PNACROSS,
Ctrl_PNAIU,
Ctrl_PNAIUD,
Ctrl_PNAIUEO,
Ctrl_PNAIUEOD,
Ctrl_PNB,
Ctrl_PNBIDIA,
Ctrl_PNBIDIB,
Ctrl_PNCAPS,
Ctrl_PNCARD,
Ctrl_PNCF,
Ctrl_PNCHOSUNG,
Ctrl_PNCNUM,
Ctrl_PNDBNUM,
Ctrl_PNDBNUMD,
Ctrl_PNDBNUMK,
Ctrl_PNDBNUML,
Ctrl_PNDBNUMT,
Ctrl_PNDEC,
Ctrl_PNDECD,
Ctrl_PNF,
Ctrl_PNFS,
Ctrl_PNGANADA,
Ctrl_PNGBLIP,
Ctrl_PNGBNUM,
Ctrl_PNGBNUMD,
Ctrl_PNGBNUMK,
Ctrl_PNGBNUML,
Ctrl_PNHANG,
Ctrl_PNI,
Ctrl_PNINDENT,
Ctrl_PNIROHA,
Ctrl_PNIROHAD,
Ctrl_PNLCLTR,
Ctrl_PNLCRM,
Ctrl_PNLVL,
Ctrl_PNLVLBLT,
Ctrl_PNLVLBODY,
Ctrl_PNLVLCONT,
Ctrl_PNNUMONCE,
Ctrl_PNORD,
Ctrl_PNORDT,
Ctrl_PNPREV,
Ctrl_PNQC,
Ctrl_PNQL,
Ctrl_PNQR,
Ctrl_PNRAUTH,
Ctrl_PNRDATE,
Ctrl_PNRESTART,
Ctrl_PNRNFC,
Ctrl_PNRNOT,
Ctrl_PNRPNBR,
Ctrl_PNRRGB,
Ctrl_PNRSTART,
Ctrl_PNRSTOP,
Ctrl_PNRXST,
Ctrl_PNSCAPS,
Ctrl_PNSECLVL,
Ctrl_PNSP,
Ctrl_PNSTART,
Ctrl_PNSTRIKE,
Ctrl_PNTEXT,
Ctrl_PNTXTA,
Ctrl_PNTXTB,
Ctrl_PNUCLTR,
Ctrl_PNUCRM,
Ctrl_PNUL,
Ctrl_PNULD,
Ctrl_PNULDASH,
Ctrl_PNULDASHD,
Ctrl_PNULDASHDD,
Ctrl_PNULDB,
Ctrl_PNULHAIR,
Ctrl_PNULNONE,
Ctrl_PNULTH,
Ctrl_PNULW,
Ctrl_PNULWAVE,
Ctrl_PNZODIAC,
Ctrl_PNZODIACD,
Ctrl_PNZODIACL,
Ctrl_POSNEGX,
Ctrl_POSNEGY,
Ctrl_POSX,
Ctrl_POSXC,
Ctrl_POSXI,
Ctrl_POSXL,
Ctrl_POSXO,
Ctrl_POSXR,
Ctrl_POSY,
Ctrl_POSYB,
Ctrl_POSYC,
Ctrl_POSYIL,
Ctrl_POSYIN,
Ctrl_POSYOUT,
Ctrl_POSYT,
Ctrl_PRCOLBL,
Ctrl_PRINTDATA,
Ctrl_PRINTIM,
Ctrl_PRIVATE,
Ctrl_PROPNAME,
Ctrl_PROPTYPE,
Ctrl_PSOVER,
Ctrl_PSZ,
Ctrl_PUBAUTO,
Ctrl_PVMRG,
Ctrl_PVPARA,
Ctrl_PVPG,
Ctrl_PWD,
Ctrl_PXE,
Ctrl_QC,
Ctrl_QD,
Ctrl_QJ,
Ctrl_QL,
Ctrl_QMSPACE,
Ctrl_QR,
Ctrl_RDBLQUOTE,
Ctrl_RED,
Ctrl_RESULT,
Ctrl_REVAUTH,
Ctrl_REVAUTHDEL,
Ctrl_REVBAR,
Ctrl_REVDTTM,
Ctrl_REVDTTMDEL,
Ctrl_REVISED,
Ctrl_REVISIONS,
Ctrl_REVPROP,
Ctrl_REVPROT,
Ctrl_REVTBL,
Ctrl_REVTIM,
Ctrl_RI,
Ctrl_RIN,
Ctrl_ROW,
Ctrl_RQUOTE,
Ctrl_RSLTBMP,
Ctrl_RSLTHTML,
Ctrl_RSLTMERGE,
Ctrl_RSLTPICT,
Ctrl_RSLTRTF,
Ctrl_RSLTTXT,
Ctrl_RTF,
Ctrl_RTLCH,
Ctrl_RTLDOC,
Ctrl_RTLGUTTER,
Ctrl_RTLMARK,
Ctrl_RTLPAR,
Ctrl_RTLROW,
Ctrl_RTLSECT,
Ctrl_RXE,
Ctrl_S,
Ctrl_SA,
Ctrl_SAAUTO,
Ctrl_SAUTOUPD,
Ctrl_SB,
Ctrl_SBASEDON,
Ctrl_SBAUTO,
Ctrl_SBKCOL,
Ctrl_SBKEVEN,
Ctrl_SBKNONE,
Ctrl_SBKODD,
Ctrl_SBKPAGE,
Ctrl_SBYS,
Ctrl_SCAPS,
Ctrl_SCOMPOSE,
Ctrl_SEC,
Ctrl_SECT,
Ctrl_SECTD,
Ctrl_SECTDEFAULTCL,
Ctrl_SECTEXPAND,
Ctrl_SECTLINEGRID,
Ctrl_SECTNUM,
Ctrl_SECTSPECIFYCL,
Ctrl_SECTSPECIFYGEN,
Ctrl_SECTSPECIFYL,
Ctrl_SECTUNLOCKED,
Ctrl_SHAD,
Ctrl_SHADING,
Ctrl_SHIDDEN,
Ctrl_SHIFT,
Ctrl_SHPBOTTOM,
Ctrl_SHPBXCOLUMN,
Ctrl_SHPBXIGNORE,
Ctrl_SHPBXMARGIN,
Ctrl_SHPBXPAGE,
Ctrl_SHPBYIGNORE,
Ctrl_SHPBYMARGIN,
Ctrl_SHPBYPAGE,
Ctrl_SHPBYPARA,
Ctrl_SHPFBLWTXT,
Ctrl_SHPFHDR,
Ctrl_SHPGRP,
Ctrl_SHPINST,
Ctrl_SHPLEFT,
Ctrl_SHPLID,
Ctrl_SHPLOCKANCHOR,
Ctrl_SHPPICT,
Ctrl_SHPRIGHT,
Ctrl_SHPRSLT,
Ctrl_SHPTOP,
Ctrl_SHPTXT,
Ctrl_SHPWRK,
Ctrl_SHPWR,
Ctrl_SHPZ,
Ctrl_SL,
Ctrl_SLMULT,
Ctrl_SNEXT,
Ctrl_SOFTCOL,
Ctrl_SOFTLHEIGHT,
Ctrl_SOFTLINE,
Ctrl_SOFTPAGE,
Ctrl_SPERSONAL,
Ctrl_SPLYTWNINE,
Ctrl_SPRSBSP,
Ctrl_SPRSLNSP,
Ctrl_SPRSSPBF,
Ctrl_SPRSTSM,
Ctrl_SPRSTSP,
Ctrl_SREPLY,
Ctrl_STATICVAL,
Ctrl_STEXTFLOW,
Ctrl_STRIKE,
Ctrl_STRIKED,
Ctrl_STYLESHEET,
Ctrl_SUB,
Ctrl_SUBDOCUMENT,
Ctrl_SUBFONTBYSIZE,
Ctrl_SUBJECT,
Ctrl_SUPER,
Ctrl_SWPBDR,
Ctrl_TAB,
Ctrl_TABSNOOVRLP,
Ctrl_TAPRTL,
Ctrl_TB,
Ctrl_TC,
Ctrl_TCELLD,
Ctrl_TCF,
Ctrl_TCL,
Ctrl_TCN,
Ctrl_TDFRMTXTBOTTOM,
Ctrl_TDFRMTXTLEFT,
Ctrl_TDFRMTXTRIGHT,
Ctrl_TDFRMTXTTOP,
Ctrl_TEMPLATE,
Ctrl_TIME,
Ctrl_TITLE,
Ctrl_TITLEPG,
Ctrl_TLDOT,
Ctrl_TLEQ,
Ctrl_TLHYPH,
Ctrl_TLMDOT,
Ctrl_TLTH,
Ctrl_TLUL,
Ctrl_TPHCOL,
Ctrl_TPHMRG,
Ctrl_TPHPG,
Ctrl_TPOSNEGX,
Ctrl_TPOSNEGY,
Ctrl_TPOSXC,
Ctrl_TPOSXI,
Ctrl_TPOSXL,
Ctrl_TPOSX,
Ctrl_TPOSXO,
Ctrl_TPOSXR,
Ctrl_TPOSY,
Ctrl_TPOSYB,
Ctrl_TPOSYC,
Ctrl_TPOSYIL,
Ctrl_TPOSYIN,
Ctrl_TPOSYOUTV,
Ctrl_TPOSYT,
Ctrl_TPVMRG,
Ctrl_TPVPARA,
Ctrl_TPVPG,
Ctrl_TQC,
Ctrl_TQDEC,
Ctrl_TQR,
Ctrl_TRANSMF,
Ctrl_TRAUTOFIT, // TABLE: ROW:
Ctrl_TRBRDRB, // TABLE: ROW: Table row border bottom
Ctrl_TRBRDRH, // TABLE: ROW: Table row border horizontal (inside)
Ctrl_TRBRDRL, // TABLE: ROW: Table row border left
Ctrl_TRBRDRR, // TABLE: ROW: Table row border right
Ctrl_TRBRDRT, // TABLE: ROW: Table row border top
Ctrl_TRBRDRV, // TABLE: ROW: Table row border vertical (inside)
Ctrl_TRFTSWIDTHA, // TABLE: ROW: units for trwWidthA (1 - auto, 2 - pct, 3 - twips
Ctrl_TRFTSWIDTHB, // TABLE: ROW: units for trwWidthB (1 - auto, 2 - pct, 3 - twips
Ctrl_TRFTSWIDTH, // TABLE: ROW: units for clwWidth (1 - auto, 2 - pct, 3 - twips
Ctrl_TRGAPH, // TABLE: ROW: Half the space between cells in a table in twips
Ctrl_TRHDR,
Ctrl_TRKEEP,
Ctrl_TRLEFT, // TABLE: ROW: Left offset of table in TWIPS, relative to column edge
Ctrl_TROWD, // TABLE: ROW: reset defaults
Ctrl_TRPADDB, // TABLE: ROW: default bottom cell padding for row (overridden by CLPADDB)
Ctrl_TRPADDFB, // TABLE: ROW: units for TRPADDB (0 - ignore, 3 - twips)
Ctrl_TRPADDFL, // TABLE: ROW: units for TRPADDL (0 - ignore, 3 - twips)
Ctrl_TRPADDFR, // TABLE: ROW: units for TRPADDR (0 - ignore, 3 - twips)
Ctrl_TRPADDFT, // TABLE: ROW: units for TRPADDT (0 - ignore, 3 - twips)
Ctrl_TRPADDL, // TABLE: ROW: default left cell padding for row (overridden by CLPADDL)
Ctrl_TRPADDR, // TABLE: ROW: default right cell padding for row (overridden by CLPADDR)
Ctrl_TRPADDT, // TABLE: ROW: default top cell padding for row (overridden by CLPADDT)
Ctrl_TRQC, // TABLE: ROW: default cell alignment is centered
Ctrl_TRQL, // TABLE: ROW: default cell alignment is left
Ctrl_TRQR, // TABLE: ROW: default cell alignment is right
Ctrl_TRRH,
Ctrl_TRSPDB,
Ctrl_TRSPDFB,
Ctrl_TRSPDFL,
Ctrl_TRSPDFR,
Ctrl_TRSPDFT,
Ctrl_TRSPDL,
Ctrl_TRSPDR,
Ctrl_TRSPDT,
Ctrl_TRUNCATEFONTHEIGHT,
Ctrl_TRWWIDTHA, // TABLE: ROW: width of invisible cell at end of row
Ctrl_TRWWIDTHB, // TABLE: ROW: width of invisible cell at beginning of row
Ctrl_TRWWIDTH, // TABLE: ROW: preferred row width (overrides trautofit)
Ctrl_TWOONONE,
Ctrl_TX,
Ctrl_TXE,
Ctrl_UC,
Ctrl_UD,
Ctrl_UL,
Ctrl_ULC,
Ctrl_ULD,
Ctrl_ULDASH,
Ctrl_ULDASHD,
Ctrl_ULDASHDD,
Ctrl_ULDB,
Ctrl_ULHAIR,
Ctrl_ULHWAVE,
Ctrl_ULLDASH,
Ctrl_ULNONE,
Ctrl_ULTH,
Ctrl_ULTHD,
Ctrl_ULTHDASH,
Ctrl_ULTHDASHD,
Ctrl_ULTHDASHDD,
Ctrl_ULTHLDASH,
Ctrl_ULULDBWAVE,
Ctrl_ULW,
Ctrl_ULWAVE,
Ctrl_U,
Ctrl_UP,
Ctrl_UPR,
Ctrl_URTF,
Ctrl_USELTBALN,
Ctrl_USERPROPS,
Ctrl_V,
Ctrl_VERN,
Ctrl_VERSION,
Ctrl_VERTALB,
Ctrl_VERTALC,
Ctrl_VERTALJ,
Ctrl_VERTALT,
Ctrl_VERTDOC,
Ctrl_VERTSECT,
Ctrl_VIEWKIND,
Ctrl_VIEWSCALE,
Ctrl_VIEWZK,
Ctrl_WBITMAP,
Ctrl_WBMBITSPIXEL,
Ctrl_WBMPLANES,
Ctrl_WBMWIDTHBYTES,
Ctrl_WEBHIDDEN,
Ctrl_WIDCTLPAR,
Ctrl_WIDOWCTRL,
Ctrl_WINDOWCAPTION,
Ctrl_WMETAFILE,
Ctrl_WPEQN,
Ctrl_WPJST,
Ctrl_WPSP,
Ctrl_WRAPTRSP,
Ctrl_XE,
Ctrl_XEF,
Ctrl_YR,
Ctrl_YXE,
Ctrl_ZWBO,
Ctrl_ZWJ,
Ctrl_ZWNBO,
Ctrl_ZWNJ
};
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
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 [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using fyiReporting.RDL;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Text;
using System.Xml;
using System.Globalization;
using System.Drawing;
namespace fyiReporting.RDL
{
///<summary>
/// Renders a report to HTML. All positioning is handled via tables.
///</summary>
internal class RenderHtmlTable: IPresent
{
Report r; // report
// Stack<string> _Container; // container for body/list/rectangle/ ...
StringWriter tw; // temporary location where the output is going
IStreamGen _sg; // stream generater
Hashtable _styles; // hash table of styles we've generated
int cssId=1; // ID for css when names are usable or available
bool bScriptToggle=false; // need to generate toggle javascript in header
bool bScriptTableSort=false; // need to generate table sort javascript in header
Bitmap _bm=null; // bm and
Graphics _g=null; // g are needed when calculating string heights
bool _Asp=false; // denotes ASP.NET compatible HTML; e.g. no <html>, <body>
// separate JavaScript and CSS
string _Prefix=""; // prefix to generating all HTML names (e.g. css, ...
string _CSS; // when ASP we put the CSS into a string
string _JavaScript; // as well as any required javascript
int _SkipMatrixCols=0; // # of matrix columns to skip
public RenderHtmlTable(Report rep, IStreamGen sg)
{
r = rep;
_sg = sg; // We need this in future
tw = new StringWriter(); // will hold the bulk of the HTML until we generate
// final file
_styles = new Hashtable();
}
//Replaced from forum, User: Aulofee http://www.fyireporting.com/forum/viewtopic.php?t=793
//~RenderHtmlTable()
public void Dispose()
{
// These should already be cleaned up; but in case of an unexpected error
// these still need to be disposed of
if (_bm != null)
_bm.Dispose();
if (_g != null)
_g.Dispose();
}
public Report Report()
{
return r;
}
public bool Asp
{
get {return _Asp;}
set {_Asp = value;}
}
public string JavaScript
{
get {return _JavaScript;}
}
public string CSS
{
get {return _CSS;}
}
public string Prefix
{
get {return _Prefix;}
set
{
_Prefix = value==null? "": value;
if (_Prefix.Length > 0 &&
_Prefix[0] == '_')
_Prefix = "a" + _Prefix; // not perfect but underscores as first letter don't work
}
}
public bool IsPagingNeeded()
{
return false;
}
public void Start()
{
// Create three tables that represent how each top level report item (e.g. those not in a table
// or matrix) will be positioned.
return;
}
string FixupRelativeName(string relativeName)
{
if (_sg is OneFileStreamGen)
{
if (relativeName[0] == Path.DirectorySeparatorChar || relativeName[0] == Path.AltDirectorySeparatorChar)
relativeName = relativeName.Substring(1);
}
else if (relativeName[0] != Path.DirectorySeparatorChar)
relativeName = Path.DirectorySeparatorChar + relativeName;
return relativeName;
}
// puts the JavaScript into the header
private void ScriptGenerate(TextWriter ftw)
{
if (bScriptToggle || bScriptTableSort)
{
ftw.WriteLine("<script language=\"javascript\">");
}
if (bScriptToggle)
{
ftw.WriteLine("var dname='';");
ftw.WriteLine(@"function hideShow(node, hideCount, showID) {
if (navigator.appName.toLowerCase().indexOf('netscape') > -1)
dname = 'table-row';
else
dname = 'block';
var tNode;
for (var ci=0;ci<node.childNodes.length;ci++) {
if (node.childNodes[ci].tagName && node.childNodes[ci].tagName.toLowerCase() == 'img') tNode = node.childNodes[ci];
}
var rows = findObject(showID);
if (rows[0].style.display == dname) {hideRows(rows, hideCount); tNode.src='plus.gif';}
else {
tNode.src='minus.gif';
for (var i = 0; i < rows.length; i++) {
rows[i].style.display = dname;
}
}
}
function hideRows(rows, count) {
var row;
if (navigator.appName.toLowerCase().indexOf('netscape') > -1)
{
for (var r=0; r < rows.length; r++) {
row = rows[r];
row.style.display = 'none';
var imgs = row.getElementsByTagName('img');
for (var ci=0;ci<imgs.length;ci++) {
if (imgs[ci].className == 'toggle') {
imgs[ci].src='plus.gif';
}
}
}
return;
}
if (rows.tagName == 'TR')
row = rows;
else
row = rows[0];
while (count > 0) {
row.style.display = 'none';
var imgs = row.getElementsByTagName('img');
for (var ci=0;ci<imgs.length;ci++) {
if (imgs[ci].className == 'toggle') {
imgs[ci].src='plus.gif';
}
}
row = row.nextSibling;
count--;
}
}
function findObject(id) {
if (navigator.appName.toLowerCase().indexOf('netscape') > -1)
{
var a = new Array();
var count=0;
for (var i=0; i < document.all.length; i++)
{
if (document.all[i].id == id)
a[count++] = document.all[i];
}
return a;
}
else
{
var o = document.all[id];
if (o.tagName == 'TR')
{
var a = new Array();
a[0] = o;
return a;
}
return o;
}
}
");
}
if (bScriptTableSort)
{
ftw.WriteLine("var SORT_INDEX;");
ftw.WriteLine("var SORT_DIR;");
ftw.WriteLine("function sort_getInnerText(element) {");
ftw.WriteLine(" if (typeof element == 'string') return element;");
ftw.WriteLine(" if (typeof element == 'undefined') return element;");
ftw.WriteLine(" if (element.innerText) return element.innerText;");
ftw.WriteLine(" var s = '';");
ftw.WriteLine(" var cn = element.childNodes;");
ftw.WriteLine(" for (var i = 0; i < cn.length; i++) {");
ftw.WriteLine(" switch (cn[i].nodeType) {");
ftw.WriteLine(" case 1:"); // element node
ftw.WriteLine(" s += sort_getInnerText(cn[i]);");
ftw.WriteLine(" break;");
ftw.WriteLine(" case 3:"); // text node
ftw.WriteLine(" s += cn[i].nodeValue;");
ftw.WriteLine(" break;");
ftw.WriteLine(" }");
ftw.WriteLine(" }");
ftw.WriteLine(" return s;");
ftw.WriteLine("}");
ftw.WriteLine("function sort_table(node, sortfn, header_rows, footer_rows) {");
ftw.WriteLine(" var arrowNode;"); // arrow node
ftw.WriteLine(" for (var ci=0;ci<node.childNodes.length;ci++) {");
ftw.WriteLine(" if (node.childNodes[ci].tagName && node.childNodes[ci].tagName.toLowerCase() == 'span') arrowNode = node.childNodes[ci];");
ftw.WriteLine(" }");
ftw.WriteLine(" var td = node.parentNode;");
ftw.WriteLine(" SORT_INDEX = td.cellIndex;"); // need to remember SORT_INDEX in compare function
ftw.WriteLine(" var table = sort_getTable(td);");
ftw.WriteLine(" var sortnext;");
ftw.WriteLine(" if (arrowNode.getAttribute('sortdir') == 'down') {");
ftw.WriteLine(" arrow = ' ↑';");
ftw.WriteLine(" SORT_DIR = -1;"); // descending SORT_DIR in compare function
ftw.WriteLine(" sortnext = 'up';");
ftw.WriteLine(" } else {");
ftw.WriteLine(" arrow = ' ↓';");
ftw.WriteLine(" SORT_DIR = 1;"); // ascending SORT_DIR in compare function
ftw.WriteLine(" sortnext = 'down';");
ftw.WriteLine(" }");
ftw.WriteLine(" var newRows = new Array();");
ftw.WriteLine(" for (j=header_rows;j<table.rows.length-footer_rows;j++) { newRows[j-header_rows] = table.rows[j]; }");
ftw.WriteLine(" newRows.sort(sortfn);");
// We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
ftw.WriteLine(" for (i=0;i<newRows.length;i++) {table.tBodies[0].appendChild(newRows[i]);}");
// Reset all arrows and directions for next time
ftw.WriteLine(" var spans = document.getElementsByTagName('span');");
ftw.WriteLine(" for (var ci=0;ci<spans.length;ci++) {");
ftw.WriteLine(" if (spans[ci].className == 'sortarrow') {");
// in the same table as us?
ftw.WriteLine(" if (sort_getTable(spans[ci]) == sort_getTable(node)) {");
ftw.WriteLine(" spans[ci].innerHTML = ' ';");
ftw.WriteLine(" spans[ci].setAttribute('sortdir','up');");
ftw.WriteLine(" }");
ftw.WriteLine(" }");
ftw.WriteLine(" }");
ftw.WriteLine(" arrowNode.innerHTML = arrow;");
ftw.WriteLine(" arrowNode.setAttribute('sortdir',sortnext);");
ftw.WriteLine("}");
ftw.WriteLine("function sort_getTable(el) {");
ftw.WriteLine(" if (el == null) return null;");
ftw.WriteLine(" else if (el.nodeType == 1 && el.tagName.toLowerCase() == 'table')");
ftw.WriteLine(" return el;");
ftw.WriteLine(" else");
ftw.WriteLine(" return sort_getTable(el.parentNode);");
ftw.WriteLine("}");
ftw.WriteLine("function sort_cmp_date(c1,c2) {");
ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]);");
ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]);");
ftw.WriteLine(" dt1 = new Date(t1);");
ftw.WriteLine(" dt2 = new Date(t2);");
ftw.WriteLine(" if (dt1==dt2) return 0;");
ftw.WriteLine(" if (dt1<dt2) return -SORT_DIR;");
ftw.WriteLine(" return SORT_DIR;");
ftw.WriteLine("}");
// numeric - removes any extraneous formating characters before parsing
ftw.WriteLine("function sort_cmp_number(c1,c2) {");
ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]).replace(/[^0-9.]/g,'');");
ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]).replace(/[^0-9.]/g,'');");
ftw.WriteLine(" n1 = parseFloat(t1);");
ftw.WriteLine(" n2 = parseFloat(t2);");
ftw.WriteLine(" if (isNaN(n1)) n1 = Number.MAX_VALUE");
ftw.WriteLine(" if (isNaN(n2)) n2 = Number.MAX_VALUE");
ftw.WriteLine(" return (n1 - n2)*SORT_DIR;");
ftw.WriteLine("}");
// For string we first do a case insensitive comparison;
// when equal we then do a case sensitive comparison
ftw.WriteLine("function sort_cmp_string(c1,c2) {");
ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]).toLowerCase();");
ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]).toLowerCase();");
ftw.WriteLine(" if (t1==t2) return sort_cmp_casesensitive(c1,c2);");
ftw.WriteLine(" if (t1<t2) return -SORT_DIR;");
ftw.WriteLine(" return SORT_DIR;");
ftw.WriteLine("}");
ftw.WriteLine("function sort_cmp_casesensitive(c1,c2) {");
ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]);");
ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]);");
ftw.WriteLine(" if (t1==t2) return 0;");
ftw.WriteLine(" if (t2<t2) return -SORT_DIR;");
ftw.WriteLine(" return SORT_DIR;");
ftw.WriteLine("}");
}
if (bScriptToggle || bScriptTableSort)
{
ftw.WriteLine("</script>");
}
return;
}
// handle the Action tag
private string Action(Action a, Row r, string t, string tooltip)
{
if (a == null)
return t;
string result = t;
if (a.Hyperlink != null)
{ // Handle a hyperlink
string url = a.HyperLinkValue(this.r, r);
if (tooltip == null)
result = String.Format("<a target=\"_top\" href=\"{0}\">{1}</a>", url, t);
else
result = String.Format("<a target=\"_top\" href=\"{0}\" title=\"{1}\">{2}</a>", url, tooltip, t);
}
else if (a.Drill != null)
{ // Handle a drill through
StringBuilder args= new StringBuilder("<a target=\"_top\" href=\"");
if (_Asp) // for ASP we go thru the default page and pass it as an argument
args.Append("Default.aspx?rs:url=");
args.Append(a.Drill.ReportName);
args.Append(".rdl");
if (a.Drill.DrillthroughParameters != null)
{
bool bFirst = !_Asp; // ASP already have an argument
foreach (DrillthroughParameter dtp in a.Drill.DrillthroughParameters.Items)
{
if (!dtp.OmitValue(this.r, r))
{
if (bFirst)
{ // First parameter - prefixed by '?'
args.Append('?');
bFirst = false;
}
else
{ // Subsequant parameters - prefixed by '&'
args.Append('&');
}
args.Append(dtp.Name.Nm);
args.Append('=');
args.Append(dtp.ValueValue(this.r, r));
}
}
}
args.Append('"');
if (tooltip != null)
args.Append(String.Format(" title=\"{0}\"", tooltip));
args.Append(">");
args.Append(t);
args.Append("</a>");
result = args.ToString();
}
else if (a.BookmarkLink != null)
{ // Handle a bookmark
string bm = a.BookmarkLinkValue(this.r, r);
if (tooltip == null)
result = String.Format("<a href=\"#{0}\">{1}</a>", bm, t);
else
result = String.Format("<a href=\"#{0}\" title=\"{1}\">{2}</a>", bm, tooltip, t);
}
return result;
}
private string Bookmark(string bm, string t)
{
if (bm == null)
return t;
return String.Format("<div id=\"{0}\">{1}</div>", bm, t);
}
// Generate the CSS styles and put them in the header
private void CssGenerate(TextWriter ftw)
{
if (_styles.Count <= 0)
return;
if (!_Asp)
ftw.WriteLine("<style type='text/css'>");
foreach (CssCacheEntry2 cce in _styles.Values)
{
int i = cce.Css.IndexOf('{');
if (cce.Name.IndexOf('#') >= 0)
ftw.WriteLine("{0} {1}", cce.Name, cce.Css.Substring(i));
else
ftw.WriteLine(".{0} {1}", cce.Name, cce.Css.Substring(i));
}
if (!_Asp)
ftw.WriteLine("</style>");
}
private string CssAdd(Style s, ReportLink rl, Row row)
{
return CssAdd(s, rl, row, false, float.MinValue, float.MinValue);
}
private string CssAdd(Style s, ReportLink rl, Row row, bool bForceRelative)
{
return CssAdd(s, rl, row, bForceRelative, float.MinValue, float.MinValue);
}
private string CssAdd(Style s, ReportLink rl, Row row, bool bForceRelative, float h, float w)
{
string css;
string prefix = CssPrefix(s, rl);
if (_Asp && prefix == "table#")
bForceRelative = true;
if (s != null)
css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + s.GetCSS(this.r, row, true) + "}";
else if (rl is Table || rl is Matrix)
css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + "border-collapse:collapse;}";
else
css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + "}";
CssCacheEntry2 cce = (CssCacheEntry2) _styles[css];
if (cce == null)
{
string name = prefix + this.Prefix + "css" + cssId++.ToString();
cce = new CssCacheEntry2(css, name);
_styles.Add(cce.Css, cce);
}
int i = cce.Name.IndexOf('#');
if (i > 0)
return cce.Name.Substring(i+1);
else
return cce.Name;
}
private string CssPosition(ReportLink rl,Row row, bool bForceRelative, float h, float w)
{
if (!(rl is ReportItem)) // if not a report item then no position
return "";
// no positioning within a table
for (ReportLink p=rl.Parent; p != null; p=p.Parent)
{
if (p is TableCell)
return "";
if (p is RowGrouping ||
p is MatrixCell ||
p is ColumnGrouping ||
p is Corner)
{
StringBuilder sb2 = new StringBuilder();
if (h != float.MinValue)
sb2.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}pt; ", h);
if (w != float.MinValue)
sb2.AppendFormat(NumberFormatInfo.InvariantInfo, "width: {0}pt; ", w);
return sb2.ToString();
}
}
// TODO: optimize by putting this into ReportItem and caching result???
ReportItem ri = (ReportItem) rl;
StringBuilder sb = new StringBuilder();
if (ri.Left != null)
{
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "left: {0}; ", ri.Left.CSS);
}
if (!(ri is Matrix))
{
if (ri.Width != null)
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "width: {0}; ", ri.Width.CSS);
}
if (ri.Top != null)
{
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "top: {0}pt; ", ri.Gap(this.r));
}
if (ri is List)
{
List l = ri as List;
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}pt; ", l.HeightOfList(this.r, GetGraphics,row));
}
else if (ri is Matrix || ri is Table)
{}
else if (ri.Height != null)
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}; ", ri.Height.CSS);
if (sb.Length > 0)
{
if (bForceRelative || ri.YParents != null)
sb.Insert(0, "position: relative; ");
else
sb.Insert(0, "position: absolute; ");
}
return sb.ToString();
}
private Graphics GetGraphics
{
get
{
if (_g == null)
{
_bm = new Bitmap(10, 10);
_g = Graphics.FromImage(_bm);
}
return _g;
}
}
private string CssPrefix(Style s, ReportLink rl)
{
string cssPrefix=null;
ReportLink p;
if (rl is Table || rl is Matrix || rl is Rectangle)
{
cssPrefix = "table#";
}
else if (rl is Body)
{
cssPrefix = "body#";
}
else if (rl is Line)
{
cssPrefix = "table#";
}
else if (rl is List)
{
cssPrefix = "";
}
else if (rl is Subreport)
{
cssPrefix = "";
}
else if (rl is Chart)
{
cssPrefix = "";
}
if (cssPrefix != null)
return cssPrefix;
// now find what the style applies to
for (p=rl.Parent; p != null; p=p.Parent)
{
if (p is TableCell)
{
bool bHead = false;
ReportLink p2;
for (p2=p.Parent; p2 != null; p2=p2.Parent)
{
Type t2 = p2.GetType();
if (t2 == typeof(Header))
{
if (p2.Parent is Table)
bHead=true;
break;
}
}
if (bHead)
cssPrefix = "th#";
else
cssPrefix = "td#";
break;
}
else if (p is RowGrouping ||
p is MatrixCell ||
p is ColumnGrouping ||
p is Corner)
{
cssPrefix = "td#";
break;
}
}
return cssPrefix == null? "": cssPrefix;
}
public void End()
{
string bodyCssId;
if (r.ReportDefinition.Body != null)
bodyCssId = CssAdd(r.ReportDefinition.Body.Style, r.ReportDefinition.Body, null); // add the style for the body
else
bodyCssId = null;
TextWriter ftw = _sg.GetTextWriter(); // the final text writer location
if (_Asp)
{
// do any required JavaScript
StringWriter sw = new StringWriter();
ScriptGenerate(sw);
_JavaScript = sw.ToString();
sw.Close();
// do any required CSS
sw = new StringWriter();
CssGenerate(sw);
_CSS = sw.ToString();
sw.Close();
}
else
{
ftw.WriteLine(@"<html>");
// handle the <head>: description, javascript and CSS goes here
ftw.WriteLine("<head>");
ScriptGenerate(ftw);
CssGenerate(ftw);
if (r.Description != null) // Use description as title if provided
ftw.WriteLine(string.Format(@"<title>{0}</title>", XmlUtil.XmlAnsi(r.Description)));
ftw.WriteLine(@"</head>");
}
// Always want an HTML body - even if report doesn't have a body stmt
if (this._Asp)
{
ftw.WriteLine("<table style=\"position: relative;\">");
}
else if (bodyCssId != null)
ftw.WriteLine(@"<body id='{0}'><table>", bodyCssId);
else
ftw.WriteLine("<body><table>");
ftw.Write(tw.ToString());
if (this._Asp)
ftw.WriteLine(@"</table>");
else
ftw.WriteLine(@"</table></body></html>");
if (_g != null)
{
_g.Dispose();
_g = null;
}
if (_bm != null)
{
_bm.Dispose();
_bm = null;
}
return;
}
// Body: main container for the report
public void BodyStart(Body b)
{
if (b.ReportItems != null && b.ReportItems.Items.Count > 0)
tw.WriteLine("<tr><td><div style=\"POSITION: relative; \">");
}
public void BodyEnd(Body b)
{
if (b.ReportItems != null && b.ReportItems.Items.Count > 0)
tw.WriteLine("</div></td></tr>");
}
public void PageHeaderStart(PageHeader ph)
{
if (ph.ReportItems != null && ph.ReportItems.Items.Count > 0)
tw.WriteLine("<tr><td><div style=\"overflow: clip; POSITION: relative; HEIGHT: {0};\">", ph.Height.CSS);
}
public void PageHeaderEnd(PageHeader ph)
{
if (ph.ReportItems != null && ph.ReportItems.Items.Count > 0)
tw.WriteLine("</div></td></tr>");
}
public void PageFooterStart(PageFooter pf)
{
if (pf.ReportItems != null && pf.ReportItems.Items.Count > 0)
tw.WriteLine("<tr><td><div style=\"overflow: clip; POSITION: relative; HEIGHT: {0};\">", pf.Height.CSS);
}
public void PageFooterEnd(PageFooter pf)
{
if (pf.ReportItems != null && pf.ReportItems.Items.Count > 0)
tw.WriteLine("</div></td></tr>");
}
public void Textbox(Textbox tb, string t, Row row)
{
if (!tb.IsHtml(this.r, row)) // we leave the text as is when request is to treat as html
{ // this can screw up the generated HTML if not properly formed HTML
// make all the characters browser readable
t = XmlUtil.XmlAnsi(t);
// handle any specified bookmark
t = Bookmark(tb.BookmarkValue(this.r, row), t);
// handle any specified actions
t = Action(tb.Action, row, t, tb.ToolTipValue(this.r, row));
}
// determine if we're in a tablecell
Type tp = tb.Parent.Parent.GetType();
bool bCell;
if (tp == typeof(TableCell) ||
tp == typeof(Corner) ||
tp == typeof(DynamicColumns) ||
tp == typeof(DynamicRows) ||
tp == typeof(StaticRow) ||
tp == typeof(StaticColumn) ||
tp == typeof(Subtotal) ||
tp == typeof(MatrixCell))
bCell = true;
else
bCell = false;
if (tp == typeof(Rectangle))
tw.Write("<td>");
if (bCell)
{ // The cell has the formatting for this text
if (t == "")
tw.Write("<br />"); // must have something in cell for formating
else
tw.Write(t);
}
else
{ // Formatting must be specified
string cssName = CssAdd(tb.Style, tb, row); // get the style name for this item
tw.Write("<div class='{0}'>{1}</div>", cssName, t);
}
if (tp == typeof(Rectangle))
tw.Write("</td>");
}
public void DataRegionNoRows(DataRegion d, string noRowsMsg) // no rows in table
{
if (noRowsMsg == null)
noRowsMsg = "";
bool bTableCell = d.Parent.Parent.GetType() == typeof(TableCell);
if (bTableCell)
{
if (noRowsMsg == "")
tw.Write("<br />");
else
tw.Write(noRowsMsg);
}
else
{
string cssName = CssAdd(d.Style, d, null); // get the style name for this item
tw.Write("<div class='{0}'>{1}</div>", cssName, noRowsMsg);
}
}
// Lists
public bool ListStart(List l, Row r)
{
// identifiy reportitem it if necessary
string bookmark = l.BookmarkValue(this.r, r);
if (bookmark != null) //
tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
return true;
}
public void ListEnd(List l, Row r)
{
string bookmark = l.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("</div>");
}
public void ListEntryBegin(List l, Row r)
{
string cssName = CssAdd(l.Style, l, r, true); // get the style name for this item; force to be relative
tw.WriteLine();
tw.WriteLine("<div class={0}>", cssName);
}
public void ListEntryEnd(List l, Row r)
{
tw.WriteLine();
tw.WriteLine("</div>");
}
// Tables // Report item table
public bool TableStart(Table t, Row row)
{
string cssName = CssAdd(t.Style, t, row); // get the style name for this item
// Determine if report custom defn want this table to be sortable
if (IsTableSortable(t))
{
this.bScriptTableSort = true;
}
string bookmark = t.BookmarkValue(this.r, row);
if (bookmark != null)
tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
// Calculate the width of all the columns
int width = t.WidthInPixels(this.r, row);
if (width <= 0)
tw.WriteLine("<table id='{0}'>", cssName);
else
tw.WriteLine("<table id='{0}' width={1}>", cssName, width);
return true;
}
public bool IsTableSortable(Table t)
{
if (t.TableGroups != null || t.Details == null ||
t.Details.TableRows == null || t.Details.TableRows.Items.Count != 1)
return false; // can't have tableGroups; must have 1 detail row
// Determine if report custom defn want this table to be sortable
bool bReturn = false;
if (t.Custom != null)
{
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in t.Custom.CustomXmlNode.ChildNodes)
{
if (xNodeLoop.Name == "HTML")
{
if (xNodeLoop.LastChild.InnerText.ToLower() == "true")
{
bReturn = true;
}
break;
}
}
}
return bReturn;
}
public void TableEnd(Table t, Row row)
{
string bookmark = t.BookmarkValue(this.r, row);
if (bookmark != null)
tw.WriteLine("</div>");
tw.WriteLine("</table>");
return;
}
public void TableBodyStart(Table t, Row row)
{
tw.WriteLine("<tbody>");
}
public void TableBodyEnd(Table t, Row row)
{
tw.WriteLine("</tbody>");
}
public void TableFooterStart(Footer f, Row row)
{
tw.WriteLine("<tfoot>");
}
public void TableFooterEnd(Footer f, Row row)
{
tw.WriteLine("</tfoot>");
}
public void TableHeaderStart(Header h, Row row)
{
tw.WriteLine("<thead>");
}
public void TableHeaderEnd(Header h, Row row)
{
tw.WriteLine("</thead>");
}
public void TableRowStart(TableRow tr, Row row)
{
tw.Write("\t<tr");
ReportLink rl = tr.Parent.Parent;
Visibility v=null;
Textbox togText=null; // holds the toggle text box if any
if (rl is Details)
{
Details d = (Details) rl;
v = d.Visibility;
togText = d.ToggleTextbox;
}
else if (rl.Parent is TableGroup)
{
TableGroup tg = (TableGroup) rl.Parent;
v = tg.Visibility;
togText = tg.ToggleTextbox;
}
if (v != null &&
v.Hidden != null)
{
bool bHide = v.Hidden.EvaluateBoolean(this.r, row);
if (bHide)
tw.Write(" style=\"display:none;\"");
}
if (togText != null && togText.Name != null)
{
string name = togText.Name.Nm + "_" + togText.RunCount(this.r).ToString();
tw.Write(" id='{0}'", name);
}
tw.Write(">");
}
public void TableRowEnd(TableRow tr, Row row)
{
tw.WriteLine("</tr>");
}
public void TableCellStart(TableCell t, Row row)
{
string cellType = t.InTableHeader? "th": "td";
ReportItem r = t.ReportItems.Items[0];
string cssName = CssAdd(r.Style, r, row); // get the style name for this item
tw.Write("<{0} id='{1}'", cellType, cssName);
// calculate width of column
if (t.InTableHeader && t.OwnerTable.TableColumns != null)
{
// Calculate the width across all the spanned columns
int width = 0;
for (int ci=t.ColIndex; ci < t.ColIndex + t.ColSpan; ci++)
{
TableColumn tc = t.OwnerTable.TableColumns.Items[ci] as TableColumn;
if (tc != null && tc.Width != null)
width += tc.Width.PixelsX;
}
if (width > 0)
tw.Write(" width={0}", width);
}
if (t.ColSpan > 1)
tw.Write(" colspan={0}", t.ColSpan);
Textbox tb = r as Textbox;
if (tb != null && // have textbox
tb.IsToggle && // and its a toggle
tb.Name != null) // and need name as well
{
int groupNestCount = t.OwnerTable.GetGroupNestCount(this.r);
if (groupNestCount > 0) // anything to toggle?
{
string name = tb.Name.Nm + "_" + (tb.RunCount(this.r)+1).ToString();
bScriptToggle = true;
// need both hand and pointer because IE and Firefox use different names
tw.Write(" onClick=\"hideShow(this, {0}, '{1}')\" onMouseOver=\"style.cursor ='hand';style.cursor ='pointer'\">", groupNestCount, name);
tw.Write("<img class='toggle' src=\"plus.gif\" align=\"top\"/>");
}
else
tw.Write("<img src=\"empty.gif\" align=\"top\"/>");
}
else
tw.Write(">");
if (t.InTableHeader)
{
// put the second half of the sort tags for the column; if needed
// first half ---- <a href="#" onclick="sort_table(this,sort_cmp_string,1,0);return false;">
// next half follows text ---- <span class="sortarrow"> </span></a></th>
string sortcmp = SortType(t, tb); // obtain the sort type
if (sortcmp != null) // null if sort not needed
{
int headerRows, footerRows;
headerRows = t.OwnerTable.Header.TableRows.Items.Count; // since we're in header we know we have some rows
if (t.OwnerTable.Footer != null &&
t.OwnerTable.Footer.TableRows != null)
footerRows = t.OwnerTable.Footer.TableRows.Items.Count;
else
footerRows = 0;
tw.Write("<a href=\"#\" title='Sort' onclick=\"sort_table(this,{0},{1},{2});return false;\">",sortcmp, headerRows, footerRows);
}
}
return;
}
private string SortType(TableCell tc, Textbox tb)
{
// return of null means don't sort
if (tb == null || !IsTableSortable(tc.OwnerTable))
return null;
// default is true if table is sortable;
// but user may place override on Textbox custom tag
if (tb.Custom != null)
{
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in tb.Custom.CustomXmlNode.ChildNodes)
{
if (xNodeLoop.Name == "HTML")
{
if (xNodeLoop.LastChild.InnerText.ToLower() == "false")
{
return null;
}
break;
}
}
}
// Must find out the type of the detail column
Details d = tc.OwnerTable.Details;
if (d == null)
return null;
TableRow tr = d.TableRows.Items[0] as TableRow;
if (tr == null)
return null;
TableCell dtc = tr.TableCells.Items[tc.ColIndex] as TableCell;
if (dtc == null)
return null;
Textbox dtb = dtc.ReportItems.Items[0] as Textbox;
if (dtb == null)
return null;
string sortcmp;
switch (dtb.Value.Type)
{
case TypeCode.DateTime:
sortcmp = "sort_cmp_date";
break;
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Decimal:
case TypeCode.Single:
case TypeCode.Double:
sortcmp = "sort_cmp_number";
break;
case TypeCode.String:
sortcmp = "sort_cmp_string";
break;
case TypeCode.Empty: // Not a type we know how to sort
default:
sortcmp = null;
break;
}
return sortcmp;
}
public void TableCellEnd(TableCell t, Row row)
{
string cellType = t.InTableHeader? "th": "td";
Textbox tb = t.ReportItems.Items[0] as Textbox;
if (cellType == "th" && SortType(t, tb) != null)
{ // put the second half of the sort tags for the column
// first half ---- <a href="#" onclick="sort_table(this,sort_cmp_string,1,0);return false;">
// next half follows text ---- <span class="sortarrow"> </span></a></th>
tw.Write("<span class=\"sortarrow\"> </span></a>");
}
tw.Write("</{0}>", cellType);
return;
}
public bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) // called first
{
string bookmark = m.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
// output some of the table styles
string cssName = CssAdd(m.Style, m, r); // get the style name for this item
tw.WriteLine("<table id='{0}'>", cssName);
return true;
}
public void MatrixColumns(Matrix m, MatrixColumns mc) // called just after MatrixStart
{
}
public void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan)
{
if (ri == null) // Empty cell?
{
if (_SkipMatrixCols == 0)
tw.Write("<td>");
return;
}
string cssName = CssAdd(ri.Style, ri, r, false, h, w); // get the style name for this item
tw.Write("<td id='{0}'", cssName);
if (colSpan != 1)
{
tw.Write(" colspan={0}", colSpan);
_SkipMatrixCols=-(colSpan-1); // start it as negative as indicator that we need this </td>
}
else
_SkipMatrixCols=0;
if (ri is Textbox)
{
Textbox tb = (Textbox) ri;
if (tb.IsToggle && tb.Name != null) // name is required for this
{
string name = tb.Name.Nm + "_" + (tb.RunCount(this.r)+1).ToString();
bScriptToggle = true; // we need to generate JavaScript in header
// TODO -- need to calculate the hide count correctly
tw.Write(" onClick=\"hideShow(this, {0}, '{1}')\" onMouseOver=\"style.cursor ='hand'\"", 0, name);
}
}
tw.Write(">");
}
public void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r)
{
if (_SkipMatrixCols == 0)
tw.Write("</td>");
else if (_SkipMatrixCols < 0)
{
tw.Write("</td>");
_SkipMatrixCols = -_SkipMatrixCols;
}
else
_SkipMatrixCols--;
return;
}
public void MatrixRowStart(Matrix m, int row, Row r)
{
tw.Write("\t<tr");
tw.Write(">");
}
public void MatrixRowEnd(Matrix m, int row, Row r)
{
tw.WriteLine("</tr>");
}
public void MatrixEnd(Matrix m, Row r) // called last
{
tw.Write("</table>");
string bookmark = m.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("</div>");
return;
}
public void Chart(Chart c, Row r, ChartBase cb)
{
string relativeName;
Stream io = _sg.GetIOStream(out relativeName, "png");
try
{
cb.Save(this.r, io, ImageFormat.Png);
}
finally
{
io.Flush();
io.Close();
}
relativeName = FixupRelativeName(relativeName);
// Create syntax in a string buffer
StringWriter sw = new StringWriter();
string bookmark = c.BookmarkValue(this.r, r);
if (bookmark != null)
sw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
string cssName = CssAdd(c.Style, c, null); // get the style name for this item
sw.Write("<img src=\"{0}\" class='{1}'", relativeName, cssName);
string tooltip = c.ToolTipValue(this.r, r);
if (tooltip != null)
sw.Write(" alt=\"{0}\"", tooltip);
if (c.Height != null)
sw.Write(" height=\"{0}\"", c.Height.PixelsY.ToString());
if (c.Width != null)
sw.Write(" width=\"{0}\"", c.Width.PixelsX.ToString());
sw.Write(">");
if (bookmark != null)
sw.Write("</div>");
tw.Write(Action(c.Action, r, sw.ToString(), tooltip));
return;
}
public void Image(Image i, Row r, string mimeType, Stream ioin)
{
string relativeName;
string suffix;
switch (mimeType)
{
case "image/bmp":
suffix = "bmp";
break;
case "image/jpeg":
suffix = "jpeg";
break;
case "image/gif":
suffix = "gif";
break;
case "image/png":
case "image/x-png":
suffix = "png";
break;
default:
suffix = "unk";
break;
}
Stream io = _sg.GetIOStream(out relativeName, suffix);
try
{
if (ioin.CanSeek) // ioin.Length requires Seek support
{
byte[] ba = new byte[ioin.Length];
ioin.Read(ba, 0, ba.Length);
io.Write(ba, 0, ba.Length);
}
else
{
byte[] ba = new byte[1000]; // read a 1000 bytes at a time
while (true)
{
int length = ioin.Read(ba, 0, ba.Length);
if (length <= 0)
break;
io.Write(ba, 0, length);
}
}
}
finally
{
io.Flush();
io.Close();
}
relativeName = FixupRelativeName(relativeName);
// Create syntax in a string buffer
StringWriter sw = new StringWriter();
string bookmark = i.BookmarkValue(this.r, r);
if (bookmark != null)
sw.WriteLine("<div id=\"{0}\">", bookmark); // we're using for css style
string cssName = CssAdd(i.Style, i, null); // get the style name for this item
sw.Write("<img src=\"{0}\" class='{1}'", relativeName, cssName);
string tooltip = i.ToolTipValue(this.r, r);
if (tooltip != null)
sw.Write(" alt=\"{0}\"", tooltip);
if (i.Height != null)
sw.Write(" height=\"{0}\"", i.Height.PixelsY.ToString());
if (i.Width != null)
sw.Write(" width=\"{0}\"", i.Width.PixelsX.ToString());
sw.Write("/>");
if (bookmark != null)
sw.Write("</div>");
tw.Write(Action(i.Action, r, sw.ToString(), tooltip));
return;
}
public void Line(Line l, Row r)
{
bool bVertical;
string t;
if (l.Height == null || l.Height.PixelsY > 0) // only handle horizontal rule
{
if (l.Width == null || l.Width.PixelsX > 0) // and vertical rules
return;
bVertical = true;
t = "<TABLE style=\"border-collapse:collapse;BORDER-STYLE: none;WIDTH: {0}; POSITION: absolute; LEFT: {1}; TOP: {2}; HEIGHT: {3}; BACKGROUND-COLOR:{4};\"><TBODY><TR style=\"WIDTH:{0}\"><TD style=\"WIDTH:{0}\"></TD></TR></TBODY></TABLE>";
}
else
{
bVertical = false;
t = "<TABLE style=\"border-collapse:collapse;BORDER-STYLE: none;WIDTH: {0}; POSITION: absolute; LEFT: {1}; TOP: {2}; HEIGHT: {3}; BACKGROUND-COLOR:{4};\"><TBODY><TR style=\"HEIGHT:{3}\"><TD style=\"HEIGHT:{3}\"></TD></TR></TBODY></TABLE>";
}
string width, left, top, height, color;
Style s = l.Style;
left = l.Left == null? "0px": l.Left.CSS;
top = l.Top == null? "0px": l.Top.CSS;
if (bVertical)
{
height = l.Height == null? "0px": l.Height.CSS;
// width comes from the BorderWidth
if (s != null && s.BorderWidth != null && s.BorderWidth.Default != null)
width = s.BorderWidth.Default.EvaluateString(this.r, r);
else
width = "1px";
}
else
{
width = l.Width == null? "0px": l.Width.CSS;
// height comes from the BorderWidth
if (s != null && s.BorderWidth != null && s.BorderWidth.Default != null)
height = s.BorderWidth.Default.EvaluateString(this.r, r);
else
height = "1px";
}
if (s != null && s.BorderColor != null && s.BorderColor.Default != null)
color = s.BorderColor.Default.EvaluateString(this.r, r);
else
color = "black";
tw.WriteLine(t, width, left, top, height, color);
return;
}
public bool RectangleStart(RDL.Rectangle rect, Row r)
{
string cssName = CssAdd(rect.Style, rect, r); // get the style name for this item
string bookmark = rect.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
// Calculate the width of all the columns
int width = rect.Width.PixelsX;
if (width < 0)
tw.WriteLine("<table id='{0}'><tr>", cssName);
else
tw.WriteLine("<table id='{0}' width={1}><tr>", cssName, width);
return true;
}
public void RectangleEnd(RDL.Rectangle rect, Row r)
{
tw.WriteLine("</tr></table>");
string bookmark = rect.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("</div>");
return;
}
// Subreport:
public void Subreport(Subreport s, Row r)
{
string cssName = CssAdd(s.Style, s, r); // get the style name for this item
tw.WriteLine("<div class='{0}'>", cssName);
s.ReportDefn.Run(this);
tw.WriteLine("</div>");
}
public void GroupingStart(Grouping g) // called at start of grouping
{
}
public void GroupingInstanceStart(Grouping g) // called at start for each grouping instance
{
}
public void GroupingInstanceEnd(Grouping g) // called at start for each grouping instance
{
}
public void GroupingEnd(Grouping g) // called at end of grouping
{
}
public void RunPages(Pages pgs) // we don't have paging turned on for html
{
}
}
class CssCacheEntry2
{
string _Css; // css
string _Name; // name of entry
public CssCacheEntry2(string css, string name)
{
_Css = css;
_Name = name;
}
public string Css
{
get { return _Css; }
set { _Css = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
}
| |
using System;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
namespace Palaso.UI.WindowsForms
{
public static class ReflectionHelper
{
/// ------------------------------------------------------------------------------------
/// <summary>
/// Loads a DLL.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Assembly LoadAssembly(string dllPath)
{
try
{
if (!File.Exists(dllPath))
{
string dllFile = Path.GetFileName(dllPath);
dllPath = Path.Combine(Application.StartupPath, dllFile);
if (!File.Exists(dllPath))
return null;
}
return Assembly.LoadFrom(dllPath);
}
catch (Exception)
{
return null;
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
public static object CreateClassInstance(Assembly assembly, string className)
{
return CreateClassInstance(assembly, className, null);
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
public static object CreateClassInstance(Assembly assembly, string className, object[] args)
{
try
{
// First, take a stab at creating the instance with the specified name.
object instance = assembly.CreateInstance(className, false,
BindingFlags.CreateInstance, null, args, null, null);
if (instance != null)
return instance;
Type[] types = assembly.GetTypes();
// At this point, we know we failed to instantiate a class with the
// specified name, so try to find a type with that name and attempt
// to instantiate the class using the full namespace.
foreach (Type type in types)
{
if (type.Name == className)
{
return assembly.CreateInstance(type.FullName, false,
BindingFlags.CreateInstance, null, args, null, null);
}
}
}
catch { }
return null;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a string value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static string GetStrResult(object binding, string methodName, object[] args)
{
return (GetResult(binding, methodName, args) as string);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a string value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static string GetStrResult(object binding, string methodName, object args)
{
return (GetResult(binding, methodName, args) as string);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a integer value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static int GetIntResult(object binding, string methodName, object args)
{
return ((int)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a integer value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static int GetIntResult(object binding, string methodName, object[] args)
{
return ((int)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a float value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static float GetFloatResult(object binding, string methodName, object args)
{
return ((float)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a float value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static float GetFloatResult(object binding, string methodName, object[] args)
{
return ((float)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a boolean value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static bool GetBoolResult(object binding, string methodName, object args)
{
return ((bool)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a boolean value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static bool GetBoolResult(object binding, string methodName, object[] args)
{
return ((bool)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName)
{
CallMethod(binding, methodName, null);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object args)
{
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object arg1, object arg2)
{
object[] args = new[] {arg1, arg2};
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object arg1,
object arg2, object arg3)
{
object[] args = new[] { arg1, arg2, arg3 };
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object arg1,
object arg2, object arg3, object arg4)
{
object[] args = new[] { arg1, arg2, arg3, arg4 };
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object[] args)
{
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns the result of calling a method on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetResult(object binding, string methodName, object args)
{
return Invoke(binding, methodName, new[] { args }, BindingFlags.InvokeMethod);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns the result of calling a method on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetResult(object binding, string methodName, object[] args)
{
return Invoke(binding, methodName, args, BindingFlags.InvokeMethod);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified property on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void SetProperty(object binding, string propertyName, object args)
{
Invoke(binding, propertyName, new[] { args }, BindingFlags.SetProperty);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified field (i.e. member variable) on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void SetField(object binding, string fieldName, object args)
{
Invoke(binding, fieldName, new[] { args }, BindingFlags.SetField);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the specified property on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetProperty(object binding, string propertyName)
{
return Invoke(binding, propertyName, null, BindingFlags.GetProperty);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the specified field (i.e. member variable) on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetField(object binding, string fieldName)
{
return Invoke(binding, fieldName, null, BindingFlags.GetField);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified member variable or property (specified by name) on the
/// specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
private static object Invoke(object binding, string name, object[] args, BindingFlags flags)
{
flags |= (BindingFlags.NonPublic | BindingFlags.Public);
//if (CanInvoke(binding, name, flags))
{
try
{
// If binding is a Type then assume invoke on a static method, property or field.
// Otherwise invoke on an instance method, property or field.
if (binding is Type)
{
return ((binding as Type).InvokeMember(name,
flags | BindingFlags.Static, null, binding, args));
}
return binding.GetType().InvokeMember(name,
flags | BindingFlags.Instance, null, binding, args);
}
catch { }
}
return null;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding, throwing any exceptions that
/// may occur.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object CallMethodWithThrow(object binding, string name, object[] args)
{
const BindingFlags flags =
(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod);
// If binding is a Type then assume invoke on a static method, property or field.
// Otherwise invoke on an instance method, property or field.
if (binding is Type)
{
return ((binding as Type).InvokeMember(name,
flags | BindingFlags.Static, null, binding, args));
}
return binding.GetType().InvokeMember(name,
flags | BindingFlags.Instance, null, binding, args);
}
///// ------------------------------------------------------------------------------------
///// <summary>
///// Gets a value indicating whether or not the specified binding contains the field,
///// property or method indicated by name and having the specified flags.
///// </summary>
///// ------------------------------------------------------------------------------------
//private static bool CanInvoke(object binding, string name, BindingFlags flags)
//{
// var srchFlags = (BindingFlags.Public | BindingFlags.NonPublic);
// Type bindingType = null;
// if (binding is Type)
// {
// bindingType = (Type)binding;
// srchFlags |= BindingFlags.Static;
// }
// else
// {
// binding.GetType();
// srchFlags |= BindingFlags.Instance;
// }
// if (((flags & BindingFlags.GetProperty) == BindingFlags.GetProperty) ||
// ((flags & BindingFlags.SetProperty) == BindingFlags.SetProperty))
// {
// return (bindingType.GetProperty(name, srchFlags) != null);
// }
// if (((flags & BindingFlags.GetField) == BindingFlags.GetField) ||
// ((flags & BindingFlags.SetField) == BindingFlags.SetField))
// {
// return (bindingType.GetField(name, srchFlags) != null);
// }
// if ((flags & BindingFlags.InvokeMethod) == BindingFlags.InvokeMethod)
// return (bindingType.GetMethod(name, srchFlags) != null);
// return false;
//}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using AutoRest.Core.Model;
using AutoRest.Core.Logging;
using AutoRest.Core.Utilities;
using AutoRest.Swagger.Model;
using AutoRest.Swagger.Properties;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ParameterLocation = AutoRest.Swagger.Model.ParameterLocation;
using static AutoRest.Core.Utilities.DependencyInjection;
namespace AutoRest.Swagger
{
/// <summary>
/// The builder for building swagger operations into client model methods.
/// </summary>
public class OperationBuilder
{
private readonly IReadOnlyList<string> _effectiveProduces;
private readonly IReadOnlyList<string> _effectiveConsumes;
private readonly SwaggerModeler _swaggerModeler;
private readonly Operation _operation;
private const string APP_JSON_MIME = "application/json";
private const string APP_XML_MIME = "application/xml";
public OperationBuilder(Operation operation, SwaggerModeler swaggerModeler)
{
_operation = operation ?? throw new ArgumentNullException("operation");
_swaggerModeler = swaggerModeler ?? throw new ArgumentNullException("swaggerModeler");
_effectiveProduces = (operation.Produces.Any() ? operation.Produces : swaggerModeler.ServiceDefinition.Produces).ToList();
_effectiveConsumes = (operation.Consumes.Any() ? operation.Consumes : swaggerModeler.ServiceDefinition.Consumes).ToList();
}
public Method BuildMethod(HttpMethod httpMethod, string url, string methodName, string methodGroup)
{
EnsureUniqueMethodName(methodName, methodGroup);
var method = New<Method>(new
{
HttpMethod = httpMethod,
Url = url,
Name = methodName,
SerializedName = _operation.OperationId
});
// assume that without specifying Consumes, that a service will consume JSON
method.RequestContentType = _effectiveConsumes.FirstOrDefault() ?? APP_JSON_MIME;
// does the method Consume JSON or XML?
string serviceConsumes = _effectiveConsumes.FirstOrDefault(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase)) ?? _effectiveConsumes.FirstOrDefault(s => s.StartsWith(APP_XML_MIME, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(serviceConsumes))
{
method.RequestContentType = serviceConsumes;
}
// if they accept JSON or XML, and don't specify the charset, lets default to utf-8
if ((method.RequestContentType.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase) ||
method.RequestContentType.StartsWith(APP_XML_MIME, StringComparison.OrdinalIgnoreCase)) &&
method.RequestContentType.IndexOf("charset=", StringComparison.OrdinalIgnoreCase) == -1)
{
// Enable UTF-8 charset
method.RequestContentType += "; charset=utf-8";
}
// if the method produces xml, make sure that the method knows that.
method.ResponseContentTypes = _effectiveProduces.ToArray();
method.Description = _operation.Description;
method.Summary = _operation.Summary;
method.ExternalDocsUrl = _operation.ExternalDocs?.Url;
method.Deprecated = _operation.Deprecated;
// Service parameters
if (_operation.Parameters != null)
{
BuildMethodParameters(method);
}
// Directly requested header types (x-ms-headers)
var headerTypeReferences = new List<IModelType>();
var headerTypeName = $"{methodGroup}-{methodName}-Headers".Trim('-');
// Build header object
var responseHeaders = new Dictionary<string, Header>();
foreach (var response in _operation.Responses.Values)
{
var xMsHeaders = response.Extensions?.GetValue<JObject>("x-ms-headers");
if (xMsHeaders != null)
{
var schema =
xMsHeaders.ToObject<Schema>(JsonSerializer.Create(new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore
}));
headerTypeReferences.Add(schema.GetBuilder(_swaggerModeler).BuildServiceType(headerTypeName));
}
else
{
response.Headers?.ForEach(h => responseHeaders[h.Key] = h.Value);
}
}
headerTypeReferences = headerTypeReferences.Distinct().ToList();
CompositeType headerType;
if (headerTypeReferences.Count == 0)
{
headerType = New<CompositeType>(headerTypeName, new
{
SerializedName = headerTypeName,
RealPath = new[] {headerTypeName},
Documentation = $"Defines headers for {methodName} operation."
});
foreach (var h in responseHeaders)
{
if (h.Value.Extensions != null && h.Value.Extensions.ContainsKey("x-ms-header-collection-prefix"))
{
var property = New<Property>(new
{
Name = h.Key,
SerializedName = h.Key,
RealPath = new[] {h.Key},
Extensions = h.Value.Extensions,
ModelType = New<DictionaryType>(new
{
ValueType = h.Value.GetBuilder(this._swaggerModeler).BuildServiceType(h.Key)
})
});
headerType.Add(property);
}
else
{
var property = New<Property>(new
{
Name = h.Key,
SerializedName = h.Key,
RealPath = new[] {h.Key},
ModelType = h.Value.GetBuilder(this._swaggerModeler).BuildServiceType(h.Key),
Documentation = h.Value.Description
});
headerType.Add(property);
}
};
}
else if (headerTypeReferences.Count == 1
&& headerTypeReferences[0] is CompositeType singleType
&& responseHeaders.Count == 0)
{
headerType = singleType;
}
else
{
Logger.Instance.Log(Category.Error, "Detected invalid reference(s) to response header types." +
" 1) All references must point to the very same type." +
" 2) That type must be an object type (i.e. no array or primitive type)." +
" 3) No response may only define classical `headers`.");
throw new CodeGenerationException("Invalid response header types.");
}
if (!headerType.Properties.Any())
{
headerType = null;
}
// Response format
List<Stack<IModelType>> typesList = BuildResponses(method, headerType);
method.ReturnType = BuildMethodReturnType(typesList, headerType);
if (method.Responses.Count == 0)
{
method.ReturnType = method.DefaultResponse;
}
if (method.ReturnType.Headers != null)
{
_swaggerModeler.CodeModel.AddHeader(method.ReturnType.Headers as CompositeType);
}
// Copy extensions
_operation.Extensions.ForEach(extention => method.Extensions.Add(extention.Key, extention.Value));
return method;
}
private static IEnumerable<SwaggerParameter> DeduplicateParameters(IEnumerable<SwaggerParameter> parameters)
{
return parameters
.Select(s =>
{
// if parameter with the same name exists in Body and Path/Query then we need to give it a unique name
if (s.In == ParameterLocation.Body)
{
string newName = s.Name;
while (parameters.Any(t => t.In != ParameterLocation.Body &&
string.Equals(t.Name, newName,
StringComparison.OrdinalIgnoreCase)))
{
newName += "Body";
}
s.Name = newName;
}
// if parameter with same name exists in Query and Path, make Query one required
if (s.In == ParameterLocation.Query &&
parameters.Any(t => t.In == ParameterLocation.Path &&
t.Name.EqualsIgnoreCase(s.Name)))
{
s.IsRequired = true;
}
return s;
});
}
private static void BuildMethodReturnTypeStack(IModelType type, List<Stack<IModelType>> types)
{
var typeStack = new Stack<IModelType>();
typeStack.Push(type);
types.Add(typeStack);
}
private void BuildMethodParameters(Method method)
{
foreach (var swaggerParameter in DeduplicateParameters(_operation.Parameters))
{
var parameter = ((ParameterBuilder)swaggerParameter.GetBuilder(_swaggerModeler)).Build();
var actualSwaggerParameter = _swaggerModeler.Unwrap(swaggerParameter);
if (parameter.IsContentTypeHeader){
// you have to specify the content type, even if the OpenAPI definition claims it's optional
parameter.IsRequired = true;
// enrich Content-Type header with "consumes"
if (actualSwaggerParameter.Enum == null &&
swaggerParameter.Extensions.GetValue<JObject>("x-ms-enum") == null &&
_effectiveConsumes.Count > 1)
{
actualSwaggerParameter.Enum = _effectiveConsumes.ToList();
actualSwaggerParameter.Extensions["x-ms-enum"] =
JObject.FromObject(new
{
name = "ContentType",
modelAsString = false
});
parameter = ((ParameterBuilder)actualSwaggerParameter.GetBuilder(_swaggerModeler)).Build();
}
}
method.Add(parameter);
CollectionFormatBuilder.OnBuildMethodParameter(method, swaggerParameter, new StringBuilder(parameter.Name));
}
}
private List<Stack<IModelType>> BuildResponses(Method method, CompositeType headerType)
{
string methodName = method.Name;
var typesList = new List<Stack<IModelType>>();
foreach (var response in _operation.Responses)
{
if (response.Key.EqualsIgnoreCase("default"))
{
TryBuildDefaultResponse(methodName, response.Value, method, headerType);
}
else
{
if (
!(TryBuildResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method,
typesList, headerType) ||
TryBuildStreamResponse(response.Key.ToHttpStatusCode(), response.Value, method, typesList, headerType) ||
TryBuildEmptyResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method,
typesList, headerType)))
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture,
Resources.UnsupportedMimeTypeForResponseBody,
methodName,
response.Key));
}
method.Responses[response.Key.ToHttpStatusCode()].Extensions = response.Value.Extensions;
}
}
return typesList;
}
private Response BuildMethodReturnType(List<Stack<IModelType>> types, IModelType headerType)
{
IModelType baseType = New<PrimaryType>(KnownPrimaryType.Object);
// Return null if no response is specified
if (types.Count == 0)
{
return new Response(null, headerType);
}
// Return first if only one return type
if (types.Count == 1)
{
return new Response(types.First().Pop(), headerType);
}
// BuildParameter up type inheritance tree
types.ForEach(typeStack =>
{
IModelType type = typeStack.Peek();
while (!Equals(type, baseType))
{
if (type is CompositeType && _swaggerModeler.ExtendedTypes.ContainsKey(type.Name.RawValue))
{
type = _swaggerModeler.GeneratedTypes[_swaggerModeler.ExtendedTypes[type.Name.RawValue]];
}
else
{
type = baseType;
}
typeStack.Push(type);
}
});
// Eliminate commonly shared base classes
while (!types.First().IsNullOrEmpty())
{
IModelType currentType = types.First().Peek();
foreach (var typeStack in types)
{
IModelType t = typeStack.Pop();
if (!t.StructurallyEquals(currentType))
{
return new Response(baseType, headerType);
}
}
baseType = currentType;
}
return new Response(baseType, headerType);
}
private bool TryBuildStreamResponse(HttpStatusCode responseStatusCode, OperationResponse response,
Method method, List<Stack<IModelType>> types, IModelType headerType)
{
bool handled = false;
if (SwaggerOperationProducesNotEmpty())
{
if (response.Schema != null)
{
IModelType serviceType = response.Schema.GetBuilder(_swaggerModeler)
.BuildServiceType(response.Schema.Reference.StripDefinitionPath());
Debug.Assert(serviceType != null);
BuildMethodReturnTypeStack(serviceType, types);
var compositeType = serviceType as CompositeType;
if (compositeType != null)
{
VerifyFirstPropertyIsByteArray(compositeType);
}
method.Responses[responseStatusCode] = new Response(serviceType, headerType);
handled = true;
}
}
return handled;
}
private void VerifyFirstPropertyIsByteArray(CompositeType serviceType)
{
var referenceKey = serviceType.Name.RawValue;
var responseType = _swaggerModeler.GeneratedTypes[referenceKey];
var property = responseType.Properties.FirstOrDefault(p => p.ModelType is PrimaryType && ((PrimaryType)p.ModelType).KnownPrimaryType == KnownPrimaryType.ByteArray);
if (property == null)
{
throw new KeyNotFoundException(
"Please specify a field with type of System.Byte[] to deserialize the file contents to");
}
}
private bool TryBuildResponse(string methodName, HttpStatusCode responseStatusCode,
OperationResponse response, Method method, List<Stack<IModelType>> types, IModelType headerType)
{
bool handled = false;
IModelType serviceType;
if (SwaggerOperationProducesSomethingDeserializable())
{
if (TryBuildResponseBody(methodName, response,
s => GenerateResponseObjectName(s, responseStatusCode), out serviceType))
{
method.Responses[responseStatusCode] = new Response(serviceType, headerType);
BuildMethodReturnTypeStack(serviceType, types);
handled = true;
}
}
return handled;
}
private bool TryBuildEmptyResponse(string methodName, HttpStatusCode responseStatusCode,
OperationResponse response, Method method, List<Stack<IModelType>> types, IModelType headerType)
{
bool handled = false;
if (response.Schema == null)
{
method.Responses[responseStatusCode] = new Response(null, headerType);
handled = true;
}
else
{
if (_operation.Produces.IsNullOrEmpty())
{
method.Responses[responseStatusCode] = new Response(New<PrimaryType>(KnownPrimaryType.Object), headerType);
BuildMethodReturnTypeStack(New<PrimaryType>(KnownPrimaryType.Object), types);
handled = true;
}
var unwrapedSchemaProperties =
_swaggerModeler.Resolver.Unwrap(response.Schema).Properties;
if (unwrapedSchemaProperties != null && unwrapedSchemaProperties.Any())
{
Logger.Instance.Log(Category.Warning, Resources.NoProduceOperationWithBody,
methodName);
}
}
return handled;
}
private void TryBuildDefaultResponse(string methodName, OperationResponse response, Method method, IModelType headerType)
{
IModelType errorModel = null;
if (SwaggerOperationProducesSomethingDeserializable())
{
if (TryBuildResponseBody(methodName, response, s => GenerateErrorModelName(s), out errorModel))
{
method.DefaultResponse = new Response(errorModel, headerType);
method.DefaultResponse.Extensions = response.Extensions;
}
}
}
private bool TryBuildResponseBody(string methodName, OperationResponse response,
Func<string, string> typeNamer, out IModelType responseType)
{
bool handled = false;
responseType = null;
if (SwaggerOperationProducesSomethingDeserializable())
{
if (response.Schema != null)
{
string referenceKey;
if (response.Schema.Reference != null)
{
referenceKey = response.Schema.Reference.StripDefinitionPath();
response.Schema.Reference = referenceKey;
}
else
{
referenceKey = typeNamer(methodName);
}
responseType = response.Schema.GetBuilder(_swaggerModeler).BuildServiceType(referenceKey);
handled = true;
}
}
return handled;
}
private bool SwaggerOperationProducesSomethingDeserializable()
{
return true == _effectiveProduces?.Any(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase) || s.StartsWith(APP_XML_MIME, StringComparison.OrdinalIgnoreCase));
}
private bool SwaggerOperationProducesNotEmpty() => true == _effectiveProduces?.Any();
private void EnsureUniqueMethodName(string methodName, string methodGroup)
{
string serviceOperationPrefix = "";
if (methodGroup != null)
{
serviceOperationPrefix = methodGroup + "_";
}
if (_swaggerModeler.CodeModel.Methods.Any(m => m.Group == methodGroup && m.Name == methodName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
Resources.DuplicateOperationIdException,
serviceOperationPrefix + methodName));
}
}
private static string GenerateResponseObjectName(string methodName, HttpStatusCode responseStatusCode)
{
return string.Format(CultureInfo.InvariantCulture,
"{0}{1}Response", methodName, responseStatusCode);
}
private static string GenerateErrorModelName(string methodName)
{
return string.Format(CultureInfo.InvariantCulture,
"{0}ErrorModel", methodName);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace WingroveAudio
{
[AddComponentMenu("WingroveAudio/Wingrove Root")]
public class WingroveRoot : MonoBehaviour
{
public static IEnumerator WaitForInstance()
{
while (Instance == null)
{
yield return null;
}
}
static WingroveRoot s_instance;
[SerializeField]
private bool m_useDecibelScale = true;
[SerializeField]
private bool m_allowMultipleListeners = false;
public enum MultipleListenerPositioningModel
{
InverseSquareDistanceWeighted
}
[SerializeField]
private AudioRolloffMode m_defaultRolloffMode = AudioRolloffMode.Linear;
[SerializeField]
private float m_defaultMaxDistance = 100.0f;
[SerializeField]
private float m_defaultMinDistance = 1.0f;
[SerializeField]
private MultipleListenerPositioningModel m_listeningModel = MultipleListenerPositioningModel.InverseSquareDistanceWeighted;
private GUISkin m_editorSkin;
public static WingroveRoot Instance
{
get
{
if (s_instance == null)
{
s_instance = (WingroveRoot)GameObject.FindObjectOfType(typeof(WingroveRoot));
}
return s_instance;
}
}
[SerializeField]
private int m_audioSourcePoolSize = 32;
[SerializeField]
private int m_calculateRMSIntervalFrames = 1;
[SerializeField]
private bool m_useDSPTime = true;
private int m_rmsFrame;
private static double m_lastDSPTime;
private static double m_dspDeltaTime;
public class AudioSourcePoolItem
{
public AudioSource m_audioSource;
public ActiveCue m_user;
public int m_index;
}
List<AudioSourcePoolItem> m_audioSourcePool = new List<AudioSourcePoolItem>();
Dictionary<string, List<BaseEventReceiveAction>> m_eventReceivers = new Dictionary<string, List<BaseEventReceiveAction>>();
[SerializeField]
public EventGroup[] m_eventGroups;
private List<WingroveListener> m_listeners = new List<WingroveListener>();
class ParameterValues
{
public Dictionary<string, float> m_parameterValues = new Dictionary<string, float>();
}
ParameterValues m_globalValues = new ParameterValues();
Dictionary<GameObject, ParameterValues> m_objectValues = new Dictionary<GameObject, ParameterValues>();
#if UNITY_EDITOR
public class LoggedEvent
{
public string m_eventName = null;
public GameObject m_linkedObject = null;
public double m_time;
}
private List<LoggedEvent> m_loggedEvents = new List<LoggedEvent>();
private int m_maxEvents = 50;
private double m_startTime;
public void LogEvent(string eventName, GameObject linkedObject)
{
LoggedEvent lge = new LoggedEvent();
lge.m_eventName = eventName;
lge.m_linkedObject = linkedObject;
lge.m_time = AudioSettings.dspTime - m_startTime;
m_loggedEvents.Add(lge);
if (m_loggedEvents.Count > m_maxEvents)
{
m_loggedEvents.RemoveAt(0);
}
}
public List<LoggedEvent> GetLogList()
{
return m_loggedEvents;
}
#endif
// Use this for initialization
void Awake()
{
s_instance = this;
GameObject pool = new GameObject("AudioSourcePool");
pool.transform.parent = transform;
for (int i = 0; i < m_audioSourcePoolSize; ++i)
{
GameObject newAudioSource = new GameObject("PooledAudioSource");
newAudioSource.transform.parent = pool.transform;
AudioSource aSource = newAudioSource.AddComponent<AudioSource>();
AudioSourcePoolItem aspi = new AudioSourcePoolItem();
aspi.m_audioSource = aSource;
aSource.enabled = false;
aSource.rolloffMode = m_defaultRolloffMode;
aSource.maxDistance = m_defaultMaxDistance;
aSource.minDistance = m_defaultMinDistance;
aspi.m_index = i;
m_audioSourcePool.Add(aspi);
}
BaseEventReceiveAction[] evrs = GetComponentsInChildren<BaseEventReceiveAction>();
foreach (BaseEventReceiveAction evr in evrs)
{
string[] events = evr.GetEvents();
if (events != null)
{
foreach (string ev in events)
{
if (!m_eventReceivers.ContainsKey(ev))
{
m_eventReceivers[ev] = new List<BaseEventReceiveAction>();
}
m_eventReceivers[ev].Add(evr);
}
}
}
gameObject.AddComponent<AudioListener>();
transform.position = Vector3.zero;
m_lastDSPTime = AudioSettings.dspTime;
#if UNITY_EDITOR
m_startTime = AudioSettings.dspTime;
#endif
}
public void SetDefault3DSettings(AudioSource aSource)
{
aSource.rolloffMode = m_defaultRolloffMode;
aSource.maxDistance = m_defaultMaxDistance;
aSource.minDistance = m_defaultMinDistance;
}
public float GetParameterForGameObject(string parameter, GameObject go)
{
float result = 0.0f;
if ( go == null )
{
m_globalValues.m_parameterValues.TryGetValue(parameter, out result);
}
else
{
ParameterValues pv = null;
if ( m_objectValues.TryGetValue(go, out pv) )
{
if ( !(pv.m_parameterValues.TryGetValue(parameter, out result)) )
{
m_globalValues.m_parameterValues.TryGetValue(parameter, out result);
}
}
else
{
m_globalValues.m_parameterValues.TryGetValue(parameter, out result);
}
}
return result;
}
public void SetParameterGlobal(string parameter, float setValue)
{
m_globalValues.m_parameterValues[parameter] = setValue;
}
public void SetParameterForObject(string parameter, GameObject go, float setValue)
{
ParameterValues pv = null;
if (!m_objectValues.TryGetValue(go, out pv))
{
pv = m_objectValues[go] = new ParameterValues();
}
pv.m_parameterValues[parameter] = setValue;
}
public bool UseDBScale
{
get { return m_useDecibelScale; }
set { m_useDecibelScale = value; }
}
//StoredImportSettings m_storedImportSettings;
//public bool Is3D(string path)
//{
// if (m_storedImportSettings == null)
// {
// m_storedImportSettings = (StoredImportSettings)Resources.Load("ImportSettings");
// }
// return m_storedImportSettings.Is3D(path);
//}
public int FindEvent(string eventName)
{
int index = 0;
foreach (EventGroup eg in m_eventGroups)
{
if (eg != null && eg.m_events != null)
{
foreach (string st in eg.m_events)
{
if (st == eventName)
{
return index;
}
}
}
++index;
}
return -1;
}
public GUISkin GetSkin()
{
if (m_editorSkin == null)
{
m_editorSkin = (GUISkin)Resources.Load("WingroveAudioSkin");
}
return m_editorSkin;
}
public void PostEvent(string eventName)
{
PostEventCL(eventName, (List<ActiveCue>)null, null);
}
public void PostEventCL(string eventName, List<ActiveCue> cuesIn)
{
PostEventCL(eventName, cuesIn, null);
}
public void PostEventGO(string eventName, GameObject targetObject)
{
PostEventGO(eventName, targetObject, null);
}
public void PostEventGO(string eventName, GameObject targetObject, List<ActiveCue> cuesOut)
{
#if UNITY_EDITOR
LogEvent(eventName, targetObject);
#endif
List<BaseEventReceiveAction> listOfReceivers = null;
if (m_eventReceivers.TryGetValue(eventName, out listOfReceivers))
{
foreach (BaseEventReceiveAction evr in listOfReceivers)
{
evr.PerformAction(eventName, targetObject, cuesOut);
}
}
}
public void PostEventCL(string eventName, List<ActiveCue> cuesIn, List<ActiveCue> cuesOut)
{
#if UNITY_EDITOR
LogEvent(eventName, null);
#endif
List<BaseEventReceiveAction> listOfReceivers = null;
if (m_eventReceivers.TryGetValue(eventName, out listOfReceivers))
{
foreach (BaseEventReceiveAction evr in listOfReceivers)
{
evr.PerformAction(eventName, cuesIn, cuesOut);
}
}
}
public AudioSourcePoolItem TryClaimPoolSource(ActiveCue cue)
{
AudioSourcePoolItem bestSteal = null;
int lowestImportance = cue.GetImportance();
float quietestSimilarImportance = 1.0f;
foreach (AudioSourcePoolItem aspi in m_audioSourcePool)
{
if (aspi.m_user == null)
{
aspi.m_user = cue;
return aspi;
}
else
{
if (aspi.m_user.GetImportance() < cue.GetImportance())
{
if (aspi.m_user.GetImportance() < lowestImportance)
{
lowestImportance = aspi.m_user.GetImportance();
bestSteal = aspi;
}
}
else if (aspi.m_user.GetImportance() == lowestImportance)
{
if (aspi.m_user.GetTheoreticalVolume() < quietestSimilarImportance)
{
quietestSimilarImportance = aspi.m_user.GetTheoreticalVolume();
bestSteal = aspi;
}
}
}
}
if (bestSteal != null)
{
bestSteal.m_user.Virtualise();
bestSteal.m_user = cue;
return bestSteal;
}
return null;
}
public void UnlinkSource(AudioSourcePoolItem item)
{
//item.m_audioSource.Stop();
//item.m_audioSource.enabled = false;
//item.m_audioSource.clip = null;
// flush test
GameObject go = item.m_audioSource.gameObject;
Destroy(item.m_audioSource);
item.m_audioSource = go.AddComponent<AudioSource>();
item.m_audioSource.enabled = false;
item.m_audioSource.rolloffMode = m_defaultRolloffMode;
item.m_audioSource.maxDistance = m_defaultMaxDistance;
item.m_audioSource.minDistance = m_defaultMinDistance;
item.m_user = null;
}
public string dbStringUtil(float amt)
{
string result = "";
float dbMix = 20 * Mathf.Log10(amt);
if (dbMix == 0)
{
result = "-0.00 dB";
}
else if (float.IsInfinity(dbMix))
{
result = "-inf dB";
}
else
{
result = System.String.Format("{0:0.00}", dbMix) + " dB";
}
return result;
}
public bool ShouldCalculateMS(int index)
{
if (m_calculateRMSIntervalFrames <= 1)
{
return true;
}
if ((index % m_calculateRMSIntervalFrames)
== m_rmsFrame)
{
return true;
}
else
{
return false;
}
}
void Update()
{
m_rmsFrame++;
if (m_rmsFrame >= m_calculateRMSIntervalFrames)
{
m_rmsFrame = 0;
}
if (m_useDSPTime)
{
m_dspDeltaTime = AudioSettings.dspTime - m_lastDSPTime;
}
else
{
m_dspDeltaTime = Time.deltaTime;
}
m_lastDSPTime = AudioSettings.dspTime;
}
public static float GetDeltaTime()
{
return (float)m_dspDeltaTime;
}
public void RegisterListener(WingroveListener listener)
{
m_listeners.Add(listener);
}
public void UnregisterListener(WingroveListener listener)
{
m_listeners.Remove(listener);
}
public Vector3 GetRelativeListeningPosition(Vector3 inPosition)
{
int listenerCount = m_listeners.Count;
if (!m_allowMultipleListeners || listenerCount <= 1)
{
if (listenerCount == 0)
{
return inPosition;
}
return m_listeners[0].transform.worldToLocalMatrix * new Vector4(inPosition.x, inPosition.y, inPosition.z, 1.0f);
//return inPosition - m_listeners[0].transform.position;
}
else
{
if (m_listeningModel == MultipleListenerPositioningModel.InverseSquareDistanceWeighted)
{
float totalWeight = 0;
Vector3 totalPosition = Vector3.zero;
foreach (WingroveListener listener in m_listeners)
{
Vector3 dist = inPosition - listener.transform.position;
if (dist.magnitude == 0)
{
// early out if one is right here
return Vector3.zero;
}
else
{
float weight = 1 / (dist.magnitude * dist.magnitude);
totalWeight += weight;
totalPosition += (Vector3)(listener.transform.worldToLocalMatrix * new Vector4(inPosition.x, inPosition.y, inPosition.z, 1.0f)) * weight;
}
}
totalPosition /= totalWeight;
return totalPosition;
}
return Vector3.zero;
}
}
}
}
| |
// 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.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net.Sockets
{
internal static class SocketPal
{
public const bool SupportsMultipleConnectAttempts = true;
private static void MicrosecondsToTimeValue(long microseconds, ref Interop.Winsock.TimeValue socketTime)
{
const int microcnv = 1000000;
socketTime.Seconds = (int)(microseconds / microcnv);
socketTime.Microseconds = (int)(microseconds % microcnv);
}
public static void Initialize()
{
// Ensure that WSAStartup has been called once per process.
// The System.Net.NameResolution contract is responsible for the initialization.
Dns.GetHostName();
}
public static SocketError GetLastSocketError()
{
int win32Error = Marshal.GetLastWin32Error();
Debug.Assert(win32Error != 0, "Expected non-0 error");
return (SocketError)win32Error;
}
public static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeSocketHandle socket)
{
socket = SafeSocketHandle.CreateWSASocket(addressFamily, socketType, protocolType);
return socket.IsInvalid ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetBlocking(SafeSocketHandle handle, bool shouldBlock, out bool willBlock)
{
int intBlocking = shouldBlock ? 0 : -1;
SocketError errorCode;
errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONBIO,
ref intBlocking);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
willBlock = intBlocking == 0;
return errorCode;
}
public static SocketError GetSockName(SafeSocketHandle handle, byte[] buffer, ref int nameLen)
{
SocketError errorCode = Interop.Winsock.getsockname(handle, buffer, ref nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetAvailable(SafeSocketHandle handle, out int available)
{
int value = 0;
SocketError errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONREAD,
ref value);
available = value;
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetPeerName(SafeSocketHandle handle, byte[] buffer, ref int nameLen)
{
SocketError errorCode = Interop.Winsock.getpeername(handle, buffer, ref nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Bind(SafeSocketHandle handle, ProtocolType socketProtocolType, byte[] buffer, int nameLen)
{
SocketError errorCode = Interop.Winsock.bind(handle, buffer, nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Listen(SafeSocketHandle handle, int backlog)
{
SocketError errorCode = Interop.Winsock.listen(handle, backlog);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Accept(SafeSocketHandle handle, byte[] buffer, ref int nameLen, out SafeSocketHandle socket)
{
socket = SafeSocketHandle.Accept(handle, buffer, ref nameLen);
return socket.IsInvalid ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Connect(SafeSocketHandle handle, byte[] peerAddress, int peerAddressLen)
{
SocketError errorCode = Interop.Winsock.WSAConnect(
handle.DangerousGetHandle(),
peerAddress,
peerAddressLen,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Send(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out int bytesTransferred)
{
const int StackThreshold = 16; // arbitrary limit to avoid too much space on stack (note: may be over-sized, that's OK - length passed separately)
int count = buffers.Count;
bool useStack = count <= StackThreshold;
WSABuffer[] leasedWSA = null;
GCHandle[] leasedGC = null;
Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0];
Span<GCHandle> objectsToPin = stackalloc GCHandle[0];
if (useStack)
{
WSABuffers = stackalloc WSABuffer[StackThreshold];
objectsToPin = stackalloc GCHandle[StackThreshold];
}
else
{
WSABuffers = leasedWSA = ArrayPool<WSABuffer>.Shared.Rent(count);
objectsToPin = leasedGC = ArrayPool<GCHandle>.Shared.Rent(count);
}
objectsToPin = objectsToPin.Slice(0, count);
objectsToPin.Clear(); // note: touched in finally
try
{
for (int i = 0; i < count; ++i)
{
ArraySegment<byte> buffer = buffers[i];
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
}
unsafe
{
SocketError errorCode = Interop.Winsock.WSASend(
handle.DangerousGetHandle(),
WSABuffers,
count,
out bytesTransferred,
socketFlags,
null,
IntPtr.Zero);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
finally
{
for (int i = 0; i < count; ++i)
{
if (objectsToPin[i].IsAllocated)
{
objectsToPin[i].Free();
}
}
if (!useStack)
{
ArrayPool<WSABuffer>.Shared.Return(leasedWSA);
ArrayPool<GCHandle>.Shared.Return(leasedGC);
}
}
}
public static unsafe SocketError Send(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) =>
Send(handle, new ReadOnlySpan<byte>(buffer, offset, size), socketFlags, out bytesTransferred);
public static unsafe SocketError Send(SafeSocketHandle handle, ReadOnlySpan<byte> buffer, SocketFlags socketFlags, out int bytesTransferred)
{
int bytesSent;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
bytesSent = Interop.Winsock.send(handle.DangerousGetHandle(), bufferPtr, buffer.Length, socketFlags);
}
if (bytesSent == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesSent;
return SocketError.Success;
}
public static unsafe SocketError SendFile(SafeSocketHandle handle, SafeFileHandle fileHandle, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
{
fixed (byte* prePinnedBuffer = preBuffer)
fixed (byte* postPinnedBuffer = postBuffer)
{
bool success = TransmitFileHelper(handle, fileHandle, null, preBuffer, postBuffer, flags);
return (success ? SocketError.Success : SocketPal.GetLastSocketError());
}
}
public static unsafe SocketError SendTo(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] peerAddress, int peerAddressSize, out int bytesTransferred)
{
int bytesSent;
if (buffer.Length == 0)
{
bytesSent = Interop.Winsock.sendto(
handle.DangerousGetHandle(),
null,
0,
socketFlags,
peerAddress,
peerAddressSize);
}
else
{
fixed (byte* pinnedBuffer = &buffer[0])
{
bytesSent = Interop.Winsock.sendto(
handle.DangerousGetHandle(),
pinnedBuffer + offset,
size,
socketFlags,
peerAddress,
peerAddressSize);
}
}
if (bytesSent == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesSent;
return SocketError.Success;
}
public static SocketError Receive(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, ref SocketFlags socketFlags, out int bytesTransferred)
{
const int StackThreshold = 16; // arbitrary limit to avoid too much space on stack (note: may be over-sized, that's OK - length passed separately)
int count = buffers.Count;
bool useStack = count <= StackThreshold;
WSABuffer[] leasedWSA = null;
GCHandle[] leasedGC = null;
Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0];
Span<GCHandle> objectsToPin = stackalloc GCHandle[0];
if (useStack)
{
WSABuffers = stackalloc WSABuffer[StackThreshold];
objectsToPin = stackalloc GCHandle[StackThreshold];
}
else
{
WSABuffers = leasedWSA = ArrayPool<WSABuffer>.Shared.Rent(count);
objectsToPin = leasedGC = ArrayPool<GCHandle>.Shared.Rent(count);
}
objectsToPin = objectsToPin.Slice(0, count);
objectsToPin.Clear(); // note: touched in finally
try
{
for (int i = 0; i < count; ++i)
{
ArraySegment<byte> buffer = buffers[i];
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
}
unsafe
{
SocketError errorCode = Interop.Winsock.WSARecv(
handle.DangerousGetHandle(),
WSABuffers,
count,
out bytesTransferred,
ref socketFlags,
null,
IntPtr.Zero);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
finally
{
for (int i = 0; i < count; ++i)
{
if (objectsToPin[i].IsAllocated)
{
objectsToPin[i].Free();
}
}
if (!useStack)
{
ArrayPool<WSABuffer>.Shared.Return(leasedWSA);
ArrayPool<GCHandle>.Shared.Return(leasedGC);
}
}
}
public static unsafe SocketError Receive(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) =>
Receive(handle, new Span<byte>(buffer, offset, size), socketFlags, out bytesTransferred);
public static unsafe SocketError Receive(SafeSocketHandle handle, Span<byte> buffer, SocketFlags socketFlags, out int bytesTransferred)
{
int bytesReceived;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
bytesReceived = Interop.Winsock.recv(handle.DangerousGetHandle(), bufferPtr, buffer.Length, socketFlags);
}
if (bytesReceived == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesReceived;
return SocketError.Success;
}
public static unsafe IPPacketInformation GetIPPacketInformation(Interop.Winsock.ControlData* controlBuffer)
{
IPAddress address = controlBuffer->length == UIntPtr.Zero ? IPAddress.None : new IPAddress((long)controlBuffer->address);
return new IPPacketInformation(address, (int)controlBuffer->index);
}
public static unsafe IPPacketInformation GetIPPacketInformation(Interop.Winsock.ControlDataIPv6* controlBuffer)
{
IPAddress address = controlBuffer->length != UIntPtr.Zero ?
new IPAddress(new ReadOnlySpan<byte>(controlBuffer->address, Interop.Winsock.IPv6AddressLength)) :
IPAddress.IPv6None;
return new IPPacketInformation(address, (int)controlBuffer->index);
}
public static unsafe SocketError ReceiveMessageFrom(Socket socket, SafeSocketHandle handle, byte[] buffer, int offset, int size, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
{
bool ipv4, ipv6;
Socket.GetIPProtocolInformation(socket.AddressFamily, socketAddress, out ipv4, out ipv6);
bytesTransferred = 0;
receiveAddress = socketAddress;
ipPacketInformation = default(IPPacketInformation);
fixed (byte* ptrBuffer = buffer)
fixed (byte* ptrSocketAddress = socketAddress.Buffer)
{
Interop.Winsock.WSAMsg wsaMsg;
wsaMsg.socketAddress = (IntPtr)ptrSocketAddress;
wsaMsg.addressLength = (uint)socketAddress.Size;
wsaMsg.flags = socketFlags;
WSABuffer wsaBuffer;
wsaBuffer.Length = size;
wsaBuffer.Pointer = (IntPtr)(ptrBuffer + offset);
wsaMsg.buffers = (IntPtr)(&wsaBuffer);
wsaMsg.count = 1;
if (ipv4)
{
Interop.Winsock.ControlData controlBuffer;
wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer);
wsaMsg.controlBuffer.Length = sizeof(Interop.Winsock.ControlData);
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
(IntPtr)(&wsaMsg),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
return GetLastSocketError();
}
ipPacketInformation = GetIPPacketInformation(&controlBuffer);
}
else if (ipv6)
{
Interop.Winsock.ControlDataIPv6 controlBuffer;
wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer);
wsaMsg.controlBuffer.Length = sizeof(Interop.Winsock.ControlDataIPv6);
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
(IntPtr)(&wsaMsg),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
return GetLastSocketError();
}
ipPacketInformation = GetIPPacketInformation(&controlBuffer);
}
else
{
wsaMsg.controlBuffer.Pointer = IntPtr.Zero;
wsaMsg.controlBuffer.Length = 0;
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
(IntPtr)(&wsaMsg),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
return GetLastSocketError();
}
}
socketFlags = wsaMsg.flags;
}
return SocketError.Success;
}
public static unsafe SocketError ReceiveFrom(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] socketAddress, ref int addressLength, out int bytesTransferred)
{
int bytesReceived;
if (buffer.Length == 0)
{
bytesReceived = Interop.Winsock.recvfrom(handle.DangerousGetHandle(), null, 0, socketFlags, socketAddress, ref addressLength);
}
else
{
fixed (byte* pinnedBuffer = &buffer[0])
{
bytesReceived = Interop.Winsock.recvfrom(handle.DangerousGetHandle(), pinnedBuffer + offset, size, socketFlags, socketAddress, ref addressLength);
}
}
if (bytesReceived == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesReceived;
return SocketError.Success;
}
public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength)
{
if (ioControlCode == Interop.Winsock.IoctlSocketConstants.FIONBIO)
{
throw new InvalidOperationException(SR.net_sockets_useblocking);
}
SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking(
handle.DangerousGetHandle(),
ioControlCode,
optionInValue,
optionInValue != null ? optionInValue.Length : 0,
optionOutValue,
optionOutValue != null ? optionOutValue.Length : 0,
out optionLength,
IntPtr.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static unsafe SocketError SetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
SocketError errorCode;
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) &&
IOControlKeepAlive.IsNeeded)
{
errorCode = IOControlKeepAlive.Set(handle, optionName, optionValue);
}
else
{
errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
ref optionValue,
sizeof(int));
}
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
SocketError errorCode;
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) &&
IOControlKeepAlive.IsNeeded)
{
return IOControlKeepAlive.Set(handle, optionName, optionValue);
}
else
{
errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
optionValue,
optionValue != null ? optionValue.Length : 0);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
}
public static void SetReceivingDualModeIPv4PacketInformation(Socket socket)
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
}
public static SocketError SetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, MulticastOption optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest();
#pragma warning disable CS0618 // Address is marked obsolete
ipmr.MulticastAddress = unchecked((int)optionValue.Group.Address);
#pragma warning restore CS0618
if (optionValue.LocalAddress != null)
{
#pragma warning disable CS0618 // Address is marked obsolete
ipmr.InterfaceAddress = unchecked((int)optionValue.LocalAddress.Address);
#pragma warning restore CS0618
}
else
{ //this structure works w/ interfaces as well
int ifIndex = IPAddress.HostToNetworkOrder(optionValue.InterfaceIndex);
ipmr.InterfaceAddress = unchecked((int)ifIndex);
}
#if BIGENDIAN
ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) |
(((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) |
(((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) |
((uint) ipmr.MulticastAddress >> 24));
if (optionValue.LocalAddress != null)
{
ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) |
(((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) |
(((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) |
((uint) ipmr.InterfaceAddress >> 24));
}
#endif
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.IP,
optionName,
ref ipmr,
Interop.Winsock.IPMulticastRequest.Size);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, IPv6MulticastOption optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest();
ipmr.MulticastAddress = optionValue.Group.GetAddressBytes();
ipmr.InterfaceIndex = unchecked((int)optionValue.InterfaceIndex);
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.IPv6,
optionName,
ref ipmr,
Interop.Winsock.IPv6MulticastRequest.Size);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetLingerOption(SafeSocketHandle handle, LingerOption optionValue)
{
Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger();
lngopt.OnOff = optionValue.Enabled ? (ushort)1 : (ushort)0;
lngopt.Time = (ushort)optionValue.LingerTime;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
ref lngopt,
4);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static void SetIPProtectionLevel(Socket socket, SocketOptionLevel optionLevel, int protectionLevel)
{
socket.SetSocketOption(optionLevel, SocketOptionName.IPProtectionLevel, protectionLevel);
}
public static SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue)
{
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) &&
IOControlKeepAlive.IsNeeded)
{
optionValue = IOControlKeepAlive.Get(handle, optionName);
return SocketError.Success;
}
int optionLength = 4; // sizeof(int)
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
optionName,
out optionValue,
ref optionLength);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue, ref int optionLength)
{
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) &&
IOControlKeepAlive.IsNeeded)
{
return IOControlKeepAlive.Get(handle, optionName, optionValue, ref optionLength);
}
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
optionName,
optionValue,
ref optionLength);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest();
int optlen = Interop.Winsock.IPMulticastRequest.Size;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.IP,
optionName,
out ipmr,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(MulticastOption);
return GetLastSocketError();
}
#if BIGENDIAN
ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) |
(((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) |
(((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) |
((uint) ipmr.MulticastAddress >> 24));
ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) |
(((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) |
(((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) |
((uint) ipmr.InterfaceAddress >> 24));
#endif // BIGENDIAN
IPAddress multicastAddr = new IPAddress(ipmr.MulticastAddress);
IPAddress multicastIntr = new IPAddress(ipmr.InterfaceAddress);
optionValue = new MulticastOption(multicastAddr, multicastIntr);
return SocketError.Success;
}
public static SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest();
int optlen = Interop.Winsock.IPv6MulticastRequest.Size;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.IP,
optionName,
out ipmr,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(IPv6MulticastOption);
return GetLastSocketError();
}
optionValue = new IPv6MulticastOption(new IPAddress(ipmr.MulticastAddress), ipmr.InterfaceIndex);
return SocketError.Success;
}
public static SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption optionValue)
{
Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger();
int optlen = 4;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
out lngopt,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(LingerOption);
return GetLastSocketError();
}
optionValue = new LingerOption(lngopt.OnOff != 0, (int)lngopt.Time);
return SocketError.Success;
}
public static unsafe SocketError Poll(SafeSocketHandle handle, int microseconds, SelectMode mode, out bool status)
{
IntPtr rawHandle = handle.DangerousGetHandle();
IntPtr* fileDescriptorSet = stackalloc IntPtr[2] { (IntPtr)1, rawHandle };
Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue();
// A negative timeout value implies an indefinite wait.
int socketCount;
if (microseconds != -1)
{
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
Interop.Winsock.select(
0,
mode == SelectMode.SelectRead ? fileDescriptorSet : null,
mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
mode == SelectMode.SelectError ? fileDescriptorSet : null,
ref IOwait);
}
else
{
socketCount =
Interop.Winsock.select(
0,
mode == SelectMode.SelectRead ? fileDescriptorSet : null,
mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
mode == SelectMode.SelectError ? fileDescriptorSet : null,
IntPtr.Zero);
}
if ((SocketError)socketCount == SocketError.SocketError)
{
status = false;
return GetLastSocketError();
}
status = (int)fileDescriptorSet[0] != 0 && fileDescriptorSet[1] == rawHandle;
return SocketError.Success;
}
public static unsafe SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds)
{
const int StackThreshold = 64; // arbitrary limit to avoid too much space on stack
bool ShouldStackAlloc(IList list, ref IntPtr[] lease, out Span<IntPtr> span)
{
int count;
if (list == null || (count = list.Count) == 0)
{
span = default;
return false;
}
if (count >= StackThreshold) // note on >= : the first element is reserved for internal length
{
span = lease = ArrayPool<IntPtr>.Shared.Rent(count + 1);
return false;
}
span = default;
return true;
}
IntPtr[] leaseRead = null, leaseWrite = null, leaseError = null;
try
{
Span<IntPtr> readfileDescriptorSet = ShouldStackAlloc(checkRead, ref leaseRead, out var tmp) ? stackalloc IntPtr[StackThreshold] : tmp;
Socket.SocketListToFileDescriptorSet(checkRead, readfileDescriptorSet);
Span<IntPtr> writefileDescriptorSet = ShouldStackAlloc(checkWrite, ref leaseWrite, out tmp) ? stackalloc IntPtr[StackThreshold] : tmp;
Socket.SocketListToFileDescriptorSet(checkWrite, writefileDescriptorSet);
Span<IntPtr> errfileDescriptorSet = ShouldStackAlloc(checkError, ref leaseError, out tmp) ? stackalloc IntPtr[StackThreshold] : tmp;
Socket.SocketListToFileDescriptorSet(checkError, errfileDescriptorSet);
// This code used to erroneously pass a non-null timeval structure containing zeroes
// to select() when the caller specified (-1) for the microseconds parameter. That
// caused select to actually have a *zero* timeout instead of an infinite timeout
// turning the operation into a non-blocking poll.
//
// Now we pass a null timeval struct when microseconds is (-1).
//
// Negative microsecond values that weren't exactly (-1) were originally successfully
// converted to a timeval struct containing unsigned non-zero integers. This code
// retains that behavior so that any app working around the original bug with,
// for example, (-2) specified for microseconds, will continue to get the same behavior.
int socketCount;
fixed (IntPtr* readPtr = &MemoryMarshal.GetReference(readfileDescriptorSet))
fixed (IntPtr* writePtr = &MemoryMarshal.GetReference(writefileDescriptorSet))
fixed (IntPtr* errPtr = &MemoryMarshal.GetReference(errfileDescriptorSet))
{
if (microseconds != -1)
{
Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue();
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
Interop.Winsock.select(
0, // ignored value
readPtr,
writePtr,
errPtr,
ref IOwait);
}
else
{
socketCount =
Interop.Winsock.select(
0, // ignored value
readPtr,
writePtr,
errPtr,
IntPtr.Zero);
}
}
if (NetEventSource.IsEnabled)
NetEventSource.Info(null, $"Interop.Winsock.select returns socketCount:{socketCount}");
if ((SocketError)socketCount == SocketError.SocketError)
{
return GetLastSocketError();
}
Socket.SelectFileDescriptor(checkRead, readfileDescriptorSet);
Socket.SelectFileDescriptor(checkWrite, writefileDescriptorSet);
Socket.SelectFileDescriptor(checkError, errfileDescriptorSet);
return SocketError.Success;
}
finally
{
if (leaseRead != null) ArrayPool<IntPtr>.Shared.Return(leaseRead);
if (leaseWrite != null) ArrayPool<IntPtr>.Shared.Return(leaseWrite);
if (leaseError != null) ArrayPool<IntPtr>.Shared.Return(leaseError);
}
}
public static SocketError Shutdown(SafeSocketHandle handle, bool isConnected, bool isDisconnected, SocketShutdown how)
{
SocketError err = Interop.Winsock.shutdown(handle, (int)how);
if (err != SocketError.SocketError)
{
return SocketError.Success;
}
err = GetLastSocketError();
Debug.Assert(err != SocketError.NotConnected || (!isConnected && !isDisconnected));
return err;
}
public static unsafe SocketError ConnectAsync(Socket socket, SafeSocketHandle handle, byte[] socketAddress, int socketAddressLen, ConnectOverlappedAsyncResult asyncResult)
{
// This will pin the socketAddress buffer.
asyncResult.SetUnmanagedStructures(socketAddress);
try
{
int ignoreBytesSent;
bool success = socket.ConnectEx(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(socketAddress, 0),
socketAddressLen,
IntPtr.Zero,
0,
out ignoreBytesSent,
asyncResult.DangerousOverlappedPointer); // SafeHandle was just created in SetUnmanagedStructures
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError SendAsync(SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up unmanaged structures for overlapped WSASend.
asyncResult.SetUnmanagedStructures(buffer, offset, count, null);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASend(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
ref asyncResult._singleBuffer,
1, // There is only ever 1 buffer being sent.
out bytesTransferred,
socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError SendAsync(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASend.
asyncResult.SetUnmanagedStructures(buffers);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASend(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
asyncResult._wsaBuffers,
asyncResult._wsaBuffers.Length,
out bytesTransferred,
socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
// This assumes preBuffer/postBuffer are pinned already
private static unsafe bool TransmitFileHelper(
SafeHandle socket,
SafeHandle fileHandle,
NativeOverlapped* overlapped,
byte[] preBuffer,
byte[] postBuffer,
TransmitFileOptions flags)
{
bool needTransmitFileBuffers = false;
Interop.Mswsock.TransmitFileBuffers transmitFileBuffers = default(Interop.Mswsock.TransmitFileBuffers);
if (preBuffer != null && preBuffer.Length > 0)
{
needTransmitFileBuffers = true;
transmitFileBuffers.Head = Marshal.UnsafeAddrOfPinnedArrayElement(preBuffer, 0);
transmitFileBuffers.HeadLength = preBuffer.Length;
}
if (postBuffer != null && postBuffer.Length > 0)
{
needTransmitFileBuffers = true;
transmitFileBuffers.Tail = Marshal.UnsafeAddrOfPinnedArrayElement(postBuffer, 0);
transmitFileBuffers.TailLength = postBuffer.Length;
}
bool success = Interop.Mswsock.TransmitFile(socket, fileHandle, 0, 0, overlapped,
needTransmitFileBuffers ? &transmitFileBuffers : null, flags);
return success;
}
public static unsafe SocketError SendFileAsync(SafeSocketHandle handle, FileStream fileStream, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, TransmitFileAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(fileStream, preBuffer, postBuffer, (flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0);
try
{
bool success = TransmitFileHelper(
handle,
fileStream?.SafeFileHandle,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
preBuffer,
postBuffer,
flags);
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError SendToAsync(SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASendTo.
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASendTo(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
ref asyncResult._singleBuffer,
1, // There is only ever 1 buffer being sent.
out bytesTransferred,
socketFlags,
asyncResult.GetSocketAddressPtr(),
asyncResult.SocketAddress.Size,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveAsync(SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSARecv.
asyncResult.SetUnmanagedStructures(buffer, offset, count, null);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecv(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
ref asyncResult._singleBuffer,
1,
out bytesTransferred,
ref socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveAsync(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASend.
asyncResult.SetUnmanagedStructures(buffers);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecv(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
asyncResult._wsaBuffers,
asyncResult._wsaBuffers.Length,
out bytesTransferred,
ref socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveFromAsync(SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSARecvFrom.
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecvFrom(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
ref asyncResult._singleBuffer,
1,
out bytesTransferred,
ref socketFlags,
asyncResult.GetSocketAddressPtr(),
asyncResult.GetSocketAddressSizePtr(),
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveMessageFromAsync(Socket socket, SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, socketFlags);
try
{
int bytesTransfered;
SocketError errorCode = (SocketError)socket.WSARecvMsg(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
out bytesTransfered,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransfered);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError AcceptAsync(Socket socket, SafeSocketHandle handle, SafeSocketHandle acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult)
{
// The buffer needs to contain the requested data plus room for two sockaddrs and 16 bytes
// of associated data for each.
int addressBufferSize = socketAddressSize + 16;
byte[] buffer = new byte[receiveSize + ((addressBufferSize) * 2)];
// Set up asyncResult for overlapped AcceptEx.
// This call will use completion ports on WinNT.
asyncResult.SetUnmanagedStructures(buffer, addressBufferSize);
try
{
// This can throw ObjectDisposedException.
int bytesTransferred;
bool success = socket.AcceptEx(
handle,
acceptHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.Buffer, 0),
receiveSize,
addressBufferSize,
addressBufferSize,
out bytesTransferred,
asyncResult.DangerousOverlappedPointer); // SafeHandle was just created in SetUnmanagedStructures
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static void CheckDualModeReceiveSupport(Socket socket)
{
// Dual-mode sockets support received packet info on Windows.
}
internal static unsafe SocketError DisconnectAsync(Socket socket, SafeSocketHandle handle, bool reuseSocket, DisconnectOverlappedAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(null);
try
{
// This can throw ObjectDisposedException
bool success = socket.DisconnectEx(
handle,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
(int)(reuseSocket ? TransmitFileOptions.ReuseSocket : 0),
0);
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
internal static SocketError Disconnect(Socket socket, SafeSocketHandle handle, bool reuseSocket)
{
SocketError errorCode = SocketError.Success;
// This can throw ObjectDisposedException (handle, and retrieving the delegate).
if (!socket.DisconnectExBlocking(handle, IntPtr.Zero, (int)(reuseSocket ? TransmitFileOptions.ReuseSocket : 0), 0))
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Collections;
using System.Management.Automation;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Microsoft.Azure.Management.Storage;
using Microsoft.Azure.Management.Storage.Models;
using StorageModels = Microsoft.Azure.Management.Storage.Models;
using Microsoft.Azure.Commands.Management.Storage.Models;
using System.Collections.Generic;
using System;
namespace Microsoft.Azure.Commands.Management.Storage
{
[Cmdlet(VerbsCommon.Remove, StorageAccountRuleNounStr, SupportsShouldProcess = true, DefaultParameterSetName = NetWorkRuleStringParameterSet)]
[OutputType(typeof(PSVirtualNetworkRule), ParameterSetName = new string[] { NetWorkRuleStringParameterSet, NetworkRuleObjectParameterSet })]
[OutputType(typeof(PSIpRule), ParameterSetName = new string[] { IpRuleStringParameterSet, IpRuleObjectParameterSet })]
public class RemoveAzureStorageAccountNetworkRuleCommand : StorageAccountBaseCmdlet
{
/// <summary>
/// NetWorkRule in String parameter set name
/// </summary>
private const string NetWorkRuleStringParameterSet = "NetWorkRuleString";
/// <summary>
/// IpRule in String paremeter set name
/// </summary>
private const string IpRuleStringParameterSet = "IpRuleString";
/// <summary>
/// NetWorkRule Objects pipeline parameter set
/// </summary>
private const string NetworkRuleObjectParameterSet = "NetworkRuleObject";
/// <summary>
/// IpRule Objects pipeline parameter set
/// </summary>
private const string IpRuleObjectParameterSet = "IpRuleObject";
[Parameter(
Position = 0,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Resource Group Name.")]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Parameter(
Position = 1,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Storage Account Name.")]
[Alias(StorageAccountNameAlias, AccountNameAlias)]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
[Parameter(
Mandatory = true,
HelpMessage = "Storage Account NetworkRule IPRules.",
ValueFromPipeline = true, ParameterSetName = IpRuleObjectParameterSet)]
public PSIpRule[] IPRule { get; set; }
[Parameter(
Mandatory = true,
HelpMessage = "Storage Account NetworkRule VirtualNetworkRules.",
ValueFromPipeline = true, ParameterSetName = NetworkRuleObjectParameterSet)]
public PSVirtualNetworkRule[] VirtualNetworkRule { get; set; }
[Parameter(
Mandatory = true,
HelpMessage = "Storage Account NetworkRule IPRules IPAddressOrRange in string.",
ParameterSetName = IpRuleStringParameterSet)]
public string[] IPAddressOrRange { get; set; }
[Parameter(
Mandatory = true,
HelpMessage = "Storage Account NetworkRule VirtualNetworkRules VirtualNetworkResourceId in string.",
ParameterSetName = NetWorkRuleStringParameterSet)]
[Alias("SubnetId", "VirtualNetworkId")]
public string[] VirtualNetworkResourceId { get; set; }
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
if (ShouldProcess(this.Name, "Remove Storage Account Networkrules"))
{
var storageAccount = this.StorageClient.StorageAccounts.GetProperties(
this.ResourceGroupName,
this.Name);
StorageNetworkAcls storageACL = storageAccount.NetworkAcls;
if (storageACL == null)
{
storageACL = new StorageNetworkAcls();
}
switch (ParameterSetName)
{
case NetWorkRuleStringParameterSet:
if (storageACL.VirtualNetworkRules == null)
storageACL.VirtualNetworkRules = new List<VirtualNetworkRule>();
foreach (string s in VirtualNetworkResourceId)
{
VirtualNetworkRule rule = new VirtualNetworkRule(s);
if (!RemoveNetworkRule(storageACL.VirtualNetworkRules, rule))
throw new ArgumentOutOfRangeException("VirtualNetworkResourceId", String.Format("Can't remove VirtualNetworkRule with specific ResourceId since not exist: {0}", rule.VirtualNetworkResourceId));
}
break;
case IpRuleStringParameterSet:
if (storageACL.IpRules == null)
storageACL.IpRules = new List<IPRule>();
foreach (string s in IPAddressOrRange)
{
IPRule rule = new IPRule(s);
if (!RemoveIpRule(storageACL.IpRules, rule))
throw new ArgumentOutOfRangeException("IPAddressOrRange", String.Format("Can't remove IpRule with specific IPAddressOrRange since not exist: {0}", rule.IPAddressOrRange));
}
break;
case NetworkRuleObjectParameterSet:
if (storageACL.VirtualNetworkRules == null)
storageACL.VirtualNetworkRules = new List<VirtualNetworkRule>();
foreach (PSVirtualNetworkRule rule in VirtualNetworkRule)
{
if (!RemoveNetworkRule(storageACL.VirtualNetworkRules, PSNetworkRuleSet.ParseStorageNetworkRuleVirtualNetworkRule(rule)))
throw new ArgumentOutOfRangeException("VirtualNetworkRule", String.Format("Can't remove VirtualNetworkRule with specific ResourceId since not exist: {0}", rule.VirtualNetworkResourceId));
}
break;
case IpRuleObjectParameterSet:
if (storageACL.IpRules == null)
storageACL.IpRules = new List<IPRule>();
foreach (PSIpRule rule in IPRule)
{
if (!RemoveIpRule(storageACL.IpRules, PSNetworkRuleSet.ParseStorageNetworkRuleIPRule(rule)))
throw new ArgumentOutOfRangeException("IPRule", String.Format("Can't remove IpRule with specific IPAddressOrRange since not exist: {0}", rule.IPAddressOrRange));
}
break;
}
StorageAccountUpdateParameters updateParameters = new StorageAccountUpdateParameters();
updateParameters.NetworkAcls = storageACL;
var updatedAccountResponse = this.StorageClient.StorageAccounts.Update(
this.ResourceGroupName,
this.Name,
updateParameters);
storageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name);
switch (ParameterSetName)
{
case NetWorkRuleStringParameterSet:
case NetworkRuleObjectParameterSet:
WriteObject(PSNetworkRuleSet.ParsePSNetworkRule(storageAccount.NetworkAcls).VirtualNetworkRules);
break;
case IpRuleStringParameterSet:
case IpRuleObjectParameterSet:
WriteObject(PSNetworkRuleSet.ParsePSNetworkRule(storageAccount.NetworkAcls).IpRules);
break;
}
}
}
/// <summary>
/// Remove one IpRule from IpRule List
/// </summary>
/// <param name="ruleList">The IpRule List</param>
/// <param name="ruleToRemove">The IP Rule to remove</param>
/// <returns>true if reove success</returns>
public bool RemoveIpRule(IList<IPRule> ruleList, IPRule ruleToRemove)
{
foreach (IPRule rule in ruleList)
{
if (rule.IPAddressOrRange == ruleToRemove.IPAddressOrRange)
{
ruleList.Remove(rule);
return true;
}
}
return false;
}
/// <summary>
/// Remove one NetworkRule from NetworkRule List
/// </summary>
/// <param name="ruleList">The NetworkRule List</param>
/// <param name="ruleToRemove">The NetworkRulee to remove</param>
/// <returns>true if reove success</returns>
public bool RemoveNetworkRule(IList<VirtualNetworkRule> ruleList, VirtualNetworkRule ruleToRemove)
{
foreach (VirtualNetworkRule rule in ruleList)
{
if (rule.VirtualNetworkResourceId == ruleToRemove.VirtualNetworkResourceId)
{
ruleList.Remove(rule);
return true;
}
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Diagnostics
{
public class StatusCodeMiddlewareTest
{
[Fact]
public async Task Redirect_StatusPage()
{
var expectedStatusCode = 432;
var destination = "/location";
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseStatusCodePagesWithRedirects("/errorPage?id={0}");
app.Map(destination, (innerAppBuilder) =>
{
innerAppBuilder.Run((httpContext) =>
{
httpContext.Response.StatusCode = expectedStatusCode;
return Task.FromResult(1);
});
});
app.Map("/errorPage", (innerAppBuilder) =>
{
innerAppBuilder.Run(async (httpContext) =>
{
await httpContext.Response.WriteAsync(httpContext.Request.QueryString.Value);
});
});
app.Run((context) =>
{
throw new InvalidOperationException($"Invalid input provided. {context.Request.Path}");
});
});
}).Build();
await host.StartAsync();
var expectedQueryString = $"?id={expectedStatusCode}";
var expectedUri = $"/errorPage{expectedQueryString}";
using var server = host.GetTestServer();
var client = server.CreateClient();
var response = await client.GetAsync(destination);
Assert.Equal(HttpStatusCode.Found, response.StatusCode);
Assert.Equal(expectedUri, response.Headers.First(s => s.Key == "Location").Value.First());
response = await client.GetAsync(expectedUri);
var content = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedQueryString, content);
Assert.Equal(expectedQueryString, response.RequestMessage.RequestUri.Query);
}
[Fact]
public async Task Reexecute_CanRetrieveInformationAboutOriginalRequest()
{
var expectedStatusCode = 432;
var destination = "/location";
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.Use(async (context, next) =>
{
var beforeNext = context.Request.QueryString;
await next(context);
var afterNext = context.Request.QueryString;
Assert.Equal(beforeNext, afterNext);
});
app.UseStatusCodePagesWithReExecute(pathFormat: "/errorPage", queryFormat: "?id={0}");
app.Map(destination, (innerAppBuilder) =>
{
innerAppBuilder.Run((httpContext) =>
{
httpContext.Response.StatusCode = expectedStatusCode;
return Task.FromResult(1);
});
});
app.Map("/errorPage", (innerAppBuilder) =>
{
innerAppBuilder.Run(async (httpContext) =>
{
var statusCodeReExecuteFeature = httpContext.Features.Get<IStatusCodeReExecuteFeature>();
await httpContext.Response.WriteAsync(
httpContext.Request.QueryString.Value
+ ", "
+ statusCodeReExecuteFeature.OriginalPath
+ ", "
+ statusCodeReExecuteFeature.OriginalQueryString);
});
});
app.Run((context) =>
{
throw new InvalidOperationException("Invalid input provided.");
});
});
}).Build();
await host.StartAsync();
using var server = host.GetTestServer();
var client = server.CreateClient();
var response = await client.GetAsync(destination + "?name=James");
var content = await response.Content.ReadAsStringAsync();
Assert.Equal($"?id={expectedStatusCode}, /location, ?name=James", content);
}
[Fact]
public async Task Reexecute_ClearsEndpointAndRouteData()
{
var expectedStatusCode = 432;
var destination = "/location";
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseStatusCodePagesWithReExecute(pathFormat: "/errorPage", queryFormat: "?id={0}");
app.Use((context, next) =>
{
Assert.Empty(context.Request.RouteValues);
Assert.Null(context.GetEndpoint());
return next(context);
});
app.Map(destination, (innerAppBuilder) =>
{
innerAppBuilder.Run((httpContext) =>
{
httpContext.SetEndpoint(new Endpoint((_) => Task.CompletedTask, new EndpointMetadataCollection(), "Test"));
httpContext.Request.RouteValues["John"] = "Doe";
httpContext.Response.StatusCode = expectedStatusCode;
return Task.CompletedTask;
});
});
app.Map("/errorPage", (innerAppBuilder) =>
{
innerAppBuilder.Run(async (httpContext) =>
{
var statusCodeReExecuteFeature = httpContext.Features.Get<IStatusCodeReExecuteFeature>();
await httpContext.Response.WriteAsync(
httpContext.Request.QueryString.Value
+ ", "
+ statusCodeReExecuteFeature.OriginalPath
+ ", "
+ statusCodeReExecuteFeature.OriginalQueryString);
});
});
app.Run((context) =>
{
throw new InvalidOperationException("Invalid input provided.");
});
});
}).Build();
await host.StartAsync();
using var server = host.GetTestServer();
var client = server.CreateClient();
var response = await client.GetAsync(destination + "?name=James");
var content = await response.Content.ReadAsStringAsync();
Assert.Equal($"?id={expectedStatusCode}, /location, ?name=James", content);
}
[Fact]
public async Task Reexecute_CaptureEndpointAndRouteData()
{
var expectedStatusCode = 432;
var destination = "/location";
var endpoint = new Endpoint((_) => Task.CompletedTask, new EndpointMetadataCollection(), "Test");
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseStatusCodePagesWithReExecute(pathFormat: "/errorPage", queryFormat: "?id={0}");
app.Map(destination, (innerAppBuilder) =>
{
innerAppBuilder.Run((httpContext) =>
{
httpContext.SetEndpoint(endpoint);
httpContext.Request.RouteValues["John"] = "Doe";
httpContext.Response.StatusCode = expectedStatusCode;
return Task.CompletedTask;
});
});
app.Map("/errorPage", (innerAppBuilder) =>
{
innerAppBuilder.Run(httpContext =>
{
var statusCodeReExecuteFeature = httpContext.Features.Get<IStatusCodeReExecuteFeature>();
Assert.Equal(endpoint, statusCodeReExecuteFeature.Endpoint);
Assert.Equal("Doe", statusCodeReExecuteFeature.RouteValues["John"]);
return Task.CompletedTask;
});
});
app.Run((context) =>
{
throw new InvalidOperationException("Invalid input provided.");
});
});
}).Build();
await host.StartAsync();
using var server = host.GetTestServer();
var client = server.CreateClient();
var response = await client.GetAsync(destination + "?name=James");
}
[Fact]
public async Task Reexecute_WorksAfterUseRoutingWithGlobalRouteBuilder()
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseTestServer();
await using var app = builder.Build();
app.UseRouting();
app.UseStatusCodePagesWithReExecute(pathFormat: "/errorPage", queryFormat: "?id={0}");
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", c =>
{
c.Response.StatusCode = 404;
return Task.CompletedTask;
});
endpoints.MapGet("/errorPage", () => "errorPage");
});
app.Run((context) =>
{
throw new InvalidOperationException("Invalid input provided.");
});
await app.StartAsync();
using var server = app.GetTestServer();
var client = server.CreateClient();
var response = await client.GetAsync("/");
var content = await response.Content.ReadAsStringAsync();
Assert.Equal("errorPage", content);
}
}
}
| |
using System;
using System.Reflection;
using Xunit;
namespace Invio.Immutable {
public abstract class PropertyHandlerTestsBase {
[Fact]
public void PropertyName() {
// Arrange
var property = this.NextValidPropertyInfo();
var handler = this.CreateHandler(property);
// Act
var handlerPropertyName = handler.PropertyName;
// Assert
Assert.Equal(property.Name, handlerPropertyName);
}
[Fact]
public void PropertyType() {
// Arrange
var property = this.NextValidPropertyInfo();
var handler = this.CreateHandler(property);
// Act
var handlerPropertyType = handler.PropertyType;
// Assert
Assert.Equal(property.PropertyType, handlerPropertyType);
}
[Fact]
public void GetPropertyValueHashCode_NullParent() {
// Arrange
var property = this.NextValidPropertyInfo();
var handler = this.CreateHandler(property);
// Act
var exception = Record.Exception(
() => handler.GetPropertyValueHashCode(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void GetPropertyValueHashCode_InvalidParent() {
// Arrange
var property = this.NextValidPropertyInfo();
var handler = this.CreateHandler(property);
var invalidParent = new object();
// Act
var exception = Record.Exception(
() => handler.GetPropertyValueHashCode(invalidParent)
);
// Assert
Assert.Equal(
$"The value object provided is of type {nameof(Object)}, " +
$"which does not contains the {property.Name} property." +
Environment.NewLine + "Parameter name: parent",
exception.Message
);
Assert.IsType<ArgumentException>(exception);
Assert.NotNull(exception.InnerException);
}
[Fact]
public void ArePropertyValuesEqual_NullLeftParent() {
// Arrange
var property = this.NextValidPropertyInfo();
var handler = this.CreateHandler(property);
var leftParent = this.NextParent();
// Act
var exception = Record.Exception(
() => handler.ArePropertyValuesEqual(leftParent, null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void ArePropertyValuesEqual_NullRightParent() {
// Arrange
var property = this.NextValidPropertyInfo();
var handler = this.CreateHandler(property);
var rightParent = this.NextParent();
// Act
var exception = Record.Exception(
() => handler.ArePropertyValuesEqual(null, rightParent)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void ArePropertyValuesEqual_InvalidLeftParent() {
// Arrange
var property = this.NextValidPropertyInfo();
var handler = CreateHandler(property);
var leftParent = new object();
var rightParent = this.NextParent();
// Act
var exception = Record.Exception(
() => handler.ArePropertyValuesEqual(leftParent, rightParent)
);
// Assert
Assert.Equal(
$"The value object provided is of type {nameof(Object)}, " +
$"which does not contains the {property.Name} property." +
Environment.NewLine + "Parameter name: leftParent",
exception.Message
);
Assert.IsType<ArgumentException>(exception);
Assert.NotNull(exception.InnerException);
}
[Fact]
public void ArePropertyValuesEqual_InvalidRightParent() {
// Arrange
var property = this.NextValidPropertyInfo();
var handler = this.CreateHandler(property);
var leftParent = this.NextParent();
var rightParent = new object();
// Act
var exception = Record.Exception(
() => handler.ArePropertyValuesEqual(leftParent, rightParent)
);
// Assert
Assert.Equal(
$"The value object provided is of type {nameof(Object)}, " +
$"which does not contains the {property.Name} property." +
Environment.NewLine + "Parameter name: rightParent",
exception.Message
);
Assert.IsType<ArgumentException>(exception);
Assert.NotNull(exception.InnerException);
}
[Fact]
public void GetPropertyValue_NullParent() {
// Arrange
var property = this.NextValidPropertyInfo();
var handler = this.CreateHandler(property);
// Act
var exception = Record.Exception(
() => handler.GetPropertyValue(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void GetPropertyValue_InvalidParent() {
// Arrange
var property = this.NextValidPropertyInfo();
var handler = this.CreateHandler(property);
var invalidParent = new object();
// Act
var exception = Record.Exception(
() => handler.GetPropertyValue(invalidParent)
);
// Assert
Assert.Equal(
$"The value object provided is of type {nameof(Object)}, " +
$"which does not contains the {property.Name} property." +
Environment.NewLine + "Parameter name: parent",
exception.Message
);
Assert.IsType<ArgumentException>(exception);
Assert.NotNull(exception.InnerException);
}
protected abstract PropertyInfo NextValidPropertyInfo();
protected abstract object NextParent();
protected abstract IPropertyHandler CreateHandler(PropertyInfo property);
}
}
| |
/* ====================================================================
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.HSSF.Record
{
using System;
using System.Text;
using NPOI.Util;
/**
* The common object data record is used to store all common preferences for an excel object.
* NOTE: This source is automatically generated please do not modify this file. Either subclass or
* Remove the record in src/records/definitions.
* @author Glen Stampoultzis (glens at apache.org)
*/
public enum CommonObjectType:short
{
Group = 0,
Line = 1,
Rectangle = 2,
Oval = 3,
Arc = 4,
Chart = 5,
Text = 6,
Button = 7,
Picture = 8,
Polygon = 9,
Reserved1 = 10,
Checkbox = 11,
OptionButton = 12,
EditBox = 13,
Label = 14,
DialogBox = 15,
Spinner = 16,
ScrollBar = 17,
ListBox = 18,
GroupBox = 19,
ComboBox = 20,
Reserved2 = 21,
Reserved3 = 22,
Reserved4 = 23,
Reserved5 = 24,
Comment = 25,
Reserved6 = 26,
Reserved7 = 27,
Reserved8 = 28,
Reserved9 = 29,
MicrosoftOfficeDrawing = 30,
}
public class CommonObjectDataSubRecord : SubRecord, ICloneable
{
public const short sid = 0x15;
private short field_1_objectType;
private int field_2_objectId;
private short field_3_option;
private BitField locked = BitFieldFactory.GetInstance(0x1);
private BitField printable = BitFieldFactory.GetInstance(0x10);
private BitField autoFill = BitFieldFactory.GetInstance(0x2000);
private BitField autoline = BitFieldFactory.GetInstance(0x4000);
private int field_4_reserved1;
private int field_5_reserved2;
private int field_6_reserved3;
public CommonObjectDataSubRecord()
{
}
/**
* Constructs a CommonObjectData record and Sets its fields appropriately.
*
* @param in the RecordInputstream to Read the record from
*/
public CommonObjectDataSubRecord(ILittleEndianInput in1, int size)
{
if (size != 18)
{
throw new RecordFormatException("Expected size 18 but got (" + size + ")");
}
field_1_objectType = in1.ReadShort();
field_2_objectId = in1.ReadUShort();
field_3_option = in1.ReadShort();
field_4_reserved1 = in1.ReadInt();
field_5_reserved2 = in1.ReadInt();
field_6_reserved3 = in1.ReadInt();
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[ftCmo]\n");
buffer.Append(" .objectType = ")
.Append("0x").Append(HexDump.ToHex((short)ObjectType))
.Append(" (").Append(ObjectType).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .objectId = ")
.Append("0x").Append(HexDump.ToHex(ObjectId))
.Append(" (").Append(ObjectId).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .option = ")
.Append("0x").Append(HexDump.ToHex(Option))
.Append(" (").Append(Option).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .locked = ").Append(IsLocked).Append('\n');
buffer.Append(" .printable = ").Append(IsPrintable).Append('\n');
buffer.Append(" .autoFill = ").Append(IsAutoFill).Append('\n');
buffer.Append(" .autoline = ").Append(IsAutoline).Append('\n');
buffer.Append(" .reserved1 = ")
.Append("0x").Append(HexDump.ToHex(Reserved1))
.Append(" (").Append(Reserved1).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .reserved2 = ")
.Append("0x").Append(HexDump.ToHex(Reserved2))
.Append(" (").Append(Reserved2).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .reserved3 = ")
.Append("0x").Append(HexDump.ToHex(Reserved3))
.Append(" (").Append(Reserved3).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append("[/ftCmo]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(sid);
out1.WriteShort(DataSize);
out1.WriteShort(field_1_objectType);
out1.WriteShort(field_2_objectId);
out1.WriteShort(field_3_option);
out1.WriteInt(field_4_reserved1);
out1.WriteInt(field_5_reserved2);
out1.WriteInt(field_6_reserved3);
}
/**
* Size of record (exluding 4 byte header)
*/
public override int DataSize
{
get { return 2 + 2 + 2 + 4 + 4 + 4; }
}
public override short Sid
{
get { return sid; }
}
public override Object Clone()
{
CommonObjectDataSubRecord rec = new CommonObjectDataSubRecord();
rec.field_1_objectType = field_1_objectType;
rec.field_2_objectId = field_2_objectId;
rec.field_3_option = field_3_option;
rec.field_4_reserved1 = field_4_reserved1;
rec.field_5_reserved2 = field_5_reserved2;
rec.field_6_reserved3 = field_6_reserved3;
return rec;
}
/**
* Get the object type field for the CommonObjectData record.
*/
public CommonObjectType ObjectType
{
get
{
return (CommonObjectType)field_1_objectType;
}
set { this.field_1_objectType = (short)value; }
}
/**
* Get the object id field for the CommonObjectData record.
*/
public int ObjectId
{
get
{
return field_2_objectId;
}
set { this.field_2_objectId = value; }
}
/**
* Get the option field for the CommonObjectData record.
*/
public short Option
{
get
{
return field_3_option;
}
set { this.field_3_option = value; }
}
/**
* Get the reserved1 field for the CommonObjectData record.
*/
public int Reserved1
{
get
{
return field_4_reserved1;
}
set { this.field_4_reserved1 = value; }
}
/**
* Get the reserved2 field for the CommonObjectData record.
*/
public int Reserved2
{
get
{
return field_5_reserved2;
}
set { this.field_5_reserved2 = value; }
}
/**
* Get the reserved3 field for the CommonObjectData record.
*/
public int Reserved3
{
get
{
return field_6_reserved3;
}
set { this.field_6_reserved3 = value; }
}
/**
* true if object is locked when sheet has been protected
* @return the locked field value.
*/
public bool IsLocked
{
get
{
return locked.IsSet(field_3_option);
}
set { field_3_option = locked.SetShortBoolean(field_3_option, value); }
}
/**
* object appears when printed
* @return the printable field value.
*/
public bool IsPrintable
{
get
{
return printable.IsSet(field_3_option);
}
set { field_3_option = printable.SetShortBoolean(field_3_option, value); }
}
/**
* whether object uses an automatic Fill style
* @return the autoFill field value.
*/
public bool IsAutoFill
{
get
{
return autoFill.IsSet(field_3_option);
}
set { field_3_option = autoFill.SetShortBoolean(field_3_option, value); }
}
/**
* whether object uses an automatic line style
* @return the autoline field value.
*/
public bool IsAutoline
{
get
{
return autoline.IsSet(field_3_option);
}
set { field_3_option = autoline.SetShortBoolean(field_3_option, value); }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NMagickWand.Enums;
using NMagickWand.Structs;
namespace NMagickWand
{
public class DrawingWand
: IDisposable
{
internal IntPtr Wand { get; set; }
public PixelWand BorderColor
{
get
{
var pw = new PixelWand();
MagickWandApi.DrawGetBorderColor(Wand, pw.Wand);
return pw;
}
set
{
MagickWandApi.DrawSetBorderColor(Wand, value.Wand);
}
}
public string ClipPath
{
get
{
return MagickHelper.GetMagickString(MagickWandApi.DrawGetClipPath(Wand));
}
set
{
MagickWandApi.DrawSetClipPath(Wand, value);
}
}
public FillRule ClipRule
{
get
{
return MagickWandApi.DrawGetClipRule(Wand);
}
set
{
MagickWandApi.DrawSetClipRule(Wand, value);
}
}
public ClipPathUnits ClipUnits
{
get
{
return MagickWandApi.DrawGetClipUnits(Wand);
}
set
{
MagickWandApi.DrawSetClipUnits(Wand, value);
}
}
public string Density
{
get
{
return MagickHelper.GetMagickString(MagickWandApi.DrawGetDensity(Wand));
}
set
{
MagickWandApi.DrawSetDensity(Wand, value);
}
}
public PixelWand FillColor
{
get
{
var pw = new PixelWand();
MagickWandApi.DrawGetFillColor(Wand, pw.Wand);
return pw;
}
set
{
MagickWandApi.DrawSetFillColor(Wand, value.Wand);
}
}
public double FillOpacity
{
get
{
return MagickWandApi.DrawGetFillOpacity(Wand);
}
set
{
MagickWandApi.DrawSetFillOpacity(Wand, value);
}
}
public FillRule FillRule
{
get
{
return MagickWandApi.DrawGetFillRule(Wand);
}
set
{
MagickWandApi.DrawSetFillRule(Wand, value);
}
}
public string Font
{
get
{
return MagickHelper.GetMagickString(MagickWandApi.DrawGetFont(Wand));
}
set
{
MagickWandApi.DrawSetFont(Wand, value);
}
}
public string FontFamily
{
get
{
return MagickHelper.GetMagickString(MagickWandApi.DrawGetFontFamily(Wand));
}
set
{
MagickWandApi.DrawSetFontFamily(Wand, value);
}
}
public double FontSize
{
get
{
return MagickWandApi.DrawGetFontSize(Wand);
}
set
{
MagickWandApi.DrawSetFontSize(Wand, value);
}
}
public StretchType FontStretch
{
get
{
return MagickWandApi.DrawGetFontStretch(Wand);
}
set
{
MagickWandApi.DrawSetFontStretch(Wand, value);
}
}
public StyleType FontStyle
{
get
{
return MagickWandApi.DrawGetFontStyle(Wand);
}
set
{
MagickWandApi.DrawSetFontStyle(Wand, value);
}
}
public uint FontWeight
{
get
{
return (uint)MagickWandApi.DrawGetFontWeight(Wand);
}
set
{
MagickWandApi.DrawSetFontWeight(Wand, (UIntPtr)value);
}
}
public GravityType Gravity
{
get
{
return MagickWandApi.DrawGetGravity(Wand);
}
set
{
MagickWandApi.DrawSetGravity(Wand, value);
}
}
public bool IsDrawingWand
{
get
{
return MagickWandApi.IsDrawingWand(Wand) == MagickBooleanType.True;
}
}
public double Opacity
{
get
{
return MagickWandApi.DrawGetOpacity(Wand);
}
set
{
MagickWandApi.DrawSetOpacity(Wand, value);
}
}
public bool StrokeAntialias
{
get
{
return MagickWandApi.DrawGetStrokeAntialias(Wand) == MagickBooleanType.True;
}
set
{
var a = value ? MagickBooleanType.True : MagickBooleanType.False;
MagickWandApi.DrawSetStrokeAntialias(Wand, a);
}
}
public PixelWand StrokeColor
{
get
{
var pw = new PixelWand();
MagickWandApi.DrawGetStrokeColor(Wand, pw.Wand);
return pw;
}
set
{
MagickWandApi.DrawSetStrokeColor(Wand, value.Wand);
}
}
public IReadOnlyList<double> StrokeDashArray
{
get
{
return MagickHelper.ExecuteMagickWandDoubleList(Wand, MagickWandApi.DrawGetStrokeDashArray);
}
set
{
MagickWandApi.DrawSetStrokeDashArray(Wand, (UIntPtr)value.Count, value.ToArray());
}
}
public double StrokeDashOffset
{
get
{
return MagickWandApi.DrawGetStrokeDashOffset(Wand);
}
set
{
MagickWandApi.DrawSetStrokeDashOffset(Wand, value);
}
}
public LineCap StrokeLineCap
{
get
{
return MagickWandApi.DrawGetStrokeLineCap(Wand);
}
set
{
MagickWandApi.DrawSetStrokeLineCap(Wand, value);
}
}
public LineJoin StrokeLineJoin
{
get
{
return MagickWandApi.DrawGetStrokeLineJoin(Wand);
}
set
{
MagickWandApi.DrawSetStrokeLineJoin(Wand, value);
}
}
public uint StrokeMiterLimit
{
get
{
return (uint)MagickWandApi.DrawGetStrokeMiterLimit(Wand);
}
set
{
MagickWandApi.DrawSetStrokeMiterLimit(Wand, (UIntPtr)value);
}
}
public double StrokeOpacity
{
get
{
return MagickWandApi.DrawGetStrokeOpacity(Wand);
}
set
{
MagickWandApi.DrawSetStrokeOpacity(Wand, value);
}
}
public double StrokeWidth
{
get
{
return MagickWandApi.DrawGetStrokeWidth(Wand);
}
set
{
MagickWandApi.DrawSetStrokeWidth(Wand, value);
}
}
public AlignType TextAlignment
{
get
{
return MagickWandApi.DrawGetTextAlignment(Wand);
}
set
{
MagickWandApi.DrawSetTextAlignment(Wand, value);
}
}
public bool TextAntialias
{
get
{
return MagickWandApi.DrawGetTextAntialias(Wand) == MagickBooleanType.True;
}
set
{
var a = value ? MagickBooleanType.True : MagickBooleanType.False;
MagickWandApi.DrawSetTextAntialias(Wand, a);
}
}
public DecorationType TextDecoration
{
get
{
return MagickWandApi.DrawGetTextDecoration(Wand);
}
set
{
MagickWandApi.DrawSetTextDecoration(Wand, value);
}
}
public DirectionType TextDirection
{
get
{
return MagickWandApi.DrawGetTextDirection(Wand);
}
set
{
MagickWandApi.DrawSetTextDirection(Wand, value);
}
}
public string TextEncoding
{
get
{
return MagickHelper.GetMagickString(MagickWandApi.DrawGetTextEncoding(Wand));
}
set
{
MagickWandApi.DrawSetTextEncoding(Wand, value);
}
}
public double TextKerning
{
get
{
return MagickWandApi.DrawGetTextKerning(Wand);
}
set
{
MagickWandApi.DrawSetTextKerning(Wand, value);
}
}
public double TextInterlineSpacing
{
get
{
return MagickWandApi.DrawGetTextInterlineSpacing(Wand);
}
set
{
MagickWandApi.DrawSetTextInterlineSpacing(Wand, value);
}
}
public double TextInterwordSpacing
{
get
{
return MagickWandApi.DrawGetTextInterwordSpacing(Wand);
}
set
{
MagickWandApi.DrawSetTextInterwordSpacing(Wand, value);
}
}
public string VectorGraphics
{
get
{
return MagickHelper.GetMagickString(MagickWandApi.DrawGetVectorGraphics(Wand));
}
set
{
MagickWandApi.DrawSetVectorGraphics(Wand, value);
}
}
public PixelWand TextUnderColor
{
get
{
var pw = new PixelWand();
MagickWandApi.DrawGetTextUnderColor(Wand, pw.Wand);
return pw;
}
set
{
MagickWandApi.DrawSetTextUnderColor(Wand, value.Wand);
}
}
public DrawingWand()
{
Wand = MagickWandApi.NewDrawingWand();
}
internal DrawingWand(IntPtr drawingWand)
{
Wand = drawingWand;
}
public void Clear()
{
MagickWandApi.ClearDrawingWand(Wand);
}
public DrawingWand Clone()
{
return new DrawingWand(MagickWandApi.CloneDrawingWand(Wand));
}
public void DrawAffine(AffineMatrix affine)
{
MagickWandApi.DrawAffine(Wand, ref affine);
}
public void DrawAnnotation(double x, double y, string text)
{
MagickWandApi.DrawAnnotation(Wand, x, y, text);
}
public void DrawArc(double sx, double sy, double ex, double ey, double sd, double ed)
{
MagickWandApi.DrawArc(Wand, sx, sy, ex, ey, sd, ed);
}
public void DrawBezier(IReadOnlyList<PointInfo> points)
{
throw new NotImplementedException();
}
public void DrawCircle(double ox, double oy, double px, double py)
{
MagickWandApi.DrawCircle(Wand, ox, oy, px, py);
}
public void DrawColor(double x, double y, PaintMethod method)
{
MagickWandApi.DrawColor(Wand, x, y, method);
}
public void DrawComment(string comment)
{
MagickWandApi.DrawComment(Wand, comment);
}
public void DrawComposite(CompositeOperator compose, double x, double y, double width, double height, MagickWand magickWand)
{
Check(MagickWandApi.DrawComposite(Wand, compose, x, y, width, height, magickWand.Wand));
}
public void DrawEllipse(double ox, double oy, double rx, double ry, double start, double end)
{
MagickWandApi.DrawEllipse(Wand, ox, oy, rx, ry, start, end);
}
public void DrawLine(double sx, double sy, double ex, double ey)
{
MagickWandApi.DrawLine(Wand, sx, sy, ex, ey);
}
public void DrawMatte(double x, double y, PaintMethod method)
{
MagickWandApi.DrawMatte(Wand, x, y, method);
}
public void DrawPathClose()
{
MagickWandApi.DrawPathClose(Wand);
}
public void DrawPathCurveToAbsolute(double x1, double y1, double x2, double y2, double x, double y)
{
MagickWandApi.DrawPathCurveToAbsolute(Wand, x1, y1, x2, y2, x, y);
}
public void GetFontResolution(out double x, out double y)
{
Check(MagickWandApi.DrawGetFontResolution(Wand, out x, out y));
}
public void DrawPathCurveToRelative(double x1, double y1, double x2, double y2, double x, double y)
{
MagickWandApi.DrawPathCurveToRelative(Wand, x1, y1, x2, y2, x, y);
}
public void DrawPathCurveToQuadraticBezierAbsolute(double x1, double y1, double x, double y)
{
MagickWandApi.DrawPathCurveToQuadraticBezierAbsolute(Wand, x1, y1, x, y);
}
public void DrawPathCurveToQuadraticBezierRelative(double x1, double y1, double x, double y)
{
MagickWandApi.DrawPathCurveToQuadraticBezierRelative(Wand, x1, y1, x, y);
}
public void DrawPathCurveToQuadraticBezierSmoothAbsolute(double x, double y)
{
MagickWandApi.DrawPathCurveToQuadraticBezierSmoothAbsolute(Wand, x, y);
}
public void DrawPathCurveToQuadraticBezierSmoothRelative(double x, double y)
{
MagickWandApi.DrawPathCurveToQuadraticBezierSmoothRelative(Wand, x, y);
}
public void DrawPathCurveToSmoothAbsolute(double x2, double y2, double x, double y)
{
MagickWandApi.DrawPathCurveToSmoothAbsolute(Wand, x2, y2, x, y);
}
public void DrawPathCurveToSmoothRelative(double x2, double y2, double x, double y)
{
MagickWandApi.DrawPathCurveToSmoothRelative(Wand, x2, y2, x, y);
}
public void DrawPathEllipticArcAbsolute(double rx, double ry, double xAxisRotation, bool largeArcFlag, bool sweepFlag, double x, double y)
{
var arc = largeArcFlag ? MagickBooleanType.True : MagickBooleanType.False;
var sweep = sweepFlag ? MagickBooleanType.True : MagickBooleanType.False;
MagickWandApi.DrawPathEllipticArcAbsolute(Wand, rx, ry, xAxisRotation, arc, sweep, x, y);
}
public void DrawPathEllipticArcRelative(double rx, double ry, double xAxisRotation, bool largeArcFlag, bool sweepFlag, double x, double y)
{
var arc = largeArcFlag ? MagickBooleanType.True : MagickBooleanType.False;
var sweep = sweepFlag ? MagickBooleanType.True : MagickBooleanType.False;
MagickWandApi.DrawPathEllipticArcRelative(Wand, rx, ry, xAxisRotation, arc, sweep, x, y);
}
public void DrawPathFinish()
{
MagickWandApi.DrawPathFinish(Wand);
}
public void DrawPathLineToAbsolute(double x, double y)
{
MagickWandApi.DrawPathLineToAbsolute(Wand, x, y);
}
public void DrawPathLineToRelative(double x, double y)
{
MagickWandApi.DrawPathLineToRelative(Wand, x, y);
}
public void DrawPathLineToHorizontalAbsolute(double x)
{
MagickWandApi.DrawPathLineToHorizontalAbsolute(Wand, x);
}
public void DrawPathLineToHorizontalRelative(double x)
{
MagickWandApi.DrawPathLineToHorizontalRelative(Wand, x);
}
public void DrawPathLineToVerticalAbsolute(double y)
{
MagickWandApi.DrawPathLineToVerticalAbsolute(Wand, y);
}
public void DrawPathLineToVerticalRelative(double y)
{
MagickWandApi.DrawPathLineToVerticalRelative(Wand, y);
}
public void DrawPathMoveToAbsolute(double x, double y)
{
MagickWandApi.DrawPathMoveToAbsolute(Wand, x, y);
}
public void DrawPathMoveToRelative(double x, double y)
{
MagickWandApi.DrawPathMoveToRelative(Wand, x, y);
}
public void DrawPathStart()
{
MagickWandApi.DrawPathStart(Wand);
}
public void DrawPoint(double x, double y)
{
MagickWandApi.DrawPoint(Wand, x, y);
}
public void DrawPolygon(IReadOnlyList<PointInfo> points)
{
throw new NotImplementedException();
}
public void DrawPolyline(IReadOnlyList<PointInfo> points)
{
throw new NotImplementedException();
}
public void PopClipPath()
{
MagickWandApi.DrawPopClipPath(Wand);
}
public void PopDefs()
{
MagickWandApi.DrawPopDefs(Wand);
}
public void PopDrawingWand()
{
MagickWandApi.PopDrawingWand(Wand);
}
public void PopPattern()
{
Check(MagickWandApi.DrawPopPattern(Wand));
}
public void PushClipPath(string clipMaskId)
{
MagickWandApi.DrawPushClipPath(Wand, clipMaskId);
}
public void PushDefs()
{
MagickWandApi.DrawPushDefs(Wand);
}
public void PushDrawingWand()
{
MagickWandApi.PushDrawingWand(Wand);
}
public void PushPattern(string pattern, double x, double y, double width, double height)
{
Check(MagickWandApi.DrawPushPattern(Wand, pattern, x, y, width, height));
}
public void DrawRectangle(double x1, double y1, double x2, double y2)
{
MagickWandApi.DrawRectangle(Wand, x1, y1, x2, y2);
}
public void PeekDrawingWand()
{
throw new NotImplementedException();
}
public void ResetVectorGraphics()
{
MagickWandApi.DrawResetVectorGraphics(Wand);
}
public void Rotate(double degrees)
{
MagickWandApi.DrawRotate(Wand, degrees);
}
public void DrawRoundRectangle(double x1, double y1, double x2, double y2, double rx, double ry)
{
MagickWandApi.DrawRoundRectangle(Wand, x1, y1, x2, y2, rx, ry);
}
public void Scale(double x, double y)
{
MagickWandApi.DrawScale(Wand, x, y);
}
public void SetFontResolution(double xResolution, double yResolution)
{
MagickWandApi.DrawSetFontResolution(Wand, xResolution, yResolution);
}
public void SetFillPatternUrl(string url)
{
MagickWandApi.DrawSetFillPatternURL(Wand, url);
}
public void SetStrokePatternUrl(string url)
{
MagickWandApi.DrawSetStrokePatternURL(Wand, url);
}
public void SetVectorGraphics(string xml)
{
MagickWandApi.DrawSetVectorGraphics(Wand, xml);
}
public void SetViewBox(int x1, int y1, int x2, int y2)
{
MagickWandApi.DrawSetViewbox(Wand, (IntPtr)x1, (IntPtr)y1, (IntPtr)x2, (IntPtr)y2);
}
public void SkewX(double degrees)
{
MagickWandApi.DrawSkewX(Wand, degrees);
}
public void SkewY(double degrees)
{
MagickWandApi.DrawSkewY(Wand, degrees);
}
public void Translate(double x, double y)
{
MagickWandApi.DrawTranslate(Wand, x, y);
}
void Check(MagickBooleanType result)
{
if(result == MagickBooleanType.False)
{
CheckAndRaiseException();
}
}
void CheckAndRaiseException()
{
var exType = ExceptionType.UndefinedException;
var msgPtr = MagickWandApi.DrawGetException(Wand, ref exType);
if(exType != ExceptionType.UndefinedException)
{
var msg = MagickHelper.GetMagickString(msgPtr);
MagickWandApi.MagickRelinquishMemory(msgPtr);
MagickWandApi.DrawClearException(Wand);
throw new MagickWandException(exType, msg);
}
}
~DrawingWand()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(disposing)
{
// free managed objects
}
// free native objects
if(Wand != IntPtr.Zero)
{
MagickWandApi.DestroyDrawingWand(Wand);
Wand = IntPtr.Zero;
}
}
}
}
| |
using System;
using Invio.Xunit;
using Xunit;
namespace Invio.Immutable {
[UnitTest]
public sealed class SimpleImmutableTests {
private Random random { get; }
public SimpleImmutableTests() {
this.random = new Random();
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("foo")]
public void SetStringProperty(String newStringValue) {
// Arrange
var fake = this.NextFake();
var originalValue = fake.StringProperty;
// Act
var updated = fake.SetStringProperty(newStringValue);
// Assert
Assert.Equal(originalValue, fake.StringProperty);
Assert.Equal(newStringValue, updated.StringProperty);
}
[Theory]
[InlineData(Int32.MinValue)]
[InlineData(0)]
[InlineData(1)]
[InlineData(Int32.MaxValue)]
public void SetValueProperty(int newValue) {
// Arrange
var fake = this.NextFake();
var originalValue = fake.ValueProperty;
// Act
var updated = fake.SetValueProperty(newValue);
// Assert
Assert.Equal(originalValue, fake.ValueProperty);
Assert.Equal(newValue, updated.ValueProperty);
}
[Fact]
public void SetReferenceProperty_Null() {
// Arrange
var fake = this.NextFake();
// Act
var updated = fake.SetReferenceProperty(null);
// Assert
Assert.Null(fake.ReferenceProperty);
}
[Fact]
public void SetReferenceProperty_NonNull() {
// Arrange
var fake = this.NextFake();
var value = new object();
// Act
var updated = fake.SetReferenceProperty(value);
// Assert
Assert.Equal(value, updated.ReferenceProperty);
}
[Fact]
public void Inequality_NullObject() {
// Arrange
var fake = this.NextFake();
object other = null;
// Act
var isEqual = fake.Equals(other);
// Assert
Assert.False(isEqual);
}
[Fact]
public void Inequality_NonNullTypeMismatch() {
// Arrange
var fake = this.NextFake();
var other = new object();
// Act
var isEqual = fake.Equals(other);
// Assert
Assert.False(isEqual);
}
[Fact]
public void Inequality_Null_MatchingImmutableType() {
// Arrange
var fake = this.NextFake();
SimpleImmutableFake other = null;
// Act
var isEqual = fake.Equals(other);
// Assert
Assert.False(isEqual);
AssertFakesNotEqual(fake, other);
}
[Theory]
[InlineData(Int32.MinValue)]
[InlineData(0)]
[InlineData(1)]
[InlineData(Int32.MaxValue)]
public void Equality_SetValueProperty(int value) {
// Arrange
var fake = this.NextFake();
// Act
var left = fake.SetValueProperty(value);
var right = fake.SetValueProperty(value);
// Assert
AssertFakesEqual(left, right);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("foo")]
public void Equality_SetStringProperty(String stringValue) {
// Arrange
var fake = this.NextFake();
// Act
var left = fake.SetStringProperty(stringValue);
var right = fake.SetStringProperty(stringValue);
// Assert
AssertFakesEqual(left, right);
}
[Fact]
public void Equality_SetReferenceProperty_NonNull() {
// Arrange
var fake = this.NextFake();
var value = new object();
// Act
var left = fake.SetReferenceProperty(value);
var right = fake.SetReferenceProperty(value);
// Assert
AssertFakesEqual(left, right);
}
[Fact]
public void Equality_SetReferenceProperty_Null() {
// Arrange
var fake = this.NextFake();
object value = null;
// Act
var left = fake.SetReferenceProperty(value);
var right = fake.SetReferenceProperty(value);
// Assert
AssertFakesEqual(left, right);
}
[Fact]
public void Inequality_SetReferenceProperty_NonNull() {
// Arrange
var fake = this.NextFake();
// Act
var left = fake.SetReferenceProperty(new object());
var right = fake.SetReferenceProperty(new object());
// Assert
AssertFakesNotEqual(left, right);
}
[Fact]
public void Inequality_SetReferenceProperty_Null() {
// Arrange
var fake = this.NextFake();
// Act
var left = fake.SetReferenceProperty(new object());
var right = fake.SetReferenceProperty(null);
// Assert
AssertFakesNotEqual(left, right);
}
[Fact]
public void Equality_SameImmutableObjectReference() {
// Assert
var fake = this.NextFake();
// Assert
AssertFakesEqual(fake, fake);
}
[Fact]
public void MultipleConstructors_ValidImmutableSetterDecoration() {
// Arrange
var original = new SimpleDecoratedFake("Foo", Guid.NewGuid());
// Act
const string updatedFoo = "Updated";
var updated = original.SetFoo(updatedFoo);
// Assert
Assert.Equal(updatedFoo, updated.Foo);
Assert.Equal(original.Bar, updated.Bar);
}
[Fact]
public void EqualityOverride_Nulls() {
// Arrange
SimpleImmutableFake left = null;
SimpleImmutableFake right = null;
// Act
var isEqual = (left == right);
// Assert
Assert.True(isEqual);
}
[Fact]
public void InequalityOverride_Nulls() {
// Arrange
SimpleImmutableFake left = null;
SimpleImmutableFake right = null;
// Act
var isNotEqual = (left != right);
// Assert
Assert.False(isNotEqual);
}
private static void AssertFakesEqual(
SimpleImmutableFake left,
SimpleImmutableFake right) {
Assert.Equal(left, right);
Assert.Equal((Object)left, (Object)right);
Assert.Equal(right, left);
Assert.Equal((Object)right, (Object)left);
Assert.True(left == right);
Assert.False(left != right);
if (left != null && right != null) {
Assert.Equal(left.GetHashCode(), right.GetHashCode());
}
}
private static void AssertFakesNotEqual(
SimpleImmutableFake left,
SimpleImmutableFake right) {
Assert.NotEqual(left, right);
Assert.NotEqual((Object)left, (Object)right);
Assert.False(left == right);
Assert.True(left != right);
}
private SimpleImmutableFake NextFake() {
return new SimpleImmutableFake(
this.random.Next(),
Guid.NewGuid().ToString("N"),
this.random.Next(0, 1) == 1 ? new object() : null
);
}
private class SimpleImmutableFake : ImmutableBase<SimpleImmutableFake> {
public int ValueProperty { get; }
public String StringProperty { get; }
public Object ReferenceProperty { get; }
public SimpleImmutableFake(
int valueProperty,
String stringProperty,
Object referenceProperty) {
this.ValueProperty = valueProperty;
this.StringProperty = stringProperty;
this.ReferenceProperty = referenceProperty;
}
public SimpleImmutableFake SetValueProperty(int valueProperty) {
return this.SetPropertyValueImpl(nameof(ValueProperty), valueProperty);
}
public SimpleImmutableFake SetStringProperty(String stringProperty) {
return this.SetPropertyValueImpl(nameof(StringProperty), stringProperty);
}
public SimpleImmutableFake SetReferenceProperty(Object referenceProperty) {
return this.SetPropertyValueImpl(nameof(ReferenceProperty), referenceProperty);
}
}
private class SimpleDecoratedFake : ImmutableBase<SimpleDecoratedFake> {
public String Foo { get; }
public Guid Bar { get; }
public SimpleDecoratedFake(Tuple<String, Guid> tuple) :
this(tuple.Item1, tuple.Item2) {}
[ImmutableSetterConstructor]
public SimpleDecoratedFake(String foo, Guid bar) {
this.Foo = foo;
this.Bar = bar;
}
public SimpleDecoratedFake SetFoo(String foo) {
return this.SetPropertyValueImpl(nameof(Foo), foo);
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="EwsHttpWebRequest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>Defines the EwsHttpWebRequest class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
/// <summary>
/// Represents an implementation of the IEwsHttpWebRequest interface that uses HttpWebRequest.
/// </summary>
internal class EwsHttpWebRequest : IEwsHttpWebRequest
{
/// <summary>
/// Underlying HttpWebRequest.
/// </summary>
private HttpWebRequest request;
/// <summary>
/// Initializes a new instance of the <see cref="EwsHttpWebRequest"/> class.
/// </summary>
/// <param name="uri">The URI.</param>
internal EwsHttpWebRequest(Uri uri)
{
this.request = (HttpWebRequest)WebRequest.Create(uri);
}
#region IEwsHttpWebRequest Members
/// <summary>
/// Aborts this instance.
/// </summary>
void IEwsHttpWebRequest.Abort()
{
this.request.Abort();
}
/// <summary>
/// Begins an asynchronous request for a <see cref="T:System.IO.Stream"/> object to use to write data.
/// </summary>
/// <param name="callback">The <see cref="T:System.AsyncCallback"/> delegate.</param>
/// <param name="state">The state object for this request.</param>
/// <returns>
/// An <see cref="T:System.IAsyncResult"/> that references the asynchronous request.
/// </returns>
IAsyncResult IEwsHttpWebRequest.BeginGetRequestStream(AsyncCallback callback, object state)
{
return this.request.BeginGetRequestStream(callback, state);
}
/// <summary>
/// Begins an asynchronous request to an Internet resource.
/// </summary>
/// <param name="callback">The <see cref="T:System.AsyncCallback"/> delegate</param>
/// <param name="state">The state object for this request.</param>
/// <returns>
/// An <see cref="T:System.IAsyncResult"/> that references the asynchronous request for a response.
/// </returns>
IAsyncResult IEwsHttpWebRequest.BeginGetResponse(AsyncCallback callback, object state)
{
return this.request.BeginGetResponse(callback, state);
}
/// <summary>
/// Ends an asynchronous request for a <see cref="T:System.IO.Stream"/> object to use to write data.
/// </summary>
/// <param name="asyncResult">The pending request for a stream.</param>
/// <returns>
/// A <see cref="T:System.IO.Stream"/> to use to write request data.
/// </returns>
Stream IEwsHttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult)
{
return this.request.EndGetRequestStream(asyncResult);
}
/// <summary>
/// Ends an asynchronous request to an Internet resource.
/// </summary>
/// <param name="asyncResult">The pending request for a response.</param>
/// <returns>
/// A <see cref="IEwsHttpWebResponse"/> that contains the response from the Internet resource.
/// </returns>
IEwsHttpWebResponse IEwsHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
{
return new EwsHttpWebResponse((HttpWebResponse)this.request.EndGetResponse(asyncResult));
}
/// <summary>
/// Gets a <see cref="T:System.IO.Stream"/> object to use to write request data.
/// </summary>
/// <returns>
/// A <see cref="T:System.IO.Stream"/> to use to write request data.
/// </returns>
Stream IEwsHttpWebRequest.GetRequestStream()
{
return this.request.GetRequestStream();
}
/// <summary>
/// Returns a response from an Internet resource.
/// </summary>
/// <returns>
/// A <see cref="T:System.Net.HttpWebResponse"/> that contains the response from the Internet resource.
/// </returns>
IEwsHttpWebResponse IEwsHttpWebRequest.GetResponse()
{
return new EwsHttpWebResponse(this.request.GetResponse() as HttpWebResponse);
}
/// <summary>
/// Gets or sets the value of the Accept HTTP header.
/// </summary>
/// <returns>The value of the Accept HTTP header. The default value is null.</returns>
string IEwsHttpWebRequest.Accept
{
get { return this.request.Accept; }
set { this.request.Accept = value; }
}
/// <summary>
/// Gets or sets a value that indicates whether the request should follow redirection responses.
/// </summary>
/// <returns>
/// True if the request should automatically follow redirection responses from the Internet resource; otherwise, false.
/// The default value is true.
/// </returns>
bool IEwsHttpWebRequest.AllowAutoRedirect
{
get { return this.request.AllowAutoRedirect; }
set { this.request.AllowAutoRedirect = value; }
}
/// <summary>
/// Gets or sets the client certificates.
/// </summary>
/// <value></value>
/// <returns>The collection of X509 client certificates.</returns>
X509CertificateCollection IEwsHttpWebRequest.ClientCertificates
{
get { return this.request.ClientCertificates; }
set { this.request.ClientCertificates = value; }
}
/// <summary>
/// Gets or sets the value of the Content-type HTTP header.
/// </summary>
/// <returns>The value of the Content-type HTTP header. The default value is null.</returns>
string IEwsHttpWebRequest.ContentType
{
get { return this.request.ContentType; }
set { this.request.ContentType = value; }
}
/// <summary>
/// Gets or sets the cookie container.
/// </summary>
/// <value>The cookie container.</value>
CookieContainer IEwsHttpWebRequest.CookieContainer
{
get { return this.request.CookieContainer; }
set { this.request.CookieContainer = value; }
}
/// <summary>
/// Gets or sets authentication information for the request.
/// </summary>
/// <returns>An <see cref="T:System.Net.ICredentials"/> that contains the authentication credentials associated with the request. The default is null.</returns>
ICredentials IEwsHttpWebRequest.Credentials
{
get { return this.request.Credentials; }
set { this.request.Credentials = value; }
}
/// <summary>
/// Specifies a collection of the name/value pairs that make up the HTTP headers.
/// </summary>
/// <returns>A <see cref="T:System.Net.WebHeaderCollection"/> that contains the name/value pairs that make up the headers for the HTTP request.</returns>
WebHeaderCollection IEwsHttpWebRequest.Headers
{
get { return this.request.Headers; }
set { this.request.Headers = value; }
}
/// <summary>
/// Gets or sets the method for the request.
/// </summary>
/// <returns>The request method to use to contact the Internet resource. The default value is GET.</returns>
/// <exception cref="T:System.ArgumentException">No method is supplied.-or- The method string contains invalid characters. </exception>
string IEwsHttpWebRequest.Method
{
get { return this.request.Method; }
set { this.request.Method = value; }
}
/// <summary>
/// Gets or sets proxy information for the request.
/// </summary>
IWebProxy IEwsHttpWebRequest.Proxy
{
get { return this.request.Proxy; }
set { this.request.Proxy = value; }
}
/// <summary>
/// Gets or sets a value that indicates whether to send an authenticate header with the request.
/// </summary>
/// <returns>true to send a WWW-authenticate HTTP header with requests after authentication has taken place; otherwise, false. The default is false.</returns>
bool IEwsHttpWebRequest.PreAuthenticate
{
get { return this.request.PreAuthenticate; }
set { this.request.PreAuthenticate = value; }
}
/// <summary>
/// Gets the original Uniform Resource Identifier (URI) of the request.
/// </summary>
/// <returns>A <see cref="T:System.Uri"/> that contains the URI of the Internet resource passed to the <see cref="M:System.Net.WebRequest.Create(System.String)"/> method.</returns>
Uri IEwsHttpWebRequest.RequestUri
{
get { return this.request.RequestUri; }
}
/// <summary>
/// Gets or sets the time-out value in milliseconds for the <see cref="M:System.Net.HttpWebRequest.GetResponse"/> and <see cref="M:System.Net.HttpWebRequest.GetRequestStream"/> methods.
/// </summary>
/// <returns>The number of milliseconds to wait before the request times out. The default is 100,000 milliseconds (100 seconds).</returns>
int IEwsHttpWebRequest.Timeout
{
get { return this.request.Timeout; }
set { this.request.Timeout = value; }
}
/// <summary>
/// Gets or sets a <see cref="T:System.Boolean"/> value that controls whether default credentials are sent with requests.
/// </summary>
/// <returns>true if the default credentials are used; otherwise false. The default value is false.</returns>
bool IEwsHttpWebRequest.UseDefaultCredentials
{
get { return this.request.UseDefaultCredentials; }
set { this.request.UseDefaultCredentials = value; }
}
/// <summary>
/// Gets or sets the value of the User-agent HTTP header.
/// </summary>
/// <returns>The value of the User-agent HTTP header. The default value is null.The value for this property is stored in <see cref="T:System.Net.WebHeaderCollection"/>. If WebHeaderCollection is set, the property value is lost.</returns>
string IEwsHttpWebRequest.UserAgent
{
get { return this.request.UserAgent; }
set { this.request.UserAgent = value; }
}
/// <summary>
/// Gets or sets if the request to the internet resource should contain a Connection HTTP header with the value Keep-alive
/// </summary>
public bool KeepAlive
{
get { return this.request.KeepAlive; }
set { this.request.KeepAlive = value; }
}
/// <summary>
/// Gets or sets the name of the connection group for the request.
/// </summary>
public string ConnectionGroupName
{
get { return this.request.ConnectionGroupName; }
set { this.request.ConnectionGroupName = value; }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Pathoschild.Stardew.Common;
using Pathoschild.Stardew.DataLayers.Framework;
using StardewValley;
using StardewValley.TerrainFeatures;
using SObject = StardewValley.Object;
namespace Pathoschild.Stardew.DataLayers.Layers.Coverage
{
/// <summary>A data layer which shows sprinkler coverage.</summary>
internal class SprinklerLayer : BaseLayer
{
/*********
** Fields
*********/
/// <summary>The legend entry for sprinkled tiles.</summary>
private readonly LegendEntry Wet;
/// <summary>The legend entry for unsprinkled tiles.</summary>
private readonly LegendEntry Dry;
/// <summary>The border color for the sprinkler under the cursor.</summary>
private readonly Color SelectedColor = Color.Blue;
/// <summary>The maximum number of tiles outside the visible screen area to search for sprinklers.</summary>
private readonly int SearchRadius;
/// <summary>Handles access to the supported mod integrations.</summary>
private readonly ModIntegrations Mods;
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="config">The data layer settings.</param>
/// <param name="mods">Handles access to the supported mod integrations.</param>
public SprinklerLayer(LayerConfig config, ModIntegrations mods)
: base(I18n.Sprinklers_Name(), config)
{
// init
this.Mods = mods;
this.Legend = new[]
{
this.Wet = new LegendEntry(I18n.Keys.Sprinklers_Covered, Color.Green),
this.Dry = new LegendEntry(I18n.Keys.Sprinklers_DryCrops, Color.Red)
};
// get search radius
this.SearchRadius = 10;
if (mods.BetterSprinklers.IsLoaded)
this.SearchRadius = Math.Max(this.SearchRadius, mods.BetterSprinklers.MaxRadius);
if (mods.LineSprinklers.IsLoaded)
this.SearchRadius = Math.Max(this.SearchRadius, mods.LineSprinklers.MaxRadius);
}
/// <summary>Get the updated data layer tiles.</summary>
/// <param name="location">The current location.</param>
/// <param name="visibleArea">The tile area currently visible on the screen.</param>
/// <param name="visibleTiles">The tile positions currently visible on the screen.</param>
/// <param name="cursorTile">The tile position under the cursor.</param>
public override TileGroup[] Update(GameLocation location, in Rectangle visibleArea, in Vector2[] visibleTiles, in Vector2 cursorTile)
{
// get coverage
IDictionary<int, Vector2[]> customCoverageBySprinklerId = this.GetCustomSprinklerTiles();
// get sprinklers
Vector2[] searchTiles = visibleArea.Expand(this.SearchRadius).GetTiles().ToArray();
SObject[] sprinklers =
(
from Vector2 tile in searchTiles
where location.objects.ContainsKey(tile)
let sprinkler = location.objects[tile]
where this.IsSprinkler(sprinkler, customCoverageBySprinklerId)
select sprinkler
)
.ToArray();
// yield sprinkler coverage
var covered = new HashSet<Vector2>();
var groups = new List<TileGroup>();
foreach (SObject sprinkler in sprinklers)
{
TileData[] tiles = this
.GetCoverage(sprinkler, sprinkler.TileLocation, customCoverageBySprinklerId, isHeld: false)
.Select(pos => new TileData(pos, this.Wet))
.ToArray();
foreach (TileData tile in tiles)
covered.Add(tile.TilePosition);
groups.Add(new TileGroup(tiles, outerBorderColor: sprinkler.TileLocation == cursorTile ? this.SelectedColor : this.Wet.Color));
}
// yield dry crops
var dryCrops = this
.GetDryCrops(location, visibleTiles, covered)
.Select(pos => new TileData(pos, this.Dry));
groups.Add(new TileGroup(dryCrops, outerBorderColor: this.Dry.Color));
// yield sprinkler being placed
SObject heldObj = Game1.player.ActiveObject;
if (this.IsSprinkler(heldObj, customCoverageBySprinklerId))
{
var tiles = this
.GetCoverage(heldObj, cursorTile, customCoverageBySprinklerId, isHeld: true)
.Select(pos => new TileData(pos, this.Wet, this.Wet.Color * 0.75f));
groups.Add(new TileGroup(tiles, outerBorderColor: this.SelectedColor, shouldExport: false));
}
return groups.ToArray();
}
/*********
** Private methods
*********/
/// <summary>Get whether a map terrain feature is a crop.</summary>
/// <param name="terrain">The map terrain feature.</param>
private bool IsCrop(TerrainFeature terrain)
{
return terrain is HoeDirt { crop: not null };
}
/// <summary>Get whether an object is a sprinkler.</summary>
/// <param name="sprinkler">The object to check.</param>
/// <param name="customCoverageBySprinklerId">The current relative sprinkler coverage, including any dynamic mod changes.</param>
private bool IsSprinkler(SObject sprinkler, IDictionary<int, Vector2[]> customCoverageBySprinklerId)
{
return
sprinkler != null
&& (
sprinkler.IsSprinkler()
|| (sprinkler.bigCraftable.Value && customCoverageBySprinklerId.ContainsKey(sprinkler.ParentSheetIndex)) // older custom sprinklers
);
}
/// <summary>Get the current relative sprinkler coverage, including any dynamic mod changes.</summary>
private IDictionary<int, Vector2[]> GetCustomSprinklerTiles()
{
var tilesBySprinklerID = new Dictionary<int, Vector2[]>();
// Better Sprinklers
if (this.Mods.BetterSprinklers.IsLoaded)
{
foreach (var pair in this.Mods.BetterSprinklers.GetSprinklerTiles())
tilesBySprinklerID[pair.Key] = pair.Value;
}
// Line Sprinklers
if (this.Mods.LineSprinklers.IsLoaded)
{
foreach (var pair in this.Mods.LineSprinklers.GetSprinklerTiles())
tilesBySprinklerID[pair.Key] = pair.Value;
}
// Simple Sprinkler
if (this.Mods.SimpleSprinkler.IsLoaded)
{
foreach (var pair in this.Mods.SimpleSprinkler.GetNewSprinklerTiles())
tilesBySprinklerID[pair.Key] = pair.Value;
}
return tilesBySprinklerID;
}
/// <summary>Get a sprinkler tile radius.</summary>
/// <param name="sprinkler">The sprinkler whose radius to get.</param>
/// <param name="origin">The sprinkler's tile.</param>
/// <param name="customSprinklerRanges">The custom sprinkler ranges centered on (0, 0) indexed by sprinkler ID.</param>
/// <param name="isHeld">Whether the player is holding the sprinkler.</param>
/// <remarks>Derived from <see cref="SObject.DayUpdate"/>.</remarks>
private IEnumerable<Vector2> GetCoverage(SObject sprinkler, Vector2 origin, IDictionary<int, Vector2[]> customSprinklerRanges, bool isHeld)
{
// get vanilla tiles
IEnumerable<Vector2> tiles = sprinkler.GetSprinklerTiles();
if (isHeld)
tiles = tiles.Select(tile => tile + origin); // when the sprinkler is held, the vanilla coverage is relative to (0, 0)
// add custom tiles
if (customSprinklerRanges.TryGetValue(sprinkler.ParentSheetIndex, out Vector2[] customTiles))
tiles = new HashSet<Vector2>(tiles.Concat(customTiles.Select(tile => tile + origin)));
return tiles;
}
/// <summary>Get tiles containing crops not covered by a sprinkler.</summary>
/// <param name="location">The current location.</param>
/// <param name="visibleTiles">The tiles currently visible on the screen.</param>
/// <param name="coveredTiles">The tiles covered by a sprinkler.</param>
private IEnumerable<Vector2> GetDryCrops(GameLocation location, Vector2[] visibleTiles, HashSet<Vector2> coveredTiles)
{
foreach (Vector2 tile in visibleTiles)
{
if (coveredTiles.Contains(tile))
continue;
if (location.terrainFeatures.TryGetValue(tile, out TerrainFeature terrain) && this.IsCrop(terrain))
yield return tile;
}
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Google.Protobuf.TestProtos;
using NUnit.Framework;
using ProtobufUnittest;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnitTest.Issues.TestProtos;
namespace Google.Protobuf.Reflection
{
/// <summary>
/// Tests for descriptors. (Not in its own namespace or broken up into individual classes as the
/// size doesn't warrant it. On the other hand, this makes me feel a bit dirty...)
/// </summary>
public class DescriptorsTest
{
[Test]
public void FileDescriptor_GeneratedCode()
{
TestFileDescriptor(
UnittestProto3Reflection.Descriptor,
UnittestImportProto3Reflection.Descriptor,
UnittestImportPublicProto3Reflection.Descriptor);
}
[Test]
public void FileDescriptor_BuildFromByteStrings()
{
// The descriptors have to be supplied in an order such that all the
// dependencies come before the descriptors depending on them.
var descriptorData = new List<ByteString>
{
UnittestImportPublicProto3Reflection.Descriptor.SerializedData,
UnittestImportProto3Reflection.Descriptor.SerializedData,
UnittestProto3Reflection.Descriptor.SerializedData
};
var converted = FileDescriptor.BuildFromByteStrings(descriptorData);
Assert.AreEqual(3, converted.Count);
TestFileDescriptor(converted[2], converted[1], converted[0]);
}
[Test]
public void FileDescriptor_BuildFromByteStrings_WithExtensionRegistry()
{
var extension = UnittestCustomOptionsProto3Extensions.MessageOpt1;
var byteStrings = new[]
{
DescriptorReflection.Descriptor.Proto.ToByteString(),
UnittestCustomOptionsProto3Reflection.Descriptor.Proto.ToByteString()
};
var registry = new ExtensionRegistry { extension };
var descriptor = FileDescriptor.BuildFromByteStrings(byteStrings, registry).Last();
var message = descriptor.MessageTypes.Single(t => t.Name == nameof(TestMessageWithCustomOptions));
var extensionValue = message.GetOptions().GetExtension(extension);
Assert.AreEqual(-56, extensionValue);
}
private void TestFileDescriptor(FileDescriptor file, FileDescriptor importedFile, FileDescriptor importedPublicFile)
{
Assert.AreEqual("unittest_proto3.proto", file.Name);
Assert.AreEqual("protobuf_unittest3", file.Package);
Assert.AreEqual("UnittestProto", file.Proto.Options.JavaOuterClassname);
Assert.AreEqual("unittest_proto3.proto", file.Proto.Name);
// unittest_proto3.proto doesn't have any public imports, but unittest_import_proto3.proto does.
Assert.AreEqual(0, file.PublicDependencies.Count);
Assert.AreEqual(1, importedFile.PublicDependencies.Count);
Assert.AreEqual(importedPublicFile, importedFile.PublicDependencies[0]);
Assert.AreEqual(1, file.Dependencies.Count);
Assert.AreEqual(importedFile, file.Dependencies[0]);
Assert.Null(file.FindTypeByName<MessageDescriptor>("NoSuchType"));
Assert.Null(file.FindTypeByName<MessageDescriptor>("protobuf_unittest3.TestAllTypes"));
for (int i = 0; i < file.MessageTypes.Count; i++)
{
Assert.AreEqual(i, file.MessageTypes[i].Index);
}
Assert.AreEqual(file.EnumTypes[0], file.FindTypeByName<EnumDescriptor>("ForeignEnum"));
Assert.Null(file.FindTypeByName<EnumDescriptor>("NoSuchType"));
Assert.Null(file.FindTypeByName<EnumDescriptor>("protobuf_unittest3.ForeignEnum"));
Assert.AreEqual(1, importedFile.EnumTypes.Count);
Assert.AreEqual("ImportEnum", importedFile.EnumTypes[0].Name);
for (int i = 0; i < file.EnumTypes.Count; i++)
{
Assert.AreEqual(i, file.EnumTypes[i].Index);
}
Assert.AreEqual(10, file.SerializedData[0]);
}
[Test]
public void FileDescriptor_NonRootPath()
{
// unittest_proto3.proto used to be in google/protobuf. Now it's in the C#-specific location,
// let's test something that's still in a directory.
FileDescriptor file = UnittestWellKnownTypesReflection.Descriptor;
Assert.AreEqual("google/protobuf/unittest_well_known_types.proto", file.Name);
Assert.AreEqual("protobuf_unittest", file.Package);
}
[Test]
public void FileDescriptor_BuildFromByteStrings_MissingDependency()
{
var descriptorData = new List<ByteString>
{
UnittestImportProto3Reflection.Descriptor.SerializedData,
UnittestProto3Reflection.Descriptor.SerializedData,
};
// This will fail, because we're missing UnittestImportPublicProto3Reflection
Assert.Throws<ArgumentException>(() => FileDescriptor.BuildFromByteStrings(descriptorData));
}
[Test]
public void FileDescriptor_BuildFromByteStrings_DuplicateNames()
{
var descriptorData = new List<ByteString>
{
UnittestImportPublicProto3Reflection.Descriptor.SerializedData,
UnittestImportPublicProto3Reflection.Descriptor.SerializedData,
};
// This will fail due to the same name being used twice
Assert.Throws<ArgumentException>(() => FileDescriptor.BuildFromByteStrings(descriptorData));
}
[Test]
public void FileDescriptor_BuildFromByteStrings_IncorrectOrder()
{
var descriptorData = new List<ByteString>
{
UnittestProto3Reflection.Descriptor.SerializedData,
UnittestImportPublicProto3Reflection.Descriptor.SerializedData,
UnittestImportProto3Reflection.Descriptor.SerializedData
};
// This will fail, because the dependencies should come first
Assert.Throws<ArgumentException>(() => FileDescriptor.BuildFromByteStrings(descriptorData));
}
[Test]
public void MessageDescriptorFromGeneratedCodeFileDescriptor()
{
var file = UnittestProto3Reflection.Descriptor;
MessageDescriptor messageType = TestAllTypes.Descriptor;
Assert.AreSame(typeof(TestAllTypes), messageType.ClrType);
Assert.AreSame(TestAllTypes.Parser, messageType.Parser);
Assert.AreEqual(messageType, file.MessageTypes[0]);
Assert.AreEqual(messageType, file.FindTypeByName<MessageDescriptor>("TestAllTypes"));
}
[Test]
public void MessageDescriptor()
{
MessageDescriptor messageType = TestAllTypes.Descriptor;
MessageDescriptor nestedType = TestAllTypes.Types.NestedMessage.Descriptor;
Assert.AreEqual("TestAllTypes", messageType.Name);
Assert.AreEqual("protobuf_unittest3.TestAllTypes", messageType.FullName);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, messageType.File);
Assert.IsNull(messageType.ContainingType);
Assert.IsNull(messageType.Proto.Options);
Assert.AreEqual("TestAllTypes", messageType.Name);
Assert.AreEqual("NestedMessage", nestedType.Name);
Assert.AreEqual("protobuf_unittest3.TestAllTypes.NestedMessage", nestedType.FullName);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, nestedType.File);
Assert.AreEqual(messageType, nestedType.ContainingType);
FieldDescriptor field = messageType.Fields.InDeclarationOrder()[0];
Assert.AreEqual("single_int32", field.Name);
Assert.AreEqual(field, messageType.FindDescriptor<FieldDescriptor>("single_int32"));
Assert.Null(messageType.FindDescriptor<FieldDescriptor>("no_such_field"));
Assert.AreEqual(field, messageType.FindFieldByNumber(1));
Assert.Null(messageType.FindFieldByNumber(571283));
var fieldsInDeclarationOrder = messageType.Fields.InDeclarationOrder();
for (int i = 0; i < fieldsInDeclarationOrder.Count; i++)
{
Assert.AreEqual(i, fieldsInDeclarationOrder[i].Index);
}
Assert.AreEqual(nestedType, messageType.NestedTypes[0]);
Assert.AreEqual(nestedType, messageType.FindDescriptor<MessageDescriptor>("NestedMessage"));
Assert.Null(messageType.FindDescriptor<MessageDescriptor>("NoSuchType"));
for (int i = 0; i < messageType.NestedTypes.Count; i++)
{
Assert.AreEqual(i, messageType.NestedTypes[i].Index);
}
Assert.AreEqual(messageType.EnumTypes[0], messageType.FindDescriptor<EnumDescriptor>("NestedEnum"));
Assert.Null(messageType.FindDescriptor<EnumDescriptor>("NoSuchType"));
for (int i = 0; i < messageType.EnumTypes.Count; i++)
{
Assert.AreEqual(i, messageType.EnumTypes[i].Index);
}
}
[Test]
public void FieldDescriptor_GeneratedCode()
{
TestFieldDescriptor(UnittestProto3Reflection.Descriptor, TestAllTypes.Descriptor, ForeignMessage.Descriptor, ImportMessage.Descriptor);
}
[Test]
public void FieldDescriptor_BuildFromByteStrings()
{
// The descriptors have to be supplied in an order such that all the
// dependencies come before the descriptors depending on them.
var descriptorData = new List<ByteString>
{
UnittestImportPublicProto3Reflection.Descriptor.SerializedData,
UnittestImportProto3Reflection.Descriptor.SerializedData,
UnittestProto3Reflection.Descriptor.SerializedData
};
var converted = FileDescriptor.BuildFromByteStrings(descriptorData);
TestFieldDescriptor(
converted[2],
converted[2].FindTypeByName<MessageDescriptor>("TestAllTypes"),
converted[2].FindTypeByName<MessageDescriptor>("ForeignMessage"),
converted[1].FindTypeByName<MessageDescriptor>("ImportMessage"));
}
public void TestFieldDescriptor(
FileDescriptor unitTestProto3Descriptor,
MessageDescriptor testAllTypesDescriptor,
MessageDescriptor foreignMessageDescriptor,
MessageDescriptor importMessageDescriptor)
{
FieldDescriptor primitiveField = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("single_int32");
FieldDescriptor enumField = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("single_nested_enum");
FieldDescriptor foreignMessageField = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("single_foreign_message");
FieldDescriptor importMessageField = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("single_import_message");
FieldDescriptor fieldInOneof = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("oneof_string");
Assert.AreEqual("single_int32", primitiveField.Name);
Assert.AreEqual("protobuf_unittest3.TestAllTypes.single_int32",
primitiveField.FullName);
Assert.AreEqual(1, primitiveField.FieldNumber);
Assert.AreEqual(testAllTypesDescriptor, primitiveField.ContainingType);
Assert.AreEqual(unitTestProto3Descriptor, primitiveField.File);
Assert.AreEqual(FieldType.Int32, primitiveField.FieldType);
Assert.IsNull(primitiveField.Proto.Options);
Assert.AreEqual("single_nested_enum", enumField.Name);
Assert.AreEqual(FieldType.Enum, enumField.FieldType);
Assert.AreEqual(testAllTypesDescriptor.EnumTypes[0], enumField.EnumType);
Assert.AreEqual("single_foreign_message", foreignMessageField.Name);
Assert.AreEqual(FieldType.Message, foreignMessageField.FieldType);
Assert.AreEqual(foreignMessageDescriptor, foreignMessageField.MessageType);
Assert.AreEqual("single_import_message", importMessageField.Name);
Assert.AreEqual(FieldType.Message, importMessageField.FieldType);
Assert.AreEqual(importMessageDescriptor, importMessageField.MessageType);
// For a field in a regular onoef, ContainingOneof and RealContainingOneof should be the same.
Assert.AreEqual("oneof_field", fieldInOneof.ContainingOneof.Name);
Assert.AreSame(fieldInOneof.ContainingOneof, fieldInOneof.RealContainingOneof);
}
[Test]
public void FieldDescriptorLabel()
{
FieldDescriptor singleField =
TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("single_int32");
FieldDescriptor repeatedField =
TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_int32");
Assert.IsFalse(singleField.IsRepeated);
Assert.IsTrue(repeatedField.IsRepeated);
}
[Test]
public void EnumDescriptor()
{
// Note: this test is a bit different to the Java version because there's no static way of getting to the descriptor
EnumDescriptor enumType = UnittestProto3Reflection.Descriptor.FindTypeByName<EnumDescriptor>("ForeignEnum");
EnumDescriptor nestedType = TestAllTypes.Descriptor.FindDescriptor<EnumDescriptor>("NestedEnum");
Assert.AreEqual("ForeignEnum", enumType.Name);
Assert.AreEqual("protobuf_unittest3.ForeignEnum", enumType.FullName);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, enumType.File);
Assert.Null(enumType.ContainingType);
Assert.Null(enumType.Proto.Options);
Assert.AreEqual("NestedEnum", nestedType.Name);
Assert.AreEqual("protobuf_unittest3.TestAllTypes.NestedEnum",
nestedType.FullName);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, nestedType.File);
Assert.AreEqual(TestAllTypes.Descriptor, nestedType.ContainingType);
EnumValueDescriptor value = enumType.FindValueByName("FOREIGN_FOO");
Assert.AreEqual(value, enumType.Values[1]);
Assert.AreEqual("FOREIGN_FOO", value.Name);
Assert.AreEqual(4, value.Number);
Assert.AreEqual((int) ForeignEnum.ForeignFoo, value.Number);
Assert.AreEqual(value, enumType.FindValueByNumber(4));
Assert.Null(enumType.FindValueByName("NO_SUCH_VALUE"));
for (int i = 0; i < enumType.Values.Count; i++)
{
Assert.AreEqual(i, enumType.Values[i].Index);
}
}
[Test]
public void OneofDescriptor()
{
OneofDescriptor descriptor = TestAllTypes.Descriptor.FindDescriptor<OneofDescriptor>("oneof_field");
Assert.IsFalse(descriptor.IsSynthetic);
Assert.AreEqual("oneof_field", descriptor.Name);
Assert.AreEqual("protobuf_unittest3.TestAllTypes.oneof_field", descriptor.FullName);
var expectedFields = new[] {
TestAllTypes.OneofBytesFieldNumber,
TestAllTypes.OneofNestedMessageFieldNumber,
TestAllTypes.OneofStringFieldNumber,
TestAllTypes.OneofUint32FieldNumber }
.Select(fieldNumber => TestAllTypes.Descriptor.FindFieldByNumber(fieldNumber))
.ToList();
foreach (var field in expectedFields)
{
Assert.AreSame(descriptor, field.ContainingOneof);
}
CollectionAssert.AreEquivalent(expectedFields, descriptor.Fields);
}
[Test]
public void MapEntryMessageDescriptor()
{
var descriptor = MapWellKnownTypes.Descriptor.NestedTypes[0];
Assert.IsNull(descriptor.Parser);
Assert.IsNull(descriptor.ClrType);
Assert.IsNull(descriptor.Fields[1].Accessor);
}
// From TestFieldOrdering:
// string my_string = 11;
// int64 my_int = 1;
// float my_float = 101;
// NestedMessage single_nested_message = 200;
[Test]
public void FieldListOrderings()
{
var fields = TestFieldOrderings.Descriptor.Fields;
Assert.AreEqual(new[] { 11, 1, 101, 200 }, fields.InDeclarationOrder().Select(x => x.FieldNumber));
Assert.AreEqual(new[] { 1, 11, 101, 200 }, fields.InFieldNumberOrder().Select(x => x.FieldNumber));
}
[Test]
public void DescriptorProtoFileDescriptor()
{
var descriptor = Google.Protobuf.Reflection.FileDescriptor.DescriptorProtoFileDescriptor;
Assert.AreEqual("google/protobuf/descriptor.proto", descriptor.Name);
}
[Test]
public void DescriptorImportingExtensionsFromOldCodeGen()
{
// The extension collection includes a null extension. There's not a lot we can do about that
// in itself, as the old generator didn't provide us the extension information.
var extensions = TestProtos.OldGenerator.OldExtensions2Reflection.Descriptor.Extensions;
Assert.AreEqual(1, extensions.UnorderedExtensions.Count);
// Note: this assertion is present so that it will fail if OldExtensions2 is regenerated
// with a new generator.
Assert.Null(extensions.UnorderedExtensions[0].Extension);
// ... but we can make sure we at least don't cause a failure when retrieving descriptors.
// In particular, old_extensions1.proto imports old_extensions2.proto, and this used to cause
// an execution-time failure.
var importingDescriptor = TestProtos.OldGenerator.OldExtensions1Reflection.Descriptor;
Assert.NotNull(importingDescriptor);
}
[Test]
public void Proto3OptionalDescriptors()
{
var descriptor = TestProto3Optional.Descriptor;
var field = descriptor.Fields[TestProto3Optional.OptionalInt32FieldNumber];
Assert.NotNull(field.ContainingOneof);
Assert.IsTrue(field.ContainingOneof.IsSynthetic);
Assert.Null(field.RealContainingOneof);
}
[Test]
public void SyntheticOneofReflection()
{
// Expect every oneof in TestProto3Optional to be synthetic
var proto3OptionalDescriptor = TestProto3Optional.Descriptor;
Assert.AreEqual(0, proto3OptionalDescriptor.RealOneofCount);
foreach (var oneof in proto3OptionalDescriptor.Oneofs)
{
Assert.True(oneof.IsSynthetic);
}
// Expect no oneof in the original proto3 unit test file to be synthetic.
foreach (var descriptor in ProtobufTestMessages.Proto3.TestMessagesProto3Reflection.Descriptor.MessageTypes)
{
Assert.AreEqual(descriptor.Oneofs.Count, descriptor.RealOneofCount);
foreach (var oneof in descriptor.Oneofs)
{
Assert.False(oneof.IsSynthetic);
}
}
// Expect no oneof in the original proto2 unit test file to be synthetic.
foreach (var descriptor in ProtobufTestMessages.Proto2.TestMessagesProto2Reflection.Descriptor.MessageTypes)
{
Assert.AreEqual(descriptor.Oneofs.Count, descriptor.RealOneofCount);
foreach (var oneof in descriptor.Oneofs)
{
Assert.False(oneof.IsSynthetic);
}
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.Forms.dll
// Description: The Windows Forms user interface layer for the DotSpatial.Symbology library.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 9/27/2009 8:18:57 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using DotSpatial.Data;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// BreakSliderGraph
/// </summary>
[DefaultEvent("SliderMoved")]
public class BreakSliderGraph : Control
{
/// <summary>
/// Occurs when manual break sliding begins so that the mode can be
/// switched to manual, rather than showing equal breaks or something.
/// </summary>
public event EventHandler<BreakSliderEventArgs> SliderMoving;
/// <summary>
/// Occurs when a click in a range changes the slider that is selected.
/// </summary>
public event EventHandler<BreakSliderEventArgs> SliderSelected;
/// <summary>
/// Occurs after the slider has been completely repositioned.
/// </summary>
public event EventHandler<BreakSliderEventArgs> SliderMoved;
/// <summary>
/// Occurs after the statistics have been re-calculated.
/// </summary>
public event EventHandler<StatisticalEventArgs> StatisticsUpdated;
/// <summary>
/// Given a scheme, this resets the graph extents to the statistical bounds.
/// </summary>
public void ResetExtents()
{
if (_graph == null) return;
Statistics stats;
if (_isRaster)
{
if (_raster == null) return;
stats = _rasterSymbolizer.Scheme.Statistics;
}
else
{
if (_scheme == null) return;
stats = _scheme.Statistics;
}
_graph.Minimum = stats.Minimum;
_graph.Maximum = stats.Maximum;
_graph.Mean = stats.Mean;
_graph.StandardDeviation = stats.StandardDeviation;
}
/// <summary>
///
/// </summary>
public void UpdateRasterBreaks()
{
if (_rasterLayer == null) return;
IColorCategory selectedBrk = null;
if (_selectedSlider != null) selectedBrk = _selectedSlider.Category as IColorCategory;
_breaks.Clear();
Statistics stats = _rasterSymbolizer.Scheme.Statistics;
Rectangle gb = _graph.GetGraphBounds();
_graph.ColorRanges.Clear();
foreach (IColorCategory category in _rasterSymbolizer.Scheme.Categories)
{
ColorRange cr = new ColorRange(category.LowColor, category.Range);
_graph.ColorRanges.Add(cr);
BreakSlider bs = new BreakSlider(gb, _graph.Minimum, _graph.Maximum, cr);
bs.Color = _breakColor;
bs.SelectColor = _selectedBreakColor;
if (selectedBrk != null && category == selectedBrk)
{
bs.Selected = true;
_selectedSlider = bs;
_graph.SelectedRange = cr;
}
if (category.Maximum != null)
{
bs.Value = double.Parse(category.Maximum.ToString());
}
else
{
bs.Value = stats.Maximum;
}
bs.Category = category;
_breaks.Add(bs);
}
_breaks.Sort();
// Moving a break generally affects both a maximum and a minimum.
// Point to the next category to actuate that.
for (int i = 0; i < _breaks.Count - 1; i++)
{
_breaks[i].NextCategory = _breaks[i + 1].Category;
// We use the maximums to set up breaks. Minimums should simply
// be set to work with the maximums of the previous category.
//_breaks[i + 1].Category.Minimum = _breaks[i].Value; REMOVED BY jany_ (2015-07-07) Don't set minimum, because that changes the minimum of the rasters category which causes the colors to change when saving in RasterColorControl without making changes or for example only applying opacity without wanting to use statistics.
}
if (_breaks.Count == 0) return;
int breakIndex = 0;
BreakSlider nextSlider = _breaks[breakIndex];
int count = 0;
if (_graph == null || _graph.Bins == null) return;
foreach (double value in _values)
{
if (value < nextSlider.Value)
{
count++;
continue;
}
nextSlider.Count = count;
while (value > nextSlider.Value)
{
breakIndex++;
if (breakIndex >= _breaks.Count)
{
break;
}
nextSlider = _breaks[breakIndex];
}
count = 0;
}
}
/// <summary>
/// Given a scheme, this will build the break list to match approximately. This does not
/// force the interval method to build a new scheme.
/// </summary>
public void UpdateBreaks()
{
if (_isRaster)
{
UpdateRasterBreaks();
return;
}
if (_scheme == null) return;
IFeatureCategory selectedCat = null;
if (_selectedSlider != null) selectedCat = _selectedSlider.Category as IFeatureCategory;
_breaks.Clear();
Statistics stats = _scheme.Statistics;
Rectangle gb = _graph.GetGraphBounds();
_graph.ColorRanges.Clear();
foreach (IFeatureCategory category in _scheme.GetCategories())
{
ColorRange cr = new ColorRange(category.GetColor(), category.Range);
_graph.ColorRanges.Add(cr);
BreakSlider bs = new BreakSlider(gb, _graph.Minimum, _graph.Maximum, cr);
bs.Color = _breakColor;
bs.SelectColor = _selectedBreakColor;
if (selectedCat != null && category == selectedCat)
{
bs.Selected = true;
_selectedSlider = bs;
_graph.SelectedRange = cr;
}
if (category.Maximum != null)
{
bs.Value = double.Parse(category.Maximum.ToString());
}
else
{
bs.Value = stats.Maximum;
}
bs.Category = category;
_breaks.Add(bs);
}
_breaks.Sort();
// Moving a break generally affects both a maximum and a minimum.
// Point to the next category to actuate that.
for (int i = 0; i < _breaks.Count - 1; i++)
{
_breaks[i].NextCategory = _breaks[i + 1].Category;
// We use the maximums to set up breaks. Minimums should simply
// be set to work with the maximums of the previous category.
_breaks[i + 1].Category.Minimum = _breaks[i].Value;
}
if (_breaks.Count == 0) return;
int breakIndex = 0;
BreakSlider nextSlider = _breaks[breakIndex];
int count = 0;
if (_graph == null || _graph.Bins == null) return;
foreach (double value in _values)
{
if (value < nextSlider.Value)
{
count++;
continue;
}
nextSlider.Count = count;
while (value > nextSlider.Value)
{
breakIndex++;
if (breakIndex >= _breaks.Count)
{
break;
}
nextSlider = _breaks[breakIndex];
}
count = 0;
}
}
private void UpdateBins()
{
if (_isRaster)
{
if (_raster == null) return;
}
else
{
if (_source == null && _table == null) return;
if (!IsValidField(_fieldName)) return;
}
ReadValues();
FillBins();
UpdateBreaks();
}
private bool IsValidField(string fieldName)
{
if (fieldName == null) return false;
if (_source != null) return _source.GetColumn(fieldName) != null;
return _table != null && _table.Columns.Contains(fieldName);
}
private void ReadValues()
{
if (_isRaster)
{
_values = _raster.GetRandomValues(_rasterSymbolizer.EditorSettings.MaxSampleCount);
_statistics.Calculate(_values, _rasterSymbolizer.EditorSettings.Min, _rasterSymbolizer.EditorSettings.Max);
if (_values == null) return;
return;
}
_values = _scheme.Values;
if (_values == null) return;
_scheme.Statistics.Calculate(_values);
}
private void FillBins()
{
if (_values == null) return;
double min = _graph.Minimum;
double max = _graph.Maximum;
if (min == max)
{
min = min - 10;
max = max + 10;
}
double binSize = (max - min) / _graph.NumColumns;
int numBins = _graph.NumColumns;
int[] bins = new int[numBins];
int maxBinCount = 0;
foreach (double val in _values)
{
if (val < min || val > max) continue;
int index = (int)Math.Ceiling((val - min) / binSize);
if (index >= numBins) index = numBins - 1;
bins[index]++;
if (bins[index] > maxBinCount)
{
maxBinCount = bins[index];
}
}
_graph.MaxBinCount = maxBinCount;
_graph.Bins = bins;
}
/// <summary>
/// Fires the statistics updated event
/// </summary>
protected virtual void OnStatisticsUpdated()
{
if (StatisticsUpdated != null)
{
StatisticsUpdated(this, new StatisticalEventArgs(_scheme.Statistics));
}
}
/// <summary>
/// Fires the SliderSelected event
/// </summary>
/// <param name="slider"></param>
protected virtual void OnSliderSelected(BreakSlider slider)
{
if (SliderSelected != null)
{
SliderSelected(this, new BreakSliderEventArgs(slider));
}
}
/// <summary>
/// Handles disposing to release unmanaged memory
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
if (_graph != null) _graph.Dispose();
base.Dispose(disposing);
}
#region Private Variables
private readonly List<BreakSlider> _breaks;
private BorderStyle _borderStyle;
private Color _breakColor;
private ContextMenu _contextMenu;
private bool _dragCursor;
private string _fieldName;
private BarGraph _graph;
private bool _isDragging;
private bool _isRaster;
private int _maxSampleSize;
private string _normalizationField;
private IRaster _raster;
private IRasterLayer _rasterLayer;
private IRasterSymbolizer _rasterSymbolizer;
private IFeatureScheme _scheme;
private Color _selectedBreakColor;
private BreakSlider _selectedSlider;
private IAttributeSource _source;
private Statistics _statistics;
private DataTable _table;
private List<double> _values;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of BreakSliderGraph
/// </summary>
public BreakSliderGraph()
{
_graph = new BarGraph(Width, Height);
_maxSampleSize = 10000;
_breaks = new List<BreakSlider>();
_selectedBreakColor = Color.Red;
_breakColor = Color.Blue;
TitleFont = new Font("Arial", 20, FontStyle.Bold);
_borderStyle = BorderStyle.Fixed3D;
_contextMenu = new ContextMenu();
_contextMenu.MenuItems.Add("Reset Zoom", ResetZoomClicked);
_contextMenu.MenuItems.Add("Zoom To Categories", CategoryZoomClicked);
_statistics = new Statistics();
}
#endregion
#region Methods
private void CategoryZoomClicked(object sender, EventArgs e)
{
ZoomToCategoryRange();
}
/// <summary>
/// Zooms so that the minimum is the minimum of the lowest category or else the
/// minimum of the extents, and the maximum is the maximum of the largest category
/// or else the maximum of the statistics.
/// </summary>
public void ZoomToCategoryRange()
{
if (_graph == null) return;
Statistics stats;
double? min;
double? max;
if (_isRaster)
{
if (_raster == null) return;
stats = _rasterSymbolizer.Scheme.Statistics;
min = _rasterSymbolizer.Scheme.Categories[0].Minimum;
max = _rasterSymbolizer.Scheme.Categories[_rasterSymbolizer.Scheme.Categories.Count - 1].Maximum;
}
else
{
if (_scheme == null) return;
stats = _scheme.Statistics;
IEnumerable<IFeatureCategory> cats = _scheme.GetCategories();
min = cats.First().Minimum;
max = cats.Last().Maximum;
}
_graph.Minimum = (min == null || min.Value < stats.Minimum) ? stats.Minimum : min.Value;
_graph.Maximum = (max == null || max.Value > stats.Maximum) ? stats.Maximum : max.Value;
FillBins();
UpdateBreaks();
Invalidate();
}
private void ResetZoomClicked(object sender, EventArgs e)
{
ResetZoom();
}
private void ResetZoom()
{
ResetExtents();
FillBins();
UpdateBreaks();
Invalidate();
}
/// <summary>
/// resets the breaks using the current settings, and generates a new set of
/// categories using the given interval method.
/// </summary>
public void ResetBreaks(ICancelProgressHandler handler)
{
if (_fieldName == null) return;
if (_scheme == null) return;
if (_scheme.EditorSettings == null) return;
if (_source != null)
{
_scheme.CreateCategories(_source, handler);
}
else
{
if (_table == null) return;
_scheme.CreateCategories(_table);
}
ResetZoom();
}
/// <summary>
/// Selects one of the specific breaks.
/// </summary>
/// <param name="slider"></param>
public void SelectBreak(BreakSlider slider)
{
if (_selectedSlider != null) _selectedSlider.Selected = false;
_selectedSlider = slider;
if (_selectedSlider != null)
{
_selectedSlider.Selected = true;
_graph.SelectedRange = _selectedSlider.Range;
}
}
/// <summary>
/// occurs during a resize
/// </summary>
/// <param name="e"></param>
protected override void OnResize(EventArgs e)
{
_graph.Width = Width;
_graph.Height = Height;
base.OnResize(e);
Invalidate();
}
/// <summary>
/// When the mouse wheel event occurs, this forwards the event to this contro.
/// </summary>
public void DoMouseWheel(int delta, float x)
{
double val = _graph.GetValue(x);
if (delta > 0)
{
_graph.Minimum = _graph.Minimum + (val - _graph.Minimum) / 2;
_graph.Maximum = _graph.Maximum - (_graph.Maximum - val) / 2;
}
else
{
_graph.Minimum = _graph.Minimum - (val - _graph.Minimum);
_graph.Maximum = _graph.Maximum + (_graph.Maximum - val);
}
if (_isRaster)
{
if (_graph.Minimum < _rasterSymbolizer.Scheme.Statistics.Minimum) _graph.Minimum = _rasterSymbolizer.Scheme.Statistics.Minimum;
if (_graph.Maximum > _rasterSymbolizer.Scheme.Statistics.Maximum) _graph.Maximum = _rasterSymbolizer.Scheme.Statistics.Maximum;
}
else
{
if (_graph.Minimum < _scheme.Statistics.Minimum) _graph.Minimum = _scheme.Statistics.Minimum;
if (_graph.Maximum > _scheme.Statistics.Maximum) _graph.Maximum = _scheme.Statistics.Maximum;
}
FillBins();
UpdateBreaks();
Invalidate();
}
/// <summary>
/// Occurs when the mose down occurs
/// </summary>
/// <param name="e"></param>
protected override void OnMouseDown(MouseEventArgs e)
{
Focus();
if (e.Button == MouseButtons.Right)
{
_contextMenu.Show(this, e.Location);
return;
}
foreach (BreakSlider slider in _breaks)
{
if (!slider.Bounds.Contains(e.Location) && !slider.HandleBounds.Contains(e.Location)) continue;
// not sure if this works right. Hopefully, just the little rectangles form a double region.
Region rg = new Region();
if (_selectedSlider != null)
{
rg.Union(_selectedSlider.Bounds);
_selectedSlider.Selected = false;
}
_selectedSlider = slider;
slider.Selected = true;
rg.Union(_selectedSlider.Bounds);
Invalidate(rg);
_isDragging = true;
OnSliderMoving();
return;
}
if (_selectedSlider != null) _selectedSlider.Selected = false;
_selectedSlider = null;
base.OnMouseDown(e);
}
/// <summary>
/// Occurs when the slider moves
/// </summary>
protected virtual void OnSliderMoving()
{
if (SliderMoving != null)
{
SliderMoving(this, new BreakSliderEventArgs(_selectedSlider));
}
}
/// <summary>
/// Handles the mouse move event
/// </summary>
/// <param name="e"></param>
protected override void OnMouseMove(MouseEventArgs e)
{
if (_isDragging)
{
Region rg = new Region();
Rectangle gb = _graph.GetGraphBounds();
if (_selectedSlider != null)
{
rg.Union(_selectedSlider.Bounds);
int x = e.X;
int index = _breaks.IndexOf(_selectedSlider);
if (x > gb.Right) x = gb.Right;
if (x < gb.Left) x = gb.Left;
if (index > 0)
{
if (x < _breaks[index - 1].Position + 2) x = (int)_breaks[index - 1].Position + 2;
}
if (index < _breaks.Count - 1)
{
if (x > _breaks[index + 1].Position - 2) x = (int)_breaks[index + 1].Position - 2;
}
_selectedSlider.Position = x;
rg.Union(_selectedSlider.Bounds);
Invalidate(rg);
}
return;
}
bool overSlider = false;
foreach (BreakSlider slider in _breaks)
{
if (slider.Bounds.Contains(e.Location) || slider.HandleBounds.Contains(e.Location))
{
overSlider = true;
}
}
if (_dragCursor && !overSlider)
{
Cursor = Cursors.Arrow;
_dragCursor = false;
}
if (!_dragCursor && overSlider)
{
_dragCursor = true;
Cursor = Cursors.SizeWE;
}
base.OnMouseMove(e);
}
/// <summary>
/// Handles the mouse up event
/// </summary>
/// <param name="e"></param>
protected override void OnMouseUp(MouseEventArgs e)
{
if (_isDragging)
{
_isDragging = false;
_selectedSlider.Category.Maximum = _selectedSlider.Value;
if (_isRaster)
{
_rasterSymbolizer.Scheme.ApplySnapping(_selectedSlider.Category);
_selectedSlider.Category.ApplyMinMax(_rasterSymbolizer.Scheme.EditorSettings);
}
else
{
_scheme.ApplySnapping(_selectedSlider.Category);
_selectedSlider.Category.ApplyMinMax(_scheme.EditorSettings);
}
if (_selectedSlider.NextCategory != null)
{
_selectedSlider.NextCategory.Minimum = _selectedSlider.Value;
if (_isRaster)
{
_rasterSymbolizer.Scheme.ApplySnapping(_selectedSlider.NextCategory);
_selectedSlider.Category.ApplyMinMax(_rasterSymbolizer.Scheme.EditorSettings);
}
else
{
_scheme.ApplySnapping(_selectedSlider.NextCategory);
_selectedSlider.NextCategory.ApplyMinMax(_scheme.EditorSettings);
}
}
OnSliderMoved();
Invalidate();
return;
}
BreakSlider s = GetBreakAt(e.Location);
SelectBreak(s);
OnSliderSelected(s);
Invalidate();
base.OnMouseUp(e);
}
/// <summary>
/// Given a break slider's new position, this will update the category related to that
/// break.
/// </summary>
/// <param name="slider"></param>
public void UpdateCategory(BreakSlider slider)
{
slider.Category.Maximum = slider.Value;
slider.Category.ApplyMinMax(_scheme.EditorSettings);
int index = _breaks.IndexOf(slider);
if (index < 0) return;
if (index < _breaks.Count - 1)
{
_breaks[index + 1].Category.Minimum = slider.Value;
_breaks[index + 1].Category.ApplyMinMax(_scheme.EditorSettings);
}
}
/// <summary>
/// Returns the BreakSlider that corresponds to the specified mouse position, where
/// the actual handle and divider represent the maximum of that range.
/// </summary>
/// <param name="location">The location, which can be anywhere to the left of the slider but to the
/// right of any other sliders.</param>
/// <returns>The BreakSlider that covers the range that contains the location, or null.</returns>
public BreakSlider GetBreakAt(Point location)
{
if (location.X < 0) return null;
foreach (BreakSlider slider in _breaks)
{
if (slider.Position < location.X) continue;
return slider;
}
return null;
}
/// <summary>
/// Fires the slider moved event
/// </summary>
protected virtual void OnSliderMoved()
{
if (SliderMoved != null) SliderMoved(this, new BreakSliderEventArgs(_selectedSlider));
}
/// <summary>
/// Occurs during drawing
/// </summary>
/// <param name="g"></param>
/// <param name="clip"></param>
protected virtual void OnDraw(Graphics g, Rectangle clip)
{
if (Height <= 1 || Width <= 1) return;
// Draw text first because the text is used to auto-fit the remaining graph.
_graph.Draw(g, clip);
if (_borderStyle == BorderStyle.Fixed3D)
{
g.DrawLine(Pens.White, 0, Height - 1, Width - 1, Height - 1);
g.DrawLine(Pens.White, Width - 1, 0, Width - 1, Height - 1);
g.DrawLine(Pens.Gray, 0, 0, 0, Height - 1);
g.DrawLine(Pens.Gray, 0, 0, Width - 1, 0);
}
if (_borderStyle == BorderStyle.FixedSingle)
{
g.DrawRectangle(Pens.Black, 0, 0, Width - 1, Height - 1);
}
if (_breaks == null) return;
Rectangle gb = _graph.GetGraphBounds();
foreach (BreakSlider slider in _breaks)
{
slider.Setup(gb, _graph.Minimum, _graph.Maximum);
if (slider.Bounds.IntersectsWith(clip)) slider.Draw(g);
}
}
/// <summary>
/// prevents flicker by preventing the white background being drawn here
/// </summary>
/// <param name="pevent"></param>
protected override void OnPaintBackground(PaintEventArgs pevent)
{
//base.OnPaintBackground(pevent);
}
/// <summary>
/// Custom drawing
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
Rectangle clip = e.ClipRectangle;
if (clip.IsEmpty) clip = ClientRectangle;
Bitmap bmp = new Bitmap(clip.Width, clip.Height);
Graphics g = Graphics.FromImage(bmp);
g.TranslateTransform(-clip.X, -clip.Y);
g.Clip = new Region(clip);
g.Clear(BackColor);
g.SmoothingMode = SmoothingMode.AntiAlias;
OnDraw(g, clip);
g.Dispose();
e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the attribute source.
/// </summary>
public IAttributeSource AttributeSource
{
get { return _source; }
set
{
_source = value;
UpdateBins();
}
}
/// <summary>
/// Gets or sets the border style for this control
/// </summary>
public BorderStyle BorderStyle
{
get { return _borderStyle; }
set { _borderStyle = value; }
}
/// <summary>
/// Gets the list of breaks that are currently part of this graph.
/// </summary>
public List<BreakSlider> Breaks
{
get { return _breaks; }
}
/// <summary>
/// Gets or sets the color to use for the moveable breaks.
/// </summary>
public Color BreakColor
{
get { return _breakColor; }
set
{
_breakColor = value;
if (_breaks == null) return;
foreach (BreakSlider slider in _breaks)
{
slider.Color = value;
}
}
}
/// <summary>
/// Gets or sets the color to use when a break is selected
/// </summary>
public Color BreakSelectedColor
{
get { return _selectedBreakColor; }
set
{
_selectedBreakColor = value;
if (_breaks == null) return;
foreach (BreakSlider slider in _breaks)
{
slider.SelectColor = value;
}
}
}
/// <summary>
/// Gets or sets the font color
/// </summary>
[Category("Appearance"), Description("Gets or sets the color for the axis labels")]
public Color FontColor
{
get
{
if (_graph != null) return _graph.Font.Color;
return Color.Black;
}
set
{
if (_graph != null) _graph.Font.Color = value;
}
}
/// <summary>
/// Gets or sets the number of columns. Setting this will recalculate the bins.
/// </summary>
[Category("Behavior"), Description("Gets or sets the number of columns representing the data histogram")]
public int NumColumns
{
get
{
if (_graph == null) return 0;
return _graph.NumColumns;
}
set
{
if (_graph == null) return;
_graph.NumColumns = value;
FillBins();
UpdateBreaks();
Invalidate();
}
}
/// <summary>
/// The method to use when breaks are calculated or reset
/// </summary>
public IntervalMethod IntervalMethod
{
get
{
if (_scheme == null) return IntervalMethod.EqualInterval;
if (_scheme.EditorSettings == null) return IntervalMethod.EqualInterval;
return _scheme.EditorSettings.IntervalMethod;
}
set
{
if (_scheme == null) return;
if (_scheme.EditorSettings == null) return;
_scheme.EditorSettings.IntervalMethod = value;
UpdateBreaks();
}
}
/// <summary>
/// Boolean, if this is true, the mean will be shown as a blue dotted line.
/// </summary>
[Category("Appearance"), Description("Boolean, if this is true, the mean will be shown as a blue dotted line.")]
public bool ShowMean
{
get
{
return _graph != null && _graph.ShowMean;
}
set
{
if (_graph != null)
{
_graph.ShowMean = value;
Invalidate();
}
}
}
/// <summary>
/// Boolean, if this is true, the integral standard deviations from the mean will be drawn
/// as red dotted lines.
/// </summary>
[Category("Appearance"), Description("Boolean, if this is true, the integral standard deviations from the mean will be drawn as red dotted lines.")]
public bool ShowStandardDeviation
{
get
{
return _graph != null && _graph.ShowStandardDeviation;
}
set
{
if (_graph != null)
{
_graph.ShowStandardDeviation = value;
Invalidate();
}
}
}
/// <summary>
/// Gets or sets the data Table for which the statistics should be applied
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DataTable Table
{
get { return _table; }
set
{
_table = value;
UpdateBins();
}
}
/// <summary>
/// Gets or sets the title of the graph.
/// </summary>
[Category("Appearance"), Description("Gets or sets the title of the graph.")]
public string Title
{
get
{
return (_graph != null) ? _graph.Title : null;
}
set
{
if (_graph != null) _graph.Title = value;
}
}
/// <summary>
/// Gets or sets the color to use for the graph title
/// </summary>
[Category("Appearance"), Description("Gets or sets the color to use for the graph title.")]
public Color TitleColor
{
get { return (_graph != null) ? _graph.TitleFont.Color : Color.Black; }
set { if (_graph != null) _graph.TitleFont.Color = value; }
}
/// <summary>
/// Gets or sets the font to use for the graph title
/// </summary>
[Category("Appearance"), Description("Gets or sets the font to use for the graph title.")]
public Font TitleFont
{
get
{
return _graph == null ? null : _graph.TitleFont.GetFont();
}
set
{
if (_graph != null) _graph.TitleFont.SetFont(value);
}
}
/// <summary>
/// Gets or sets the string field name
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Fieldname
{
get { return _fieldName; }
set
{
_fieldName = value;
UpdateBins();
}
}
/// <summary>
/// Gets or sets the string normalization field
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string NormalizationField
{
get { return _normalizationField; }
set
{
_normalizationField = value;
UpdateBins();
}
}
/// <summary>
/// Very small counts frequently dissappear next to big counts. One strategey is to use a
/// minimum height, so that the difference between 0 and 1 is magnified on the columns.
/// </summary>
public int MinHeight
{
get { return (_graph != null) ? _graph.MinHeight : 20; }
set { if (_graph != null) _graph.MinHeight = value; }
}
/// <summary>
/// Gets or sets the maximum sample size to use when calculating statistics.
/// The default is 10000.
/// </summary>
[Category("Behavior"), Description("Gets or sets the maximum sample size to use when calculating statistics.")]
public int MaximumSampleSize
{
get { return _maxSampleSize; }
set { _maxSampleSize = value; }
}
/// <summary>
/// Gets the statistics that have been currently calculated for this graph.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Statistics Statistics
{
get
{
if (_isRaster)
{
return _statistics;
}
return _scheme == null ? null : _scheme.Statistics;
}
}
/// <summary>
/// Gets or sets the scheme that is currently being used to symbolize the values.
/// Setting this automatically updates the graph extents to the statistical bounds
/// of the scheme.
/// </summary>
public IFeatureScheme Scheme
{
get { return _scheme; }
set
{
_scheme = value;
_isRaster = false;
ResetExtents();
UpdateBreaks();
}
}
/// <summary>
/// Gets or sets the raster layer. This will also force this control to use
/// the raster for calculations, rather than the dataset.
/// </summary>
public IRasterLayer RasterLayer
{
get { return _rasterLayer; }
set
{
_rasterLayer = value;
if (value == null) return;
_isRaster = true;
_raster = _rasterLayer.DataSet;
_rasterSymbolizer = _rasterLayer.Symbolizer;
ResetExtents();
UpdateBins();
}
}
/// <summary>
/// Gets or sets a boolean that indicates whether or not count values should be drawn with
/// heights that are proportional to the logarithm of the count, instead of the count itself.
/// </summary>
public bool LogY
{
get { return _graph != null && _graph.LogY; }
set
{
if (_graph != null)
{
_graph.LogY = value;
Invalidate();
}
}
}
#endregion
}
}
| |
// 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!
namespace Google.Apis.DoubleClickBidManager.v1_1
{
/// <summary>The DoubleClickBidManager Service.</summary>
public class DoubleClickBidManagerService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1.1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public DoubleClickBidManagerService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public DoubleClickBidManagerService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Queries = new QueriesResource(this);
Reports = new ReportsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "doubleclickbidmanager";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://doubleclickbidmanager.googleapis.com/doubleclickbidmanager/v1.1/";
#else
"https://doubleclickbidmanager.googleapis.com/doubleclickbidmanager/v1.1/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "doubleclickbidmanager/v1.1/";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://doubleclickbidmanager.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the DoubleClick Bid Manager API.</summary>
public class Scope
{
/// <summary>View and manage your reports in DoubleClick Bid Manager</summary>
public static string Doubleclickbidmanager = "https://www.googleapis.com/auth/doubleclickbidmanager";
}
/// <summary>Available OAuth 2.0 scope constants for use with the DoubleClick Bid Manager API.</summary>
public static class ScopeConstants
{
/// <summary>View and manage your reports in DoubleClick Bid Manager</summary>
public const string Doubleclickbidmanager = "https://www.googleapis.com/auth/doubleclickbidmanager";
}
/// <summary>Gets the Queries resource.</summary>
public virtual QueriesResource Queries { get; }
/// <summary>Gets the Reports resource.</summary>
public virtual ReportsResource Reports { get; }
}
/// <summary>A base abstract class for DoubleClickBidManager requests.</summary>
public abstract class DoubleClickBidManagerBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new DoubleClickBidManagerBaseServiceRequest instance.</summary>
protected DoubleClickBidManagerBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes DoubleClickBidManager parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "queries" collection of methods.</summary>
public class QueriesResource
{
private const string Resource = "queries";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public QueriesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates a query.</summary>
/// <param name="body">The body of the request.</param>
public virtual CreatequeryRequest Createquery(Google.Apis.DoubleClickBidManager.v1_1.Data.Query body)
{
return new CreatequeryRequest(service, body);
}
/// <summary>Creates a query.</summary>
public class CreatequeryRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1_1.Data.Query>
{
/// <summary>Constructs a new Createquery request.</summary>
public CreatequeryRequest(Google.Apis.Services.IClientService service, Google.Apis.DoubleClickBidManager.v1_1.Data.Query body) : base(service)
{
Body = body;
InitParameters();
}
/// <summary>
/// If true, tries to run the query asynchronously. Only applicable when the frequency is ONE_TIME.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("asynchronous", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Asynchronous { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.DoubleClickBidManager.v1_1.Data.Query Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "createquery";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "query";
/// <summary>Initializes Createquery parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("asynchronous", new Google.Apis.Discovery.Parameter
{
Name = "asynchronous",
IsRequired = false,
ParameterType = "query",
DefaultValue = "false",
Pattern = null,
});
}
}
/// <summary>Deletes a stored query as well as the associated stored reports.</summary>
/// <param name="queryId">Query ID to delete.</param>
public virtual DeletequeryRequest Deletequery(long queryId)
{
return new DeletequeryRequest(service, queryId);
}
/// <summary>Deletes a stored query as well as the associated stored reports.</summary>
public class DeletequeryRequest : DoubleClickBidManagerBaseServiceRequest<string>
{
/// <summary>Constructs a new Deletequery request.</summary>
public DeletequeryRequest(Google.Apis.Services.IClientService service, long queryId) : base(service)
{
QueryId = queryId;
InitParameters();
}
/// <summary>Query ID to delete.</summary>
[Google.Apis.Util.RequestParameterAttribute("queryId", Google.Apis.Util.RequestParameterType.Path)]
public virtual long QueryId { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "deletequery";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "query/{queryId}";
/// <summary>Initializes Deletequery parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("queryId", new Google.Apis.Discovery.Parameter
{
Name = "queryId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Retrieves a stored query.</summary>
/// <param name="queryId">Query ID to retrieve.</param>
public virtual GetqueryRequest Getquery(long queryId)
{
return new GetqueryRequest(service, queryId);
}
/// <summary>Retrieves a stored query.</summary>
public class GetqueryRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1_1.Data.Query>
{
/// <summary>Constructs a new Getquery request.</summary>
public GetqueryRequest(Google.Apis.Services.IClientService service, long queryId) : base(service)
{
QueryId = queryId;
InitParameters();
}
/// <summary>Query ID to retrieve.</summary>
[Google.Apis.Util.RequestParameterAttribute("queryId", Google.Apis.Util.RequestParameterType.Path)]
public virtual long QueryId { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getquery";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "query/{queryId}";
/// <summary>Initializes Getquery parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("queryId", new Google.Apis.Discovery.Parameter
{
Name = "queryId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Retrieves stored queries.</summary>
public virtual ListqueriesRequest Listqueries()
{
return new ListqueriesRequest(service);
}
/// <summary>Retrieves stored queries.</summary>
public class ListqueriesRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1_1.Data.ListQueriesResponse>
{
/// <summary>Constructs a new Listqueries request.</summary>
public ListqueriesRequest(Google.Apis.Services.IClientService service) : base(service)
{
InitParameters();
}
/// <summary>
/// Maximum number of results per page. Must be between 1 and 100. Defaults to 100 if unspecified.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>Optional pagination token.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "listqueries";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "queries";
/// <summary>Initializes Listqueries parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Runs a stored query to generate a report.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="queryId">Query ID to run.</param>
public virtual RunqueryRequest Runquery(Google.Apis.DoubleClickBidManager.v1_1.Data.RunQueryRequest body, long queryId)
{
return new RunqueryRequest(service, body, queryId);
}
/// <summary>Runs a stored query to generate a report.</summary>
public class RunqueryRequest : DoubleClickBidManagerBaseServiceRequest<string>
{
/// <summary>Constructs a new Runquery request.</summary>
public RunqueryRequest(Google.Apis.Services.IClientService service, Google.Apis.DoubleClickBidManager.v1_1.Data.RunQueryRequest body, long queryId) : base(service)
{
QueryId = queryId;
Body = body;
InitParameters();
}
/// <summary>Query ID to run.</summary>
[Google.Apis.Util.RequestParameterAttribute("queryId", Google.Apis.Util.RequestParameterType.Path)]
public virtual long QueryId { get; private set; }
/// <summary>If true, tries to run the query asynchronously.</summary>
[Google.Apis.Util.RequestParameterAttribute("asynchronous", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Asynchronous { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.DoubleClickBidManager.v1_1.Data.RunQueryRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "runquery";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "query/{queryId}";
/// <summary>Initializes Runquery parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("queryId", new Google.Apis.Discovery.Parameter
{
Name = "queryId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("asynchronous", new Google.Apis.Discovery.Parameter
{
Name = "asynchronous",
IsRequired = false,
ParameterType = "query",
DefaultValue = "false",
Pattern = null,
});
}
}
}
/// <summary>The "reports" collection of methods.</summary>
public class ReportsResource
{
private const string Resource = "reports";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ReportsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Retrieves stored reports.</summary>
/// <param name="queryId">Query ID with which the reports are associated.</param>
public virtual ListreportsRequest Listreports(long queryId)
{
return new ListreportsRequest(service, queryId);
}
/// <summary>Retrieves stored reports.</summary>
public class ListreportsRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1_1.Data.ListReportsResponse>
{
/// <summary>Constructs a new Listreports request.</summary>
public ListreportsRequest(Google.Apis.Services.IClientService service, long queryId) : base(service)
{
QueryId = queryId;
InitParameters();
}
/// <summary>Query ID with which the reports are associated.</summary>
[Google.Apis.Util.RequestParameterAttribute("queryId", Google.Apis.Util.RequestParameterType.Path)]
public virtual long QueryId { get; private set; }
/// <summary>
/// Maximum number of results per page. Must be between 1 and 100. Defaults to 100 if unspecified.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>Optional pagination token.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "listreports";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "queries/{queryId}/reports";
/// <summary>Initializes Listreports parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("queryId", new Google.Apis.Discovery.Parameter
{
Name = "queryId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.DoubleClickBidManager.v1_1.Data
{
/// <summary>
/// A channel grouping defines a set of rules that can be used to categorize events in a path report.
/// </summary>
public class ChannelGrouping : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The name to apply to an event that does not match any of the rules in the channel grouping.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("fallbackName")]
public virtual string FallbackName { get; set; }
/// <summary>Channel Grouping name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// Rules within Channel Grouping. There is a limit of 100 rules that can be set per channel grouping.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("rules")]
public virtual System.Collections.Generic.IList<Rule> Rules { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>DisjunctiveMatchStatement that OR's all contained filters.</summary>
public class DisjunctiveMatchStatement : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Filters. There is a limit of 100 filters that can be set per disjunctive match statement.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("eventFilters")]
public virtual System.Collections.Generic.IList<EventFilter> EventFilters { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Defines the type of filter to be applied to the path, a DV360 event dimension filter.</summary>
public class EventFilter : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Filter on a dimension.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("dimensionFilter")]
public virtual PathQueryOptionsFilter DimensionFilter { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Filter used to match traffic data in your report.</summary>
public class FilterPair : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Filter type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>Filter value.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual string Value { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>List queries response.</summary>
public class ListQueriesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Identifies what kind of resource this is. Value: the fixed string
/// "doubleclickbidmanager#listQueriesResponse".
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Next page's pagination token if one exists.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>Retrieved queries.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queries")]
public virtual System.Collections.Generic.IList<Query> Queries { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>List reports response.</summary>
public class ListReportsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Identifies what kind of resource this is. Value: the fixed string
/// "doubleclickbidmanager#listReportsResponse".
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Next page's pagination token if one exists.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>Retrieved reports.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reports")]
public virtual System.Collections.Generic.IList<Report> Reports { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Additional query options.</summary>
public class Options : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Set to true and filter your report by `FILTER_INSERTION_ORDER` or `FILTER_LINE_ITEM` to include data for
/// audience lists specifically targeted by those items.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("includeOnlyTargetedUserLists")]
public virtual System.Nullable<bool> IncludeOnlyTargetedUserLists { get; set; }
/// <summary>Options that contain Path Filters and Custom Channel Groupings.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pathQueryOptions")]
public virtual PathQueryOptions PathQueryOptions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Parameters of a query or report.</summary>
public class Parameters : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Filters used to match traffic data in your report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("filters")]
public virtual System.Collections.Generic.IList<FilterPair> Filters { get; set; }
/// <summary>Data is grouped by the filters listed in this field.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("groupBys")]
public virtual System.Collections.Generic.IList<string> GroupBys { get; set; }
/// <summary>Deprecated. This field is no longer in use.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("includeInviteData")]
public virtual System.Nullable<bool> IncludeInviteData { get; set; }
/// <summary>Metrics to include as columns in your report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metrics")]
public virtual System.Collections.Generic.IList<string> Metrics { get; set; }
/// <summary>Additional query options.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("options")]
public virtual Options Options { get; set; }
/// <summary>Report type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Path filters specify which paths to include in a report. A path is the result of combining DV360 events based on
/// User ID to create a workflow of users' actions. When a path filter is set, the resulting report will only
/// include paths that match the specified event at the specified position. All other paths will be excluded.
/// </summary>
public class PathFilter : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Filter on an event to be applied to some part of the path.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("eventFilters")]
public virtual System.Collections.Generic.IList<EventFilter> EventFilters { get; set; }
/// <summary>
/// Indicates the position of the path the filter should match to (first, last, or any event in path).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("pathMatchPosition")]
public virtual string PathMatchPosition { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Path Query Options for Report Options.</summary>
public class PathQueryOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Custom Channel Groupings.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("channelGrouping")]
public virtual ChannelGrouping ChannelGrouping { get; set; }
/// <summary>Path Filters. There is a limit of 100 path filters that can be set per report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pathFilters")]
public virtual System.Collections.Generic.IList<PathFilter> PathFilters { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Dimension Filter on path events.</summary>
public class PathQueryOptionsFilter : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Dimension the filter is applied to.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("filter")]
public virtual string Filter { get; set; }
/// <summary>Indicates how the filter should be matched to the value.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("match")]
public virtual string Match { get; set; }
/// <summary>Value to filter on.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("values")]
public virtual System.Collections.Generic.IList<string> Values { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a query.</summary>
public class Query : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Identifies what kind of resource this is. Value: the fixed string "doubleclickbidmanager#query".
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Query metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual QueryMetadata Metadata { get; set; }
/// <summary>Query parameters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("params")]
public virtual Parameters Params__ { get; set; }
/// <summary>Query ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queryId")]
public virtual System.Nullable<long> QueryId { get; set; }
/// <summary>
/// The ending time for the data that is shown in the report. Note, reportDataEndTimeMs is required if
/// metadata.dataRange is CUSTOM_DATES and ignored otherwise.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportDataEndTimeMs")]
public virtual System.Nullable<long> ReportDataEndTimeMs { get; set; }
/// <summary>
/// The starting time for the data that is shown in the report. Note, reportDataStartTimeMs is required if
/// metadata.dataRange is CUSTOM_DATES and ignored otherwise.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportDataStartTimeMs")]
public virtual System.Nullable<long> ReportDataStartTimeMs { get; set; }
/// <summary>Information on how often and when to run a query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("schedule")]
public virtual QuerySchedule Schedule { get; set; }
/// <summary>Canonical timezone code for report data time. Defaults to America/New_York.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("timezoneCode")]
public virtual string TimezoneCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Query metadata.</summary>
public class QueryMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Range of report data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("dataRange")]
public virtual string DataRange { get; set; }
/// <summary>Format of the generated report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("format")]
public virtual string Format { get; set; }
/// <summary>The path to the location in Google Cloud Storage where the latest report is stored.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("googleCloudStoragePathForLatestReport")]
public virtual string GoogleCloudStoragePathForLatestReport { get; set; }
/// <summary>The path in Google Drive for the latest report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("googleDrivePathForLatestReport")]
public virtual string GoogleDrivePathForLatestReport { get; set; }
/// <summary>The time when the latest report started to run.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("latestReportRunTimeMs")]
public virtual System.Nullable<long> LatestReportRunTimeMs { get; set; }
/// <summary>
/// Locale of the generated reports. Valid values are cs CZECH de GERMAN en ENGLISH es SPANISH fr FRENCH it
/// ITALIAN ja JAPANESE ko KOREAN pl POLISH pt-BR BRAZILIAN_PORTUGUESE ru RUSSIAN tr TURKISH uk UKRAINIAN zh-CN
/// CHINA_CHINESE zh-TW TAIWAN_CHINESE An locale string not in the list above will generate reports in English.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("locale")]
public virtual string Locale { get; set; }
/// <summary>Number of reports that have been generated for the query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportCount")]
public virtual System.Nullable<int> ReportCount { get; set; }
/// <summary>Whether the latest report is currently running.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("running")]
public virtual System.Nullable<bool> Running { get; set; }
/// <summary>Whether to send an email notification when a report is ready. Default to false.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sendNotification")]
public virtual System.Nullable<bool> SendNotification { get; set; }
/// <summary>
/// List of email addresses which are sent email notifications when the report is finished. Separate from
/// sendNotification.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("shareEmailAddress")]
public virtual System.Collections.Generic.IList<string> ShareEmailAddress { get; set; }
/// <summary>Query title. It is used to name the reports generated from this query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Information on how frequently and when to run a query.</summary>
public class QuerySchedule : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Datetime to periodically run the query until.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTimeMs")]
public virtual System.Nullable<long> EndTimeMs { get; set; }
/// <summary>How often the query is run.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("frequency")]
public virtual string Frequency { get; set; }
/// <summary>
/// Time of day at which a new report will be generated, represented as minutes past midnight. Range is 0 to
/// 1439. Only applies to scheduled reports.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextRunMinuteOfDay")]
public virtual System.Nullable<int> NextRunMinuteOfDay { get; set; }
/// <summary>Canonical timezone code for report generation time. Defaults to America/New_York.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextRunTimezoneCode")]
public virtual string NextRunTimezoneCode { get; set; }
/// <summary>When to start running the query. Not applicable to `ONE_TIME` frequency.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startTimeMs")]
public virtual System.Nullable<long> StartTimeMs { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a report.</summary>
public class Report : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Key used to identify a report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("key")]
public virtual ReportKey Key { get; set; }
/// <summary>Report metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual ReportMetadata Metadata { get; set; }
/// <summary>Report parameters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("params")]
public virtual Parameters Params__ { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An explanation of a report failure.</summary>
public class ReportFailure : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Error code that shows why the report was not created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorCode")]
public virtual string ErrorCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Key used to identify a report.</summary>
public class ReportKey : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Query ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queryId")]
public virtual System.Nullable<long> QueryId { get; set; }
/// <summary>Report ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportId")]
public virtual System.Nullable<long> ReportId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Report metadata.</summary>
public class ReportMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The path to the location in Google Cloud Storage where the report is stored.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("googleCloudStoragePath")]
public virtual string GoogleCloudStoragePath { get; set; }
/// <summary>The ending time for the data that is shown in the report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportDataEndTimeMs")]
public virtual System.Nullable<long> ReportDataEndTimeMs { get; set; }
/// <summary>The starting time for the data that is shown in the report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportDataStartTimeMs")]
public virtual System.Nullable<long> ReportDataStartTimeMs { get; set; }
/// <summary>Report status.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("status")]
public virtual ReportStatus Status { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Report status.</summary>
public class ReportStatus : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>If the report failed, this records the cause.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("failure")]
public virtual ReportFailure Failure { get; set; }
/// <summary>The time when this report either completed successfully or failed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("finishTimeMs")]
public virtual System.Nullable<long> FinishTimeMs { get; set; }
/// <summary>The file type of the report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("format")]
public virtual string Format { get; set; }
/// <summary>The state of the report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A Rule defines a name, and a boolean expression in [conjunctive normal form](http:
/// //mathworld.wolfram.com/ConjunctiveNormalForm.html){.external} that can be // applied to a path event to
/// determine if that name should be applied.
/// </summary>
public class Rule : Google.Apis.Requests.IDirectResponseSchema
{
[Newtonsoft.Json.JsonPropertyAttribute("disjunctiveMatchStatements")]
public virtual System.Collections.Generic.IList<DisjunctiveMatchStatement> DisjunctiveMatchStatements { get; set; }
/// <summary>Rule name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request to run a stored query to generate a report.</summary>
public class RunQueryRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Report data range used to generate the report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("dataRange")]
public virtual string DataRange { get; set; }
/// <summary>
/// The ending time for the data that is shown in the report. Note, reportDataEndTimeMs is required if dataRange
/// is CUSTOM_DATES and ignored otherwise.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportDataEndTimeMs")]
public virtual System.Nullable<long> ReportDataEndTimeMs { get; set; }
/// <summary>
/// The starting time for the data that is shown in the report. Note, reportDataStartTimeMs is required if
/// dataRange is CUSTOM_DATES and ignored otherwise.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportDataStartTimeMs")]
public virtual System.Nullable<long> ReportDataStartTimeMs { get; set; }
/// <summary>Canonical timezone code for report data time. Defaults to America/New_York.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("timezoneCode")]
public virtual string TimezoneCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// Copyright (c) 2002-2019 "Neo4j,"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Reactive.Testing;
using Neo4j.Driver.IntegrationTests.Shared;
using Neo4j.Driver.Internal;
using Neo4j.Driver.Internal.Connector;
using Neo4j.Driver.Internal.Metrics;
using Neo4j.Driver.Internal.Types;
using Neo4j.Driver.Reactive;
using Xunit.Abstractions;
using static Neo4j.Driver.IntegrationTests.VersionComparison;
namespace Neo4j.Driver.IntegrationTests.Stress
{
public abstract class StressTest<TContext> : IDisposable
where TContext : StressTestContext
{
private const bool LoggingEnabled = false;
private const int StressTestThreadCount = 8;
private const int StressTestAsyncBatchSize = 10;
private static readonly TimeSpan StressTestExecutionTime = TimeSpan.FromSeconds(30);
private const int BigDataTestBatchCount = 3;
private const int BigDataTestBatchSize = 10_000;
private const int BigDataTestBatchBuffer = 500;
private const int PoolTestThreadCount = 50;
private static readonly TimeSpan PoolTestDuration = TimeSpan.FromSeconds(15);
protected readonly ITestOutputHelper _output;
protected readonly IDriver _driver;
private readonly IAuthToken _authToken;
private readonly Uri _databaseUri;
protected StressTest(ITestOutputHelper output, Uri databaseUri, IAuthToken authToken)
{
_output = output ?? throw new ArgumentNullException(nameof(output));
_databaseUri = databaseUri;
_authToken = authToken;
_driver = GraphDatabase.Driver(databaseUri, authToken,
Config.Builder.WithDriverLogger(new StressTestLogger(_output, LoggingEnabled))
.WithMaxConnectionPoolSize(100).WithConnectionAcquisitionTimeout(TimeSpan.FromMinutes(1))
.ToConfig());
CleanupDatabase();
}
#region Abstract Members
protected abstract TContext CreateContext();
protected abstract IEnumerable<IBlockingCommand<TContext>> CreateTestSpecificBlockingCommands();
protected abstract IEnumerable<IAsyncCommand<TContext>> CreateTestSpecificAsyncCommands();
protected abstract IEnumerable<IRxCommand<TContext>> CreateTestSpecificRxCommands();
protected abstract void PrintStats(TContext context);
protected abstract void VerifyReadQueryDistribution(TContext context);
public abstract bool HandleWriteFailure(Exception error, TContext context);
#endregion
#region Blocking Stress Test
[RequireServerFact]
public async Task Blocking()
{
await RunStressTest(LaunchBlockingWorkers);
}
private IList<IBlockingCommand<TContext>> CreateBlockingCommands()
{
var result = new List<IBlockingCommand<TContext>>
{
new BlockingReadCommand<TContext>(_driver, false),
new BlockingReadCommand<TContext>(_driver, true),
new BlockingReadCommandInTx<TContext>(_driver, false),
new BlockingReadCommandInTx<TContext>(_driver, true),
new BlockingWriteCommand<TContext>(this, _driver, false),
new BlockingWriteCommand<TContext>(this, _driver, true),
new BlockingWriteCommandInTx<TContext>(this, _driver, false),
new BlockingWriteCommandInTx<TContext>(this, _driver, true),
new BlockingWrongCommand<TContext>(_driver),
new BlockingWrongCommandInTx<TContext>(_driver),
new BlockingFailingCommand<TContext>(_driver),
new BlockingFailingCommandInTx<TContext>(_driver)
};
result.AddRange(CreateTestSpecificBlockingCommands());
return result;
}
private IEnumerable<Task> LaunchBlockingWorkers(TContext context)
{
var commands = CreateBlockingCommands();
var tasks = new List<Task>();
for (var i = 0; i < StressTestThreadCount; i++)
{
tasks.Add(LaunchBlockingWorkerThread(context, commands));
}
return tasks;
}
private static Task LaunchBlockingWorkerThread(TContext context, IList<IBlockingCommand<TContext>> commands)
{
return Task.Factory.StartNew(() =>
{
while (!context.Stopped)
{
commands.RandomElement().Execute(context);
}
}, TaskCreationOptions.LongRunning);
}
#endregion
#region Async Stress Test
[RequireServerFact]
public async Task Async()
{
await RunStressTest(LaunchAsyncWorkers);
}
private IList<IAsyncCommand<TContext>> CreateAsyncCommands()
{
var result = new List<IAsyncCommand<TContext>>
{
new AsyncReadCommand<TContext>(_driver, false),
new AsyncReadCommand<TContext>(_driver, true),
new AsyncReadCommandInTx<TContext>(_driver, false),
new AsyncReadCommandInTx<TContext>(_driver, true),
new AsyncWriteCommand<TContext>(this, _driver, false),
new AsyncWriteCommand<TContext>(this, _driver, true),
new AsyncWriteCommandInTx<TContext>(this, _driver, false),
new AsyncWriteCommandInTx<TContext>(this, _driver, true),
new AsyncWrongCommand<TContext>(_driver),
new AsyncWrongCommandInTx<TContext>(_driver),
new AsyncFailingCommand<TContext>(_driver),
new AsyncFailingCommandInTx<TContext>(_driver)
};
result.AddRange(CreateTestSpecificAsyncCommands());
return result;
}
private IEnumerable<Task> LaunchAsyncWorkers(TContext context)
{
var commands = CreateAsyncCommands();
var tasks = new List<Task>();
for (var i = 0; i < StressTestThreadCount; i++)
{
tasks.Add(LaunchAsyncWorkerThread(context, commands));
}
return tasks;
}
private static Task LaunchAsyncWorkerThread(TContext context, IList<IAsyncCommand<TContext>> commands)
{
return Task.Factory.StartNew(() =>
{
while (!context.Stopped)
{
Task.WaitAll(Enumerable.Range(1, StressTestAsyncBatchSize)
.Select(_ => commands.RandomElement().ExecuteAsync(context))
.ToArray());
}
}, TaskCreationOptions.LongRunning);
}
#endregion
#region Reactive Stress Test
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task Reactive()
{
await RunStressTest(LaunchRxWorkers);
}
private IList<IRxCommand<TContext>> CreateRxCommands()
{
var result = new List<IRxCommand<TContext>>
{
new RxReadCommand<TContext>(_driver, false),
new RxReadCommand<TContext>(_driver, true),
new RxReadCommandInTx<TContext>(_driver, false),
new RxReadCommandInTx<TContext>(_driver, true),
new RxWriteCommand<TContext>(this, _driver, false),
new RxWriteCommand<TContext>(this, _driver, true),
new RxWriteCommandInTx<TContext>(this, _driver, false),
new RxWriteCommandInTx<TContext>(this, _driver, true),
new RxWrongCommand<TContext>(_driver),
new RxWrongCommandInTx<TContext>(_driver),
new RxFailingCommand<TContext>(_driver),
new RxFailingCommandInTx<TContext>(_driver)
};
result.AddRange(CreateTestSpecificRxCommands());
return result;
}
private IEnumerable<Task> LaunchRxWorkers(TContext context)
{
var commands = CreateRxCommands();
var tasks = new List<Task>();
for (var i = 0; i < StressTestThreadCount; i++)
{
tasks.Add(LaunchRxWorkerThread(context, commands));
}
return tasks;
}
private static Task LaunchRxWorkerThread(TContext context, IList<IRxCommand<TContext>> commands)
{
return Task.Factory.StartNew(() =>
{
while (!context.Stopped)
{
Task.WaitAll(Enumerable.Range(1, StressTestAsyncBatchSize)
.Select(_ => commands.RandomElement().ExecuteAsync(context))
.ToArray());
}
}, TaskCreationOptions.LongRunning);
}
#endregion
#region Async Big Data Tests
[RequireServerFact]
public async Task AsyncBigData()
{
var bookmark = await CreateNodesAsync(BigDataTestBatchCount, BigDataTestBatchSize, BigDataTestBatchBuffer,
_driver);
await ReadNodesAsync(_driver, bookmark, BigDataTestBatchCount * BigDataTestBatchSize);
}
private async Task<Bookmark> CreateNodesAsync(int batchCount, int batchSize, int batchBuffer, IDriver driver)
{
var timer = Stopwatch.StartNew();
var session = driver.AsyncSession();
try
{
for (var batchIndex = 0; batchIndex < batchCount; batchIndex++)
{
await session.WriteTransactionAsync(txc => Task.WhenAll(
Enumerable.Range(1, batchSize)
.Select(index => (batchIndex * batchSize) + index)
.Batch(batchBuffer)
.Select(indices =>
txc.RunAsync(CreateBatchNodesStatement(indices))
.ContinueWith(t => t.Result.ConsumeAsync()).Unwrap()).ToArray()));
}
}
finally
{
await session.CloseAsync();
}
_output.WriteLine("Creating nodes with Async API took: {0}ms", timer.ElapsedMilliseconds);
return session.LastBookmark;
}
private Statement CreateBatchNodesStatement(IEnumerable<int> batch)
{
return new Statement("UNWIND $values AS props CREATE (n:Test:Node) SET n = props", new
{
values = batch.Select(nodeIndex => new
{
index = nodeIndex,
name = $"name-{nodeIndex}",
surname = $"surname-{nodeIndex}",
longList = Enumerable.Repeat((long) nodeIndex, 10),
doubleList = Enumerable.Repeat((double) nodeIndex, 10),
boolList = Enumerable.Repeat(nodeIndex % 2 == 0, 10),
})
});
}
private async Task ReadNodesAsync(IDriver driver, Bookmark bookmark, int expectedNodes)
{
var timer = Stopwatch.StartNew();
var session = driver.AsyncSession(o => o.WithDefaultAccessMode(AccessMode.Read).WithBookmarks(bookmark));
try
{
await session.ReadTransactionAsync(async txc =>
{
var records = await txc.RunAsync("MATCH (n:Node) RETURN n ORDER BY n.index")
.ContinueWith(r => r.Result.ToListAsync())
.Unwrap();
records.Select(r => r[0].As<INode>())
.Should().BeEquivalentTo(
Enumerable.Range(1, expectedNodes).Select(index =>
new
{
Labels = new[] {"Test", "Node"},
Properties = new Dictionary<string, object>(6)
{
{"index", (long) index},
{"name", $"name-{index}"},
{"surname", $"surname-{index}"},
{
"longList",
Enumerable.Repeat((long) index, 10)
},
{
"doubleList",
Enumerable.Repeat((double) index, 10)
},
{
"boolList",
Enumerable.Repeat(index % 2 == 0, 10)
},
}
}), opts => opts.Including(x => x.Labels).Including(x => x.Properties));
});
}
finally
{
await session.CloseAsync();
}
_output.WriteLine("Reading nodes with Async API took: {0}ms", timer.ElapsedMilliseconds);
}
#endregion
#region Blocking Big Data Tests
[RequireServerFact]
public void BlockingBigData()
{
var bookmark = CreateNodes(BigDataTestBatchCount, BigDataTestBatchSize, BigDataTestBatchBuffer,
_driver);
ReadNodes(_driver, bookmark, BigDataTestBatchCount * BigDataTestBatchSize);
}
private Bookmark CreateNodes(int batchCount, int batchSize, int batchBuffer, IDriver driver)
{
var timer = Stopwatch.StartNew();
using (var session = driver.Session())
{
for (var batchIndex = 0; batchIndex < batchCount; batchIndex++)
{
var index = batchIndex;
session.WriteTransaction(txc =>
Enumerable.Range(1, batchSize)
.Select(item => (index * batchSize) + item)
.Batch(batchBuffer).Select(indices => txc.Run(CreateBatchNodesStatement(indices)).Consume())
.ToArray());
}
_output.WriteLine("Creating nodes with Sync API took: {0}ms", timer.ElapsedMilliseconds);
return session.LastBookmark;
}
}
private void ReadNodes(IDriver driver, Bookmark bookmark, int expectedNodes)
{
var timer = Stopwatch.StartNew();
using (var session = driver.Session(o => o.WithDefaultAccessMode(AccessMode.Read).WithBookmarks(bookmark)))
{
session.ReadTransaction(txc =>
{
var result = txc.Run("MATCH (n:Node) RETURN n ORDER BY n.index");
result.Select(r => r[0].As<INode>())
.Should().BeEquivalentTo(
Enumerable.Range(1, expectedNodes).Select(index =>
new
{
Labels = new[] {"Test", "Node"},
Properties = new Dictionary<string, object>(6)
{
{"index", (long) index},
{"name", $"name-{index}"},
{"surname", $"surname-{index}"},
{
"longList",
Enumerable.Repeat((long) index, 10)
},
{
"doubleList",
Enumerable.Repeat((double) index, 10)
},
{
"boolList",
Enumerable.Repeat(index % 2 == 0, 10)
},
}
}), opts => opts.Including(x => x.Labels).Including(x => x.Properties));
return result.Summary;
});
}
_output.WriteLine("Reading nodes with Sync API took: {0}ms", timer.ElapsedMilliseconds);
}
#endregion
#region Reactive Big Data Tests
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public void ReactiveBigData()
{
var bookmark = CreateNodesRx(BigDataTestBatchCount, BigDataTestBatchSize, BigDataTestBatchBuffer,
_driver);
ReadNodesRx(_driver, bookmark, BigDataTestBatchCount * BigDataTestBatchSize);
}
private Bookmark CreateNodesRx(int batchCount, int batchSize, int batchBuffer, IDriver driver)
{
var timer = Stopwatch.StartNew();
var session = driver.RxSession();
Observable.Range(0, batchCount).Select(batchIndex =>
session.WriteTransaction(txc => Observable.Range(1, batchSize)
.Select(index => (batchIndex * batchSize) + index)
.Buffer(batchBuffer)
.SelectMany(batch => txc.Run(CreateBatchNodesStatement(batch)).Summary())
))
.Concat()
.Concat(session.Close<IResultSummary>()).CatchAndThrow(_ => session.Close<IResultSummary>())
.Wait();
_output.WriteLine("Creating nodes with Async API took: {0}ms", timer.ElapsedMilliseconds);
return session.LastBookmark;
}
private void ReadNodesRx(IDriver driver, Bookmark bookmark, int expectedNodes)
{
var timer = Stopwatch.StartNew();
var session = driver.RxSession(o => o.WithDefaultAccessMode(AccessMode.Read).WithBookmarks(bookmark));
session.ReadTransaction(txc =>
txc.Run("MATCH (n:Node) RETURN n ORDER BY n.index").Records().Select(r => r[0].As<INode>()).Do(n =>
{
var index = n.Properties["index"].As<int>();
n.Should().BeEquivalentTo(
new
{
Labels = new[] {"Test", "Node"},
Properties = new Dictionary<string, object>(6)
{
{"index", (long) index},
{"name", $"name-{index}"},
{"surname", $"surname-{index}"},
{
"longList",
Enumerable.Repeat((long) index, 10)
},
{
"doubleList",
Enumerable.Repeat((double) index, 10)
},
{
"boolList",
Enumerable.Repeat(index % 2 == 0, 10)
},
}
}, opts => opts.Including(x => x.Labels).Including(x => x.Properties));
}))
.Concat(session.Close<INode>())
.CatchAndThrow(_ => session.Close<INode>())
.Wait();
_output.WriteLine("Reading nodes with Async API took: {0}ms", timer.ElapsedMilliseconds);
}
#endregion
#region Pooling Stress Tests
[RequireServerFact]
public void Pool()
{
var tokenSource = new CancellationTokenSource();
var failure = new AtomicReference<Exception>(null);
var tasks = LaunchPoolWorkers(_driver, tokenSource.Token, worker => worker.RunWithNoTx(), failure);
Thread.Sleep(PoolTestDuration);
tokenSource.Cancel();
Task.WaitAll(tasks);
failure.Get().Should().BeNull("Some workers have failed");
}
[RequireServerFact]
public void PoolWithTxFunc()
{
var tokenSource = new CancellationTokenSource();
var failure = new AtomicReference<Exception>(null);
var tasks = LaunchPoolWorkers(_driver, tokenSource.Token, worker => worker.RunWithTxFunc(), failure);
Thread.Sleep(PoolTestDuration);
tokenSource.Cancel();
Task.WaitAll(tasks);
failure.Get().Should().BeNull("Some workers have failed");
}
[RequireServerFact]
public void PoolWithTxFuncWithFailingConnections()
{
var tokenSource = new CancellationTokenSource();
var failure = new AtomicReference<Exception>(null);
var (driver, connections) = SetupMonitoredDriver();
var terminator = LaunchConnectionTerminator(connections, tokenSource.Token);
var tasks = LaunchPoolWorkers(driver, tokenSource.Token, worker => worker.RunWithTxFunc(), failure);
Thread.Sleep(PoolTestDuration);
tokenSource.Cancel();
Task.WaitAll(tasks.Union(new[] {terminator}).ToArray());
failure.Get().Should().BeNull("no workers should fail");
}
private static Task[] LaunchPoolWorkers(IDriver driver, CancellationToken token, Action<Worker> job,
AtomicReference<Exception> failure)
{
var tasks = new List<Task>();
for (var i = 0; i < PoolTestThreadCount; i++)
{
tasks.Add(Task.Factory.StartNew(() =>
{
var worker = new Worker(driver, token, failure);
job(worker);
}, TaskCreationOptions.LongRunning));
}
return tasks.ToArray();
}
private (IDriver, ConcurrentQueue<IPooledConnection>) SetupMonitoredDriver()
{
var config = new Config
{
MetricsFactory = new DefaultMetricsFactory(),
ConnectionAcquisitionTimeout = TimeSpan.FromMinutes(5),
ConnectionTimeout = Config.InfiniteInterval,
MaxConnectionPoolSize = 100,
DriverLogger = new StressTestLogger(_output, LoggingEnabled)
};
var connectionSettings = new ConnectionSettings(_authToken, config);
var bufferSettings = new BufferSettings(config);
var connectionFactory = new MonitoredPooledConnectionFactory(
new PooledConnectionFactory(connectionSettings, bufferSettings, config.DriverLogger));
return ((Internal.Driver) GraphDatabase.CreateDriver(_databaseUri, config, connectionFactory),
connectionFactory.Connections);
}
private Task LaunchConnectionTerminator(ConcurrentQueue<IPooledConnection> connections, CancellationToken token)
{
return Task.Factory.StartNew(async () =>
{
const int minimalConnCount = 3;
while (!token.IsCancellationRequested)
{
if (connections.Count > minimalConnCount && connections.TryDequeue(out var conn))
{
if (conn.Server.Version != null)
{
await conn.DestroyAsync();
_output.WriteLine($"Terminator killed connection {conn} towards server {conn.Server}");
}
else
{
// connection is still being initialized, put it back to the connections list
connections.Enqueue(conn);
}
}
else
{
_output.WriteLine("Terminator failed to find a open connection to kill.");
}
try
{
await Task.Delay(1000, token); // sleep
}
catch (TaskCanceledException)
{
// we are fine with cancelled sleep
}
}
}, TaskCreationOptions.LongRunning);
}
private class Worker
{
private
static
readonly
(AccessMode, string)[]
Queries =
{
(AccessMode.Read, "RETURN 1295+42"), (AccessMode.Write,
"UNWIND range(1,10000) AS x CREATE (n {prop:x}) DELETE n")
};
private readonly IDriver _driver;
private readonly CancellationToken _token;
private readonly Random _rnd = new Random();
private readonly AtomicReference<Exception> _failure;
public Worker(IDriver driver, CancellationToken token, AtomicReference<Exception> failure)
{
_driver = driver ?? throw new ArgumentNullException(nameof(driver));
_token = token;
_failure = failure;
}
public void RunWithNoTx()
{
try
{
while (!_token.IsCancellationRequested)
{
foreach (var (accessMode, statement) in Queries)
{
RunWithNoTx(accessMode, statement);
}
}
}
catch (Exception exc)
{
_failure.CompareAndSet(exc, null);
}
}
public void RunWithTxFunc()
{
try
{
while (!_token.IsCancellationRequested)
{
foreach (var (accessMode, statement) in Queries)
{
RunWithTxFunc(accessMode, statement);
}
}
}
catch (Exception exc)
{
_failure.CompareAndSet(exc, null);
}
}
private void RunWithNoTx(AccessMode mode, string statement)
{
using (var session = _driver.Session(o => o.WithDefaultAccessMode(mode)))
{
Execute(session, statement);
}
}
private void RunWithTxFunc(AccessMode mode, string statement)
{
using (var session = _driver.Session())
{
switch (mode)
{
case AccessMode.Read:
session.ReadTransaction(txc => Execute(txc, statement));
break;
case AccessMode.Write:
session.WriteTransaction(txc => Execute(txc, statement));
break;
default:
throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
}
}
}
private IResultSummary Execute(IStatementRunner runner, string statement)
{
var result = runner.Run(statement);
Thread.Sleep(_rnd.Next(100));
result.Consume();
Thread.Sleep(_rnd.Next(100));
return result.Summary;
}
}
private class AtomicReference<T>
where T : class
{
private volatile T _reference;
public AtomicReference(T reference)
{
_reference = reference;
}
public T Get()
{
return _reference;
}
public bool CompareAndSet(T value, T comparand)
{
return Interlocked.CompareExchange(ref _reference, value, comparand) == comparand;
}
}
private class MonitoredPooledConnectionFactory : IPooledConnectionFactory
{
private readonly IPooledConnectionFactory _delegate;
public readonly ConcurrentQueue<IPooledConnection> Connections = new ConcurrentQueue<IPooledConnection>();
public MonitoredPooledConnectionFactory(IPooledConnectionFactory factory)
{
_delegate = factory;
}
public IPooledConnection Create(Uri uri, IConnectionReleaseManager releaseManager,
IConnectionListener metricsListener)
{
var pooledConnection = _delegate.Create(uri, releaseManager, metricsListener);
Connections.Enqueue(pooledConnection);
return pooledConnection;
}
}
#endregion
#region Test and Verifications
private async Task RunStressTest(Func<TContext, IEnumerable<Task>> launcher)
{
var context = CreateContext();
var workers = launcher(context);
await Task.Delay(StressTestExecutionTime);
context.Stop();
await Task.WhenAll(workers);
PrintStats(context);
VerifyResults(context);
}
private void VerifyResults(TContext context)
{
VerifyNodesCreated(context.CreatedNodesCount);
VerifyReadQueryDistribution(context);
}
private void VerifyNodesCreated(long expected)
{
using (var session = _driver.Session(o => o.WithDefaultAccessMode(AccessMode.Write)))
{
var count = session.Run("MATCH (n) RETURN count(n) as createdNodes")
.Select(r => r["createdNodes"].As<long>()).Single();
count.Should().Be(expected);
}
}
#endregion
#region Cleanup
public void Dispose()
{
CleanupDatabase();
}
private void CleanupDatabase()
{
using (var session = _driver.Session(o => o.WithDefaultAccessMode(AccessMode.Write)))
{
session.Run("MATCH (n) DETACH DELETE n").Consume();
}
}
#endregion
private class StressTestLogger : IDriverLogger
{
private readonly ITestOutputHelper _output;
private readonly bool _enabled;
public StressTestLogger(ITestOutputHelper output, bool enabled)
{
_output = output ?? throw new ArgumentNullException(nameof(output));
_enabled = enabled;
}
private void Write(string message, params object[] args)
{
if (_enabled)
{
_output.WriteLine(message, args);
}
}
public void Error(Exception cause, string message, params object[] args)
{
Write(string.Format($"{message} - caused by{Environment.NewLine}{0}", cause), args);
}
public void Warn(Exception cause, string message, params object[] args)
{
Write(string.Format($"{message} - caused by{Environment.NewLine}{0}", cause), args);
}
public void Info(string message, params object[] args)
{
Write(message, args);
}
public void Debug(string message, params object[] args)
{
Write(message, args);
}
public void Trace(string message, params object[] args)
{
Write(message, args);
}
public bool IsTraceEnabled()
{
return false;
}
public bool IsDebugEnabled()
{
return true;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using OpenIddict.Core;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Navigation;
using OrchardCore.OpenId.Models;
using OrchardCore.OpenId.Services;
using OrchardCore.OpenId.ViewModels;
using OrchardCore.Security.Services;
using OrchardCore.Settings;
using OrchardCore.Users;
namespace OrchardCore.OpenId.Controllers
{
public class AdminController : Controller
{
private readonly IAuthorizationService _authorizationService;
private readonly IStringLocalizer<AdminController> T;
private readonly IHtmlLocalizer<AdminController> H;
private readonly ISiteService _siteService;
private readonly IShapeFactory _shapeFactory;
private readonly IRoleProvider _roleProvider;
private readonly OpenIddictApplicationManager<OpenIdApplication> _applicationManager;
private readonly OpenIdApplicationStore _applicationStore;
private readonly INotifier _notifier;
private readonly IOpenIdService _openIdService;
private readonly IEnumerable<IPasswordValidator<IUser>> _passwordValidators;
private readonly UserManager<IUser> _userManager;
private readonly IOptions<IdentityOptions> _identityOptions;
public AdminController(
IShapeFactory shapeFactory,
ISiteService siteService,
IStringLocalizer<AdminController> stringLocalizer,
IAuthorizationService authorizationService,
IRoleProvider roleProvider,
OpenIddictApplicationManager<OpenIdApplication> applicationManager,
OpenIdApplicationStore applicationStore,
IEnumerable<IPasswordValidator<IUser>> passwordValidators,
UserManager<IUser> userManager,
IOptions<IdentityOptions> identityOptions,
IHtmlLocalizer<AdminController> htmlLocalizer,
INotifier notifier,
IOpenIdService openIdService)
{
_shapeFactory = shapeFactory;
_siteService = siteService;
T = stringLocalizer;
H = htmlLocalizer;
_authorizationService = authorizationService;
_applicationManager = applicationManager;
_roleProvider = roleProvider;
_applicationStore = applicationStore;
_notifier = notifier;
_openIdService = openIdService;
_passwordValidators = passwordValidators;
_userManager = userManager;
_identityOptions = identityOptions;
}
public async Task<ActionResult> Index(PagerParameters pagerParameters)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOpenIdApplications))
{
return Unauthorized();
}
var openIdSettings = await _openIdService.GetOpenIdSettingsAsync();
if (!_openIdService.IsValidOpenIdSettings(openIdSettings))
{
_notifier.Warning(H["OpenID Connect settings are not properly configured."]);
}
var siteSettings = await _siteService.GetSiteSettingsAsync();
var pager = new Pager(pagerParameters, siteSettings.PageSize);
var results = await _applicationStore.GetAppsAsync(pager.GetStartIndex(), pager.PageSize);
var pagerShape = _shapeFactory.Create("Pager", new { TotalItemCount = await _applicationStore.GetCount() });
var model = new OpenIdApplicationsIndexViewModel
{
Applications = results
.Select(x => new OpenIdApplicationEntry { Application = x })
.ToList(),
Pager = pagerShape
};
return View(model);
}
public async Task<IActionResult> Edit(string id, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOpenIdApplications))
{
return Unauthorized();
}
var openIdSettings = await _openIdService.GetOpenIdSettingsAsync();
if (!_openIdService.IsValidOpenIdSettings(openIdSettings))
{
_notifier.Warning(H["OpenID Connect settings are not properly configured."]);
}
var application = await _applicationManager.FindByIdAsync(id, HttpContext.RequestAborted);
if (application == null)
{
return NotFound();
}
var model = new EditOpenIdApplicationViewModel()
{
Id = id,
DisplayName = application.DisplayName,
RedirectUri = application.RedirectUri,
LogoutRedirectUri = application.LogoutRedirectUri,
ClientId = application.ClientId,
Type = application.Type,
SkipConsent = application.SkipConsent,
RoleEntries = (await _roleProvider.GetRoleNamesAsync())
.Select(r => new RoleEntry()
{
Name = r,
Selected = application.RoleNames.Contains(r),
}).ToList(),
AllowAuthorizationCodeFlow = application.AllowAuthorizationCodeFlow,
AllowClientCredentialsFlow = application.AllowClientCredentialsFlow,
AllowImplicitFlow = application.AllowImplicitFlow,
AllowPasswordFlow = application.AllowPasswordFlow,
AllowRefreshTokenFlow = application.AllowRefreshTokenFlow
};
ViewData["OpenIdSettings"] = openIdSettings;
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
[HttpPost]
public async Task<IActionResult> Edit(EditOpenIdApplicationViewModel model, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOpenIdApplications))
{
return Unauthorized();
}
if (model.Type == ClientType.Public && !string.IsNullOrEmpty(model.ClientSecret))
{
ModelState.AddModelError(nameof(model.ClientSecret), T["No client secret can be set for public applications."]);
}
else if (model.UpdateClientSecret)
{
var user = await _userManager.FindByNameAsync(User.Identity.Name);
await ValidateClientSecretAsync(user, model.ClientSecret, (key, message) => ModelState.AddModelError(key, message));
}
OpenIdApplication application = null;
if (ModelState.IsValid)
{
application = await _applicationManager.FindByIdAsync(model.Id, HttpContext.RequestAborted);
if (application == null)
{
return NotFound();
}
if (application.Type == ClientType.Public && model.Type == ClientType.Confidential && !model.UpdateClientSecret)
{
ModelState.AddModelError(nameof(model.UpdateClientSecret), T["Setting a new client secret is required"]);
}
}
if (!ModelState.IsValid)
{
var openIdSettings = await _openIdService.GetOpenIdSettingsAsync();
if (!_openIdService.IsValidOpenIdSettings(openIdSettings))
{
_notifier.Warning(H["OpenID Connect settings are not properly configured."]);
}
ViewData["OpenIdSettings"] = openIdSettings;
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
// If the application was confidential and is now public, the client secret must be reset.
if (application.Type == ClientType.Confidential && model.Type == ClientType.Public)
{
model.UpdateClientSecret = true;
model.ClientSecret = null;
}
application.DisplayName = model.DisplayName;
application.RedirectUri = model.RedirectUri;
application.LogoutRedirectUri = model.LogoutRedirectUri;
application.ClientId = model.ClientId;
application.Type = model.Type;
application.SkipConsent = model.SkipConsent;
application.AllowAuthorizationCodeFlow = model.AllowAuthorizationCodeFlow;
application.AllowClientCredentialsFlow = model.AllowClientCredentialsFlow;
application.AllowImplicitFlow = model.AllowImplicitFlow;
application.AllowPasswordFlow = model.AllowPasswordFlow;
application.AllowRefreshTokenFlow = model.AllowRefreshTokenFlow;
application.AllowHybridFlow = model.AllowHybridFlow;
application.RoleNames = new List<string>();
if (application.Type == ClientType.Confidential && application.AllowClientCredentialsFlow)
{
application.RoleNames = model.RoleEntries.Where(r => r.Selected).Select(r => r.Name).ToList();
}
if (model.UpdateClientSecret)
{
await _applicationManager.UpdateAsync(application, model.ClientSecret, HttpContext.RequestAborted);
}
else
{
await _applicationManager.UpdateAsync(application, HttpContext.RequestAborted);
}
if (string.IsNullOrEmpty(returnUrl))
{
return RedirectToAction("Index");
}
return LocalRedirect(returnUrl);
}
[HttpGet]
public async Task<IActionResult> Create(string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOpenIdApplications))
{
return Unauthorized();
}
var openIdSettings = await _openIdService.GetOpenIdSettingsAsync();
if (!_openIdService.IsValidOpenIdSettings(openIdSettings))
{
_notifier.Warning(H["OpenID Connect settings are not properly configured."]);
}
var model = new CreateOpenIdApplicationViewModel()
{
RoleEntries = (await _roleProvider.GetRoleNamesAsync()).Select(r => new RoleEntry() { Name = r }).ToList()
};
ViewData["OpenIdSettings"] = openIdSettings;
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
[HttpPost]
public async Task<IActionResult> Create(CreateOpenIdApplicationViewModel model, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOpenIdApplications))
{
return Unauthorized();
}
if (model.Type == ClientType.Confidential)
{
var user = await _userManager.FindByNameAsync(User.Identity.Name);
await ValidateClientSecretAsync(user, model.ClientSecret, (key, message) => ModelState.AddModelError(key, message));
}
else if (model.Type == ClientType.Public && !string.IsNullOrEmpty(model.ClientSecret))
{
ModelState.AddModelError(nameof(model.ClientSecret), T["No client secret can be set for public applications."]);
}
if (!ModelState.IsValid)
{
var openIdSettings = await _openIdService.GetOpenIdSettingsAsync();
if (!_openIdService.IsValidOpenIdSettings(openIdSettings))
{
_notifier.Warning(H["OpenID Connect settings are not properly configured."]);
}
ViewData["OpenIdSettings"] = openIdSettings;
ViewData["ReturnUrl"] = returnUrl;
return View("Create", model);
}
var roleNames = new List<string>();
if (model.Type == ClientType.Confidential && model.AllowClientCredentialsFlow)
{
roleNames = model.RoleEntries.Where(r => r.Selected).Select(r => r.Name).ToList();
}
var application = new OpenIdApplication
{
DisplayName = model.DisplayName,
RedirectUri = model.RedirectUri,
LogoutRedirectUri = model.LogoutRedirectUri,
ClientId = model.ClientId,
Type = model.Type,
SkipConsent = model.SkipConsent,
RoleNames = roleNames,
AllowAuthorizationCodeFlow = model.AllowAuthorizationCodeFlow,
AllowClientCredentialsFlow = model.AllowClientCredentialsFlow,
AllowImplicitFlow = model.AllowImplicitFlow,
AllowPasswordFlow = model.AllowPasswordFlow,
AllowRefreshTokenFlow = model.AllowRefreshTokenFlow,
AllowHybridFlow = model.AllowHybridFlow
};
await _applicationManager.CreateAsync(application, model.ClientSecret, HttpContext.RequestAborted);
if (string.IsNullOrEmpty(returnUrl))
{
return RedirectToAction("Index");
}
return LocalRedirect(returnUrl);
}
private async Task<bool> ValidateClientSecretAsync(IUser user, string password, Action<string, string> reportError)
{
if (string.IsNullOrEmpty(password))
{
reportError("ClientSecret", T["The client secret is required for confidential applications."]);
return false;
}
var result = true;
foreach (var v in _passwordValidators)
{
var validationResult = await v.ValidateAsync(_userManager, user, password);
if (!validationResult.Succeeded)
{
result = false;
foreach (var error in validationResult.Errors)
{
switch (error.Code)
{
case "PasswordRequiresDigit":
reportError("ClientSecret", T["Passwords must have at least one digit ('0'-'9')."]);
break;
case "PasswordRequiresLower":
reportError("ClientSecret", T["Passwords must have at least one lowercase ('a'-'z')."]);
break;
case "PasswordRequiresUpper":
reportError("ClientSecret", T["Passwords must have at least one uppercase('A'-'Z')."]);
break;
case "PasswordRequiresNonAlphanumeric":
reportError("ClientSecret", T["Passwords must have at least one non letter or digit character."]);
break;
case "PasswordTooShort":
reportError("ClientSecret", T["Passwords must be at least {0} characters.", _identityOptions.Value.Password.RequiredLength]);
break;
}
}
}
}
return result;
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOpenIdApplications))
{
return Unauthorized();
}
var application = await _applicationManager.FindByIdAsync(id, HttpContext.RequestAborted);
if (application == null)
{
return NotFound();
}
await _applicationManager.DeleteAsync(application, HttpContext.RequestAborted);
return RedirectToAction(nameof(Index));
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using System.Text;
using System.IO;
using System.Xml;
using Newtonsoft.Json.Utilities;
using System.Diagnostics;
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public partial class JsonTextWriter : JsonWriter
{
private const int IndentCharBufferSize = 12;
private readonly TextWriter _writer;
private Base64Encoder? _base64Encoder;
private char _indentChar;
private int _indentation;
private char _quoteChar;
private bool _quoteName;
private bool[]? _charEscapeFlags;
private char[]? _writeBuffer;
private IArrayPool<char>? _arrayPool;
private char[]? _indentChars;
private Base64Encoder Base64Encoder
{
get
{
if (_base64Encoder == null)
{
_base64Encoder = new Base64Encoder(_writer);
}
return _base64Encoder;
}
}
/// <summary>
/// Gets or sets the writer's character array pool.
/// </summary>
public IArrayPool<char>? ArrayPool
{
get => _arrayPool;
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_arrayPool = value;
}
}
/// <summary>
/// Gets or sets how many <see cref="JsonTextWriter.IndentChar"/>s to write for each level in the hierarchy when <see cref="JsonWriter.Formatting"/> is set to <see cref="Formatting.Indented"/>.
/// </summary>
public int Indentation
{
get => _indentation;
set
{
if (value < 0)
{
throw new ArgumentException("Indentation value must be greater than 0.");
}
_indentation = value;
}
}
/// <summary>
/// Gets or sets which character to use to quote attribute values.
/// </summary>
public char QuoteChar
{
get => _quoteChar;
set
{
if (value != '"' && value != '\'')
{
throw new ArgumentException(@"Invalid JavaScript string quote character. Valid quote characters are ' and "".");
}
_quoteChar = value;
UpdateCharEscapeFlags();
}
}
/// <summary>
/// Gets or sets which character to use for indenting when <see cref="JsonWriter.Formatting"/> is set to <see cref="Formatting.Indented"/>.
/// </summary>
public char IndentChar
{
get => _indentChar;
set
{
if (value != _indentChar)
{
_indentChar = value;
_indentChars = null;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether object names will be surrounded with quotes.
/// </summary>
public bool QuoteName
{
get => _quoteName;
set => _quoteName = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonTextWriter"/> class using the specified <see cref="TextWriter"/>.
/// </summary>
/// <param name="textWriter">The <see cref="TextWriter"/> to write to.</param>
public JsonTextWriter(TextWriter textWriter)
{
if (textWriter == null)
{
throw new ArgumentNullException(nameof(textWriter));
}
_writer = textWriter;
_quoteChar = '"';
_quoteName = true;
_indentChar = ' ';
_indentation = 2;
UpdateCharEscapeFlags();
#if HAVE_ASYNC
_safeAsync = GetType() == typeof(JsonTextWriter);
#endif
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying <see cref="TextWriter"/> and also flushes the underlying <see cref="TextWriter"/>.
/// </summary>
public override void Flush()
{
_writer.Flush();
}
/// <summary>
/// Closes this writer.
/// If <see cref="JsonWriter.CloseOutput"/> is set to <c>true</c>, the underlying <see cref="TextWriter"/> is also closed.
/// If <see cref="JsonWriter.AutoCompleteOnClose"/> is set to <c>true</c>, the JSON is auto-completed.
/// </summary>
public override void Close()
{
base.Close();
CloseBufferAndWriter();
}
private void CloseBufferAndWriter()
{
if (_writeBuffer != null)
{
BufferUtils.ReturnBuffer(_arrayPool, _writeBuffer);
_writeBuffer = null;
}
if (CloseOutput)
{
#if HAVE_STREAM_READER_WRITER_CLOSE
_writer?.Close();
#else
_writer?.Dispose();
#endif
}
}
/// <summary>
/// Writes the beginning of a JSON object.
/// </summary>
public override void WriteStartObject()
{
InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object);
_writer.Write('{');
}
/// <summary>
/// Writes the beginning of a JSON array.
/// </summary>
public override void WriteStartArray()
{
InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array);
_writer.Write('[');
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public override void WriteStartConstructor(string name)
{
InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor);
_writer.Write("new ");
_writer.Write(name);
_writer.Write('(');
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected override void WriteEnd(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
_writer.Write('}');
break;
case JsonToken.EndArray:
_writer.Write(']');
break;
case JsonToken.EndConstructor:
_writer.Write(')');
break;
default:
throw JsonWriterException.Create(this, "Invalid JsonToken: " + token, null);
}
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
public override void WritePropertyName(string name)
{
InternalWritePropertyName(name);
WriteEscapedString(name, _quoteName);
_writer.Write(':');
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param>
public override void WritePropertyName(string name, bool escape)
{
InternalWritePropertyName(name);
if (escape)
{
WriteEscapedString(name, _quoteName);
}
else
{
if (_quoteName)
{
_writer.Write(_quoteChar);
}
_writer.Write(name);
if (_quoteName)
{
_writer.Write(_quoteChar);
}
}
_writer.Write(':');
}
internal override void OnStringEscapeHandlingChanged()
{
UpdateCharEscapeFlags();
}
private void UpdateCharEscapeFlags()
{
_charEscapeFlags = JavaScriptUtils.GetCharEscapeFlags(StringEscapeHandling, _quoteChar);
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected override void WriteIndent()
{
// levels of indentation multiplied by the indent count
int currentIndentCount = Top * _indentation;
int newLineLen = SetIndentChars();
_writer.Write(_indentChars, 0, newLineLen + Math.Min(currentIndentCount, IndentCharBufferSize));
while ((currentIndentCount -= IndentCharBufferSize) > 0)
{
_writer.Write(_indentChars, newLineLen, Math.Min(currentIndentCount, IndentCharBufferSize));
}
}
private int SetIndentChars()
{
// Set _indentChars to be a newline followed by IndentCharBufferSize indent characters.
string writerNewLine = _writer.NewLine;
int newLineLen = writerNewLine.Length;
bool match = _indentChars != null && _indentChars.Length == IndentCharBufferSize + newLineLen;
if (match)
{
for (int i = 0; i != newLineLen; ++i)
{
if (writerNewLine[i] != _indentChars![i])
{
match = false;
break;
}
}
}
if (!match)
{
// If we're here, either _indentChars hasn't been set yet, or _writer.NewLine
// has been changed, or _indentChar has been changed.
_indentChars = (writerNewLine + new string(_indentChar, IndentCharBufferSize)).ToCharArray();
}
return newLineLen;
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected override void WriteValueDelimiter()
{
_writer.Write(',');
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected override void WriteIndentSpace()
{
_writer.Write(' ');
}
private void WriteValueInternal(string value, JsonToken token)
{
_writer.Write(value);
}
#region WriteValue methods
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public override void WriteValue(object? value)
{
#if HAVE_BIG_INTEGER
if (value is BigInteger i)
{
InternalWriteValue(JsonToken.Integer);
WriteValueInternal(i.ToString(CultureInfo.InvariantCulture), JsonToken.String);
}
else
#endif
{
base.WriteValue(value);
}
}
/// <summary>
/// Writes a null value.
/// </summary>
public override void WriteNull()
{
InternalWriteValue(JsonToken.Null);
WriteValueInternal(JsonConvert.Null, JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public override void WriteUndefined()
{
InternalWriteValue(JsonToken.Undefined);
WriteValueInternal(JsonConvert.Undefined, JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public override void WriteRaw(string? json)
{
InternalWriteRaw();
_writer.Write(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public override void WriteValue(string? value)
{
InternalWriteValue(JsonToken.String);
if (value == null)
{
WriteValueInternal(JsonConvert.Null, JsonToken.Null);
}
else
{
WriteEscapedString(value, true);
}
}
private void WriteEscapedString(string value, bool quote)
{
EnsureWriteBuffer();
JavaScriptUtils.WriteEscapedJavaScriptString(_writer, value, _quoteChar, quote, _charEscapeFlags!, StringEscapeHandling, _arrayPool, ref _writeBuffer);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public override void WriteValue(int value)
{
InternalWriteValue(JsonToken.Integer);
WriteIntegerValue(value);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public override void WriteValue(uint value)
{
InternalWriteValue(JsonToken.Integer);
WriteIntegerValue(value);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public override void WriteValue(long value)
{
InternalWriteValue(JsonToken.Integer);
WriteIntegerValue(value);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public override void WriteValue(ulong value)
{
InternalWriteValue(JsonToken.Integer);
WriteIntegerValue(value, false);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public override void WriteValue(float value)
{
InternalWriteValue(JsonToken.Float);
WriteValueInternal(JsonConvert.ToString(value, FloatFormatHandling, QuoteChar, false), JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Single"/> value to write.</param>
public override void WriteValue(float? value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.Float);
WriteValueInternal(JsonConvert.ToString(value.GetValueOrDefault(), FloatFormatHandling, QuoteChar, true), JsonToken.Float);
}
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public override void WriteValue(double value)
{
InternalWriteValue(JsonToken.Float);
WriteValueInternal(JsonConvert.ToString(value, FloatFormatHandling, QuoteChar, false), JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Double"/> value to write.</param>
public override void WriteValue(double? value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.Float);
WriteValueInternal(JsonConvert.ToString(value.GetValueOrDefault(), FloatFormatHandling, QuoteChar, true), JsonToken.Float);
}
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public override void WriteValue(bool value)
{
InternalWriteValue(JsonToken.Boolean);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public override void WriteValue(short value)
{
InternalWriteValue(JsonToken.Integer);
WriteIntegerValue(value);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public override void WriteValue(ushort value)
{
InternalWriteValue(JsonToken.Integer);
WriteIntegerValue(value);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public override void WriteValue(char value)
{
InternalWriteValue(JsonToken.String);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public override void WriteValue(byte value)
{
InternalWriteValue(JsonToken.Integer);
WriteIntegerValue(value);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public override void WriteValue(sbyte value)
{
InternalWriteValue(JsonToken.Integer);
WriteIntegerValue(value);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public override void WriteValue(decimal value)
{
InternalWriteValue(JsonToken.Float);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public override void WriteValue(DateTime value)
{
InternalWriteValue(JsonToken.Date);
value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling);
if (StringUtils.IsNullOrEmpty(DateFormatString))
{
int length = WriteValueToBuffer(value);
_writer.Write(_writeBuffer, 0, length);
}
else
{
_writer.Write(_quoteChar);
_writer.Write(value.ToString(DateFormatString, Culture));
_writer.Write(_quoteChar);
}
}
private int WriteValueToBuffer(DateTime value)
{
EnsureWriteBuffer();
MiscellaneousUtils.Assert(_writeBuffer != null);
int pos = 0;
_writeBuffer[pos++] = _quoteChar;
pos = DateTimeUtils.WriteDateTimeString(_writeBuffer, pos, value, null, value.Kind, DateFormatHandling);
_writeBuffer[pos++] = _quoteChar;
return pos;
}
/// <summary>
/// Writes a <see cref="Byte"/>[] value.
/// </summary>
/// <param name="value">The <see cref="Byte"/>[] value to write.</param>
public override void WriteValue(byte[]? value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.Bytes);
_writer.Write(_quoteChar);
Base64Encoder.Encode(value, 0, value.Length);
Base64Encoder.Flush();
_writer.Write(_quoteChar);
}
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public override void WriteValue(DateTimeOffset value)
{
InternalWriteValue(JsonToken.Date);
if (StringUtils.IsNullOrEmpty(DateFormatString))
{
int length = WriteValueToBuffer(value);
_writer.Write(_writeBuffer, 0, length);
}
else
{
_writer.Write(_quoteChar);
_writer.Write(value.ToString(DateFormatString, Culture));
_writer.Write(_quoteChar);
}
}
private int WriteValueToBuffer(DateTimeOffset value)
{
EnsureWriteBuffer();
MiscellaneousUtils.Assert(_writeBuffer != null);
int pos = 0;
_writeBuffer[pos++] = _quoteChar;
pos = DateTimeUtils.WriteDateTimeString(_writeBuffer, pos, (DateFormatHandling == DateFormatHandling.IsoDateFormat) ? value.DateTime : value.UtcDateTime, value.Offset, DateTimeKind.Local, DateFormatHandling);
_writeBuffer[pos++] = _quoteChar;
return pos;
}
#endif
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public override void WriteValue(Guid value)
{
InternalWriteValue(JsonToken.String);
string text;
#if HAVE_CHAR_TO_STRING_WITH_CULTURE
text = value.ToString("D", CultureInfo.InvariantCulture);
#else
text = value.ToString("D");
#endif
_writer.Write(_quoteChar);
_writer.Write(text);
_writer.Write(_quoteChar);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public override void WriteValue(TimeSpan value)
{
InternalWriteValue(JsonToken.String);
string text;
#if !HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE
text = value.ToString();
#else
text = value.ToString(null, CultureInfo.InvariantCulture);
#endif
_writer.Write(_quoteChar);
_writer.Write(text);
_writer.Write(_quoteChar);
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public override void WriteValue(Uri? value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.String);
WriteEscapedString(value.OriginalString, true);
}
}
#endregion
/// <summary>
/// Writes a comment <c>/*...*/</c> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public override void WriteComment(string? text)
{
InternalWriteComment();
_writer.Write("/*");
_writer.Write(text);
_writer.Write("*/");
}
/// <summary>
/// Writes the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public override void WriteWhitespace(string ws)
{
InternalWriteWhitespace(ws);
_writer.Write(ws);
}
private void EnsureWriteBuffer()
{
if (_writeBuffer == null)
{
// maximum buffer sized used when writing iso date
_writeBuffer = BufferUtils.RentBuffer(_arrayPool, 35);
}
}
private void WriteIntegerValue(long value)
{
if (value >= 0 && value <= 9)
{
_writer.Write((char)('0' + value));
}
else
{
bool negative = value < 0;
WriteIntegerValue(negative ? (ulong)-value : (ulong)value, negative);
}
}
private void WriteIntegerValue(ulong value, bool negative)
{
if (!negative & value <= 9)
{
_writer.Write((char)('0' + value));
}
else
{
int length = WriteNumberToBuffer(value, negative);
_writer.Write(_writeBuffer, 0, length);
}
}
private int WriteNumberToBuffer(ulong value, bool negative)
{
if (value <= uint.MaxValue)
{
// avoid the 64 bit division if possible
return WriteNumberToBuffer((uint)value, negative);
}
EnsureWriteBuffer();
MiscellaneousUtils.Assert(_writeBuffer != null);
int totalLength = MathUtils.IntLength(value);
if (negative)
{
totalLength++;
_writeBuffer[0] = '-';
}
int index = totalLength;
do
{
ulong quotient = value / 10;
ulong digit = value - (quotient * 10);
_writeBuffer[--index] = (char)('0' + digit);
value = quotient;
} while (value != 0);
return totalLength;
}
private void WriteIntegerValue(int value)
{
if (value >= 0 && value <= 9)
{
_writer.Write((char)('0' + value));
}
else
{
bool negative = value < 0;
WriteIntegerValue(negative ? (uint)-value : (uint)value, negative);
}
}
private void WriteIntegerValue(uint value, bool negative)
{
if (!negative & value <= 9)
{
_writer.Write((char)('0' + value));
}
else
{
int length = WriteNumberToBuffer(value, negative);
_writer.Write(_writeBuffer, 0, length);
}
}
private int WriteNumberToBuffer(uint value, bool negative)
{
EnsureWriteBuffer();
MiscellaneousUtils.Assert(_writeBuffer != null);
int totalLength = MathUtils.IntLength(value);
if (negative)
{
totalLength++;
_writeBuffer[0] = '-';
}
int index = totalLength;
do
{
uint quotient = value / 10;
uint digit = value - (quotient * 10);
_writeBuffer[--index] = (char)('0' + digit);
value = quotient;
} while (value != 0);
return totalLength;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// DecoderReplacementFallback.cs
//
namespace System.Text
{
using System;
using System.Diagnostics.Contracts;
[Serializable]
public sealed class DecoderReplacementFallback : DecoderFallback
{
// Our variables
private String strDefault;
// Construction. Default replacement fallback uses no best fit and ? replacement string
public DecoderReplacementFallback() : this("?")
{
}
public DecoderReplacementFallback(String replacement)
{
if (replacement == null)
throw new ArgumentNullException("replacement");
Contract.EndContractBlock();
// Make sure it doesn't have bad surrogate pairs
bool bFoundHigh=false;
for (int i = 0; i < replacement.Length; i++)
{
// Found a surrogate?
if (Char.IsSurrogate(replacement,i))
{
// High or Low?
if (Char.IsHighSurrogate(replacement, i))
{
// if already had a high one, stop
if (bFoundHigh)
break; // break & throw at the bFoundHIgh below
bFoundHigh = true;
}
else
{
// Low, did we have a high?
if (!bFoundHigh)
{
// Didn't have one, make if fail when we stop
bFoundHigh = true;
break;
}
// Clear flag
bFoundHigh = false;
}
}
// If last was high we're in trouble (not surrogate so not low surrogate, so break)
else if (bFoundHigh)
break;
}
if (bFoundHigh)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", "replacement"));
strDefault = replacement;
}
public String DefaultString
{
get
{
return strDefault;
}
}
public override DecoderFallbackBuffer CreateFallbackBuffer()
{
return new DecoderReplacementFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return strDefault.Length;
}
}
public override bool Equals(Object value)
{
DecoderReplacementFallback that = value as DecoderReplacementFallback;
if (that != null)
{
return (this.strDefault == that.strDefault);
}
return (false);
}
public override int GetHashCode()
{
return strDefault.GetHashCode();
}
}
public sealed class DecoderReplacementFallbackBuffer : DecoderFallbackBuffer
{
// Store our default string
private String strDefault;
int fallbackCount = -1;
int fallbackIndex = -1;
// Construction
public DecoderReplacementFallbackBuffer(DecoderReplacementFallback fallback)
{
this.strDefault = fallback.DefaultString;
}
// Fallback Methods
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
// We can't call recursively but others might (note, we don't test on last char!!!)
if (fallbackCount >= 1)
{
ThrowLastBytesRecursive(bytesUnknown);
}
// Go ahead and get our fallback
if (strDefault.Length == 0)
return false;
fallbackCount = strDefault.Length;
fallbackIndex = -1;
return true;
}
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
fallbackCount--;
fallbackIndex++;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (fallbackCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (fallbackCount == int.MaxValue)
{
fallbackCount = -1;
return '\0';
}
// Now make sure its in the expected range
Contract.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
"Index exceeds buffer range");
return strDefault[fallbackIndex];
}
public override bool MovePrevious()
{
// Back up one, only if we just processed the last character (or earlier)
if (fallbackCount >= -1 && fallbackIndex >= 0)
{
fallbackIndex--;
fallbackCount++;
return true;
}
// Return false 'cause we couldn't do it.
return false;
}
// How many characters left to output?
public override int Remaining
{
get
{
// Our count is 0 for 1 character left.
return (fallbackCount < 0) ? 0 : fallbackCount;
}
}
// Clear the buffer
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Reset()
{
fallbackCount = -1;
fallbackIndex = -1;
byteStart = null;
}
// This version just counts the fallback and doesn't actually copy anything.
[System.Security.SecurityCritical] // auto-generated
internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
{
// return our replacement string Length
return strDefault.Length;
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations.Infrastructure;
using MVC6BearerToken.DAL;
namespace MVC6BearerTokenMigrations
{
[ContextType(typeof(ApplicationDbContext))]
partial class Initial
{
public override string Id
{
get { return "20150831032152_Initial"; }
}
public override string ProductVersion
{
get { return "7.0.0-beta6-13815"; }
}
public override void BuildTargetModel(ModelBuilder builder)
{
builder
.Annotation("ProductVersion", "7.0.0-beta6-13815")
.Annotation("SqlServer:ValueGenerationStrategy", "IdentityColumn");
builder.Entity("MVC6BearerToken.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken();
b.Property<string>("Email")
.Annotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.Annotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.Annotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.Annotation("MaxLength", 256);
b.Key("Id");
b.Index("NormalizedEmail")
.Annotation("Relational:Name", "EmailIndex");
b.Index("NormalizedUserName")
.Annotation("Relational:Name", "UserNameIndex");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("MVC6BearerToken.Models.Client", b =>
{
b.Property<string>("Id");
b.Property<bool>("Active");
b.Property<string>("AllowedOrigin")
.Annotation("MaxLength", 100);
b.Property<int>("ApplicationType");
b.Property<string>("Name")
.Required()
.Annotation("MaxLength", 100);
b.Property<int>("RefreshTokenLifeTime");
b.Property<string>("Secret")
.Required();
b.Key("Id");
});
builder.Entity("MVC6BearerToken.Models.RefreshToken", b =>
{
b.Property<string>("Id");
b.Property<string>("ClientId")
.Required()
.Annotation("MaxLength", 50);
b.Property<DateTime>("ExpiresUtc");
b.Property<DateTime>("IssuedUtc");
b.Property<string>("Subject")
.Required()
.Annotation("MaxLength", 50);
b.Key("Id");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken();
b.Property<string>("Name")
.Annotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.Annotation("MaxLength", 256);
b.Key("Id");
b.Index("NormalizedName")
.Annotation("Relational:Name", "RoleNameIndex");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId");
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId");
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId");
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Reference("MVC6BearerToken.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Reference("MVC6BearerToken.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
b.Reference("MVC6BearerToken.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
}
}
}
| |
// LogicWidget.cs
//
// Author:
// Stephen Shaw <[email protected]>
// Larry Ewing <[email protected]>
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2013 Stephen Shaw
// Copyright (C) 2006-2007 Novell, Inc.
// Copyright (C) 2006 Larry Ewing
// Copyright (C) 2006-2007 Gabriel Burt
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Gdk;
using FSpot.Core;
using FSpot.Database;
namespace FSpot.Query
{
public class LogicWidget : HBox
{
readonly PhotoQuery query;
static Term rootTerm;
EventBox rootAdd;
HBox rootBox;
Label help;
HBox sepBox;
bool preventUpdate;
bool preview;
public event EventHandler Changed;
public static Term Root
{
get {
return rootTerm;
}
}
static LogicWidget logic_widget;
public static LogicWidget Box {
get { return logic_widget; }
}
// Drag and Drop
static readonly TargetEntry [] tag_dest_target_table =
{
DragDropTargets.TagListEntry,
DragDropTargets.TagQueryEntry
};
public LogicWidget (PhotoQuery query, TagStore tagStore)
{
//SetFlag (WidgetFlags.NoWindow);
this.query = query;
CanFocus = true;
Sensitive = true;
Init ();
tagStore.ItemsChanged += HandleTagChanged;
tagStore.ItemsRemoved += HandleTagDeleted;
Show ();
logic_widget = this;
}
void Init ()
{
sepBox = null;
preview = false;
rootAdd = new Gtk.EventBox ();
rootAdd.VisibleWindow = false;
rootAdd.CanFocus = true;
rootAdd.DragMotion += HandleDragMotion;
rootAdd.DragDataReceived += HandleDragDataReceived;
rootAdd.DragLeave += HandleDragLeave;
help = new Gtk.Label ("<i>" + Catalog.GetString ("Drag tags here to search for them") + "</i>");
help.UseMarkup = true;
help.Visible = true;
rootBox = new HBox();
rootBox.Add (help);
rootBox.Show ();
rootAdd.Child = rootBox;
rootAdd.Show ();
Gtk.Drag.DestSet (rootAdd, DestDefaults.All, tag_dest_target_table,
DragAction.Copy | DragAction.Move );
PackEnd (rootAdd, true, true, 0);
rootTerm = new OrTerm (null, null);
}
void Preview ()
{
if (sepBox == null) {
sepBox = new HBox ();
Widget sep = rootTerm.SeparatorWidget ();
if (sep != null) {
sep.Show ();
sepBox.PackStart (sep, false, false, 0);
}
rootBox.Add (sepBox);
}
help.Hide ();
sepBox.Show ();
}
/** Handlers **/
// When the user edits a tag (it's icon, name, etc) we get called
// and update the images/text in the query as needed to reflect the changes.
void HandleTagChanged (object sender, DbItemEventArgs<Tag> args)
{
foreach (Tag t in args.Items)
foreach (Literal term in rootTerm.FindByTag (t))
term.Update ();
}
// If the user deletes a tag that is in use in the query, remove it from the query too.
void HandleTagDeleted (object sender, DbItemEventArgs<Tag> args)
{
foreach (Tag t in args.Items)
foreach (Literal term in rootTerm.FindByTag (t))
term.RemoveSelf ();
}
void HandleDragMotion (object o, DragMotionArgs args)
{
if (!preview && rootTerm.Count > 0 && (Literal.FocusedLiterals.Count == 0 || Children.Length > 2)) {
Preview ();
preview = true;
}
}
void HandleDragLeave (object o, EventArgs args)
{
if (preview && Children.Length > 1) {
sepBox.Hide ();
preview = false;
} else if (preview && Children.Length == 1) {
help.Show ();
}
}
void HandleLiteralsMoved (List<Literal> literals, Term parent, Literal after)
{
preventUpdate = true;
foreach (Literal term in literals) {
Tag tag = term.Tag;
// Don't listen for it to be removed since we are
// moving it. We will update when we're done.
term.Removed -= HandleRemoved;
term.RemoveSelf ();
// Add it to where it was dropped
List<Literal> groups = InsertTerm (new [] {tag}, parent, after);
if (term.IsNegated)
foreach (Literal group in groups)
group.IsNegated = true;
}
preventUpdate = false;
UpdateQuery ();
}
void HandleTagsAdded (Tag[] tags, Term parent, Literal after)
{
InsertTerm (tags, parent, after);
}
void HandleAttachTag (Tag tag, Term parent, Literal after)
{
InsertTerm (new Tag [] {tag}, parent, after);
}
void HandleNegated (Literal group)
{
UpdateQuery ();
}
void HandleRemoving (Literal term)
{
foreach (Widget w in HangersOn (term))
Remove (w);
// Remove the term's widget
Remove (term.Widget);
}
public List<Gtk.Widget> HangersOn (Literal term)
{
var w = new List<Gtk.Widget> ();
// Find separators that only exist because of this term
if (term.Parent != null) {
if (term.Parent.Count > 1)
{
if (term == term.Parent.Last)
w.Add (Children[WidgetPosition (term.Widget) - 1]);
else
w.Add (Children[WidgetPosition (term.Widget) + 1]);
}
else if (term.Parent.Count == 1)
{
if (term.Parent.Parent != null) {
if (term.Parent.Parent.Count > 1) {
if (term.Parent == term.Parent.Parent.Last)
w.Add (Children[WidgetPosition (term.Widget) - 1]);
else
w.Add (Children[WidgetPosition (term.Widget) + 1]);
}
}
}
}
return w;
}
void HandleRemoved (Literal group)
{
UpdateQuery ();
}
void HandleDragDataReceived (object o, DragDataReceivedArgs args)
{
args.RetVal = true;
if (args.Info == DragDropTargets.TagListEntry.Info) {
InsertTerm (args.SelectionData.GetTagsData (), rootTerm, null);
return;
}
if (args.Info == DragDropTargets.TagQueryEntry.Info) {
// FIXME: use drag data
HandleLiteralsMoved (Literal.FocusedLiterals, rootTerm, null);
// Prevent them from being removed again
Literal.FocusedLiterals = new List<Literal> ();
}
}
/** Helper Functions **/
public void PhotoTagsChanged (Tag [] tags)
{
bool refresh_required = false;
foreach (Tag tag in tags) {
if ((rootTerm.FindByTag (tag)).Count > 0) {
refresh_required = true;
break;
}
}
if (refresh_required)
UpdateQuery ();
}
// Inserts a widget into a Box at a certain index
void InsertWidget (int index, Gtk.Widget widget) {
widget.Visible = true;
PackStart (widget, false, false, 0);
ReorderChild (widget, index);
}
// Return the index position of a widget in this Box
int WidgetPosition (Gtk.Widget widget)
{
for (int i = 0; i < Children.Length; i++)
if (Children[i] == widget)
return i;
return Children.Length - 1;
}
public bool TagIncluded (Tag tag)
{
return rootTerm.TagIncluded (tag);
}
public bool TagRequired (Tag tag)
{
return rootTerm.TagRequired (tag);
}
// Add a tag or group of tags to the rootTerm, at the end of the Box
public void Include (Tag [] tags)
{
// Filter out any tags that are already included
// FIXME: Does this really need to be set to a length?
List<Tag> new_tags = new List<Tag> (tags.Length);
foreach (Tag tag in tags) {
if (! rootTerm.TagIncluded (tag))
new_tags.Add (tag);
}
if (new_tags.Count == 0)
return;
tags = new_tags.ToArray ();
InsertTerm (tags, rootTerm, null);
}
public void UnInclude (Tag [] tags)
{
var new_tags = new List<Tag> (tags.Length);
foreach (Tag tag in tags) {
if (rootTerm.TagIncluded (tag))
new_tags.Add (tag);
}
if (new_tags.Count == 0)
return;
tags = new_tags.ToArray ();
bool needsUpdate = false;
preventUpdate = true;
foreach (Term parent in rootTerm.LiteralParents ()) {
if (parent.Count == 1) {
foreach (Tag tag in tags) {
if ((parent.Last as Literal).Tag == tag) {
(parent.Last as Literal).RemoveSelf ();
needsUpdate = true;
break;
}
}
}
}
preventUpdate = false;
if (needsUpdate)
UpdateQuery ();
}
// AND this tag with all terms
public void Require (Tag [] tags)
{
// TODO it would be awesome if this was done by putting parentheses around
// OR terms and ANDing the result with this term (eg factored out)
// Trim out tags that are already required
var new_tags = new List<Tag> (tags.Length);
foreach (Tag tag in tags) {
if (! rootTerm.TagRequired (tag))
new_tags.Add (tag);
}
if (new_tags.Count == 0)
return;
tags = new_tags.ToArray ();
bool added = false;
preventUpdate = true;
foreach (Term parent in rootTerm.LiteralParents ()) {
// TODO logic could be broken if a term's SubTerms are a mixture
// of Literals and non-Literals
InsertTerm (tags, parent, parent.Last as Literal);
added = true;
}
// If there were no LiteralParents to add this tag to, then add it to the rootTerm
// TODO should add the first tag in the array,
// then add the others to the first's parent (so they will be ANDed together)
if (!added)
InsertTerm (tags, rootTerm, null);
preventUpdate = false;
UpdateQuery ();
}
public void UnRequire (Tag [] tags)
{
// Trim out tags that are not required
var new_tags = new List<Tag> (tags.Length);
foreach (Tag tag in tags) {
if (rootTerm.TagRequired (tag))
new_tags.Add (tag);
}
if (new_tags.Count == 0)
return;
tags = new_tags.ToArray ();
preventUpdate = true;
foreach (Term parent in rootTerm.LiteralParents ()) {
// Don't remove if this tag is the only child of a term
if (parent.Count > 1) {
foreach (Tag tag in tags) {
((parent.FindByTag (tag))[0] as Literal).RemoveSelf ();
}
}
}
preventUpdate = false;
UpdateQuery ();
}
public List<Literal> InsertTerm (Tag [] tags, Term parent, Literal after)
{
int position;
if (after != null)
position = WidgetPosition (after.Widget) + 1;
else
position = Children.Length - 1;
var added = new List<Literal>();
foreach (Tag tag in tags) {
//Console.WriteLine ("Adding tag {0}", tag.Name);
// Don't put a tag into a Term twice
if (parent != Root && (parent.FindByTag (tag, true)).Count > 0)
continue;
if (parent.Count > 0) {
Widget sep = parent.SeparatorWidget ();
InsertWidget (position, sep);
position++;
}
// Encapsulate new OR terms within a new AND term of which they are the
// only member, so later other terms can be AND'd with them
//
// TODO should really see what type of term the parent is, and
// encapsulate this term in a term of the opposite type. This will
// allow the query system to be expanded to work for multiple levels much easier.
if (parent == rootTerm) {
parent = new AndTerm (rootTerm, after);
after = null;
}
Literal term = new Literal (parent, tag, after);
term.TagsAdded += HandleTagsAdded;
term.LiteralsMoved += HandleLiteralsMoved;
term.AttachTag += HandleAttachTag;
term.NegatedToggled += HandleNegated;
term.Removing += HandleRemoving;
term.Removed += HandleRemoved;
term.RequireTag += Require;
term.UnRequireTag += UnRequire;
added.Add (term);
// Insert this widget into the appropriate place in the hbox
InsertWidget (position, term.Widget);
}
UpdateQuery ();
return added;
}
// Update the query, which updates the icon_view
public void UpdateQuery ()
{
if (preventUpdate)
return;
if (sepBox != null)
sepBox.Hide ();
if (rootTerm.Count == 0) {
help.Show ();
query.TagTerm = null;
} else {
help.Hide ();
query.TagTerm = new ConditionWrapper (rootTerm.SqlCondition ());
}
Changed?.Invoke (this, new EventArgs ());
}
public bool IsClear => rootTerm.Count == 0;
public void Clear ()
{
// Clear out the query, starting afresh
foreach (Widget widget in Children) {
Remove (widget);
widget.Destroy ();
}
Init ();
}
}
}
| |
#region BSD License
/*
Copyright (c) 2004-2005 Matthew Holmes ([email protected]), Dan Moorehead ([email protected])
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
#region CVS Information
/*
* $Source$
* $Author: jendave $
* $Date: 2007-04-26 08:10:27 +0000 (Thu, 26 Apr 2007) $
* $Revision: 236 $
*/
#endregion
using System;
using System.Collections;
using System.IO;
using System.Xml;
namespace Prebuild.Core.Parse
{
/// <summary>
///
/// </summary>
public enum OperatorSymbol
{
/// <summary>
///
/// </summary>
None,
/// <summary>
///
/// </summary>
Equal,
/// <summary>
///
/// </summary>
NotEqual,
/// <summary>
///
/// </summary>
LessThan,
/// <summary>
///
/// </summary>
GreaterThan,
/// <summary>
///
/// </summary>
LessThanEqual,
/// <summary>
///
/// </summary>
GreaterThanEqual
}
/// <summary>
///
/// </summary>
public class Preprocessor
{
#region Fields
XmlDocument m_OutDoc;
Stack m_IfStack;
Hashtable m_Variables;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Preprocessor"/> class.
/// </summary>
public Preprocessor()
{
m_OutDoc = new XmlDocument();
m_IfStack = new Stack();
m_Variables = new Hashtable();
RegisterVariable("OS", GetOS());
RegisterVariable("RuntimeVersion", Environment.Version.Major);
RegisterVariable("RuntimeMajor", Environment.Version.Major);
RegisterVariable("RuntimeMinor", Environment.Version.Minor);
RegisterVariable("RuntimeRevision", Environment.Version.Revision);
}
#endregion
#region Properties
/// <summary>
/// Gets the processed doc.
/// </summary>
/// <value>The processed doc.</value>
public XmlDocument ProcessedDoc
{
get
{
return m_OutDoc;
}
}
#endregion
#region Private Methods
/// <summary>
/// Parts of this code were taken from NAnt and is subject to the GPL
/// as per NAnt's license. Thanks to the NAnt guys for this little gem.
/// </summary>
/// <returns></returns>
public static string GetOS()
{
PlatformID platId = Environment.OSVersion.Platform;
if(platId == PlatformID.Win32NT || platId == PlatformID.Win32Windows)
{
return "Win32";
}
if (File.Exists("/System/Library/Frameworks/Cocoa.framework/Cocoa"))
{
return "MACOSX";
}
/*
* .NET 1.x, under Mono, the UNIX code is 128. Under
* .NET 2.x, Mono or MS, the UNIX code is 4
*/
if(Environment.Version.Major == 1)
{
if((int)platId == 128)
{
return "UNIX";
}
}
else if((int)platId == 4)
{
return "UNIX";
}
return "Unknown";
}
private static bool CompareNum(OperatorSymbol oper, int val1, int val2)
{
switch(oper)
{
case OperatorSymbol.Equal:
return (val1 == val2);
case OperatorSymbol.NotEqual:
return (val1 != val2);
case OperatorSymbol.LessThan:
return (val1 < val2);
case OperatorSymbol.LessThanEqual:
return (val1 <= val2);
case OperatorSymbol.GreaterThan:
return (val1 > val2);
case OperatorSymbol.GreaterThanEqual:
return (val1 >= val2);
}
throw new WarningException("Unknown operator type");
}
private static bool CompareStr(OperatorSymbol oper, string val1, string val2)
{
switch(oper)
{
case OperatorSymbol.Equal:
return (val1 == val2);
case OperatorSymbol.NotEqual:
return (val1 != val2);
case OperatorSymbol.LessThan:
return (val1.CompareTo(val2) < 0);
case OperatorSymbol.LessThanEqual:
return (val1.CompareTo(val2) <= 0);
case OperatorSymbol.GreaterThan:
return (val1.CompareTo(val2) > 0);
case OperatorSymbol.GreaterThanEqual:
return (val1.CompareTo(val2) >= 0);
}
throw new WarningException("Unknown operator type");
}
private static char NextChar(int idx, string str)
{
if((idx + 1) >= str.Length)
{
return Char.MaxValue;
}
return str[idx + 1];
}
// Very very simple expression parser. Can only match expressions of the form
// <var> <op> <value>:
// OS = Windows
// OS != Linux
// RuntimeMinor > 0
private bool ParseExpression(string exp)
{
if(exp == null)
{
throw new ArgumentException("Invalid expression, cannot be null");
}
exp = exp.Trim();
if(exp.Length < 1)
{
throw new ArgumentException("Invalid expression, cannot be 0 length");
}
string id = "";
string str = "";
OperatorSymbol oper = OperatorSymbol.None;
bool inStr = false;
char c;
for(int i = 0; i < exp.Length; i++)
{
c = exp[i];
if(Char.IsWhiteSpace(c))
{
continue;
}
if(Char.IsLetterOrDigit(c) || c == '_')
{
if(inStr)
{
str += c;
}
else
{
id += c;
}
}
else if(c == '\"')
{
inStr = !inStr;
if(inStr)
{
str = "";
}
}
else
{
if(inStr)
{
str += c;
}
else
{
switch(c)
{
case '=':
oper = OperatorSymbol.Equal;
break;
case '!':
if(NextChar(i, exp) == '=')
{
oper = OperatorSymbol.NotEqual;
}
break;
case '<':
if(NextChar(i, exp) == '=')
{
oper = OperatorSymbol.LessThanEqual;
}
else
{
oper = OperatorSymbol.LessThan;
}
break;
case '>':
if(NextChar(i, exp) == '=')
{
oper = OperatorSymbol.GreaterThanEqual;
}
else
{
oper = OperatorSymbol.GreaterThan;
}
break;
}
}
}
}
if(inStr)
{
throw new WarningException("Expected end of string in expression");
}
if(oper == OperatorSymbol.None)
{
throw new WarningException("Expected operator in expression");
}
else if(id.Length < 1)
{
throw new WarningException("Expected identifier in expression");
}
else if(str.Length < 1)
{
throw new WarningException("Expected value in expression");
}
bool ret = false;
try
{
object val = m_Variables[id.ToLower()];
if(val == null)
{
throw new WarningException("Unknown identifier '{0}'", id);
}
int numVal, numVal2;
string strVal, strVal2;
Type t = val.GetType();
if(t.IsAssignableFrom(typeof(int)))
{
numVal = (int)val;
numVal2 = Int32.Parse(str);
ret = CompareNum(oper, numVal, numVal2);
}
else
{
strVal = val.ToString();
strVal2 = str;
ret = CompareStr(oper, strVal, strVal2);
}
}
catch(ArgumentException ex)
{
ex.ToString();
throw new WarningException("Invalid value type for system variable '{0}', expected int", id);
}
return ret;
}
#endregion
#region Public Methods
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="variableValue"></param>
public void RegisterVariable(string name, object variableValue)
{
if(name == null || variableValue == null)
{
return;
}
m_Variables[name.ToLower()] = variableValue;
}
/// <summary>
/// Performs validation on the xml source as well as evaluates conditional and flow expresions
/// </summary>
/// <exception cref="ArgumentException">For invalid use of conditional expressions or for invalid XML syntax. If a XmlValidatingReader is passed, then will also throw exceptions for non-schema-conforming xml</exception>
/// <param name="reader"></param>
/// <returns>the output xml </returns>
public string Process(XmlReader reader)
{
if(reader == null)
{
throw new ArgumentException("Invalid XML reader to pre-process");
}
IfContext context = new IfContext(true, true, IfState.None);
StringWriter xmlText = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(xmlText);
writer.Formatting = Formatting.Indented;
while(reader.Read())
{
if(reader.NodeType == XmlNodeType.ProcessingInstruction)
{
bool ignore = false;
switch(reader.LocalName)
{
case "if":
m_IfStack.Push(context);
context = new IfContext(context.Keep & context.Active, ParseExpression(reader.Value), IfState.If);
ignore = true;
break;
case "elseif":
if(m_IfStack.Count == 0)
{
throw new WarningException("Unexpected 'elseif' outside of 'if'");
}
else if(context.State != IfState.If && context.State != IfState.ElseIf)
{
throw new WarningException("Unexpected 'elseif' outside of 'if'");
}
context.State = IfState.ElseIf;
if(!context.EverKept)
{
context.Keep = ParseExpression(reader.Value);
}
else
{
context.Keep = false;
}
ignore = true;
break;
case "else":
if(m_IfStack.Count == 0)
{
throw new WarningException("Unexpected 'else' outside of 'if'");
}
else if(context.State != IfState.If && context.State != IfState.ElseIf)
{
throw new WarningException("Unexpected 'else' outside of 'if'");
}
context.State = IfState.Else;
context.Keep = !context.EverKept;
ignore = true;
break;
case "endif":
if(m_IfStack.Count == 0)
{
throw new WarningException("Unexpected 'endif' outside of 'if'");
}
context = (IfContext)m_IfStack.Pop();
ignore = true;
break;
}
if(ignore)
{
continue;
}
}//end pre-proc instruction
if(!context.Active || !context.Keep)
{
continue;
}
switch(reader.NodeType)
{
case XmlNodeType.Element:
bool empty = reader.IsEmptyElement;
writer.WriteStartElement(reader.Name);
while (reader.MoveToNextAttribute())
{
writer.WriteAttributeString(reader.Name, reader.Value);
}
if(empty)
{
writer.WriteEndElement();
}
break;
case XmlNodeType.EndElement:
writer.WriteEndElement();
break;
case XmlNodeType.Text:
writer.WriteString(reader.Value);
break;
case XmlNodeType.CDATA:
writer.WriteCData(reader.Value);
break;
default:
break;
}
}
if(m_IfStack.Count != 0)
{
throw new WarningException("Mismatched 'if', 'endif' pair");
}
return xmlText.ToString();
}
#endregion
}
}
| |
using System;
using Server.Network;
namespace Server.Items
{
[FlipableAttribute( 0xc77, 0xc78 )]
public class Carrot : Food
{
[Constructable]
public Carrot() : this( 1 )
{
}
[Constructable]
public Carrot( int amount ) : base( amount, 0xc78 )
{
this.Name = "Carotte";
this.Weight = 1.0;
this.FillFactor = 1;
}
public Carrot( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0xc7b, 0xc7c )]
public class Cabbage : Food
{
[Constructable]
public Cabbage() : this( 1 )
{
}
[Constructable]
public Cabbage( int amount ) : base( amount, 0xc7b )
{
this.Name = "Chou";
this.Weight = 1.0;
this.FillFactor = 1;
}
public Cabbage( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0xc6d, 0xc6e )]
public class Onion : Food
{
[Constructable]
public Onion() : this( 1 )
{
}
[Constructable]
public Onion( int amount ) : base( amount, 0xc6d )
{
this.Name = "Oignon";
this.Weight = 1.0;
this.FillFactor = 1;
}
public Onion( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0xc70, 0xc71 )]
public class Lettuce : Food
{
[Constructable]
public Lettuce() : this( 1 )
{
}
[Constructable]
public Lettuce( int amount ) : base( amount, 0xc70 )
{
this.Name = "Laitue";
this.Weight = 1.0;
this.FillFactor = 1;
}
public Lettuce( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0xC6A, 0xC6B )]
public class Pumpkin : Food
{
[Constructable]
public Pumpkin() : this( 1 )
{
}
[Constructable]
public Pumpkin( int amount ) : base( amount, 0xC6A )
{
this.Name = "Citrouille";
this.Weight = 1.0;
this.FillFactor = 8;
}
public Pumpkin( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 1 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
if ( version < 1 )
{
if ( FillFactor == 4 )
FillFactor = 8;
if ( Weight == 5.0 )
Weight = 1.0;
}
}
}
public class SmallPumpkin : Food
{
[Constructable]
public SmallPumpkin() : this( 1 )
{
}
[Constructable]
public SmallPumpkin( int amount ) : base( amount, 0xC6C )
{
this.Name = "Potiron";
this.Weight = 1.0;
this.FillFactor = 8;
}
public SmallPumpkin( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
}
| |
#region --- License ---
/* Licensed under the MIT/X11 license.
* Copyright (c) 2006-2008 the OpenTK Team.
* This notice may not be removed from any source distribution.
* See license.txt for licensing detailed licensing details.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using OpenTK.Graphics;
namespace OpenTK.Platform.X11
{
class X11GraphicsMode : IGraphicsMode
{
// Todo: Add custom visual selection algorithm, instead of ChooseFBConfig/ChooseVisual.
// It seems the Choose* methods do not take multisampling into account (at least on some
// drivers).
#region Constructors
public X11GraphicsMode()
{
}
#endregion
#region IGraphicsMode Members
public GraphicsMode SelectGraphicsMode(ColorFormat color, int depth, int stencil, int samples, ColorFormat accum,
int buffers, bool stereo)
{
GraphicsMode gfx;
// The actual GraphicsMode that will be selected.
IntPtr visual = IntPtr.Zero;
IntPtr display = API.DefaultDisplay;
// Try to select a visual using Glx.ChooseFBConfig and Glx.GetVisualFromFBConfig.
// This is only supported on GLX 1.3 - if it fails, fall back to Glx.ChooseVisual.
visual = SelectVisualUsingFBConfig(color, depth, stencil, samples, accum, buffers, stereo);
if (visual == IntPtr.Zero)
visual = SelectVisualUsingChooseVisual(color, depth, stencil, samples, accum, buffers, stereo);
if (visual == IntPtr.Zero)
throw new GraphicsModeException("Requested GraphicsMode not available.");
XVisualInfo info = (XVisualInfo)Marshal.PtrToStructure(visual, typeof(XVisualInfo));
// See what we *really* got:
int r, g, b, a;
Glx.GetConfig(display, ref info, GLXAttribute.ALPHA_SIZE, out a);
Glx.GetConfig(display, ref info, GLXAttribute.RED_SIZE, out r);
Glx.GetConfig(display, ref info, GLXAttribute.GREEN_SIZE, out g);
Glx.GetConfig(display, ref info, GLXAttribute.BLUE_SIZE, out b);
int ar, ag, ab, aa;
Glx.GetConfig(display, ref info, GLXAttribute.ACCUM_ALPHA_SIZE, out aa);
Glx.GetConfig(display, ref info, GLXAttribute.ACCUM_RED_SIZE, out ar);
Glx.GetConfig(display, ref info, GLXAttribute.ACCUM_GREEN_SIZE, out ag);
Glx.GetConfig(display, ref info, GLXAttribute.ACCUM_BLUE_SIZE, out ab);
Glx.GetConfig(display, ref info, GLXAttribute.DEPTH_SIZE, out depth);
Glx.GetConfig(display, ref info, GLXAttribute.STENCIL_SIZE, out stencil);
Glx.GetConfig(display, ref info, GLXAttribute.SAMPLES, out samples);
Glx.GetConfig(display, ref info, GLXAttribute.DOUBLEBUFFER, out buffers);
++buffers;
// the above lines returns 0 - false and 1 - true.
int st;
Glx.GetConfig(display, ref info, GLXAttribute.STEREO, out st);
stereo = st != 0;
gfx = new GraphicsMode(info.VisualID, new ColorFormat(r, g, b, a), depth, stencil, samples,
new ColorFormat(ar, ag, ab, aa), buffers, stereo);
using (new XLock(display))
{
Functions.XFree(visual);
}
return gfx;
}
#endregion
#region Private Members
// See http://publib.boulder.ibm.com/infocenter/systems/index.jsp?topic=/com.ibm.aix.opengl/doc/openglrf/glXChooseFBConfig.htm
// for the attribute declarations. Note that the attributes are different than those used in Glx.ChooseVisual.
IntPtr SelectVisualUsingFBConfig(ColorFormat color, int depth, int stencil, int samples, ColorFormat accum,
int buffers, bool stereo)
{
List<int> visualAttributes = new List<int>();
IntPtr visual = IntPtr.Zero;
Debug.Print("Bits per pixel: {0}", color.BitsPerPixel);
if (color.BitsPerPixel > 0)
{
if (!color.IsIndexed)
{
visualAttributes.Add((int)GLXAttribute.RGBA);
visualAttributes.Add(1);
}
visualAttributes.Add((int)GLXAttribute.RED_SIZE);
visualAttributes.Add(color.Red);
visualAttributes.Add((int)GLXAttribute.GREEN_SIZE);
visualAttributes.Add(color.Green);
visualAttributes.Add((int)GLXAttribute.BLUE_SIZE);
visualAttributes.Add(color.Blue);
visualAttributes.Add((int)GLXAttribute.ALPHA_SIZE);
visualAttributes.Add(color.Alpha);
}
Debug.Print("Depth: {0}", depth);
if (depth > 0)
{
visualAttributes.Add((int)GLXAttribute.DEPTH_SIZE);
visualAttributes.Add(depth);
}
if (buffers > 1)
{
visualAttributes.Add((int)GLXAttribute.DOUBLEBUFFER);
visualAttributes.Add(1);
}
if (stencil > 1)
{
visualAttributes.Add((int)GLXAttribute.STENCIL_SIZE);
visualAttributes.Add(stencil);
}
if (accum.BitsPerPixel > 0)
{
visualAttributes.Add((int)GLXAttribute.ACCUM_ALPHA_SIZE);
visualAttributes.Add(accum.Alpha);
visualAttributes.Add((int)GLXAttribute.ACCUM_BLUE_SIZE);
visualAttributes.Add(accum.Blue);
visualAttributes.Add((int)GLXAttribute.ACCUM_GREEN_SIZE);
visualAttributes.Add(accum.Green);
visualAttributes.Add((int)GLXAttribute.ACCUM_RED_SIZE);
visualAttributes.Add(accum.Red);
}
if (samples > 0)
{
visualAttributes.Add((int)GLXAttribute.SAMPLE_BUFFERS);
visualAttributes.Add(1);
visualAttributes.Add((int)GLXAttribute.SAMPLES);
visualAttributes.Add(samples);
}
if (stereo)
{
visualAttributes.Add((int)GLXAttribute.STEREO);
visualAttributes.Add(1);
}
visualAttributes.Add(0);
// Select a visual that matches the parameters set by the user.
IntPtr display = API.DefaultDisplay;
using (new XLock(display))
{
try
{
int screen = Functions.XDefaultScreen(display);
IntPtr root = Functions.XRootWindow(display, screen);
Debug.Print("Display: {0}, Screen: {1}, RootWindow: {2}", display, screen, root);
unsafe
{
Debug.Print("Getting FB config.");
int fbcount;
// Note that ChooseFBConfig returns an array of GLXFBConfig opaque structures (i.e. mapped to IntPtrs).
IntPtr* fbconfigs = Glx.ChooseFBConfig(display, screen, visualAttributes.ToArray(), out fbcount);
if (fbcount > 0 && fbconfigs != null)
{
// We want to use the first GLXFBConfig from the fbconfigs array (the first one is the best match).
visual = Glx.GetVisualFromFBConfig(display, *fbconfigs);
Functions.XFree((IntPtr)fbconfigs);
}
}
}
catch (EntryPointNotFoundException)
{
Debug.Print("Function glXChooseFBConfig not supported.");
return IntPtr.Zero;
}
}
return visual;
}
// See http://publib.boulder.ibm.com/infocenter/systems/index.jsp?topic=/com.ibm.aix.opengl/doc/openglrf/glXChooseVisual.htm
IntPtr SelectVisualUsingChooseVisual(ColorFormat color, int depth, int stencil, int samples, ColorFormat accum,
int buffers, bool stereo)
{
List<int> visualAttributes = new List<int>();
Debug.Print("Bits per pixel: {0}", color.BitsPerPixel);
if (color.BitsPerPixel > 0)
{
if (!color.IsIndexed)
visualAttributes.Add((int)GLXAttribute.RGBA);
visualAttributes.Add((int)GLXAttribute.RED_SIZE);
visualAttributes.Add(color.Red);
visualAttributes.Add((int)GLXAttribute.GREEN_SIZE);
visualAttributes.Add(color.Green);
visualAttributes.Add((int)GLXAttribute.BLUE_SIZE);
visualAttributes.Add(color.Blue);
visualAttributes.Add((int)GLXAttribute.ALPHA_SIZE);
visualAttributes.Add(color.Alpha);
}
Debug.Print("Depth: {0}", depth);
if (depth > 0)
{
visualAttributes.Add((int)GLXAttribute.DEPTH_SIZE);
visualAttributes.Add(depth);
}
if (buffers > 1)
visualAttributes.Add((int)GLXAttribute.DOUBLEBUFFER);
if (stencil > 1)
{
visualAttributes.Add((int)GLXAttribute.STENCIL_SIZE);
visualAttributes.Add(stencil);
}
if (accum.BitsPerPixel > 0)
{
visualAttributes.Add((int)GLXAttribute.ACCUM_ALPHA_SIZE);
visualAttributes.Add(accum.Alpha);
visualAttributes.Add((int)GLXAttribute.ACCUM_BLUE_SIZE);
visualAttributes.Add(accum.Blue);
visualAttributes.Add((int)GLXAttribute.ACCUM_GREEN_SIZE);
visualAttributes.Add(accum.Green);
visualAttributes.Add((int)GLXAttribute.ACCUM_RED_SIZE);
visualAttributes.Add(accum.Red);
}
if (samples > 0)
{
visualAttributes.Add((int)GLXAttribute.SAMPLE_BUFFERS);
visualAttributes.Add(1);
visualAttributes.Add((int)GLXAttribute.SAMPLES);
visualAttributes.Add(samples);
}
if (stereo)
visualAttributes.Add((int)GLXAttribute.STEREO);
visualAttributes.Add(0);
Debug.Print("Falling back to glXChooseVisual.");
IntPtr display = API.DefaultDisplay;
using (new XLock(display))
{
return Glx.ChooseVisual(display, Functions.XDefaultScreen(display), visualAttributes.ToArray());
}
}
#endregion
}
}
| |
/*
* CSharpCompiler.cs - Implement the "cscompmgd" assembly.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace Microsoft.CSharp
{
using System;
using System.Text;
using System.Collections;
using System.CodeDom.Compiler;
// Level of error that caused a message.
public enum ErrorLevel
{
None = 0,
Warning = 1,
Error = 2,
FatalError = 3
} // enum ErrorLevel
// Wrapped version of a compiler error message.
public class CompilerError
{
// Public error information.
public ErrorLevel ErrorLevel;
public String ErrorMessage;
public int ErrorNumber;
public int SourceColumn;
public String SourceFile;
public int SourceLine;
// Convert the error information into a string.
public override String ToString()
{
StringBuilder builder = new StringBuilder();
if(SourceFile != null)
{
builder.AppendFormat("{0}({1},{2}): ", SourceFile,
SourceLine, SourceColumn);
}
switch(ErrorLevel)
{
case ErrorLevel.Warning:
{
builder.Append("warning ");
}
break;
case ErrorLevel.Error:
{
builder.Append("error ");
}
break;
case ErrorLevel.FatalError:
{
builder.Append("fatal error ");
}
break;
default: break;
}
builder.AppendFormat("CS{0:D4}: ", ErrorNumber);
if(ErrorMessage != null)
{
builder.Append(ErrorMessage);
}
return builder.ToString();
}
} // class CompilerError
// Public interface to the C# compiler.
public class Compiler
{
// Compile a number of source files.
public static CompilerError[] Compile
(String[] sourceTexts, String[] sourceTextNames,
String target, String[] imports, IDictionary options)
{
// Validate the parameters.
if(sourceTexts == null)
{
throw new ArgumentNullException("sourceTexts");
}
if(sourceTextNames == null)
{
throw new ArgumentNullException("sourceTextNames");
}
if(target == null)
{
throw new ArgumentNullException("target");
}
if(sourceTexts.Length == 0)
{
throw new ArgumentOutOfRangeException("sourceTexts");
}
if(sourceTexts.Length != sourceTextNames.Length)
{
throw new ArgumentOutOfRangeException("sourceTextNames");
}
#if CONFIG_CODEDOM
// Build the compiler parameter block.
CompilerParameters paramBlock;
paramBlock = new CompilerParameters
(imports, target, OptionSet(options, "debug"));
int len = target.Length;
if(len > 4 && target[len - 4] == '.' &&
(target[len - 3] == 'd' || target[len - 3] == 'D') &&
(target[len - 2] == 'l' || target[len - 2] == 'L') &&
(target[len - 1] == 'l' || target[len - 1] == 'L'))
{
paramBlock.GenerateExecutable = false;
}
else
{
paramBlock.GenerateExecutable = true;
}
if(OptionSet(options, "warnaserror"))
{
paramBlock.TreatWarningsAsErrors = true;
}
StringBuilder opts = new StringBuilder();
if(OptionSet(options, "o"))
{
opts.Append(" /optimize");
}
if(OptionSet(options, "checked"))
{
opts.Append(" /checked");
}
String opt = (String)(options["d"]);
if(opt != null)
{
opts.AppendFormat(" /define:{0}", opt);
}
opt = (String)(options["m"]);
if(opt != null)
{
opts.AppendFormat(" /m:{0}", opt);
}
if(OptionSet(options, "nostdlib"))
{
opts.Append(" /nostdlib");
}
opt = (String)(options["res"]);
if(opt != null)
{
opts.AppendFormat(" /resource:{0}", opt);
}
opt = (String)(options["target"]);
if(opt != null)
{
paramBlock.GenerateExecutable = (opt != "library");
}
if(OptionSet(options, "unsafe"))
{
opts.Append(" /unsafe");
}
paramBlock.CompilerOptions = opts.ToString();
// Build a new set of source texts, with the filename
// information from "sourceTextNames" prepended.
String[] sources = new String [sourceTexts.Length];
int posn;
for(posn = 0; posn < sourceTexts.Length; ++posn)
{
if(sourceTextNames[posn] == null)
{
sources[posn] = sourceTexts[posn];
}
else
{
sources[posn] = "#line 1 \"" + sourceTextNames[posn] +
"\"" + Environment.NewLine +
sourceTexts[posn];
}
}
// Compile the source texts.
ICodeCompiler compiler =
(new CSharpCodeProvider()).CreateCompiler();
CompilerResults results =
compiler.CompileAssemblyFromSourceBatch
(paramBlock, sources);
// Convert the errors into the correct format and return them.
CompilerErrorCollection errors = results.Errors;
CompilerError[] newErrors = new CompilerError [errors.Count];
posn = 0;
foreach(System.CodeDom.Compiler.CompilerError error in errors)
{
newErrors[posn] = new CompilerError();
newErrors[posn].ErrorLevel =
(error.IsWarning ? ErrorLevel.Warning
: ErrorLevel.Error);
newErrors[posn].ErrorMessage = error.ErrorText;
if(error.ErrorNumber != null &&
error.ErrorNumber.StartsWith("CS"))
{
newErrors[posn].ErrorNumber =
Int32.Parse(error.ErrorNumber.Substring(2));
}
newErrors[posn].SourceColumn = error.Column;
newErrors[posn].SourceFile = error.FileName;
newErrors[posn].SourceLine = error.Line;
++posn;
}
return newErrors;
#else
// We don't have the necessary CodeDom API's.
throw new NotImplementedException();
#endif
}
// Determine if a boolean option is set.
private static bool OptionSet(IDictionary options, String name)
{
Object obj = options[name];
if(obj != null)
{
if(obj is Boolean)
{
return (bool)obj;
}
else if(obj is String)
{
String str = (String)obj;
if(str == "true" || str == "1" || str == "+")
{
return true;
}
}
}
return false;
}
} // class Compiler
} // namespace Microsoft.CSharp
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Xunit;
namespace System.IO.Tests
{
public class Directory_GetFileSystemEntries_str : FileSystemTest
{
#region Utilities
public static TheoryData WindowsInvalidUnixValid = new TheoryData<string> { " ", " ", "\n", ">", "<", "\t" };
protected virtual bool TestFiles { get { return true; } } // True if the virtual GetEntries mmethod returns files
protected virtual bool TestDirectories { get { return true; } } // True if the virtual GetEntries mmethod returns Directories
public virtual string[] GetEntries(string dirName)
{
return Directory.GetFileSystemEntries(dirName);
}
/// <summary>
/// Create a file at the given path or directory if GetEntries doesn't return files
/// </summary>
protected void CreateItem(string path)
{
if (TestFiles)
File.WriteAllText(path, path);
else
Directory.CreateDirectory(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullFileName()
{
Assert.Throws<ArgumentNullException>(() => GetEntries(null));
}
[Fact]
public void EmptyFileName()
{
Assert.Throws<ArgumentException>(() => GetEntries(string.Empty));
}
[Fact]
public void InvalidFileNames()
{
Assert.Throws<DirectoryNotFoundException>(() => GetEntries("DoesNotExist"));
Assert.Throws<ArgumentException>(() => GetEntries("\0"));
}
[Fact]
public void EmptyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Empty(GetEntries(testDir.FullName));
}
[Fact]
public void GetEntriesThenDelete()
{
string testDirPath = GetTestFilePath();
DirectoryInfo testDirInfo = new DirectoryInfo(testDirPath);
testDirInfo.Create();
string testDir1 = GetTestFileName();
string testDir2 = GetTestFileName();
string testFile1 = GetTestFileName();
string testFile2 = GetTestFileName();
string testFile3 = GetTestFileName();
string testFile4 = GetTestFileName();
string testFile5 = GetTestFileName();
testDirInfo.CreateSubdirectory(testDir1);
testDirInfo.CreateSubdirectory(testDir2);
using (File.Create(Path.Combine(testDirPath, testFile1)))
using (File.Create(Path.Combine(testDirPath, testFile2)))
using (File.Create(Path.Combine(testDirPath, testFile3)))
{
string[] results;
using (File.Create(Path.Combine(testDirPath, testFile4)))
using (File.Create(Path.Combine(testDirPath, testFile5)))
{
results = GetEntries(testDirPath);
Assert.NotNull(results);
Assert.NotEmpty(results);
if (TestFiles)
{
Assert.Contains(Path.Combine(testDirPath, testFile1), results);
Assert.Contains(Path.Combine(testDirPath, testFile2), results);
Assert.Contains(Path.Combine(testDirPath, testFile3), results);
Assert.Contains(Path.Combine(testDirPath, testFile4), results);
Assert.Contains(Path.Combine(testDirPath, testFile5), results);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDirPath, testDir1), results);
Assert.Contains(Path.Combine(testDirPath, testDir2), results);
}
}
File.Delete(Path.Combine(testDirPath, testFile4));
File.Delete(Path.Combine(testDirPath, testFile5));
FailSafeDirectoryOperations.DeleteDirectory(testDir1, true);
results = GetEntries(testDirPath);
Assert.NotNull(results);
Assert.NotEmpty(results);
if (TestFiles)
{
Assert.Contains(Path.Combine(testDirPath, testFile1), results);
Assert.Contains(Path.Combine(testDirPath, testFile2), results);
Assert.Contains(Path.Combine(testDirPath, testFile3), results);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDirPath, testDir2), results);
}
}
}
[Fact]
public virtual void IgnoreSubDirectoryFiles()
{
string subDir = GetTestFileName();
Directory.CreateDirectory(Path.Combine(TestDirectory, subDir));
string testFile = Path.Combine(TestDirectory, GetTestFileName());
string testFileInSub = Path.Combine(TestDirectory, subDir, GetTestFileName());
string testDir = Path.Combine(TestDirectory, GetTestFileName());
string testDirInSub = Path.Combine(TestDirectory, subDir, GetTestFileName());
Directory.CreateDirectory(testDir);
Directory.CreateDirectory(testDirInSub);
using (File.Create(testFile))
using (File.Create(testFileInSub))
{
string[] results = GetEntries(TestDirectory);
if (TestFiles)
Assert.Contains(testFile, results);
if (TestDirectories)
Assert.Contains(testDir, results);
Assert.DoesNotContain(testFileInSub, results);
Assert.DoesNotContain(testDirInSub, results);
}
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingFile_ThrowsDirectoryNotFound(char trailingChar)
{
string path = GetTestFilePath() + trailingChar;
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(path));
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingDirectory_ThrowsDirectoryNotFound(char trailingChar)
{
string path = Path.Combine(GetTestFilePath(), "file" + trailingChar);
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(path));
}
[Fact]
public void TrailingSlashes()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, GetTestFileName()));
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
{
string[] strArr = GetEntries(testDir.FullName + new string(Path.DirectorySeparatorChar, 5));
Assert.NotNull(strArr);
Assert.NotEmpty(strArr);
}
}
[Fact]
public void HiddenFilesAreReturned()
{
// Note that APIs that take EnumerationOptions do NOT find hidden files by default
DirectoryInfo testDirectory = Directory.CreateDirectory(GetTestFilePath());
FileInfo fileOne = new FileInfo(Path.Combine(testDirectory.FullName, GetTestFileName()));
// Put a period in front to make it hidden on Unix
FileInfo fileTwo = new FileInfo(Path.Combine(testDirectory.FullName, "." + GetTestFileName()));
fileOne.Create().Dispose();
fileTwo.Create().Dispose();
if (PlatformDetection.IsWindows)
fileTwo.Attributes = fileTwo.Attributes | FileAttributes.Hidden;
if (TestFiles)
{
FSAssert.EqualWhenOrdered(new string[] { fileOne.FullName, fileTwo.FullName }, GetEntries(testDirectory.FullName));
}
else
{
Assert.Empty(GetEntries(testDirectory.FullName));
}
}
#endregion
#region PlatformSpecific
[Fact]
public void InvalidPath()
{
foreach (char invalid in Path.GetInvalidFileNameChars())
{
if (invalid == '/' || invalid == '\\')
{
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString()))));
}
else if (invalid == ':')
{
if (FileSystemDebugInfo.IsCurrentDriveNTFS())
Assert.Throws<NotSupportedException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString()))));
}
else
{
Assert.Throws<ArgumentException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString()))));
}
}
}
[Theory,
MemberData(nameof(WindowsInvalidUnixValid))]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-only Invalid chars in path
public void WindowsInvalidCharsPath(string invalid)
{
Assert.Throws<ArgumentException>(() => GetEntries(invalid));
}
[Theory,
MemberData(nameof(WindowsInvalidUnixValid))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-only valid chars in file path
public void UnixValidCharsFilePath(string valid)
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
File.Create(Path.Combine(testDir.FullName, valid)).Dispose();
string[] results = GetEntries(testDir.FullName);
Assert.Contains(Path.Combine(testDir.FullName, valid), results);
}
}
[Theory,
MemberData(nameof(WindowsInvalidUnixValid))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Windows-only invalid chars in directory path
public void UnixValidCharsDirectoryPath(string valid)
{
if (TestDirectories)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory(valid);
string[] results = GetEntries(testDir.FullName);
Assert.Contains(Path.Combine(testDir.FullName, valid), results);
}
}
#endregion
}
public sealed class Directory_GetEntries_CurrentDirectory : RemoteExecutorTestBase
{
[Fact]
public void CurrentDirectory()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
File.WriteAllText(Path.Combine(testDir, GetTestFileName()), "cat");
Directory.CreateDirectory(Path.Combine(testDir, GetTestFileName()));
RemoteInvoke((testDirectory) =>
{
Directory.SetCurrentDirectory(testDirectory);
Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory()));
Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory()));
Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory()));
Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory()));
Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory()));
Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory()));
Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
return SuccessExitCode;
}, testDir).Dispose();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Trionic5Tools
{
public class SymbolAxesTranslator
{
public string GetXaxisSymbol(string symbolname)
{
string retval = string.Empty;
if (symbolname.StartsWith("Ign_map_0!") || symbolname == "Knock_count_map")
{
retval = "Ign_map_0_x_axis!";
}
else if (symbolname.StartsWith("Ign_map_1!"))
{
retval = "Ign_map_1_x_axis!";
}
else if (symbolname.StartsWith("Ign_map_2!"))
{
retval = "Ign_map_2_x_axis!";
}
else if (symbolname.StartsWith("Ign_map_3!"))
{
retval = "Ign_map_3_x_axis!";
}
else if (symbolname.StartsWith("Ign_map_4!"))
{
retval = "Ign_map_0_x_axis!";
}
else if (symbolname.StartsWith("Ign_map_5!"))
{
retval = "Ign_map_5_x_axis!";
}
else if (symbolname.StartsWith("Ign_map_6!"))
{
retval = "Ign_map_6_x_axis!";
}
else if (symbolname.StartsWith("Ign_map_7!"))
{
retval = "Ign_map_7_x_axis!";
}
else if (symbolname.StartsWith("Ign_map_8!"))
{
retval = "Ign_map_8_x_axis!";
}
else if (symbolname == "Lambdamatris!" || symbolname == "Lambdamatris_diag!")
{
retval = "Lam_laststeg!";
}
else if (symbolname.StartsWith("Tryck_mat!") || symbolname.StartsWith("Pressure map"))
{
//retval = "Trans_x_st!";
retval = "Pwm_ind_trot!";
}
else if (symbolname.StartsWith("Idle_tryck!"))
{
retval = "Trans_x_st!";
}
else if (symbolname.StartsWith("Overs_tab!"))
{
retval = "Overs_tab_xaxis!";
}
else if (symbolname.StartsWith("Tryck_mat_a!"))
{
// retval = "Trans_x_st!";
retval = "Pwm_ind_trot!";
}
else if (symbolname.StartsWith("Insp_mat!") || symbolname == "Adapt_ggr" || symbolname == "Adapt_ref" || symbolname == "Adapt_ind_mat")
{
retval = "Fuel_map_xaxis!";
}
else if (symbolname.StartsWith("Adapt_ref"))
{
retval = "Fuel_map_xaxis!";
}
else if (symbolname.StartsWith("Inj_map_0!"))
{
retval = "Inj_map_0_x_axis!";
}
else if (symbolname.StartsWith("Dash_tab!"))
{
retval = "Dash_trot_axis!";
}
else if (symbolname.StartsWith("Purge_tab!"))
{
retval = "Fuel_map_xaxis!";
}
else if (symbolname.StartsWith("Adapt_korr"))
{
retval = "Fuel_map_xaxis!";
}
else if (symbolname.StartsWith("Idle_fuel_korr!"))
{
retval = "Idle_st_last!";
}
else if (symbolname.StartsWith("Lacc_konst!"))
{
retval = "Trans_x_st!";
}
else if (symbolname.StartsWith("Lret_konst!"))
{
retval = "Trans_x_st!";
}
else if (symbolname.StartsWith("Accel_konst!"))
{
retval = "Trans_x_st!";
}
else if (symbolname.StartsWith("Retard_konst!"))
{
retval = "Trans_x_st!";
}
else if (symbolname.StartsWith("P_fors!") || symbolname.StartsWith("I_fors!") || symbolname.StartsWith("D_fors!"))
{
retval = "Reg_last!";
}
else if (symbolname.StartsWith("P_fors_a!") || symbolname.StartsWith("I_fors_a!") || symbolname.StartsWith("D_fors_a!"))
{
retval = "Reg_last!";
}
else if (symbolname.StartsWith("Del_mat!"))
{
retval = "Fuel_map_xaxis!";
}
else if (symbolname.StartsWith("Fuel_knock_mat!"))
{
retval = "Fuel_knock_xaxis!";
}
else if (symbolname.StartsWith("Mis200_map!") || symbolname.StartsWith("Mis1000_map!"))
{
retval = "Misfire_map_x_axis!";
}
else if (symbolname.StartsWith("Misfire_map!"))
{
retval = "Misfire_map_x_axis!";
}
else if (symbolname.StartsWith("Knock_ref_matrix!"))
{
retval = "Ign_map_0_x_axis!";
}
else if (symbolname.StartsWith("Temp_reduce_mat!") || symbolname.StartsWith("Temp_reduce_mat_2!"))
{
retval = "Temp_reduce_x_st!";
}
else if (symbolname.StartsWith("Detect_map!"))
{
retval = "Detect_map_x_axis!";
}
else if ((symbolname.StartsWith("Reg_kon_mat!") || symbolname.StartsWith("Reg_kon_mat_a!")))
{
retval = "Pwm_ind_trot!";
}
return retval;
}
public string GetYaxisSymbol(string symbolname)
{
string retval = string.Empty;
if (symbolname.StartsWith("Ign_map_0!") || symbolname == "Knock_count_map")
{
retval = "Ign_map_0_y_axis!";
}
else if (symbolname.StartsWith("Ign_map_1!"))
{
retval = "Ign_map_1_y_axis!";
}
else if (symbolname.StartsWith("Ign_map_2!"))
{
retval = "Ign_map_2_y_axis!";
}
else if (symbolname.StartsWith("Ign_map_3!"))
{
retval = "Ign_map_3_y_axis!";
}
else if (symbolname.StartsWith("Ign_map_4!"))
{
retval = "Ign_map_0_y_axis!";
}
else if (symbolname.StartsWith("Ign_map_5!"))
{
retval = "Ign_map_5_y_axis!";
}
else if (symbolname.StartsWith("Ign_map_6!"))
{
retval = "Ign_map_6_y_axis!";
}
else if (symbolname.StartsWith("Ign_map_7!"))
{
retval = "Ign_map_7_y_axis!";
}
else if (symbolname.StartsWith("Open_loop_adapt!") || symbolname.StartsWith("Open_loop!") || symbolname.StartsWith("Open_loop_knock!"))
{
retval = "Fuel_map_yaxis";
}
else if (symbolname.StartsWith("Fload_tab!") || symbolname.StartsWith("Fload_throt_tab!"))
{
retval = "Fuel_map_yaxis";
}
else if (symbolname.StartsWith("Ign_map_8!"))
{
retval = "Ign_map_8_y_axis!";
}
else if (symbolname.StartsWith("Before_start!") || symbolname.StartsWith("Startvev_fak!") || symbolname.StartsWith("Start_dead_tab!") || symbolname.StartsWith("Ramp_fak!"))
{
retval = "Temp_steg";
}
else if (symbolname.StartsWith("Kyltemp_tab!"))
{
retval = "Kyltemp_steg!";
}
else if (symbolname.StartsWith("Lufttemp_tab!"))
{
retval = "Lufttemp_steg!";
}
else if (symbolname.StartsWith("Idle_ac_tab!"))
{
retval = "Lufttemp_steg!";
}
else if (symbolname.StartsWith("Derivata_br_tab_pos!") || symbolname.StartsWith("Derivata_br_tab_neg!"))
{
retval = "Derivata_br_sp!";
}
else if (symbolname.StartsWith("I_last_rpm!") || symbolname.StartsWith("Last_reg_ac!"))
{
retval = "Last_varv_st!";
}
else if (symbolname.StartsWith("I_last_temp!"))
{
retval = "Last_temp_st!";
}
else if (symbolname.StartsWith("Iv_start_time_tab!"))
{
retval = "I_kyl_st!";
}
else if (symbolname.StartsWith("Idle_start_extra!"))
{
retval = "Idle_start_extra_sp!";
}
else if (symbolname.StartsWith("Restart_corr_hp!"))
{
retval = "Hp_support_points!";
}
else if (symbolname.StartsWith("Lam_minlast!"))
{
retval = "Fuel_map_yaxis";
}
else if (symbolname.StartsWith("Lamb_tid!") || symbolname.StartsWith("Lamb_idle!") || symbolname.StartsWith("Lamb_ej!"))
{
retval = "Lamb_kyl!";
}
else if (symbolname.StartsWith("Overstid_tab!"))
{
retval = "Pwm_ind_rpm!";
}
else if (symbolname.StartsWith("AC_wait_on!") || symbolname.StartsWith("AC_wait_off!"))
{
retval = "I_luft_st!";
}
else if (symbolname.StartsWith("Tryck_mat!") || symbolname.StartsWith("Pressure map"))
{
retval = "Pwm_ind_rpm!";
}
else if (symbolname.StartsWith("Idle_temp_off!") || symbolname.StartsWith("Idle_rpm_tab!") || symbolname.StartsWith("Start_tab!"))
{
retval = "I_kyl_st!";
}
else if (symbolname.StartsWith("Overs_tab!"))
{
retval = "Pwm_ind_rpm!";
}
else if (symbolname.StartsWith("Tryck_mat_a!"))
{
retval = "Pwm_ind_rpm!";
}
else if (symbolname.StartsWith("Insp_mat!") || symbolname == "Lambdamatris!" || symbolname == "Lambdamatris_diag!")
{
retval = "Fuel_map_yaxis!";
}
else if (symbolname.StartsWith("Adapt_ref"))
{
retval = "Fuel_map_yaxis!";
}
else if (symbolname.StartsWith("Inj_map_0!"))
{
retval = "Inj_map_0_y_axis!";
}
else if (symbolname.StartsWith("Max_regl_temp_"))
{
retval = "Max_regl_sp!";
}
else if (symbolname.StartsWith("Knock_wind_on_tab!") || symbolname.StartsWith("Knock_wind_off_tab!"))
{
retval = "Knock_wind_rpm!";
}
else if (symbolname.StartsWith("Knock_ref_tab!"))
{
retval = "Knock_ref_rpm!";
}
else if (symbolname.StartsWith("Knock_average_tab!") || symbolname.StartsWith("Turbo_knock_tab!") || symbolname.StartsWith("Knock_press_tab!") || symbolname.StartsWith("Lknock_oref_tab!") || symbolname.StartsWith("Knock_lim_tab!"))
{
retval = "Wait_count_tab!";
}
else if (symbolname.StartsWith("Dash_tab!"))
{
retval = "Dash_rpm_axis!";
}
else if (symbolname.StartsWith("Adapt_korr") || symbolname == "Adapt_ind_mat!")
{
retval = "Fuel_map_yaxis!";
}
else if (symbolname.StartsWith("Idle_fuel_korr!"))
{
retval = "Idle_st_rpm!";
}
else if (symbolname.StartsWith("Lacc_konst!"))
{
retval = "Trans_y_st!";
}
else if (symbolname.StartsWith("Lret_konst!"))
{
retval = "Trans_y_st!";
}
else if (symbolname.StartsWith("Accel_konst!"))
{
retval = "Trans_y_st!";
}
else if (symbolname.StartsWith("Retard_konst!"))
{
retval = "Trans_y_st!";
}
else if (symbolname.StartsWith("P_fors!") || symbolname.StartsWith("I_fors!") || symbolname.StartsWith("D_fors!"))
{
retval = "Reg_varv!";
}
else if (symbolname.StartsWith("P_fors_a!") || symbolname.StartsWith("I_fors_a!") || symbolname.StartsWith("D_fors_a!"))
{
retval = "Reg_varv!";
}
else if (symbolname.StartsWith("Del_mat!"))
{
retval = "Fuel_map_yaxis!";
}
else if (symbolname.StartsWith("Tryck_vakt_tab!"))
{
retval = "Pwm_ind_rpm!";
}
else if (symbolname.StartsWith("Regl_tryck_sgm!") || symbolname.StartsWith("Regl_tryck_fgm!") || symbolname.StartsWith("Regl_tryck_fgaut!"))
{
retval = "Pwm_ind_rpm!";
}
else if (symbolname.StartsWith("Fuel_knock_mat!"))
{
retval = "Fuel_map_yaxis!";
}
else if (symbolname.StartsWith("Mis200_map!") || symbolname.StartsWith("Mis1000_map!"))
{
retval = "Misfire_map_y_axis!";
}
else if (symbolname.StartsWith("Misfire_map!"))
{
retval = "Misfire_map_y_axis!";
}
else if (symbolname.StartsWith("Eftersta_fak") || symbolname.StartsWith("Eft_dec_") || symbolname.StartsWith("Eft_fak_") || symbolname.StartsWith("Tempkomp_konst!") || symbolname.StartsWith("Accel_temp!") || symbolname.StartsWith("Accel_temp2!") || symbolname.StartsWith("Retard_temp!") || symbolname.StartsWith("Throt_after_tab!") || symbolname.StartsWith("Throt_aft_dec_fak!"))
{
retval = "Temp_steg!";
}
else if (symbolname.StartsWith("Temp_reduce_mat!") || symbolname.StartsWith("Temp_reduce_mat_2!"))
{
retval = "Temp_reduce_y_st!";
}
else if (symbolname.StartsWith("Knock_ref_matrix!"))
{
retval = "Ign_map_0_y_axis!";
}
else if (symbolname.StartsWith("Detect_map!"))
{
retval = "Detect_map_y_axis!";
}
else if (symbolname.StartsWith("Reg_kon_mat!") || symbolname.StartsWith("Reg_kon_mat_a!"))
{
//TODO: this is only for 3D reg_kon_mat maps... otherwise it's hardcoded
retval = "Pwm_ind_rpm!";
//retval = "";
}
else if (symbolname.StartsWith("Luft_kompfak!"))
{
retval = "Lufttemp_steg!";
}
return retval;
}
}
}
| |
/* New BSD License
-------------------------------------------------------------------------------
Copyright (c) 2006-2012, EntitySpaces, LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the EntitySpaces, LLC nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL EntitySpaces, LLC 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 Mono.Data.Sqlite;
using Tiraggo.DynamicQuery;
using Tiraggo.Interfaces;
namespace Tiraggo.SQLiteProvider
{
class Shared
{
static public SqliteCommand BuildDynamicInsertCommand(tgDataRequest request, tgEntitySavePacket packet)
{
string sql = String.Empty;
string defaults = String.Empty;
string into = String.Empty;
string values = String.Empty;
string comma = String.Empty;
string defaultComma = String.Empty;
string where = String.Empty;
string whereComma = String.Empty;
PropertyCollection props = new PropertyCollection();
Dictionary<string, SqliteParameter> types = Cache.GetParameters(request);
SqliteCommand cmd = new SqliteCommand();
if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
tgColumnMetadataCollection cols = request.Columns;
foreach (tgColumnMetadata col in cols)
{
bool isModified = packet.ModifiedColumns == null ? false : packet.ModifiedColumns.Contains(col.Name);
if (isModified && (!col.IsAutoIncrement && !col.IsConcurrency && !col.IsTiraggoConcurrency))
{
SqliteParameter p = types[col.Name];
cmd.Parameters.Add(CloneParameter(p));
into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
values += comma + p.ParameterName;
comma = ", ";
}
else if (col.IsAutoIncrement)
{
props["AutoInc"] = col.Name;
props["Source"] = request.ProviderMetadata.Source;
}
else if (col.IsConcurrency)
{
props["Timestamp"] = col.Name;
props["Source"] = request.ProviderMetadata.Source;
}
else if (col.IsTiraggoConcurrency)
{
props["EntitySpacesConcurrency"] = col.Name;
SqliteParameter p = types[col.Name];
into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
values += comma + "1";
comma = ", ";
SqliteParameter clone = CloneParameter(p);
clone.Value = 1;
cmd.Parameters.Add(clone);
}
else if (col.IsComputed)
{
// Do nothing but leave this here
}
else if (cols.IsSpecialColumn(col))
{
// Do nothing but leave this here
}
else if (col.HasDefault)
{
defaults += defaultComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
defaultComma = ",";
}
if (col.IsInPrimaryKey)
{
where += whereComma + col.Name;
whereComma = ",";
}
}
#region Special Columns
if (cols.DateAdded != null && cols.DateAdded.IsServerSide)
{
into += comma + Delimiters.ColumnOpen + cols.DateAdded.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["DateAdded.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.DateAdded.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
if (cols.DateModified != null && cols.DateModified.IsServerSide)
{
into += comma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["DateModified.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
if (cols.AddedBy != null && cols.AddedBy.IsServerSide)
{
into += comma + Delimiters.ColumnOpen + cols.AddedBy.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["AddedBy.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.AddedBy.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
if (cols.ModifiedBy != null && cols.ModifiedBy.IsServerSide)
{
into += comma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["ModifiedBy.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
#endregion
if (defaults.Length > 0)
{
comma = String.Empty;
props["Defaults"] = defaults;
props["Where"] = where;
}
sql += " INSERT INTO " + CreateFullName(request);
if (into.Length != 0)
{
sql += "(" + into + ") VALUES (" + values + ")";
}
else
{
sql += "DEFAULT VALUES";
}
request.Properties = props;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return cmd;
}
static public SqliteCommand BuildDynamicUpdateCommand(tgDataRequest request, tgEntitySavePacket packet)
{
string where = String.Empty;
string scomma = String.Empty;
string wcomma = String.Empty;
string defaults = String.Empty;
string defaultsWhere = String.Empty;
string defaultsComma = String.Empty;
string defaultsWhereComma = String.Empty;
string sql = "UPDATE " + CreateFullName(request) + " SET ";
PropertyCollection props = new PropertyCollection();
Dictionary<string, SqliteParameter> types = Cache.GetParameters(request);
SqliteCommand cmd = new SqliteCommand();
if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
tgColumnMetadataCollection cols = request.Columns;
foreach (tgColumnMetadata col in cols)
{
bool isModified = packet.ModifiedColumns == null ? false : packet.ModifiedColumns.Contains(col.Name);
if (isModified && (!col.IsAutoIncrement && !col.IsConcurrency && !col.IsTiraggoConcurrency))
{
SqliteParameter p = types[col.Name];
cmd.Parameters.Add(CloneParameter(p));
sql += scomma;
sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
scomma = ", ";
}
else if (col.IsAutoIncrement)
{
// Nothing to do but leave this here
}
else if (col.IsConcurrency)
{
SqliteParameter p = types[col.Name];
p = CloneParameter(p);
p.SourceVersion = DataRowVersion.Original;
cmd.Parameters.Add(p);
where += wcomma;
where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
wcomma = " AND ";
}
else if (col.IsTiraggoConcurrency)
{
props["EntitySpacesConcurrency"] = col.Name;
SqliteParameter p = types[col.Name];
p = CloneParameter(p);
p.SourceVersion = DataRowVersion.Original;
cmd.Parameters.Add(p);
sql += scomma;
sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " + 1";
scomma = ", ";
where += wcomma;
where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
wcomma = " AND ";
}
else if (col.IsComputed)
{
// Do nothing but leave this here
}
else if (cols.IsSpecialColumn(col))
{
// Do nothing but leave this here
}
else if (col.HasDefault)
{
// defaults += defaultsComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
// defaultsComma = ",";
}
if (col.IsInPrimaryKey)
{
SqliteParameter p = types[col.Name];
p = CloneParameter(p);
p.SourceVersion = DataRowVersion.Original;
cmd.Parameters.Add(p);
where += wcomma;
where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
wcomma = " AND ";
defaultsWhere += defaultsWhereComma + col.Name;
defaultsWhereComma = ",";
}
}
#region Special Columns
if (cols.DateModified != null && cols.DateModified.IsServerSide)
{
sql += scomma;
sql += Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose + " = " + request.ProviderMetadata["DateModified.ServerSideText"];
scomma = ", ";
defaults += defaultsComma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose;
defaultsComma = ",";
}
if (cols.ModifiedBy != null && cols.ModifiedBy.IsServerSide)
{
sql += scomma;
sql += Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose + " = " + request.ProviderMetadata["ModifiedBy.ServerSideText"];
scomma = ", ";
defaults += defaultsComma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose;
defaultsComma = ",";
}
#endregion
if (defaults.Length > 0)
{
props["Defaults"] = defaults;
props["Where"] = defaultsWhere;
}
sql += " WHERE (" + where + ")";
request.Properties = props;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return cmd;
}
static public SqliteCommand BuildDynamicDeleteCommand(tgDataRequest request)
{
Dictionary<string, SqliteParameter> types = Cache.GetParameters(request);
SqliteCommand cmd = new SqliteCommand();
if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
string sql = "DELETE FROM " + CreateFullName(request) + " ";
string comma = String.Empty;
comma = String.Empty;
sql += " WHERE ";
foreach (tgColumnMetadata col in request.Columns)
{
if (col.IsInPrimaryKey || col.IsTiraggoConcurrency)
{
SqliteParameter p = types[col.Name];
cmd.Parameters.Add(CloneParameter(p));
sql += comma;
sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
comma = " AND ";
}
}
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return cmd;
}
static public SqliteCommand BuildStoredProcInsertCommand(tgDataRequest request)
{
return null;
}
static public SqliteCommand BuildStoredProcUpdateCommand(tgDataRequest request)
{
return null;
}
static public SqliteCommand BuildStoredProcDeleteCommand(tgDataRequest request)
{
return null;
}
static public void PopulateStoredProcParameters(SqliteCommand cmd, tgDataRequest request)
{
Dictionary<string, SqliteParameter> types = Cache.GetParameters(request);
SqliteParameter p;
foreach (tgColumnMetadata col in request.Columns)
{
p = types[col.Name];
p = CloneParameter(p);
p.SourceVersion = DataRowVersion.Current;
if (col.IsComputed && col.CharacterMaxLength > 0)
{
p.Size = (int)col.CharacterMaxLength;
}
cmd.Parameters.Add(p);
}
}
static private SqliteParameter CloneParameter(SqliteParameter p)
{
ICloneable param = p as ICloneable;
return param.Clone() as SqliteParameter;
}
static public string CreateFullName(tgDynamicQuerySerializable query)
{
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
tgProviderSpecificMetadata providerMetadata = iQuery.ProviderMetadata as tgProviderSpecificMetadata;
string name = String.Empty;
name += Delimiters.TableOpen;
if (query.tg.QuerySource != null)
name += query.tg.QuerySource;
else
name += providerMetadata.Destination;
name += Delimiters.TableClose;
return name;
}
static public string CreateFullName(tgDataRequest request)
{
string name = String.Empty;
name += Delimiters.TableOpen;
if(request.DynamicQuery != null && request.DynamicQuery.tg.QuerySource != null)
name += request.DynamicQuery.tg.QuerySource;
else
name += request.QueryText != null ? request.QueryText : request.ProviderMetadata.Destination;
name += Delimiters.TableClose;
return name;
}
static public string CreateFullName(tgProviderSpecificMetadata providerMetadata)
{
return Delimiters.TableOpen + providerMetadata.Destination + Delimiters.TableClose;
}
static public tgConcurrencyException CheckForConcurrencyException(SqliteException ex)
{
tgConcurrencyException ce = null;
return ce;
}
static public void AddParameters(SqliteCommand cmd, tgDataRequest request)
{
if (request.QueryType == tgQueryType.Text && request.QueryText != null && request.QueryText.Contains("{0}"))
{
int i = 0;
string token = String.Empty;
string sIndex = String.Empty;
string param = String.Empty;
foreach (tgParameter esParam in request.Parameters)
{
sIndex = i.ToString();
token = '{' + sIndex + '}';
param = Delimiters.Param + "p" + sIndex;
request.QueryText = request.QueryText.Replace(token, param);
i++;
cmd.Parameters.AddWithValue(Delimiters.Param + esParam.Name, esParam.Value);
}
}
else
{
SqliteParameter param;
foreach (tgParameter esParam in request.Parameters)
{
param = cmd.Parameters.AddWithValue(Delimiters.Param + esParam.Name, esParam.Value);
switch (esParam.Direction)
{
case tgParameterDirection.InputOutput:
param.Direction = ParameterDirection.InputOutput;
break;
case tgParameterDirection.Output:
param.Direction = ParameterDirection.Output;
param.DbType = esParam.DbType;
param.Size = esParam.Size;
break;
case tgParameterDirection.ReturnValue:
param.Direction = ParameterDirection.ReturnValue;
break;
// The default is ParameterDirection.Input;
}
}
}
}
static public void GatherReturnParameters(SqliteCommand cmd, tgDataRequest request, tgDataResponse response)
{
if (cmd.Parameters.Count > 0)
{
if (request.Parameters != null && request.Parameters.Count > 0)
{
response.Parameters = new tgParameters();
foreach (tgParameter esParam in request.Parameters)
{
if (esParam.Direction != tgParameterDirection.Input)
{
response.Parameters.Add(esParam);
SqliteParameter p = cmd.Parameters[Delimiters.Param + esParam.Name];
esParam.Value = p.Value;
}
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
namespace RealtimeGraph
{
public class GraphMeasurementCollection : SortableCollectionBase, ICustomTypeDescriptor
{
#region CollectionBase implementation
public GraphMeasurementCollection()
{
//In your collection class constructor add this line.
//set the SortObjectType for sorting.
base.SortObjectType = typeof(GraphMeasurement);
}
public GraphMeasurement this[int index]
{
get
{
if (index < List.Count && index >= 0)
{
return ((GraphMeasurement)List[index]);
}
else return new GraphMeasurement();
}
set
{
List[index] = value;
}
}
public int Add(GraphMeasurement value)
{
return (List.Add(value));
}
public int IndexOf(GraphMeasurement value)
{
return (List.IndexOf(value));
}
public void Insert(int index, GraphMeasurement value)
{
List.Insert(index, value);
}
public void Remove(GraphMeasurement value)
{
List.Remove(value);
}
public bool Contains(GraphMeasurement value)
{
// If value is not of type Int16, this will return false.
return (List.Contains(value));
}
protected override void OnInsert(int index, Object value)
{
// Insert additional code to be run only when inserting values.
}
protected override void OnRemove(int index, Object value)
{
// Insert additional code to be run only when removing values.
}
protected override void OnSet(int index, Object oldValue, Object newValue)
{
// Insert additional code to be run only when setting values.
}
protected override void OnValidate(Object value)
{
}
#endregion
[TypeConverter(typeof(GraphMeasurementCollectionConverter))]
public GraphMeasurementCollection Symbols
{
get { return this; }
}
internal class SymbolConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is GraphMeasurement)
{
// Cast the value to an Employee type
GraphMeasurement pp = (GraphMeasurement)value;
return pp.Symbol + ", " + pp.Value.ToString() + ", " + pp.Timestamp.ToString("dd/MM/yyyy HH:mm:ss");
}
return base.ConvertTo(context, culture, value, destType);
}
}
// This is a special type converter which will be associated with the EmployeeCollection class.
// It converts an EmployeeCollection object to a string representation for use in a property grid.
internal class GraphMeasurementCollectionConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is GraphMeasurementCollection)
{
// Return department and department role separated by comma.
return "Symbols";
}
return base.ConvertTo(context, culture, value, destType);
}
}
#region ICustomTypeDescriptor impl
public String GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
public AttributeCollection GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
public String GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
public TypeConverter GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
public EventDescriptor GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
public PropertyDescriptor GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(this, true);
}
public object GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
public EventDescriptorCollection GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
public object GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
/// <summary>
/// Called to get the properties of this type. Returns properties with certain
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
return GetProperties();
}
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{
// Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list of employees
for (int i = 0; i < this.List.Count; i++)
{
// Create a property descriptor for the employee item and add to the property descriptor collection
GraphMeasurementCollectionPropertyDescriptor pd = new GraphMeasurementCollectionPropertyDescriptor(this, i);
pds.Add(pd);
}
// return the property descriptor collection
return pds;
}
#endregion
public class GraphMeasurementCollectionPropertyDescriptor : PropertyDescriptor
{
private GraphMeasurementCollection collection = null;
private int index = -1;
public GraphMeasurementCollectionPropertyDescriptor(GraphMeasurementCollection coll, int idx)
:
base("#" + idx.ToString(), null)
{
this.collection = coll;
this.index = idx;
}
public override AttributeCollection Attributes
{
get
{
return new AttributeCollection(null);
}
}
public override bool CanResetValue(object component)
{
return true;
}
public override Type ComponentType
{
get
{
return this.collection.GetType();
}
}
public override string DisplayName
{
get
{
GraphMeasurement emp = this.collection[index];
return (string)(emp.Symbol);
}
}
public override string Description
{
get
{
GraphMeasurement emp = this.collection[index];
StringBuilder sb = new StringBuilder();
sb.Append(emp.Symbol);
sb.Append(", ");
sb.Append(emp.Value.ToString());
sb.Append(", ");
sb.Append(emp.Timestamp.ToString("dd/MM/yyyy HH:mm:ss"));
return sb.ToString();
}
}
public override object GetValue(object component)
{
return this.collection[index];
}
public override bool IsReadOnly
{
get { return false; }
}
public override string Name
{
get { return "#" + index.ToString(); }
}
public override Type PropertyType
{
get { return this.collection[index].GetType(); }
}
public override void ResetValue(object component)
{
}
public override bool ShouldSerializeValue(object component)
{
return true;
}
public override void SetValue(object component, object value)
{
// this.collection[index] = value;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Xml;
using System.Collections.Generic;
namespace System.Runtime.Serialization
{
// NOTE: XmlReader methods that are not needed have been left un-implemented
internal class ExtensionDataReader : XmlReader
{
private enum ExtensionDataNodeType
{
None,
Element,
EndElement,
Text,
Xml,
ReferencedElement,
NullElement,
}
private ElementData[] _elements;
private ElementData _element;
private ElementData _nextElement;
private ReadState _readState = ReadState.Initial;
private ExtensionDataNodeType _internalNodeType;
private XmlNodeType _nodeType;
private int _depth;
private string _localName;
private string _ns;
private string _prefix;
private string _value;
private int _attributeCount;
private int _attributeIndex;
#pragma warning disable 0649
private XmlNodeReader _xmlNodeReader;
#pragma warning restore 0649
private Queue<IDataNode> _deserializedDataNodes;
private XmlObjectSerializerReadContext _context;
private static Dictionary<string, string> s_nsToPrefixTable;
private static Dictionary<string, string> s_prefixToNsTable;
static ExtensionDataReader()
{
s_nsToPrefixTable = new Dictionary<string, string>();
s_prefixToNsTable = new Dictionary<string, string>();
AddPrefix(Globals.XsiPrefix, Globals.SchemaInstanceNamespace);
AddPrefix(Globals.SerPrefix, Globals.SerializationNamespace);
AddPrefix(String.Empty, String.Empty);
}
internal ExtensionDataReader(XmlObjectSerializerReadContext context)
{
_attributeIndex = -1;
_context = context;
}
internal void SetDeserializedValue(object obj)
{
IDataNode deserializedDataNode = (_deserializedDataNodes == null || _deserializedDataNodes.Count == 0) ? null : _deserializedDataNodes.Dequeue();
if (deserializedDataNode != null && !(obj is IDataNode))
{
deserializedDataNode.Value = obj;
deserializedDataNode.IsFinalValue = true;
}
}
internal IDataNode GetCurrentNode()
{
IDataNode retVal = _element.dataNode;
Skip();
return retVal;
}
internal void SetDataNode(IDataNode dataNode, string name, string ns)
{
SetNextElement(dataNode, name, ns, null);
_element = _nextElement;
_nextElement = null;
SetElement();
}
internal void Reset()
{
_localName = null;
_ns = null;
_prefix = null;
_value = null;
_attributeCount = 0;
_attributeIndex = -1;
_depth = 0;
_element = null;
_nextElement = null;
_elements = null;
_deserializedDataNodes = null;
}
private bool IsXmlDataNode { get { return (_internalNodeType == ExtensionDataNodeType.Xml); } }
public override XmlNodeType NodeType { get { return IsXmlDataNode ? _xmlNodeReader.NodeType : _nodeType; } }
public override string LocalName { get { return IsXmlDataNode ? _xmlNodeReader.LocalName : _localName; } }
public override string NamespaceURI { get { return IsXmlDataNode ? _xmlNodeReader.NamespaceURI : _ns; } }
public override string Prefix { get { return IsXmlDataNode ? _xmlNodeReader.Prefix : _prefix; } }
public override string Value { get { return IsXmlDataNode ? _xmlNodeReader.Value : _value; } }
public override int Depth { get { return IsXmlDataNode ? _xmlNodeReader.Depth : _depth; } }
public override int AttributeCount { get { return IsXmlDataNode ? _xmlNodeReader.AttributeCount : _attributeCount; } }
public override bool EOF { get { return IsXmlDataNode ? _xmlNodeReader.EOF : (_readState == ReadState.EndOfFile); } }
public override ReadState ReadState { get { return IsXmlDataNode ? _xmlNodeReader.ReadState : _readState; } }
public override bool IsEmptyElement { get { return IsXmlDataNode ? _xmlNodeReader.IsEmptyElement : false; } }
public override bool IsDefault { get { return IsXmlDataNode ? _xmlNodeReader.IsDefault : base.IsDefault; } }
//public override char QuoteChar { get { return IsXmlDataNode ? xmlNodeReader.QuoteChar : base.QuoteChar; } }
public override XmlSpace XmlSpace { get { return IsXmlDataNode ? _xmlNodeReader.XmlSpace : base.XmlSpace; } }
public override string XmlLang { get { return IsXmlDataNode ? _xmlNodeReader.XmlLang : base.XmlLang; } }
public override string this[int i] { get { return IsXmlDataNode ? _xmlNodeReader[i] : GetAttribute(i); } }
public override string this[string name] { get { return IsXmlDataNode ? _xmlNodeReader[name] : GetAttribute(name); } }
public override string this[string name, string namespaceURI] { get { return IsXmlDataNode ? _xmlNodeReader[name, namespaceURI] : GetAttribute(name, namespaceURI); } }
public override bool MoveToFirstAttribute()
{
if (IsXmlDataNode)
return _xmlNodeReader.MoveToFirstAttribute();
if (_attributeCount == 0)
return false;
MoveToAttribute(0);
return true;
}
public override bool MoveToNextAttribute()
{
if (IsXmlDataNode)
return _xmlNodeReader.MoveToNextAttribute();
if (_attributeIndex + 1 >= _attributeCount)
return false;
MoveToAttribute(_attributeIndex + 1);
return true;
}
public override void MoveToAttribute(int index)
{
if (IsXmlDataNode)
_xmlNodeReader.MoveToAttribute(index);
else
{
if (index < 0 || index >= _attributeCount)
throw new XmlException(SR.InvalidXmlDeserializingExtensionData);
_nodeType = XmlNodeType.Attribute;
AttributeData attribute = _element.attributes[index];
_localName = attribute.localName;
_ns = attribute.ns;
_prefix = attribute.prefix;
_value = attribute.value;
_attributeIndex = index;
}
}
public override string GetAttribute(string name, string namespaceURI)
{
if (IsXmlDataNode)
return _xmlNodeReader.GetAttribute(name, namespaceURI);
for (int i = 0; i < _element.attributeCount; i++)
{
AttributeData attribute = _element.attributes[i];
if (attribute.localName == name && attribute.ns == namespaceURI)
return attribute.value;
}
return null;
}
public override bool MoveToAttribute(string name, string namespaceURI)
{
if (IsXmlDataNode)
return _xmlNodeReader.MoveToAttribute(name, _ns);
for (int i = 0; i < _element.attributeCount; i++)
{
AttributeData attribute = _element.attributes[i];
if (attribute.localName == name && attribute.ns == namespaceURI)
{
MoveToAttribute(i);
return true;
}
}
return false;
}
public override bool MoveToElement()
{
if (IsXmlDataNode)
return _xmlNodeReader.MoveToElement();
if (_nodeType != XmlNodeType.Attribute)
return false;
SetElement();
return true;
}
private void SetElement()
{
_nodeType = XmlNodeType.Element;
_localName = _element.localName;
_ns = _element.ns;
_prefix = _element.prefix;
_value = String.Empty;
_attributeCount = _element.attributeCount;
_attributeIndex = -1;
}
public override string LookupNamespace(string prefix)
{
if (IsXmlDataNode)
return _xmlNodeReader.LookupNamespace(prefix);
string ns;
if (!s_prefixToNsTable.TryGetValue(prefix, out ns))
return null;
return ns;
}
public override void Skip()
{
if (IsXmlDataNode)
_xmlNodeReader.Skip();
else
{
if (ReadState != ReadState.Interactive)
return;
MoveToElement();
if (IsElementNode(_internalNodeType))
{
int depth = 1;
while (depth != 0)
{
if (!Read())
throw new XmlException(SR.InvalidXmlDeserializingExtensionData);
if (IsElementNode(_internalNodeType))
depth++;
else if (_internalNodeType == ExtensionDataNodeType.EndElement)
{
ReadEndElement();
depth--;
}
}
}
else
Read();
}
}
private bool IsElementNode(ExtensionDataNodeType nodeType)
{
return (nodeType == ExtensionDataNodeType.Element ||
nodeType == ExtensionDataNodeType.ReferencedElement ||
nodeType == ExtensionDataNodeType.NullElement);
}
protected override void Dispose(bool disposing)
{
if (IsXmlDataNode)
_xmlNodeReader.Dispose();
else
{
Reset();
_readState = ReadState.Closed;
}
base.Dispose(disposing);
}
public override bool Read()
{
if (_nodeType == XmlNodeType.Attribute && MoveToNextAttribute())
return true;
MoveNext(_element.dataNode);
switch (_internalNodeType)
{
case ExtensionDataNodeType.Element:
case ExtensionDataNodeType.ReferencedElement:
case ExtensionDataNodeType.NullElement:
PushElement();
SetElement();
break;
case ExtensionDataNodeType.Text:
_nodeType = XmlNodeType.Text;
_prefix = String.Empty;
_ns = String.Empty;
_localName = String.Empty;
_attributeCount = 0;
_attributeIndex = -1;
break;
case ExtensionDataNodeType.EndElement:
_nodeType = XmlNodeType.EndElement;
_prefix = String.Empty;
_ns = String.Empty;
_localName = String.Empty;
_value = String.Empty;
_attributeCount = 0;
_attributeIndex = -1;
PopElement();
break;
case ExtensionDataNodeType.None:
if (_depth != 0)
throw new XmlException(SR.InvalidXmlDeserializingExtensionData);
_nodeType = XmlNodeType.None;
_prefix = String.Empty;
_ns = String.Empty;
_localName = String.Empty;
_value = String.Empty;
_attributeCount = 0;
_readState = ReadState.EndOfFile;
return false;
case ExtensionDataNodeType.Xml:
// do nothing
break;
default:
Fx.Assert("ExtensionDataReader in invalid state");
throw new SerializationException(SR.InvalidStateInExtensionDataReader);
}
_readState = ReadState.Interactive;
return true;
}
public override string Name
{
get
{
if (IsXmlDataNode)
{
return _xmlNodeReader.Name;
}
Fx.Assert("ExtensionDataReader Name property should only be called for IXmlSerializable");
return string.Empty;
}
}
public override bool HasValue
{
get
{
if (IsXmlDataNode)
{
return _xmlNodeReader.HasValue;
}
Fx.Assert("ExtensionDataReader HasValue property should only be called for IXmlSerializable");
return false;
}
}
public override string BaseURI
{
get
{
if (IsXmlDataNode)
{
return _xmlNodeReader.BaseURI;
}
Fx.Assert("ExtensionDataReader BaseURI property should only be called for IXmlSerializable");
return string.Empty;
}
}
public override XmlNameTable NameTable
{
get
{
if (IsXmlDataNode)
{
return _xmlNodeReader.NameTable;
}
Fx.Assert("ExtensionDataReader NameTable property should only be called for IXmlSerializable");
return null;
}
}
public override string GetAttribute(string name)
{
if (IsXmlDataNode)
{
return _xmlNodeReader.GetAttribute(name);
}
Fx.Assert("ExtensionDataReader GetAttribute method should only be called for IXmlSerializable");
return null;
}
public override string GetAttribute(int i)
{
if (IsXmlDataNode)
{
return _xmlNodeReader.GetAttribute(i);
}
Fx.Assert("ExtensionDataReader GetAttribute method should only be called for IXmlSerializable");
return null;
}
public override bool MoveToAttribute(string name)
{
if (IsXmlDataNode)
{
return _xmlNodeReader.MoveToAttribute(name);
}
Fx.Assert("ExtensionDataReader MoveToAttribute method should only be called for IXmlSerializable");
return false;
}
public override void ResolveEntity()
{
if (IsXmlDataNode)
{
_xmlNodeReader.ResolveEntity();
}
else
{
Fx.Assert("ExtensionDataReader ResolveEntity method should only be called for IXmlSerializable");
}
}
public override bool ReadAttributeValue()
{
if (IsXmlDataNode)
{
return _xmlNodeReader.ReadAttributeValue();
}
Fx.Assert("ExtensionDataReader ReadAttributeValue method should only be called for IXmlSerializable");
return false;
}
private void MoveNext(IDataNode dataNode)
{
throw NotImplemented.ByDesign;
}
private void SetNextElement(IDataNode node, string name, string ns, string prefix)
{
throw NotImplemented.ByDesign;
}
private void PushElement()
{
GrowElementsIfNeeded();
_elements[_depth++] = _element;
if (_nextElement == null)
_element = GetNextElement();
else
{
_element = _nextElement;
_nextElement = null;
}
}
private void PopElement()
{
_prefix = _element.prefix;
_localName = _element.localName;
_ns = _element.ns;
if (_depth == 0)
return;
_depth--;
if (_elements != null)
{
_element = _elements[_depth];
}
}
private void GrowElementsIfNeeded()
{
if (_elements == null)
_elements = new ElementData[8];
else if (_elements.Length == _depth)
{
ElementData[] newElements = new ElementData[_elements.Length * 2];
Array.Copy(_elements, 0, newElements, 0, _elements.Length);
_elements = newElements;
}
}
private ElementData GetNextElement()
{
int nextDepth = _depth + 1;
return (_elements == null || _elements.Length <= nextDepth || _elements[nextDepth] == null)
? new ElementData() : _elements[nextDepth];
}
internal static string GetPrefix(string ns)
{
string prefix;
ns = ns ?? String.Empty;
if (!s_nsToPrefixTable.TryGetValue(ns, out prefix))
{
lock (s_nsToPrefixTable)
{
if (!s_nsToPrefixTable.TryGetValue(ns, out prefix))
{
prefix = (ns == null || ns.Length == 0) ? String.Empty : "p" + s_nsToPrefixTable.Count;
AddPrefix(prefix, ns);
}
}
}
return prefix;
}
private static void AddPrefix(string prefix, string ns)
{
s_nsToPrefixTable.Add(ns, prefix);
s_prefixToNsTable.Add(prefix, ns);
}
}
#if USE_REFEMIT || NET_NATIVE
public class AttributeData
#else
internal class AttributeData
#endif
{
public string prefix;
public string ns;
public string localName;
public string value;
}
#if USE_REFEMIT || NET_NATIVE
public class ElementData
#else
internal class ElementData
#endif
{
public string localName;
public string ns;
public string prefix;
public int attributeCount;
public AttributeData[] attributes;
public IDataNode dataNode;
public int childElementIndex;
public void AddAttribute(string prefix, string ns, string name, string value)
{
GrowAttributesIfNeeded();
AttributeData attribute = attributes[attributeCount];
if (attribute == null)
attributes[attributeCount] = attribute = new AttributeData();
attribute.prefix = prefix;
attribute.ns = ns;
attribute.localName = name;
attribute.value = value;
attributeCount++;
}
private void GrowAttributesIfNeeded()
{
if (attributes == null)
attributes = new AttributeData[4];
else if (attributes.Length == attributeCount)
{
AttributeData[] newAttributes = new AttributeData[attributes.Length * 2];
Array.Copy(attributes, 0, newAttributes, 0, attributes.Length);
attributes = newAttributes;
}
}
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using Telerik.JustMock.Core.Castle.DynamicProxy.Internal;
internal abstract class AbstractTypeEmitter
{
private const MethodAttributes defaultAttributes =
MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Public;
private readonly ConstructorCollection constructors;
private readonly EventCollection events;
private readonly IDictionary<string, FieldReference> fields =
new Dictionary<string, FieldReference>(StringComparer.OrdinalIgnoreCase);
private readonly MethodCollection methods;
private readonly Dictionary<String, GenericTypeParameterBuilder> name2GenericType;
private readonly NestedClassCollection nested;
private readonly PropertiesCollection properties;
private readonly TypeBuilder typebuilder;
private GenericTypeParameterBuilder[] genericTypeParams;
protected AbstractTypeEmitter(TypeBuilder typeBuilder)
{
typebuilder = typeBuilder;
nested = new NestedClassCollection();
methods = new MethodCollection();
constructors = new ConstructorCollection();
properties = new PropertiesCollection();
events = new EventCollection();
name2GenericType = new Dictionary<String, GenericTypeParameterBuilder>();
}
public Type BaseType
{
get
{
if (TypeBuilder.IsInterface)
{
throw new InvalidOperationException("This emitter represents an interface; interfaces have no base types.");
}
return TypeBuilder.BaseType;
}
}
public TypeConstructorEmitter ClassConstructor { get; private set; }
public ConstructorCollection Constructors
{
get { return constructors; }
}
public GenericTypeParameterBuilder[] GenericTypeParams
{
get { return genericTypeParams; }
}
public NestedClassCollection Nested
{
get { return nested; }
}
public TypeBuilder TypeBuilder
{
get { return typebuilder; }
}
public void AddCustomAttributes(ProxyGenerationOptions proxyGenerationOptions)
{
foreach (var attribute in proxyGenerationOptions.AdditionalAttributes)
{
typebuilder.SetCustomAttribute(attribute.Builder);
}
}
public virtual Type BuildType()
{
EnsureBuildersAreInAValidState();
var type = CreateType(typebuilder);
foreach (var builder in nested)
{
builder.BuildType();
}
return type;
}
public void CopyGenericParametersFromMethod(MethodInfo methodToCopyGenericsFrom)
{
// big sanity check
if (genericTypeParams != null)
{
throw new ProxyGenerationException("CopyGenericParametersFromMethod: cannot invoke me twice");
}
SetGenericTypeParameters(GenericUtil.CopyGenericArguments(methodToCopyGenericsFrom, typebuilder, name2GenericType));
}
public ConstructorEmitter CreateConstructor(params ArgumentReference[] arguments)
{
if (TypeBuilder.IsInterface)
{
throw new InvalidOperationException("Interfaces cannot have constructors.");
}
var member = new ConstructorEmitter(this, arguments);
constructors.Add(member);
return member;
}
public void CreateDefaultConstructor()
{
if (TypeBuilder.IsInterface)
{
throw new InvalidOperationException("Interfaces cannot have constructors.");
}
constructors.Add(new ConstructorEmitter(this));
}
public EventEmitter CreateEvent(string name, EventAttributes atts, Type type)
{
var eventEmitter = new EventEmitter(this, name, atts, type);
events.Add(eventEmitter);
return eventEmitter;
}
public FieldReference CreateField(string name, Type fieldType)
{
return CreateField(name, fieldType, true);
}
public FieldReference CreateField(string name, Type fieldType, bool serializable)
{
var atts = FieldAttributes.Private;
if (!serializable)
{
atts |= FieldAttributes.NotSerialized;
}
return CreateField(name, fieldType, atts);
}
public FieldReference CreateField(string name, Type fieldType, FieldAttributes atts)
{
var fieldBuilder = typebuilder.DefineField(name, fieldType, atts);
var reference = new FieldReference(fieldBuilder);
fields[name] = reference;
return reference;
}
public MethodEmitter CreateMethod(string name, MethodAttributes attrs, Type returnType, params Type[] argumentTypes)
{
var member = new MethodEmitter(this, name, attrs, returnType, argumentTypes ?? Type.EmptyTypes);
methods.Add(member);
return member;
}
public MethodEmitter CreateMethod(string name, Type returnType, params Type[] parameterTypes)
{
return CreateMethod(name, defaultAttributes, returnType, parameterTypes);
}
public MethodEmitter CreateMethod(string name, MethodInfo methodToUseAsATemplate)
{
return CreateMethod(name, defaultAttributes, methodToUseAsATemplate);
}
public MethodEmitter CreateMethod(string name, MethodAttributes attributes, MethodInfo methodToUseAsATemplate)
{
var method = new MethodEmitter(this, name, attributes, methodToUseAsATemplate);
methods.Add(method);
return method;
}
public PropertyEmitter CreateProperty(string name, PropertyAttributes attributes, Type propertyType, Type[] arguments)
{
var propEmitter = new PropertyEmitter(this, name, attributes, propertyType, arguments);
properties.Add(propEmitter);
return propEmitter;
}
public FieldReference CreateStaticField(string name, Type fieldType)
{
return CreateStaticField(name, fieldType, FieldAttributes.Private);
}
public FieldReference CreateStaticField(string name, Type fieldType, FieldAttributes atts)
{
atts |= FieldAttributes.Static;
return CreateField(name, fieldType, atts);
}
public ConstructorEmitter CreateTypeConstructor()
{
var member = new TypeConstructorEmitter(this);
constructors.Add(member);
ClassConstructor = member;
return member;
}
public void DefineCustomAttribute(CustomAttributeBuilder attribute)
{
typebuilder.SetCustomAttribute(attribute);
}
public void DefineCustomAttribute<TAttribute>(object[] constructorArguments) where TAttribute : Attribute
{
var customAttributeInfo = AttributeUtil.CreateInfo(typeof(TAttribute), constructorArguments);
typebuilder.SetCustomAttribute(customAttributeInfo.Builder);
}
public void DefineCustomAttribute<TAttribute>() where TAttribute : Attribute, new()
{
var customAttributeInfo = AttributeUtil.CreateInfo<TAttribute>();
typebuilder.SetCustomAttribute(customAttributeInfo.Builder);
}
public void DefineCustomAttributeFor<TAttribute>(FieldReference field) where TAttribute : Attribute, new()
{
var customAttributeInfo = AttributeUtil.CreateInfo<TAttribute>();
var fieldbuilder = field.Fieldbuilder;
if (fieldbuilder == null)
{
throw new ArgumentException(
"Invalid field reference.This reference does not point to field on type being generated", "field");
}
fieldbuilder.SetCustomAttribute(customAttributeInfo.Builder);
}
public IEnumerable<FieldReference> GetAllFields()
{
return fields.Values;
}
public FieldReference GetField(string name)
{
if (string.IsNullOrEmpty(name))
{
return null;
}
FieldReference value;
fields.TryGetValue(name, out value);
return value;
}
public Type GetGenericArgument(String genericArgumentName)
{
if (name2GenericType.ContainsKey(genericArgumentName))
return name2GenericType[genericArgumentName].AsType();
return null;
}
public Type[] GetGenericArgumentsFor(Type genericType)
{
var types = new List<Type>();
foreach (var genType in genericType.GetGenericArguments())
{
if (genType.GetTypeInfo().IsGenericParameter)
{
types.Add(name2GenericType[genType.Name].AsType());
}
else
{
types.Add(genType);
}
}
return types.ToArray();
}
public Type[] GetGenericArgumentsFor(MethodInfo genericMethod)
{
var types = new List<Type>();
foreach (var genType in genericMethod.GetGenericArguments())
{
types.Add(name2GenericType[genType.Name].AsType());
}
return types.ToArray();
}
public void SetGenericTypeParameters(GenericTypeParameterBuilder[] genericTypeParameterBuilders)
{
genericTypeParams = genericTypeParameterBuilders;
}
protected Type CreateType(TypeBuilder type)
{
try
{
#if FEATURE_LEGACY_REFLECTION_API
return type.CreateType();
#else
return type.CreateTypeInfo().AsType();
#endif
}
catch (BadImageFormatException ex)
{
if (Debugger.IsAttached == false)
{
throw;
}
if (ex.Message.Contains(@"HRESULT: 0x8007000B") == false)
{
throw;
}
if (type.IsGenericTypeDefinition == false)
{
throw;
}
var message =
"This is a DynamicProxy2 error: It looks like you encountered a bug in Visual Studio debugger, " +
"which causes this exception when proxying types with generic methods having constraints on their generic arguments." +
"This code will work just fine without the debugger attached. " +
"If you wish to use debugger you may have to switch to Visual Studio 2010 where this bug was fixed.";
var exception = new ProxyGenerationException(message);
exception.Data.Add("ProxyType", type.ToString());
throw exception;
}
}
protected virtual void EnsureBuildersAreInAValidState()
{
if (!typebuilder.IsInterface && constructors.Count == 0)
{
CreateDefaultConstructor();
}
foreach (IMemberEmitter builder in properties)
{
builder.EnsureValidCodeBlock();
builder.Generate();
}
foreach (IMemberEmitter builder in events)
{
builder.EnsureValidCodeBlock();
builder.Generate();
}
foreach (IMemberEmitter builder in constructors)
{
builder.EnsureValidCodeBlock();
builder.Generate();
}
foreach (IMemberEmitter builder in methods)
{
builder.EnsureValidCodeBlock();
builder.Generate();
}
}
}
}
| |
// 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: A collection of methods for manipulating Files.
**
** April 09,2000 (some design refactorization)
**
===========================================================*/
using Win32Native = Microsoft.Win32.Win32Native;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.IO
{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
internal static class File
{
private const int ERROR_INVALID_PARAMETER = 87;
internal const int GENERIC_READ = unchecked((int)0x80000000);
private const int GetFileExInfoStandard = 0;
// Tests if a file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false. Note that if path describes a directory,
// Exists will return true.
public static bool Exists(String path)
{
return InternalExistsHelper(path);
}
private static bool InternalExistsHelper(String path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
path = Path.GetFullPath(path);
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPath should never return null
Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]))
{
return false;
}
return InternalExists(path);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
internal static bool InternalExists(String path)
{
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(path, ref data, false, true);
return (dataInitialised == 0) && (data.fileAttributes != -1)
&& ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0);
}
public static byte[] ReadAllBytes(String path)
{
byte[] bytes;
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
FileStream.DefaultBufferSize, FileOptions.None))
{
// Do a blocking read
int index = 0;
long fileLength = fs.Length;
if (fileLength > Int32.MaxValue)
throw new IOException(SR.IO_FileTooLong2GB);
int count = (int)fileLength;
bytes = new byte[count];
while (count > 0)
{
int n = fs.Read(bytes, index, count);
if (n == 0)
__Error.EndOfFile();
index += n;
count -= n;
}
}
return bytes;
}
#if PLATFORM_UNIX
public static String[] ReadAllLines(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath);
return InternalReadAllLines(path, Encoding.UTF8);
}
private static String[] InternalReadAllLines(String path, Encoding encoding)
{
Debug.Assert(path != null);
Debug.Assert(encoding != null);
Debug.Assert(path.Length != 0);
String line;
List<String> lines = new List<String>();
using (StreamReader sr = new StreamReader(path, encoding))
while ((line = sr.ReadLine()) != null)
lines.Add(line);
return lines.ToArray();
}
#endif // PLATFORM_UNIX
// Returns 0 on success, otherwise a Win32 error code. Note that
// classes should use -1 as the uninitialized state for dataInitialized.
internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
{
int dataInitialised = 0;
if (tryagain) // someone has a handle to the file open, or other error
{
Win32Native.WIN32_FIND_DATA findData;
findData = new Win32Native.WIN32_FIND_DATA();
// Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error
String tempPath = path.TrimEnd(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
#if !PLATFORM_UNIX
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetThreadErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
uint oldMode;
bool errorModeSuccess = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode);
try
{
#endif
bool error = false;
SafeFindHandle handle = Win32Native.FindFirstFile(tempPath, findData);
try
{
if (handle.IsInvalid)
{
error = true;
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready
{
if (!returnErrorOnNotFound)
{
// Return default value for backward compatibility
dataInitialised = 0;
data.fileAttributes = -1;
}
}
return dataInitialised;
}
}
finally
{
// Close the Win32 handle
try
{
handle.Close();
}
catch
{
// if we're already returning an error, don't throw another one.
if (!error)
{
Debug.Fail("File::FillAttributeInfo - FindClose failed!");
throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
}
#if !PLATFORM_UNIX
}
finally
{
if (errorModeSuccess)
Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
}
#endif
// Copy the information to data
data.PopulateFrom(findData);
}
else
{
bool success = false;
#if !PLATFORM_UNIX
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetThreadErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
uint oldMode;
bool errorModeSuccess = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode);
try
{
#endif
success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data);
#if !PLATFORM_UNIX
}
finally
{
if (errorModeSuccess)
Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
}
#endif
if (!success)
{
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised != Win32Native.ERROR_FILE_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_PATH_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_NOT_READY) // floppy device not ready
{
// In case someone latched onto the file. Take the perf hit only for failure
return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound);
}
else
{
if (!returnErrorOnNotFound)
{
// Return default value for backward compbatibility
dataInitialised = 0;
data.fileAttributes = -1;
}
}
}
}
return dataInitialised;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2016 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if PARALLEL
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Globalization;
using System.Runtime.Serialization;
using System.Threading;
#if NET_2_0 || NET_3_5
using ManualResetEventSlim = System.Threading.ManualResetEvent;
#endif
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Execution
{
#region Individual Event Classes
/// <summary>
/// NUnit.Core.Event is the abstract base for all stored events.
/// An Event is the stored representation of a call to the
/// ITestListener interface and is used to record such calls
/// or to queue them for forwarding on another thread or at
/// a later time.
/// </summary>
public abstract class Event
{
/// <summary>
/// The Send method is implemented by derived classes to send the event to the specified listener.
/// </summary>
/// <param name="listener">The listener.</param>
public abstract void Send(ITestListener listener);
}
/// <summary>
/// TestStartedEvent holds information needed to call the TestStarted method.
/// </summary>
public class TestStartedEvent : Event
{
private readonly ITest _test;
/// <summary>
/// Initializes a new instance of the <see cref="TestStartedEvent"/> class.
/// </summary>
/// <param name="test">The test.</param>
public TestStartedEvent(ITest test)
{
_test = test;
}
/// <summary>
/// Calls TestStarted on the specified listener.
/// </summary>
/// <param name="listener">The listener.</param>
public override void Send(ITestListener listener)
{
listener.TestStarted(_test);
}
}
/// <summary>
/// TestFinishedEvent holds information needed to call the TestFinished method.
/// </summary>
public class TestFinishedEvent : Event
{
private readonly ITestResult _result;
/// <summary>
/// Initializes a new instance of the <see cref="TestFinishedEvent"/> class.
/// </summary>
/// <param name="result">The result.</param>
public TestFinishedEvent(ITestResult result)
{
_result = result;
}
/// <summary>
/// Calls TestFinished on the specified listener.
/// </summary>
/// <param name="listener">The listener.</param>
public override void Send(ITestListener listener)
{
listener.TestFinished(_result);
}
}
/// <summary>
/// TestOutputEvent holds information needed to call the TestOutput method.
/// </summary>
public class TestOutputEvent : Event
{
private readonly TestOutput _output;
/// <summary>
/// Initializes a new instance of the <see cref="TestOutputEvent"/> class.
/// </summary>
/// <param name="output">The output object.</param>
public TestOutputEvent(TestOutput output)
{
_output = output;
}
/// <summary>
/// Calls TestOutput on the specified listener.
/// </summary>
/// <param name="listener">The listener.</param>
public override void Send(ITestListener listener)
{
listener.TestOutput(_output);
}
}
#endregion
/// <summary>
/// Implements a queue of work items each of which
/// is queued as a WaitCallback.
/// </summary>
public class EventQueue
{
private const int spinCount = 5;
// static readonly Logger log = InternalTrace.GetLogger("EventQueue");
private readonly ConcurrentQueue<Event> _queue = new ConcurrentQueue<Event>();
/* This event is used solely for the purpose of having an optimized sleep cycle when
* we have to wait on an external event (Add or Remove for instance)
*/
private readonly ManualResetEventSlim _mreAdd = new ManualResetEventSlim(false);
/* The whole idea is to use these two values in a transactional
* way to track and manage the actual data inside the underlying lock-free collection
* instead of directly working with it or using external locking.
*
* They are manipulated with CAS and are guaranteed to increase over time and use
* of the instance thus preventing ABA problems.
*/
private int _addId = int.MinValue;
private int _removeId = int.MinValue;
private int _stopped;
/// <summary>
/// Gets the count of items in the queue.
/// </summary>
public int Count
{
get
{
return _queue.Count;
}
}
/// <summary>
/// Enqueues the specified event
/// </summary>
/// <param name="e">The event to enqueue.</param>
public void Enqueue(Event e)
{
do
{
int cachedAddId = _addId;
// Validate that we have are the current enqueuer
if (Interlocked.CompareExchange(ref _addId, cachedAddId + 1, cachedAddId) != cachedAddId)
continue;
// Add to the collection
_queue.Enqueue(e);
// Wake up threads that may have been sleeping
_mreAdd.Set();
break;
} while (true);
// Setting this to anything other than 0 causes NUnit to be sensitive
// to the windows timer resolution - see issue #2217
Thread.Sleep(0); // give EventPump thread a chance to process the event
}
/// <summary>
/// Removes the first element from the queue and returns it (or <c>null</c>).
/// </summary>
/// <param name="blockWhenEmpty">
/// If <c>true</c> and the queue is empty, the calling thread is blocked until
/// either an element is enqueued, or <see cref="Stop"/> is called.
/// </param>
/// <returns>
/// <list type="bullet">
/// <item>
/// <term>If the queue not empty</term>
/// <description>the first element.</description>
/// </item>
/// <item>
/// <term>otherwise, if <paramref name="blockWhenEmpty"/>==<c>false</c>
/// or <see cref="Stop"/> has been called</term>
/// <description><c>null</c>.</description>
/// </item>
/// </list>
/// </returns>
public Event Dequeue(bool blockWhenEmpty)
{
SpinWait sw = new SpinWait();
do
{
int cachedRemoveId = _removeId;
int cachedAddId = _addId;
// Empty case
if (cachedRemoveId == cachedAddId)
{
if (!blockWhenEmpty || _stopped != 0)
return null;
// Spin a few times to see if something changes
if (sw.Count <= spinCount)
{
sw.SpinOnce();
}
else
{
// Reset to wait for an enqueue
_mreAdd.Reset();
// Recheck for an enqueue to avoid a Wait
if (cachedRemoveId != _removeId || cachedAddId != _addId)
{
// Queue is not empty, set the event
_mreAdd.Set();
continue;
}
// Wait for something to happen
_mreAdd.Wait(500);
}
continue;
}
// Validate that we are the current dequeuer
if (Interlocked.CompareExchange(ref _removeId, cachedRemoveId + 1, cachedRemoveId) != cachedRemoveId)
continue;
// Dequeue our work item
Event e;
while (!_queue.TryDequeue (out e))
{
if (!blockWhenEmpty || _stopped != 0)
return null;
}
return e;
} while (true);
}
/// <summary>
/// Stop processing of the queue
/// </summary>
public void Stop()
{
if (Interlocked.CompareExchange(ref _stopped, 1, 0) == 0)
_mreAdd.Set();
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Net.Tests;
using System.Runtime.ExceptionServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Security.Tests
{
public class ServerAsyncAuthenticateTest : IDisposable
{
private readonly ITestOutputHelper _log;
private readonly ITestOutputHelper _logVerbose;
private readonly X509Certificate2 _serverCertificate;
public ServerAsyncAuthenticateTest()
{
_log = TestLogging.GetInstance();
_logVerbose = VerboseTestLogging.GetInstance();
_serverCertificate = CertificateConfiguration.GetServerCertificate();
}
public void Dispose()
{
_serverCertificate.Dispose();
}
[Theory]
[ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))]
public async Task ServerAsyncAuthenticate_EachSupportedProtocol_Success(SslProtocols protocol)
{
await ServerAsyncSslHelper(protocol, protocol);
}
[Theory]
[ClassData(typeof(SslProtocolSupport.UnsupportedSslProtocolsTestData))]
public async Task ServerAsyncAuthenticate_EachServerUnsupportedProtocol_Fail(SslProtocols protocol)
{
await Assert.ThrowsAsync<NotSupportedException>(() =>
{
return ServerAsyncSslHelper(
SslProtocolSupport.SupportedSslProtocols,
protocol,
expectedToFail: true);
});
}
[Theory]
[MemberData(nameof(ProtocolMismatchData))]
public async Task ServerAsyncAuthenticate_MismatchProtocols_Fails(
SslProtocols serverProtocol,
SslProtocols clientProtocol,
Type expectedException)
{
await Assert.ThrowsAsync(
expectedException,
() =>
{
return ServerAsyncSslHelper(
serverProtocol,
clientProtocol,
expectedToFail: true);
});
}
[Fact]
public async Task ServerAsyncAuthenticate_UnsuportedAllServer_Fail()
{
await Assert.ThrowsAsync<NotSupportedException>(() =>
{
return ServerAsyncSslHelper(
SslProtocolSupport.SupportedSslProtocols,
SslProtocolSupport.UnsupportedSslProtocols,
expectedToFail: true);
});
}
[Theory]
[ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))]
public async Task ServerAsyncAuthenticate_AllClientVsIndividualServerSupportedProtocols_Success(
SslProtocols serverProtocol)
{
await ServerAsyncSslHelper(SslProtocolSupport.SupportedSslProtocols, serverProtocol);
}
private static IEnumerable<object[]> ProtocolMismatchData()
{
yield return new object[] { SslProtocols.Tls, SslProtocols.Tls11, typeof(AuthenticationException) };
yield return new object[] { SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException) };
yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls, typeof(TimeoutException) };
yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls12, typeof(AuthenticationException) };
yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls, typeof(TimeoutException) };
yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls11, typeof(TimeoutException) };
}
#region Helpers
private async Task ServerAsyncSslHelper(
SslProtocols clientSslProtocols,
SslProtocols serverSslProtocols,
bool expectedToFail = false)
{
_log.WriteLine(
"Server: " + serverSslProtocols + "; Client: " + clientSslProtocols +
" expectedToFail: " + expectedToFail);
int timeOut = expectedToFail ? TestConfiguration.FailingTestTimeoutMiliseconds
: TestConfiguration.PassingTestTimeoutMilliseconds;
IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0);
var server = new TcpListener(endPoint);
server.Start();
using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6))
{
IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint;
Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port);
Task<TcpClient> serverAccept = server.AcceptTcpClientAsync();
// We expect that the network-level connect will always complete.
await Task.WhenAll(new Task[] { clientConnect, serverAccept }).TimeoutAfter(
TestConfiguration.PassingTestTimeoutMilliseconds);
using (TcpClient serverConnection = await serverAccept)
using (SslStream sslClientStream = new SslStream(clientConnection.GetStream()))
using (SslStream sslServerStream = new SslStream(
serverConnection.GetStream(),
false,
AllowAnyServerCertificate))
{
string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.AuthenticateAsClientAsync start.");
Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync(
serverName,
null,
clientSslProtocols,
false);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.AuthenticateAsServerAsync start.");
Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync(
_serverCertificate,
true,
serverSslProtocols,
false);
try
{
await clientAuthentication.TimeoutAfter(timeOut);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.clientAuthentication complete.");
}
catch (Exception ex)
{
// Ignore client-side errors: we're only interested in server-side behavior.
_log.WriteLine("Client exception: " + ex);
}
await serverAuthentication.TimeoutAfter(timeOut);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.serverAuthentication complete.");
_log.WriteLine(
"Server({0}) authenticated with encryption cipher: {1} {2}-bit strength",
serverEndPoint,
sslServerStream.CipherAlgorithm,
sslServerStream.CipherStrength);
Assert.True(
sslServerStream.CipherAlgorithm != CipherAlgorithmType.Null,
"Cipher algorithm should not be NULL");
Assert.True(sslServerStream.CipherStrength > 0, "Cipher strength should be greater than 0");
}
}
}
// The following method is invoked by the RemoteCertificateValidationDelegate.
private bool AllowAnyServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
Assert.True(
(sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == SslPolicyErrors.RemoteCertificateNotAvailable,
"Client didn't supply a cert, the server required one, yet sslPolicyErrors is " + sslPolicyErrors);
return true; // allow everything
}
#endregion Helpers
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Threading;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.Host
{
/// <summary>
/// Allows programmatically hosting an Orleans silo in the curent app domain.
/// </summary>
public class SiloHost : MarshalByRefObject, IDisposable
{
/// <summary> Name of this silo. </summary>
public string Name { get; set; }
/// <summary> Type of this silo - either <c>Primary</c> or <c>Secondary</c>. </summary>
public Silo.SiloType Type { get; set; }
/// <summary>
/// Configuration file used for this silo.
/// Changing this after the silo has started (when <c>ConfigLoaded == true</c>) will have no effect.
/// </summary>
public string ConfigFileName { get; set; }
/// <summary>
/// Directory to use for the trace log file written by this silo.
/// </summary>
/// <remarks>
/// <para>
/// The values of <c>null</c> or <c>"None"</c> mean no log file will be written by Orleans Logger manager.
/// </para>
/// <para>
/// When deciding The values of <c>null</c> or <c>"None"</c> mean no log file will be written by Orleans Logger manager.
/// </para>
/// </remarks>
public string TraceFilePath { get; set; }
/// <summary> Configuration data for the Orleans system. </summary>
public ClusterConfiguration Config { get; set; }
/// <summary> Configuration data for this silo. </summary>
public NodeConfiguration NodeConfig { get; private set; }
/// <summary>
/// Silo Debug flag.
/// If set to <c>true</c> then additional diagnostic info will be written during silo startup.
/// </summary>
public bool Debug { get; set; }
/// <summary>
/// Whether the silo config has been loaded and initializing it's runtime config.
/// </summary>
/// <remarks>
/// Changes to silo config properties will be ignored after <c>ConfigLoaded == true</c>.
/// </remarks>
public bool ConfigLoaded { get; private set; }
/// <summary> Deployment Id (if any) for the cluster this silo is running in. </summary>
public string DeploymentId { get; set; }
/// <summary>
/// Verbose flag.
/// If set to <c>true</c> then additional status and diagnostics info will be written during silo startup.
/// </summary>
public int Verbose { get; set; }
/// <summary> Whether this silo started successfully and is currently running. </summary>
public bool IsStarted { get; private set; }
private Logger logger;
private Silo orleans;
private EventWaitHandle startupEvent;
private EventWaitHandle shutdownEvent;
private bool disposed;
/// <summary>
/// Constructor
/// </summary>
/// <param name="siloName">Name of this silo.</param>
public SiloHost(string siloName)
{
Name = siloName;
Type = Silo.SiloType.Secondary; // Default
IsStarted = false;
}
/// <summary> Constructor </summary>
/// <param name="siloName">Name of this silo.</param>
/// <param name="config">Silo config that will be used to initialize this silo.</param>
public SiloHost(string siloName, ClusterConfiguration config) : this(siloName)
{
SetSiloConfig(config);
}
/// <summary> Constructor </summary>
/// <param name="siloName">Name of this silo.</param>
/// <param name="configFile">Silo config file that will be used to initialize this silo.</param>
public SiloHost(string siloName, FileInfo configFile)
: this(siloName)
{
ConfigFileName = configFile.FullName;
var config = new ClusterConfiguration();
config.LoadFromFile(ConfigFileName);
SetSiloConfig(config);
}
/// <summary>
/// Initialize this silo.
/// </summary>
public void InitializeOrleansSilo()
{
#if DEBUG
AssemblyLoaderUtils.EnableAssemblyLoadTracing();
#endif
try
{
if (!ConfigLoaded) LoadOrleansConfig();
orleans = new Silo(Name, Type, Config);
logger.Info(ErrorCode.Runtime_Error_100288, "Successfully initialized Orleans silo '{0}' as a {1} node.", orleans.Name, orleans.Type);
}
catch (Exception exc)
{
ReportStartupError(exc);
orleans = null;
}
}
/// <summary>
/// Uninitialize this silo.
/// </summary>
public void UnInitializeOrleansSilo()
{
Utils.SafeExecute(UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler);
Utils.SafeExecute(LogManager.UnInitialize);
}
/// <summary>
/// Start this silo.
/// </summary>
/// <returns></returns>
public bool StartOrleansSilo(bool catchExceptions = true)
{
try
{
if (string.IsNullOrEmpty(Thread.CurrentThread.Name))
Thread.CurrentThread.Name = this.GetType().Name;
if (orleans != null)
{
var shutdownEventName = Config.Defaults.SiloShutdownEventName ?? Name + "-Shutdown";
logger.Info(ErrorCode.SiloShutdownEventName, "Silo shutdown event name: {0}", shutdownEventName);
bool createdNew;
shutdownEvent = new EventWaitHandle(false, EventResetMode.ManualReset, shutdownEventName, out createdNew);
if (!createdNew)
{
logger.Info(ErrorCode.SiloShutdownEventOpened, "Opened existing shutdown event. Setting the event {0}", shutdownEventName);
}
else
{
logger.Info(ErrorCode.SiloShutdownEventCreated, "Created and set shutdown event {0}", shutdownEventName);
}
// Start silo
orleans.Start();
// Wait for the shutdown event, and trigger a graceful shutdown if we receive it.
var shutdownThread = new Thread(o =>
{
shutdownEvent.WaitOne();
logger.Info(ErrorCode.SiloShutdownEventReceived, "Received a shutdown event. Starting graceful shutdown.");
orleans.Shutdown();
});
shutdownThread.IsBackground = true;
shutdownThread.Start();
var startupEventName = Name;
logger.Info(ErrorCode.SiloStartupEventName, "Silo startup event name: {0}", startupEventName);
startupEvent = new EventWaitHandle(true, EventResetMode.ManualReset, startupEventName, out createdNew);
if (!createdNew)
{
logger.Info(ErrorCode.SiloStartupEventOpened, "Opened existing startup event. Setting the event {0}", startupEventName);
startupEvent.Set();
}
else
{
logger.Info(ErrorCode.SiloStartupEventCreated, "Created and set startup event {0}", startupEventName);
}
logger.Info(ErrorCode.SiloStarted, "Silo {0} started successfully", Name);
IsStarted = true;
}
else
{
throw new InvalidOperationException("Cannot start silo " + this.Name + " due to prior initialization error");
}
}
catch (Exception exc)
{
if (catchExceptions)
{
ReportStartupError(exc);
orleans = null;
IsStarted = false;
return false;
}
else
throw;
}
return true;
}
/// <summary>
/// Stop this silo.
/// </summary>
public void StopOrleansSilo()
{
IsStarted = false;
if (orleans != null) orleans.Stop();
}
/// <summary>
/// Gracefully shutdown this silo.
/// </summary>
public void ShutdownOrleansSilo()
{
IsStarted = false;
if (orleans != null) orleans.Shutdown();
}
/// <summary>
/// Wait for this silo to shutdown.
/// </summary>
/// <remarks>
/// Note: This method call will block execution of current thread,
/// and will not return control back to the caller until the silo is shutdown.
/// </remarks>
public void WaitForOrleansSiloShutdown()
{
WaitForOrleansSiloShutdownImpl();
}
/// <summary>
/// Wait for this silo to shutdown or to be stopped with provided cancellation token.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <remarks>
/// Note: This method call will block execution of current thread,
/// and will not return control back to the caller until the silo is shutdown or
/// an external request for cancellation has been issued.
/// </remarks>
public void WaitForOrleansSiloShutdown(CancellationToken cancellationToken)
{
WaitForOrleansSiloShutdownImpl(cancellationToken);
}
/// <summary>
/// Set the DeploymentId for this silo,
/// as well as the connection string to use the silo system data,
/// such as the cluster membership table..
/// </summary>
/// <param name="deploymentId">DeploymentId this silo is part of.</param>
/// <param name="connectionString">Azure connection string to use the silo system data.</param>
public void SetDeploymentId(string deploymentId, string connectionString)
{
logger.Info(ErrorCode.SiloSetDeploymentId, "Setting Deployment Id to {0} and data connection string to {1}",
deploymentId, ConfigUtilities.RedactConnectionStringInfo(connectionString));
Config.Globals.DeploymentId = deploymentId;
Config.Globals.DataConnectionString = connectionString;
}
/// <summary>
/// Set the main endpoint address for this silo,
/// plus the silo generation value to be used to distinguish this silo instance
/// from any previous silo instances previously running on this endpoint.
/// </summary>
/// <param name="endpoint">IP address and port of the main inter-silo socket connection.</param>
/// <param name="generation">Generation number for this silo.</param>
public void SetSiloEndpoint(IPEndPoint endpoint, int generation)
{
logger.Info(ErrorCode.SiloSetSiloEndpoint, "Setting silo endpoint address to {0}:{1}", endpoint, generation);
NodeConfig.HostNameOrIPAddress = endpoint.Address.ToString();
NodeConfig.Port = endpoint.Port;
NodeConfig.Generation = generation;
}
/// <summary>
/// Set the gateway proxy endpoint address for this silo.
/// </summary>
/// <param name="endpoint">IP address of the gateway socket connection.</param>
public void SetProxyEndpoint(IPEndPoint endpoint)
{
logger.Info(ErrorCode.SiloSetProxyEndpoint, "Setting silo proxy endpoint address to {0}", endpoint);
NodeConfig.ProxyGatewayEndpoint = endpoint;
}
/// <summary>
/// Set the seed node endpoint address to be used by silo.
/// </summary>
/// <param name="endpoint">IP address of the inter-silo connection socket on the seed node silo.</param>
public void SetSeedNodeEndpoint(IPEndPoint endpoint)
{
logger.Info(ErrorCode.SiloSetSeedNode, "Adding seed node address={0} port={1}", endpoint.Address, endpoint.Port);
Config.Globals.SeedNodes.Clear();
Config.Globals.SeedNodes.Add(endpoint);
}
/// <summary>
/// Set the set of seed node endpoint addresses to be used by silo.
/// </summary>
/// <param name="endpoints">IP addresses of the inter-silo connection socket on the seed node silos.</param>
public void SetSeedNodeEndpoints(IPEndPoint[] endpoints)
{
// Add all silos as seed nodes
Config.Globals.SeedNodes.Clear();
foreach (IPEndPoint endpoint in endpoints)
{
logger.Info(ErrorCode.SiloAddSeedNode, "Adding seed node address={0} port={1}", endpoint.Address, endpoint.Port);
Config.Globals.SeedNodes.Add(endpoint);
}
}
/// <summary>
/// Set the endpoint addresses for the Primary silo (if any).
/// This silo may be Primary, in which case this address should match
/// this silo's inter-silo connection socket address.
/// </summary>
/// <param name="endpoint">The IP address for the inter-silo connection socket on the Primary silo.</param>
public void SetPrimaryNodeEndpoint(IPEndPoint endpoint)
{
logger.Info(ErrorCode.SiloSetPrimaryNode, "Setting primary node address={0} port={1}", endpoint.Address, endpoint.Port);
Config.PrimaryNode = endpoint;
}
/// <summary>
/// Set the type of this silo. Default is Secondary.
/// </summary>
/// <param name="siloType">Type of this silo.</param>
public void SetSiloType(Silo.SiloType siloType)
{
logger.Info(ErrorCode.SiloSetSiloType, "Setting silo type {0}", siloType);
Type = siloType;
}
/// <summary>
/// Set the membership liveness type to be used by this silo.
/// </summary>
/// <param name="livenessType">Liveness type for this silo</param>
public void SetSiloLivenessType(GlobalConfiguration.LivenessProviderType livenessType)
{
logger.Info(ErrorCode.SetSiloLivenessType, "Setting silo Liveness Provider Type={0}", livenessType);
Config.Globals.LivenessType = livenessType;
}
/// <summary>
/// Set the reminder service type to be used by this silo.
/// </summary>
/// <param name="reminderType">Reminder service type for this silo</param>
public void SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType reminderType)
{
logger.Info(ErrorCode.SetSiloLivenessType, "Setting silo Reminder Service Provider Type={0}", reminderType);
Config.Globals.SetReminderServiceType(reminderType);
}
/// <summary>
/// Set expected deployment size.
/// </summary>
/// <param name="size">The expected deployment size.</param>
public void SetExpectedClusterSize(int size)
{
logger.Info(ErrorCode.SetSiloLivenessType, "Setting Expected Cluster Size to={0}", size);
Config.Globals.ExpectedClusterSize = size;
}
/// <summary>
/// Report an error during silo startup.
/// </summary>
/// <remarks>
/// Information on the silo startup issue will be logged to any attached Loggers,
/// then a timestamped StartupError text file will be written to
/// the current working directory (if possible).
/// </remarks>
/// <param name="exc">Exception which caused the silo startup issue.</param>
public void ReportStartupError(Exception exc)
{
if (string.IsNullOrWhiteSpace(Name))
Name = "Silo";
var errMsg = "ERROR starting Orleans silo name=" + Name + " Exception=" + LogFormatter.PrintException(exc);
if (logger != null) logger.Error(ErrorCode.Runtime_Error_100105, errMsg, exc);
// Dump Startup error to a log file
var now = DateTime.UtcNow;
const string dateFormat = "yyyy-MM-dd-HH.mm.ss.fffZ";
var dateString = now.ToString(dateFormat, CultureInfo.InvariantCulture);
var startupLog = Name + "-StartupError-" + dateString + ".txt";
try
{
File.AppendAllText(startupLog, dateString + "Z" + Environment.NewLine + errMsg);
}
catch (Exception exc2)
{
if (logger != null) logger.Error(ErrorCode.Runtime_Error_100106, "Error writing log file " + startupLog, exc2);
}
LogManager.Flush();
}
/// <summary>
/// Search for and load the config file for this silo.
/// </summary>
public void LoadOrleansConfig()
{
if (ConfigLoaded) return;
var config = Config ?? new ClusterConfiguration();
try
{
if (ConfigFileName == null)
config.StandardLoad();
else
config.LoadFromFile(ConfigFileName);
}
catch (Exception ex)
{
throw new AggregateException("Error loading Config file: " + ex.Message, ex);
}
SetSiloConfig(config);
}
/// <summary>
/// Allows silo config to be programmatically set.
/// </summary>
/// <param name="config">Configuration data for this silo and cluster.</param>
private void SetSiloConfig(ClusterConfiguration config)
{
Config = config;
if (Verbose > 0)
Config.Defaults.DefaultTraceLevel = (Severity.Verbose - 1 + Verbose);
if (!String.IsNullOrEmpty(DeploymentId))
Config.Globals.DeploymentId = DeploymentId;
if (string.IsNullOrWhiteSpace(Name))
throw new ArgumentException("SiloName not defined - cannot initialize config");
NodeConfig = Config.GetOrCreateNodeConfigurationForSilo(Name);
Type = NodeConfig.IsPrimaryNode ? Silo.SiloType.Primary : Silo.SiloType.Secondary;
if (TraceFilePath != null)
{
var traceFileName = NodeConfig.TraceFileName;
if (traceFileName != null && !Path.IsPathRooted(traceFileName))
NodeConfig.TraceFileName = TraceFilePath + "\\" + traceFileName;
}
ConfigLoaded = true;
InitializeLogger(NodeConfig);
}
private void InitializeLogger(NodeConfiguration nodeCfg)
{
LogManager.Initialize(nodeCfg);
logger = LogManager.GetLogger("OrleansSiloHost", LoggerType.Runtime);
}
/// <summary>
/// Helper to wait for this silo to shutdown or to be stopped via a cancellation token.
/// </summary>
/// <param name="cancellationToken">Optional cancellation token.</param>
/// <remarks>
/// Note: This method call will block execution of current thread,
/// and will not return control back to the caller until the silo is shutdown or
/// an external request for cancellation has been issued.
/// </remarks>
private void WaitForOrleansSiloShutdownImpl(CancellationToken? cancellationToken = null)
{
if (!IsStarted)
throw new InvalidOperationException("Cannot wait for silo " + this.Name + " since it was not started successfully previously.");
if (startupEvent != null)
startupEvent.Reset();
else
throw new InvalidOperationException("Cannot wait for silo " + this.Name + " due to prior initialization error");
if (orleans != null)
{
// Intercept cancellation to initiate silo stop
if (cancellationToken.HasValue)
cancellationToken.Value.Register(HandleExternalCancellation);
orleans.SiloTerminatedEvent.WaitOne();
}
else
throw new InvalidOperationException("Cannot wait for silo " + this.Name + " due to prior initialization error");
}
/// <summary>
/// Handle the silo stop request coming from an external cancellation token.
/// </summary>
private void HandleExternalCancellation()
{
// Try to perform gracefull shutdown of Silo when we a cancellation request has been made
logger.Info(ErrorCode.SiloStopping, "External cancellation triggered, starting to shutdown silo.");
ShutdownOrleansSilo();
}
/// <summary>
/// Called when this silo is being Disposed by .NET runtime.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary> Perform the Dispose / cleanup operation. </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (startupEvent != null)
{
startupEvent.Dispose();
startupEvent = null;
}
this.IsStarted = false;
}
}
disposed = true;
}
}
}
| |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.CloudSearch.Model
{
/// <summary>
/// <para>The current status of the search domain.</para>
/// </summary>
public class DomainStatus
{
private string domainId;
private string domainName;
private bool? created;
private bool? deleted;
private int? numSearchableDocs;
private ServiceEndpoint docService;
private ServiceEndpoint searchService;
private bool? requiresIndexDocuments;
private bool? processing;
private string searchInstanceType;
private int? searchPartitionCount;
private int? searchInstanceCount;
/// <summary>
/// An internally generated unique identifier for a domain.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 64</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string DomainId
{
get { return this.domainId; }
set { this.domainId = value; }
}
/// <summary>
/// Sets the DomainId property
/// </summary>
/// <param name="domainId">The value to set for the DomainId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DomainStatus WithDomainId(string domainId)
{
this.domainId = domainId;
return this;
}
// Check to see if DomainId property is set
internal bool IsSetDomainId()
{
return this.domainId != null;
}
/// <summary>
/// A string that represents the name of a domain. Domain names must be unique across the domains owned by an account within an AWS region.
/// Domain names must start with a letter or number and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen). Uppercase
/// letters and underscores are not allowed.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>3 - 28</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[a-z][a-z0-9\-]+</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string DomainName
{
get { return this.domainName; }
set { this.domainName = value; }
}
/// <summary>
/// Sets the DomainName property
/// </summary>
/// <param name="domainName">The value to set for the DomainName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DomainStatus WithDomainName(string domainName)
{
this.domainName = domainName;
return this;
}
// Check to see if DomainName property is set
internal bool IsSetDomainName()
{
return this.domainName != null;
}
/// <summary>
/// True if the search domain is created. It can take several minutes to initialize a domain when <a>CreateDomain</a> is called. Newly created
/// search domains are returned from <a>DescribeDomains</a> with a false value for Created until domain creation is complete.
///
/// </summary>
public bool Created
{
get { return this.created ?? default(bool); }
set { this.created = value; }
}
/// <summary>
/// Sets the Created property
/// </summary>
/// <param name="created">The value to set for the Created property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DomainStatus WithCreated(bool created)
{
this.created = created;
return this;
}
// Check to see if Created property is set
internal bool IsSetCreated()
{
return this.created.HasValue;
}
/// <summary>
/// True if the search domain has been deleted. The system must clean up resources dedicated to the search domain when <a>DeleteDomain</a> is
/// called. Newly deleted search domains are returned from <a>DescribeDomains</a> with a true value for IsDeleted for several minutes until
/// resource cleanup is complete.
///
/// </summary>
public bool Deleted
{
get { return this.deleted ?? default(bool); }
set { this.deleted = value; }
}
/// <summary>
/// Sets the Deleted property
/// </summary>
/// <param name="deleted">The value to set for the Deleted property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DomainStatus WithDeleted(bool deleted)
{
this.deleted = deleted;
return this;
}
// Check to see if Deleted property is set
internal bool IsSetDeleted()
{
return this.deleted.HasValue;
}
/// <summary>
/// The number of documents that have been submitted to the domain and indexed.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>0 - </description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int NumSearchableDocs
{
get { return this.numSearchableDocs ?? default(int); }
set { this.numSearchableDocs = value; }
}
/// <summary>
/// Sets the NumSearchableDocs property
/// </summary>
/// <param name="numSearchableDocs">The value to set for the NumSearchableDocs property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DomainStatus WithNumSearchableDocs(int numSearchableDocs)
{
this.numSearchableDocs = numSearchableDocs;
return this;
}
// Check to see if NumSearchableDocs property is set
internal bool IsSetNumSearchableDocs()
{
return this.numSearchableDocs.HasValue;
}
/// <summary>
/// The service endpoint for updating documents in a search domain.
///
/// </summary>
public ServiceEndpoint DocService
{
get { return this.docService; }
set { this.docService = value; }
}
/// <summary>
/// Sets the DocService property
/// </summary>
/// <param name="docService">The value to set for the DocService property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DomainStatus WithDocService(ServiceEndpoint docService)
{
this.docService = docService;
return this;
}
// Check to see if DocService property is set
internal bool IsSetDocService()
{
return this.docService != null;
}
/// <summary>
/// The service endpoint for requesting search results from a search domain.
///
/// </summary>
public ServiceEndpoint SearchService
{
get { return this.searchService; }
set { this.searchService = value; }
}
/// <summary>
/// Sets the SearchService property
/// </summary>
/// <param name="searchService">The value to set for the SearchService property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DomainStatus WithSearchService(ServiceEndpoint searchService)
{
this.searchService = searchService;
return this;
}
// Check to see if SearchService property is set
internal bool IsSetSearchService()
{
return this.searchService != null;
}
/// <summary>
/// True if <a>IndexDocuments</a> needs to be called to activate the current domain configuration.
///
/// </summary>
public bool RequiresIndexDocuments
{
get { return this.requiresIndexDocuments ?? default(bool); }
set { this.requiresIndexDocuments = value; }
}
/// <summary>
/// Sets the RequiresIndexDocuments property
/// </summary>
/// <param name="requiresIndexDocuments">The value to set for the RequiresIndexDocuments property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DomainStatus WithRequiresIndexDocuments(bool requiresIndexDocuments)
{
this.requiresIndexDocuments = requiresIndexDocuments;
return this;
}
// Check to see if RequiresIndexDocuments property is set
internal bool IsSetRequiresIndexDocuments()
{
return this.requiresIndexDocuments.HasValue;
}
/// <summary>
/// True if processing is being done to activate the current domain configuration.
///
/// </summary>
public bool Processing
{
get { return this.processing ?? default(bool); }
set { this.processing = value; }
}
/// <summary>
/// Sets the Processing property
/// </summary>
/// <param name="processing">The value to set for the Processing property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DomainStatus WithProcessing(bool processing)
{
this.processing = processing;
return this;
}
// Check to see if Processing property is set
internal bool IsSetProcessing()
{
return this.processing.HasValue;
}
/// <summary>
/// The instance type (such as search.m1.small) that is being used to process search requests.
///
/// </summary>
public string SearchInstanceType
{
get { return this.searchInstanceType; }
set { this.searchInstanceType = value; }
}
/// <summary>
/// Sets the SearchInstanceType property
/// </summary>
/// <param name="searchInstanceType">The value to set for the SearchInstanceType property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DomainStatus WithSearchInstanceType(string searchInstanceType)
{
this.searchInstanceType = searchInstanceType;
return this;
}
// Check to see if SearchInstanceType property is set
internal bool IsSetSearchInstanceType()
{
return this.searchInstanceType != null;
}
/// <summary>
/// The number of partitions across which the search index is spread.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>1 - </description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int SearchPartitionCount
{
get { return this.searchPartitionCount ?? default(int); }
set { this.searchPartitionCount = value; }
}
/// <summary>
/// Sets the SearchPartitionCount property
/// </summary>
/// <param name="searchPartitionCount">The value to set for the SearchPartitionCount property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DomainStatus WithSearchPartitionCount(int searchPartitionCount)
{
this.searchPartitionCount = searchPartitionCount;
return this;
}
// Check to see if SearchPartitionCount property is set
internal bool IsSetSearchPartitionCount()
{
return this.searchPartitionCount.HasValue;
}
/// <summary>
/// The number of search instances that are available to process search requests.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>1 - </description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int SearchInstanceCount
{
get { return this.searchInstanceCount ?? default(int); }
set { this.searchInstanceCount = value; }
}
/// <summary>
/// Sets the SearchInstanceCount property
/// </summary>
/// <param name="searchInstanceCount">The value to set for the SearchInstanceCount property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DomainStatus WithSearchInstanceCount(int searchInstanceCount)
{
this.searchInstanceCount = searchInstanceCount;
return this;
}
// Check to see if SearchInstanceCount property is set
internal bool IsSetSearchInstanceCount()
{
return this.searchInstanceCount.HasValue;
}
}
}
| |
using System.Text;
using Exceptionless.Core.AppStats;
using Exceptionless.Core.Extensions;
using Exceptionless.Core.Models;
using Exceptionless.Core.Pipeline;
using Exceptionless.Core.Plugins.EventParser;
using Exceptionless.Core.Queues.Models;
using Exceptionless.Core.Repositories;
using Exceptionless.Core.Repositories.Base;
using Exceptionless.Core.Services;
using FluentValidation;
using Foundatio.Jobs;
using Foundatio.Metrics;
using Foundatio.Queues;
using Foundatio.Repositories;
using Foundatio.Utility;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Exceptionless.Core.Jobs;
[Job(Description = "Processes queued events.", InitialDelay = "2s")]
public class EventPostsJob : QueueJobBase<EventPost> {
private readonly long _maximumEventPostFileSize;
private readonly long _maximumUncompressedEventPostSize;
private readonly EventPostService _eventPostService;
private readonly EventParserPluginManager _eventParserPluginManager;
private readonly EventPipeline _eventPipeline;
private readonly IMetricsClient _metrics;
private readonly UsageService _usageService;
private readonly IOrganizationRepository _organizationRepository;
private readonly IProjectRepository _projectRepository;
private readonly JsonSerializerSettings _jsonSerializerSettings;
private readonly AppOptions _appOptions;
public EventPostsJob(IQueue<EventPost> queue, EventPostService eventPostService, EventParserPluginManager eventParserPluginManager, EventPipeline eventPipeline, IMetricsClient metrics, UsageService usageService, IOrganizationRepository organizationRepository, IProjectRepository projectRepository, JsonSerializerSettings jsonSerializerSettings, AppOptions appOptions, ILoggerFactory loggerFactory = null) : base(queue, loggerFactory) {
_eventPostService = eventPostService;
_eventParserPluginManager = eventParserPluginManager;
_eventPipeline = eventPipeline;
_metrics = metrics;
_usageService = usageService;
_organizationRepository = organizationRepository;
_projectRepository = projectRepository;
_jsonSerializerSettings = jsonSerializerSettings;
_appOptions = appOptions;
_maximumEventPostFileSize = _appOptions.MaximumEventPostSize + 1024;
_maximumUncompressedEventPostSize = _appOptions.MaximumEventPostSize * 10;
AutoComplete = false;
}
protected override async Task<JobResult> ProcessQueueEntryAsync(QueueEntryContext<EventPost> context) {
var entry = context.QueueEntry;
var ep = entry.Value;
string payloadPath = Path.ChangeExtension(entry.Value.FilePath, ".payload");
var payloadTask = _metrics.TimeAsync(() => _eventPostService.GetEventPostPayloadAsync(payloadPath), MetricNames.PostsMarkFileActiveTime);
var projectTask = _projectRepository.GetByIdAsync(ep.ProjectId, o => o.Cache());
var organizationTask = _organizationRepository.GetByIdAsync(ep.OrganizationId, o => o.Cache());
byte[] payload = await payloadTask.AnyContext();
if (payload == null) {
await Task.WhenAll(AbandonEntryAsync(entry), projectTask, organizationTask).AnyContext();
return JobResult.FailedWithMessage($"Unable to retrieve payload '{payloadPath}'.");
}
_metrics.Gauge(MetricNames.PostsMessageSize, payload.LongLength);
if (payload.LongLength > _maximumEventPostFileSize) {
await Task.WhenAll(_metrics.TimeAsync(() => entry.CompleteAsync(), MetricNames.PostsCompleteTime), projectTask, organizationTask).AnyContext();
return JobResult.FailedWithMessage($"Unable to process payload '{payloadPath}' ({payload.LongLength} bytes): Maximum event post size limit ({_appOptions.MaximumEventPostSize} bytes) reached.");
}
using (_logger.BeginScope(new ExceptionlessState().Organization(ep.OrganizationId).Project(ep.ProjectId))) {
_metrics.Gauge(MetricNames.PostsCompressedSize, payload.Length);
bool isDebugLogLevelEnabled = _logger.IsEnabled(LogLevel.Debug);
bool isInternalProject = ep.ProjectId == _appOptions.InternalProjectId;
if (!isInternalProject && _logger.IsEnabled(LogLevel.Information)) {
using (_logger.BeginScope(new ExceptionlessState().Tag("processing").Tag("compressed").Tag(ep.ContentEncoding).Value(payload.Length)))
_logger.LogInformation("Processing post: id={QueueEntryId} path={FilePath} project={project} ip={IpAddress} v={ApiVersion} agent={UserAgent}", entry.Id, payloadPath, ep.ProjectId, ep.IpAddress, ep.ApiVersion, ep.UserAgent);
}
var project = await projectTask.AnyContext();
if (project == null) {
if (!isInternalProject) _logger.LogError("Unable to process EventPost {FilePath}: Unable to load project: {Project}", payloadPath, ep.ProjectId);
await Task.WhenAll(CompleteEntryAsync(entry, ep, SystemClock.UtcNow), organizationTask).AnyContext();
return JobResult.Success;
}
long maxEventPostSize = _appOptions.MaximumEventPostSize;
byte[] uncompressedData = payload;
if (!String.IsNullOrEmpty(ep.ContentEncoding)) {
if (!isInternalProject && isDebugLogLevelEnabled) {
using (_logger.BeginScope(new ExceptionlessState().Tag("decompressing").Tag(ep.ContentEncoding)))
_logger.LogDebug("Decompressing EventPost: {QueueEntryId} ({CompressedBytes} bytes)", entry.Id, payload.Length);
}
maxEventPostSize = _maximumUncompressedEventPostSize;
try {
_metrics.Time(() => {
uncompressedData = uncompressedData.Decompress(ep.ContentEncoding);
}, MetricNames.PostsDecompressionTime);
} catch (Exception ex) {
_metrics.Counter(MetricNames.PostsDecompressionErrors);
await Task.WhenAll(CompleteEntryAsync(entry, ep, SystemClock.UtcNow), organizationTask).AnyContext();
return JobResult.FailedWithMessage($"Unable to decompress EventPost data '{payloadPath}' ({payload.Length} bytes compressed): {ex.Message}");
}
}
_metrics.Gauge(MetricNames.PostsUncompressedSize, payload.LongLength);
if (uncompressedData.Length > maxEventPostSize) {
var org = await organizationTask.AnyContext();
await _usageService.IncrementTooBigAsync(org, project).AnyContext();
await CompleteEntryAsync(entry, ep, SystemClock.UtcNow).AnyContext();
return JobResult.FailedWithMessage($"Unable to process decompressed EventPost data '{payloadPath}' ({payload.Length} bytes compressed, {uncompressedData.Length} bytes): Maximum uncompressed event post size limit ({maxEventPostSize} bytes) reached.");
}
if (!isInternalProject && isDebugLogLevelEnabled) {
using (_logger.BeginScope(new ExceptionlessState().Tag("uncompressed").Value(uncompressedData.Length)))
_logger.LogDebug("Processing uncompressed EventPost: {QueueEntryId} ({UncompressedBytes} bytes)", entry.Id, uncompressedData.Length);
}
var createdUtc = SystemClock.UtcNow;
var events = ParseEventPost(ep, createdUtc, uncompressedData, entry.Id, isInternalProject);
if (events == null || events.Count == 0) {
await Task.WhenAll(CompleteEntryAsync(entry, ep, createdUtc), organizationTask).AnyContext();
return JobResult.Success;
}
if (context.CancellationToken.IsCancellationRequested) {
await Task.WhenAll(AbandonEntryAsync(entry), organizationTask).AnyContext();
return JobResult.Cancelled;
}
var organization = await organizationTask.AnyContext();
if (organization == null) {
if (!isInternalProject)
_logger.LogError("Unable to process EventPost {FilePath}: Unable to load organization: {OrganizationId}", payloadPath, project.OrganizationId);
await CompleteEntryAsync(entry, ep, SystemClock.UtcNow).AnyContext();
return JobResult.Success;
}
bool isSingleEvent = events.Count == 1;
if (!isSingleEvent) {
// Don't process all the events if it will put the account over its limits.
int eventsToProcess = await _usageService.GetRemainingEventLimitAsync(organization).AnyContext();
// Add 1 because we already counted 1 against their limit when we received the event post.
if (eventsToProcess < Int32.MaxValue)
eventsToProcess += 1;
// Discard any events over the plan limit.
if (eventsToProcess < events.Count) {
int discarded = events.Count - eventsToProcess;
events = events.Take(eventsToProcess).ToList();
_metrics.Counter(MetricNames.EventsDiscarded, discarded);
}
}
int errorCount = 0;
var eventsToRetry = new List<PersistentEvent>();
try {
var contexts = await _eventPipeline.RunAsync(events, organization, project, ep).AnyContext();
if (!isInternalProject && isDebugLogLevelEnabled) {
using (_logger.BeginScope(new ExceptionlessState().Value(contexts.Count)))
_logger.LogDebug("Ran {@value} events through the pipeline: id={QueueEntryId} success={SuccessCount} error={ErrorCount}", contexts.Count, entry.Id, contexts.Count(r => r.IsProcessed), contexts.Count(r => r.HasError));
}
// increment the plan usage counters (note: OverageHandler already incremented usage by 1)
int processedEvents = contexts.Count(c => c.IsProcessed);
await _usageService.IncrementUsageAsync(organization, project, processedEvents, applyHourlyLimit: false).AnyContext();
int discardedEvents = contexts.Count(c => c.IsDiscarded);
_metrics.Counter(MetricNames.EventsDiscarded, discardedEvents);
foreach (var ctx in contexts) {
if (ctx.IsCancelled)
continue;
if (!ctx.HasError)
continue;
if (!isInternalProject) _logger.LogError(ctx.Exception, "Error processing EventPost {QueueEntryId} {FilePath}: {Message}", entry.Id, payloadPath, ctx.ErrorMessage);
if (ctx.Exception is ValidationException)
continue;
errorCount++;
if (!isSingleEvent) {
// Put this single event back into the queue so we can retry it separately.
eventsToRetry.Add(ctx.Event);
}
}
}
catch (Exception ex) {
if (!isInternalProject) _logger.LogError(ex, "Error processing EventPost {QueueEntryId} {FilePath}: {Message}", entry.Id, payloadPath, ex.Message);
if (ex is ArgumentException || ex is DocumentNotFoundException) {
await CompleteEntryAsync(entry, ep, createdUtc).AnyContext();
return JobResult.Success;
}
errorCount++;
if (!isSingleEvent)
eventsToRetry.AddRange(events);
}
if (eventsToRetry.Count > 0)
await _metrics.TimeAsync(() => RetryEventsAsync(eventsToRetry, ep, entry, project, isInternalProject), MetricNames.PostsRetryTime).AnyContext();
if (isSingleEvent && errorCount > 0)
await AbandonEntryAsync(entry).AnyContext();
else
await CompleteEntryAsync(entry, ep, createdUtc).AnyContext();
return JobResult.Success;
}
}
private List<PersistentEvent> ParseEventPost(EventPostInfo ep, DateTime createdUtc, byte[] uncompressedData, string queueEntryId, bool isInternalProject) {
using (_logger.BeginScope(new ExceptionlessState().Tag("parsing"))) {
if (!isInternalProject && _logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug("Parsing EventPost: {QueueEntryId}", queueEntryId);
List<PersistentEvent> events = null;
try {
var encoding = Encoding.UTF8;
if (!String.IsNullOrEmpty(ep.CharSet))
encoding = Encoding.GetEncoding(ep.CharSet);
_metrics.Time(() => {
string input = encoding.GetString(uncompressedData);
events = _eventParserPluginManager.ParseEvents(input, ep.ApiVersion, ep.UserAgent) ?? new List<PersistentEvent>(0);
foreach (var ev in events) {
ev.CreatedUtc = createdUtc;
ev.OrganizationId = ep.OrganizationId;
ev.ProjectId = ep.ProjectId;
// set the reference id to the event id if one was defined.
if (!String.IsNullOrEmpty(ev.Id) && String.IsNullOrEmpty(ev.ReferenceId))
ev.ReferenceId = ev.Id;
// the event id and stack id should never be set for posted events
ev.Id = ev.StackId = null;
}
}, MetricNames.PostsParsingTime);
_metrics.Counter(MetricNames.PostsParsed);
_metrics.Gauge(MetricNames.PostsEventCount, events.Count);
}
catch (Exception ex) {
_metrics.Counter(MetricNames.PostsParseErrors);
if (!isInternalProject) _logger.LogError(ex, "An error occurred while processing the EventPost {QueueEntryId}: {Message}", queueEntryId, ex.Message);
}
if (!isInternalProject && _logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug("Parsed {ParsedCount} events from EventPost: {QueueEntryId}", events?.Count ?? 0, queueEntryId);
return events;
}
}
private async Task RetryEventsAsync(List<PersistentEvent> eventsToRetry, EventPostInfo ep, IQueueEntry<EventPost> queueEntry, Project project, bool isInternalProject) {
_metrics.Gauge(MetricNames.EventsRetryCount, eventsToRetry.Count);
foreach (var ev in eventsToRetry) {
try {
var stream = new MemoryStream(ev.GetBytes(_jsonSerializerSettings));
// Put this single event back into the queue so we can retry it separately.
await _eventPostService.EnqueueAsync(new EventPost(false) {
ApiVersion = ep.ApiVersion,
CharSet = ep.CharSet,
ContentEncoding = null,
IpAddress = ep.IpAddress,
MediaType = ep.MediaType,
OrganizationId = ep.OrganizationId ?? project.OrganizationId,
ProjectId = ep.ProjectId,
UserAgent = ep.UserAgent
}, stream).AnyContext();
}
catch (Exception ex) {
if (!isInternalProject && _logger.IsEnabled(LogLevel.Critical)) {
using (_logger.BeginScope(new ExceptionlessState().Property("Event", new { ev.Date, ev.StackId, ev.Type, ev.Source, ev.Message, ev.Value, ev.Geo, ev.ReferenceId, ev.Tags })))
_logger.LogCritical(ex, "Error while requeuing event post {FilePath}: {Message}", queueEntry.Value.FilePath, ex.Message);
}
_metrics.Counter(MetricNames.EventsRetryErrors);
}
}
}
private Task AbandonEntryAsync(IQueueEntry<EventPost> queueEntry) {
return _metrics.TimeAsync(queueEntry.AbandonAsync, MetricNames.PostsAbandonTime);
}
private Task CompleteEntryAsync(IQueueEntry<EventPost> entry, EventPostInfo eventPostInfo, DateTime created) {
return _metrics.TimeAsync(async () => {
await entry.CompleteAsync().AnyContext();
await _eventPostService.CompleteEventPostAsync(entry.Value.FilePath, eventPostInfo.ProjectId, created, entry.Value.ShouldArchive).AnyContext();
}, MetricNames.PostsCompleteTime);
}
protected override void LogProcessingQueueEntry(IQueueEntry<EventPost> entry) {
_logger.LogDebug("Processing {QueueEntryName} queue entry ({QueueEntryId}).", _queueEntryName, entry.Id);
}
protected override void LogAutoCompletedQueueEntry(IQueueEntry<EventPost> entry) {
_logger.LogDebug("Auto completed {QueueEntryName} queue entry ({QueueEntryId}).", _queueEntryName, entry.Id);
}
}
| |
//=============================================================================
// The Custom Channel Interface Contract
// (C) Copyright 2003, Roman Kiss ([email protected])
// All rights reserved.
// The code and information is provided "as-is" without waranty of any kind,
// either expresed or implied.
//
//-----------------------------------------------------------------------------
// History:
// 06/05/2003 Roman Kiss Initial Revision
//=============================================================================
//
#region references
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Messaging;
using System.Runtime.Serialization;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization.Formatters.Binary;
#endregion
namespace RKiss.CustomChannel
{
#region IKnowledgeBaseControl
public interface IKnowledgeBaseControl
{
void Save(string filename); // save it into the config file
void Load(string filename); // refresh from the config file
void Store(string strLURL, bool bOverwrite); // store logical addresses name/value, ...
void Store(string name, string val, bool bOverwrite); // store single logical address
void Update(string strLURL); // update logical addresses name/value, ...
void Update(string name, string val); // update single logical address
void RemoveAll(); // remove all logical addresses
void Remove(string name); // remove specified logical name
object GetAll(); // get all logical addresses
string Get(string name); // get the specified logical name
string Mapping(string name); // mapping logical name by physical, if it doesn't exist, just copy
bool Exists(string name); // check if we have a specified logical name
bool CanBeUpdated(); // check the status
}
#endregion
#region IRemotingResponse
[Serializable]
public class MsgSourceInfo
{
Acknowledgment m_Acknowledgment;
DateTime m_MessageSentTime;
string m_ResponseQueuePath;
string m_ReportQueuePath;
public Acknowledgment Acknowledgment { get { return m_Acknowledgment;} set { m_Acknowledgment = value; }}
public DateTime MessageSentTime { get { return m_MessageSentTime;} set { m_MessageSentTime = value; }}
public string ResponseQueuePath { get { return m_ResponseQueuePath;} set { m_ResponseQueuePath = value; }}
public string ReportQueuePath { get { return m_ReportQueuePath;} set { m_ReportQueuePath = value; }}
}
public interface IRemotingResponse
{
void ResponseNotify(MsgSourceInfo src, object msg); // remoting notification
void ResponseAck(object msg); // remoting response notification
void ResponseError(object msg, Exception ex); // remoting exception notification
}
#endregion
#region Constants Definitions
public class MSMQChannelDefaults
{
public const string ChannelName = "msmq";
public const int ChannelPriority = 1;
public const int TimeoutInSec = 60;
public const int RetryCounter = 0;
public const int MaxThreads = 20; // max. number threads in the pool
public const bool CanBeUpdated = true;
public const bool UseTimeout = false; // disable timeout over retry mechanism
public const bool UseHeaders = false; // allow to pass a transport headers via msmq
public const bool ACK = false;
public const string EmptyStr = "";
public const string QueuePath = @".\Private$\ReqChannel";
public const string EventLog = "Application"; // Event Log Entry
public const int EventId = 500; // Event Id of the Channel
public const short EventCategory = 0; // Event Category
}
public class MSMQChannelProperties
{
public const string ChannelName = "name";
public const string ChannelPriority = "priority";
public const string Listener = "listener";
public const string NotifyTime = "notifytime";
public const string UseTimeout = "usetimeout";
public const string UseHeaders = "useheaders";
public const string RetryTime = "retrytime";
public const string Retry = "retry";
public const string RetryFilter = "retryfilter";
public const string MaxThreads = "maxthreads";
public const string NotifyUrl = "notifyurl";
public const string AckUrl = "acknowledgeurl";
public const string ExceptionUrl = "exceptionurl";
public const string Timeout = "timeout";
public const string RcvAck = "receiveack";
public const string SendAck = "sendack";
public const string RcvTimeout = "receivetimeout";
public const string SendTimeout = "sendtimeout";
public const string AdminQueuePath = "admin";
public const string LURL = "lurl";
public const string Uri = "__Uri";
public const string ObjectUri = "__ObjectUri";
public const string MethodName = "___MethodName";
public const string MethodSignature = "___MethodSignature";
public const string TypeName = "___TypeName";
public const string RetryCounter = "___RetryCounter";
public const string UpdateKB = "updatekb";
}
#endregion
#region CallContext Ticket
[Serializable]
public class LogicalTicket : NameValueCollection, ILogicalThreadAffinative
{
public LogicalTicket() { init(null); }
public LogicalTicket(params string[] args) { init(args); }
public LogicalTicket(IMessage imsg)
{
if(imsg != null)
{
object obj = imsg.Properties["__CallContext"];
if(obj != null && obj is LogicalCallContext)
{
LogicalCallContext lcc = obj as LogicalCallContext;
object ticket = lcc.GetData("___Ticket");
if(ticket != null && ticket is LogicalTicket)
{
LogicalTicket lt = ticket as LogicalTicket;
for(int ii = 0; ii < lt.Count; ii++)
{
base[lt.GetKey(ii)] = lt.Get(ii);
}
}
}
}
}
protected LogicalTicket(SerializationInfo info, StreamingContext context): base(info, context) {}
public void Set() { CallContext.SetData("___Ticket", this); }
public void Reset() { CallContext.FreeNamedDataSlot("___Ticket"); }
private void init(params string[] args)
{
object obj = CallContext.GetData("___Ticket");
if(obj != null)
{
LogicalTicket lt = obj as LogicalTicket;
for(int ii = 0; ii < lt.Count; ii++)
{
base[lt.GetKey(ii)] = lt.Get(ii);
}
}
if(args != null)
{
foreach(string s in args)
{
string[] nv = s.Split(new char[]{'='}, 2);
if(nv.Length != 2)
throw new Exception(string.Format("Wrong name/value pattern in the Ticket, arg={0}", s));
base[nv[0].Trim()] = nv[1].Trim();
}
}
}
}
#endregion
#region helpers
public sealed class RemotingConvert
{
public static byte[] ToArray(IMessage imsg)
{
byte[] buffer = null;
//serialize IMessage
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
bf.Serialize(stream, imsg);
stream.Position = 0;
//write stream to the buffer
buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
return buffer;
}
public static IMessage ToMessage(object msg)
{
IMessage imsg = null;
// deserialize IMessage
if(msg is byte[])
{
byte[] buffer = msg as byte[];
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
stream.Write(buffer, 0, buffer.Length);
stream.Position = 0;
imsg = (IMessage)bf.Deserialize(stream);
stream.Close();
}
return imsg;
}
}
#endregion
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion
{
/// <summary>
/// csharp automatic line ender command handler
/// </summary>
[ExportCommandHandler(PredefinedCommandHandlerNames.AutomaticLineEnder, ContentTypeNames.CSharpContentType)]
[Order(After = PredefinedCommandHandlerNames.Completion)]
internal class AutomaticLineEnderCommandHandler : AbstractAutomaticLineEnderCommandHandler
{
[ImportingConstructor]
public AutomaticLineEnderCommandHandler(
IWaitIndicator waitIndicator,
ITextUndoHistoryRegistry undoRegistry,
IEditorOperationsFactoryService editorOperations)
: base(waitIndicator, undoRegistry, editorOperations)
{
}
protected override void NextAction(IEditorOperations editorOperation, Action nextAction)
{
editorOperation.InsertNewLine();
}
protected override bool TreatAsReturn(Document document, int position, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var endToken = root.FindToken(position);
if (endToken.IsMissing)
{
return false;
}
var tokenToLeft = root.FindTokenOnLeftOfPosition(position);
var startToken = endToken.GetPreviousToken();
// case 1:
// Consider code like so: try {|}
// With auto brace completion on, user types `{` and `Return` in a hurry.
// During typing, it is possible that shift was still down and not released after typing `{`.
// So we've got an unintentional `shift + enter` and also we have nothing to complete this,
// so we put in a newline,
// which generates code like so : try { }
// |
// which is not useful as : try {
// |
// }
// To support this, we treat `shift + enter` like `enter` here.
var afterOpenBrace = startToken.Kind() == SyntaxKind.OpenBraceToken
&& endToken.Kind() == SyntaxKind.CloseBraceToken
&& tokenToLeft == startToken
&& endToken.Parent.IsKind(SyntaxKind.Block)
&& FormattingRangeHelper.AreTwoTokensOnSameLine(startToken, endToken);
return afterOpenBrace;
}
protected override void FormatAndApply(Document document, int position, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var endToken = root.FindToken(position);
if (endToken.IsMissing)
{
return;
}
var ranges = FormattingRangeHelper.FindAppropriateRange(endToken, useDefaultRange: false);
if (ranges == null)
{
return;
}
var startToken = ranges.Value.Item1;
if (startToken.IsMissing || startToken.Kind() == SyntaxKind.None)
{
return;
}
var changes = Formatter.GetFormattedTextChanges(root, new TextSpan[] { TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End) }, document.Project.Solution.Workspace, options: document.Options,
rules: null, // use default
cancellationToken: cancellationToken);
document.ApplyTextChanges(changes.ToArray(), cancellationToken);
}
protected override string GetEndingString(Document document, int position, CancellationToken cancellationToken)
{
// prepare expansive information from document
var tree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var root = tree.GetRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var text = tree.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var semicolon = SyntaxFacts.GetText(SyntaxKind.SemicolonToken);
// Go through the set of owning nodes in leaf to root chain.
foreach (var owningNode in GetOwningNodes(root, position))
{
SyntaxToken lastToken;
if (!TryGetLastToken(text, position, owningNode, out lastToken))
{
// If we can't get last token, there is nothing more to do, just skip
// the other owning nodes and return.
return null;
}
if (!CheckLocation(text, position, owningNode, lastToken))
{
// If we failed this check, we indeed got the intended owner node and
// inserting line ender here would introduce errors.
return null;
}
// so far so good. we only add semi-colon if it makes statement syntax error free
var textToParse = owningNode.NormalizeWhitespace().ToFullString() + semicolon;
// currently, Parsing a field is not supported. as a workaround, wrap the field in a type and parse
var node = owningNode.TypeSwitch(
(BaseFieldDeclarationSyntax n) => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options),
(BaseMethodDeclarationSyntax n) => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options),
(BasePropertyDeclarationSyntax n) => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options),
(StatementSyntax n) => SyntaxFactory.ParseStatement(textToParse, options: (CSharpParseOptions)tree.Options),
(UsingDirectiveSyntax n) => (SyntaxNode)SyntaxFactory.ParseCompilationUnit(textToParse, options: (CSharpParseOptions)tree.Options));
// Insert line ender if we didn't introduce any diagnostics, if not try the next owning node.
if (node != null && !node.ContainsDiagnostics)
{
return semicolon;
}
}
return null;
}
/// <summary>
/// wrap field in type
/// </summary>
private string WrapInType(string textToParse)
{
return "class C { " + textToParse + " }";
}
/// <summary>
/// make sure current location is okay to put semicolon
/// </summary>
private static bool CheckLocation(SourceText text, int position, SyntaxNode owningNode, SyntaxToken lastToken)
{
var line = text.Lines.GetLineFromPosition(position);
// if caret is at the end of the line and containing statement is expression statement
// don't do anything
if (position == line.End && owningNode is ExpressionStatementSyntax)
{
return false;
}
var locatedAtTheEndOfLine = LocatedAtTheEndOfLine(line, lastToken);
// make sure that there is no trailing text after last token on the line if it is not at the end of the line
if (!locatedAtTheEndOfLine)
{
var endingString = text.ToString(TextSpan.FromBounds(lastToken.Span.End, line.End));
if (!string.IsNullOrWhiteSpace(endingString))
{
return false;
}
}
// check whether using has contents
if (owningNode.TypeSwitch((UsingDirectiveSyntax u) => u.Name == null || u.Name.IsMissing))
{
return false;
}
// make sure there is no open string literals
var previousToken = lastToken.GetPreviousToken();
if (previousToken.Kind() == SyntaxKind.StringLiteralToken && previousToken.ToString().Last() != '"')
{
return false;
}
if (previousToken.Kind() == SyntaxKind.CharacterLiteralToken && previousToken.ToString().Last() != '\'')
{
return false;
}
// now, check embedded statement case
if (owningNode.IsEmbeddedStatementOwner())
{
var embeddedStatement = owningNode.GetEmbeddedStatement();
if (embeddedStatement == null || embeddedStatement.Span.IsEmpty)
{
return false;
}
}
return true;
}
/// <summary>
/// get last token of the given using/field/statement/expression bodied member if one exists
/// </summary>
private static bool TryGetLastToken(SourceText text, int position, SyntaxNode owningNode, out SyntaxToken lastToken)
{
lastToken = owningNode.GetLastToken(includeZeroWidth: true);
// last token must be on the same line as the caret
var line = text.Lines.GetLineFromPosition(position);
var locatedAtTheEndOfLine = LocatedAtTheEndOfLine(line, lastToken);
if (!locatedAtTheEndOfLine && text.Lines.IndexOf(lastToken.Span.End) != line.LineNumber)
{
return false;
}
// if we already have last semicolon, we don't need to do anything
if (!lastToken.IsMissing && lastToken.Kind() == SyntaxKind.SemicolonToken)
{
return false;
}
return true;
}
/// <summary>
/// check whether the line is located at the end of the line
/// </summary>
private static bool LocatedAtTheEndOfLine(TextLine line, SyntaxToken lastToken)
{
return lastToken.IsMissing && lastToken.Span.End == line.EndIncludingLineBreak;
}
/// <summary>
/// find owning usings/field/statement/expression-bodied member of the given position
/// </summary>
private static IEnumerable<SyntaxNode> GetOwningNodes(SyntaxNode root, int position)
{
// make sure caret position is somewhere we can find a token
var token = root.FindTokenFromEnd(position);
if (token.Kind() == SyntaxKind.None)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
return token.GetAncestors<SyntaxNode>()
.Where(AllowedConstructs)
.Select(OwningNode);
}
private static bool AllowedConstructs(SyntaxNode n)
{
return n is StatementSyntax ||
n is BaseFieldDeclarationSyntax ||
n is UsingDirectiveSyntax ||
n is ArrowExpressionClauseSyntax;
}
private static SyntaxNode OwningNode(SyntaxNode n)
{
return n is ArrowExpressionClauseSyntax ? n.Parent : n;
}
}
}
| |
// ThreadPool.cs
//
// This file defines a custom ThreadPool class that supports the following
// characteristics (property and method names shown in []):
//
// * can be explicitly started and stopped (and restarted) [Start,Stop,StopAndWait]
//
// * configurable thread priority [Priority]
//
// * configurable foreground/background characteristic [IsBackground]
//
// * configurable minimum thread count (called 'static' or 'permanent' threads) [constructor]
//
// * configurable maximum thread count (threads added over the minimum are
// called 'dynamic' threads) [constructor, MaxThreadCount]
//
// * configurable dynamic thread creation trigger (the point at which
// the pool decides to add new threads) [NewThreadTrigger]
//
// * configurable dynamic thread decay interval (the time period
// after which an idle dynamic thread will exit) [DynamicThreadDecay]
//
// * configurable limit (optional) to the request queue size (by default unbounded) [RequestQueueLimit]
//
// * pool extends WaitHandle, becomes signaled when last thread exits [StopAndWait, WaitHandle methods]
//
// * operations enqueued to the pool are cancellable [IWorkRequest returned by PostRequest]
//
// * enqueue operation supports early bound approach (ala ThreadPool.QueueUserWorkItem)
// as well as late bound approach (ala Control.Invoke/BeginInvoke) to posting work requests [PostRequest]
//
// * optional propogation of calling thread call context to target [PropogateCallContext]
//
// * optional propogation of calling thread principal to target [PropogateThreadPrincipal]
//
// * optional propogation of calling thread HttpContext to target [PropogateHttpContext]
//
// * support for started/stopped event subscription & notification [Started, Stopped]
//
// Known issues/limitations/comments:
//
// * The PropogateCASMarkers property exists for future support for propogating
// the calling thread's installed CAS markers in the same way that the built-in thread
// pool does. Currently, there is no support for user-defined code to perform that
// operation.
//
// * PropogateCallContext and PropogateHttpContext both use reflection against private
// members to due their job. As such, these two properties are set to false by default,
// but do work on the first release of the framework (including .NET Server) and its
// service packs. These features have not been tested on Everett at this time.
//
// Mike Woodring
// http://staff.develop.com/woodring
//
using System;
using System.Threading;
using System.Collections;
using System.Diagnostics;
using System.Security.Principal;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Web;
namespace AtomicNet.Dependencies.DevelopMentor
{
public delegate void WorkRequestDelegate( object state, DateTime requestEnqueueTime );
public delegate void ThreadPoolDelegate();
#region IWorkRequest interface
public interface IWorkRequest
{
bool Cancel();
}
#endregion
#region ThreadPool class
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public sealed class ThreadPool : WaitHandle
{
#region ThreadPool constructors
public ThreadPool( int initialThreadCount, int maxThreadCount, string poolName )
: this( initialThreadCount, maxThreadCount, poolName,
DEFAULT_NEW_THREAD_TRIGGER_TIME,
DEFAULT_DYNAMIC_THREAD_DECAY_TIME,
DEFAULT_THREAD_PRIORITY,
DEFAULT_REQUEST_QUEUE_LIMIT )
{
}
public ThreadPool( int initialThreadCount, int maxThreadCount, string poolName,
int newThreadTrigger, int dynamicThreadDecayTime,
ThreadPriority threadPriority, int requestQueueLimit )
{
Debug.WriteLine(string.Format("New thread pool {0} created:", poolName));
Debug.WriteLine(string.Format(" initial thread count: {0}", initialThreadCount));
Debug.WriteLine(string.Format(" max thread count: {0}", maxThreadCount));
Debug.WriteLine(string.Format(" new thread trigger: {0} ms", newThreadTrigger));
Debug.WriteLine(string.Format(" dynamic thread decay time: {0} ms", dynamicThreadDecayTime));
Debug.WriteLine(string.Format(" request queue limit: {0} entries", requestQueueLimit));
this.SafeWaitHandle = stopCompleteEvent.SafeWaitHandle;
if( maxThreadCount < initialThreadCount )
{
throw new ArgumentException("Maximum thread count must be >= initial thread count.", "maxThreadCount");
}
if( dynamicThreadDecayTime <= 0 )
{
throw new ArgumentException("Dynamic thread decay time cannot be <= 0.", "dynamicThreadDecayTime");
}
if( newThreadTrigger <= 0 )
{
throw new ArgumentException("New thread trigger time cannot be <= 0.", "newThreadTrigger");
}
this.initialThreadCount = initialThreadCount;
this.maxThreadCount = maxThreadCount;
this.requestQueueLimit = (requestQueueLimit < 0 ? DEFAULT_REQUEST_QUEUE_LIMIT : requestQueueLimit);
this.decayTime = dynamicThreadDecayTime;
this.newThreadTrigger = new TimeSpan(TimeSpan.TicksPerMillisecond * newThreadTrigger);
this.threadPriority = threadPriority;
this.requestQueue = new Queue(requestQueueLimit < 0 ? 4096 : requestQueueLimit);
if( poolName == null )
{
throw new ArgumentNullException("poolName", "Thread pool name cannot be null");
}
else
{
this.threadPoolName = poolName;
}
}
#endregion
private
readonly object threadPoolLock = new object();
#region ThreadPool properties
// The Priority & DynamicThreadDecay properties are not thread safe
// and can only be set before Start is called.
//
public ThreadPriority Priority
{
get { return(threadPriority); }
set
{
if( hasBeenStarted )
{
throw new InvalidOperationException("Cannot adjust thread priority after pool has been started.");
}
threadPriority = value;
}
}
public int DynamicThreadDecay
{
get { return(decayTime); }
set
{
if( hasBeenStarted )
{
throw new InvalidOperationException("Cannot adjust dynamic thread decay time after pool has been started.");
}
if( value <= 0 )
{
throw new ArgumentException("Dynamic thread decay time cannot be <= 0.", "value");
}
decayTime = value;
}
}
public int NewThreadTrigger
{
get { return((int)newThreadTrigger.TotalMilliseconds); }
set
{
if( value <= 0 )
{
throw new ArgumentException("New thread trigger time cannot be <= 0.", "value");
}
lock( this.threadPoolLock )
{
newThreadTrigger = new TimeSpan(TimeSpan.TicksPerMillisecond * value);
}
}
}
public int RequestQueueLimit
{
get { return(requestQueueLimit); }
set { requestQueueLimit = (value < 0 ? DEFAULT_REQUEST_QUEUE_LIMIT : value); }
}
public int AvailableThreads
{
get { return(maxThreadCount - currentThreadCount); }
}
public int MaxThreads
{
get { return(maxThreadCount); }
set
{
if( value < initialThreadCount )
{
throw new ArgumentException("Maximum thread count must be >= initial thread count.", "MaxThreads");
}
maxThreadCount = value;
}
}
public bool IsStarted
{
get { return(hasBeenStarted); }
}
public bool PropogateThreadPrincipal
{
get { return(propogateThreadPrincipal); }
set { propogateThreadPrincipal = value; }
}
public bool PropogateCallContext
{
get { return(propogateCallContext); }
set { propogateCallContext = value; }
}
public bool PropogateHttpContext
{
get { return(propogateHttpContext); }
set { propogateHttpContext = value; }
}
public bool PropogateCASMarkers
{
get { return(propogateCASMarkers); }
// When CompressedStack get/set is opened up,
// add the following setter back in.
//
// set { propogateCASMarkers = value; }
}
public bool IsBackground
{
get { return(useBackgroundThreads); }
set
{
if( hasBeenStarted )
{
throw new InvalidOperationException("Cannot adjust background status after pool has been started.");
}
useBackgroundThreads = value;
}
}
#endregion
#region ThreadPool events
public event ThreadPoolDelegate Started;
public event ThreadPoolDelegate Stopped;
#endregion
public void Start()
{
lock( this.threadPoolLock )
{
if( hasBeenStarted )
{
throw new InvalidOperationException("Pool has already been started.");
}
hasBeenStarted = true;
// Check to see if there were already items posted to the queue
// before Start was called. If so, reset their timestamps to
// the current time.
//
if( requestQueue.Count > 0 )
{
ResetWorkRequestTimes();
}
for( int n = 0; n < initialThreadCount; n++ )
{
ThreadWrapper thread =
new ThreadWrapper( this, true, threadPriority,
string.Format("{0} (static)", threadPoolName) );
thread.Start();
}
if( Started != null )
{
Started(); // TODO: reconsider firing this event while holding the lock...
}
}
}
#region ThreadPool.Stop and InternalStop
public void Stop()
{
InternalStop(false, Timeout.Infinite);
}
public void StopAndWait()
{
InternalStop(true, Timeout.Infinite);
}
public bool StopAndWait( int timeout )
{
return InternalStop(true, timeout);
}
private bool InternalStop( bool wait, int timeout )
{
if( !hasBeenStarted )
{
throw new InvalidOperationException("Cannot stop a thread pool that has not been started yet.");
}
lock(this.threadPoolLock)
{
Debug.WriteLine(string.Format( "[{0}, {1}] Stopping pool (# threads = {2})",
Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name,
currentThreadCount ));
stopInProgress = true;
Monitor.PulseAll(this);
}
if( wait )
{
bool stopComplete = WaitOne(timeout, true);
if( stopComplete )
{
// If the stop was successful, we can support being
// to be restarted. If the stop was requested, but not
// waited on, then we don't support restarting.
//
hasBeenStarted = false;
stopInProgress = false;
requestQueue.Clear();
stopCompleteEvent.Reset();
}
return(stopComplete);
}
return(true);
}
#endregion
#region ThreadPool.PostRequest(early bound)
// Overloads for the early bound WorkRequestDelegate-based targets.
//
public bool PostRequest( WorkRequestDelegate cb )
{
return PostRequest(cb, (object)null);
}
public bool PostRequest( WorkRequestDelegate cb, object state )
{
IWorkRequest notUsed;
return PostRequest(cb, state, out notUsed);
}
public bool PostRequest( WorkRequestDelegate cb, object state, out IWorkRequest reqStatus )
{
WorkRequest request =
new WorkRequest( cb, state,
propogateThreadPrincipal, propogateCallContext,
propogateHttpContext, propogateCASMarkers );
reqStatus = request;
return PostRequest(request);
}
#endregion
#region ThreadPool.PostRequest(late bound)
// Overloads for the late bound Delegate.DynamicInvoke-based targets.
//
public bool PostRequest( Delegate cb, object[] args )
{
IWorkRequest notUsed;
return PostRequest(cb, args, out notUsed);
}
public bool PostRequest( Delegate cb, object[] args, out IWorkRequest reqStatus )
{
WorkRequest request =
new WorkRequest( cb, args,
propogateThreadPrincipal, propogateCallContext,
propogateHttpContext, propogateCASMarkers );
reqStatus = request;
return PostRequest(request);
}
#endregion
// The actual implementation of PostRequest.
//
bool PostRequest( WorkRequest request )
{
lock(this.threadPoolLock)
{
// A requestQueueLimit of -1 means the queue is "unbounded"
// (subject to available resources). IOW, no artificial limit
// has been placed on the maximum # of requests that can be
// placed into the queue.
//
if( (requestQueueLimit == -1) || (requestQueue.Count < requestQueueLimit) )
{
try
{
requestQueue.Enqueue(request);
Monitor.Pulse(this);
return(true);
}
catch
{
}
}
}
return(false);
}
void ResetWorkRequestTimes()
{
lock( this.threadPoolLock )
{
DateTime newTime = DateTime.Now; // DateTime.Now.Add(pool.newThreadTrigger);
foreach( WorkRequest wr in requestQueue )
{
wr.workingTime = newTime;
}
}
}
#region Private ThreadPool constants
// Default parameters.
//
const int DEFAULT_DYNAMIC_THREAD_DECAY_TIME = 5 /* minutes */ * 60 /* sec/min */ * 1000 /* ms/sec */;
const int DEFAULT_NEW_THREAD_TRIGGER_TIME = 500; // milliseconds
const ThreadPriority DEFAULT_THREAD_PRIORITY = ThreadPriority.Normal;
const int DEFAULT_REQUEST_QUEUE_LIMIT = -1; // unbounded
#endregion
#region Private ThreadPool member variables
private bool hasBeenStarted = false;
private bool stopInProgress = false;
private readonly string threadPoolName;
private readonly int initialThreadCount; // Initial # of threads to create (called "static threads" in this class).
private int maxThreadCount; // Cap for thread count. Threads added above initialThreadCount are called "dynamic" threads.
private int currentThreadCount = 0; // Current # of threads in the pool (static + dynamic).
private int decayTime; // If a dynamic thread is idle for this period of time w/o processing work requests, it will exit.
private TimeSpan newThreadTrigger; // If a work request sits in the queue this long before being processed, a new thread will be added to queue up to the max.
private ThreadPriority threadPriority;
private ManualResetEvent stopCompleteEvent = new ManualResetEvent(false); // Signaled after Stop called and last thread exits.
private Queue requestQueue;
private int requestQueueLimit; // Throttle for maximum # of work requests that can be added.
private bool useBackgroundThreads = true;
private bool propogateThreadPrincipal = false;
private bool propogateCallContext = false;
private bool propogateHttpContext = false;
private bool propogateCASMarkers = false;
#endregion
#region ThreadPool.ThreadInfo
class ThreadInfo
{
public static ThreadInfo Capture( bool propogateThreadPrincipal, bool propogateCallContext,
bool propogateHttpContext, bool propogateCASMarkers )
{
return new ThreadInfo( propogateThreadPrincipal, propogateCallContext,
propogateHttpContext, propogateCASMarkers );
}
public static ThreadInfo Impersonate( ThreadInfo ti )
{
if( ti == null ) throw new ArgumentNullException("ti");
ThreadInfo prevInfo = Capture(true, true, true, true);
Restore(ti);
return(prevInfo);
}
public static void Restore( ThreadInfo ti )
{
if( ti == null ) throw new ArgumentNullException("ti");
// Restore call context.
//
if( miSetLogicalCallContext != null )
{
miSetLogicalCallContext.Invoke(Thread.CurrentThread, new object[]{ti.callContext});
}
// Restore HttpContext with the moral equivalent of
// HttpContext.Current = ti.httpContext;
//
CallContext.SetData(HttpContextSlotName, ti.httpContext);
// Restore thread identity. It's important that this be done after
// restoring call context above, since restoring call context also
// overwrites the current thread principal setting. If propogateCallContext
// and propogateThreadPrincipal are both true, then the following is redundant.
// However, since propogating call context requires the use of reflection
// to capture/restore call context, I want that behavior to be independantly
// switchable so that it can be disabled; while still allowing thread principal
// to be propogated. This also covers us in the event that call context
// propogation changes so that it no longer propogates thread principal.
//
Thread.CurrentPrincipal = ti.principal;
if( ti.compressedStack != null )
{
// TODO: Uncomment the following when Thread.SetCompressedStack is no longer guarded
// by a StrongNameIdentityPermission.
//
// Thread.CurrentThread.SetCompressedStack(ti.compressedStack);
}
}
private ThreadInfo( bool propogateThreadPrincipal, bool propogateCallContext,
bool propogateHttpContext, bool propogateCASMarkers )
{
if( propogateThreadPrincipal )
{
principal = Thread.CurrentPrincipal;
}
if( propogateHttpContext )
{
httpContext = HostContext.Current;
}
if( propogateCallContext && (miGetLogicalCallContext != null) )
{
callContext = (LogicalCallContext)miGetLogicalCallContext.Invoke(Thread.CurrentThread, null);
callContext = (LogicalCallContext)callContext.Clone();
// TODO: consider serialize/deserialize call context to get a MBV snapshot
// instead of leaving it up to the Clone method.
}
if( propogateCASMarkers )
{
// TODO: Uncomment the following when Thread.GetCompressedStack is no longer guarded
// by a StrongNameIdentityPermission.
//
// compressedStack = Thread.CurrentThread.GetCompressedStack();
}
}
IPrincipal principal;
LogicalCallContext callContext;
CompressedStack compressedStack = null; // Always null until Get/SetCompressedStack are opened up.
HostContext httpContext;
// Cached type information.
//
const BindingFlags bfNonPublicInstance = BindingFlags.Instance | BindingFlags.NonPublic;
const BindingFlags bfNonPublicStatic = BindingFlags.Static | BindingFlags.NonPublic;
static MethodInfo miGetLogicalCallContext =
typeof(Thread).GetMethod("GetLogicalCallContext", bfNonPublicInstance);
static MethodInfo miSetLogicalCallContext =
typeof(Thread).GetMethod("SetLogicalCallContext", bfNonPublicInstance);
static string HttpContextSlotName;
static ThreadInfo()
{
// Lookup the value of HttpContext.CallContextSlotName (if it exists)
// to see what the name of the call context slot is where HttpContext.Current
// is stashed. As a fallback, if this field isn't present anymore, just
// try for the original "HttpContext" slot name.
//
FieldInfo fi = typeof(HostContext).GetField("CallContextSlotName", bfNonPublicStatic);
if( fi != null )
{
HttpContextSlotName = (string)fi.GetValue(null);
}
else
{
HttpContextSlotName = "HttpContext";
}
}
}
#endregion
#region ThreadPool.WorkRequest
class WorkRequest : IWorkRequest
{
internal const int PENDING = 0;
internal const int PROCESSED = 1;
internal const int CANCELLED = 2;
public WorkRequest( WorkRequestDelegate cb, object arg,
bool propogateThreadPrincipal, bool propogateCallContext,
bool propogateHttpContext, bool propogateCASMarkers )
{
targetProc = cb;
procArg = arg;
procArgs = null;
Initialize( propogateThreadPrincipal, propogateCallContext,
propogateHttpContext, propogateCASMarkers );
}
public WorkRequest( Delegate cb, object[] args,
bool propogateThreadPrincipal, bool propogateCallContext,
bool propogateHttpContext, bool propogateCASMarkers )
{
targetProc = cb;
procArg = null;
procArgs = args;
Initialize( propogateThreadPrincipal, propogateCallContext,
propogateHttpContext, propogateCASMarkers );
}
void Initialize( bool propogateThreadPrincipal, bool propogateCallContext,
bool propogateHttpContext, bool propogateCASMarkers )
{
workingTime = timeStampStarted = DateTime.Now;
threadInfo = ThreadInfo.Capture( propogateThreadPrincipal, propogateCallContext,
propogateHttpContext, propogateCASMarkers );
}
public bool Cancel()
{
// If the work request was pending, mark it cancelled. Otherwise,
// this method was called too late. Note that this call can
// cancel an operation without any race conditions. But if the
// result of this test-and-set indicates the request is in the
// "processed" state, it might actually be about to be processed.
//
return(Interlocked.CompareExchange(ref state, CANCELLED, PENDING) == PENDING);
}
internal Delegate targetProc; // Function to call.
internal object procArg; // State to pass to function.
internal object[] procArgs; // Used with Delegate.DynamicInvoke.
internal DateTime timeStampStarted; // Time work request was originally enqueued (held constant).
internal DateTime workingTime; // Current timestamp used for triggering new threads (moving target).
internal ThreadInfo threadInfo; // Everything we know about a thread.
internal int state = PENDING; // The state of this particular request.
}
#endregion
#region ThreadPool.ThreadWrapper
class ThreadWrapper
{
private ThreadPool pool;
private
readonly object poolLock = new object();
private bool isPermanent;
private ThreadPriority priority;
private string name;
public ThreadWrapper( ThreadPool pool, bool isPermanent,
ThreadPriority priority, string name )
{
this.pool = pool;
this.isPermanent = isPermanent;
this.priority = priority;
this.name = name;
lock( this.poolLock )
{
// Update the total # of threads in the pool.
//
pool.currentThreadCount++;
}
}
public void Start()
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.SetApartmentState(ApartmentState.MTA);
t.Name = name;
t.Priority = priority;
t.IsBackground = pool.useBackgroundThreads;
t.Start();
}
void ThreadProc()
{
Debug.WriteLine(string.Format( "[{0}, {1}] Worker thread started",
Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name ));
bool done = false;
while( !done )
{
WorkRequest wr = null;
ThreadWrapper newThread = null;
lock( this.poolLock )
{
// As long as the request queue is empty and a shutdown hasn't
// been initiated, wait for a new work request to arrive.
//
bool timedOut = false;
while( !pool.stopInProgress && !timedOut && (pool.requestQueue.Count == 0) )
{
if( !Monitor.Wait(pool, (isPermanent ? Timeout.Infinite : pool.decayTime)) )
{
// Timed out waiting for something to do. Only dynamically created
// threads will get here, so bail out.
//
timedOut = true;
}
}
// We exited the loop above because one of the following conditions
// was met:
// - ThreadPool.Stop was called to initiate a shutdown.
// - A dynamic thread timed out waiting for a work request to arrive.
// - There are items in the work queue to process.
// If we exited the loop because there's work to be done,
// a shutdown hasn't been initiated, and we aren't a dynamic thread
// that timed out, pull the request off the queue and prepare to
// process it.
//
if( !pool.stopInProgress && !timedOut && (pool.requestQueue.Count > 0) )
{
wr = (WorkRequest)pool.requestQueue.Dequeue();
Debug.Assert(wr != null);
// Check to see if this work request languished in the queue
// very long. If it was in the queue >= the new thread trigger
// time, and if we haven't reached the max thread count cap,
// add a new thread to the pool.
//
// If the decision is made, create the new thread object (updating
// the current # of threads in the pool), but defer starting the new
// thread until the lock is released.
//
TimeSpan requestTimeInQ = DateTime.Now.Subtract(wr.workingTime);
if( (requestTimeInQ >= pool.newThreadTrigger) && (pool.currentThreadCount < pool.maxThreadCount) )
{
// Note - the constructor for ThreadWrapper will update
// pool.currentThreadCount.
//
newThread =
new ThreadWrapper( pool, false, priority,
string.Format("{0} (dynamic)", pool.threadPoolName) );
// Since the current request we just dequeued is stale,
// everything else behind it in the queue is also stale.
// So reset the timestamps of the remaining pending work
// requests so that we don't start creating threads
// for every subsequent request.
//
pool.ResetWorkRequestTimes();
}
}
else
{
// Should only get here if this is a dynamic thread that
// timed out waiting for a work request, or if the pool
// is shutting down.
//
Debug.Assert((timedOut && !isPermanent) || pool.stopInProgress);
pool.currentThreadCount--;
if( pool.currentThreadCount == 0 )
{
// Last one out turns off the lights.
//
Debug.Assert(pool.stopInProgress);
if( pool.Stopped != null )
{
pool.Stopped();
}
pool.stopCompleteEvent.Set();
}
done = true;
}
} // lock
// No longer holding pool lock here...
if( !done && (wr != null) )
{
// Check to see if this request has been cancelled while
// stuck in the work queue.
//
// If the work request was pending, mark it processed and proceed
// to handle. Otherwise, the request must have been cancelled
// before we plucked it off the request queue.
//
if( Interlocked.CompareExchange(ref wr.state, WorkRequest.PROCESSED, WorkRequest.PENDING) != WorkRequest.PENDING )
{
// Request was cancelled before we could get here.
// Bail out.
continue;
}
if( newThread != null )
{
Debug.WriteLine(string.Format( "[{0}, {1}] Adding dynamic thread to pool",
Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name ));
newThread.Start();
}
// Dispatch the work request.
//
ThreadInfo originalThreadInfo = null;
try
{
// Impersonate (as much as possible) what we know about
// the thread that issued the work request.
//
originalThreadInfo = ThreadInfo.Impersonate(wr.threadInfo);
WorkRequestDelegate targetProc = wr.targetProc as WorkRequestDelegate;
if( targetProc != null )
{
targetProc(wr.procArg, wr.timeStampStarted);
}
else
{
wr.targetProc.DynamicInvoke(wr.procArgs);
}
}
catch( Exception e )
{
Debug.WriteLine(string.Format("Exception thrown performing callback:\n{0}\n{1}", e.Message, e.StackTrace));
}
finally
{
// Restore our worker thread's identity.
//
ThreadInfo.Restore(originalThreadInfo);
}
}
}
Debug.WriteLine(string.Format( "[{0}, {1}] Worker thread exiting pool",
Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name ));
}
}
#endregion
}
#endregion
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the AutTipoPNP class.
/// </summary>
[Serializable]
public partial class AutTipoPNPCollection : ActiveList<AutTipoPNP, AutTipoPNPCollection>
{
public AutTipoPNPCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>AutTipoPNPCollection</returns>
public AutTipoPNPCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
AutTipoPNP o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Aut_TipoPNP table.
/// </summary>
[Serializable]
public partial class AutTipoPNP : ActiveRecord<AutTipoPNP>, IActiveRecord
{
#region .ctors and Default Settings
public AutTipoPNP()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public AutTipoPNP(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public AutTipoPNP(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public AutTipoPNP(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Aut_TipoPNP", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdTipoPMP = new TableSchema.TableColumn(schema);
colvarIdTipoPMP.ColumnName = "idTipoPMP";
colvarIdTipoPMP.DataType = DbType.Int32;
colvarIdTipoPMP.MaxLength = 0;
colvarIdTipoPMP.AutoIncrement = false;
colvarIdTipoPMP.IsNullable = false;
colvarIdTipoPMP.IsPrimaryKey = true;
colvarIdTipoPMP.IsForeignKey = false;
colvarIdTipoPMP.IsReadOnly = false;
colvarIdTipoPMP.DefaultSetting = @"";
colvarIdTipoPMP.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdTipoPMP);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "Nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 50;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = true;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Aut_TipoPNP",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdTipoPMP")]
[Bindable(true)]
public int IdTipoPMP
{
get { return GetColumnValue<int>(Columns.IdTipoPMP); }
set { SetColumnValue(Columns.IdTipoPMP, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdTipoPMP,string varNombre)
{
AutTipoPNP item = new AutTipoPNP();
item.IdTipoPMP = varIdTipoPMP;
item.Nombre = varNombre;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdTipoPMP,string varNombre)
{
AutTipoPNP item = new AutTipoPNP();
item.IdTipoPMP = varIdTipoPMP;
item.Nombre = varNombre;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdTipoPMPColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdTipoPMP = @"idTipoPMP";
public static string Nombre = @"Nombre";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// This file is part of the OWASP O2 Platform (http://www.owasp.org/index.php/OWASP_O2_Platform) and is released under the Apache 2.0 License (http://www.apache.org/licenses/LICENSE-2.0)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Threading;
namespace FluentSharp.CoreLib.API
{
public class KReflection //: IReflection
{
public bool verbose { get; set; }
public const BindingFlags BindingFlagsAll = BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static;
public const BindingFlags BindingFlagsAllDeclared = BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static |
BindingFlags.DeclaredOnly;
#region get
public PropertyInfo getPropertyInfo(String sPropertyToGet, Type targetType)
{
return getPropertyInfo(sPropertyToGet, targetType, false);
}
public PropertyInfo getPropertyInfo(String sPropertyToGet, Type targetType, bool bVerbose)
{
try
{
/*var targetType = (oTargetObject is Type)
? ((Type) oTargetObject)
: oTargetObject.GetType();*/
return targetType.GetProperty(sPropertyToGet,
BindingFlags.GetProperty |
BindingFlags.NonPublic | BindingFlags.Public |
BindingFlags.Instance | BindingFlags.Static);
}
catch (Exception ex)
{
if (bVerbose)
PublicDI.log.error("in reflection.getPropertyInfo: {0} ", ex.Message);
return null;
}
}
public Object getProperty(String typeName, String propertyName, object liveObject)
{
Object result = null;
var type = getType(typeName);
if (type != null)
{
var propertyInfo = PublicDI.reflection.getPropertyInfo(propertyName, type);
if (propertyInfo != null)
result = getProperty(propertyInfo, propertyName);
}
return result;
}
public Object getProperty(PropertyInfo propertyToGet)
{
return getProperty(propertyToGet, null);
}
public Object getProperty(PropertyInfo propertyInfo, object liveObject)
{
try
{
return propertyInfo.GetValue(liveObject,
BindingFlags.GetProperty |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static, null,
new object[] {},null);
}
catch (Exception ex)
{
PublicDI.log.error("in reflection.getProperty: {0} ", ex.Message);
return null;
}
}
public Object getProperty(String sPropertyToGet, Object oTargetObject)
{
return getProperty(sPropertyToGet, oTargetObject, false);
}
public Object getProperty(String sPropertyToGet, Object oTargetObject, bool bVerbose)
{
try
{
if (oTargetObject == null)
return null;
var targetType = (oTargetObject is Type)
? ((Type)oTargetObject)
: oTargetObject.GetType();
var propertyInfo = getPropertyInfo(sPropertyToGet, targetType, bVerbose);
if (null == propertyInfo)
{
if (bVerbose)
PublicDI.log.error(
"in getProperty, desired property ({0}) doesn't exist in the target object's class {1} ",
sPropertyToGet, oTargetObject.GetType().FullName);
}
else
return targetType.InvokeMember(sPropertyToGet,
BindingFlags.GetProperty |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static, null,
oTargetObject, new object[] { });
}
catch (Exception ex)
{
if (bVerbose)
PublicDI.log.error("in reflection.getInstance: {0} ", ex.Message);
}
return null;
}
public Object getInstance(Type tTypeToCreate)
{
try
{
return tTypeToCreate.InvokeMember("",
BindingFlags.Public | BindingFlags.Instance |
BindingFlags.CreateInstance, null, null, new object[] {});
}
catch (Exception ex)
{
PublicDI.log.error("in reflection.getInstance: {0} ", ex.Message);
return null;
}
}
public List<Module> getModules(Assembly assembly)
{
return (assembly!=null) ? new List<Module>(assembly.GetModules()) : new List<Module>();
}
public List<Type> getTypes(Assembly assembly)
{
var types = new List<Type>();
try
{
foreach (Module module in getModules(assembly))
types.AddRange(module.GetTypes());
return types;
}
catch (ReflectionTypeLoadException ex)
{
PublicDI.log.error("in Reflection.getTypes for assembly {0}got error: {1}", assembly.GetName(),
ex.Message);
foreach (Exception loaderExpection in ex.LoaderExceptions)
PublicDI.log.error(" LoaderException {0}", loaderExpection.Message);
}
return types;
}
public List<Type> getTypes(Module module)
{
return new List<Type>(module.GetTypes());
}
public List<Type> getTypes(Type type)
{
return type.isNull() ? new List<Type>() : new List<Type>(type.GetNestedTypes());
}
public Type getType(string assemblyName, string typeToFind)
{
Assembly assembly = getAssembly(assemblyName);
if (assembly != null)
return getType(assembly, typeToFind);
return null;
}
public Type getType(Assembly assembly, string typeToFind)
{
if (assembly != null && false == string.IsNullOrEmpty(typeToFind))
{
if (assembly.GetType(typeToFind) != null)
return assembly.GetType(typeToFind);
foreach (Type type in getTypes(assembly))
if (type.FullName == typeToFind || type.Name == typeToFind)
return type;
}
return null;
}
public Type getType(Type type, string typeToFind)
{
if (type != null && false == string.IsNullOrEmpty(typeToFind))
foreach (Type nestedType in type.GetNestedTypes())
if (nestedType.FullName == typeToFind || nestedType.Name == typeToFind)
return type;
return null;
}
public Type getType(string typeToFind)
{
foreach (var assembly in getAssembliesInCurrentAppDomain())
{
var type = getType(assembly, typeToFind);
if (type != null)
return type;
}
if (PublicDI.log != null)
PublicDI.log.info("In KReflection.getType, could not find the requested type in all appDomain assemblies: {0}", typeToFind);
return null;
}
// this is an example of using dynamic reflection so that we don't have to add reference to O2_Kernel.dll
//tip (to document): the code below can also be represented like this
//var typeName = "Microsoft.VisualBasic".assembly().type("Information").invoke("TypeName");
// or
//var typeName = "Microsoft.VisualBasic".type("Information").invoke("TypeName");
public string getComObjectTypeName(object _object)
{
var assembly = PublicDI.reflection.getAssembly("Microsoft.VisualBasic");
if (assembly != null)
{
var type = PublicDI.reflection.getType(assembly, "Information");
if (type != null)
{
var method = PublicDI.reflection.getMethod(type, "TypeName");
if (method != null)
{
var typeName = PublicDI.reflection.invoke(method, new [] {_object});
if (typeName is string)
return typeName.ToString();
}
}
}
return null;
}
public List<MethodInfo> getMethods(string pathToassemblyToProcess)
{
return getMethods(getAssembly(pathToassemblyToProcess));
}
public List<MethodInfo> getMethods(Assembly assembly)
{
var methods = new List<MethodInfo>();
foreach (Type type in getTypes(assembly))
methods.AddRange(type.GetMethods(BindingFlagsAllDeclared));
return methods;
}
public List<MethodInfo> getMethods(Type type, Attribute attribute)
{
var methods = getMethods(type);
var results = new List<MethodInfo>();
try
{
foreach (var method in methods)
{
var attributes = getAttributes(method);
if (attributes.Contains(attribute))
results.Add(method);
}
}
catch (Exception ex)
{
ex.log("in KReflection.getMethods(Type type, Attribute attribute)");
}
return results;
}
public Attribute getAttribute(MethodInfo method, Type type)
{
var attributes = getAttributes(method);
foreach (var attribute in attributes)
if (attribute.GetType() == type)
return attribute;
return null;
}
public List<Attribute> getAttributes(MethodInfo methodInfo)
{
var attributes = new List<Attribute>();
foreach(var attribute in methodInfo.GetCustomAttributes(true))
if (attribute is Attribute)
attributes.Add((Attribute)attribute);
return attributes;
}
public List<Attribute> getAttributes(Type targetType)
{
var attributes = new List<Attribute>();
foreach(var attribute in targetType.GetCustomAttributes(true))
if (attribute is Attribute)
attributes.Add((Attribute)attribute);
return attributes;
}
public List<Attribute> getAttributes(Assembly assembly)
{
var attributes = new List<Attribute>();
foreach(var attribute in assembly.GetCustomAttributes(true))
if (attribute is Attribute)
attributes.Add((Attribute)attribute);
return attributes;
}
public List<MethodInfo> getMethods(Type type, BindingFlags bindingFlags)
{
return (type== null)? new List<MethodInfo>() : new List<MethodInfo>(type.GetMethods(bindingFlags));
}
public List<MethodInfo> getMethods(Type type)
{
return (type == null) ? new List<MethodInfo>() : new List<MethodInfo>(type.GetMethods(BindingFlagsAllDeclared));
}
public MethodInfo getMethod(string pathToAssembly, string methodName)
{
return getMethod(pathToAssembly, methodName, new object[0]);
}
public MethodInfo getMethod(string pathToAssembly, string methodName, object[] methodParameters)
{
try
{
foreach (Type type in getTypes(getAssembly(pathToAssembly)))
{
MethodInfo methodInfo = getMethod(type, methodName, (methodParameters ?? new object[0]));
if (methodInfo != null)
return methodInfo;
}
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "imn getMethod");
}
return null;
}
/// <summary>
/// This will return the first method in control Type that matches the methodName
/// </summary>
/// <param name="controlType"></param>
/// <param name="methodName"></param>
/// <returns></returns>
public MethodInfo getMethod(Type controlType, string methodName)
{
if (controlType !=null)
{
foreach (var method in PublicDI.reflection.getMethods(controlType))
if (method.Name == methodName)
return method;
}
return null;
}
public MethodInfo getMethod(Type type, string methodName, object[] methodParameters)
{
return type.GetMethod(methodName,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance |
BindingFlags.Static, null, GetObjectsTypes(methodParameters).ToArray(), null);
}
public List<string> getParametersName(MethodInfo method)
{
var parametersType = new List<string>();
if (method!= null)
foreach(var parameter in method.GetParameters())
parametersType.Add(parameter.Name);
return parametersType;
}
public List<Type> getParametersType(MethodInfo method)
{
var parametersType = new List<Type>();
if (method != null)
foreach (var parameter in method.GetParameters())
parametersType.Add(parameter.ParameterType);
return parametersType;
}
public List<ParameterInfo> getParameters(MethodInfo method)
{
var parametersType = new List<ParameterInfo>();
if (method != null)
parametersType.AddRange(method.GetParameters());
return parametersType;
}
public List<Type> GetObjectsTypes(object[] objectsToGetType)
{
var types = new List<Type>();
if (objectsToGetType != null)
foreach (object objectToGetType in objectsToGetType)
if (objectToGetType!=null)
types.Add(objectToGetType.GetType());
return types;
}
public List<MemberInfo> getMembers(Assembly assembly)
{
var members = new List<MemberInfo>();
foreach (Type type in getTypes(assembly))
members.AddRange(type.GetMembers());
return members;
}
public List<MemberInfo> getMembers(Type type)
{
return new List<MemberInfo>(type.GetMembers());
}
public List<FieldInfo> getFields(Type type)
{
try
{
return new List<FieldInfo>(type.GetFields(BindingFlagsAllDeclared));
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in Reflection.getFields");
return new List<FieldInfo>();
}
}
public FieldInfo getField(Type type, string fieldName)
{
var fields = getFields(type);
foreach (var field in fields)
if (field.Name.Contains(fieldName))
return field;
return null;
}
public Object getFieldValue(FieldInfo fieldToGet, Object oTargetObject)
{
return fieldToGet.GetValue(oTargetObject);
}
public Object getFieldValue(String sFieldToGet, Object oTargetObject)
{
if (oTargetObject != null)
{
FieldInfo fiFieldInfo = oTargetObject.GetType().GetField(sFieldToGet,
BindingFlags.GetField |
BindingFlags.NonPublic |
BindingFlags.Public | BindingFlags.Instance |
BindingFlags.Static);
if (fiFieldInfo != null)
return fiFieldInfo.GetValue(oTargetObject);
}
return null;
}
public List<PropertyInfo> getProperties(Object targetObject)
{
return (targetObject != null) ? getProperties(targetObject.GetType()) : new List<PropertyInfo>();
}
public List<PropertyInfo> getProperties(Type type)
{
var properties = new List<PropertyInfo>();
if (type!=null)
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static))
{
//if (property.IsSpecialName == false)
properties.Add(property);
}
return properties;
//return (type!=null) ? new List<PropertyInfo>(
// ) : new List<PropertyInfo>();
}
public Dictionary<string, List<Type>> getDictionaryWithTypesMappedToNamespaces(Module module)
{
var typesMappedToNamespaces = new Dictionary<string, List<Type>>();
foreach (Type type in getTypes(module))
{
string typeNamespace = type.Namespace;
if (typeNamespace == null)
{
if (!typesMappedToNamespaces.ContainsKey(""))
typesMappedToNamespaces.Add("", new List<Type>());
typesMappedToNamespaces[""].Add(type);
}
else
{
if (!typesMappedToNamespaces.ContainsKey(typeNamespace))
typesMappedToNamespaces.Add(typeNamespace, new List<Type>());
typesMappedToNamespaces[typeNamespace].Add(type);
}
}
return typesMappedToNamespaces;
}
public Assembly getAssembly(string pathToAssemblyToLoad)
{
return loadAssembly(pathToAssemblyToLoad);
}
public Assembly getCurrentAssembly()
{
return Assembly.GetExecutingAssembly();
}
public List<Assembly> getAssembliesInCurrentAppDomain()
{
return new List<Assembly>(AppDomain.CurrentDomain.GetAssemblies());
}
public object[] getRealObjects(object[] objectsToConvert)
{
var realObjects = new List<object>();
if (objectsToConvert!=null)
foreach (object objectToConvert in objectsToConvert)
if (objectToConvert is O2Object)
realObjects.Add(((O2Object) objectToConvert).Obj);
else
realObjects.Add(objectToConvert);
return realObjects.ToArray();
}
public List<MethodInfo> getTypesWithAttribute(Assembly assembly, Type attributeType)
{
var methods = new List<MethodInfo>();
if (assembly != null)
{ }
return methods;
}
public List<MethodInfo> getMethodsWithAttribute(Assembly assembly, Type attributeType)
{
var methods = new List<MethodInfo>();
return methods;
}
public List<MethodInfo> getMethodsWithAttribute(Type targetType, Type attributeType)
{
var methods = new List<MethodInfo>();
return methods;
}
/* public Object getLiveObject(object liveObject, string typeToFind)
{
return null;
}*/
#endregion
#region set
public bool setField(FieldInfo fieldToSet, object fieldValue)
{
return setField(fieldToSet, null, fieldValue);
}
public bool setField(FieldInfo fieldToSet, object liveObject, object fieldValue)
{
try
{
fieldToSet.SetValue(liveObject, fieldValue,
BindingFlags.SetField | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null,
// ReSharper disable AssignNullToNotNullAttribute
default(CultureInfo));
// ReSharper restore AssignNullToNotNullAttribute
return true;
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in Reflection.setField");
}
return false;
}
public bool setField(String fieldToSet, Type targetType, object fieldValue)
{
try
{
if (targetType != null)
targetType.InvokeMember(fieldToSet,
BindingFlags.SetField | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Static, null,
targetType, new[] { fieldValue });
return true;
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in Reflection.setField");
}
return false;
}
public bool setField(String fieldToSet, object targetObject, object fieldValue)
{
try
{
if (targetObject != null)
targetObject.GetType().InvokeMember(fieldToSet,
BindingFlags.SetField | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance, null,
targetObject, new[] { fieldValue });
return true;
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in Reflection.setProperty");
}
return false;
}
public bool setProperty(PropertyInfo propertyToSet, object propertyValue)
{
return setProperty(propertyToSet, null, propertyValue);
}
public bool setProperty(PropertyInfo propertyToSet, object liveObject, object propertyValue)
{
try
{
propertyToSet.SetValue(liveObject,propertyValue,
BindingFlags.SetProperty | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null,null,
// ReSharper disable AssignNullToNotNullAttribute
null );
// ReSharper restore AssignNullToNotNullAttribute
return true;
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in Reflection.setProperty");
}
return false;
}
public bool setProperty(String propertyToSet, Type targetType, object propertyValue)
{
try
{
var propertyInfo = getPropertyInfo(propertyToSet, targetType);
if (propertyInfo == null)
PublicDI.log.error("in setProperty, could not find property {0} in type {1}", propertyToSet, targetType.FullName);
else
return setProperty(propertyInfo, propertyValue);
/*return false;
if (targetType != null)
targetType.InvokeMember(propertyToSet,
BindingFlags.SetProperty | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null,
targetType, new[] {propertyValue});
return true;*/
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in Reflection.setProperty");
}
return false;
}
public bool setProperty(String sPropertyToSet, object oTargetObject, object propertyValue)
{
try
{
if (oTargetObject != null)
oTargetObject.GetType().InvokeMember(sPropertyToSet,
BindingFlags.SetProperty | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance, null,
oTargetObject, new[] {propertyValue});
return true;
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in Reflection.setProperty");
}
return false;
}
#endregion
#region load
public Assembly loadAssembly(string assemblyToLoad)
{
try
{
if (AssemblyResolver.CachedMappedAssemblies.hasKey(assemblyToLoad))
{
var cachedAssembly = AssemblyResolver.CachedMappedAssemblies[assemblyToLoad];
return cachedAssembly;
}
Assembly assembly = AssemblyResolver.loadFromDiskOrResource(assemblyToLoad);
if (assembly != null)
{
AssemblyResolver.CachedMappedAssemblies.add(assemblyToLoad, assembly);
AssemblyResolver.CachedMappedAssemblies.add(assembly.FullName, assembly); // this has side effects on dynamic code scanning
AssemblyResolver.CachedMappedAssemblies.add(assembly.GetName().Name, assembly);
return assembly;
}
// try with load method #1
#pragma warning disable 618
try
{
assembly = Assembly.LoadWithPartialName(assemblyToLoad);
if (assembly.isNull() && assemblyToLoad.lower().ends(".dll") || assemblyToLoad.lower().ends(".exe"))
{
assembly = Assembly.LoadWithPartialName(assemblyToLoad.fileName_WithoutExtension());
}
}
catch { }
#pragma warning restore 618
if (assembly.isNull())
{
// try with load method #2
try
{
//if (System.IO.File.Exists(assemblyToLoad) == false &&
// System.IO.File.Exists(System.IO.Path.Combine( PublicDI.config.CurrentExecutableDirectory,assemblyToLoad))) // if this assembly is not on the current executable folder
// new O2GitHub().tryToFetchAssemblyFromO2GitHub(assemblyToLoad);
//assembly = Assembly.Load(assemblyToLoad);
assembly = Assembly.LoadFrom(assemblyToLoad);
}
catch //(Exception ex1)
{
// try with load method #3
try
{
assembly = Assembly.Load(AssemblyName.GetAssemblyName(assemblyToLoad).FullName);
}
catch// (Exception ex2)
{
// try with load method #4
try
{
assembly = Assembly.Load(assemblyToLoad);
}
catch //(Exception ex3)
{
// PublicDI.log.error("in loadAssembly (Assembly.LoadFrom) :{0}", ex1.Message);
// PublicDI.log.error("in loadAssembly (Assembly.Load) :{0}", ex2.Message);
// PublicDI.log.error("in loadAssembly (Assembly.LoadWithPartialName) :{0}", ex3.Message);
}
}
}
}
if (assembly != null)
{
AssemblyResolver.CachedMappedAssemblies.add(assemblyToLoad, assembly);
AssemblyResolver.CachedMappedAssemblies.add(assembly.FullName, assembly);
AssemblyResolver.CachedMappedAssemblies.add(assembly.GetName().Name, assembly);
return assembly;
}
}
catch (Exception ex)
{
"[loadAssembly] {0}".error(ex.Message);
}
PublicDI.log.info("could not load/find assembly ('{0}')",assemblyToLoad);
//PublicDI.log.error("load using partial name ('{0}') returned null",assemblyToLoad);
return null;
}
public bool loadAssemblyAndCheckIfAllTypesCanBeLoaded(string assemblyFile)
{
try
{
Assembly reflectionAssembly = getAssembly(assemblyFile);
List<Type> reflectionTypes = getTypes(reflectionAssembly);
if (reflectionTypes != null)
return true;
}
catch (Exception ex)
{
PublicDI.log.error("in loadAssemblyAndCheckIfAllTypesCanBeLoaded:{0}", ex.Message);
}
return false;
}
#endregion
#region invoke
public Thread invokeASync(MethodInfo methodInfo, Action<object> onMethodExecutionCompletion)
{
return O2Thread.mtaThread(
() =>
{
var result = invokeMethod_Static(methodInfo);
onMethodExecutionCompletion(result);
});
}
public Thread invokeASync(object oLiveObject, MethodInfo methodInfo, Action<object> onMethodExecutionCompletion)
{
return invokeASync(oLiveObject, methodInfo, null, onMethodExecutionCompletion);
}
public Thread invokeASync(object oLiveObject, MethodInfo methodInfo, object[] methodParameters, Action<object> onMethodExecutionCompletion)
{
return O2Thread.mtaThread(
() =>
{
try
{
//var result = invoke(oLiveObject, methodInfo, methodParameters);
var result = methodInfo.Invoke(oLiveObject, methodParameters);
onMethodExecutionCompletion(result);
}
catch (Exception ex)
{
//PublicDI.log.ex(ex, "in reflection.invokeASync", true);
PublicDI.log.error("in reflection.invokeASync: {0}", ex.Message);
var exceptionMessage = "Exception occured during invocation of method: " + methodInfo.Name;
exceptionMessage += " Exception.Message: " + ex.Message;
if (ex.InnerException != null)
exceptionMessage += " InnerException.Message: " + ex.InnerException.Message;
onMethodExecutionCompletion(exceptionMessage);
}
});
}
public bool invokeMethod_returnSucess(Object oLiveObject, String sMethodToInvoke, Object[] oParams)
{
try
{
oLiveObject.GetType().InvokeMember(sMethodToInvoke,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static |
BindingFlags.Instance | BindingFlags.InvokeMethod, null, oLiveObject,
(oParams ?? new object[0]));
return true;
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in reflection..invokeMethod", true);
//log.error("in reflection.invokeMethod: {0} ", ex.Message);
return false;
}
}
public object invoke(MethodInfo methodInfo)
{
if (methodInfo.IsStatic)
return invokeMethod_Static(methodInfo);
return invokeMethod_Instance(methodInfo);
}
/// <summary>
/// invokes static or instance method
/// (for instance methods, the default constructor will be used to create the method's class)
/// </summary>
/// <param name="methodInfo"></param>
/// <param name="methodParameters"></param>
/// <returns></returns>
public object invoke(MethodInfo methodInfo, object[] methodParameters)
{
try
{
if (methodInfo.IsStatic)
return invoke(null, methodInfo, methodParameters);
object oLiveObject = createObjectUsingDefaultConstructor(methodInfo.ReflectedType);
return invoke(oLiveObject, methodInfo, methodParameters);
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in reflection.invokeMethod_InstanceStaticPublicNonPublic", true);
}
return null;
}
public object invoke(object oLiveObject, MethodInfo methodInfo)
{
return invoke(oLiveObject, methodInfo, new object[] {});
}
public object invoke(object oLiveObject, MethodInfo methodInfo, object[] methodParameters)
{
try
{
// ReSharper disable AssignNullToNotNullAttribute
return methodInfo.Invoke(oLiveObject, BindingFlags.OptionalParamBinding , null, methodParameters, null);
// ReSharper restore AssignNullToNotNullAttribute
}
catch (Exception ex)
{
if (ex is TargetParameterCountException || ex is MissingMethodException || ex is ArgumentException)
{
//Hack: to deal with weird reflection behaviour that happens when the parameter is an array
methodParameters = new object[] { methodParameters };
try
{
// ReSharper disable AssignNullToNotNullAttribute
return methodInfo.Invoke(oLiveObject, BindingFlags.OptionalParamBinding, null, methodParameters, null);
// ReSharper restore AssignNullToNotNullAttribute
}
catch (Exception ex2)
{
PublicDI.log.ex(ex2, "in reflection.invoke", true);
return null;
}
}
PublicDI.log.ex(ex, "in reflection.invoke", true);
return null;
}
}
public object invoke(object oLiveObject, string sMethodToInvoke, object[] methodParameters)
{
return invokeMethod_InstanceStaticPublicNonPublic(oLiveObject, sMethodToInvoke, methodParameters);
}
public object invokeMethod_InstanceStaticPublicNonPublic(object oLiveObject, string sMethodToInvoke,
object[] methodParameters)
{
try
{
return oLiveObject.GetType().InvokeMember(sMethodToInvoke,
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.Instance |
BindingFlags.InvokeMethod, null, oLiveObject, (methodParameters ?? new object[0]));
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in reflection.invokeMethod_InstanceStaticPublicNonPublic", true);
return null;
}
}
public object invokeMethod_Instance(MethodInfo methodInfo)
{
try
{
PublicDI.log.info("Executing Instance Method:{0}", methodInfo.Name);
var liveObject = PublicDI.reflection.createObjectUsingDefaultConstructor(methodInfo.DeclaringType);
if (liveObject != null)
return invoke(liveObject, methodInfo);
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in invokeMethod_Instance: ");
}
return null;
}
public Object invokeMethod_Static(MethodInfo methodToExecute)
{
return invokeMethod_Static(methodToExecute, null);
}
public Object invokeMethod_Static(MethodInfo methodToExecute ,object[] oParams)
{
try
{
return methodToExecute.Invoke(null,
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.InvokeMethod, null,
(oParams ?? new object[0]),
// ReSharper disable AssignNullToNotNullAttribute
null);
// ReSharper restore AssignNullToNotNullAttribute
}
catch (Exception ex)
{
if (ex is TargetParameterCountException || ex is MissingMethodException || ex is ArgumentException)
{
try
{
//HACK: deal with the problem of invoking into a method with an array as a parameter
oParams = new object[] { oParams };
return methodToExecute.Invoke(null,
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.InvokeMethod, null,
(oParams),
// ReSharper disable AssignNullToNotNullAttribute
null);
// ReSharper restore AssignNullToNotNullAttribute
}
catch (Exception ex2)
{
PublicDI.log.ex(ex2, "in reflection..invokeMethod_Static", true);
return null;
}
}
PublicDI.log.ex(ex, "in reflection..invokeMethod_Static", true);
return null;
}
}
public Object invokeMethod_Static(Type tMethodToInvokeType, string sMethodToInvokeName, object[] oParams)
{
try
{
return tMethodToInvokeType.InvokeMember(sMethodToInvokeName,
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.InvokeMethod, null, null,
(oParams ?? new object[0]));
}
catch (Exception ex)
{
if (ex is TargetParameterCountException || ex is MissingMethodException || ex is ArgumentException)
{
try
{
//HACK: deal with the problem of invoking into a method with an array as a parameter
oParams = new object[] { oParams };
return tMethodToInvokeType.InvokeMember(sMethodToInvokeName,
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.InvokeMethod, null, null,
(oParams));
}
catch (Exception ex2)
{
PublicDI.log.ex(ex2, "in reflection.invokeMethod_Static", true);
return null;
}
}
PublicDI.log.ex(ex, "in reflection..invokeMethod_Static", true);
return null;
}
}
public Object invokeMethod_Static(string sMethodToInvokeType, string sMethodToInvokeName,
object[] oParams)
{
try
{
// first get the type
Type tMethodToInvokeType = PublicDI.reflection.getType(sMethodToInvokeType);
// then invoke the method
return tMethodToInvokeType.InvokeMember(sMethodToInvokeName,
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.InvokeMethod, null, null,
(oParams ?? new object[0]));
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in reflection.invokeMethod_Static", true);
//log.ex(ex);
return null;
}
}
#endregion
#region create
public object createObject(String assemblyToLoad, String typeToCreateObject,
params object[] constructorArguments)
{
try
{
Assembly assembly = getAssembly(assemblyToLoad);
return createObject(assembly, typeToCreateObject, constructorArguments);
}
catch (Exception ex)
{
PublicDI.log.ex(ex, " in createObject(String assemblyToLoad,");
}
return null;
}
public object createObject(Assembly assembly, Type typeToCreateObject,
params object[] constructorArguments)
{
return (typeToCreateObject != null)
? createObject(assembly, typeToCreateObject.FullName, constructorArguments)
: null;
}
public object createObject(Assembly assembly, String typeToCreateObject,
params object[] constructorArguments)
{
Type type = getType(assembly, typeToCreateObject);
return createObject(type,constructorArguments);
}
public object createObject(Type type, params object[] constructorArguments)
{
try
{
if (type == null)
{
"in createObject, type provided was null".error();
return null;
}
var constructorArgumentTypes = new List<Type>();
if (constructorArguments != null)
foreach (object argument in constructorArguments)
constructorArgumentTypes.Add(argument.GetType());
ConstructorInfo constructor = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, constructorArgumentTypes.ToArray(), null);
if (constructor == null)
{
"In createObject, could not find constructor for type: {0}"
.format(type.Name).error();
return null;
}
return constructor.Invoke(constructorArguments ?? new object[0]);
/*try
{
var constructorArgumentTypes = new List<Type>();
if (constructorArguments != null)
foreach (object argument in constructorArguments)
constructorArgumentTypes.Add(argument.GetType());
ConstructorInfo constructor = type.GetConstructor(constructorArgumentTypes.ToArray());
return constructor.Invoke(constructorArguments ?? new object[0]);
*/
// this only really works for types derived from marshal by object
//var wrappedObject = Activator.CreateInstanceFrom(assemblyToLoad, typeToCreateObject, arguments);
//return (wrappedObject != null) ? wrappedObject.Unwrap() : null;
}
catch (Exception ex)
{
PublicDI.log.ex(ex, " createObject for type: " + type.Name,true);
}
return null;
}
public Object createObjectUsingDefaultConstructor(Type tTypeToCreateObject)
{
try
{
return Activator.CreateInstance(tTypeToCreateObject);
}
catch (Exception ex)
{
PublicDI.log.error("..In createObjectUsingDefaultConstructor: {0}", ex.Message);
if (ex.InnerException != null)
PublicDI.log.error(" InnerException : {0}", ex.InnerException.Message);
return null;
}
}
public bool invoke_Ctor_Static(Type targetType)
{
try
{
targetType.TypeInitializer.Invoke(null, null);
/* the code below doesn't work
constructorInfo.Invoke(BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static,
new object[] {});
*/
return true;
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in reflection..invoke (ConstructorInfo", true);
return false;
}
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute
{
/// <summary>
/// The Service Management API includes operations for managing the hosted
/// services beneath your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx for
/// more information)
/// </summary>
public partial interface IHostedServiceOperations
{
/// <summary>
/// The Add Extension operation adds an available extension to your
/// cloud service. In Azure, a process can run as an extension of a
/// cloud service. For example, Remote Desktop Access or the Azure
/// Diagnostics Agent can run as extensions to the cloud service. You
/// can find the available extension by using the List Available
/// Extensions operation. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Add Extension operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
Task<OperationStatusResponse> AddExtensionAsync(string serviceName, HostedServiceAddExtensionParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The Begin Adding Extension operation adds an available extension to
/// your cloud service. In Azure, a process can run as an extension of
/// a cloud service. For example, Remote Desktop Access or the Azure
/// Diagnostics Agent can run as extensions to the cloud service. You
/// can find the available extension by using the List Available
/// Extensions operation. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Adding Extension operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> BeginAddingExtensionAsync(string serviceName, HostedServiceAddExtensionParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The DeleteAll Hosted Service operation deletes the specified cloud
/// service as well as operating system disk, attached data disks, and
/// the source blobs for the disks from storage from Microsoft Azure.
/// (see
/// 'http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx'
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> BeginDeletingAllAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The Begin Deleting Extension operation deletes the specified
/// extension from a cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='extensionId'>
/// The identifier that was assigned to the extension when it was added
/// to the cloud service
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> BeginDeletingExtensionAsync(string serviceName, string extensionId, CancellationToken cancellationToken);
/// <summary>
/// The Check Hosted Service Name Availability operation checks for the
/// availability of the specified cloud service name. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154116.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The cloud service name that you would like to use.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Check Hosted Service Name Availability operation response.
/// </returns>
Task<HostedServiceCheckNameAvailabilityResponse> CheckNameAvailabilityAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The Create Hosted Service operation creates a new cloud service in
/// Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg441304.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Create Hosted Service operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> CreateAsync(HostedServiceCreateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The Delete Hosted Service operation deletes the specified cloud
/// service from Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> DeleteAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The DeleteAll Hosted Service operation deletes the specified cloud
/// service as well as operating system disk, attached data disks, and
/// the source blobs for the disks from storage from Microsoft Azure.
/// (see
/// 'http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx'
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
Task<OperationStatusResponse> DeleteAllAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The Delete Extension operation deletes the specified extension from
/// a cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='extensionId'>
/// The identifier that was assigned to the extension when it was added
/// to the cloud service
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
Task<OperationStatusResponse> DeleteExtensionAsync(string serviceName, string extensionId, CancellationToken cancellationToken);
/// <summary>
/// The Get Hosted Service Properties operation retrieves system
/// properties for the specified cloud service. These properties
/// include the service name and service type; and the name of the
/// affinity group to which the service belongs, or its location if it
/// is not part of an affinity group. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Hosted Service operation response.
/// </returns>
Task<HostedServiceGetResponse> GetAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The Get Detailed Hosted Service Properties operation retrieves
/// system properties for the specified cloud service. These
/// properties include the service name and service type; the name of
/// the affinity group to which the service belongs, or its location
/// if it is not part of an affinity group; and information on the
/// deployments of the service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The detailed Get Hosted Service operation response.
/// </returns>
Task<HostedServiceGetDetailedResponse> GetDetailedAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The Get Extension operation retrieves information about a specified
/// extension that was added to a cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169557.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='extensionId'>
/// The identifier that was assigned to the extension when it was added
/// to the cloud service
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Extension operation response.
/// </returns>
Task<HostedServiceGetExtensionResponse> GetExtensionAsync(string serviceName, string extensionId, CancellationToken cancellationToken);
/// <summary>
/// The List Hosted Services operation lists the cloud services
/// available under the current subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460781.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Hosted Service operation response.
/// </returns>
Task<HostedServiceListResponse> ListAsync(CancellationToken cancellationToken);
/// <summary>
/// The List Available Extensions operation lists the extensions that
/// are available to add to your cloud service. In Windows Azure, a
/// process can run as an extension of a cloud service. For example,
/// Remote Desktop Access or the Azure Diagnostics Agent can run as
/// extensions to the cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169559.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Available Extensions operation response.
/// </returns>
Task<HostedServiceListAvailableExtensionsResponse> ListAvailableExtensionsAsync(CancellationToken cancellationToken);
/// <summary>
/// The List Extensions operation lists all of the extensions that were
/// added to a cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169561.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Extensions operation response.
/// </returns>
Task<HostedServiceListExtensionsResponse> ListExtensionsAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The List Extension Versions operation lists the versions of an
/// extension that are available to add to a cloud service. In Azure,
/// a process can run as an extension of a cloud service. For example,
/// Remote Desktop Access or the Azure Diagnostics Agent can run as
/// extensions to the cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn495437.aspx
/// for more information)
/// </summary>
/// <param name='providerNamespace'>
/// The provider namespace.
/// </param>
/// <param name='extensionType'>
/// The extension type name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Available Extensions operation response.
/// </returns>
Task<HostedServiceListAvailableExtensionsResponse> ListExtensionVersionsAsync(string providerNamespace, string extensionType, CancellationToken cancellationToken);
/// <summary>
/// The List Available Extensions operation lists the extensions that
/// are available to add to your cloud service. In Windows Azure, a
/// process can run as an extension of a cloud service. For example,
/// Remote Desktop Access or the Azure Diagnostics Agent can run as
/// extensions to the cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169559.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Available Extensions operation response.
/// </returns>
Task<HostedServiceListAvailableExtensionsResponse> ListPublisherExtensionsAsync(CancellationToken cancellationToken);
/// <summary>
/// The Update Hosted Service operation can update the label or
/// description of a cloud service in Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg441303.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Hosted Service operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> UpdateAsync(string serviceName, HostedServiceUpdateParameters parameters, CancellationToken cancellationToken);
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Tests.Brokerages
{
public abstract class BrokerageTests
{
// ideally this class would be abstract, but I wanted to keep the order test cases here which use the
// various parameters required from derived types
private IBrokerage _brokerage;
private OrderProvider _orderProvider;
private SecurityProvider _securityProvider;
/// <summary>
/// Provides the data required to test each order type in various cases
/// </summary>
public virtual TestCaseData[] OrderParameters
{
get
{
return new []
{
new TestCaseData(new MarketOrderTestParameters(Symbol)).SetName("MarketOrder"),
new TestCaseData(new LimitOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("LimitOrder"),
new TestCaseData(new StopMarketOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("StopMarketOrder"),
new TestCaseData(new StopLimitOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("StopLimitOrder")
};
}
}
#region Test initialization and cleanup
[SetUp]
public void Setup()
{
Log.Trace("");
Log.Trace("");
Log.Trace("--- SETUP ---");
Log.Trace("");
Log.Trace("");
// we want to regenerate these for each test
_brokerage = null;
_orderProvider = null;
_securityProvider = null;
Thread.Sleep(1000);
CancelOpenOrders();
LiquidateHoldings();
Thread.Sleep(1000);
}
[TearDown]
public void Teardown()
{
try
{
Log.Trace("");
Log.Trace("");
Log.Trace("--- TEARDOWN ---");
Log.Trace("");
Log.Trace("");
Thread.Sleep(1000);
CancelOpenOrders();
LiquidateHoldings();
Thread.Sleep(1000);
}
finally
{
if (_brokerage != null)
{
DisposeBrokerage(_brokerage);
}
}
}
public IBrokerage Brokerage
{
get
{
if (_brokerage == null)
{
_brokerage = InitializeBrokerage();
}
return _brokerage;
}
}
private IBrokerage InitializeBrokerage()
{
Log.Trace("");
Log.Trace("- INITIALIZING BROKERAGE -");
Log.Trace("");
var brokerage = CreateBrokerage(OrderProvider, SecurityProvider);
brokerage.Connect();
if (!brokerage.IsConnected)
{
Assert.Fail("Failed to connect to brokerage");
}
Log.Trace("");
Log.Trace("GET OPEN ORDERS");
Log.Trace("");
foreach (var openOrder in brokerage.GetOpenOrders())
{
OrderProvider.Add(openOrder);
}
Log.Trace("");
Log.Trace("GET ACCOUNT HOLDINGS");
Log.Trace("");
foreach (var accountHolding in brokerage.GetAccountHoldings())
{
// these securities don't need to be real, just used for the ISecurityProvider impl, required
// by brokerages to track holdings
SecurityProvider[accountHolding.Symbol] = new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
new SubscriptionDataConfig(typeof (TradeBar), accountHolding.Symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, false, false, false), 1);
}
brokerage.OrderStatusChanged += (sender, args) =>
{
Log.Trace("");
Log.Trace("ORDER STATUS CHANGED: " + args);
Log.Trace("");
// we need to keep this maintained properly
if (args.Status == OrderStatus.Filled || args.Status == OrderStatus.PartiallyFilled)
{
Log.Trace("FILL EVENT: " + args.FillQuantity + " units of " + args.Symbol.ToString());
Security security;
if (_securityProvider.TryGetValue(args.Symbol, out security))
{
var holding = _securityProvider[args.Symbol].Holdings;
holding.SetHoldings(args.FillPrice, holding.Quantity + args.FillQuantity);
}
else
{
var accountHoldings = brokerage.GetAccountHoldings().ToDictionary(x => x.Symbol);
if (accountHoldings.ContainsKey(args.Symbol))
{
_securityProvider[args.Symbol].Holdings.SetHoldings(args.FillPrice, args.FillQuantity);
}
else
{
_securityProvider[args.Symbol] = new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
new SubscriptionDataConfig(typeof (TradeBar), args.Symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, false, false, false), 1);
_securityProvider[args.Symbol].Holdings.SetHoldings(args.FillPrice, args.FillQuantity);
}
}
Log.Trace("--HOLDINGS: " + _securityProvider[args.Symbol]);
// update order mapping
var order = _orderProvider.GetOrderById(args.OrderId);
order.Status = args.Status;
}
};
return brokerage;
}
public OrderProvider OrderProvider
{
get { return _orderProvider ?? (_orderProvider = new OrderProvider()); }
}
public SecurityProvider SecurityProvider
{
get { return _securityProvider ?? (_securityProvider = new SecurityProvider()); }
}
/// <summary>
/// Creates the brokerage under test and connects it
/// </summary>
/// <returns>A connected brokerage instance</returns>
protected abstract IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider);
/// <summary>
/// Disposes of the brokerage and any external resources started in order to create it
/// </summary>
/// <param name="brokerage">The brokerage instance to be disposed of</param>
protected virtual void DisposeBrokerage(IBrokerage brokerage)
{
}
/// <summary>
/// This is used to ensure each test starts with a clean, known state.
/// </summary>
protected void LiquidateHoldings()
{
Log.Trace("");
Log.Trace("LIQUIDATE HOLDINGS");
Log.Trace("");
var holdings = Brokerage.GetAccountHoldings();
foreach (var holding in holdings)
{
if (holding.Quantity == 0) continue;
Log.Trace("Liquidating: " + holding);
var order = new MarketOrder(holding.Symbol, (int)-holding.Quantity, DateTime.Now, type: holding.Type);
_orderProvider.Add(order);
PlaceOrderWaitForStatus(order, OrderStatus.Filled);
}
}
protected void CancelOpenOrders()
{
Log.Trace("");
Log.Trace("CANCEL OPEN ORDERS");
Log.Trace("");
var openOrders = Brokerage.GetOpenOrders();
foreach (var openOrder in openOrders)
{
Log.Trace("Canceling: " + openOrder);
Brokerage.CancelOrder(openOrder);
}
}
#endregion
/// <summary>
/// Gets the symbol to be traded, must be shortable
/// </summary>
protected abstract Symbol Symbol { get; }
/// <summary>
/// Gets the security type associated with the <see cref="Symbol"/>
/// </summary>
protected abstract SecurityType SecurityType { get; }
/// <summary>
/// Gets a high price for the specified symbol so a limit sell won't fill
/// </summary>
protected abstract decimal HighPrice { get; }
/// <summary>
/// Gets a low price for the specified symbol so a limit buy won't fill
/// </summary>
protected abstract decimal LowPrice { get; }
/// <summary>
/// Gets the current market price of the specified security
/// </summary>
protected abstract decimal GetAskPrice(Symbol symbol);
/// <summary>
/// Gets the default order quantity
/// </summary>
protected virtual int GetDefaultQuantity()
{
return 1;
}
[Test]
public void IsConnected()
{
Assert.IsTrue(Brokerage.IsConnected);
}
[Test, TestCaseSource("OrderParameters")]
public void LongFromZero(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("LONG FROM ZERO");
Log.Trace("");
PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void CloseFromLong(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("CLOSE FROM LONG");
Log.Trace("");
// first go long
PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()), OrderStatus.Filled);
// now close it
PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void ShortFromZero(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("SHORT FROM ZERO");
Log.Trace("");
PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void CloseFromShort(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("CLOSE FROM SHORT");
Log.Trace("");
// first go short
PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(GetDefaultQuantity()), OrderStatus.Filled);
// now close it
PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
}
[Test, TestCaseSource("OrderParameters")]
public void ShortFromLong(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("SHORT FROM LONG");
Log.Trace("");
// first go long
PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()));
// now go net short
var order = PlaceOrderWaitForStatus(parameters.CreateShortOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus);
if (parameters.ModifyUntilFilled)
{
ModifyOrderUntilFilled(order, parameters);
}
}
[Test, TestCaseSource("OrderParameters")]
public void LongFromShort(OrderTestParameters parameters)
{
Log.Trace("");
Log.Trace("LONG FROM SHORT");
Log.Trace("");
// first fo short
PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(-GetDefaultQuantity()), OrderStatus.Filled);
// now go long
var order = PlaceOrderWaitForStatus(parameters.CreateLongOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus);
if (parameters.ModifyUntilFilled)
{
ModifyOrderUntilFilled(order, parameters);
}
}
[Test]
public void GetCashBalanceContainsUSD()
{
Log.Trace("");
Log.Trace("GET CASH BALANCE");
Log.Trace("");
var balance = Brokerage.GetCashBalance();
Assert.AreEqual(1, balance.Count(x => x.Symbol == "USD"));
}
[Test]
public void GetAccountHoldings()
{
Log.Trace("");
Log.Trace("GET ACCOUNT HOLDINGS");
Log.Trace("");
var before = Brokerage.GetAccountHoldings();
PlaceOrderWaitForStatus(new MarketOrder(Symbol, GetDefaultQuantity(), DateTime.Now, type: SecurityType));
var after = Brokerage.GetAccountHoldings();
var beforeHoldings = before.FirstOrDefault(x => x.Symbol == Symbol);
var afterHoldings = after.FirstOrDefault(x => x.Symbol == Symbol);
var beforeQuantity = beforeHoldings == null ? 0 : beforeHoldings.Quantity;
var afterQuantity = afterHoldings == null ? 0 : afterHoldings.Quantity;
Assert.AreEqual(GetDefaultQuantity(), afterQuantity - beforeQuantity);
}
[Test, Ignore("This test requires reading the output and selection of a low volume security for the Brokerageage")]
public void PartialFills()
{
bool orderFilled = false;
var manualResetEvent = new ManualResetEvent(false);
var qty = 1000000;
var remaining = qty;
var sync = new object();
Brokerage.OrderStatusChanged += (sender, orderEvent) =>
{
lock (sync)
{
remaining -= orderEvent.FillQuantity;
Console.WriteLine("Remaining: " + remaining + " FillQuantity: " + orderEvent.FillQuantity);
if (orderEvent.Status == OrderStatus.Filled)
{
orderFilled = true;
manualResetEvent.Set();
}
}
};
// pick a security with low, but some, volume
var symbol = Symbols.EURUSD;
var order = new MarketOrder(symbol, qty, DateTime.UtcNow, type: symbol.ID.SecurityType) { Id = 1 };
Brokerage.PlaceOrder(order);
// pause for a while to wait for fills to come in
manualResetEvent.WaitOne(2500);
manualResetEvent.WaitOne(2500);
manualResetEvent.WaitOne(2500);
Console.WriteLine("Remaining: " + remaining);
Assert.AreEqual(0, remaining);
}
/// <summary>
/// Updates the specified order in the brokerage until it fills or reaches a timeout
/// </summary>
/// <param name="order">The order to be modified</param>
/// <param name="parameters">The order test parameters that define how to modify the order</param>
/// <param name="secondsTimeout">Maximum amount of time to wait until the order fills</param>
protected void ModifyOrderUntilFilled(Order order, OrderTestParameters parameters, double secondsTimeout = 90)
{
if (order.Status == OrderStatus.Filled)
{
return;
}
var filledResetEvent = new ManualResetEvent(false);
EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) =>
{
if (args.Status == OrderStatus.Filled)
{
filledResetEvent.Set();
}
if (args.Status == OrderStatus.Canceled || args.Status == OrderStatus.Invalid)
{
Log.Trace("ModifyOrderUntilFilled(): " + order);
Assert.Fail("Unexpected order status: " + args.Status);
}
};
Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged;
Log.Trace("");
Log.Trace("MODIFY UNTIL FILLED: " + order);
Log.Trace("");
var stopwatch = Stopwatch.StartNew();
while (!filledResetEvent.WaitOne(3000) && stopwatch.Elapsed.TotalSeconds < secondsTimeout)
{
filledResetEvent.Reset();
if (order.Status == OrderStatus.PartiallyFilled) continue;
var marketPrice = GetAskPrice(order.Symbol);
Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): Ask: " + marketPrice);
var updateOrder = parameters.ModifyOrderToFill(Brokerage, order, marketPrice);
if (updateOrder)
{
if (order.Status == OrderStatus.Filled) break;
Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): " + order);
if (!Brokerage.UpdateOrder(order))
{
Assert.Fail("Brokerage failed to update the order");
}
}
}
Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged;
}
/// <summary>
/// Places the specified order with the brokerage and wait until we get the <paramref name="expectedStatus"/> back via an OrderStatusChanged event.
/// This function handles adding the order to the <see cref="IOrderProvider"/> instance as well as incrementing the order ID.
/// </summary>
/// <param name="order">The order to be submitted</param>
/// <param name="expectedStatus">The status to wait for</param>
/// <param name="secondsTimeout">Maximum amount of time to wait for <paramref name="expectedStatus"/></param>
/// <returns>The same order that was submitted.</returns>
protected Order PlaceOrderWaitForStatus(Order order, OrderStatus expectedStatus = OrderStatus.Filled, double secondsTimeout = 10.0, bool allowFailedSubmission = false)
{
var requiredStatusEvent = new ManualResetEvent(false);
var desiredStatusEvent = new ManualResetEvent(false);
EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) =>
{
// no matter what, every order should fire at least one of these
if (args.Status == OrderStatus.Submitted || args.Status == OrderStatus.Invalid)
{
Log.Trace("");
Log.Trace("SUBMITTED: " + args);
Log.Trace("");
requiredStatusEvent.Set();
}
// make sure we fire the status we're expecting
if (args.Status == expectedStatus)
{
Log.Trace("");
Log.Trace("EXPECTED: " + args);
Log.Trace("");
desiredStatusEvent.Set();
}
};
Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged;
OrderProvider.Add(order);
if (!Brokerage.PlaceOrder(order) && !allowFailedSubmission)
{
Assert.Fail("Brokerage failed to place the order: " + order);
}
requiredStatusEvent.WaitOneAssertFail((int) (1000*secondsTimeout), "Expected every order to fire a submitted or invalid status event");
desiredStatusEvent.WaitOneAssertFail((int) (1000*secondsTimeout), "OrderStatus " + expectedStatus + " was not encountered within the timeout.");
Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged;
return order;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace JeffBot2BAPI.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.PageSettings.cs
//
// Authors:
// Dennis Hayes ([email protected])
// Herve Poussineau ([email protected])
// Andreas Nahr ([email protected])
//
// (C) 2002 Ximian, Inc
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.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.
//
using System;
using System.Runtime.InteropServices;
namespace System.Drawing.Printing
{
[Serializable]
public class PageSettings : ICloneable
{
internal bool color;
internal bool landscape;
internal PaperSize paperSize;
internal PaperSource paperSource;
internal PrinterResolution printerResolution;
// create a new default Margins object (is 1 inch for all margins)
Margins margins = new Margins();
#pragma warning disable 649
float hardMarginX;
float hardMarginY;
RectangleF printableArea;
PrinterSettings printerSettings;
#pragma warning restore 649
public PageSettings() : this(new PrinterSettings())
{
}
public PageSettings(PrinterSettings printerSettings)
{
PrinterSettings = printerSettings;
this.color = printerSettings.DefaultPageSettings.color;
this.landscape = printerSettings.DefaultPageSettings.landscape;
this.paperSize = printerSettings.DefaultPageSettings.paperSize;
this.paperSource = printerSettings.DefaultPageSettings.paperSource;
this.printerResolution = printerSettings.DefaultPageSettings.printerResolution;
}
// used by PrinterSettings.DefaultPageSettings
internal PageSettings(PrinterSettings printerSettings, bool color, bool landscape, PaperSize paperSize, PaperSource paperSource, PrinterResolution printerResolution)
{
PrinterSettings = printerSettings;
this.color = color;
this.landscape = landscape;
this.paperSize = paperSize;
this.paperSource = paperSource;
this.printerResolution = printerResolution;
}
//props
public Rectangle Bounds
{
get
{
int width = this.paperSize.Width;
int height = this.paperSize.Height;
width -= this.margins.Left + this.margins.Right;
height -= this.margins.Top + this.margins.Bottom;
if (this.landscape)
{
// swap width and height
int tmp = width;
width = height;
height = tmp;
}
return new Rectangle(this.margins.Left, this.margins.Top, width, height);
}
}
public bool Color
{
get
{
if (!this.printerSettings.IsValid)
throw new InvalidPrinterException(this.printerSettings);
return color;
}
set
{
color = value;
}
}
public bool Landscape
{
get
{
if (!this.printerSettings.IsValid)
throw new InvalidPrinterException(this.printerSettings);
return landscape;
}
set
{
landscape = value;
}
}
public Margins Margins
{
get
{
if (!this.printerSettings.IsValid)
throw new InvalidPrinterException(this.printerSettings);
return margins;
}
set
{
margins = value;
}
}
public PaperSize PaperSize
{
get
{
if (!this.printerSettings.IsValid)
throw new InvalidPrinterException(this.printerSettings);
return paperSize;
}
set
{
if (value != null)
paperSize = value;
}
}
public PaperSource PaperSource
{
get
{
if (!this.printerSettings.IsValid)
throw new InvalidPrinterException(this.printerSettings);
return paperSource;
}
set
{
if (value != null)
paperSource = value;
}
}
public PrinterResolution PrinterResolution
{
get
{
if (!this.printerSettings.IsValid)
throw new InvalidPrinterException(this.printerSettings);
return printerResolution;
}
set
{
if (value != null)
printerResolution = value;
}
}
public PrinterSettings PrinterSettings
{
get
{
return printerSettings;
}
set
{
printerSettings = value;
}
}
public float HardMarginX
{
get
{
return hardMarginX;
}
}
public float HardMarginY
{
get
{
return hardMarginY;
}
}
public RectangleF PrintableArea
{
get
{
return printableArea;
}
}
public object Clone()
{
// We do a deep copy
PrinterResolution pres = new PrinterResolution(this.printerResolution.Kind, this.printerResolution.X, this.printerResolution.Y);
PaperSource psource = new PaperSource(this.paperSource.Kind, this.paperSource.SourceName);
PaperSize psize = new PaperSize(this.paperSize.PaperName, this.paperSize.Width, this.paperSize.Height);
psize.RawKind = (int)this.paperSize.Kind;
PageSettings ps = new PageSettings(this.printerSettings, this.color, this.landscape,
psize, psource, pres);
ps.Margins = (Margins)this.margins.Clone();
return ps;
}
public void CopyToHdevmode(IntPtr hdevmode)
{
throw new NotImplementedException();
}
public void SetHdevmode(IntPtr hdevmode)
{
throw new NotImplementedException();
}
public override string ToString()
{
string ret = "[PageSettings: Color={0}";
ret += ", Landscape={1}";
ret += ", Margins={2}";
ret += ", PaperSize={3}";
ret += ", PaperSource={4}";
ret += ", PrinterResolution={5}";
ret += "]";
return string.Format(ret, this.color, this.landscape, this.margins, this.paperSize, this.paperSource, this.printerResolution);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;
namespace Mvc.Bootstrap.Datatables
{
public class DataTablesResult : JsonResult
{
public static DataTablesResult<TRes> Create<T, TRes>(IQueryable<T> q, DataTablesParam dataTableParam, DataTablesOptions dataTableOptions, Func<T, TRes> transform)
{
return new DataTablesResult<T, TRes>(q, dataTableParam, dataTableOptions, transform);
}
public static DataTablesResult<T> Create<T>(IQueryable<T> q, DataTablesParam dataTableParam)
{
return new DataTablesResult<T, T>(q, dataTableParam, null, t => t);
}
public static DataTablesResult<T> CreateResultUsingEnumerable<T>(IEnumerable<T> q, DataTablesParam dataTableParam)
{
return new DataTablesResult<T, T>(q.AsQueryable(), dataTableParam, null, t => t);
}
public static DataTablesResult Create(object queryable, DataTablesParam dataTableParam)
{
queryable = ((IEnumerable) queryable).AsQueryable();
var s = "Create";
var openCreateMethod =
typeof (DataTablesResult).GetMethods().Single(x => x.Name == s && x.GetGenericArguments().Count() == 1);
var queryableType = queryable.GetType().GetGenericArguments()[0];
var closedCreateMethod = openCreateMethod.MakeGenericMethod(queryableType);
return (DataTablesResult) closedCreateMethod.Invoke(null, new[] {queryable, dataTableParam});
}
}
public class DataTablesResult<T> : DataTablesResult
{
}
public class DataTablesResult<T, TRes> : DataTablesResult<TRes>
{
private readonly Func<T, TRes> _transform;
public DataTablesResult(IQueryable<T> q, DataTablesParam dataTableParam, DataTablesOptions dataTableOptions, Func<T, TRes> transform)
{
_transform = transform;
var properties = typeof(TRes).GetProperties();
if (dataTableOptions == null)
{
dataTableOptions = new DataTablesOptions();
}
var content = GetResults(q, dataTableParam, dataTableOptions, properties.Select(p => Tuple.Create(p.Name, (string)null, p.PropertyType)).ToArray());
this.Data = content;
this.JsonRequestBehavior = JsonRequestBehavior.DenyGet;
}
static readonly List<PropertyTransformer> PropertyTransformers = new List<PropertyTransformer>()
{
Guard<DateTimeOffset>(dateTimeOffset => dateTimeOffset.ToLocalTime().ToString("g")),
Guard<DateTime>(dateTime => dateTime.ToLocalTime().ToString("g")),
Guard<IHtmlString>(s => s.ToHtmlString()),
Guard<object>(o => (o ?? "").ToString())
};
public delegate object PropertyTransformer(Type type, object value);
public delegate object GuardedValueTransformer<TVal>(TVal value);
static PropertyTransformer Guard<TVal>(GuardedValueTransformer<TVal> transformer)
{
return (t, v) =>
{
if (!typeof(TVal).IsAssignableFrom(t))
{
return null;
}
return transformer((TVal) v);
};
}
public static void RegisterFilter<TVal>(GuardedValueTransformer<TVal> filter)
{
PropertyTransformers.Add(Guard<TVal>(filter));
}
private DataTablesData GetResults(IQueryable<T> data, DataTablesParam param, DataTablesOptions dataTableOptions, Tuple<string, string, Type>[] searchColumns)
{
int totalRecords = data.Count();
int totalRecordsDisplay;
//var filters = new DataTablesFilter();
//var dataArray = data.Select(_transform).AsQueryable();
//var dataArray = filters.FilterPagingSortingSearch(param, data, out totalRecordsDisplay, searchColumns).Cast<TRes>();
var dtParameters = param;
var columns = searchColumns;
//// CDEUTSCH: searching doesn't work at all in EnitityFramework due to lack of .ToString() support.
// https://github.com/mcintyre321/mvc.jquery.datatables/issues/18
//if (!String.IsNullOrEmpty(dtParameters.sSearch))
//{
// var parts = new List<string>();
// var parameters = new List<object>();
// for (var i = 0; i < dtParameters.iColumns; i++)
// {
// if (dtParameters.bSearchable[i])
// {
// parts.Add(DataTablesFilter.GetFilterClause(dtParameters.sSearch, columns[i], parameters));
// }
// }
// data = data.Where(string.Join(" or ", parts), parameters.ToArray());
//}
//for (int i = 0; i < dtParameters.sSearchColumns.Count; i++)
//{
// if (dtParameters.bSearchable[i])
// {
// var searchColumn = dtParameters.sSearchColumns[i];
// if (!string.IsNullOrWhiteSpace(searchColumn))
// {
// var parameters = new List<object>();
// var filterClause = DataTablesFilter.GetFilterClause(dtParameters.sSearchColumns[i], columns[i], parameters);
// data = data.Where(filterClause, parameters.ToArray());
// }
// }
//}
string sortString = "";
for (int i = 0; i < dtParameters.iSortingCols; i++)
{
int columnNumber = dtParameters.iSortCol[i];
string columnName = columns[columnNumber].Item1;
string sortDir = dtParameters.sSortDir[i];
if (i != 0)
sortString += ", ";
if (dataTableOptions.SearchAliases.ContainsKey(columnName))
{
// check for comma if so add direction to all tokens.
var toks = dataTableOptions.SearchAliases[columnName].Split(',');
for (var xx = 0; xx < toks.Length; xx++)
{
if (xx == (toks.Length - 1))
{
sortString += toks[xx] + " " + sortDir;
}
else
{
sortString += toks[xx] + " " + sortDir + ", ";
}
}
}
else
{
sortString += columnName + " " + sortDir;
}
}
totalRecordsDisplay = data.Count();
data = data.OrderBy(sortString);
data = data.Skip(dtParameters.iDisplayStart);
if (dtParameters.iDisplayLength > -1)
{
data = data.Take(dtParameters.iDisplayLength);
}
var type = typeof(TRes);
var properties = type.GetProperties();
var aaData = data.Select(_transform).Cast<object>().ToArray();
//var toArrayQuery = from i in data.Select(_transform)
// let pairs = properties.Select(p => new {p.PropertyType, Value = (p.GetGetMethod().Invoke(i, null))})
// let values = pairs.Select(p => GetTransformedValue(p.PropertyType, p.Value))
// select values;
var result = new DataTablesData
{
iTotalRecords = totalRecords,
iTotalDisplayRecords = totalRecordsDisplay,
sEcho = param.sEcho,
aaData = aaData
};
return result;
}
private object GetTransformedValue(Type propertyType, object value)
{
foreach (var transformer in PropertyTransformers)
{
var result = transformer(propertyType, value);
if (result != null) return result;
}
return (value as object ?? "").ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace Aga.Controls.Tree
{
internal class NormalInputState : InputState
{
private bool _mouseDownFlag = false;
public NormalInputState(TreeViewAdv tree) : base(tree)
{
}
public override void KeyDown(KeyEventArgs args)
{
if (Tree.CurrentNode == null && Tree.Root.Nodes.Count > 0)
Tree.CurrentNode = Tree.Root.Nodes[0];
if (Tree.CurrentNode != null)
{
switch (args.KeyCode)
{
case Keys.Right:
if (!Tree.CurrentNode.IsExpanded)
Tree.CurrentNode.IsExpanded = true;
else if (Tree.CurrentNode.Nodes.Count > 0)
Tree.SelectedNode = Tree.CurrentNode.Nodes[0];
args.Handled = true;
break;
case Keys.Left:
if (Tree.CurrentNode.IsExpanded)
Tree.CurrentNode.IsExpanded = false;
else if (Tree.CurrentNode.Parent != Tree.Root)
Tree.SelectedNode = Tree.CurrentNode.Parent;
args.Handled = true;
break;
case Keys.Down:
NavigateForward(1);
args.Handled = true;
break;
case Keys.Up:
NavigateBackward(1);
args.Handled = true;
break;
case Keys.PageDown:
NavigateForward(Math.Max(1, Tree.CurrentPageSize - 1));
args.Handled = true;
break;
case Keys.PageUp:
NavigateBackward(Math.Max(1, Tree.CurrentPageSize - 1));
args.Handled = true;
break;
case Keys.Home:
if (Tree.RowMap.Count > 0)
FocusRow(Tree.RowMap[0]);
args.Handled = true;
break;
case Keys.End:
if (Tree.RowMap.Count > 0)
FocusRow(Tree.RowMap[Tree.RowMap.Count-1]);
args.Handled = true;
break;
case Keys.Subtract:
Tree.CurrentNode.Collapse();
args.Handled = true;
args.SuppressKeyPress = true;
break;
case Keys.Add:
Tree.CurrentNode.Expand();
args.Handled = true;
args.SuppressKeyPress = true;
break;
case Keys.Multiply:
Tree.CurrentNode.ExpandAll();
args.Handled = true;
args.SuppressKeyPress = true;
break;
}
}
}
public override void MouseDown(TreeNodeAdvMouseEventArgs args)
{
if (args.Node != null)
{
Tree.ItemDragMode = true;
Tree.ItemDragStart = args.Location;
if (args.Button == MouseButtons.Left || args.Button == MouseButtons.Right)
{
Tree.BeginUpdate();
try
{
Tree.CurrentNode = args.Node;
if (args.Node.IsSelected)
_mouseDownFlag = true;
else
{
_mouseDownFlag = false;
DoMouseOperation(args);
}
}
finally
{
Tree.EndUpdate();
}
}
}
else
{
Tree.ItemDragMode = false;
MouseDownAtEmptySpace(args);
}
}
public override void MouseUp(TreeNodeAdvMouseEventArgs args)
{
Tree.ItemDragMode = false;
if (_mouseDownFlag)
{
if (args.Button == MouseButtons.Left)
DoMouseOperation(args);
else if (args.Button == MouseButtons.Right)
Tree.CurrentNode = args.Node;
}
_mouseDownFlag = false;
}
private void NavigateBackward(int n)
{
int row = Math.Max(Tree.CurrentNode.Row - n, 0);
if (row != Tree.CurrentNode.Row)
FocusRow(Tree.RowMap[row]);
}
private void NavigateForward(int n)
{
int row = Math.Min(Tree.CurrentNode.Row + n, Tree.RowCount - 1);
if (row != Tree.CurrentNode.Row)
FocusRow(Tree.RowMap[row]);
}
protected virtual void MouseDownAtEmptySpace(TreeNodeAdvMouseEventArgs args)
{
Tree.ClearSelectionInternal();
}
protected virtual void FocusRow(TreeNodeAdv node)
{
Tree.SuspendSelectionEvent = true;
try
{
Tree.ClearSelectionInternal();
Tree.CurrentNode = node;
Tree.SelectionStart = node;
node.IsSelected = true;
Tree.ScrollTo(node);
}
finally
{
Tree.SuspendSelectionEvent = false;
}
}
protected bool CanSelect(TreeNodeAdv node)
{
if (Tree.SelectionMode == TreeSelectionMode.MultiSameParent)
{
return (Tree.SelectionStart == null || node.Parent == Tree.SelectionStart.Parent);
}
else
return true;
}
protected virtual void DoMouseOperation(TreeNodeAdvMouseEventArgs args)
{
if (Tree.SelectedNodes.Count == 1 && args.Node.IsSelected && Tree.ColumnSelectionMode == ColumnSelectionMode.All)
return;
Tree.SuspendSelectionEvent = true;
try
{
Tree.ClearSelectionInternal();
if (args.Node != null)
{
args.Node.IsSelected = true;
Tree.SelectedColumnIndex = ((args.Control != null) && (args.Control.ParentColumn != null)) ? args.Control.ParentColumn.Index : -1;
}
Tree.SelectionStart = args.Node;
}
finally
{
Tree.SuspendSelectionEvent = false;
}
}
}
}
| |
// 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.Immutable;
using System.Globalization;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.DocumentationCommentFormatting;
namespace Microsoft.CodeAnalysis.MetadataAsSource
{
internal partial class AbstractMetadataAsSourceService
{
private abstract class AbstractWrappedSymbol : ISymbol
{
private readonly ISymbol _symbol;
protected readonly bool CanImplementImplicitly;
protected readonly IDocumentationCommentFormattingService DocCommentFormattingService;
protected AbstractWrappedSymbol(ISymbol symbol, bool canImplementImplicitly, IDocumentationCommentFormattingService docCommentFormattingService)
{
_symbol = symbol;
this.CanImplementImplicitly = canImplementImplicitly;
this.DocCommentFormattingService = docCommentFormattingService;
}
public bool CanBeReferencedByName
{
get
{
return _symbol.CanBeReferencedByName;
}
}
public IAssemblySymbol ContainingAssembly
{
get
{
return _symbol.ContainingAssembly;
}
}
public IModuleSymbol ContainingModule
{
get
{
return _symbol.ContainingModule;
}
}
public INamespaceSymbol ContainingNamespace
{
get
{
return _symbol.ContainingNamespace;
}
}
public ISymbol ContainingSymbol
{
get
{
return _symbol.ContainingSymbol;
}
}
public INamedTypeSymbol ContainingType
{
get
{
return _symbol.ContainingType;
}
}
public Accessibility DeclaredAccessibility
{
get
{
return _symbol.DeclaredAccessibility;
}
}
public ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return _symbol.DeclaringSyntaxReferences;
}
}
public bool IsAbstract
{
get
{
return _symbol.IsAbstract;
}
}
public bool IsDefinition
{
get
{
return _symbol.IsDefinition;
}
}
public bool IsExtern
{
get
{
return _symbol.IsExtern;
}
}
public bool IsImplicitlyDeclared
{
get
{
return _symbol.IsImplicitlyDeclared;
}
}
public bool IsOverride
{
get
{
return _symbol.IsOverride;
}
}
public bool IsSealed
{
get
{
return _symbol.IsSealed;
}
}
public bool IsStatic
{
get
{
return _symbol.IsStatic;
}
}
public bool IsVirtual
{
get
{
return _symbol.IsVirtual;
}
}
public SymbolKind Kind
{
get
{
return _symbol.Kind;
}
}
public string Language
{
get
{
return _symbol.Language;
}
}
public ImmutableArray<Location> Locations
{
get
{
return _symbol.Locations;
}
}
public string MetadataName
{
get
{
return _symbol.MetadataName;
}
}
public string Name
{
get
{
return _symbol.Name;
}
}
public ISymbol OriginalDefinition
{
get
{
return _symbol.OriginalDefinition;
}
}
public bool HasUnsupportedMetadata
{
get
{
return _symbol.HasUnsupportedMetadata;
}
}
public void Accept(SymbolVisitor visitor)
{
_symbol.Accept(visitor);
}
public TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
{
return _symbol.Accept<TResult>(visitor);
}
public ImmutableArray<AttributeData> GetAttributes()
{
return _symbol.GetAttributes();
}
public string GetDocumentationCommentId()
{
return _symbol.GetDocumentationCommentId();
}
public string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken))
{
return _symbol.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken);
}
public ImmutableArray<SymbolDisplayPart> ToDisplayParts(SymbolDisplayFormat format = null)
{
return _symbol.ToDisplayParts(format);
}
public string ToDisplayString(SymbolDisplayFormat format = null)
{
return _symbol.ToDisplayString(format);
}
public string ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null)
{
return _symbol.ToMinimalDisplayString(semanticModel, position, format);
}
public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null)
{
return _symbol.ToMinimalDisplayParts(semanticModel, position, format);
}
public bool Equals(ISymbol other)
{
return this.Equals((object)other);
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
namespace Microsoft.PackageManagement.Internal.Implementation {
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Api;
using PackageManagement.Implementation;
using PackageManagement.Packaging;
using PackageManagement.Internal.Packaging;
using PackageManagement.Internal.Utility.Plugin;
using Messages = Resources.Messages;
internal class SoftwareIdentityRequestObject : EnumerableRequestObject<SoftwareIdentity> {
private SoftwareIdentity _currentItem;
private readonly string _status;
public SoftwareIdentityRequestObject(ProviderBase provider, IHostApi request, Action<RequestObject> action, string status)
: base(provider, request, action) {
_status = status;
InvokeImpl();
}
private void CommitCurrentItem() {
if (_currentItem != null) {
Results.Add(_currentItem);
}
_currentItem = null;
}
public override string YieldSoftwareIdentity(string fastPath, string name, string version, string versionScheme, string summary, string source, string searchKey, string fullPath, string packageFileName) {
Activity();
CommitCurrentItem();
_currentItem = new SoftwareIdentity {
FastPackageReference = fastPath,
Name = name,
Version = version,
VersionScheme = versionScheme,
Summary = summary,
Provider = (PackageProvider)Provider,
Source = source,
Status = _status,
SearchKey = searchKey,
FullPath = fullPath,
PackageFilename = packageFileName
};
return fastPath;
}
public override string YieldSoftwareIdentityXml(string xmlSwidTag, bool commitImmediately=false)
{
Activity();
CommitCurrentItem();
if (string.IsNullOrWhiteSpace(xmlSwidTag))
{
return null;
}
try
{
XDocument xdoc = XDocument.Parse(xmlSwidTag);
if (xdoc != null && xdoc.Root != null && Swidtag.IsSwidtag(xdoc.Root))
{
_currentItem = new SoftwareIdentity(xdoc);
if (Provider != null) {
_currentItem.Provider = (PackageProvider)Provider;
}
}
else
{
Verbose(string.Format(CultureInfo.CurrentCulture, Resources.Messages.SwidTagXmlInvalidNameSpace, xmlSwidTag, Iso19770_2.Namespace.Iso19770_2));
}
}
catch (Exception e)
{
Verbose(e.Message);
Verbose(e.StackTrace);
}
if (_currentItem == null)
{
Warning(string.Format(CultureInfo.CurrentCulture, Messages.SwidTagXmlNotValid));
return null;
}
string result = _currentItem.FastPackageReference;
// provider author wants us to commit at once
if (commitImmediately)
{
CommitCurrentItem();
}
return result;
}
/// <summary>
/// Adds a metadata key/value pair to the Swidtag.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public override string AddMetadata(string name, string value) {
Activity();
var swid = _currentItem;
return swid != null ? swid.AddMetadataValue(swid.FastPackageReference, name, value) : null;
}
/// <summary>
/// Adds a tagID to the swidtag
/// </summary>
/// <param name="tagId"></param>
/// <returns></returns>
public override string AddTagId(string tagId)
{
Activity();
var swid = _currentItem;
if (swid == null)
{
return null;
}
// we can't modify it once add so check that there is no swidtag
if (string.IsNullOrWhiteSpace(swid.TagId))
{
swid.TagId = tagId;
}
return swid.TagId;
}
public override string AddCulture(string xmlLang)
{
Activity();
var swid = _currentItem;
if (swid == null)
{
return null;
}
// we can't modify it once add, so check that there is no swidtag
if (string.IsNullOrWhiteSpace(swid.Culture))
{
swid.Culture = xmlLang;
}
return swid.Culture;
}
/// <summary>
/// Adds an attribute to a 'Meta' object. If called for a Swidtag or Entity, it implicitly adds a child Meta object.
/// Any other elementPath is an error and will be ignored.
/// </summary>
/// <param name="elementPath">
/// the string that represents one of :
/// a Swidtag (the fastPackageReference) (passing null as the elementPath will default to the swidtag)
/// an Entity (the result gained from an YieldEntity(...) call )
/// a Meta object (the result from previously calling AddMetadataValue(...) )
/// </param>
/// <param name="name">the name of the attribute to add</param>
/// <param name="value">the value of the attribute to add</param>
/// <returns></returns>
public override string AddMetadata(string elementPath, string name, string value) {
Activity();
var swid = _currentItem;
return swid != null ? swid.AddMetadataValue(elementPath, name, value) : null;
}
public override string AddMetadata(string elementPath, Uri @namespace, string name, string value) {
Activity();
var swid = _currentItem;
if (swid == null || string.IsNullOrWhiteSpace(elementPath)) {
return null;
}
return swid.AddMetadataValue(elementPath, @namespace, name, value);
}
public override string AddMeta(string elementPath) {
Activity();
var swid = _currentItem;
return swid != null ? swid.AddMeta(elementPath) : null;
}
public override string AddPayload() {
var swid = _currentItem;
return swid != null ? swid.AddPayload().ElementUniqueId : null;
}
public override string AddEvidence(DateTime date, string deviceId) {
var swid = _currentItem;
return swid != null ? swid.AddEvidence(date, deviceId).ElementUniqueId : null;
}
public override string AddDirectory(string elementPath, string directoryName, string location, string root, bool isKey) {
Activity();
var swid = _currentItem;
return swid != null ? swid.AddDirectory(elementPath, directoryName, location, root, isKey) : null;
}
public override string AddFile(string elementPath, string fileName, string location, string root, bool isKey, long size, string version) {
Activity();
var swid = _currentItem;
return swid != null ? swid.AddFile(elementPath, fileName, location, root, isKey, size, version) : null;
}
public override string AddProcess(string elementPath, string processName, int pid) {
Activity();
var swid = _currentItem;
return swid != null ? swid.AddProcess(elementPath, processName, pid) : null;
}
public override string AddResource(string elementPath, string type) {
Activity();
var swid = _currentItem;
return swid != null ? swid.AddResource(elementPath, type) : null;
}
public override string AddEntity(string name, string regid, string role, string thumbprint) {
Activity();
var swid = _currentItem;
return swid != null ? swid.AddEntity(name, regid, role, thumbprint) : null;
}
public override string AddLink(Uri referenceUri, string relationship, string mediaType, string ownership, string use, string appliesToMedia, string artifact) {
Activity();
var swid = _currentItem;
return swid != null ? swid.AddLink(referenceUri, relationship, mediaType, ownership, use, appliesToMedia, artifact) : null;
}
public override string AddDependency(string providerName, string packageName, string version, string source, string appliesTo) {
Activity();
var swid = _currentItem;
return swid != null ? swid.AddDependency(providerName, packageName, version, source, appliesTo) : null;
}
protected override void Complete() {
CommitCurrentItem();
base.Complete();
}
}
}
| |
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 BunniesCraft.Services.Areas.HelpPage.ModelDescriptions;
using BunniesCraft.Services.Areas.HelpPage.Models;
namespace BunniesCraft.Services.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
namespace PTWin
{
partial class ResourceEdit
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.Label FirstNameLabel;
System.Windows.Forms.Label IdLabel;
System.Windows.Forms.Label LastNameLabel;
this.CloseButton = new System.Windows.Forms.Button();
this.ApplyButton = new System.Windows.Forms.Button();
this.Cancel_Button = new System.Windows.Forms.Button();
this.OKButton = new System.Windows.Forms.Button();
this.GroupBox1 = new System.Windows.Forms.GroupBox();
this.AssignmentsDataGridView = new System.Windows.Forms.DataGridView();
this.RoleListBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.AssignmentsBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.ResourceBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.UnassignButton = new System.Windows.Forms.Button();
this.AssignButton = new System.Windows.Forms.Button();
this.FirstNameTextBox = new System.Windows.Forms.TextBox();
this.IdLabel1 = new System.Windows.Forms.Label();
this.LastNameTextBox = new System.Windows.Forms.TextBox();
this.ErrorProvider1 = new System.Windows.Forms.ErrorProvider(this.components);
this.ReadWriteAuthorization1 = new Csla.Windows.ReadWriteAuthorization(this.components);
this.RefreshButton = new System.Windows.Forms.Button();
this.bindingSourceRefresh1 = new Csla.Windows.BindingSourceRefresh(this.components);
this.ProjectId = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ProjectName = new System.Windows.Forms.DataGridViewLinkColumn();
this.Assigned = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Role = new System.Windows.Forms.DataGridViewComboBoxColumn();
FirstNameLabel = new System.Windows.Forms.Label();
IdLabel = new System.Windows.Forms.Label();
LastNameLabel = new System.Windows.Forms.Label();
this.GroupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.AssignmentsDataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.RoleListBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.AssignmentsBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ResourceBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ErrorProvider1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.bindingSourceRefresh1)).BeginInit();
this.SuspendLayout();
//
// FirstNameLabel
//
this.ReadWriteAuthorization1.SetApplyAuthorization(FirstNameLabel, false);
FirstNameLabel.AutoSize = true;
FirstNameLabel.Location = new System.Drawing.Point(13, 42);
FirstNameLabel.Name = "FirstNameLabel";
FirstNameLabel.Size = new System.Drawing.Size(60, 13);
FirstNameLabel.TabIndex = 2;
FirstNameLabel.Text = "First Name:";
//
// IdLabel
//
this.ReadWriteAuthorization1.SetApplyAuthorization(IdLabel, false);
IdLabel.AutoSize = true;
IdLabel.Location = new System.Drawing.Point(13, 13);
IdLabel.Name = "IdLabel";
IdLabel.Size = new System.Drawing.Size(19, 13);
IdLabel.TabIndex = 0;
IdLabel.Text = "Id:";
//
// LastNameLabel
//
this.ReadWriteAuthorization1.SetApplyAuthorization(LastNameLabel, false);
LastNameLabel.AutoSize = true;
LastNameLabel.Location = new System.Drawing.Point(13, 68);
LastNameLabel.Name = "LastNameLabel";
LastNameLabel.Size = new System.Drawing.Size(61, 13);
LastNameLabel.TabIndex = 4;
LastNameLabel.Text = "Last Name:";
//
// CloseButton
//
this.CloseButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.CloseButton, false);
this.CloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CloseButton.Location = new System.Drawing.Point(501, 100);
this.CloseButton.Name = "CloseButton";
this.CloseButton.Size = new System.Drawing.Size(75, 23);
this.CloseButton.TabIndex = 10;
this.CloseButton.Text = "Close";
this.CloseButton.UseVisualStyleBackColor = true;
this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click);
//
// ApplyButton
//
this.ApplyButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.ApplyButton, false);
this.ApplyButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.ApplyButton.Location = new System.Drawing.Point(501, 42);
this.ApplyButton.Name = "ApplyButton";
this.ApplyButton.Size = new System.Drawing.Size(75, 23);
this.ApplyButton.TabIndex = 8;
this.ApplyButton.Text = "Apply";
this.ApplyButton.UseVisualStyleBackColor = true;
this.ApplyButton.Click += new System.EventHandler(this.ApplyButton_Click);
//
// Cancel_Button
//
this.Cancel_Button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.Cancel_Button, false);
this.Cancel_Button.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Cancel_Button.Location = new System.Drawing.Point(501, 71);
this.Cancel_Button.Name = "Cancel_Button";
this.Cancel_Button.Size = new System.Drawing.Size(75, 23);
this.Cancel_Button.TabIndex = 9;
this.Cancel_Button.Text = "Cancel";
this.Cancel_Button.UseVisualStyleBackColor = true;
this.Cancel_Button.Click += new System.EventHandler(this.Cancel_Button_Click);
//
// OKButton
//
this.OKButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.OKButton, false);
this.OKButton.Location = new System.Drawing.Point(501, 13);
this.OKButton.Name = "OKButton";
this.OKButton.Size = new System.Drawing.Size(75, 23);
this.OKButton.TabIndex = 7;
this.OKButton.Text = "OK";
this.OKButton.UseVisualStyleBackColor = true;
this.OKButton.Click += new System.EventHandler(this.OKButton_Click);
//
// GroupBox1
//
this.GroupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.GroupBox1, false);
this.GroupBox1.Controls.Add(this.AssignmentsDataGridView);
this.GroupBox1.Controls.Add(this.UnassignButton);
this.GroupBox1.Controls.Add(this.AssignButton);
this.GroupBox1.Location = new System.Drawing.Point(16, 91);
this.GroupBox1.Name = "GroupBox1";
this.GroupBox1.Size = new System.Drawing.Size(449, 310);
this.GroupBox1.TabIndex = 6;
this.GroupBox1.TabStop = false;
this.GroupBox1.Text = "Assigned projects";
//
// AssignmentsDataGridView
//
this.AssignmentsDataGridView.AllowUserToAddRows = false;
this.AssignmentsDataGridView.AllowUserToDeleteRows = false;
this.AssignmentsDataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.AssignmentsDataGridView, false);
this.AssignmentsDataGridView.AutoGenerateColumns = false;
this.AssignmentsDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.AssignmentsDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ProjectId,
this.ProjectName,
this.Assigned,
this.Role});
this.AssignmentsDataGridView.DataSource = this.AssignmentsBindingSource;
this.AssignmentsDataGridView.Location = new System.Drawing.Point(6, 19);
this.AssignmentsDataGridView.MultiSelect = false;
this.AssignmentsDataGridView.Name = "AssignmentsDataGridView";
this.AssignmentsDataGridView.RowHeadersVisible = false;
this.AssignmentsDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.AssignmentsDataGridView.Size = new System.Drawing.Size(356, 285);
this.AssignmentsDataGridView.TabIndex = 0;
this.AssignmentsDataGridView.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.AssignmentsDataGridView_CellContentClick);
//
// RoleListBindingSource
//
this.RoleListBindingSource.DataSource = typeof(ProjectTracker.Library.RoleList);
this.bindingSourceRefresh1.SetReadValuesOnChange(this.RoleListBindingSource, false);
//
// AssignmentsBindingSource
//
this.AssignmentsBindingSource.DataMember = "Assignments";
this.AssignmentsBindingSource.DataSource = this.ResourceBindingSource;
this.bindingSourceRefresh1.SetReadValuesOnChange(this.AssignmentsBindingSource, false);
//
// ResourceBindingSource
//
this.ResourceBindingSource.DataSource = typeof(ProjectTracker.Library.ResourceEdit);
this.bindingSourceRefresh1.SetReadValuesOnChange(this.ResourceBindingSource, true);
//
// UnassignButton
//
this.UnassignButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.UnassignButton, false);
this.UnassignButton.Location = new System.Drawing.Point(368, 48);
this.UnassignButton.Name = "UnassignButton";
this.UnassignButton.Size = new System.Drawing.Size(75, 23);
this.UnassignButton.TabIndex = 2;
this.UnassignButton.Text = "Unassign";
this.UnassignButton.UseVisualStyleBackColor = true;
this.UnassignButton.Click += new System.EventHandler(this.UnassignButton_Click);
//
// AssignButton
//
this.AssignButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.AssignButton, false);
this.AssignButton.Location = new System.Drawing.Point(368, 19);
this.AssignButton.Name = "AssignButton";
this.AssignButton.Size = new System.Drawing.Size(75, 23);
this.AssignButton.TabIndex = 1;
this.AssignButton.Text = "Assign";
this.AssignButton.UseVisualStyleBackColor = true;
this.AssignButton.Click += new System.EventHandler(this.AssignButton_Click);
//
// FirstNameTextBox
//
this.FirstNameTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.FirstNameTextBox, true);
this.FirstNameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ResourceBindingSource, "FirstName", true));
this.FirstNameTextBox.Location = new System.Drawing.Point(80, 39);
this.FirstNameTextBox.Name = "FirstNameTextBox";
this.FirstNameTextBox.Size = new System.Drawing.Size(385, 20);
this.FirstNameTextBox.TabIndex = 3;
//
// IdLabel1
//
this.IdLabel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.IdLabel1, true);
this.IdLabel1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ResourceBindingSource, "Id", true));
this.IdLabel1.Location = new System.Drawing.Point(80, 13);
this.IdLabel1.Name = "IdLabel1";
this.IdLabel1.Size = new System.Drawing.Size(385, 23);
this.IdLabel1.TabIndex = 1;
//
// LastNameTextBox
//
this.LastNameTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.LastNameTextBox, true);
this.LastNameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ResourceBindingSource, "LastName", true));
this.LastNameTextBox.Location = new System.Drawing.Point(80, 65);
this.LastNameTextBox.Name = "LastNameTextBox";
this.LastNameTextBox.Size = new System.Drawing.Size(385, 20);
this.LastNameTextBox.TabIndex = 5;
//
// ErrorProvider1
//
this.ErrorProvider1.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink;
this.ErrorProvider1.ContainerControl = this;
this.ErrorProvider1.DataSource = this.ResourceBindingSource;
//
// RefreshButton
//
this.RefreshButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ReadWriteAuthorization1.SetApplyAuthorization(this.RefreshButton, false);
this.RefreshButton.Location = new System.Drawing.Point(501, 129);
this.RefreshButton.Name = "RefreshButton";
this.RefreshButton.Size = new System.Drawing.Size(75, 23);
this.RefreshButton.TabIndex = 11;
this.RefreshButton.Text = "Refresh";
this.RefreshButton.UseVisualStyleBackColor = true;
this.RefreshButton.Click += new System.EventHandler(this.RefreshButton_Click);
//
// bindingSourceRefresh1
//
this.bindingSourceRefresh1.Host = this;
//
// projectIdDataGridViewTextBoxColumn
//
this.ProjectId.DataPropertyName = "ProjectId";
this.ProjectId.HeaderText = "ProjectId";
this.ProjectId.Name = "ProjectId";
this.ProjectId.ReadOnly = true;
this.ProjectId.Visible = false;
this.ProjectId.Width = 74;
//
// projectNameDataGridViewTextBoxColumn
//
this.ProjectName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ProjectName.DataPropertyName = "ProjectName";
this.ProjectName.FillWeight = 200F;
this.ProjectName.HeaderText = "Project Name";
this.ProjectName.Name = "ProjectName";
this.ProjectName.ReadOnly = true;
this.ProjectName.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.ProjectName.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
//
// assignedDataGridViewTextBoxColumn
//
this.Assigned.DataPropertyName = "Assigned";
this.Assigned.HeaderText = "Assigned";
this.Assigned.Name = "Assigned";
this.Assigned.ReadOnly = true;
this.Assigned.Width = 75;
//
// Role
//
this.Role.DataPropertyName = "Role";
this.Role.DataSource = this.RoleListBindingSource;
this.Role.DisplayMember = "Value";
this.Role.FillWeight = 200F;
this.Role.HeaderText = "Role";
this.Role.Name = "Role";
this.Role.ValueMember = "Key";
this.Role.Width = 35;
//
// ResourceEdit
//
this.ReadWriteAuthorization1.SetApplyAuthorization(this, false);
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.RefreshButton);
this.Controls.Add(this.CloseButton);
this.Controls.Add(this.ApplyButton);
this.Controls.Add(this.Cancel_Button);
this.Controls.Add(this.OKButton);
this.Controls.Add(this.GroupBox1);
this.Controls.Add(FirstNameLabel);
this.Controls.Add(this.FirstNameTextBox);
this.Controls.Add(IdLabel);
this.Controls.Add(this.IdLabel1);
this.Controls.Add(LastNameLabel);
this.Controls.Add(this.LastNameTextBox);
this.Name = "ResourceEdit";
this.Size = new System.Drawing.Size(588, 415);
this.Load += new System.EventHandler(this.ResourceEdit_Load);
this.GroupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.AssignmentsDataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.RoleListBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.AssignmentsBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ResourceBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ErrorProvider1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.bindingSourceRefresh1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
internal System.Windows.Forms.Button CloseButton;
internal System.Windows.Forms.Button ApplyButton;
internal System.Windows.Forms.Button Cancel_Button;
internal System.Windows.Forms.Button OKButton;
internal System.Windows.Forms.GroupBox GroupBox1;
internal System.Windows.Forms.Button UnassignButton;
internal System.Windows.Forms.Button AssignButton;
internal System.Windows.Forms.TextBox FirstNameTextBox;
internal System.Windows.Forms.Label IdLabel1;
internal System.Windows.Forms.TextBox LastNameTextBox;
internal Csla.Windows.ReadWriteAuthorization ReadWriteAuthorization1;
internal System.Windows.Forms.DataGridView AssignmentsDataGridView;
internal System.Windows.Forms.BindingSource RoleListBindingSource;
internal System.Windows.Forms.BindingSource AssignmentsBindingSource;
internal System.Windows.Forms.BindingSource ResourceBindingSource;
internal System.Windows.Forms.ErrorProvider ErrorProvider1;
private Csla.Windows.BindingSourceRefresh bindingSourceRefresh1;
internal System.Windows.Forms.Button RefreshButton;
private System.Windows.Forms.DataGridViewTextBoxColumn ProjectId;
private System.Windows.Forms.DataGridViewLinkColumn ProjectName;
private System.Windows.Forms.DataGridViewTextBoxColumn Assigned;
private System.Windows.Forms.DataGridViewComboBoxColumn Role;
}
}
| |
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEngine.Audio;
using System.Collections;
// GVR soundfield component that allows playback of first-order ambisonic recordings. The
// audio sample should be in Ambix (ACN-SN3D) format.
[AddComponentMenu("GoogleVR/Audio/GvrAudioSoundfield")]
public class GvrAudioSoundfield : MonoBehaviour {
/// Input gain in decibels.
public float gainDb = 0.0f;
/// Play source on awake.
public bool playOnAwake = true;
/// The default AudioClip to play.
public AudioClip clip0102 {
get { return soundfieldClip0102; }
set {
soundfieldClip0102 = value;
if (audioSources != null && audioSources.Length > 0) {
audioSources[0].clip = soundfieldClip0102;
}
}
}
[SerializeField]
private AudioClip soundfieldClip0102 = null;
public AudioClip clip0304 {
get { return soundfieldClip0304; }
set {
soundfieldClip0304 = value;
if (audioSources != null && audioSources.Length > 0) {
audioSources[1].clip = soundfieldClip0304;
}
}
}
[SerializeField]
private AudioClip soundfieldClip0304 = null;
/// Is the clip playing right now (Read Only)?
public bool isPlaying {
get {
if(audioSources != null && audioSources.Length > 0) {
return audioSources[0].isPlaying;
}
return false;
}
}
/// Is the audio clip looping?
public bool loop {
get { return soundfieldLoop; }
set {
soundfieldLoop = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].loop = soundfieldLoop;
}
}
}
}
[SerializeField]
private bool soundfieldLoop = false;
/// Un- / Mutes the soundfield. Mute sets the volume=0, Un-Mute restore the original volume.
public bool mute {
get { return soundfieldMute; }
set {
soundfieldMute = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].mute = soundfieldMute;
}
}
}
}
[SerializeField]
private bool soundfieldMute = false;
/// The pitch of the audio source.
public float pitch {
get { return soundfieldPitch; }
set {
soundfieldPitch = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].pitch = soundfieldPitch;
}
}
}
}
[SerializeField]
[Range(-3.0f, 3.0f)]
private float soundfieldPitch = 1.0f;
/// Sets the priority of the soundfield.
public int priority {
get { return soundfieldPriority; }
set {
soundfieldPriority = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].priority = soundfieldPriority;
}
}
}
}
[SerializeField]
[Range(0, 256)]
private int soundfieldPriority = 32;
/// Playback position in seconds.
public float time {
get {
if(audioSources != null && audioSources.Length > 0) {
return audioSources[0].time;
}
return 0.0f;
}
set {
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].time = value;
}
}
}
}
/// Playback position in PCM samples.
public int timeSamples {
get {
if(audioSources != null && audioSources.Length > 0) {
return audioSources[0].timeSamples;
}
return 0;
}
set {
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].timeSamples = value;
}
}
}
}
/// The volume of the audio source (0.0 to 1.0).
public float volume {
get { return soundfieldVolume; }
set {
soundfieldVolume = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].volume = soundfieldVolume;
}
}
}
}
[SerializeField]
[Range(0.0f, 1.0f)]
private float soundfieldVolume = 1.0f;
// Unique source id.
private int id = -1;
// Unity audio sources per each soundfield channel set.
private AudioSource[] audioSources = null;
// Denotes whether the source is currently paused or not.
private bool isPaused = false;
void Awake () {
// Route the source output to |GvrAudioMixer|.
AudioMixer mixer = (Resources.Load("GvrAudioMixer") as AudioMixer);
if(mixer == null) {
Debug.LogError("GVRAudioMixer could not be found in Resources. Make sure that the GVR SDK" +
"Unity package is imported properly.");
return;
}
audioSources = new AudioSource[GvrAudio.numFoaChannels / 2];
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
GameObject channelSetObject = new GameObject("Channel Set " + channelSet);
channelSetObject.transform.parent = gameObject.transform;
channelSetObject.hideFlags = HideFlags.HideAndDontSave;
audioSources[channelSet] = channelSetObject.AddComponent<AudioSource>();
audioSources[channelSet].enabled = false;
audioSources[channelSet].playOnAwake = false;
audioSources[channelSet].bypassReverbZones = true;
audioSources[channelSet].dopplerLevel = 0.0f;
audioSources[channelSet].spatialBlend = 0.0f;
audioSources[channelSet].outputAudioMixerGroup = mixer.FindMatchingGroups("Master")[0];
}
OnValidate();
}
void OnEnable () {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].enabled = true;
}
if (playOnAwake && !isPlaying && InitializeSoundfield()) {
Play();
}
}
void Start () {
if (playOnAwake && !isPlaying) {
Play();
}
}
void OnDisable () {
Stop();
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].enabled = false;
}
}
void OnDestroy () {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
Destroy(audioSources[channelSet].gameObject);
}
}
void OnApplicationPause (bool pauseStatus) {
if (pauseStatus) {
Pause();
} else {
UnPause();
}
}
void Update () {
// Update soundfield.
if (!isPlaying && !isPaused) {
Stop();
} else {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].SetSpatializerFloat((int) GvrAudio.SpatializerData.Gain,
GvrAudio.ConvertAmplitudeFromDb(gainDb));
}
}
}
void OnValidate () {
clip0102 = soundfieldClip0102;
clip0304 = soundfieldClip0304;
loop = soundfieldLoop;
mute = soundfieldMute;
pitch = soundfieldPitch;
priority = soundfieldPriority;
volume = soundfieldVolume;
}
/// Pauses playing the clip.
public void Pause () {
if (audioSources != null) {
isPaused = true;
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].Pause();
}
}
}
/// Plays the clip.
public void Play () {
double dspTime = AudioSettings.dspTime;
PlayScheduled(dspTime);
}
/// Plays the clip with a delay specified in seconds.
public void PlayDelayed (float delay) {
double delayedDspTime = AudioSettings.dspTime + (double)delay;
PlayScheduled(delayedDspTime);
}
/// Plays the clip at a specific time on the absolute time-line that AudioSettings.dspTime reads
/// from.
public void PlayScheduled (double time) {
if (audioSources != null && InitializeSoundfield()) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].PlayScheduled(time);
}
isPaused = false;
} else {
Debug.LogWarning ("GVR Audio soundfield not initialized. Audio playback not supported " +
"until after Awake() and OnEnable(). Try calling from Start() instead.");
}
}
/// Stops playing the clip.
public void Stop () {
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].Stop();
}
ShutdownSoundfield();
isPaused = false;
}
}
/// Unpauses the paused playback.
public void UnPause () {
if (audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].UnPause();
}
isPaused = true;
}
}
// Initializes the source.
private bool InitializeSoundfield () {
if (id < 0) {
id = GvrAudio.CreateAudioSoundfield();
if (id >= 0) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
InitializeChannelSet(audioSources[channelSet], channelSet);
}
}
}
return id >= 0;
}
// Shuts down the source.
private void ShutdownSoundfield () {
if (id >= 0) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
ShutdownChannelSet(audioSources[channelSet], channelSet);
}
GvrAudio.DestroyAudioSoundfield(id);
id = -1;
}
}
// Initializes given channel set of the soundfield.
private void InitializeChannelSet(AudioSource source, int channelSet) {
source.spatialize = true;
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.Type,
(float) GvrAudio.SpatializerType.Soundfield);
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.NumChannels,
(float) GvrAudio.numFoaChannels);
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.ChannelSet, (float) channelSet);
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.Gain,
GvrAudio.ConvertAmplitudeFromDb(gainDb));
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.ZeroOutput, 0.0f);
// Soundfield id must be set after all the spatializer parameters, to ensure that the soundfield
// is properly initialized before processing.
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.Id, (float) id);
}
// Shuts down given channel set of the soundfield.
private void ShutdownChannelSet(AudioSource source, int channelSet) {
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.Id, -1.0f);
// Ensure that the output is zeroed after shutdown.
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.ZeroOutput, 1.0f);
source.spatialize = false;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Maps;
using Signum.Engine.Operations;
using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Entities.Isolation;
using Signum.Utilities;
using Signum.Utilities.Reflection;
using Signum.Engine.Processes;
using Signum.Entities.Processes;
using Signum.Entities.Scheduler;
namespace Signum.Engine.Isolation
{
public static class IsolationLogic
{
public static bool IsStarted;
public static ResetLazy<List<Lite<IsolationEntity>>> Isolations = null!;
internal static Dictionary<Type, IsolationStrategy> strategies = new Dictionary<Type, IsolationStrategy>();
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
sb.Include<IsolationEntity>()
.WithSave(IsolationOperation.Save)
.WithQuery(() => iso => new
{
Entity = iso,
iso.Id,
iso.Name
});
sb.Schema.EntityEventsGlobal.PreSaving += EntityEventsGlobal_PreSaving;
sb.Schema.SchemaCompleted += AssertIsolationStrategies;
OperationLogic.SurroundOperation += OperationLogic_SurroundOperation;
Isolations = sb.GlobalLazy(() => Database.RetrieveAllLite<IsolationEntity>(),
new InvalidateWith(typeof(IsolationEntity)));
ProcessLogic.ApplySession += ProcessLogic_ApplySession;
Validator.OverridePropertyValidator((IsolationMixin m) => m.Isolation).StaticPropertyValidation += (mi, pi) =>
{
if (strategies.GetOrThrow(mi.MainEntity.GetType()) == IsolationStrategy.Isolated && mi.Isolation == null)
return ValidationMessage._0IsNotSet.NiceToString(pi.NiceName());
return null;
};
IsStarted = true;
}
}
static IDisposable? ProcessLogic_ApplySession(ProcessEntity process)
{
return IsolationEntity.Override(process.Data!.TryIsolation());
}
static IDisposable? OperationLogic_SurroundOperation(IOperation operation, OperationLogEntity log, Entity? entity, object?[]? args)
{
return IsolationEntity.Override(entity?.TryIsolation() ?? args.TryGetArgC<Lite<IsolationEntity>>());
}
static void EntityEventsGlobal_PreSaving(Entity ident, PreSavingContext ctx)
{
if (strategies.TryGet(ident.GetType(), IsolationStrategy.None) != IsolationStrategy.None && IsolationEntity.Current != null)
{
if (ident.Mixin<IsolationMixin>().Isolation == null)
{
ident.Mixin<IsolationMixin>().Isolation = IsolationEntity.Current;
ctx.InvalidateGraph();
}
else if (!ident.Mixin<IsolationMixin>().Isolation.Is(IsolationEntity.Current))
throw new ApplicationException(IsolationMessage.Entity0HasIsolation1ButCurrentIsolationIs2.NiceToString(ident, ident.Mixin<IsolationMixin>().Isolation, IsolationEntity.Current));
}
}
static void AssertIsolationStrategies()
{
var result = EnumerableExtensions.JoinStrict(
strategies.Keys,
Schema.Current.Tables.Keys.Where(a => !a.IsEnumEntityOrSymbol() && !typeof(SemiSymbol).IsAssignableFrom(a)),
a => a,
a => a,
(a, b) => 0);
var extra = result.Extra.OrderBy(a => a.Namespace).ThenBy(a => a.Name).ToString(t => " IsolationLogic.Register<{0}>(IsolationStrategy.XXX);".FormatWith(t.Name), "\r\n");
var lacking = result.Missing.GroupBy(a => a.Namespace).OrderBy(gr => gr.Key).ToString(gr => " //{0}\r\n".FormatWith(gr.Key) +
gr.ToString(t => " IsolationLogic.Register<{0}>(IsolationStrategy.XXX);".FormatWith(t.Name), "\r\n"), "\r\n\r\n");
if (extra.HasText() || lacking.HasText())
throw new InvalidOperationException("IsolationLogic's strategies are not synchronized with the Schema.\r\n" +
(extra.HasText() ? ("Remove something like:\r\n" + extra + "\r\n\r\n") : null) +
(lacking.HasText() ? ("Add something like:\r\n" + lacking + "\r\n\r\n") : null));
foreach (var item in strategies.Where(kvp => kvp.Value == IsolationStrategy.Isolated || kvp.Value == IsolationStrategy.Optional).Select(a => a.Key))
{
giRegisterFilterQuery.GetInvoker(item)();
}
Schema.Current.EntityEvents<IsolationEntity>().FilterQuery += () =>
{
if (IsolationEntity.Current == null || ExecutionMode.InGlobal)
return null;
return new FilterQueryResult<IsolationEntity>(
a => a.ToLite().Is(IsolationEntity.Current),
a => a.ToLite().Is(IsolationEntity.Current));
};
}
public static IsolationStrategy GetStrategy(Type type)
{
return strategies[type];
}
static readonly GenericInvoker<Action> giRegisterFilterQuery = new GenericInvoker<Action>(() => Register_FilterQuery<Entity>());
static void Register_FilterQuery<T>() where T : Entity
{
Schema.Current.EntityEvents<T>().FilterQuery += () =>
{
if (ExecutionMode.InGlobal || IsolationEntity.Current == null)
return null;
return new FilterQueryResult<T>(
a => a.Mixin<IsolationMixin>().Isolation.Is(IsolationEntity.Current),
a => a.Mixin<IsolationMixin>().Isolation.Is(IsolationEntity.Current));
};
Schema.Current.EntityEvents<T>().PreUnsafeInsert += (IQueryable query, LambdaExpression constructor, IQueryable<T> entityQuery) =>
{
if (ExecutionMode.InGlobal || IsolationEntity.Current == null)
return constructor;
if (constructor.Body.Type == typeof(T))
{
var newBody = Expression.Call(
miSetMixin.MakeGenericMethod(typeof(T), typeof(IsolationMixin), typeof(Lite<IsolationEntity>)),
constructor.Body,
Expression.Quote(IsolationLambda),
Expression.Constant(IsolationEntity.Current));
return Expression.Lambda(newBody, constructor.Parameters);
}
return constructor; //MListTable
};
}
static MethodInfo miSetMixin = ReflectionTools.GetMethodInfo((Entity a) => a.SetMixin((IsolationMixin m) => m.Isolation, null)).GetGenericMethodDefinition();
static Expression<Func<IsolationMixin, Lite<IsolationEntity>?>> IsolationLambda = (IsolationMixin m) => m.Isolation;
public static void Register<T>(IsolationStrategy strategy) where T : Entity
{
strategies.Add(typeof(T), strategy);
if (strategy == IsolationStrategy.Isolated || strategy == IsolationStrategy.Optional)
MixinDeclarations.Register(typeof(T), typeof(IsolationMixin));
if (strategy == IsolationStrategy.Optional)
{
Schema.Current.Settings.FieldAttributes((T e) => e.Mixin<IsolationMixin>().Isolation).Remove<ForceNotNullableAttribute>(); //Remove non-null
}
}
public static IEnumerable<T> WhereCurrentIsolationInMemory<T>(this IEnumerable<T> collection) where T : Entity
{
var curr = IsolationEntity.Current;
if (curr == null || strategies[typeof(T)] == IsolationStrategy.None)
return collection;
return collection.Where(a => a.Isolation().Is(curr));
}
public static Lite<IsolationEntity>? GetOnlyIsolation(List<Lite<Entity>> selectedEntities)
{
return selectedEntities.GroupBy(a => a.EntityType)
.Select(gr => strategies[gr.Key] == IsolationStrategy.None ? null : giGetOnlyIsolation.GetInvoker(gr.Key)(gr))
.NotNull()
.Only();
}
static GenericInvoker<Func<IEnumerable<Lite<Entity>>, Lite<IsolationEntity>?>> giGetOnlyIsolation =
new GenericInvoker<Func<IEnumerable<Lite<Entity>>, Lite<IsolationEntity>?>>(list => GetOnlyIsolation<Entity>(list));
public static Lite<IsolationEntity>? GetOnlyIsolation<T>(IEnumerable<Lite<Entity>> selectedEntities) where T : Entity
{
return selectedEntities.Cast<Lite<T>>().GroupsOf(100).Select(gr =>
Database.Query<T>().Where(e => gr.Contains(e.ToLite())).Select(e => e.Isolation()).Only()
).NotNull().Only();
}
public static Dictionary<Type, IsolationStrategy> GetIsolationStrategies()
{
return strategies.ToDictionary();
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
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 [email protected] or visit
the website www.fyiReporting.com.
*/
using fyiReporting.RDL;
using fyiReporting.RdlDesign.Resources;
using fyiReporting.RdlDesign.Syntax;
using fyiReporting.RdlViewer;
using ScintillaNET;
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Xml;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for RdlEditPreview.
/// </summary>
internal class RdlEditPreview : System.Windows.Forms.UserControl
{
private System.Windows.Forms.TabControl tcEHP;
private System.Windows.Forms.TabPage tpEditor;
private System.Windows.Forms.TabPage tpBrowser;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private fyiReporting.RdlViewer.RdlViewer rdlPreview;
private System.Windows.Forms.TabPage tpDesign;
private DesignCtl dcDesign;
public FindTab FindTab;
public delegate void RdlChangeHandler(object sender, EventArgs e);
public event RdlChangeHandler OnRdlChanged;
public event DesignCtl.HeightEventHandler OnHeightChanged;
public event RdlChangeHandler OnSelectionChanged;
public event RdlChangeHandler OnSelectionMoved;
public event RdlChangeHandler OnReportItemInserted;
public event RdlChangeHandler OnDesignTabChanged;
public event DesignCtl.OpenSubreportEventHandler OnOpenSubreport;
// When toggling between the items we need to track who has latest changes
DesignTabs _DesignChanged; // last designer that triggered change
DesignTabs _CurrentTab = DesignTabs.Design;
private DesignRuler dcTopRuler;
private DesignRuler dcLeftRuler;
private Scintilla scintilla1; // file position; for use with search
private bool noFireRDLTextChanged;
// Indicators 0-7 could be in use by a lexer
// so we'll use indicator 8 to highlight words.
const int SEARCH_INDICATOR_NUM = 8;
public RdlEditPreview()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
rdlPreview.Zoom=1; // force default zoom to 1
// initialize the design tab
dcTopRuler = new DesignRuler();
dcLeftRuler = new DesignRuler();
dcLeftRuler.Vertical = true; // need to set before setting Design property
dcDesign = new DesignCtl();
dcTopRuler.Design = dcDesign; // associate rulers with design ctl
dcLeftRuler.Design = dcDesign;
tpDesign.Controls.Add(dcTopRuler);
tpDesign.Controls.Add(dcLeftRuler);
tpDesign.Controls.Add(dcDesign);
// Top ruler
dcTopRuler.Height = 14;
dcTopRuler.Width = tpDesign.Width;
dcTopRuler.Dock = DockStyle.Top;
dcTopRuler.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
dcTopRuler.Enabled = false;
// Left ruler
dcLeftRuler.Width = 14;
dcLeftRuler.Height = tpDesign.Height;
dcLeftRuler.Dock = DockStyle.Left;
dcLeftRuler.Anchor = AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Top;
dcLeftRuler.Enabled = false;
dcTopRuler.Offset = dcLeftRuler.Width;
dcLeftRuler.Offset = dcTopRuler.Height;
// dcDesign.Dock = System.Windows.Forms.DockStyle.Bottom;
dcDesign.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
dcDesign.Location = new System.Drawing.Point(dcLeftRuler.Width, dcTopRuler.Height);
dcDesign.Name = "dcDesign";
dcDesign.Size = new System.Drawing.Size(tpDesign.Width-dcLeftRuler.Width, tpDesign.Height-dcTopRuler.Height);
dcDesign.TabIndex = 0;
dcDesign.ReportChanged += new System.EventHandler(dcDesign_ReportChanged);
dcDesign.HeightChanged += new DesignCtl.HeightEventHandler(dcDesign_HeightChanged);
dcDesign.SelectionChanged += new System.EventHandler(dcDesign_SelectionChanged);
dcDesign.SelectionMoved += new System.EventHandler(dcDesign_SelectionMoved);
dcDesign.ReportItemInserted += new System.EventHandler(dcDesign_ReportItemInserted);
dcDesign.OpenSubreport += new DesignCtl.OpenSubreportEventHandler(dcDesign_OpenSubreport);
//ScintillaNET Init
ScintillaXMLStyle.ConfigureScintillaStyle(scintilla1);
scintilla1.SetSavePoint();
}
void scintilla1_TextChanged(object sender, EventArgs e)
{
_DesignChanged = DesignTabs.Edit;
if (noFireRDLTextChanged)
return;
if (OnRdlChanged != null)
{
OnRdlChanged(this, e);
}
}
internal DesignCtl DesignCtl
{
get {return dcDesign;}
}
internal RdlViewer.RdlViewer PreviewCtl
{
get { return rdlPreview; }
}
internal DesignXmlDraw DrawCtl
{
get {return dcDesign.DrawCtl;}
}
public XmlDocument ReportDocument
{
get {return dcDesign.ReportDocument;}
}
internal DesignTabs DesignTab
{
get {return _CurrentTab;}
set
{
tcEHP.SelectedIndex = (int)value;
}
}
internal void SetFocus()
{
switch (_CurrentTab)
{
case DesignTabs.Edit:
scintilla1.Focus();
break;
case DesignTabs.Preview:
rdlPreview.Focus();
break;
case DesignTabs.Design:
dcDesign.SetFocus();
break;
}
}
internal void ShowEditLines(bool bShow)
{
scintilla1.Margins[0].Width = bShow ? 40 : 0;
}
internal void ShowPreviewWaitDialog(bool bShow)
{
rdlPreview.ShowWaitDialog = bShow;
}
internal bool ShowReportItemOutline
{
get {return dcDesign.ShowReportItemOutline;}
set {dcDesign.ShowReportItemOutline = value;}
}
override public string Text
{
get
{
if (_CurrentTab == DesignTabs.Design)
return dcDesign.ReportSource;
else
return scintilla1.Text;
}
set
{
if (_CurrentTab == DesignTabs.Edit)
SetTextToScintilla(value);
else
{
dcDesign.ReportSource = value;
}
if (_CurrentTab == DesignTabs.Preview)
{
_CurrentTab = DesignTabs.Design;
tcEHP.SelectedIndex = 0; // Force current tab to design
}
}
}
public StyleInfo SelectedStyle
{
get {return dcDesign.SelectedStyle;}
}
public string SelectionName
{
get {return dcDesign.SelectionName;}
}
public PointF SelectionPosition
{
get {return dcDesign.SelectionPosition;}
}
public SizeF SelectionSize
{
get {return dcDesign.SelectionSize;}
}
public void ApplyStyleToSelected(string name, string v)
{
if (_CurrentTab == DesignTabs.Design)
dcDesign.ApplyStyleToSelected(name, v);
}
public void SetSelectedText(string v)
{
if (_CurrentTab == DesignTabs.Design)
dcDesign.SetSelectedText(v);
}
public bool CanEdit
{
get
{
return _CurrentTab != DesignTabs.Preview;
}
}
private bool modified = false;
public bool Modified
{
get
{
return modified || scintilla1.Modified;
}
set
{
_DesignChanged = _CurrentTab;
modified = value;
if (value == false)
scintilla1.SetSavePoint();
}
}
public string UndoDescription
{
get
{
return _CurrentTab == DesignTabs.Design? dcDesign.UndoDescription: "";
}
}
public void StartUndoGroup(string description)
{
if (_CurrentTab == DesignTabs.Design)
dcDesign.StartUndoGroup(description);
}
public void EndUndoGroup(bool keepChanges)
{
if (_CurrentTab == DesignTabs.Design)
dcDesign.EndUndoGroup(keepChanges);
}
public bool CanUndo
{
get
{
switch (_CurrentTab)
{
case DesignTabs.Design:
return dcDesign.CanUndo;
case DesignTabs.Edit:
return scintilla1.CanUndo;
default:
return false;
}
}
}
public bool CanRedo
{
get
{
switch (_CurrentTab)
{
case DesignTabs.Design:
return dcDesign.CanUndo;
case DesignTabs.Edit:
return scintilla1.CanRedo;
default:
return false;
}
}
}
public int SelectionLength
{
get
{
switch (_CurrentTab)
{
case DesignTabs.Design:
return dcDesign.SelectionCount;
case DesignTabs.Edit:
return scintilla1.SelectedText.Length;
case DesignTabs.Preview:
return rdlPreview.CanCopy ? 1 : 0;
default:
return 0;
}
}
}
public string SelectedText
{
get
{
switch (_CurrentTab)
{
case DesignTabs.Design:
return dcDesign.SelectedText;
case DesignTabs.Edit:
return scintilla1.SelectedText;
case DesignTabs.Preview:
return rdlPreview.SelectText;
default:
return "";
}
}
set
{
if (_CurrentTab == DesignTabs.Edit && String.IsNullOrWhiteSpace(value))
scintilla1.ClearSelections();
else if (_CurrentTab == DesignTabs.Design && value.Length == 0)
dcDesign.Delete();
}
}
public void CleanUp()
{
}
public void ClearUndo()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.ClearUndo();
break;
case DesignTabs.Edit:
scintilla1.EmptyUndoBuffer();
break;
default:
break;
}
}
public void Undo()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.Undo();
break;
case DesignTabs.Edit:
scintilla1.Undo();
break;
default:
break;
}
}
public void Redo()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.Redo();
break;
case DesignTabs.Edit:
scintilla1.Redo();
break;
default:
break;
}
}
public void Cut()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.Cut();
break;
case DesignTabs.Edit:
scintilla1.Cut();
break;
default:
break;
}
}
public void Copy()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.Copy();
break;
case DesignTabs.Edit:
scintilla1.Copy();
break;
case DesignTabs.Preview:
rdlPreview.Copy();
break;
default:
break;
}
}
public void Clear()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.Clear();
break;
case DesignTabs.Edit:
scintilla1.Clear();
break;
default:
break;
}
}
public void Paste()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.Paste();
break;
case DesignTabs.Edit:
scintilla1.Paste();
break;
default:
break;
}
}
public void SelectAll()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.SelectAll();
break;
case DesignTabs.Edit:
scintilla1.SelectAll();
break;
default:
break;
}
}
public string CurrentInsert
{
get {return dcDesign.CurrentInsert; }
set
{
dcDesign.CurrentInsert = value;
}
}
public int CurrentLine
{
get
{
return scintilla1.CurrentLine + 1;
}
}
public int CurrentCh
{
get
{
return scintilla1.GetColumn(scintilla1.CurrentPosition);
}
}
public bool SelectionTool
{
get
{
if (_CurrentTab == DesignTabs.Preview)
{
return rdlPreview.SelectTool;
}
else
return false;
}
set
{
if (_CurrentTab == DesignTabs.Preview)
{
rdlPreview.SelectTool = value;
}
}
}
/// <summary>
/// Zoom
/// </summary>
public float Zoom
{
get {return this.rdlPreview.Zoom;}
set {this.rdlPreview.Zoom = value;}
}
/// <summary>
/// ZoomMode
/// </summary>
public ZoomEnum ZoomMode
{
get {return this.rdlPreview.ZoomMode;}
set {this.rdlPreview.ZoomMode = value;}
}
public void FindNext(Control ctl, string str, bool matchCase, bool revertSearch, bool showEndMsg = true)
{
if (_CurrentTab != DesignTabs.Edit)
return;
scintilla1.SearchFlags = matchCase ? SearchFlags.MatchCase : SearchFlags.None;
HighlightWord(str);
if (revertSearch)
{
scintilla1.TargetStart = scintilla1.SelectionStart;
scintilla1.TargetEnd = 0;
}
else
{
scintilla1.TargetStart = scintilla1.SelectionEnd;
scintilla1.TargetEnd = scintilla1.TextLength;
}
var pos = scintilla1.SearchInTarget(str);
if (pos == -1)
{
if (showEndMsg)
MessageBox.Show(ctl, Strings.RdlEditPreview_ShowI_ReachedEndDocument);
}
else
{
scintilla1.GotoPosition(pos);
scintilla1.SelectionStart = scintilla1.TargetStart;
scintilla1.SelectionEnd = scintilla1.TargetEnd;
}
}
private void HighlightWord(string text)
{
// Remove all uses of our indicator
scintilla1.IndicatorCurrent = SEARCH_INDICATOR_NUM;
scintilla1.IndicatorClearRange(0, scintilla1.TextLength);
// Update indicator appearance
scintilla1.Indicators[SEARCH_INDICATOR_NUM].Style = IndicatorStyle.StraightBox;
scintilla1.Indicators[SEARCH_INDICATOR_NUM].Under = true;
scintilla1.Indicators[SEARCH_INDICATOR_NUM].ForeColor = Color.Orange;
scintilla1.Indicators[SEARCH_INDICATOR_NUM].OutlineAlpha = 50;
scintilla1.Indicators[SEARCH_INDICATOR_NUM].Alpha = 30;
// Search the document
scintilla1.TargetStart = 0;
scintilla1.TargetEnd = scintilla1.TextLength;
while (scintilla1.SearchInTarget(text) != -1)
{
// Mark the search results with the current indicator
scintilla1.IndicatorFillRange(scintilla1.TargetStart, scintilla1.TargetEnd - scintilla1.TargetStart);
// Search the remainder of the document
scintilla1.TargetStart = scintilla1.TargetEnd;
scintilla1.TargetEnd = scintilla1.TextLength;
}
}
public void ClearSearchHighlight()
{
scintilla1.IndicatorCurrent = SEARCH_INDICATOR_NUM;
scintilla1.IndicatorClearRange(0, scintilla1.TextLength);
FindTab = null;
}
public void ReplaceNext(Control ctl, string str, string strReplace, bool matchCase)
{
if (_CurrentTab != DesignTabs.Edit)
return;
if (String.Compare(scintilla1.SelectedText, str, !matchCase) == 0)
{
scintilla1.ReplaceSelection(strReplace);
}
else
{
FindNext(ctl, str, matchCase, false);
if (String.Compare(scintilla1.SelectedText, str, !matchCase) == 0)
scintilla1.ReplaceSelection(strReplace);
}
}
public void ReplaceAll(Control ctl, string str, string strReplace, bool matchCase)
{
if (_CurrentTab != DesignTabs.Edit)
return;
scintilla1.TargetStart = 0;
scintilla1.TargetEnd = scintilla1.TextLength;
scintilla1.SearchFlags = matchCase ? SearchFlags.MatchCase : SearchFlags.None;
while (scintilla1.SearchInTarget(str) != -1)
{
scintilla1.ReplaceTarget(strReplace);
// Search the remainder of the document
scintilla1.TargetStart = scintilla1.TargetEnd;
scintilla1.TargetEnd = scintilla1.TextLength;
}
}
public void Goto(Control ctl, int nLine)
{
if (_CurrentTab != DesignTabs.Edit)
return;
if(nLine > scintilla1.Lines.Count)
nLine = scintilla1.Lines.Count;
scintilla1.Lines[nLine-1].Goto();
scintilla1.SelectionStart = scintilla1.Lines[nLine - 1].Position;
scintilla1.SelectionEnd = scintilla1.Lines[nLine - 1].EndPosition;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RdlEditPreview));
this.tcEHP = new System.Windows.Forms.TabControl();
this.tpDesign = new System.Windows.Forms.TabPage();
this.tpEditor = new System.Windows.Forms.TabPage();
this.scintilla1 = new ScintillaNET.Scintilla();
this.tpBrowser = new System.Windows.Forms.TabPage();
this.rdlPreview = new fyiReporting.RdlViewer.RdlViewer();
this.tcEHP.SuspendLayout();
this.tpEditor.SuspendLayout();
this.tpBrowser.SuspendLayout();
this.SuspendLayout();
//
// tcEHP
//
resources.ApplyResources(this.tcEHP, "tcEHP");
this.tcEHP.Controls.Add(this.tpDesign);
this.tcEHP.Controls.Add(this.tpEditor);
this.tcEHP.Controls.Add(this.tpBrowser);
this.tcEHP.Name = "tcEHP";
this.tcEHP.SelectedIndex = 0;
this.tcEHP.SelectedIndexChanged += new System.EventHandler(this.tcEHP_SelectedIndexChanged);
//
// tpDesign
//
resources.ApplyResources(this.tpDesign, "tpDesign");
this.tpDesign.Name = "tpDesign";
this.tpDesign.Tag = "design";
//
// tpEditor
//
this.tpEditor.Controls.Add(this.scintilla1);
resources.ApplyResources(this.tpEditor, "tpEditor");
this.tpEditor.Name = "tpEditor";
this.tpEditor.Tag = "edit";
//
// scintilla1
//
resources.ApplyResources(this.scintilla1, "scintilla1");
this.scintilla1.Lexer = ScintillaNET.Lexer.Xml;
this.scintilla1.Name = "scintilla1";
this.scintilla1.UseTabs = false;
this.scintilla1.UpdateUI += new System.EventHandler<ScintillaNET.UpdateUIEventArgs>(this.scintilla1_UpdateUI);
this.scintilla1.TextChanged += new System.EventHandler(this.scintilla1_TextChanged);
//
// tpBrowser
//
this.tpBrowser.Controls.Add(this.rdlPreview);
resources.ApplyResources(this.tpBrowser, "tpBrowser");
this.tpBrowser.Name = "tpBrowser";
this.tpBrowser.Tag = "preview";
//
// rdlPreview
//
this.rdlPreview.Cursor = System.Windows.Forms.Cursors.Default;
resources.ApplyResources(this.rdlPreview, "rdlPreview");
this.rdlPreview.dSubReportGetContent = null;
this.rdlPreview.Folder = null;
this.rdlPreview.HighlightAll = false;
this.rdlPreview.HighlightAllColor = System.Drawing.Color.Fuchsia;
this.rdlPreview.HighlightCaseSensitive = false;
this.rdlPreview.HighlightItemColor = System.Drawing.Color.Aqua;
this.rdlPreview.HighlightPageItem = null;
this.rdlPreview.HighlightText = null;
this.rdlPreview.Name = "rdlPreview";
this.rdlPreview.PageCurrent = 1;
this.rdlPreview.Parameters = "";
this.rdlPreview.ReportName = null;
this.rdlPreview.ScrollMode = fyiReporting.RdlViewer.ScrollModeEnum.Continuous;
this.rdlPreview.SelectTool = false;
this.rdlPreview.ShowFindPanel = false;
this.rdlPreview.ShowParameterPanel = true;
this.rdlPreview.ShowWaitDialog = true;
this.rdlPreview.SourceFile = null;
this.rdlPreview.SourceRdl = null;
this.rdlPreview.UseTrueMargins = true;
this.rdlPreview.Zoom = 0.5495112F;
this.rdlPreview.ZoomMode = fyiReporting.RdlViewer.ZoomEnum.FitWidth;
//
// RdlEditPreview
//
this.Controls.Add(this.tcEHP);
this.Name = "RdlEditPreview";
resources.ApplyResources(this, "$this");
this.tcEHP.ResumeLayout(false);
this.tpEditor.ResumeLayout(false);
this.tpBrowser.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void dcDesign_ReportChanged(object sender, System.EventArgs e)
{
_DesignChanged = DesignTabs.Design;
if (!Modified)
SetTextToScintilla(dcDesign.ReportSource);
if (OnRdlChanged != null)
{
OnRdlChanged(this, e);
}
}
private void SetTextToScintilla(string text)
{
bool firstSet = String.IsNullOrEmpty(scintilla1.Text);
noFireRDLTextChanged = firstSet;
scintilla1.Text = text;
if (firstSet)
{
scintilla1.EmptyUndoBuffer();
scintilla1.SetSavePoint();
noFireRDLTextChanged = false;
}
}
private void dcDesign_HeightChanged(object sender, HeightEventArgs e)
{
if (OnHeightChanged != null)
{
OnHeightChanged(this, e);
}
}
private void dcDesign_ReportItemInserted(object sender, System.EventArgs e)
{
if (OnReportItemInserted != null)
{
OnReportItemInserted(this, e);
}
}
private void dcDesign_OpenSubreport(object sender, SubReportEventArgs e)
{
if (OnOpenSubreport != null)
{
OnOpenSubreport(this, e);
}
}
private void dcDesign_SelectionChanged(object sender, System.EventArgs e)
{
if (OnSelectionChanged != null)
{
OnSelectionChanged(this, e);
}
}
private void dcDesign_SelectionMoved(object sender, System.EventArgs e)
{
if (OnSelectionMoved != null)
{
OnSelectionMoved(this, e);
}
}
private void tcEHP_SelectedIndexChanged(object sender, System.EventArgs e)
{
TabControl tc = (TabControl) sender;
DesignTabs tag = (DesignTabs)tc.SelectedIndex;
// Sync up the various pane whenever they switch so the editor is always accurate
switch (_DesignChanged)
{ // Sync up the editor in every case
case DesignTabs.Design:
// sync up the editor
SetTextToScintilla(dcDesign.ReportSource);
break;
case DesignTabs.Edit:
case DesignTabs.Preview:
break;
}
// Below sync up the changed item
if (tag == DesignTabs.Preview)
{
if (rdlPreview.SourceRdl != scintilla1.Text) // sync up preview
this.rdlPreview.SourceRdl = scintilla1.Text;
}
else if (tag == DesignTabs.Design)
{
if (_DesignChanged != DesignTabs.Design)
{
try
{
dcDesign.ReportSource = scintilla1.Text;
}
catch (Exception ge)
{
MessageBox.Show(ge.Message, Strings.RdlEditPreview_Show_Report);
tc.SelectedIndex = 1; // Force current tab to edit syntax
return;
}
}
}
_CurrentTab = tag;
if (OnDesignTabChanged != null)
OnDesignTabChanged(this, e);
}
/// <summary>
/// Print the report.
/// </summary>
public void Print(PrintDocument pd)
{
this.rdlPreview.Print(pd);
}
public void SaveAs(string filename, OutputPresentationType type)
{
this.rdlPreview.SaveAs(filename, type);
}
public string GetRdlText()
{
if (_CurrentTab == DesignTabs.Design)
return dcDesign.ReportSource;
else
return scintilla1.Text;
}
public void SetRdlText(string text)
{
if (_CurrentTab == DesignTabs.Design)
{
try
{
dcDesign.ReportSource = text;
dcDesign.Refresh();
SetTextToScintilla(text);
}
catch (Exception e)
{
MessageBox.Show(e.Message, Strings.RdlEditPreview_Show_Report);
SetTextToScintilla(text);
tcEHP.SelectedIndex = (int)DesignTabs.Edit; // Force current tab to edit syntax
_DesignChanged = DesignTabs.Edit;
}
}
else
{
SetTextToScintilla(text);
}
}
/// <summary>
/// Number of pages in the report.
/// </summary>
public int PageCount
{
get {return this.rdlPreview.PageCount;}
}
/// <summary>
/// Current page in view on report
/// </summary>
public int PageCurrent
{
get {return this.rdlPreview.PageCurrent;}
}
/// <summary>
/// Page height of the report.
/// </summary>
public float PageHeight
{
get {return this.rdlPreview.PageHeight;}
}
/// <summary>
/// Page width of the report.
/// </summary>
public float PageWidth
{
get {return this.rdlPreview.PageWidth;}
}
public fyiReporting.RdlViewer.RdlViewer Viewer
{
get {return this.rdlPreview;}
}
private void scintilla1_UpdateUI(object sender, UpdateUIEventArgs e)
{
if ((e.Change & UpdateChange.Selection) > 0)
{
if (OnSelectionChanged != null)
{
OnSelectionChanged(this, e);
}
}
}
}
public enum DesignTabs
{
Design,
Edit,
Preview
}
}
| |
// 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.IdentityModel.Tokens;
using System.Reflection;
using System.Security.Cryptography;
using System.ServiceModel;
namespace System.IdentityModel
{
internal static class CryptoHelper
{
private static RandomNumberGenerator s_random;
private const string SHAString = "SHA";
private const string SHA1String = "SHA1";
private const string SHA256String = "SHA256";
private const string SystemSecurityCryptographySha1String = "System.Security.Cryptography.SHA1";
private static Dictionary<string, Func<object>> s_algorithmDelegateDictionary = new Dictionary<string, Func<object>>();
private static object s_algorithmDictionaryLock = new object();
internal static bool IsSymmetricAlgorithm(string algorithm)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static byte[] UnwrapKey(byte[] wrappingKey, byte[] wrappedKey, string algorithm)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static byte[] WrapKey(byte[] wrappingKey, byte[] keyToBeWrapped, string algorithm)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static byte[] GenerateDerivedKey(byte[] key, string algorithm, byte[] label, byte[] nonce, int derivedKeySize, int position)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static int GetIVSize(string algorithm)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, string algorithm)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, string algorithm)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static KeyedHashAlgorithm CreateKeyedHashAlgorithm(byte[] key, string algorithm)
{
object algorithmObject = GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
KeyedHashAlgorithm keyedHashAlgorithm = algorithmObject as KeyedHashAlgorithm;
if (keyedHashAlgorithm != null)
{
keyedHashAlgorithm.Key = key;
return keyedHashAlgorithm;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.Format(SR.CustomCryptoAlgorithmIsNotValidKeyedHashAlgorithm, algorithm)));
}
switch (algorithm)
{
case SecurityAlgorithms.HmacSha1Signature:
#pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1.
return new HMACSHA1(key);
#pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1.
case SecurityAlgorithms.HmacSha256Signature:
return new HMACSHA256(key);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.Format(SR.UnsupportedCryptoAlgorithm, algorithm)));
}
}
internal static SymmetricAlgorithm GetSymmetricAlgorithm(byte[] key, string algorithm)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static bool IsAsymmetricAlgorithm(string algorithm)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static bool IsSymmetricSupportedAlgorithm(string algorithm, int keySize)
{
bool found = false;
object algorithmObject = null;
try
{
algorithmObject = GetAlgorithmFromConfig(algorithm);
}
catch (InvalidOperationException)
{
// We swallow the exception and continue.
}
if (algorithmObject != null)
{
SymmetricAlgorithm symmetricAlgorithm = algorithmObject as SymmetricAlgorithm;
KeyedHashAlgorithm keyedHashAlgorithm = algorithmObject as KeyedHashAlgorithm;
if (symmetricAlgorithm != null || keyedHashAlgorithm != null)
{
found = true;
}
// The reason we do not return here even when the user has provided a custom algorithm to CryptoConfig
// is because we need to check if the user has overwritten an existing standard URI.
}
switch (algorithm)
{
case SecurityAlgorithms.DsaSha1Signature:
case SecurityAlgorithms.RsaSha1Signature:
case SecurityAlgorithms.RsaSha256Signature:
case SecurityAlgorithms.RsaOaepKeyWrap:
case SecurityAlgorithms.RsaV15KeyWrap:
return false;
case SecurityAlgorithms.HmacSha1Signature:
case SecurityAlgorithms.HmacSha256Signature:
case SecurityAlgorithms.Psha1KeyDerivation:
case SecurityAlgorithms.Psha1KeyDerivationDec2005:
return true;
case SecurityAlgorithms.Aes128Encryption:
case SecurityAlgorithms.Aes128KeyWrap:
return keySize >= 128 && keySize <= 256;
case SecurityAlgorithms.Aes192Encryption:
case SecurityAlgorithms.Aes192KeyWrap:
return keySize >= 192 && keySize <= 256;
case SecurityAlgorithms.Aes256Encryption:
case SecurityAlgorithms.Aes256KeyWrap:
return keySize == 256;
case SecurityAlgorithms.TripleDesEncryption:
case SecurityAlgorithms.TripleDesKeyWrap:
return keySize == 128 || keySize == 192;
default:
if (found)
{
return true;
}
return false;
// We do not expect the user to map the uri of an existing standrad algorithm with say key size 128 bit
// to a custom algorithm with keySize 192 bits. If he does that, we anyways make sure that we return false.
}
}
internal static void FillRandomBytes(byte[] buffer)
{
RandomNumberGenerator.GetBytes(buffer);
}
internal static RandomNumberGenerator RandomNumberGenerator
{
get
{
if (s_random == null)
{
s_random = RandomNumberGenerator.Create();
}
return s_random;
}
}
internal static HashAlgorithm CreateHashAlgorithm(string algorithm)
{
object algorithmObject = GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
HashAlgorithm hashAlgorithm = algorithmObject as HashAlgorithm;
if (hashAlgorithm != null)
{
return hashAlgorithm;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.Format(SR.CustomCryptoAlgorithmIsNotValidHashAlgorithm, algorithm)));
}
switch (algorithm)
{
case SHAString:
case SHA1String:
case SystemSecurityCryptographySha1String:
case SecurityAlgorithms.Sha1Digest:
#pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1.
return SHA1.Create();
#pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1.
case SHA256String:
case SecurityAlgorithms.Sha256Digest:
return SHA256.Create();
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.Format(SR.UnsupportedCryptoAlgorithm, algorithm)));
}
}
private static object GetDefaultAlgorithm(string algorithm)
{
if (string.IsNullOrEmpty(algorithm))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(algorithm)));
}
switch (algorithm)
{
//case SecurityAlgorithms.RsaSha1Signature:
//case SecurityAlgorithms.DsaSha1Signature:
// For these algorithms above, crypto config returns internal objects.
// As we cannot create those internal objects, we are returning null.
// If no custom algorithm is plugged-in, at least these two algorithms
// will be inside the delegate dictionary.
case SecurityAlgorithms.Sha1Digest:
#pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1.
return SHA1.Create();
#pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1.
case SecurityAlgorithms.ExclusiveC14n:
throw ExceptionHelper.PlatformNotSupported();
case SHA256String:
case SecurityAlgorithms.Sha256Digest:
return SHA256.Create();
case SecurityAlgorithms.Sha512Digest:
return SHA512.Create();
case SecurityAlgorithms.Aes128Encryption:
case SecurityAlgorithms.Aes192Encryption:
case SecurityAlgorithms.Aes256Encryption:
case SecurityAlgorithms.Aes128KeyWrap:
case SecurityAlgorithms.Aes192KeyWrap:
case SecurityAlgorithms.Aes256KeyWrap:
return Aes.Create();
case SecurityAlgorithms.TripleDesEncryption:
case SecurityAlgorithms.TripleDesKeyWrap:
#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
return TripleDES.Create();
#pragma warning restore CA5350 // Do Not Use Weak Cryptographic Algorithms
case SecurityAlgorithms.HmacSha1Signature:
#pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1.
return new HMACSHA1();
#pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1.
case SecurityAlgorithms.HmacSha256Signature:
return new HMACSHA256();
case SecurityAlgorithms.ExclusiveC14nWithComments:
throw ExceptionHelper.PlatformNotSupported();
case SecurityAlgorithms.Ripemd160Digest:
return null;
case SecurityAlgorithms.DesEncryption:
#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
return DES.Create();
#pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms
default:
return null;
}
}
internal static object GetAlgorithmFromConfig(string algorithm)
{
if (string.IsNullOrEmpty(algorithm))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(algorithm)));
}
object algorithmObject = null;
object defaultObject = null;
Func<object> delegateFunction = null;
if (!s_algorithmDelegateDictionary.TryGetValue(algorithm, out delegateFunction))
{
lock (s_algorithmDictionaryLock)
{
if (!s_algorithmDelegateDictionary.ContainsKey(algorithm))
{
try
{
algorithmObject = CryptoConfig.CreateFromName(algorithm);
}
catch (TargetInvocationException)
{
s_algorithmDelegateDictionary[algorithm] = null;
}
if (algorithmObject == null)
{
s_algorithmDelegateDictionary[algorithm] = null;
}
else
{
defaultObject = GetDefaultAlgorithm(algorithm);
if (defaultObject != null && defaultObject.GetType() == algorithmObject.GetType())
{
s_algorithmDelegateDictionary[algorithm] = null;
}
else
{
// Create a factory delegate which returns new instances of the algorithm type for later calls.
Type algorithmType = algorithmObject.GetType();
Linq.Expressions.NewExpression algorithmCreationExpression = Linq.Expressions.Expression.New(algorithmType);
Linq.Expressions.LambdaExpression creationFunction = Linq.Expressions.Expression.Lambda<Func<object>>(algorithmCreationExpression);
delegateFunction = creationFunction.Compile() as Func<object>;
if (delegateFunction != null)
{
s_algorithmDelegateDictionary[algorithm] = delegateFunction;
}
return algorithmObject;
}
}
}
}
}
else
{
if (delegateFunction != null)
{
return delegateFunction.Invoke();
}
}
//
// This is a fallback in case CryptoConfig fails to return a valid
// algorithm object. CrytoConfig does not understand all the uri's and
// can return a null in that case, in which case it is our responsibility
// to fallback and create the right algorithm if it is a uri we understand
//
switch (algorithm)
{
case SHA256String:
case SecurityAlgorithms.Sha256Digest:
return SHA256.Create();
case SecurityAlgorithms.Sha1Digest:
#pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1.
return SHA1.Create();
#pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1.
case SecurityAlgorithms.HmacSha1Signature:
#pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1.
return new HMACSHA1();
#pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1.
default:
break;
}
return null;
}
internal static HashAlgorithm NewSha1HashAlgorithm()
{
return CreateHashAlgorithm(SecurityAlgorithms.Sha1Digest);
}
internal static HashAlgorithm NewSha256HashAlgorithm()
{
return CreateHashAlgorithm(SecurityAlgorithms.Sha256Digest);
}
internal static KeyedHashAlgorithm NewHmacSha1KeyedHashAlgorithm(byte[] key)
{
return CryptoHelper.CreateKeyedHashAlgorithm(key, SecurityAlgorithms.HmacSha1Signature);
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
namespace NFCoreEx
{
public class NFCKernel : NFIKernel
{
#region Instance
private static NFIKernel _Instance = null;
private static readonly object _syncLock = new object();
public static NFIKernel Instance
{
get
{
lock (_syncLock)
{
if (_Instance == null)
{
_Instance = new NFCKernel();
}
return _Instance;
}
}
}
#endregion
public NFCKernel()
{
mhtObject = new Dictionary<NFIDENTID, NFIObject>();
mhtClassHandleDel = new Hashtable();
mxLogicClassManager = new NFCLogicClassManager();
mxElementManager = new NFCElementManager();
}
~NFCKernel()
{
mhtObject = null;
mxElementManager = null;
mxLogicClassManager = null;
}
public override bool AddHeartBeat(NFIDENTID self, string strHeartBeatName, NFIHeartBeat.HeartBeatEventHandler handler, float fTime, NFIDataList valueList)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
xGameObject.GetHeartBeatManager().AddHeartBeat(strHeartBeatName, fTime, handler, valueList);
}
return true;
}
public override void RegisterPropertyCallback(NFIDENTID self, string strPropertyName, NFIProperty.PropertyEventHandler handler)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
xGameObject.GetPropertyManager().RegisterCallback(strPropertyName, handler);
}
}
public override void RegisterRecordCallback(NFIDENTID self, string strRecordName, NFIRecord.RecordEventHandler handler)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
xGameObject.GetRecordManager().RegisterCallback(strRecordName, handler);
}
}
public override void RegisterClassCallBack(string strClassName, NFIObject.ClassEventHandler handler)
{
if(mhtClassHandleDel.ContainsKey(strClassName))
{
ClassHandleDel xHandleDel = (ClassHandleDel)mhtClassHandleDel[strClassName];
xHandleDel.AddDel(handler);
}
else
{
ClassHandleDel xHandleDel = new ClassHandleDel();
xHandleDel.AddDel(handler);
mhtClassHandleDel[strClassName] = xHandleDel;
}
}
public override void RegisterEventCallBack(NFIDENTID self, int nEventID, NFIEvent.EventHandler handler, NFIDataList valueList)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
xGameObject.GetEventManager().RegisterCallback(nEventID, handler, valueList);
}
}
public override bool FindHeartBeat(NFIDENTID self, string strHeartBeatName)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
//gameObject.GetHeartBeatManager().AddHeartBeat()
}
return false;
}
public override bool RemoveHeartBeat(NFIDENTID self, string strHeartBeatName)
{
return true;
}
public override bool UpDate(float fTime)
{
foreach (NFIDENTID id in mhtObject.Keys)
{
NFIObject xGameObject = (NFIObject)mhtObject[id];
xGameObject.GetHeartBeatManager().Update(fTime);
}
return true;
}
/////////////////////////////////////////////////////////////
//public override bool AddRecordCallBack( NFIDENTID self, string strRecordName, RECORD_EVENT_FUNC cb );
//public override bool AddPropertyCallBack( NFIDENTID self, string strCriticalName, PROPERTY_EVENT_FUNC cb );
// public override bool AddClassCallBack( string strClassName, CLASS_EVENT_FUNC cb );
//
// public override bool RemoveClassCallBack( string strClassName, CLASS_EVENT_FUNC cb );
/////////////////////////////////////////////////////////////////
public override NFIObject GetObject(NFIDENTID ident)
{
if (null != ident && mhtObject.ContainsKey(ident))
{
return (NFIObject)mhtObject[ident];
}
return null;
}
public override NFIObject CreateObject(NFIDENTID self, int nContainerID, int nGroupID, string strClassName, string strConfigIndex, NFIDataList arg)
{
if (!mhtObject.ContainsKey(self))
{
NFIObject xNewObject = new NFCObject(self, nContainerID, nGroupID, strClassName, strConfigIndex);
mhtObject.Add(self, xNewObject);
NFCDataList varConfigID = new NFCDataList();
varConfigID.AddString(strConfigIndex);
xNewObject.GetPropertyManager().AddProperty("ConfigID", varConfigID);
NFCDataList varConfigClass = new NFCDataList();
varConfigClass.AddString(strClassName);
xNewObject.GetPropertyManager().AddProperty("ClassName", varConfigClass);
if (arg.Count() % 2 == 0)
{
for (int i = 0; i < arg.Count() - 1; i += 2)
{
string strPropertyName = arg.StringVal(i);
NFIDataList.VARIANT_TYPE eType = arg.GetType(i + 1);
switch (eType)
{
case NFIDataList.VARIANT_TYPE.VTYPE_INT:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddInt(arg.IntVal(i+1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_FLOAT:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddFloat(arg.FloatVal(i + 1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_DOUBLE:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddDouble(arg.DoubleVal(i + 1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_STRING:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddString(arg.StringVal(i + 1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_OBJECT:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddObject(arg.ObjectVal(i + 1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
default:
break;
}
}
}
InitProperty(self, strClassName);
InitRecord(self, strClassName);
ClassHandleDel xHandleDel = (ClassHandleDel)mhtClassHandleDel[strClassName];
if (null != xHandleDel && null != xHandleDel.GetHandler())
{
NFIObject.ClassEventHandler xHandlerList = xHandleDel.GetHandler();
xHandlerList(self, nContainerID, nGroupID, NFIObject.CLASS_EVENT_TYPE.OBJECT_CREATE, strClassName, strConfigIndex);
xHandlerList(self, nContainerID, nGroupID, NFIObject.CLASS_EVENT_TYPE.OBJECT_LOADDATA, strClassName, strConfigIndex);
xHandlerList(self, nContainerID, nGroupID, NFIObject.CLASS_EVENT_TYPE.OBJECT_CREATE_FINISH, strClassName, strConfigIndex);
}
return xNewObject;
}
return null;
}
public override bool DestroyObject(NFIDENTID self)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
string strClassName = xGameObject.ClassName();
ClassHandleDel xHandleDel = (ClassHandleDel)mhtClassHandleDel[strClassName];
if (null != xHandleDel && null != xHandleDel.GetHandler())
{
NFIObject.ClassEventHandler xHandlerList = xHandleDel.GetHandler();
xHandlerList(self, xGameObject.ContainerID(), xGameObject.GroupID(), NFIObject.CLASS_EVENT_TYPE.OBJECT_DESTROY, xGameObject.ClassName(), xGameObject.ConfigIndex());
}
mhtObject.Remove(self);
return true;
}
return false;
}
public override bool FindProperty(NFIDENTID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.FindProperty(strPropertyName);
}
return false;
}
public override bool SetPropertyInt(NFIDENTID self, string strPropertyName, Int64 nValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyInt(strPropertyName, nValue);
}
return false;
}
public override bool SetPropertyFloat(NFIDENTID self, string strPropertyName, float fValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyFloat(strPropertyName, fValue);
}
return false;
}
public override bool SetPropertyDouble(NFIDENTID self, string strPropertyName, double dValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyDouble(strPropertyName, dValue);
}
return false;
}
public override bool SetPropertyString(NFIDENTID self, string strPropertyName, string strValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyString(strPropertyName, strValue);
}
return false;
}
public override bool SetPropertyObject(NFIDENTID self, string strPropertyName, NFIDENTID objectValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyObject(strPropertyName, objectValue);
}
return false;
}
public override Int64 QueryPropertyInt(NFIDENTID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyInt(strPropertyName);
}
return 0;
}
public override float QueryPropertyFloat(NFIDENTID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyFloat(strPropertyName);
}
return 0.0f;
}
public override double QueryPropertyDouble(NFIDENTID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyDouble(strPropertyName);
}
return 0.0;
}
public override string QueryPropertyString(NFIDENTID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyString(strPropertyName);
}
return "";
}
public override NFIDENTID QueryPropertyObject(NFIDENTID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyObject(strPropertyName);
}
return new NFIDENTID();
}
public override NFIRecord FindRecord(NFIDENTID self, string strRecordName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.GetRecordManager().GetRecord(strRecordName);
}
return null;
}
public override bool SetRecordInt(NFIDENTID self, string strRecordName, int nRow, int nCol, Int64 nValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordInt(strRecordName, nRow, nCol, nValue);
}
return false;
}
public override bool SetRecordFloat(NFIDENTID self, string strRecordName, int nRow, int nCol, float fValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordFloat(strRecordName, nRow, nCol, fValue);
}
return false;
}
public override bool SetRecordDouble(NFIDENTID self, string strRecordName, int nRow, int nCol, double dwValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordDouble(strRecordName, nRow, nCol, dwValue);
}
return false;
}
public override bool SetRecordString(NFIDENTID self, string strRecordName, int nRow, int nCol, string strValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordString(strRecordName, nRow, nCol, strValue);
}
return false;
}
public override bool SetRecordObject(NFIDENTID self, string strRecordName, int nRow, int nCol, NFIDENTID objectValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordObject(strRecordName, nRow, nCol, objectValue);
}
return false;
}
public override Int64 QueryRecordInt(NFIDENTID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordInt(strRecordName, nRow, nCol);
}
return 0;
}
public override float QueryRecordFloat(NFIDENTID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordFloat(strRecordName, nRow, nCol);
}
return 0.0f;
}
public override double QueryRecordDouble(NFIDENTID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordDouble(strRecordName, nRow, nCol);
}
return 0.0;
}
public override string QueryRecordString(NFIDENTID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordString(strRecordName, nRow, nCol);
}
return "";
}
public override NFIDENTID QueryRecordObject(NFIDENTID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordObject(strRecordName, nRow, nCol);
}
return new NFIDENTID();
}
public override NFIDataList GetObjectList()
{
NFIDataList varData = new NFCDataList();
foreach (KeyValuePair<NFIDENTID, NFIObject> kv in mhtObject)
{
varData.AddObject(kv.Key);
}
return varData;
}
public override int FindRecordRow(NFIDENTID self, string strRecordName, int nCol, int nValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFCoreEx.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindInt(nCol, nValue);
}
}
return -1;
}
public override int FindRecordRow(NFIDENTID self, string strRecordName, int nCol, float fValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFCoreEx.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindFloat(nCol, fValue);
}
}
return -1;
}
public override int FindRecordRow(NFIDENTID self, string strRecordName, int nCol, double fValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFCoreEx.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindDouble(nCol, fValue);
}
}
return -1;
}
public override int FindRecordRow(NFIDENTID self, string strRecordName, int nCol, string strValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFCoreEx.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindString(nCol, strValue);
}
}
return -1;
}
public override int FindRecordRow(NFIDENTID self, string strRecordName, int nCol, NFIDENTID nValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFCoreEx.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindObject(nCol, nValue);
}
}
return -1;
}
void InitProperty(NFIDENTID self, string strClassName)
{
NFILogicClass xLogicClass = NFCLogicClassManager.Instance.GetElement(strClassName);
NFIDataList xDataList = xLogicClass.GetPropertyManager().GetPropertyList();
for (int i = 0; i < xDataList.Count(); ++i )
{
string strPropertyName = xDataList.StringVal(i);
NFIProperty xProperty = xLogicClass.GetPropertyManager().GetProperty(strPropertyName);
NFIObject xObject = GetObject(self);
NFIPropertyManager xPropertyManager = xObject.GetPropertyManager();
xPropertyManager.AddProperty(strPropertyName, xProperty.GetValue());
}
}
void InitRecord(NFIDENTID self, string strClassName)
{
NFILogicClass xLogicClass = NFCLogicClassManager.Instance.GetElement(strClassName);
NFIDataList xDataList = xLogicClass.GetRecordManager().GetRecordList();
for (int i = 0; i < xDataList.Count(); ++i)
{
string strRecordyName = xDataList.StringVal(i);
NFIRecord xRecord = xLogicClass.GetRecordManager().GetRecord(strRecordyName);
NFIObject xObject = GetObject(self);
NFIRecordManager xRecordManager = xObject.GetRecordManager();
xRecordManager.AddRecord(strRecordyName, xRecord.GetRows(), xRecord.GetColsData());
}
}
Dictionary<NFIDENTID, NFIObject> mhtObject;
Hashtable mhtClassHandleDel;
NFIElementManager mxElementManager;
NFILogicClassManager mxLogicClassManager;
class ClassHandleDel
{
public ClassHandleDel()
{
mhtHandleDelList = new Hashtable();
}
public void AddDel(NFIObject.ClassEventHandler handler)
{
if (!mhtHandleDelList.ContainsKey(handler))
{
mhtHandleDelList.Add(handler, handler.ToString());
mHandleDel += handler;
}
}
public NFIObject.ClassEventHandler GetHandler()
{
return mHandleDel;
}
private NFIObject.ClassEventHandler mHandleDel;
Hashtable mhtHandleDelList;
}
}
}
| |
using System;
using System.IO;
namespace CatLib._3rd.SharpCompress.Compressors.LZMA.LZ
{
internal class BinTree : InWindow
{
private UInt32 _cyclicBufferPos;
private UInt32 _cyclicBufferSize;
private UInt32 _matchMaxLen;
private UInt32[] _son;
private UInt32[] _hash;
private UInt32 _cutValue = 0xFF;
private UInt32 _hashMask;
private UInt32 _hashSizeSum;
private bool HASH_ARRAY = true;
private const UInt32 kHash2Size = 1 << 10;
private const UInt32 kHash3Size = 1 << 16;
private const UInt32 kBT2HashSize = 1 << 16;
private const UInt32 kStartMaxLen = 1;
private const UInt32 kHash3Offset = kHash2Size;
private const UInt32 kEmptyHashValue = 0;
private const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1;
private UInt32 kNumHashDirectBytes;
private UInt32 kMinMatchCheck = 4;
private UInt32 kFixHashSize = kHash2Size + kHash3Size;
public void SetType(int numHashBytes)
{
HASH_ARRAY = (numHashBytes > 2);
if (HASH_ARRAY)
{
kNumHashDirectBytes = 0;
kMinMatchCheck = 4;
kFixHashSize = kHash2Size + kHash3Size;
}
else
{
kNumHashDirectBytes = 2;
kMinMatchCheck = 2 + 1;
kFixHashSize = 0;
}
}
public new void SetStream(Stream stream)
{
base.SetStream(stream);
}
public new void ReleaseStream()
{
base.ReleaseStream();
}
public new void Init()
{
base.Init();
for (UInt32 i = 0; i < _hashSizeSum; i++)
{
_hash[i] = kEmptyHashValue;
}
_cyclicBufferPos = 0;
ReduceOffsets(-1);
}
public new void MovePos()
{
if (++_cyclicBufferPos >= _cyclicBufferSize)
{
_cyclicBufferPos = 0;
}
base.MovePos();
if (_pos == kMaxValForNormalize)
{
Normalize();
}
}
public new Byte GetIndexByte(Int32 index)
{
return base.GetIndexByte(index);
}
public new UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit)
{
return base.GetMatchLen(index, distance, limit);
}
public new UInt32 GetNumAvailableBytes()
{
return base.GetNumAvailableBytes();
}
public void Create(UInt32 historySize, UInt32 keepAddBufferBefore,
UInt32 matchMaxLen, UInt32 keepAddBufferAfter)
{
if (historySize > kMaxValForNormalize - 256)
{
throw new Exception();
}
_cutValue = 16 + (matchMaxLen >> 1);
UInt32 windowReservSize = (historySize + keepAddBufferBefore +
matchMaxLen + keepAddBufferAfter) / 2 + 256;
base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize);
_matchMaxLen = matchMaxLen;
UInt32 cyclicBufferSize = historySize + 1;
if (_cyclicBufferSize != cyclicBufferSize)
{
_son = new UInt32[(_cyclicBufferSize = cyclicBufferSize) * 2];
}
UInt32 hs = kBT2HashSize;
if (HASH_ARRAY)
{
hs = historySize - 1;
hs |= (hs >> 1);
hs |= (hs >> 2);
hs |= (hs >> 4);
hs |= (hs >> 8);
hs >>= 1;
hs |= 0xFFFF;
if (hs > (1 << 24))
{
hs >>= 1;
}
_hashMask = hs;
hs++;
hs += kFixHashSize;
}
if (hs != _hashSizeSum)
{
_hash = new UInt32[_hashSizeSum = hs];
}
}
public UInt32 GetMatches(UInt32[] distances)
{
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
{
lenLimit = _matchMaxLen;
}
else
{
lenLimit = _streamPos - _pos;
if (lenLimit < kMinMatchCheck)
{
MovePos();
return 0;
}
}
UInt32 offset = 0;
UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0;
UInt32 cur = _bufferOffset + _pos;
UInt32 maxLen = kStartMaxLen; // to avoid items for len < hashSize;
UInt32 hashValue, hash2Value = 0, hash3Value = 0;
if (HASH_ARRAY)
{
UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1];
hash2Value = temp & (kHash2Size - 1);
temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8);
hash3Value = temp & (kHash3Size - 1);
hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask;
}
else
{
hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8);
}
UInt32 curMatch = _hash[kFixHashSize + hashValue];
if (HASH_ARRAY)
{
UInt32 curMatch2 = _hash[hash2Value];
UInt32 curMatch3 = _hash[kHash3Offset + hash3Value];
_hash[hash2Value] = _pos;
_hash[kHash3Offset + hash3Value] = _pos;
if (curMatch2 > matchMinPos)
{
if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur])
{
distances[offset++] = maxLen = 2;
distances[offset++] = _pos - curMatch2 - 1;
}
}
if (curMatch3 > matchMinPos)
{
if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur])
{
if (curMatch3 == curMatch2)
{
offset -= 2;
}
distances[offset++] = maxLen = 3;
distances[offset++] = _pos - curMatch3 - 1;
curMatch2 = curMatch3;
}
}
if (offset != 0 && curMatch2 == curMatch)
{
offset -= 2;
maxLen = kStartMaxLen;
}
}
_hash[kFixHashSize + hashValue] = _pos;
UInt32 ptr0 = (_cyclicBufferPos << 1) + 1;
UInt32 ptr1 = (_cyclicBufferPos << 1);
UInt32 len0, len1;
len0 = len1 = kNumHashDirectBytes;
if (kNumHashDirectBytes != 0)
{
if (curMatch > matchMinPos)
{
if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] !=
_bufferBase[cur + kNumHashDirectBytes])
{
distances[offset++] = maxLen = kNumHashDirectBytes;
distances[offset++] = _pos - curMatch - 1;
}
}
}
UInt32 count = _cutValue;
while (true)
{
if (curMatch <= matchMinPos || count-- == 0)
{
_son[ptr0] = _son[ptr1] = kEmptyHashValue;
break;
}
UInt32 delta = _pos - curMatch;
UInt32 cyclicPos = ((delta <= _cyclicBufferPos)
? (_cyclicBufferPos - delta)
: (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1;
UInt32 pby1 = _bufferOffset + curMatch;
UInt32 len = Math.Min(len0, len1);
if (_bufferBase[pby1 + len] == _bufferBase[cur + len])
{
while (++len != lenLimit)
{
if (_bufferBase[pby1 + len] != _bufferBase[cur + len])
{
break;
}
}
if (maxLen < len)
{
distances[offset++] = maxLen = len;
distances[offset++] = delta - 1;
if (len == lenLimit)
{
_son[ptr1] = _son[cyclicPos];
_son[ptr0] = _son[cyclicPos + 1];
break;
}
}
}
if (_bufferBase[pby1 + len] < _bufferBase[cur + len])
{
_son[ptr1] = curMatch;
ptr1 = cyclicPos + 1;
curMatch = _son[ptr1];
len1 = len;
}
else
{
_son[ptr0] = curMatch;
ptr0 = cyclicPos;
curMatch = _son[ptr0];
len0 = len;
}
}
MovePos();
return offset;
}
public void Skip(UInt32 num)
{
do
{
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
{
lenLimit = _matchMaxLen;
}
else
{
lenLimit = _streamPos - _pos;
if (lenLimit < kMinMatchCheck)
{
MovePos();
continue;
}
}
UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0;
UInt32 cur = _bufferOffset + _pos;
UInt32 hashValue;
if (HASH_ARRAY)
{
UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1];
UInt32 hash2Value = temp & (kHash2Size - 1);
_hash[hash2Value] = _pos;
temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8);
UInt32 hash3Value = temp & (kHash3Size - 1);
_hash[kHash3Offset + hash3Value] = _pos;
hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask;
}
else
{
hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8);
}
UInt32 curMatch = _hash[kFixHashSize + hashValue];
_hash[kFixHashSize + hashValue] = _pos;
UInt32 ptr0 = (_cyclicBufferPos << 1) + 1;
UInt32 ptr1 = (_cyclicBufferPos << 1);
UInt32 len0, len1;
len0 = len1 = kNumHashDirectBytes;
UInt32 count = _cutValue;
while (true)
{
if (curMatch <= matchMinPos || count-- == 0)
{
_son[ptr0] = _son[ptr1] = kEmptyHashValue;
break;
}
UInt32 delta = _pos - curMatch;
UInt32 cyclicPos = ((delta <= _cyclicBufferPos)
? (_cyclicBufferPos - delta)
: (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1;
UInt32 pby1 = _bufferOffset + curMatch;
UInt32 len = Math.Min(len0, len1);
if (_bufferBase[pby1 + len] == _bufferBase[cur + len])
{
while (++len != lenLimit)
{
if (_bufferBase[pby1 + len] != _bufferBase[cur + len])
{
break;
}
}
if (len == lenLimit)
{
_son[ptr1] = _son[cyclicPos];
_son[ptr0] = _son[cyclicPos + 1];
break;
}
}
if (_bufferBase[pby1 + len] < _bufferBase[cur + len])
{
_son[ptr1] = curMatch;
ptr1 = cyclicPos + 1;
curMatch = _son[ptr1];
len1 = len;
}
else
{
_son[ptr0] = curMatch;
ptr0 = cyclicPos;
curMatch = _son[ptr0];
len0 = len;
}
}
MovePos();
}
while (--num != 0);
}
private void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue)
{
for (UInt32 i = 0; i < numItems; i++)
{
UInt32 value = items[i];
if (value <= subValue)
{
value = kEmptyHashValue;
}
else
{
value -= subValue;
}
items[i] = value;
}
}
private void Normalize()
{
UInt32 subValue = _pos - _cyclicBufferSize;
NormalizeLinks(_son, _cyclicBufferSize * 2, subValue);
NormalizeLinks(_hash, _hashSizeSum, subValue);
ReduceOffsets((Int32)subValue);
}
public void SetCutValue(UInt32 cutValue)
{
_cutValue = cutValue;
}
}
}
| |
//#define USE_SIN_TABLE
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UniverseEngine
{
public class Universe
{
public const int MAX_THINGS = 8192;
private const float HALF_PI = Mathf.PI * 0.5f; //90 degress in radians
private const float TWO_PI = Mathf.PI * 2.0f; //360 degress in radians
private const float INV_TWO_PI = 1.0f / (Mathf.PI * 2.0f);
private const float DEG_TO_RAD_OVER_100 = 0.000174532925f; //(degrees to radians / 100)
private const float POSITIONS_TIME_SCALE = 0.01f;
private Thing[] things = new Thing[MAX_THINGS];
private ThingPosition[] thingsPositions = new ThingPosition[MAX_THINGS];
private ushort thingsAmount;
private ushort[] thingsToRender = new ushort[MAX_THINGS];
private ushort thingsToRenderAmount;
private ushort startingPlanet;
private List<Planet> planets = new List<Planet>();
private List<UniverseObject> tilemapObjects = new List<UniverseObject>();
private UniverseFactory universeFactory = new UniverseFactory();
private float time;
private Avatar avatar;
private Ship ship;
private IUniverseListener listener;
public ushort StartingPlanet
{
get { return startingPlanet; }
}
public Avatar Avatar
{
get { return avatar; }
}
public Ship Ship
{
get { return ship; }
}
public Thing[] Things
{
get { return things; }
}
public ThingPosition[] ThingsPositions
{
get { return thingsPositions; }
}
public ushort[] ThingsToRender
{
get { return thingsToRender; }
}
public ushort ThingsToRenderAmount
{
get { return thingsToRenderAmount; }
}
public IUniverseListener Listener
{
get { return listener; }
set { listener = value; }
}
public void Init(int seed, IUniverseListener listener)
{
this.listener = listener;
time = 0.0f;
thingsAmount = new UniverseGeneratorDefault().Generate(seed, things);
UpdateThingsToRender();
startingPlanet = thingsToRender[1];
UpdateUniverse(0);
AddAvatar();
AddShip();
}
private void UpdateThingsToRender()
{
thingsToRenderAmount = 0;
for (int i = 0; i < thingsAmount; i++)
{
ThingType type = (ThingType)things[i].type;
if (type == ThingType.Sun || type == ThingType.Planet || type == ThingType.Moon)
thingsToRender[thingsToRenderAmount++] = (ushort) i;
}
}
public void UpdateUniverse(float deltaTime)
{
#if USE_SIN_TABLE
if (sinTable == null)
InitSinTable();
#endif
time += deltaTime;
UEProfiler.BeginSample("Universe.UpdatePositions");
UpdatePositions(time);
UEProfiler.EndSample();
for (int i = 0; i < planets.Count; i++)
planets[i].Update(deltaTime);
for (int i = 0; i < tilemapObjects.Count; i++)
tilemapObjects[i].Update(deltaTime);
}
#if USE_SIN_TABLE
private const int SIN_TABLE_LEN = 512;
private const float SIN_TABLE_LEN_F = SIN_TABLE_LEN;
private const float SIN_TABLE_INDEX = INV_TWO_PI * SIN_TABLE_LEN_F;
static private float[] sinTable;
static private float[] cosTable;
static private void InitSinTable()
{
sinTable = new float[SIN_TABLE_LEN];
cosTable = new float[SIN_TABLE_LEN];
for (int i = 0; i < sinTable.Length; i++)
{
sinTable[i] = Mathf.Sin((i * TWO_PI) / SIN_TABLE_LEN_F);
cosTable[i] = Mathf.Cos((i * TWO_PI) / SIN_TABLE_LEN_F);
//Debug.Log(sinTable[i]);
}
}
static private float Sin(float angle)
{
return sinTable[(int)(angle * SIN_TABLE_INDEX) % SIN_TABLE_LEN];
}
static private float Cos(float angle)
{
//return cosTable[(int)(angle * SIN_TABLE_INDEX) % SIN_TABLE_LEN];
return sinTable[(int)((angle + HALF_PI) * SIN_TABLE_INDEX) % SIN_TABLE_LEN];
}
#endif
private void UpdatePositions(float time)
{
time *= POSITIONS_TIME_SCALE;
for (int index = 1; index < thingsAmount; index++)
{
Thing thing = things[index];
float parentX = thingsPositions[thing.parent].x;
float parentY = thingsPositions[thing.parent].y;
float angle = thing.angle * DEG_TO_RAD_OVER_100;
float distance = thing.distance;
float normalizedOrbitalPeriod = time * thing.orbitalPeriodInv;
normalizedOrbitalPeriod -= (int)normalizedOrbitalPeriod;
float normalizedRotationPeriod = time * thing.rotationPeriodInv;
normalizedRotationPeriod -= (int)normalizedRotationPeriod;
angle += TWO_PI * normalizedOrbitalPeriod; //360 degrees to radians
#if USE_SIN_TABLE
if (angle < 0)
angle += TWO_PI;
thingsPositions[index].x = parentX + Cos(angle) * distance;
thingsPositions[index].y = parentY + Sin(angle) * distance;
#else
thingsPositions[index].x = parentX + ((float)Math.Cos(angle)) * distance;
thingsPositions[index].y = parentY + ((float)Math.Sin(angle)) * distance;
#endif
thingsPositions[index].rotation = normalizedRotationPeriod * TWO_PI; //360 degrees to radian
thingsPositions[index].radius = thing.radius;
}
}
public Thing GetThing(ushort thingIndex)
{
return things[thingIndex];
}
public ThingPosition GetThingPosition(ushort thingIndex)
{
return thingsPositions[thingIndex];
}
public Planet GetPlanet(ushort thingIndex)
{
for (int i = 0; i < planets.Count; i++)
if (planets[i].ThingIndex == thingIndex)
return planets[i];
if (things[thingIndex].type != (ushort) ThingType.Sun &&
things[thingIndex].type != (ushort) ThingType.Planet &&
things[thingIndex].type != (ushort) ThingType.Moon)
{
return null;
}
Planet planet = universeFactory.GetPlanet(Planet.GetPlanetHeightWithRadius(things[thingIndex].radius));
planet.InitPlanet(this, thingIndex);
planets.Add(planet);
return planet;
}
public void ReturnPlanet(Planet planet)
{
if (planets.Remove(planet))
{
if (listener != null)
listener.OnPlanetReturned(planet);
universeFactory.ReturnPlanet(planet);
}
}
private void AddAvatar()
{
Planet planet = GetPlanet(startingPlanet);
avatar = universeFactory.GetAvatar();
avatar.Init(
new Vector2(0.75f, 1.05f),
planet,
FollowParentParameters.Default,
planet.GetPositionFromTileCoordinate(0, planet.Height),
0.0f
);
AddUniverseObject(avatar);
}
private void AddShip()
{
ship = universeFactory.GetShip();
ship.Init(
new Vector2(1.0f, 1.0f),
avatar.parent,
FollowParentParameters.None,
avatar.parent.GetPositionFromTileCoordinate(0, avatar.parent.Height + 5),
Mathf.PI * 0.5f
);
AddUniverseObject(ship);
}
public void AddUniverseObject(UniverseObject universeObject)
{
tilemapObjects.Add(universeObject);
if (listener != null)
listener.OnUniverseObjectAdded(universeObject);
}
public int FindClosestRenderedThing(Vector2 worldPos, float searchRadius)
{
ushort closestThingIndex = ushort.MaxValue;
float closestThingDistance = float.MaxValue;
for (ushort i = 0; i < thingsToRenderAmount; i++)
{
ThingPosition thingPosition = thingsPositions[thingsToRender[i]];
float distance = (worldPos - new Vector2(thingPosition.x, thingPosition.y)).sqrMagnitude;
if (distance < (thingPosition.radius + searchRadius) * (thingPosition.radius + searchRadius) &&
distance < closestThingDistance)
{
closestThingIndex = thingsToRender[i];
closestThingDistance = distance;
}
}
if (closestThingIndex != ushort.MaxValue)
return closestThingIndex;
else
return -1;
}
public List<ushort> FindClosestRenderedThings(Vector2 worldPos, float searchRadius, List<ushort> toReturn)
{
if (toReturn == null)
toReturn = new List<ushort>();
else
toReturn.Clear();
for (ushort i = 0; i < thingsToRenderAmount; i++)
{
ThingPosition thingPosition = thingsPositions[thingsToRender[i]];
float distance = (worldPos - new Vector2(thingPosition.x, thingPosition.y)).sqrMagnitude;
if (distance < (thingPosition.radius + searchRadius) * (thingPosition.radius + searchRadius))
toReturn.Add(thingsToRender[i]);
}
ThingDistanceComparerReference = worldPos;
toReturn.Sort(ThingDistanceComparer);
return toReturn;
}
private Vector2 ThingDistanceComparerReference;
private int ThingDistanceComparer(ushort index1, ushort index2)
{
Vector2 p1 = new Vector2(thingsPositions[index1].x, thingsPositions[index1].y) - ThingDistanceComparerReference;
Vector2 p2 = new Vector2(thingsPositions[index2].x, thingsPositions[index2].y) - ThingDistanceComparerReference;
float diff = p1.sqrMagnitude - p2.sqrMagnitude;
if (diff < 0)
return -1;
else if (diff > 0)
return 1;
else
return 0;
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.CloudDms.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedDataMigrationServiceClientTest
{
[xunit::FactAttribute]
public void GetMigrationJobRequestObject()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetMigrationJobRequest request = new GetMigrationJobRequest
{
MigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
};
MigrationJob expectedResponse = new MigrationJob
{
MigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
State = MigrationJob.Types.State.Restarting,
Phase = MigrationJob.Types.Phase.WaitingForSourceWritesToStop,
Type = MigrationJob.Types.Type.Unspecified,
DumpPath = "dump_path9da43556",
Source = "sourcef438cd36",
Destination = "destination43a59069",
Duration = new wkt::Duration(),
Error = new gr::Status(),
SourceDatabase = new DatabaseType(),
DestinationDatabase = new DatabaseType(),
EndTime = new wkt::Timestamp(),
ReverseSshConnectivity = new ReverseSshConnectivity(),
VpcPeeringConnectivity = new VpcPeeringConnectivity(),
StaticIpConnectivity = new StaticIpConnectivity(),
};
mockGrpcClient.Setup(x => x.GetMigrationJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
MigrationJob response = client.GetMigrationJob(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetMigrationJobRequestObjectAsync()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetMigrationJobRequest request = new GetMigrationJobRequest
{
MigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
};
MigrationJob expectedResponse = new MigrationJob
{
MigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
State = MigrationJob.Types.State.Restarting,
Phase = MigrationJob.Types.Phase.WaitingForSourceWritesToStop,
Type = MigrationJob.Types.Type.Unspecified,
DumpPath = "dump_path9da43556",
Source = "sourcef438cd36",
Destination = "destination43a59069",
Duration = new wkt::Duration(),
Error = new gr::Status(),
SourceDatabase = new DatabaseType(),
DestinationDatabase = new DatabaseType(),
EndTime = new wkt::Timestamp(),
ReverseSshConnectivity = new ReverseSshConnectivity(),
VpcPeeringConnectivity = new VpcPeeringConnectivity(),
StaticIpConnectivity = new StaticIpConnectivity(),
};
mockGrpcClient.Setup(x => x.GetMigrationJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MigrationJob>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
MigrationJob responseCallSettings = await client.GetMigrationJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
MigrationJob responseCancellationToken = await client.GetMigrationJobAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetMigrationJob()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetMigrationJobRequest request = new GetMigrationJobRequest
{
MigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
};
MigrationJob expectedResponse = new MigrationJob
{
MigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
State = MigrationJob.Types.State.Restarting,
Phase = MigrationJob.Types.Phase.WaitingForSourceWritesToStop,
Type = MigrationJob.Types.Type.Unspecified,
DumpPath = "dump_path9da43556",
Source = "sourcef438cd36",
Destination = "destination43a59069",
Duration = new wkt::Duration(),
Error = new gr::Status(),
SourceDatabase = new DatabaseType(),
DestinationDatabase = new DatabaseType(),
EndTime = new wkt::Timestamp(),
ReverseSshConnectivity = new ReverseSshConnectivity(),
VpcPeeringConnectivity = new VpcPeeringConnectivity(),
StaticIpConnectivity = new StaticIpConnectivity(),
};
mockGrpcClient.Setup(x => x.GetMigrationJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
MigrationJob response = client.GetMigrationJob(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetMigrationJobAsync()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetMigrationJobRequest request = new GetMigrationJobRequest
{
MigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
};
MigrationJob expectedResponse = new MigrationJob
{
MigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
State = MigrationJob.Types.State.Restarting,
Phase = MigrationJob.Types.Phase.WaitingForSourceWritesToStop,
Type = MigrationJob.Types.Type.Unspecified,
DumpPath = "dump_path9da43556",
Source = "sourcef438cd36",
Destination = "destination43a59069",
Duration = new wkt::Duration(),
Error = new gr::Status(),
SourceDatabase = new DatabaseType(),
DestinationDatabase = new DatabaseType(),
EndTime = new wkt::Timestamp(),
ReverseSshConnectivity = new ReverseSshConnectivity(),
VpcPeeringConnectivity = new VpcPeeringConnectivity(),
StaticIpConnectivity = new StaticIpConnectivity(),
};
mockGrpcClient.Setup(x => x.GetMigrationJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MigrationJob>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
MigrationJob responseCallSettings = await client.GetMigrationJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
MigrationJob responseCancellationToken = await client.GetMigrationJobAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetMigrationJobResourceNames()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetMigrationJobRequest request = new GetMigrationJobRequest
{
MigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
};
MigrationJob expectedResponse = new MigrationJob
{
MigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
State = MigrationJob.Types.State.Restarting,
Phase = MigrationJob.Types.Phase.WaitingForSourceWritesToStop,
Type = MigrationJob.Types.Type.Unspecified,
DumpPath = "dump_path9da43556",
Source = "sourcef438cd36",
Destination = "destination43a59069",
Duration = new wkt::Duration(),
Error = new gr::Status(),
SourceDatabase = new DatabaseType(),
DestinationDatabase = new DatabaseType(),
EndTime = new wkt::Timestamp(),
ReverseSshConnectivity = new ReverseSshConnectivity(),
VpcPeeringConnectivity = new VpcPeeringConnectivity(),
StaticIpConnectivity = new StaticIpConnectivity(),
};
mockGrpcClient.Setup(x => x.GetMigrationJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
MigrationJob response = client.GetMigrationJob(request.MigrationJobName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetMigrationJobResourceNamesAsync()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetMigrationJobRequest request = new GetMigrationJobRequest
{
MigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
};
MigrationJob expectedResponse = new MigrationJob
{
MigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
State = MigrationJob.Types.State.Restarting,
Phase = MigrationJob.Types.Phase.WaitingForSourceWritesToStop,
Type = MigrationJob.Types.Type.Unspecified,
DumpPath = "dump_path9da43556",
Source = "sourcef438cd36",
Destination = "destination43a59069",
Duration = new wkt::Duration(),
Error = new gr::Status(),
SourceDatabase = new DatabaseType(),
DestinationDatabase = new DatabaseType(),
EndTime = new wkt::Timestamp(),
ReverseSshConnectivity = new ReverseSshConnectivity(),
VpcPeeringConnectivity = new VpcPeeringConnectivity(),
StaticIpConnectivity = new StaticIpConnectivity(),
};
mockGrpcClient.Setup(x => x.GetMigrationJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MigrationJob>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
MigrationJob responseCallSettings = await client.GetMigrationJobAsync(request.MigrationJobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
MigrationJob responseCancellationToken = await client.GetMigrationJobAsync(request.MigrationJobName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GenerateSshScriptRequestObject()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GenerateSshScriptRequest request = new GenerateSshScriptRequest
{
MigrationJobAsMigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
Vm = "vm1a826c68",
VmPort = 1861054020,
VmCreationConfig = new VmCreationConfig(),
VmSelectionConfig = new VmSelectionConfig(),
};
SshScript expectedResponse = new SshScript
{
Script = "scriptdec00532",
};
mockGrpcClient.Setup(x => x.GenerateSshScript(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
SshScript response = client.GenerateSshScript(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GenerateSshScriptRequestObjectAsync()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GenerateSshScriptRequest request = new GenerateSshScriptRequest
{
MigrationJobAsMigrationJobName = MigrationJobName.FromProjectLocationMigrationJob("[PROJECT]", "[LOCATION]", "[MIGRATION_JOB]"),
Vm = "vm1a826c68",
VmPort = 1861054020,
VmCreationConfig = new VmCreationConfig(),
VmSelectionConfig = new VmSelectionConfig(),
};
SshScript expectedResponse = new SshScript
{
Script = "scriptdec00532",
};
mockGrpcClient.Setup(x => x.GenerateSshScriptAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SshScript>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
SshScript responseCallSettings = await client.GenerateSshScriptAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SshScript responseCancellationToken = await client.GenerateSshScriptAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConnectionProfileRequestObject()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConnectionProfileRequest request = new GetConnectionProfileRequest
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
};
ConnectionProfile expectedResponse = new ConnectionProfile
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
State = ConnectionProfile.Types.State.Deleted,
DisplayName = "display_name137f65c2",
Error = new gr::Status(),
Provider = DatabaseProvider.Cloudsql,
Mysql = new MySqlConnectionProfile(),
Postgresql = new PostgreSqlConnectionProfile(),
Cloudsql = new CloudSqlConnectionProfile(),
};
mockGrpcClient.Setup(x => x.GetConnectionProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
ConnectionProfile response = client.GetConnectionProfile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConnectionProfileRequestObjectAsync()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConnectionProfileRequest request = new GetConnectionProfileRequest
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
};
ConnectionProfile expectedResponse = new ConnectionProfile
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
State = ConnectionProfile.Types.State.Deleted,
DisplayName = "display_name137f65c2",
Error = new gr::Status(),
Provider = DatabaseProvider.Cloudsql,
Mysql = new MySqlConnectionProfile(),
Postgresql = new PostgreSqlConnectionProfile(),
Cloudsql = new CloudSqlConnectionProfile(),
};
mockGrpcClient.Setup(x => x.GetConnectionProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConnectionProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
ConnectionProfile responseCallSettings = await client.GetConnectionProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConnectionProfile responseCancellationToken = await client.GetConnectionProfileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConnectionProfile()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConnectionProfileRequest request = new GetConnectionProfileRequest
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
};
ConnectionProfile expectedResponse = new ConnectionProfile
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
State = ConnectionProfile.Types.State.Deleted,
DisplayName = "display_name137f65c2",
Error = new gr::Status(),
Provider = DatabaseProvider.Cloudsql,
Mysql = new MySqlConnectionProfile(),
Postgresql = new PostgreSqlConnectionProfile(),
Cloudsql = new CloudSqlConnectionProfile(),
};
mockGrpcClient.Setup(x => x.GetConnectionProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
ConnectionProfile response = client.GetConnectionProfile(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConnectionProfileAsync()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConnectionProfileRequest request = new GetConnectionProfileRequest
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
};
ConnectionProfile expectedResponse = new ConnectionProfile
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
State = ConnectionProfile.Types.State.Deleted,
DisplayName = "display_name137f65c2",
Error = new gr::Status(),
Provider = DatabaseProvider.Cloudsql,
Mysql = new MySqlConnectionProfile(),
Postgresql = new PostgreSqlConnectionProfile(),
Cloudsql = new CloudSqlConnectionProfile(),
};
mockGrpcClient.Setup(x => x.GetConnectionProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConnectionProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
ConnectionProfile responseCallSettings = await client.GetConnectionProfileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConnectionProfile responseCancellationToken = await client.GetConnectionProfileAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConnectionProfileResourceNames()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConnectionProfileRequest request = new GetConnectionProfileRequest
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
};
ConnectionProfile expectedResponse = new ConnectionProfile
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
State = ConnectionProfile.Types.State.Deleted,
DisplayName = "display_name137f65c2",
Error = new gr::Status(),
Provider = DatabaseProvider.Cloudsql,
Mysql = new MySqlConnectionProfile(),
Postgresql = new PostgreSqlConnectionProfile(),
Cloudsql = new CloudSqlConnectionProfile(),
};
mockGrpcClient.Setup(x => x.GetConnectionProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
ConnectionProfile response = client.GetConnectionProfile(request.ConnectionProfileName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConnectionProfileResourceNamesAsync()
{
moq::Mock<DataMigrationService.DataMigrationServiceClient> mockGrpcClient = new moq::Mock<DataMigrationService.DataMigrationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConnectionProfileRequest request = new GetConnectionProfileRequest
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
};
ConnectionProfile expectedResponse = new ConnectionProfile
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
State = ConnectionProfile.Types.State.Deleted,
DisplayName = "display_name137f65c2",
Error = new gr::Status(),
Provider = DatabaseProvider.Cloudsql,
Mysql = new MySqlConnectionProfile(),
Postgresql = new PostgreSqlConnectionProfile(),
Cloudsql = new CloudSqlConnectionProfile(),
};
mockGrpcClient.Setup(x => x.GetConnectionProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConnectionProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DataMigrationServiceClient client = new DataMigrationServiceClientImpl(mockGrpcClient.Object, null);
ConnectionProfile responseCallSettings = await client.GetConnectionProfileAsync(request.ConnectionProfileName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConnectionProfile responseCancellationToken = await client.GetConnectionProfileAsync(request.ConnectionProfileName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace SpriteParticleEmitter
{
#if UNITY_5_3_OR_NEWER
/// <summary>
/// This class is a modification on the class shared publicly by Glenn Powell (glennpow) tha can be found here
/// http://forum.unity3d.com/threads/free-script-particle-systems-in-ui-screen-space-overlay.406862/
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(CanvasRenderer))]
[RequireComponent(typeof(ParticleSystem))]
[AddComponentMenu("UI/Effects/Extensions/UI Particle System")]
public class UIParticleRenderer : MaskableGraphic
{
[Tooltip("Having this enabled run the system in LateUpdate rather than in Update making it faster but less precise (more clunky)")]
public bool fixedTime = true;
private Transform _transform;
private ParticleSystem pSystem;
private ParticleSystem.Particle[] particles;
private UIVertex[] _quad = new UIVertex[4];
private Vector4 imageUV = Vector4.zero;
private ParticleSystem.TextureSheetAnimationModule textureSheetAnimation;
private int textureSheetAnimationFrames;
private Vector2 textureSheetAnimationFrameSize;
private ParticleSystemRenderer pRenderer;
private Material currentMaterial;
private Texture currentTexture;
#if UNITY_5_5_OR_NEWER
private ParticleSystem.MainModule mainModule;
#endif
public override Texture mainTexture
{
get
{
return currentTexture;
}
}
protected bool Initialize()
{
// initialize members
if (_transform == null)
{
_transform = transform;
}
if (pSystem == null)
{
pSystem = GetComponent<ParticleSystem>();
if (pSystem == null)
{
return false;
}
#if UNITY_5_5_OR_NEWER
mainModule = pSystem.main;
if (pSystem.main.maxParticles > 14000)
{
mainModule.maxParticles = 14000;
}
#else
if (pSystem.maxParticles > 14000)
pSystem.maxParticles = 14000;
#endif
pRenderer = pSystem.GetComponent<ParticleSystemRenderer>();
if (pRenderer != null)
pRenderer.enabled = false;
Shader foundShader = Shader.Find("UI/Particles/Additive");
Material pMaterial = new Material(foundShader);
if (material == null)
material = pMaterial;
currentMaterial = material;
if (currentMaterial && currentMaterial.HasProperty("_MainTex"))
{
currentTexture = currentMaterial.mainTexture;
if (currentTexture == null)
currentTexture = Texture2D.whiteTexture;
}
material = currentMaterial;
// automatically set scaling
#if UNITY_5_5_OR_NEWER
mainModule.scalingMode = ParticleSystemScalingMode.Hierarchy;
#else
pSystem.scalingMode = ParticleSystemScalingMode.Hierarchy;
#endif
particles = null;
}
#if UNITY_5_5_OR_NEWER
if (particles == null)
particles = new ParticleSystem.Particle[pSystem.main.maxParticles];
#else
if (particles == null)
particles = new ParticleSystem.Particle[pSystem.maxParticles];
#endif
imageUV = new Vector4(0, 0, 1, 1);
// prepare texture sheet animation
textureSheetAnimation = pSystem.textureSheetAnimation;
textureSheetAnimationFrames = 0;
textureSheetAnimationFrameSize = Vector2.zero;
if (textureSheetAnimation.enabled)
{
textureSheetAnimationFrames = textureSheetAnimation.numTilesX * textureSheetAnimation.numTilesY;
textureSheetAnimationFrameSize = new Vector2(1f / textureSheetAnimation.numTilesX, 1f / textureSheetAnimation.numTilesY);
}
return true;
}
protected override void Awake()
{
base.Awake();
if (!Initialize())
enabled = false;
}
protected override void OnPopulateMesh(VertexHelper vh)
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
if (!Initialize())
{
return;
}
}
#endif
// prepare vertices
vh.Clear();
if (!gameObject.activeInHierarchy)
{
return;
}
Vector2 temp = Vector2.zero;
Vector2 corner1 = Vector2.zero;
Vector2 corner2 = Vector2.zero;
// iterate through current particles
int count = pSystem.GetParticles(particles);
for (int i = 0; i < count; ++i)
{
ParticleSystem.Particle particle = particles[i];
// get particle properties
#if UNITY_5_5_OR_NEWER
Vector2 position = (mainModule.simulationSpace == ParticleSystemSimulationSpace.Local ? particle.position : _transform.InverseTransformPoint(particle.position));
#else
Vector2 position = (pSystem.simulationSpace == ParticleSystemSimulationSpace.Local ? particle.position : _transform.InverseTransformPoint(particle.position));
#endif
float rotation = -particle.rotation * Mathf.Deg2Rad;
float rotation90 = rotation + Mathf.PI / 2;
Color32 color = particle.GetCurrentColor(pSystem);
float size = particle.GetCurrentSize(pSystem) * 0.5f;
// apply scale
#if UNITY_5_5_OR_NEWER
if (mainModule.scalingMode == ParticleSystemScalingMode.Shape)
position /= canvas.scaleFactor;
#else
if (pSystem.scalingMode == ParticleSystemScalingMode.Shape)
position /= canvas.scaleFactor;
#endif
// apply texture sheet animation
Vector4 particleUV = imageUV;
if (textureSheetAnimation.enabled)
{
#if UNITY_5_5_OR_NEWER
float frameProgress = textureSheetAnimation.frameOverTime.curveMin.Evaluate(1 - (particle.remainingLifetime / particle.startLifetime));
#else
float frameProgress = 1 - (particle.lifetime / particle.startLifetime);
#endif
frameProgress = Mathf.Repeat(frameProgress * textureSheetAnimation.cycleCount, 1);
int frame = 0;
switch (textureSheetAnimation.animation)
{
case ParticleSystemAnimationType.WholeSheet:
frame = Mathf.FloorToInt(frameProgress * textureSheetAnimationFrames);
break;
case ParticleSystemAnimationType.SingleRow:
frame = Mathf.FloorToInt(frameProgress * textureSheetAnimation.numTilesX);
int row = textureSheetAnimation.rowIndex;
// if (textureSheetAnimation.useRandomRow) { // FIXME - is this handled internally by rowIndex?
// row = Random.Range(0, textureSheetAnimation.numTilesY, using: particle.randomSeed);
// }
frame += row * textureSheetAnimation.numTilesX;
break;
}
frame %= textureSheetAnimationFrames;
particleUV.x = (frame % textureSheetAnimation.numTilesX) * textureSheetAnimationFrameSize.x;
particleUV.y = Mathf.FloorToInt(frame / textureSheetAnimation.numTilesX) * textureSheetAnimationFrameSize.y;
particleUV.z = particleUV.x + textureSheetAnimationFrameSize.x;
particleUV.w = particleUV.y + textureSheetAnimationFrameSize.y;
}
temp.x = particleUV.x;
temp.y = particleUV.y;
_quad[0] = UIVertex.simpleVert;
_quad[0].color = color;
_quad[0].uv0 = temp;
temp.x = particleUV.x;
temp.y = particleUV.w;
_quad[1] = UIVertex.simpleVert;
_quad[1].color = color;
_quad[1].uv0 = temp;
temp.x = particleUV.z;
temp.y = particleUV.w;
_quad[2] = UIVertex.simpleVert;
_quad[2].color = color;
_quad[2].uv0 = temp;
temp.x = particleUV.z;
temp.y = particleUV.y;
_quad[3] = UIVertex.simpleVert;
_quad[3].color = color;
_quad[3].uv0 = temp;
if (rotation == 0)
{
// no rotation
corner1.x = position.x - size;
corner1.y = position.y - size;
corner2.x = position.x + size;
corner2.y = position.y + size;
temp.x = corner1.x;
temp.y = corner1.y;
_quad[0].position = temp;
temp.x = corner1.x;
temp.y = corner2.y;
_quad[1].position = temp;
temp.x = corner2.x;
temp.y = corner2.y;
_quad[2].position = temp;
temp.x = corner2.x;
temp.y = corner1.y;
_quad[3].position = temp;
}
else
{
// apply rotation
Vector2 right = new Vector2(Mathf.Cos(rotation), Mathf.Sin(rotation)) * size;
Vector2 up = new Vector2(Mathf.Cos(rotation90), Mathf.Sin(rotation90)) * size;
_quad[0].position = position - right - up;
_quad[1].position = position - right + up;
_quad[2].position = position + right + up;
_quad[3].position = position + right - up;
}
vh.AddUIVertexQuad(_quad);
}
}
void Update()
{
if (!fixedTime && Application.isPlaying)
{
pSystem.Simulate(Time.unscaledDeltaTime, false, false, true);
SetAllDirty();
if ((currentMaterial!= null && currentTexture != currentMaterial.mainTexture) ||
(material!=null && currentMaterial != null && material.shader != currentMaterial.shader))
{
pSystem = null;
Initialize();
}
}
}
void LateUpdate()
{
if (!Application.isPlaying)
{
SetAllDirty();
}
else
{
if (fixedTime)
{
pSystem.Simulate(Time.unscaledDeltaTime, false, false, true);
SetAllDirty();
if ((currentMaterial != null && currentTexture != currentMaterial.mainTexture) ||
(material != null && currentMaterial != null && material.shader != currentMaterial.shader))
{
pSystem = null;
Initialize();
}
}
}
if (material == currentMaterial)
return;
pSystem = null;
Initialize();
}
}
#endif
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ASP.NETSinglePageApplication.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// 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: Base class for representing Events
**
**
=============================================================================*/
namespace System.Security.AccessControl
{
internal class EventWaitHandleSecurity
{
}
internal enum EventWaitHandleRights
{
}
}
namespace System.Threading
{
using System;
using System.Threading;
using System.Runtime.CompilerServices;
using System.IO;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.AccessControl;
[ComVisibleAttribute(true)]
public class EventWaitHandle : WaitHandle
{
private const uint AccessRights =
(uint)Win32Native.MAXIMUM_ALLOWED | Win32Native.SYNCHRONIZE | Win32Native.EVENT_MODIFY_STATE;
public EventWaitHandle(bool initialState, EventResetMode mode) : this(initialState, mode, null) { }
public EventWaitHandle(bool initialState, EventResetMode mode, string name)
{
if (name != null)
{
#if PLATFORM_UNIX
throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives);
#else
if (System.IO.Path.MaxPath < name.Length)
{
throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, name, Path.MaxPath), nameof(name));
}
#endif
}
uint eventFlags = initialState ? Win32Native.CREATE_EVENT_INITIAL_SET : 0;
switch (mode)
{
case EventResetMode.ManualReset:
eventFlags |= Win32Native.CREATE_EVENT_MANUAL_RESET;
break;
case EventResetMode.AutoReset:
break;
default:
throw new ArgumentException(SR.Format(SR.Argument_InvalidFlag, name));
};
SafeWaitHandle _handle = Win32Native.CreateEventEx(null, name, eventFlags, AccessRights);
if (_handle.IsInvalid)
{
int errorCode = Marshal.GetLastWin32Error();
_handle.SetHandleAsInvalid();
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
throw Win32Marshal.GetExceptionForWin32Error(errorCode, name);
}
SetHandleInternal(_handle);
}
public EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew)
: this(initialState, mode, name, out createdNew, null)
{
}
internal unsafe EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity)
{
if (name != null)
{
#if PLATFORM_UNIX
throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives);
#else
if (System.IO.Path.MaxPath < name.Length)
{
throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, name, Path.MaxPath), nameof(name));
}
#endif
}
Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
uint eventFlags = initialState ? Win32Native.CREATE_EVENT_INITIAL_SET : 0;
switch (mode)
{
case EventResetMode.ManualReset:
eventFlags |= Win32Native.CREATE_EVENT_MANUAL_RESET;
break;
case EventResetMode.AutoReset:
break;
default:
throw new ArgumentException(SR.Format(SR.Argument_InvalidFlag, name));
};
SafeWaitHandle _handle = Win32Native.CreateEventEx(secAttrs, name, eventFlags, AccessRights);
int errorCode = Marshal.GetLastWin32Error();
if (_handle.IsInvalid)
{
_handle.SetHandleAsInvalid();
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
throw Win32Marshal.GetExceptionForWin32Error(errorCode, name);
}
createdNew = errorCode != Win32Native.ERROR_ALREADY_EXISTS;
SetHandleInternal(_handle);
}
private EventWaitHandle(SafeWaitHandle handle)
{
SetHandleInternal(handle);
}
public static EventWaitHandle OpenExisting(string name)
{
return OpenExisting(name, (EventWaitHandleRights)0);
}
internal static EventWaitHandle OpenExisting(string name, EventWaitHandleRights rights)
{
EventWaitHandle result;
switch (OpenExistingWorker(name, rights, out result))
{
case OpenExistingResult.NameNotFound:
throw new WaitHandleCannotBeOpenedException();
case OpenExistingResult.NameInvalid:
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
case OpenExistingResult.PathNotFound:
throw Win32Marshal.GetExceptionForWin32Error(Win32Native.ERROR_PATH_NOT_FOUND, "");
default:
return result;
}
}
public static bool TryOpenExisting(string name, out EventWaitHandle result)
{
return OpenExistingWorker(name, (EventWaitHandleRights)0, out result) == OpenExistingResult.Success;
}
private static OpenExistingResult OpenExistingWorker(string name, EventWaitHandleRights rights, out EventWaitHandle result)
{
#if PLATFORM_UNIX
throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives);
#else
if (name == null)
{
throw new ArgumentNullException(nameof(name), SR.ArgumentNull_WithParamName);
}
if (name.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
}
if (null != name && System.IO.Path.MaxPath < name.Length)
{
throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, name, Path.MaxPath), nameof(name));
}
result = null;
SafeWaitHandle myHandle = Win32Native.OpenEvent(AccessRights, false, name);
if (myHandle.IsInvalid)
{
int errorCode = Marshal.GetLastWin32Error();
if (Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode)
return OpenExistingResult.NameNotFound;
if (Win32Native.ERROR_PATH_NOT_FOUND == errorCode)
return OpenExistingResult.PathNotFound;
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
return OpenExistingResult.NameInvalid;
//this is for passed through Win32Native Errors
throw Win32Marshal.GetExceptionForWin32Error(errorCode, "");
}
result = new EventWaitHandle(myHandle);
return OpenExistingResult.Success;
#endif
}
public bool Reset()
{
bool res = Win32Native.ResetEvent(safeWaitHandle);
if (!res)
throw Win32Marshal.GetExceptionForLastWin32Error();
return res;
}
public bool Set()
{
bool res = Win32Native.SetEvent(safeWaitHandle);
if (!res)
throw Win32Marshal.GetExceptionForLastWin32Error();
return res;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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.
*
*/
#region Import
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ASC.CRM.Core.Dao;
using ASC.Web.CRM.Classes;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using EnumExtension = ASC.Web.CRM.Classes.EnumExtension;
#endregion
namespace ASC.CRM.Core.Entities
{
public abstract class FilterObject
{
public string SortBy { get; set; }
public string SortOrder { get; set; }
public string FilterValue { get; set; }
public bool IsAsc
{
get
{
return !String.IsNullOrEmpty(SortOrder) && SortOrder != "descending";
}
}
public abstract ICollection GetItemsByFilter(DaoFactory daofactory);
}
public class CasesFilterObject : FilterObject
{
public bool? IsClosed { get; set; }
public List<string> Tags { get; set; }
public CasesFilterObject()
{
SortBy = "title";
SortOrder = "ascending";
}
public CasesFilterObject(string base64String)
{
if (string.IsNullOrEmpty(base64String)) return;
var json = Encoding.UTF8.GetString(Convert.FromBase64String(base64String));
var jsonArray = json.Split(';');
foreach (var filterItem in jsonArray)
{
var filterObj = JObject.Parse(filterItem);
var paramString = filterObj.Value<string>("params");
if (string.IsNullOrEmpty(paramString)) continue;
var filterParam = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(paramString)));
switch (filterObj.Value<string>("id"))
{
case "sorter":
SortBy = filterParam.Value<string>("id");
SortOrder = filterParam.Value<string>("sortOrder");
break;
case "text":
FilterValue = filterParam.Value<string>("value");
break;
case "closed":
case "opened":
IsClosed = filterParam.Value<bool>("value");
break;
case "tags":
Tags = filterParam.Value<JArray>("value").ToList().ConvertAll(n => n.ToString());
break;
}
}
}
public override ICollection GetItemsByFilter(DaoFactory daofactory)
{
SortedByType sortBy;
if (!EnumExtension.TryParse(SortBy, true, out sortBy))
{
sortBy = SortedByType.Title;
}
return daofactory.CasesDao.GetCases(
FilterValue,
0,
IsClosed,
Tags,
0, 0,
new OrderBy(sortBy, IsAsc));
}
}
public class TaskFilterObject : FilterObject
{
public int CategoryId { get; set; }
public int ContactId { get; set; }
public Guid ResponsibleId { get; set; }
public bool? IsClosed { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public TaskFilterObject()
{
IsClosed = null;
FromDate = DateTime.MinValue;
ToDate = DateTime.MinValue;
SortBy = "deadline";
SortOrder = "ascending";
}
public TaskFilterObject(string base64String)
{
if (string.IsNullOrEmpty(base64String)) return;
var json = Encoding.UTF8.GetString(Convert.FromBase64String(base64String));
var jsonArray = json.Split(';');
foreach (var filterItem in jsonArray)
{
var filterObj = JObject.Parse(filterItem);
var paramString = filterObj.Value<string>("params");
if (string.IsNullOrEmpty(paramString)) continue;
var filterParam = Global.JObjectParseWithDateAsString(Encoding.UTF8.GetString(Convert.FromBase64String(paramString)));
switch (filterObj.Value<string>("id"))
{
case "sorter":
SortBy = filterParam.Value<string>("id");
SortOrder = filterParam.Value<string>("sortOrder");
break;
case "text":
FilterValue = filterParam.Value<string>("value");
break;
case "my":
case "responsibleID":
ResponsibleId = new Guid(filterParam.Value<string>("value"));
break;
case "overdue":
case "today":
case "theNext":
var valueString = filterParam.Value<string>("value");
var fromToArray = JsonConvert.DeserializeObject<List<string>>(valueString);
if (fromToArray.Count != 2) continue;
FromDate = !String.IsNullOrEmpty(fromToArray[0])
? Global.ApiDateTimeParse(fromToArray[0]) : DateTime.MinValue;
ToDate = !String.IsNullOrEmpty(fromToArray[1])
? Global.ApiDateTimeParse(fromToArray[1]) : DateTime.MinValue;
break;
case "fromToDate":
FromDate = filterParam.Value<DateTime>("from");
ToDate = (filterParam.Value<DateTime>("to")).AddDays(1).AddSeconds(-1);
break;
case "categoryID":
CategoryId = filterParam.Value<int>("value");
break;
case "openTask":
case "closedTask":
IsClosed = filterParam.Value<bool>("value");
break;
case "contactID":
ContactId = filterParam.Value<int>("id");
break;
}
}
}
public override ICollection GetItemsByFilter(DaoFactory daofactory)
{
TaskSortedByType sortBy;
if (!EnumExtension.TryParse(SortBy, true, out sortBy))
{
sortBy = TaskSortedByType.DeadLine;
}
return daofactory.TaskDao.GetTasks(
FilterValue,
ResponsibleId,
CategoryId,
IsClosed,
FromDate,
ToDate,
ContactId > 0 ? EntityType.Contact : EntityType.Any,
ContactId,
0, 0,
new OrderBy(sortBy, IsAsc));
}
}
public class DealFilterObject : FilterObject
{
public Guid ResponsibleId { get; set; }
public String StageType { get; set; }
public int OpportunityStageId { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public int ContactId { get; set; }
public bool? ContactAlsoIsParticipant { get; set; }
public List<string> Tags { get; set; }
public DealFilterObject()
{
ContactAlsoIsParticipant = null;
FromDate = DateTime.MinValue;
ToDate = DateTime.MinValue;
SortBy = "stage";
SortOrder = "ascending";
}
public DealFilterObject(string base64String)
{
if (string.IsNullOrEmpty(base64String)) return;
var json = Encoding.UTF8.GetString(Convert.FromBase64String(base64String));
var jsonArray = json.Split(';');
foreach (var filterItem in jsonArray)
{
var filterObj = JObject.Parse(filterItem);
var paramString = filterObj.Value<string>("params");
if (string.IsNullOrEmpty(paramString)) continue;
var filterParam = Global.JObjectParseWithDateAsString(Encoding.UTF8.GetString(Convert.FromBase64String(paramString)));
switch (filterObj.Value<string>("id"))
{
case "sorter":
SortBy = filterParam.Value<string>("id");
SortOrder = filterParam.Value<string>("sortOrder");
break;
case "text":
FilterValue = filterParam.Value<string>("value");
break;
case "my":
case "responsibleID":
ResponsibleId = new Guid(filterParam.Value<string>("value"));
break;
case "stageTypeOpen":
case "stageTypeClosedAndWon":
case "stageTypeClosedAndLost":
StageType = filterParam.Value<string>("value");
break;
case "opportunityStagesID":
OpportunityStageId = filterParam.Value<int>("value");
break;
case "lastMonth":
case "yesterday":
case "today":
case "thisMonth":
var valueString = filterParam.Value<string>("value");
var fromToArray = JsonConvert.DeserializeObject<List<string>>(valueString);
if (fromToArray.Count != 2) continue;
FromDate = Global.ApiDateTimeParse(fromToArray[0]);
ToDate = Global.ApiDateTimeParse(fromToArray[1]);
break;
case "fromToDate":
FromDate = Global.ApiDateTimeParse(filterParam.Value<string>("from"));
ToDate = Global.ApiDateTimeParse(filterParam.Value<string>("to"));
break;
case "participantID":
ContactId = filterParam.Value<int>("id");
ContactAlsoIsParticipant = true;
break;
case "contactID":
ContactId = filterParam.Value<int>("id");
ContactAlsoIsParticipant = false;
break;
case "tags":
Tags = filterParam.Value<JArray>("value").ToList().ConvertAll(n => n.ToString());
break;
}
}
}
public override ICollection GetItemsByFilter(DaoFactory daofactory)
{
DealSortedByType sortBy;
EnumExtension.TryParse(SortBy, true, out sortBy);
DealMilestoneStatus? stageType = null;
DealMilestoneStatus stage;
if (EnumExtension.TryParse(StageType, true, out stage))
{
stageType = stage;
}
return daofactory.DealDao.GetDeals(
FilterValue,
ResponsibleId,
OpportunityStageId,
Tags,
ContactId,
stageType,
ContactAlsoIsParticipant,
FromDate,
ToDate,
0, 0,
new OrderBy(sortBy, IsAsc));
}
}
public class ContactFilterObject : FilterObject
{
public List<string> Tags { get; set; }
public string ContactListView { get; set; }
public int ContactStage { get; set; }
public int ContactType { get; set; }
public Guid? ResponsibleId { get; set; }
public bool? IsShared { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public ContactFilterObject()
{
FromDate = DateTime.MinValue;
ToDate = DateTime.MinValue;
ResponsibleId = null;
ContactStage = -1;
ContactType = -1;
SortBy = "created";
SortOrder = "descending";
}
public ContactFilterObject(string base64String)
{
ContactStage = -1;
ContactType = -1;
if (string.IsNullOrEmpty(base64String)) return;
var json = Encoding.UTF8.GetString(Convert.FromBase64String(base64String));
var jsonArray = json.Split(';');
foreach (var filterItem in jsonArray)
{
var filterObj = JObject.Parse(filterItem);
var paramString = filterObj.Value<string>("params");
if (string.IsNullOrEmpty(paramString)) continue;
var filterParam = Global.JObjectParseWithDateAsString(Encoding.UTF8.GetString(Convert.FromBase64String(paramString)));
switch (filterObj.Value<string>("id"))
{
case "sorter":
SortBy = filterParam.Value<string>("id");
SortOrder = filterParam.Value<string>("sortOrder");
break;
case "text":
FilterValue = filterParam.Value<string>("value");
break;
case "my":
case "responsibleID":
case "noresponsible":
ResponsibleId = new Guid(filterParam.Value<string>("value"));
break;
case "tags":
Tags = filterParam.Value<JArray>("value").ToList().ConvertAll(n => n.ToString());
break;
case "withopportunity":
case "person":
case "company":
ContactListView = filterParam.Value<string>("value");
break;
case "contactType":
ContactType = filterParam.Value<int>("value");
break;
case "contactStage":
ContactStage = filterParam.Value<int>("value");
break;
case "lastMonth":
case "yesterday":
case "today":
case "thisMonth":
var valueString = filterParam.Value<string>("value");
var fromToArray = JsonConvert.DeserializeObject<List<string>>(valueString);
if (fromToArray.Count != 2) continue;
FromDate = Global.ApiDateTimeParse(fromToArray[0]);
ToDate = Global.ApiDateTimeParse(fromToArray[1]);
break;
case "fromToDate":
FromDate = Global.ApiDateTimeParse(filterParam.Value<string>("from"));
ToDate = Global.ApiDateTimeParse(filterParam.Value<string>("to"));
break;
case "restricted":
case "shared":
IsShared = filterParam.Value<bool>("value");
break;
}
}
}
public override ICollection GetItemsByFilter(DaoFactory daofactory)
{
ContactSortedByType sortBy;
if (!EnumExtension.TryParse(SortBy, true, out sortBy))
{
sortBy = ContactSortedByType.Created;
}
ContactListViewType contactListViewType;
EnumExtension.TryParse(ContactListView, true, out contactListViewType);
return daofactory.ContactDao.GetContacts(
FilterValue,
Tags,
ContactStage,
ContactType,
contactListViewType,
FromDate,
ToDate,
0,
0,
new OrderBy(sortBy, IsAsc),
ResponsibleId,
IsShared);
}
};
public class InvoiceItemFilterObject : FilterObject
{
public bool? InventoryStock { get; set; }
public InvoiceItemFilterObject()
{
InventoryStock = null;
SortBy = "name";
SortOrder = "ascending";
}
public InvoiceItemFilterObject(string base64String)
{
if (string.IsNullOrEmpty(base64String)) return;
var json = Encoding.UTF8.GetString(Convert.FromBase64String(base64String));
var jsonArray = json.Split(';');
foreach (var filterItem in jsonArray)
{
var filterObj = JObject.Parse(filterItem);
var paramString = filterObj.Value<string>("params");
if (string.IsNullOrEmpty(paramString)) continue;
var filterParam = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(paramString)));
switch (filterObj.Value<string>("id"))
{
case "sorter":
SortBy = filterParam.Value<string>("id");
SortOrder = filterParam.Value<string>("sortOrder");
break;
case "text":
FilterValue = filterParam.Value<string>("value");
break;
case "withInventoryStock":
case "withoutInventoryStock":
InventoryStock = filterParam.Value<bool>("value");
break;
}
}
}
public override ICollection GetItemsByFilter(DaoFactory daofactory)
{
InvoiceItemSortedByType sortBy;
EnumExtension.TryParse(SortBy, true, out sortBy);
return daofactory.InvoiceItemDao.GetInvoiceItems(
FilterValue,
0,
InventoryStock,
0, 0,
new OrderBy(sortBy, IsAsc));
}
}
}
| |
//
// DictionaryContainer.cs: Foundation implementation for NSDictionary based setting classes
//
// Authors: Marek Safar ([email protected])
//
// Copyright 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Runtime.InteropServices;
using MonoMac.CoreFoundation;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public abstract class DictionaryContainer
{
#if !COREBUILD
internal /*protected*/ DictionaryContainer ()
{
Dictionary = new NSMutableDictionary ();
}
internal /*protected*/ DictionaryContainer (NSDictionary dictionary)
{
if (dictionary == null)
throw new ArgumentNullException ("dictionary");
Dictionary = dictionary;
}
public NSDictionary Dictionary { get; private set; }
protected T[] GetArray<T> (NSString key) where T : NSObject
{
if (key == null)
throw new ArgumentNullException ("key");
var value = CFDictionary.GetValue (Dictionary.Handle, key.Handle);
if (value == IntPtr.Zero)
return null;
return NSArray.ArrayFromHandle<T> (value);
}
protected T[] GetArray<T> (NSString key, Func<IntPtr, T> creator)
{
if (key == null)
throw new ArgumentNullException ("key");
var value = CFDictionary.GetValue (Dictionary.Handle, key.Handle);
if (value == IntPtr.Zero)
return null;
return NSArray.ArrayFromHandleFunc<T> (value, creator);
}
protected int? GetInt32Value (NSString key)
{
if (key == null)
throw new ArgumentNullException ("key");
NSObject value;
if (!Dictionary.TryGetValue (key, out value))
return null;
return ((NSNumber) value).Int32Value;
}
protected long? GetLongValue (NSString key)
{
if (key == null)
throw new ArgumentNullException ("key");
NSObject value;
if (!Dictionary.TryGetValue (key, out value))
return null;
return ((NSNumber) value).Int64Value;
}
protected uint? GetUIntValue (NSString key)
{
if (key == null)
throw new ArgumentNullException ("key");
NSObject value;
if (!Dictionary.TryGetValue (key, out value))
return null;
return ((NSNumber) value).UInt32Value;
}
protected float? GetFloatValue (NSString key)
{
if (key == null)
throw new ArgumentNullException ("key");
NSObject value;
if (!Dictionary.TryGetValue (key, out value))
return null;
return ((NSNumber) value).FloatValue;
}
protected double? GetDoubleValue (NSString key)
{
if (key == null)
throw new ArgumentNullException ("key");
NSObject value;
if (!Dictionary.TryGetValue (key, out value))
return null;
return ((NSNumber) value).DoubleValue;
}
protected bool? GetBoolValue (NSString key)
{
if (key == null)
throw new ArgumentNullException ("key");
var value = CFDictionary.GetValue (Dictionary.Handle, key.Handle);
if (value == IntPtr.Zero)
return null;
return CFBoolean.GetValue (value);
}
protected NSDictionary GetNSDictionary (NSString key)
{
if (key == null)
throw new ArgumentNullException ("key");
NSObject value;
Dictionary.TryGetValue (key, out value);
return value as NSDictionary;
}
protected string GetNSStringValue (NSString key)
{
if (key == null)
throw new ArgumentNullException ("key");
NSObject value;
Dictionary.TryGetValue (key, out value);
return value as NSString;
}
protected string GetStringValue (NSString key)
{
if (key == null)
throw new ArgumentNullException ("key");
NSObject value;
if (!Dictionary.TryGetValue (key, out value))
return null;
return CFString.FetchString (value.Handle);
}
protected string GetStringValue (string key)
{
if (key == null)
throw new ArgumentNullException ("key");
using (var str = new CFString (key)) {
return CFString.FetchString (CFDictionary.GetValue (Dictionary.Handle, str.handle));
}
}
protected void SetArrayValue (NSString key, NSNumber[] values)
{
if (key == null)
throw new ArgumentNullException ("key");
if (values == null) {
RemoveValue (key);
return;
}
Dictionary [key] = NSArray.FromNSObjects (values);
}
protected void SetArrayValue (NSString key, string[] values)
{
if (key == null)
throw new ArgumentNullException ("key");
if (values == null) {
RemoveValue (key);
return;
}
Dictionary [key] = NSArray.FromStrings (values);
}
protected void SetArrayValue (NSString key, INativeObject[] values)
{
if (key == null)
throw new ArgumentNullException ("key");
if (values == null) {
RemoveValue (key);
return;
}
CFMutableDictionary.SetValue (Dictionary.Handle, key.Handle, CFArray.FromNativeObjects (values).Handle);
}
#region Sets CFBoolean value
protected void SetBooleanValue (NSString key, bool? value)
{
if (key == null)
throw new ArgumentNullException ("key");
if (value == null) {
RemoveValue (key);
return;
}
CFMutableDictionary.SetValue (Dictionary.Handle, key.Handle, value.Value ? CFBoolean.True.Handle : CFBoolean.False.Handle);
}
#endregion
#region Sets NSNumber value
protected void SetNumberValue (NSString key, int? value)
{
if (key == null)
throw new ArgumentNullException ("key");
if (value == null) {
RemoveValue (key);
return;
}
Dictionary [key] = new NSNumber (value.Value);
}
protected void SetNumberValue (NSString key, uint? value)
{
if (key == null)
throw new ArgumentNullException ("key");
if (value == null) {
RemoveValue (key);
return;
}
Dictionary [key] = new NSNumber (value.Value);
}
protected void SetNumberValue (NSString key, long? value)
{
if (key == null)
throw new ArgumentNullException ("key");
Dictionary [key] = new NSNumber (value.Value);
}
protected void SetNumberValue (NSString key, float? value)
{
if (key == null)
throw new ArgumentNullException ("key");
if (value == null) {
RemoveValue (key);
return;
}
Dictionary [key] = new NSNumber (value.Value);
}
protected void SetNumberValue (NSString key, double? value)
{
if (key == null)
throw new ArgumentNullException ("key");
if (value == null) {
RemoveValue (key);
return;
}
Dictionary [key] = new NSNumber (value.Value);
}
#endregion
#region Sets NSString value
protected void SetStringValue (NSString key, string value)
{
SetStringValue (key, value == null ? (NSString) null : new NSString (value));
}
protected void SetStringValue (NSString key, NSString value)
{
if (key == null)
throw new ArgumentNullException ("key");
if (value == null) {
RemoveValue (key);
} else {
Dictionary [key] = value;
}
}
#endregion
#region Sets Native value
protected void SetNativeValue (NSString key, INativeObject value, bool removeNullValue = true)
{
if (key == null)
throw new ArgumentNullException ("key");
if (value == null && removeNullValue) {
RemoveValue (key);
} else {
CFMutableDictionary.SetValue (Dictionary.Handle, key.Handle, value == null ? IntPtr.Zero : value.Handle);
}
}
#endregion
protected void RemoveValue (NSString key)
{
if (key == null)
throw new ArgumentNullException ("key");
((NSMutableDictionary) Dictionary).Remove (key);
}
#endif
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.BitStamp.Native.BitStamp
File: PusherClient.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.BitStamp.Native
{
using System;
using Ecng.Common;
using Ecng.Net;
using Ecng.Serialization;
using Newtonsoft.Json.Linq;
using StockSharp.Logging;
using StockSharp.Localization;
using StockSharp.Messages;
using StockSharp.BitStamp.Native.Model;
class PusherClient : BaseLogReceiver
{
public event Action<string, Trade> NewTrade;
public event Action<string, OrderBook> NewOrderBook;
public event Action<string, OrderStates, Order> NewOrderLog;
public event Action<Exception> Error;
public event Action Connected;
public event Action<bool> Disconnected;
public event Action<string> TradesSubscribed;
public event Action<string> OrderBookSubscribed;
public event Action<string> OrderLogSubscribed;
public event Action<string> TradesUnSubscribed;
public event Action<string> OrderBookUnSubscribed;
public event Action<string> OrderLogUnSubscribed;
private int _activityTimeout;
private DateTime? _nextPing;
private readonly WebSocketClient _client;
public PusherClient()
{
_client = new WebSocketClient(
() =>
{
this.AddInfoLog(LocalizedStrings.Connected);
Connected?.Invoke();
},
expected =>
{
if (expected)
this.AddInfoLog(LocalizedStrings.Disconnected);
else
this.AddErrorLog(LocalizedStrings.Str2959);
Disconnected?.Invoke(expected);
},
error =>
{
this.AddErrorLog(error);
Error?.Invoke(error);
},
OnProcess,
(s, a) => this.AddInfoLog(s, a),
(s, a) => this.AddErrorLog(s, a),
(s, a) => this.AddVerboseLog(s, a),
(s) => this.AddVerboseLog(s));
}
protected override void DisposeManaged()
{
_client.Dispose();
base.DisposeManaged();
}
public void Connect()
{
_nextPing = null;
_activityTimeout = 0;
this.AddInfoLog(LocalizedStrings.Connecting);
_client.Connect("wss://ws.bitstamp.net", true);
}
public void Disconnect()
{
this.AddInfoLog(LocalizedStrings.Disconnecting);
_client.Disconnect();
}
private void OnProcess(dynamic obj)
{
var channel = (string)obj.channel;
var evt = (string)obj.@event;
var data = obj.data;
//if (data != null && evt != "bts:error")
// data = ((string)data).DeserializeObject<object>();
switch (evt)
{
//case "pusher:connection_established":
// _activityTimeout = (int)data.activity_timeout;
// _nextPing = DateTime.UtcNow.AddSeconds(_activityTimeout);
// Connected?.Invoke();
// break;
case "bts:error":
Error?.Invoke(new InvalidOperationException((string)data.message));
break;
case "ping":
SendPingPong("pong");
break;
case "pong":
break;
case "bts:subscription_succeeded":
{
if (channel.StartsWith(ChannelNames.OrderBook))
OrderBookSubscribed?.Invoke(GetPair(channel, ChannelNames.OrderBook));
else if (channel.StartsWith(ChannelNames.Trades))
TradesSubscribed?.Invoke(GetPair(channel, ChannelNames.Trades));
else if (channel.StartsWith(ChannelNames.OrderLog))
OrderLogSubscribed?.Invoke(GetPair(channel, ChannelNames.OrderLog));
else
this.AddErrorLog(LocalizedStrings.Str3311Params, channel);
break;
}
case "bts:unsubscription_succeeded":
{
if (channel.StartsWith(ChannelNames.OrderBook))
OrderBookUnSubscribed?.Invoke(GetPair(channel, ChannelNames.OrderBook));
else if (channel.StartsWith(ChannelNames.Trades))
TradesUnSubscribed?.Invoke(GetPair(channel, ChannelNames.Trades));
else if (channel.StartsWith(ChannelNames.OrderLog))
OrderLogUnSubscribed?.Invoke(GetPair(channel, ChannelNames.OrderLog));
else
this.AddErrorLog(LocalizedStrings.Str3311Params, channel);
break;
}
case "trade":
NewTrade?.Invoke(GetPair(channel, ChannelNames.Trades), ((JToken)data).DeserializeObject<Trade>());
break;
case "data":
NewOrderBook?.Invoke(GetPair(channel, ChannelNames.OrderBook), ((JToken)data).DeserializeObject<OrderBook>());
break;
case "order_created":
case "order_changed":
case "order_deleted":
NewOrderLog?.Invoke(GetPair(channel, ChannelNames.OrderLog), evt == "order_deleted" ? OrderStates.Done : OrderStates.Active, ((JToken)data).DeserializeObject<Order>());
break;
default:
this.AddErrorLog(LocalizedStrings.Str3312Params, evt);
break;
}
}
private static string GetPair(string channel, string name)
{
channel = channel.Remove(name).Remove("_");
if (channel.IsEmpty())
channel = "btcusd";
return channel;
}
private static class ChannelNames
{
public const string Trades = "live_trades_";
public const string OrderBook = "order_book_";
public const string OrderLog = "live_orders_";
}
private static class Commands
{
public const string Subscribe = "subscribe";
public const string UnSubscribe = "unsubscribe";
}
public void SubscribeTrades(string currency)
{
Process(Commands.Subscribe, ChannelNames.Trades + currency);
}
public void UnSubscribeTrades(string currency)
{
Process(Commands.UnSubscribe, ChannelNames.Trades + currency);
}
public void SubscribeOrderBook(string currency)
{
Process(Commands.Subscribe, ChannelNames.OrderBook + currency);
}
public void UnSubscribeOrderBook(string currency)
{
Process(Commands.UnSubscribe, ChannelNames.OrderBook + currency);
}
public void SubscribeOrderLog(string currency)
{
Process(Commands.Subscribe, ChannelNames.OrderLog + currency);
}
public void UnSubscribeOrderLog(string currency)
{
Process(Commands.UnSubscribe, ChannelNames.OrderLog + currency);
}
private void Process(string action, string channel)
{
if (action.IsEmpty())
throw new ArgumentNullException(nameof(action));
if (channel.IsEmpty())
throw new ArgumentNullException(nameof(channel));
_client.Send(new
{
@event = $"bts:{action}",
data = new { channel }
});
}
public void ProcessPing()
{
if (_nextPing == null || DateTime.UtcNow < _nextPing.Value)
return;
SendPingPong("ping");
}
private void SendPingPong(string action)
{
_client.Send(new { @event = $"{action}" });
if (_activityTimeout > 0)
_nextPing = DateTime.UtcNow.AddSeconds(_activityTimeout);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
namespace System.Reflection.Emit
{
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo
{
#region Private Static Members
internal static MethodInfo GetMethod(MethodInfo method, TypeBuilderInstantiation type)
{
return new MethodOnTypeBuilderInstantiation(method, type);
}
#endregion
#region Private Data Mebers
internal MethodInfo m_method;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal MethodOnTypeBuilderInstantiation(MethodInfo method, TypeBuilderInstantiation type)
{
Contract.Assert(method is MethodBuilder || method is RuntimeMethodInfo);
m_method = method;
m_type = type;
}
#endregion
internal override Type[] GetParameterTypes()
{
return m_method.GetParameterTypes();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return m_method.MemberType; } }
public override String Name { get { return m_method.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
public override Object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
MethodBuilder mb = m_method as MethodBuilder;
if (mb != null)
return mb.MetadataTokenInternal;
else
{
Contract.Assert(m_method is RuntimeMethodInfo);
return m_method.MetadataToken;
}
}
}
public override Module Module { get { return m_method.Module; } }
public new Type GetType() { return base.GetType(); }
#endregion
#region MethodBase Members
[Pure]
public override ParameterInfo[] GetParameters() { return m_method.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle { get { return m_method.MethodHandle; } }
public override MethodAttributes Attributes { get { return m_method.Attributes; } }
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException();
}
public override CallingConventions CallingConvention { get { return m_method.CallingConvention; } }
public override Type [] GetGenericArguments() { return m_method.GetGenericArguments(); }
public override MethodInfo GetGenericMethodDefinition() { return m_method; }
public override bool IsGenericMethodDefinition { get { return m_method.IsGenericMethodDefinition; } }
public override bool ContainsGenericParameters { get { return m_method.ContainsGenericParameters; } }
public override MethodInfo MakeGenericMethod(params Type[] typeArgs)
{
if (!IsGenericMethodDefinition)
throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericMethodDefinition"));
Contract.EndContractBlock();
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArgs);
}
public override bool IsGenericMethod { get { return m_method.IsGenericMethod; } }
#endregion
#region Public Abstract\Virtual Members
public override Type ReturnType { get { return m_method.ReturnType; } }
public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } }
public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } }
public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); }
#endregion
}
internal sealed class ConstructorOnTypeBuilderInstantiation : ConstructorInfo
{
#region Private Static Members
internal static ConstructorInfo GetConstructor(ConstructorInfo Constructor, TypeBuilderInstantiation type)
{
return new ConstructorOnTypeBuilderInstantiation(Constructor, type);
}
#endregion
#region Private Data Mebers
internal ConstructorInfo m_ctor;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal ConstructorOnTypeBuilderInstantiation(ConstructorInfo constructor, TypeBuilderInstantiation type)
{
Contract.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo);
m_ctor = constructor;
m_type = type;
}
#endregion
internal override Type[] GetParameterTypes()
{
return m_ctor.GetParameterTypes();
}
internal override Type GetReturnType()
{
return DeclaringType;
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return m_ctor.MemberType; } }
public override String Name { get { return m_ctor.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
public override Object[] GetCustomAttributes(bool inherit) { return m_ctor.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_ctor.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_ctor.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
ConstructorBuilder cb = m_ctor as ConstructorBuilder;
if (cb != null)
return cb.MetadataTokenInternal;
else
{
Contract.Assert(m_ctor is RuntimeConstructorInfo);
return m_ctor.MetadataToken;
}
}
}
public override Module Module { get { return m_ctor.Module; } }
public new Type GetType() { return base.GetType(); }
#endregion
#region MethodBase Members
[Pure]
public override ParameterInfo[] GetParameters() { return m_ctor.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_ctor.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle { get { return m_ctor.MethodHandle; } }
public override MethodAttributes Attributes { get { return m_ctor.Attributes; } }
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException();
}
public override CallingConventions CallingConvention { get { return m_ctor.CallingConvention; } }
public override Type[] GetGenericArguments() { return m_ctor.GetGenericArguments(); }
public override bool IsGenericMethodDefinition { get { return false; } }
public override bool ContainsGenericParameters { get { return false; } }
public override bool IsGenericMethod { get { return false; } }
#endregion
#region ConstructorInfo Members
public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new InvalidOperationException();
}
#endregion
}
internal sealed class FieldOnTypeBuilderInstantiation : FieldInfo
{
#region Private Static Members
internal static FieldInfo GetField(FieldInfo Field, TypeBuilderInstantiation type)
{
FieldInfo m = null;
// This ifdef was introduced when non-generic collections were pulled from
// silverlight. See code:Dictionary#DictionaryVersusHashtableThreadSafety
// for information about this change.
//
// There is a pre-existing race condition in this code with the side effect
// that the second thread's value clobbers the first in the hashtable. This is
// an acceptable ---- since we make no guarantees that this will return the
// same object.
//
// We're not entirely sure if this cache helps any specific scenarios, so
// long-term, one could investigate whether it's needed. In any case, this
// method isn't expected to be on any critical paths for performance.
if (type.m_hashtable.Contains(Field)) {
m = type.m_hashtable[Field] as FieldInfo;
}
else {
m = new FieldOnTypeBuilderInstantiation(Field, type);
type.m_hashtable[Field] = m;
}
return m;
}
#endregion
#region Private Data Members
private FieldInfo m_field;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal FieldOnTypeBuilderInstantiation(FieldInfo field, TypeBuilderInstantiation type)
{
Contract.Assert(field is FieldBuilder || field is RuntimeFieldInfo);
m_field = field;
m_type = type;
}
#endregion
internal FieldInfo FieldInfo { get { return m_field; } }
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } }
public override String Name { get { return m_field.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
public override Object[] GetCustomAttributes(bool inherit) { return m_field.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_field.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_field.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
FieldBuilder fb = m_field as FieldBuilder;
if (fb != null)
return fb.MetadataTokenInternal;
else
{
Contract.Assert(m_field is RuntimeFieldInfo);
return m_field.MetadataToken;
}
}
}
public override Module Module { get { return m_field.Module; } }
public new Type GetType() { return base.GetType(); }
#endregion
#region Public Abstract\Virtual Members
public override Type[] GetRequiredCustomModifiers() { return m_field.GetRequiredCustomModifiers(); }
public override Type[] GetOptionalCustomModifiers() { return m_field.GetOptionalCustomModifiers(); }
public override void SetValueDirect(TypedReference obj, Object value)
{
throw new NotImplementedException();
}
public override Object GetValueDirect(TypedReference obj)
{
throw new NotImplementedException();
}
public override RuntimeFieldHandle FieldHandle
{
get { throw new NotImplementedException(); }
}
public override Type FieldType { get { throw new NotImplementedException(); } }
public override Object GetValue(Object obj) { throw new InvalidOperationException(); }
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new InvalidOperationException(); }
public override FieldAttributes Attributes { get { return m_field.Attributes; } }
#endregion
}
}
| |
/*
Copyright (c) 2005 Poderosa Project, All Rights Reserved.
This file is a part of the Granados SSH Client Library that is subject to
the license included in the distributed package.
You may not use this file except in compliance with the license.
I implemented this algorithm with reference to following products and books though the algorithm is known publicly.
* MindTerm ( AppGate Network Security )
* Applied Cryptography ( Bruce Schneier )
$Id: Blowfish.cs,v 1.2 2005/04/20 08:58:56 okajima Exp $
*/
using System;
namespace Granados.Crypto {
public class Blowfish {
byte[] IV;
byte[] enc;
byte[] dec;
private const int BLOCK_SIZE = 8; // bytes in a data-block
protected uint[] S0;
protected uint[] S1;
protected uint[] S2;
protected uint[] S3;
protected uint[] P;
public Blowfish() {
S0 = new uint[256];
S1 = new uint[256];
S2 = new uint[256];
S3 = new uint[256];
P = new uint[18];
IV = new byte[8];
enc = new byte[8];
dec = new byte[8];
}
public void SetIV(byte[] newiv) {
Array.Copy(newiv, 0, IV, 0, IV.Length);
}
public void initializeKey(byte[] key) {
int i, j, len = key.Length;
uint temp;
Array.Copy(blowfish_pbox, 0, P, 0, 18);
Array.Copy(blowfish_sbox, 0, S0, 0, 256);
Array.Copy(blowfish_sbox, 256, S1, 0, 256);
Array.Copy(blowfish_sbox, 512, S2, 0, 256);
Array.Copy(blowfish_sbox, 768, S3, 0, 256);
for(j = 0, i = 0; i < 16 + 2; i++) {
temp = (((uint)(key[j ]) << 24) |
((uint)(key[(j + 1) % len]) << 16) |
((uint)(key[(j + 2) % len]) << 8) |
((uint)(key[(j + 3) % len])));
P[i] = P[i] ^ temp;
j = (j + 4) % len;
}
byte[] LR = new byte[8];
for(i = 0; i < 16 + 2; i += 2) {
blockEncrypt(LR, 0, LR, 0);
P[i] = CipherUtil.GetIntBE(LR, 0);
P[i + 1] = CipherUtil.GetIntBE(LR, 4);
}
for(j = 0; j < 256; j += 2) {
blockEncrypt(LR, 0, LR, 0);
S0[j] = CipherUtil.GetIntBE(LR, 0);
S0[j + 1] = CipherUtil.GetIntBE(LR, 4);
}
for(j = 0; j < 256; j += 2) {
blockEncrypt(LR, 0, LR, 0);
S1[j] = CipherUtil.GetIntBE(LR, 0);
S1[j + 1] = CipherUtil.GetIntBE(LR, 4);
}
for(j = 0; j < 256; j += 2) {
blockEncrypt(LR, 0, LR, 0);
S2[j] = CipherUtil.GetIntBE(LR, 0);
S2[j + 1] = CipherUtil.GetIntBE(LR, 4);
}
for(j = 0; j < 256; j += 2) {
blockEncrypt(LR, 0, LR, 0);
S3[j] = CipherUtil.GetIntBE(LR, 0);
S3[j + 1] = CipherUtil.GetIntBE(LR, 4);
}
}
public void blockEncrypt(byte[] input, int inOffset, byte[] output, int outOffset) {
uint L, R;
L = CipherUtil.GetIntBE(input, inOffset);
R = CipherUtil.GetIntBE(input, inOffset + 4);
L ^= P[0];
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[1]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[2]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[3]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[4]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[5]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[6]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[7]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[8]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[9]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[10]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[11]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[12]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[13]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[14]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[15]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[16]);
R ^= P[17];
CipherUtil.PutIntBE(R, output, outOffset);
CipherUtil.PutIntBE(L, output, outOffset + 4);
}
public void blockDecrypt(byte[] input, int inOffset, byte[] output, int outOffset) {
uint L, R;
L = CipherUtil.GetIntBE(input, inOffset);
R = CipherUtil.GetIntBE(input, inOffset + 4);
L ^= P[17];
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[16]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[15]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[14]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[13]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[12]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[11]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[10]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[9]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[8]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[7]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[6]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[5]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[4]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[3]);
R ^= ((((S0[(int)((L >> 24) & 0xff)] + S1[(int)((L >> 16) & 0xff)]) ^
S2[(int)((L >> 8) & 0xff)]) + S3[(int)(L & 0xff)]) ^ P[2]);
L ^= ((((S0[(int)((R >> 24) & 0xff)] + S1[(int)((R >> 16) & 0xff)]) ^
S2[(int)((R >> 8) & 0xff)]) + S3[(int)(R & 0xff)]) ^ P[1]);
R ^= P[0];
CipherUtil.PutIntBE(R, output, outOffset);
CipherUtil.PutIntBE(L, output, outOffset + 4);
}
public void encryptSSH1Style(byte[] src, int srcOff, int len, byte[] dest, int destOff) {
int end = srcOff + len;
int i, j;
for(int si = srcOff, di = destOff; si < end; si += 8, di += 8) {
for(i = 0; i < 4; i++) {
j = 3 - i;
IV[i] ^= src[si + j];
IV[i + 4] ^= src[si + 4 + j];
}
blockEncrypt(IV, 0, IV, 0);
for(i = 0; i < 4; i++) {
j = 3 - i;
dest[di + i] = IV[j];
dest[di + i + 4] = IV[4 + j];
}
}
}
public void decryptSSH1Style(byte[] src, int srcOff, int len, byte[] dest, int destOff) {
int end = srcOff + len;
int i, j;
for(int si = srcOff, di = destOff; si < end; si += 8, di += 8) {
for(i = 0; i < 4; i++) {
j = (3 - i);
enc[i] = src[si + j];
enc[i + 4] = src[si + 4 + j];
}
blockDecrypt(enc, 0, dec, 0);
for(i = 0; i < 4; i++) {
j = 3 - i;
dest[di + i] = (byte)((IV[j] ^ dec[j]) & 0xff);
IV[j] = enc[j];
dest[di + i + 4] = (byte)((IV[4 + j] ^ dec[4 + j]) & 0xff);
IV[4 + j] = enc[4 + j];
}
}
}
public void encryptCBC(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) {
int nBlocks = inputLen / BLOCK_SIZE;
for(int bc = 0; bc < nBlocks; bc++) {
CipherUtil.BlockXor(input, inputOffset, BLOCK_SIZE, IV, 0);
blockEncrypt(IV, 0, output, outputOffset);
Array.Copy(output, outputOffset, IV, 0, BLOCK_SIZE);
inputOffset += BLOCK_SIZE;
outputOffset += BLOCK_SIZE;
}
}
public void decryptCBC(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) {
byte[] tmpBlk = new byte[BLOCK_SIZE];
int nBlocks = inputLen / BLOCK_SIZE;
for(int bc = 0; bc < nBlocks; bc++) {
blockDecrypt(input, inputOffset, tmpBlk, 0);
for(int i = 0; i < BLOCK_SIZE; i++) {
tmpBlk[i] ^= IV[i];
IV[i] = input[inputOffset + i];
output[outputOffset + i] = tmpBlk[i];
}
inputOffset += BLOCK_SIZE;
outputOffset += BLOCK_SIZE;
}
}
private static readonly uint[] blowfish_pbox = new uint[] {
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
0x9216d5d9, 0x8979fb1b
};
private static readonly uint[] blowfish_sbox = new uint[] {
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
};
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\BehaviorTree\BlackboardComponent.h:41
namespace UnrealEngine
{
public partial class UBlackboardComponent : UActorComponent
{
public UBlackboardComponent(IntPtr adress)
: base(adress)
{
}
public UBlackboardComponent(UObject Parent = null, string Name = "BlackboardComponent")
: base(IntPtr.Zero)
{
NativePointer = E_NewObject_UBlackboardComponent(Parent, Name);
NativeManager.AddNativeWrapper(NativePointer, this);
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_NewObject_UBlackboardComponent(IntPtr Parent, string Name);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_CacheBrainComponent(IntPtr self, IntPtr brainComponent);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_ClearValue(IntPtr self, string keyName);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_UBlackboardComponent_GetBrainComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UBlackboardComponent_GetLocationFromEntry(IntPtr self, string keyName, IntPtr resultLocation);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_UBlackboardComponent_GetNumKeys(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UBlackboardComponent_GetRotationFromEntry(IntPtr self, string keyName, IntPtr resultRotation);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UBlackboardComponent_GetValueAsBool(IntPtr self, string keyName);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_UBlackboardComponent_GetValueAsEnum(IntPtr self, string keyName);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_UBlackboardComponent_GetValueAsFloat(IntPtr self, string keyName);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_UBlackboardComponent_GetValueAsInt(IntPtr self, string keyName);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_UBlackboardComponent_GetValueAsName(IntPtr self, string keyName);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_UBlackboardComponent_GetValueAsObject(IntPtr self, string keyName);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_UBlackboardComponent_GetValueAsRotator(IntPtr self, string keyName);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_UBlackboardComponent_GetValueAsString(IntPtr self, string keyName);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_UBlackboardComponent_GetValueAsVector(IntPtr self, string keyName);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UBlackboardComponent_HasValidAsset(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UBlackboardComponent_IsVectorValueSet(IntPtr self, string keyName);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_PauseObserverNotifications(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_PauseUpdates(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_ResumeObserverNotifications(IntPtr self, bool bSendQueuedObserverNotifications);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_ResumeUpdates(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_SetValueAsBool(IntPtr self, string keyName, bool boolValue);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_SetValueAsEnum(IntPtr self, string keyName, byte enumValue);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_SetValueAsFloat(IntPtr self, string keyName, float floatValue);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_SetValueAsInt(IntPtr self, string keyName, int intValue);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_SetValueAsName(IntPtr self, string keyName, string nameValue);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_SetValueAsObject(IntPtr self, string keyName, IntPtr objectValue);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_SetValueAsRotator(IntPtr self, string keyName, IntPtr vectorValue);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_SetValueAsString(IntPtr self, string keyName, string stringValue);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_SetValueAsVector(IntPtr self, string keyName, IntPtr vectorValue);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UBlackboardComponent_UnregisterObserversFrom(IntPtr self, IntPtr notifyOwner);
#endregion
#region ExternMethods
/// <summary>
/// caches UBrainComponent pointer to be used in communication
/// </summary>
public void CacheBrainComponent(UBrainComponent brainComponent)
=> E_UBlackboardComponent_CacheBrainComponent(this, brainComponent);
public void ClearValue(string keyName)
=> E_UBlackboardComponent_ClearValue(this, keyName);
/// <summary>
/// </summary>
/// <return>associated</return>
public UBrainComponent GetBrainComponent()
=> E_UBlackboardComponent_GetBrainComponent(this);
/// <summary>
/// return false if call failed (most probably no such entry in BB)
/// </summary>
public bool GetLocationFromEntry(string keyName, FVector resultLocation)
=> E_UBlackboardComponent_GetLocationFromEntry(this, keyName, resultLocation);
/// <summary>
/// </summary>
/// <return>number</return>
public int GetNumKeys()
=> E_UBlackboardComponent_GetNumKeys(this);
/// <summary>
/// return false if call failed (most probably no such entry in BB)
/// </summary>
public bool GetRotationFromEntry(string keyName, FRotator resultRotation)
=> E_UBlackboardComponent_GetRotationFromEntry(this, keyName, resultRotation);
public bool GetValueAsBool(string keyName)
=> E_UBlackboardComponent_GetValueAsBool(this, keyName);
public byte GetValueAsEnum(string keyName)
=> E_UBlackboardComponent_GetValueAsEnum(this, keyName);
public float GetValueAsFloat(string keyName)
=> E_UBlackboardComponent_GetValueAsFloat(this, keyName);
public int GetValueAsInt(string keyName)
=> E_UBlackboardComponent_GetValueAsInt(this, keyName);
public string GetValueAsName(string keyName)
=> E_UBlackboardComponent_GetValueAsName(this, keyName);
public UObject GetValueAsObject(string keyName)
=> E_UBlackboardComponent_GetValueAsObject(this, keyName);
public FRotator GetValueAsRotator(string keyName)
=> E_UBlackboardComponent_GetValueAsRotator(this, keyName);
public string GetValueAsString(string keyName)
=> E_UBlackboardComponent_GetValueAsString(this, keyName);
public FVector GetValueAsVector(string keyName)
=> E_UBlackboardComponent_GetValueAsVector(this, keyName);
/// <summary>
/// </summary>
/// <return>true</return>
public bool HasValidAsset()
=> E_UBlackboardComponent_HasValidAsset(this);
public bool IsVectorValueSet(string keyName)
=> E_UBlackboardComponent_IsVectorValueSet(this, keyName);
/// <summary>
/// pause observer change notifications, any new ones will be added to a queue
/// </summary>
public void PauseObserverNotifications()
=> E_UBlackboardComponent_PauseObserverNotifications(this);
/// <summary>
/// pause change notifies and add them to queue
/// </summary>
public void PauseUpdates()
=> E_UBlackboardComponent_PauseUpdates(this);
/// <summary>
/// resume observer change notifications and, optionally, process the queued observation list
/// </summary>
public void ResumeObserverNotifications(bool bSendQueuedObserverNotifications)
=> E_UBlackboardComponent_ResumeObserverNotifications(this, bSendQueuedObserverNotifications);
/// <summary>
/// resume change notifies and process queued list
/// </summary>
public void ResumeUpdates()
=> E_UBlackboardComponent_ResumeUpdates(this);
public void SetValueAsBool(string keyName, bool boolValue)
=> E_UBlackboardComponent_SetValueAsBool(this, keyName, boolValue);
public void SetValueAsEnum(string keyName, byte enumValue)
=> E_UBlackboardComponent_SetValueAsEnum(this, keyName, enumValue);
public void SetValueAsFloat(string keyName, float floatValue)
=> E_UBlackboardComponent_SetValueAsFloat(this, keyName, floatValue);
public void SetValueAsInt(string keyName, int intValue)
=> E_UBlackboardComponent_SetValueAsInt(this, keyName, intValue);
public void SetValueAsName(string keyName, string nameValue)
=> E_UBlackboardComponent_SetValueAsName(this, keyName, nameValue);
public void SetValueAsObject(string keyName, UObject objectValue)
=> E_UBlackboardComponent_SetValueAsObject(this, keyName, objectValue);
public void SetValueAsRotator(string keyName, FRotator vectorValue)
=> E_UBlackboardComponent_SetValueAsRotator(this, keyName, vectorValue);
public void SetValueAsString(string keyName, string stringValue)
=> E_UBlackboardComponent_SetValueAsString(this, keyName, stringValue);
public void SetValueAsVector(string keyName, FVector vectorValue)
=> E_UBlackboardComponent_SetValueAsVector(this, keyName, vectorValue);
/// <summary>
/// unregister all observers associated with given owner
/// </summary>
public void UnregisterObserversFrom(UObject notifyOwner)
=> E_UBlackboardComponent_UnregisterObserversFrom(this, notifyOwner);
#endregion
public static implicit operator IntPtr(UBlackboardComponent self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator UBlackboardComponent(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<UBlackboardComponent>(PtrDesc);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
internal abstract class AbstractChangeSignatureService : ILanguageService
{
protected SyntaxAnnotation changeSignatureFormattingAnnotation = new SyntaxAnnotation("ChangeSignatureFormatting");
/// <summary>
/// Determines the symbol on which we are invoking ReorderParameters
/// </summary>
public abstract Task<ISymbol> GetInvocationSymbolAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken);
/// <summary>
/// Given a SyntaxNode for which we want to reorder parameters/arguments, find the
/// SyntaxNode of a kind where we know how to reorder parameters/arguments.
/// </summary>
public abstract SyntaxNode FindNodeToUpdate(Document document, SyntaxNode node);
public abstract Task<IEnumerable<ISymbol>> DetermineCascadedSymbolsFromDelegateInvoke(IMethodSymbol symbol, Document document, CancellationToken cancellationToken);
public abstract SyntaxNode ChangeSignature(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken);
protected abstract IEnumerable<IFormattingRule> GetFormattingRules(Document document);
public async Task<IEnumerable<ChangeSignatureCodeAction>> GetChangeSignatureCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var context = await GetContextAsync(document, span.Start, restrictToDeclarations: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return context.CanChangeSignature
? SpecializedCollections.SingletonEnumerable(new ChangeSignatureCodeAction(this, context))
: SpecializedCollections.EmptyEnumerable<ChangeSignatureCodeAction>();
}
internal ChangeSignatureResult ChangeSignature(Document document, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken)
{
var context = GetContextAsync(document, position, restrictToDeclarations: false, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
if (context.CanChangeSignature)
{
return ChangeSignatureWithContext(context, cancellationToken);
}
else
{
switch (context.CannotChangeSignatureReason)
{
case CannotChangeSignatureReason.DefinedInMetadata:
errorHandler(FeaturesResources.The_member_is_defined_in_metadata, NotificationSeverity.Error);
break;
case CannotChangeSignatureReason.IncorrectKind:
errorHandler(FeaturesResources.You_can_only_change_the_signature_of_a_constructor_indexer_method_or_delegate, NotificationSeverity.Error);
break;
case CannotChangeSignatureReason.InsufficientParameters:
errorHandler(FeaturesResources.This_signature_does_not_contain_parameters_that_can_be_changed, NotificationSeverity.Error);
break;
}
return new ChangeSignatureResult(succeeded: false);
}
}
private async Task<ChangeSignatureAnalyzedContext> GetContextAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var symbol = await GetInvocationSymbolAsync(document, position, restrictToDeclarations, cancellationToken).ConfigureAwait(false);
// Cross-lang symbols will show as metadata, so map it to source if possible.
symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false) ?? symbol;
if (symbol == null)
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.IncorrectKind);
}
if (symbol is IMethodSymbol)
{
var method = symbol as IMethodSymbol;
var containingType = method.ContainingType;
if (method.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
containingType != null &&
containingType.IsDelegateType() &&
containingType.DelegateInvokeMethod != null)
{
symbol = containingType.DelegateInvokeMethod;
}
}
if (symbol is IEventSymbol)
{
symbol = (symbol as IEventSymbol).Type;
}
if (symbol is INamedTypeSymbol)
{
var typeSymbol = symbol as INamedTypeSymbol;
if (typeSymbol.IsDelegateType() && typeSymbol.DelegateInvokeMethod != null)
{
symbol = typeSymbol.DelegateInvokeMethod;
}
}
if (symbol.Locations.Any(loc => loc.IsInMetadata))
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.DefinedInMetadata);
}
if (!symbol.MatchesKind(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType))
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.IncorrectKind);
}
var parameterConfiguration = ParameterConfiguration.Create(symbol.GetParameters().ToList(), symbol is IMethodSymbol && (symbol as IMethodSymbol).IsExtensionMethod);
if (!parameterConfiguration.IsChangeable())
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.InsufficientParameters);
}
return new ChangeSignatureAnalyzedContext(document.Project.Solution, symbol, parameterConfiguration);
}
private ChangeSignatureResult ChangeSignatureWithContext(ChangeSignatureAnalyzedContext context, CancellationToken cancellationToken)
{
var options = GetChangeSignatureOptions(context, CancellationToken.None);
if (options.IsCancelled)
{
return new ChangeSignatureResult(succeeded: false);
}
return ChangeSignatureWithContext(context, options, cancellationToken);
}
internal ChangeSignatureResult ChangeSignatureWithContext(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken)
{
Solution updatedSolution;
var succeeded = TryCreateUpdatedSolution(context, options, cancellationToken, out updatedSolution);
return new ChangeSignatureResult(succeeded, updatedSolution, context.Symbol.ToDisplayString(), context.Symbol.GetGlyph(), options.PreviewChanges);
}
internal ChangeSignatureOptionsResult GetChangeSignatureOptions(ChangeSignatureAnalyzedContext context, CancellationToken cancellationToken)
{
var notificationService = context.Solution.Workspace.Services.GetService<INotificationService>();
var changeSignatureOptionsService = context.Solution.Workspace.Services.GetService<IChangeSignatureOptionsService>();
var isExtensionMethod = context.Symbol is IMethodSymbol && (context.Symbol as IMethodSymbol).IsExtensionMethod;
return changeSignatureOptionsService.GetChangeSignatureOptions(context.Symbol, context.ParameterConfiguration, notificationService);
}
private static Task<IEnumerable<ReferencedSymbol>> FindChangeSignatureReferencesAsync(
ISymbol symbol,
Solution solution,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.FindReference_ChangeSignature, cancellationToken))
{
IImmutableSet<Document> documents = null;
var engine = new FindReferencesSearchEngine(
solution,
documents,
ReferenceFinders.DefaultReferenceFinders.Add(DelegateInvokeMethodReferenceFinder.DelegateInvokeMethod),
FindReferencesProgress.Instance,
cancellationToken);
return engine.FindReferencesAsync(symbol);
}
}
private bool TryCreateUpdatedSolution(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken, out Solution updatedSolution)
{
updatedSolution = context.Solution;
var declaredSymbol = context.Symbol;
var nodesToUpdate = new Dictionary<DocumentId, List<SyntaxNode>>();
var definitionToUse = new Dictionary<SyntaxNode, ISymbol>();
bool hasLocationsInMetadata = false;
var symbols = FindChangeSignatureReferencesAsync(declaredSymbol, context.Solution, cancellationToken).WaitAndGetResult(cancellationToken);
foreach (var symbol in symbols)
{
if (symbol.Definition.Kind == SymbolKind.Method &&
((symbol.Definition as IMethodSymbol).MethodKind == MethodKind.PropertyGet || (symbol.Definition as IMethodSymbol).MethodKind == MethodKind.PropertySet))
{
continue;
}
if (symbol.Definition.Kind == SymbolKind.NamedType)
{
continue;
}
if (symbol.Definition.Locations.Any(loc => loc.IsInMetadata))
{
hasLocationsInMetadata = true;
continue;
}
var symbolWithSyntacticParameters = symbol.Definition;
var symbolWithSemanticParameters = symbol.Definition;
var includeDefinitionLocations = true;
if (symbol.Definition.Kind == SymbolKind.Field)
{
includeDefinitionLocations = false;
}
if (symbolWithSyntacticParameters.Kind == SymbolKind.Event)
{
var eventSymbol = symbolWithSyntacticParameters as IEventSymbol;
var type = eventSymbol.Type as INamedTypeSymbol;
if (type != null && type.DelegateInvokeMethod != null)
{
symbolWithSemanticParameters = type.DelegateInvokeMethod;
}
else
{
continue;
}
}
if (symbolWithSyntacticParameters.Kind == SymbolKind.Method)
{
var methodSymbol = symbolWithSyntacticParameters as IMethodSymbol;
if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
{
symbolWithSyntacticParameters = methodSymbol.ContainingType;
}
if (methodSymbol.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
methodSymbol.ContainingType != null &&
methodSymbol.ContainingType.IsDelegateType())
{
includeDefinitionLocations = false;
}
}
// Find and annotate all the relevant definitions
if (includeDefinitionLocations)
{
foreach (var def in symbolWithSyntacticParameters.Locations)
{
DocumentId documentId;
SyntaxNode nodeToUpdate;
if (!TryGetNodeWithEditableSignatureOrAttributes(def, updatedSolution, out nodeToUpdate, out documentId))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId))
{
nodesToUpdate.Add(documentId, new List<SyntaxNode>());
}
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId, nodeToUpdate, definitionToUse, symbolWithSemanticParameters);
}
}
// Find and annotate all the relevant references
foreach (var location in symbol.Locations)
{
if (location.Location.IsInMetadata)
{
hasLocationsInMetadata = true;
continue;
}
DocumentId documentId2;
SyntaxNode nodeToUpdate2;
if (!TryGetNodeWithEditableSignatureOrAttributes(location.Location, updatedSolution, out nodeToUpdate2, out documentId2))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId2))
{
nodesToUpdate.Add(documentId2, new List<SyntaxNode>());
}
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId2, nodeToUpdate2, definitionToUse, symbolWithSemanticParameters);
}
}
if (hasLocationsInMetadata)
{
var notificationService = context.Solution.Workspace.Services.GetService<INotificationService>();
if (!notificationService.ConfirmMessageBox(FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue, severity: NotificationSeverity.Warning))
{
return false;
}
}
// Construct all the relevant syntax trees from the base solution
var updatedRoots = new Dictionary<DocumentId, SyntaxNode>();
foreach (var docId in nodesToUpdate.Keys)
{
var doc = updatedSolution.GetDocument(docId);
var updater = doc.Project.LanguageServices.GetService<AbstractChangeSignatureService>();
var root = doc.GetSyntaxRootSynchronously(CancellationToken.None);
var nodes = nodesToUpdate[docId];
var newRoot = root.ReplaceNodes(nodes, (originalNode, potentiallyUpdatedNode) =>
{
return updater.ChangeSignature(doc, definitionToUse[originalNode], potentiallyUpdatedNode, originalNode, CreateCompensatingSignatureChange(definitionToUse[originalNode], options.UpdatedSignature), cancellationToken);
});
var annotatedNodes = newRoot.GetAnnotatedNodes<SyntaxNode>(syntaxAnnotation: changeSignatureFormattingAnnotation);
var formattedRoot = Formatter.FormatAsync(
newRoot,
changeSignatureFormattingAnnotation,
doc.Project.Solution.Workspace,
options: null,
rules: GetFormattingRules(doc),
cancellationToken: CancellationToken.None).WaitAndGetResult(CancellationToken.None);
updatedRoots[docId] = formattedRoot;
}
// Update the documents using the updated syntax trees
foreach (var docId in nodesToUpdate.Keys)
{
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(docId, updatedRoots[docId]);
}
return true;
}
private void AddUpdatableNodeToDictionaries(Dictionary<DocumentId, List<SyntaxNode>> nodesToUpdate, DocumentId documentId, SyntaxNode nodeToUpdate, Dictionary<SyntaxNode, ISymbol> definitionToUse, ISymbol symbolWithSemanticParameters)
{
nodesToUpdate[documentId].Add(nodeToUpdate);
ISymbol sym;
if (definitionToUse.TryGetValue(nodeToUpdate, out sym) && sym != symbolWithSemanticParameters)
{
Debug.Assert(false, "Change Signature: Attempted to modify node twice with different semantic parameters.");
}
definitionToUse[nodeToUpdate] = symbolWithSemanticParameters;
}
private bool TryGetNodeWithEditableSignatureOrAttributes(Location location, Solution solution, out SyntaxNode nodeToUpdate, out DocumentId documentId)
{
var tree = location.SourceTree;
documentId = solution.GetDocumentId(tree);
var document = solution.GetDocument(documentId);
var root = tree.GetRoot();
SyntaxNode node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
var updater = document.Project.LanguageServices.GetService<AbstractChangeSignatureService>();
nodeToUpdate = updater.FindNodeToUpdate(document, node);
return nodeToUpdate != null;
}
protected static List<IUnifiedArgumentSyntax> PermuteArguments(
Document document,
ISymbol declarationSymbol,
List<IUnifiedArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
// 1. Determine which parameters are permutable
var declarationParameters = declarationSymbol.GetParameters().ToList();
var declarationParametersToPermute = GetParametersToPermute(arguments, declarationParameters, isReducedExtensionMethod);
var argumentsToPermute = arguments.Take(declarationParametersToPermute.Count).ToList();
// 2. Create an argument to parameter map, and a parameter to index map for the sort.
var argumentToParameterMap = new Dictionary<IUnifiedArgumentSyntax, IParameterSymbol>();
var parameterToIndexMap = new Dictionary<IParameterSymbol, int>();
for (int i = 0; i < declarationParametersToPermute.Count; i++)
{
var decl = declarationParametersToPermute[i];
var arg = argumentsToPermute[i];
argumentToParameterMap[arg] = decl;
var originalIndex = declarationParameters.IndexOf(decl);
var updatedIndex = updatedSignature.GetUpdatedIndex(originalIndex);
// If there's no value, then we may be handling a method with more parameters than the original symbol (like BeginInvoke).
parameterToIndexMap[decl] = updatedIndex.HasValue ? updatedIndex.Value : -1;
}
// 3. Sort the arguments that need to be reordered
argumentsToPermute.Sort((a1, a2) => { return parameterToIndexMap[argumentToParameterMap[a1]].CompareTo(parameterToIndexMap[argumentToParameterMap[a2]]); });
// 4. Add names to arguments where necessary.
var newArguments = new List<IUnifiedArgumentSyntax>();
int expectedIndex = 0 + (isReducedExtensionMethod ? 1 : 0);
bool seenNamedArgument = false;
foreach (var argument in argumentsToPermute)
{
var param = argumentToParameterMap[argument];
var actualIndex = updatedSignature.GetUpdatedIndex(declarationParameters.IndexOf(param));
if (!actualIndex.HasValue)
{
continue;
}
if ((seenNamedArgument || actualIndex != expectedIndex) && !argument.IsNamed)
{
newArguments.Add(argument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(argument);
}
seenNamedArgument |= argument.IsNamed;
expectedIndex++;
}
// 5. Add the remaining arguments. These will already have names or be params arguments, but may have been removed.
bool removedParams = updatedSignature.OriginalConfiguration.ParamsParameter != null && updatedSignature.UpdatedConfiguration.ParamsParameter == null;
for (int i = declarationParametersToPermute.Count; i < arguments.Count; i++)
{
if (!arguments[i].IsNamed && removedParams && i >= updatedSignature.UpdatedConfiguration.ToListOfParameters().Count)
{
break;
}
if (!arguments[i].IsNamed || updatedSignature.UpdatedConfiguration.ToListOfParameters().Any(p => p.Name == arguments[i].GetName()))
{
newArguments.Add(arguments[i]);
}
}
return newArguments;
}
private static SignatureChange CreateCompensatingSignatureChange(ISymbol declarationSymbol, SignatureChange updatedSignature)
{
if (declarationSymbol.GetParameters().Length > updatedSignature.OriginalConfiguration.ToListOfParameters().Count)
{
var origStuff = updatedSignature.OriginalConfiguration.ToListOfParameters();
var newStuff = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var realStuff = declarationSymbol.GetParameters();
var bonusParameters = realStuff.Skip(origStuff.Count);
origStuff.AddRange(bonusParameters);
newStuff.AddRange(bonusParameters);
var newOrigParams = ParameterConfiguration.Create(origStuff, updatedSignature.OriginalConfiguration.ThisParameter != null);
var newUpdatedParams = ParameterConfiguration.Create(newStuff, updatedSignature.OriginalConfiguration.ThisParameter != null);
updatedSignature = new SignatureChange(newOrigParams, newUpdatedParams);
}
return updatedSignature;
}
private static List<IParameterSymbol> GetParametersToPermute(
List<IUnifiedArgumentSyntax> arguments,
List<IParameterSymbol> originalParameters,
bool isReducedExtensionMethod)
{
int position = -1 + (isReducedExtensionMethod ? 1 : 0);
var parametersToPermute = new List<IParameterSymbol>();
foreach (var argument in arguments)
{
if (argument.IsNamed)
{
var name = argument.GetName();
// TODO: file bug for var match = originalParameters.FirstOrDefault(p => p.Name == <ISymbol here>);
var match = originalParameters.FirstOrDefault(p => p.Name == name);
if (match == null || originalParameters.IndexOf(match) <= position)
{
break;
}
else
{
position = originalParameters.IndexOf(match);
parametersToPermute.Add(match);
}
}
else
{
position++;
if (position >= originalParameters.Count)
{
break;
}
parametersToPermute.Add(originalParameters[position]);
}
}
return parametersToPermute;
}
}
}
| |
/*
* Copyright (c) Contributors
* 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 OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Mono.Addins;
using System;
using System.Reflection;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Scripting;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.OptionalModules.Scripting.JsonStore
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "JsonStoreScriptModule")]
public class JsonStoreScriptModule : INonSharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IConfig m_config = null;
private bool m_enabled = false;
private Scene m_scene = null;
private IScriptModuleComms m_comms;
private IJsonStoreModule m_store;
private Dictionary<UUID,HashSet<UUID>> m_scriptStores = new Dictionary<UUID,HashSet<UUID>>();
#region Region Module interface
// -----------------------------------------------------------------
/// <summary>
/// Name of this shared module is it's class name
/// </summary>
// -----------------------------------------------------------------
public string Name
{
get { return this.GetType().Name; }
}
// -----------------------------------------------------------------
/// <summary>
/// Initialise this shared module
/// </summary>
/// <param name="scene">this region is getting initialised</param>
/// <param name="source">nini config, we are not using this</param>
// -----------------------------------------------------------------
public void Initialise(IConfigSource config)
{
try
{
if ((m_config = config.Configs["JsonStore"]) == null)
{
// There is no configuration, the module is disabled
// m_log.InfoFormat("[JsonStoreScripts] no configuration info");
return;
}
m_enabled = m_config.GetBoolean("Enabled", m_enabled);
}
catch (Exception e)
{
m_log.ErrorFormat("[JsonStoreScripts]: initialization error: {0}", e.Message);
return;
}
if (m_enabled)
m_log.DebugFormat("[JsonStoreScripts]: module is enabled");
}
// -----------------------------------------------------------------
/// <summary>
/// everything is loaded, perform post load configuration
/// </summary>
// -----------------------------------------------------------------
public void PostInitialise()
{
}
// -----------------------------------------------------------------
/// <summary>
/// Nothing to do on close
/// </summary>
// -----------------------------------------------------------------
public void Close()
{
}
// -----------------------------------------------------------------
/// <summary>
/// </summary>
// -----------------------------------------------------------------
public void AddRegion(Scene scene)
{
scene.EventManager.OnScriptReset += HandleScriptReset;
scene.EventManager.OnRemoveScript += HandleScriptReset;
}
// -----------------------------------------------------------------
/// <summary>
/// </summary>
// -----------------------------------------------------------------
public void RemoveRegion(Scene scene)
{
scene.EventManager.OnScriptReset -= HandleScriptReset;
scene.EventManager.OnRemoveScript -= HandleScriptReset;
// need to remove all references to the scene in the subscription
// list to enable full garbage collection of the scene object
}
// -----------------------------------------------------------------
/// <summary>
/// </summary>
// -----------------------------------------------------------------
private void HandleScriptReset(uint localID, UUID itemID)
{
HashSet<UUID> stores;
lock (m_scriptStores)
{
if (! m_scriptStores.TryGetValue(itemID, out stores))
return;
m_scriptStores.Remove(itemID);
}
foreach (UUID id in stores)
m_store.DestroyStore(id);
}
// -----------------------------------------------------------------
/// <summary>
/// Called when all modules have been added for a region. This is
/// where we hook up events
/// </summary>
// -----------------------------------------------------------------
public void RegionLoaded(Scene scene)
{
if (m_enabled)
{
m_scene = scene;
m_comms = m_scene.RequestModuleInterface<IScriptModuleComms>();
if (m_comms == null)
{
m_log.ErrorFormat("[JsonStoreScripts]: ScriptModuleComms interface not defined");
m_enabled = false;
return;
}
m_store = m_scene.RequestModuleInterface<IJsonStoreModule>();
if (m_store == null)
{
m_log.ErrorFormat("[JsonStoreScripts]: JsonModule interface not defined");
m_enabled = false;
return;
}
try
{
m_comms.RegisterScriptInvocations(this);
m_comms.RegisterConstants(this);
}
catch (Exception e)
{
// See http://opensimulator.org/mantis/view.php?id=5971 for more information
m_log.WarnFormat("[JsonStoreScripts]: script method registration failed; {0}", e.Message);
m_enabled = false;
}
}
}
/// -----------------------------------------------------------------
/// <summary>
/// </summary>
// -----------------------------------------------------------------
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
#region ScriptConstantsInterface
[ScriptConstant]
public static readonly int JSON_NODETYPE_UNDEF = (int)JsonStoreNodeType.Undefined;
[ScriptConstant]
public static readonly int JSON_NODETYPE_OBJECT = (int)JsonStoreNodeType.Object;
[ScriptConstant]
public static readonly int JSON_NODETYPE_ARRAY = (int)JsonStoreNodeType.Array;
[ScriptConstant]
public static readonly int JSON_NODETYPE_VALUE = (int)JsonStoreNodeType.Value;
[ScriptConstant]
public static readonly int JSON_VALUETYPE_UNDEF = (int)JsonStoreValueType.Undefined;
[ScriptConstant]
public static readonly int JSON_VALUETYPE_BOOLEAN = (int)JsonStoreValueType.Boolean;
[ScriptConstant]
public static readonly int JSON_VALUETYPE_INTEGER = (int)JsonStoreValueType.Integer;
[ScriptConstant]
public static readonly int JSON_VALUETYPE_FLOAT = (int)JsonStoreValueType.Float;
[ScriptConstant]
public static readonly int JSON_VALUETYPE_STRING = (int)JsonStoreValueType.String;
#endregion
#region ScriptInvocationInteface
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonAttachObjectStore(UUID hostID, UUID scriptID)
{
UUID uuid = UUID.Zero;
if (! m_store.AttachObjectStore(hostID))
GenerateRuntimeError("Failed to create Json store");
return hostID;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonCreateStore(UUID hostID, UUID scriptID, string value)
{
UUID uuid = UUID.Zero;
if (! m_store.CreateStore(value, ref uuid))
GenerateRuntimeError("Failed to create Json store");
lock (m_scriptStores)
{
if (! m_scriptStores.ContainsKey(scriptID))
m_scriptStores[scriptID] = new HashSet<UUID>();
m_scriptStores[scriptID].Add(uuid);
}
return uuid;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonDestroyStore(UUID hostID, UUID scriptID, UUID storeID)
{
lock(m_scriptStores)
{
if (m_scriptStores.ContainsKey(scriptID))
m_scriptStores[scriptID].Remove(storeID);
}
return m_store.DestroyStore(storeID) ? 1 : 0;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonTestStore(UUID hostID, UUID scriptID, UUID storeID)
{
return m_store.TestStore(storeID) ? 1 : 0;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonRezAtRoot(UUID hostID, UUID scriptID, string item, Vector3 pos, Vector3 vel, Quaternion rot, string param)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonRezObject(hostID, scriptID, reqID, item, pos, vel, rot, param), null, "JsonStoreScriptModule.DoJsonRezObject");
return reqID;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonReadNotecard(UUID hostID, UUID scriptID, UUID storeID, string path, string notecardIdentifier)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonReadNotecard(reqID, hostID, scriptID, storeID, path, notecardIdentifier), null, "JsonStoreScriptModule.JsonReadNotecard");
return reqID;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonWriteNotecard(UUID hostID, UUID scriptID, UUID storeID, string path, string name)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonWriteNotecard(reqID,hostID,scriptID,storeID,path,name), null, "JsonStoreScriptModule.DoJsonWriteNotecard");
return reqID;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public string JsonList2Path(UUID hostID, UUID scriptID, object[] pathlist)
{
string ipath = ConvertList2Path(pathlist);
string opath;
if (JsonStore.CanonicalPathExpression(ipath,out opath))
return opath;
// This won't parse if passed to the other routines as opposed to
// returning an empty string which is a valid path and would overwrite
// the entire store
return "**INVALID**";
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonGetNodeType(UUID hostID, UUID scriptID, UUID storeID, string path)
{
return (int)m_store.GetNodeType(storeID,path);
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonGetValueType(UUID hostID, UUID scriptID, UUID storeID, string path)
{
return (int)m_store.GetValueType(storeID,path);
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonSetValue(UUID hostID, UUID scriptID, UUID storeID, string path, string value)
{
return m_store.SetValue(storeID,path,value,false) ? 1 : 0;
}
[ScriptInvocation]
public int JsonSetJson(UUID hostID, UUID scriptID, UUID storeID, string path, string value)
{
return m_store.SetValue(storeID,path,value,true) ? 1 : 0;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonRemoveValue(UUID hostID, UUID scriptID, UUID storeID, string path)
{
return m_store.RemoveValue(storeID,path) ? 1 : 0;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public int JsonGetArrayLength(UUID hostID, UUID scriptID, UUID storeID, string path)
{
return m_store.GetArrayLength(storeID,path);
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public string JsonGetValue(UUID hostID, UUID scriptID, UUID storeID, string path)
{
string value = String.Empty;
m_store.GetValue(storeID,path,false,out value);
return value;
}
[ScriptInvocation]
public string JsonGetJson(UUID hostID, UUID scriptID, UUID storeID, string path)
{
string value = String.Empty;
m_store.GetValue(storeID,path,true, out value);
return value;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonTakeValue(UUID hostID, UUID scriptID, UUID storeID, string path)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonTakeValue(scriptID,reqID,storeID,path,false), null, "JsonStoreScriptModule.DoJsonTakeValue");
return reqID;
}
[ScriptInvocation]
public UUID JsonTakeValueJson(UUID hostID, UUID scriptID, UUID storeID, string path)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonTakeValue(scriptID,reqID,storeID,path,true), null, "JsonStoreScriptModule.DoJsonTakeValueJson");
return reqID;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
[ScriptInvocation]
public UUID JsonReadValue(UUID hostID, UUID scriptID, UUID storeID, string path)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonReadValue(scriptID,reqID,storeID,path,false), null, "JsonStoreScriptModule.DoJsonReadValue");
return reqID;
}
[ScriptInvocation]
public UUID JsonReadValueJson(UUID hostID, UUID scriptID, UUID storeID, string path)
{
UUID reqID = UUID.Random();
Util.FireAndForget(
o => DoJsonReadValue(scriptID,reqID,storeID,path,true), null, "JsonStoreScriptModule.DoJsonReadValueJson");
return reqID;
}
#endregion
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
protected void GenerateRuntimeError(string msg)
{
m_log.InfoFormat("[JsonStore] runtime error: {0}",msg);
throw new Exception("JsonStore Runtime Error: " + msg);
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
protected void DispatchValue(UUID scriptID, UUID reqID, string value)
{
m_comms.DispatchReply(scriptID,1,value,reqID.ToString());
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
private void DoJsonTakeValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson)
{
try
{
m_store.TakeValue(storeID,path,useJson,delegate(string value) { DispatchValue(scriptID,reqID,value); });
return;
}
catch (Exception e)
{
m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}",e.ToString());
}
DispatchValue(scriptID,reqID,String.Empty);
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
private void DoJsonReadValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson)
{
try
{
m_store.ReadValue(storeID,path,useJson,delegate(string value) { DispatchValue(scriptID,reqID,value); });
return;
}
catch (Exception e)
{
m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}",e.ToString());
}
DispatchValue(scriptID,reqID,String.Empty);
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
private void DoJsonReadNotecard(
UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string notecardIdentifier)
{
UUID assetID;
if (!UUID.TryParse(notecardIdentifier, out assetID))
{
SceneObjectPart part = m_scene.GetSceneObjectPart(hostID);
assetID = ScriptUtils.GetAssetIdFromItemName(part, notecardIdentifier, (int)AssetType.Notecard);
}
AssetBase a = m_scene.AssetService.Get(assetID.ToString());
if (a == null)
GenerateRuntimeError(String.Format("Unable to find notecard asset {0}", assetID));
if (a.Type != (sbyte)AssetType.Notecard)
GenerateRuntimeError(String.Format("Invalid notecard asset {0}", assetID));
m_log.DebugFormat("[JsonStoreScripts]: read notecard in context {0}",storeID);
try
{
string jsondata = SLUtil.ParseNotecardToString(a.Data);
int result = m_store.SetValue(storeID, path, jsondata,true) ? 1 : 0;
m_comms.DispatchReply(scriptID, result, "", reqID.ToString());
return;
}
catch(SLUtil.NotANotecardFormatException e)
{
m_log.WarnFormat("[JsonStoreScripts]: Notecard parsing failed; assetId {0} at line number {1}", assetID.ToString(), e.lineNumber);
}
catch (Exception e)
{
m_log.WarnFormat("[JsonStoreScripts]: Json parsing failed; {0}", e.Message);
}
GenerateRuntimeError(String.Format("Json parsing failed for {0}", assetID));
m_comms.DispatchReply(scriptID, 0, "", reqID.ToString());
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
private void DoJsonWriteNotecard(UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string name)
{
string data;
if (! m_store.GetValue(storeID,path,true, out data))
{
m_comms.DispatchReply(scriptID,0,UUID.Zero.ToString(),reqID.ToString());
return;
}
SceneObjectPart host = m_scene.GetSceneObjectPart(hostID);
// Create new asset
UUID assetID = UUID.Random();
AssetBase asset = new AssetBase(assetID, name, (sbyte)AssetType.Notecard, host.OwnerID.ToString());
asset.Description = "Json store";
int textLength = data.Length;
data = "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length "
+ textLength.ToString() + "\n" + data + "}\n";
asset.Data = Util.UTF8.GetBytes(data);
m_scene.AssetService.Store(asset);
// Create Task Entry
TaskInventoryItem taskItem = new TaskInventoryItem();
taskItem.ResetIDs(host.UUID);
taskItem.ParentID = host.UUID;
taskItem.CreationDate = (uint)Util.UnixTimeSinceEpoch();
taskItem.Name = asset.Name;
taskItem.Description = asset.Description;
taskItem.Type = (int)AssetType.Notecard;
taskItem.InvType = (int)InventoryType.Notecard;
taskItem.OwnerID = host.OwnerID;
taskItem.CreatorID = host.OwnerID;
taskItem.BasePermissions = (uint)PermissionMask.All;
taskItem.CurrentPermissions = (uint)PermissionMask.All;
taskItem.EveryonePermissions = 0;
taskItem.NextPermissions = (uint)PermissionMask.All;
taskItem.GroupID = host.GroupID;
taskItem.GroupPermissions = 0;
taskItem.Flags = 0;
taskItem.PermsGranter = UUID.Zero;
taskItem.PermsMask = 0;
taskItem.AssetID = asset.FullID;
host.Inventory.AddInventoryItem(taskItem, false);
host.ParentGroup.AggregatePerms();
m_comms.DispatchReply(scriptID,1,assetID.ToString(),reqID.ToString());
}
// -----------------------------------------------------------------
/// <summary>
/// Convert a list of values that are path components to a single string path
/// </summary>
// -----------------------------------------------------------------
protected static Regex m_ArrayPattern = new Regex("^([0-9]+|\\+)$");
private string ConvertList2Path(object[] pathlist)
{
string path = "";
for (int i = 0; i < pathlist.Length; i++)
{
string token = "";
if (pathlist[i] is string)
{
token = pathlist[i].ToString();
// Check to see if this is a bare number which would not be a valid
// identifier otherwise
if (m_ArrayPattern.IsMatch(token))
token = '[' + token + ']';
}
else if (pathlist[i] is int)
{
token = "[" + pathlist[i].ToString() + "]";
}
else
{
token = "." + pathlist[i].ToString() + ".";
}
path += token + ".";
}
return path;
}
// -----------------------------------------------------------------
/// <summary>
///
/// </summary>
// -----------------------------------------------------------------
private void DoJsonRezObject(UUID hostID, UUID scriptID, UUID reqID, string name, Vector3 pos, Vector3 vel, Quaternion rot, string param)
{
if (Double.IsNaN(rot.X) || Double.IsNaN(rot.Y) || Double.IsNaN(rot.Z) || Double.IsNaN(rot.W))
{
GenerateRuntimeError("Invalid rez rotation");
return;
}
SceneObjectGroup host = m_scene.GetSceneObjectGroup(hostID);
if (host == null)
{
GenerateRuntimeError(String.Format("Unable to find rezzing host '{0}'",hostID));
return;
}
// hpos = host.RootPart.GetWorldPosition()
// float dist = (float)llVecDist(hpos, pos);
// if (dist > m_ScriptDistanceFactor * 10.0f)
// return;
TaskInventoryItem item = host.RootPart.Inventory.GetInventoryItem(name);
if (item == null)
{
GenerateRuntimeError(String.Format("Unable to find object to rez '{0}'",name));
return;
}
if (item.InvType != (int)InventoryType.Object)
{
GenerateRuntimeError("Can't create requested object; object is missing from database");
return;
}
List<SceneObjectGroup> objlist;
List<Vector3> veclist;
Vector3 bbox = new Vector3();
float offsetHeight;
bool success = host.RootPart.Inventory.GetRezReadySceneObjects(item, out objlist, out veclist, out bbox, out offsetHeight);
if (! success)
{
GenerateRuntimeError("Failed to create object");
return;
}
int totalPrims = 0;
foreach (SceneObjectGroup group in objlist)
totalPrims += group.PrimCount;
if (! m_scene.Permissions.CanRezObject(totalPrims, item.OwnerID, pos))
{
GenerateRuntimeError("Not allowed to create the object");
return;
}
if (! m_scene.Permissions.BypassPermissions())
{
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
host.RootPart.Inventory.RemoveInventoryItem(item.ItemID);
}
for (int i = 0; i < objlist.Count; i++)
{
SceneObjectGroup group = objlist[i];
Vector3 curpos = pos + veclist[i];
if (group.IsAttachment == false && group.RootPart.Shape.State != 0)
{
group.RootPart.AttachedPos = group.AbsolutePosition;
group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint;
}
group.RezzerID = host.RootPart.UUID;
m_scene.AddNewSceneObject(group, true, curpos, rot, vel);
UUID storeID = group.UUID;
if (! m_store.CreateStore(param, ref storeID))
{
GenerateRuntimeError("Unable to create jsonstore for new object");
continue;
}
// We can only call this after adding the scene object, since the scene object references the scene
// to find out if scripts should be activated at all.
group.RootPart.SetDieAtEdge(true);
group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 3);
group.ResumeScripts();
group.ScheduleGroupForFullUpdate();
// send the reply back to the host object, use the integer param to indicate the number
// of remaining objects
m_comms.DispatchReply(scriptID, objlist.Count-i-1, group.RootPart.UUID.ToString(), reqID.ToString());
}
}
}
}
| |
using Support;
/*
* 02/23/99 JavaConversion by E.B, JavaLayer
*/
/*===========================================================================
riff.h - Don Cross, April 1993.
RIFF file format classes.
See Chapter 8 of "Multimedia Programmer's Reference" in
the Microsoft Windows SDK.
See also:
..\source\riff.cpp
ddc.h
===========================================================================*/
namespace javazoom.jl.converter
{
using System;
/// <summary> Class allowing WaveFormat Access
/// </summary>
internal class WaveFile:RiffFile
{
public const int MAX_WAVE_CHANNELS = 2;
//UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'WaveFormat_ChunkData' to access its enclosing instance. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1019"'
internal class WaveFormat_ChunkData
{
private void InitBlock(WaveFile enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private WaveFile enclosingInstance;
public WaveFile Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public short wFormatTag = 0; // Format category (PCM=1)
public short nChannels = 0; // Number of channels (mono=1, stereo=2)
public int nSamplesPerSec = 0; // Sampling rate [Hz]
public int nAvgBytesPerSec = 0;
public short nBlockAlign = 0;
public short nBitsPerSample = 0;
public WaveFormat_ChunkData(WaveFile enclosingInstance)
{
InitBlock(enclosingInstance);
wFormatTag = 1; // PCM
Config(44100, (short) 16, (short) 1);
}
public virtual void Config(int NewSamplingRate, short NewBitsPerSample, short NewNumChannels)
{
nSamplesPerSec = NewSamplingRate;
nChannels = NewNumChannels;
nBitsPerSample = NewBitsPerSample;
nAvgBytesPerSec = (nChannels * nSamplesPerSec * nBitsPerSample) / 8;
nBlockAlign = (short) ((nChannels * nBitsPerSample) / 8);
}
}
//UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'WaveFormat_Chunk' to access its enclosing instance. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1019"'
internal class WaveFormat_Chunk
{
private void InitBlock(WaveFile enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private WaveFile enclosingInstance;
public WaveFile Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public RiffChunkHeader header;
public WaveFormat_ChunkData data;
public WaveFormat_Chunk(WaveFile enclosingInstance)
{
InitBlock(enclosingInstance);
header = new RiffChunkHeader(enclosingInstance);
data = new WaveFormat_ChunkData(enclosingInstance);
header.ckID = javazoom.jl.converter.RiffFile.FourCC("fmt ");
header.ckSize = 16;
}
public virtual int VerifyValidity()
{
bool ret = header.ckID == javazoom.jl.converter.RiffFile.FourCC("fmt ") && (data.nChannels == 1 || data.nChannels == 2) && data.nAvgBytesPerSec == (data.nChannels * data.nSamplesPerSec * data.nBitsPerSample) / 8 && data.nBlockAlign == (data.nChannels * data.nBitsPerSample) / 8;
if (ret == true)
return 1;
else
return 0;
}
}
//UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'WaveFileSample' to access its enclosing instance. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1019"'
internal class WaveFileSample
{
private void InitBlock(WaveFile enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private WaveFile enclosingInstance;
public WaveFile Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public short[] chan;
public WaveFileSample(WaveFile enclosingInstance)
{
InitBlock(enclosingInstance);
chan = new short[WaveFile.MAX_WAVE_CHANNELS];
}
}
private WaveFormat_Chunk wave_format;
private RiffChunkHeader pcm_data;
private long pcm_data_offset = 0; // offset of 'pcm_data' in output file
private int num_samples = 0;
/// <summary> Constructs a new WaveFile instance.
/// </summary>
public WaveFile()
{
pcm_data = new RiffChunkHeader(this);
wave_format = new WaveFormat_Chunk(this);
pcm_data.ckID = FourCC("data");
pcm_data.ckSize = 0;
num_samples = 0;
}
/// <summary>*
/// *
/// public int OpenForRead (String Filename)
/// {
/// // Verify filename parameter as best we can...
/// if (Filename == null)
/// {
/// return DDC_INVALID_CALL;
/// }
/// int retcode = Open ( Filename, RFM_READ );
/// </summary>
/// <summary>if ( retcode == DDC_SUCCESS )
/// {
/// retcode = Expect ( "WAVE", 4 );
/// </summary>
/// <summary>if ( retcode == DDC_SUCCESS )
/// {
/// retcode = Read(wave_format,24);
/// </summary>
/// <summary>if ( retcode == DDC_SUCCESS && !wave_format.VerifyValidity() )
/// {
/// // This isn't standard PCM, so we don't know what it is!
/// retcode = DDC_FILE_ERROR;
/// }
/// </summary>
/// <summary>if ( retcode == DDC_SUCCESS )
/// {
/// pcm_data_offset = CurrentFilePosition();
/// </summary>
/// <summary>// Figure out number of samples from
/// // file size, current file position, and
/// // WAVE header.
/// retcode = Read (pcm_data, 8 );
/// num_samples = filelength(fileno(file)) - CurrentFilePosition();
/// num_samples /= NumChannels();
/// num_samples /= (BitsPerSample() / 8);
/// }
/// }
/// }
/// return retcode;
/// }
/// </summary>
/// <summary>
/// Pass in either a FileName or a Stream.
/// </summary>
public virtual int OpenForWrite(System.String Filename, System.IO.Stream stream, int SamplingRate, short BitsPerSample, short NumChannels)
{
// Verify parameters...
if ((BitsPerSample != 8 && BitsPerSample != 16) || NumChannels < 1 || NumChannels > 2)
{
return DDC_INVALID_CALL;
}
wave_format.data.Config(SamplingRate, BitsPerSample, NumChannels);
int retcode = 0;
if (stream != null)
Open(stream, RFM_WRITE);
else
Open(Filename, RFM_WRITE);
if (retcode == DDC_SUCCESS)
{
sbyte[] theWave = new sbyte[]{(sbyte) SupportClass.Identity('W'), (sbyte) SupportClass.Identity('A'), (sbyte) SupportClass.Identity('V'), (sbyte) SupportClass.Identity('E')};
retcode = Write(theWave, 4);
if (retcode == DDC_SUCCESS)
{
// Ecriture de wave_format
retcode = Write(wave_format.header, 8);
retcode = Write(wave_format.data.wFormatTag, 2);
retcode = Write(wave_format.data.nChannels, 2);
retcode = Write(wave_format.data.nSamplesPerSec, 4);
retcode = Write(wave_format.data.nAvgBytesPerSec, 4);
retcode = Write(wave_format.data.nBlockAlign, 2);
retcode = Write(wave_format.data.nBitsPerSample, 2);
if (retcode == DDC_SUCCESS)
{
pcm_data_offset = CurrentFilePosition();
retcode = Write(pcm_data, 8);
}
}
}
return retcode;
}
/// <summary>*
/// *
/// public int ReadSample ( short[] Sample )
/// {
/// </summary>
/// <summary>}
/// </summary>
/// <summary>*
/// *
/// public int WriteSample( short[] Sample )
/// {
/// int retcode = DDC_SUCCESS;
/// switch ( wave_format.data.nChannels )
/// {
/// case 1:
/// switch ( wave_format.data.nBitsPerSample )
/// {
/// case 8:
/// pcm_data.ckSize += 1;
/// retcode = Write ( Sample, 1 );
/// break;
/// </summary>
/// <summary>case 16:
/// pcm_data.ckSize += 2;
/// retcode = Write ( Sample, 2 );
/// break;
/// </summary>
/// <summary>default:
/// retcode = DDC_INVALID_CALL;
/// }
/// break;
/// </summary>
/// <summary>case 2:
/// switch ( wave_format.data.nBitsPerSample )
/// {
/// case 8:
/// retcode = Write ( Sample, 1 );
/// if ( retcode == DDC_SUCCESS )
/// {
/// // &Sample[1]
/// retcode = Write (Sample, 1 );
/// if ( retcode == DDC_SUCCESS )
/// {
/// pcm_data.ckSize += 2;
/// }
/// }
/// break;
/// </summary>
/// <summary>case 16:
/// retcode = Write ( Sample, 2 );
/// if ( retcode == DDC_SUCCESS )
/// {
/// // &Sample[1]
/// retcode = Write (Sample, 2 );
/// if ( retcode == DDC_SUCCESS )
/// {
/// pcm_data.ckSize += 4;
/// }
/// }
/// break;
/// </summary>
/// <summary>default:
/// retcode = DDC_INVALID_CALL;
/// }
/// break;
/// </summary>
/// <summary>default:
/// retcode = DDC_INVALID_CALL;
/// }
/// </summary>
/// <summary>return retcode;
/// }
/// </summary>
/// <summary>*
/// *
/// public int SeekToSample ( long SampleIndex )
/// {
/// if ( SampleIndex >= NumSamples() )
/// {
/// return DDC_INVALID_CALL;
/// }
/// int SampleSize = (BitsPerSample() + 7) / 8;
/// int rc = Seek ( pcm_data_offset + 8 +
/// SampleSize * NumChannels() * SampleIndex );
/// return rc;
/// }
/// </summary>
/// <summary> Write 16-bit audio
/// </summary>
public virtual int WriteData(short[] data, int numData)
{
int extraBytes = numData * 2;
pcm_data.ckSize += extraBytes;
return base.Write(data, extraBytes);
}
/// <summary> Read 16-bit audio.
/// *
/// public int ReadData (short[] data, int numData)
/// {return super.Read ( data, numData * 2);}
/// </summary>
/// <summary> Write 8-bit audio.
/// *
/// public int WriteData ( byte[] data, int numData )
/// {
/// pcm_data.ckSize += numData;
/// return super.Write ( data, numData );
/// }
/// </summary>
/// <summary> Read 8-bit audio.
/// *
/// public int ReadData ( byte[] data, int numData )
/// {return super.Read ( data, numData );}
/// </summary>
/// <summary>*
/// *
/// public int ReadSamples (int num, int [] WaveFileSample)
/// {
/// </summary>
/// <summary>}
/// </summary>
/// <summary>*
/// *
/// public int WriteMonoSample ( short[] SampleData )
/// {
/// switch ( wave_format.data.nBitsPerSample )
/// {
/// case 8:
/// pcm_data.ckSize += 1;
/// return Write ( SampleData, 1 );
/// </summary>
/// <summary>case 16:
/// pcm_data.ckSize += 2;
/// return Write ( SampleData, 2 );
/// }
/// return DDC_INVALID_CALL;
/// }
/// </summary>
/// <summary>*
/// *
/// public int WriteStereoSample ( short[] LeftSample, short[] RightSample )
/// {
/// int retcode = DDC_SUCCESS;
/// switch ( wave_format.data.nBitsPerSample )
/// {
/// case 8:
/// retcode = Write ( LeftSample, 1 );
/// if ( retcode == DDC_SUCCESS )
/// {
/// retcode = Write ( RightSample, 1 );
/// if ( retcode == DDC_SUCCESS )
/// {
/// pcm_data.ckSize += 2;
/// }
/// }
/// break;
/// </summary>
/// <summary>case 16:
/// retcode = Write ( LeftSample, 2 );
/// if ( retcode == DDC_SUCCESS )
/// {
/// retcode = Write ( RightSample, 2 );
/// if ( retcode == DDC_SUCCESS )
/// {
/// pcm_data.ckSize += 4;
/// }
/// }
/// break;
/// </summary>
/// <summary>default:
/// retcode = DDC_INVALID_CALL;
/// }
/// return retcode;
/// }
/// </summary>
/// <summary>*
/// *
/// public int ReadMonoSample ( short[] Sample )
/// {
/// int retcode = DDC_SUCCESS;
/// switch ( wave_format.data.nBitsPerSample )
/// {
/// case 8:
/// byte[] x = {0};
/// retcode = Read ( x, 1 );
/// Sample[0] = (short)(x[0]);
/// break;
/// </summary>
/// <summary>case 16:
/// retcode = Read ( Sample, 2 );
/// break;
/// </summary>
/// <summary>default:
/// retcode = DDC_INVALID_CALL;
/// }
/// return retcode;
/// }
/// </summary>
/// <summary>*
/// *
/// public int ReadStereoSample ( short[] LeftSampleData, short[] RightSampleData )
/// {
/// int retcode = DDC_SUCCESS;
/// byte[] x = new byte[2];
/// short[] y = new short[2];
/// switch ( wave_format.data.nBitsPerSample )
/// {
/// case 8:
/// retcode = Read ( x, 2 );
/// L[0] = (short) ( x[0] );
/// R[0] = (short) ( x[1] );
/// break;
/// </summary>
/// <summary>case 16:
/// retcode = Read ( y, 4 );
/// L[0] = (short) ( y[0] );
/// R[0] = (short) ( y[1] );
/// break;
/// </summary>
/// <summary>default:
/// retcode = DDC_INVALID_CALL;
/// }
/// return retcode;
/// }
/// </summary>
/// <summary>*
/// </summary>
public override int Close()
{
int rc = DDC_SUCCESS;
if (fmode == RFM_WRITE)
rc = Backpatch(pcm_data_offset, pcm_data, 8);
if (!JustWriteLengthBytes)
{
if (rc == DDC_SUCCESS)
rc = base.Close();
}
return rc;
}
public int Close(bool justWriteLengthBytes)
{
JustWriteLengthBytes = justWriteLengthBytes;
int ret = Close();
JustWriteLengthBytes = false;
return ret;
}
bool JustWriteLengthBytes = false;
// [Hz]
public virtual int SamplingRate()
{
return wave_format.data.nSamplesPerSec;
}
public virtual short BitsPerSample()
{
return wave_format.data.nBitsPerSample;
}
public virtual short NumChannels()
{
return wave_format.data.nChannels;
}
public virtual int NumSamples()
{
return num_samples;
}
/// <summary> Open for write using another wave file's parameters...
/// </summary>
public virtual int OpenForWrite(System.String Filename, WaveFile OtherWave)
{
return OpenForWrite(Filename, null, OtherWave.SamplingRate(), OtherWave.BitsPerSample(), OtherWave.NumChannels());
}
/// <summary>*
/// </summary>
public override long CurrentFilePosition()
{
return base.CurrentFilePosition();
}
/* public int FourCC(String ChunkName)
{
byte[] p = {0x20,0x20,0x20,0x20};
ChunkName.getBytes(0,4,p,0);
int ret = (((p[0] << 24)& 0xFF000000) | ((p[1] << 16)&0x00FF0000) | ((p[2] << 8)&0x0000FF00) | (p[3]&0x000000FF));
return ret;
}*/
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MBProgressHUD;
using MonoTouch.Dialog;
namespace MBProgressHUDDemo
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow window;
UINavigationController navController;
DialogViewController dvcDialog;
MTMBProgressHUD hud;
// vars for managing NSUrlConnection Demo
public long expectedLength;
public long currentLength;
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
window = new UIWindow (UIScreen.MainScreen.Bounds);
var root = new RootElement("MBProgressHUD")
{
new Section ("Samples")
{
new StringElement ("Simple indeterminate progress", ShowSimple),
new StringElement ("With label", ShowWithLabel),
new StringElement ("With details label", ShowWithDetailsLabel),
new StringElement ("Determinate mode", ShowWithLabelDeterminate),
new StringElement ("Annular determinate mode", ShowWithLabelAnnularDeterminate),
new StringElement ("Horizontal determinate mode", ShowWithLabelDeterminateHorizontalBar),
new StringElement ("Custom view", ShowWithCustomView),
new StringElement ("Mode switching", ShowWithLabelMixed),
new StringElement ("Using handlers", ShowUsingHandlers),
new StringElement ("On Window", ShowOnWindow),
new StringElement ("NSURLConnection", ShowUrl),
new StringElement ("Dim background", ShowWithGradient),
new StringElement ("Text only", ShowTextOnly),
new StringElement ("Colored", ShowWithColor),
}
};
dvcDialog = new DialogViewController(UITableViewStyle.Grouped, root, false);
navController = new UINavigationController(dvcDialog);
window.RootViewController = navController;
window.MakeKeyAndVisible ();
return true;
}
#region Button Actions
void ShowSimple ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Show the HUD while the provided method executes in a new thread
hud.Show (new MonoTouch.ObjCRuntime.Selector("MyTask"), this, null, true);
}
void ShowWithLabel ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Loading";
// Show the HUD while the provided method executes in a new thread
hud.Show (new MonoTouch.ObjCRuntime.Selector ("MyTask"), this, null, true);
}
void ShowWithDetailsLabel ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Loading";
hud.DetailsLabelText = "updating data";
hud.Square = true;
// Show the HUD while the provided method executes in a new thread
hud.Show (new MonoTouch.ObjCRuntime.Selector ("MyTask"), this, null, true);
}
void ShowWithLabelDeterminate ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Set determinate mode
hud.Mode = MBProgressHUDMode.Determinate;
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Loading";
// Show the HUD while the provided method executes in a new thread
hud.Show (new MonoTouch.ObjCRuntime.Selector ("MyProgressTask"), this, null, true);
}
void ShowWithLabelAnnularDeterminate ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview(hud);
// Set determinate mode
hud.Mode = MBProgressHUDMode.AnnularDeterminate;
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Loading";
// Show the HUD while the provided method executes in a new thread
hud.Show (new MonoTouch.ObjCRuntime.Selector ("MyProgressTask"), this, null, true);
}
void ShowWithLabelDeterminateHorizontalBar ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview(hud);
// Set determinate mode
hud.Mode = MBProgressHUDMode.DeterminateHorizontalBar;
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Loading";
// Show the HUD while the provided method executes in a new thread
hud.Show (new MonoTouch.ObjCRuntime.Selector ("MyProgressTask"), this, null, true);
}
void ShowWithCustomView ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Set custom view mode
hud.Mode = MBProgressHUDMode.CustomView;
// The sample image is based on the work by http://www.pixelpressicons.com, http://creativecommons.org/licenses/by/2.5/ca/
// Make the customViews 37 by 37 pixels for best results (those are the bounds of the build-in progress indicators)
hud.CustomView = new UIImageView (UIImage.FromBundle ("37x-Checkmark.png"));
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Completed";
// Show the HUD
hud.Show(true);
// Hide the HUD after 3 seconds
hud.Hide (true, 3);
}
void ShowWithLabelMixed ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Connecting";
hud.MinSize = new System.Drawing.SizeF (135f, 135f);
// Show the HUD while the provided method executes in a new thread
hud.Show (new MonoTouch.ObjCRuntime.Selector ("MyMixedTask"), this, null, true);
}
void ShowUsingHandlers ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Add information to your HUD
hud.LabelText = "With a handler";
// We show the hud while executing MyTask, and then we clean up
hud.Show (true, () => {
MyTask();
}, () => {
hud.RemoveFromSuperview();
hud = null;
});
}
void ShowOnWindow ()
{
// The hud will dispable all input on the window
hud = new MTMBProgressHUD (window);
this.window.AddSubview (hud);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Add information to your HUD
hud.LabelText = "Loading";
// Show the HUD while the provided method executes in a new thread
hud.Show (new MonoTouch.ObjCRuntime.Selector ("MyTask"), this, null, true);
}
void ShowUrl ()
{
// Show the hud on top most view
hud = MTMBProgressHUD.ShowHUD (this.navController.View, true);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
NSUrl url = new NSUrl ("https://github.com/matej/MBProgressHUD/zipball/master");
NSUrlRequest request = new NSUrlRequest (url);
NSUrlConnection connection = new NSUrlConnection (request, new MyNSUrlConnectionDelegete (this, hud));
connection.Start();
}
void ShowWithGradient ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Set HUD to dim Background
hud.DimBackground = true;
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Show the HUD while the provided method executes in a new thread
hud.Show(new MonoTouch.ObjCRuntime.Selector ("MyTask"), this, null, true);
}
void ShowTextOnly ()
{
// Show the hud on top most view
hud = MTMBProgressHUD.ShowHUD (this.navController.View, true);
// Configure for text only and offset down
hud.Mode = MBProgressHUDMode.Text;
hud.LabelText = "Some message...";
hud.Margin = 10f;
hud.YOffset = 150f;
hud.RemoveFromSuperViewOnHide = true;
hud.Hide (true, 3);
}
void ShowWithColor ()
{
// The hud will dispable all input on the view (use the higest view possible in the view hierarchy)
hud = new MTMBProgressHUD (navController.View);
navController.View.AddSubview (hud);
// Set the hud to display with a color
hud.Color = new UIColor (0.23f, 0.5f, 0.82f, 0.90f);
// Regiser for DidHide Event so we can remove it from the window at the right time
hud.DidHide += HandleDidHide;
// Show the HUD while the provided method executes in a new thread
hud.Show(new MonoTouch.ObjCRuntime.Selector ("MyTask"), this, null, true);
}
#endregion
#region fake tasks and Hide Handler
[Export ("MyTask")]
void MyTask ()
{
System.Threading.Thread.Sleep(3000);
}
[Export ("MyProgressTask")]
void MyProgressTask ()
{
float progress = 0.0f;
while (progress < 1.0f) {
progress += 0.01f;
hud.Progress = progress;
System.Threading.Thread.Sleep(50);
}
}
[Export ("MyMixedTask")]
void MyMixedTask ()
{
// Indeterminate mode
System.Threading.Thread.Sleep(2000);
// Switch to determinate mode
hud.Mode = MBProgressHUDMode.Determinate;
hud.LabelText = "Progress";
float progress = 0.0f;
while (progress < 1.0f)
{
progress += 0.01f;
hud.Progress = progress;
System.Threading.Thread.Sleep(50);
}
// Back to indeterminate mode
hud.Mode = MBProgressHUDMode.Indeterminate;
hud.LabelText = "Cleaning up";
System.Threading.Thread.Sleep(2000);
// The sample image is based on the work by www.pixelpressicons.com, http://creativecommons.org/licenses/by/2.5/ca/
// Make the customViews 37 by 37 pixels for best results (those are the bounds of the build-in progress indicators)
// Since HUD is already on screen, we must set It's custom vien on Main Thread
BeginInvokeOnMainThread ( ()=> {
hud.CustomView = new UIImageView (UIImage.FromBundle ("37x-Checkmark.png"));
});
hud.Mode = MBProgressHUDMode.CustomView;
hud.LabelText = "Completed";
System.Threading.Thread.Sleep (2000);
}
void HandleDidHide (object sender, EventArgs e)
{
hud.RemoveFromSuperview();
hud = null;
}
#endregion
}
// Custom NSUrlConnectionDelegate that handles NSUrlConnection Events
public class MyNSUrlConnectionDelegete : MonoTouch.Foundation.NSUrlConnectionDelegate
{
AppDelegate del;
MTMBProgressHUD hud;
public MyNSUrlConnectionDelegete (AppDelegate del, MTMBProgressHUD hud)
{
this.del = del;
this.hud = hud;
}
public override void ReceivedResponse (NSUrlConnection connection, NSUrlResponse response)
{
del.expectedLength = response.ExpectedContentLength;
del.currentLength = 0;
hud.Mode = MBProgressHUDMode.Determinate;
}
public override void ReceivedData (NSUrlConnection connection, NSData data)
{
del.currentLength += data.Length;
hud.Progress = (del.currentLength / (float) del.expectedLength);
}
public override void FinishedLoading (NSUrlConnection connection)
{
BeginInvokeOnMainThread ( ()=> {
hud.CustomView = new UIImageView (UIImage.FromBundle ("37x-Checkmark.png"));
});
hud.Mode = MBProgressHUDMode.CustomView;
hud.Hide(true, 2);
}
public override void FailedWithError (NSUrlConnection connection, NSError error)
{
hud.Hide(true);
}
}
}
| |
// 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="AssetGroupSignalServiceClient"/> instances.</summary>
public sealed partial class AssetGroupSignalServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AssetGroupSignalServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AssetGroupSignalServiceSettings"/>.</returns>
public static AssetGroupSignalServiceSettings GetDefault() => new AssetGroupSignalServiceSettings();
/// <summary>
/// Constructs a new <see cref="AssetGroupSignalServiceSettings"/> object with default settings.
/// </summary>
public AssetGroupSignalServiceSettings()
{
}
private AssetGroupSignalServiceSettings(AssetGroupSignalServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateAssetGroupSignalsSettings = existing.MutateAssetGroupSignalsSettings;
OnCopy(existing);
}
partial void OnCopy(AssetGroupSignalServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AssetGroupSignalServiceClient.MutateAssetGroupSignals</c> and
/// <c>AssetGroupSignalServiceClient.MutateAssetGroupSignalsAsync</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 MutateAssetGroupSignalsSettings { 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="AssetGroupSignalServiceSettings"/> object.</returns>
public AssetGroupSignalServiceSettings Clone() => new AssetGroupSignalServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AssetGroupSignalServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class AssetGroupSignalServiceClientBuilder : gaxgrpc::ClientBuilderBase<AssetGroupSignalServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AssetGroupSignalServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AssetGroupSignalServiceClientBuilder()
{
UseJwtAccessWithScopes = AssetGroupSignalServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AssetGroupSignalServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AssetGroupSignalServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AssetGroupSignalServiceClient Build()
{
AssetGroupSignalServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AssetGroupSignalServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AssetGroupSignalServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AssetGroupSignalServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AssetGroupSignalServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AssetGroupSignalServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AssetGroupSignalServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AssetGroupSignalServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AssetGroupSignalServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AssetGroupSignalServiceClient.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>AssetGroupSignalService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage asset group signal.
/// </remarks>
public abstract partial class AssetGroupSignalServiceClient
{
/// <summary>
/// The default endpoint for the AssetGroupSignalService 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 AssetGroupSignalService scopes.</summary>
/// <remarks>
/// The default AssetGroupSignalService 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="AssetGroupSignalServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AssetGroupSignalServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AssetGroupSignalServiceClient"/>.</returns>
public static stt::Task<AssetGroupSignalServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AssetGroupSignalServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AssetGroupSignalServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AssetGroupSignalServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AssetGroupSignalServiceClient"/>.</returns>
public static AssetGroupSignalServiceClient Create() => new AssetGroupSignalServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AssetGroupSignalServiceClient"/> 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="AssetGroupSignalServiceSettings"/>.</param>
/// <returns>The created <see cref="AssetGroupSignalServiceClient"/>.</returns>
internal static AssetGroupSignalServiceClient Create(grpccore::CallInvoker callInvoker, AssetGroupSignalServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AssetGroupSignalService.AssetGroupSignalServiceClient grpcClient = new AssetGroupSignalService.AssetGroupSignalServiceClient(callInvoker);
return new AssetGroupSignalServiceClientImpl(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 AssetGroupSignalService client</summary>
public virtual AssetGroupSignalService.AssetGroupSignalServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates or removes asset group signals. Operation statuses are
/// returned.
/// </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 MutateAssetGroupSignalsResponse MutateAssetGroupSignals(MutateAssetGroupSignalsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates or removes asset group signals. Operation statuses are
/// returned.
/// </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<MutateAssetGroupSignalsResponse> MutateAssetGroupSignalsAsync(MutateAssetGroupSignalsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates or removes asset group signals. Operation statuses are
/// returned.
/// </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<MutateAssetGroupSignalsResponse> MutateAssetGroupSignalsAsync(MutateAssetGroupSignalsRequest request, st::CancellationToken cancellationToken) =>
MutateAssetGroupSignalsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates or removes asset group signals. Operation statuses are
/// returned.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose asset group signals are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual asset group signals.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAssetGroupSignalsResponse MutateAssetGroupSignals(string customerId, scg::IEnumerable<AssetGroupSignalOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAssetGroupSignals(new MutateAssetGroupSignalsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates or removes asset group signals. Operation statuses are
/// returned.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose asset group signals are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual asset group signals.
/// </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<MutateAssetGroupSignalsResponse> MutateAssetGroupSignalsAsync(string customerId, scg::IEnumerable<AssetGroupSignalOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAssetGroupSignalsAsync(new MutateAssetGroupSignalsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates or removes asset group signals. Operation statuses are
/// returned.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose asset group signals are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual asset group signals.
/// </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<MutateAssetGroupSignalsResponse> MutateAssetGroupSignalsAsync(string customerId, scg::IEnumerable<AssetGroupSignalOperation> operations, st::CancellationToken cancellationToken) =>
MutateAssetGroupSignalsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AssetGroupSignalService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage asset group signal.
/// </remarks>
public sealed partial class AssetGroupSignalServiceClientImpl : AssetGroupSignalServiceClient
{
private readonly gaxgrpc::ApiCall<MutateAssetGroupSignalsRequest, MutateAssetGroupSignalsResponse> _callMutateAssetGroupSignals;
/// <summary>
/// Constructs a client wrapper for the AssetGroupSignalService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="AssetGroupSignalServiceSettings"/> used within this client.
/// </param>
public AssetGroupSignalServiceClientImpl(AssetGroupSignalService.AssetGroupSignalServiceClient grpcClient, AssetGroupSignalServiceSettings settings)
{
GrpcClient = grpcClient;
AssetGroupSignalServiceSettings effectiveSettings = settings ?? AssetGroupSignalServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateAssetGroupSignals = clientHelper.BuildApiCall<MutateAssetGroupSignalsRequest, MutateAssetGroupSignalsResponse>(grpcClient.MutateAssetGroupSignalsAsync, grpcClient.MutateAssetGroupSignals, effectiveSettings.MutateAssetGroupSignalsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAssetGroupSignals);
Modify_MutateAssetGroupSignalsApiCall(ref _callMutateAssetGroupSignals);
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_MutateAssetGroupSignalsApiCall(ref gaxgrpc::ApiCall<MutateAssetGroupSignalsRequest, MutateAssetGroupSignalsResponse> call);
partial void OnConstruction(AssetGroupSignalService.AssetGroupSignalServiceClient grpcClient, AssetGroupSignalServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AssetGroupSignalService client</summary>
public override AssetGroupSignalService.AssetGroupSignalServiceClient GrpcClient { get; }
partial void Modify_MutateAssetGroupSignalsRequest(ref MutateAssetGroupSignalsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates or removes asset group signals. Operation statuses are
/// returned.
/// </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 MutateAssetGroupSignalsResponse MutateAssetGroupSignals(MutateAssetGroupSignalsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAssetGroupSignalsRequest(ref request, ref callSettings);
return _callMutateAssetGroupSignals.Sync(request, callSettings);
}
/// <summary>
/// Creates or removes asset group signals. Operation statuses are
/// returned.
/// </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<MutateAssetGroupSignalsResponse> MutateAssetGroupSignalsAsync(MutateAssetGroupSignalsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAssetGroupSignalsRequest(ref request, ref callSettings);
return _callMutateAssetGroupSignals.Async(request, callSettings);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.VisualTree;
using Xunit;
namespace Avalonia.Styling.UnitTests
{
public class SelectorTests_Multiple
{
[Fact]
public void Named_Template_Child_Of_Control_With_Two_Classes()
{
var template = new FuncControlTemplate((parent, scope) =>
{
return new Border
{
Name = "border",
}.RegisterInNameScope(scope);
});
var control = new Button
{
Template = template,
};
control.ApplyTemplate();
var selector = default(Selector)
.OfType<Button>()
.Class("foo")
.Class("bar")
.Template()
.Name("border");
var border = (Border)((IVisual)control).VisualChildren.Single();
var values = new List<bool>();
var match = selector.Match(border);
Assert.Equal(SelectorMatchResult.Sometimes, match.Result);
match.Activator.Subscribe(x => values.Add(x));
Assert.Equal(new[] { false }, values);
control.Classes.AddRange(new[] { "foo", "bar" });
Assert.Equal(new[] { false, true }, values);
control.Classes.Remove("foo");
Assert.Equal(new[] { false, true, false }, values);
}
[Fact]
public void Named_OfType_Template_Child_Of_Control_With_Two_Classes_Wrong_Type()
{
var template = new FuncControlTemplate((parent, scope) =>
{
return new Border
{
Name = "border",
}.RegisterInNameScope(scope);
});
var control = new Button
{
Template = template,
};
control.ApplyTemplate();
var selector = default(Selector)
.OfType<Button>()
.Class("foo")
.Class("bar")
.Template()
.OfType<TextBlock>()
.Name("baz");
var border = (Border)((IVisual)control).VisualChildren.Single();
var values = new List<bool>();
var match = selector.Match(border);
Assert.Equal(SelectorMatchResult.NeverThisType, match.Result);
}
[Fact]
public void Control_With_Class_Descendent_Of_Control_With_Two_Classes()
{
var textBlock = new TextBlock();
var control = new Button { Content = textBlock };
control.ApplyTemplate();
var selector = default(Selector)
.OfType<Button>()
.Class("foo")
.Class("bar")
.Descendant()
.OfType<TextBlock>()
.Class("baz");
var values = new List<bool>();
var match = selector.Match(textBlock);
Assert.Equal(SelectorMatchResult.Sometimes, match.Result);
match.Activator.Subscribe(x => values.Add(x));
Assert.Equal(new[] { false }, values);
control.Classes.AddRange(new[] { "foo", "bar" });
Assert.Equal(new[] { false }, values);
textBlock.Classes.Add("baz");
Assert.Equal(new[] { false, true }, values);
}
[Fact]
public void Named_Class_Template_Child_Of_Control()
{
var template = new FuncControlTemplate((parent, scope) =>
{
return new Border
{
Name = "border",
}.RegisterInNameScope(scope);
});
var control = new Button
{
Template = template,
};
control.ApplyTemplate();
var selector = default(Selector)
.OfType<Button>()
.Template()
.Name("border")
.Class("foo");
var border = (Border)((IVisual)control).VisualChildren.Single();
var values = new List<bool>();
var match = selector.Match(border);
Assert.Equal(SelectorMatchResult.Sometimes, match.Result);
match.Activator.Subscribe(x => values.Add(x));
Assert.Equal(new[] { false }, values);
border.Classes.AddRange(new[] { "foo" });
Assert.Equal(new[] { false, true }, values);
border.Classes.Remove("foo");
Assert.Equal(new[] { false, true, false }, values);
}
[Fact]
public async Task Nested_PropertyEquals()
{
var control = new Canvas();
var parent = new Border { Child = control };
var target = default(Selector)
.OfType<Border>()
.PropertyEquals(Border.TagProperty, "foo")
.Child()
.OfType<Canvas>()
.PropertyEquals(Canvas.TagProperty, "bar");
var match = target.Match(control);
Assert.Equal(SelectorMatchResult.Sometimes, match.Result);
var activator = match.Activator;
Assert.False(await activator.Take(1));
control.Tag = "bar";
Assert.False(await activator.Take(1));
parent.Tag = "foo";
Assert.True(await activator.Take(1));
}
[Fact]
public void TargetType_OfType()
{
var selector = default(Selector).OfType<Button>();
Assert.Equal(typeof(Button), selector.TargetType);
}
[Fact]
public void TargetType_OfType_Class()
{
var selector = default(Selector)
.OfType<Button>()
.Class("foo");
Assert.Equal(typeof(Button), selector.TargetType);
}
[Fact]
public void TargetType_Is_Class()
{
var selector = default(Selector)
.Is<Button>()
.Class("foo");
Assert.Equal(typeof(Button), selector.TargetType);
}
[Fact]
public void TargetType_Child()
{
var selector = default(Selector)
.OfType<Button>()
.Child()
.OfType<TextBlock>();
Assert.Equal(typeof(TextBlock), selector.TargetType);
}
[Fact]
public void TargetType_Descendant()
{
var selector = default(Selector)
.OfType<Button>()
.Descendant()
.OfType<TextBlock>();
Assert.Equal(typeof(TextBlock), selector.TargetType);
}
[Fact]
public void TargetType_Template()
{
var selector = default(Selector)
.OfType<Button>()
.Template()
.OfType<TextBlock>();
Assert.Equal(typeof(TextBlock), selector.TargetType);
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// UserAccountManagementGranularInformation
/// </summary>
[DataContract]
public partial class UserAccountManagementGranularInformation : IEquatable<UserAccountManagementGranularInformation>, IValidatableObject
{
public UserAccountManagementGranularInformation()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="UserAccountManagementGranularInformation" /> class.
/// </summary>
/// <param name="CanManageAdmins">.</param>
/// <param name="CanManageAdminsMetadata">CanManageAdminsMetadata.</param>
/// <param name="CanManageGroups">.</param>
/// <param name="CanManageGroupsMetadata">CanManageGroupsMetadata.</param>
/// <param name="CanManageSharing">.</param>
/// <param name="CanManageSharingMetadata">CanManageSharingMetadata.</param>
/// <param name="CanManageUsers">.</param>
/// <param name="CanManageUsersMetadata">CanManageUsersMetadata.</param>
public UserAccountManagementGranularInformation(string CanManageAdmins = default(string), SettingsMetadata CanManageAdminsMetadata = default(SettingsMetadata), string CanManageGroups = default(string), SettingsMetadata CanManageGroupsMetadata = default(SettingsMetadata), string CanManageSharing = default(string), SettingsMetadata CanManageSharingMetadata = default(SettingsMetadata), string CanManageUsers = default(string), SettingsMetadata CanManageUsersMetadata = default(SettingsMetadata))
{
this.CanManageAdmins = CanManageAdmins;
this.CanManageAdminsMetadata = CanManageAdminsMetadata;
this.CanManageGroups = CanManageGroups;
this.CanManageGroupsMetadata = CanManageGroupsMetadata;
this.CanManageSharing = CanManageSharing;
this.CanManageSharingMetadata = CanManageSharingMetadata;
this.CanManageUsers = CanManageUsers;
this.CanManageUsersMetadata = CanManageUsersMetadata;
}
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="canManageAdmins", EmitDefaultValue=false)]
public string CanManageAdmins { get; set; }
/// <summary>
/// Gets or Sets CanManageAdminsMetadata
/// </summary>
[DataMember(Name="canManageAdminsMetadata", EmitDefaultValue=false)]
public SettingsMetadata CanManageAdminsMetadata { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="canManageGroups", EmitDefaultValue=false)]
public string CanManageGroups { get; set; }
/// <summary>
/// Gets or Sets CanManageGroupsMetadata
/// </summary>
[DataMember(Name="canManageGroupsMetadata", EmitDefaultValue=false)]
public SettingsMetadata CanManageGroupsMetadata { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="canManageSharing", EmitDefaultValue=false)]
public string CanManageSharing { get; set; }
/// <summary>
/// Gets or Sets CanManageSharingMetadata
/// </summary>
[DataMember(Name="canManageSharingMetadata", EmitDefaultValue=false)]
public SettingsMetadata CanManageSharingMetadata { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="canManageUsers", EmitDefaultValue=false)]
public string CanManageUsers { get; set; }
/// <summary>
/// Gets or Sets CanManageUsersMetadata
/// </summary>
[DataMember(Name="canManageUsersMetadata", EmitDefaultValue=false)]
public SettingsMetadata CanManageUsersMetadata { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UserAccountManagementGranularInformation {\n");
sb.Append(" CanManageAdmins: ").Append(CanManageAdmins).Append("\n");
sb.Append(" CanManageAdminsMetadata: ").Append(CanManageAdminsMetadata).Append("\n");
sb.Append(" CanManageGroups: ").Append(CanManageGroups).Append("\n");
sb.Append(" CanManageGroupsMetadata: ").Append(CanManageGroupsMetadata).Append("\n");
sb.Append(" CanManageSharing: ").Append(CanManageSharing).Append("\n");
sb.Append(" CanManageSharingMetadata: ").Append(CanManageSharingMetadata).Append("\n");
sb.Append(" CanManageUsers: ").Append(CanManageUsers).Append("\n");
sb.Append(" CanManageUsersMetadata: ").Append(CanManageUsersMetadata).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as UserAccountManagementGranularInformation);
}
/// <summary>
/// Returns true if UserAccountManagementGranularInformation instances are equal
/// </summary>
/// <param name="other">Instance of UserAccountManagementGranularInformation to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(UserAccountManagementGranularInformation other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.CanManageAdmins == other.CanManageAdmins ||
this.CanManageAdmins != null &&
this.CanManageAdmins.Equals(other.CanManageAdmins)
) &&
(
this.CanManageAdminsMetadata == other.CanManageAdminsMetadata ||
this.CanManageAdminsMetadata != null &&
this.CanManageAdminsMetadata.Equals(other.CanManageAdminsMetadata)
) &&
(
this.CanManageGroups == other.CanManageGroups ||
this.CanManageGroups != null &&
this.CanManageGroups.Equals(other.CanManageGroups)
) &&
(
this.CanManageGroupsMetadata == other.CanManageGroupsMetadata ||
this.CanManageGroupsMetadata != null &&
this.CanManageGroupsMetadata.Equals(other.CanManageGroupsMetadata)
) &&
(
this.CanManageSharing == other.CanManageSharing ||
this.CanManageSharing != null &&
this.CanManageSharing.Equals(other.CanManageSharing)
) &&
(
this.CanManageSharingMetadata == other.CanManageSharingMetadata ||
this.CanManageSharingMetadata != null &&
this.CanManageSharingMetadata.Equals(other.CanManageSharingMetadata)
) &&
(
this.CanManageUsers == other.CanManageUsers ||
this.CanManageUsers != null &&
this.CanManageUsers.Equals(other.CanManageUsers)
) &&
(
this.CanManageUsersMetadata == other.CanManageUsersMetadata ||
this.CanManageUsersMetadata != null &&
this.CanManageUsersMetadata.Equals(other.CanManageUsersMetadata)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.CanManageAdmins != null)
hash = hash * 59 + this.CanManageAdmins.GetHashCode();
if (this.CanManageAdminsMetadata != null)
hash = hash * 59 + this.CanManageAdminsMetadata.GetHashCode();
if (this.CanManageGroups != null)
hash = hash * 59 + this.CanManageGroups.GetHashCode();
if (this.CanManageGroupsMetadata != null)
hash = hash * 59 + this.CanManageGroupsMetadata.GetHashCode();
if (this.CanManageSharing != null)
hash = hash * 59 + this.CanManageSharing.GetHashCode();
if (this.CanManageSharingMetadata != null)
hash = hash * 59 + this.CanManageSharingMetadata.GetHashCode();
if (this.CanManageUsers != null)
hash = hash * 59 + this.CanManageUsers.GetHashCode();
if (this.CanManageUsersMetadata != null)
hash = hash * 59 + this.CanManageUsersMetadata.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using AgenaTrader.API;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
using AgenaTrader.Helper;
/// <summary>
/// Version: 1.2.
/// -------------------------------------------------------------------------
/// Simon Pucher 2016
/// Christian Kovar 2016
/// -------------------------------------------------------------------------
/// Description: https://en.wikipedia.org/wiki/Algorithmic_trading#Mean_reversion
/// -------------------------------------------------------------------------
/// todo
/// Statistic
/// -------------------------------------------------------------------------
/// ****** Important ******
/// To compile this indicator without any error you also need access to the utility indicator to use these global source code elements.
/// You will find this indicator on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs
/// -------------------------------------------------------------------------
/// Namespace holds all indicators and is required. Do not change it.
/// </summary>
namespace AgenaTrader.UserCode
{
[Category("Script-Trading")]
[Description("Mean Reversion")]
[IsEntryAttribute(true)]
[IsStopAttribute(false)]
[IsTargetAttribute(false)]
[OverrulePreviousStopPrice(false)]
public class Mean_Reversion_Condition : UserScriptedCondition, IMean_Reversion
{
#region Variables
//interface
private bool _IsShortEnabled = false;
private bool _IsLongEnabled = true;
private bool _WarningOccured = false;
private bool _ErrorOccured = false;
private int _Bollinger_Period = 20;
private double _Bollinger_Standard_Deviation = 2;
private int _Momentum_Period = 100;
private int _RSI_Period = 14;
private int _RSI_Smooth = 3;
private int _RSI_Level_Low = 30;
private int _RSI_Level_High = 70;
private int _Momentum_Level_Low = -1;
private int _Momentum_Level_High = 1;
//input
//output
//internal
private Mean_Reversion_Indicator _Mean_Reversion_Indicator = null;
#endregion
protected override void OnInit()
{
IsEntry = true;
IsStop = false;
IsTarget = false;
Add(new OutputDescriptor(Const.DefaultIndicatorColor, "Occurred"));
Add(new OutputDescriptor(Const.DefaultIndicatorColor, "Entry"));
IsOverlay = false;
CalculateOnClosedBar = true;
//We need at least xy bars
this.RequiredBarsCount = 130;
}
protected override void OnBarsRequirements()
{
base.OnBarsRequirements();
}
protected override void OnStart()
{
base.OnStart();
//Init our indicator to get code access
this._Mean_Reversion_Indicator = new Mean_Reversion_Indicator();
this.ErrorOccured = false;
this.WarningOccured = false;
}
protected override void OnCalculate()
{
//calculate data
ResultValue returnvalue = this._Mean_Reversion_Indicator.calculate(InSeries, Open, High, null, null, this.Bollinger_Period, this.Bollinger_Standard_Deviation, this.Momentum_Period, this.RSI_Period, this.RSI_Smooth, this.RSI_Level_Low, this.RSI_Level_High, this.Momentum_Level_Low, this.Momentum_Level_High);
//If the calculate method was not finished we need to stop and show an alert message to the user.
if (returnvalue.ErrorOccured)
{
//Display error just one time
if (!this.ErrorOccured)
{
Log(this.DisplayName + ": " + Const.DefaultStringErrorDuringCalculation, InfoLogLevel.AlertLog);
this.ErrorOccured = true;
}
return;
}
//Entry
if (returnvalue.Entry.HasValue)
{
switch (returnvalue.Entry)
{
case OrderDirection.Buy:
Occurred.Set(1);
break;
case OrderDirection.Sell:
Occurred.Set(-1);
break;
}
}
////Exit
//if (returnvalue.Exit.HasValue)
//{
// switch (returnvalue.Exit)
// {
// case OrderDirection.Buy:
// this.DoExitShort();
// break;
// case OrderDirection.Sell:
// this.DoExitLong();
// break;
// }
//}
}
public override string ToString()
{
return "Mean Reversion(C)";
}
public override string DisplayName
{
get
{
return "Mean Reversion (C)";
}
}
#region Properties
#region Interface
/// <summary>
/// </summary>
[Description("If true it is allowed to create long positions.")]
[InputParameter]
[DisplayName("Allow Long")]
public bool IsLongEnabled
{
get { return _IsLongEnabled; }
set { _IsLongEnabled = value; }
}
/// <summary>
/// </summary>
[Description("If true it is allowed to create short positions.")]
[InputParameter]
[DisplayName("Allow Short")]
public bool IsShortEnabled
{
get { return _IsShortEnabled; }
set { _IsShortEnabled = value; }
}
[Browsable(false)]
[XmlIgnore()]
public bool ErrorOccured
{
get { return _ErrorOccured; }
set { _ErrorOccured = value; }
}
[Browsable(false)]
[XmlIgnore()]
public bool WarningOccured
{
get { return _WarningOccured; }
set { _WarningOccured = value; }
}
[Description("Period of the Bollinger Band.")]
[InputParameter]
[DisplayName("BB Period")]
public int Bollinger_Period
{
get { return _Bollinger_Period; }
set { _Bollinger_Period = value; }
}
[Description("Standard Deviation of the Bollinger Band.")]
[InputParameter]
[DisplayName("BB StdDev")]
public double Bollinger_Standard_Deviation
{
get { return _Bollinger_Standard_Deviation; }
set { _Bollinger_Standard_Deviation = value; }
}
[Description("Period of the Momentum.")]
[InputParameter]
[DisplayName("MOM Period")]
public int Momentum_Period
{
get { return _Momentum_Period; }
set { _Momentum_Period = value; }
}
[Description("Period of the RSI.")]
[InputParameter]
[DisplayName("RSI Period")]
public int RSI_Period
{
get { return _RSI_Period; }
set { _RSI_Period = value; }
}
[Description("Smooth Period of the RSI.")]
[InputParameter]
[DisplayName("RSI Smooth Period")]
public int RSI_Smooth
{
get { return _RSI_Smooth; }
set { _RSI_Smooth = value; }
}
[Description("We trade long below this RSI level.")]
[InputParameter]
[DisplayName("RSI Level Low")]
public int RSI_Level_Low
{
get { return _RSI_Level_Low; }
set { _RSI_Level_Low = value; }
}
[Description("We trade short above this RSI level.")]
[InputParameter]
[DisplayName("RSI Level High")]
public int RSI_Level_High
{
get { return _RSI_Level_High; }
set { _RSI_Level_High = value; }
}
[Description("We trade long if momentum is above this level.")]
[InputParameter]
[DisplayName("MOM Level Low")]
public int Momentum_Level_Low
{
get { return _Momentum_Level_Low; }
set { _Momentum_Level_Low = value; }
}
[Description("We trade short if momentum is below this level.")]
[InputParameter]
[DisplayName("MOM Level High")]
public int Momentum_Level_High
{
get { return _Momentum_Level_High; }
set { _Momentum_Level_High = value; }
}
#endregion
#region InSeries
#endregion
#region Output
[Browsable(false)]
[XmlIgnore()]
public DataSeries Occurred
{
get { return Outputs[0]; }
}
[Browsable(false)]
[XmlIgnore()]
public DataSeries Entry
{
get { return Outputs[1]; }
}
public override IList<DataSeries> GetEntries()
{
return new[] { Entry };
}
#endregion
#region Internals
#endregion
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.