context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
#region License
/*
* HttpServer.cs
*
* A simple HTTP server that allows to accept the WebSocket connection requests.
*
* The MIT License
*
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contributors
/*
* Contributors:
* - Juan Manuel Lallana <juan.manuel.lallana@gmail.com>
* - Liryna <liryna.stark@gmail.com>
* - Rohan Singh <rohan-singh@hotmail.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading;
using WebSocketSharp.Net;
using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp.Server
{
/// <summary>
/// Provides a simple HTTP server that allows to accept the WebSocket connection requests.
/// </summary>
/// <remarks>
/// The HttpServer class can provide multiple WebSocket services.
/// </remarks>
public class HttpServer
{
#region Private Fields
private System.Net.IPAddress _address;
private string _hostname;
private HttpListener _listener;
private Logger _logger;
private int _port;
private Thread _receiveThread;
private string _rootPath;
private bool _secure;
private WebSocketServiceManager _services;
private volatile ServerState _state;
private object _sync;
private bool _windows;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming requests on port 80.
/// </remarks>
public HttpServer ()
{
init ("*", System.Net.IPAddress.Any, 80, false);
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming requests on
/// <paramref name="port"/>.
/// </para>
/// <para>
/// If <paramref name="port"/> is 443, that instance provides a secure connection.
/// </para>
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535 inclusive.
/// </exception>
public HttpServer (int port)
: this (port, port == 443)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified HTTP URL.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming requests on
/// the host name and port in <paramref name="url"/>.
/// </para>
/// <para>
/// If <paramref name="url"/> doesn't include a port, either port 80 or 443 is used on
/// which to listen. It's determined by the scheme (http or https) in <paramref name="url"/>.
/// (Port 80 if the scheme is http.)
/// </para>
/// </remarks>
/// <param name="url">
/// A <see cref="string"/> that represents the HTTP URL of the server.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="url"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="url"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="url"/> is invalid.
/// </para>
/// </exception>
public HttpServer (string url)
{
if (url == null)
throw new ArgumentNullException ("url");
if (url.Length == 0)
throw new ArgumentException ("An empty string.", "url");
Uri uri;
string msg;
if (!tryCreateUri (url, out uri, out msg))
throw new ArgumentException (msg, "url");
var host = uri.DnsSafeHost;
var addr = host.ToIPAddress ();
if (!addr.IsLocal ())
throw new ArgumentException ("The host part isn't a local host name: " + url, "url");
init (host, addr, uri.Port, uri.Scheme == "https");
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="port"/> and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming requests on
/// <paramref name="port"/>.
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/> that indicates providing a secure connection or not.
/// (<c>true</c> indicates providing a secure connection.)
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535 inclusive.
/// </exception>
public HttpServer (int port, bool secure)
{
if (!port.IsPortNumber ())
throw new ArgumentOutOfRangeException (
"port", "Not between 1 and 65535 inclusive: " + port);
init ("*", System.Net.IPAddress.Any, port, secure);
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="address"/> and <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming requests on
/// <paramref name="address"/> and <paramref name="port"/>.
/// </para>
/// <para>
/// If <paramref name="port"/> is 443, that instance provides a secure connection.
/// </para>
/// </remarks>
/// <param name="address">
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
/// </param>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="address"/> isn't a local IP address.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535 inclusive.
/// </exception>
public HttpServer (System.Net.IPAddress address, int port)
: this (address, port, port == 443)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="address"/>, <paramref name="port"/>,
/// and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming requests on
/// <paramref name="address"/> and <paramref name="port"/>.
/// </remarks>
/// <param name="address">
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
/// </param>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/> that indicates providing a secure connection or not.
/// (<c>true</c> indicates providing a secure connection.)
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="address"/> isn't a local IP address.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535 inclusive.
/// </exception>
public HttpServer (System.Net.IPAddress address, int port, bool secure)
{
if (address == null)
throw new ArgumentNullException ("address");
if (!address.IsLocal ())
throw new ArgumentException ("Not a local IP address: " + address, "address");
if (!port.IsPortNumber ())
throw new ArgumentOutOfRangeException (
"port", "Not between 1 and 65535 inclusive: " + port);
init (null, address, port, secure);
}
#endregion
#region Public Properties
/// <summary>
/// Gets the local IP address of the server.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
/// </value>
public System.Net.IPAddress Address {
get {
return _address;
}
}
/// <summary>
/// Gets or sets the scheme used to authenticate the clients.
/// </summary>
/// <value>
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values,
/// indicates the scheme used to authenticate the clients. The default value is
/// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
/// </value>
public AuthenticationSchemes AuthenticationSchemes {
get {
return _listener.AuthenticationSchemes;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.AuthenticationSchemes = value;
}
}
/// <summary>
/// Gets a value indicating whether the server has started.
/// </summary>
/// <value>
/// <c>true</c> if the server has started; otherwise, <c>false</c>.
/// </value>
public bool IsListening {
get {
return _state == ServerState.Start;
}
}
/// <summary>
/// Gets a value indicating whether the server provides a secure connection.
/// </summary>
/// <value>
/// <c>true</c> if the server provides a secure connection; otherwise, <c>false</c>.
/// </value>
public bool IsSecure {
get {
return _secure;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server cleans up
/// the inactive sessions in the WebSocket services periodically.
/// </summary>
/// <value>
/// <c>true</c> if the server cleans up the inactive sessions every 60 seconds;
/// otherwise, <c>false</c>. The default value is <c>true</c>.
/// </value>
public bool KeepClean {
get {
return _services.KeepClean;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_services.KeepClean = value;
}
}
/// <summary>
/// Gets the logging functions.
/// </summary>
/// <remarks>
/// The default logging level is <see cref="LogLevel.Error"/>. If you would like to change it,
/// you should set the <c>Log.Level</c> property to any of the <see cref="LogLevel"/> enum
/// values.
/// </remarks>
/// <value>
/// A <see cref="Logger"/> that provides the logging functions.
/// </value>
public Logger Log {
get {
return _logger;
}
}
/// <summary>
/// Gets the port on which to listen for incoming requests.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the port number on which to listen.
/// </value>
public int Port {
get {
return _port;
}
}
/// <summary>
/// Gets or sets the name of the realm associated with the server.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the name of the realm. The default value is
/// <c>"SECRET AREA"</c>.
/// </value>
public string Realm {
get {
return _listener.Realm;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.Realm = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server is allowed to be bound to
/// an address that is already in use.
/// </summary>
/// <remarks>
/// If you would like to resolve to wait for socket in <c>TIME_WAIT</c> state,
/// you should set this property to <c>true</c>.
/// </remarks>
/// <value>
/// <c>true</c> if the server is allowed to be bound to an address that is already in use;
/// otherwise, <c>false</c>. The default value is <c>false</c>.
/// </value>
public bool ReuseAddress {
get {
return _listener.ReuseAddress;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.ReuseAddress = value;
}
}
/// <summary>
/// Gets or sets the document root path of the server.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the document root path of the server.
/// The default value is <c>"./Public"</c>.
/// </value>
public string RootPath {
get {
return _rootPath != null && _rootPath.Length > 0 ? _rootPath : (_rootPath = "./Public");
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_rootPath = value;
}
}
/// <summary>
/// Gets or sets the SSL configuration used to authenticate the server and
/// optionally the client for secure connection.
/// </summary>
/// <value>
/// A <see cref="ServerSslConfiguration"/> that represents the configuration used to
/// authenticate the server and optionally the client for secure connection.
/// </value>
public ServerSslConfiguration SslConfiguration {
get {
return _listener.SslConfiguration;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.SslConfiguration = value;
}
}
/// <summary>
/// Gets or sets the delegate called to find the credentials for an identity used to
/// authenticate a client.
/// </summary>
/// <value>
/// A <c>Func<<see cref="IIdentity"/>, <see cref="NetworkCredential"/>></c> delegate that
/// references the method(s) used to find the credentials. The default value is a function that
/// only returns <see langword="null"/>.
/// </value>
public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
get {
return _listener.UserCredentialsFinder;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.UserCredentialsFinder = value;
}
}
/// <summary>
/// Gets or sets the wait time for the response to the WebSocket Ping or Close.
/// </summary>
/// <value>
/// A <see cref="TimeSpan"/> that represents the wait time. The default value is
/// the same as 1 second.
/// </value>
public TimeSpan WaitTime {
get {
return _services.WaitTime;
}
set {
var msg = _state.CheckIfStartable () ?? value.CheckIfValidWaitTime ();
if (msg != null) {
_logger.Error (msg);
return;
}
_services.WaitTime = value;
}
}
/// <summary>
/// Gets the access to the WebSocket services provided by the server.
/// </summary>
/// <value>
/// A <see cref="WebSocketServiceManager"/> that manages the WebSocket services.
/// </value>
public WebSocketServiceManager WebSocketServices {
get {
return _services;
}
}
#endregion
#region Public Events
/// <summary>
/// Occurs when the server receives an HTTP CONNECT request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnConnect;
/// <summary>
/// Occurs when the server receives an HTTP DELETE request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnDelete;
/// <summary>
/// Occurs when the server receives an HTTP GET request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnGet;
/// <summary>
/// Occurs when the server receives an HTTP HEAD request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnHead;
/// <summary>
/// Occurs when the server receives an HTTP OPTIONS request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnOptions;
/// <summary>
/// Occurs when the server receives an HTTP PATCH request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnPatch;
/// <summary>
/// Occurs when the server receives an HTTP POST request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnPost;
/// <summary>
/// Occurs when the server receives an HTTP PUT request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnPut;
/// <summary>
/// Occurs when the server receives an HTTP TRACE request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnTrace;
#endregion
#region Private Methods
private void abort ()
{
lock (_sync) {
if (!IsListening)
return;
_state = ServerState.ShuttingDown;
}
_services.Stop (new CloseEventArgs (CloseStatusCode.ServerError), true, false);
_listener.Abort ();
_state = ServerState.Stop;
}
private string checkIfCertificateExists ()
{
if (!_secure)
return null;
var usr = _listener.SslConfiguration.ServerCertificate != null;
var port = EndPointListener.CertificateExists (_port, _listener.CertificateFolderPath);
if (usr && port) {
_logger.Warn ("The server certificate associated with the port number already exists.");
return null;
}
return !(usr || port) ? "The secure connection requires a server certificate." : null;
}
private void init (string hostname, System.Net.IPAddress address, int port, bool secure)
{
_hostname = hostname ?? address.ToString ();
_address = address;
_port = port;
_secure = secure;
_listener = new HttpListener ();
_listener.Prefixes.Add (
String.Format ("http{0}://{1}:{2}/", secure ? "s" : "", _hostname, port));
_logger = _listener.Log;
_services = new WebSocketServiceManager (_logger);
_sync = new object ();
var os = Environment.OSVersion;
_windows = os.Platform != PlatformID.Unix && os.Platform != PlatformID.MacOSX;
}
private void processRequest (HttpListenerContext context)
{
var method = context.Request.HttpMethod;
var evt = method == "GET"
? OnGet
: method == "HEAD"
? OnHead
: method == "POST"
? OnPost
: method == "PUT"
? OnPut
: method == "DELETE"
? OnDelete
: method == "OPTIONS"
? OnOptions
: method == "TRACE"
? OnTrace
: method == "CONNECT"
? OnConnect
: method == "PATCH"
? OnPatch
: null;
if (evt != null)
evt (this, new HttpRequestEventArgs (context));
else
context.Response.StatusCode = (int) HttpStatusCode.NotImplemented;
context.Response.Close ();
}
private void processRequest (HttpListenerWebSocketContext context)
{
WebSocketServiceHost host;
if (!_services.InternalTryGetServiceHost (context.RequestUri.AbsolutePath, out host)) {
context.Close (HttpStatusCode.NotImplemented);
return;
}
host.StartSession (context);
}
private void receiveRequest ()
{
while (true) {
try {
var ctx = _listener.GetContext ();
ThreadPool.QueueUserWorkItem (
state => {
try {
if (ctx.Request.IsUpgradeTo ("websocket")) {
processRequest (ctx.AcceptWebSocket (null));
return;
}
processRequest (ctx);
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
ctx.Connection.Close (true);
}
});
}
catch (HttpListenerException ex) {
_logger.Warn ("Receiving has been stopped.\n reason: " + ex.Message);
break;
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
break;
}
}
if (IsListening)
abort ();
}
private void startReceiving ()
{
_listener.Start ();
_receiveThread = new Thread (new ThreadStart (receiveRequest));
_receiveThread.IsBackground = true;
_receiveThread.Start ();
}
private void stopReceiving (int millisecondsTimeout)
{
_listener.Close ();
_receiveThread.Join (millisecondsTimeout);
}
private static bool tryCreateUri (string uriString, out Uri result, out string message)
{
result = null;
var uri = uriString.ToUri ();
if (uri == null) {
message = "An invalid URI string: " + uriString;
return false;
}
if (!uri.IsAbsoluteUri) {
message = "Not an absolute URI: " + uriString;
return false;
}
var schm = uri.Scheme;
if (!(schm == "http" || schm == "https")) {
message = "The scheme part isn't 'http' or 'https': " + uriString;
return false;
}
if (uri.PathAndQuery != "/") {
message = "Includes the path or query component: " + uriString;
return false;
}
if (uri.Fragment.Length > 0) {
message = "Includes the fragment component: " + uriString;
return false;
}
if (uri.Port == 0) {
message = "The port part is zero: " + uriString;
return false;
}
result = uri;
message = String.Empty;
return true;
}
#endregion
#region Public Methods
/// <summary>
/// Adds the WebSocket service with the specified behavior, <paramref name="path"/>,
/// and <paramref name="initializer"/>.
/// </summary>
/// <remarks>
/// <para>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </para>
/// <para>
/// <paramref name="initializer"/> returns an initialized specified typed
/// <see cref="WebSocketBehavior"/> instance.
/// </para>
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to add.
/// </param>
/// <param name="initializer">
/// A <c>Func<T></c> delegate that references the method used to initialize
/// a new specified typed <see cref="WebSocketBehavior"/> instance (a new
/// <see cref="IWebSocketSession"/> instance).
/// </param>
/// <typeparam name="TBehavior">
/// The type of the behavior of the service to add. The TBehavior must inherit
/// the <see cref="WebSocketBehavior"/> class.
/// </typeparam>
public void AddWebSocketService<TBehavior> (string path, Func<TBehavior> initializer)
where TBehavior : WebSocketBehavior
{
var msg = path.CheckIfValidServicePath () ??
(initializer == null ? "'initializer' is null." : null);
if (msg != null) {
_logger.Error (msg);
return;
}
_services.Add<TBehavior> (path, initializer);
}
/// <summary>
/// Adds a WebSocket service with the specified behavior and <paramref name="path"/>.
/// </summary>
/// <remarks>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to add.
/// </param>
/// <typeparam name="TBehaviorWithNew">
/// The type of the behavior of the service to add. The TBehaviorWithNew must inherit
/// the <see cref="WebSocketBehavior"/> class, and must have a public parameterless
/// constructor.
/// </typeparam>
public void AddWebSocketService<TBehaviorWithNew> (string path)
where TBehaviorWithNew : WebSocketBehavior, new ()
{
AddWebSocketService<TBehaviorWithNew> (path, () => new TBehaviorWithNew ());
}
/// <summary>
/// Gets the contents of the file with the specified <paramref name="path"/>.
/// </summary>
/// <returns>
/// An array of <see cref="byte"/> that receives the contents of the file,
/// or <see langword="null"/> if it doesn't exist.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents the virtual path to the file to find.
/// </param>
public byte[] GetFile (string path)
{
path = RootPath + path;
if (_windows)
path = path.Replace ("/", "\\");
return File.Exists (path) ? File.ReadAllBytes (path) : null;
}
/// <summary>
/// Removes the WebSocket service with the specified <paramref name="path"/>.
/// </summary>
/// <remarks>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </remarks>
/// <returns>
/// <c>true</c> if the service is successfully found and removed; otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to find.
/// </param>
public bool RemoveWebSocketService (string path)
{
var msg = path.CheckIfValidServicePath ();
if (msg != null) {
_logger.Error (msg);
return false;
}
return _services.Remove (path);
}
/// <summary>
/// Starts receiving the HTTP requests.
/// </summary>
public void Start ()
{
lock (_sync) {
var msg = _state.CheckIfStartable () ?? checkIfCertificateExists ();
if (msg != null) {
_logger.Error (msg);
return;
}
_services.Start ();
startReceiving ();
_state = ServerState.Start;
}
}
/// <summary>
/// Stops receiving the HTTP requests.
/// </summary>
public void Stop ()
{
lock (_sync) {
var msg = _state.CheckIfStart ();
if (msg != null) {
_logger.Error (msg);
return;
}
_state = ServerState.ShuttingDown;
}
_services.Stop (new CloseEventArgs (), true, true);
stopReceiving (5000);
_state = ServerState.Stop;
}
/// <summary>
/// Stops receiving the HTTP requests with the specified <see cref="ushort"/> and
/// <see cref="string"/> used to stop the WebSocket services.
/// </summary>
/// <param name="code">
/// A <see cref="ushort"/> that represents the status code indicating the reason for the stop.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for the stop.
/// </param>
public void Stop (ushort code, string reason)
{
lock (_sync) {
var msg = _state.CheckIfStart () ?? WebSocket.CheckCloseParameters (code, reason, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_state = ServerState.ShuttingDown;
}
if (code == (ushort) CloseStatusCode.NoStatus) {
_services.Stop (new CloseEventArgs (), true, true);
}
else {
var send = !code.IsReserved ();
_services.Stop (new CloseEventArgs (code, reason), send, send);
}
stopReceiving (5000);
_state = ServerState.Stop;
}
/// <summary>
/// Stops receiving the HTTP requests with the specified <see cref="CloseStatusCode"/> and
/// <see cref="string"/> used to stop the WebSocket services.
/// </summary>
/// <param name="code">
/// One of the <see cref="CloseStatusCode"/> enum values, represents the status code indicating
/// the reason for the stop.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for the stop.
/// </param>
public void Stop (CloseStatusCode code, string reason)
{
lock (_sync) {
var msg = _state.CheckIfStart () ?? WebSocket.CheckCloseParameters (code, reason, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_state = ServerState.ShuttingDown;
}
if (code == CloseStatusCode.NoStatus) {
_services.Stop (new CloseEventArgs (), true, true);
}
else {
var send = !code.IsReserved ();
_services.Stop (new CloseEventArgs (code, reason), send, send);
}
stopReceiving (5000);
_state = ServerState.Stop;
}
#endregion
}
}
| |
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 food_therapist.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;
}
}
}
| |
/*
* Unity VSCode Support
*
* Seamless support for Microsoft Visual Studio Code in Unity
*
* Version:
* 2.5
*
* Authors:
* Matthew Davey <matthew.davey@dotbunny.com>
*/
// REQUIRES: VSCode 0.8.0 - Settings directory moved to .vscode
// TODO: Currently VSCode will not debug mono on Windows -- need a solution.
namespace dotBunny.Unity
{
using System;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public static class VSCode
{
/// <summary>
/// Current Version Number
/// </summary>
public const float Version = 2.5f;
/// <summary>
/// Current Version Code
/// </summary>
public const string VersionCode = "-RELEASE";
/// <summary>
/// Download URL for Unity Debbuger
/// </summary>
public const string UnityDebuggerURL = "https://raw.githubusercontent.com/dotBunny/VSCode-Test/master/Downloads/unity-debug-101.vsix";
#region Properties
/// <summary>
/// Path to VSCode executable
public static string CodePath
{
get
{
#if UNITY_EDITOR_OSX
var newPath = "/Applications/Visual Studio Code.app";
#elif UNITY_EDITOR_WIN
var newPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar + "Code" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "code.cmd";
#else
var newPath = "/usr/local/bin/code";
#endif
return EditorPrefs.GetString("VSCode_CodePath", newPath);
}
set
{
EditorPrefs.SetString("VSCode_CodePath", value);
}
}
/// <summary>
/// Should debug information be displayed in the Unity terminal?
/// </summary>
public static bool Debug
{
get
{
return EditorPrefs.GetBool("VSCode_Debug", false);
}
set
{
EditorPrefs.SetBool("VSCode_Debug", value);
}
}
/// <summary>
/// Is the Visual Studio Code Integration Enabled?
/// </summary>
/// <remarks>
/// We do not want to automatically turn it on, for in larger projects not everyone is using VSCode
/// </remarks>
public static bool Enabled
{
get
{
return EditorPrefs.GetBool("VSCode_Enabled", false);
}
set
{
// When turning the plugin on, we should remove all the previous project files
if (!Enabled && value)
{
ClearProjectFiles();
}
EditorPrefs.SetBool("VSCode_Enabled", value);
}
}
public static bool UseUnityDebugger
{
get
{
return EditorPrefs.GetBool("VSCode_UseUnityDebugger", false);
}
set
{
if ( value != UseUnityDebugger ) {
// Set value
EditorPrefs.SetBool("VSCode_UseUnityDebugger", value);
// Do not write the launch JSON file because the debugger uses its own
if ( value ) {
WriteLaunchFile = false;
}
// Update launch file
UpdateLaunchFile();
}
}
}
/// <summary>
/// Should the launch.json file be written?
/// </summary>
/// <remarks>
/// Useful to disable if someone has their own custom one rigged up
/// </remarks>
public static bool WriteLaunchFile
{
get
{
return EditorPrefs.GetBool("VSCode_WriteLaunchFile", true);
}
set
{
EditorPrefs.SetBool("VSCode_WriteLaunchFile", value);
}
}
/// <summary>
/// Should the plugin automatically update itself.
/// </summary>
static bool AutomaticUpdates
{
get
{
return EditorPrefs.GetBool("VSCode_AutomaticUpdates", false);
}
set
{
EditorPrefs.SetBool("VSCode_AutomaticUpdates", value);
}
}
static float GitHubVersion
{
get
{
return EditorPrefs.GetFloat("VSCode_GitHubVersion", Version);
}
set
{
EditorPrefs.SetFloat("VSCode_GitHubVersion", value);
}
}
/// <summary>
/// When was the last time that the plugin was updated?
/// </summary>
static DateTime LastUpdate
{
get
{
// Feature creation date.
DateTime lastTime = new DateTime(2015, 10, 8);
if (EditorPrefs.HasKey("VSCode_LastUpdate"))
{
DateTime.TryParse(EditorPrefs.GetString("VSCode_LastUpdate"), out lastTime);
}
return lastTime;
}
set
{
EditorPrefs.SetString("VSCode_LastUpdate", value.ToString());
}
}
/// <summary>
/// Quick reference to the VSCode launch settings file
/// </summary>
static string LaunchPath
{
get
{
return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "launch.json";
}
}
/// <summary>
/// The full path to the project
/// </summary>
static string ProjectPath
{
get
{
return System.IO.Path.GetDirectoryName(UnityEngine.Application.dataPath);
}
}
/// <summary>
/// Should the script editor be reverted when quiting Unity.
/// </summary>
/// <remarks>
/// Useful for environments where you do not use VSCode for everything.
/// </remarks>
static bool RevertExternalScriptEditorOnExit
{
get
{
return EditorPrefs.GetBool("VSCode_RevertScriptEditorOnExit", true);
}
set
{
EditorPrefs.SetBool("VSCode_RevertScriptEditorOnExit", value);
}
}
/// <summary>
/// Quick reference to the VSCode settings folder
/// </summary>
static string SettingsFolder
{
get
{
return ProjectPath + System.IO.Path.DirectorySeparatorChar + ".vscode";
}
}
static string SettingsPath
{
get
{
return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "settings.json";
}
}
static int UpdateTime
{
get
{
return EditorPrefs.GetInt("VSCode_UpdateTime", 7);
}
set
{
EditorPrefs.SetInt("VSCode_UpdateTime", value);
}
}
#endregion
/// <summary>
/// Integration Constructor
/// </summary>
static VSCode()
{
if (Enabled)
{
UpdateUnityPreferences(true);
UpdateLaunchFile();
// Add Update Check
DateTime targetDate = LastUpdate.AddDays(UpdateTime);
if (DateTime.Now >= targetDate && AutomaticUpdates)
{
CheckForUpdate();
}
}
// Event for when script is reloaded
System.AppDomain.CurrentDomain.DomainUnload += System_AppDomain_CurrentDomain_DomainUnload;
}
static void System_AppDomain_CurrentDomain_DomainUnload(object sender, System.EventArgs e)
{
if (Enabled && RevertExternalScriptEditorOnExit)
{
UpdateUnityPreferences(false);
}
}
#region Public Members
/// <summary>
/// Force Unity To Write Project File
/// </summary>
/// <remarks>
/// Reflection!
/// </remarks>
public static void SyncSolution()
{
System.Type T = System.Type.GetType("UnityEditor.SyncVS,UnityEditor");
System.Reflection.MethodInfo SyncSolution = T.GetMethod("SyncSolution", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
SyncSolution.Invoke(null, null);
}
/// <summary>
/// Update the solution files so that they work with VS Code
/// </summary>
public static void UpdateSolution()
{
// No need to process if we are not enabled
if (!VSCode.Enabled)
{
return;
}
if (VSCode.Debug)
{
UnityEngine.Debug.Log("[VSCode] Updating Solution & Project Files");
}
var currentDirectory = Directory.GetCurrentDirectory();
var solutionFiles = Directory.GetFiles(currentDirectory, "*.sln");
var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj");
foreach (var filePath in solutionFiles)
{
string content = File.ReadAllText(filePath);
content = ScrubSolutionContent(content);
File.WriteAllText(filePath, content);
ScrubFile(filePath);
}
foreach (var filePath in projectFiles)
{
string content = File.ReadAllText(filePath);
content = ScrubProjectContent(content);
File.WriteAllText(filePath, content);
ScrubFile(filePath);
}
}
#endregion
#region Private Members
/// <summary>
/// Call VSCode with arguements
/// </summary>
static void CallVSCode(string args)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
#if UNITY_EDITOR_OSX
proc.StartInfo.FileName = "open";
proc.StartInfo.Arguments = " -n -b \"com.microsoft.VSCode\" --args " + args;
proc.StartInfo.UseShellExecute = false;
#elif UNITY_EDITOR_WIN
proc.StartInfo.FileName = CodePath;
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
#else
//TODO: Allow for manual path to code?
proc.StartInfo.FileName = CodePath;
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
#endif
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
}
/// <summary>
/// Check for Updates with GitHub
/// </summary>
static void CheckForUpdate()
{
var fileContent = string.Empty;
EditorUtility.DisplayProgressBar("VSCode", "Checking for updates ...", 0.5f);
// Because were not a runtime framework, lets just use the simplest way of doing this
try
{
using (var webClient = new System.Net.WebClient())
{
fileContent = webClient.DownloadString("https://raw.githubusercontent.com/dotBunny/VSCode/master/Plugins/Editor/VSCode.cs");
}
}
catch (Exception e)
{
if (Debug)
{
UnityEngine.Debug.Log("[VSCode] " + e.Message);
}
// Don't go any further if there is an error
return;
}
finally
{
EditorUtility.ClearProgressBar();
}
// Set the last update time
LastUpdate = DateTime.Now;
// Fix for oddity in downlo
if (fileContent.Substring(0, 2) != "/*")
{
int startPosition = fileContent.IndexOf("/*", StringComparison.CurrentCultureIgnoreCase);
// Jump over junk characters
fileContent = fileContent.Substring(startPosition);
}
string[] fileExploded = fileContent.Split('\n');
if (fileExploded.Length > 7)
{
float github = Version;
if (float.TryParse(fileExploded[6].Replace("*", "").Trim(), out github))
{
GitHubVersion = github;
}
if (github > Version)
{
var GUIDs = AssetDatabase.FindAssets("t:Script VSCode");
var path = Application.dataPath.Substring(0, Application.dataPath.Length - "/Assets".Length) + System.IO.Path.DirectorySeparatorChar +
AssetDatabase.GUIDToAssetPath(GUIDs[0]).Replace('/', System.IO.Path.DirectorySeparatorChar);
if (EditorUtility.DisplayDialog("VSCode Update", "A newer version of the VSCode plugin is available, would you like to update your version?", "Yes", "No"))
{
// Always make sure the file is writable
System.IO.FileInfo fileInfo = new System.IO.FileInfo(path);
fileInfo.IsReadOnly = false;
// Write update file
File.WriteAllText(path, fileContent);
// Force update on text file
AssetDatabase.ImportAsset(AssetDatabase.GUIDToAssetPath(GUIDs[0]), ImportAssetOptions.ForceUpdate);
}
}
}
}
/// <summary>
/// Clear out any existing project files and lingering stuff that might cause problems
/// </summary>
static void ClearProjectFiles()
{
var currentDirectory = Directory.GetCurrentDirectory();
var solutionFiles = Directory.GetFiles(currentDirectory, "*.sln");
var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj");
var unityProjectFiles = Directory.GetFiles(currentDirectory, "*.unityproj");
foreach (string solutionFile in solutionFiles)
{
File.Delete(solutionFile);
}
foreach (string projectFile in projectFiles)
{
File.Delete(projectFile);
}
foreach (string unityProjectFile in unityProjectFiles)
{
File.Delete(unityProjectFile);
}
// Replace with our clean files (only in Unity 5)
#if !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5 && !UNITY_4_6 && !UNITY_4_7
SyncSolution();
#endif
}
/// <summary>
/// Force Unity Preferences Window To Read From Settings
/// </summary>
static void FixUnityPreferences()
{
// I want that window, please and thank you
System.Type T = System.Type.GetType("UnityEditor.PreferencesWindow,UnityEditor");
if (EditorWindow.focusedWindow == null)
return;
// Only run this when the editor window is visible (cause its what screwed us up)
if (EditorWindow.focusedWindow.GetType() == T)
{
var window = EditorWindow.GetWindow(T, true, "Unity Preferences");
if (window == null)
{
if (Debug)
{
UnityEngine.Debug.Log("[VSCode] No Preferences Window Found (really?)");
}
return;
}
var invokerType = window.GetType();
var invokerMethod = invokerType.GetMethod("ReadPreferences",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (invokerMethod != null)
{
invokerMethod.Invoke(window, null);
}
else if (Debug)
{
UnityEngine.Debug.Log("[VSCode] No Reflection Method Found For Preferences");
}
}
// // Get internal integration class
// System.Type iT = System.Type.GetType("UnityEditor.VisualStudioIntegration.UnityVSSupport,UnityEditor.VisualStudioIntegration");
// var iinvokerMethod = iT.GetMethod("ScriptEditorChanged", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
// var temp = EditorPrefs.GetString("kScriptsDefaultApp");
// iinvokerMethod.Invoke(null,new object[] { temp } );
}
/// <summary>
/// Determine what port Unity is listening for on Windows
/// </summary>
static int GetDebugPort()
{
#if UNITY_EDITOR_WIN
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "netstat";
process.StartInfo.Arguments = "-a -n -o -p TCP";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
string[] lines = output.Split('\n');
process.WaitForExit();
foreach (string line in lines)
{
string[] tokens = Regex.Split(line, "\\s+");
if (tokens.Length > 4)
{
int test = -1;
int.TryParse(tokens[5], out test);
if (test > 1023)
{
try
{
var p = System.Diagnostics.Process.GetProcessById(test);
if (p.ProcessName == "Unity")
{
return test;
}
}
catch
{
}
}
}
}
#else
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "lsof";
process.StartInfo.Arguments = "-c /^Unity$/ -i 4tcp -a";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
// Not thread safe (yet!)
string output = process.StandardOutput.ReadToEnd();
string[] lines = output.Split('\n');
process.WaitForExit();
foreach (string line in lines)
{
int port = -1;
if (line.StartsWith("Unity"))
{
string[] portions = line.Split(new string[] { "TCP *:" }, System.StringSplitOptions.None);
if (portions.Length >= 2)
{
Regex digitsOnly = new Regex(@"[^\d]");
string cleanPort = digitsOnly.Replace(portions[1], "");
if (int.TryParse(cleanPort, out port))
{
if (port > -1)
{
return port;
}
}
}
}
}
#endif
return -1;
}
static void InstallUnityDebugger()
{
EditorUtility.DisplayProgressBar("VSCode", "Downloading Unity Debugger ...", 0.1f);
byte[] fileContent;
try
{
using (var webClient = new System.Net.WebClient())
{
fileContent = webClient.DownloadData(UnityDebuggerURL);
}
}
catch (Exception e)
{
if (Debug)
{
UnityEngine.Debug.Log("[VSCode] " + e.Message);
}
// Don't go any further if there is an error
return;
}
finally
{
EditorUtility.ClearProgressBar();
}
// Do we have a file to install?
if ( fileContent != null ) {
string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".vsix";
File.WriteAllBytes(fileName, fileContent);
CallVSCode(fileName);
}
}
// HACK: This is in until Unity can figure out why MD keeps opening even though a different program is selected.
[MenuItem("Assets/Open C# Project In Code", false, 1000)]
static void MenuOpenProject()
{
// Force the project files to be sync
SyncSolution();
// Load Project
CallVSCode("\"" + ProjectPath + "\" -r");
}
[MenuItem("Assets/Open C# Project In Code", true, 1000)]
static bool ValidateMenuOpenProject()
{
return Enabled;
}
/// <summary>
/// VS Code Integration Preferences Item
/// </summary>
/// <remarks>
/// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off
/// </remarks>
[PreferenceItem("VSCode")]
static void VSCodePreferencesItem()
{
if (EditorApplication.isCompiling)
{
EditorGUILayout.HelpBox("Please wait for Unity to finish compiling. \nIf the window doesn't refresh, simply click on the window or move it around to cause a repaint to happen.", MessageType.Warning);
return;
}
EditorGUILayout.BeginVertical();
EditorGUILayout.HelpBox("Support development of this plugin, follow @reapazor and @dotbunny on Twitter.", MessageType.Info);
EditorGUI.BeginChangeCheck();
Enabled = EditorGUILayout.Toggle(new GUIContent("Enable Integration", "Should the integration work its magic for you?"), Enabled);
#if UNITY_5_3_OR_NEWER
CodePath = EditorGUILayout.DelayedTextField(new GUIContent("VS Code Path", "Full path to the Micosoft Visual Studio code executable."), CodePath);
#else
CodePath = EditorGUILayout.TextField(new GUIContent("VS Code Path", "Full path to the Micosoft Visual Studio code executable."), CodePath);
#endif
UseUnityDebugger = EditorGUILayout.Toggle(new GUIContent("Use Unity Debugger", "Should the integration integrate with Unity's VSCode Extension (must be installed)."), UseUnityDebugger);
EditorGUILayout.Space();
RevertExternalScriptEditorOnExit = EditorGUILayout.Toggle(new GUIContent("Revert Script Editor On Unload", "Should the external script editor setting be reverted to its previous setting on project unload? This is useful if you do not use Code with all your projects."),RevertExternalScriptEditorOnExit);
Debug = EditorGUILayout.Toggle(new GUIContent("Output Messages To Console", "Should informational messages be sent to Unity's Console?"), Debug);
WriteLaunchFile = EditorGUILayout.Toggle(new GUIContent("Always Write Launch File", "Always write the launch.json settings when entering play mode?"), WriteLaunchFile);
EditorGUILayout.Space();
AutomaticUpdates = EditorGUILayout.Toggle(new GUIContent("Automatic Updates", "Should the plugin automatically update itself?"), AutomaticUpdates);
UpdateTime = EditorGUILayout.IntSlider(new GUIContent("Update Timer (Days)", "After how many days should updates be checked for?"), UpdateTime, 1, 31);
EditorGUILayout.Space();
EditorGUILayout.Space();
if (EditorGUI.EndChangeCheck())
{
UpdateUnityPreferences(Enabled);
//UnityEditor.PreferencesWindow.Read
// TODO: Force Unity To Reload Preferences
// This seems to be a hick up / issue
if (VSCode.Debug)
{
if (Enabled)
{
UnityEngine.Debug.Log("[VSCode] Integration Enabled");
}
else
{
UnityEngine.Debug.Log("[VSCode] Integration Disabled");
}
}
}
if (GUILayout.Button(new GUIContent("Force Update", "Check for updates to the plugin, right NOW!")))
{
CheckForUpdate();
EditorGUILayout.EndVertical();
return;
}
if (GUILayout.Button(new GUIContent("Write Workspace Settings", "Output a default set of workspace settings for VSCode to use, ignoring many different types of files.")))
{
WriteWorkspaceSettings();
EditorGUILayout.EndVertical();
return;
}
EditorGUILayout.Space();
if (UseUnityDebugger)
{
EditorGUILayout.HelpBox("In order for the \"Use Unity Debuggger\" option to function above, you need to have installed the Unity Debugger Extension for Visual Studio Code. You can do this by simply clicking the button below and it will take care of the rest.", MessageType.Warning);
if (GUILayout.Button(new GUIContent("Install Unity Debugger", "Install the Unity Debugger Extension into Code")))
{
InstallUnityDebugger();
EditorGUILayout.EndVertical();
return;
}
}
GUILayout.FlexibleSpace();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(
new GUIContent(
string.Format("{0:0.00}", Version) + VersionCode,
"GitHub's Version @ " + string.Format("{0:0.00}", GitHubVersion)));
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
}
/// <summary>
/// Asset Open Callback (from Unity)
/// </summary>
/// <remarks>
/// Called when Unity is about to open an asset.
/// </remarks>
[UnityEditor.Callbacks.OnOpenAssetAttribute()]
static bool OnOpenedAsset(int instanceID, int line)
{
// bail out if we are not using VSCode
if (!Enabled)
{
return false;
}
// current path without the asset folder
string appPath = ProjectPath;
// determine asset that has been double clicked in the project view
UnityEngine.Object selected = EditorUtility.InstanceIDToObject(instanceID);
if (selected.GetType().ToString() == "UnityEditor.MonoScript")
{
string completeFilepath = appPath + Path.DirectorySeparatorChar + AssetDatabase.GetAssetPath(selected);
string args = null;
if (line == -1)
{
args = "\"" + ProjectPath + "\" \"" + completeFilepath + "\" -r";
}
else
{
args = "\"" + ProjectPath + "\" -g \"" + completeFilepath + ":" + line.ToString() + "\" -r";
}
// call 'open'
CallVSCode(args);
return true;
}
// Didnt find a code file? let Unity figure it out
return false;
}
/// <summary>
/// Executed when the Editor's playmode changes allowing for capture of required data
/// </summary>
static void OnPlaymodeStateChanged()
{
if (UnityEngine.Application.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode)
{
UpdateLaunchFile();
}
}
/// <summary>
/// Detect when scripts are reloaded and relink playmode detection
/// </summary>
[UnityEditor.Callbacks.DidReloadScripts()]
static void OnScriptReload()
{
EditorApplication.playmodeStateChanged -= OnPlaymodeStateChanged;
EditorApplication.playmodeStateChanged += OnPlaymodeStateChanged;
}
/// <summary>
/// Remove extra/erroneous lines from a file.
static void ScrubFile(string path)
{
string[] lines = File.ReadAllLines(path);
System.Collections.Generic.List<string> newLines = new System.Collections.Generic.List<string>();
for (int i = 0; i < lines.Length; i++)
{
// Check Empty
if (string.IsNullOrEmpty(lines[i].Trim()) || lines[i].Trim() == "\t" || lines[i].Trim() == "\t\t")
{
}
else
{
newLines.Add(lines[i]);
}
}
File.WriteAllLines(path, newLines.ToArray());
}
/// <summary>
/// Remove extra/erroneous data from project file (content).
/// </summary>
static string ScrubProjectContent(string content)
{
if (content.Length == 0)
return "";
// Note: it causes OmniSharp faults on Windows, such as "not seeing UnityEngine.UI". 3.5 target works fine
#if !UNITY_EDITOR_WIN
// Make sure our reference framework is 2.0, still the base for Unity
if (content.IndexOf("<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>") != -1)
{
content = Regex.Replace(content, "<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>", "<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>");
}
#endif
string targetPath = "";// "<TargetPath>Temp" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "</TargetPath>"; //OutputPath
string langVersion = "<LangVersion>default</LangVersion>";
bool found = true;
int location = 0;
string addedOptions = "";
int startLocation = -1;
int endLocation = -1;
int endLength = 0;
while (found)
{
startLocation = -1;
endLocation = -1;
endLength = 0;
addedOptions = "";
startLocation = content.IndexOf("<PropertyGroup", location);
if (startLocation != -1)
{
endLocation = content.IndexOf("</PropertyGroup>", startLocation);
endLength = (endLocation - startLocation);
if (endLocation == -1)
{
found = false;
continue;
}
else
{
found = true;
location = endLocation;
}
if (content.Substring(startLocation, endLength).IndexOf("<TargetPath>") == -1)
{
addedOptions += "\n\r\t" + targetPath + "\n\r";
}
if (content.Substring(startLocation, endLength).IndexOf("<LangVersion>") == -1)
{
addedOptions += "\n\r\t" + langVersion + "\n\r";
}
if (!string.IsNullOrEmpty(addedOptions))
{
content = content.Substring(0, endLocation) + addedOptions + content.Substring(endLocation);
}
}
else
{
found = false;
}
}
return content;
}
/// <summary>
/// Remove extra/erroneous data from solution file (content).
/// </summary>
static string ScrubSolutionContent(string content)
{
// Replace Solution Version
content = content.Replace(
"Microsoft Visual Studio Solution File, Format Version 11.00\r\n# Visual Studio 2008\r\n",
"\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio 2012");
// Remove Solution Properties (Unity Junk)
int startIndex = content.IndexOf("GlobalSection(SolutionProperties) = preSolution");
if (startIndex != -1)
{
int endIndex = content.IndexOf("EndGlobalSection", startIndex);
content = content.Substring(0, startIndex) + content.Substring(endIndex + 16);
}
return content;
}
/// <summary>
/// Update Visual Studio Code Launch file
/// </summary>
static void UpdateLaunchFile()
{
if ( !VSCode.Enabled ) return;
else if ( VSCode.UseUnityDebugger ) {
if (!Directory.Exists(VSCode.SettingsFolder))
System.IO.Directory.CreateDirectory(VSCode.SettingsFolder);
// Write out proper formatted JSON (hence no more SimpleJSON here)
string fileContent = "{\n\t\"version\": \"0.2.0\",\n\t\"configurations\": [\n\t\t{\n\t\t\t\"name\": \"Unity Editor\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Windows Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"OSX Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Linux Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"iOS Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Android Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\n\t\t}\n\t]\n}";
File.WriteAllText(VSCode.LaunchPath, fileContent);
}
else if (VSCode.WriteLaunchFile)
{
int port = GetDebugPort();
if (port > -1)
{
if (!Directory.Exists(VSCode.SettingsFolder))
System.IO.Directory.CreateDirectory(VSCode.SettingsFolder);
// Write out proper formatted JSON (hence no more SimpleJSON here)
string fileContent = "{\n\t\"version\":\"0.2.0\",\n\t\"configurations\":[ \n\t\t{\n\t\t\t\"name\":\"Unity\",\n\t\t\t\"type\":\"mono\",\n\t\t\t\"request\":\"attach\",\n\t\t\t\"address\":\"localhost\",\n\t\t\t\"port\":" + port + "\n\t\t}\n\t]\n}";
File.WriteAllText(VSCode.LaunchPath, fileContent);
if (VSCode.Debug)
{
UnityEngine.Debug.Log("[VSCode] Debug Port Found (" + port + ")");
}
}
else
{
if (VSCode.Debug)
{
UnityEngine.Debug.LogWarning("[VSCode] Unable to determine debug port.");
}
}
}
}
/// <summary>
/// Update Unity Editor Preferences
static void UpdateUnityPreferences(bool enabled)
{
if (enabled)
{
// App
if (EditorPrefs.GetString("kScriptsDefaultApp") != CodePath)
{
EditorPrefs.SetString("VSCode_PreviousApp", EditorPrefs.GetString("kScriptsDefaultApp"));
}
EditorPrefs.SetString("kScriptsDefaultApp", CodePath);
// Arguments
if (EditorPrefs.GetString("kScriptEditorArgs") != "-r -g \"$(File):$(Line)\"")
{
EditorPrefs.SetString("VSCode_PreviousArgs", EditorPrefs.GetString("kScriptEditorArgs"));
}
EditorPrefs.SetString("kScriptEditorArgs", "-r -g \"$(File):$(Line)\"");
EditorPrefs.SetString("kScriptEditorArgs" + CodePath, "-r -g \"$(File):$(Line)\"");
// MonoDevelop Solution
if (EditorPrefs.GetBool("kMonoDevelopSolutionProperties", false))
{
EditorPrefs.SetBool("VSCode_PreviousMD", true);
}
EditorPrefs.SetBool("kMonoDevelopSolutionProperties", false);
// Support Unity Proj (JS)
if (EditorPrefs.GetBool("kExternalEditorSupportsUnityProj", false))
{
EditorPrefs.SetBool("VSCode_PreviousUnityProj", true);
}
EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", false);
if (!EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", false))
{
EditorPrefs.SetBool("VSCode_PreviousAttach", false);
}
EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", true);
}
else
{
// Restore previous app
if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousApp")))
{
EditorPrefs.SetString("kScriptsDefaultApp", EditorPrefs.GetString("VSCode_PreviousApp"));
}
// Restore previous args
if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousArgs")))
{
EditorPrefs.SetString("kScriptEditorArgs", EditorPrefs.GetString("VSCode_PreviousArgs"));
}
// Restore MD setting
if (EditorPrefs.GetBool("VSCode_PreviousMD", false))
{
EditorPrefs.SetBool("kMonoDevelopSolutionProperties", true);
}
// Restore MD setting
if (EditorPrefs.GetBool("VSCode_PreviousUnityProj", false))
{
EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", true);
}
// Always leave editor attaching on, I know, it solves the problem of needing to restart for this
// to actually work
EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", true);
}
FixUnityPreferences();
}
/// <summary>
/// Write Default Workspace Settings
/// </summary>
static void WriteWorkspaceSettings()
{
if (Debug)
{
UnityEngine.Debug.Log("[VSCode] Workspace Settings Written");
}
if (!Directory.Exists(VSCode.SettingsFolder))
{
System.IO.Directory.CreateDirectory(VSCode.SettingsFolder);
}
string exclusions =
"{\n" +
"\t\"files.exclude\":\n" +
"\t{\n" +
// Hidden Files
"\t\t\"**/.DS_Store\":true,\n" +
"\t\t\"**/.git\":true,\n" +
"\t\t\"**/.gitignore\":true,\n" +
"\t\t\"**/.gitattributes\":true,\n" +
"\t\t\"**/.gitmodules\":true,\n" +
"\t\t\"**/.svn\":true,\n" +
// Project Files
"\t\t\"**/*.booproj\":true,\n" +
"\t\t\"**/*.pidb\":true,\n" +
"\t\t\"**/*.suo\":true,\n" +
"\t\t\"**/*.user\":true,\n" +
"\t\t\"**/*.userprefs\":true,\n" +
"\t\t\"**/*.unityproj\":true,\n" +
"\t\t\"**/*.dll\":true,\n" +
"\t\t\"**/*.exe\":true,\n" +
// Media Files
"\t\t\"**/*.pdf\":true,\n" +
// Audio
"\t\t\"**/*.mid\":true,\n" +
"\t\t\"**/*.midi\":true,\n" +
"\t\t\"**/*.wav\":true,\n" +
// Textures
"\t\t\"**/*.gif\":true,\n" +
"\t\t\"**/*.ico\":true,\n" +
"\t\t\"**/*.jpg\":true,\n" +
"\t\t\"**/*.jpeg\":true,\n" +
"\t\t\"**/*.png\":true,\n" +
"\t\t\"**/*.psd\":true,\n" +
"\t\t\"**/*.tga\":true,\n" +
"\t\t\"**/*.tif\":true,\n" +
"\t\t\"**/*.tiff\":true,\n" +
// Models
"\t\t\"**/*.3ds\":true,\n" +
"\t\t\"**/*.3DS\":true,\n" +
"\t\t\"**/*.fbx\":true,\n" +
"\t\t\"**/*.FBX\":true,\n" +
"\t\t\"**/*.lxo\":true,\n" +
"\t\t\"**/*.LXO\":true,\n" +
"\t\t\"**/*.ma\":true,\n" +
"\t\t\"**/*.MA\":true,\n" +
"\t\t\"**/*.obj\":true,\n" +
"\t\t\"**/*.OBJ\":true,\n" +
// Unity File Types
"\t\t\"**/*.asset\":true,\n" +
"\t\t\"**/*.cubemap\":true,\n" +
"\t\t\"**/*.flare\":true,\n" +
"\t\t\"**/*.mat\":true,\n" +
"\t\t\"**/*.meta\":true,\n" +
"\t\t\"**/*.prefab\":true,\n" +
"\t\t\"**/*.unity\":true,\n" +
// Folders
"\t\t\"build/\":true,\n" +
"\t\t\"Build/\":true,\n" +
"\t\t\"Library/\":true,\n" +
"\t\t\"library/\":true,\n" +
"\t\t\"obj/\":true,\n" +
"\t\t\"Obj/\":true,\n" +
"\t\t\"ProjectSettings/\":true,\r" +
"\t\t\"temp/\":true,\n" +
"\t\t\"Temp/\":true\n" +
"\t}\n" +
"}";
// Dont like the replace but it fixes the issue with the JSON
File.WriteAllText(VSCode.SettingsPath, exclusions);
}
#endregion
}
/// <summary>
/// VSCode Asset AssetPostprocessor
/// <para>This will ensure any time that the project files are generated the VSCode versions will be made</para>
/// </summary>
/// <remarks>Undocumented Event</remarks>
public class VSCodeAssetPostprocessor : AssetPostprocessor
{
/// <summary>
/// On documented, project generation event callback
/// </summary>
private static void OnGeneratedCSProjectFiles()
{
// Force execution of VSCode update
VSCode.UpdateSolution();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Diagnostics {
using System;
using System.Collections;
using System.Text;
using System.Threading;
using System.Security;
using System.Security.Permissions;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
// READ ME:
// Modifying the order or fields of this object may require other changes
// to the unmanaged definition of the StackFrameHelper class, in
// VM\DebugDebugger.h. The binder will catch some of these layout problems.
[Serializable]
internal class StackFrameHelper : IDisposable
{
[NonSerialized]
private Thread targetThread;
private int[] rgiOffset;
private int[] rgiILOffset;
// this field is here only for backwards compatibility of serialization format
private MethodBase[] rgMethodBase;
#pragma warning disable 414 // Field is not used from managed.
// dynamicMethods is an array of System.Resolver objects, used to keep
// DynamicMethodDescs alive for the lifetime of StackFrameHelper.
private Object dynamicMethods;
#pragma warning restore 414
[NonSerialized]
private IntPtr[] rgMethodHandle;
private String[] rgAssemblyPath;
private IntPtr[] rgLoadedPeAddress;
private int[] rgiLoadedPeSize;
private IntPtr[] rgInMemoryPdbAddress;
private int[] rgiInMemoryPdbSize;
// if rgiMethodToken[i] == 0, then don't attempt to get the portable PDB source/info
private int[] rgiMethodToken;
private String[] rgFilename;
private int[] rgiLineNumber;
private int[] rgiColumnNumber;
#if FEATURE_EXCEPTIONDISPATCHINFO
[OptionalField]
private bool[] rgiLastFrameFromForeignExceptionStackTrace;
#endif // FEATURE_EXCEPTIONDISPATCHINFO
private GetSourceLineInfoDelegate getSourceLineInfo;
private int iFrameCount;
private delegate void GetSourceLineInfoDelegate(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize,
IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset,
out string sourceFile, out int sourceLine, out int sourceColumn);
private static Type s_symbolsType = null;
private static MethodInfo s_symbolsMethodInfo = null;
[ThreadStatic]
private static int t_reentrancy = 0;
public StackFrameHelper(Thread target)
{
targetThread = target;
rgMethodBase = null;
rgMethodHandle = null;
rgiMethodToken = null;
rgiOffset = null;
rgiILOffset = null;
rgAssemblyPath = null;
rgLoadedPeAddress = null;
rgiLoadedPeSize = null;
rgInMemoryPdbAddress = null;
rgiInMemoryPdbSize = null;
dynamicMethods = null;
rgFilename = null;
rgiLineNumber = null;
rgiColumnNumber = null;
getSourceLineInfo = null;
#if FEATURE_EXCEPTIONDISPATCHINFO
rgiLastFrameFromForeignExceptionStackTrace = null;
#endif // FEATURE_EXCEPTIONDISPATCHINFO
// 0 means capture all frames. For StackTraces from an Exception, the EE always
// captures all frames. For other uses of StackTraces, we can abort stack walking after
// some limit if we want to by setting this to a non-zero value. In Whidbey this was
// hard-coded to 512, but some customers complained. There shouldn't be any need to limit
// this as memory/CPU is no longer allocated up front. If there is some reason to provide a
// limit in the future, then we should expose it in the managed API so applications can
// override it.
iFrameCount = 0;
}
//
// Initializes the stack trace helper. If fNeedFileInfo is true, initializes rgFilename,
// rgiLineNumber and rgiColumnNumber fields using the portable PDB reader if not already
// done by GetStackFramesInternal (on Windows for old PDB format).
//
internal void InitializeSourceInfo(int iSkip, bool fNeedFileInfo, Exception exception)
{
StackTrace.GetStackFramesInternal(this, iSkip, fNeedFileInfo, exception);
if (!fNeedFileInfo)
return;
// Check if this function is being reentered because of an exception in the code below
if (t_reentrancy > 0)
return;
t_reentrancy++;
try
{
if (s_symbolsMethodInfo == null)
{
s_symbolsType = Type.GetType("System.Diagnostics.StackTraceSymbols, System.Diagnostics.StackTrace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
if (s_symbolsType == null)
return;
s_symbolsMethodInfo = s_symbolsType.GetMethod("GetSourceLineInfo");
if (s_symbolsMethodInfo == null)
return;
}
if (getSourceLineInfo == null)
{
// Create an instance of System.Diagnostics.Stacktrace.Symbols
object target = Activator.CreateInstance(s_symbolsType);
// Create an instance delegate for the GetSourceLineInfo method
getSourceLineInfo = (GetSourceLineInfoDelegate)s_symbolsMethodInfo.CreateDelegate(typeof(GetSourceLineInfoDelegate), target);
}
for (int index = 0; index < iFrameCount; index++)
{
// If there was some reason not to try get get the symbols from the portable PDB reader like the module was
// ENC or the source/line info was already retrieved, the method token is 0.
if (rgiMethodToken[index] != 0)
{
getSourceLineInfo(rgAssemblyPath[index], rgLoadedPeAddress[index], rgiLoadedPeSize[index],
rgInMemoryPdbAddress[index], rgiInMemoryPdbSize[index], rgiMethodToken[index],
rgiILOffset[index], out rgFilename[index], out rgiLineNumber[index], out rgiColumnNumber[index]);
}
}
}
finally
{
t_reentrancy--;
}
}
void IDisposable.Dispose()
{
if (getSourceLineInfo != null)
{
IDisposable disposable = getSourceLineInfo.Target as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
[System.Security.SecuritySafeCritical]
public virtual MethodBase GetMethodBase(int i)
{
// There may be a better way to do this.
// we got RuntimeMethodHandles here and we need to go to MethodBase
// but we don't know whether the reflection info has been initialized
// or not. So we call GetMethods and GetConstructors on the type
// and then we fetch the proper MethodBase!!
IntPtr mh = rgMethodHandle[i];
if (mh.IsNull())
return null;
IRuntimeMethodInfo mhReal = RuntimeMethodHandle.GetTypicalMethodDefinition(new RuntimeMethodInfoStub(mh, this));
return RuntimeType.GetMethodBase(mhReal);
}
public virtual int GetOffset(int i) { return rgiOffset[i];}
public virtual int GetILOffset(int i) { return rgiILOffset[i];}
public virtual String GetFilename(int i) { return rgFilename == null ? null : rgFilename[i];}
public virtual int GetLineNumber(int i) { return rgiLineNumber == null ? 0 : rgiLineNumber[i];}
public virtual int GetColumnNumber(int i) { return rgiColumnNumber == null ? 0 : rgiColumnNumber[i];}
#if FEATURE_EXCEPTIONDISPATCHINFO
public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i)
{
return (rgiLastFrameFromForeignExceptionStackTrace == null)?false:rgiLastFrameFromForeignExceptionStackTrace[i];
}
#endif // FEATURE_EXCEPTIONDISPATCHINFO
public virtual int GetNumberOfFrames() { return iFrameCount;}
public virtual void SetNumberOfFrames(int i) { iFrameCount = i;}
//
// serialization implementation
//
[OnSerializing]
[SecuritySafeCritical]
void OnSerializing(StreamingContext context)
{
// this is called in the process of serializing this object.
// For compatibility with Everett we need to assign the rgMethodBase field as that is the field
// that will be serialized
rgMethodBase = (rgMethodHandle == null) ? null : new MethodBase[rgMethodHandle.Length];
if (rgMethodHandle != null)
{
for (int i = 0; i < rgMethodHandle.Length; i++)
{
if (!rgMethodHandle[i].IsNull())
rgMethodBase[i] = RuntimeType.GetMethodBase(new RuntimeMethodInfoStub(rgMethodHandle[i], this));
}
}
}
[OnSerialized]
void OnSerialized(StreamingContext context)
{
// after we are done serializing null the rgMethodBase field
rgMethodBase = null;
}
[OnDeserialized]
[SecuritySafeCritical]
void OnDeserialized(StreamingContext context)
{
// after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle
rgMethodHandle = (rgMethodBase == null) ? null : new IntPtr[rgMethodBase.Length];
if (rgMethodBase != null)
{
for (int i = 0; i < rgMethodBase.Length; i++)
{
if (rgMethodBase[i] != null)
rgMethodHandle[i] = rgMethodBase[i].MethodHandle.Value;
}
}
rgMethodBase = null;
}
}
// Class which represents a description of a stack trace
// There is no good reason for the methods of this class to be virtual.
// In order to ensure trusted code can trust the data it gets from a
// StackTrace, we use an InheritanceDemand to prevent partially-trusted
// subclasses.
#if !FEATURE_CORECLR
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
#endif
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StackTrace
{
private StackFrame[] frames;
private int m_iNumOfFrames;
public const int METHODS_TO_SKIP = 0;
private int m_iMethodsToSkip;
// Constructs a stack trace from the current location.
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
public StackTrace()
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, false, null, null);
}
// Constructs a stack trace from the current location.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(bool fNeedFileInfo)
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, null);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(int skipFrames)
{
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, null);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(int skipFrames, bool fNeedFileInfo)
{
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, null);
}
// Constructs a stack trace from the current location.
public StackTrace(Exception e)
{
if (e == null)
throw new ArgumentNullException("e");
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, false, null, e);
}
// Constructs a stack trace from the current location.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(Exception e, bool fNeedFileInfo)
{
if (e == null)
throw new ArgumentNullException("e");
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, e);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(Exception e, int skipFrames)
{
if (e == null)
throw new ArgumentNullException("e");
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, e);
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo)
{
if (e == null)
throw new ArgumentNullException("e");
if (skipFrames < 0)
throw new ArgumentOutOfRangeException("skipFrames",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, e);
}
// Constructs a "fake" stack trace, just containing a single frame.
// Does not have the overhead of a full stack trace.
//
public StackTrace(StackFrame frame)
{
frames = new StackFrame[1];
frames[0] = frame;
m_iMethodsToSkip = 0;
m_iNumOfFrames = 1;
}
// Constructs a stack trace for the given thread
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
[Obsolete("This constructor has been deprecated. Please use a constructor that does not require a Thread parameter. http://go.microsoft.com/fwlink/?linkid=14202")]
public StackTrace(Thread targetThread, bool needFileInfo)
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, needFileInfo, targetThread, null);
}
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, bool fNeedFileInfo, Exception e);
internal static int CalculateFramesToSkip(StackFrameHelper StackF, int iNumFrames)
{
int iRetVal = 0;
String PackageName = "System.Diagnostics";
// Check if this method is part of the System.Diagnostics
// package. If so, increment counter keeping track of
// System.Diagnostics functions
for (int i = 0; i < iNumFrames; i++)
{
MethodBase mb = StackF.GetMethodBase(i);
if (mb != null)
{
Type t = mb.DeclaringType;
if (t == null)
break;
String ns = t.Namespace;
if (ns == null)
break;
if (String.Compare(ns, PackageName, StringComparison.Ordinal) != 0)
break;
}
iRetVal++;
}
return iRetVal;
}
// Retrieves an object with stack trace information encoded.
// It leaves out the first "iSkip" lines of the stacktrace.
//
private void CaptureStackTrace(int iSkip, bool fNeedFileInfo, Thread targetThread, Exception e)
{
m_iMethodsToSkip += iSkip;
using (StackFrameHelper StackF = new StackFrameHelper(targetThread))
{
StackF.InitializeSourceInfo(0, fNeedFileInfo, e);
m_iNumOfFrames = StackF.GetNumberOfFrames();
if (m_iMethodsToSkip > m_iNumOfFrames)
m_iMethodsToSkip = m_iNumOfFrames;
if (m_iNumOfFrames != 0)
{
frames = new StackFrame[m_iNumOfFrames];
for (int i = 0; i < m_iNumOfFrames; i++)
{
bool fDummy1 = true;
bool fDummy2 = true;
StackFrame sfTemp = new StackFrame(fDummy1, fDummy2);
sfTemp.SetMethodBase(StackF.GetMethodBase(i));
sfTemp.SetOffset(StackF.GetOffset(i));
sfTemp.SetILOffset(StackF.GetILOffset(i));
#if FEATURE_EXCEPTIONDISPATCHINFO
sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i));
#endif // FEATURE_EXCEPTIONDISPATCHINFO
if (fNeedFileInfo)
{
sfTemp.SetFileName(StackF.GetFilename(i));
sfTemp.SetLineNumber(StackF.GetLineNumber(i));
sfTemp.SetColumnNumber(StackF.GetColumnNumber(i));
}
frames[i] = sfTemp;
}
// CalculateFramesToSkip skips all frames in the System.Diagnostics namespace,
// but this is not desired if building a stack trace from an exception.
if (e == null)
m_iMethodsToSkip += CalculateFramesToSkip(StackF, m_iNumOfFrames);
m_iNumOfFrames -= m_iMethodsToSkip;
if (m_iNumOfFrames < 0)
{
m_iNumOfFrames = 0;
}
}
// In case this is the same object being re-used, set frames to null
else
frames = null;
}
}
// Property to get the number of frames in the stack trace
//
public virtual int FrameCount
{
get { return m_iNumOfFrames;}
}
// Returns a given stack frame. Stack frames are numbered starting at
// zero, which is the last stack frame pushed.
//
public virtual StackFrame GetFrame(int index)
{
if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0))
return frames[index+m_iMethodsToSkip];
return null;
}
// Returns an array of all stack frames for this stacktrace.
// The array is ordered and sized such that GetFrames()[i] == GetFrame(i)
// The nth element of this array is the same as GetFrame(n).
// The length of the array is the same as FrameCount.
//
[ComVisible(false)]
public virtual StackFrame [] GetFrames()
{
if (frames == null || m_iNumOfFrames <= 0)
return null;
// We have to return a subset of the array. Unfortunately this
// means we have to allocate a new array and copy over.
StackFrame [] array = new StackFrame[m_iNumOfFrames];
Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames);
return array;
}
// Builds a readable representation of the stack trace
//
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
public override String ToString()
{
// Include a trailing newline for backwards compatibility
return ToString(TraceFormat.TrailingNewLine);
}
// TraceFormat is Used to specify options for how the
// string-representation of a StackTrace should be generated.
internal enum TraceFormat
{
Normal,
TrailingNewLine, // include a trailing new line character
NoResourceLookup // to prevent infinite resource recusion
}
// Builds a readable representation of the stack trace, specifying
// the format for backwards compatibility.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal String ToString(TraceFormat traceFormat)
{
bool displayFilenames = true; // we'll try, but demand may fail
String word_At = "at";
String inFileLineNum = "in {0}:line {1}";
if(traceFormat != TraceFormat.NoResourceLookup)
{
word_At = Environment.GetResourceString("Word_At");
inFileLineNum = Environment.GetResourceString("StackTrace_InFileLineNumber");
}
bool fFirstFrame = true;
StringBuilder sb = new StringBuilder(255);
for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++)
{
StackFrame sf = GetFrame(iFrameIndex);
MethodBase mb = sf.GetMethod();
if (mb != null)
{
// We want a newline at the end of every line except for the last
if (fFirstFrame)
fFirstFrame = false;
else
sb.Append(Environment.NewLine);
sb.AppendFormat(CultureInfo.InvariantCulture, " {0} ", word_At);
Type t = mb.DeclaringType;
// if there is a type (non global method) print it
if (t != null)
{
// Append t.FullName, replacing '+' with '.'
string fullName = t.FullName;
for (int i = 0; i < fullName.Length; i++)
{
char ch = fullName[i];
sb.Append(ch == '+' ? '.' : ch);
}
sb.Append('.');
}
sb.Append(mb.Name);
// deal with the generic portion of the method
if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod)
{
Type[] typars = ((MethodInfo)mb).GetGenericArguments();
sb.Append('[');
int k=0;
bool fFirstTyParam = true;
while (k < typars.Length)
{
if (fFirstTyParam == false)
sb.Append(',');
else
fFirstTyParam = false;
sb.Append(typars[k].Name);
k++;
}
sb.Append(']');
}
ParameterInfo[] pi = null;
#if FEATURE_CORECLR
try
{
#endif
pi = mb.GetParameters();
#if FEATURE_CORECLR
}
catch
{
// The parameter info cannot be loaded, so we don't
// append the parameter list.
}
#endif
if (pi != null)
{
// arguments printing
sb.Append('(');
bool fFirstParam = true;
for (int j = 0; j < pi.Length; j++)
{
if (fFirstParam == false)
sb.Append(", ");
else
fFirstParam = false;
String typeName = "<UnknownType>";
if (pi[j].ParameterType != null)
typeName = pi[j].ParameterType.Name;
sb.Append(typeName);
sb.Append(' ');
sb.Append(pi[j].Name);
}
sb.Append(')');
}
// source location printing
if (displayFilenames && (sf.GetILOffset() != -1))
{
// If we don't have a PDB or PDB-reading is disabled for the module,
// then the file name will be null.
String fileName = null;
// Getting the filename from a StackFrame is a privileged operation - we won't want
// to disclose full path names to arbitrarily untrusted code. Rather than just omit
// this we could probably trim to just the filename so it's still mostly usefull.
try
{
fileName = sf.GetFileName();
}
#if FEATURE_CAS_POLICY
catch (NotSupportedException)
{
// Having a deprecated stack modifier on the callstack (such as Deny) will cause
// a NotSupportedException to be thrown. Since we don't know if the app can
// access the file names, we'll conservatively hide them.
displayFilenames = false;
}
#endif // FEATURE_CAS_POLICY
catch (SecurityException)
{
// If the demand for displaying filenames fails, then it won't
// succeed later in the loop. Avoid repeated exceptions by not trying again.
displayFilenames = false;
}
if (fileName != null)
{
// tack on " in c:\tmp\MyFile.cs:line 5"
sb.Append(' ');
sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber());
}
}
#if FEATURE_EXCEPTIONDISPATCHINFO
if (sf.GetIsLastFrameFromForeignExceptionStackTrace())
{
sb.Append(Environment.NewLine);
sb.Append(Environment.GetResourceString("Exception_EndStackTraceFromPreviousThrow"));
}
#endif // FEATURE_EXCEPTIONDISPATCHINFO
}
}
if(traceFormat == TraceFormat.TrailingNewLine)
sb.Append(Environment.NewLine);
return sb.ToString();
}
// This helper is called from within the EE to construct a string representation
// of the current stack trace.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
private static String GetManagedStackTraceStringHelper(bool fNeedFileInfo)
{
// Note all the frames in System.Diagnostics will be skipped when capturing
// a normal stack trace (not from an exception) so we don't need to explicitly
// skip the GetManagedStackTraceStringHelper frame.
StackTrace st = new StackTrace(0, fNeedFileInfo);
return st.ToString();
}
}
}
| |
using Lucene.Net.Analysis;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Humanizer;
namespace AddressFinder
{
public class SynonymEngine : ISynonymEngine
{
public class Fields
{
public static readonly string Recipient = "Recipient";
public static readonly string UnitType = "UnitType";
public static readonly string FloorType = "FloorType";
public static readonly string BuildingName = "BuildingName";
public static readonly string Prefix = "Prefix";
public static readonly string Organisation = "Organisation";
public static readonly string StreetDirection = "StreetDirection";
public static readonly string StreetType = "StreetType";
public static readonly string Ordinal = "StreetType";
}
private readonly static IEnumerable<CharArraySet> _synonymGroups = GetSynonymGroups();
private static IEnumerable<CharArraySet> GetSynonymGroups()
{
var abbreviations = new Collection<CharArraySet>();
GetRecipientAbbreviations(abbreviations);
GetUnitTypeAbbreviations(abbreviations);
GetFloorTypeAbbreviations(abbreviations);
GetBuildingNameAbbreviations(abbreviations);
GetPrefixAbbreviations(abbreviations);
GetOrganisationAbbreviations(abbreviations);
GetStreetDirectionAbbreviations(abbreviations);
GetStreetTypeAbbreviations(abbreviations);
GetOrdinalAbbreviations(abbreviations);
return abbreviations;
}
private static void GetOrdinalAbbreviations(Collection<CharArraySet> abbreviations)
{
for (int i = 0; i < 100; i++)
{
abbreviations.Add(new CharArraySet(new Collection<string>() { i.Ordinal(), i.ToOrdinalWords() }, true));
}
}
private static void GetUnitTypeAbbreviations(ICollection<CharArraySet> abbreviations)
{
abbreviations.Add(new CharArraySet(new Collection<string>() {"Apartment", "Apt"}, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Kiosk", "Ksk" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Room", "Rm" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Shop", "Shp" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Suite", "Ste" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Villa", "Vlla" }, true));
}
private static void GetFloorTypeAbbreviations(ICollection<CharArraySet> abbreviations)
{
abbreviations.Add(new CharArraySet(new Collection<string>() { "Floor", "Fl" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Level", "L" }, true));
}
private static void GetRecipientAbbreviations(ICollection<CharArraySet> abbreviations)
{
abbreviations.Add(new CharArraySet(new Collection<string>() { "Attention", "Attn" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Care of", "C/-", "C/O" }, true));
}
private static void GetBuildingNameAbbreviations(ICollection<CharArraySet> abbreviations)
{
abbreviations.Add(new CharArraySet(new Collection<string>() { "Building", "Bldg" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "House", "Hse" }, true));
}
private static void GetPrefixAbbreviations(ICollection<CharArraySet> abbreviations)
{
abbreviations.Add(new CharArraySet(new Collection<string>() { "Mount", "Mt" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Saint", "St" }, true));
}
private static void GetOrganisationAbbreviations(ICollection<CharArraySet> abbreviations)
{
abbreviations.Add(new CharArraySet(new Collection<string>() { "Administration", "Admn" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Agency", "Agcy" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Branch", "Brnch,", "Br" }, true));
//abbreviations.Add(new CharArraySet(new Collection<string>() { "Care of", "C/-,", "C/O" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Centre", "Ctr" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Company", "Co" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Corporation", "Corp" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Department", "Dept" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Division", "Div" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Enterprise", "Entprs" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Government", "Govt" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Group", "Gp" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Headquarters", "HQ" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Incorporated", "Inc" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Laboratory", "Lab" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Limited", "Ltd" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Management", "Mgmt" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Manufacturer", "Mfr" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Manufacturing", "Mfg" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "National", "Natl" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Office", "Ofc" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Partnership", "Prtnrshp" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Proprietary", "Pty" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "System", "Sys" }, true));
}
private static void GetStreetDirectionAbbreviations(ICollection<CharArraySet> abbreviations)
{
abbreviations.Add(new CharArraySet(new Collection<string>() { "North", "N" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "East", "E" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "South", "S" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "West", "W" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Northeast", "NE" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Southeast", "SE" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Northwest", "NW" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Southwest", "SW" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Upper", "Upr" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Lower", "Lwr" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Central", "Ctrl" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Extension", "Ext" }, true));
}
private static void GetStreetTypeAbbreviations(ICollection<CharArraySet> abbreviations)
{
abbreviations.Add(new CharArraySet(new Collection<string>() { "Access", "Accs" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Avenue", "Ave" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Bank", "Bank" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Bay", "Bay" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Beach", "Bch" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Belt", "Belt" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Bend", "Bnd" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Boulevard", "Blvd" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Brae", "Brae" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Centre", "Ctr" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Circle", "Cir" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Circus", "Crcs" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Close", "Cl" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Common", "Cmn" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Leader", "Ledr" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Leigh", "Lgh" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Mount", "Mt" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Paku", "Paku" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Parade", "Pde" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Park", "Pk" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Place", "Pl" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Cove", "Cv" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Promenade", "Prom" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Crescent", "Cres" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Quay", "Qy" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Crest", "Crst" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Ridge", "Rdge" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Dale", "Dle" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Dell", "Del" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Road", "Rd" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Drive Dr" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Square", "Sq" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Esplanade", "Esp" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Strand", "Strd" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Fairway", "Fawy" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Street", "St" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Gardens", "Gdns" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Terrace", "Tce" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Gate", "Gte" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Track", "Trk" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Glade", "Gld" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Glen", "Gln" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Valley", "Vly" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Green", "Grn" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "View", "Vw" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Grove", "Grv" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Views", "Vws" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Village Vlg" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Heights Hts" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Villas", "Vlls" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Highway", "Hwy" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Vista", "Vis" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Hill", "Hl" }, true));
abbreviations.Add(new CharArraySet(new Collection<string>() { "Walk", "Wlk" }, true));
}
public CharArraySet GetSynonyms(char[] word, int len)
{
if (word == null || word .Length == 0)
return null;
foreach (var synonymGroup in _synonymGroups)
{
//if the word is a part of the group return
//the group as the results.
if (synonymGroup.Contains(word, 0, len))
{
return synonymGroup;
}
}
return null;
}
}
internal static class OrdinalExtensions
{
public static string Ordinal(this int number)
{
const string TH = "th";
string s = number.ToString();
// Negative and zero have no ordinal representation
if (number < 1)
{
return s;
}
number %= 100;
if ((number >= 11) && (number <= 13))
{
return s + TH;
}
switch (number % 10)
{
case 1: return s + "st";
case 2: return s + "nd";
case 3: return s + "rd";
default: return s + TH;
}
}
}
}
| |
/*
* 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.ElastiCache.Model
{
/// <summary>
/// <para>Represents the output of a <i>PurchaseReservedCacheNodesOffering</i> operation.</para>
/// </summary>
public class ReservedCacheNode
{
private string reservedCacheNodeId;
private string reservedCacheNodesOfferingId;
private string cacheNodeType;
private DateTime? startTime;
private int? duration;
private double? fixedPrice;
private double? usagePrice;
private int? cacheNodeCount;
private string productDescription;
private string offeringType;
private string state;
private List<RecurringCharge> recurringCharges = new List<RecurringCharge>();
/// <summary>
/// The unique identifier for the reservation.
///
/// </summary>
public string ReservedCacheNodeId
{
get { return this.reservedCacheNodeId; }
set { this.reservedCacheNodeId = value; }
}
/// <summary>
/// Sets the ReservedCacheNodeId property
/// </summary>
/// <param name="reservedCacheNodeId">The value to set for the ReservedCacheNodeId 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 ReservedCacheNode WithReservedCacheNodeId(string reservedCacheNodeId)
{
this.reservedCacheNodeId = reservedCacheNodeId;
return this;
}
// Check to see if ReservedCacheNodeId property is set
internal bool IsSetReservedCacheNodeId()
{
return this.reservedCacheNodeId != null;
}
/// <summary>
/// The offering identifier.
///
/// </summary>
public string ReservedCacheNodesOfferingId
{
get { return this.reservedCacheNodesOfferingId; }
set { this.reservedCacheNodesOfferingId = value; }
}
/// <summary>
/// Sets the ReservedCacheNodesOfferingId property
/// </summary>
/// <param name="reservedCacheNodesOfferingId">The value to set for the ReservedCacheNodesOfferingId 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 ReservedCacheNode WithReservedCacheNodesOfferingId(string reservedCacheNodesOfferingId)
{
this.reservedCacheNodesOfferingId = reservedCacheNodesOfferingId;
return this;
}
// Check to see if ReservedCacheNodesOfferingId property is set
internal bool IsSetReservedCacheNodesOfferingId()
{
return this.reservedCacheNodesOfferingId != null;
}
/// <summary>
/// The cache node type for the reserved cache nodes.
///
/// </summary>
public string CacheNodeType
{
get { return this.cacheNodeType; }
set { this.cacheNodeType = value; }
}
/// <summary>
/// Sets the CacheNodeType property
/// </summary>
/// <param name="cacheNodeType">The value to set for the CacheNodeType 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 ReservedCacheNode WithCacheNodeType(string cacheNodeType)
{
this.cacheNodeType = cacheNodeType;
return this;
}
// Check to see if CacheNodeType property is set
internal bool IsSetCacheNodeType()
{
return this.cacheNodeType != null;
}
/// <summary>
/// The time the reservation started.
///
/// </summary>
public DateTime StartTime
{
get { return this.startTime ?? default(DateTime); }
set { this.startTime = value; }
}
/// <summary>
/// Sets the StartTime property
/// </summary>
/// <param name="startTime">The value to set for the StartTime 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 ReservedCacheNode WithStartTime(DateTime startTime)
{
this.startTime = startTime;
return this;
}
// Check to see if StartTime property is set
internal bool IsSetStartTime()
{
return this.startTime.HasValue;
}
/// <summary>
/// The duration of the reservation in seconds.
///
/// </summary>
public int Duration
{
get { return this.duration ?? default(int); }
set { this.duration = value; }
}
/// <summary>
/// Sets the Duration property
/// </summary>
/// <param name="duration">The value to set for the Duration 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 ReservedCacheNode WithDuration(int duration)
{
this.duration = duration;
return this;
}
// Check to see if Duration property is set
internal bool IsSetDuration()
{
return this.duration.HasValue;
}
/// <summary>
/// The fixed price charged for this reserved cache node.
///
/// </summary>
public double FixedPrice
{
get { return this.fixedPrice ?? default(double); }
set { this.fixedPrice = value; }
}
/// <summary>
/// Sets the FixedPrice property
/// </summary>
/// <param name="fixedPrice">The value to set for the FixedPrice 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 ReservedCacheNode WithFixedPrice(double fixedPrice)
{
this.fixedPrice = fixedPrice;
return this;
}
// Check to see if FixedPrice property is set
internal bool IsSetFixedPrice()
{
return this.fixedPrice.HasValue;
}
/// <summary>
/// The hourly price charged for this reserved cache node.
///
/// </summary>
public double UsagePrice
{
get { return this.usagePrice ?? default(double); }
set { this.usagePrice = value; }
}
/// <summary>
/// Sets the UsagePrice property
/// </summary>
/// <param name="usagePrice">The value to set for the UsagePrice 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 ReservedCacheNode WithUsagePrice(double usagePrice)
{
this.usagePrice = usagePrice;
return this;
}
// Check to see if UsagePrice property is set
internal bool IsSetUsagePrice()
{
return this.usagePrice.HasValue;
}
/// <summary>
/// The number of cache nodes that have been reserved.
///
/// </summary>
public int CacheNodeCount
{
get { return this.cacheNodeCount ?? default(int); }
set { this.cacheNodeCount = value; }
}
/// <summary>
/// Sets the CacheNodeCount property
/// </summary>
/// <param name="cacheNodeCount">The value to set for the CacheNodeCount 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 ReservedCacheNode WithCacheNodeCount(int cacheNodeCount)
{
this.cacheNodeCount = cacheNodeCount;
return this;
}
// Check to see if CacheNodeCount property is set
internal bool IsSetCacheNodeCount()
{
return this.cacheNodeCount.HasValue;
}
/// <summary>
/// The description of the reserved cache node.
///
/// </summary>
public string ProductDescription
{
get { return this.productDescription; }
set { this.productDescription = value; }
}
/// <summary>
/// Sets the ProductDescription property
/// </summary>
/// <param name="productDescription">The value to set for the ProductDescription 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 ReservedCacheNode WithProductDescription(string productDescription)
{
this.productDescription = productDescription;
return this;
}
// Check to see if ProductDescription property is set
internal bool IsSetProductDescription()
{
return this.productDescription != null;
}
/// <summary>
/// The offering type of this reserved cache node.
///
/// </summary>
public string OfferingType
{
get { return this.offeringType; }
set { this.offeringType = value; }
}
/// <summary>
/// Sets the OfferingType property
/// </summary>
/// <param name="offeringType">The value to set for the OfferingType 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 ReservedCacheNode WithOfferingType(string offeringType)
{
this.offeringType = offeringType;
return this;
}
// Check to see if OfferingType property is set
internal bool IsSetOfferingType()
{
return this.offeringType != null;
}
/// <summary>
/// The state of the reserved cache node.
///
/// </summary>
public string State
{
get { return this.state; }
set { this.state = value; }
}
/// <summary>
/// Sets the State property
/// </summary>
/// <param name="state">The value to set for the State 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 ReservedCacheNode WithState(string state)
{
this.state = state;
return this;
}
// Check to see if State property is set
internal bool IsSetState()
{
return this.state != null;
}
/// <summary>
/// The recurring price charged to run this reserved cache node.
///
/// </summary>
public List<RecurringCharge> RecurringCharges
{
get { return this.recurringCharges; }
set { this.recurringCharges = value; }
}
/// <summary>
/// Adds elements to the RecurringCharges collection
/// </summary>
/// <param name="recurringCharges">The values to add to the RecurringCharges collection </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 ReservedCacheNode WithRecurringCharges(params RecurringCharge[] recurringCharges)
{
foreach (RecurringCharge element in recurringCharges)
{
this.recurringCharges.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the RecurringCharges collection
/// </summary>
/// <param name="recurringCharges">The values to add to the RecurringCharges collection </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 ReservedCacheNode WithRecurringCharges(IEnumerable<RecurringCharge> recurringCharges)
{
foreach (RecurringCharge element in recurringCharges)
{
this.recurringCharges.Add(element);
}
return this;
}
// Check to see if RecurringCharges property is set
internal bool IsSetRecurringCharges()
{
return this.recurringCharges.Count > 0;
}
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2018 Helix Toolkit contributors
*/
using System;
using System.IO;
using SharpDX.Direct3D11;
using SharpDX.IO;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// A Texture 3D front end to <see cref="SharpDX.Direct3D11.Texture3D"/>.
/// </summary>
public class Texture3D : Texture3DBase
{
internal Texture3D(Device device, Texture3DDescription description3D, params DataBox[] dataBox)
: base(device, description3D, dataBox)
{
}
internal Texture3D(Device device, Direct3D11.Texture3D texture) : base(device, texture)
{
}
/// <summary>
/// Makes a copy of this texture.
/// </summary>
/// <remarks>
/// This method doesn't copy the content of the texture.
/// </remarks>
/// <returns>
/// A copy of this texture.
/// </returns>
public override Texture Clone()
{
return new Texture3D(GraphicsDevice, this.Description);
}
/// <summary>
/// Creates a new texture from a <see cref="Texture3DDescription"/>.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="description">The description.</param>
/// <returns>
/// A new instance of <see cref="Texture3D"/> class.
/// </returns>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public static Texture3D New(Device device, Texture3DDescription description)
{
return new Texture3D(device, description);
}
/// <summary>
/// Creates a new texture from a <see cref="Direct3D11.Texture3D"/>.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="texture">The native texture <see cref="Direct3D11.Texture3D"/>.</param>
/// <returns>
/// A new instance of <see cref="Texture3D"/> class.
/// </returns>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public static Texture3D New(Device device, Direct3D11.Texture3D texture)
{
return new Texture3D(device, texture);
}
/// <summary>
/// Creates a new <see cref="Texture3D"/> with a single mipmap.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <returns>
/// A new instance of <see cref="Texture3D"/> class.
/// </returns>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public static Texture3D New(Device device, int width, int height, int depth, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Default)
{
return New(device, width, height, depth, false, format, flags, usage);
}
/// <summary>
/// Creates a new <see cref="Texture3D"/>.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <returns>
/// A new instance of <see cref="Texture3D"/> class.
/// </returns>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public static Texture3D New(Device device, int width, int height, int depth, MipMapCount mipCount, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Default)
{
return new Texture3D(device, NewDescription(width, height, depth, format, flags, mipCount, usage));
}
/// <summary>
/// Creates a new <see cref="Texture3D" /> with texture data for the firs map.
/// </summary>
/// <typeparam name="T">Type of the data to upload to the texture</typeparam>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="textureData">The texture data, width * height * depth data </param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <returns>A new instance of <see cref="Texture3D" /> class.</returns>
/// <remarks>
/// The first dimension of mipMapTextures describes the number of is an array ot Texture3D Array
/// </remarks>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public unsafe static Texture3D New<T>(Device device, int width, int height, int depth, PixelFormat format, T[] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) where T : unmanaged
{
Texture3D texture = null;
Utilities.Pin(textureData, ptr =>
{
texture = New(device, width, height, depth, 1, format, new[] { GetDataBox(format, width, height, depth, textureData, ptr) }, flags, usage);
});
return texture;
}
/// <summary>
/// Creates a new <see cref="Texture3D"/>.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="textureData">DataBox used to fill texture data.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <returns>
/// A new instance of <see cref="Texture3D"/> class.
/// </returns>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public static Texture3D New(Device device, int width, int height, int depth, MipMapCount mipCount, PixelFormat format, DataBox[] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Default)
{
// TODO Add check for number of texture data according to width/height/depth/mipCount.
return new Texture3D(device, NewDescription(width, height, depth, format, flags, mipCount, usage), textureData);
}
/// <summary>
/// Creates a new <see cref="Texture3D" /> directly from an <see cref="Image"/>.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="image">An image in CPU memory.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">The usage.</param>
/// <returns>A new instance of <see cref="Texture3D" /> class.</returns>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public static Texture3D New(Device device, Image image, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
if (image == null)
throw new ArgumentNullException("image");
if (image.Description.Dimension != TextureDimension.Texture3D)
throw new ArgumentException("Invalid image. Must be 3D", "image");
return new Texture3D(device, CreateTextureDescriptionFromImage(image, flags, usage), image.ToDataBox());
}
/// <summary>
/// Loads a 3D texture from a stream.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="stream">The stream to load the texture from.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
/// <exception cref="ArgumentException">If the texture is not of type 3D</exception>
/// <returns>A texture</returns>
public static new Texture3D Load(Device device, Stream stream, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
var texture = Texture.Load(device, stream, flags, usage);
if (!(texture is Texture3D))
throw new ArgumentException(string.Format("Texture is not type of [Texture3D] but [{0}]", texture.GetType().Name));
return (Texture3D)texture;
}
/// <summary>
/// Loads a 3D texture from a stream.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="filePath">The file to load the texture from.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
/// <exception cref="ArgumentException">If the texture is not of type 3D</exception>
/// <returns>A texture</returns>
public static new Texture3D Load(Device device, string filePath, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read))
return Load(device, stream, flags, usage);
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Text;
using System.Xml;
using System.IO;
using Oranikle.Report.Engine;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// Summary description for DialogDataSourceRef.
/// </summary>
internal class DialogDataSources : System.Windows.Forms.Form
{
DesignXmlDraw _Draw;
string _FileName; // file name of open file; used to obtain directory
private Oranikle.Studio.Controls.CustomTextControl tbFilename;
private Oranikle.Studio.Controls.StyledButton bGetFilename;
private Oranikle.Studio.Controls.StyledComboBox cbDataProvider;
private Oranikle.Studio.Controls.CustomTextControl tbConnection;
private Oranikle.Studio.Controls.StyledCheckBox ckbIntSecurity;
private Oranikle.Studio.Controls.CustomTextControl tbPrompt;
private Oranikle.Studio.Controls.StyledButton bOK;
private Oranikle.Studio.Controls.StyledButton bCancel;
private Oranikle.Studio.Controls.StyledButton bTestConnection;
private System.Windows.Forms.ListBox lbDataSources;
private Oranikle.Studio.Controls.StyledButton bRemove;
private Oranikle.Studio.Controls.StyledButton bAdd;
private Oranikle.Studio.Controls.StyledCheckBox chkSharedDataSource;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lDataProvider;
private System.Windows.Forms.Label lConnectionString;
private System.Windows.Forms.Label lPrompt;
private Oranikle.Studio.Controls.CustomTextControl tbDSName;
private Oranikle.Studio.Controls.StyledButton bExprConnect;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal DialogDataSources(string filename, DesignXmlDraw draw)
{
_Draw = draw;
_FileName = filename;
//
// Required for Windows Form Designer support
//
InitializeComponent();
InitValues();
}
private void InitValues()
{
// Populate the DataProviders
cbDataProvider.Items.Clear();
string[] items = RdlEngineConfig.GetProviders();
cbDataProvider.Items.AddRange(items);
//
// Obtain the existing DataSets info
//
XmlNode rNode = _Draw.GetReportNode();
XmlNode dsNode = _Draw.GetNamedChildNode(rNode, "DataSources");
if (dsNode == null)
return;
foreach (XmlNode dNode in dsNode)
{
if (dNode.Name != "DataSource")
continue;
XmlAttribute nAttr = dNode.Attributes["Name"];
if (nAttr == null) // shouldn't really happen
continue;
DataSourceValues dsv = new DataSourceValues(nAttr.Value);
dsv.Node = dNode;
dsv.DataSourceReference = _Draw.GetElementValue(dNode, "DataSourceReference", null);
if (dsv.DataSourceReference == null)
{ // this is not a data source reference
dsv.bDataSourceReference = false;
dsv.DataSourceReference = "";
XmlNode cpNode = DesignXmlDraw.FindNextInHierarchy(dNode, "ConnectionProperties", "ConnectString");
dsv.ConnectionString = cpNode == null? "": cpNode.InnerText;
XmlNode datap = DesignXmlDraw.FindNextInHierarchy(dNode, "ConnectionProperties", "DataProvider");
dsv.DataProvider = datap == null? "": datap.InnerText;
XmlNode p = DesignXmlDraw.FindNextInHierarchy(dNode, "ConnectionProperties", "Prompt");
dsv.Prompt = p == null? "": p.InnerText;
}
else
{ // we have a data source reference
dsv.bDataSourceReference = true;
dsv.ConnectionString = "";
dsv.DataProvider = "";
dsv.Prompt = "";
}
this.lbDataSources.Items.Add(dsv);
}
if (lbDataSources.Items.Count > 0)
lbDataSources.SelectedIndex = 0;
else
this.bOK.Enabled = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tbFilename = new Oranikle.Studio.Controls.CustomTextControl();
this.bGetFilename = new Oranikle.Studio.Controls.StyledButton();
this.lDataProvider = new System.Windows.Forms.Label();
this.cbDataProvider = new Oranikle.Studio.Controls.StyledComboBox();
this.lConnectionString = new System.Windows.Forms.Label();
this.tbConnection = new Oranikle.Studio.Controls.CustomTextControl();
this.ckbIntSecurity = new Oranikle.Studio.Controls.StyledCheckBox();
this.lPrompt = new System.Windows.Forms.Label();
this.tbPrompt = new Oranikle.Studio.Controls.CustomTextControl();
this.bOK = new Oranikle.Studio.Controls.StyledButton();
this.bCancel = new Oranikle.Studio.Controls.StyledButton();
this.bTestConnection = new Oranikle.Studio.Controls.StyledButton();
this.lbDataSources = new System.Windows.Forms.ListBox();
this.bRemove = new Oranikle.Studio.Controls.StyledButton();
this.bAdd = new Oranikle.Studio.Controls.StyledButton();
this.chkSharedDataSource = new Oranikle.Studio.Controls.StyledCheckBox();
this.label1 = new System.Windows.Forms.Label();
this.tbDSName = new Oranikle.Studio.Controls.CustomTextControl();
this.bExprConnect = new Oranikle.Studio.Controls.StyledButton();
this.SuspendLayout();
//
// tbFilename
//
this.tbFilename.AddX = 0;
this.tbFilename.AddY = 0;
this.tbFilename.AllowSpace = false;
this.tbFilename.BorderColor = System.Drawing.Color.LightGray;
this.tbFilename.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbFilename.ChangeVisibility = false;
this.tbFilename.ChildControl = null;
this.tbFilename.ConvertEnterToTab = true;
this.tbFilename.ConvertEnterToTabForDialogs = false;
this.tbFilename.Decimals = 0;
this.tbFilename.DisplayList = new object[0];
this.tbFilename.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbFilename.Location = new System.Drawing.Point(192, 112);
this.tbFilename.Name = "tbFilename";
this.tbFilename.OnDropDownCloseFocus = true;
this.tbFilename.SelectType = 0;
this.tbFilename.Size = new System.Drawing.Size(216, 20);
this.tbFilename.TabIndex = 2;
this.tbFilename.UseValueForChildsVisibilty = false;
this.tbFilename.Value = true;
this.tbFilename.TextChanged += new System.EventHandler(this.tbFilename_TextChanged);
//
// bGetFilename
//
this.bGetFilename.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bGetFilename.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bGetFilename.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bGetFilename.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bGetFilename.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bGetFilename.Font = new System.Drawing.Font("Arial", 9F);
this.bGetFilename.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bGetFilename.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bGetFilename.Location = new System.Drawing.Point(424, 112);
this.bGetFilename.Name = "bGetFilename";
this.bGetFilename.OverriddenSize = null;
this.bGetFilename.Size = new System.Drawing.Size(24, 21);
this.bGetFilename.TabIndex = 3;
this.bGetFilename.Text = "...";
this.bGetFilename.UseVisualStyleBackColor = true;
this.bGetFilename.Click += new System.EventHandler(this.bGetFilename_Click);
//
// lDataProvider
//
this.lDataProvider.Location = new System.Drawing.Point(8, 152);
this.lDataProvider.Name = "lDataProvider";
this.lDataProvider.Size = new System.Drawing.Size(80, 23);
this.lDataProvider.TabIndex = 7;
this.lDataProvider.Text = "Data provider";
//
// cbDataProvider
//
this.cbDataProvider.AutoAdjustItemHeight = false;
this.cbDataProvider.BorderColor = System.Drawing.Color.LightGray;
this.cbDataProvider.ConvertEnterToTabForDialogs = false;
this.cbDataProvider.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbDataProvider.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbDataProvider.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbDataProvider.Items.AddRange(new object[] {
"SQL",
"ODBC",
"OLEDB"});
this.cbDataProvider.Location = new System.Drawing.Point(96, 152);
this.cbDataProvider.Name = "cbDataProvider";
this.cbDataProvider.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbDataProvider.SeparatorMargin = 1;
this.cbDataProvider.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbDataProvider.SeparatorWidth = 1;
this.cbDataProvider.Size = new System.Drawing.Size(144, 21);
this.cbDataProvider.TabIndex = 4;
this.cbDataProvider.SelectedIndexChanged += new System.EventHandler(this.cbDataProvider_SelectedIndexChanged);
//
// lConnectionString
//
this.lConnectionString.Location = new System.Drawing.Point(8, 192);
this.lConnectionString.Name = "lConnectionString";
this.lConnectionString.Size = new System.Drawing.Size(100, 16);
this.lConnectionString.TabIndex = 10;
this.lConnectionString.Text = "Connection string";
//
// tbConnection
//
this.tbConnection.AddX = 0;
this.tbConnection.AddY = 0;
this.tbConnection.AllowSpace = false;
this.tbConnection.BorderColor = System.Drawing.Color.LightGray;
this.tbConnection.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbConnection.ChangeVisibility = false;
this.tbConnection.ChildControl = null;
this.tbConnection.ConvertEnterToTab = true;
this.tbConnection.ConvertEnterToTabForDialogs = false;
this.tbConnection.Decimals = 0;
this.tbConnection.DisplayList = new object[0];
this.tbConnection.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbConnection.Location = new System.Drawing.Point(16, 216);
this.tbConnection.Multiline = true;
this.tbConnection.Name = "tbConnection";
this.tbConnection.OnDropDownCloseFocus = true;
this.tbConnection.SelectType = 0;
this.tbConnection.Size = new System.Drawing.Size(424, 40);
this.tbConnection.TabIndex = 6;
this.tbConnection.UseValueForChildsVisibilty = false;
this.tbConnection.Value = true;
this.tbConnection.TextChanged += new System.EventHandler(this.tbConnection_TextChanged);
//
// ckbIntSecurity
//
this.ckbIntSecurity.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.ckbIntSecurity.ForeColor = System.Drawing.Color.Black;
this.ckbIntSecurity.Location = new System.Drawing.Point(280, 152);
this.ckbIntSecurity.Name = "ckbIntSecurity";
this.ckbIntSecurity.Size = new System.Drawing.Size(144, 24);
this.ckbIntSecurity.TabIndex = 5;
this.ckbIntSecurity.Text = "Use integrated security";
this.ckbIntSecurity.CheckedChanged += new System.EventHandler(this.ckbIntSecurity_CheckedChanged);
//
// lPrompt
//
this.lPrompt.Location = new System.Drawing.Point(8, 272);
this.lPrompt.Name = "lPrompt";
this.lPrompt.Size = new System.Drawing.Size(432, 16);
this.lPrompt.TabIndex = 12;
this.lPrompt.Text = "(Optional) Enter the prompt displayed when asking for database credentials ";
//
// tbPrompt
//
this.tbPrompt.AddX = 0;
this.tbPrompt.AddY = 0;
this.tbPrompt.AllowSpace = false;
this.tbPrompt.BorderColor = System.Drawing.Color.LightGray;
this.tbPrompt.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbPrompt.ChangeVisibility = false;
this.tbPrompt.ChildControl = null;
this.tbPrompt.ConvertEnterToTab = true;
this.tbPrompt.ConvertEnterToTabForDialogs = false;
this.tbPrompt.Decimals = 0;
this.tbPrompt.DisplayList = new object[0];
this.tbPrompt.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbPrompt.Location = new System.Drawing.Point(16, 296);
this.tbPrompt.Name = "tbPrompt";
this.tbPrompt.OnDropDownCloseFocus = true;
this.tbPrompt.SelectType = 0;
this.tbPrompt.Size = new System.Drawing.Size(424, 20);
this.tbPrompt.TabIndex = 7;
this.tbPrompt.UseValueForChildsVisibilty = false;
this.tbPrompt.Value = true;
this.tbPrompt.TextChanged += new System.EventHandler(this.tbPrompt_TextChanged);
//
// bOK
//
this.bOK.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bOK.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bOK.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bOK.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bOK.Font = new System.Drawing.Font("Arial", 9F);
this.bOK.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bOK.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bOK.Location = new System.Drawing.Point(272, 344);
this.bOK.Name = "bOK";
this.bOK.OverriddenSize = null;
this.bOK.Size = new System.Drawing.Size(75, 23);
this.bOK.TabIndex = 9;
this.bOK.Text = "OK";
this.bOK.UseVisualStyleBackColor = true;
this.bOK.Click += new System.EventHandler(this.bOK_Click);
//
// bCancel
//
this.bCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bCancel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bCancel.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bCancel.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bCancel.CausesValidation = false;
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bCancel.Font = new System.Drawing.Font("Arial", 9F);
this.bCancel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bCancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bCancel.Location = new System.Drawing.Point(368, 344);
this.bCancel.Name = "bCancel";
this.bCancel.OverriddenSize = null;
this.bCancel.Size = new System.Drawing.Size(75, 23);
this.bCancel.TabIndex = 10;
this.bCancel.Text = "Cancel";
this.bCancel.UseVisualStyleBackColor = true;
//
// bTestConnection
//
this.bTestConnection.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bTestConnection.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bTestConnection.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bTestConnection.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bTestConnection.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bTestConnection.Font = new System.Drawing.Font("Arial", 9F);
this.bTestConnection.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bTestConnection.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bTestConnection.Location = new System.Drawing.Point(16, 344);
this.bTestConnection.Name = "bTestConnection";
this.bTestConnection.OverriddenSize = null;
this.bTestConnection.Size = new System.Drawing.Size(96, 21);
this.bTestConnection.TabIndex = 8;
this.bTestConnection.Text = "Test Connection";
this.bTestConnection.UseVisualStyleBackColor = true;
this.bTestConnection.Click += new System.EventHandler(this.bTestConnection_Click);
//
// lbDataSources
//
this.lbDataSources.Location = new System.Drawing.Point(16, 8);
this.lbDataSources.Name = "lbDataSources";
this.lbDataSources.Size = new System.Drawing.Size(120, 82);
this.lbDataSources.TabIndex = 11;
this.lbDataSources.SelectedIndexChanged += new System.EventHandler(this.lbDataSources_SelectedIndexChanged);
//
// bRemove
//
this.bRemove.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bRemove.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bRemove.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bRemove.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bRemove.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bRemove.Font = new System.Drawing.Font("Arial", 9F);
this.bRemove.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bRemove.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bRemove.Location = new System.Drawing.Point(144, 40);
this.bRemove.Name = "bRemove";
this.bRemove.OverriddenSize = null;
this.bRemove.Size = new System.Drawing.Size(56, 21);
this.bRemove.TabIndex = 20;
this.bRemove.Text = "Remove";
this.bRemove.UseVisualStyleBackColor = true;
this.bRemove.Click += new System.EventHandler(this.bRemove_Click);
//
// bAdd
//
this.bAdd.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bAdd.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bAdd.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bAdd.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bAdd.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bAdd.Font = new System.Drawing.Font("Arial", 9F);
this.bAdd.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bAdd.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bAdd.Location = new System.Drawing.Point(144, 8);
this.bAdd.Name = "bAdd";
this.bAdd.OverriddenSize = null;
this.bAdd.Size = new System.Drawing.Size(56, 21);
this.bAdd.TabIndex = 19;
this.bAdd.Text = "Add";
this.bAdd.UseVisualStyleBackColor = true;
this.bAdd.Click += new System.EventHandler(this.bAdd_Click);
//
// chkSharedDataSource
//
this.chkSharedDataSource.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkSharedDataSource.ForeColor = System.Drawing.Color.Black;
this.chkSharedDataSource.Location = new System.Drawing.Point(8, 112);
this.chkSharedDataSource.Name = "chkSharedDataSource";
this.chkSharedDataSource.Size = new System.Drawing.Size(184, 16);
this.chkSharedDataSource.TabIndex = 1;
this.chkSharedDataSource.Text = "Shared Data Source Reference";
this.chkSharedDataSource.CheckedChanged += new System.EventHandler(this.chkSharedDataSource_CheckedChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(216, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(104, 23);
this.label1.TabIndex = 22;
this.label1.Text = "Data Source Name";
//
// tbDSName
//
this.tbDSName.AddX = 0;
this.tbDSName.AddY = 0;
this.tbDSName.AllowSpace = false;
this.tbDSName.BorderColor = System.Drawing.Color.LightGray;
this.tbDSName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbDSName.ChangeVisibility = false;
this.tbDSName.ChildControl = null;
this.tbDSName.ConvertEnterToTab = true;
this.tbDSName.ConvertEnterToTabForDialogs = false;
this.tbDSName.Decimals = 0;
this.tbDSName.DisplayList = new object[0];
this.tbDSName.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbDSName.Location = new System.Drawing.Point(216, 24);
this.tbDSName.Name = "tbDSName";
this.tbDSName.OnDropDownCloseFocus = true;
this.tbDSName.SelectType = 0;
this.tbDSName.Size = new System.Drawing.Size(216, 20);
this.tbDSName.TabIndex = 0;
this.tbDSName.UseValueForChildsVisibilty = false;
this.tbDSName.Value = true;
this.tbDSName.TextChanged += new System.EventHandler(this.tbDSName_TextChanged);
this.tbDSName.Validating += new System.ComponentModel.CancelEventHandler(this.tbDSName_Validating);
//
// bExprConnect
//
this.bExprConnect.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bExprConnect.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bExprConnect.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bExprConnect.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bExprConnect.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bExprConnect.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bExprConnect.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bExprConnect.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bExprConnect.Location = new System.Drawing.Point(416, 192);
this.bExprConnect.Name = "bExprConnect";
this.bExprConnect.OverriddenSize = null;
this.bExprConnect.Size = new System.Drawing.Size(22, 21);
this.bExprConnect.TabIndex = 23;
this.bExprConnect.Tag = "pright";
this.bExprConnect.Text = "fx";
this.bExprConnect.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bExprConnect.UseVisualStyleBackColor = true;
this.bExprConnect.Click += new System.EventHandler(this.bExprConnect_Click);
//
// DialogDataSources
//
this.AcceptButton = this.bOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(228)))), ((int)(((byte)(241)))), ((int)(((byte)(249)))));
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(456, 374);
this.Controls.Add(this.bExprConnect);
this.Controls.Add(this.tbDSName);
this.Controls.Add(this.label1);
this.Controls.Add(this.chkSharedDataSource);
this.Controls.Add(this.bRemove);
this.Controls.Add(this.bAdd);
this.Controls.Add(this.lbDataSources);
this.Controls.Add(this.bTestConnection);
this.Controls.Add(this.bCancel);
this.Controls.Add(this.bOK);
this.Controls.Add(this.tbPrompt);
this.Controls.Add(this.lPrompt);
this.Controls.Add(this.ckbIntSecurity);
this.Controls.Add(this.tbConnection);
this.Controls.Add(this.lConnectionString);
this.Controls.Add(this.cbDataProvider);
this.Controls.Add(this.lDataProvider);
this.Controls.Add(this.bGetFilename);
this.Controls.Add(this.tbFilename);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DialogDataSources";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "DataSources in Report";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public void Apply()
{
XmlNode rNode = _Draw.GetReportNode();
_Draw.RemoveElement(rNode, "DataSources"); // remove old DataSources
if (this.lbDataSources.Items.Count <= 0)
return; // nothing in list? all done
XmlNode dsNode = _Draw.SetElement(rNode, "DataSources", null);
foreach (DataSourceValues dsv in lbDataSources.Items)
{
if (dsv.Name == null || dsv.Name.Length <= 0)
continue; // shouldn't really happen
XmlNode dNode = _Draw.CreateElement(dsNode, "DataSource", null);
// Create the name attribute
_Draw.SetElementAttribute(dNode, "Name", dsv.Name);
if (dsv.bDataSourceReference)
{
_Draw.SetElement(dNode, "DataSourceReference", dsv.DataSourceReference);
continue;
}
// must fill out the connection properties
XmlNode cNode = _Draw.CreateElement(dNode, "ConnectionProperties", null);
_Draw.SetElement(cNode, "DataProvider", dsv.DataProvider);
_Draw.SetElement(cNode, "ConnectString", dsv.ConnectionString);
_Draw.SetElement(cNode, "IntegratedSecurity", dsv.IntegratedSecurity? "true": "false");
if (dsv.Prompt != null && dsv.Prompt.Length > 0)
_Draw.SetElement(cNode, "Prompt", dsv.Prompt);
}
}
private void bGetFilename_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Data source reference files (*.dsr)|*.dsr" +
"|All files (*.*)|*.*";
ofd.FilterIndex = 1;
if (tbFilename.Text.Length > 0)
ofd.FileName = tbFilename.Text;
else
ofd.FileName = "*.dsr";
ofd.Title = "Specify Data Source Reference File Name";
ofd.DefaultExt = "dsr";
ofd.AddExtension = true;
try
{
if (_FileName != null)
ofd.InitialDirectory = Path.GetDirectoryName(_FileName);
}
catch
{
}
try
{
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
string dsr = DesignerUtility.RelativePathTo(
Path.GetDirectoryName(_FileName), Path.GetDirectoryName(ofd.FileName));
string f = Path.GetFileNameWithoutExtension(ofd.FileName);
tbFilename.Text = dsr == "" ? f : dsr + Path.DirectorySeparatorChar + f;
}
catch
{
tbFilename.Text = Path.GetFileNameWithoutExtension(ofd.FileName);
}
}
}
finally
{
ofd.Dispose();
}
}
private void tbFilename_TextChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
dsv.DataSourceReference = tbFilename.Text;
return;
}
private void bOK_Click(object sender, System.EventArgs e)
{
// Verify there are no duplicate names in the data sources
Hashtable ht = new Hashtable(this.lbDataSources.Items.Count+1);
foreach (DataSourceValues dsv in lbDataSources.Items)
{
if (dsv.Name == null || dsv.Name.Length == 0)
{
MessageBox.Show(this, "Name must be specified for all DataSources.", "Data Sources");
return;
}
if (!ReportNames.IsNameValid(dsv.Name))
{
MessageBox.Show(this,
string.Format("Name '{0}' contains invalid characters.", dsv.Name), "Data Sources");
return;
}
string name = (string) ht[dsv.Name];
if (name != null)
{
MessageBox.Show(this,
string.Format("Each DataSource must have a unique name. '{0}' is repeated.", dsv.Name), "Data Sources");
return;
}
ht.Add(dsv.Name, dsv.Name);
}
// apply the result
Apply();
DialogResult = DialogResult.OK;
}
private void bTestConnection_Click(object sender, System.EventArgs e)
{
if (DesignerUtility.TestConnection(this.cbDataProvider.Text, tbConnection.Text))
MessageBox.Show("Connection succeeded!", "Test Connection");
}
private void tbDSName_TextChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
if (dsv.Name == tbDSName.Text)
return;
dsv.Name = tbDSName.Text;
// text doesn't change in listbox; force change by removing and re-adding item
lbDataSources.BeginUpdate();
lbDataSources.Items.RemoveAt(cur);
lbDataSources.Items.Insert(cur, dsv);
lbDataSources.SelectedIndex = cur;
lbDataSources.EndUpdate();
}
private void chkSharedDataSource_CheckedChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
dsv.bDataSourceReference = chkSharedDataSource.Checked;
bool bEnableDataSourceRef = chkSharedDataSource.Checked;
// shared data source fields
tbFilename.Enabled = bEnableDataSourceRef;
bGetFilename.Enabled = bEnableDataSourceRef;
// in report data source
cbDataProvider.Enabled = !bEnableDataSourceRef;
tbConnection.Enabled = !bEnableDataSourceRef;
ckbIntSecurity.Enabled = !bEnableDataSourceRef;
tbPrompt.Enabled = !bEnableDataSourceRef;
bTestConnection.Enabled = !bEnableDataSourceRef;
lDataProvider.Enabled = !bEnableDataSourceRef;
lConnectionString.Enabled = !bEnableDataSourceRef;
lPrompt.Enabled = !bEnableDataSourceRef;
}
private void lbDataSources_SelectedIndexChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
tbDSName.Text = dsv.Name;
cbDataProvider.Text = dsv.DataProvider;
tbConnection.Text = dsv.ConnectionString;
ckbIntSecurity.Checked = dsv.IntegratedSecurity;
this.tbFilename.Text = dsv.DataSourceReference;
tbPrompt.Text = dsv.Prompt;
this.chkSharedDataSource.Checked = dsv.bDataSourceReference;
chkSharedDataSource_CheckedChanged(this.chkSharedDataSource, e); // force message
}
private void bAdd_Click(object sender, System.EventArgs e)
{
DataSourceValues dsv = new DataSourceValues("datasource");
int cur = this.lbDataSources.Items.Add(dsv);
lbDataSources.SelectedIndex = cur;
this.tbDSName.Focus();
}
private void bRemove_Click(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
lbDataSources.Items.RemoveAt(cur);
if (lbDataSources.Items.Count <= 0)
return;
cur--;
if (cur < 0)
cur = 0;
lbDataSources.SelectedIndex = cur;
}
private void tbDSName_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
if (!ReportNames.IsNameValid(tbDSName.Text))
{
e.Cancel = true;
MessageBox.Show(this,
string.Format("Name '{0}' contains invalid characters.", tbDSName.Text), "Data Sources");
}
}
private void tbConnection_TextChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
dsv.ConnectionString = tbConnection.Text;
}
private void tbPrompt_TextChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
dsv.Prompt = tbPrompt.Text;
}
private void cbDataProvider_SelectedIndexChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
dsv.DataProvider = cbDataProvider.Text;
}
private void ckbIntSecurity_CheckedChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
dsv.IntegratedSecurity = ckbIntSecurity.Checked;
}
private void bExprConnect_Click(object sender, System.EventArgs e)
{
DialogExprEditor ee = new DialogExprEditor(_Draw, this.tbConnection.Text, null, false);
try
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
tbConnection.Text = ee.Expression;
}
finally
{
ee.Dispose();
}
}
}
class DataSourceValues
{
string _Name;
bool _bDataSourceReference;
string _DataSourceReference;
string _DataProvider;
string _ConnectionString;
bool _IntegratedSecurity;
string _Prompt;
XmlNode _Node;
internal DataSourceValues(string name)
{
_Name = name;
}
internal string Name
{
get {return _Name;}
set {_Name = value;}
}
internal bool bDataSourceReference
{
get {return _bDataSourceReference;}
set {_bDataSourceReference = value;}
}
internal string DataSourceReference
{
get {return _DataSourceReference;}
set {_DataSourceReference = value;}
}
internal string DataProvider
{
get {return _DataProvider;}
set {_DataProvider = value;}
}
internal string ConnectionString
{
get {return _ConnectionString;}
set {_ConnectionString = value;}
}
internal bool IntegratedSecurity
{
get {return _IntegratedSecurity;}
set {_IntegratedSecurity = value;}
}
internal string Prompt
{
get {return _Prompt;}
set {_Prompt = value;}
}
internal XmlNode Node
{
get {return _Node;}
set {_Node = value;}
}
override public string ToString()
{
return _Name;
}
}
}
| |
using System.IO;
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\fieldToPolyData.tcl
// output file is AVfieldToPolyData.cs
/// <summary>
/// The testing class derived from AVfieldToPolyData
/// </summary>
public class AVfieldToPolyDataClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVfieldToPolyData(String [] argv)
{
//Prefix Content is: ""
// This example demonstrates the reading of a field and conversion to PolyData[]
// The output should be the same as polyEx.tcl.[]
// get the interactor ui[]
// Create a reader and write out the field[]
reader = new vtkPolyDataReader();
reader.SetFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/polyEx.vtk");
ds2do = new vtkDataSetToDataObjectFilter();
ds2do.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort());
try
{
channel = new StreamWriter("PolyField.vtk");
tryCatchError = "NOERROR";
}
catch(Exception)
{tryCatchError = "ERROR";}
if(tryCatchError.Equals("NOERROR"))
{
channel.Close();
writer = new vtkDataObjectWriter();
writer.SetInputConnection((vtkAlgorithmOutput)ds2do.GetOutputPort());
writer.SetFileName((string)"PolyField.vtk");
writer.Write();
// create pipeline[]
//[]
dor = new vtkDataObjectReader();
dor.SetFileName((string)"PolyField.vtk");
do2ds = new vtkDataObjectToDataSetFilter();
do2ds.SetInputConnection((vtkAlgorithmOutput)dor.GetOutputPort());
do2ds.SetDataSetTypeToPolyData();
do2ds.SetPointComponent((int)0,(string)"Points",(int)0);
do2ds.SetPointComponent((int)1,(string)"Points",(int)1);
do2ds.SetPointComponent((int)2,(string)"Points",(int)2);
do2ds.SetPolysComponent((string)"Polys",(int)0);
fd2ad = new vtkFieldDataToAttributeDataFilter();
fd2ad.SetInputConnection(do2ds.GetOutputPort());
fd2ad.SetInputFieldToDataObjectField();
fd2ad.SetOutputAttributeDataToPointData();
fd2ad.SetScalarComponent((int)0,(string)"my_scalars",(int)0);
mapper = vtkPolyDataMapper.New();
mapper.SetInputConnection(fd2ad.GetOutputPort());
mapper.SetScalarRange((double)((vtkDataSet)fd2ad.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)fd2ad.GetOutput()).GetScalarRange()[1]);
actor = new vtkActor();
actor.SetMapper((vtkMapper)mapper);
// Create the RenderWindow, Renderer and both Actors[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
ren1.AddActor((vtkProp)actor);
ren1.SetBackground((double)1,(double)1,(double)1);
renWin.SetSize((int)300,(int)300);
ren1.ResetCamera();
cam1 = ren1.GetActiveCamera();
cam1.SetClippingRange((double).348,(double)17.43);
cam1.SetPosition((double)2.92,(double)2.62,(double)-0.836);
cam1.SetViewUp((double)-0.436,(double)-0.067,(double)-0.897);
cam1.Azimuth((double)90);
// render the image[]
//[]
renWin.Render();
File.Delete("PolyField.vtk");
}
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkPolyDataReader reader;
static vtkDataSetToDataObjectFilter ds2do;
static string tryCatchError;
static StreamWriter channel;
static vtkDataObjectWriter writer;
static vtkDataObjectReader dor;
static vtkDataObjectToDataSetFilter do2ds;
static vtkFieldDataToAttributeDataFilter fd2ad;
static vtkPolyDataMapper mapper;
static vtkActor actor;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkCamera cam1;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataReader Getreader()
{
return reader;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setreader(vtkPolyDataReader toSet)
{
reader = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetToDataObjectFilter Getds2do()
{
return ds2do;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setds2do(vtkDataSetToDataObjectFilter toSet)
{
ds2do = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static string GettryCatchError()
{
return tryCatchError;
}
///<summary> A Set Method for Static Variables </summary>
public static void SettryCatchError(string toSet)
{
tryCatchError = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static StreamWriter Getchannel()
{
return channel;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setchannel(StreamWriter toSet)
{
channel = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataObjectWriter Getwriter()
{
return writer;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setwriter(vtkDataObjectWriter toSet)
{
writer = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataObjectReader Getdor()
{
return dor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setdor(vtkDataObjectReader toSet)
{
dor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataObjectToDataSetFilter Getdo2ds()
{
return do2ds;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setdo2ds(vtkDataObjectToDataSetFilter toSet)
{
do2ds = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkFieldDataToAttributeDataFilter Getfd2ad()
{
return fd2ad;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setfd2ad(vtkFieldDataToAttributeDataFilter toSet)
{
fd2ad = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Getmapper()
{
return mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmapper(vtkPolyDataMapper toSet)
{
mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Getactor()
{
return actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setactor(vtkActor toSet)
{
actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcam1()
{
return cam1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcam1(vtkCamera toSet)
{
cam1 = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(reader!= null){reader.Dispose();}
if(ds2do!= null){ds2do.Dispose();}
if(writer!= null){writer.Dispose();}
if(dor!= null){dor.Dispose();}
if(do2ds!= null){do2ds.Dispose();}
if(fd2ad!= null){fd2ad.Dispose();}
if(mapper!= null){mapper.Dispose();}
if(actor!= null){actor.Dispose();}
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(cam1!= null){cam1.Dispose();}
}
}
//--- end of script --//
| |
using System;
namespace Aardvark.Base
{
/// <summary>
/// Specifies an image boder, all entries should be positive values.
/// </summary>
public struct Border2i
{
public V2i Min;
public V2i Max;
#region Constructors
public Border2i(V2i min, V2i max)
{
Min = min; Max = max;
}
public Border2i(int minx, int miny, int maxx, int maxy)
: this(new V2i(minx, miny), new V2i(maxx, maxy))
{ }
public Border2i(int val)
: this(new V2i(val, val), new V2i(val, val))
{ }
#endregion
#region Properties
public Border2i Flipped { get { return new Border2i(Max, Min); } }
#endregion
#region Operations
public Border2l ToBorder2l()
{
return new Border2l(Min.ToV2l(), Max.ToV2l());
}
#endregion
}
/// <summary>
/// Specifies an image boder, all entries should be positive values.
/// </summary>
public struct Border2l
{
public V2l Min;
public V2l Max;
#region Constructors
public Border2l(V2l min, V2l max)
{
Min = min; Max = max;
}
public Border2l(long minx, long miny, long maxx, long maxy)
: this(new V2l(minx, miny), new V2l(maxx, maxy))
{ }
public Border2l(long val)
: this(new V2l(val, val), new V2l(val, val))
{ }
#endregion
#region Properties
public Border2l Flipped { get { return new Border2l(Max, Min); } }
#endregion
#region Operations
public Border2i ToBorder2i()
{
return new Border2i(Min.ToV2i(), Max.ToV2i());
}
#endregion
}
public static class BorderMatrixAndVolumeExtensions
{
#region Matrix Parts
/// <summary>
/// Get the minimal x edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<T> SubMinX<T>(this Matrix<T> m, long b)
{
return m.SubMatrixWindow(m.FX, m.FY, b, m.SY);
}
/// <summary>
/// Get the minimal x edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubMinX<Td, Tv>(this Matrix<Td, Tv> m, long b)
{
return m.SubMatrixWindow(m.FX, m.FY, b, m.SY);
}
/// <summary>
/// Get the maximal x edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<T> SubMaxX<T>(this Matrix<T> m, long b)
{
return m.SubMatrixWindow(m.EX - b, m.FY, b, m.SY);
}
/// <summary>
/// Get the maximal x edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubMaxX<Td, Tv>(this Matrix<Td, Tv> m, long b)
{
return m.SubMatrixWindow(m.EX - b, m.FY, b, m.SY);
}
/// <summary>
/// Get the minimal y edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
/// <summary>
/// Get the minimal y edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<T> SubMinY<T>(this Matrix<T> m, long b)
{
return m.SubMatrixWindow(m.FX, m.FY, m.SX, b);
}
/// <summary>
/// Get the minimal y edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubMinY<Td, Tv>(this Matrix<Td, Tv> m, long b)
{
return m.SubMatrixWindow(m.FX, m.FY, m.SX, b);
}
/// <summary>
/// Get the maximal y edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<T> SubMaxY<T>(this Matrix<T> m, long b)
{
return m.SubMatrixWindow(m.FX, m.EY - b, m.SX, b);
}
/// <summary>
/// Get the maximal y edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubMaxY<Td, Tv>(this Matrix<Td, Tv> m, long b)
{
return m.SubMatrixWindow(m.FX, m.EY - b, m.SX, b);
}
/// <summary>
/// Get the center part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<T> SubCenter<T>(this Matrix<T> m, Border2l b)
{
return m.SubMatrixWindow(m.FX + b.Min.X, m.FY + b.Min.Y,
m.SX - b.Max.X - b.Min.X, m.SY - b.Max.Y - b.Min.Y);
}
/// <summary>
/// Get the center part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubCenter<Td, Tv>(this Matrix<Td, Tv> m, Border2l b)
{
return m.SubMatrixWindow(m.FX + b.Min.X, m.FY + b.Min.Y,
m.SX - b.Max.X - b.Min.X, m.SY - b.Max.Y - b.Min.Y);
}
/// <summary>
/// Get the minimal x/minmal y corner part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<T> SubMinXMinY<T>(this Matrix<T> m, Border2l b)
{
return m.SubMatrixWindow(m.FX, m.FY,
b.Min.X, b.Min.Y);
}
/// <summary>
/// Get the minimal x/minmal y corner part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubMinXMinY<Td, Tv>(this Matrix<Td, Tv> m, Border2l b)
{
return m.SubMatrixWindow(m.FX, m.FY,
b.Min.X, b.Min.Y);
}
/// <summary>
/// Get the minimal x/maximal y corner part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<T> SubMinXMaxY<T>(this Matrix<T> m, Border2l b)
{
return m.SubMatrixWindow(m.FX, m.EY - b.Max.Y,
b.Min.X, b.Max.Y);
}
/// <summary>
/// Get the minimal x/maximal y corner part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubMinXMaxY<Td, Tv>(this Matrix<Td, Tv> m, Border2l b)
{
return m.SubMatrixWindow(m.FX, m.EY - b.Max.Y,
b.Min.X, b.Max.Y);
}
/// <summary>
/// Get the maximal x/minimal y corner part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<T> SubMaxXMinY<T>(this Matrix<T> m, Border2l b)
{
return m.SubMatrixWindow(m.EX - b.Max.X, m.FY,
b.Max.X, b.Min.Y);
}
/// <summary>
/// Get the maximal x/minimal y corner part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubMaxXMinY<Td, Tv>(this Matrix<Td, Tv> m, Border2l b)
{
return m.SubMatrixWindow(m.EX - b.Max.X, m.FY,
b.Max.X, b.Min.Y);
}
/// <summary>
/// Get the maximal x/maximal y corner part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<T> SubMaxXMaxY<T>(this Matrix<T> m, Border2l b)
{
return m.SubMatrixWindow(m.EX - b.Max.X, m.EY - b.Max.Y,
b.Max.X, b.Max.Y);
}
/// <summary>
/// Get the maximal x/maximal y corner part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubMaxXMaxY<Td, Tv>(this Matrix<Td, Tv> m, Border2l b)
{
return m.SubMatrixWindow(m.EX - b.Max.X, m.EY - b.Max.Y,
b.Max.X, b.Max.Y);
}
/// <summary>
/// Get the minimal x edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<T> SubMinX<T>(this Matrix<T> m, Border2l b)
{
return m.SubMatrixWindow(m.FX, m.FY + b.Min.Y,
b.Min.X, m.SY - b.Min.Y - b.Max.Y);
}
/// <summary>
/// Get the minimal x edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubMinX<Td, Tv>(this Matrix<Td, Tv> m, Border2l b)
{
return m.SubMatrixWindow(m.FX, m.FY + b.Min.Y,
b.Min.X, m.SY - b.Min.Y - b.Max.Y);
}
/// <summary>
/// Get the maximal x edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<T> SubMaxX<T>(this Matrix<T> m, Border2l b)
{
return m.SubMatrixWindow(m.EX - b.Max.X, m.FY + b.Min.Y,
b.Max.X, m.SY - b.Min.Y - b.Max.Y);
}
/// <summary>
/// Get the maximal x edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubMaxX<Td, Tv>(this Matrix<Td, Tv> m, Border2l b)
{
return m.SubMatrixWindow(m.EX - b.Max.X, m.FY + b.Min.Y,
b.Max.X, m.SY - b.Min.Y - b.Max.Y);
}
public static Matrix<T> SubMinY<T>(this Matrix<T> m, Border2l b)
{
return m.SubMatrixWindow(m.FX + b.Min.X, m.FY,
m.SX - b.Min.X - b.Max.X, b.Min.Y);
}
/// <summary>
/// Get the minimal y edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubMinY<Td, Tv>(this Matrix<Td, Tv> m, Border2l b)
{
return m.SubMatrixWindow(m.FX + b.Min.X, m.FY,
m.SX - b.Min.X - b.Max.X, b.Min.Y);
}
/// <summary>
/// Get the maximal y edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<T> SubMaxY<T>(this Matrix<T> m, Border2l b)
{
return m.SubMatrixWindow(m.FX + b.Min.X, m.EY - b.Max.Y,
m.SX - b.Min.X - b.Max.X, b.Max.Y);
}
/// <summary>
/// Get the maximal y edge part of a matrix with the specified border.
/// Note that the part retains the pixel coordinates of the original matrix.
/// </summary>
public static Matrix<Td, Tv> SubMaxY<Td, Tv>(this Matrix<Td, Tv> m, Border2l b)
{
return m.SubMatrixWindow(m.FX + b.Min.X, m.EY - b.Max.Y,
m.SX - b.Min.X - b.Max.X, b.Max.Y);
}
#endregion
#region Volume Parts
/// <summary>
/// Get the minimal x edge part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubMinX<T>(this Volume<T> v, long b)
{
return v.SubVolumeWindow(v.FX, v.FY, v.FZ, b, v.SY, v.SZ);
}
/// <summary>
/// Get the maximal x edge part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubMaxX<T>(this Volume<T> v, long b)
{
return v.SubVolumeWindow(v.EX - b, v.FY, v.FZ, b, v.SY, v.SZ);
}
/// <summary>
/// Get the minimal y edge part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubMinY<T>(this Volume<T> v, long b)
{
return v.SubVolumeWindow(v.FX, v.FY, v.FZ, v.SX, b, v.SZ);
}
/// <summary>
/// Get the maximal y edge part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubMaxY<T>(this Volume<T> v, long b)
{
return v.SubVolumeWindow(v.FX, v.EY - b, v.FZ, v.SX, b, v.SZ);
}
/// <summary>
/// Get the center part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubCenter<T>(this Volume<T> v, Border2l b)
{
return v.SubVolumeWindow(v.FX + b.Min.X, v.FY + b.Min.Y, v.FZ,
v.SX - b.Max.X - b.Min.X, v.SY - b.Max.Y - b.Min.Y, v.SZ);
}
/// <summary>
/// Get the minimal x/minmal y corner part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubMinXMinY<T>(this Volume<T> v, Border2l b)
{
return v.SubVolumeWindow(v.FX, v.FY, v.FZ,
b.Min.X, b.Min.Y, v.SZ);
}
/// <summary>
/// Get the minimal x/maximal y corner part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubMinXMaxY<T>(this Volume<T> v, Border2l b)
{
return v.SubVolumeWindow(v.FX, v.EY - b.Max.Y, v.FZ,
b.Min.X, b.Max.Y, v.SZ);
}
/// <summary>
/// Get the maximal x/minimal y corner part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubMaxXMinY<T>(this Volume<T> v, Border2l b)
{
return v.SubVolumeWindow(v.EX - b.Max.X, v.FY, v.FZ,
b.Max.X, b.Min.Y, v.SZ);
}
/// <summary>
/// Get the maximal x/maximal y corner part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubMaxXMaxY<T>(this Volume<T> v, Border2l b)
{
return v.SubVolumeWindow(v.EX - b.Max.X, v.EY - b.Max.Y, v.FZ,
b.Max.X, b.Max.Y, v.SZ);
}
/// <summary>
/// Get the minimal x edge part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubMinX<T>(this Volume<T> v, Border2l b)
{
return v.SubVolumeWindow(v.FX, v.FY + b.Min.Y, v.FZ,
b.Min.X, v.SY - b.Min.Y - b.Max.Y, v.SZ);
}
/// <summary>
/// Get the maximal x edge part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubMaxX<T>(this Volume<T> v, Border2l b)
{
return v.SubVolumeWindow(v.EX - b.Max.X, v.FY + b.Min.Y, v.FZ,
b.Max.X, v.SY - b.Min.Y - b.Max.Y, v.SZ);
}
/// <summary>
/// Get the minimal y edge part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubMinY<T>(this Volume<T> v, Border2l b)
{
return v.SubVolumeWindow(v.FX + b.Min.X, v.FY, v.FZ,
v.SX - b.Min.X - b.Max.X, b.Min.Y, v.SZ);
}
/// <summary>
/// Get the maximal y edge part of an image volume with the specified border.
/// Note that the part retains the pixel coordinates of the original volume.
/// </summary>
public static Volume<T> SubMaxY<T>(this Volume<T> v, Border2l b)
{
return v.SubVolumeWindow(v.FX + b.Min.X, v.EY - b.Max.Y, v.FZ,
v.SX - b.Min.X - b.Max.X, b.Max.Y, v.SZ);
}
#endregion
#region Generic Matrix Processing
/// <summary>
/// Process an image volume with specific actions for the center and border
/// parts.
/// </summary>
public static Matrix<T1> ProcessCenterBordersAndCorners<T, T1>(
this Matrix<T> source, Border2l border,
Action<Matrix<T>, Matrix<T1>> actCenter,
Action<Matrix<T>, Matrix<T1>> actMinX, Action<Matrix<T>, Matrix<T1>> actMaxX,
Action<Matrix<T>, Matrix<T1>> actMinY, Action<Matrix<T>, Matrix<T1>> actMaxY,
Action<Matrix<T>, Matrix<T1>> actMinXMinY, Action<Matrix<T>, Matrix<T1>> actMaxXMinY,
Action<Matrix<T>, Matrix<T1>> actMinXMaxY, Action<Matrix<T>, Matrix<T1>> actMaxXMaxY)
{
var target = new Matrix<T1>(source.Size);
target.F = source.F;
actCenter(source.SubCenter(border), target.SubCenter(border));
actMinX(source.SubMinX(border), target.SubMinX(border));
actMaxX(source.SubMaxX(border), target.SubMaxX(border));
actMinY(source.SubMinY(border), target.SubMinY(border));
actMaxY(source.SubMaxY(border), target.SubMaxY(border));
actMinXMinY(source.SubMinXMinY(border), target.SubMinXMinY(border));
actMaxXMinY(source.SubMaxXMinY(border), target.SubMaxXMinY(border));
actMinXMaxY(source.SubMinXMaxY(border), target.SubMinXMaxY(border));
actMaxXMaxY(source.SubMaxXMaxY(border), target.SubMaxXMaxY(border));
return target;
}
/// <summary>
/// Process an image volume with specific actions for the center and border
/// parts.
/// </summary>
public static void ApplyCenterBordersAndCorners<T>(
this Matrix<T> source, Border2l border,
Action<Matrix<T>> actCenter,
Action<Matrix<T>> actMinX, Action<Matrix<T>> actMaxX,
Action<Matrix<T>> actMinY, Action<Matrix<T>> actMaxY,
Action<Matrix<T>> actMinXMinY, Action<Matrix<T>> actMaxXMinY,
Action<Matrix<T>> actMinXMaxY, Action<Matrix<T>> actMaxXMaxY)
{
actCenter(source.SubCenter(border));
actMinX(source.SubMinX(border)); actMaxX(source.SubMaxX(border));
actMinY(source.SubMinY(border)); actMaxY(source.SubMaxY(border));
actMinXMinY(source.SubMinXMinY(border)); actMaxXMinY(source.SubMaxXMinY(border));
actMinXMaxY(source.SubMinXMaxY(border)); actMaxXMaxY(source.SubMaxXMaxY(border));
}
/// <summary>
/// Process an image volume with specific actions for the center and border
/// parts.
/// </summary>
public static void ApplyCenterBordersAndCorners<Td, Tv>(
this Matrix<Td, Tv> source, Border2l border,
Action<Matrix<Td, Tv>> actCenter,
Action<Matrix<Td, Tv>> actMinX, Action<Matrix<Td, Tv>> actMaxX,
Action<Matrix<Td, Tv>> actMinY, Action<Matrix<Td, Tv>> actMaxY,
Action<Matrix<Td, Tv>> actMinXMinY, Action<Matrix<Td, Tv>> actMaxXMinY,
Action<Matrix<Td, Tv>> actMinXMaxY, Action<Matrix<Td, Tv>> actMaxXMaxY)
{
actCenter(source.SubCenter(border));
actMinX(source.SubMinX(border)); actMaxX(source.SubMaxX(border));
actMinY(source.SubMinY(border)); actMaxY(source.SubMaxY(border));
actMinXMinY(source.SubMinXMinY(border)); actMaxXMinY(source.SubMaxXMinY(border));
actMinXMaxY(source.SubMinXMaxY(border)); actMaxXMaxY(source.SubMaxXMaxY(border));
}
#endregion
#region Generic Volume Processing
/// <summary>
/// Process an image volume with specific actions for the center and
/// border parts.
/// </summary>
public static Volume<T1> WithProcessedCenterBordersAndCorners<T, T1>(
this Volume<T> source, Border2l border,
Func<Volume<T>, Volume<T1>> funCenter,
Func<Volume<T>, Volume<T1>> funMinX, Func<Volume<T>, Volume<T1>> funMaxX,
Func<Volume<T>, Volume<T1>> funMinY, Func<Volume<T>, Volume<T1>> funMaxY,
Func<Volume<T>, Volume<T1>> funMinXMinY, Func<Volume<T>, Volume<T1>> funMaxXMinY,
Func<Volume<T>, Volume<T1>> funMinXMaxY, Func<Volume<T>, Volume<T1>> funMaxXMaxY)
{
var target = source.Size.CreateImageVolume<T1>();
target.F = source.F;
target.SubCenter(border).Set(funCenter(source.SubCenter(border)));
target.SubMinX(border).Set(funMinX(source.SubMinX(border)));
target.SubMaxX(border).Set(funMaxX(source.SubMaxX(border)));
target.SubMinY(border).Set(funMinY(source.SubMinY(border)));
target.SubMaxY(border).Set(funMaxY(source.SubMaxY(border)));
target.SubMinXMinY(border).Set(funMinXMinY(source.SubMinXMinY(border)));
target.SubMaxXMinY(border).Set(funMaxXMinY(source.SubMaxXMinY(border)));
target.SubMinXMaxY(border).Set(funMinXMaxY(source.SubMinXMaxY(border)));
target.SubMaxXMaxY(border).Set(funMaxXMaxY(source.SubMaxXMaxY(border)));
return target;
}
/// <summary>
/// Process an image volume with specific actions for the center and border
/// parts.
/// </summary>
public static void ApplyCenterBordersAndCorners<T>(
this Volume<T> source, Border2l border,
Action<Volume<T>> actCenter,
Action<Volume<T>> actMinX, Action<Volume<T>> actMaxX,
Action<Volume<T>> actMinY, Action<Volume<T>> actMaxY,
Action<Volume<T>> actMinXMinY, Action<Volume<T>> actMaxXMinY,
Action<Volume<T>> actMinXMaxY, Action<Volume<T>> actMaxXMaxY)
{
actCenter(source.SubCenter(border));
actMinX(source.SubMinX(border)); actMaxX(source.SubMaxX(border));
actMinY(source.SubMinY(border)); actMaxY(source.SubMaxY(border));
actMinXMinY(source.SubMinXMinY(border)); actMaxXMinY(source.SubMaxXMinY(border));
actMinXMaxY(source.SubMinXMaxY(border)); actMaxXMaxY(source.SubMaxXMaxY(border));
}
#endregion
#region Specific Matrix Border Manipulations
/// <summary>
/// Creates a new matrix with a border of the supplied size around the supplied matrix.
/// The resulting matrix retains the coordinates of the original matrix.
/// </summary>
public static Matrix<T> CopyWithBorderWindow<T>(this Matrix<T> matrix, Border2l border)
{
var bm = new Matrix<T>(matrix.SX + border.Min.X + border.Max.X,
matrix.SY + border.Min.Y + border.Max.Y)
{ F = new V2l(matrix.FX - border.Min.X, matrix.FY - border.Min.Y) };
bm.SubCenter(border).Set(matrix);
return bm;
}
/// <summary>
/// Creates a new matrix with a border of the supplied size around the supplied matrix.
/// The resulting matrix retains the coordinates of the original matrix.
/// </summary>
public static Matrix<T1> MapWithBorderWindow<T, T1>(
this Matrix<T> matrix, Border2l border,
Func<T, T1> item_fun)
{
var bm = new Matrix<T1>(matrix.SX + border.Min.X + border.Max.X,
matrix.SY + border.Min.Y + border.Max.Y)
{ F = new V2l(matrix.FX - border.Min.X, matrix.FY - border.Min.Y) };
bm.SubCenter(border).SetMap(matrix, item_fun);
return bm;
}
/// <summary>
/// Creates a new matrix with a border of the supplied size around the supplied matrix.
/// the resulting matrix starts at zero coordinates.
/// </summary>
public static Matrix<T> CopyWithBorder<T>(this Matrix<T> matrix, Border2l border)
{
var bm = new Matrix<T>(matrix.SX + border.Min.X + border.Max.X,
matrix.SY + border.Min.Y + border.Max.Y);
bm.SubCenter(border).Set(matrix);
return bm;
}
/// <summary>
/// Creates a new matrix with a border of the supplied size around the supplied matrix.
/// the resulting matrix starts at zero coordinates.
/// </summary>
public static Matrix<T1> MapWithBorder<T, T1>(
this Matrix<T> matrix, Border2l border,
Func<T, T1> item_fun)
{
var bm = new Matrix<T1>(matrix.SX + border.Min.X + border.Max.X,
matrix.SY + border.Min.Y + border.Max.Y);
bm.SubCenter(border).SetMap(matrix, item_fun);
return bm;
}
/// <summary>
/// Set the border of a matrix to a specific value.
/// </summary>
public static void SetBorder<T>(this Matrix<T> matrix, Border2l border, T value)
{
matrix.ApplyCenterBordersAndCorners(border,
m => { },
m => m.Set(value), m => m.Set(value), m => m.Set(value), m => m.Set(value),
m => m.Set(value), m => m.Set(value), m => m.Set(value), m => m.Set(value));
}
/// <summary>
/// Replicate the border pixels of the center region outward.
/// </summary>
public static void ReplicateBorder<T>(this Matrix<T> matrix, Border2l border)
{
matrix.ApplyCenterBordersAndCorners(new Border2l(border.Min, border.Max),
m => { },
m => m.SetByCoord(y => m[m.EX, y], (y, x, vy) => vy),
m => m.SetByCoord(y => m[m.FX - 1, y], (y, x, vy) => vy),
m =>
{
var tm = m.SubMatrixWindow(m.F, m.S.YX, m.D.YX, m.F.YX);
tm.SetByCoord(y => tm[tm.EX, y], (y, x, vy) => vy);
},
m =>
{
var tm = m.SubMatrixWindow(m.F, m.S.YX, m.D.YX, m.F.YX);
tm.SetByCoord(y => tm[tm.FX - 1, y], (y, x, vy) => vy);
},
m => { var v = m[m.EX, m.EY]; m.SetByCoord((x, y) => v); },
m => { var v = m[m.FX - 1, m.EY]; m.SetByCoord((x, y) => v); },
m => { var v = m[m.EX, m.FY - 1]; m.SetByCoord((x, y) => v); },
m => { var v = m[m.FX - 1, m.FY - 1]; m.SetByCoord((x, y) => v); });
}
public static Matrix<T> GetMatrixFromTiles<T>(
this Border2l border, long x, long y, Func<long, long, Box.Flags, Matrix<T>> x_y_loadFun)
{
var flipped = border.Flipped;
var center = x_y_loadFun(x, y, Box.Flags.All);
if (center.IsInvalid) return center;
var result = center.CopyWithBorderWindow(border);
if (border.Min.Y > 0)
{
if (border.Min.X > 0)
{
var tnn = x_y_loadFun(x - 1, y - 1, Box.Flags.MaxXMaxY);
if (tnn.IsValid) result.SubMinXMinY(border).Set(tnn.SubMaxXMaxY(flipped));
}
var t0n = x_y_loadFun(x, y - 1, Box.Flags.MaxY);
if (t0n.IsValid) result.SubMinY(border).Set(t0n.SubMaxY(border.Min.Y));
if (border.Max.X > 0)
{
var tpn = x_y_loadFun(x + 1, y - 1, Box.Flags.MinXMaxY);
if (tpn.IsValid) result.SubMaxXMinY(border).Set(tpn.SubMinXMaxY(flipped));
}
}
if (border.Min.X > 0)
{
var tn0 = x_y_loadFun(x - 1, y, Box.Flags.MaxX);
if (tn0.IsValid) result.SubMinX(border).Set(tn0.SubMaxX(border.Min.X));
}
if (border.Max.X > 0)
{
var tp0 = x_y_loadFun(x + 1, y, Box.Flags.MinX);
if (tp0.IsValid) result.SubMaxX(border).Set(tp0.SubMinX(border.Max.X));
}
if (border.Max.Y > 0)
{
if (border.Min.X > 0)
{
var tnp = x_y_loadFun(x - 1, y + 1, Box.Flags.MaxXMinY);
if (tnp.IsValid) result.SubMinXMaxY(border).Set(tnp.SubMaxXMinY(flipped));
}
var t0p = x_y_loadFun(x, y + 1, Box.Flags.MinY);
if (t0p.IsValid) result.SubMaxY(border).Set(t0p.SubMinY(border.Max.Y));
if (border.Max.X > 0)
{
var tpp = x_y_loadFun(x + 1, y + 1, Box.Flags.MinXMinY);
if (tpp.IsValid) result.SubMaxXMaxY(border).Set(tpp.SubMinXMinY(flipped));
}
}
return result;
}
#endregion
#region Specific Volume Border Manipulations
/// <summary>
/// Creates a new image volume with a border of the supplied size
/// around the supplied image volume.
/// </summary>
public static Volume<T> CopyWithBorderWindow<T>(this Volume<T> volume, Border2l border)
{
var iv = new V3l(volume.SX + border.Min.X + border.Max.X,
volume.SY + border.Min.Y + border.Max.Y,
volume.SZ).CreateImageVolume<T>();
iv.F = new V3l(volume.FX - border.Min.X, volume.FY - border.Min.Y, volume.FZ);
iv.SubCenter(border).Set(volume);
return iv;
}
/// <summary>
/// Creates a new image volume with a border of the supplied size
/// around the supplied image volume.
/// </summary>
public static Volume<T1> MapWithBorderWindow<T, T1>(
this Volume<T> volume, Border2l border,
Func<T, T1> item_fun)
{
var iv = new V3l(volume.SX + border.Min.X + border.Max.X,
volume.SY + border.Min.Y + border.Max.Y,
volume.SZ).CreateImageVolume<T1>();
iv.F = new V3l(volume.FX - border.Min.X, volume.FY - border.Min.Y, volume.FZ);
iv.SubCenter(border).SetMap(volume, item_fun);
return iv;
}
/// <summary>
/// Creates a new image volume with a border of the supplied size
/// around the supplied image volume.
/// </summary>
public static Volume<T> CopyWithBorder<T>(this Volume<T> volume, Border2l border)
{
var iv = new V3l(volume.SX + border.Min.X + border.Max.X,
volume.SY + border.Min.Y + border.Max.Y,
volume.SZ).CreateImageVolume<T>();
iv.SubCenter(border).Set(volume);
return iv;
}
/// <summary>
/// Creates a new image volume with a border of the supplied size
/// around the supplied image volume.
/// </summary>
public static Volume<T1> MapWithBorder<T, T1>(
this Volume<T> volume, Border2l border,
Func<T, T1> item_fun)
{
var iv = new V3l(volume.SX + border.Min.X + border.Max.X,
volume.SY + border.Min.Y + border.Max.Y,
volume.SZ).CreateImageVolume<T1>();
iv.SubCenter(border).SetMap(volume, item_fun);
return iv;
}
/// <summary>
/// Set the border of an image volume to a specific value.
/// </summary>
public static void SetBorder<T>(this Volume<T> volume, Border2l border, T value)
{
volume.ApplyCenterBordersAndCorners(border,
v => { },
v => v.Set(value), v => v.Set(value), v => v.Set(value), v => v.Set(value),
v => v.Set(value), v => v.Set(value), v => v.Set(value), v => v.Set(value));
}
/// <summary>
/// Replicate the border pixels of the center region outward.
/// </summary>
public static void ReplicateBorder<T>(this Volume<T> volume, Border2l border)
{
volume.ApplyCenterBordersAndCorners(border,
v => { },
v => v.SetByCoord(z => false, (z, y, vz) => v[v.EX, y, z], (z, y, x, vz, vy) => vy),
v => v.SetByCoord(z => false, (z, y, vz) => v[v.FX - 1, y, z], (z, y, x, vz, vy) => vy),
v =>
{
var tv = v.SubVolumeWindow(v.F, v.S.YXZ, v.D.YXZ, v.F.YXZ);
tv.SetByCoord(z => false, (z, y, vz) => tv[tv.EX, y, z], (z, y, x, vz, vy) => vy);
},
v =>
{
var tv = v.SubVolumeWindow(v.F, v.S.YXZ, v.D.YXZ, v.F.YXZ);
tv.SetByCoord(z => false, (z, y, vz) => tv[tv.FX - 1, y, z], (z, y, x, vz, vy) => vy);
},
v => v.SetByCoord(z => v[v.EX, v.EY, z], (z, y, vz) => false, (z, y, x, vz, vy) => vz),
v => v.SetByCoord(z => v[v.FX - 1, v.EY, z], (z, y, vz) => false, (z, y, x, vz, vy) => vz),
v => v.SetByCoord(z => v[v.EX, v.FY - 1, z], (z, y, vz) => false, (z, y, x, vz, vy) => vz),
v => v.SetByCoord(z => v[v.FX - 1, v.FY - 1, z], (z, y, vz) => false, (z, y, x, vz, vy) => vz));
}
public static Volume<T> GetMatrixFromTiles<T>(
this Border2l border, long x, long y, Func<long, long, Box.Flags, Volume<T>> x_y_loadFun)
{
var flipped = border.Flipped;
var center = x_y_loadFun(x, y, Box.Flags.All);
if (center.IsInvalid) return center;
var result = center.CopyWithBorderWindow(border);
if (border.Min.Y > 0)
{
if (border.Min.X > 0)
{
var tnn = x_y_loadFun(x - 1, y - 1, Box.Flags.MaxXMaxY);
if (tnn.IsValid) result.SubMinXMinY(border).Set(tnn.SubMaxXMaxY(flipped));
}
var t0n = x_y_loadFun(x, y - 1, Box.Flags.MaxY);
if (t0n.IsValid) result.SubMinY(border).Set(t0n.SubMaxY(border.Min.Y));
if (border.Max.X > 0)
{
var tpn = x_y_loadFun(x + 1, y - 1, Box.Flags.MinXMaxY);
if (tpn.IsValid) result.SubMaxXMinY(border).Set(tpn.SubMinXMaxY(flipped));
}
}
if (border.Min.X > 0)
{
var tn0 = x_y_loadFun(x - 1, y, Box.Flags.MaxX);
if (tn0.IsValid) result.SubMinX(border).Set(tn0.SubMaxX(border.Min.X));
}
if (border.Max.X > 0)
{
var tp0 = x_y_loadFun(x + 1, y, Box.Flags.MinX);
if (tp0.IsValid) result.SubMaxX(border).Set(tp0.SubMinX(border.Max.X));
}
if (border.Max.Y > 0)
{
if (border.Min.X > 0)
{
var tnp = x_y_loadFun(x - 1, y + 1, Box.Flags.MaxXMinY);
if (tnp.IsValid) result.SubMinXMaxY(border).Set(tnp.SubMaxXMinY(flipped));
}
var t0p = x_y_loadFun(x, y + 1, Box.Flags.MinY);
if (t0p.IsValid) result.SubMaxY(border).Set(t0p.SubMinY(border.Max.Y));
if (border.Max.X > 0)
{
var tpp = x_y_loadFun(x + 1, y + 1, Box.Flags.MinXMinY);
if (tpp.IsValid) result.SubMaxXMaxY(border).Set(tpp.SubMinXMinY(flipped));
}
}
return result;
}
#endregion
}
}
| |
//
// BansheeDbFormatMigrator.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2007-2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Reflection;
using System.Text;
using System.Threading;
using Mono.Unix;
using Hyena;
using Hyena.Jobs;
using Hyena.Data.Sqlite;
using Timer=Hyena.Timer;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Streaming;
// MIGRATION NOTE: Return true if the step should allow the driver to continue
// Return false if the step should terminate driver
namespace Banshee.Database
{
public class BansheeDbFormatMigrator
{
// NOTE: Whenever there is a change in ANY of the database schema,
// this version MUST be incremented and a migration method
// MUST be supplied to match the new version number
protected const int CURRENT_VERSION = 43;
protected const int CURRENT_METADATA_VERSION = 7;
#region Migration Driver
public delegate void SlowStartedHandler(string title, string message);
public event SlowStartedHandler SlowStarted;
public event EventHandler SlowPulse;
public event EventHandler SlowFinished;
public event EventHandler Started;
public event EventHandler Finished;
protected sealed class DatabaseVersionAttribute : Attribute
{
private int version;
public DatabaseVersionAttribute(int version)
{
this.version = version;
}
public int Version {
get { return version; }
}
}
private HyenaSqliteConnection connection;
public BansheeDbFormatMigrator (HyenaSqliteConnection connection)
{
this.connection = connection;
}
protected virtual void OnSlowStarted(string title, string message)
{
SlowStartedHandler handler = SlowStarted;
if(handler != null) {
handler(title, message);
}
}
protected virtual void OnSlowPulse()
{
EventHandler handler = SlowPulse;
if(handler != null) {
handler(this, EventArgs.Empty);
}
}
protected virtual void OnSlowFinished()
{
EventHandler handler = SlowFinished;
if(handler != null) {
handler(this, EventArgs.Empty);
}
}
protected virtual void OnStarted ()
{
EventHandler handler = Started;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
protected virtual void OnFinished ()
{
EventHandler handler = Finished;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
public void Migrate ()
{
try {
if (DatabaseVersion > CURRENT_VERSION) {
throw new DatabaseVersionTooHigh (CURRENT_VERSION, DatabaseVersion);
} else if (DatabaseVersion < CURRENT_VERSION) {
Execute ("BEGIN");
InnerMigrate ();
Execute ("COMMIT");
} else {
Log.DebugFormat ("Database version {0} is up to date", DatabaseVersion);
}
// Trigger metadata refreshes if necessary
int metadata_version = connection.Query<int> ("SELECT Value FROM CoreConfiguration WHERE Key = 'MetadataVersion'");
if (DatabaseVersion == CURRENT_VERSION && metadata_version < CURRENT_METADATA_VERSION) {
ServiceManager.ServiceStarted += OnServiceStarted;
}
} catch (DatabaseVersionTooHigh) {
throw;
} catch (Exception) {
Log.Warning ("Rolling back database migration");
Execute ("ROLLBACK");
throw;
}
OnFinished ();
}
private void InnerMigrate ()
{
MethodInfo [] methods = GetType ().GetMethods (BindingFlags.Instance | BindingFlags.NonPublic);
bool terminate = false;
bool ran_migration_step = false;
Log.DebugFormat ("Migrating from database version {0} to {1}", DatabaseVersion, CURRENT_VERSION);
for (int i = DatabaseVersion + 1; i <= CURRENT_VERSION; i++) {
foreach (MethodInfo method in methods) {
foreach (DatabaseVersionAttribute attr in method.GetCustomAttributes (
typeof (DatabaseVersionAttribute), false)) {
if (attr.Version != i) {
continue;
}
if (!ran_migration_step) {
ran_migration_step = true;
OnStarted ();
}
if (!(bool)method.Invoke (this, null)) {
terminate = true;
}
break;
}
}
if (terminate) {
break;
}
}
Execute (String.Format ("UPDATE CoreConfiguration SET Value = {0} WHERE Key = 'DatabaseVersion'", CURRENT_VERSION));
}
protected bool TableExists(string tableName)
{
return connection.TableExists (tableName);
}
protected void Execute(string query)
{
connection.Execute (query);
}
protected int DatabaseVersion {
get {
if (!TableExists("CoreConfiguration")) {
return 0;
}
return connection.Query<int> ("SELECT Value FROM CoreConfiguration WHERE Key = 'DatabaseVersion'");
}
}
#endregion
#pragma warning disable 0169
#region Version 1
[DatabaseVersion (1)]
private bool Migrate_1 ()
{
if (TableExists("Tracks")) {
InitializeFreshDatabase (true);
uint timer_id = Log.DebugTimerStart ("Database Schema Migration");
OnSlowStarted (Catalog.GetString ("Upgrading your Banshee Database"),
Catalog.GetString ("Please wait while your old Banshee database is migrated to the new format."));
Thread thread = new Thread (MigrateFromLegacyBanshee);
thread.Name = "Database Migrator";
thread.Start ();
while (thread.IsAlive) {
OnSlowPulse ();
Thread.Sleep (100);
}
Log.DebugTimerPrint (timer_id);
OnSlowFinished ();
return false;
} else {
InitializeFreshDatabase (false);
return false;
}
}
#endregion
#region Version 2
[DatabaseVersion (2)]
private bool Migrate_2 ()
{
Execute (String.Format ("ALTER TABLE CoreTracks ADD COLUMN Attributes INTEGER DEFAULT {0}",
(int)TrackMediaAttributes.Default));
return true;
}
#endregion
#region Version 3
[DatabaseVersion (3)]
private bool Migrate_3 ()
{
Execute ("ALTER TABLE CorePlaylists ADD COLUMN PrimarySourceID INTEGER");
Execute ("UPDATE CorePlaylists SET PrimarySourceID = 1");
Execute ("ALTER TABLE CoreSmartPlaylists ADD COLUMN PrimarySourceID INTEGER");
Execute ("UPDATE CoreSmartPlaylists SET PrimarySourceID = 1");
return true;
}
#endregion
#region Version 4
[DatabaseVersion (4)]
private bool Migrate_4 ()
{
Execute ("ALTER TABLE CoreTracks ADD COLUMN LastSkippedStamp INTEGER");
return true;
}
#endregion
#region Version 5
[DatabaseVersion (5)]
private bool Migrate_5 ()
{
Execute ("ALTER TABLE CoreTracks ADD COLUMN TitleLowered TEXT");
Execute ("ALTER TABLE CoreArtists ADD COLUMN NameLowered TEXT");
Execute ("ALTER TABLE CoreAlbums ADD COLUMN TitleLowered TEXT");
// Set default so sorting isn't whack while we regenerate
Execute ("UPDATE CoreTracks SET TitleLowered = lower(Title)");
Execute ("UPDATE CoreArtists SET NameLowered = lower(Name)");
Execute ("UPDATE CoreAlbums SET TitleLowered = lower(Title)");
// Drop old indexes
Execute ("DROP INDEX IF EXISTS CoreTracksPrimarySourceIndex");
Execute ("DROP INDEX IF EXISTS CoreTracksArtistIndex");
Execute ("DROP INDEX IF EXISTS CoreTracksAlbumIndex");
Execute ("DROP INDEX IF EXISTS CoreTracksRatingIndex");
Execute ("DROP INDEX IF EXISTS CoreTracksLastPlayedStampIndex");
Execute ("DROP INDEX IF EXISTS CoreTracksDateAddedStampIndex");
Execute ("DROP INDEX IF EXISTS CoreTracksPlayCountIndex");
Execute ("DROP INDEX IF EXISTS CoreTracksTitleIndex");
Execute ("DROP INDEX IF EXISTS CoreAlbumsIndex");
Execute ("DROP INDEX IF EXISTS CoreAlbumsArtistID");
Execute ("DROP INDEX IF EXISTS CoreArtistsIndex");
Execute ("DROP INDEX IF EXISTS CorePlaylistEntriesIndex");
Execute ("DROP INDEX IF EXISTS CorePlaylistTrackIDIndex");
Execute ("DROP INDEX IF EXISTS CoreSmartPlaylistEntriesPlaylistIndex");
Execute ("DROP INDEX IF EXISTS CoreSmartPlaylistEntriesTrackIndex");
// Create new indexes
Execute ("CREATE INDEX IF NOT EXISTS CoreTracksIndex ON CoreTracks(ArtistID, AlbumID, PrimarySourceID, Disc, TrackNumber, Uri)");
Execute ("CREATE INDEX IF NOT EXISTS CoreArtistsIndex ON CoreArtists(NameLowered)");
Execute ("CREATE INDEX IF NOT EXISTS CoreAlbumsIndex ON CoreAlbums(ArtistID, TitleLowered)");
Execute ("CREATE INDEX IF NOT EXISTS CoreSmartPlaylistEntriesIndex ON CoreSmartPlaylistEntries(SmartPlaylistID, TrackID)");
Execute ("CREATE INDEX IF NOT EXISTS CorePlaylistEntriesIndex ON CorePlaylistEntries(PlaylistID, TrackID)");
return true;
}
#endregion
#region Version 6
[DatabaseVersion (6)]
private bool Migrate_6 ()
{
Execute ("INSERT INTO CoreConfiguration (EntryID, Key, Value) VALUES (null, 'MetadataVersion', 0)");
return true;
}
#endregion
#region Version 7
[DatabaseVersion (7)]
private bool Migrate_7 ()
{
try { Execute ("UPDATE CorePrimarySources SET StringID = 'MusicLibrarySource-Library' WHERE StringID = 'Library'"); } catch {}
try { Execute ("UPDATE CorePrimarySources SET StringID = 'VideoLibrarySource-VideoLibrary' WHERE StringID = 'VideoLibrary'"); } catch {}
try { Execute ("UPDATE CorePrimarySources SET StringID = 'PodcastSource-podcasting' WHERE StringID = 'podcasting'"); } catch {}
try { Execute ("DELETE FROM CoreCache; DELETE FROM CoreCacheModels"); } catch {}
return true;
}
#endregion
#region Version 8
[DatabaseVersion (8)]
private bool Migrate_8 ()
{
Execute ("ALTER TABLE CorePrimarySources ADD COLUMN CachedCount INTEGER");
Execute ("ALTER TABLE CorePlaylists ADD COLUMN CachedCount INTEGER");
Execute ("ALTER TABLE CoreSmartPlaylists ADD COLUMN CachedCount INTEGER");
// This once, we need to reload all the sources at start up. Then never again, woo!
Application.ClientStarted += ReloadAllSources;
return true;
}
#endregion
#region Version 9
[DatabaseVersion (9)]
private bool Migrate_9 ()
{
Execute (String.Format ("ALTER TABLE CoreTracks ADD COLUMN LastStreamError INTEGER DEFAULT {0}",
(int)StreamPlaybackError.None));
return true;
}
#endregion
#region Version 10
[DatabaseVersion (10)]
private bool Migrate_10 ()
{
// Clear these out for people who ran the pre-alpha podcast plugin
Execute ("DROP TABLE IF EXISTS PodcastEnclosures");
Execute ("DROP TABLE IF EXISTS PodcastItems");
Execute ("DROP TABLE IF EXISTS PodcastSyndications");
Execute ("ALTER TABLE CoreTracks ADD COLUMN ExternalID INTEGER");
return true;
}
#endregion
#region Version 11
[DatabaseVersion (11)]
private bool Migrate_11 ()
{
Execute("CREATE INDEX CoreTracksExternalIDIndex ON CoreTracks(PrimarySourceID, ExternalID)");
return true;
}
#endregion
#region Version 12
[DatabaseVersion (12)]
private bool Migrate_12 ()
{
Execute ("ALTER TABLE CoreAlbums ADD COLUMN ArtistName STRING");
Execute ("ALTER TABLE CoreAlbums ADD COLUMN ArtistNameLowered STRING");
return true;
}
#endregion
#region Version 13
[DatabaseVersion (13)]
private bool Migrate_13 ()
{
Execute("CREATE INDEX CoreAlbumsArtistIndex ON CoreAlbums(TitleLowered, ArtistNameLowered)");
Execute("CREATE INDEX CoreTracksUriIndex ON CoreTracks(PrimarySourceID, Uri)");
return true;
}
#endregion
#region Version 14
[DatabaseVersion (14)]
private bool Migrate_14 ()
{
InitializeOrderedTracks ();
return true;
}
#endregion
#region Version 15
[DatabaseVersion (15)]
private bool Migrate_15 ()
{
string [] columns = new string [] {"Genre", "Composer", "Copyright", "LicenseUri", "Comment"};
foreach (string column in columns) {
Execute (String.Format ("UPDATE CoreTracks SET {0} = NULL WHERE {0} IS NOT NULL AND trim({0}) = ''", column));
}
return true;
}
#endregion
#region Version 16
[DatabaseVersion (16)]
private bool Migrate_16 ()
{
// The CoreCache table is now created as needed, and as a TEMP table
Execute ("DROP TABLE CoreCache");
Execute ("COMMIT; VACUUM; BEGIN");
Execute ("ANALYZE");
return true;
}
#endregion
#region Version 17
[DatabaseVersion (17)]
private bool Migrate_17 ()
{
Execute ("CREATE INDEX CoreTracksCoverArtIndex ON CoreTracks (PrimarySourceID, AlbumID, DateUpdatedStamp)");
Execute ("ANALYZE");
return true;
}
#endregion
#region Version 18
[DatabaseVersion (18)]
private bool Migrate_18 ()
{
Execute ("ALTER TABLE CoreTracks ADD COLUMN MetadataHash TEXT");
return true;
}
#endregion
#region Version 19
[DatabaseVersion (19)]
private bool Migrate_19 ()
{
Execute ("ALTER TABLE CoreAlbums ADD COLUMN IsCompilation INTEGER DEFAULT 0");
Execute ("ALTER TABLE CoreTracks ADD COLUMN BPM INTEGER");
Execute ("ALTER TABLE CoreTracks ADD COLUMN DiscCount INTEGER");
Execute ("ALTER TABLE CoreTracks ADD COLUMN Conductor TEXT");
Execute ("ALTER TABLE CoreTracks ADD COLUMN Grouping TEXT");
Execute ("ALTER TABLE CoreTracks ADD COLUMN BitRate INTEGER DEFAULT 0");
return true;
}
#endregion
#region Version 20
[DatabaseVersion (20)]
private bool Migrate_20 ()
{
Execute ("ALTER TABLE CoreSmartPlaylists ADD COLUMN IsTemporary INTEGER DEFAULT 0");
Execute ("ALTER TABLE CorePlaylists ADD COLUMN IsTemporary INTEGER DEFAULT 0");
Execute ("ALTER TABLE CorePrimarySources ADD COLUMN IsTemporary INTEGER DEFAULT 0");
return true;
}
#endregion
#region Version 21
[DatabaseVersion (21)]
private bool Migrate_21 ()
{
// We had a bug where downloaded podcast episodes would no longer have the Podcast attribute.
int id = connection.Query<int> ("SELECT PrimarySourceId FROM CorePrimarySources WHERE StringID = 'PodcastSource-PodcastLibrary'");
if (id > 0) {
connection.Execute ("UPDATE CoreTracks SET Attributes = Attributes | ? WHERE PrimarySourceID = ?", (int)TrackMediaAttributes.Podcast, id);
}
return true;
}
#endregion
#region Version 22
[DatabaseVersion (22)]
private bool Migrate_22 ()
{
Execute ("ALTER TABLE CoreTracks ADD COLUMN LastSyncedStamp INTEGER DEFAULT NULL");
Execute ("ALTER TABLE CoreTracks ADD COLUMN FileModifiedStamp INTEGER DEFAULT NULL");
Execute ("UPDATE CoreTracks SET LastSyncedStamp = DateAddedStamp;");
return true;
}
#endregion
#region Version 23
[DatabaseVersion (23)]
private bool Migrate_23 ()
{
Execute ("ALTER TABLE CoreArtists ADD COLUMN NameSort TEXT");
Execute ("ALTER TABLE CoreAlbums ADD COLUMN ArtistNameSort TEXT");
Execute ("ALTER TABLE CoreAlbums ADD COLUMN TitleSort TEXT");
Execute ("ALTER TABLE CoreTracks ADD COLUMN TitleSort TEXT");
return true;
}
#endregion
#region Version 24
[DatabaseVersion (24)]
private bool Migrate_24 ()
{
Execute ("UPDATE CoreArtists SET NameLowered = HYENA_SEARCH_KEY(Name)");
Execute ("UPDATE CoreAlbums SET ArtistNameLowered = HYENA_SEARCH_KEY(ArtistName)");
Execute ("UPDATE CoreAlbums SET TitleLowered = HYENA_SEARCH_KEY(Title)");
Execute ("UPDATE CoreTracks SET TitleLowered = HYENA_SEARCH_KEY(Title)");
return true;
}
#endregion
#region Version 25
[DatabaseVersion (25)]
private bool Migrate_25 ()
{
Execute ("ALTER TABLE CoreArtists ADD COLUMN NameSortKey BLOB");
Execute ("ALTER TABLE CoreAlbums ADD COLUMN ArtistNameSortKey BLOB");
Execute ("ALTER TABLE CoreAlbums ADD COLUMN TitleSortKey BLOB");
Execute ("ALTER TABLE CoreTracks ADD COLUMN TitleSortKey BLOB");
return true;
}
#endregion
#region Version 26
[DatabaseVersion (26)]
private bool Migrate_26 ()
{
string unknown_artist = "Unknown Artist";
string unknown_album = "Unknown Album";
string unknown_title = "Unknown Title";
connection.Execute ("UPDATE CoreArtists SET Name = NULL, NameLowered = HYENA_SEARCH_KEY(?)" +
" WHERE Name IN ('', ?, ?) OR Name IS NULL",
ArtistInfo.UnknownArtistName, unknown_artist, ArtistInfo.UnknownArtistName);
connection.Execute ("UPDATE CoreAlbums SET ArtistName = NULL, ArtistNameLowered = HYENA_SEARCH_KEY(?)" +
" WHERE ArtistName IN ('', ?, ?) OR ArtistName IS NULL",
ArtistInfo.UnknownArtistName, unknown_artist, ArtistInfo.UnknownArtistName);
connection.Execute ("UPDATE CoreAlbums SET Title = NULL, TitleLowered = HYENA_SEARCH_KEY(?)" +
" WHERE Title IN ('', ?, ?) OR Title IS NULL",
AlbumInfo.UnknownAlbumTitle, unknown_album, AlbumInfo.UnknownAlbumTitle);
connection.Execute ("UPDATE CoreTracks SET Title = NULL, TitleLowered = HYENA_SEARCH_KEY(?)" +
" WHERE Title IN ('', ?, ?) OR Title IS NULL",
TrackInfo.UnknownTitle, unknown_title, TrackInfo.UnknownTitle);
return true;
}
#endregion
#region Version 27
[DatabaseVersion (27)]
private bool Migrate_27 ()
{
// One time fixup to MetadataHash now that our unknown metadata is handled properly
string sql_select = @"
SELECT t.TrackID, al.Title, ar.Name, t.Duration,
t.Genre, t.Title, t.TrackNumber, t.Year
FROM CoreTracks AS t
JOIN CoreAlbums AS al ON al.AlbumID=t.AlbumID
JOIN CoreArtists AS ar ON ar.ArtistID=t.ArtistID
WHERE t.Title IS NULL OR ar.Name IS NULL OR al.Title IS NULL
";
HyenaSqliteCommand sql_update = new HyenaSqliteCommand (@"
UPDATE CoreTracks SET MetadataHash = ? WHERE TrackID = ?
");
StringBuilder sb = new StringBuilder ();
using (var reader = new HyenaDataReader (connection.Query (sql_select))) {
while (reader.Read ()) {
sb.Length = 0;
sb.Append (reader.Get<string> (1));
sb.Append (reader.Get<string> (2));
sb.Append ((int)reader.Get<TimeSpan> (3).TotalSeconds);
sb.Append (reader.Get<string> (4));
sb.Append (reader.Get<string> (5));
sb.Append (reader.Get<int> (6));
sb.Append (reader.Get<int> (7));
string hash = Hyena.CryptoUtil.Md5Encode (sb.ToString (), System.Text.Encoding.UTF8);
connection.Execute (sql_update, hash, reader.Get<int> (0));
}
}
return true;
}
#endregion
#region Version 28
[DatabaseVersion (28)]
private bool Migrate_28 ()
{
// Update search keys for new space-stripping behavior.
connection.Execute ("UPDATE CoreArtists SET NameLowered = HYENA_SEARCH_KEY(IFNULL(Name, ?))",
ArtistInfo.UnknownArtistName);
connection.Execute ("UPDATE CoreAlbums SET ArtistNameLowered = HYENA_SEARCH_KEY(IFNULL(ArtistName, ?))," +
" TitleLowered = HYENA_SEARCH_KEY(IFNULL(Title, ?))",
ArtistInfo.UnknownArtistName, AlbumInfo.UnknownAlbumTitle);
connection.Execute ("UPDATE CoreTracks SET TitleLowered = HYENA_SEARCH_KEY(IFNULL(Title, ?))",
TrackInfo.UnknownTitle);
return true;
}
#endregion
#region Version 29
[DatabaseVersion (29)]
private bool Migrate_29 ()
{
Execute ("ALTER TABLE CoreTracks ADD COLUMN Score INTEGER DEFAULT 0");
Execute (@"
UPDATE CoreTracks
SET Score = CAST(ROUND(100.00 * PlayCount / (PlayCount + SkipCount)) AS INTEGER)
WHERE PlayCount + SkipCount > 0
");
return true;
}
#endregion
#region Version 30
[DatabaseVersion (30)]
private bool Migrate_30 ()
{
Execute ("DROP INDEX IF EXISTS CoreAlbumsIndex");
Execute ("DROP INDEX IF EXISTS CoreAlbumsArtistIndex");
Execute ("DROP INDEX IF EXISTS CoreArtistsIndex");
Execute ("CREATE INDEX CoreAlbumsIndex ON CoreAlbums(ArtistID, TitleSortKey)");
Execute ("CREATE INDEX CoreAlbumsArtistIndex ON CoreAlbums(TitleSortKey, ArtistNameSortKey)");
Execute ("CREATE INDEX CoreArtistsIndex ON CoreArtists(NameSortKey)");
Execute ("ANALYZE");
return true;
}
#endregion
#region Version 31
[DatabaseVersion (31)]
private bool Migrate_31 ()
{
try {
// Make paths not relative for Music Library items
string library_path = Banshee.Library.LibrarySource.OldLocationSchema.Get (Banshee.Library.MusicLibrarySource.GetDefaultBaseDirectory ());
if (library_path != null) {
connection.AddFunction<MigratePartialFunction> ();
int podcast_src_id = connection.Query<int> ("SELECT PrimarySourceID FROM CorePrimarySources WHERE StringID = 'PodcastSource-PodcastLibrary'");
connection.Execute (@"
UPDATE CoreTracks SET Uri = BANSHEE_MIGRATE_PARTIAL(?, Uri)
WHERE UriType = 1
AND PrimarySourceID != ?", library_path, podcast_src_id);
string podcast_path = Paths.Combine (library_path, "Podcasts");
connection.Execute (@"
UPDATE CoreTracks SET Uri = BANSHEE_MIGRATE_PARTIAL(?, Uri)
WHERE UriType = 1
AND PrimarySourceID = ?", podcast_path, podcast_src_id);
connection.RemoveFunction<MigratePartialFunction> ();
}
} catch (Exception e) {
Hyena.Log.Exception (e);
}
return true;
}
#endregion
#region Version 32
[DatabaseVersion (32)]
private bool Migrate_32 ()
{
Execute ("DROP INDEX IF EXISTS CoreSmartPlaylistEntriesPlaylistIndex");
Execute ("DROP INDEX IF EXISTS CoreSmartPlaylistEntriesIndex");
Execute ("ANALYZE");
return true;
}
#endregion
#region Version 33
[DatabaseVersion (33)]
private bool Migrate_33 ()
{
// We used to have a bug where MimeType didn't get set for tracks we ripped,
// so set any blank ones now. See BGO #536590
foreach (var ext in new string [] {"mp3", "ogg", "flac", "aac", "oga", "wma", "wm"}) {
Execute (String.Format (
"UPDATE CoreTracks SET MimeType = 'taglib/{0}' WHERE PrimarySourceId = 1 AND (MimeType IS NULL OR MimeType = '') AND Uri LIKE '%.{0}'", ext
));
}
return true;
}
#endregion
#region Version 34
[DatabaseVersion (34)]
private bool Migrate_34 ()
{
Execute ("CREATE INDEX IF NOT EXISTS CoreSmartPlaylistEntriesIndex ON CoreSmartPlaylistEntries(SmartPlaylistID, TrackID)");
return true;
}
#endregion
#region Version 35
[DatabaseVersion (35)]
private bool Migrate_35 ()
{
if (!connection.ColumnExists ("CorePlaylistEntries", "Generated")) {
Execute ("ALTER TABLE CorePlaylistEntries ADD COLUMN Generated INTEGER NOT NULL DEFAULT 0");
}
return true;
}
#endregion
#region Version 36
[DatabaseVersion (36)]
private bool Migrate_36 ()
{
Execute(@"
CREATE TABLE CoreShuffles (
ShufflerId INTEGER,
TrackID INTEGER,
LastShuffledAt INTEGER,
CONSTRAINT one_entry_per_track UNIQUE (ShufflerID, TrackID)
)
");
Execute("CREATE INDEX CoreShufflesIndex ON CoreShuffles (ShufflerId, TrackID, LastShuffledAt)");
Execute(@"
CREATE TABLE CoreShufflers (
ShufflerId INTEGER PRIMARY KEY,
Id TEXT UNIQUE
)
");
return true;
}
#endregion
#region Version 37
[DatabaseVersion (37)]
private bool Migrate_37 ()
{
SortKeyUpdater.ForceUpdate ();
return true;
}
#endregion
#region Version 38
[DatabaseVersion (38)]
private bool Migrate_38 ()
{
Execute ("ALTER TABLE CoreTracks ADD COLUMN SampleRate INTEGER DEFAULT 0");
Execute ("ALTER TABLE CoreTracks ADD COLUMN BitsPerSample INTEGER DEFAULT 0");
return true;
}
#endregion
#region Version 39
[DatabaseVersion (39)]
private bool Migrate_39 ()
{
// One time fixup to MetadataHash, since we no longer include the Duration
string sql_select = @"
SELECT t.TrackID, al.Title, ar.Name,
t.Genre, t.Title, t.TrackNumber, t.Year
FROM CoreTracks AS t
JOIN CoreAlbums AS al ON al.AlbumID=t.AlbumID
JOIN CoreArtists AS ar ON ar.ArtistID=t.ArtistID
";
HyenaSqliteCommand sql_update = new HyenaSqliteCommand (@"
UPDATE CoreTracks SET MetadataHash = ? WHERE TrackID = ?
");
StringBuilder sb = new StringBuilder ();
using (var reader = new HyenaDataReader (connection.Query (sql_select))) {
while (reader.Read ()) {
sb.Length = 0;
sb.Append (reader.Get<string> (1));
sb.Append (reader.Get<string> (2));
sb.Append (reader.Get<string> (3));
sb.Append (reader.Get<string> (4));
sb.Append (reader.Get<int> (5));
sb.Append (reader.Get<int> (6));
string hash = Hyena.CryptoUtil.Md5Encode (sb.ToString (), System.Text.Encoding.UTF8);
connection.Execute (sql_update, hash, reader.Get<int> (0));
}
}
return true;
}
#endregion
[DatabaseVersion (40)]
private bool Migrate_40 ()
{
Execute(@"
CREATE TABLE CoreShuffleDiscards (
ShufflerId INTEGER,
TrackID INTEGER,
LastDiscardedAt INTEGER,
CONSTRAINT one_entry_per_track UNIQUE (ShufflerID, TrackID)
)
");
Execute("CREATE INDEX CoreShuffleDiscardsIndex ON CoreShuffleDiscards (ShufflerId, TrackID, LastDiscardedAt)");
return true;
}
[DatabaseVersion (41)]
private bool Migrate_41 ()
{
Execute ("DROP TABLE IF EXISTS CoreShuffleDiscards");
Execute ("DROP INDEX IF EXISTS CoreShuffleDiscardsIndex");
Execute (@"
CREATE TABLE CoreShuffleModifications (
ShufflerId INTEGER,
TrackID INTEGER,
LastModifiedAt INTEGER,
ModificationType INTEGER,
CONSTRAINT one_entry_per_track UNIQUE (ShufflerID, TrackID)
)
");
Execute ("CREATE INDEX CoreShuffleModificationsIndex ON CoreShuffleModifications (ShufflerId, TrackID, LastModifiedAt, ModificationType)");
return true;
}
[DatabaseVersion (42)]
private bool Migrate_42 ()
{
// Unset the Music attribute for any videos or podcasts
connection.Execute (
@"UPDATE CoreTracks SET Attributes = Attributes & ? WHERE (Attributes & ?) != 0",
(int)(~TrackMediaAttributes.Music),
(int)(TrackMediaAttributes.VideoStream | TrackMediaAttributes.Podcast)
);
return true;
}
[DatabaseVersion (43)]
private bool Migrate_43 ()
{
Execute ("ALTER TABLE CoreSmartPlaylists ADD COLUMN IsHiddenWhenEmpty INTEGER");
return true;
}
#pragma warning restore 0169
#region Fresh database setup
private void InitializeFreshDatabase (bool refresh_metadata)
{
Execute("DROP TABLE IF EXISTS CoreConfiguration");
Execute("DROP TABLE IF EXISTS CoreTracks");
Execute("DROP TABLE IF EXISTS CoreArtists");
Execute("DROP TABLE IF EXISTS CoreAlbums");
Execute("DROP TABLE IF EXISTS CorePlaylists");
Execute("DROP TABLE IF EXISTS CorePlaylistEntries");
Execute("DROP TABLE IF EXISTS CoreSmartPlaylists");
Execute("DROP TABLE IF EXISTS CoreSmartPlaylistEntries");
Execute("DROP TABLE IF EXISTS CoreRemovedTracks");
Execute("DROP TABLE IF EXISTS CoreTracksCache");
Execute("DROP TABLE IF EXISTS CoreCache");
Execute(@"
CREATE TABLE CoreConfiguration (
EntryID INTEGER PRIMARY KEY,
Key TEXT,
Value TEXT
)
");
Execute (String.Format ("INSERT INTO CoreConfiguration (EntryID, Key, Value) VALUES (null, 'DatabaseVersion', {0})", CURRENT_VERSION));
if (!refresh_metadata) {
Execute (String.Format ("INSERT INTO CoreConfiguration (EntryID, Key, Value) VALUES (null, 'MetadataVersion', {0})", CURRENT_METADATA_VERSION));
}
Execute(@"
CREATE TABLE CorePrimarySources (
PrimarySourceID INTEGER PRIMARY KEY,
StringID TEXT UNIQUE,
CachedCount INTEGER,
IsTemporary INTEGER DEFAULT 0
)
");
Execute ("INSERT INTO CorePrimarySources (StringID) VALUES ('MusicLibrarySource-Library')");
// TODO add these:
// Others to consider:
// AlbumArtist (TPE2) (in CoreAlbums?)
Execute(String.Format (@"
CREATE TABLE CoreTracks (
PrimarySourceID INTEGER NOT NULL,
TrackID INTEGER PRIMARY KEY,
ArtistID INTEGER,
AlbumID INTEGER,
TagSetID INTEGER,
ExternalID INTEGER,
MusicBrainzID TEXT,
Uri TEXT,
MimeType TEXT,
FileSize INTEGER,
BitRate INTEGER,
SampleRate INTEGER,
BitsPerSample INTEGER,
Attributes INTEGER DEFAULT {0},
LastStreamError INTEGER DEFAULT {1},
Title TEXT,
TitleLowered TEXT,
TitleSort TEXT,
TitleSortKey BLOB,
TrackNumber INTEGER,
TrackCount INTEGER,
Disc INTEGER,
DiscCount INTEGER,
Duration INTEGER,
Year INTEGER,
Genre TEXT,
Composer TEXT,
Conductor TEXT,
Grouping TEXT,
Copyright TEXT,
LicenseUri TEXT,
Comment TEXT,
Rating INTEGER,
Score INTEGER,
PlayCount INTEGER,
SkipCount INTEGER,
LastPlayedStamp INTEGER,
LastSkippedStamp INTEGER,
DateAddedStamp INTEGER,
DateUpdatedStamp INTEGER,
MetadataHash TEXT,
BPM INTEGER,
LastSyncedStamp INTEGER,
FileModifiedStamp INTEGER
)
", (int)TrackMediaAttributes.Default, (int)StreamPlaybackError.None));
Execute("CREATE INDEX CoreTracksPrimarySourceIndex ON CoreTracks(ArtistID, AlbumID, PrimarySourceID, Disc, TrackNumber, Uri)");
Execute("CREATE INDEX CoreTracksAggregatesIndex ON CoreTracks(FileSize, Duration)");
Execute("CREATE INDEX CoreTracksExternalIDIndex ON CoreTracks(PrimarySourceID, ExternalID)");
Execute("CREATE INDEX CoreTracksUriIndex ON CoreTracks(PrimarySourceID, Uri)");
Execute("CREATE INDEX CoreTracksCoverArtIndex ON CoreTracks (PrimarySourceID, AlbumID, DateUpdatedStamp)");
Execute(@"
CREATE TABLE CoreAlbums (
AlbumID INTEGER PRIMARY KEY,
ArtistID INTEGER,
TagSetID INTEGER,
MusicBrainzID TEXT,
Title TEXT,
TitleLowered TEXT,
TitleSort TEXT,
TitleSortKey BLOB,
ReleaseDate INTEGER,
Duration INTEGER,
Year INTEGER,
IsCompilation INTEGER DEFAULT 0,
ArtistName TEXT,
ArtistNameLowered TEXT,
ArtistNameSort TEXT,
ArtistNameSortKey BLOB,
Rating INTEGER
)
");
Execute ("CREATE INDEX CoreAlbumsIndex ON CoreAlbums(ArtistID, TitleSortKey)");
Execute ("CREATE INDEX CoreAlbumsArtistIndex ON CoreAlbums(TitleSortKey, ArtistNameSortKey)");
Execute(@"
CREATE TABLE CoreArtists (
ArtistID INTEGER PRIMARY KEY,
TagSetID INTEGER,
MusicBrainzID TEXT,
Name TEXT,
NameLowered TEXT,
NameSort TEXT,
NameSortKey BLOB,
Rating INTEGER
)
");
Execute ("CREATE INDEX CoreArtistsIndex ON CoreArtists(NameSortKey)");
Execute(@"
CREATE TABLE CorePlaylists (
PrimarySourceID INTEGER,
PlaylistID INTEGER PRIMARY KEY,
Name TEXT,
SortColumn INTEGER NOT NULL DEFAULT -1,
SortType INTEGER NOT NULL DEFAULT 0,
Special INTEGER NOT NULL DEFAULT 0,
CachedCount INTEGER,
IsTemporary INTEGER DEFAULT 0
)
");
Execute(@"
CREATE TABLE CorePlaylistEntries (
EntryID INTEGER PRIMARY KEY,
PlaylistID INTEGER NOT NULL,
TrackID INTEGER NOT NULL,
ViewOrder INTEGER NOT NULL DEFAULT 0,
Generated INTEGER NOT NULL DEFAULT 0
)
");
Execute("CREATE INDEX CorePlaylistEntriesIndex ON CorePlaylistEntries(PlaylistID, TrackID)");
Execute(@"
CREATE TABLE CoreSmartPlaylists (
PrimarySourceID INTEGER,
SmartPlaylistID INTEGER PRIMARY KEY,
Name TEXT NOT NULL,
Condition TEXT,
OrderBy TEXT,
LimitNumber TEXT,
LimitCriterion TEXT,
CachedCount INTEGER,
IsTemporary INTEGER DEFAULT 0,
IsHiddenWhenEmpty INTEGER DEFAULT 0
)
");
Execute(@"
CREATE TABLE CoreSmartPlaylistEntries (
EntryID INTEGER PRIMARY KEY,
SmartPlaylistID INTEGER NOT NULL,
TrackID INTEGER NOT NULL
)
");
Execute ("CREATE INDEX CoreSmartPlaylistEntriesIndex ON CoreSmartPlaylistEntries(SmartPlaylistID, TrackID)");
Execute(@"
CREATE TABLE CoreRemovedTracks (
TrackID INTEGER NOT NULL,
Uri TEXT,
DateRemovedStamp INTEGER
)
");
Execute(@"
CREATE TABLE CoreCacheModels (
CacheID INTEGER PRIMARY KEY,
ModelID TEXT
)
");
// This index slows down queries were we shove data into the CoreCache.
// Since we do that frequently, not using it.
//Execute("CREATE INDEX CoreCacheModelId ON CoreCache(ModelID)");
Execute(@"
CREATE TABLE CoreShuffles (
ShufflerId INTEGER,
TrackID INTEGER,
LastShuffledAt INTEGER,
CONSTRAINT one_entry_per_track UNIQUE (ShufflerID, TrackID)
)
");
Execute("CREATE INDEX CoreShufflesIndex ON CoreShuffles (ShufflerId, TrackID, LastShuffledAt)");
Execute(@"
CREATE TABLE CoreShufflers (
ShufflerId INTEGER PRIMARY KEY,
Id TEXT UNIQUE
)
");
Execute (@"
CREATE TABLE CoreShuffleModifications (
ShufflerId INTEGER,
TrackID INTEGER,
LastModifiedAt INTEGER,
ModificationType INTEGER,
CONSTRAINT one_entry_per_track UNIQUE (ShufflerID, TrackID)
)
");
Execute ("CREATE INDEX CoreShuffleModificationsIndex ON CoreShuffleModifications (ShufflerId, TrackID, LastModifiedAt, ModificationType)");
}
#endregion
#region Legacy database migration
private void MigrateFromLegacyBanshee()
{
Execute(@"
INSERT INTO CoreArtists
(ArtistID, TagSetID, MusicBrainzID, Name, NameLowered, NameSort, Rating)
SELECT DISTINCT null, 0, null, Artist, NULL, NULL, 0
FROM Tracks
ORDER BY Artist
");
Execute(@"
INSERT INTO CoreAlbums
(AlbumID, ArtistID, TagSetID, MusicBrainzID, Title, TitleLowered, TitleSort, ReleaseDate,
Duration, Year, IsCompilation, ArtistName, ArtistNameLowered, ArtistNameSort, Rating)
SELECT DISTINCT null,
(SELECT ArtistID
FROM CoreArtists
WHERE Name = Tracks.Artist
LIMIT 1),
0, null, AlbumTitle, NULL, NULL, ReleaseDate, 0, 0, 0, Artist, NULL, NULL, 0
FROM Tracks
ORDER BY AlbumTitle
");
Execute (String.Format (@"
INSERT INTO CoreTracks
(PrimarySourceID, TrackID, ArtistID, AlbumID, TagSetID, ExternalID, MusicBrainzID, Uri, MimeType,
FileSize, BitRate, Attributes, LastStreamError, Title, TitleLowered, TrackNumber, TrackCount,
Disc, DiscCount, Duration, Year, Genre, Composer, Conductor, Grouping, Copyright, LicenseUri,
Comment, Rating, Score, PlayCount, SkipCount, LastPlayedStamp, LastSkippedStamp, DateAddedStamp,
DateUpdatedStamp, MetadataHash, BPM, LastSyncedStamp, FileModifiedStamp)
SELECT
1,
TrackID,
(SELECT ArtistID
FROM CoreArtists
WHERE Name = Artist),
(SELECT a.AlbumID
FROM CoreAlbums a, CoreArtists b
WHERE a.Title = AlbumTitle
AND a.ArtistID = b.ArtistID
AND b.Name = Artist),
0,
0,
0,
Uri,
MimeType,
0, 0,
{0},
{1},
Title, NULL,
TrackNumber,
TrackCount,
0, 0,
Duration * 1000,
Year,
Genre,
NULL, NULL, NULL, NULL, NULL, NULL,
Rating,
0,
NumberOfPlays,
0,
LastPlayedStamp,
NULL,
DateAddedStamp,
DateAddedStamp,
NULL, NULL, DateAddedStamp, NULL
FROM Tracks
", (int)TrackMediaAttributes.Default, (int)StreamPlaybackError.None));
Execute ("UPDATE CoreTracks SET LastPlayedStamp = NULL WHERE LastPlayedStamp = -62135575200");
// Old versions of Banshee had different columns for Playlists/PlaylistEntries, so be careful
try {
Execute(@"
INSERT INTO CorePlaylists (PlaylistID, Name, SortColumn, SortType)
SELECT * FROM Playlists;
INSERT INTO CorePlaylistEntries
(EntryID, PlaylistID, TrackID, ViewOrder)
SELECT * FROM PlaylistEntries
");
} catch (Exception e) {
Log.Exception ("Must be a pre-0.13.2 banshee.db, attempting to migrate", e);
try {
Execute(@"
INSERT INTO CorePlaylists (PlaylistID, Name)
SELECT PlaylistID, Name FROM Playlists;
INSERT INTO CorePlaylistEntries (EntryID, PlaylistID, TrackID)
SELECT EntryID, PlaylistID, TrackID FROM PlaylistEntries
");
Log.Debug ("Success, was able to migrate older playlist information");
} catch (Exception e2) {
Log.Exception ("Failed to migrate playlists", e2);
}
}
// Really old versions of Banshee didn't have SmartPlaylists, so ignore errors
try {
Execute(@"
INSERT INTO CoreSmartPlaylists (SmartPlaylistID, Name, Condition, OrderBy, LimitNumber, LimitCriterion)
SELECT * FROM SmartPlaylists
");
} catch {}
Execute ("UPDATE CoreSmartPlaylists SET PrimarySourceID = 1");
Execute ("UPDATE CorePlaylists SET PrimarySourceID = 1");
InitializeOrderedTracks ();
Migrate_15 ();
}
#endregion
#region Utilities / Source / Service Stuff
private void InitializeOrderedTracks ()
{
foreach (long playlist_id in connection.QueryEnumerable<long> ("SELECT PlaylistID FROM CorePlaylists ORDER BY PlaylistID")) {
if (connection.Query<long> (@"SELECT COUNT(*) FROM CorePlaylistEntries
WHERE PlaylistID = ? AND ViewOrder > 0", playlist_id) <= 0) {
long first_id = connection.Query<long> ("SELECT COUNT(*) FROM CorePlaylistEntries WHERE PlaylistID < ?", playlist_id);
connection.Execute (
@"UPDATE CorePlaylistEntries SET ViewOrder = (ROWID - ?) WHERE PlaylistID = ?",
first_id, playlist_id
);
}
}
}
private void OnServiceStarted (ServiceStartedArgs args)
{
if (args.Service is JobScheduler) {
ServiceManager.ServiceStarted -= OnServiceStarted;
if (ServiceManager.SourceManager.MusicLibrary != null) {
RefreshMetadataDelayed ();
} else {
ServiceManager.SourceManager.SourceAdded += OnSourceAdded;
}
}
}
private void OnSourceAdded (SourceAddedArgs args)
{
if (ServiceManager.SourceManager.MusicLibrary != null && ServiceManager.SourceManager.VideoLibrary != null) {
ServiceManager.SourceManager.SourceAdded -= OnSourceAdded;
RefreshMetadataDelayed ();
}
}
private void ReloadAllSources (Client client)
{
Application.ClientStarted -= ReloadAllSources;
foreach (Source source in ServiceManager.SourceManager.Sources) {
if (source is ITrackModelSource) {
((ITrackModelSource)source).Reload ();
}
}
}
#endregion
#region Metadata Refresh Driver
private void RefreshMetadataDelayed ()
{
Application.RunTimeout (3000, RefreshMetadata);
}
private bool RefreshMetadata ()
{
ThreadPool.QueueUserWorkItem (RefreshMetadataThread);
return false;
}
private void RefreshMetadataThread (object state)
{
int total = ServiceManager.DbConnection.Query<int> ("SELECT count(*) FROM CoreTracks");
if (total <= 0) {
return;
}
UserJob job = new UserJob (Catalog.GetString ("Refreshing Metadata"));
job.SetResources (Resource.Cpu, Resource.Disk, Resource.Database);
job.PriorityHints = PriorityHints.SpeedSensitive;
job.Status = Catalog.GetString ("Scanning...");
job.IconNames = new string [] { "system-search", "gtk-find" };
job.Register ();
HyenaSqliteCommand select_command = new HyenaSqliteCommand (
String.Format (
"SELECT {0} FROM {1} WHERE {2}",
DatabaseTrackInfo.Provider.Select,
DatabaseTrackInfo.Provider.From,
DatabaseTrackInfo.Provider.Where
)
);
int count = 0;
using (var reader = ServiceManager.DbConnection.Query (select_command)) {
while (reader.Read ()) {
DatabaseTrackInfo track = null;
try {
track = DatabaseTrackInfo.Provider.Load (reader);
if (track != null && track.Uri != null && track.Uri.IsFile) {
try {
using (var file = StreamTagger.ProcessUri (track.Uri)) {
StreamTagger.TrackInfoMerge (track, file, true);
}
} catch (Exception e) {
Log.Warning (String.Format ("Failed to update metadata for {0}", track),
e.GetType ().ToString (), false);
}
track.Save (false);
track.Artist.Save ();
track.Album.Save ();
job.Status = String.Format ("{0} - {1}", track.DisplayArtistName, track.DisplayTrackTitle);
}
} catch (Exception e) {
Log.Warning (String.Format ("Failed to update metadata for {0}", track), e.ToString (), false);
}
job.Progress = (double)++count / (double)total;
}
}
if (ServiceManager.DbConnection.Query<int> ("SELECT count(*) FROM CoreConfiguration WHERE Key = 'MetadataVersion'") == 0) {
Execute (String.Format ("INSERT INTO CoreConfiguration (EntryID, Key, Value) VALUES (null, 'MetadataVersion', {0})", CURRENT_METADATA_VERSION));
} else {
Execute (String.Format ("UPDATE CoreConfiguration SET Value = {0} WHERE Key = 'MetadataVersion'", CURRENT_METADATA_VERSION));
}
job.Finish ();
ServiceManager.SourceManager.MusicLibrary.NotifyTracksChanged ();
}
#endregion
class DatabaseVersionTooHigh : ApplicationException
{
internal DatabaseVersionTooHigh (int currentVersion, int databaseVersion)
: base (String.Format (
"This version of Banshee was prepared to work with older database versions (=< {0}) thus it is too old to support the current version of the database ({1}).",
currentVersion, databaseVersion))
{
}
private DatabaseVersionTooHigh ()
{
}
}
}
[SqliteFunction (Name = "BANSHEE_MIGRATE_PARTIAL", FuncType = FunctionType.Scalar, Arguments = 2)]
internal class MigratePartialFunction : SqliteFunction
{
public override object Invoke (object[] args)
{
string library_path = (string)args[0];
string filename_fragment = (string)args[1];
string full_path = Paths.Combine (library_path, filename_fragment);
return SafeUri.FilenameToUri (full_path);
}
}
}
| |
// Copyright: Krzysztof Kowalczyk
// License: BSD
namespace Volante
{
using System;
using System.Collections;
using System.Collections.Generic;
public class TestLinkPArray : ITest
{
public class RelMember : Persistent
{
long l;
public RelMember()
{
}
public RelMember(long v)
{
l = v;
}
}
public class Root : Persistent
{
public IPArray<RecordFull> arr;
public ILink<RecordFull> link;
public RecordFull relOwner;
public Relation<RelMember, RecordFull> rel;
}
public void Run(TestConfig config)
{
RecordFull r;
RelMember rm;
RecordFull[] recs;
RelMember[] rmArr;
RecordFull notInArr1;
IDatabase db = config.GetDatabase();
config.Result = new TestResult();
Root root = new Root();
var arr = db.CreateArray<RecordFull>(256);
arr = db.CreateArray<RecordFull>();
var link = db.CreateLink<RecordFull>(256);
link = db.CreateLink<RecordFull>();
root.relOwner = new RecordFull();
var rel = db.CreateRelation<RelMember, RecordFull>(root.relOwner);
Tests.Assert(rel.Owner == root.relOwner);
rel.SetOwner(new RecordFull(88));
Tests.Assert(rel.Owner != root.relOwner);
rel.Owner = root.relOwner;
Tests.Assert(rel.Owner == root.relOwner);
root.arr = arr;
root.link = link;
root.rel = rel;
db.Root = root;
Tests.Assert(arr.Count == 0);
Tests.Assert(((IGenericPArray)arr).Size() == 0);
var inMem = new List<RecordFull>();
for (long i = 0; i < 256; i++)
{
r = new RecordFull(i);
rm = new RelMember(i);
inMem.Add(r);
arr.Add(r);
Tests.Assert(arr.Count == i + 1);
link.Add(r);
rel.Add(rm);
Tests.Assert(link.Count == i + 1);
}
recs = arr.ToArray();
rmArr = rel.ToArray();
Tests.Assert(recs.Length == rmArr.Length);
Tests.Assert(rel.Count == rel.Length);
Tests.Assert(rel.Size() == rel.Count);
rel.CopyTo(rmArr, 0);
Tests.Assert(recs.Length == arr.Length);
for (int j = 0; j < recs.Length; j++)
{
Tests.Assert(recs[j] == arr[j]);
Tests.Assert(rmArr[j] == rel[j]);
}
recs = inMem.ToArray();
arr.AddAll(recs);
rel.AddAll(rmArr);
notInArr1 = new RecordFull(256);
inMem.Add(notInArr1);
db.Commit();
var e = link.GetEnumerator();
int idx = 0;
while (e.MoveNext())
{
Tests.Assert(e.Current == inMem[idx++]);
}
Tests.AssertException<InvalidOperationException>(
() => { var tmp = e.Current; });
Tests.Assert(!e.MoveNext());
e.Reset();
idx = 0;
int nullCount = 0;
while (e.MoveNext())
{
Tests.Assert(e.Current == inMem[idx++]);
IEnumerator e2 = (IEnumerator)e;
if (e2.Current == null)
nullCount++;
}
var e3 = rel.GetEnumerator();
while (e3.MoveNext())
{
Tests.Assert(e3.Current != null);
}
Tests.Assert(!e3.MoveNext());
Tests.AssertException<InvalidOperationException>(
() => { var tmp = e3.Current; });
e3.Reset();
Tests.Assert(e3.MoveNext());
nullCount = 0;
foreach (var r2 in link)
{
if (null == r2)
nullCount++;
}
Tests.Assert(arr.Length == 512);
Array a = arr.ToArray();
Tests.Assert(a.Length == 512);
a = arr.ToRawArray();
Tests.Assert(a.Length == 512);
arr.RemoveAt(0);
db.Commit();
Tests.Assert(arr.Count == 511);
arr.RemoveAt(arr.Count - 1);
db.Commit();
Tests.Assert(arr.Count == 510);
r = arr[5];
Tests.Assert(arr.Contains(r));
Tests.Assert(!arr.Contains(null));
Tests.Assert(!arr.Contains(notInArr1));
Tests.Assert(arr.ContainsElement(5, r));
Tests.Assert(!arr.IsReadOnly);
Tests.Assert(!link.IsReadOnly);
Tests.Assert(5 == arr.IndexOf(r));
Tests.Assert(-1 == arr.IndexOf(notInArr1));
Tests.Assert(-1 == arr.IndexOf(null));
Tests.Assert(r.Oid == arr.GetOid(5));
arr[5] = new RecordFull(17);
Tests.AssertException<IndexOutOfRangeException>(() =>
{ r = arr[1024]; });
Tests.AssertException<IndexOutOfRangeException>(() =>
{ arr.Insert(9999, null); });
Tests.AssertException<IndexOutOfRangeException>(() =>
{ link.Insert(9999, null); });
Tests.AssertException<IndexOutOfRangeException>(() =>
{ arr.Insert(-1, null); });
Tests.AssertException<IndexOutOfRangeException>(() =>
{ link.Insert(-1, null); });
Tests.AssertException<IndexOutOfRangeException>(() =>
{ arr.RemoveAt(9999); });
Tests.AssertException<IndexOutOfRangeException>(() =>
{ arr.RemoveAt(-1); });
Tests.AssertException<IndexOutOfRangeException>(() =>
{ arr.GetOid(9999); });
Tests.AssertException<IndexOutOfRangeException>(() =>
{ arr.GetOid(-1); });
Tests.AssertException<IndexOutOfRangeException>(() =>
{ arr.GetRaw(9999); });
Tests.AssertException<IndexOutOfRangeException>(() =>
{ arr.GetRaw(-1); });
Tests.AssertException<IndexOutOfRangeException>(() =>
{ arr.Set(9999, new RecordFull(9988)); });
Tests.AssertException<IndexOutOfRangeException>(() =>
{ arr.Set(-1, new RecordFull(9988)); });
Tests.Assert(null != arr.GetRaw(8));
arr.Set(25, arr[24]);
arr.Pin();
arr.Unpin();
Tests.Assert(arr.Remove(arr[12]));
Tests.Assert(!arr.Remove(notInArr1));
Tests.Assert(link.Remove(link[3]));
Tests.Assert(!link.Remove(notInArr1));
Tests.Assert(arr.Length == 509);
arr.Insert(5, new RecordFull(88));
Tests.Assert(arr.Length == 510);
link.Insert(5, new RecordFull(88));
int expectedCount = arr.Count + link.Count;
arr.AddAll(link);
Tests.Assert(arr.Count == expectedCount);
Tests.Assert(null != arr.GetEnumerator());
Tests.Assert(null != link.GetEnumerator());
link.Length = 1024;
Tests.Assert(link.Length == 1024);
link.Length = 128;
Tests.Assert(link.Length == 128);
link.AddAll(arr);
arr.Clear();
Tests.Assert(0 == arr.Length);
db.Commit();
arr.AddAll(link);
arr.AddAll(arr);
recs = arr.ToArray();
link.AddAll(new RecordFull[1] { recs[0] });
link.AddAll(recs, 1, 1);
db.Commit();
recs = link.ToArray();
Tests.Assert(recs.Length == link.Length);
link.Length = link.Length - 2;
rel.Length = rel.Length / 2;
idx = rel.Length / 2;
Tests.Assert(null != rel.Get(idx));
rel[idx] = new RelMember(55);
db.Commit();
IPersistent raw = rel.GetRaw(idx);
Tests.Assert(raw.IsRaw());
rm = rel[idx];
Tests.Assert(rel.Contains(rm));
Tests.Assert(rel.ContainsElement(idx, rm));
Tests.Assert(rel.Remove(rm));
Tests.Assert(!rel.Contains(rm));
Tests.Assert(!rel.Remove(rm));
idx = rel.Length / 2;
rm = rel[idx];
Tests.Assert(idx == rel.IndexOf(rm));
int cnt = rel.Count;
rel.RemoveAt(idx);
Tests.Assert(rel.Count == cnt - 1);
Tests.Assert(!rel.Contains(rm));
rel.Add(rm);
db.Commit();
//TODO: LinkImpl.ToRawArray() seems wrong but changing it
//breaks a lot of code
//Array ra = rel.ToRawArray();
Array ra2 = rel.ToArray();
//Tests.Assert(ra2.Length == ra.Length);
//Tests.Assert(ra.Length == rel.Count);
rel.Insert(1, new RelMember(123));
//Tests.Assert(rel.Count == ra.Length + 1);
rel.Unpin();
rel.Pin();
rel.Unpin();
rel.Clear();
Tests.Assert(rel.Count == 0);
db.Close();
}
}
}
| |
// Copyright 2011 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.
namespace Microsoft.Data.OData.Metadata
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Data.Services.Common;
using System.Diagnostics;
using System.Linq;
using Microsoft.Data.Edm;
using Microsoft.Data.Edm.Annotations;
using Microsoft.Data.Edm.Library;
using Microsoft.Data.Edm.Library.Annotations;
using Microsoft.Data.Edm.Library.Values;
using Microsoft.Data.Edm.Values;
using Microsoft.Data.OData.Atom;
using o = Microsoft.Data.OData;
#endregion Namespaces
/// <summary>
/// Extension methods to make it easier to work with EPM.
/// </summary>
internal static class EpmExtensionMethods
{
/// <summary>
/// All supported base names for serializable EPM annotations.
/// </summary>
private static readonly string[] EpmAnnotationBaseNames = new string[]
{
EpmConstants.ODataEpmTargetPath,
EpmConstants.ODataEpmSourcePath,
EpmConstants.ODataEpmKeepInContent,
EpmConstants.ODataEpmContentKind,
EpmConstants.ODataEpmNsUri,
EpmConstants.ODataEpmNsPrefix,
};
/// <summary>
/// FC_TargetPath to <see cref="SyndicationItemProperty"/> enum mapping.
/// </summary>
private static readonly Dictionary<string, SyndicationItemProperty> TargetPathToSyndicationItemMap =
new Dictionary<string, SyndicationItemProperty>(StringComparer.OrdinalIgnoreCase)
{
{ EpmConstants.ODataSyndItemAuthorEmail, SyndicationItemProperty.AuthorEmail },
{ EpmConstants.ODataSyndItemAuthorName, SyndicationItemProperty.AuthorName },
{ EpmConstants.ODataSyndItemAuthorUri, SyndicationItemProperty.AuthorUri },
{ EpmConstants.ODataSyndItemContributorEmail, SyndicationItemProperty.ContributorEmail },
{ EpmConstants.ODataSyndItemContributorName, SyndicationItemProperty.ContributorName },
{ EpmConstants.ODataSyndItemContributorUri, SyndicationItemProperty.ContributorUri },
{ EpmConstants.ODataSyndItemUpdated, SyndicationItemProperty.Updated },
{ EpmConstants.ODataSyndItemPublished, SyndicationItemProperty.Published },
{ EpmConstants.ODataSyndItemRights, SyndicationItemProperty.Rights },
{ EpmConstants.ODataSyndItemSummary, SyndicationItemProperty.Summary },
{ EpmConstants.ODataSyndItemTitle, SyndicationItemProperty.Title },
};
/// <summary>
/// Ensures that an up-to-date EPM cache exists for the specified <paramref name="entityType"/>.
/// If no cache exists, a new one will be created based on the public mappings (if any).
/// If the public mappings have changed (and the cache is thus dirty), the method re-constructs the cache.
/// If all public mappings have been removed, the method also removes the EPM cache.
/// </summary>
/// <param name="model">IEdmModel containing the annotations.</param>
/// <param name="entityType">IEdmEntityType instance for which to ensure the EPM cache.</param>
/// <param name="maxMappingCount">The maximum allowed number of entity property mappings
/// for a given entity type (on the type itself and all its base types).</param>
/// <returns>An instance of <see cref="ODataEntityPropertyMappingCache"/>, if there are any EPM mappings for the given entity type, otherwise returns null.</returns>
internal static ODataEntityPropertyMappingCache EnsureEpmCache(this IEdmModel model, IEdmEntityType entityType, int maxMappingCount)
{
DebugUtils.CheckNoExternalCallers();
bool cacheModified;
return EnsureEpmCacheInternal(model, entityType, maxMappingCount, out cacheModified);
}
/// <summary>
/// Determines if the <paramref name="entityType"/> has any EPM defined on it (or its base types).
/// </summary>
/// <param name="model">The model containing the annotations.</param>
/// <param name="entityType">The entity type to test for presence of EPM.</param>
/// <returns>true if the <paramref name="entityType"/> has EPM; false otherwise.</returns>
internal static bool HasEntityPropertyMappings(this IEdmModel model, IEdmEntityType entityType)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(model != null, "model != null");
Debug.Assert(entityType != null, "entityType != null");
// Walk the base types and determine if there's EPM anywhere in there.
IEdmEntityType entityTypeToTest = entityType;
while (entityTypeToTest != null)
{
if (model.GetEntityPropertyMappings(entityTypeToTest) != null)
{
return true;
}
entityTypeToTest = entityTypeToTest.BaseEntityType();
}
return false;
}
/// <summary>
/// Returns the EPM information for an entity type.
/// </summary>
/// <param name="model">The model containing the annotations.</param>
/// <param name="entityType">The entity type to get the EPM information for.</param>
/// <returns>Returns the EPM information for an entity type. If there's no such information, this returns null.</returns>
internal static ODataEntityPropertyMappingCollection GetEntityPropertyMappings(this IEdmModel model, IEdmEntityType entityType)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(model != null, "model != null");
Debug.Assert(entityType != null, "entityType != null");
return model.GetAnnotationValue<ODataEntityPropertyMappingCollection>(entityType);
}
/// <summary>
/// Returns the cached EPM information for an entity type.
/// </summary>
/// <param name="model">The model containing the annotations.</param>
/// <param name="entityType">The entity type to get the cached EPM information for.</param>
/// <returns>Returns the cached EPM information for an entity type. If there's no cached information, this returns null.</returns>
internal static ODataEntityPropertyMappingCache GetEpmCache(this IEdmModel model, IEdmEntityType entityType)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(model != null, "model != null");
Debug.Assert(entityType != null, "entityType != null");
return model.GetAnnotationValue<ODataEntityPropertyMappingCache>(entityType);
}
/// <summary>
/// Gets all the annotations bindings in order to remove all EPM related annotations from a given <see cref="IEdmElement"/>.
/// </summary>
/// <param name="model">The model containing the annotations.</param>
/// <param name="annotatable">The annotatable to get the EPM annotations for.</param>
/// <returns>A dictionary of local annotation name to annotation binding mappings for all serializable EPM annotations on <paramref name="annotatable"/>.</returns>
internal static Dictionary<string, IEdmDirectValueAnnotationBinding> GetAnnotationBindingsToRemoveSerializableEpmAnnotations(
this IEdmModel model,
IEdmElement annotatable)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(model != null, "model != null");
Debug.Assert(annotatable != null, "annotatable != null");
Dictionary<string, IEdmDirectValueAnnotationBinding> annotationBindingsToRemove = new Dictionary<string, IEdmDirectValueAnnotationBinding>(StringComparer.Ordinal);
IEnumerable<IEdmDirectValueAnnotation> annotations = model.GetODataAnnotations(annotatable);
if (annotations != null)
{
foreach (IEdmDirectValueAnnotation annotation in annotations)
{
if (annotation.IsEpmAnnotation())
{
annotationBindingsToRemove.Add(
annotation.Name,
new EdmDirectValueAnnotationBinding(annotatable, annotation.NamespaceUri, annotation.Name, /*value*/ null));
}
}
}
return annotationBindingsToRemove;
}
/// <summary>
/// Removes the in-memory EPM annotations from an entity type; potentially also drops an existing EPM cache.
/// </summary>
/// <param name="model">The <see cref="IEdmModel"/> containing the annotation.</param>
/// <param name="annotatable">The <see cref="IEdmElement"/> to remove the EPM annotation from.</param>
internal static void ClearInMemoryEpmAnnotations(this IEdmModel model, IEdmElement annotatable)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(model != null, "model != null");
Debug.Assert(annotatable != null, "annotatable != null");
IEdmDirectValueAnnotationBinding[] annotationSetters = new IEdmDirectValueAnnotationBinding[2];
// remove the in-memory annotation
annotationSetters[0] = new EdmTypedDirectValueAnnotationBinding<ODataEntityPropertyMappingCollection>(annotatable, null);
// remove the cache
annotationSetters[1] = new EdmTypedDirectValueAnnotationBinding<ODataEntityPropertyMappingCache>(annotatable, null);
model.SetAnnotationValues(annotationSetters);
}
/// <summary>
/// Saves the EPM annotations on the given <paramref name="property"/>.
/// </summary>
/// <param name="model">The <see cref="IEdmModel"/> containing the annotations.</param>
/// <param name="property">The <see cref="IEdmProperty"/> to save the EPM annotations for.</param>
/// <param name="epmCache">The EPM cache for the owning entity type.</param>
internal static void SaveEpmAnnotationsForProperty(this IEdmModel model, IEdmProperty property, ODataEntityPropertyMappingCache epmCache)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(model != null, "model != null");
Debug.Assert(property != null, "property != null");
Debug.Assert(epmCache != null, "epmCache != null");
// get the mappings for the current property; this is based on the source path of the mapping
string propertyName = property.Name;
IEnumerable<EntityPropertyMappingAttribute> propertyMappings = epmCache.MappingsForDeclaredProperties.Where(
m => m.SourcePath.StartsWith(propertyName, StringComparison.Ordinal) &&
(m.SourcePath.Length == propertyName.Length || m.SourcePath[propertyName.Length] == '/'));
bool skipSourcePath;
bool removePrefix;
if (property.Type.IsODataPrimitiveTypeKind())
{
// Since only a single mapping from a primitive property can exist, it is fine to not write the source path.
Debug.Assert(propertyMappings.Count() <= 1, "At most one entity property mapping can exist from a primitive property.");
skipSourcePath = true;
removePrefix = false;
}
else
{
Debug.Assert(
property.Type.IsODataComplexTypeKind() || property.Type.IsNonEntityODataCollectionTypeKind(),
"Only primitive, complex or collectionValue properties can have EPM defined on them.");
removePrefix = true;
skipSourcePath = propertyMappings.Any(m => m.SourcePath == propertyName);
Debug.Assert(
!skipSourcePath || propertyMappings.Count() == 1,
"We must not have multiple mappings for a property if one of them matches the property name exactly (the other ones would not make sense).");
}
model.SaveEpmAnnotations(property, propertyMappings, skipSourcePath, removePrefix);
}
/// <summary>
/// Saves the EPM annotations on the given <paramref name="annotatable"/>.
/// </summary>
/// <param name="model">The <see cref="IEdmModel"/> containing the annotations.</param>
/// <param name="annotatable">The <see cref="IEdmElement"/> to save the EPM annotations on.</param>
/// <param name="mappings">All the EPM annotations to be saved.</param>
/// <param name="skipSourcePath">true if the source path should be saved explicitly; otherwise false.</param>
/// <param name="removePrefix">true if the prefix of the source path should be removed; otherwise false.</param>
internal static void SaveEpmAnnotations(this IEdmModel model, IEdmElement annotatable, IEnumerable<EntityPropertyMappingAttribute> mappings, bool skipSourcePath, bool removePrefix)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(model != null, "model != null");
Debug.Assert(annotatable != null, "annotatable != null");
Debug.Assert(mappings != null, "mappings != null");
Debug.Assert(!skipSourcePath || mappings.Count() <= 1, "Skipping the source path is only valid if at most a single mapping exists.");
EpmAttributeNameBuilder epmAttributeNameBuilder = new EpmAttributeNameBuilder();
// Get the annotation bindings for all serializable EPM annotations with a null value (which will remove them).
// NOTE: we use a dictionary here and replace existing annotation bindings below to ensure we have at most
// one binding per annotation name; the default annotation manager will process annotations in order and thus
// the last binding for an annotation would win but custom annotation managers might not.
Dictionary<string, IEdmDirectValueAnnotationBinding> epmAnnotationBindings =
GetAnnotationBindingsToRemoveSerializableEpmAnnotations(model, annotatable);
string localName;
foreach (EntityPropertyMappingAttribute mapping in mappings)
{
// Check whether the mapping represents a custom mapping
if (mapping.TargetSyndicationItem == SyndicationItemProperty.CustomProperty)
{
localName = epmAttributeNameBuilder.EpmTargetPath;
epmAnnotationBindings[localName] = GetODataAnnotationBinding(annotatable, localName, mapping.TargetPath);
localName = epmAttributeNameBuilder.EpmNsUri;
epmAnnotationBindings[localName] = GetODataAnnotationBinding(annotatable, localName, mapping.TargetNamespaceUri);
string targetNamespacePrefix = mapping.TargetNamespacePrefix;
if (!string.IsNullOrEmpty(targetNamespacePrefix))
{
localName = epmAttributeNameBuilder.EpmNsPrefix;
epmAnnotationBindings[localName] = GetODataAnnotationBinding(annotatable, localName, targetNamespacePrefix);
}
}
else
{
localName = epmAttributeNameBuilder.EpmTargetPath;
epmAnnotationBindings[localName] = GetODataAnnotationBinding(annotatable, localName, mapping.TargetSyndicationItem.ToAttributeValue());
localName = epmAttributeNameBuilder.EpmContentKind;
epmAnnotationBindings[localName] = GetODataAnnotationBinding(annotatable, localName, mapping.TargetTextContentKind.ToAttributeValue());
}
if (!skipSourcePath)
{
string sourcePath = mapping.SourcePath;
if (removePrefix)
{
sourcePath = sourcePath.Substring(sourcePath.IndexOf('/') + 1);
}
localName = epmAttributeNameBuilder.EpmSourcePath;
epmAnnotationBindings[localName] = GetODataAnnotationBinding(annotatable, localName, sourcePath);
}
string keepInContent = mapping.KeepInContent ? AtomConstants.AtomTrueLiteral : AtomConstants.AtomFalseLiteral;
localName = epmAttributeNameBuilder.EpmKeepInContent;
epmAnnotationBindings[localName] = GetODataAnnotationBinding(annotatable, localName, keepInContent);
epmAttributeNameBuilder.MoveNext();
}
model.SetAnnotationValues(epmAnnotationBindings.Values);
}
/// <summary>
/// Returns the cached keep-in-content annotation for the primitive properties of a complex type.
/// </summary>
/// <param name="model">The model containing the annotation.</param>
/// <param name="complexType">The complex type to get the cached keep-in-content annotation for.</param>
/// <returns>Returns the keep-in-content annotation for a type. If there's no such annotation this returns null.</returns>
internal static CachedPrimitiveKeepInContentAnnotation EpmCachedKeepPrimitiveInContent(this IEdmModel model, IEdmComplexType complexType)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(model != null, "model != null");
Debug.Assert(complexType != null, "complexType != null");
return model.GetAnnotationValue<CachedPrimitiveKeepInContentAnnotation>(complexType);
}
/// <summary>
/// Maps the enumeration of allowed <see cref="SyndicationItemProperty"/> values to their string representations.
/// </summary>
/// <param name="targetSyndicationItem">Value of the <see cref="SyndicationItemProperty"/> given in
/// the <see cref="EntityPropertyMappingAttribute"/> contstructor.</param>
/// <returns>String representing the xml element path in the syndication property.</returns>
internal static string ToTargetPath(this SyndicationItemProperty targetSyndicationItem)
{
DebugUtils.CheckNoExternalCallers();
switch (targetSyndicationItem)
{
case SyndicationItemProperty.AuthorEmail: return EpmConstants.PropertyMappingTargetPathAuthorEmail;
case SyndicationItemProperty.AuthorName: return EpmConstants.PropertyMappingTargetPathAuthorName;
case SyndicationItemProperty.AuthorUri: return EpmConstants.PropertyMappingTargetPathAuthorUri;
case SyndicationItemProperty.ContributorEmail: return EpmConstants.PropertyMappingTargetPathContributorEmail;
case SyndicationItemProperty.ContributorName: return EpmConstants.PropertyMappingTargetPathContributorName;
case SyndicationItemProperty.ContributorUri: return EpmConstants.PropertyMappingTargetPathContributorUri;
case SyndicationItemProperty.Updated: return EpmConstants.PropertyMappingTargetPathUpdated;
case SyndicationItemProperty.Published: return EpmConstants.PropertyMappingTargetPathPublished;
case SyndicationItemProperty.Rights: return EpmConstants.PropertyMappingTargetPathRights;
case SyndicationItemProperty.Summary: return EpmConstants.PropertyMappingTargetPathSummary;
case SyndicationItemProperty.Title: return EpmConstants.PropertyMappingTargetPathTitle;
default:
throw new ArgumentException(o.Strings.EntityPropertyMapping_EpmAttribute("targetSyndicationItem"));
}
}
/// <summary>
/// Loads the serializable EPM annotations on the given <paramref name="entityType"/> into their in-memory representation.
/// </summary>
/// <param name="model">The model the entity type belongs to.</param>
/// <param name="entityType">The <see cref="IEdmEntityType"/> to load the EPM annotations for.</param>
private static void LoadEpmAnnotations(IEdmModel model, IEdmEntityType entityType)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(entityType != null, "entityType != null");
string entityTypeName = entityType.ODataFullName();
ODataEntityPropertyMappingCollection mappings = new ODataEntityPropertyMappingCollection();
// Load the annotations from the type (these are the mappings for properties not explicitly declared on this type)
model.LoadEpmAnnotations(entityType, mappings, entityTypeName, null /*property*/);
IEnumerable<IEdmProperty> declaredProperties = entityType.DeclaredProperties;
if (declaredProperties != null)
{
foreach (IEdmProperty property in declaredProperties)
{
// Load the EPM annotations for all properties independent of their kind in order to fail on invalid property kinds.
model.LoadEpmAnnotations(property, mappings, entityTypeName, property);
}
}
// Set the new EPM annotation on the entity type only at the very end to not leave a
// inconsistent annotation if building it fails.
model.SetAnnotationValue(entityType, mappings);
}
/// <summary>
/// Loads the serializable EPM annotations on the given <paramref name="annotatable"/> into their in-memory representation.
/// </summary>
/// <param name="model">The model the annotatable belongs to.</param>
/// <param name="annotatable">The <see cref="IEdmElement"/> to load the EPM annotations for.</param>
/// <param name="mappings">The collection of EPM annotations to add newly loaded annotations to.</param>
/// <param name="typeName">The name of the type for which to load the annotations or that declares the <paramref name="property"/>. Only used in error messages.</param>
/// <param name="property">The property to parse the EPM annotations for.</param>
private static void LoadEpmAnnotations(this IEdmModel model, IEdmElement annotatable, ODataEntityPropertyMappingCollection mappings, string typeName, IEdmProperty property)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(model != null, "model != null");
Debug.Assert(annotatable != null, "annotatable != null");
Debug.Assert(mappings != null, "mappings != null");
Debug.Assert(!string.IsNullOrEmpty(typeName), "!string.IsNullOrEmpty(typeName)");
IEnumerable<EpmAnnotationValues> allAnnotationValues = ParseSerializableEpmAnnotations(model, annotatable, typeName, property);
if (allAnnotationValues != null)
{
foreach (EpmAnnotationValues annotationValues in allAnnotationValues)
{
// check whether we found a valid EPM configuration
EntityPropertyMappingAttribute mapping = ValidateAnnotationValues(annotationValues, typeName, property);
mappings.Add(mapping);
}
}
}
/// <summary>
/// Given a <paramref name="targetPath"/> gets the corresponding syndication property.
/// </summary>
/// <param name="targetPath">Target path in the form of a syndication property name.</param>
/// <returns>
/// Enumeration value of a <see cref="SyndicationItemProperty"/> or SyndicationItemProperty.CustomProperty
/// if the <paramref name="targetPath"/> does not map to any syndication property name.
/// </returns>
private static SyndicationItemProperty MapTargetPathToSyndicationProperty(string targetPath)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(targetPath != null, "targetPath != null");
SyndicationItemProperty targetSyndicationItem;
return TargetPathToSyndicationItemMap.TryGetValue(targetPath, out targetSyndicationItem) ? targetSyndicationItem : SyndicationItemProperty.CustomProperty;
}
/// <summary>
/// Translates a content kind enumeration value to the corresponding string attribute value for serialization to CSDL.
/// </summary>
/// <param name="contentKind">The content kind to translate.</param>
/// <returns>A string corresponding to the <paramref name="contentKind"/> value.</returns>
private static string ToAttributeValue(this SyndicationTextContentKind contentKind)
{
switch (contentKind)
{
case SyndicationTextContentKind.Xhtml:
return EpmConstants.ODataSyndContentKindXHtml;
case SyndicationTextContentKind.Html:
return EpmConstants.ODataSyndContentKindHtml;
default:
return EpmConstants.ODataSyndContentKindPlaintext;
}
}
/// <summary>
/// Translates a syndication item property enumeration value to the corresponding string attribute value for serialization to CSDL.
/// </summary>
/// <param name="syndicationItemProperty">The syndication item property to translate.</param>
/// <returns>A string corresponding to the <paramref name="syndicationItemProperty"/> value.</returns>
private static string ToAttributeValue(this SyndicationItemProperty syndicationItemProperty)
{
switch (syndicationItemProperty)
{
case SyndicationItemProperty.AuthorEmail: return EpmConstants.ODataSyndItemAuthorEmail;
case SyndicationItemProperty.AuthorName: return EpmConstants.ODataSyndItemAuthorName;
case SyndicationItemProperty.AuthorUri: return EpmConstants.ODataSyndItemAuthorUri;
case SyndicationItemProperty.ContributorEmail: return EpmConstants.ODataSyndItemContributorEmail;
case SyndicationItemProperty.ContributorName: return EpmConstants.ODataSyndItemContributorName;
case SyndicationItemProperty.ContributorUri: return EpmConstants.ODataSyndItemContributorUri;
case SyndicationItemProperty.Updated: return EpmConstants.ODataSyndItemUpdated;
case SyndicationItemProperty.Published: return EpmConstants.ODataSyndItemPublished;
case SyndicationItemProperty.Rights: return EpmConstants.ODataSyndItemRights;
case SyndicationItemProperty.Summary: return EpmConstants.ODataSyndItemSummary;
case SyndicationItemProperty.Title: return EpmConstants.ODataSyndItemTitle;
case SyndicationItemProperty.CustomProperty: // fall through
default:
throw new ODataException(o.Strings.General_InternalError(InternalErrorCodes.EpmExtensionMethods_ToAttributeValue_SyndicationItemProperty));
}
}
/// <summary>
/// Maps the <paramref name="contentKind"/> string to an enumeration value of the <see cref="SyndicationTextContentKind"/> enumeration.
/// </summary>
/// <param name="contentKind">The content kind string to map.</param>
/// <param name="attributeSuffix">The suffix of the attribute name currently being parsed or validated.Only used in error messages.</param>
/// <param name="typeName">The name of the type for which to load the annotations or that declares the <paramref name="propertyName"/>. Only used in error messages.</param>
/// <param name="propertyName">The name of the property to parse the EPM annotations for. Only used in error messages.</param>
/// <returns>An <see cref="SyndicationTextContentKind"/> value if the <paramref name="contentKind"/> could be successfully mapped; otherwise throws.</returns>
private static SyndicationTextContentKind MapContentKindToSyndicationTextContentKind(
string contentKind,
string attributeSuffix,
string typeName,
string propertyName)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(contentKind != null, "contentKind != null");
Debug.Assert(attributeSuffix != null, "attributeSuffix != null");
Debug.Assert(!string.IsNullOrEmpty(typeName), "!string.IsNullOrEmpty(typeName)");
switch (contentKind)
{
case EpmConstants.ODataSyndContentKindPlaintext: return SyndicationTextContentKind.Plaintext;
case EpmConstants.ODataSyndContentKindHtml: return SyndicationTextContentKind.Html;
case EpmConstants.ODataSyndContentKindXHtml: return SyndicationTextContentKind.Xhtml;
default:
string errorMessage = propertyName == null
? o.Strings.EpmExtensionMethods_InvalidTargetTextContentKindOnType(EpmConstants.ODataEpmContentKind + attributeSuffix, typeName)
: o.Strings.EpmExtensionMethods_InvalidTargetTextContentKindOnProperty(EpmConstants.ODataEpmContentKind + attributeSuffix, propertyName, typeName);
throw new ODataException(errorMessage);
}
}
/// <summary>
/// Parses the serializable EPM annotations of the <paramref name="annotatable"/>, groups them by suffix
/// and translates them into a set of structs.
/// </summary>
/// <param name="model">The <see cref="IEdmModel"/> containing the annotations.</param>
/// <param name="annotatable">The <see cref="IEdmElement"/> to parse the EPM annotations for.</param>
/// <param name="typeName">The name of the type for which the annotations are parsed or that declares the <paramref name="property"/>. Only used in error messages.</param>
/// <param name="property">The property to parse the EPM annotations for.</param>
/// <returns>An enumerable of <see cref="EpmAnnotationValues"/> that represents all the parsed annotations grouped by their suffix.</returns>
private static IEnumerable<EpmAnnotationValues> ParseSerializableEpmAnnotations(this IEdmModel model, IEdmElement annotatable, string typeName, IEdmProperty property)
{
Debug.Assert(model != null, "model != null");
Debug.Assert(annotatable != null, "annotatable != null");
Debug.Assert(typeName != null, "typeName != null");
Dictionary<string, EpmAnnotationValues> allAnnotationValues = null;
IEnumerable<IEdmDirectValueAnnotation> annotations = model.GetODataAnnotations(annotatable);
if (annotations != null)
{
foreach (IEdmDirectValueAnnotation annotation in annotations)
{
string suffix;
string baseName;
if (annotation.IsEpmAnnotation(out baseName, out suffix))
{
Debug.Assert(baseName != null, "baseName != null");
Debug.Assert(suffix != null, "suffix != null");
string annotationValue = ConvertEdmAnnotationValue(annotation);
if (allAnnotationValues == null)
{
allAnnotationValues = new Dictionary<string, EpmAnnotationValues>(StringComparer.Ordinal);
}
EpmAnnotationValues annotationValues;
if (!allAnnotationValues.TryGetValue(suffix, out annotationValues))
{
annotationValues = new EpmAnnotationValues
{
AttributeSuffix = suffix
};
allAnnotationValues[suffix] = annotationValues;
}
// NOTE: we don't have to check for duplicate definitions since the Xml attribute
// nature of the annotations prevents that.
if (NamesMatchByReference(EpmConstants.ODataEpmTargetPath, baseName))
{
Debug.Assert(annotationValues.TargetPath == null, "Can have only a single target path annotation per suffix.");
annotationValues.TargetPath = annotationValue;
}
else if (NamesMatchByReference(EpmConstants.ODataEpmSourcePath, baseName))
{
Debug.Assert(annotationValues.SourcePath == null, "Can have only a single source path annotation per suffix.");
annotationValues.SourcePath = annotationValue;
}
else if (NamesMatchByReference(EpmConstants.ODataEpmKeepInContent, baseName))
{
Debug.Assert(annotationValues.KeepInContent == null, "Can have only a single keep-in-content annotation per suffix.");
annotationValues.KeepInContent = annotationValue;
}
else if (NamesMatchByReference(EpmConstants.ODataEpmContentKind, baseName))
{
Debug.Assert(annotationValues.ContentKind == null, "Can have only a single content kind annotation per suffix.");
annotationValues.ContentKind = annotationValue;
}
else if (NamesMatchByReference(EpmConstants.ODataEpmNsUri, baseName))
{
Debug.Assert(annotationValues.NamespaceUri == null, "Can have only a single namespace URI annotation per suffix.");
annotationValues.NamespaceUri = annotationValue;
}
else if (NamesMatchByReference(EpmConstants.ODataEpmNsPrefix, baseName))
{
Debug.Assert(annotationValues.NamespacePrefix == null, "Can have only a single namespace prefix annotation per suffix.");
annotationValues.NamespacePrefix = annotationValue;
}
else
{
throw new ODataException(o.Strings.General_InternalError(InternalErrorCodes.ODataUtils_ParseSerializableEpmAnnotations_UnreachableCodePath));
}
}
}
// Fix up the source path values
if (allAnnotationValues != null)
{
foreach (EpmAnnotationValues annotationValues in allAnnotationValues.Values)
{
string sourcePath = annotationValues.SourcePath;
// set the default source path based on the property name if none was found in the annotations
if (sourcePath == null)
{
if (property == null)
{
string attributeName = EpmConstants.ODataEpmSourcePath + annotationValues.AttributeSuffix;
throw new ODataException(o.Strings.EpmExtensionMethods_MissingAttributeOnType(attributeName, typeName));
}
annotationValues.SourcePath = property.Name;
}
else
{
// For non-primitive properties we strip the property name from the source path if the
// source path is not the same as the property name; re-add the property name here.
if (property != null && !property.Type.IsODataPrimitiveTypeKind())
{
annotationValues.SourcePath = property.Name + "/" + sourcePath;
}
}
}
}
}
return allAnnotationValues == null ? null : allAnnotationValues.Values;
}
/// <summary>
/// Validates the annotation values parsed for an EPM mapping.
/// </summary>
/// <param name="annotationValues">The <see cref="EpmAnnotationValues"/> to validate.</param>
/// <param name="typeName">The name of the type for which the annotations are validated or that declares the <paramref name="property"/>. Only used in error messages.</param>
/// <param name="property">The property for which the annotations are validated; null if the annotations are for a type.</param>
/// <returns>An <see cref="EntityPropertyMappingAttribute"/> instance that represents the mapping created from the <paramref name="annotationValues"/>.</returns>
private static EntityPropertyMappingAttribute ValidateAnnotationValues(EpmAnnotationValues annotationValues, string typeName, IEdmProperty property)
{
Debug.Assert(annotationValues != null, "annotationValues != null");
Debug.Assert(annotationValues.AttributeSuffix != null, "annotationValues.AttributeSuffix != null");
Debug.Assert(!string.IsNullOrEmpty(typeName), "!string.IsNullOrEmpty(typeName)");
//// Conditions for EPM annotation values to represent a valid mapping:
//// 1. must have target path
//// 2. can have keep-in-content (default is 'true')
//// 3a. if custom mapping: target path must map to custom property, content kind must be null
//// 3b. if syndication mapping: content kind (optional; default: plain text), no ns uri, no ns prefix
if (annotationValues.TargetPath == null)
{
string attributeName = EpmConstants.ODataEpmTargetPath + annotationValues.AttributeSuffix;
string errorMessage = property == null
? o.Strings.EpmExtensionMethods_MissingAttributeOnType(attributeName, typeName)
: o.Strings.EpmExtensionMethods_MissingAttributeOnProperty(attributeName, property.Name, typeName);
throw new ODataException(errorMessage);
}
EntityPropertyMappingAttribute mapping;
bool keepInContent = true;
if (annotationValues.KeepInContent != null)
{
if (!bool.TryParse(annotationValues.KeepInContent, out keepInContent))
{
string attributeName = EpmConstants.ODataEpmKeepInContent + annotationValues.AttributeSuffix;
throw new InvalidOperationException(property == null
? o.Strings.EpmExtensionMethods_InvalidKeepInContentOnType(attributeName, typeName)
: o.Strings.EpmExtensionMethods_InvalidKeepInContentOnProperty(attributeName, property.Name, typeName));
}
}
// figure out whether this is a custom mapping or not
SyndicationItemProperty targetSyndicationItem = MapTargetPathToSyndicationProperty(annotationValues.TargetPath);
if (targetSyndicationItem == SyndicationItemProperty.CustomProperty)
{
if (annotationValues.ContentKind != null)
{
string attributeName = EpmConstants.ODataEpmContentKind + annotationValues.AttributeSuffix;
string errorMessage = property == null
? o.Strings.EpmExtensionMethods_AttributeNotAllowedForCustomMappingOnType(attributeName, typeName)
: o.Strings.EpmExtensionMethods_AttributeNotAllowedForCustomMappingOnProperty(attributeName, property.Name, typeName);
throw new ODataException(errorMessage);
}
mapping = new EntityPropertyMappingAttribute(
annotationValues.SourcePath,
annotationValues.TargetPath,
annotationValues.NamespacePrefix,
annotationValues.NamespaceUri,
keepInContent);
}
else
{
if (annotationValues.NamespaceUri != null)
{
string attributeName = EpmConstants.ODataEpmNsUri + annotationValues.AttributeSuffix;
string errorMessage = property == null
? o.Strings.EpmExtensionMethods_AttributeNotAllowedForAtomPubMappingOnType(attributeName, typeName)
: o.Strings.EpmExtensionMethods_AttributeNotAllowedForAtomPubMappingOnProperty(attributeName, property.Name, typeName);
throw new ODataException(errorMessage);
}
if (annotationValues.NamespacePrefix != null)
{
string attributeName = EpmConstants.ODataEpmNsPrefix + annotationValues.AttributeSuffix;
string errorMessage = property == null
? o.Strings.EpmExtensionMethods_AttributeNotAllowedForAtomPubMappingOnType(attributeName, typeName)
: o.Strings.EpmExtensionMethods_AttributeNotAllowedForAtomPubMappingOnProperty(attributeName, property.Name, typeName);
throw new ODataException(errorMessage);
}
SyndicationTextContentKind contentKind = SyndicationTextContentKind.Plaintext;
if (annotationValues.ContentKind != null)
{
contentKind = MapContentKindToSyndicationTextContentKind(
annotationValues.ContentKind,
annotationValues.AttributeSuffix,
typeName,
property == null ? null : property.Name);
}
mapping = new EntityPropertyMappingAttribute(
annotationValues.SourcePath,
targetSyndicationItem,
contentKind,
keepInContent);
}
Debug.Assert(mapping != null, "mapping != null");
return mapping;
}
/// <summary>
/// Removes an existing EPM cache annotation.
/// </summary>
/// <param name="model">The <see cref="IEdmModel"/> containing the annotations.</param>
/// <param name="entityType">The <see cref="IEdmEntityType"/> to remove the EPM cache from.</param>
private static void RemoveEpmCache(this IEdmModel model, IEdmEntityType entityType)
{
Debug.Assert(model != null, "model != null");
Debug.Assert(entityType != null, "entityType != null");
model.SetAnnotationValue<ODataEntityPropertyMappingCache>(entityType, null);
}
/// <summary>
/// Checks whether a given OData annotation is an EPM related annotation.
/// </summary>
/// <param name="annotation">The <see cref="IEdmDirectValueAnnotation"/> instance to check.</param>
/// <returns>true if the annotation is EPM related; otherwise false.</returns>
private static bool IsEpmAnnotation(this IEdmDirectValueAnnotation annotation)
{
Debug.Assert(annotation != null, "annotation != null");
Debug.Assert(annotation.NamespaceUri == AtomConstants.ODataMetadataNamespace, "Expected only OData annotations in the metadata namespace.");
string baseName;
string suffix;
return annotation.IsEpmAnnotation(out baseName, out suffix);
}
/// <summary>
/// Checks whether a given serializable annotation represents part of an EPM mapping.
/// </summary>
/// <param name="annotation">The annotation to check.</param>
/// <param name="baseName">The base name of the EPM annotation.</param>
/// <param name="suffix">The suffix of the EPM annotation or null if not an EPM annotation.</param>
/// <returns>true if the <paramref name="annotation"/> is an EPM annotation; otherwise false.</returns>
private static bool IsEpmAnnotation(this IEdmDirectValueAnnotation annotation, out string baseName, out string suffix)
{
Debug.Assert(annotation != null, "annotation != null");
Debug.Assert(annotation.NamespaceUri == AtomConstants.ODataMetadataNamespace, "Annotation must be OData-specific.");
string localName = annotation.Name;
for (int i = 0; i < EpmAnnotationBaseNames.Length; ++i)
{
string annotationBaseName = EpmAnnotationBaseNames[i];
if (localName.StartsWith(annotationBaseName, StringComparison.Ordinal))
{
baseName = annotationBaseName;
suffix = localName.Substring(annotationBaseName.Length);
return true;
}
}
baseName = null;
suffix = null;
return false;
}
/// <summary>
/// Converts the value of the <paramref name="annotation"/> to a string.
/// </summary>
/// <param name="annotation">The <see cref="IEdmDirectValueAnnotation"/> to convert.</param>
/// <returns>The string representation of the converted annotation value.</returns>
private static string ConvertEdmAnnotationValue(IEdmDirectValueAnnotation annotation)
{
Debug.Assert(annotation != null, "annotation != null");
object annotationValue = annotation.Value;
if (annotationValue == null)
{
return null;
}
IEdmStringValue stringValue = annotationValue as IEdmStringValue;
if (stringValue != null)
{
return stringValue.Value;
}
throw new ODataException(o.Strings.EpmExtensionMethods_CannotConvertEdmAnnotationValue(annotation.NamespaceUri, annotation.Name, annotation.GetType().FullName));
}
/// <summary>
/// Checks that two strings are the same references (and asserts that if they are not they also
/// don't have the same value).
/// </summary>
/// <param name="first">The first string to compare.</param>
/// <param name="second">The second string to compare.</param>
/// <returns>true if the <paramref name="first"/> and <paramref name="second"/> are the same reference; otherwise false;</returns>
private static bool NamesMatchByReference(string first, string second)
{
Debug.Assert(
object.ReferenceEquals(first, second) || string.CompareOrdinal(first, second) != 0,
"Either the references are the same or the values must also be differnt.");
return object.ReferenceEquals(first, second);
}
/// <summary>
/// Checks whether the <paramref name="entityType"/> has EPM defined for it (either directly
/// on the type or on one of the base types).
/// </summary>
/// <param name="model">The <see cref="IEdmModel"/> containing the annotation.</param>
/// <param name="entityType">The <see cref="IEdmEntityType"/> to check.</param>
/// <returns>true if the <paramref name="entityType"/> has EPM defined; otherwise false.</returns>
private static bool HasOwnOrInheritedEpm(this IEdmModel model, IEdmEntityType entityType)
{
if (entityType == null)
{
return false;
}
Debug.Assert(model != null, "model != null");
if (model.GetAnnotationValue<ODataEntityPropertyMappingCollection>(entityType) != null)
{
return true;
}
// If we don't have an in-memory annotation, try to load the serializable EPM annotations
LoadEpmAnnotations(model, entityType);
if (model.GetAnnotationValue<ODataEntityPropertyMappingCollection>(entityType) != null)
{
return true;
}
return model.HasOwnOrInheritedEpm(entityType.BaseEntityType());
}
/// <summary>
/// Gets the annotation binding with the OData metadata namespace and the specified <paramref name="localName" /> for the <paramref name="annotatable"/>.
/// </summary>
/// <param name="annotatable">The <see cref="IEdmElement"/> to set the annotation on.</param>
/// <param name="localName">The local name of the annotation to set.</param>
/// <param name="value">The value of the annotation to set.</param>
/// <returns>An <see cref="IEdmDirectValueAnnotationBinding"/> instance that represnets the annotation with the specified name and value.</returns>
private static IEdmDirectValueAnnotationBinding GetODataAnnotationBinding(IEdmElement annotatable, string localName, string value)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(annotatable != null, "annotatable != null");
Debug.Assert(!string.IsNullOrEmpty(localName), "!string.IsNullOrEmpty(localName)");
IEdmStringValue stringValue = null;
if (value != null)
{
IEdmStringTypeReference typeReference = EdmCoreModel.Instance.GetString(/*nullable*/true);
stringValue = new EdmStringConstant(typeReference, value);
}
return new EdmDirectValueAnnotationBinding(annotatable, AtomConstants.ODataMetadataNamespace, localName, stringValue);
}
/// <summary>
/// Ensures that an up-to-date EPM cache exists for the specified <paramref name="entityType"/>.
/// If no cache exists, a new one will be created based on the public mappings (if any).
/// If the public mappings have changed (and the cache is thus dirty), the method re-constructs the cache.
/// If all public mappings have been removed, the method also removes the EPM cache.
/// </summary>
/// <param name="model">IEdmModel instance containing the annotations.</param>
/// <param name="entityType">IEdmEntityType instance for which to ensure the EPM cache.</param>
/// <param name="maxMappingCount">The maximum allowed number of entity property mappings
/// for a given entity type (on the type itself and all its base types).</param>
/// <param name="cacheModified">true if the cache was modified; otherwise false.</param>
/// <returns>An instance of <see cref="ODataEntityPropertyMappingCache"/>, if there are any EPM mappings for the given entity type, otherwise returns null.</returns>
private static ODataEntityPropertyMappingCache EnsureEpmCacheInternal(
IEdmModel model,
IEdmEntityType entityType,
int maxMappingCount,
out bool cacheModified)
{
cacheModified = false;
if (entityType == null)
{
return null;
}
// Make sure the EPM of the base type is initialized.
IEdmEntityType baseEntityType = entityType.BaseEntityType();
ODataEntityPropertyMappingCache baseCache = null;
if (baseEntityType != null)
{
baseCache = EnsureEpmCacheInternal(model, baseEntityType, maxMappingCount, out cacheModified);
}
ODataEntityPropertyMappingCache epmCache = model.GetEpmCache(entityType);
if (model.HasOwnOrInheritedEpm(entityType))
{
ODataEntityPropertyMappingCollection mappings = model.GetEntityPropertyMappings(entityType);
bool needToBuildCache = epmCache == null || cacheModified || epmCache.IsDirty(mappings);
if (needToBuildCache)
{
cacheModified = true;
int totalMappingCount = ValidationUtils.ValidateTotalEntityPropertyMappingCount(baseCache, mappings, maxMappingCount);
epmCache = new ODataEntityPropertyMappingCache(mappings, model, totalMappingCount);
// Build the EPM tree and validate it
try
{
epmCache.BuildEpmForType(entityType, entityType);
epmCache.EpmSourceTree.Validate(entityType);
epmCache.EpmTargetTree.Validate();
// We set the annotation here, so if anything fails during
// building of the cache the annotation will not even be set so
// not leaving the type in an inconsistent state.
model.SetAnnotationValue(entityType, epmCache);
}
catch
{
// Remove an existing EPM cache if it is dirty to make sure we don't leave
// stale caches in case building of the cache fails.
// NOTE: we do this in the catch block to ensure that we always make a single
// SetAnnotation call to either set or clear the existing annotation
// since the SetAnnotation method is thread-safe
model.RemoveEpmCache(entityType);
throw;
}
}
}
else
{
if (epmCache != null)
{
// remove an existing EPM cache if the mappings have been removed from the type
cacheModified = true;
model.RemoveEpmCache(entityType);
}
}
return epmCache;
}
/// <summary>
/// Private struct to store the values of the serializable EPM annotations during loading.
/// </summary>
private sealed class EpmAnnotationValues
{
/// <summary>The string value of the FC_SourcePath attribute (or null if not present).</summary>
internal string SourcePath { get; set; }
/// <summary>The string value of the FC_TargetPath attribute (or null if not present).</summary>
internal string TargetPath { get; set; }
/// <summary>The string value of the FC_KeepInContent attribute (or null if not present).</summary>
internal string KeepInContent { get; set; }
/// <summary>The string value of the FC_ContentKind attribute (or null if not present).</summary>
internal string ContentKind { get; set; }
/// <summary>The string value of the FC_NsUri attribute (or null if not present).</summary>
internal string NamespaceUri { get; set; }
/// <summary>The string value of the FC_NsPrefix attribute (or null if not present).</summary>
internal string NamespacePrefix { get; set; }
/// <summary>The attribute suffix used for the attribute names.</summary>
internal string AttributeSuffix { get; set; }
}
}
}
| |
namespace StandaloneReview.Tests
{
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AutoFixture;
using Model;
using MockViews;
using Presenters;
[TestClass]
public class FrmPreviewPresenterTests
{
private readonly Fixture _fixture = new Fixture();
private MockFrmPreview CreateReviewWithTwoComments(out ReviewComment commentTop, out ReviewComment commentSecond, out ReviewedFile reviewedFile)
{
reviewedFile = _fixture.Build<ReviewedFile>()
.With(p => p.Comments, new List<ReviewComment>())
.Create();
commentTop = _fixture.Build<ReviewComment>()
.With(p => p.Position, 0)
.Create();
commentSecond = _fixture.Build<ReviewComment>()
.With(p => p.Position, 1)
.Create();
reviewedFile.Comments.Add(commentTop);
reviewedFile.Comments.Add(commentSecond);
var reviewedFiles = new Dictionary<string, ReviewedFile>();
reviewedFiles.Add(reviewedFile.Filename, reviewedFile);
var mockView = new MockFrmPreview();
mockView.AppState.CurrentReview = _fixture.Build<Review>()
.With(p => p.ReviewedFiles, reviewedFiles)
.Create();
return mockView;
}
[TestMethod]
public void PreviewMoveComments_MoveTopCommentUp_ExpectCorrectPosition()
{
// Arrange
ReviewComment commentTop;
ReviewComment commentSecond;
ReviewedFile reviewedFile;
MockFrmPreview mockView = CreateReviewWithTwoComments(out commentTop, out commentSecond, out reviewedFile);
var presenter = new FrmPreviewPresenter(mockView);
// Act
mockView.FireMoveCommentUpEvent(reviewedFile.Filename, 0);
// Assert
Assert.AreEqual(0, commentTop.Position); // Nothing should be changed when trying to moved top comment up
Assert.AreEqual(1, commentSecond.Position); // Nothing should be changed when trying to moved top comment up
Assert.IsFalse(mockView.SetTxtPreviewTextWasCalled);
}
[TestMethod]
public void PreviewMoveComments_MoveSecondCommentUp_ExpectCorrectPosition()
{
// Arrange
ReviewComment commentTop;
ReviewComment commentSecond;
ReviewedFile reviewedFile;
MockFrmPreview mockView = CreateReviewWithTwoComments(out commentTop, out commentSecond, out reviewedFile);
var presenter = new FrmPreviewPresenter(mockView);
// Act
mockView.FireMoveCommentUpEvent(reviewedFile.Filename, 1);
// Assert
Assert.AreEqual(1, commentTop.Position); // Top comment up should be moved down
Assert.AreEqual(0, commentSecond.Position); // Second comment up should be moved up
Assert.IsTrue(mockView.SetTxtPreviewTextWasCalled);
}
[TestMethod]
public void PreviewMoveComments_MoveBottomCommentDown_ExpectCorrectPosition()
{
// Arrange
ReviewComment commentTop;
ReviewComment commentSecond;
ReviewedFile reviewedFile;
MockFrmPreview mockView = CreateReviewWithTwoComments(out commentTop, out commentSecond, out reviewedFile);
var presenter = new FrmPreviewPresenter(mockView);
// Act
mockView.FireMoveCommentDownEvent(reviewedFile.Filename, 1);
// Assert
Assert.AreEqual(0, commentTop.Position); // Nothing should be changed when trying to moved bottom comment down
Assert.AreEqual(1, commentSecond.Position); // Nothing should be changed when trying to moved bottom comment down
Assert.IsFalse(mockView.SetTxtPreviewTextWasCalled);
}
[TestMethod]
public void PreviewMoveComments_MoveTopCommentDown_ExpectCorrectPosition()
{
// Arrange
ReviewComment commentTop;
ReviewComment commentSecond;
ReviewedFile reviewedFile;
MockFrmPreview mockView = CreateReviewWithTwoComments(out commentTop, out commentSecond, out reviewedFile);
var presenter = new FrmPreviewPresenter(mockView);
// Act
mockView.FireMoveCommentDownEvent(reviewedFile.Filename, 0);
// Assert
Assert.AreEqual(1, commentTop.Position); // Top comment up should be moved down
Assert.AreEqual(0, commentSecond.Position); // Second comment up should be moved up
Assert.IsTrue(mockView.SetTxtPreviewTextWasCalled);
}
private MockFrmPreview CreateReviewWithThreeComments(out ReviewedFile reviewedFile)
{
reviewedFile = _fixture.Build<ReviewedFile>()
.With(p => p.Comments, new List<ReviewComment>())
.Create();
var commentTop = _fixture.Build<ReviewComment>()
.With(p => p.Position, 0)
.Create();
var commentSecond = _fixture.Build<ReviewComment>()
.With(p => p.Position, 1)
.Create();
var commentThird = _fixture.Build<ReviewComment>()
.With(p => p.Position, 2)
.Create();
reviewedFile.Comments.Add(commentTop);
reviewedFile.Comments.Add(commentSecond);
reviewedFile.Comments.Add(commentThird);
var reviewedFiles = new Dictionary<string, ReviewedFile>();
reviewedFiles.Add(reviewedFile.Filename, reviewedFile);
var mockView = new MockFrmPreview();
mockView.AppState.CurrentReview = _fixture.Build<Review>()
.With(p => p.ReviewedFiles, reviewedFiles)
.Create();
return mockView;
}
[TestMethod]
public void PreviewLstCommentsSelectedIndexChanged_TopCommentClicked_ExpectMoveUpButtonDisableAndMoveDownButtonEnabled()
{
// Arrange
ReviewedFile reviewedFile;
MockFrmPreview mockView = CreateReviewWithThreeComments(out reviewedFile);
var presenter = new FrmPreviewPresenter(mockView);
// Act
mockView.FireLstCommentsSelectedIndexChanged(reviewedFile.Filename, 0);
// Assert
Assert.IsTrue(mockView.EnableDisableMoveCommentButtonsWasCalled);
Assert.IsFalse(mockView.BtnMoveCommentUpEnabledValue);
Assert.IsTrue(mockView.BtnMoveCommentDownEnabledValue);
}
[TestMethod]
public void PreviewLstCommentsSelectedIndexChanged_SecondCommentClicked_ExpectMoveUpButtonDisableAndMoveDownButtonEnabled()
{
// Arrange
ReviewedFile reviewedFile;
MockFrmPreview mockView = CreateReviewWithThreeComments(out reviewedFile);
var presenter = new FrmPreviewPresenter(mockView);
// Act
mockView.FireLstCommentsSelectedIndexChanged(reviewedFile.Filename, 1);
// Assert
Assert.IsTrue(mockView.EnableDisableMoveCommentButtonsWasCalled);
Assert.IsTrue(mockView.BtnMoveCommentUpEnabledValue);
Assert.IsTrue(mockView.BtnMoveCommentDownEnabledValue);
}
[TestMethod]
public void PreviewLstCommentsSelectedIndexChanged_ThirdCommentClicked_ExpectMoveUpButtonDisableAndMoveDownButtonEnabled()
{
// Arrange
ReviewedFile reviewedFile;
MockFrmPreview mockView = CreateReviewWithThreeComments(out reviewedFile);
var presenter = new FrmPreviewPresenter(mockView);
// Act
mockView.FireLstCommentsSelectedIndexChanged(reviewedFile.Filename, 2);
// Assert
Assert.IsTrue(mockView.EnableDisableMoveCommentButtonsWasCalled);
Assert.IsTrue(mockView.BtnMoveCommentUpEnabledValue);
Assert.IsFalse(mockView.BtnMoveCommentDownEnabledValue);
}
private MockFrmPreview CreateReviewWithThreeFiles(out ReviewedFile reviewedFileTop, out ReviewedFile reviewedFileSecond, out ReviewedFile reviewedFileThird)
{
reviewedFileTop = _fixture.Build<ReviewedFile>()
.With(p => p.Comments, new List<ReviewComment>())
.Create();
reviewedFileSecond = _fixture.Build<ReviewedFile>()
.With(p => p.Comments, new List<ReviewComment>())
.Create();
reviewedFileThird = _fixture.Build<ReviewedFile>()
.With(p => p.Comments, new List<ReviewComment>())
.Create();
var reviewedFiles = new Dictionary<string, ReviewedFile>();
reviewedFiles.Add(reviewedFileTop.Filename, reviewedFileTop);
reviewedFiles.Add(reviewedFileSecond.Filename, reviewedFileSecond);
reviewedFiles.Add(reviewedFileThird.Filename, reviewedFileThird);
var mockView = new MockFrmPreview();
mockView.AppState.CurrentReview = _fixture.Build<Review>()
.With(p => p.ReviewedFiles, reviewedFiles)
.Create();
return mockView;
}
[TestMethod]
public void PreviewLstFilesSelectedIndexChanged_TopFileClicked_ExpectMoveUpButtonDisableAndMoveDownButtonEnabled()
{
// Arrange
ReviewedFile reviewedFileTop;
ReviewedFile reviewedFileSecond;
ReviewedFile reviewedFileThird;
MockFrmPreview mockView = CreateReviewWithThreeFiles(out reviewedFileTop, out reviewedFileSecond, out reviewedFileThird);
var presenter = new FrmPreviewPresenter(mockView);
// Act
mockView.FireLstFilesSelectedIndexChanged(reviewedFileTop.Filename, 0);
// Assert
Assert.IsTrue(mockView.EnableDisableMoveFileButtonsWasCalled);
Assert.IsTrue(mockView.BtnMoveFileDownEnabledValue);
Assert.IsFalse(mockView.BtnMoveFileUpEnabledValue);
Assert.IsTrue(mockView.EnableDisableMoveCommentButtonsWasCalled);
Assert.IsFalse(mockView.BtnMoveCommentUpEnabledValue);
Assert.IsFalse(mockView.BtnMoveCommentDownEnabledValue);
}
[TestMethod]
public void PreviewLstFilesSelectedIndexChanged_SecondFileClicked_ExpectMoveUpButtonDisableAndMoveDownButtonEnabled()
{
// Arrange
ReviewedFile reviewedFileTop;
ReviewedFile reviewedFileSecond;
ReviewedFile reviewedFileThird;
MockFrmPreview mockView = CreateReviewWithThreeFiles(out reviewedFileTop, out reviewedFileSecond, out reviewedFileThird);
var presenter = new FrmPreviewPresenter(mockView);
// Act
mockView.FireLstFilesSelectedIndexChanged(reviewedFileSecond.Filename, 1);
// Assert
Assert.IsTrue(mockView.EnableDisableMoveFileButtonsWasCalled);
Assert.IsTrue(mockView.BtnMoveFileDownEnabledValue);
Assert.IsTrue(mockView.BtnMoveFileUpEnabledValue);
Assert.IsTrue(mockView.EnableDisableMoveCommentButtonsWasCalled);
Assert.IsFalse(mockView.BtnMoveCommentUpEnabledValue);
Assert.IsFalse(mockView.BtnMoveCommentDownEnabledValue);
}
[TestMethod]
public void PreviewLstCommentsSelectedIndexChanged_ThirdFileClicked_ExpectMoveUpButtonDisableAndMoveDownButtonEnabled()
{
// Arrange
ReviewedFile reviewedFileTop;
ReviewedFile reviewedFileSecond;
ReviewedFile reviewedFileThird;
MockFrmPreview mockView = CreateReviewWithThreeFiles(out reviewedFileTop, out reviewedFileSecond, out reviewedFileThird);
var presenter = new FrmPreviewPresenter(mockView);
// Act
mockView.FireLstFilesSelectedIndexChanged(reviewedFileThird.Filename, 2);
// Assert
Assert.IsTrue(mockView.EnableDisableMoveFileButtonsWasCalled);
Assert.IsFalse(mockView.BtnMoveFileDownEnabledValue);
Assert.IsTrue(mockView.BtnMoveFileUpEnabledValue);
Assert.IsTrue(mockView.EnableDisableMoveCommentButtonsWasCalled);
Assert.IsFalse(mockView.BtnMoveCommentUpEnabledValue);
Assert.IsFalse(mockView.BtnMoveCommentDownEnabledValue);
}
}
}
| |
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 ApiFox.Areas.HelpPage.ModelDescriptions;
using ApiFox.Areas.HelpPage.Models;
namespace ApiFox.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);
}
}
}
}
| |
/*
*
* 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.
*
*/
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Lucene.Net.QueryParsers.Flexible.Core.Messages {
using System;
using System.Reflection;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class QueryParserMessagesBundle {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal QueryParserMessagesBundle() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lucene.Net.QueryParsers.Flexible.Core.Messages.QueryParserMessagesBundle", typeof(QueryParserMessagesBundle).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Could not parse text "{0}" using {1}.
/// </summary>
internal static string COULD_NOT_PARSE_NUMBER {
get {
return ResourceManager.GetString("COULD_NOT_PARSE_NUMBER", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to .
/// </summary>
internal static string EMPTY_MESSAGE {
get {
return ResourceManager.GetString("EMPTY_MESSAGE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Syntax Error: {0}.
/// </summary>
internal static string INVALID_SYNTAX {
get {
return ResourceManager.GetString("INVALID_SYNTAX", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Syntax Error, cannot parse {0}: {1}.
/// </summary>
internal static string INVALID_SYNTAX_CANNOT_PARSE {
get {
return ResourceManager.GetString("INVALID_SYNTAX_CANNOT_PARSE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Term can not end with escape character..
/// </summary>
internal static string INVALID_SYNTAX_ESCAPE_CHARACTER {
get {
return ResourceManager.GetString("INVALID_SYNTAX_ESCAPE_CHARACTER", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Non-hex character in Unicode escape sequence: {0}.
/// </summary>
internal static string INVALID_SYNTAX_ESCAPE_NONE_HEX_UNICODE {
get {
return ResourceManager.GetString("INVALID_SYNTAX_ESCAPE_NONE_HEX_UNICODE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Truncated unicode escape sequence..
/// </summary>
internal static string INVALID_SYNTAX_ESCAPE_UNICODE_TRUNCATION {
get {
return ResourceManager.GetString("INVALID_SYNTAX_ESCAPE_UNICODE_TRUNCATION", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fractional edit distances are not allowed..
/// </summary>
internal static string INVALID_SYNTAX_FUZZY_EDITS {
get {
return ResourceManager.GetString("INVALID_SYNTAX_FUZZY_EDITS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The similarity value for a fuzzy search must be between 0.0 and 1.0..
/// </summary>
internal static string INVALID_SYNTAX_FUZZY_LIMITS {
get {
return ResourceManager.GetString("INVALID_SYNTAX_FUZZY_LIMITS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Leading wildcard is not allowed: {0}.
/// </summary>
internal static string LEADING_WILDCARD_NOT_ALLOWED {
get {
return ResourceManager.GetString("LEADING_WILDCARD_NOT_ALLOWED", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot convert query to lucene syntax: {0} error: {1}.
/// </summary>
internal static string LUCENE_QUERY_CONVERSION_ERROR {
get {
return ResourceManager.GetString("LUCENE_QUERY_CONVERSION_ERROR", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This node does not support this action..
/// </summary>
internal static string NODE_ACTION_NOT_SUPPORTED {
get {
return ResourceManager.GetString("NODE_ACTION_NOT_SUPPORTED", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Number class not supported by NumericRangeQueryNode: {0}.
/// </summary>
internal static string NUMBER_CLASS_NOT_SUPPORTED_BY_NUMERIC_RANGE_QUERY {
get {
return ResourceManager.GetString("NUMBER_CLASS_NOT_SUPPORTED_BY_NUMERIC_RANGE_QUERY", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Field "{0}" is numeric and cannot have an empty value..
/// </summary>
internal static string NUMERIC_CANNOT_BE_EMPTY {
get {
return ResourceManager.GetString("NUMERIC_CANNOT_BE_EMPTY", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Parameter {1} with value {0} not supported..
/// </summary>
internal static string PARAMETER_VALUE_NOT_SUPPORTED {
get {
return ResourceManager.GetString("PARAMETER_VALUE_NOT_SUPPORTED", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Too many boolean clauses, the maximum supported is {0}: {1}.
/// </summary>
internal static string TOO_MANY_BOOLEAN_CLAUSES {
get {
return ResourceManager.GetString("TOO_MANY_BOOLEAN_CLAUSES", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unsupported NumericField.DataType: {0}.
/// </summary>
internal static string UNSUPPORTED_NUMERIC_DATA_TYPE {
get {
return ResourceManager.GetString("UNSUPPORTED_NUMERIC_DATA_TYPE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Wildcard is not supported for query: {0}.
/// </summary>
internal static string WILDCARD_NOT_SUPPORTED {
get {
return ResourceManager.GetString("WILDCARD_NOT_SUPPORTED", resourceCulture);
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Avalonia.Collections;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Diagnostics;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Logging;
using Avalonia.LogicalTree;
using Avalonia.Styling;
namespace Avalonia.Controls
{
/// <summary>
/// Base class for Avalonia controls.
/// </summary>
/// <remarks>
/// The control class extends <see cref="InputElement"/> and adds the following features:
///
/// - An inherited <see cref="DataContext"/>.
/// - A <see cref="Tag"/> property to allow user-defined data to be attached to the control.
/// - A collection of class strings for custom styling.
/// - Implements <see cref="IStyleable"/> to allow styling to work on the control.
/// - Implements <see cref="ILogical"/> to form part of a logical tree.
/// </remarks>
public class Control : InputElement, IControl, INamed, ISetInheritanceParent, ISetLogicalParent, ISupportInitialize
{
/// <summary>
/// Defines the <see cref="DataContext"/> property.
/// </summary>
public static readonly StyledProperty<object> DataContextProperty =
AvaloniaProperty.Register<Control, object>(
nameof(DataContext),
inherits: true,
notifying: DataContextNotifying);
/// <summary>
/// Defines the <see cref="FocusAdorner"/> property.
/// </summary>
public static readonly StyledProperty<ITemplate<IControl>> FocusAdornerProperty =
AvaloniaProperty.Register<Control, ITemplate<IControl>>(nameof(FocusAdorner));
/// <summary>
/// Defines the <see cref="Name"/> property.
/// </summary>
public static readonly DirectProperty<Control, string> NameProperty =
AvaloniaProperty.RegisterDirect<Control, string>(nameof(Name), o => o.Name, (o, v) => o.Name = v);
/// <summary>
/// Defines the <see cref="Parent"/> property.
/// </summary>
public static readonly DirectProperty<Control, IControl> ParentProperty =
AvaloniaProperty.RegisterDirect<Control, IControl>(nameof(Parent), o => o.Parent);
/// <summary>
/// Defines the <see cref="Tag"/> property.
/// </summary>
public static readonly StyledProperty<object> TagProperty =
AvaloniaProperty.Register<Control, object>(nameof(Tag));
/// <summary>
/// Defines the <see cref="TemplatedParent"/> property.
/// </summary>
public static readonly StyledProperty<ITemplatedControl> TemplatedParentProperty =
AvaloniaProperty.Register<Control, ITemplatedControl>(nameof(TemplatedParent), inherits: true);
/// <summary>
/// Defines the <see cref="ContextMenu"/> property.
/// </summary>
public static readonly StyledProperty<ContextMenu> ContextMenuProperty =
AvaloniaProperty.Register<Control, ContextMenu>(nameof(ContextMenu));
/// <summary>
/// Event raised when an element wishes to be scrolled into view.
/// </summary>
public static readonly RoutedEvent<RequestBringIntoViewEventArgs> RequestBringIntoViewEvent =
RoutedEvent.Register<Control, RequestBringIntoViewEventArgs>("RequestBringIntoView", RoutingStrategies.Bubble);
private int _initCount;
private string _name;
private IControl _parent;
private readonly Classes _classes = new Classes();
private DataTemplates _dataTemplates;
private IControl _focusAdorner;
private bool _isAttachedToLogicalTree;
private IAvaloniaList<ILogical> _logicalChildren;
private INameScope _nameScope;
private Styles _styles;
private bool _styled;
private Subject<IStyleable> _styleDetach = new Subject<IStyleable>();
/// <summary>
/// Initializes static members of the <see cref="Control"/> class.
/// </summary>
static Control()
{
AffectsMeasure(IsVisibleProperty);
PseudoClass(IsEnabledCoreProperty, x => !x, ":disabled");
PseudoClass(IsFocusedProperty, ":focus");
PseudoClass(IsPointerOverProperty, ":pointerover");
}
/// <summary>
/// Initializes a new instance of the <see cref="Control"/> class.
/// </summary>
public Control()
{
_nameScope = this as INameScope;
}
/// <summary>
/// Raised when the control is attached to a rooted logical tree.
/// </summary>
public event EventHandler<LogicalTreeAttachmentEventArgs> AttachedToLogicalTree;
/// <summary>
/// Raised when the control is detached from a rooted logical tree.
/// </summary>
public event EventHandler<LogicalTreeAttachmentEventArgs> DetachedFromLogicalTree;
/// <summary>
/// Occurs when the <see cref="DataContext"/> property changes.
/// </summary>
/// <remarks>
/// This event will be raised when the <see cref="DataContext"/> property has changed and
/// all subscribers to that change have been notified.
/// </remarks>
public event EventHandler DataContextChanged;
/// <summary>
/// Occurs when the control has finished initialization.
/// </summary>
/// <remarks>
/// The Initialized event indicates that all property values on the control have been set.
/// When loading the control from markup, it occurs when
/// <see cref="ISupportInitialize.EndInit"/> is called *and* the control
/// is attached to a rooted logical tree. When the control is created by code and
/// <see cref="ISupportInitialize"/> is not used, it is called when the control is attached
/// to the visual tree.
/// </remarks>
public event EventHandler Initialized;
/// <summary>
/// Gets or sets the name of the control.
/// </summary>
/// <remarks>
/// An element's name is used to uniquely identify a control within the control's name
/// scope. Once the element is added to a logical tree, its name cannot be changed.
/// </remarks>
public string Name
{
get
{
return _name;
}
set
{
if (value.Trim() == string.Empty)
{
throw new InvalidOperationException("Cannot set Name to empty string.");
}
if (_styled)
{
throw new InvalidOperationException("Cannot set Name : control already styled.");
}
_name = value;
}
}
/// <summary>
/// Gets or sets the control's classes.
/// </summary>
/// <remarks>
/// <para>
/// Classes can be used to apply user-defined styling to controls, or to allow controls
/// that share a common purpose to be easily selected.
/// </para>
/// <para>
/// Even though this property can be set, the setter is only intended for use in object
/// initializers. Assigning to this property does not change the underlying collection,
/// it simply clears the existing collection and addds the contents of the assigned
/// collection.
/// </para>
/// </remarks>
public Classes Classes
{
get
{
return _classes;
}
set
{
if (_classes != value)
{
_classes.Replace(value);
}
}
}
/// <summary>
/// Gets or sets the control's data context.
/// </summary>
/// <remarks>
/// The data context is an inherited property that specifies the default object that will
/// be used for data binding.
/// </remarks>
public object DataContext
{
get { return GetValue(DataContextProperty); }
set { SetValue(DataContextProperty, value); }
}
/// <summary>
/// Gets or sets the control's focus adorner.
/// </summary>
public ITemplate<IControl> FocusAdorner
{
get { return GetValue(FocusAdornerProperty); }
set { SetValue(FocusAdornerProperty, value); }
}
/// <summary>
/// Gets or sets the data templates for the control.
/// </summary>
/// <remarks>
/// Each control may define data templates which are applied to the control itself and its
/// children.
/// </remarks>
public DataTemplates DataTemplates
{
get { return _dataTemplates ?? (_dataTemplates = new DataTemplates()); }
set { _dataTemplates = value; }
}
/// <summary>
/// Gets a value that indicates whether the element has finished initialization.
/// </summary>
/// <remarks>
/// For more information about when IsInitialized is set, see the <see cref="Initialized"/>
/// event.
/// </remarks>
public bool IsInitialized { get; private set; }
/// <summary>
/// Gets or sets the styles for the control.
/// </summary>
/// <remarks>
/// Styles for the entire application are added to the Application.Styles collection, but
/// each control may in addition define its own styles which are applied to the control
/// itself and its children.
/// </remarks>
public Styles Styles
{
get { return _styles ?? (_styles = new Styles()); }
set { _styles = value; }
}
/// <summary>
/// Gets the control's logical parent.
/// </summary>
public IControl Parent => _parent;
/// <summary>
/// Gets or sets a context menu to the control.
/// </summary>
public ContextMenu ContextMenu
{
get { return GetValue(ContextMenuProperty); }
set { SetValue(ContextMenuProperty, value); }
}
/// <summary>
/// Gets or sets a user-defined object attached to the control.
/// </summary>
public object Tag
{
get { return GetValue(TagProperty); }
set { SetValue(TagProperty, value); }
}
/// <summary>
/// Gets the control whose lookless template this control is part of.
/// </summary>
public ITemplatedControl TemplatedParent
{
get { return GetValue(TemplatedParentProperty); }
internal set { SetValue(TemplatedParentProperty, value); }
}
/// <summary>
/// Gets a value indicating whether the element is attached to a rooted logical tree.
/// </summary>
bool ILogical.IsAttachedToLogicalTree => _isAttachedToLogicalTree;
/// <summary>
/// Gets the control's logical parent.
/// </summary>
ILogical ILogical.LogicalParent => Parent;
/// <summary>
/// Gets the control's logical children.
/// </summary>
IAvaloniaReadOnlyList<ILogical> ILogical.LogicalChildren => LogicalChildren;
/// <inheritdoc/>
IAvaloniaReadOnlyList<string> IStyleable.Classes => Classes;
/// <summary>
/// Gets the type by which the control is styled.
/// </summary>
/// <remarks>
/// Usually controls are styled by their own type, but there are instances where you want
/// a control to be styled by its base type, e.g. creating SpecialButton that
/// derives from Button and adds extra functionality but is still styled as a regular
/// Button.
/// </remarks>
Type IStyleable.StyleKey => GetType();
/// <inheritdoc/>
IObservable<IStyleable> IStyleable.StyleDetach => _styleDetach;
/// <inheritdoc/>
IStyleHost IStyleHost.StylingParent => (IStyleHost)InheritanceParent;
/// <inheritdoc/>
public virtual void BeginInit()
{
++_initCount;
}
/// <inheritdoc/>
public virtual void EndInit()
{
if (_initCount == 0)
{
throw new InvalidOperationException("BeginInit was not called.");
}
if (--_initCount == 0 && _isAttachedToLogicalTree)
{
if (!_styled)
{
RegisterWithNameScope();
ApplyStyling();
_styled = true;
}
if (!IsInitialized)
{
IsInitialized = true;
Initialized?.Invoke(this, EventArgs.Empty);
}
}
}
/// <inheritdoc/>
void ILogical.NotifyDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
this.OnDetachedFromLogicalTreeCore(e);
}
/// <summary>
/// Gets the control's logical children.
/// </summary>
protected IAvaloniaList<ILogical> LogicalChildren
{
get
{
if (_logicalChildren == null)
{
var list = new AvaloniaList<ILogical>();
list.ResetBehavior = ResetBehavior.Remove;
list.Validate = ValidateLogicalChild;
list.CollectionChanged += LogicalChildrenCollectionChanged;
_logicalChildren = list;
}
return _logicalChildren;
}
}
/// <summary>
/// Gets the <see cref="Classes"/> collection in a form that allows adding and removing
/// pseudoclasses.
/// </summary>
protected IPseudoClasses PseudoClasses => Classes;
/// <summary>
/// Sets the control's logical parent.
/// </summary>
/// <param name="parent">The parent.</param>
void ISetLogicalParent.SetParent(ILogical parent)
{
var old = Parent;
if (parent != old)
{
if (old != null && parent != null)
{
throw new InvalidOperationException("The Control already has a parent.");
}
if (_isAttachedToLogicalTree)
{
var oldRoot = FindStyleRoot(old);
if (oldRoot == null)
{
throw new AvaloniaInternalException("Was attached to logical tree but cannot find root.");
}
var e = new LogicalTreeAttachmentEventArgs(oldRoot);
OnDetachedFromLogicalTreeCore(e);
}
if (InheritanceParent == null || parent == null)
{
InheritanceParent = parent as AvaloniaObject;
}
_parent = (IControl)parent;
if (_parent is IStyleRoot || _parent?.IsAttachedToLogicalTree == true)
{
var newRoot = FindStyleRoot(this);
if (newRoot == null)
{
throw new AvaloniaInternalException("Parent is atttached to logical tree but cannot find root.");
}
var e = new LogicalTreeAttachmentEventArgs(newRoot);
OnAttachedToLogicalTreeCore(e);
}
RaisePropertyChanged(ParentProperty, old, _parent, BindingPriority.LocalValue);
}
}
/// <summary>
/// Sets the control's inheritance parent.
/// </summary>
/// <param name="parent">The parent.</param>
void ISetInheritanceParent.SetParent(IAvaloniaObject parent)
{
InheritanceParent = parent;
}
/// <summary>
/// Adds a pseudo-class to be set when a property is true.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="className">The pseudo-class.</param>
protected static void PseudoClass(AvaloniaProperty<bool> property, string className)
{
PseudoClass(property, x => x, className);
}
/// <summary>
/// Adds a pseudo-class to be set when a property equals a certain value.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="property">The property.</param>
/// <param name="selector">Returns a boolean value based on the property value.</param>
/// <param name="className">The pseudo-class.</param>
protected static void PseudoClass<T>(
AvaloniaProperty<T> property,
Func<T, bool> selector,
string className)
{
Contract.Requires<ArgumentNullException>(property != null);
Contract.Requires<ArgumentNullException>(selector != null);
Contract.Requires<ArgumentNullException>(className != null);
Contract.Requires<ArgumentNullException>(property != null);
if (string.IsNullOrWhiteSpace(className))
{
throw new ArgumentException("Cannot supply an empty className.");
}
property.Changed.Merge(property.Initialized)
.Where(e => e.Sender is Control)
.Subscribe(e =>
{
if (selector((T)e.NewValue))
{
((Control)e.Sender).PseudoClasses.Add(className);
}
else
{
((Control)e.Sender).PseudoClasses.Remove(className);
}
});
}
/// <summary>
/// Gets the element that recieves the focus adorner.
/// </summary>
/// <returns>The control that recieves the focus adorner.</returns>
protected virtual IControl GetTemplateFocusTarget()
{
return this;
}
/// <summary>
/// Called when the control is added to a rooted logical tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
AttachedToLogicalTree?.Invoke(this, e);
}
/// <summary>
/// Called when the control is removed from a rooted logical tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
DetachedFromLogicalTree?.Invoke(this, e);
}
/// <inheritdoc/>
protected sealed override void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTreeCore(e);
if (!IsInitialized)
{
IsInitialized = true;
Initialized?.Invoke(this, EventArgs.Empty);
}
}
/// <inheritdoc/>
protected sealed override void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTreeCore(e);
}
/// <summary>
/// Called before the <see cref="DataContext"/> property changes.
/// </summary>
protected virtual void OnDataContextChanging()
{
}
/// <summary>
/// Called after the <see cref="DataContext"/> property changes.
/// </summary>
protected virtual void OnDataContextChanged()
{
DataContextChanged?.Invoke(this, EventArgs.Empty);
}
/// <inheritdoc/>
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
if (IsFocused &&
(e.NavigationMethod == NavigationMethod.Tab ||
e.NavigationMethod == NavigationMethod.Directional))
{
var adornerLayer = AdornerLayer.GetAdornerLayer(this);
if (adornerLayer != null)
{
if (_focusAdorner == null)
{
var template = GetValue(FocusAdornerProperty);
if (template != null)
{
_focusAdorner = template.Build();
}
}
if (_focusAdorner != null)
{
var target = (Visual)GetTemplateFocusTarget();
if (target != null)
{
AdornerLayer.SetAdornedElement((Visual)_focusAdorner, target);
adornerLayer.Children.Add(_focusAdorner);
}
}
}
}
}
/// <inheritdoc/>
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
if (_focusAdorner != null)
{
var adornerLayer = _focusAdorner.Parent as Panel;
adornerLayer.Children.Remove(_focusAdorner);
_focusAdorner = null;
}
}
/// <summary>
/// Called when the <see cref="DataContext"/> property begins and ends being notified.
/// </summary>
/// <param name="o">The object on which the DataContext is changing.</param>
/// <param name="notifying">Whether the notifcation is beginning or ending.</param>
private static void DataContextNotifying(IAvaloniaObject o, bool notifying)
{
var control = o as Control;
if (control != null)
{
if (notifying)
{
control.OnDataContextChanging();
}
else
{
control.OnDataContextChanged();
}
}
}
private static IStyleRoot FindStyleRoot(IStyleHost e)
{
while (e != null)
{
var root = e as IStyleRoot;
if (root != null && root.StylingParent == null)
{
return root;
}
e = e.StylingParent;
}
return null;
}
private void ApplyStyling()
{
AvaloniaLocator.Current.GetService<IStyler>()?.ApplyStyles(this);
}
private void RegisterWithNameScope()
{
if (_nameScope == null)
{
_nameScope = NameScope.GetNameScope(this) ?? ((Control)Parent)?._nameScope;
}
if (Name != null)
{
_nameScope?.Register(Name, this);
}
}
private static void ValidateLogicalChild(ILogical c)
{
if (c == null)
{
throw new ArgumentException("Cannot add null to LogicalChildren.");
}
}
private void OnAttachedToLogicalTreeCore(LogicalTreeAttachmentEventArgs e)
{
// This method can be called when a control is already attached to the logical tree
// in the following scenario:
// - ListBox gets assigned Items containing ListBoxItem
// - ListBox makes ListBoxItem a logical child
// - ListBox template gets applied; making its Panel get attached to logical tree
// - That AttachedToLogicalTree signal travels down to the ListBoxItem
if (!_isAttachedToLogicalTree)
{
_isAttachedToLogicalTree = true;
if (_initCount == 0)
{
RegisterWithNameScope();
ApplyStyling();
_styled = true;
}
OnAttachedToLogicalTree(e);
}
foreach (var child in LogicalChildren.OfType<Control>())
{
child.OnAttachedToLogicalTreeCore(e);
}
}
private void OnDetachedFromLogicalTreeCore(LogicalTreeAttachmentEventArgs e)
{
if (_isAttachedToLogicalTree)
{
if (Name != null)
{
_nameScope?.Unregister(Name);
}
_isAttachedToLogicalTree = false;
_styleDetach.OnNext(this);
OnDetachedFromLogicalTree(e);
foreach (var child in LogicalChildren.OfType<Control>())
{
child.OnDetachedFromLogicalTreeCore(e);
}
#if DEBUG
if (((INotifyCollectionChangedDebug)_classes).GetCollectionChangedSubscribers()?.Length > 0)
{
Logger.Warning(
LogArea.Control,
this,
"{Type} detached from logical tree but still has class listeners",
this.GetType());
}
#endif
}
}
private void LogicalChildrenCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
SetLogicalParent(e.NewItems.Cast<ILogical>());
break;
case NotifyCollectionChangedAction.Remove:
ClearLogicalParent(e.OldItems.Cast<ILogical>());
break;
case NotifyCollectionChangedAction.Replace:
ClearLogicalParent(e.OldItems.Cast<ILogical>());
SetLogicalParent(e.NewItems.Cast<ILogical>());
break;
case NotifyCollectionChangedAction.Reset:
throw new NotSupportedException("Reset should not be signalled on LogicalChildren collection");
}
}
private void SetLogicalParent(IEnumerable<ILogical> children)
{
foreach (var i in children)
{
if (i.LogicalParent == null)
{
((ISetLogicalParent)i).SetParent(this);
}
}
}
private void ClearLogicalParent(IEnumerable<ILogical> children)
{
foreach (var i in children)
{
if (i.LogicalParent == this)
{
((ISetLogicalParent)i).SetParent(null);
}
}
}
}
}
| |
using System;
using System.Linq;
using System.Xml;
using Umbraco.Core;
using System.Collections.Generic;
using umbraco.MacroEngines;
namespace umbraco
{
/// <summary>
/// The UmbracoSettings Class contains general settings information for the entire Umbraco instance based on information from the /config/umbracoSettings.config file
/// </summary>
public class UmbracoSettings
{
public const string TEMP_FRIENDLY_XML_CHILD_CONTAINER_NODENAME = ""; // "children";
/// <summary>
/// Gets the umbraco settings document.
/// </summary>
/// <value>The _umbraco settings.</value>
public static XmlDocument _umbracoSettings
{
get { return Umbraco.Core.Configuration.UmbracoSettings.UmbracoSettingsXmlDoc; }
}
/// <summary>
/// Gets/sets the settings file path, the setter can be used in unit tests
/// </summary>
internal static string SettingsFilePath
{
get { return Umbraco.Core.Configuration.UmbracoSettings.SettingsFilePath; }
set { Umbraco.Core.Configuration.UmbracoSettings.SettingsFilePath = value; }
}
/// <summary>
/// Selects a xml node in the umbraco settings config file.
/// </summary>
/// <param name="Key">The xpath query to the specific node.</param>
/// <returns>If found, it returns the specific configuration xml node.</returns>
public static XmlNode GetKeyAsNode(string Key)
{
return Umbraco.Core.Configuration.UmbracoSettings.GetKeyAsNode(Key);
}
/// <summary>
/// Gets the value of configuration xml node with the specified key.
/// </summary>
/// <param name="Key">The key.</param>
/// <returns></returns>
public static string GetKey(string Key)
{
return Umbraco.Core.Configuration.UmbracoSettings.GetKey(Key);
}
/// <summary>
/// Gets a value indicating whether the media library will create new directories in the /media directory.
/// </summary>
/// <value>
/// <c>true</c> if new directories are allowed otherwise, <c>false</c>.
/// </value>
public static bool UploadAllowDirectories
{
get { return Umbraco.Core.Configuration.UmbracoSettings.UploadAllowDirectories; }
}
/// <summary>
/// Gets a value indicating whether logging is enabled in umbracoSettings.config (/settings/logging/enableLogging).
/// </summary>
/// <value><c>true</c> if logging is enabled; otherwise, <c>false</c>.</value>
public static bool EnableLogging
{
get { return Umbraco.Core.Configuration.UmbracoSettings.EnableLogging; }
}
/// <summary>
/// Gets a value indicating whether logging happens async.
/// </summary>
/// <value><c>true</c> if async logging is enabled; otherwise, <c>false</c>.</value>
public static bool EnableAsyncLogging
{
get { return Umbraco.Core.Configuration.UmbracoSettings.EnableAsyncLogging; }
}
/// <summary>
/// Gets the assembly of an external logger that can be used to store log items in 3rd party systems
/// </summary>
public static string ExternalLoggerAssembly
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ExternalLoggerAssembly; }
}
/// <summary>
/// Gets the type of an external logger that can be used to store log items in 3rd party systems
/// </summary>
public static string ExternalLoggerType
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ExternalLoggerType; }
}
/// <summary>
/// Long Audit Trail to external log too
/// </summary>
public static bool ExternalLoggerLogAuditTrail
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ExternalLoggerLogAuditTrail; }
}
/// <summary>
/// Keep user alive as long as they have their browser open? Default is true
/// </summary>
public static bool KeepUserLoggedIn
{
get { return Umbraco.Core.Configuration.UmbracoSettings.KeepUserLoggedIn; }
}
/// <summary>
/// Enables the experimental canvas (live) editing on the frontend of the website
/// </summary>
public static bool EnableCanvasEditing
{
get { return Umbraco.Core.Configuration.UmbracoSettings.EnableCanvasEditing; }
}
/// <summary>
/// Show disabled users in the tree in the Users section in the backoffice
/// </summary>
public static bool HideDisabledUsersInBackoffice
{
get { return Umbraco.Core.Configuration.UmbracoSettings.HideDisabledUsersInBackoffice; }
}
/// <summary>
/// Gets a value indicating whether the logs will be auto cleaned
/// </summary>
/// <value><c>true</c> if logs are to be automatically cleaned; otherwise, <c>false</c></value>
public static bool AutoCleanLogs
{
get { return Umbraco.Core.Configuration.UmbracoSettings.AutoCleanLogs; }
}
/// <summary>
/// Gets the value indicating the log cleaning frequency (in miliseconds)
/// </summary>
public static int CleaningMiliseconds
{
get { return Umbraco.Core.Configuration.UmbracoSettings.CleaningMiliseconds; }
}
public static int MaxLogAge
{
get { return Umbraco.Core.Configuration.UmbracoSettings.MaxLogAge; }
}
/// <summary>
/// Gets the disabled log types.
/// </summary>
/// <value>The disabled log types.</value>
public static XmlNode DisabledLogTypes
{
get { return Umbraco.Core.Configuration.UmbracoSettings.DisabledLogTypes; }
}
/// <summary>
/// Gets the package server url.
/// </summary>
/// <value>The package server url.</value>
public static string PackageServer
{
get { return Umbraco.Core.Configuration.UmbracoSettings.PackageServer; }
}
/// <summary>
/// Gets a value indicating whether umbraco will use domain prefixes.
/// </summary>
/// <value><c>true</c> if umbraco will use domain prefixes; otherwise, <c>false</c>.</value>
public static bool UseDomainPrefixes
{
get { return Umbraco.Core.Configuration.UmbracoSettings.UseDomainPrefixes; }
}
/// <summary>
/// This will add a trailing slash (/) to urls when in directory url mode
/// NOTICE: This will always return false if Directory Urls in not active
/// </summary>
public static bool AddTrailingSlash
{
get { return Umbraco.Core.Configuration.UmbracoSettings.AddTrailingSlash; }
}
/// <summary>
/// Gets a value indicating whether umbraco will use ASP.NET MasterPages for rendering instead of its propriatary templating system.
/// </summary>
/// <value><c>true</c> if umbraco will use ASP.NET MasterPages; otherwise, <c>false</c>.</value>
public static bool UseAspNetMasterPages
{
get { return Umbraco.Core.Configuration.UmbracoSettings.UseAspNetMasterPages; }
}
/// <summary>
/// Gets a value indicating whether umbraco will attempt to load any skins to override default template files
/// </summary>
/// <value><c>true</c> if umbraco will override templates with skins if present and configured <c>false</c>.</value>
public static bool EnableTemplateFolders
{
get { return Umbraco.Core.Configuration.UmbracoSettings.EnableTemplateFolders; }
}
/// <summary>
/// razor DynamicNode typecasting detects XML and returns DynamicXml - Root elements that won't convert to DynamicXml
/// </summary>
public static List<string> NotDynamicXmlDocumentElements
{
get { return Umbraco.Core.Configuration.UmbracoSettings.NotDynamicXmlDocumentElements.ToList(); }
}
public static List<RazorDataTypeModelStaticMappingItem> RazorDataTypeModelStaticMapping
{
get
{
var mapping = Umbraco.Core.Configuration.UmbracoSettings.RazorDataTypeModelStaticMapping;
//now we need to map to the old object until we can clean all this nonsense up
return mapping.Select(x => new RazorDataTypeModelStaticMappingItem()
{
DataTypeGuid = x.DataTypeGuid,
NodeTypeAlias = x.NodeTypeAlias,
PropertyTypeAlias = x.PropertyTypeAlias,
Raw = x.Raw,
TypeName = x.TypeName
}).ToList();
}
}
/// <summary>
/// Gets a value indicating whether umbraco will clone XML cache on publish.
/// </summary>
/// <value>
/// <c>true</c> if umbraco will clone XML cache on publish; otherwise, <c>false</c>.
/// </value>
public static bool CloneXmlCacheOnPublish
{
get { return Umbraco.Core.Configuration.UmbracoSettings.CloneXmlCacheOnPublish; }
}
/// <summary>
/// Gets a value indicating whether rich text editor content should be parsed by tidy.
/// </summary>
/// <value><c>true</c> if content is parsed; otherwise, <c>false</c>.</value>
public static bool TidyEditorContent
{
get { return Umbraco.Core.Configuration.UmbracoSettings.TidyEditorContent; }
}
/// <summary>
/// Gets the encoding type for the tidyied content.
/// </summary>
/// <value>The encoding type as string.</value>
public static string TidyCharEncoding
{
get { return Umbraco.Core.Configuration.UmbracoSettings.TidyCharEncoding; }
}
/// <summary>
/// Gets the property context help option, this can either be 'text', 'icon' or 'none'
/// </summary>
/// <value>The property context help option.</value>
public static string PropertyContextHelpOption
{
get { return Umbraco.Core.Configuration.UmbracoSettings.PropertyContextHelpOption; }
}
public static string DefaultBackofficeProvider
{
get { return Umbraco.Core.Configuration.UmbracoSettings.DefaultBackofficeProvider; }
}
/// <summary>
/// Whether to force safe aliases (no spaces, no special characters) at businesslogic level on contenttypes and propertytypes
/// </summary>
public static bool ForceSafeAliases
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ForceSafeAliases; }
}
/// <summary>
/// File types that will not be allowed to be uploaded via the content/media upload control
/// </summary>
public static IEnumerable<string> DisallowedUploadFiles
{
get { return Umbraco.Core.Configuration.UmbracoSettings.DisallowedUploadFiles; }
}
/// <summary>
/// Gets the allowed image file types.
/// </summary>
/// <value>The allowed image file types.</value>
public static string ImageFileTypes
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ImageFileTypes; }
}
/// <summary>
/// Gets the allowed script file types.
/// </summary>
/// <value>The allowed script file types.</value>
public static string ScriptFileTypes
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ScriptFileTypes; }
}
/// <summary>
/// Gets the duration in seconds to cache queries to umbraco library member and media methods
/// Default is 1800 seconds (30 minutes)
/// </summary>
public static int UmbracoLibraryCacheDuration
{
get { return Umbraco.Core.Configuration.UmbracoSettings.UmbracoLibraryCacheDuration; }
}
/// <summary>
/// Gets the path to the scripts folder used by the script editor.
/// </summary>
/// <value>The script folder path.</value>
public static string ScriptFolderPath
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ScriptFolderPath; }
}
/// <summary>
/// Enabled or disable the script/code editor
/// </summary>
public static bool ScriptDisableEditor
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ScriptDisableEditor; }
}
/// <summary>
/// Gets a value indicating whether umbraco will ensure unique node naming.
/// This will ensure that nodes cannot have the same url, but will add extra characters to a url.
/// ex: existingnodename.aspx would become existingnodename(1).aspx if a node with the same name is found
/// </summary>
/// <value><c>true</c> if umbraco ensures unique node naming; otherwise, <c>false</c>.</value>
public static bool EnsureUniqueNaming
{
get { return Umbraco.Core.Configuration.UmbracoSettings.EnsureUniqueNaming; }
}
/// <summary>
/// Gets the notification email sender.
/// </summary>
/// <value>The notification email sender.</value>
public static string NotificationEmailSender
{
get { return Umbraco.Core.Configuration.UmbracoSettings.NotificationEmailSender; }
}
/// <summary>
/// Gets a value indicating whether notification-emails are HTML.
/// </summary>
/// <value>
/// <c>true</c> if html notification-emails are disabled; otherwise, <c>false</c>.
/// </value>
public static bool NotificationDisableHtmlEmail
{
get { return Umbraco.Core.Configuration.UmbracoSettings.NotificationDisableHtmlEmail; }
}
/// <summary>
/// Gets the allowed attributes on images.
/// </summary>
/// <value>The allowed attributes on images.</value>
public static string ImageAllowedAttributes
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ImageAllowedAttributes; }
}
public static XmlNode ImageAutoFillImageProperties
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ImageAutoFillImageProperties; }
}
/// <summary>
/// Gets the scheduled tasks as XML
/// </summary>
/// <value>The scheduled tasks.</value>
public static XmlNode ScheduledTasks
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ScheduledTasks; }
}
/// <summary>
/// Gets a list of characters that will be replaced when generating urls
/// </summary>
/// <value>The URL replacement characters.</value>
public static XmlNode UrlReplaceCharacters
{
get { return Umbraco.Core.Configuration.UmbracoSettings.UrlReplaceCharacters; }
}
/// <summary>
/// Whether to replace double dashes from url (ie my--story----from--dash.aspx caused by multiple url replacement chars
/// </summary>
public static bool RemoveDoubleDashesFromUrlReplacing
{
get { return Umbraco.Core.Configuration.UmbracoSettings.RemoveDoubleDashesFromUrlReplacing; }
}
/// <summary>
/// Gets a value indicating whether umbraco will use distributed calls.
/// This enables umbraco to share cache and content across multiple servers.
/// Used for load-balancing high-traffic sites.
/// </summary>
/// <value><c>true</c> if umbraco uses distributed calls; otherwise, <c>false</c>.</value>
public static bool UseDistributedCalls
{
get { return Umbraco.Core.Configuration.UmbracoSettings.UseDistributedCalls; }
}
/// <summary>
/// Gets the ID of the user with access rights to perform the distributed calls.
/// </summary>
/// <value>The distributed call user.</value>
public static int DistributedCallUser
{
get { return Umbraco.Core.Configuration.UmbracoSettings.DistributedCallUser; }
}
/// <summary>
/// Gets the html injected into a (x)html page if Umbraco is running in preview mode
/// </summary>
public static string PreviewBadge
{
get { return Umbraco.Core.Configuration.UmbracoSettings.PreviewBadge; }
}
/// <summary>
/// Gets IP or hostnames of the distribution servers.
/// These servers will receive a call everytime content is created/deleted/removed
/// and update their content cache accordingly, ensuring a consistent cache on all servers
/// </summary>
/// <value>The distribution servers.</value>
public static XmlNode DistributionServers
{
get { return Umbraco.Core.Configuration.UmbracoSettings.DistributionServers; }
}
/// <summary>
/// Gets HelpPage configurations.
/// A help page configuration specify language, user type, application, application url and
/// the target help page url.
/// </summary>
public static XmlNode HelpPages
{
get { return Umbraco.Core.Configuration.UmbracoSettings.HelpPages; }
}
/// <summary>
/// Gets all repositories registered, and returns them as XmlNodes, containing name, alias and webservice url.
/// These repositories are used by the build-in package installer and uninstaller to install new packages and check for updates.
/// All repositories should have a unique alias.
/// All packages installed from a repository gets the repository alias included in the install information
/// </summary>
/// <value>The repository servers.</value>
public static XmlNode Repositories
{
get { return Umbraco.Core.Configuration.UmbracoSettings.Repositories; }
}
/// <summary>
/// Gets a value indicating whether umbraco will use the viewstate mover module.
/// The viewstate mover will move all asp.net viewstate information to the bottom of the aspx page
/// to ensure that search engines will index text instead of javascript viewstate information.
/// </summary>
/// <value>
/// <c>true</c> if umbraco will use the viewstate mover module; otherwise, <c>false</c>.
/// </value>
public static bool UseViewstateMoverModule
{
get { return Umbraco.Core.Configuration.UmbracoSettings.UseViewstateMoverModule; }
}
/// <summary>
/// Tells us whether the Xml Content cache is disabled or not
/// Default is enabled
/// </summary>
public static bool isXmlContentCacheDisabled
{
get { return Umbraco.Core.Configuration.UmbracoSettings.IsXmlContentCacheDisabled; }
}
/// <summary>
/// Check if there's changes to the umbraco.config xml file cache on disk on each request
/// Makes it possible to updates environments by syncing the umbraco.config file across instances
/// Relates to http://umbraco.codeplex.com/workitem/30722
/// </summary>
public static bool XmlContentCheckForDiskChanges
{
get { return Umbraco.Core.Configuration.UmbracoSettings.XmlContentCheckForDiskChanges; }
}
/// <summary>
/// If this is enabled, all Umbraco objects will generate data in the preview table (cmsPreviewXml).
/// If disabled, only documents will generate data.
/// This feature is useful if anyone would like to see how data looked at a given time
/// </summary>
public static bool EnableGlobalPreviewStorage
{
get { return Umbraco.Core.Configuration.UmbracoSettings.EnableGlobalPreviewStorage; }
}
/// <summary>
/// Whether to use the new 4.1 schema or the old legacy schema
/// </summary>
/// <value>
/// <c>true</c> if yes, use the old node/data model; otherwise, <c>false</c>.
/// </value>
public static bool UseLegacyXmlSchema
{
get { return Umbraco.Core.Configuration.UmbracoSettings.UseLegacyXmlSchema; }
}
public static IEnumerable<string> AppCodeFileExtensionsList
{
get { return Umbraco.Core.Configuration.UmbracoSettings.AppCodeFileExtensionsList; }
}
[Obsolete("Use AppCodeFileExtensionsList instead")]
public static XmlNode AppCodeFileExtensions
{
get { return Umbraco.Core.Configuration.UmbracoSettings.AppCodeFileExtensions; }
}
/// <summary>
/// Tells us whether the Xml to always update disk cache, when changes are made to content
/// Default is enabled
/// </summary>
public static bool continouslyUpdateXmlDiskCache
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ContinouslyUpdateXmlDiskCache; }
}
/// <summary>
/// Tells us whether to use a splash page while umbraco is initializing content.
/// If not, requests are queued while umbraco loads content. For very large sites (+10k nodes) it might be usefull to
/// have a splash page
/// Default is disabled
/// </summary>
public static bool EnableSplashWhileLoading
{
get { return Umbraco.Core.Configuration.UmbracoSettings.EnableSplashWhileLoading; }
}
public static bool ResolveUrlsFromTextString
{
get { return Umbraco.Core.Configuration.UmbracoSettings.ResolveUrlsFromTextString; }
}
/// <summary>
/// This configuration setting defines how to handle macro errors:
/// - Inline - Show error within macro as text (default and current Umbraco 'normal' behavior)
/// - Silent - Suppress error and hide macro
/// - Throw - Throw an exception and invoke the global error handler (if one is defined, if not you'll get a YSOD)
/// </summary>
/// <value>MacroErrorBehaviour enum defining how to handle macro errors.</value>
public static MacroErrorBehaviour MacroErrorBehaviour
{
get { return Umbraco.Core.Configuration.UmbracoSettings.MacroErrorBehaviour; }
}
/// <summary>
/// This configuration setting defines how to show icons in the document type editor.
/// - ShowDuplicates - Show duplicates in files and sprites. (default and current Umbraco 'normal' behaviour)
/// - HideSpriteDuplicates - Show files on disk and hide duplicates from the sprite
/// - HideFileDuplicates - Show files in the sprite and hide duplicates on disk
/// </summary>
/// <value>MacroErrorBehaviour enum defining how to show icons in the document type editor.</value>
public static IconPickerBehaviour IconPickerBehaviour
{
get { return Umbraco.Core.Configuration.UmbracoSettings.IconPickerBehaviour; }
}
/// <summary>
/// Gets the default document type property used when adding new properties through the back-office
/// </summary>
/// <value>Configured text for the default document type property</value>
/// <remarks>If undefined, 'Textstring' is the default</remarks>
public static string DefaultDocumentTypeProperty
{
get { return Umbraco.Core.Configuration.UmbracoSettings.DefaultDocumentTypeProperty; }
}
/// <summary>
/// Configuration regarding webservices
/// </summary>
/// <remarks>Put in seperate class for more logik/seperation</remarks>
public class Webservices
{
/// <summary>
/// Gets a value indicating whether this <see cref="Webservices"/> is enabled.
/// </summary>
/// <value><c>true</c> if enabled; otherwise, <c>false</c>.</value>
public static bool Enabled
{
get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.Enabled; }
}
#region "Webservice configuration"
/// <summary>
/// Gets the document service users who have access to use the document web service
/// </summary>
/// <value>The document service users.</value>
public static string[] documentServiceUsers
{
get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.DocumentServiceUsers; }
}
/// <summary>
/// Gets the file service users who have access to use the file web service
/// </summary>
/// <value>The file service users.</value>
public static string[] fileServiceUsers
{
get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.FileServiceUsers; }
}
/// <summary>
/// Gets the folders used by the file web service
/// </summary>
/// <value>The file service folders.</value>
public static string[] fileServiceFolders
{
get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.FileServiceFolders; }
}
/// <summary>
/// Gets the member service users who have access to use the member web service
/// </summary>
/// <value>The member service users.</value>
public static string[] memberServiceUsers
{
get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.MemberServiceUsers; }
}
/// <summary>
/// Gets the stylesheet service users who have access to use the stylesheet web service
/// </summary>
/// <value>The stylesheet service users.</value>
public static string[] stylesheetServiceUsers
{
get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.StylesheetServiceUsers; }
}
/// <summary>
/// Gets the template service users who have access to use the template web service
/// </summary>
/// <value>The template service users.</value>
public static string[] templateServiceUsers
{
get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.TemplateServiceUsers; }
}
/// <summary>
/// Gets the media service users who have access to use the media web service
/// </summary>
/// <value>The media service users.</value>
public static string[] mediaServiceUsers
{
get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.MediaServiceUsers; }
}
/// <summary>
/// Gets the maintenance service users who have access to use the maintance web service
/// </summary>
/// <value>The maintenance service users.</value>
public static string[] maintenanceServiceUsers
{
get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.MaintenanceServiceUsers; }
}
#endregion
}
}
}
| |
// Copyright (c) 2017 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Xml.Linq;
using Newtonsoft.Json;
using Palaso.Extensions;
namespace LfMerge.AutomatedSRTests
{
/// <summary>
/// Converts the JSON datastructure which describes the expected data for the tests into
/// a corresponding XML form that can be used to verify language depot data.
/// </summary>
public class JsonToXml
{
private JsonTextReader _reader;
public static XElement Convert(string expected)
{
return new JsonToXml().Translate(expected);
}
private JsonToXml()
{
}
private XElement Translate(string expected)
{
_reader = new JsonTextReader(new StringReader(expected));
var popStack = new Stack<XElement>();
while (_reader.Read())
{
switch (_reader.TokenType)
{
case JsonToken.StartArray:
{
if (popStack.Count == 0)
popStack.Push(AddChildElement(null, "Lexicon"));
break;
}
case JsonToken.StartObject:
{
if (popStack.Count == 1)
popStack.Push(AddChildElement(popStack.Peek(), "LexEntry"));
break;
}
case JsonToken.EndObject:
popStack.Pop();
break;
case JsonToken.EndArray:
if (popStack.Count == 1)
return popStack.Pop();
break;
case JsonToken.PropertyName:
popStack.Peek().Add(ProcessPropertyName());
break;
case JsonToken.Comment:
popStack.Peek().Add(ProcessComment());
break;
case JsonToken.Date:
case JsonToken.Bytes:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
break;
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.None:
case JsonToken.StartConstructor:
case JsonToken.EndConstructor:
case JsonToken.Raw:
break;
}
}
throw new InvalidDataException("JSON data didn't end with an end-of-array token");
}
private XElement ProcessComment()
{
// we use the comment to specify fields that should not exist;
// format: "no <fieldname>"
XElement child = null;
var parts = _reader.Value.ToString()
.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 1)
{
if (parts[0] == "no")
{
child = new XElement(parts[1].ToUpperFirstLetter());
child.Add(new XAttribute("expectAbsence", true));
}
}
return child;
}
private XElement ProcessPropertyName()
{
XElement element = null;
switch (_reader.Value as string)
{
case "lexeme":
// "lexeme": { "fr" : { "value" : "lf1<br/>" } }
element = new XElement("LexemeForm");
element.Add(ProcessLexeme());
break;
case "senses":
element = new XElement("Senses");
element.Add(ProcessSenses());
break;
case "definition":
{
// "definition" : { "en" : { "value" : "Word added by LF<br/>" } }
element = new XElement("Definition");
var aStr = ProcessAStrElement();
if (string.IsNullOrEmpty(aStr.Element("Run").Value))
element.Add(new XAttribute("expectAbsence", true));
else
element.Add(aStr);
break;
}
case "gloss":
{
// "gloss" : { "en" : { "value" : "created in FLEx" } },
element = new XElement("Gloss");
var aUni = ProcessAUniElement();
if (string.IsNullOrEmpty(aUni.Value))
element.Add(new XAttribute("expectAbsence", true));
else
element.Add(aUni);
break;
}
case "partOfSpeech":
// "partOfSpeech" : { "value" : "adv1" }
// How do we deal with POS? For now just ignore
Read(JsonToken.StartObject); // {
Read(JsonToken.PropertyName); // "value"
Read(JsonToken.String); // "adv1"
Read(JsonToken.EndObject); // }
break;
}
return element;
}
private XContainer ProcessSenses()
{
// [ { "gloss" : { "en" : { "value" : "created in FLEx" } },
// "partOfSpeech" : { "value" : "adv1" } } ]
Read(JsonToken.StartArray); // [
Read(JsonToken.StartObject); // {
var ownseq = new XElement("ownseq");
while (_reader.Read())
{
switch (_reader.TokenType)
{
case JsonToken.PropertyName:
ownseq.Add(ProcessPropertyName());
break;
case JsonToken.EndObject:
case JsonToken.EndArray:
return ownseq;
case JsonToken.Comment:
ownseq.Add(ProcessComment());
break;
}
}
return ownseq;
}
private XElement ProcessLexeme()
{
// { "fr" : { "value" : "lf1<br/>" } }
var mostem = new XElement("MoStemAllomorph");
var form = new XElement("Form");
form.Add(ProcessAUniElement());
mostem.Add(form);
return mostem;
}
private XElement ProcessAUniElement()
{
// { "fr" : { "value" : "lf1<br/>" } }
Read(JsonToken.StartObject); // {
var aUni = new XElement("AUni");
AddWritingSystemAttribute(aUni); // "fr"
Read(JsonToken.StartObject); // {
Read(JsonToken.PropertyName); // "value"
Debug.Assert(_reader.Value as string == "value");
Read(JsonToken.String); // "lf1<br/>"
aUni.Add((string) _reader.Value);
Read(JsonToken.EndObject); // }
Read(JsonToken.EndObject); // }
return aUni;
}
private XElement ProcessAStrElement()
{
// { "en" : { "value" : "Word added by LF<br/>" } }
Read(JsonToken.StartObject); // {
var aStr = new XElement("AStr");
var ws = AddWritingSystemAttribute(aStr); // "en"
Read(JsonToken.StartObject); // {
Read(JsonToken.PropertyName); // "value"
Debug.Assert(_reader.Value as string == "value");
Read(JsonToken.String); // "Word added by LF<br/>"
var run = new XElement("Run");
AddWritingSystemAttribute(run, ws);
run.Add((string) _reader.Value);
aStr.Add(run);
Read(JsonToken.EndObject); // }
Read(JsonToken.EndObject); // }
return aStr;
}
private void Read(JsonToken token)
{
_reader.Read();
Debug.Assert(_reader.TokenType == token);
}
private string AddWritingSystemAttribute(XContainer auni, string ws = null)
{
if (ws == null)
{
Read(JsonToken.PropertyName); // "fr"
ws = _reader.Value as string;
}
auni.Add(new XAttribute("ws", ws));
return ws;
}
private XElement AddChildElement(XContainer parent, string name)
{
var element = new XElement(name);
parent?.Add(element);
return element;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// Convert.ToUInt16(object,IFormatProvider)
/// </summary>
public class ConvertToUInt1614
{
public static int Main()
{
ConvertToUInt1614 convertToUInt1614 = new ConvertToUInt1614();
TestLibrary.TestFramework.BeginTestCase("ConvertToUInt1614");
if (convertToUInt1614.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1:Convert to UInt16 from object 1");
try
{
TestClass2 objVal = new TestClass2();
TestIFormat iformat = new TestIFormat();
ushort unshortVal1 = Convert.ToUInt16(objVal,iformat);
ushort unshortVal2 = Convert.ToUInt16(objVal, null);
if (unshortVal1 != UInt16.MaxValue || unshortVal2 != UInt16.MinValue)
{
TestLibrary.TestFramework.LogError("001", "the ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2:Convert to UInt16 from object 2");
try
{
object objVal = true;
TestIFormat iformat = new TestIFormat();
ushort unshortVal1 = Convert.ToUInt16(objVal, iformat);
ushort unshortVal2 = Convert.ToUInt16(objVal, null);
if (unshortVal1 != 1 || unshortVal2 != 1)
{
TestLibrary.TestFramework.LogError("003", "the ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3:Convert to UInt16 from object 3");
try
{
object objVal = false;
TestIFormat iformat = new TestIFormat();
ushort unshortVal1 = Convert.ToUInt16(objVal, iformat);
ushort unshortVal2 = Convert.ToUInt16(objVal, null);
if (unshortVal1 != 0 || unshortVal2 != 0)
{
TestLibrary.TestFramework.LogError("005", "the ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4:Convert to UInt16 from object 4");
try
{
object objVal = null;
TestIFormat iformat = new TestIFormat();
ushort unshortVal1 = Convert.ToUInt16(objVal, iformat);
ushort unshortVal2 = Convert.ToUInt16(objVal, null);
if (unshortVal1 != 0 || unshortVal2 != 0)
{
TestLibrary.TestFramework.LogError("007", "the ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1:The object does not implement IConvertible");
try
{
TestClass1 objVal = new TestClass1();
ushort unshortVal = Convert.ToUInt16(objVal,null);
TestLibrary.TestFramework.LogError("N001", "The object does not implement IConvertible but not throw exception");
retVal = false;
}
catch (InvalidCastException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region ForTestClass
public class TestClass1 { }
public class TestIFormat : IFormatProvider
{
public bool IsUInt16MaxValue = true;
public object GetFormat(Type argType)
{
if (argType == typeof(TestIFormat))
return this;
else
return null;
}
}
public class TestClass2 : IConvertible
{
public TypeCode GetTypeCode()
{
throw new Exception("The method or operation is not implemented.");
}
public bool ToBoolean(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public byte ToByte(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public char ToChar(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public DateTime ToDateTime(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public decimal ToDecimal(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public double ToDouble(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public short ToInt16(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public int ToInt32(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public long ToInt64(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public sbyte ToSByte(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public float ToSingle(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public string ToString(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public object ToType(Type conversionType, IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public ushort ToUInt16(IFormatProvider provider)
{
bool IsUInt16MinValue = true;
if (provider != null)
{
TestIFormat iformat = (TestIFormat)provider.GetFormat(typeof(TestIFormat));
if (iformat != null && iformat.IsUInt16MaxValue)
{
IsUInt16MinValue = false;
}
}
if (IsUInt16MinValue)
{
return UInt16.MinValue;
}
else
{
return UInt16.MaxValue;
}
}
public uint ToUInt32(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public ulong ToUInt64(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
}
#endregion
#region HelpMethod
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Serilog.Debugging;
namespace Serilog.Sinks.Amazon.Kinesis.Common
{
abstract class HttpLogShipperBase<TRecord, TResponse>
{
private readonly ILogReaderFactory _logReaderFactory;
private readonly IPersistedBookmarkFactory _persistedBookmarkFactory;
private readonly ILogShipperFileManager _fileManager;
protected readonly int _batchPostingLimit;
protected readonly string _bookmarkFilename;
protected readonly string _candidateSearchPath;
protected readonly string _logFolder;
protected readonly string _streamName;
protected HttpLogShipperBase(
ILogShipperOptions options,
ILogReaderFactory logReaderFactory,
IPersistedBookmarkFactory persistedBookmarkFactory,
ILogShipperFileManager fileManager
)
{
if (options == null) throw new ArgumentNullException(nameof(options));
if (logReaderFactory == null) throw new ArgumentNullException(nameof(logReaderFactory));
if (persistedBookmarkFactory == null) throw new ArgumentNullException(nameof(persistedBookmarkFactory));
if (fileManager == null) throw new ArgumentNullException(nameof(fileManager));
_logReaderFactory = logReaderFactory;
_persistedBookmarkFactory = persistedBookmarkFactory;
_fileManager = fileManager;
_batchPostingLimit = options.BatchPostingLimit;
_streamName = options.StreamName;
_bookmarkFilename = Path.GetFullPath(options.BufferBaseFilename + ".bookmark");
_logFolder = Path.GetDirectoryName(_bookmarkFilename);
_candidateSearchPath = Path.GetFileName(options.BufferBaseFilename) + "*.json";
}
protected abstract TRecord PrepareRecord(MemoryStream stream);
protected abstract TResponse SendRecords(List<TRecord> records, out bool successful);
protected abstract void HandleError(TResponse response, int originalRecordCount);
public event EventHandler<LogSendErrorEventArgs> LogSendError;
protected void OnLogSendError(LogSendErrorEventArgs e)
{
var handler = LogSendError;
if (handler != null)
{
handler(this, e);
}
}
private IPersistedBookmark TryCreateBookmark()
{
try
{
return _persistedBookmarkFactory.Create(_bookmarkFilename);
}
catch (IOException ex)
{
SelfLog.WriteLine("Bookmark cannot be opened.", ex);
return null;
}
}
protected void ShipLogs()
{
try
{
// Locking the bookmark ensures that though there may be multiple instances of this
// class running, only one will ship logs at a time.
using (var bookmark = TryCreateBookmark())
{
if (bookmark == null)
return;
ShipLogs(bookmark);
}
}
catch (IOException ex)
{
SelfLog.WriteLine("Error shipping logs", ex);
}
catch (Exception ex)
{
SelfLog.WriteLine("Error shipping logs", ex);
OnLogSendError(new LogSendErrorEventArgs(string.Format("Error in shipping logs to '{0}' stream", _streamName), ex));
}
}
private void ShipLogs(IPersistedBookmark bookmark)
{
do
{
string currentFilePath = bookmark.FileName;
SelfLog.WriteLine("Bookmark is currently at offset {0} in '{1}'", bookmark.Position, currentFilePath);
var fileSet = GetFileSet();
if (currentFilePath == null)
{
currentFilePath = fileSet.FirstOrDefault();
SelfLog.WriteLine("New log file is {0}", currentFilePath);
bookmark.UpdateFileNameAndPosition(currentFilePath, 0L);
}
else if (fileSet.All(f => CompareFileNames(f, currentFilePath) != 0))
{
currentFilePath = fileSet.FirstOrDefault(f => CompareFileNames(f, currentFilePath) >= 0);
SelfLog.WriteLine("New log file is {0}", currentFilePath);
bookmark.UpdateFileNameAndPosition(currentFilePath, 0L);
}
// delete all previous files - we will not read them anyway
if (currentFilePath == null)
{
foreach (var fileToDelete in fileSet)
{
TryDeleteFile(fileToDelete);
}
}
else
{
foreach (var fileToDelete in fileSet.TakeWhile(f => CompareFileNames(f, currentFilePath) < 0))
{
TryDeleteFile(fileToDelete);
}
}
if (currentFilePath == null)
{
SelfLog.WriteLine("No log file is found. Nothing to do.");
break;
}
// now we are interested in current file and all after it.
fileSet =
fileSet.SkipWhile(f => CompareFileNames(f, currentFilePath) < 0)
.ToArray();
var initialPosition = bookmark.Position;
List<TRecord> records;
do
{
var batch = ReadRecordBatch(currentFilePath, bookmark.Position, _batchPostingLimit);
records = batch.Item2;
if (records.Count > 0)
{
bool successful;
var response = SendRecords(records, out successful);
if (!successful)
{
SelfLog.WriteLine("SendRecords failed for {0} records.", records.Count);
HandleError(response, records.Count);
return;
}
}
var newPosition = batch.Item1;
if (initialPosition < newPosition)
{
SelfLog.WriteLine("Advancing bookmark from {0} to {1} on {2}", initialPosition, newPosition, currentFilePath);
bookmark.UpdatePosition(newPosition);
}
else if (initialPosition > newPosition)
{
newPosition = 0;
SelfLog.WriteLine("File {2} has been truncated or re-created, bookmark reset from {0} to {1}", initialPosition, newPosition, currentFilePath);
bookmark.UpdatePosition(newPosition);
}
} while (records.Count >= _batchPostingLimit);
if (initialPosition == bookmark.Position)
{
SelfLog.WriteLine("Found no records to process");
// Only advance the bookmark if there is next file in the queue
// and no other process has the current file locked, and its length is as we found it.
if (fileSet.Length > 1)
{
SelfLog.WriteLine("BufferedFilesCount: {0}; checking if can advance to the next file", fileSet.Length);
var weAreAtEndOfTheFileAndItIsNotLockedByAnotherThread = WeAreAtEndOfTheFileAndItIsNotLockedByAnotherThread(currentFilePath, bookmark.Position);
if (weAreAtEndOfTheFileAndItIsNotLockedByAnotherThread)
{
SelfLog.WriteLine("Advancing bookmark from '{0}' to '{1}'", currentFilePath, fileSet[1]);
bookmark.UpdateFileNameAndPosition(fileSet[1], 0);
}
else
{
break;
}
}
else
{
SelfLog.WriteLine("This is a single log file, and we are in the end of it. Nothing to do.");
break;
}
}
} while (true);
}
private Tuple<long, List<TRecord>> ReadRecordBatch(string currentFilePath, long position, int maxRecords)
{
var records = new List<TRecord>(maxRecords);
long positionSent;
using (var reader = _logReaderFactory.Create(currentFilePath, position))
{
do
{
var stream = reader.ReadLine();
if (stream.Length == 0)
{
break;
}
records.Add(PrepareRecord(stream));
} while (records.Count < maxRecords);
positionSent = reader.Position;
}
return Tuple.Create(positionSent, records);
}
private bool TryDeleteFile(string fileToDelete)
{
try
{
_fileManager.LockAndDeleteFile(fileToDelete);
SelfLog.WriteLine("Log file deleted: {0}", fileToDelete);
return true;
}
catch (Exception ex)
{
SelfLog.WriteLine("Exception deleting file: {0}", ex, fileToDelete);
return false;
}
}
private bool WeAreAtEndOfTheFileAndItIsNotLockedByAnotherThread(string file, long nextLineBeginsAtOffset)
{
try
{
return _fileManager.GetFileLengthExclusiveAccess(file) <= nextLineBeginsAtOffset;
}
catch (IOException ex)
{
SelfLog.WriteLine("Swallowed I/O exception while testing locked status of {0}", ex, file);
}
catch (Exception ex)
{
SelfLog.WriteLine("Unexpected exception while testing locked status of {0}", ex, file);
}
return false;
}
private string[] GetFileSet()
{
var fileSet = _fileManager.GetFiles(_logFolder, _candidateSearchPath)
.OrderBy(n => n, StringComparer.OrdinalIgnoreCase)
.ToArray();
SelfLog.WriteLine("FileSet contains: {0}", string.Join(";", fileSet));
return fileSet;
}
private static int CompareFileNames(string fileName1, string fileName2)
{
return string.Compare(fileName1, fileName2, StringComparison.OrdinalIgnoreCase);
}
}
}
| |
using XPT.Games.Generic.Constants;
using XPT.Games.Generic.Maps;
using XPT.Games.Twinion.Entities;
namespace XPT.Games.Twinion.Maps {
class TwMap20 : TwMap {
public override int MapIndex => 20;
public override int MapID => 0x0802;
protected override int RandomEncounterChance => 10;
protected override int RandomEncounterExtraCount => 1;
private const int WIZCHOICE = 1;
private const int DRAGON_B = 9;
private const int DRAGON_A = 10;
private const int ONE_NORTH = 14;
private const int ONE_CENTER = 15;
private const int ONE_SOUTH = 16;
protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE, 1);
TeleportParty(player, type, doMsgs, 8, 2, 124, Direction.South);
}
protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == GNOME || GetRace(player, type, doMsgs) == TROLL) {
TeleportParty(player, type, doMsgs, 8, 2, 251, Direction.North);
}
else if (GetRace(player, type, doMsgs) == ELF || GetRace(player, type, doMsgs) == GREMLIN) {
TeleportParty(player, type, doMsgs, 8, 2, 96, Direction.East);
}
else if (GetRace(player, type, doMsgs) == DWARF || GetRace(player, type, doMsgs) == ORC) {
TeleportParty(player, type, doMsgs, 8, 2, 77, Direction.East);
}
else {
TeleportParty(player, type, doMsgs, 8, 2, 145, Direction.West);
}
}
protected override void FnEvent03(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE, 2);
TeleportParty(player, type, doMsgs, 8, 2, 124, Direction.East);
}
protected override void FnEvent04(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == GNOME || GetRace(player, type, doMsgs) == ELF) {
TeleportParty(player, type, doMsgs, 8, 2, 81, Direction.East);
}
else if (GetRace(player, type, doMsgs) == TROLL || GetRace(player, type, doMsgs) == GREMLIN) {
TeleportParty(player, type, doMsgs, 8, 2, 163, Direction.North);
}
else if (GetRace(player, type, doMsgs) == DWARF || GetRace(player, type, doMsgs) == HALFLING) {
TeleportParty(player, type, doMsgs, 8, 2, 204, Direction.West);
}
else {
TeleportParty(player, type, doMsgs, 8, 2, 44, Direction.West);
}
}
protected override void FnEvent05(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == GNOME || GetRace(player, type, doMsgs) == ELF) {
TeleportParty(player, type, doMsgs, 8, 2, 204, Direction.West);
}
else if (GetRace(player, type, doMsgs) == TROLL || GetRace(player, type, doMsgs) == GREMLIN) {
TeleportParty(player, type, doMsgs, 8, 2, 44, Direction.West);
}
else if (GetRace(player, type, doMsgs) == DWARF || GetRace(player, type, doMsgs) == HALFLING) {
TeleportParty(player, type, doMsgs, 8, 2, 81, Direction.East);
}
else {
TeleportParty(player, type, doMsgs, 8, 2, 163, Direction.North);
}
}
protected override void FnEvent06(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == GNOME || GetRace(player, type, doMsgs) == ELF) {
TeleportParty(player, type, doMsgs, 8, 2, 44, Direction.West);
}
else if (GetRace(player, type, doMsgs) == TROLL || GetRace(player, type, doMsgs) == GREMLIN) {
TeleportParty(player, type, doMsgs, 8, 2, 204, Direction.West);
}
else if (GetRace(player, type, doMsgs) == DWARF || GetRace(player, type, doMsgs) == HALFLING) {
TeleportParty(player, type, doMsgs, 8, 2, 163, Direction.North);
}
else {
TeleportParty(player, type, doMsgs, 8, 2, 81, Direction.East);
}
}
protected override void FnEvent07(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == GNOME || GetRace(player, type, doMsgs) == ELF) {
TeleportParty(player, type, doMsgs, 8, 2, 163, Direction.North);
}
else if (GetRace(player, type, doMsgs) == TROLL || GetRace(player, type, doMsgs) == GREMLIN) {
TeleportParty(player, type, doMsgs, 8, 2, 81, Direction.East);
}
else if (GetRace(player, type, doMsgs) == DWARF || GetRace(player, type, doMsgs) == HALFLING) {
TeleportParty(player, type, doMsgs, 8, 2, 44, Direction.West);
}
else {
TeleportParty(player, type, doMsgs, 8, 2, 204, Direction.West);
}
}
protected override void FnEvent08(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == GNOME || GetRace(player, type, doMsgs) == TROLL) {
TeleportParty(player, type, doMsgs, 8, 2, 255, Direction.West);
}
else if (GetRace(player, type, doMsgs) == ELF || GetRace(player, type, doMsgs) == GREMLIN) {
TeleportParty(player, type, doMsgs, 8, 2, 240, Direction.East);
}
else if (GetRace(player, type, doMsgs) == DWARF || GetRace(player, type, doMsgs) == ORC) {
TeleportParty(player, type, doMsgs, 8, 2, 10, Direction.South);
}
else {
TeleportParty(player, type, doMsgs, 8, 2, 4, Direction.South);
}
}
protected override void FnEvent09(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE, 4);
TeleportParty(player, type, doMsgs, 8, 2, 124, Direction.West);
}
protected override void FnEvent0A(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE, 3);
TeleportParty(player, type, doMsgs, 8, 2, 124, Direction.North);
}
protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Beyond this portal lies the wizard village Hocus Pocus.");
TeleportParty(player, type, doMsgs, 9, 1, 247, Direction.North);
}
protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, GREMLINWIZARD);
ModifyGold(player, type, doMsgs, - 1000);
ShowText(player, type, doMsgs, "'I am the wizard Majikyl. For a mere pittance I shall envelop you in a Vapor Cloud. This cloud will allow you to approach the dragon unseen.");
ShowText(player, type, doMsgs, "If you wish to continue, step through the door to the east.'");
}
protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You find a page from MyMy's and Sinestra's journal with a faded map of many doors.");
ShowText(player, type, doMsgs, "Across the top you can barely make out the words 'Hocus Pocus' and across the bottom you see four words but can only decipher S h W S We .");
}
protected override void FnEvent0E(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, HUMANWIZARD);
ModifyGold(player, type, doMsgs, - 1000);
ShowText(player, type, doMsgs, "'I am the wizard Artsenis. For this fee I will aid your quest. I shall place upon you a Chameleon Shroud spell. So disguised, you should be successful in approaching the dragon.");
ShowText(player, type, doMsgs, "If you choose to continue, step through the door to the south.'");
}
protected override void FnEvent0F(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, ELFBARBARIAN);
ShowText(player, type, doMsgs, "'I was told that you have to search every nook and cranny in the tunnels to find access to the dragons.'");
}
protected override void FnEvent10(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "A bloody hand print marks the wall.");
}
protected override void FnEvent11(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, TROLLCLERIC);
ShowText(player, type, doMsgs, "You cross paths with a Troll Cleric, who whispers to you,");
ShowText(player, type, doMsgs, "'After searching all over, I retraced my steps and found an opening where none appeared before. This dungeon is a strange place.'");
}
protected override void FnEvent12(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, DWARFWIZARD);
ModifyGold(player, type, doMsgs, - 1000);
ShowText(player, type, doMsgs, "'I am the wizard Aillacsar. I shall take my fee for the Invisibility I cast upon you. It will get you close to your prey.");
ShowText(player, type, doMsgs, "If you choose to continue, walk east through the teleport.'");
}
protected override void FnEvent13(TwPlayerServer player, MapEventType type, bool doMsgs) {
AddEncounter(player, type, doMsgs, 01, 16);
AddEncounter(player, type, doMsgs, 02, 28);
AddEncounter(player, type, doMsgs, 03, 37);
AddEncounter(player, type, doMsgs, 04, 36);
AddEncounter(player, type, doMsgs, 05, 38);
AddEncounter(player, type, doMsgs, 06, 29);
}
protected override void FnEvent14(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, GNOMEWIZARD);
ModifyGold(player, type, doMsgs, - 1000);
ShowText(player, type, doMsgs, "'I am the wizard Mirloch. Accept my magic for a small fee. I have cast upon you a Charismatic Aura. The enemy will look upon you as a friend.");
ShowText(player, type, doMsgs, "If you wish to continue, walk to the west through the teleport.");
}
protected override void FnEvent15(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You step into a deep crevice and fall to your death.");
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
}
protected override void FnEvent16(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The searing heat of the lava engulfs you in flames.");
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
}
protected override void FnEvent17(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasUsedSkill(player, type, ref doMsgs, DETECT_SKILL) >= 10 || HasUsedSpell(player, type, ref doMsgs, TRUE_SEEING_SPELL) >= 1 || UsedItem(player, type, ref doMsgs, HELMOFWISDOM, HELMOFWISDOM) || UsedItem(player, type, ref doMsgs, VALKYRIESHELM, VALKYRIESHELM) || UsedItem(player, type, ref doMsgs, RINGOFTHIEVES, RINGOFTHIEVES) || UsedItem(player, type, ref doMsgs, CRYSTALBALL, CRYSTALBALL)) {
ShowText(player, type, doMsgs, "You discover an opening.");
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
else {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
}
protected override void FnEvent18(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasUsedSkill(player, type, ref doMsgs, DETECT_SKILL) >= 10 || HasUsedSpell(player, type, ref doMsgs, TRUE_SEEING_SPELL) >= 1 || UsedItem(player, type, ref doMsgs, HELMOFWISDOM, HELMOFWISDOM) || UsedItem(player, type, ref doMsgs, VALKYRIESHELM, VALKYRIESHELM) || UsedItem(player, type, ref doMsgs, RINGOFTHIEVES, RINGOFTHIEVES) || UsedItem(player, type, ref doMsgs, CRYSTALBALL, CRYSTALBALL)) {
ShowText(player, type, doMsgs, "You push aside a pile of rubble and find a clear path ahead.");
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
else {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
}
protected override void FnEvent19(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasUsedSkill(player, type, ref doMsgs, DETECT_SKILL) >= 10 || HasUsedSpell(player, type, ref doMsgs, TRUE_SEEING_SPELL) >= 1 || UsedItem(player, type, ref doMsgs, HELMOFWISDOM, HELMOFWISDOM) || UsedItem(player, type, ref doMsgs, VALKYRIESHELM, VALKYRIESHELM) || UsedItem(player, type, ref doMsgs, RINGOFTHIEVES, RINGOFTHIEVES) || UsedItem(player, type, ref doMsgs, CRYSTALBALL, CRYSTALBALL)) {
ShowText(player, type, doMsgs, "Your keen senses detect a hidden door.");
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
else {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
}
protected override void FnEvent1A(TwPlayerServer player, MapEventType type, bool doMsgs) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
protected override void FnEvent1B(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You are teleported to a series of long, dark tunnels. Here is where the dragons continue their feud.");
if (GetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE) == 1) {
SetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE, 5);
}
}
protected override void FnEvent1C(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You are teleported to a series of long, dark tunnels. Here is where the dragons continue their feud.");
if (GetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE) == 2) {
SetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE, 5);
}
}
protected override void FnEvent1D(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You are teleported to a series of long, dark tunnels. Here is where the dragons continue their feud.");
if (GetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE) == 3) {
SetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE, 5);
}
}
protected override void FnEvent1E(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You are teleported to a series of long, dark tunnels. Here is where the dragons continue their feud.");
if (GetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE) == 4) {
SetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE, 5);
}
}
protected override void FnEvent1F(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeParty, DRAGON_B) == 1 && HasItem(player, type, doMsgs, DRAGONSSKIN)) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
else {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
}
protected override void FnEvent20(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeParty, DRAGON_A) == 1 && GetFlag(player, type, doMsgs, FlagTypeParty, ONE_NORTH) == 1 && GetFlag(player, type, doMsgs, FlagTypeParty, ONE_CENTER) == 1 && GetFlag(player, type, doMsgs, FlagTypeParty, ONE_SOUTH) == 1) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
else {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
}
protected override void FnEvent21(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeParty, DRAGON_A) == 1 && HasItem(player, type, doMsgs, DRAGONSSKIN)) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
else {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
}
protected override void FnEvent22(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeParty, DRAGON_B) == 1 && GetFlag(player, type, doMsgs, FlagTypeParty, ONE_NORTH) == 1 && GetFlag(player, type, doMsgs, FlagTypeParty, ONE_CENTER) == 1 && GetFlag(player, type, doMsgs, FlagTypeParty, ONE_SOUTH) == 1) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
else {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
}
protected override void FnEvent23(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, GREMLINTHIEF);
ShowText(player, type, doMsgs, "'Greetings! Have you seen my two companions? We were separated when we walked alone through a teleport.'");
SetFlag(player, type, doMsgs, FlagTypeParty, ONE_NORTH, 1);
if (GetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE) != 5) {
ShowText(player, type, doMsgs, "'You say you have visited a wizard for magic? Hmmm, I see no signs of that. Well, good journeys!'");
}
else {
ShowText(player, type, doMsgs, "'If you see them, please tell them I'm still searching. Good journeys to you!'");
}
}
protected override void FnEvent25(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, ELFCLERIC);
ShowText(player, type, doMsgs, "You encounter a tired elf leaning on a wall.");
SetFlag(player, type, doMsgs, FlagTypeParty, ONE_SOUTH, 1);
if (GetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE) != 5) {
ShowText(player, type, doMsgs, "'Have you had the same problem as us? Either the magic was weak or something stripped it from us in our wanderings.'");
}
else {
ShowText(player, type, doMsgs, "'Well met! I am searching for my lost companions. I must hurry on, safe paths!'");
}
}
protected override void FnEvent26(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You notice a sign in pieces on the ground and barely make out the wording 'WARNING!!! These teleports are condemned by order of Queen Aeowyn!!!'");
ShowText(player, type, doMsgs, "Attached to the sign is a hand written note, 'Olyces, some thief told me my magic protection was gone! Something odd about these teleports or where they take me.");
ShowText(player, type, doMsgs, "I'm off to the wizards again and will meet you inside. I hope to use the correct teleport this time.' The note is signed, Bawcrs.");
}
protected override void FnEvent28(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, TROLLKNIGHT);
ShowText(player, type, doMsgs, "You stumble upon an injured troll and administer aid.");
SetFlag(player, type, doMsgs, FlagTypeParty, ONE_CENTER, 1);
if (GetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE) != 5) {
ShowText(player, type, doMsgs, "'A dangerous place indeed. I see no signs of magic about you. If you have visited the wizards, I suggest you try again. Sometimes shifting clouds of old magic strip the defenses. My thanks to you.'");
}
else {
ShowText(player, type, doMsgs, "'My thanks to you for much needed aid. You appear to be well protected. I shall remember your kindness; fare well my friends.'");
}
}
protected override void FnEvent29(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SCALE) == 1) {
ShowText(player, type, doMsgs, "Gambril lumbers away.");
SetFlag(player, type, doMsgs, FlagTypeParty, DRAGON_B, 1);
}
else {
if (HasItem(player, type, doMsgs, DRAGONSSKIN)) {
ShowPortrait(player, type, doMsgs, WHITEDRAGON);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SCALE, 1);
ModifyExperience(player, type, doMsgs, 500000);
ModifyGold(player, type, doMsgs, 25000);
GiveItem(player, type, doMsgs, STONEGIANTSHAMMER);
GiveItem(player, type, doMsgs, MIDNIGHTAEGIS);
GiveItem(player, type, doMsgs, FLAMETONGUE);
GiveItem(player, type, doMsgs, HEALAMPHORA);
GiveItem(player, type, doMsgs, ZEUSSCROLL);
ShowText(player, type, doMsgs, "Gambril is obviously relieved that his nemesis is finally dead.");
ShowText(player, type, doMsgs, "He gives you a reward and says, 'It would be wise to take your trophy to Hocus Pocus. The wizards there oftentimes need unique items.'");
}
else {
ShowPortrait(player, type, doMsgs, WHITEDRAGON);
SetFlag(player, type, doMsgs, FlagTypeParty, DRAGON_B, 1);
ShowText(player, type, doMsgs, "You meet Gambril, the Frost Dragon.");
ShowText(player, type, doMsgs, "'For longer than I care to remember, I have feuded with my nemesis Osterog, the Ice Dragon.");
ShowText(player, type, doMsgs, "Our continued battles have formed tunnels within the land, and we can no longer maneuver ourselves through them.");
ShowText(player, type, doMsgs, "I beseech you to help me. I will reward you generously if you bring me proof of your kill.");
ShowText(player, type, doMsgs, "To be successful, you may need greater magic than you now possess.'");
}
}
}
protected override void FnEvent2A(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE) == 5) {
ShowText(player, type, doMsgs, "With the help of the proper magic, you find the dragon Gambril.");
if (HasItem(player, type, doMsgs, DRAGONSSKIN)) {
SetTreasure(player, type, doMsgs, ELIXIROFHEALTH, 0, 0, 0, 0, 2000);
}
else {
SetTreasure(player, type, doMsgs, DRAGONSSKIN, HEALALLPOTION, 0, 0, 0, 5000);
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 39);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 11);
AddEncounter(player, type, doMsgs, 02, 38);
AddEncounter(player, type, doMsgs, 06, 39);
}
else {
AddEncounter(player, type, doMsgs, 01, 11);
AddEncounter(player, type, doMsgs, 02, 11);
AddEncounter(player, type, doMsgs, 03, 12);
AddEncounter(player, type, doMsgs, 06, 39);
}
}
else {
ShowText(player, type, doMsgs, "The magic protection you try to weave around yourself is not enough to protect you from Gambril's keen vision.");
ShowText(player, type, doMsgs, "Scoffing that Osterog has selected a particularly pitiful party to kill him, the dragon toasts you with his flame-breath.");
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
}
}
protected override void FnEvent2B(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SCALE) == 1) {
ShowText(player, type, doMsgs, "Osterog lumbers away.");
SetFlag(player, type, doMsgs, FlagTypeParty, DRAGON_A, 1);
}
else {
if (HasItem(player, type, doMsgs, DRAGONSSKIN)) {
ShowPortrait(player, type, doMsgs, WHITEDRAGON);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SCALE, 1);
ModifyExperience(player, type, doMsgs, 500000);
ModifyGold(player, type, doMsgs, 25000);
GiveItem(player, type, doMsgs, STONEGIANTSHAMMER);
GiveItem(player, type, doMsgs, MIDNIGHTAEGIS);
GiveItem(player, type, doMsgs, FLAMETONGUE);
GiveItem(player, type, doMsgs, HEALAMPHORA);
GiveItem(player, type, doMsgs, ZEUSSCROLL);
ShowText(player, type, doMsgs, "Osterog smiles broadly, gloating that his nemesis is finally dead.");
ShowText(player, type, doMsgs, "As he doles out his reward, he says, 'I understand that the wizards of Hocus Pocus are much interested in unusual items. You may wish to show them your trophies.'");
}
else {
ShowPortrait(player, type, doMsgs, WHITEDRAGON);
SetFlag(player, type, doMsgs, FlagTypeParty, DRAGON_A, 1);
ShowText(player, type, doMsgs, "You encounter Osterog, the Ice Dragon.");
ShowText(player, type, doMsgs, "'Long have I feuded with Gambril, the Frost Dragon.");
ShowText(player, type, doMsgs, "Our endless battles have weakened the tunnels hereabout, and we no longer dare tread them.");
ShowText(player, type, doMsgs, "If you can help me destroy my sworn enemy, I will reward you most generously. Bring me proof of your kill.");
ShowText(player, type, doMsgs, "Your success may depend on greater magic than you now know.'");
}
}
}
protected override void FnEvent2C(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE) == 5) {
ShowText(player, type, doMsgs, "The proper magic has led you to the dragon Osterog.");
if (HasItem(player, type, doMsgs, DRAGONSSKIN)) {
SetTreasure(player, type, doMsgs, ELIXIROFHEALTH, 0, 0, 0, 0, 2000);
}
else {
SetTreasure(player, type, doMsgs, DRAGONSSKIN, HEALALLPOTION, 0, 0, 0, 5000);
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 40);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 11);
AddEncounter(player, type, doMsgs, 02, 38);
AddEncounter(player, type, doMsgs, 06, 40);
}
else {
AddEncounter(player, type, doMsgs, 01, 11);
AddEncounter(player, type, doMsgs, 02, 11);
AddEncounter(player, type, doMsgs, 04, 29);
AddEncounter(player, type, doMsgs, 06, 40);
}
}
else {
ShowText(player, type, doMsgs, "As you tiptoe towards the great beast, Osterog sniffs once and smiles a saurian smile.");
ShowText(player, type, doMsgs, "'Gambril has sent fools to kill me.'");
ShowText(player, type, doMsgs, "He turns toward you and roasts you with his flame-breath.");
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
}
}
protected override void FnEvent2D(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You encounter other adventurers who seek the dragon's reward.");
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 20);
AddEncounter(player, type, doMsgs, 02, 36);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 20);
AddEncounter(player, type, doMsgs, 02, 28);
AddEncounter(player, type, doMsgs, 05, 36);
AddEncounter(player, type, doMsgs, 06, 33);
}
else {
AddEncounter(player, type, doMsgs, 01, 20);
AddEncounter(player, type, doMsgs, 02, 20);
AddEncounter(player, type, doMsgs, 03, 24);
AddEncounter(player, type, doMsgs, 04, 24);
AddEncounter(player, type, doMsgs, 05, 36);
AddEncounter(player, type, doMsgs, 06, 37);
}
}
protected override void FnEvent2E(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 17);
AddEncounter(player, type, doMsgs, 02, 28);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 28);
AddEncounter(player, type, doMsgs, 02, 15);
AddEncounter(player, type, doMsgs, 05, 12);
}
else {
AddEncounter(player, type, doMsgs, 01, 14);
AddEncounter(player, type, doMsgs, 02, 14);
AddEncounter(player, type, doMsgs, 03, 29);
AddEncounter(player, type, doMsgs, 05, 32);
AddEncounter(player, type, doMsgs, 06, 32);
}
}
protected override void FnEvent2F(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 2);
AddEncounter(player, type, doMsgs, 02, 31);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 31);
AddEncounter(player, type, doMsgs, 02, 1);
AddEncounter(player, type, doMsgs, 05, 25);
AddEncounter(player, type, doMsgs, 06, 26);
}
else {
AddEncounter(player, type, doMsgs, 01, 5);
AddEncounter(player, type, doMsgs, 02, 5);
AddEncounter(player, type, doMsgs, 03, 27);
AddEncounter(player, type, doMsgs, 04, 30);
AddEncounter(player, type, doMsgs, 05, 29);
}
}
protected override void FnEvent30(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAGSTR) == 1) {
ShowText(player, type, doMsgs, "You push open the broken door with ease.");
}
else {
ShowText(player, type, doMsgs, "As you push against the stubborn door, debris falls and injures you.");
if (GetAttribute(player, type, doMsgs, STRENGTH) >= 23) {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAGSTR, 1);
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 3);
}
else {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAGSTR, 1);
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 4);
}
}
}
protected override void FnEvent31(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAGDEF) == 1) {
ShowText(player, type, doMsgs, "The walls around you have been fortified.");
}
else {
ShowText(player, type, doMsgs, "The walls collapse upon you! Amnesia causes you to forget your more recent experiences.");
if (GetAttribute(player, type, doMsgs, DEFENSE) >= 18) {
ModifyExperience(player, type, doMsgs, - 10000);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAGDEF, 1);
}
else {
ModifyExperience(player, type, doMsgs, - 20000);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAGDEF, 1);
}
}
}
protected override void FnEvent32(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAGINI) == 1) {
ShowText(player, type, doMsgs, "You elude a thief hiding in the shadows.");
}
else {
ShowText(player, type, doMsgs, "A thief runs by you and picks your pocket.");
if (GetAttribute(player, type, doMsgs, INITIATIVE) >= 13) {
ModifyGold(player, type, doMsgs, - 25000);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAGINI, 1);
}
else {
ModifyGold(player, type, doMsgs, - 50000);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAGINI, 1);
}
}
}
protected override void FnEvent33(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAGAGI) == 1) {
ShowText(player, type, doMsgs, "You resist the magical forces emanating from the chamber.");
}
else {
ShowText(player, type, doMsgs, "You feel magical forces drain your mana.");
if (GetAttribute(player, type, doMsgs, AGILITY) >= 11) {
ModifyMana(player, type, doMsgs, - 200);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAGAGI, 1);
}
else {
ModifyMana(player, type, doMsgs, - 400);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DRAGAGI, 1);
}
}
}
protected override void FnEvent34(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, WRAITH);
ShowText(player, type, doMsgs, "The ghost of an adventurer appears before you.");
ShowText(player, type, doMsgs, "'Seek out the wizards in Dragon's Flame for help. Each, for a fee, will aid you with his or her unusual magic.");
ShowText(player, type, doMsgs, "BUT, all spells are not successful for all.");
ShowText(player, type, doMsgs, "I wish you better luck than I had. And remember, it is imperative that you stay in the area until you successfully complete your quest.'");
}
protected override void FnEvent35(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 8, 2, 69, Direction.East);
}
protected override void FnEvent36(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 8, 2, 185, Direction.North);
}
protected override void FnEvent37(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetFlag(player, type, doMsgs, FlagTypeParty, WIZCHOICE, 0);
SetFlag(player, type, doMsgs, FlagTypeParty, ONE_NORTH, 0);
SetFlag(player, type, doMsgs, FlagTypeParty, ONE_CENTER, 0);
SetFlag(player, type, doMsgs, FlagTypeParty, ONE_SOUTH, 0);
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2014 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 11.0Release
// Tag = $Name: AKW11_000 $
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace Dynastream.Fit
{
/// <summary>
/// Implements the UserProfile profile message.
/// </summary>
public class UserProfileMesg : Mesg
{
#region Fields
#endregion
#region Constructors
public UserProfileMesg() : base(Profile.mesgs[Profile.UserProfileIndex])
{
}
public UserProfileMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the MessageIndex field</summary>
/// <returns>Returns nullable ushort representing the MessageIndex field</returns>
public ushort? GetMessageIndex()
{
return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set MessageIndex field</summary>
/// <param name="messageIndex_">Nullable field value to be set</param>
public void SetMessageIndex(ushort? messageIndex_)
{
SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the FriendlyName field</summary>
/// <returns>Returns byte[] representing the FriendlyName field</returns>
public byte[] GetFriendlyName()
{
return (byte[])GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set FriendlyName field</summary>
/// <param name="friendlyName_">field value to be set</param>
public void SetFriendlyName(byte[] friendlyName_)
{
SetFieldValue(0, 0, friendlyName_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Gender field</summary>
/// <returns>Returns nullable Gender enum representing the Gender field</returns>
public Gender? GetGender()
{
object obj = GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
Gender? value = obj == null ? (Gender?)null : (Gender)obj;
return value;
}
/// <summary>
/// Set Gender field</summary>
/// <param name="gender_">Nullable field value to be set</param>
public void SetGender(Gender? gender_)
{
SetFieldValue(1, 0, gender_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Age field
/// Units: years</summary>
/// <returns>Returns nullable byte representing the Age field</returns>
public byte? GetAge()
{
return (byte?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Age field
/// Units: years</summary>
/// <param name="age_">Nullable field value to be set</param>
public void SetAge(byte? age_)
{
SetFieldValue(2, 0, age_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Height field
/// Units: m</summary>
/// <returns>Returns nullable float representing the Height field</returns>
public float? GetHeight()
{
return (float?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Height field
/// Units: m</summary>
/// <param name="height_">Nullable field value to be set</param>
public void SetHeight(float? height_)
{
SetFieldValue(3, 0, height_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Weight field
/// Units: kg</summary>
/// <returns>Returns nullable float representing the Weight field</returns>
public float? GetWeight()
{
return (float?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Weight field
/// Units: kg</summary>
/// <param name="weight_">Nullable field value to be set</param>
public void SetWeight(float? weight_)
{
SetFieldValue(4, 0, weight_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Language field</summary>
/// <returns>Returns nullable Language enum representing the Language field</returns>
public Language? GetLanguage()
{
object obj = GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
Language? value = obj == null ? (Language?)null : (Language)obj;
return value;
}
/// <summary>
/// Set Language field</summary>
/// <param name="language_">Nullable field value to be set</param>
public void SetLanguage(Language? language_)
{
SetFieldValue(5, 0, language_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ElevSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the ElevSetting field</returns>
public DisplayMeasure? GetElevSetting()
{
object obj = GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set ElevSetting field</summary>
/// <param name="elevSetting_">Nullable field value to be set</param>
public void SetElevSetting(DisplayMeasure? elevSetting_)
{
SetFieldValue(6, 0, elevSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the WeightSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the WeightSetting field</returns>
public DisplayMeasure? GetWeightSetting()
{
object obj = GetFieldValue(7, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set WeightSetting field</summary>
/// <param name="weightSetting_">Nullable field value to be set</param>
public void SetWeightSetting(DisplayMeasure? weightSetting_)
{
SetFieldValue(7, 0, weightSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the RestingHeartRate field
/// Units: bpm</summary>
/// <returns>Returns nullable byte representing the RestingHeartRate field</returns>
public byte? GetRestingHeartRate()
{
return (byte?)GetFieldValue(8, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set RestingHeartRate field
/// Units: bpm</summary>
/// <param name="restingHeartRate_">Nullable field value to be set</param>
public void SetRestingHeartRate(byte? restingHeartRate_)
{
SetFieldValue(8, 0, restingHeartRate_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DefaultMaxRunningHeartRate field
/// Units: bpm</summary>
/// <returns>Returns nullable byte representing the DefaultMaxRunningHeartRate field</returns>
public byte? GetDefaultMaxRunningHeartRate()
{
return (byte?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set DefaultMaxRunningHeartRate field
/// Units: bpm</summary>
/// <param name="defaultMaxRunningHeartRate_">Nullable field value to be set</param>
public void SetDefaultMaxRunningHeartRate(byte? defaultMaxRunningHeartRate_)
{
SetFieldValue(9, 0, defaultMaxRunningHeartRate_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DefaultMaxBikingHeartRate field
/// Units: bpm</summary>
/// <returns>Returns nullable byte representing the DefaultMaxBikingHeartRate field</returns>
public byte? GetDefaultMaxBikingHeartRate()
{
return (byte?)GetFieldValue(10, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set DefaultMaxBikingHeartRate field
/// Units: bpm</summary>
/// <param name="defaultMaxBikingHeartRate_">Nullable field value to be set</param>
public void SetDefaultMaxBikingHeartRate(byte? defaultMaxBikingHeartRate_)
{
SetFieldValue(10, 0, defaultMaxBikingHeartRate_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DefaultMaxHeartRate field
/// Units: bpm</summary>
/// <returns>Returns nullable byte representing the DefaultMaxHeartRate field</returns>
public byte? GetDefaultMaxHeartRate()
{
return (byte?)GetFieldValue(11, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set DefaultMaxHeartRate field
/// Units: bpm</summary>
/// <param name="defaultMaxHeartRate_">Nullable field value to be set</param>
public void SetDefaultMaxHeartRate(byte? defaultMaxHeartRate_)
{
SetFieldValue(11, 0, defaultMaxHeartRate_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the HrSetting field</summary>
/// <returns>Returns nullable DisplayHeart enum representing the HrSetting field</returns>
public DisplayHeart? GetHrSetting()
{
object obj = GetFieldValue(12, 0, Fit.SubfieldIndexMainField);
DisplayHeart? value = obj == null ? (DisplayHeart?)null : (DisplayHeart)obj;
return value;
}
/// <summary>
/// Set HrSetting field</summary>
/// <param name="hrSetting_">Nullable field value to be set</param>
public void SetHrSetting(DisplayHeart? hrSetting_)
{
SetFieldValue(12, 0, hrSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SpeedSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the SpeedSetting field</returns>
public DisplayMeasure? GetSpeedSetting()
{
object obj = GetFieldValue(13, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set SpeedSetting field</summary>
/// <param name="speedSetting_">Nullable field value to be set</param>
public void SetSpeedSetting(DisplayMeasure? speedSetting_)
{
SetFieldValue(13, 0, speedSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DistSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the DistSetting field</returns>
public DisplayMeasure? GetDistSetting()
{
object obj = GetFieldValue(14, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set DistSetting field</summary>
/// <param name="distSetting_">Nullable field value to be set</param>
public void SetDistSetting(DisplayMeasure? distSetting_)
{
SetFieldValue(14, 0, distSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the PowerSetting field</summary>
/// <returns>Returns nullable DisplayPower enum representing the PowerSetting field</returns>
public DisplayPower? GetPowerSetting()
{
object obj = GetFieldValue(16, 0, Fit.SubfieldIndexMainField);
DisplayPower? value = obj == null ? (DisplayPower?)null : (DisplayPower)obj;
return value;
}
/// <summary>
/// Set PowerSetting field</summary>
/// <param name="powerSetting_">Nullable field value to be set</param>
public void SetPowerSetting(DisplayPower? powerSetting_)
{
SetFieldValue(16, 0, powerSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActivityClass field</summary>
/// <returns>Returns nullable ActivityClass enum representing the ActivityClass field</returns>
public ActivityClass? GetActivityClass()
{
object obj = GetFieldValue(17, 0, Fit.SubfieldIndexMainField);
ActivityClass? value = obj == null ? (ActivityClass?)null : (ActivityClass)obj;
return value;
}
/// <summary>
/// Set ActivityClass field</summary>
/// <param name="activityClass_">Nullable field value to be set</param>
public void SetActivityClass(ActivityClass? activityClass_)
{
SetFieldValue(17, 0, activityClass_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the PositionSetting field</summary>
/// <returns>Returns nullable DisplayPosition enum representing the PositionSetting field</returns>
public DisplayPosition? GetPositionSetting()
{
object obj = GetFieldValue(18, 0, Fit.SubfieldIndexMainField);
DisplayPosition? value = obj == null ? (DisplayPosition?)null : (DisplayPosition)obj;
return value;
}
/// <summary>
/// Set PositionSetting field</summary>
/// <param name="positionSetting_">Nullable field value to be set</param>
public void SetPositionSetting(DisplayPosition? positionSetting_)
{
SetFieldValue(18, 0, positionSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TemperatureSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the TemperatureSetting field</returns>
public DisplayMeasure? GetTemperatureSetting()
{
object obj = GetFieldValue(21, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set TemperatureSetting field</summary>
/// <param name="temperatureSetting_">Nullable field value to be set</param>
public void SetTemperatureSetting(DisplayMeasure? temperatureSetting_)
{
SetFieldValue(21, 0, temperatureSetting_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the LocalId field</summary>
/// <returns>Returns nullable ushort representing the LocalId field</returns>
public ushort? GetLocalId()
{
return (ushort?)GetFieldValue(22, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set LocalId field</summary>
/// <param name="localId_">Nullable field value to be set</param>
public void SetLocalId(ushort? localId_)
{
SetFieldValue(22, 0, localId_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field GlobalId</returns>
public int GetNumGlobalId()
{
return GetNumFieldValues(23, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the GlobalId field</summary>
/// <param name="index">0 based index of GlobalId element to retrieve</param>
/// <returns>Returns nullable byte representing the GlobalId field</returns>
public byte? GetGlobalId(int index)
{
return (byte?)GetFieldValue(23, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set GlobalId field</summary>
/// <param name="index">0 based index of global_id</param>
/// <param name="globalId_">Nullable field value to be set</param>
public void SetGlobalId(int index, byte? globalId_)
{
SetFieldValue(23, index, globalId_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the HeightSetting field</summary>
/// <returns>Returns nullable DisplayMeasure enum representing the HeightSetting field</returns>
public DisplayMeasure? GetHeightSetting()
{
object obj = GetFieldValue(30, 0, Fit.SubfieldIndexMainField);
DisplayMeasure? value = obj == null ? (DisplayMeasure?)null : (DisplayMeasure)obj;
return value;
}
/// <summary>
/// Set HeightSetting field</summary>
/// <param name="heightSetting_">Nullable field value to be set</param>
public void SetHeightSetting(DisplayMeasure? heightSetting_)
{
SetFieldValue(30, 0, heightSetting_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.CustomerInsights.Models
{
using Azure;
using Management;
using CustomerInsights;
using Rest;
using Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The KPI resource format.
/// </summary>
[JsonTransformation]
public partial class KpiResourceFormat : ProxyResource
{
/// <summary>
/// Initializes a new instance of the KpiResourceFormat class.
/// </summary>
public KpiResourceFormat() { }
/// <summary>
/// Initializes a new instance of the KpiResourceFormat class.
/// </summary>
/// <param name="entityType">The mapping entity type. Possible values
/// include: 'None', 'Profile', 'Interaction', 'Relationship'</param>
/// <param name="entityTypeName">The mapping entity name.</param>
/// <param name="calculationWindow">The calculation window. Possible
/// values include: 'Hour', 'Day', 'Week', 'Month'</param>
/// <param name="function">The computation function for the KPI.
/// Possible values include: 'Sum', 'Avg', 'Min', 'Max', 'Last',
/// 'Count', 'None'</param>
/// <param name="expression">The computation expression for the
/// KPI.</param>
/// <param name="id">Resource ID.</param>
/// <param name="name">Resource name.</param>
/// <param name="type">Resource type.</param>
/// <param name="tenantId">The hub name.</param>
/// <param name="kpiName">The KPI name.</param>
/// <param name="displayName">Localized display name for the
/// KPI.</param>
/// <param name="description">Localized description for the
/// KPI.</param>
/// <param name="unit">The unit of measurement for the KPI.</param>
/// <param name="filter">The filter expression for the KPI.</param>
/// <param name="groupBy">the group by properties for the KPI.</param>
/// <param name="groupByMetadata">The KPI GroupByMetadata.</param>
/// <param name="participantProfilesMetadata">The participant
/// profiles.</param>
/// <param name="provisioningState">The provisioning state.</param>
/// <param name="thresHolds">The KPI thresholds.</param>
/// <param name="aliases">The aliases.</param>
/// <param name="extracts">The KPI extracts.</param>
public KpiResourceFormat(EntityTypes entityType, string entityTypeName, CalculationWindowTypes calculationWindow, KpiFunctions function, string expression, string id = default(string), string name = default(string), string type = default(string), string tenantId = default(string), string kpiName = default(string), IDictionary<string, string> displayName = default(IDictionary<string, string>), IDictionary<string, string> description = default(IDictionary<string, string>), string unit = default(string), string filter = default(string), IList<string> groupBy = default(IList<string>), IList<KpiGroupByMetadata> groupByMetadata = default(IList<KpiGroupByMetadata>), IList<KpiParticipantProfilesMetadata> participantProfilesMetadata = default(IList<KpiParticipantProfilesMetadata>), string provisioningState = default(string), KpiThresholds thresHolds = default(KpiThresholds), IList<KpiAlias> aliases = default(IList<KpiAlias>), IList<KpiExtract> extracts = default(IList<KpiExtract>))
: base(id, name, type)
{
EntityType = entityType;
EntityTypeName = entityTypeName;
TenantId = tenantId;
KpiName = kpiName;
DisplayName = displayName;
Description = description;
CalculationWindow = calculationWindow;
Function = function;
Expression = expression;
Unit = unit;
Filter = filter;
GroupBy = groupBy;
GroupByMetadata = groupByMetadata;
ParticipantProfilesMetadata = participantProfilesMetadata;
ProvisioningState = provisioningState;
ThresHolds = thresHolds;
Aliases = aliases;
Extracts = extracts;
}
/// <summary>
/// Gets or sets the mapping entity type. Possible values include:
/// 'None', 'Profile', 'Interaction', 'Relationship'
/// </summary>
[JsonProperty(PropertyName = "properties.entityType")]
public EntityTypes EntityType { get; set; }
/// <summary>
/// Gets or sets the mapping entity name.
/// </summary>
[JsonProperty(PropertyName = "properties.entityTypeName")]
public string EntityTypeName { get; set; }
/// <summary>
/// Gets the hub name.
/// </summary>
[JsonProperty(PropertyName = "properties.tenantId")]
public string TenantId { get; protected set; }
/// <summary>
/// Gets the KPI name.
/// </summary>
[JsonProperty(PropertyName = "properties.kpiName")]
public string KpiName { get; protected set; }
/// <summary>
/// Gets or sets localized display name for the KPI.
/// </summary>
[JsonProperty(PropertyName = "properties.displayName")]
public IDictionary<string, string> DisplayName { get; set; }
/// <summary>
/// Gets or sets localized description for the KPI.
/// </summary>
[JsonProperty(PropertyName = "properties.description")]
public IDictionary<string, string> Description { get; set; }
/// <summary>
/// Gets or sets the calculation window. Possible values include:
/// 'Hour', 'Day', 'Week', 'Month'
/// </summary>
[JsonProperty(PropertyName = "properties.calculationWindow")]
public CalculationWindowTypes CalculationWindow { get; set; }
/// <summary>
/// Gets or sets the computation function for the KPI. Possible values
/// include: 'Sum', 'Avg', 'Min', 'Max', 'Last', 'Count', 'None'
/// </summary>
[JsonProperty(PropertyName = "properties.function")]
public KpiFunctions Function { get; set; }
/// <summary>
/// Gets or sets the computation expression for the KPI.
/// </summary>
[JsonProperty(PropertyName = "properties.expression")]
public string Expression { get; set; }
/// <summary>
/// Gets or sets the unit of measurement for the KPI.
/// </summary>
[JsonProperty(PropertyName = "properties.unit")]
public string Unit { get; set; }
/// <summary>
/// Gets or sets the filter expression for the KPI.
/// </summary>
[JsonProperty(PropertyName = "properties.filter")]
public string Filter { get; set; }
/// <summary>
/// Gets or sets the group by properties for the KPI.
/// </summary>
[JsonProperty(PropertyName = "properties.groupBy")]
public IList<string> GroupBy { get; set; }
/// <summary>
/// Gets the KPI GroupByMetadata.
/// </summary>
[JsonProperty(PropertyName = "properties.groupByMetadata")]
public IList<KpiGroupByMetadata> GroupByMetadata { get; protected set; }
/// <summary>
/// Gets the participant profiles.
/// </summary>
[JsonProperty(PropertyName = "properties.participantProfilesMetadata")]
public IList<KpiParticipantProfilesMetadata> ParticipantProfilesMetadata { get; protected set; }
/// <summary>
/// Gets the provisioning state.
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public string ProvisioningState { get; protected set; }
/// <summary>
/// Gets or sets the KPI thresholds.
/// </summary>
[JsonProperty(PropertyName = "properties.thresHolds")]
public KpiThresholds ThresHolds { get; set; }
/// <summary>
/// Gets or sets the aliases.
/// </summary>
[JsonProperty(PropertyName = "properties.aliases")]
public IList<KpiAlias> Aliases { get; set; }
/// <summary>
/// Gets or sets the KPI extracts.
/// </summary>
[JsonProperty(PropertyName = "properties.extracts")]
public IList<KpiExtract> Extracts { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (EntityTypeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "EntityTypeName");
}
if (Expression == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Expression");
}
if (ParticipantProfilesMetadata != null)
{
foreach (var element in ParticipantProfilesMetadata)
{
if (element != null)
{
element.Validate();
}
}
}
if (ThresHolds != null)
{
ThresHolds.Validate();
}
if (Aliases != null)
{
foreach (var element1 in Aliases)
{
if (element1 != null)
{
element1.Validate();
}
}
}
if (Extracts != null)
{
foreach (var element2 in Extracts)
{
if (element2 != null)
{
element2.Validate();
}
}
}
}
}
}
| |
#region License
/* Copyright (c) 2006 Leslie Sanford
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contact
/*
* Leslie Sanford
* Email: jabberdabber@hotmail.com
*/
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;
using Sanford.Multimedia.Timers;
namespace Sanford.Multimedia.Midi
{
public sealed class OutputStream : OutputDeviceBase
{
[DllImport("winmm.dll")]
private static extern int midiStreamOpen(ref IntPtr handle, ref int deviceID, int reserved,
OutputDevice.MidiOutProc proc, int instance, uint flag);
[DllImport("winmm.dll")]
private static extern int midiStreamClose(IntPtr handle);
[DllImport("winmm.dll")]
private static extern int midiStreamOut(IntPtr handle, IntPtr headerPtr, int sizeOfMidiHeader);
[DllImport("winmm.dll")]
private static extern int midiStreamPause(IntPtr handle);
[DllImport("winmm.dll")]
private static extern int midiStreamPosition(IntPtr handle, ref Time t, int sizeOfTime);
[DllImport("winmm.dll")]
private static extern int midiStreamProperty(IntPtr handle, ref Property p, uint flags);
[DllImport("winmm.dll")]
private static extern int midiStreamRestart(IntPtr handle);
[DllImport("winmm.dll")]
private static extern int midiStreamStop(IntPtr handle);
[StructLayout(LayoutKind.Sequential)]
private struct Property
{
public int sizeOfProperty;
public int property;
}
private const uint MIDIPROP_SET = 0x80000000;
private const uint MIDIPROP_GET = 0x40000000;
private const uint MIDIPROP_TIMEDIV = 0x00000001;
private const uint MIDIPROP_TEMPO = 0x00000002;
private const byte MEVT_CALLBACK = 0x40;
private const byte MEVT_SHORTMSG = 0x00;
private const byte MEVT_TEMPO = 0x01;
private const byte MEVT_NOP = 0x02;
private const byte MEVT_LONGMSG = 0x80;
private const byte MEVT_COMMENT = 0x82;
private const byte MEVT_VERSION = 0x84;
private const int MOM_POSITIONCB = 0x3CA;
private const int SizeOfMidiEvent = 12;
private const int EventTypeIndex = 11;
private const int EventCodeOffset = 8;
private MidiOutProc midiOutProc;
private int offsetTicks = 0;
private byte[] streamID = new byte[4];
private List<byte> events = new List<byte>();
private MidiHeaderBuilder headerBuilder = new MidiHeaderBuilder();
public event EventHandler<NoOpEventArgs> NoOpOccurred;
public OutputStream(int deviceID) : base(deviceID)
{
midiOutProc = HandleMessage;
int result = midiStreamOpen(ref handle, ref deviceID, 1, midiOutProc, 0, CALLBACK_FUNCTION);
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
throw new OutputDeviceException(result);
}
}
protected override void Dispose(bool disposing)
{
if(disposing)
{
lock(lockObject)
{
Reset();
int result = midiStreamClose(Handle);
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
throw new OutputDeviceException(result);
}
}
}
else
{
midiOutReset(Handle);
midiStreamClose(Handle);
}
base.Dispose(disposing);
}
public override void Close()
{
#region Guard
if(IsDisposed)
{
return;
}
#endregion
Dispose(true);
}
public void StartPlaying()
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException("OutputStream");
}
#endregion
lock(lockObject)
{
int result = midiStreamRestart(Handle);
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
throw new OutputDeviceException(result);
}
}
}
public void PausePlaying()
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException("OutputStream");
}
#endregion
lock(lockObject)
{
int result = midiStreamPause(Handle);
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
throw new OutputDeviceException(result);
}
}
}
public void StopPlaying()
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException("OutputStream");
}
#endregion
lock(lockObject)
{
int result = midiStreamStop(Handle);
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
throw new OutputDeviceException(result);
}
}
}
public override void Reset()
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException("OutputStream");
}
#endregion
offsetTicks = 0;
events.Clear();
base.Reset();
}
public void Write(MidiEvent e)
{
switch(e.MidiMessage.MessageType)
{
case MessageType.Channel:
case MessageType.SystemCommon:
case MessageType.SystemRealtime:
Write(e.DeltaTicks, (ShortMessage)e.MidiMessage);
break;
case MessageType.SystemExclusive:
Write(e.DeltaTicks, (SysExMessage)e.MidiMessage);
break;
case MessageType.Meta:
Write(e.DeltaTicks, (MetaMessage)e.MidiMessage);
break;
}
}
private void Write(int deltaTicks, ShortMessage message)
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException("OutputStream");
}
#endregion
// Delta time.
events.AddRange(BitConverter.GetBytes(deltaTicks + offsetTicks));
// Stream ID.
events.AddRange(streamID);
// Event code.
byte[] eventCode = message.GetBytes();
eventCode[eventCode.Length - 1] = MEVT_SHORTMSG;
events.AddRange(eventCode);
offsetTicks = 0;
}
private void Write(int deltaTicks, SysExMessage message)
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException("OutputStream");
}
#endregion
// Delta time.
events.AddRange(BitConverter.GetBytes(deltaTicks + offsetTicks));
// Stream ID.
events.AddRange(streamID);
// Event code.
byte[] eventCode = BitConverter.GetBytes(message.Length);
eventCode[eventCode.Length - 1] = MEVT_LONGMSG;
events.AddRange(eventCode);
byte[] sysExData;
if(message.Length % 4 != 0)
{
sysExData = new byte[message.Length + (message.Length % 4)];
message.GetBytes().CopyTo(sysExData, 0);
}
else
{
sysExData = message.GetBytes();
}
// SysEx data.
events.AddRange(sysExData);
offsetTicks = 0;
}
private void Write(int deltaTicks, MetaMessage message)
{
if(message.MetaType == MetaType.Tempo)
{
// Delta time.
events.AddRange(BitConverter.GetBytes(deltaTicks + offsetTicks));
// Stream ID.
events.AddRange(streamID);
TempoChangeBuilder builder = new TempoChangeBuilder(message);
byte[] t = BitConverter.GetBytes(builder.Tempo);
t[t.Length - 1] = MEVT_SHORTMSG | MEVT_TEMPO;
// Event code.
events.AddRange(t);
offsetTicks = 0;
}
else
{
offsetTicks += deltaTicks;
}
}
public void WriteNoOp(int deltaTicks, int data)
{
// Delta time.
events.AddRange(BitConverter.GetBytes(deltaTicks + offsetTicks));
// Stream ID.
events.AddRange(streamID);
// Event code.
byte[] eventCode = BitConverter.GetBytes(data);
eventCode[eventCode.Length - 1] = (byte)(MEVT_NOP | MEVT_CALLBACK);
events.AddRange(eventCode);
offsetTicks = 0;
}
public void Flush()
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException("OutputStream");
}
#endregion
lock(lockObject)
{
headerBuilder.InitializeBuffer(events);
headerBuilder.Build();
events.Clear();
int result = midiOutPrepareHeader(Handle, headerBuilder.Result, SizeOfMidiHeader);
if(result == MidiDeviceException.MMSYSERR_NOERROR)
{
bufferCount++;
}
else
{
headerBuilder.Destroy();
throw new OutputDeviceException(result);
}
result = midiStreamOut(Handle, headerBuilder.Result, SizeOfMidiHeader);
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
midiOutUnprepareHeader(Handle, headerBuilder.Result, SizeOfMidiHeader);
headerBuilder.Destroy();
throw new OutputDeviceException(result);
}
}
}
public Time GetTime(TimeType type)
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException("OutputStream");
}
#endregion
Time t = new Time();
t.type = (int)type;
lock(lockObject)
{
int result = midiStreamPosition(Handle, ref t, Marshal.SizeOf(typeof(Time)));
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
throw new OutputDeviceException(result);
}
}
return t;
}
private void OnNoOpOccurred(NoOpEventArgs e)
{
EventHandler<NoOpEventArgs> handler = NoOpOccurred;
if(handler != null)
{
handler(this, e);
}
}
protected override void HandleMessage(int handle, int msg, int instance, int param1, int param2)
{
if(msg == MOM_POSITIONCB)
{
delegateQueue.Post(HandleNoOp, new IntPtr(param1));
}
else
{
base.HandleMessage(handle, msg, instance, param1, param2);
}
}
private void HandleNoOp(object state)
{
IntPtr headerPtr = (IntPtr)state;
MidiHeader header = (MidiHeader)Marshal.PtrToStructure(headerPtr, typeof(MidiHeader));
byte[] midiEvent = new byte[SizeOfMidiEvent];
for(int i = 0; i < midiEvent.Length; i++)
{
midiEvent[i] = Marshal.ReadByte(header.data, header.offset + i);
}
// If this is a NoOp event.
if((midiEvent[EventTypeIndex] & MEVT_NOP) == MEVT_NOP)
{
// Clear the event type byte.
midiEvent[EventTypeIndex] = 0;
NoOpEventArgs e = new NoOpEventArgs(BitConverter.ToInt32(midiEvent, EventCodeOffset));
context.Post(new SendOrPostCallback(delegate(object s)
{
OnNoOpOccurred(e);
}), null);
}
}
public int Division
{
get
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException("OutputStream");
}
#endregion
Property d = new Property();
d.sizeOfProperty = Marshal.SizeOf(typeof(Property));
lock(lockObject)
{
int result = midiStreamProperty(Handle, ref d, MIDIPROP_GET | MIDIPROP_TIMEDIV);
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
throw new OutputDeviceException(result);
}
}
return d.property;
}
set
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException("OutputStream");
}
else if((value % PpqnClock.PpqnMinValue) != 0)
{
throw new ArgumentException();
}
#endregion
Property d = new Property();
d.sizeOfProperty = Marshal.SizeOf(typeof(Property));
d.property = value;
lock(lockObject)
{
int result = midiStreamProperty(Handle, ref d, MIDIPROP_SET | MIDIPROP_TIMEDIV);
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
throw new OutputDeviceException(result);
}
}
}
}
public int Tempo
{
get
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException("OutputStream");
}
#endregion
Property t = new Property();
t.sizeOfProperty = Marshal.SizeOf(typeof(Property));
lock(lockObject)
{
int result = midiStreamProperty(Handle, ref t, MIDIPROP_GET | MIDIPROP_TEMPO);
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
throw new OutputDeviceException(result);
}
}
return t.property;
}
set
{
#region Require
if(IsDisposed)
{
throw new ObjectDisposedException("OutputStream");
}
else if(value < 0)
{
throw new ArgumentOutOfRangeException("Tempo", value,
"Tempo out of range.");
}
#endregion
Property t = new Property();
t.sizeOfProperty = Marshal.SizeOf(typeof(Property));
t.property = value;
lock(lockObject)
{
int result = midiStreamProperty(Handle, ref t, MIDIPROP_SET | MIDIPROP_TEMPO);
if(result != MidiDeviceException.MMSYSERR_NOERROR)
{
throw new OutputDeviceException(result);
}
}
}
}
}
}
| |
namespace GitVersion
{
using Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
public class AssemblyInfoFileUpdater : IDisposable
{
readonly List<Action> restoreBackupTasks = new List<Action>();
readonly List<Action> cleanupBackupTasks = new List<Action>();
ISet<string> assemblyInfoFileNames;
string workingDirectory;
VersionVariables variables;
IFileSystem fileSystem;
bool ensureAssemblyInfo;
TemplateManager templateManager;
public AssemblyInfoFileUpdater(string assemblyInfoFileName, string workingDirectory, VersionVariables variables, IFileSystem fileSystem, bool ensureAssemblyInfo) :
this(new HashSet<string> { assemblyInfoFileName }, workingDirectory, variables, fileSystem, ensureAssemblyInfo)
{ }
public AssemblyInfoFileUpdater(ISet<string> assemblyInfoFileNames, string workingDirectory, VersionVariables variables, IFileSystem fileSystem, bool ensureAssemblyInfo)
{
this.assemblyInfoFileNames = assemblyInfoFileNames;
this.workingDirectory = workingDirectory;
this.variables = variables;
this.fileSystem = fileSystem;
this.ensureAssemblyInfo = ensureAssemblyInfo;
templateManager = new TemplateManager(TemplateType.VersionAssemblyInfoResources);
}
public void Update()
{
Logger.WriteInfo("Updating assembly info files");
var assemblyInfoFiles = GetAssemblyInfoFiles(workingDirectory, assemblyInfoFileNames, fileSystem, ensureAssemblyInfo).ToList();
Logger.WriteInfo($"Found {assemblyInfoFiles.Count} files");
var assemblyVersion = variables.AssemblySemVer;
var assemblyVersionRegex = new Regex(@"AssemblyVersion(Attribute)?\s*\(.*\)\s*");
var assemblyVersionString = !string.IsNullOrWhiteSpace(assemblyVersion) ? $"AssemblyVersion(\"{assemblyVersion}\")" : null;
var assemblyInfoVersion = variables.InformationalVersion;
var assemblyInfoVersionRegex = new Regex(@"AssemblyInformationalVersion(Attribute)?\s*\(.*\)\s*");
var assemblyInfoVersionString = $"AssemblyInformationalVersion(\"{assemblyInfoVersion}\")";
var assemblyFileVersion = variables.AssemblySemFileVer;
var assemblyFileVersionRegex = new Regex(@"AssemblyFileVersion(Attribute)?\s*\(.*\)\s*");
var assemblyFileVersionString = !string.IsNullOrWhiteSpace(assemblyFileVersion) ? $"AssemblyFileVersion(\"{assemblyFileVersion}\")" : null;
foreach (var assemblyInfoFile in assemblyInfoFiles)
{
var backupAssemblyInfo = assemblyInfoFile.FullName + ".bak";
var localAssemblyInfo = assemblyInfoFile.FullName;
fileSystem.Copy(assemblyInfoFile.FullName, backupAssemblyInfo, true);
restoreBackupTasks.Add(() =>
{
if (fileSystem.Exists(localAssemblyInfo))
{
fileSystem.Delete(localAssemblyInfo);
}
fileSystem.Move(backupAssemblyInfo, localAssemblyInfo);
});
cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo));
var originalFileContents = fileSystem.ReadAllText(assemblyInfoFile.FullName);
var fileContents = originalFileContents;
var appendedAttributes = false;
if (!string.IsNullOrWhiteSpace(assemblyVersion))
{
fileContents = ReplaceOrAppend(assemblyVersionRegex, fileContents, assemblyVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
}
if (!string.IsNullOrWhiteSpace(assemblyFileVersion))
{
fileContents = ReplaceOrAppend(assemblyFileVersionRegex, fileContents, assemblyFileVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
}
fileContents = ReplaceOrAppend(assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
if (appendedAttributes)
{
// If we appended any attributes, put a new line after them
fileContents += Environment.NewLine;
}
if (originalFileContents != fileContents)
{
fileSystem.WriteAllText(assemblyInfoFile.FullName, fileContents);
}
}
}
string ReplaceOrAppend(Regex replaceRegex, string inputString, string replaceString, string fileExtension, ref bool appendedAttributes)
{
var assemblyAddFormat = templateManager.GetAddFormatFor(fileExtension);
if (replaceRegex.IsMatch(inputString))
{
inputString = replaceRegex.Replace(inputString, replaceString);
}
else
{
inputString += Environment.NewLine + string.Format(assemblyAddFormat, replaceString);
appendedAttributes = true;
}
return inputString;
}
IEnumerable<FileInfo> GetAssemblyInfoFiles(string workingDirectory, ISet<string> assemblyInfoFileNames, IFileSystem fileSystem, bool ensureAssemblyInfo)
{
if (assemblyInfoFileNames != null && assemblyInfoFileNames.Any(x => !string.IsNullOrWhiteSpace(x)))
{
foreach (var item in assemblyInfoFileNames)
{
var fullPath = Path.Combine(workingDirectory, item);
if (EnsureVersionAssemblyInfoFile(ensureAssemblyInfo, fileSystem, fullPath))
{
yield return new FileInfo(fullPath);
}
}
}
else
{
foreach (var item in fileSystem.DirectoryGetFiles(workingDirectory, "AssemblyInfo.*", SearchOption.AllDirectories))
{
var assemblyInfoFile = new FileInfo(item);
if (templateManager.IsSupported(assemblyInfoFile.Extension))
{
yield return assemblyInfoFile;
}
}
}
}
bool EnsureVersionAssemblyInfoFile(bool ensureAssemblyInfo, IFileSystem fileSystem, string fullPath)
{
if (fileSystem.Exists(fullPath))
{
return true;
}
if (!ensureAssemblyInfo)
{
return false;
}
var assemblyInfoSource = templateManager.GetTemplateFor(Path.GetExtension(fullPath));
if (!string.IsNullOrWhiteSpace(assemblyInfoSource))
{
var fileInfo = new FileInfo(fullPath);
if (!fileSystem.DirectoryExists(fileInfo.Directory.FullName))
{
fileSystem.CreateDirectory(fileInfo.Directory.FullName);
}
fileSystem.WriteAllText(fullPath, assemblyInfoSource);
return true;
}
Logger.WriteWarning($"No version assembly info template available to create source file '{fullPath}'");
return false;
}
public void Dispose()
{
foreach (var restoreBackup in restoreBackupTasks)
{
restoreBackup();
}
cleanupBackupTasks.Clear();
restoreBackupTasks.Clear();
}
public void CommitChanges()
{
foreach (var cleanupBackupTask in cleanupBackupTasks)
{
cleanupBackupTask();
}
cleanupBackupTasks.Clear();
restoreBackupTasks.Clear();
}
}
}
| |
/*************************************************************************
Copyright (c) 2005-2007, Sergey Bochkanov (ALGLIB project).
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 listed
in this license in the documentation and/or other materials
provided with the distribution.
- Neither the name of the copyright holders 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.
*************************************************************************/
using System;
namespace AlgLib
{
class blas
{
public static double vectornorm2(ref double[] x,
int i1,
int i2)
{
double result = 0;
int n = 0;
int ix = 0;
double absxi = 0;
double scl = 0;
double ssq = 0;
n = i2 - i1 + 1;
if (n < 1)
{
result = 0;
return result;
}
if (n == 1)
{
result = Math.Abs(x[i1]);
return result;
}
scl = 0;
ssq = 1;
for (ix = i1; ix <= i2; ix++)
{
if (x[ix] != 0)
{
absxi = Math.Abs(x[ix]);
if (scl < absxi)
{
ssq = 1 + ssq * AP.APMath.Sqr(scl / absxi);
scl = absxi;
}
else
{
ssq = ssq + AP.APMath.Sqr(absxi / scl);
}
}
}
result = scl * Math.Sqrt(ssq);
return result;
}
public static int vectoridxabsmax(ref double[] x,
int i1,
int i2)
{
int result = 0;
int i = 0;
double a = 0;
result = i1;
a = Math.Abs(x[result]);
for (i = i1 + 1; i <= i2; i++)
{
if (Math.Abs(x[i]) > Math.Abs(x[result]))
{
result = i;
}
}
return result;
}
public static int columnidxabsmax(ref double[,] x,
int i1,
int i2,
int j)
{
int result = 0;
int i = 0;
double a = 0;
result = i1;
a = Math.Abs(x[result, j]);
for (i = i1 + 1; i <= i2; i++)
{
if (Math.Abs(x[i, j]) > Math.Abs(x[result, j]))
{
result = i;
}
}
return result;
}
public static int rowidxabsmax(ref double[,] x,
int j1,
int j2,
int i)
{
int result = 0;
int j = 0;
double a = 0;
result = j1;
a = Math.Abs(x[i, result]);
for (j = j1 + 1; j <= j2; j++)
{
if (Math.Abs(x[i, j]) > Math.Abs(x[i, result]))
{
result = j;
}
}
return result;
}
public static double upperhessenberg1norm(ref double[,] a,
int i1,
int i2,
int j1,
int j2,
ref double[] work)
{
double result = 0;
int i = 0;
int j = 0;
System.Diagnostics.Debug.Assert(i2 - i1 == j2 - j1, "UpperHessenberg1Norm: I2-I1<>J2-J1!");
for (j = j1; j <= j2; j++)
{
work[j] = 0;
}
for (i = i1; i <= i2; i++)
{
for (j = Math.Max(j1, j1 + i - i1 - 1); j <= j2; j++)
{
work[j] = work[j] + Math.Abs(a[i, j]);
}
}
result = 0;
for (j = j1; j <= j2; j++)
{
result = Math.Max(result, work[j]);
}
return result;
}
public static void copymatrix(ref double[,] a,
int is1,
int is2,
int js1,
int js2,
ref double[,] b,
int id1,
int id2,
int jd1,
int jd2)
{
int isrc = 0;
int idst = 0;
int i_ = 0;
int i1_ = 0;
if (is1 > is2 | js1 > js2)
{
return;
}
System.Diagnostics.Debug.Assert(is2 - is1 == id2 - id1, "CopyMatrix: different sizes!");
System.Diagnostics.Debug.Assert(js2 - js1 == jd2 - jd1, "CopyMatrix: different sizes!");
for (isrc = is1; isrc <= is2; isrc++)
{
idst = isrc - is1 + id1;
i1_ = (js1) - (jd1);
for (i_ = jd1; i_ <= jd2; i_++)
{
b[idst, i_] = a[isrc, i_ + i1_];
}
}
}
public static void inplacetranspose(ref double[,] a,
int i1,
int i2,
int j1,
int j2,
ref double[] work)
{
int i = 0;
int j = 0;
int ips = 0;
int jps = 0;
int l = 0;
int i_ = 0;
int i1_ = 0;
if (i1 > i2 | j1 > j2)
{
return;
}
System.Diagnostics.Debug.Assert(i1 - i2 == j1 - j2, "InplaceTranspose error: incorrect array size!");
for (i = i1; i <= i2 - 1; i++)
{
j = j1 + i - i1;
ips = i + 1;
jps = j1 + ips - i1;
l = i2 - i;
i1_ = (ips) - (1);
for (i_ = 1; i_ <= l; i_++)
{
work[i_] = a[i_ + i1_, j];
}
i1_ = (jps) - (ips);
for (i_ = ips; i_ <= i2; i_++)
{
a[i_, j] = a[i, i_ + i1_];
}
i1_ = (1) - (jps);
for (i_ = jps; i_ <= j2; i_++)
{
a[i, i_] = work[i_ + i1_];
}
}
}
public static void copyandtranspose(ref double[,] a,
int is1,
int is2,
int js1,
int js2,
ref double[,] b,
int id1,
int id2,
int jd1,
int jd2)
{
int isrc = 0;
int jdst = 0;
int i_ = 0;
int i1_ = 0;
if (is1 > is2 | js1 > js2)
{
return;
}
System.Diagnostics.Debug.Assert(is2 - is1 == jd2 - jd1, "CopyAndTranspose: different sizes!");
System.Diagnostics.Debug.Assert(js2 - js1 == id2 - id1, "CopyAndTranspose: different sizes!");
for (isrc = is1; isrc <= is2; isrc++)
{
jdst = isrc - is1 + jd1;
i1_ = (js1) - (id1);
for (i_ = id1; i_ <= id2; i_++)
{
b[i_, jdst] = a[isrc, i_ + i1_];
}
}
}
public static void matrixvectormultiply(ref double[,] a,
int i1,
int i2,
int j1,
int j2,
bool trans,
ref double[] x,
int ix1,
int ix2,
double alpha,
ref double[] y,
int iy1,
int iy2,
double beta)
{
int i = 0;
double v = 0;
int i_ = 0;
int i1_ = 0;
if (!trans)
{
//
// y := alpha*A*x + beta*y;
//
if (i1 > i2 | j1 > j2)
{
return;
}
System.Diagnostics.Debug.Assert(j2 - j1 == ix2 - ix1, "MatrixVectorMultiply: A and X dont match!");
System.Diagnostics.Debug.Assert(i2 - i1 == iy2 - iy1, "MatrixVectorMultiply: A and Y dont match!");
//
// beta*y
//
if (beta == 0)
{
for (i = iy1; i <= iy2; i++)
{
y[i] = 0;
}
}
else
{
for (i_ = iy1; i_ <= iy2; i_++)
{
y[i_] = beta * y[i_];
}
}
//
// alpha*A*x
//
for (i = i1; i <= i2; i++)
{
i1_ = (ix1) - (j1);
v = 0.0;
for (i_ = j1; i_ <= j2; i_++)
{
v += a[i, i_] * x[i_ + i1_];
}
y[iy1 + i - i1] = y[iy1 + i - i1] + alpha * v;
}
}
else
{
//
// y := alpha*A'*x + beta*y;
//
if (i1 > i2 | j1 > j2)
{
return;
}
System.Diagnostics.Debug.Assert(i2 - i1 == ix2 - ix1, "MatrixVectorMultiply: A and X dont match!");
System.Diagnostics.Debug.Assert(j2 - j1 == iy2 - iy1, "MatrixVectorMultiply: A and Y dont match!");
//
// beta*y
//
if (beta == 0)
{
for (i = iy1; i <= iy2; i++)
{
y[i] = 0;
}
}
else
{
for (i_ = iy1; i_ <= iy2; i_++)
{
y[i_] = beta * y[i_];
}
}
//
// alpha*A'*x
//
for (i = i1; i <= i2; i++)
{
v = alpha * x[ix1 + i - i1];
i1_ = (j1) - (iy1);
for (i_ = iy1; i_ <= iy2; i_++)
{
y[i_] = y[i_] + v * a[i, i_ + i1_];
}
}
}
}
public static double pythag2(double x,
double y)
{
double result = 0;
double w = 0;
double xabs = 0;
double yabs = 0;
double z = 0;
xabs = Math.Abs(x);
yabs = Math.Abs(y);
w = Math.Max(xabs, yabs);
z = Math.Min(xabs, yabs);
if (z == 0)
{
result = w;
}
else
{
result = w * Math.Sqrt(1 + AP.APMath.Sqr(z / w));
}
return result;
}
public static void matrixmatrixmultiply(ref double[,] a,
int ai1,
int ai2,
int aj1,
int aj2,
bool transa,
ref double[,] b,
int bi1,
int bi2,
int bj1,
int bj2,
bool transb,
double alpha,
ref double[,] c,
int ci1,
int ci2,
int cj1,
int cj2,
double beta,
ref double[] work)
{
int arows = 0;
int acols = 0;
int brows = 0;
int bcols = 0;
int crows = 0;
int ccols = 0;
int i = 0;
int j = 0;
int k = 0;
int l = 0;
int r = 0;
double v = 0;
int i_ = 0;
int i1_ = 0;
//
// Setup
//
if (!transa)
{
arows = ai2 - ai1 + 1;
acols = aj2 - aj1 + 1;
}
else
{
arows = aj2 - aj1 + 1;
acols = ai2 - ai1 + 1;
}
if (!transb)
{
brows = bi2 - bi1 + 1;
bcols = bj2 - bj1 + 1;
}
else
{
brows = bj2 - bj1 + 1;
bcols = bi2 - bi1 + 1;
}
System.Diagnostics.Debug.Assert(acols == brows, "MatrixMatrixMultiply: incorrect matrix sizes!");
if (arows <= 0 | acols <= 0 | brows <= 0 | bcols <= 0)
{
return;
}
crows = arows;
ccols = bcols;
//
// Test WORK
//
i = Math.Max(arows, acols);
i = Math.Max(brows, i);
i = Math.Max(i, bcols);
work[1] = 0;
work[i] = 0;
//
// Prepare C
//
if (beta == 0)
{
for (i = ci1; i <= ci2; i++)
{
for (j = cj1; j <= cj2; j++)
{
c[i, j] = 0;
}
}
}
else
{
for (i = ci1; i <= ci2; i++)
{
for (i_ = cj1; i_ <= cj2; i_++)
{
c[i, i_] = beta * c[i, i_];
}
}
}
//
// A*B
//
if (!transa & !transb)
{
for (l = ai1; l <= ai2; l++)
{
for (r = bi1; r <= bi2; r++)
{
v = alpha * a[l, aj1 + r - bi1];
k = ci1 + l - ai1;
i1_ = (bj1) - (cj1);
for (i_ = cj1; i_ <= cj2; i_++)
{
c[k, i_] = c[k, i_] + v * b[r, i_ + i1_];
}
}
}
return;
}
//
// A*B'
//
if (!transa & transb)
{
if (arows * acols < brows * bcols)
{
for (r = bi1; r <= bi2; r++)
{
for (l = ai1; l <= ai2; l++)
{
i1_ = (bj1) - (aj1);
v = 0.0;
for (i_ = aj1; i_ <= aj2; i_++)
{
v += a[l, i_] * b[r, i_ + i1_];
}
c[ci1 + l - ai1, cj1 + r - bi1] = c[ci1 + l - ai1, cj1 + r - bi1] + alpha * v;
}
}
return;
}
else
{
for (l = ai1; l <= ai2; l++)
{
for (r = bi1; r <= bi2; r++)
{
i1_ = (bj1) - (aj1);
v = 0.0;
for (i_ = aj1; i_ <= aj2; i_++)
{
v += a[l, i_] * b[r, i_ + i1_];
}
c[ci1 + l - ai1, cj1 + r - bi1] = c[ci1 + l - ai1, cj1 + r - bi1] + alpha * v;
}
}
return;
}
}
//
// A'*B
//
if (transa & !transb)
{
for (l = aj1; l <= aj2; l++)
{
for (r = bi1; r <= bi2; r++)
{
v = alpha * a[ai1 + r - bi1, l];
k = ci1 + l - aj1;
i1_ = (bj1) - (cj1);
for (i_ = cj1; i_ <= cj2; i_++)
{
c[k, i_] = c[k, i_] + v * b[r, i_ + i1_];
}
}
}
return;
}
//
// A'*B'
//
if (transa & transb)
{
if (arows * acols < brows * bcols)
{
for (r = bi1; r <= bi2; r++)
{
for (i = 1; i <= crows; i++)
{
work[i] = 0.0;
}
for (l = ai1; l <= ai2; l++)
{
v = alpha * b[r, bj1 + l - ai1];
k = cj1 + r - bi1;
i1_ = (aj1) - (1);
for (i_ = 1; i_ <= crows; i_++)
{
work[i_] = work[i_] + v * a[l, i_ + i1_];
}
}
i1_ = (1) - (ci1);
for (i_ = ci1; i_ <= ci2; i_++)
{
c[i_, k] = c[i_, k] + work[i_ + i1_];
}
}
return;
}
else
{
for (l = aj1; l <= aj2; l++)
{
k = ai2 - ai1 + 1;
i1_ = (ai1) - (1);
for (i_ = 1; i_ <= k; i_++)
{
work[i_] = a[i_ + i1_, l];
}
for (r = bi1; r <= bi2; r++)
{
i1_ = (bj1) - (1);
v = 0.0;
for (i_ = 1; i_ <= k; i_++)
{
v += work[i_] * b[r, i_ + i1_];
}
c[ci1 + l - aj1, cj1 + r - bi1] = c[ci1 + l - aj1, cj1 + r - bi1] + alpha * v;
}
}
return;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
/// <summary>
/// Caches all docs, and optionally also scores, coming from
/// a search, and is then able to replay them to another
/// collector. You specify the max RAM this class may use.
/// Once the collection is done, call <see cref="IsCached"/>. If
/// this returns <c>true</c>, you can use <see cref="Replay(ICollector)"/>
/// against a new collector. If it returns <c>false</c>, this means
/// too much RAM was required and you must instead re-run the
/// original search.
///
/// <para/><b>NOTE</b>: this class consumes 4 (or 8 bytes, if
/// scoring is cached) per collected document. If the result
/// set is large this can easily be a very substantial amount
/// of RAM!
///
/// <para/><b>NOTE</b>: this class caches at least 128 documents
/// before checking RAM limits.
///
/// <para>See the Lucene <c>modules/grouping</c> module for more
/// details including a full code example.</para>
///
/// @lucene.experimental
/// </summary>
public abstract class CachingCollector : ICollector
{
// Max out at 512K arrays
private const int MAX_ARRAY_SIZE = 512 * 1024;
private const int INITIAL_ARRAY_SIZE = 128;
/// <summary>
/// NOTE: This was EMPTY_INT_ARRAY in Lucene
/// </summary>
private static readonly int[] EMPTY_INT32_ARRAY =
#if FEATURE_ARRAYEMPTY
Array.Empty<int>();
#else
new int[0];
#endif
private class SegStart
{
public AtomicReaderContext ReaderContext { get; private set; }
public int End { get; private set; }
public SegStart(AtomicReaderContext readerContext, int end)
{
this.ReaderContext = readerContext;
this.End = end;
}
}
private sealed class CachedScorer : Scorer
{
// NOTE: these members are package-private b/c that way accessing them from
// the outer class does not incur access check by the JVM. The same
// situation would be if they were defined in the outer class as private
// members.
internal int doc;
internal float score;
internal CachedScorer()
: base(null)
{
}
public override float GetScore()
{
return score;
}
public override int Advance(int target)
{
throw new NotSupportedException();
}
public override int DocID => doc;
public override int Freq => throw new NotSupportedException();
public override int NextDoc()
{
throw new NotSupportedException();
}
public override long GetCost()
{
return 1;
}
}
/// <summary>
/// A <see cref="CachingCollector"/> which caches scores
/// </summary>
private sealed class ScoreCachingCollector : CachingCollector
{
private readonly CachedScorer cachedScorer;
private readonly IList<float[]> cachedScores;
private Scorer scorer;
private float[] curScores;
internal ScoreCachingCollector(ICollector other, double maxRAMMB)
: base(other, maxRAMMB, true)
{
cachedScorer = new CachedScorer();
cachedScores = new List<float[]>();
curScores = new float[INITIAL_ARRAY_SIZE];
cachedScores.Add(curScores);
}
internal ScoreCachingCollector(ICollector other, int maxDocsToCache)
: base(other, maxDocsToCache)
{
cachedScorer = new CachedScorer();
cachedScores = new List<float[]>();
curScores = new float[INITIAL_ARRAY_SIZE];
cachedScores.Add(curScores);
}
public override void Collect(int doc)
{
if (m_curDocs == null)
{
// Cache was too large
cachedScorer.score = scorer.GetScore();
cachedScorer.doc = doc;
m_other.Collect(doc);
return;
}
// Allocate a bigger array or abort caching
if (m_upto == m_curDocs.Length)
{
m_base += m_upto;
// Compute next array length - don't allocate too big arrays
int nextLength = 8 * m_curDocs.Length;
if (nextLength > MAX_ARRAY_SIZE)
{
nextLength = MAX_ARRAY_SIZE;
}
if (m_base + nextLength > m_maxDocsToCache)
{
// try to allocate a smaller array
nextLength = m_maxDocsToCache - m_base;
if (nextLength <= 0)
{
// Too many docs to collect -- clear cache
m_curDocs = null;
curScores = null;
m_cachedSegs.Clear();
m_cachedDocs.Clear();
cachedScores.Clear();
cachedScorer.score = scorer.GetScore();
cachedScorer.doc = doc;
m_other.Collect(doc);
return;
}
}
m_curDocs = new int[nextLength];
m_cachedDocs.Add(m_curDocs);
curScores = new float[nextLength];
cachedScores.Add(curScores);
m_upto = 0;
}
m_curDocs[m_upto] = doc;
cachedScorer.score = curScores[m_upto] = scorer.GetScore();
m_upto++;
cachedScorer.doc = doc;
m_other.Collect(doc);
}
public override void Replay(ICollector other)
{
ReplayInit(other);
int curUpto = 0;
int curBase = 0;
int chunkUpto = 0;
m_curDocs = EMPTY_INT32_ARRAY;
foreach (SegStart seg in m_cachedSegs)
{
other.SetNextReader(seg.ReaderContext);
other.SetScorer(cachedScorer);
while (curBase + curUpto < seg.End)
{
if (curUpto == m_curDocs.Length)
{
curBase += m_curDocs.Length;
m_curDocs = m_cachedDocs[chunkUpto];
curScores = cachedScores[chunkUpto];
chunkUpto++;
curUpto = 0;
}
cachedScorer.score = curScores[curUpto];
cachedScorer.doc = m_curDocs[curUpto];
other.Collect(m_curDocs[curUpto++]);
}
}
}
public override void SetScorer(Scorer scorer)
{
this.scorer = scorer;
m_other.SetScorer(cachedScorer);
}
public override string ToString()
{
if (IsCached)
{
return "CachingCollector (" + (m_base + m_upto) + " docs & scores cached)";
}
else
{
return "CachingCollector (cache was cleared)";
}
}
}
/// <summary>
/// A <see cref="CachingCollector"/> which does not cache scores
/// </summary>
private sealed class NoScoreCachingCollector : CachingCollector
{
internal NoScoreCachingCollector(ICollector other, double maxRAMMB)
: base(other, maxRAMMB, false)
{
}
internal NoScoreCachingCollector(ICollector other, int maxDocsToCache)
: base(other, maxDocsToCache)
{
}
public override void Collect(int doc)
{
if (m_curDocs == null)
{
// Cache was too large
m_other.Collect(doc);
return;
}
// Allocate a bigger array or abort caching
if (m_upto == m_curDocs.Length)
{
m_base += m_upto;
// Compute next array length - don't allocate too big arrays
int nextLength = 8 * m_curDocs.Length;
if (nextLength > MAX_ARRAY_SIZE)
{
nextLength = MAX_ARRAY_SIZE;
}
if (m_base + nextLength > m_maxDocsToCache)
{
// try to allocate a smaller array
nextLength = m_maxDocsToCache - m_base;
if (nextLength <= 0)
{
// Too many docs to collect -- clear cache
m_curDocs = null;
m_cachedSegs.Clear();
m_cachedDocs.Clear();
m_other.Collect(doc);
return;
}
}
m_curDocs = new int[nextLength];
m_cachedDocs.Add(m_curDocs);
m_upto = 0;
}
m_curDocs[m_upto] = doc;
m_upto++;
m_other.Collect(doc);
}
public override void Replay(ICollector other)
{
ReplayInit(other);
int curUpto = 0;
int curbase = 0;
int chunkUpto = 0;
m_curDocs = EMPTY_INT32_ARRAY;
foreach (SegStart seg in m_cachedSegs)
{
other.SetNextReader(seg.ReaderContext);
while (curbase + curUpto < seg.End)
{
if (curUpto == m_curDocs.Length)
{
curbase += m_curDocs.Length;
m_curDocs = m_cachedDocs[chunkUpto];
chunkUpto++;
curUpto = 0;
}
other.Collect(m_curDocs[curUpto++]);
}
}
}
public override void SetScorer(Scorer scorer)
{
m_other.SetScorer(scorer);
}
public override string ToString()
{
if (IsCached)
{
return "CachingCollector (" + (m_base + m_upto) + " docs cached)";
}
else
{
return "CachingCollector (cache was cleared)";
}
}
}
// TODO: would be nice if a collector defined a
// needsScores() method so we can specialize / do checks
// up front. this is only relevant for the ScoreCaching
// version -- if the wrapped Collector does not need
// scores, it can avoid cachedScorer entirely.
protected readonly ICollector m_other;
protected readonly int m_maxDocsToCache;
private readonly IList<SegStart> m_cachedSegs = new List<SegStart>();
protected readonly IList<int[]> m_cachedDocs;
private AtomicReaderContext lastReaderContext;
protected int[] m_curDocs;
protected int m_upto;
protected int m_base;
protected int m_lastDocBase;
/// <summary>
/// Creates a <see cref="CachingCollector"/> which does not wrap another collector.
/// The cached documents and scores can later be replayed (<see cref="Replay(ICollector)"/>).
/// </summary>
/// <param name="acceptDocsOutOfOrder">
/// whether documents are allowed to be collected out-of-order </param>
public static CachingCollector Create(bool acceptDocsOutOfOrder, bool cacheScores, double maxRAMMB)
{
ICollector other = new CollectorAnonymousInnerClassHelper(acceptDocsOutOfOrder);
return Create(other, cacheScores, maxRAMMB);
}
private class CollectorAnonymousInnerClassHelper : ICollector
{
private bool acceptDocsOutOfOrder;
public CollectorAnonymousInnerClassHelper(bool acceptDocsOutOfOrder)
{
this.acceptDocsOutOfOrder = acceptDocsOutOfOrder;
}
public virtual bool AcceptsDocsOutOfOrder => acceptDocsOutOfOrder;
public virtual void SetScorer(Scorer scorer)
{
}
public virtual void Collect(int doc)
{
}
public virtual void SetNextReader(AtomicReaderContext context)
{
}
}
/// <summary>
/// Create a new <see cref="CachingCollector"/> that wraps the given collector and
/// caches documents and scores up to the specified RAM threshold.
/// </summary>
/// <param name="other">
/// The <see cref="ICollector"/> to wrap and delegate calls to. </param>
/// <param name="cacheScores">
/// Whether to cache scores in addition to document IDs. Note that
/// this increases the RAM consumed per doc. </param>
/// <param name="maxRAMMB">
/// The maximum RAM in MB to consume for caching the documents and
/// scores. If the collector exceeds the threshold, no documents and
/// scores are cached. </param>
public static CachingCollector Create(ICollector other, bool cacheScores, double maxRAMMB)
{
return cacheScores ? (CachingCollector)new ScoreCachingCollector(other, maxRAMMB) : new NoScoreCachingCollector(other, maxRAMMB);
}
/// <summary>
/// Create a new <see cref="CachingCollector"/> that wraps the given collector and
/// caches documents and scores up to the specified max docs threshold.
/// </summary>
/// <param name="other">
/// The <see cref="ICollector"/> to wrap and delegate calls to. </param>
/// <param name="cacheScores">
/// Whether to cache scores in addition to document IDs. Note that
/// this increases the RAM consumed per doc. </param>
/// <param name="maxDocsToCache">
/// The maximum number of documents for caching the documents and
/// possible the scores. If the collector exceeds the threshold,
/// no documents and scores are cached. </param>
public static CachingCollector Create(ICollector other, bool cacheScores, int maxDocsToCache)
{
return cacheScores ? (CachingCollector)new ScoreCachingCollector(other, maxDocsToCache) : new NoScoreCachingCollector(other, maxDocsToCache);
}
// Prevent extension from non-internal classes
private CachingCollector(ICollector other, double maxRAMMB, bool cacheScores)
{
this.m_other = other;
m_cachedDocs = new List<int[]>();
m_curDocs = new int[INITIAL_ARRAY_SIZE];
m_cachedDocs.Add(m_curDocs);
int bytesPerDoc = RamUsageEstimator.NUM_BYTES_INT32;
if (cacheScores)
{
bytesPerDoc += RamUsageEstimator.NUM_BYTES_SINGLE;
}
m_maxDocsToCache = (int)((maxRAMMB * 1024 * 1024) / bytesPerDoc);
}
private CachingCollector(ICollector other, int maxDocsToCache)
{
this.m_other = other;
m_cachedDocs = new List<int[]>();
m_curDocs = new int[INITIAL_ARRAY_SIZE];
m_cachedDocs.Add(m_curDocs);
this.m_maxDocsToCache = maxDocsToCache;
}
public virtual bool AcceptsDocsOutOfOrder => m_other.AcceptsDocsOutOfOrder;
public virtual bool IsCached => m_curDocs != null;
public virtual void SetNextReader(AtomicReaderContext context)
{
m_other.SetNextReader(context);
if (lastReaderContext != null)
{
m_cachedSegs.Add(new SegStart(lastReaderContext, m_base + m_upto));
}
lastReaderContext = context;
}
// LUCENENET specific - we need to implement these here, since our abstract base class
// is now an interface.
/// <summary>
/// Called before successive calls to <see cref="Collect(int)"/>. Implementations
/// that need the score of the current document (passed-in to
/// <also cref="Collect(int)"/>), should save the passed-in <see cref="Scorer"/> and call
/// <see cref="Scorer.GetScore()"/> when needed.
/// </summary>
public abstract void SetScorer(Scorer scorer);
/// <summary>
/// Called once for every document matching a query, with the unbased document
/// number.
/// <para/>Note: The collection of the current segment can be terminated by throwing
/// a <see cref="CollectionTerminatedException"/>. In this case, the last docs of the
/// current <see cref="AtomicReaderContext"/> will be skipped and <see cref="IndexSearcher"/>
/// will swallow the exception and continue collection with the next leaf.
/// <para/>
/// Note: this is called in an inner search loop. For good search performance,
/// implementations of this method should not call <see cref="IndexSearcher.Doc(int)"/> or
/// <see cref="Lucene.Net.Index.IndexReader.Document(int)"/> on every hit.
/// Doing so can slow searches by an order of magnitude or more.
/// </summary>
public abstract void Collect(int doc);
/// <summary>
/// Reused by the specialized inner classes. </summary>
internal virtual void ReplayInit(ICollector other)
{
if (!IsCached)
{
throw new InvalidOperationException("cannot replay: cache was cleared because too much RAM was required");
}
if (!other.AcceptsDocsOutOfOrder && this.m_other.AcceptsDocsOutOfOrder)
{
throw new ArgumentException("cannot replay: given collector does not support " + "out-of-order collection, while the wrapped collector does. " + "Therefore cached documents may be out-of-order.");
}
//System.out.println("CC: replay totHits=" + (upto + base));
if (lastReaderContext != null)
{
m_cachedSegs.Add(new SegStart(lastReaderContext, m_base + m_upto));
lastReaderContext = null;
}
}
/// <summary>
/// Replays the cached doc IDs (and scores) to the given <see cref="ICollector"/>. If this
/// instance does not cache scores, then <see cref="Scorer"/> is not set on
/// <c>other.SetScorer(Scorer)</c> as well as scores are not replayed.
/// </summary>
/// <exception cref="InvalidOperationException">
/// If this collector is not cached (i.e., if the RAM limits were too
/// low for the number of documents + scores to cache). </exception>
/// <exception cref="ArgumentException">
/// If the given Collect's does not support out-of-order collection,
/// while the collector passed to the ctor does. </exception>
public abstract void Replay(ICollector other);
}
}
| |
using System;
#if __UNIFIED__
using UIKit;
using CoreGraphics;
using Foundation;
using CoreLocation;
#else
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using MonoTouch.CoreLocation;
using System.Drawing;
using CGRect = global::System.Drawing.RectangleF;
using CGSize = global::System.Drawing.SizeF;
using CGPoint = global::System.Drawing.PointF;
using nfloat = global::System.Single;
using nint = global::System.Int32;
using nuint = global::System.UInt32;
#endif
using Google.Maps;
using System.Security.Cryptography;
namespace GoogleMapsAdvSample
{
public class PolygonsViewController : UIViewController
{
public PolygonsViewController () : base ()
{
Title = "Polygons";
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
var camera = CameraPosition.FromCamera (39.13006, -77.508545, 4);
var mapView = MapView.FromCamera (CGRect.Empty, camera);
// Create the first polygon.
var polygon = new Polygon () {
Path = PathOfNewYorkState (),
Title = "New York",
FillColor = UIColor.FromRGBA (0.25f, 0, 0, 0.05f),
StrokeColor = UIColor.Black,
StrokeWidth = 2,
Tappable = true,
Map = mapView
};
// Copy the existing polygon and its settings and use it as a base for the
// second polygon.
polygon = (Polygon)polygon.Copy ();
polygon.Title = "North Carolina";
polygon.Path = PathOfNorthCarolina ();
polygon.FillColor = UIColor.FromRGBA (0, 0.25f, 0, 0.05f);
polygon.Map = mapView;
mapView.OverlayTapped += (sender, e) => {
// When a polygon is tapped, randomly change its fill color to a new hue.
if (e.Overlay is Polygon) {
var pol = e.Overlay as Polygon;
var hue = GetRandomNumber ();
pol.FillColor = UIColor.FromHSBA (hue, 1, 1, 0.05f);
}
};
View = mapView;
}
Google.Maps.Path PathOfNewYorkState ()
{
var path = new MutablePath ();
path.AddLatLon (42.5142, -79.7624);
path.AddLatLon (42.7783, -79.0672);
path.AddLatLon (42.8508, -78.9313);
path.AddLatLon (42.9061, -78.9024);
path.AddLatLon (42.9554, -78.9313);
path.AddLatLon (42.9584, -78.9656);
path.AddLatLon (42.9886, -79.0219);
path.AddLatLon (43.0568, -79.0027);
path.AddLatLon (43.0769, -79.0727);
path.AddLatLon (43.1220, -79.0713);
path.AddLatLon (43.1441, -79.0302);
path.AddLatLon (43.1801, -79.0576);
path.AddLatLon (43.2482, -79.0604);
path.AddLatLon (43.2812, -79.0837);
path.AddLatLon (43.4509, -79.2004);
path.AddLatLon (43.6311, -78.6909);
path.AddLatLon (43.6321, -76.7958);
path.AddLatLon (43.9987, -76.4978);
path.AddLatLon (44.0965, -76.4388);
path.AddLatLon (44.1349, -76.3536);
path.AddLatLon (44.1989, -76.3124);
path.AddLatLon (44.2049, -76.2437);
path.AddLatLon (44.2413, -76.1655);
path.AddLatLon (44.2973, -76.1353);
path.AddLatLon (44.3327, -76.0474);
path.AddLatLon (44.3553, -75.9856);
path.AddLatLon (44.3749, -75.9196);
path.AddLatLon (44.3994, -75.8730);
path.AddLatLon (44.4308, -75.8221);
path.AddLatLon (44.4740, -75.8098);
path.AddLatLon (44.5425, -75.7288);
path.AddLatLon (44.6647, -75.5585);
path.AddLatLon (44.7672, -75.4088);
path.AddLatLon (44.8101, -75.3442);
path.AddLatLon (44.8383, -75.3058);
path.AddLatLon (44.8676, -75.2399);
path.AddLatLon (44.9211, -75.1204);
path.AddLatLon (44.9609, -74.9995);
path.AddLatLon (44.9803, -74.9899);
path.AddLatLon (44.9852, -74.9103);
path.AddLatLon (45.0017, -74.8856);
path.AddLatLon (45.0153, -74.8306);
path.AddLatLon (45.0046, -74.7633);
path.AddLatLon (45.0027, -74.7070);
path.AddLatLon (45.0007, -74.5642);
path.AddLatLon (44.9920, -74.1467);
path.AddLatLon (45.0037, -73.7306);
path.AddLatLon (45.0085, -73.4203);
path.AddLatLon (45.0109, -73.3430);
path.AddLatLon (44.9874, -73.3547);
path.AddLatLon (44.9648, -73.3379);
path.AddLatLon (44.9160, -73.3396);
path.AddLatLon (44.8354, -73.3739);
path.AddLatLon (44.8013, -73.3324);
path.AddLatLon (44.7419, -73.3667);
path.AddLatLon (44.6139, -73.3873);
path.AddLatLon (44.5787, -73.3736);
path.AddLatLon (44.4916, -73.3049);
path.AddLatLon (44.4289, -73.2953);
path.AddLatLon (44.3513, -73.3365);
path.AddLatLon (44.2757, -73.3118);
path.AddLatLon (44.1980, -73.3818);
path.AddLatLon (44.1142, -73.4079);
path.AddLatLon (44.0511, -73.4367);
path.AddLatLon (44.0165, -73.4065);
path.AddLatLon (43.9375, -73.4079);
path.AddLatLon (43.8771, -73.3749);
path.AddLatLon (43.8167, -73.3914);
path.AddLatLon (43.7790, -73.3557);
path.AddLatLon (43.6460, -73.4244);
path.AddLatLon (43.5893, -73.4340);
path.AddLatLon (43.5655, -73.3969);
path.AddLatLon (43.6112, -73.3818);
path.AddLatLon (43.6271, -73.3049);
path.AddLatLon (43.5764, -73.3063);
path.AddLatLon (43.5675, -73.2582);
path.AddLatLon (43.5227, -73.2445);
path.AddLatLon (43.2582, -73.2582);
path.AddLatLon (42.9715, -73.2733);
path.AddLatLon (42.8004, -73.2898);
path.AddLatLon (42.7460, -73.2664);
path.AddLatLon (42.4630, -73.3708);
path.AddLatLon (42.0840, -73.5095);
path.AddLatLon (42.0218, -73.4903);
path.AddLatLon (41.8808, -73.4999);
path.AddLatLon (41.2953, -73.5535);
path.AddLatLon (41.2128, -73.4834);
path.AddLatLon (41.1011, -73.7275);
path.AddLatLon (41.0237, -73.6644);
path.AddLatLon (40.9851, -73.6578);
path.AddLatLon (40.9509, -73.6132);
path.AddLatLon (41.1869, -72.4823);
path.AddLatLon (41.2551, -72.0950);
path.AddLatLon (41.3005, -71.9714);
path.AddLatLon (41.3108, -71.9193);
path.AddLatLon (41.1838, -71.7915);
path.AddLatLon (41.1249, -71.7929);
path.AddLatLon (41.0462, -71.7517);
path.AddLatLon (40.6306, -72.9465);
path.AddLatLon (40.5368, -73.4628);
path.AddLatLon (40.4887, -73.8885);
path.AddLatLon (40.5232, -73.9490);
path.AddLatLon (40.4772, -74.2271);
path.AddLatLon (40.4861, -74.2532);
path.AddLatLon (40.6468, -74.1866);
path.AddLatLon (40.6556, -74.0547);
path.AddLatLon (40.7618, -74.0156);
path.AddLatLon (40.8699, -73.9421);
path.AddLatLon (40.9980, -73.8934);
path.AddLatLon (41.0343, -73.9854);
path.AddLatLon (41.3268, -74.6274);
path.AddLatLon (41.3583, -74.7084);
path.AddLatLon (41.3811, -74.7101);
path.AddLatLon (41.4386, -74.8265);
path.AddLatLon (41.5075, -74.9913);
path.AddLatLon (41.6000, -75.0668);
path.AddLatLon (41.6719, -75.0366);
path.AddLatLon (41.7672, -75.0545);
path.AddLatLon (41.8808, -75.1945);
path.AddLatLon (42.0013, -75.3552);
path.AddLatLon (42.0003, -75.4266);
path.AddLatLon (42.0013, -77.0306);
path.AddLatLon (41.9993, -79.7250);
path.AddLatLon (42.0003, -79.7621);
path.AddLatLon (42.1827, -79.7621);
path.AddLatLon (42.5146, -79.7621);
return path;
}
Google.Maps.Path PathOfNorthCarolina ()
{
var path = new MutablePath ();
path.AddLatLon (33.7963, -78.4850);
path.AddLatLon (34.8037, -79.6742);
path.AddLatLon (34.8206, -80.8003);
path.AddLatLon (34.9377, -80.7880);
path.AddLatLon (35.1019, -80.9377);
path.AddLatLon (35.0356, -81.0379);
path.AddLatLon (35.1457, -81.0324);
path.AddLatLon (35.1660, -81.3867);
path.AddLatLon (35.1985, -82.2739);
path.AddLatLon (35.2041, -82.3933);
path.AddLatLon (35.0637, -82.7765);
path.AddLatLon (35.0817, -82.7861);
path.AddLatLon (34.9996, -83.1075);
path.AddLatLon (34.9918, -83.6183);
path.AddLatLon (34.9918, -84.3201);
path.AddLatLon (35.2131, -84.2885);
path.AddLatLon (35.2680, -84.2226);
path.AddLatLon (35.2310, -84.1113);
path.AddLatLon (35.2815, -84.0454);
path.AddLatLon (35.4058, -84.0248);
path.AddLatLon (35.4719, -83.9424);
path.AddLatLon (35.5166, -83.8559);
path.AddLatLon (35.5512, -83.6938);
path.AddLatLon (35.5680, -83.5181);
path.AddLatLon (35.6327, -83.3849);
path.AddLatLon (35.7142, -83.2475);
path.AddLatLon (35.7799, -82.9962);
path.AddLatLon (35.8445, -82.9276);
path.AddLatLon (35.9224, -82.8191);
path.AddLatLon (35.9958, -82.7710);
path.AddLatLon (36.0613, -82.6419);
path.AddLatLon (35.9702, -82.6103);
path.AddLatLon (35.9547, -82.5677);
path.AddLatLon (36.0236, -82.4730);
path.AddLatLon (36.0669, -82.4194);
path.AddLatLon (36.1168, -82.3535);
path.AddLatLon (36.1345, -82.2862);
path.AddLatLon (36.1467, -82.1461);
path.AddLatLon (36.1035, -82.1228);
path.AddLatLon (36.1268, -82.0267);
path.AddLatLon (36.2797, -81.9360);
path.AddLatLon (36.3527, -81.7987);
path.AddLatLon (36.3361, -81.7081);
path.AddLatLon (36.5880, -81.6724);
path.AddLatLon (36.5659, -80.7234);
path.AddLatLon (36.5438, -80.2977);
path.AddLatLon (36.5449, -79.6729);
path.AddLatLon (36.5449, -77.2559);
path.AddLatLon (36.5505, -75.7562);
path.AddLatLon (36.3129, -75.7068);
path.AddLatLon (35.7131, -75.4129);
path.AddLatLon (35.2041, -75.4720);
path.AddLatLon (34.9794, -76.0748);
path.AddLatLon (34.5258, -76.4951);
path.AddLatLon (34.5880, -76.8109);
path.AddLatLon (34.5314, -77.1378);
path.AddLatLon (34.3910, -77.4481);
path.AddLatLon (34.0481, -77.7983);
path.AddLatLon (33.7666, -77.9260);
path.AddLatLon (33.7963, -78.4863);
return path;
}
float GetRandomNumber ()
{
var rng = new RNGCryptoServiceProvider ();
var bytes = new Byte[8];
rng.GetBytes (bytes);
var ul = BitConverter.ToUInt64 (bytes, 0) / (1 << 11);
return (float)(ul / (Double)(1UL << 53));
}
}
}
| |
namespace Bog.Web.Dashboard.Areas.HelpPage
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Bog.Web.Dashboard.Areas.HelpPage.Models;
/// <summary>
/// The help page configuration extensions.
/// </summary>
public static class HelpPageConfigurationExtensions
{
#region Constants
/// <summary>
/// The api model prefix.
/// </summary>
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
#endregion
#region Public Methods and Operators
/// <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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
/// <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>
/// 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>
/// 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 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>
/// 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>
/// 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);
}
#endregion
#region Methods
/// <summary>
/// The generate api model.
/// </summary>
/// <param name="apiDescription">
/// The api description.
/// </param>
/// <param name="sampleGenerator">
/// The sample generator.
/// </param>
/// <returns>
/// The <see cref="HelpPageApiModel"/>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(
ApiDescription apiDescription,
HelpPageSampleGenerator sampleGenerator)
{
var apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}",
e.Message));
}
return apiModel;
}
/// <summary>
/// The log invalid sample as error.
/// </summary>
/// <param name="apiModel">
/// The api model.
/// </param>
/// <param name="sample">
/// The sample.
/// </param>
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
var invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
#endregion
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Site.Areas.Account.Models
{
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Adxstudio.Xrm.AspNet.Identity;
using Adxstudio.Xrm.AspNet.Mvc;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Web;
using Adxstudio.Xrm.Web.Mvc;
using Microsoft.AspNet.Identity;
using Site.Areas.Account.ViewModels;
using Site.Areas.AccountManagement;
/// <summary>
/// User registration handling.
/// </summary>
public class RegistrationManager
{
/// <summary>
/// Collect errors
/// </summary>
public List<string> Errors;
/// <summary>
/// Model that handles the logic
/// </summary>
private LoginManager loginManager;
/// <summary>
/// Holds Authentication settings required for the page
/// </summary>
public AuthenticationSettings Settings { get; private set; }
/// <summary>
/// Azure AD Or External Login Enabled variable used for external login
/// </summary>
public bool AzureAdOrExternalLoginEnabled { get; private set; }
/// <summary>
/// Is External Registration Enabled
/// </summary>
public bool IsExternalRegistrationEnabled { get; private set; }
/// <summary>
/// Holds protal view context to redirect to profile page
/// </summary>
public ViewDataDictionary ViewData { get; set; }
/// <summary>
/// Identity Errors to get error descriptions
/// </summary>
public CrmIdentityErrorDescriber IdentityErrors { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="RegistrationManager" /> class.
/// </summary>
/// <param name="httpContext">The context.</param>
public RegistrationManager(HttpContextBase httpContext)
{
this.loginManager = new LoginManager(httpContext);
var isLocal = httpContext.IsDebuggingEnabled && httpContext.Request.IsLocal;
var website = httpContext.GetWebsite();
this.Settings = website.GetAuthenticationSettings(isLocal);
this.AzureAdOrExternalLoginEnabled = this.Settings.ExternalLoginEnabled || this.loginManager.StartupSettingsManager.AzureAdOptions != null;
this.loginManager.IdentityErrors = this.IdentityErrors = website.GetIdentityErrors(httpContext.GetOwinContext());
this.IsExternalRegistrationEnabled = this.loginManager.StartupSettingsManager.ExternalRegistrationEnabled;
}
/// <summary>
/// On Page Init
/// </summary>
/// <param name="invitationCode">invitation Code</param>
/// <returns>returns email value</returns>
public string FindEmailByInvitationCode(string invitationCode)
{
if (Adxstudio.Xrm.Configuration.PortalSettings.Instance.Ess.IsEss || !this.Settings.RegistrationEnabled
|| (!this.Settings.OpenRegistrationEnabled && !this.Settings.InvitationEnabled)
|| (this.Settings.OpenRegistrationEnabled && !this.Settings.InvitationEnabled && !string.IsNullOrWhiteSpace(invitationCode))
|| (!this.Settings.OpenRegistrationEnabled && this.Settings.InvitationEnabled && string.IsNullOrWhiteSpace(invitationCode)))
{
this.loginManager.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
this.loginManager.HttpContext.Response.ContentType = "text/plain";
this.loginManager.HttpContext.Response.Write(ResourceManager.GetString("Not_Found_Exception"));
this.loginManager.HttpContext.Response.End();
}
Task<ApplicationInvitation> invitation = this.loginManager.FindInvitationByCodeAsync(invitationCode);
invitation.Wait();
var contactId = this.loginManager.ToContactId(invitation.Result);
var email = contactId != null ? contactId.Name : null;
return email;
}
/// <summary>
/// Validate and register
/// </summary>
/// <param name="registerViewModel">Register values to validate</param>
/// <param name="returnUrl">return URL</param>
/// <param name="invitationCode">invitation code</param>
/// <returns>redirects to respective pages on validated else loads errors</returns>
public async Task ValidateAndRegisterUser(RegisterViewModel registerViewModel, string returnUrl, string invitationCode)
{
if (Adxstudio.Xrm.Configuration.PortalSettings.Instance.Ess.IsEss || !this.Settings.RegistrationEnabled
|| (!this.Settings.OpenRegistrationEnabled && !this.Settings.InvitationEnabled)
|| (this.Settings.OpenRegistrationEnabled && !this.Settings.InvitationEnabled && !string.IsNullOrWhiteSpace(invitationCode))
|| (!this.Settings.OpenRegistrationEnabled && this.Settings.InvitationEnabled && string.IsNullOrWhiteSpace(invitationCode)))
{
this.loginManager.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
this.loginManager.HttpContext.Response.ContentType = "text/plain";
this.loginManager.HttpContext.Response.Write(ResourceManager.GetString("Not_Found_Exception"));
this.loginManager.HttpContext.Response.End();
}
if ((this.Settings.LocalLoginByEmail || this.Settings.RequireUniqueEmail) && string.IsNullOrWhiteSpace(registerViewModel.Email))
{
this.loginManager.AddErrors(this.loginManager.IdentityErrors.EmailRequired());
}
if (!string.IsNullOrWhiteSpace(registerViewModel.Email) && !this.loginManager.ValidateEmail(registerViewModel.Email))
{
this.loginManager.AddErrors(this.loginManager.IdentityErrors.ValidEmailRequired());
}
if (!this.Settings.LocalLoginByEmail && string.IsNullOrWhiteSpace(registerViewModel.Username))
{
this.loginManager.AddErrors(this.loginManager.IdentityErrors.UserNameRequired());
}
if (string.IsNullOrWhiteSpace(registerViewModel.Password))
{
this.loginManager.AddErrors(this.loginManager.IdentityErrors.PasswordRequired());
}
if (!string.Equals(registerViewModel.Password, registerViewModel.ConfirmPassword))
{
this.loginManager.AddErrors(this.loginManager.IdentityErrors.PasswordConfirmationFailure());
}
#if TELERIKWEBUI
if (registerViewModel.IsCaptchaEnabled && !registerViewModel.IsCaptchaValid)
{
this.loginManager.AddErrors(
this.loginManager.IdentityErrors.CaptchaRequired(registerViewModel.CaptchaValidationMessage));
}
#endif
if (this.loginManager.Error.Count <= 0)
{
var invitation = await this.loginManager.FindInvitationByCodeAsync(invitationCode);
// Is there a contact?
var contactId = this.loginManager.ToContactId(invitation);
if (!string.IsNullOrWhiteSpace(invitationCode) && contactId == null)
{
this.loginManager.AddErrors(this.loginManager.IdentityErrors.InvalidInvitationCode());
}
if (this.loginManager.Error.Count <= 0)
{
ApplicationUser user;
IdentityResult result;
if (contactId == null)
{
// Create a new user
user = new ApplicationUser
{
UserName = this.Settings.LocalLoginByEmail ? registerViewModel.Email : registerViewModel.Username,
Email = registerViewModel.Email
};
result = await this.loginManager.UserManager.CreateAsync(user, registerViewModel.Password);
}
else
{
// Update the existing invited user
user = await this.loginManager.UserManager.FindByIdAsync(contactId.Id.ToString());
if (user != null)
{
result = await this.loginManager.UserManager.InitializeUserAsync(
user,
this.Settings.LocalLoginByEmail ? registerViewModel.Email : registerViewModel.Username,
registerViewModel.Password,
!string.IsNullOrWhiteSpace(registerViewModel.Email) ? registerViewModel.Email : contactId.Name,
this.Settings.TriggerLockoutOnFailedPassword);
}
else
{
// Contact does not exist or login is disabled
result = IdentityResult.Failed(this.loginManager.IdentityErrors.InvalidInvitationCode().Description);
}
if (!result.Succeeded)
{
var urlHelper = this.GetUrlHelper();
this.loginManager.AddErrors(result);
this.loginManager.HttpContext.Response.Redirect(urlHelper.Action("RedeemInvitation", "Login", new { InvitationCode = invitationCode }));
}
}
if (result.Succeeded)
{
if (invitation != null)
{
var redeemResult = await this.loginManager.InvitationManager.RedeemAsync(invitation, user, this.loginManager.HttpContext.Request.UserHostAddress);
if (redeemResult.Succeeded)
{
var redirectTo = await this.loginManager.SignInAsync(user, returnUrl);
this.RedirectTo(redirectTo, returnUrl);
}
else
{
this.loginManager.AddErrors(redeemResult);
}
}
else
{
var redirectTo = await this.loginManager.SignInAsync(user, returnUrl);
this.RedirectTo(redirectTo, returnUrl);
}
}
else
{
this.loginManager.AddErrors(result);
}
}
}
// If we got this far, something failed, redisplay form
this.Errors = this.loginManager.Error;
}
/// <summary>
/// Redirects to appropriate page based on enum value
/// </summary>
/// <param name="redirectTo">Holds information to redirect page</param>
/// <param name="returnUrl">return value</param>
private void RedirectTo(Enums.RedirectTo redirectTo, string returnUrl)
{
switch (redirectTo)
{
case Enums.RedirectTo.Redeem:
var urlHelper = this.GetUrlHelper();
this.loginManager.HttpContext.Response.Redirect(urlHelper.Action("RedeemInvitation", "Login", new { ReturnUrl = returnUrl, invalid = true }));
break;
case Enums.RedirectTo.Profile:
this.RedirectToProfile(returnUrl);
break;
case Enums.RedirectTo.Local:
break;
}
}
/// <summary>
/// Returns a <see cref="UrlHelper"/>.
/// </summary>
/// <returns>The UrlHelper.</returns>
private UrlHelper GetUrlHelper()
{
var requestContext = new RequestContext(this.loginManager.HttpContext, new RouteData());
var urlHelper = new UrlHelper(requestContext, RouteTable.Routes);
return urlHelper;
}
/// <summary>
/// Redirects to profile page
/// </summary>
/// <param name="returnUrl">Return url to append</param>
private void RedirectToProfile(string returnUrl)
{
var query = !string.IsNullOrWhiteSpace(returnUrl) ? new NameValueCollection { { "ReturnUrl", returnUrl } } : null;
var obj = new RedirectToSiteMarkerResult("Profile", query);
obj.ExecutePageResult(this.ViewData, this.loginManager.HttpContext);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Xml;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes.Scripting;
namespace OpenSim.Region.Framework.Scenes
{
public class SceneObjectPartInventory : IEntityInventory
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_inventoryFileName = String.Empty;
private int m_inventoryFileNameSerial = 0;
/// <value>
/// The part to which the inventory belongs.
/// </value>
private SceneObjectPart m_part;
/// <summary>
/// Serial count for inventory file , used to tell if inventory has changed
/// no need for this to be part of Database backup
/// </summary>
protected uint m_inventorySerial = 0;
/// <summary>
/// Holds in memory prim inventory
/// </summary>
protected TaskInventoryDictionary m_items = new TaskInventoryDictionary();
/// <summary>
/// Tracks whether inventory has changed since the last persistent backup
/// </summary>
internal bool HasInventoryChanged;
/// <value>
/// Inventory serial number
/// </value>
protected internal uint Serial
{
get { return m_inventorySerial; }
set { m_inventorySerial = value; }
}
/// <value>
/// Raw inventory data
/// </value>
protected internal TaskInventoryDictionary Items
{
get { return m_items; }
set
{
m_items = value;
m_inventorySerial++;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="part">
/// A <see cref="SceneObjectPart"/>
/// </param>
public SceneObjectPartInventory(SceneObjectPart part)
{
m_part = part;
}
/// <summary>
/// Force the task inventory of this prim to persist at the next update sweep
/// </summary>
public void ForceInventoryPersistence()
{
HasInventoryChanged = true;
}
/// <summary>
/// Reset UUIDs for all the items in the prim's inventory. This involves either generating
/// new ones or setting existing UUIDs to the correct parent UUIDs.
///
/// If this method is called and there are inventory items, then we regard the inventory as having changed.
/// </summary>
/// <param name="linkNum">Link number for the part</param>
public void ResetInventoryIDs()
{
lock (Items)
{
if (0 == Items.Count)
return;
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
Items.Clear();
foreach (TaskInventoryItem item in items)
{
item.ResetIDs(m_part.UUID);
Items.Add(item.ItemID, item);
}
}
}
/// <summary>
/// Change every item in this inventory to a new owner.
/// </summary>
/// <param name="ownerId"></param>
public void ChangeInventoryOwner(UUID ownerId)
{
lock (Items)
{
if (0 == Items.Count)
{
return;
}
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
foreach (TaskInventoryItem item in items)
{
if (ownerId != item.OwnerID)
{
item.LastOwnerID = item.OwnerID;
item.OwnerID = ownerId;
}
}
}
}
/// <summary>
/// Change every item in this inventory to a new group.
/// </summary>
/// <param name="groupID"></param>
public void ChangeInventoryGroup(UUID groupID)
{
lock (Items)
{
if (0 == Items.Count)
{
return;
}
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
foreach (TaskInventoryItem item in items)
{
if (groupID != item.GroupID)
{
item.GroupID = groupID;
}
}
}
}
/// <summary>
/// Start all the scripts contained in this prim's inventory
/// </summary>
public void CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource)
{
lock (m_items)
{
foreach (TaskInventoryItem item in Items.Values)
{
if ((int)InventoryType.LSL == item.InvType)
{
CreateScriptInstance(item, startParam, postOnRez, engine, stateSource);
}
}
}
}
public ArrayList GetScriptErrors(UUID itemID)
{
ArrayList ret = new ArrayList();
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines == null) // No engine at all
return ret;
foreach (IScriptModule e in engines)
{
if (e != null)
{
ArrayList errors = e.GetScriptErrors(itemID);
foreach (Object line in errors)
ret.Add(line);
}
}
return ret;
}
/// <summary>
/// Stop all the scripts in this prim.
/// </summary>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if these scripts are being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void RemoveScriptInstances(bool sceneObjectBeingDeleted)
{
lock (Items)
{
foreach (TaskInventoryItem item in Items.Values)
{
if ((int)InventoryType.LSL == item.InvType)
{
RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted);
}
}
}
}
/// <summary>
/// Start a script which is in this prim's inventory.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public void CreateScriptInstance(TaskInventoryItem item, int startParam, bool postOnRez, string engine, int stateSource)
{
// m_log.InfoFormat(
// "[PRIM INVENTORY]: " +
// "Starting script {0}, {1} in prim {2}, {3}",
// item.Name, item.ItemID, Name, UUID);
if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID))
return;
m_part.AddFlag(PrimFlags.Scripted);
if (!m_part.ParentGroup.Scene.RegionInfo.RegionSettings.DisableScripts)
{
if (stateSource == 1 && // Prim crossing
m_part.ParentGroup.Scene.m_trustBinaries)
{
lock (m_items)
{
m_items[item.ItemID].PermsMask = 0;
m_items[item.ItemID].PermsGranter = UUID.Zero;
}
m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource);
m_part.ParentGroup.AddActiveScriptCount(1);
m_part.ScheduleFullUpdate();
return;
}
m_part.ParentGroup.Scene.AssetService.Get(
item.AssetID.ToString(), this, delegate(string id, object sender, AssetBase asset)
{
if (null == asset)
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found",
item.Name, item.ItemID, m_part.AbsolutePosition,
m_part.ParentGroup.Scene.RegionInfo.RegionName, item.AssetID);
}
else
{
if (m_part.ParentGroup.m_savedScriptState != null)
RestoreSavedScriptState(item.OldItemID, item.ItemID);
lock (m_items)
{
m_items[item.ItemID].PermsMask = 0;
m_items[item.ItemID].PermsGranter = UUID.Zero;
}
string script = Utils.BytesToString(asset.Data);
m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource);
m_part.ParentGroup.AddActiveScriptCount(1);
m_part.ScheduleFullUpdate();
}
}
);
}
}
private void RestoreSavedScriptState(UUID oldID, UUID newID)
{
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines == null) // No engine at all
return;
if (m_part.ParentGroup.m_savedScriptState.ContainsKey(oldID))
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(m_part.ParentGroup.m_savedScriptState[oldID]);
////////// CRUFT WARNING ///////////////////////////////////
//
// Old objects will have <ScriptState><State> ...
// This format is XEngine ONLY
//
// New objects have <State Engine="...." ...><ScriptState>...
// This can be passed to any engine
//
XmlNode n = doc.SelectSingleNode("ScriptState");
if (n != null) // Old format data
{
XmlDocument newDoc = new XmlDocument();
XmlElement rootN = newDoc.CreateElement("", "State", "");
XmlAttribute uuidA = newDoc.CreateAttribute("", "UUID", "");
uuidA.Value = oldID.ToString();
rootN.Attributes.Append(uuidA);
XmlAttribute engineA = newDoc.CreateAttribute("", "Engine", "");
engineA.Value = "XEngine";
rootN.Attributes.Append(engineA);
newDoc.AppendChild(rootN);
XmlNode stateN = newDoc.ImportNode(n, true);
rootN.AppendChild(stateN);
// This created document has only the minimun data
// necessary for XEngine to parse it successfully
m_part.ParentGroup.m_savedScriptState[oldID] = newDoc.OuterXml;
}
foreach (IScriptModule e in engines)
{
if (e != null)
{
if (e.SetXMLState(newID, m_part.ParentGroup.m_savedScriptState[oldID]))
break;
}
}
m_part.ParentGroup.m_savedScriptState.Remove(oldID);
}
}
/// <summary>
/// Start a script which is in this prim's inventory.
/// </summary>
/// <param name="itemId">
/// A <see cref="UUID"/>
/// </param>
public void CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
{
lock (m_items)
{
if (m_items.ContainsKey(itemId))
{
CreateScriptInstance(m_items[itemId], startParam, postOnRez, engine, stateSource);
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
itemId, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
}
}
/// <summary>
/// Stop a script which is in this prim's inventory.
/// </summary>
/// <param name="itemId"></param>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if this script is being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted)
{
bool scriptPresent = false;
lock (m_items)
{
if (m_items.ContainsKey(itemId))
scriptPresent = true;
}
if (scriptPresent)
{
if (!sceneObjectBeingDeleted)
m_part.RemoveScriptEvents(itemId);
m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemId);
m_part.ParentGroup.AddActiveScriptCount(-1);
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
itemId, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
}
/// <summary>
/// Check if the inventory holds an item with a given name.
/// This method assumes that the task inventory is already locked.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private bool InventoryContainsName(string name)
{
foreach (TaskInventoryItem item in Items.Values)
{
if (item.Name == name)
return true;
}
return false;
}
/// <summary>
/// For a given item name, return that name if it is available. Otherwise, return the next available
/// similar name (which is currently the original name with the next available numeric suffix).
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private string FindAvailableInventoryName(string name)
{
if (!InventoryContainsName(name))
return name;
int suffix=1;
while (suffix < 256)
{
string tryName=String.Format("{0} {1}", name, suffix);
if (!InventoryContainsName(tryName))
return tryName;
suffix++;
}
return String.Empty;
}
/// <summary>
/// Add an item to this prim's inventory. If an item with the same name already exists, then an alternative
/// name is chosen.
/// </summary>
/// <param name="item"></param>
public void AddInventoryItem(TaskInventoryItem item, bool allowedDrop)
{
AddInventoryItem(item.Name, item, allowedDrop);
}
/// <summary>
/// Add an item to this prim's inventory. If an item with the same name already exists, it is replaced.
/// </summary>
/// <param name="item"></param>
public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop)
{
List<TaskInventoryItem> il;
lock (m_items)
{
il = new List<TaskInventoryItem>(m_items.Values);
}
foreach (TaskInventoryItem i in il)
{
if (i.Name == item.Name)
{
if (i.InvType == (int)InventoryType.LSL)
RemoveScriptInstance(i.ItemID, false);
RemoveInventoryItem(i.ItemID);
break;
}
}
AddInventoryItem(item.Name, item, allowedDrop);
}
/// <summary>
/// Add an item to this prim's inventory.
/// </summary>
/// <param name="name">The name that the new item should have.</param>
/// <param name="item">
/// The item itself. The name within this structure is ignored in favour of the name
/// given in this method's arguments
/// </param>
/// <param name="allowedDrop">
/// Item was only added to inventory because AllowedDrop is set
/// </param>
protected void AddInventoryItem(string name, TaskInventoryItem item, bool allowedDrop)
{
name = FindAvailableInventoryName(name);
if (name == String.Empty)
return;
item.ParentID = m_part.UUID;
item.ParentPartID = m_part.UUID;
item.Name = name;
lock (m_items)
{
m_items.Add(item.ItemID, item);
if (allowedDrop)
m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP);
else
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
}
m_inventorySerial++;
//m_inventorySerial += 2;
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
}
/// <summary>
/// Restore a whole collection of items to the prim's inventory at once.
/// We assume that the items already have all their fields correctly filled out.
/// The items are not flagged for persistence to the database, since they are being restored
/// from persistence rather than being newly added.
/// </summary>
/// <param name="items"></param>
public void RestoreInventoryItems(ICollection<TaskInventoryItem> items)
{
lock (m_items)
{
foreach (TaskInventoryItem item in items)
{
m_items.Add(item.ItemID, item);
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
}
}
m_inventorySerial++;
}
/// <summary>
/// Returns an existing inventory item. Returns the original, so any changes will be live.
/// </summary>
/// <param name="itemID"></param>
/// <returns>null if the item does not exist</returns>
public TaskInventoryItem GetInventoryItem(UUID itemId)
{
TaskInventoryItem item;
lock (m_items)
m_items.TryGetValue(itemId, out item);
return item;
}
/// <summary>
/// Get inventory items by name.
/// </summary>
/// <param name="name"></param>
/// <returns>
/// A list of inventory items with that name.
/// If no inventory item has that name then an empty list is returned.
/// </returns>
public IList<TaskInventoryItem> GetInventoryItems(string name)
{
IList<TaskInventoryItem> items = new List<TaskInventoryItem>();
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.Name == name)
items.Add(item);
}
}
return items;
}
/// <summary>
/// Update an existing inventory item.
/// </summary>
/// <param name="item">The updated item. An item with the same id must already exist
/// in this prim's inventory.</param>
/// <returns>false if the item did not exist, true if the update occurred successfully</returns>
public bool UpdateInventoryItem(TaskInventoryItem item)
{
lock (m_items)
{
if (m_items.ContainsKey(item.ItemID))
{
item.ParentID = m_part.UUID;
item.ParentPartID = m_part.UUID;
item.Flags = m_items[item.ItemID].Flags;
if (item.AssetID == UUID.Zero)
{
item.AssetID = m_items[item.ItemID].AssetID;
}
else if ((InventoryType)item.Type == InventoryType.Notecard)
{
ScenePresence presence = m_part.ParentGroup.Scene.GetScenePresence(item.OwnerID);
if (presence != null)
{
presence.ControllingClient.SendAgentAlertMessage(
"Notecard saved", false);
}
}
m_items[item.ItemID] = item;
m_inventorySerial++;
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Tried to retrieve item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory",
item.ItemID, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
}
return false;
}
/// <summary>
/// Remove an item from this prim's inventory
/// </summary>
/// <param name="itemID"></param>
/// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist
/// in this prim's inventory.</returns>
public int RemoveInventoryItem(UUID itemID)
{
lock (m_items)
{
if (m_items.ContainsKey(itemID))
{
int type = m_items[itemID].InvType;
if (type == 10) // Script
{
m_part.RemoveScriptEvents(itemID);
m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID);
}
m_items.Remove(itemID);
m_inventorySerial++;
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
int scriptcount = 0;
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.Type == 10)
{
scriptcount++;
}
}
}
if (scriptcount <= 0)
{
m_part.RemFlag(PrimFlags.Scripted);
}
m_part.ScheduleFullUpdate();
return type;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Tried to remove item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory",
itemID, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
}
return -1;
}
public string GetInventoryFileName()
{
if (m_inventoryFileName == String.Empty)
m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp";
if (m_inventoryFileNameSerial < m_inventorySerial)
{
m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp";
}
return m_inventoryFileName;
}
/// <summary>
/// Return the name with which a client can request a xfer of this prim's inventory metadata
/// </summary>
/// <param name="client"></param>
/// <param name="localID"></param>
public bool GetInventoryFileName(IClientAPI client, uint localID)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Received request from client {0} for inventory file name of {1}, {2}",
// client.AgentId, Name, UUID);
if (m_inventorySerial > 0)
{
client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
Utils.StringToBytes(GetInventoryFileName()));
return true;
}
else
{
client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
return false;
}
}
/// <summary>
/// Serialize all the metadata for the items in this prim's inventory ready for sending to the client
/// </summary>
/// <param name="xferManager"></param>
public void RequestInventoryFile(IClientAPI client, IXfer xferManager)
{
byte[] fileData = new byte[0];
// Confusingly, the folder item has to be the object id, while the 'parent id' has to be zero. This matches
// what appears to happen in the Second Life protocol. If this isn't the case. then various functionality
// isn't available (such as drag from prim inventory to agent inventory)
InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
UUID ownerID = item.OwnerID;
uint everyoneMask = 0;
uint baseMask = item.BasePermissions;
uint ownerMask = item.CurrentPermissions;
invString.AddItemStart();
invString.AddNameValueLine("item_id", item.ItemID.ToString());
invString.AddNameValueLine("parent_id", m_part.UUID.ToString());
invString.AddPermissionsStart();
invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
invString.AddNameValueLine("group_mask", Utils.UIntToHexString(0));
invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
invString.AddNameValueLine("owner_id", ownerID.ToString());
invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());
invString.AddNameValueLine("group_id", item.GroupID.ToString());
invString.AddSectionEnd();
invString.AddNameValueLine("asset_id", item.AssetID.ToString());
invString.AddNameValueLine("type", TaskInventoryItem.Types[item.Type]);
invString.AddNameValueLine("inv_type", TaskInventoryItem.InvTypes[item.InvType]);
invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags));
invString.AddSaleStart();
invString.AddNameValueLine("sale_type", "not");
invString.AddNameValueLine("sale_price", "0");
invString.AddSectionEnd();
invString.AddNameValueLine("name", item.Name + "|");
invString.AddNameValueLine("desc", item.Description + "|");
invString.AddNameValueLine("creation_date", item.CreationDate.ToString());
invString.AddSectionEnd();
}
}
fileData = Utils.StringToBytes(invString.BuildString);
//m_log.Debug(Utils.BytesToString(fileData));
//m_log.Debug("[PRIM INVENTORY]: RequestInventoryFile fileData: " + Utils.BytesToString(fileData));
if (fileData.Length > 2)
{
xferManager.AddNewFile(m_inventoryFileName, fileData);
}
}
/// <summary>
/// Process inventory backup
/// </summary>
/// <param name="datastore"></param>
public void ProcessInventoryBackup(IRegionDataStore datastore)
{
if (HasInventoryChanged)
{
lock (Items)
{
datastore.StorePrimInventory(m_part.UUID, Items.Values);
}
HasInventoryChanged = false;
}
}
public class InventoryStringBuilder
{
public string BuildString = String.Empty;
public InventoryStringBuilder(UUID folderID, UUID parentID)
{
BuildString += "\tinv_object\t0\n\t{\n";
AddNameValueLine("obj_id", folderID.ToString());
AddNameValueLine("parent_id", parentID.ToString());
AddNameValueLine("type", "category");
AddNameValueLine("name", "Contents|");
AddSectionEnd();
}
public void AddItemStart()
{
BuildString += "\tinv_item\t0\n";
AddSectionStart();
}
public void AddPermissionsStart()
{
BuildString += "\tpermissions 0\n";
AddSectionStart();
}
public void AddSaleStart()
{
BuildString += "\tsale_info\t0\n";
AddSectionStart();
}
protected void AddSectionStart()
{
BuildString += "\t{\n";
}
public void AddSectionEnd()
{
BuildString += "\t}\n";
}
public void AddLine(string addLine)
{
BuildString += addLine;
}
public void AddNameValueLine(string name, string value)
{
BuildString += "\t\t";
BuildString += name + "\t";
BuildString += value + "\n";
}
public void Close()
{
}
}
public uint MaskEffectivePermissions()
{
uint mask=0x7fffffff;
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.InvType != (int)InventoryType.Object)
{
if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0)
mask &= ~((uint)PermissionMask.Copy >> 13);
if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0)
mask &= ~((uint)PermissionMask.Transfer >> 13);
if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0)
mask &= ~((uint)PermissionMask.Modify >> 13);
}
else
{
if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
mask &= ~((uint)PermissionMask.Copy >> 13);
if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
mask &= ~((uint)PermissionMask.Transfer >> 13);
if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
mask &= ~((uint)PermissionMask.Modify >> 13);
}
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
mask &= ~(uint)PermissionMask.Copy;
if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
mask &= ~(uint)PermissionMask.Transfer;
if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0)
mask &= ~(uint)PermissionMask.Modify;
}
}
return mask;
}
public void ApplyNextOwnerPermissions()
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0)
{
if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
item.CurrentPermissions |= 8;
}
item.CurrentPermissions &= item.NextPermissions;
item.BasePermissions &= item.NextPermissions;
item.EveryonePermissions &= item.NextPermissions;
}
}
m_part.TriggerScriptChangedEvent(Changed.OWNER);
}
public void ApplyGodPermissions(uint perms)
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
item.CurrentPermissions = perms;
item.BasePermissions = perms;
}
}
}
public bool ContainsScripts()
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.InvType == (int)InventoryType.LSL)
{
return true;
}
}
}
return false;
}
public List<UUID> GetInventoryList()
{
List<UUID> ret = new List<UUID>();
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
ret.Add(item.ItemID);
}
return ret;
}
public Dictionary<UUID, string> GetScriptStates()
{
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
Dictionary<UUID, string> ret = new Dictionary<UUID, string>();
if (engines == null) // No engine at all
return ret;
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.InvType == (int)InventoryType.LSL)
{
foreach (IScriptModule e in engines)
{
if (e != null)
{
string n = e.GetXMLState(item.ItemID);
if (n != String.Empty)
{
if (!ret.ContainsKey(item.ItemID))
ret[item.ItemID] = n;
break;
}
}
}
}
}
}
return ret;
}
}
}
| |
using ClosedXML.Extensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ClosedXML.Excel
{
internal struct XLRangeAddress : IXLRangeAddress, IEquatable<XLRangeAddress>
{
#region Static members
public static XLRangeAddress EntireColumn(XLWorksheet worksheet, int column)
{
return new XLRangeAddress(
new XLAddress(worksheet, 1, column, false, false),
new XLAddress(worksheet, XLHelper.MaxRowNumber, column, false, false));
}
public static XLRangeAddress EntireRow(XLWorksheet worksheet, int row)
{
return new XLRangeAddress(
new XLAddress(worksheet, row, 1, false, false),
new XLAddress(worksheet, row, XLHelper.MaxColumnNumber, false, false));
}
#endregion Static members
#region Constructor
public XLRangeAddress(XLAddress firstAddress, XLAddress lastAddress) : this()
{
Worksheet = firstAddress.Worksheet;
FirstAddress = firstAddress;
LastAddress = lastAddress;
}
public XLRangeAddress(XLWorksheet worksheet, String rangeAddress) : this()
{
string addressToUse = rangeAddress.Contains("!")
? rangeAddress.Substring(rangeAddress.IndexOf("!") + 1)
: rangeAddress;
string firstPart;
string secondPart;
if (addressToUse.Contains(':'))
{
var arrRange = addressToUse.Split(':');
firstPart = arrRange[0];
secondPart = arrRange[1];
}
else
{
firstPart = addressToUse;
secondPart = addressToUse;
}
if (XLHelper.IsValidA1Address(firstPart))
{
FirstAddress = XLAddress.Create(worksheet, firstPart);
LastAddress = XLAddress.Create(worksheet, secondPart);
}
else
{
firstPart = firstPart.Replace("$", String.Empty);
secondPart = secondPart.Replace("$", String.Empty);
if (char.IsDigit(firstPart[0]))
{
FirstAddress = XLAddress.Create(worksheet, "A" + firstPart);
LastAddress = XLAddress.Create(worksheet, XLHelper.MaxColumnLetter + secondPart);
}
else
{
FirstAddress = XLAddress.Create(worksheet, firstPart + "1");
LastAddress = XLAddress.Create(worksheet, secondPart + XLHelper.MaxRowNumber.ToInvariantString());
}
}
Worksheet = worksheet;
}
#endregion Constructor
#region Public properties
public XLWorksheet Worksheet { get; }
public XLAddress FirstAddress { get; }
public XLAddress LastAddress { get; }
IXLWorksheet IXLRangeAddress.Worksheet
{
get { return Worksheet; }
}
IXLAddress IXLRangeAddress.FirstAddress
{
[DebuggerStepThrough]
get { return FirstAddress; }
}
IXLAddress IXLRangeAddress.LastAddress
{
[DebuggerStepThrough]
get { return LastAddress; }
}
public bool IsValid
{
get
{
return FirstAddress.IsValid &&
LastAddress.IsValid;
}
}
#endregion Public properties
#region Public methods
/// <summary>
/// Lead a range address to a normal form - when <see cref="FirstAddress"/> points to the top-left address and
/// <see cref="LastAddress"/> points to the bottom-right address.
/// </summary>
/// <returns></returns>
public XLRangeAddress Normalize()
{
if (FirstAddress.RowNumber <= LastAddress.RowNumber &&
FirstAddress.ColumnNumber <= LastAddress.ColumnNumber)
return this;
int firstRow, firstColumn, lastRow, lastColumn;
bool firstRowFixed, firstColumnFixed, lastRowFixed, lastColumnFixed;
if (FirstAddress.RowNumber <= LastAddress.RowNumber)
{
firstRow = FirstAddress.RowNumber;
firstRowFixed = FirstAddress.FixedRow;
lastRow = LastAddress.RowNumber;
lastRowFixed = LastAddress.FixedRow;
}
else
{
firstRow = LastAddress.RowNumber;
firstRowFixed = LastAddress.FixedRow;
lastRow = FirstAddress.RowNumber;
lastRowFixed = FirstAddress.FixedRow;
}
if (FirstAddress.ColumnNumber <= LastAddress.ColumnNumber)
{
firstColumn = FirstAddress.ColumnNumber;
firstColumnFixed = FirstAddress.FixedColumn;
lastColumn = LastAddress.ColumnNumber;
lastColumnFixed = LastAddress.FixedColumn;
}
else
{
firstColumn = LastAddress.ColumnNumber;
firstColumnFixed = LastAddress.FixedColumn;
lastColumn = FirstAddress.ColumnNumber;
lastColumnFixed = FirstAddress.FixedColumn;
}
return new XLRangeAddress(
new XLAddress(FirstAddress.Worksheet, firstRow, firstColumn, firstRowFixed, firstColumnFixed),
new XLAddress(LastAddress.Worksheet, lastRow, lastColumn, lastRowFixed, lastColumnFixed));
}
public String ToStringRelative()
{
return ToStringRelative(false);
}
public String ToStringFixed()
{
return ToStringFixed(XLReferenceStyle.A1);
}
public String ToStringRelative(Boolean includeSheet)
{
if (includeSheet)
return String.Concat(
Worksheet.Name.EscapeSheetName(),
'!',
FirstAddress.ToStringRelative(),
':',
LastAddress.ToStringRelative());
else
return string.Concat(
FirstAddress.ToStringRelative(),
":",
LastAddress.ToStringRelative());
}
public bool Intersects(IXLRangeAddress otherAddress)
{
var xlOtherAddress = (XLRangeAddress)otherAddress;
return Intersects(in xlOtherAddress);
}
internal bool Intersects(in XLRangeAddress otherAddress)
{
return !( // See if the two ranges intersect...
otherAddress.FirstAddress.ColumnNumber > LastAddress.ColumnNumber
|| otherAddress.LastAddress.ColumnNumber < FirstAddress.ColumnNumber
|| otherAddress.FirstAddress.RowNumber > LastAddress.RowNumber
|| otherAddress.LastAddress.RowNumber < FirstAddress.RowNumber
);
}
public bool Contains(IXLAddress address)
{
var xlAddress = (XLAddress)address;
return Contains(in xlAddress);
}
internal IXLRangeAddress WithoutWorksheet()
{
return new XLRangeAddress(
FirstAddress.WithoutWorksheet(),
LastAddress.WithoutWorksheet());
}
internal bool Contains(in XLAddress address)
{
return FirstAddress.RowNumber <= address.RowNumber &&
address.RowNumber <= LastAddress.RowNumber &&
FirstAddress.ColumnNumber <= address.ColumnNumber &&
address.ColumnNumber <= LastAddress.ColumnNumber;
}
public String ToStringFixed(XLReferenceStyle referenceStyle)
{
return ToStringFixed(referenceStyle, false);
}
public String ToStringFixed(XLReferenceStyle referenceStyle, Boolean includeSheet)
{
if (includeSheet)
return String.Format("{0}!{1}:{2}",
Worksheet.Name.EscapeSheetName(),
FirstAddress.ToStringFixed(referenceStyle),
LastAddress.ToStringFixed(referenceStyle));
return FirstAddress.ToStringFixed(referenceStyle) + ":" + LastAddress.ToStringFixed(referenceStyle);
}
public override string ToString()
{
return String.Concat(FirstAddress, ':', LastAddress);
}
public string ToString(XLReferenceStyle referenceStyle)
{
return ToString(referenceStyle, false);
}
public string ToString(XLReferenceStyle referenceStyle, bool includeSheet)
{
if (referenceStyle == XLReferenceStyle.R1C1)
return ToStringFixed(referenceStyle, true);
else
return ToStringRelative(includeSheet);
}
public override bool Equals(object obj)
{
if (!(obj is XLRangeAddress))
{
return false;
}
var address = (XLRangeAddress)obj;
return FirstAddress.Equals(address.FirstAddress) &&
LastAddress.Equals(address.LastAddress) &&
EqualityComparer<XLWorksheet>.Default.Equals(Worksheet, address.Worksheet);
}
public override int GetHashCode()
{
var hashCode = -778064135;
hashCode = hashCode * -1521134295 + FirstAddress.GetHashCode();
hashCode = hashCode * -1521134295 + LastAddress.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<XLWorksheet>.Default.GetHashCode(Worksheet);
return hashCode;
}
public bool Equals(XLRangeAddress other)
{
return ReferenceEquals(Worksheet, other.Worksheet) &&
FirstAddress == other.FirstAddress &&
LastAddress == other.LastAddress;
}
#endregion Public methods
#region Operators
public static bool operator ==(XLRangeAddress left, XLRangeAddress right)
{
return left.Equals(right);
}
public static bool operator !=(XLRangeAddress left, XLRangeAddress right)
{
return !(left == right);
}
#endregion Operators
}
}
| |
#region MIT License
/*
* Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.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.
*/
#endregion
#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Drawing;
using System.IO;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Physics2DDotNet;
using Physics2DDotNet.PhysicsLogics;
using AdvanceMath;
using AdvanceMath.Geometry2D;
using System.Media;
using Tao.OpenGl;
using SdlDotNet.Core;
using SdlDotNet.Input;
using SdlDotNet.OpenGl;
using SdlDotNet.Graphics;
using Physics2DDotNet.Shapes;
using Physics2DDotNet.Joints;
using Physics2DDotNet.Ignorers;
using Graphics2DDotNet;
namespace Physics2DDotNet.Demo
{
public static class DemoStart
{
/// <summary>
/// Call this to start the demo
/// (Entry Point)
/// </summary>
public static void Run()
{
//do this becuase .Net has been erroring with file permissions
//just leave this line it.
string dir = Settings.DataDir;
//create a new window to display stuff
Window window = new Window(new System.Drawing.Size(1000, 750));
window.Title = "Physics2D.Net Demo";
//Create a new Scene
Scene scene = new Scene();
//Get the scene's physics engine
PhysicsEngine physicsEngine = scene.Engine;
//initialize the engine
physicsEngine.BroadPhase = new Physics2DDotNet.Detectors.SweepAndPruneDetector();
//physicsEngine.BroadPhase = new Physics2DDotNet.Detectors.SpatialHashDetector();
Physics2DDotNet.Solvers.SequentialImpulsesSolver solver= new Physics2DDotNet.Solvers.SequentialImpulsesSolver();
//solver.Iterations = 3;
solver.Freezing = true;
physicsEngine.Solver = solver;
//physicsEngine.Solver = new Physics2DDotNet.Solvers.Box2DSolver();
Viewport viewport = new Viewport(
new Rectangle(0, 0, window.Size.Width, window.Size.Height), //where
Matrix2x3.Identity, //how
scene, //who
new Lifespan()); // how long
window.AddViewport(viewport);
// you can change the veiwport via this
viewport.ToScreen = Matrix2x3.FromTransformation(.09f, new Vector2D(40, 0));
//make it so the veiwport will be resized whn the window is
window.Resized += delegate(object sender, SizeEventArgs e)
{
viewport.Width = e.Width;
viewport.Height = e.Height;
};
System.Windows.Forms.Application.EnableVisualStyles();
//create the GUI
DemoSelector selector = new DemoSelector();
//initialize the GUI
selector.Initialize(window, viewport, scene);
//Create the window
window.Intialize();
window.DrawingInterval = .02f;
//Add some intro text
AddIntroText(window, viewport, scene);
SetupStatus(window, scene);
//Show the GUI
selector.Show();
//start the physicstimer for Layer.PhysicsEngine
scene.Timer.IsRunning = true;
//Begin the rendering loop.
window.Run();
return;
}
//below here is code that displays the fps, ups and so on.
static string numberString = "0123456789";
static SurfacePolygons[] numbers2;
static IShape[] numbers;
private static void AddIntroText(Window window, Viewport viewport, Scene scene)
{
DemoHelper.AddText(
new DemoOpenInfo(window, viewport, scene),
@"WELCOME TO THE PHYSICS2D.NET DEMO.
PLEASE ENJOY MESSING WITH IT.
A LOT OF HARD WORK WENT INTO IT,
SO THAT YOU COULD ENJOY IT.
PLEASE SEND FEEDBACK.
EACH CHARACTER HERE IS AN
ACTUAL BODY IN THE ENGINE.
THIS IS TO SHOW OFF THE BITMAP
TO POLYGON ALGORITHM.
LOAD THE INTRO TEXT DEMO TO MANIPULATE
THIS TEXT.", new Vector2D(20, 20), 40);
}
/// <summary>
/// creates a overlay scene to display status text.
/// </summary>
/// <param name="window"></param>
/// <param name="scene"></param>
private static void SetupStatus(Window window, Scene scene)
{
Scene scene2 = new Scene();
PhysicsEngine physicsEngine2 = scene2.Engine;
physicsEngine2.BroadPhase = new Physics2DDotNet.Detectors.SelectiveSweepDetector();
//physicsEngine.BroadPhase = new Physics2DDotNet.Detectors.SpatialHashDetector();
Physics2DDotNet.Solvers.SequentialImpulsesSolver solver = new Physics2DDotNet.Solvers.SequentialImpulsesSolver();
solver.Iterations = 1;
physicsEngine2.Solver = solver;
Viewport viewport2 = new Viewport(
new Rectangle(0, 0, window.Size.Width, window.Size.Height), //where
Matrix2x3.Identity, //how
scene2, //who
new Lifespan()); // how long
window.AddViewport(viewport2);
window.Resized += delegate(object sender, SizeEventArgs e)
{
viewport2.Width = e.Width;
viewport2.Height = e.Height;
};
numbers = new IShape[10];
numbers2 = new SurfacePolygons[10];
for (int index = 0; index < numbers.Length; ++index)
{
numbers2[index] = Cache<SurfacePolygons>.GetItem(numberString[index] + "|FreeSans.ttf:20", Color.Black);
numbers[index] = ShapeFactory.CreateSprite(numbers2[index], 0, 8, 2);
SpriteDrawable s = numbers[index].Tag as SpriteDrawable;
s.Color = new ScalarColor4(.1f, .1f, 1, 1);
}
DoBodyCount(window, viewport2, scene, scene2, new Vector2D(100, 2));
DoJointCount(window, viewport2, scene, scene2, new Vector2D(100, 30));
DoLogicsCount(window, viewport2, scene, scene2, new Vector2D(270, 2));
DoFPS(window, viewport2, scene, scene2, new Vector2D(2, 2));
DoUPS(window, viewport2, scene, scene2, new Vector2D(2, 30));
}
private static void DoUPS(Window window, Viewport viewport2, Scene scene1, Scene scene2, Vector2D pos)
{
List<Body> bodies = DemoHelper.AddText(new DemoOpenInfo(window, viewport2, scene2), "UPS: 000", pos,20);
foreach (Body body in bodies)
{
SpriteDrawable s = body.Shape.Tag as SpriteDrawable;
s.Color = new ScalarColor4(.1f, .1f, 1, 1);
}
bodies.RemoveRange(0, 4);
Vector2D[] positions = new Vector2D[bodies.Count];
for (int index = 0; index < positions.Length; index++)
{
positions[index] = bodies[index].State.Position.Linear - numbers2[0].Offset;
}
int frames = 50;
Scalar frameSeconds = 1;
scene1.Engine.Updated += delegate(object sender, UpdatedEventArgs e)
{
if (frames >= 10)
{
frames /= 2;
frameSeconds /= 2;
}
frames++;
frameSeconds += e.Step.TrueDt;
int ups = (int)(frames / frameSeconds);
if (ups < 0) { ups = 0; }
string val = ups.ToString();
SetBodiesText(bodies, positions, val);
};
}
private static void DoFPS(Window window, Viewport viewport2, Scene scene1, Scene scene2, Vector2D pos)
{
List<Body> bodies = DemoHelper.AddText(new DemoOpenInfo(window, viewport2, scene2), "FPS: 000", pos,20);
foreach (Body body in bodies)
{
SpriteDrawable s = body.Shape.Tag as SpriteDrawable;
s.Color = new ScalarColor4(.1f, .1f, 1, 1);
}
bodies.RemoveRange(0, 4);
Vector2D[] positions = new Vector2D[bodies.Count];
for (int index = 0; index < positions.Length; index++)
{
positions[index] = bodies[index].State.Position.Linear - numbers2[0].Offset;
}
int frames = 100;
Scalar frameSeconds = 1;
viewport2.BeginDrawing += delegate(object sender, DrawEventArgs e)
{
if (frames >= 10)
{
frames /= 2;
frameSeconds /= 2;
}
frames++;
frameSeconds += e.DrawInfo.TrueDt;
int ups = (int)(frames / frameSeconds);
if (ups < 0) { ups = 0; }
string val = ups.ToString();
SetBodiesText(bodies, positions, val);
};
}
private static void DoLogicsCount(Window window, Viewport viewport2, Scene scene1, Scene scene2, Vector2D pos)
{
List<Body> bodies = DemoHelper.AddText(new DemoOpenInfo(window, viewport2, scene2), "Logics: 000000", pos, 20);
foreach (Body body in bodies)
{
SpriteDrawable s = body.Shape.Tag as SpriteDrawable;
s.Color = new ScalarColor4(.1f, .1f, 1, 1);
}
bodies.RemoveRange(0, 7);
Vector2D[] positions = new Vector2D[bodies.Count];
for (int index = 0; index < positions.Length; index++)
{
positions[index] = bodies[index].State.Position.Linear - numbers2[0].Offset;
}
EventHandler<CollectionEventArgs<PhysicsLogic>> handler = delegate(object sender, CollectionEventArgs<PhysicsLogic> e)
{
string val = scene1.Engine.Logics.Count.ToString();
SetBodiesText(bodies, positions, val);
};
scene1.Engine.LogicsAdded += handler;
scene1.Engine.LogicsRemoved += handler;
}
private static void DoJointCount(Window window, Viewport viewport2, Scene scene1, Scene scene2, Vector2D pos)
{
List<Body> bodies = DemoHelper.AddText(new DemoOpenInfo(window, viewport2, scene2), "Joints: 000000", pos, 20);
foreach (Body body in bodies)
{
SpriteDrawable s = body.Shape.Tag as SpriteDrawable;
s.Color = new ScalarColor4(.1f, .1f, 1, 1);
}
bodies.RemoveRange(0, 7);
Vector2D[] positions = new Vector2D[bodies.Count];
for (int index = 0; index < positions.Length; index++)
{
positions[index] = bodies[index].State.Position.Linear - numbers2[0].Offset;
}
EventHandler<CollectionEventArgs<Joint>> handler = delegate(object sender, CollectionEventArgs<Joint> e)
{
string val = scene1.Engine.Joints.Count.ToString();
SetBodiesText(bodies, positions, val);
};
scene1.Engine.JointsAdded += handler;
scene1.Engine.JointsRemoved += handler;
}
private static void DoBodyCount(Window window, Viewport viewport2, Scene scene1, Scene scene2, Vector2D pos)
{
List<Body> bodies = DemoHelper.AddText(new DemoOpenInfo(window, viewport2, scene2), "Bodies: 000000", pos,20);
foreach (Body body in bodies)
{
SpriteDrawable s = body.Shape.Tag as SpriteDrawable;
s.Color = new ScalarColor4(.1f, .1f, 1, 1);
}
bodies.RemoveRange(0, 7);
Vector2D[] positions = new Vector2D[bodies.Count];
for (int index = 0; index < positions.Length; index++)
{
positions[index] = bodies[index].State.Position.Linear - numbers2[0].Offset;
}
EventHandler<CollectionEventArgs<Body>> handler = delegate(object sender, CollectionEventArgs<Body> e)
{
string val = scene1.Engine.Bodies.Count.ToString();
SetBodiesText(bodies, positions, val);
};
scene1.Engine.BodiesAdded += handler;
scene1.Engine.BodiesRemoved += handler;
}
private static void SetBodiesText(List<Body> bodies, Vector2D[] positions, string val)
{
int offset = bodies.Count - val.Length;
for (int index = 0; index < offset; ++index)
{
bodies[index].Shape = numbers[0];
bodies[index].State.Position.Linear = positions[index] + numbers2[0].Offset;
bodies[index].ApplyPosition();
}
for (int index = 0; index < val.Length; ++index)
{
int number = numberString.IndexOf(val[index]);
bodies[index + offset].Shape = numbers[number];
bodies[index + offset].State.Position.Linear = positions[index + offset] + numbers2[number].Offset;
bodies[index + offset].ApplyPosition();
}
}
}
}
| |
namespace Humidifier.SSM
{
using System.Collections.Generic;
using MaintenanceWindowTaskTypes;
public class MaintenanceWindowTask : Humidifier.Resource
{
public override string AWSTypeName
{
get
{
return @"AWS::SSM::MaintenanceWindowTask";
}
}
/// <summary>
/// MaxErrors
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-maxerrors
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MaxErrors
{
get;
set;
}
/// <summary>
/// Description
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-description
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Description
{
get;
set;
}
/// <summary>
/// ServiceRoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-servicerolearn
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ServiceRoleArn
{
get;
set;
}
/// <summary>
/// Priority
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-priority
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Priority
{
get;
set;
}
/// <summary>
/// MaxConcurrency
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-maxconcurrency
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MaxConcurrency
{
get;
set;
}
/// <summary>
/// Targets
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-targets
/// Required: True
/// UpdateType: Mutable
/// Type: List
/// ItemType: Target
/// </summary>
public List<Target> Targets
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
/// <summary>
/// TaskArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-taskarn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic TaskArn
{
get;
set;
}
/// <summary>
/// TaskInvocationParameters
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters
/// Required: False
/// UpdateType: Mutable
/// Type: TaskInvocationParameters
/// </summary>
public TaskInvocationParameters TaskInvocationParameters
{
get;
set;
}
/// <summary>
/// WindowId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-windowid
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic WindowId
{
get;
set;
}
/// <summary>
/// TaskParameters
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-taskparameters
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Json
/// </summary>
public dynamic TaskParameters
{
get;
set;
}
/// <summary>
/// TaskType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-tasktype
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic TaskType
{
get;
set;
}
/// <summary>
/// LoggingInfo
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-logginginfo
/// Required: False
/// UpdateType: Mutable
/// Type: LoggingInfo
/// </summary>
public LoggingInfo LoggingInfo
{
get;
set;
}
}
namespace MaintenanceWindowTaskTypes
{
public class LoggingInfo
{
/// <summary>
/// S3Bucket
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-logginginfo.html#cfn-ssm-maintenancewindowtask-logginginfo-s3bucket
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic S3Bucket
{
get;
set;
}
/// <summary>
/// Region
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-logginginfo.html#cfn-ssm-maintenancewindowtask-logginginfo-region
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Region
{
get;
set;
}
/// <summary>
/// S3Prefix
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-logginginfo.html#cfn-ssm-maintenancewindowtask-logginginfo-s3prefix
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic S3Prefix
{
get;
set;
}
}
public class Target
{
/// <summary>
/// Values
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-target.html#cfn-ssm-maintenancewindowtask-target-values
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Values
{
get;
set;
}
/// <summary>
/// Key
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-target.html#cfn-ssm-maintenancewindowtask-target-key
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Key
{
get;
set;
}
}
public class MaintenanceWindowRunCommandParameters
{
/// <summary>
/// TimeoutSeconds
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-timeoutseconds
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic TimeoutSeconds
{
get;
set;
}
/// <summary>
/// Comment
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-comment
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Comment
{
get;
set;
}
/// <summary>
/// OutputS3KeyPrefix
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-outputs3keyprefix
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic OutputS3KeyPrefix
{
get;
set;
}
/// <summary>
/// Parameters
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-parameters
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Json
/// </summary>
public dynamic Parameters
{
get;
set;
}
/// <summary>
/// DocumentHashType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-documenthashtype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DocumentHashType
{
get;
set;
}
/// <summary>
/// ServiceRoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-servicerolearn
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ServiceRoleArn
{
get;
set;
}
/// <summary>
/// NotificationConfig
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-notificationconfig
/// Required: False
/// UpdateType: Mutable
/// Type: NotificationConfig
/// </summary>
public NotificationConfig NotificationConfig
{
get;
set;
}
/// <summary>
/// OutputS3BucketName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-outputs3bucketname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic OutputS3BucketName
{
get;
set;
}
/// <summary>
/// DocumentHash
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-documenthash
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DocumentHash
{
get;
set;
}
}
public class MaintenanceWindowLambdaParameters
{
/// <summary>
/// ClientContext
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowlambdaparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowlambdaparameters-clientcontext
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ClientContext
{
get;
set;
}
/// <summary>
/// Qualifier
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowlambdaparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowlambdaparameters-qualifier
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Qualifier
{
get;
set;
}
/// <summary>
/// Payload
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowlambdaparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowlambdaparameters-payload
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Payload
{
get;
set;
}
}
public class NotificationConfig
{
/// <summary>
/// NotificationArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-notificationconfig.html#cfn-ssm-maintenancewindowtask-notificationconfig-notificationarn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic NotificationArn
{
get;
set;
}
/// <summary>
/// NotificationType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-notificationconfig.html#cfn-ssm-maintenancewindowtask-notificationconfig-notificationtype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic NotificationType
{
get;
set;
}
/// <summary>
/// NotificationEvents
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-notificationconfig.html#cfn-ssm-maintenancewindowtask-notificationconfig-notificationevents
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic NotificationEvents
{
get;
set;
}
}
public class MaintenanceWindowAutomationParameters
{
/// <summary>
/// Parameters
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowautomationparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowautomationparameters-parameters
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Json
/// </summary>
public dynamic Parameters
{
get;
set;
}
/// <summary>
/// DocumentVersion
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowautomationparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowautomationparameters-documentversion
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DocumentVersion
{
get;
set;
}
}
public class TaskInvocationParameters
{
/// <summary>
/// MaintenanceWindowRunCommandParameters
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters-maintenancewindowruncommandparameters
/// Required: False
/// UpdateType: Mutable
/// Type: MaintenanceWindowRunCommandParameters
/// </summary>
public MaintenanceWindowRunCommandParameters MaintenanceWindowRunCommandParameters
{
get;
set;
}
/// <summary>
/// MaintenanceWindowAutomationParameters
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters-maintenancewindowautomationparameters
/// Required: False
/// UpdateType: Mutable
/// Type: MaintenanceWindowAutomationParameters
/// </summary>
public MaintenanceWindowAutomationParameters MaintenanceWindowAutomationParameters
{
get;
set;
}
/// <summary>
/// MaintenanceWindowStepFunctionsParameters
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters-maintenancewindowstepfunctionsparameters
/// Required: False
/// UpdateType: Mutable
/// Type: MaintenanceWindowStepFunctionsParameters
/// </summary>
public MaintenanceWindowStepFunctionsParameters MaintenanceWindowStepFunctionsParameters
{
get;
set;
}
/// <summary>
/// MaintenanceWindowLambdaParameters
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters-maintenancewindowlambdaparameters
/// Required: False
/// UpdateType: Mutable
/// Type: MaintenanceWindowLambdaParameters
/// </summary>
public MaintenanceWindowLambdaParameters MaintenanceWindowLambdaParameters
{
get;
set;
}
}
public class MaintenanceWindowStepFunctionsParameters
{
/// <summary>
/// Input
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowstepfunctionsparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowstepfunctionsparameters-input
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Input
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowstepfunctionsparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowstepfunctionsparameters-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Infrastructure.Common;
using System;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using Xunit;
public static class NegotiateStream_Tcp_Tests
{
// The tests are as follows:
//
// NegotiateStream_*_AmbientCredentials
// Windows: This should pass by default without any code changes
// Linux: This should not pass by default
// Run 'kinit user@DC.DOMAIN.COM' before running this test to use ambient credentials
// ('DC.DOMAIN.COM' must be in capital letters)
// If previous tests were run, it may be necessary to run 'kdestroy -A' to remove all
// prior Kerberos tickets
//
// NegotiateStream_*_With_ExplicitUserNameAndPassword
// Windows: Edit the s_UserName and s_Password variables to a user valid on your Kerberos realm
// Linux: Edit the s_UserName and s_Password variables to a user valid on your Kerberos realm
// If previous tests were run, it may be necessary to run 'kdestroy -A' to remove all
// prior Kerberos tickets
//
// NegotiateStream_*_With_ExplicitSpn
// Windows: Edit the s_Spn variable to match a valid SPN for the server
// Linux: Edit the s_Spn variable to match a valid SPN for the server
//
// By default, the SPN is the same as the host's fully qualified domain name, for example,
// 'host.domain.com'
// On a Windows host, one has to register the SPN using 'setspn', or run the process as LOCAL SYSTEM
// by using a tool like psexec and running 'psexec -s -h <WcfBridge.exe>'
//
// NegotiateStream_*_With_Upn
// Windows: Edit the s_Upn field to match a valid UPN for the server in the form of
// 'user@DOMAIN.COM'
// Linux: This scenario is not yet supported - dotnet/corefx#6606
//
// NegotiateStream_*_With_ExplicitUserNameAndPassword_With_Spn
// Windows: Edit the s_Spn variable to match a valid SPN for the server
// Edit the s_UserName and s_Password variables to a user valid on your Kerberos realm
// Linux: Edit the s_Spn variable to match a valid SPN for the server
// Edit the s_UserName and s_Password variables to a user valid on your Kerberos realm
//
// NegotiateStream_*_With_ExplicitUserNameAndPassword_With_Upn
// Windows: Edit the s_Upn variable to match a valid UPN for the server
// Edit the s_UserName and s_Password variables to a user valid on your Kerberos realm
// Linux: This scenario is not yet supported - dotnet/corefx#6606
// These tests are used for testing NegotiateStream (SecurityMode.Transport)
[Fact]
[ActiveIssue(1046)]
[ActiveIssue(851, PlatformID.AnyUnix)]
[OuterLoop]
public static void NegotiateStream_Tcp_AmbientCredentials()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_DefaultBinding_Address));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[ActiveIssue(851)]
[OuterLoop]
public static void NegotiateStream_Tcp_With_ExplicitUserNameAndPassword()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding();
factory = new ChannelFactory<IWcfService>(binding,
new EndpointAddress(Endpoints.Tcp_DefaultBinding_Address));
factory.Credentials.Windows.ClientCredential.Domain = NegotiateStreamTestConfiguration.Instance.NegotiateTestDomain;
factory.Credentials.Windows.ClientCredential.UserName = NegotiateStreamTestConfiguration.Instance.NegotiateTestUserName;
factory.Credentials.Windows.ClientCredential.Password = NegotiateStreamTestConfiguration.Instance.NegotiateTestPassword;
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[ActiveIssue(851)]
[OuterLoop]
public static void NegotiateStream_Tcp_With_ExplicitSpn()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding();
factory = new ChannelFactory<IWcfService>(binding,
new EndpointAddress(
new Uri(Endpoints.Tcp_DefaultBinding_Address),
new SpnEndpointIdentity(NegotiateStreamTestConfiguration.Instance.NegotiateTestSpn)
));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[ActiveIssue(851)]
[OuterLoop]
public static void NegotiateStream_Tcp_With_Upn()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding();
factory = new ChannelFactory<IWcfService>(
binding,
new EndpointAddress(
new Uri(Endpoints.Tcp_DefaultBinding_Address),
new SpnEndpointIdentity(NegotiateStreamTestConfiguration.Instance.NegotiateTestSpn)
));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[ActiveIssue(851)]
[OuterLoop]
public static void NegotiateStream_Tcp_With_ExplicitUserNameAndPassword_With_Spn()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding();
factory = new ChannelFactory<IWcfService>(
binding,
new EndpointAddress(
new Uri(Endpoints.Tcp_DefaultBinding_Address),
new SpnEndpointIdentity(NegotiateStreamTestConfiguration.Instance.NegotiateTestSpn)
));
factory.Credentials.Windows.ClientCredential.Domain = NegotiateStreamTestConfiguration.Instance.NegotiateTestDomain;
factory.Credentials.Windows.ClientCredential.UserName = NegotiateStreamTestConfiguration.Instance.NegotiateTestUserName;
factory.Credentials.Windows.ClientCredential.Password = NegotiateStreamTestConfiguration.Instance.NegotiateTestPassword;
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[Fact]
[ActiveIssue(851)]
[OuterLoop]
public static void NegotiateStream_Tcp_With_ExplicitUserNameAndPassword_With_Upn()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding();
factory = new ChannelFactory<IWcfService>(
binding,
new EndpointAddress(
new Uri(Endpoints.Tcp_DefaultBinding_Address),
new UpnEndpointIdentity(NegotiateStreamTestConfiguration.Instance.NegotiateTestUpn)
));
factory.Credentials.Windows.ClientCredential.Domain = NegotiateStreamTestConfiguration.Instance.NegotiateTestDomain;
factory.Credentials.Windows.ClientCredential.UserName = NegotiateStreamTestConfiguration.Instance.NegotiateTestUserName;
factory.Credentials.Windows.ClientCredential.Password = NegotiateStreamTestConfiguration.Instance.NegotiateTestPassword;
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
}
| |
/*
* 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.Collections.Generic;
using Amazon.Redshift.Model;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.Redshift.Model.Internal.MarshallTransformations
{
/// <summary>
/// Snapshot Unmarshaller
/// </summary>
internal class SnapshotUnmarshaller : IUnmarshaller<Snapshot, XmlUnmarshallerContext>, IUnmarshaller<Snapshot, JsonUnmarshallerContext>
{
public Snapshot Unmarshall(XmlUnmarshallerContext context)
{
Snapshot snapshot = new Snapshot();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
if (context.IsStartOfDocument)
targetDepth++;
while (context.Read())
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("SnapshotIdentifier", targetDepth))
{
snapshot.SnapshotIdentifier = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterIdentifier", targetDepth))
{
snapshot.ClusterIdentifier = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("SnapshotCreateTime", targetDepth))
{
snapshot.SnapshotCreateTime = DateTimeUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("Status", targetDepth))
{
snapshot.Status = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("Port", targetDepth))
{
snapshot.Port = IntUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("AvailabilityZone", targetDepth))
{
snapshot.AvailabilityZone = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterCreateTime", targetDepth))
{
snapshot.ClusterCreateTime = DateTimeUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("MasterUsername", targetDepth))
{
snapshot.MasterUsername = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterVersion", targetDepth))
{
snapshot.ClusterVersion = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("SnapshotType", targetDepth))
{
snapshot.SnapshotType = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("NodeType", targetDepth))
{
snapshot.NodeType = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("NumberOfNodes", targetDepth))
{
snapshot.NumberOfNodes = IntUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("DBName", targetDepth))
{
snapshot.DBName = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("VpcId", targetDepth))
{
snapshot.VpcId = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("Encrypted", targetDepth))
{
snapshot.Encrypted = BoolUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("AccountsWithRestoreAccess/AccountWithRestoreAccess", targetDepth))
{
snapshot.AccountsWithRestoreAccess.Add(AccountWithRestoreAccessUnmarshaller.GetInstance().Unmarshall(context));
continue;
}
if (context.TestExpression("OwnerAccount", targetDepth))
{
snapshot.OwnerAccount = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("TotalBackupSizeInMegaBytes", targetDepth))
{
snapshot.TotalBackupSizeInMegaBytes = DoubleUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("ActualIncrementalBackupSizeInMegaBytes", targetDepth))
{
snapshot.ActualIncrementalBackupSizeInMegaBytes = DoubleUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("BackupProgressInMegaBytes", targetDepth))
{
snapshot.BackupProgressInMegaBytes = DoubleUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("CurrentBackupRateInMegaBytesPerSecond", targetDepth))
{
snapshot.CurrentBackupRateInMegaBytesPerSecond = DoubleUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("EstimatedSecondsToCompletion", targetDepth))
{
snapshot.EstimatedSecondsToCompletion = LongUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("ElapsedTimeInSeconds", targetDepth))
{
snapshot.ElapsedTimeInSeconds = LongUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return snapshot;
}
}
return snapshot;
}
public Snapshot Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static SnapshotUnmarshaller instance;
public static SnapshotUnmarshaller GetInstance()
{
if (instance == null)
instance = new SnapshotUnmarshaller();
return instance;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
namespace System.Runtime.Versioning {
[Serializable]
public sealed class FrameworkName : IEquatable<FrameworkName> {
// ---- SECTION: members supporting exposed properties -------------*
#region members supporting exposed properties
readonly String m_identifier = null;
readonly Version m_version = null;
readonly String m_profile = null;
String m_fullName = null;
const Char c_componentSeparator = ',';
const Char c_keyValueSeparator = '=';
const Char c_versionValuePrefix = 'v';
const String c_versionKey = "Version";
const String c_profileKey = "Profile";
#endregion members supporting exposed properties
// ---- SECTION: public properties --------------*
#region public properties
public String Identifier {
get {
Contract.Assert(m_identifier != null);
return m_identifier;
}
}
public Version Version {
get {
Contract.Assert(m_version != null);
return m_version;
}
}
public String Profile {
get {
Contract.Assert(m_profile != null);
return m_profile;
}
}
public String FullName {
get {
if (m_fullName == null) {
StringBuilder sb = new StringBuilder();
sb.Append(Identifier);
sb.Append(c_componentSeparator);
sb.Append(c_versionKey).Append(c_keyValueSeparator);
sb.Append(c_versionValuePrefix);
sb.Append(Version);
if (!String.IsNullOrEmpty(Profile)) {
sb.Append(c_componentSeparator);
sb.Append(c_profileKey).Append(c_keyValueSeparator);
sb.Append(Profile);
}
m_fullName = sb.ToString();
}
Contract.Assert(m_fullName != null);
return m_fullName;
}
}
#endregion public properties
// ---- SECTION: public instance methods --------------*
#region public instance methods
public override Boolean Equals(Object obj) {
return Equals(obj as FrameworkName);
}
public Boolean Equals(FrameworkName other) {
if (Object.ReferenceEquals(other, null)) {
return false;
}
return Identifier == other.Identifier &&
Version == other.Version &&
Profile == other.Profile;
}
public override Int32 GetHashCode() {
return Identifier.GetHashCode() ^ Version.GetHashCode() ^ Profile.GetHashCode();
}
public override String ToString() {
return FullName;
}
#endregion public instance methods
// -------- SECTION: constructors -----------------*
#region constructors
public FrameworkName(String identifier, Version version)
: this(identifier, version, null) {}
public FrameworkName(String identifier, Version version, String profile) {
if (identifier == null) {
throw new ArgumentNullException("identifier");
}
if (identifier.Trim().Length == 0) {
throw new ArgumentException(SR.GetString(SR.net_emptystringcall, "identifier"), "identifier");
}
if (version == null) {
throw new ArgumentNullException("version");
}
Contract.EndContractBlock();
m_identifier = identifier.Trim();
m_version = (Version)version.Clone();
m_profile = (profile == null) ? String.Empty : profile.Trim();
}
// Parses strings in the following format: "<identifier>, Version=[v|V]<version>, Profile=<profile>"
// - The identifier and version is required, profile is optional
// - Only three components are allowed.
// - The version string must be in the System.Version format; an optional "v" or "V" prefix is allowed
public FrameworkName(String frameworkName) {
if (frameworkName == null) {
throw new ArgumentNullException("frameworkName");
}
if (frameworkName.Length == 0) {
throw new ArgumentException(SR.GetString(SR.net_emptystringcall, "frameworkName"), "frameworkName");
}
Contract.EndContractBlock();
string[] components = frameworkName.Split(c_componentSeparator);
// Identifer and Version are required, Profile is optional.
if (components.Length < 2 || components.Length > 3) {
throw new ArgumentException(SR.GetString(SR.Argument_FrameworkNameTooShort), "frameworkName");
}
//
// 1) Parse the "Identifier", which must come first. Trim any whitespace
//
m_identifier = components[0].Trim();
if (m_identifier.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_FrameworkNameInvalid), "frameworkName");
}
bool versionFound = false;
m_profile = String.Empty;
//
// The required "Version" and optional "Profile" component can be in any order
//
for (int i = 1; i < components.Length; i++) {
// Get the key/value pair separated by '='
string[] keyValuePair = components[i].Split(c_keyValueSeparator);
if (keyValuePair.Length != 2) {
throw new ArgumentException(SR.GetString(SR.Argument_FrameworkNameInvalid), "frameworkName");
}
// Get the key and value, trimming any whitespace
string key = keyValuePair[0].Trim();
string value = keyValuePair[1].Trim();
//
// 2) Parse the required "Version" key value
//
if (key.Equals(c_versionKey, StringComparison.OrdinalIgnoreCase)) {
versionFound = true;
// Allow the version to include a 'v' or 'V' prefix...
if (value.Length > 0 && (value[0] == c_versionValuePrefix || value[0] == 'V')) {
value = value.Substring(1);
}
try {
m_version = new Version(value);
}
catch (Exception e) {
throw new ArgumentException(SR.GetString(SR.Argument_FrameworkNameInvalidVersion), "frameworkName", e);
}
}
//
// 3) Parse the optional "Profile" key value
//
else if (key.Equals(c_profileKey, StringComparison.OrdinalIgnoreCase)) {
if (!String.IsNullOrEmpty(value)) {
m_profile = value;
}
}
else {
throw new ArgumentException(SR.GetString(SR.Argument_FrameworkNameInvalid), "frameworkName");
}
}
if (!versionFound) {
throw new ArgumentException(SR.GetString(SR.Argument_FrameworkNameMissingVersion), "frameworkName");
}
}
#endregion constructors
// -------- SECTION: public static methods -----------------*
#region public static methods
public static Boolean operator ==(FrameworkName left, FrameworkName right) {
if (Object.ReferenceEquals(left, null)) {
return Object.ReferenceEquals(right, null);
}
return left.Equals(right);
}
public static Boolean operator !=(FrameworkName left, FrameworkName right) {
return !(left == right);
}
#endregion public static methods
}
}
| |
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 FantasyAuctionWebRole.Areas.HelpPage.ModelDescriptions;
using FantasyAuctionWebRole.Areas.HelpPage.Models;
namespace FantasyAuctionWebRole.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using OpenSim.Region.ScriptEngine.Interfaces;
using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces
{
/// <summary>
/// To permit region owners to enable the extended scripting functionality
/// of OSSL, without allowing malicious scripts to access potentially
/// troublesome functions, each OSSL function is assigned a threat level,
/// and access to the functions is granted or denied based on a default
/// threshold set in OpenSim.ini (which can be overridden for individual
/// functions on a case-by-case basis)
/// </summary>
public enum ThreatLevel
{
// Not documented, presumably means permanently disabled ?
NoAccess = -1,
/// <summary>
/// Function is no threat at all. It doesn't constitute a threat to
/// either users or the system and has no known side effects.
/// </summary>
None = 0,
/// <summary>
/// Abuse of this command can cause a nuisance to the region operator,
/// such as log message spew.
/// </summary>
Nuisance = 1,
/// <summary>
/// Extreme levels of abuse of this function can cause impaired
/// functioning of the region, or very gullible users can be tricked
/// into experiencing harmless effects.
/// </summary>
VeryLow = 2,
/// <summary>
/// Intentional abuse can cause crashes or malfunction under certain
/// circumstances, which can be easily rectified; or certain users can
/// be tricked into certain situations in an avoidable manner.
/// </summary>
Low = 3,
/// <summary>
/// Intentional abuse can cause denial of service and crashes with
/// potential of data or state loss; or trusting users can be tricked
/// into embarrassing or uncomfortable situations.
/// </summary>
Moderate = 4,
/// <summary>
/// Casual abuse can cause impaired functionality or temporary denial
/// of service conditions. Intentional abuse can easily cause crashes
/// with potential data loss, or can be used to trick experienced and
/// cautious users into unwanted situations, or changes global data
/// permanently and without undo ability.
/// </summary>
High = 5,
/// <summary>
/// Even normal use may, depending on the number of instances, or
/// frequency of use, result in severe service impairment or crash
/// with loss of data, or can be used to cause unwanted or harmful
/// effects on users without giving the user a means to avoid it.
/// </summary>
VeryHigh = 6,
/// <summary>
/// Even casual use is a danger to region stability, or function allows
/// console or OS command execution, or function allows taking money
/// without consent, or allows deletion or modification of user data,
/// or allows the compromise of sensitive data by design.
/// </summary>
Severe = 7
};
public interface IOSSL_Api
{
void CheckThreatLevel(ThreatLevel level, string function);
//OpenSim functions
string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams, int timer);
string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams,
int timer, int alpha);
string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams,
bool blend, int disp, int timer, int alpha, int face);
string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams, int timer);
string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams,
int timer, int alpha);
string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams,
bool blend, int disp, int timer, int alpha, int face);
LSL_Float osGetTerrainHeight(int x, int y);
LSL_Float osTerrainGetHeight(int x, int y); // Deprecated
LSL_Integer osSetTerrainHeight(int x, int y, double val);
LSL_Integer osTerrainSetHeight(int x, int y, double val); //Deprecated
void osTerrainFlush();
int osRegionRestart(double seconds);
void osRegionNotice(string msg);
bool osConsoleCommand(string Command);
void osSetParcelMediaURL(string url);
void osSetPrimFloatOnWater(int floatYN);
void osSetParcelSIPAddress(string SIPAddress);
// Avatar Info Commands
string osGetAgentIP(string agent);
LSL_List osGetAgents();
// Teleport commands
void osTeleportAgent(string agent, string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat);
void osTeleportAgent(string agent, int regionX, int regionY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat);
void osTeleportAgent(string agent, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat);
void osTeleportOwner(string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat);
void osTeleportOwner(int regionX, int regionY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat);
void osTeleportOwner(LSL_Types.Vector3 position, LSL_Types.Vector3 lookat);
// Animation commands
void osAvatarPlayAnimation(string avatar, string animation);
void osAvatarStopAnimation(string avatar, string animation);
#region Attachment commands
/// <summary>
/// Attach the object containing this script to the avatar that owns it without asking for PERMISSION_ATTACH
/// </summary>
/// <param name='attachment'>The attachment point. For example, ATTACH_CHEST</param>
void osForceAttachToAvatar(int attachment);
/// <summary>
/// Attach an inventory item in the object containing this script to the avatar that owns it without asking for PERMISSION_ATTACH
/// </summary>
/// <remarks>
/// Nothing happens if the owner is not in the region.
/// </remarks>
/// <param name='itemName'>Tha name of the item. If this is not found then a warning is said to the owner</param>
/// <param name='attachment'>The attachment point. For example, ATTACH_CHEST</param>
void osForceAttachToAvatarFromInventory(string itemName, int attachment);
/// <summary>
/// Attach an inventory item in the object containing this script to any avatar in the region without asking for PERMISSION_ATTACH
/// </summary>
/// <remarks>
/// Nothing happens if the avatar is not in the region.
/// </remarks>
/// <param name='rawAvatarId'>The UUID of the avatar to which to attach. Nothing happens if this is not a UUID</para>
/// <param name='itemName'>The name of the item. If this is not found then a warning is said to the owner</param>
/// <param name='attachment'>The attachment point. For example, ATTACH_CHEST</param>
void osForceAttachToOtherAvatarFromInventory(string rawAvatarId, string itemName, int attachmentPoint);
/// <summary>
/// Detach the object containing this script from the avatar it is attached to without checking for PERMISSION_ATTACH
/// </summary>
/// <remarks>Nothing happens if the object is not attached.</remarks>
void osForceDetachFromAvatar();
/// <summary>
/// Returns a strided list of the specified attachment points and the number of attachments on those points.
/// </summary>
/// <param name="avatar">avatar UUID</param>
/// <param name="attachmentPoints">list of ATTACH_* constants</param>
/// <returns></returns>
LSL_List osGetNumberOfAttachments(LSL_Key avatar, LSL_List attachmentPoints);
/// <summary>
/// Sends a specified message to the specified avatar's attachments on
/// the specified attachment points.
/// </summary>
/// <remarks>
/// Behaves as osMessageObject(), without the sending script needing to know the attachment keys in advance.
/// </remarks>
/// <param name="avatar">avatar UUID</param>
/// <param name="message">message string</param>
/// <param name="attachmentPoints">list of ATTACH_* constants, or -1 for all attachments. If -1 is specified and OS_ATTACH_MSG_INVERT_POINTS is present in flags, no action is taken.</param>
/// <param name="flags">flags further constraining the attachments to deliver the message to.</param>
void osMessageAttachments(LSL_Key avatar, string message, LSL_List attachmentPoints, int flags);
#endregion
//texture draw functions
string osMovePen(string drawList, int x, int y);
string osDrawLine(string drawList, int startX, int startY, int endX, int endY);
string osDrawLine(string drawList, int endX, int endY);
string osDrawText(string drawList, string text);
string osDrawEllipse(string drawList, int width, int height);
string osDrawRectangle(string drawList, int width, int height);
string osDrawFilledRectangle(string drawList, int width, int height);
string osDrawPolygon(string drawList, LSL_List x, LSL_List y);
string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y);
string osSetFontName(string drawList, string fontName);
string osSetFontSize(string drawList, int fontSize);
string osSetPenSize(string drawList, int penSize);
string osSetPenColor(string drawList, string color);
string osSetPenColour(string drawList, string colour); // Deprecated
string osSetPenCap(string drawList, string direction, string type);
string osDrawImage(string drawList, int width, int height, string imageUrl);
vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize);
void osSetStateEvents(int events);
double osList2Double(LSL_Types.list src, int index);
void osSetRegionWaterHeight(double height);
void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour);
void osSetEstateSunSettings(bool sunFixed, double sunHour);
double osGetCurrentSunHour();
double osGetSunParam(string param);
double osSunGetParam(string param); // Deprecated
void osSetSunParam(string param, double value);
void osSunSetParam(string param, double value); // Deprecated
// Wind Module Functions
string osWindActiveModelPluginName();
void osSetWindParam(string plugin, string param, LSL_Float value);
LSL_Float osGetWindParam(string plugin, string param);
// Parcel commands
void osParcelJoin(vector pos1, vector pos2);
void osParcelSubdivide(vector pos1, vector pos2);
void osSetParcelDetails(vector pos, LSL_List rules);
void osParcelSetDetails(vector pos, LSL_List rules); // Deprecated
string osGetScriptEngineName();
string osGetSimulatorVersion();
string osGetPhysicsEngineType();
Object osParseJSONNew(string JSON);
Hashtable osParseJSON(string JSON);
void osMessageObject(key objectUUID,string message);
void osMakeNotecard(string notecardName, LSL_Types.list contents);
string osGetNotecardLine(string name, int line);
string osGetNotecard(string name);
int osGetNumberOfNotecardLines(string name);
string osAvatarName2Key(string firstname, string lastname);
string osKey2Name(string id);
// Grid Info Functions
string osGetGridNick();
string osGetGridName();
string osGetGridLoginURI();
string osGetGridHomeURI();
string osGetGridGatekeeperURI();
string osGetGridCustom(string key);
LSL_String osFormatString(string str, LSL_List strings);
LSL_List osMatchString(string src, string pattern, int start);
LSL_String osReplaceString(string src, string pattern, string replace, int count, int start);
// Information about data loaded into the region
string osLoadedCreationDate();
string osLoadedCreationTime();
string osLoadedCreationID();
LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules);
/// <summary>
/// Check if the given key is an npc
/// </summary>
/// <param name="npc"></param>
/// <returns>TRUE if the key belongs to an npc in the scene. FALSE otherwise.</returns>
LSL_Integer osIsNpc(LSL_Key npc);
key osNpcCreate(string user, string name, vector position, string notecard);
key osNpcCreate(string user, string name, vector position, string notecard, int options);
LSL_Key osNpcSaveAppearance(key npc, string notecard);
void osNpcLoadAppearance(key npc, string notecard);
vector osNpcGetPos(key npc);
void osNpcMoveTo(key npc, vector position);
void osNpcMoveToTarget(key npc, vector target, int options);
/// <summary>
/// Get the owner of the NPC
/// </summary>
/// <param name="npc"></param>
/// <returns>
/// The owner of the NPC for an owned NPC. The NPC's agent id for an unowned NPC. UUID.Zero if the key is not an npc.
/// </returns>
LSL_Key osNpcGetOwner(key npc);
rotation osNpcGetRot(key npc);
void osNpcSetRot(LSL_Key npc, rotation rot);
void osNpcStopMoveToTarget(LSL_Key npc);
void osNpcSay(key npc, string message);
void osNpcSay(key npc, int channel, string message);
void osNpcShout(key npc, int channel, string message);
void osNpcSit(key npc, key target, int options);
void osNpcStand(LSL_Key npc);
void osNpcRemove(key npc);
void osNpcPlayAnimation(LSL_Key npc, string animation);
void osNpcStopAnimation(LSL_Key npc, string animation);
void osNpcTouch(LSL_Key npcLSL_Key, LSL_Key object_key, LSL_Integer link_num);
void osNpcWhisper(key npc, int channel, string message);
LSL_Key osOwnerSaveAppearance(string notecard);
LSL_Key osAgentSaveAppearance(key agentId, string notecard);
key osGetMapTexture();
key osGetRegionMapTexture(string regionName);
LSL_List osGetRegionStats();
int osGetSimulatorMemory();
void osKickAvatar(string FirstName,string SurName,string alert);
void osSetSpeed(string UUID, LSL_Float SpeedModifier);
LSL_Float osGetHealth(string avatar);
void osCauseHealing(string avatar, double healing);
void osCauseDamage(string avatar, double damage);
LSL_List osGetPrimitiveParams(LSL_Key prim, LSL_List rules);
void osSetPrimitiveParams(LSL_Key prim, LSL_List rules);
void osSetProjectionParams(bool projection, LSL_Key texture, double fov, double focus, double amb);
void osSetProjectionParams(LSL_Key prim, bool projection, LSL_Key texture, double fov, double focus, double amb);
LSL_List osGetAvatarList();
LSL_String osUnixTimeToTimestamp(long time);
LSL_String osGetInventoryDesc(string item);
LSL_Integer osInviteToGroup(LSL_Key agentId);
LSL_Integer osEjectFromGroup(LSL_Key agentId);
void osSetTerrainTexture(int level, LSL_Key texture);
void osSetTerrainTextureHeight(int corner, double low, double high);
/// <summary>
/// Checks if thing is a UUID.
/// </summary>
/// <param name="thing"></param>
/// <returns>1 if thing is a valid UUID, 0 otherwise</returns>
LSL_Integer osIsUUID(string thing);
/// <summary>
/// Wraps to Math.Min()
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
LSL_Float osMin(double a, double b);
/// <summary>
/// Wraps to Math.max()
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
LSL_Float osMax(double a, double b);
/// <summary>
/// Get the key of the object that rezzed this object.
/// </summary>
/// <returns>Rezzing object key or NULL_KEY if rezzed by agent or otherwise unknown.</returns>
LSL_Key osGetRezzingObject();
/// <summary>
/// Sets the response type for an HTTP request/response
/// </summary>
/// <returns></returns>
void osSetContentType(LSL_Key id, string type);
/// <summary>
/// Attempts to drop an attachment to the ground
/// </summary>
void osDropAttachment();
/// <summary>
/// Attempts to drop an attachment to the ground while bypassing the script permissions
/// </summary>
void osForceDropAttachment();
/// <summary>
/// Attempts to drop an attachment at the specified coordinates.
/// </summary>
/// <param name="pos"></param>
/// <param name="rot"></param>
void osDropAttachmentAt(vector pos, rotation rot);
/// <summary>
/// Attempts to drop an attachment at the specified coordinates while bypassing the script permissions
/// </summary>
/// <param name="pos"></param>
/// <param name="rot"></param>
void osForceDropAttachmentAt(vector pos, rotation rot);
/// <summary>
/// Identical to llListen except for a bitfield which indicates which
/// string parameters should be parsed as regex patterns.
/// </summary>
/// <param name="channelID"></param>
/// <param name="name"></param>
/// <param name="ID"></param>
/// <param name="msg"></param>
/// <param name="regexBitfield">
/// OS_LISTEN_REGEX_NAME
/// OS_LISTEN_REGEX_MESSAGE
/// </param>
/// <returns></returns>
LSL_Integer osListenRegex(int channelID, string name, string ID,
string msg, int regexBitfield);
/// <summary>
/// Wraps to bool Regex.IsMatch(string input, string pattern)
/// </summary>
/// <param name="input">string to test for match</param>
/// <param name="regex">string to use as pattern</param>
/// <returns>boolean</returns>
LSL_Integer osRegexIsMatch(string input, string pattern);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.UI;
using Microsoft.MixedReality.Toolkit.Utilities;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// Interface defining a migration handler, which is used to migrate assets as they
/// upgrade to new versions of MRTK.
/// </summary>
public class ObjectManipulatorMigrationHandler : IMigrationHandler
{
/// <inheritdoc />
public bool CanMigrate(GameObject gameObject)
{
return gameObject.GetComponent<ManipulationHandler>() != null;
}
/// <inheritdoc />
public void Migrate(GameObject gameObject)
{
var manipHandler = gameObject.GetComponent<ManipulationHandler>();
var objManip = gameObject.AddComponent<ObjectManipulator>();
objManip.enabled = manipHandler.enabled;
objManip.HostTransform = manipHandler.HostTransform;
switch (manipHandler.ManipulationType)
{
case ManipulationHandler.HandMovementType.OneHandedOnly:
objManip.ManipulationType = ManipulationHandFlags.OneHanded;
break;
case ManipulationHandler.HandMovementType.TwoHandedOnly:
objManip.ManipulationType = ManipulationHandFlags.TwoHanded;
break;
case ManipulationHandler.HandMovementType.OneAndTwoHanded:
objManip.ManipulationType = ManipulationHandFlags.OneHanded |
ManipulationHandFlags.TwoHanded;
break;
}
objManip.AllowFarManipulation = manipHandler.AllowFarManipulation;
if (manipHandler.OneHandRotationModeNear == manipHandler.OneHandRotationModeFar)
{
MigrateOneHandRotationModes(ref objManip, manipHandler.OneHandRotationModeNear, ManipulationProximityFlags.Near | ManipulationProximityFlags.Far);
}
else
{
MigrateOneHandRotationModes(ref objManip, manipHandler.OneHandRotationModeNear, ManipulationProximityFlags.Near);
MigrateOneHandRotationModes(ref objManip, manipHandler.OneHandRotationModeFar, ManipulationProximityFlags.Far);
}
switch (manipHandler.TwoHandedManipulationType)
{
case ManipulationHandler.TwoHandedManipulation.Scale:
objManip.TwoHandedManipulationType = TransformFlags.Scale;
break;
case ManipulationHandler.TwoHandedManipulation.Rotate:
objManip.TwoHandedManipulationType = TransformFlags.Rotate;
break;
case ManipulationHandler.TwoHandedManipulation.MoveScale:
objManip.TwoHandedManipulationType = TransformFlags.Move |
TransformFlags.Scale;
break;
case ManipulationHandler.TwoHandedManipulation.MoveRotate:
objManip.TwoHandedManipulationType = TransformFlags.Move |
TransformFlags.Rotate;
break;
case ManipulationHandler.TwoHandedManipulation.RotateScale:
objManip.TwoHandedManipulationType = TransformFlags.Rotate |
TransformFlags.Scale;
break;
case ManipulationHandler.TwoHandedManipulation.MoveRotateScale:
objManip.TwoHandedManipulationType = TransformFlags.Move |
TransformFlags.Rotate |
TransformFlags.Scale;
break;
}
objManip.ReleaseBehavior = (ObjectManipulator.ReleaseBehaviorType)manipHandler.ReleaseBehavior;
if (manipHandler.ConstraintOnRotation != RotationConstraintType.None)
{
var rotateConstraint = objManip.EnsureComponent<RotationAxisConstraint>();
rotateConstraint.TargetTransform = manipHandler.HostTransform;
rotateConstraint.ConstraintOnRotation = RotationConstraintHelper.ConvertToAxisFlags(manipHandler.ConstraintOnRotation);
}
if (manipHandler.ConstraintOnMovement == MovementConstraintType.FixDistanceFromHead)
{
var moveConstraint = objManip.EnsureComponent<FixedDistanceConstraint>();
moveConstraint.TargetTransform = manipHandler.HostTransform;
moveConstraint.ConstraintTransform = CameraCache.Main.transform;
}
objManip.SmoothingActive = manipHandler.SmoothingActive;
objManip.MoveLerpTime = manipHandler.SmoothingAmoutOneHandManip;
objManip.RotateLerpTime = manipHandler.SmoothingAmoutOneHandManip;
objManip.ScaleLerpTime = manipHandler.SmoothingAmoutOneHandManip;
objManip.OnManipulationStarted = manipHandler.OnManipulationStarted;
objManip.OnManipulationEnded = manipHandler.OnManipulationEnded;
objManip.OnHoverEntered = manipHandler.OnHoverEntered;
objManip.OnHoverExited = manipHandler.OnHoverExited;
// finally check if there's a CursorContextManipulationHandler on the gameObject that we have to swap
CursorContextManipulationHandler cursorContextManipHandler = gameObject.GetComponent<CursorContextManipulationHandler>();
if (cursorContextManipHandler)
{
gameObject.AddComponent<CursorContextObjectManipulator>();
// remove old component
Object.DestroyImmediate(cursorContextManipHandler);
}
Object.DestroyImmediate(manipHandler);
}
private void MigrateOneHandRotationModes(ref ObjectManipulator objManip, ManipulationHandler.RotateInOneHandType oldMode, ManipulationProximityFlags proximity)
{
ObjectManipulator.RotateInOneHandType newMode = ObjectManipulator.RotateInOneHandType.RotateAboutGrabPoint;
switch (oldMode)
{
case ManipulationHandler.RotateInOneHandType.MaintainRotationToUser:
{
newMode = ObjectManipulator.RotateInOneHandType.RotateAboutGrabPoint;
var constraint = objManip.EnsureComponent<FixedRotationToUserConstraint>();
constraint.TargetTransform = objManip.HostTransform;
constraint.HandType = ManipulationHandFlags.OneHanded;
constraint.ProximityType = proximity;
break;
}
case ManipulationHandler.RotateInOneHandType.GravityAlignedMaintainRotationToUser:
{
newMode = ObjectManipulator.RotateInOneHandType.RotateAboutGrabPoint;
var rotConstraint = objManip.EnsureComponent<FixedRotationToUserConstraint>();
rotConstraint.TargetTransform = objManip.HostTransform;
rotConstraint.HandType = ManipulationHandFlags.OneHanded;
rotConstraint.ProximityType = proximity;
var axisConstraint = objManip.EnsureComponent<RotationAxisConstraint>();
axisConstraint.TargetTransform = objManip.HostTransform;
axisConstraint.HandType = ManipulationHandFlags.OneHanded;
axisConstraint.ProximityType = proximity;
axisConstraint.ConstraintOnRotation = AxisFlags.XAxis | AxisFlags.ZAxis;
break;
}
case ManipulationHandler.RotateInOneHandType.FaceUser:
{
newMode = ObjectManipulator.RotateInOneHandType.RotateAboutGrabPoint;
var rotConstraint = objManip.EnsureComponent<FaceUserConstraint>();
rotConstraint.TargetTransform = objManip.HostTransform;
rotConstraint.HandType = ManipulationHandFlags.OneHanded;
rotConstraint.ProximityType = proximity;
rotConstraint.FaceAway = false;
break;
}
case ManipulationHandler.RotateInOneHandType.FaceAwayFromUser:
{
newMode = ObjectManipulator.RotateInOneHandType.RotateAboutGrabPoint;
var rotConstraint = objManip.EnsureComponent<FaceUserConstraint>();
rotConstraint.TargetTransform = objManip.HostTransform;
rotConstraint.HandType = ManipulationHandFlags.OneHanded;
rotConstraint.ProximityType = proximity;
rotConstraint.FaceAway = true;
break;
}
case ManipulationHandler.RotateInOneHandType.MaintainOriginalRotation:
{
newMode = ObjectManipulator.RotateInOneHandType.RotateAboutGrabPoint;
var rotConstraint = objManip.EnsureComponent<FixedRotationToWorldConstraint>();
rotConstraint.TargetTransform = objManip.HostTransform;
rotConstraint.HandType = ManipulationHandFlags.OneHanded;
rotConstraint.ProximityType = proximity;
break;
}
case ManipulationHandler.RotateInOneHandType.RotateAboutObjectCenter:
newMode = ObjectManipulator.RotateInOneHandType.RotateAboutObjectCenter;
break;
case ManipulationHandler.RotateInOneHandType.RotateAboutGrabPoint:
newMode = ObjectManipulator.RotateInOneHandType.RotateAboutGrabPoint;
break;
}
if (proximity.HasFlag(ManipulationProximityFlags.Near))
{
objManip.OneHandRotationModeNear = newMode;
}
if (proximity.HasFlag(ManipulationProximityFlags.Far))
{
objManip.OneHandRotationModeFar = newMode;
}
}
}
}
| |
namespace Azure.Messaging.EventHubs
{
public partial class EventData
{
public EventData(System.BinaryData eventBody) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
protected EventData(System.BinaryData eventBody, System.Collections.Generic.IDictionary<string, object> properties = null, System.Collections.Generic.IReadOnlyDictionary<string, object> systemProperties = null, long sequenceNumber = (long)-9223372036854775808, long offset = (long)-9223372036854775808, System.DateTimeOffset enqueuedTime = default(System.DateTimeOffset), string partitionKey = null) { }
public EventData(System.ReadOnlyMemory<byte> eventBody) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
protected EventData(System.ReadOnlyMemory<byte> eventBody, System.Collections.Generic.IDictionary<string, object> properties = null, System.Collections.Generic.IReadOnlyDictionary<string, object> systemProperties = null, long sequenceNumber = (long)-9223372036854775808, long offset = (long)-9223372036854775808, System.DateTimeOffset enqueuedTime = default(System.DateTimeOffset), string partitionKey = null) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public System.ReadOnlyMemory<byte> Body { get { throw null; } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public System.IO.Stream BodyAsStream { get { throw null; } }
public System.DateTimeOffset EnqueuedTime { get { throw null; } }
public System.BinaryData EventBody { get { throw null; } }
public long Offset { get { throw null; } }
public string PartitionKey { get { throw null; } }
public System.Collections.Generic.IDictionary<string, object> Properties { get { throw null; } }
public long SequenceNumber { get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, object> SystemProperties { get { throw null; } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public partial class EventHubConnection : System.IAsyncDisposable
{
protected EventHubConnection() { }
public EventHubConnection(string connectionString) { }
public EventHubConnection(string connectionString, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions) { }
public EventHubConnection(string connectionString, string eventHubName) { }
public EventHubConnection(string fullyQualifiedNamespace, string eventHubName, Azure.AzureNamedKeyCredential credential, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions = null) { }
public EventHubConnection(string fullyQualifiedNamespace, string eventHubName, Azure.AzureSasCredential credential, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions = null) { }
public EventHubConnection(string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions = null) { }
public EventHubConnection(string connectionString, string eventHubName, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions) { }
public string EventHubName { get { throw null; } }
public string FullyQualifiedNamespace { get { throw null; } }
public bool IsClosed { get { throw null; } }
public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public partial class EventHubConnectionOptions
{
public EventHubConnectionOptions() { }
public System.Uri CustomEndpointAddress { get { throw null; } set { } }
public System.Net.IWebProxy Proxy { get { throw null; } set { } }
public Azure.Messaging.EventHubs.EventHubsTransportType TransportType { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public partial class EventHubProperties
{
protected internal EventHubProperties(string name, System.DateTimeOffset createdOn, string[] partitionIds) { }
public System.DateTimeOffset CreatedOn { get { throw null; } }
public string Name { get { throw null; } }
public string[] PartitionIds { get { throw null; } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public partial class EventHubsConnectionStringProperties
{
public EventHubsConnectionStringProperties() { }
public System.Uri Endpoint { get { throw null; } }
public string EventHubName { get { throw null; } }
public string FullyQualifiedNamespace { get { throw null; } }
public string SharedAccessKey { get { throw null; } }
public string SharedAccessKeyName { get { throw null; } }
public string SharedAccessSignature { get { throw null; } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static Azure.Messaging.EventHubs.EventHubsConnectionStringProperties Parse(string connectionString) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public partial class EventHubsException : System.Exception
{
public EventHubsException(bool isTransient, string eventHubName) { }
public EventHubsException(bool isTransient, string eventHubName, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { }
public EventHubsException(bool isTransient, string eventHubName, string message) { }
public EventHubsException(bool isTransient, string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { }
public EventHubsException(bool isTransient, string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason, System.Exception innerException) { }
public EventHubsException(bool isTransient, string eventHubName, string message, System.Exception innerException) { }
public EventHubsException(string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { }
public string EventHubName { get { throw null; } }
public bool IsTransient { get { throw null; } }
public override string Message { get { throw null; } }
public Azure.Messaging.EventHubs.EventHubsException.FailureReason Reason { get { throw null; } }
public override string ToString() { throw null; }
public enum FailureReason
{
GeneralError = 0,
ClientClosed = 1,
ConsumerDisconnected = 2,
ResourceNotFound = 3,
MessageSizeExceeded = 4,
QuotaExceeded = 5,
ServiceBusy = 6,
ServiceTimeout = 7,
ServiceCommunicationProblem = 8,
ProducerDisconnected = 9,
InvalidClientState = 10,
}
}
public static partial class EventHubsModelFactory
{
public static Azure.Messaging.EventHubs.EventData EventData(System.BinaryData eventBody, System.Collections.Generic.IDictionary<string, object> properties = null, System.Collections.Generic.IReadOnlyDictionary<string, object> systemProperties = null, string partitionKey = null, long sequenceNumber = (long)-9223372036854775808, long offset = (long)-9223372036854775808, System.DateTimeOffset enqueuedTime = default(System.DateTimeOffset)) { throw null; }
public static Azure.Messaging.EventHubs.Producer.EventDataBatch EventDataBatch(long batchSizeBytes, System.Collections.Generic.IList<Azure.Messaging.EventHubs.EventData> batchEventStore, Azure.Messaging.EventHubs.Producer.CreateBatchOptions batchOptions = null, System.Func<Azure.Messaging.EventHubs.EventData, bool> tryAddCallback = null) { throw null; }
public static Azure.Messaging.EventHubs.EventHubProperties EventHubProperties(string name, System.DateTimeOffset createdOn, string[] partitionIds) { throw null; }
public static Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties LastEnqueuedEventProperties(long? lastSequenceNumber, long? lastOffset, System.DateTimeOffset? lastEnqueuedTime, System.DateTimeOffset? lastReceivedTime) { throw null; }
public static Azure.Messaging.EventHubs.Consumer.PartitionContext PartitionContext(string partitionId, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties lastEnqueuedEventProperties = default(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties)) { throw null; }
public static Azure.Messaging.EventHubs.PartitionProperties PartitionProperties(string eventHubName, string partitionId, bool isEmpty, long beginningSequenceNumber, long lastSequenceNumber, long lastOffset, System.DateTimeOffset lastEnqueuedTime) { throw null; }
}
public enum EventHubsRetryMode
{
Fixed = 0,
Exponential = 1,
}
public partial class EventHubsRetryOptions
{
public EventHubsRetryOptions() { }
public Azure.Messaging.EventHubs.EventHubsRetryPolicy CustomRetryPolicy { get { throw null; } set { } }
public System.TimeSpan Delay { get { throw null; } set { } }
public System.TimeSpan MaximumDelay { get { throw null; } set { } }
public int MaximumRetries { get { throw null; } set { } }
public Azure.Messaging.EventHubs.EventHubsRetryMode Mode { get { throw null; } set { } }
public System.TimeSpan TryTimeout { get { throw null; } set { } }
}
public abstract partial class EventHubsRetryPolicy
{
protected EventHubsRetryPolicy() { }
public abstract System.TimeSpan? CalculateRetryDelay(System.Exception lastException, int attemptCount);
public abstract System.TimeSpan CalculateTryTimeout(int attemptCount);
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public enum EventHubsTransportType
{
AmqpTcp = 0,
AmqpWebSockets = 1,
}
public partial class PartitionProperties
{
protected internal PartitionProperties(string eventHubName, string partitionId, bool isEmpty, long beginningSequenceNumber, long lastSequenceNumber, long lastOffset, System.DateTimeOffset lastEnqueuedTime) { }
public long BeginningSequenceNumber { get { throw null; } }
public string EventHubName { get { throw null; } }
public string Id { get { throw null; } }
public bool IsEmpty { get { throw null; } }
public long LastEnqueuedOffset { get { throw null; } }
public long LastEnqueuedSequenceNumber { get { throw null; } }
public System.DateTimeOffset LastEnqueuedTime { get { throw null; } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
}
namespace Azure.Messaging.EventHubs.Consumer
{
public partial class EventHubConsumerClient : System.IAsyncDisposable
{
public const string DefaultConsumerGroupName = "$Default";
protected EventHubConsumerClient() { }
public EventHubConsumerClient(string consumerGroup, Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { }
public EventHubConsumerClient(string consumerGroup, string connectionString) { }
public EventHubConsumerClient(string consumerGroup, string connectionString, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions) { }
public EventHubConsumerClient(string consumerGroup, string connectionString, string eventHubName) { }
public EventHubConsumerClient(string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.AzureNamedKeyCredential credential, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { }
public EventHubConsumerClient(string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.AzureSasCredential credential, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { }
public EventHubConsumerClient(string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { }
public EventHubConsumerClient(string consumerGroup, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions) { }
public string ConsumerGroup { get { throw null; } }
public string EventHubName { get { throw null; } }
public string FullyQualifiedNamespace { get { throw null; } }
public bool IsClosed { get { throw null; } protected set { } }
public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.EventHubProperties> GetEventHubPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public virtual System.Threading.Tasks.Task<string[]> GetPartitionIdsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(string partitionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(bool startReadingAtEarliestEvent, Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions = null, [System.Runtime.CompilerServices.EnumeratorCancellationAttribute] System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsFromPartitionAsync(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition startingPosition, Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions, [System.Runtime.CompilerServices.EnumeratorCancellationAttribute] System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsFromPartitionAsync(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition startingPosition, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public partial class EventHubConsumerClientOptions
{
public EventHubConsumerClientOptions() { }
public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } }
public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct EventPosition : System.IEquatable<Azure.Messaging.EventHubs.Consumer.EventPosition>
{
private object _dummy;
private int _dummyPrimitive;
public static Azure.Messaging.EventHubs.Consumer.EventPosition Earliest { get { throw null; } }
public static Azure.Messaging.EventHubs.Consumer.EventPosition Latest { get { throw null; } }
public bool Equals(Azure.Messaging.EventHubs.Consumer.EventPosition other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
public static Azure.Messaging.EventHubs.Consumer.EventPosition FromEnqueuedTime(System.DateTimeOffset enqueuedTime) { throw null; }
public static Azure.Messaging.EventHubs.Consumer.EventPosition FromOffset(long offset, bool isInclusive = true) { throw null; }
public static Azure.Messaging.EventHubs.Consumer.EventPosition FromSequenceNumber(long sequenceNumber, bool isInclusive = true) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Messaging.EventHubs.Consumer.EventPosition left, Azure.Messaging.EventHubs.Consumer.EventPosition right) { throw null; }
public static bool operator !=(Azure.Messaging.EventHubs.Consumer.EventPosition left, Azure.Messaging.EventHubs.Consumer.EventPosition right) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct LastEnqueuedEventProperties : System.IEquatable<Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties>
{
public LastEnqueuedEventProperties(long? lastSequenceNumber, long? lastOffset, System.DateTimeOffset? lastEnqueuedTime, System.DateTimeOffset? lastReceivedTime) { throw null; }
public System.DateTimeOffset? EnqueuedTime { get { throw null; } }
public System.DateTimeOffset? LastReceivedTime { get { throw null; } }
public long? Offset { get { throw null; } }
public long? SequenceNumber { get { throw null; } }
public bool Equals(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties left, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties right) { throw null; }
public static bool operator !=(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties left, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties right) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public partial class PartitionContext
{
protected internal PartitionContext(string partitionId) { }
public string PartitionId { get { throw null; } }
public virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct PartitionEvent
{
private object _dummy;
private int _dummyPrimitive;
public PartitionEvent(Azure.Messaging.EventHubs.Consumer.PartitionContext partition, Azure.Messaging.EventHubs.EventData data) { throw null; }
public Azure.Messaging.EventHubs.EventData Data { get { throw null; } }
public Azure.Messaging.EventHubs.Consumer.PartitionContext Partition { get { throw null; } }
}
public partial class ReadEventOptions
{
public ReadEventOptions() { }
public int CacheEventCount { get { throw null; } set { } }
public System.TimeSpan? MaximumWaitTime { get { throw null; } set { } }
public long? OwnerLevel { get { throw null; } set { } }
public int PrefetchCount { get { throw null; } set { } }
public long? PrefetchSizeInBytes { get { throw null; } set { } }
public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
}
namespace Azure.Messaging.EventHubs.Primitives
{
public partial class EventProcessorCheckpoint
{
public EventProcessorCheckpoint() { }
public string ConsumerGroup { get { throw null; } set { } }
public string EventHubName { get { throw null; } set { } }
public string FullyQualifiedNamespace { get { throw null; } set { } }
public string PartitionId { get { throw null; } set { } }
public Azure.Messaging.EventHubs.Consumer.EventPosition StartingPosition { get { throw null; } set { } }
}
public partial class EventProcessorOptions
{
public EventProcessorOptions() { }
public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } }
public Azure.Messaging.EventHubs.Consumer.EventPosition DefaultStartingPosition { get { throw null; } set { } }
public string Identifier { get { throw null; } set { } }
public Azure.Messaging.EventHubs.Processor.LoadBalancingStrategy LoadBalancingStrategy { get { throw null; } set { } }
public System.TimeSpan LoadBalancingUpdateInterval { get { throw null; } set { } }
public System.TimeSpan? MaximumWaitTime { get { throw null; } set { } }
public System.TimeSpan PartitionOwnershipExpirationInterval { get { throw null; } set { } }
public int PrefetchCount { get { throw null; } set { } }
public long? PrefetchSizeInBytes { get { throw null; } set { } }
public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } }
public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public partial class EventProcessorPartition
{
public EventProcessorPartition() { }
public string PartitionId { get { throw null; } protected internal set { } }
}
public partial class EventProcessorPartitionOwnership
{
public EventProcessorPartitionOwnership() { }
public string ConsumerGroup { get { throw null; } set { } }
public string EventHubName { get { throw null; } set { } }
public string FullyQualifiedNamespace { get { throw null; } set { } }
public System.DateTimeOffset LastModifiedTime { get { throw null; } set { } }
public string OwnerIdentifier { get { throw null; } set { } }
public string PartitionId { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
}
public abstract partial class EventProcessor<TPartition> where TPartition : Azure.Messaging.EventHubs.Primitives.EventProcessorPartition, new()
{
protected EventProcessor() { }
protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string connectionString, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { }
protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.AzureNamedKeyCredential credential, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { }
protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.AzureSasCredential credential, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { }
protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { }
protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { }
public string ConsumerGroup { get { throw null; } }
public string EventHubName { get { throw null; } }
public string FullyQualifiedNamespace { get { throw null; } }
public string Identifier { get { throw null; } }
public bool IsRunning { get { throw null; } protected set { } }
protected Azure.Messaging.EventHubs.EventHubsRetryPolicy RetryPolicy { get { throw null; } }
protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership>> ClaimOwnershipAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership> desiredOwnership, System.Threading.CancellationToken cancellationToken);
protected internal virtual Azure.Messaging.EventHubs.EventHubConnection CreateConnection() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
protected virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.Primitives.EventProcessorCheckpoint> GetCheckpointAsync(string partitionId, System.Threading.CancellationToken cancellationToken) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorCheckpoint>> ListCheckpointsAsync(System.Threading.CancellationToken cancellationToken);
protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership>> ListOwnershipAsync(System.Threading.CancellationToken cancellationToken);
protected virtual System.Threading.Tasks.Task OnInitializingPartitionAsync(TPartition partition, System.Threading.CancellationToken cancellationToken) { throw null; }
protected virtual System.Threading.Tasks.Task OnPartitionProcessingStoppedAsync(TPartition partition, Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason reason, System.Threading.CancellationToken cancellationToken) { throw null; }
protected abstract System.Threading.Tasks.Task OnProcessingErrorAsync(System.Exception exception, TPartition partition, string operationDescription, System.Threading.CancellationToken cancellationToken);
protected abstract System.Threading.Tasks.Task OnProcessingEventBatchAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> events, TPartition partition, System.Threading.CancellationToken cancellationToken);
protected virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties(string partitionId) { throw null; }
public virtual void StartProcessing(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { }
public virtual System.Threading.Tasks.Task StartProcessingAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual void StopProcessing(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { }
public virtual System.Threading.Tasks.Task StopProcessingAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public partial class PartitionReceiver : System.IAsyncDisposable
{
protected PartitionReceiver() { }
public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { }
public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string connectionString, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { }
public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string fullyQualifiedNamespace, string eventHubName, Azure.AzureNamedKeyCredential credential, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { }
public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string fullyQualifiedNamespace, string eventHubName, Azure.AzureSasCredential credential, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { }
public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { }
public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { }
public string ConsumerGroup { get { throw null; } }
public string EventHubName { get { throw null; } }
public string FullyQualifiedNamespace { get { throw null; } }
public Azure.Messaging.EventHubs.Consumer.EventPosition InitialPosition { get { throw null; } }
public bool IsClosed { get { throw null; } protected set { } }
public string PartitionId { get { throw null; } }
public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties() { throw null; }
public virtual System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData>> ReceiveBatchAsync(int maximumEventCount, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData>> ReceiveBatchAsync(int maximumEventCount, System.TimeSpan maximumWaitTime, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public partial class PartitionReceiverOptions
{
public PartitionReceiverOptions() { }
public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } }
public System.TimeSpan? DefaultMaximumReceiveWaitTime { get { throw null; } set { } }
public long? OwnerLevel { get { throw null; } set { } }
public int PrefetchCount { get { throw null; } set { } }
public long? PrefetchSizeInBytes { get { throw null; } set { } }
public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } }
public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
}
namespace Azure.Messaging.EventHubs.Processor
{
public enum LoadBalancingStrategy
{
Balanced = 0,
Greedy = 1,
}
public partial class PartitionClosingEventArgs
{
public PartitionClosingEventArgs(string partitionId, Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason reason, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { }
public System.Threading.CancellationToken CancellationToken { get { throw null; } }
public string PartitionId { get { throw null; } }
public Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason Reason { get { throw null; } }
}
public partial class PartitionInitializingEventArgs
{
public PartitionInitializingEventArgs(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition defaultStartingPosition, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { }
public System.Threading.CancellationToken CancellationToken { get { throw null; } }
public Azure.Messaging.EventHubs.Consumer.EventPosition DefaultStartingPosition { get { throw null; } set { } }
public string PartitionId { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ProcessErrorEventArgs
{
private object _dummy;
private int _dummyPrimitive;
public ProcessErrorEventArgs(string partitionId, string operation, System.Exception exception, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public System.Threading.CancellationToken CancellationToken { get { throw null; } }
public System.Exception Exception { get { throw null; } }
public string Operation { get { throw null; } }
public string PartitionId { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ProcessEventArgs
{
private object _dummy;
private int _dummyPrimitive;
public ProcessEventArgs(Azure.Messaging.EventHubs.Consumer.PartitionContext partition, Azure.Messaging.EventHubs.EventData data, System.Func<System.Threading.CancellationToken, System.Threading.Tasks.Task> updateCheckpointImplementation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public System.Threading.CancellationToken CancellationToken { get { throw null; } }
public Azure.Messaging.EventHubs.EventData Data { get { throw null; } }
public bool HasEvent { get { throw null; } }
public Azure.Messaging.EventHubs.Consumer.PartitionContext Partition { get { throw null; } }
public System.Threading.Tasks.Task UpdateCheckpointAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public enum ProcessingStoppedReason
{
Shutdown = 0,
OwnershipLost = 1,
}
}
namespace Azure.Messaging.EventHubs.Producer
{
public partial class CreateBatchOptions : Azure.Messaging.EventHubs.Producer.SendEventOptions
{
public CreateBatchOptions() { }
public long? MaximumSizeInBytes { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public sealed partial class EventDataBatch : System.IDisposable
{
internal EventDataBatch() { }
public int Count { get { throw null; } }
public long MaximumSizeInBytes { get { throw null; } }
public long SizeInBytes { get { throw null; } }
public void Dispose() { }
public bool TryAdd(Azure.Messaging.EventHubs.EventData eventData) { throw null; }
}
public partial class EventHubProducerClient : System.IAsyncDisposable
{
protected EventHubProducerClient() { }
public EventHubProducerClient(Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { }
public EventHubProducerClient(string connectionString) { }
public EventHubProducerClient(string connectionString, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions) { }
public EventHubProducerClient(string connectionString, string eventHubName) { }
public EventHubProducerClient(string fullyQualifiedNamespace, string eventHubName, Azure.AzureNamedKeyCredential credential, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { }
public EventHubProducerClient(string fullyQualifiedNamespace, string eventHubName, Azure.AzureSasCredential credential, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { }
public EventHubProducerClient(string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { }
public EventHubProducerClient(string connectionString, string eventHubName, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions) { }
public string EventHubName { get { throw null; } }
public string FullyQualifiedNamespace { get { throw null; } }
public bool IsClosed { get { throw null; } protected set { } }
public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.ValueTask<Azure.Messaging.EventHubs.Producer.EventDataBatch> CreateBatchAsync(Azure.Messaging.EventHubs.Producer.CreateBatchOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.ValueTask<Azure.Messaging.EventHubs.Producer.EventDataBatch> CreateBatchAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.EventHubProperties> GetEventHubPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public virtual System.Threading.Tasks.Task<string[]> GetPartitionIdsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(string partitionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task SendAsync(Azure.Messaging.EventHubs.Producer.EventDataBatch eventBatch, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task SendAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> eventBatch, Azure.Messaging.EventHubs.Producer.SendEventOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task SendAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> eventBatch, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public partial class EventHubProducerClientOptions
{
public EventHubProducerClientOptions() { }
public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } }
public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
public partial class SendEventOptions
{
public SendEventOptions() { }
public string PartitionId { get { throw null; } set { } }
public string PartitionKey { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
}
namespace Microsoft.Extensions.Azure
{
public static partial class EventHubClientBuilderExtensions
{
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClientWithNamespace<TBuilder>(this TBuilder builder, string consumerGroup, string fullyQualifiedNamespace, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder>(this TBuilder builder, string consumerGroup, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder>(this TBuilder builder, string consumerGroup, string connectionString, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClientWithNamespace<TBuilder>(this TBuilder builder, string fullyQualifiedNamespace, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder>(this TBuilder builder, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder>(this TBuilder builder, string connectionString, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; }
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure.Management.Insights;
using Microsoft.Azure.Management.Insights.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Insights
{
/// <summary>
/// Operations for managing storage diagnostic settings.
/// </summary>
internal partial class StorageDiagnosticSettingsOperations : IServiceOperations<InsightsManagementClient>, IStorageDiagnosticSettingsOperations
{
/// <summary>
/// Initializes a new instance of the
/// StorageDiagnosticSettingsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal StorageDiagnosticSettingsOperations(InsightsManagementClient client)
{
this._client = client;
}
private InsightsManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Insights.InsightsManagementClient.
/// </summary>
public InsightsManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Gets the diagnostic settings for the specified storage service.
/// </summary>
/// <param name='resourceUri'>
/// Required. The resource identifier of the storage service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<StorageDiagnosticSettingsGetResponse> GetAsync(string resourceUri, CancellationToken cancellationToken)
{
// Validate
if (resourceUri == null)
{
throw new ArgumentNullException("resourceUri");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(resourceUri);
url = url + "/diagnosticSettings/storage";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
StorageDiagnosticSettingsGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new StorageDiagnosticSettingsGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.Name = nameInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
result.Location = locationInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
StorageDiagnosticSettings propertiesInstance = new StorageDiagnosticSettings();
result.Properties = propertiesInstance;
JToken loggingValue = propertiesValue["logging"];
if (loggingValue != null && loggingValue.Type != JTokenType.Null)
{
StorageLoggingDiagnosticSettings loggingInstance = new StorageLoggingDiagnosticSettings();
propertiesInstance.LoggingDiagnosticSettings = loggingInstance;
JToken deleteValue = loggingValue["delete"];
if (deleteValue != null && deleteValue.Type != JTokenType.Null)
{
bool deleteInstance = ((bool)deleteValue);
loggingInstance.Delete = deleteInstance;
}
JToken readValue = loggingValue["read"];
if (readValue != null && readValue.Type != JTokenType.Null)
{
bool readInstance = ((bool)readValue);
loggingInstance.Read = readInstance;
}
JToken writeValue = loggingValue["write"];
if (writeValue != null && writeValue.Type != JTokenType.Null)
{
bool writeInstance = ((bool)writeValue);
loggingInstance.Write = writeInstance;
}
JToken retentionValue = loggingValue["retention"];
if (retentionValue != null && retentionValue.Type != JTokenType.Null)
{
TimeSpan retentionInstance = XmlConvert.ToTimeSpan(((string)retentionValue));
loggingInstance.Retention = retentionInstance;
}
}
JToken metricsValue = propertiesValue["metrics"];
if (metricsValue != null && metricsValue.Type != JTokenType.Null)
{
StorageMetricDiagnosticSettings metricsInstance = new StorageMetricDiagnosticSettings();
propertiesInstance.MetricDiagnosticSettings = metricsInstance;
JToken aggregationsArray = metricsValue["aggregations"];
if (aggregationsArray != null && aggregationsArray.Type != JTokenType.Null)
{
foreach (JToken aggregationsValue in ((JArray)aggregationsArray))
{
StorageMetricAggregation storageMetricAggregationInstance = new StorageMetricAggregation();
metricsInstance.MetricAggregations.Add(storageMetricAggregationInstance);
JToken scheduledTransferPeriodValue = aggregationsValue["scheduledTransferPeriod"];
if (scheduledTransferPeriodValue != null && scheduledTransferPeriodValue.Type != JTokenType.Null)
{
TimeSpan scheduledTransferPeriodInstance = XmlConvert.ToTimeSpan(((string)scheduledTransferPeriodValue));
storageMetricAggregationInstance.ScheduledTransferPeriod = scheduledTransferPeriodInstance;
}
JToken retentionValue2 = aggregationsValue["retention"];
if (retentionValue2 != null && retentionValue2.Type != JTokenType.Null)
{
TimeSpan retentionInstance2 = XmlConvert.ToTimeSpan(((string)retentionValue2));
storageMetricAggregationInstance.Retention = retentionInstance2;
}
JToken levelValue = aggregationsValue["level"];
if (levelValue != null && levelValue.Type != JTokenType.Null)
{
StorageMetricLevel levelInstance = ((StorageMetricLevel)Enum.Parse(typeof(StorageMetricLevel), ((string)levelValue), true));
storageMetricAggregationInstance.Level = levelInstance;
}
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Creates or update the diagnostic settings for the specified storage
/// service.
/// </summary>
/// <param name='resourceUri'>
/// Required. The resource identifier of the storage service.
/// </param>
/// <param name='parameters'>
/// Required. The storage diagnostic settings parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Generic empty response. We only pass it to ensure json error
/// handling
/// </returns>
public async Task<EmptyResponse> PutAsync(string resourceUri, StorageDiagnosticSettingsPutParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceUri == null)
{
throw new ArgumentNullException("resourceUri");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PutAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(resourceUri);
url = url + "/diagnosticSettings/storage";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject storageDiagnosticSettingsPutParametersValue = new JObject();
requestDoc = storageDiagnosticSettingsPutParametersValue;
if (parameters.Properties != null)
{
JObject propertiesValue = new JObject();
storageDiagnosticSettingsPutParametersValue["properties"] = propertiesValue;
if (parameters.Properties.LoggingDiagnosticSettings != null)
{
JObject loggingValue = new JObject();
propertiesValue["logging"] = loggingValue;
loggingValue["delete"] = parameters.Properties.LoggingDiagnosticSettings.Delete;
loggingValue["read"] = parameters.Properties.LoggingDiagnosticSettings.Read;
loggingValue["write"] = parameters.Properties.LoggingDiagnosticSettings.Write;
loggingValue["retention"] = XmlConvert.ToString(parameters.Properties.LoggingDiagnosticSettings.Retention);
}
if (parameters.Properties.MetricDiagnosticSettings != null)
{
JObject metricsValue = new JObject();
propertiesValue["metrics"] = metricsValue;
if (parameters.Properties.MetricDiagnosticSettings.MetricAggregations != null)
{
if (parameters.Properties.MetricDiagnosticSettings.MetricAggregations is ILazyCollection == false || ((ILazyCollection)parameters.Properties.MetricDiagnosticSettings.MetricAggregations).IsInitialized)
{
JArray aggregationsArray = new JArray();
foreach (StorageMetricAggregation aggregationsItem in parameters.Properties.MetricDiagnosticSettings.MetricAggregations)
{
JObject storageMetricAggregationValue = new JObject();
aggregationsArray.Add(storageMetricAggregationValue);
storageMetricAggregationValue["scheduledTransferPeriod"] = XmlConvert.ToString(aggregationsItem.ScheduledTransferPeriod);
storageMetricAggregationValue["retention"] = XmlConvert.ToString(aggregationsItem.Retention);
storageMetricAggregationValue["level"] = aggregationsItem.Level.ToString();
}
metricsValue["aggregations"] = aggregationsArray;
}
}
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
EmptyResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new EmptyResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// 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.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.Numerics
{
/// <summary>
/// A structure encapsulating three single precision floating point values and provides hardware accelerated methods.
/// </summary>
[Intrinsic]
public partial struct Vector3 : IEquatable<Vector3>, IFormattable
{
#region Public Static Properties
/// <summary>
/// Returns the vector (0,0,0).
/// </summary>
public static Vector3 Zero
{
[Intrinsic]
get
{
return new Vector3();
}
}
/// <summary>
/// Returns the vector (1,1,1).
/// </summary>
public static Vector3 One
{
[Intrinsic]
get
{
return new Vector3(1.0f, 1.0f, 1.0f);
}
}
/// <summary>
/// Returns the vector (1,0,0).
/// </summary>
public static Vector3 UnitX { get { return new Vector3(1.0f, 0.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,1,0).
/// </summary>
public static Vector3 UnitY { get { return new Vector3(0.0f, 1.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,0,1).
/// </summary>
public static Vector3 UnitZ { get { return new Vector3(0.0f, 0.0f, 1.0f); } }
#endregion Public Static Properties
#region Public Instance Methods
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code.</returns>
public override readonly int GetHashCode()
{
return HashCode.Combine(this.X.GetHashCode(), this.Y.GetHashCode(), this.Z.GetHashCode());
}
/// <summary>
/// Returns a boolean indicating whether the given Object is equal to this Vector3 instance.
/// </summary>
/// <param name="obj">The Object to compare against.</param>
/// <returns>True if the Object is equal to this Vector3; False otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override readonly bool Equals(object? obj)
{
if (!(obj is Vector3))
return false;
return Equals((Vector3)obj);
}
/// <summary>
/// Returns a String representing this Vector3 instance.
/// </summary>
/// <returns>The string representation.</returns>
public override readonly string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a String representing this Vector3 instance, using the specified format to format individual elements.
/// </summary>
/// <param name="format">The format of individual elements.</param>
/// <returns>The string representation.</returns>
public readonly string ToString(string? format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a String representing this Vector3 instance, using the specified format to format individual elements
/// and the given IFormatProvider.
/// </summary>
/// <param name="format">The format of individual elements.</param>
/// <param name="formatProvider">The format provider to use when formatting elements.</param>
/// <returns>The string representation.</returns>
public readonly string ToString(string? format, IFormatProvider? formatProvider)
{
StringBuilder sb = new StringBuilder();
string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
sb.Append('<');
sb.Append(((IFormattable)this.X).ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(((IFormattable)this.Y).ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(((IFormattable)this.Z).ToString(format, formatProvider));
sb.Append('>');
return sb.ToString();
}
/// <summary>
/// Returns the length of the vector.
/// </summary>
/// <returns>The vector's length.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float Length()
{
if (Vector.IsHardwareAccelerated)
{
float ls = Vector3.Dot(this, this);
return MathF.Sqrt(ls);
}
else
{
float ls = X * X + Y * Y + Z * Z;
return MathF.Sqrt(ls);
}
}
/// <summary>
/// Returns the length of the vector squared. This operation is cheaper than Length().
/// </summary>
/// <returns>The vector's length squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float LengthSquared()
{
if (Vector.IsHardwareAccelerated)
{
return Vector3.Dot(this, this);
}
else
{
return X * X + Y * Y + Z * Z;
}
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the Euclidean distance between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Distance(Vector3 value1, Vector3 value2)
{
if (Vector.IsHardwareAccelerated)
{
Vector3 difference = value1 - value2;
float ls = Vector3.Dot(difference, difference);
return MathF.Sqrt(ls);
}
else
{
float dx = value1.X - value2.X;
float dy = value1.Y - value2.Y;
float dz = value1.Z - value2.Z;
float ls = dx * dx + dy * dy + dz * dz;
return MathF.Sqrt(ls);
}
}
/// <summary>
/// Returns the Euclidean distance squared between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DistanceSquared(Vector3 value1, Vector3 value2)
{
if (Vector.IsHardwareAccelerated)
{
Vector3 difference = value1 - value2;
return Vector3.Dot(difference, difference);
}
else
{
float dx = value1.X - value2.X;
float dy = value1.Y - value2.Y;
float dz = value1.Z - value2.Z;
return dx * dx + dy * dy + dz * dz;
}
}
/// <summary>
/// Returns a vector with the same direction as the given vector, but with a length of 1.
/// </summary>
/// <param name="value">The vector to normalize.</param>
/// <returns>The normalized vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Normalize(Vector3 value)
{
if (Vector.IsHardwareAccelerated)
{
float length = value.Length();
return value / length;
}
else
{
float ls = value.X * value.X + value.Y * value.Y + value.Z * value.Z;
float length = MathF.Sqrt(ls);
return new Vector3(value.X / length, value.Y / length, value.Z / length);
}
}
/// <summary>
/// Computes the cross product of two vectors.
/// </summary>
/// <param name="vector1">The first vector.</param>
/// <param name="vector2">The second vector.</param>
/// <returns>The cross product.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Cross(Vector3 vector1, Vector3 vector2)
{
return new Vector3(
vector1.Y * vector2.Z - vector1.Z * vector2.Y,
vector1.Z * vector2.X - vector1.X * vector2.Z,
vector1.X * vector2.Y - vector1.Y * vector2.X);
}
/// <summary>
/// Returns the reflection of a vector off a surface that has the specified normal.
/// </summary>
/// <param name="vector">The source vector.</param>
/// <param name="normal">The normal of the surface being reflected off.</param>
/// <returns>The reflected vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Reflect(Vector3 vector, Vector3 normal)
{
if (Vector.IsHardwareAccelerated)
{
float dot = Vector3.Dot(vector, normal);
Vector3 temp = normal * dot * 2f;
return vector - temp;
}
else
{
float dot = vector.X * normal.X + vector.Y * normal.Y + vector.Z * normal.Z;
float tempX = normal.X * dot * 2f;
float tempY = normal.Y * dot * 2f;
float tempZ = normal.Z * dot * 2f;
return new Vector3(vector.X - tempX, vector.Y - tempY, vector.Z - tempZ);
}
}
/// <summary>
/// Restricts a vector between a min and max value.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The restricted vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max)
{
// This compare order is very important!!!
// We must follow HLSL behavior in the case user specified min value is bigger than max value.
float x = value1.X;
x = (min.X > x) ? min.X : x; // max(x, minx)
x = (max.X < x) ? max.X : x; // min(x, maxx)
float y = value1.Y;
y = (min.Y > y) ? min.Y : y; // max(y, miny)
y = (max.Y < y) ? max.Y : y; // min(y, maxy)
float z = value1.Z;
z = (min.Z > z) ? min.Z : z; // max(z, minz)
z = (max.Z < z) ? max.Z : z; // min(z, maxz)
return new Vector3(x, y, z);
}
/// <summary>
/// Linearly interpolates between two vectors based on the given weighting.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of the second source vector.</param>
/// <returns>The interpolated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount)
{
if (Vector.IsHardwareAccelerated)
{
Vector3 firstInfluence = value1 * (1f - amount);
Vector3 secondInfluence = value2 * amount;
return firstInfluence + secondInfluence;
}
else
{
return new Vector3(
value1.X + (value2.X - value1.X) * amount,
value1.Y + (value2.Y - value1.Y) * amount,
value1.Z + (value2.Z - value1.Z) * amount);
}
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="position">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Transform(Vector3 position, Matrix4x4 matrix)
{
return new Vector3(
position.X * matrix.M11 + position.Y * matrix.M21 + position.Z * matrix.M31 + matrix.M41,
position.X * matrix.M12 + position.Y * matrix.M22 + position.Z * matrix.M32 + matrix.M42,
position.X * matrix.M13 + position.Y * matrix.M23 + position.Z * matrix.M33 + matrix.M43);
}
/// <summary>
/// Transforms a vector normal by the given matrix.
/// </summary>
/// <param name="normal">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 TransformNormal(Vector3 normal, Matrix4x4 matrix)
{
return new Vector3(
normal.X * matrix.M11 + normal.Y * matrix.M21 + normal.Z * matrix.M31,
normal.X * matrix.M12 + normal.Y * matrix.M22 + normal.Z * matrix.M32,
normal.X * matrix.M13 + normal.Y * matrix.M23 + normal.Z * matrix.M33);
}
/// <summary>
/// Transforms a vector by the given Quaternion rotation value.
/// </summary>
/// <param name="value">The source vector to be rotated.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Transform(Vector3 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wx2 = rotation.W * x2;
float wy2 = rotation.W * y2;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float xz2 = rotation.X * z2;
float yy2 = rotation.Y * y2;
float yz2 = rotation.Y * z2;
float zz2 = rotation.Z * z2;
return new Vector3(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2) + value.Z * (yz2 - wx2),
value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0f - xx2 - yy2));
}
#endregion Public Static Methods
#region Public operator methods
// All these methods should be inlined as they are implemented
// over JIT intrinsics
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Add(Vector3 left, Vector3 right)
{
return left + right;
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Subtract(Vector3 left, Vector3 right)
{
return left - right;
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Multiply(Vector3 left, Vector3 right)
{
return left * right;
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Multiply(Vector3 left, float right)
{
return left * right;
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Multiply(float left, Vector3 right)
{
return left * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Divide(Vector3 left, Vector3 right)
{
return left / right;
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="divisor">The scalar value.</param>
/// <returns>The result of the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Divide(Vector3 left, float divisor)
{
return left / divisor;
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Negate(Vector3 value)
{
return -value;
}
#endregion Public operator methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using DotNetMatrix;
namespace ERY.EMath
{
[Serializable]
public class Matrix : ICloneable
{
public static double tolerance = 1e-10;
private static MatrixDiagonalizers.IMatrixDiagonalizer sDiagonalizer;
private int mRows;
private int mCols;
private Complex[] mElements;
private bool mValidDeterminant = false;
private Complex mDeterminant;
public static bool CanDiagonalizeNonHermitian
{
get { return MatrixDiagonalizers.DiagonalizerFactory.CanDiagonalizeNonHermitian; }
}
public Matrix()
{ }
public Matrix(int rows, int cols)
{
SetMatrixSize(rows, cols);
}
public Matrix(int rows, int cols, params double[] vals)
{
if (vals.Length != rows * cols)
throw new ArgumentException("Not right number of values.");
mElements = null;
mRows = 0;
mCols = 0;
SetMatrixSize(rows, cols);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
this[i, j] = vals[i * cols + j];
}
}
}
/// <summary>
/// Creates a column vector Matrix from the input.
/// A column vector is a Matrix with a single column.
/// </summary>
/// <param name="vector"></param>
public Matrix(double[] vector)
: this(vector, true)
{
}
/// <summary>
/// Creates a row or column vector from the input.
/// A column vector is a Matrix with a single column.
/// A row vector is a Matrix with a single row.
/// </summary>
/// <param name="vector"></param>
/// <param name="columnVector">True causes a column vector to be generated, false
/// creates a row vector.</param>
public Matrix(double[] vector, bool columnVector)
{
if (columnVector)
{
SetMatrixSize(vector.Length, 1);
for (int i = 0; i < vector.Length; i++)
this[i, 0] = vector[i];
}
else
{
SetMatrixSize(1, vector.Length);
for (int i = 0; i < vector.Length; i++)
this[0, i] = vector[i];
}
}
/// <summary>
/// Creates a real matrix by copying values from the array.
/// </summary>
/// <param name="realmatrix"></param>
public Matrix(double[,] realmatrix)
{
SetMatrixSize(realmatrix.GetUpperBound(0) + 1, realmatrix.GetUpperBound(1) + 1);
for (int i = 0; i < realmatrix.GetUpperBound(0) + 1; i++)
for (int j = 0; j < realmatrix.GetUpperBound(1) + 1; j++)
{
this[i, j] = realmatrix[i, j];
}
}
public Matrix(Matrix source)
{
mElements = null;
mRows = 0;
mCols = 0;
CopyFrom(source);
}
~Matrix()
{
ClearMatrix();
}
public Complex[] GetData()
{
return (Complex[])mElements.Clone();
}
public Complex this[int row, int col]
{
get
{
if (row < 0 || row >= mRows || col < 0 || col >= mCols)
throw new Exception("Invalid matrix element accessed.");
return mElements[row * mCols + col];
}
set
{
if (row < 0 || row >= mRows || col < 0 || col >= mCols)
throw new Exception("Invalid matrix element accessed.");
mElements[row * mCols + col] = value;
if (mValidDeterminant)
mValidDeterminant = false;
}
}
public int Rows
{
get { return mRows; }
}
public int Columns
{
get { return mCols; }
}
/// <summary>
/// Calculate the sum of the squares of all the elements in a column.
/// If you wish to normalize the column, this value must be square-rooted.
/// </summary>
/// <param name="colIndex"></param>
/// <returns></returns>
public double CalcColumnNorm(int colIndex)
{
double result = 0;
for (int i = 0; i < Rows; i++)
{
result += this[i, colIndex].MagnitudeSquared;
}
return result;
}
/// <summary>
/// Calculate the sum of the squares of all the elements in a row.
/// If you wish to normalize the row, this value must be square-rooted.
/// </summary>
/// <param name="colIndex"></param>
/// <returns></returns>
public double CalcRowNorm(int rowIndex)
{
double result = 0;
for (int i = 0; i < Columns; i++)
{
result += this[rowIndex, i].MagnitudeSquared;
}
return result;
}
public void ClearMatrix()
{
mElements = null;
mRows = mCols = 0;
}
public void SetMatrixSize(int rows, int cols)
{
ClearMatrix();
mElements = new Complex[rows * cols];
mRows = rows;
mCols = cols;
}
public void SetZero()
{
for (int i = 0; i < mRows; i++)
{
for (int j = 0; j < mCols; j++)
this[i, j] = 0;
}
}
public void CopyFrom(Matrix source)
{
ClearMatrix();
SetMatrixSize(source.mRows, source.mCols);
for (int i = 0; i < mRows; i++)
{
for (int j = 0; j < mCols; j++)
{
this[i, j] = source[i, j];
}
}
}
public bool IsSquare
{
get { return mRows == mCols; }
}
public bool IsDiagonal
{
get
{
// check for meaningless condition
if (mRows != mCols)
return false;
// we want the tolerance to be for off-diagonals at a factor of tolerance less than the diagonals.
// so first find the smallest value on the diagonal
double smallest = this[0, 0].Magnitude;
for (int i = 1; i < mRows; i++)
if (this[i, i].Magnitude < smallest)
smallest = this[i, i].Magnitude;
Matrix test = Round(tolerance * smallest).Round(tolerance);
for (int i = 0; i < mRows; i++)
{
for (int j = 0; j < mCols; j++)
{
// skip diagonal
if (i == j) continue;
Complex elem = test[i, j];
// if off-diagonal element is non-zero, then this is not diagonal
if (elem != 0)
return false;
}
}
// no non-diagonal element tested positive, so return true.
return true;
}
}
public bool IsUpperTriangular
{
get
{
if (IsSquare == false)
return false;
for (int i = 1; i < Rows; i++)
{
for (int j = 0; j < i; j++)
{
if (this[i, j].MagnitudeSquared > Complex.TOLERANCE)
return false;
}
}
return true;
}
}
public bool IsIdentity
{
get
{
if (!IsSquare)
return false;
Matrix test = new Matrix(this - Identity(mRows));
return test.IsZero;
}
}
public bool IsZero
{
get
{
Matrix test = Round();
for (int i = 0; i < mRows; i++)
{
for (int j = 0; j < mCols; j++)
{
if (test[i, j] != 0)
return false;
}
}
return true;
}
}
public bool IsSymmetric
{
get
{
Matrix result = this - this.Transpose();
return (result.IsZero);
}
}
public bool IsHermitian
{
get
{
Matrix result = this - this.HermitianConjugate();
return (result.IsZero);
}
}
public bool AllElementsReal
{
get
{
for (int i = 0; i < Rows; i++)
{
for (int j = 0; j < Columns; j++)
{
Complex v = this[i, j].Round(tolerance);
if (v.ImagPart != 0)
return false;
}
}
return true;
}
}
// matrix diagonalization
public static int technique = 0;
/// <summary>
/// returns a column vector with the eigenvalues
/// </summary>
/// <returns></returns>
public Matrix EigenValues()
{
Matrix eigenvals, ev;
EigenValsVecs(out eigenvals, out ev);
return eigenvals;
}
/// <summary>
/// returns the eigenvectors
/// </summary>
/// <returns></returns>
public Matrix EigenVecs()
{
Matrix eigenvals, ev;
EigenValsVecs(out eigenvals, out ev);
return ev;
}
/// <summary>
/// returns the eigenvalues and eigenvectors.
/// </summary>
/// <param name="eigenvals"></param>
/// <param name="eigenvecs"></param>
public void EigenValsVecs(out Matrix eigenvals, out Matrix eigenvecs)
{
if (Columns == 1 && Rows == 1)
{
eigenvals = this.Clone();
eigenvecs = Matrix.Identity(1);
return;
}
MatrixDiagonalizers.DiagonalizerFactory.EigenValsVecs(this, out eigenvals, out eigenvecs);
}
private void UseGeneralMatrix(out Matrix eigenvals, out Matrix eigenvecs)
{
if (AllElementsReal == false)
throw new Exception("All matrix elements must be real to diagonalize.");
double[][] eles = new double[Rows][];
for (int i = 0; i < Rows; i++)
eles[i] = new double[Columns];
for (int i = 0; i < Rows; i++)
{
for (int j = 0; j < Columns; j++)
{
eles[i][j] = this[i, j].RealPart;
}
}
GeneralMatrix matrix = new GeneralMatrix(eles);
EigenvalueDecomposition evs = new EigenvalueDecomposition(matrix);
GeneralMatrix vectors = evs.GetV();
eigenvecs = new Matrix(Rows, Columns);
for (int i = 0; i < Rows; i++)
{
for (int j = 0; j < Columns; j++)
{
eigenvecs[i, j] = vectors.GetElement(i, j);
}
}
double[] values = evs.RealEigenvalues;
double[] valimag = evs.ImagEigenvalues;
eigenvals = new Matrix(Rows, 1);
for (int i = 0; i < Rows; i++)
{
eigenvals[i, 0] = new Complex(values[i], valimag[i]);
}
}
/*
void jacobiRotation(Matrix eigenvals);
void jacobiRotation(Matrix eigenvals, Matrix eigenvecs);
Matrix squareRoot(); // returns a matrix A satisfying A*A = *this;
*/
// matrix basic routines
// returns a matrix with each element's Complex conjugate
public Matrix ComplexConjugate()
{
Matrix retval = new Matrix(mRows, mCols);
for (int j = 0; j < mRows; j++)
{
for (int i = 0; i < mCols; i++)
retval[j, i] = this[j, i].Conjugate();
}
return retval;
}
// returns the transpose of this matrix
public Matrix Transpose()
{
Matrix retval = new Matrix(mCols, mRows);
for (int j = 0; j < mCols; j++)
{
for (int i = 0; i < mRows; i++)
retval[j, i] = this[i, j];
}
return retval;
}
// returns the hermitian conjugate of this matrix
public Matrix HermitianConjugate()
{
Matrix retval = new Matrix(mCols, mRows);
for (int j = 0; j < mCols; j++)
{
for (int i = 0; i < mRows; i++)
retval[j, i] = this[i, j].Conjugate();
}
return retval;
}
// check to see if we can add these two matrices
public static bool CanAdd(Matrix a, Matrix b)
{
if (a.mRows == b.mRows && a.mCols == b.mCols)
return true;
else
return false;
}
// check to see if we can multiply together these two matrices. This is the left matrix.
public static bool CanMultiply(Matrix a, Matrix b)
{
if (a.mCols == b.mRows)
return true;
else
return false;
}
public Complex Determinant()
{
if (mRows != mCols)
throw new Exception("Can't take the determinant of a non-square matrix!");
if (mRows == 1)
return this[0, 0];
if (!mValidDeterminant)
{
mDeterminant = CalcDeterminant();
mValidDeterminant = true;
}
return mDeterminant;
}
private Complex CalcDeterminant()
{
if (mRows == 2)
{
return this[0, 0] * this[1, 1] -
this[1, 0] * this[0, 1];
}
else
{
Complex retval = new Complex();
for (int i = 0; i < mCols; i++)
{
retval += this[0, i] * CofactorMatrix(0, i).Determinant()
* ((i % 2 == 1) ? -1 : 1);
}
return retval;
}
}
public Matrix Invert()
{
return InvertByRowOperations();
}
public Matrix SubMatrix(int startRow, int startCol, int rows, int cols)
{
Matrix retval = new Matrix(rows, cols);
for (int i = 0; i < retval.mRows; i++)
{
for (int j = 0; j < retval.mCols; j++)
{
retval[i, j] = this[i + startRow, j + startCol];
}
}
return retval;
}
public Matrix CofactorMatrix(int row, int col)
{
Matrix retval = new Matrix(mRows - 1, mCols - 1);
for (int i = 0; i < retval.mRows; i++)
{
for (int j = 0; j < retval.mCols; j++)
{
int x = i, y = j;
if (x >= row) x++;
if (y >= col) y++;
retval[i, j] = this[x, y];
}
}
return retval;
}
// inversion by cofactor
public Matrix InvertByCofactorMethod()
{
Complex det = Determinant();
Matrix retval = new Matrix(mRows, mCols);
if (det.RealPart == 0.0 && det.ImagPart == 0.0)
throw new Exception("Singular matrix.");
for (int i = 0; i < mRows; i++)
{
for (int j = 0; j < mCols; j++)
{
// transpose of cofactor matrix, so use j,i instead.
retval[j, i] = CofactorMatrix(i, j).Determinant()
* (((i + j) % 2 == 1) ? -1.0 : 1.0);
}
}
retval /= det;
return retval;
}
public Matrix InvertByRowOperations()
{
if (!IsSquare)
throw new Exception("Matrix not square!");
Matrix retval = new Matrix(Rows, Columns * 2);
// build the inversion matrix
for (int i = 0; i < Columns; i++)
for (int j = 0; j < Rows; j++)
retval[j, i] = this[j, i];
for (int i = Columns; i < Columns * 2; i++)
for (int j = 0; j < Rows; j++)
retval[j, i] = ((i - Columns) == j) ? 1 : 0;
// do the columns one by one
for (int col = 0; col < Columns; col++)
{
if (retval[col, col] == new Complex(0, 0))
{
for (int row = col + 1; row < Rows; row++)
{
if (retval[row, col] != new Complex(0, 0))
{
retval.AddRow(col, row, 1);
}
}
}
if (retval[col, col] == new Complex(0, 0))
{
// apparently we are singular.
throw new Exception("Singular matrix.");
}
retval.ScaleRow(col, 1 / retval[col, col]);
for (int row = 0; row < Rows; row++)
{
if (row == col)
continue;
Complex scale = -retval[row, col];
retval.AddRow(row, col, scale);
}
}
// extract the actual inversion matrix
return retval.SubMatrix(0, Columns, Rows, Columns);
}
public void ScaleRow(int row, Complex scale)
{
for (int i = 0; i < Columns; i++)
this[row, i] *= scale;
}
public void AddRow(int rowdest, int rowsrc, Complex scale)
{
for (int i = 0; i < Columns; i++)
this[rowdest, i] += this[rowsrc, i] * scale;
}
// operators
public static Matrix operator -(Matrix t)
{
Matrix retval = new Matrix(t.Rows, t.Columns);
for (int i = 0; i < t.Rows; i++)
{
for (int j = 0; j < t.Columns; j++)
retval[i, j] = -t[i, j];
}
return retval;
}
public static Matrix operator +(Matrix a, Matrix b)
{
if (!CanAdd(a, b))
throw new Exception("Can't add these matrices.");
Matrix retval = new Matrix(a.Rows, a.Columns);
for (int i = 0; i < a.Rows; i++)
{
for (int j = 0; j < a.Columns; j++)
{
retval[i, j] = a[i, j] + b[i, j];
}
}
return retval;
}
public static Matrix operator -(Matrix a, Matrix b)
{
if (!CanAdd(a, b))
throw new Exception("Can't add these matrices.");
Matrix retval = new Matrix(a.Rows, a.Columns);
for (int i = 0; i < a.Rows; i++)
{
for (int j = 0; j < a.Columns; j++)
{
retval[i, j] = a[i, j] - b[i, j];
}
}
return retval;
}
public static Matrix operator *(Matrix a, Matrix b)
{
if (!CanMultiply(a, b))
throw new Exception("Can't multiply these matrices in this order.");
Matrix retval = new Matrix(a.mRows, b.mCols);
//for (int i = 0; i < retval.mRows; i++)
//{
// for (int j = 0; j < retval.mCols; j++)
// {
// retval[i, j] = 0;
// for (int k = 0; k < a.mCols; k++)
// {
// retval[i, j] += a[i, k] * b[k, j];
// }
// }
//}
Complex result = new Complex();
for (int i = 0; i < retval.mRows; i++)
{
for (int j = 0; j < retval.mCols; j++)
{
int index = i * retval.mCols + j;
int m = i * a.mCols;
int n = j;
result.x = 0;
result.y = 0;
for (int k = 0; k < a.mCols; k++)
{
Complex aval = a.mElements[m];
Complex bval = b.mElements[n];
double new_x = aval.x * bval.x - aval.y * bval.y;
double new_y = aval.x * bval.y + aval.y * bval.x;
result.x += new_x;
result.y += new_y;
m += 1;
n += b.mCols;
}
retval.mElements[index] = result;
}
}
return retval;
}
public static Vector3 operator *(Matrix a, Vector3 b)
{
Vector3 retval = new Vector3();
retval.X = (a[0, 0] * b.X + a[0, 1] * b.Y + a[0, 2] * b.Z).RealPart;
retval.Y = (a[1, 0] * b.X + a[1, 1] * b.Y + a[1, 2] * b.Z).RealPart;
retval.Z = (a[2, 0] * b.X + a[2, 1] * b.Y + a[2, 2] * b.Z).RealPart;
return retval;
}
public static Matrix operator *(Matrix a, Complex b)
{
Matrix retval = new Matrix(a);
for (int i = 0; i < retval.Rows; i++)
{
for (int j = 0; j < retval.Columns; j++)
{
retval[i, j] *= b;
}
}
return retval;
}
public static Matrix operator *(Complex a, Matrix b)
{
return b * a;
}
public static Matrix operator /(Matrix a, Complex b)
{
Matrix retval = new Matrix(a);
for (int i = 0; i < retval.Rows; i++)
{
for (int j = 0; j < retval.Columns; j++)
{
retval[i, j] /= b;
}
}
return retval;
}
//Complex operator () (int row, int col) { return element(row, col); }
public override string ToString()
{
return ToString("");
}
public string ToString(string formatString)
{
string retval = "[ ";
for (int i = 0; i < mRows; i++)
{
if (i > 0)
retval += "\r\n ";
retval += "[ ";
for (int j = 0; j < mCols; j++)
{
retval += this[i, j].ToString(formatString);
retval += ", ";
}
retval += "] ";
}
retval += "]";
return retval;
}
/// <summary>
/// Returns a size by size matrix with all elements zero.
/// </summary>
/// <param name="size"></param>
/// <returns></returns>
public static Matrix Zero(int size) { return new Matrix(size, size); }
/// <summary>
/// Returns a size by size identity matrix
/// </summary>
/// <param name="size"></param>
/// <returns></returns>
public static Matrix Identity(int size)
{
Matrix retval = new Matrix(size, size);
for (int i = 0; i < retval.mRows; i++)
{
for (int j = 0; j < retval.mCols; j++)
{
if (i == j)
retval[i, j] = 1;
else
retval[i, j] = 0;
}
}
return retval;
}
/// <summary>
/// Returns a matrix with random values, from 0 to 1.
/// </summary>
/// <param name="rows">How many rows the matrix should contain.</param>
/// <param name="cols">How many columns the matrix should contain.</param>
/// <param name="real">True if all elements should be real, imaginary parts are zero.</param>
/// <param name="hermitian">True if the matrix generated should be Hermitian. If
/// real and hermitian are true, then the generated matrix will be symmetric.</param>
/// <returns></returns>
public static Matrix RandomMatrix(int rows, int cols, bool real, bool hermitian, Random rnd)
{
Matrix retval = new Matrix(rows, cols);
if (rnd == null)
rnd = new Random();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (real)
retval[i, j] = rnd.NextDouble();
else
retval[i, j] = new Complex(rnd.NextDouble(), rnd.NextDouble());
}
}
if (hermitian)
{
// copy upper triangular to lower triangular, and conjugate to make Hermitian
// make sure diagonals are real.
for (int i = 0; i < rows; i++)
{
for (int j = 0; j <= i; j++)
{
if (i == j)
{
retval[i, j] = new Complex(retval[i, j].RealPart, 0);
continue;
}
retval[i, j] = retval[j, i].Conjugate();
}
}
System.Diagnostics.Debug.Assert(retval.IsHermitian);
}
return retval;
}
/*
static Matrix random(int rows, int cols); // returns a matrix full of random integers, from zero to max-1
// returns a matrix full of random integers, from zero to max-1
static Matrix random(int rows, int cols, int max)
{
Matrix retval(rows, cols);
for (int i = 0; i < retval.mRows; i++)
{
for (int j = 0; j < retval.mCols; j++)
{
retval.this[i, j] = Complex(int(rand() * double(max) / double(RAND_MAX)));
}
}
return retval;
}
// returns a random symmetric real matrix
static Matrix randomSymmetric(int size){
Matrix retval(size, size);
for (int i = 0; i < retval.mRows; i++)
{
for (int j = i; j < retval.mCols; j++)
{
retval[j,i] = retval.this[i, j] = Complex(rand());
}
}
return retval;
}
*/
// cuts everything smaller than TOLERANCE. equivalent to *this = this.round();
public void SetRound()
{
for (int i = 0; i < mRows; i++)
{
for (int j = 0; j < mCols; j++)
{
if (Math.Abs(this[i, j].RealPart) < tolerance)
this[i, j] = new Complex(0, this[i, j].ImagPart);
if (Math.Abs(this[i, j].ImagPart) < tolerance)
this[i, j] = new Complex(this[i, j].RealPart, 0);
}
}
}
/// <summary>
/// returns a matrix with everything smaller than TOLERANCE
/// set to zero.
/// </summary>
/// <returns></returns>
public Matrix Round()
{
return Round(1);
}
/// <summary>
/// Rounds the matrix trimming off any values of
/// size tolerance * relativeTo.
/// </summary>
/// <param name="relativeTo"></param>
/// <returns></returns>
public Matrix Round(double relativeTo)
{
Matrix retval = new Matrix(this);
for (int i = 0; i < mRows; i++)
{
for (int j = 0; j < mCols; j++)
{
Complex value = retval[i, j];
retval[i, j] = retval[i, j].Round(relativeTo * tolerance);
}
}
return retval;
}
// forces this matrix to be unitary, by doing Graham-Schmidt orthogonalization of rows, and normalizing them. Use with caution.
public double ForceUnitary()
{
if (!IsSquare)
return 0;
Matrix save = new Matrix(this);
// Do Graham-Schmidt orthogonalization
for (int i = 0; i < mRows; i++)
{
// subtract out projections
for (int j = 0; j < i; j++)
{
Complex proj = new Complex();
for (int c = 0; c < mCols; c++)
proj += this[i, c] * this[j, c].Conjugate();
for (int c = 0; c < mCols; c++)
this[i, c] -= proj * this[j, c];
}
// normalize the row
double norm2 = 0;
for (int c = 0; c < mCols; c++)
norm2 += this[i, c].MagnitudeSquared;
for (int c = 0; c < mCols; c++)
this[i, c] /= Math.Sqrt(norm2);
}
return 0;
}
/// <summary>
/// Returns a matrix containing only the real parts of the values in this matrix.
/// </summary>
/// <returns></returns>
public Matrix GetRealPart()
{
Matrix retval = new Matrix(mRows, mCols);
for (int i = 0; i < Rows; i++)
{
for (int j = 0; j < Columns; j++)
{
retval[i, j] = this[i, j].RealPart;
}
}
return retval;
}
/// <summary>
/// Returns a matrix containing only the imaginary parts of the values in this matrix.
/// All values in the returned matrix are real.
/// </summary>
/// <returns></returns>
public Matrix GetImagPart()
{
Matrix retval = new Matrix(mRows, mCols);
for (int i = 0; i < Rows; i++)
{
for (int j = 0; j < Columns; j++)
{
retval[i, j] = this[i, j].ImagPart;
}
}
return retval;
}
/// <summary>
/// Calculates and returns the trace of the matrix. Throw an exception if the matrix is
/// not square.
/// </summary>
/// <returns></returns>
public Complex Trace()
{
if (!IsSquare)
throw new InvalidOperationException("Can only calculate trace of square matrix.");
Complex retval = 0;
for (int i = 0; i < Rows; i++)
retval += this[i, i];
return retval;
}
#region ICloneable Members
public Matrix Clone()
{
Matrix retval = new Matrix(Rows, Columns);
retval.mElements = new Complex[Rows * Columns];
mElements.CopyTo(retval.mElements, 0);
return retval;
}
object ICloneable.Clone()
{
return Clone();
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="matrix"></param>
/// <param name="destRow"></param>
/// <param name="destCol"></param>
/// <param name="row"></param>
/// <param name="col"></param>
/// <param name="rows"></param>
/// <param name="cols"></param>
public void CopySubmatrixFrom(Matrix matrix, int destRow, int destCol,
int row, int col, int rows, int cols)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
this[destRow + i, destCol + j] =
matrix[row + i, col + j];
}
}
}
public void SetRow(int row, Vector3 v)
{
if (Columns != 3)
throw new ArgumentException("Can only set row with a vector in a matrix with 3 columns.");
this[row, 0] = v.X;
this[row, 1] = v.Y;
this[row, 2] = v.Z;
}
public void SetColumn(int col, Vector3 v)
{
if (Columns != 3)
throw new ArgumentException("Can only set column with a vector in a matrix with 3 rows.");
this[0, col] = v.X;
this[1, col] = v.Y;
this[2, col] = v.Z;
}
public void SetColumns(params Vector3[] v)
{
if (v.Length != Columns)
throw new ArgumentException("Must supply the same amount of vectors as columns.");
for (int i = 0; i < v.Length; i++)
SetColumn(i, v[i]);
}
public void SetRows(params Vector3[] v)
{
if (v.Length != Rows)
throw new ArgumentException("Must supply the same amount of vectors as rows.");
for (int i = 0; i < v.Length; i++)
SetRow(i, v[i]);
}
public Vector3 GetRowAsVector3(int row)
{
if (Columns != 3)
throw new InvalidOperationException("Cannot get a Vector3.");
return new Vector3(this[row, 0].RealPart, this[row, 1].RealPart, this[row, 2].RealPart);
}
public Vector3 GetColumnAsVector3(int col)
{
if (Rows != 3)
throw new InvalidOperationException("Cannot get a Vector3.");
return new Vector3(this[0, col].RealPart, this[1, col].RealPart, this[2, col].RealPart);
}
public Matrix ToTriDiagonal(out Matrix transform)
{
if (IsSquare == false)
throw new InvalidOperationException("Only square matrices can be reduced to tridiagonal form.");
Matrix retval = this.Clone();
transform = Matrix.Identity(this.Rows);
for (int block = 1; block < this.Rows - 1; block++)
{
Matrix x = retval.SubMatrix(block, block - 1, this.Rows - block, 1);
const int sign = -1;
double alpha = x[0, 0].Argument;
Complex fact = Complex.Exp(new Complex(0, alpha));
Matrix u = x.Clone();
double xnorm = Math.Sqrt(x.CalcColumnNorm(0));
u[0, 0] += sign * xnorm * fact;
if (u.IsZero) continue;
double H = 0.5 * (u.HermitianConjugate() * u)[0, 0].RealPart;
double Halt = xnorm * xnorm + sign * xnorm * (x[0, 0] / fact).RealPart;
Matrix sub = Matrix.Identity(this.Rows - block) - u * u.HermitianConjugate() / H;
Matrix thisTrans = Matrix.Identity(this.Rows);
thisTrans.SetSubMatrix(block, block, sub);
transform = transform * thisTrans;
retval = transform.HermitianConjugate() * this * transform;
}
return retval;
}
private void SetSubMatrix(int startRow, int startCol, Matrix newSub)
{
for (int i = 0; i < newSub.Rows; i++)
{
for (int j = 0; j < newSub.Columns; j++)
{
this[startRow + i, startCol + j] = newSub[i, j];
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Overlays.Direct
{
public abstract class DirectPanel : OsuClickableContainer, IHasContextMenu
{
public readonly BeatmapSetInfo SetInfo;
private const double hover_transition_time = 400;
private const int maximum_difficulty_icons = 10;
private Container content;
public PreviewTrack Preview => PlayButton.Preview;
public Bindable<bool> PreviewPlaying => PlayButton?.Playing;
protected abstract PlayButton PlayButton { get; }
protected abstract Box PreviewBar { get; }
protected virtual bool FadePlayButton => true;
protected override Container<Drawable> Content => content;
protected Action ViewBeatmap;
protected DirectPanel(BeatmapSetInfo setInfo)
{
Debug.Assert(setInfo.OnlineBeatmapSetID != null);
SetInfo = setInfo;
}
private readonly EdgeEffectParameters edgeEffectNormal = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Offset = new Vector2(0f, 1f),
Radius = 2f,
Colour = Color4.Black.Opacity(0.25f),
};
private readonly EdgeEffectParameters edgeEffectHovered = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Offset = new Vector2(0f, 5f),
Radius = 10f,
Colour = Color4.Black.Opacity(0.3f),
};
[BackgroundDependencyLoader(permitNulls: true)]
private void load(BeatmapManager beatmaps, OsuColour colours, BeatmapSetOverlay beatmapSetOverlay)
{
AddInternal(content = new Container
{
RelativeSizeAxes = Axes.Both,
Masking = true,
EdgeEffect = edgeEffectNormal,
Children = new[]
{
CreateBackground(),
new DownloadProgressBar(SetInfo)
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Depth = -1,
},
}
});
Action = ViewBeatmap = () =>
{
Debug.Assert(SetInfo.OnlineBeatmapSetID != null);
beatmapSetOverlay?.FetchAndShowBeatmapSet(SetInfo.OnlineBeatmapSetID.Value);
};
}
protected override void Update()
{
base.Update();
if (PreviewPlaying.Value && Preview != null && Preview.TrackLoaded)
{
PreviewBar.Width = (float)(Preview.CurrentTime / Preview.Length);
}
}
protected override bool OnHover(HoverEvent e)
{
content.TweenEdgeEffectTo(edgeEffectHovered, hover_transition_time, Easing.OutQuint);
content.MoveToY(-4, hover_transition_time, Easing.OutQuint);
if (FadePlayButton)
PlayButton.FadeIn(120, Easing.InOutQuint);
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
content.TweenEdgeEffectTo(edgeEffectNormal, hover_transition_time, Easing.OutQuint);
content.MoveToY(0, hover_transition_time, Easing.OutQuint);
if (FadePlayButton && !PreviewPlaying.Value)
PlayButton.FadeOut(120, Easing.InOutQuint);
base.OnHoverLost(e);
}
protected override void LoadComplete()
{
base.LoadComplete();
this.FadeInFromZero(200, Easing.Out);
PreviewPlaying.ValueChanged += playing =>
{
PlayButton.FadeTo(playing.NewValue || IsHovered || !FadePlayButton ? 1 : 0, 120, Easing.InOutQuint);
PreviewBar.FadeTo(playing.NewValue ? 1 : 0, 120, Easing.InOutQuint);
};
}
protected List<DifficultyIcon> GetDifficultyIcons(OsuColour colours)
{
var icons = new List<DifficultyIcon>();
if (SetInfo.Beatmaps.Count > maximum_difficulty_icons)
{
foreach (var ruleset in SetInfo.Beatmaps.Select(b => b.Ruleset).Distinct())
icons.Add(new GroupedDifficultyIcon(SetInfo.Beatmaps.FindAll(b => b.Ruleset.Equals(ruleset)), ruleset, this is DirectListPanel ? Color4.White : colours.Gray5));
}
else
{
foreach (var b in SetInfo.Beatmaps.OrderBy(beatmap => beatmap.StarDifficulty))
icons.Add(new DifficultyIcon(b));
}
return icons;
}
protected Drawable CreateBackground() => new UpdateableBeatmapSetCover
{
RelativeSizeAxes = Axes.Both,
BeatmapSet = SetInfo,
};
public class Statistic : FillFlowContainer
{
private readonly SpriteText text;
private int value;
public int Value
{
get => value;
set
{
this.value = value;
text.Text = Value.ToString(@"N0");
}
}
public Statistic(IconUsage icon, int value = 0)
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
AutoSizeAxes = Axes.Both;
Direction = FillDirection.Horizontal;
Spacing = new Vector2(5f, 0f);
Children = new Drawable[]
{
text = new OsuSpriteText { Font = OsuFont.GetFont(weight: FontWeight.SemiBold, italics: true) },
new SpriteIcon
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Icon = icon,
Shadow = true,
Size = new Vector2(14),
},
};
Value = value;
}
}
public MenuItem[] ContextMenuItems => new MenuItem[]
{
new OsuMenuItem("View Beatmap", MenuItemType.Highlighted, ViewBeatmap),
};
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Diagnostics;
using System.Globalization;
using System.Collections;
namespace System.Xml
{
internal partial class XsdCachingReader : XmlReader, IXmlLineInfo
{
private enum CachingReaderState
{
None = 0,
Init = 1,
Record = 2,
Replay = 3,
ReaderClosed = 4,
Error = 5,
}
private XmlReader _coreReader;
private XmlNameTable _coreReaderNameTable;
private ValidatingReaderNodeData[] _contentEvents;
private ValidatingReaderNodeData[] _attributeEvents;
private ValidatingReaderNodeData _cachedNode;
private CachingReaderState _cacheState;
private int _contentIndex;
private int _attributeCount;
private bool _returnOriginalStringValues;
private CachingEventHandler _cacheHandler;
//current state
private int _currentAttrIndex;
private int _currentContentIndex;
private bool _readAhead;
//Lineinfo
private IXmlLineInfo _lineInfo;
//ReadAttributeValue TextNode
private ValidatingReaderNodeData _textNode;
//Constants
private const int InitialAttributeCount = 8;
private const int InitialContentCount = 4;
//Constructor
internal XsdCachingReader(XmlReader reader, IXmlLineInfo lineInfo, CachingEventHandler handlerMethod)
{
_coreReader = reader;
_lineInfo = lineInfo;
_cacheHandler = handlerMethod;
_attributeEvents = new ValidatingReaderNodeData[InitialAttributeCount];
_contentEvents = new ValidatingReaderNodeData[InitialContentCount];
Init();
}
private void Init()
{
_coreReaderNameTable = _coreReader.NameTable;
_cacheState = CachingReaderState.Init;
_contentIndex = 0;
_currentAttrIndex = -1;
_currentContentIndex = -1;
_attributeCount = 0;
_cachedNode = null;
_readAhead = false;
//Initialize the cachingReader with start state
if (_coreReader.NodeType == XmlNodeType.Element)
{
ValidatingReaderNodeData element = AddContent(_coreReader.NodeType);
element.SetItemData(_coreReader.LocalName, _coreReader.Prefix, _coreReader.NamespaceURI, _coreReader.Depth); //Only created for element node type
element.SetLineInfo(_lineInfo);
RecordAttributes();
}
}
internal void Reset(XmlReader reader)
{
_coreReader = reader;
Init();
}
// Settings
public override XmlReaderSettings Settings
{
get
{
return _coreReader.Settings;
}
}
// Node Properties
// Gets the type of the current node.
public override XmlNodeType NodeType
{
get
{
return _cachedNode.NodeType;
}
}
// Gets the name of the current node, including the namespace prefix.
public override string Name
{
get
{
return _cachedNode.GetAtomizedNameWPrefix(_coreReaderNameTable);
}
}
// Gets the name of the current node without the namespace prefix.
public override string LocalName
{
get
{
return _cachedNode.LocalName;
}
}
// Gets the namespace URN (as defined in the W3C Namespace Specification) of the current namespace scope.
public override string NamespaceURI
{
get
{
return _cachedNode.Namespace;
}
}
// Gets the namespace prefix associated with the current node.
public override string Prefix
{
get
{
return _cachedNode.Prefix;
}
}
// Gets a value indicating whether the current node can have a non-empty Value.
public override bool HasValue
{
get
{
return XmlReader.HasValueInternal(_cachedNode.NodeType);
}
}
// Gets the text value of the current node.
public override string Value
{
get
{
return _returnOriginalStringValues ? _cachedNode.OriginalStringValue : _cachedNode.RawValue;
}
}
// Gets the depth of the current node in the XML element stack.
public override int Depth
{
get
{
return _cachedNode.Depth;
}
}
// Gets the base URI of the current node.
public override string BaseURI
{
get
{
return _coreReader.BaseURI;
}
}
// Gets a value indicating whether the current node is an empty element (for example, <MyElement/>).
public override bool IsEmptyElement
{
get
{
return false;
}
}
// Gets a value indicating whether the current node is an attribute that was generated from the default value defined
// in the DTD or schema.
public override bool IsDefault
{
get
{
return false;
}
}
// Gets the quotation mark character used to enclose the value of an attribute node.
public override char QuoteChar
{
get
{
return _coreReader.QuoteChar;
}
}
// Gets the current xml:space scope.
public override XmlSpace XmlSpace
{
get
{
return _coreReader.XmlSpace;
}
}
// Gets the current xml:lang scope.
public override string XmlLang
{
get
{
return _coreReader.XmlLang;
}
}
// Attribute Accessors
// The number of attributes on the current node.
public override int AttributeCount
{
get
{
return _attributeCount;
}
}
// Gets the value of the attribute with the specified Name.
public override string GetAttribute(string name)
{
int i;
if (name.IndexOf(':') == -1)
{
i = GetAttributeIndexWithoutPrefix(name);
}
else
{
i = GetAttributeIndexWithPrefix(name);
}
return (i >= 0) ? _attributeEvents[i].RawValue : null;
}
// Gets the value of the attribute with the specified LocalName and NamespaceURI.
public override string GetAttribute(string name, string namespaceURI)
{
namespaceURI = (namespaceURI == null) ? string.Empty : _coreReaderNameTable.Get(namespaceURI);
name = _coreReaderNameTable.Get(name);
ValidatingReaderNodeData attribute;
for (int i = 0; i < _attributeCount; i++)
{
attribute = _attributeEvents[i];
if (Ref.Equal(attribute.LocalName, name) && Ref.Equal(attribute.Namespace, namespaceURI))
{
return attribute.RawValue;
}
}
return null;
}
// Gets the value of the attribute with the specified index.
public override string GetAttribute(int i)
{
if (i < 0 || i >= _attributeCount)
{
throw new ArgumentOutOfRangeException(nameof(i));
}
return _attributeEvents[i].RawValue;
}
// Gets the value of the attribute with the specified index.
public override string this[int i]
{
get
{
return GetAttribute(i);
}
}
// Gets the value of the attribute with the specified Name.
public override string this[string name]
{
get
{
return GetAttribute(name);
}
}
// Gets the value of the attribute with the specified LocalName and NamespaceURI.
public override string this[string name, string namespaceURI]
{
get
{
return GetAttribute(name, namespaceURI);
}
}
// Moves to the attribute with the specified Name.
public override bool MoveToAttribute(string name)
{
int i;
if (name.IndexOf(':') == -1)
{
i = GetAttributeIndexWithoutPrefix(name);
}
else
{
i = GetAttributeIndexWithPrefix(name);
}
if (i >= 0)
{
_currentAttrIndex = i;
_cachedNode = _attributeEvents[i];
return true;
}
else
{
return false;
}
}
// Moves to the attribute with the specified LocalName and NamespaceURI
public override bool MoveToAttribute(string name, string ns)
{
ns = (ns == null) ? string.Empty : _coreReaderNameTable.Get(ns);
name = _coreReaderNameTable.Get(name);
ValidatingReaderNodeData attribute;
for (int i = 0; i < _attributeCount; i++)
{
attribute = _attributeEvents[i];
if (Ref.Equal(attribute.LocalName, name) &&
Ref.Equal(attribute.Namespace, ns))
{
_currentAttrIndex = i;
_cachedNode = _attributeEvents[i];
return true;
}
}
return false;
}
// Moves to the attribute with the specified index.
public override void MoveToAttribute(int i)
{
if (i < 0 || i >= _attributeCount)
{
throw new ArgumentOutOfRangeException(nameof(i));
}
_currentAttrIndex = i;
_cachedNode = _attributeEvents[i];
}
// Moves to the first attribute.
public override bool MoveToFirstAttribute()
{
if (_attributeCount == 0)
{
return false;
}
_currentAttrIndex = 0;
_cachedNode = _attributeEvents[0];
return true;
}
// Moves to the next attribute.
public override bool MoveToNextAttribute()
{
if (_currentAttrIndex + 1 < _attributeCount)
{
_cachedNode = _attributeEvents[++_currentAttrIndex];
return true;
}
return false;
}
// Moves to the element that contains the current attribute node.
public override bool MoveToElement()
{
if (_cacheState != CachingReaderState.Replay || _cachedNode.NodeType != XmlNodeType.Attribute)
{
return false;
}
_currentContentIndex = 0;
_currentAttrIndex = -1;
Read();
return true;
}
// Reads the next node from the stream/TextReader.
public override bool Read()
{
switch (_cacheState)
{
case CachingReaderState.Init:
_cacheState = CachingReaderState.Record;
goto case CachingReaderState.Record;
case CachingReaderState.Record:
ValidatingReaderNodeData recordedNode = null;
if (_coreReader.Read())
{
switch (_coreReader.NodeType)
{
case XmlNodeType.Element:
//Dont record element within the content of a union type since the main reader will break on this and the underlying coreReader will be positioned on this node
_cacheState = CachingReaderState.ReaderClosed;
return false;
case XmlNodeType.EndElement:
recordedNode = AddContent(_coreReader.NodeType);
recordedNode.SetItemData(_coreReader.LocalName, _coreReader.Prefix, _coreReader.NamespaceURI, _coreReader.Depth); //Only created for element node type
recordedNode.SetLineInfo(_lineInfo);
break;
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
recordedNode = AddContent(_coreReader.NodeType);
recordedNode.SetItemData(_coreReader.Value);
recordedNode.SetLineInfo(_lineInfo);
recordedNode.Depth = _coreReader.Depth;
break;
default:
break;
}
_cachedNode = recordedNode;
return true;
}
else
{
_cacheState = CachingReaderState.ReaderClosed;
return false;
}
case CachingReaderState.Replay:
if (_currentContentIndex >= _contentIndex)
{ //When positioned on the last cached node, switch back as the underlying coreReader is still positioned on this node
_cacheState = CachingReaderState.ReaderClosed;
_cacheHandler(this);
if (_coreReader.NodeType != XmlNodeType.Element || _readAhead)
{ //Only when coreReader not positioned on Element node, read ahead, otherwise it is on the next element node already, since this was not cached
return _coreReader.Read();
}
return true;
}
_cachedNode = _contentEvents[_currentContentIndex];
if (_currentContentIndex > 0)
{
ClearAttributesInfo();
}
_currentContentIndex++;
return true;
default:
return false;
}
}
internal ValidatingReaderNodeData RecordTextNode(string textValue, string originalStringValue, int depth, int lineNo, int linePos)
{
ValidatingReaderNodeData textNode = AddContent(XmlNodeType.Text);
textNode.SetItemData(textValue, originalStringValue);
textNode.SetLineInfo(lineNo, linePos);
textNode.Depth = depth;
return textNode;
}
internal void SwitchTextNodeAndEndElement(string textValue, string originalStringValue)
{
Debug.Assert(_coreReader.NodeType == XmlNodeType.EndElement || (_coreReader.NodeType == XmlNodeType.Element && _coreReader.IsEmptyElement));
ValidatingReaderNodeData textNode = RecordTextNode(textValue, originalStringValue, _coreReader.Depth + 1, 0, 0);
int endElementIndex = _contentIndex - 2;
ValidatingReaderNodeData endElementNode = _contentEvents[endElementIndex];
Debug.Assert(endElementNode.NodeType == XmlNodeType.EndElement);
_contentEvents[endElementIndex] = textNode;
_contentEvents[_contentIndex - 1] = endElementNode;
}
internal void RecordEndElementNode()
{
ValidatingReaderNodeData recordedNode = AddContent(XmlNodeType.EndElement);
Debug.Assert(_coreReader.NodeType == XmlNodeType.EndElement || (_coreReader.NodeType == XmlNodeType.Element && _coreReader.IsEmptyElement));
recordedNode.SetItemData(_coreReader.LocalName, _coreReader.Prefix, _coreReader.NamespaceURI, _coreReader.Depth);
recordedNode.SetLineInfo(_coreReader as IXmlLineInfo);
if (_coreReader.IsEmptyElement)
{ //Simulated endElement node for <e/>, the coreReader is on cached Element node itself.
_readAhead = true;
}
}
internal string ReadOriginalContentAsString()
{
_returnOriginalStringValues = true;
string strValue = InternalReadContentAsString();
_returnOriginalStringValues = false;
return strValue;
}
// Gets a value indicating whether XmlReader is positioned at the end of the stream.
public override bool EOF
{
get
{
return _cacheState == CachingReaderState.ReaderClosed && _coreReader.EOF;
}
}
// Closes the stream, changes the ReadState to Closed, and sets all the properties back to zero.
public override void Close()
{
_coreReader.Close();
_cacheState = CachingReaderState.ReaderClosed;
}
// Returns the read state of the stream.
public override ReadState ReadState
{
get
{
return _coreReader.ReadState;
}
}
// Skips to the end tag of the current element.
public override void Skip()
{
//Skip on caching reader should move to the end of the subtree, past all cached events
switch (_cachedNode.NodeType)
{
case XmlNodeType.Element:
if (_coreReader.NodeType != XmlNodeType.EndElement && !_readAhead)
{ //will be true for IsDefault cases where we peek only one node ahead
int startDepth = _coreReader.Depth - 1;
while (_coreReader.Read() && _coreReader.Depth > startDepth)
;
}
_coreReader.Read();
_cacheState = CachingReaderState.ReaderClosed;
_cacheHandler(this);
break;
case XmlNodeType.Attribute:
MoveToElement();
goto case XmlNodeType.Element;
default:
Debug.Assert(_cacheState == CachingReaderState.Replay);
Read();
break;
}
}
// Gets the XmlNameTable associated with this implementation.
public override XmlNameTable NameTable
{
get
{
return _coreReaderNameTable;
}
}
// Resolves a namespace prefix in the current element's scope.
public override string LookupNamespace(string prefix)
{
return _coreReader.LookupNamespace(prefix);
}
// Resolves the entity reference for nodes of NodeType EntityReference.
public override void ResolveEntity()
{
throw new InvalidOperationException();
}
// Parses the attribute value into one or more Text and/or EntityReference node types.
public override bool ReadAttributeValue()
{
Debug.Assert(_cacheState == CachingReaderState.Replay);
if (_cachedNode.NodeType != XmlNodeType.Attribute)
{
return false;
}
_cachedNode = CreateDummyTextNode(_cachedNode.RawValue, _cachedNode.Depth + 1);
return true;
}
//
// IXmlLineInfo members
//
bool IXmlLineInfo.HasLineInfo()
{
return true;
}
int IXmlLineInfo.LineNumber
{
get
{
return _cachedNode.LineNumber;
}
}
int IXmlLineInfo.LinePosition
{
get
{
return _cachedNode.LinePosition;
}
}
//Private methods
internal void SetToReplayMode()
{
_cacheState = CachingReaderState.Replay;
_currentContentIndex = 0;
_currentAttrIndex = -1;
Read(); //Position on first node recorded to begin replaying
}
internal XmlReader GetCoreReader()
{
return _coreReader;
}
internal IXmlLineInfo GetLineInfo()
{
return _lineInfo;
}
private void ClearAttributesInfo()
{
_attributeCount = 0;
_currentAttrIndex = -1;
}
private ValidatingReaderNodeData AddAttribute(int attIndex)
{
Debug.Assert(attIndex <= _attributeEvents.Length);
ValidatingReaderNodeData attInfo = _attributeEvents[attIndex];
if (attInfo != null)
{
attInfo.Clear(XmlNodeType.Attribute);
return attInfo;
}
if (attIndex >= _attributeEvents.Length - 1)
{ //reached capacity of array, Need to increase capacity to twice the initial
ValidatingReaderNodeData[] newAttributeEvents = new ValidatingReaderNodeData[_attributeEvents.Length * 2];
Array.Copy(_attributeEvents, 0, newAttributeEvents, 0, _attributeEvents.Length);
_attributeEvents = newAttributeEvents;
}
attInfo = _attributeEvents[attIndex];
if (attInfo == null)
{
attInfo = new ValidatingReaderNodeData(XmlNodeType.Attribute);
_attributeEvents[attIndex] = attInfo;
}
return attInfo;
}
private ValidatingReaderNodeData AddContent(XmlNodeType nodeType)
{
Debug.Assert(_contentIndex <= _contentEvents.Length);
ValidatingReaderNodeData contentInfo = _contentEvents[_contentIndex];
if (contentInfo != null)
{
contentInfo.Clear(nodeType);
_contentIndex++;
return contentInfo;
}
if (_contentIndex >= _contentEvents.Length - 1)
{ //reached capacity of array, Need to increase capacity to twice the initial
ValidatingReaderNodeData[] newContentEvents = new ValidatingReaderNodeData[_contentEvents.Length * 2];
Array.Copy(_contentEvents, 0, newContentEvents, 0, _contentEvents.Length);
_contentEvents = newContentEvents;
}
contentInfo = _contentEvents[_contentIndex];
if (contentInfo == null)
{
contentInfo = new ValidatingReaderNodeData(nodeType);
_contentEvents[_contentIndex] = contentInfo;
}
_contentIndex++;
return contentInfo;
}
private void RecordAttributes()
{
Debug.Assert(_coreReader.NodeType == XmlNodeType.Element);
ValidatingReaderNodeData attInfo;
_attributeCount = _coreReader.AttributeCount;
if (_coreReader.MoveToFirstAttribute())
{
int attIndex = 0;
do
{
attInfo = AddAttribute(attIndex);
attInfo.SetItemData(_coreReader.LocalName, _coreReader.Prefix, _coreReader.NamespaceURI, _coreReader.Depth);
attInfo.SetLineInfo(_lineInfo);
attInfo.RawValue = _coreReader.Value;
attIndex++;
} while (_coreReader.MoveToNextAttribute());
_coreReader.MoveToElement();
}
}
private int GetAttributeIndexWithoutPrefix(string name)
{
name = _coreReaderNameTable.Get(name);
if (name == null)
{
return -1;
}
ValidatingReaderNodeData attribute;
for (int i = 0; i < _attributeCount; i++)
{
attribute = _attributeEvents[i];
if (Ref.Equal(attribute.LocalName, name) && attribute.Prefix.Length == 0)
{
return i;
}
}
return -1;
}
private int GetAttributeIndexWithPrefix(string name)
{
name = _coreReaderNameTable.Get(name);
if (name == null)
{
return -1;
}
ValidatingReaderNodeData attribute;
for (int i = 0; i < _attributeCount; i++)
{
attribute = _attributeEvents[i];
if (Ref.Equal(attribute.GetAtomizedNameWPrefix(_coreReaderNameTable), name))
{
return i;
}
}
return -1;
}
private ValidatingReaderNodeData CreateDummyTextNode(string attributeValue, int depth)
{
if (_textNode == null)
{
_textNode = new ValidatingReaderNodeData(XmlNodeType.Text);
}
_textNode.Depth = depth;
_textNode.RawValue = attributeValue;
return _textNode;
}
}
}
| |
// 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.Diagnostics;
using System.Runtime.InteropServices.ComTypes;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class MockSymUnmanagedReader : ISymUnmanagedReader, ISymUnmanagedReader2, ISymUnmanagedReader3
{
private readonly ImmutableDictionary<int, MethodDebugInfoBytes> _methodDebugInfoMap;
public MockSymUnmanagedReader(ImmutableDictionary<int, MethodDebugInfoBytes> methodDebugInfoMap)
{
_methodDebugInfoMap = methodDebugInfoMap;
}
public int GetMethodByVersion(int methodToken, int version, out ISymUnmanagedMethod retVal)
{
Assert.Equal(1, version);
MethodDebugInfoBytes info;
if (!_methodDebugInfoMap.TryGetValue(methodToken, out info))
{
retVal = null;
return SymUnmanagedReaderExtensions.E_FAIL;
}
Assert.NotNull(info);
retVal = info.Method;
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetSymAttribute(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation)
{
// The EE should never be calling ISymUnmanagedReader.GetSymAttribute.
// In order to account for EnC updates, it should always be calling
// ISymUnmanagedReader3.GetSymAttributeByVersion instead.
throw ExceptionUtilities.Unreachable;
}
public int GetSymAttributeByVersion(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation)
{
Assert.Equal(1, version);
Assert.Equal("MD2", name);
MethodDebugInfoBytes info;
if (!_methodDebugInfoMap.TryGetValue(methodToken, out info))
{
count = 0;
return SymUnmanagedReaderExtensions.S_FALSE; // This is a guess. We're not consuming it, so it doesn't really matter.
}
Assert.NotNull(info);
info.Bytes.TwoPhaseCopy(bufferLength, out count, customDebugInformation);
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetDocument(string url, Guid language, Guid languageVendor, Guid documentType, out ISymUnmanagedDocument document)
{
throw new NotImplementedException();
}
public int GetDocuments(int bufferLength, out int count, ISymUnmanagedDocument[] documents)
{
throw new NotImplementedException();
}
public int GetUserEntryPoint(out int methodToken)
{
throw new NotImplementedException();
}
public int GetMethod(int methodToken, out ISymUnmanagedMethod method)
{
throw new NotImplementedException();
}
public int GetVariables(int methodToken, int bufferLength, out int count, ISymUnmanagedVariable[] variables)
{
throw new NotImplementedException();
}
public int GetGlobalVariables(int bufferLength, out int count, ISymUnmanagedVariable[] variables)
{
throw new NotImplementedException();
}
public int GetMethodFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, out ISymUnmanagedMethod method)
{
throw new NotImplementedException();
}
public int GetNamespaces(int bufferLength, out int count, ISymUnmanagedNamespace[] namespaces)
{
throw new NotImplementedException();
}
public int Initialize(object metadataImporter, string fileName, string searchPath, IStream stream)
{
throw new NotImplementedException();
}
public int UpdateSymbolStore(string fileName, IStream stream)
{
throw new NotImplementedException();
}
public int ReplaceSymbolStore(string fileName, IStream stream)
{
throw new NotImplementedException();
}
public int GetSymbolStoreFileName(int bufferLength, out int count, char[] name)
{
throw new NotImplementedException();
}
public int GetMethodsFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, int bufferLength, out int count, ISymUnmanagedMethod[] methods)
{
throw new NotImplementedException();
}
public int GetDocumentVersion(ISymUnmanagedDocument document, out int version, out bool isCurrent)
{
throw new NotImplementedException();
}
public int GetMethodVersion(ISymUnmanagedMethod method, out int version)
{
throw new NotImplementedException();
}
public int GetMethodByVersionPreRemap(int methodToken, int version, out ISymUnmanagedMethod method)
{
throw new NotImplementedException();
}
public int GetSymAttributePreRemap(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation)
{
throw new NotImplementedException();
}
public int GetMethodsInDocument(ISymUnmanagedDocument document, int bufferLength, out int count, ISymUnmanagedMethod[] methods)
{
throw new NotImplementedException();
}
public int GetSymAttributeByVersionPreRemap(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation)
{
throw new NotImplementedException();
}
}
internal sealed class MockSymUnmanagedMethod : ISymUnmanagedMethod
{
private readonly ISymUnmanagedScope _rootScope;
public MockSymUnmanagedMethod(ISymUnmanagedScope rootScope)
{
_rootScope = rootScope;
}
int ISymUnmanagedMethod.GetRootScope(out ISymUnmanagedScope retVal)
{
retVal = _rootScope;
return SymUnmanagedReaderExtensions.S_OK;
}
int ISymUnmanagedMethod.GetSequencePointCount(out int retVal)
{
retVal = 1;
return SymUnmanagedReaderExtensions.S_OK;
}
int ISymUnmanagedMethod.GetSequencePoints(int cPoints, out int pcPoints, int[] offsets, ISymUnmanagedDocument[] documents, int[] lines, int[] columns, int[] endLines, int[] endColumns)
{
pcPoints = 1;
offsets[0] = 0;
documents[0] = null;
lines[0] = 0;
columns[0] = 0;
endLines[0] = 0;
endColumns[0] = 0;
return SymUnmanagedReaderExtensions.S_OK;
}
int ISymUnmanagedMethod.GetNamespace(out ISymUnmanagedNamespace retVal)
{
throw new NotImplementedException();
}
int ISymUnmanagedMethod.GetOffset(ISymUnmanagedDocument document, int line, int column, out int retVal)
{
throw new NotImplementedException();
}
int ISymUnmanagedMethod.GetParameters(int cParams, out int pcParams, ISymUnmanagedVariable[] parms)
{
throw new NotImplementedException();
}
int ISymUnmanagedMethod.GetRanges(ISymUnmanagedDocument document, int line, int column, int cRanges, out int pcRanges, int[] ranges)
{
throw new NotImplementedException();
}
int ISymUnmanagedMethod.GetScopeFromOffset(int offset, out ISymUnmanagedScope retVal)
{
throw new NotImplementedException();
}
int ISymUnmanagedMethod.GetSourceStartEnd(ISymUnmanagedDocument[] docs, int[] lines, int[] columns, out bool retVal)
{
throw new NotImplementedException();
}
int ISymUnmanagedMethod.GetToken(out int pToken)
{
throw new NotImplementedException();
}
}
internal sealed class MockSymUnmanagedScope : ISymUnmanagedScope, ISymUnmanagedScope2
{
private readonly ImmutableArray<ISymUnmanagedScope> _children;
private readonly ImmutableArray<ISymUnmanagedNamespace> _namespaces;
private readonly ISymUnmanagedConstant[] _constants;
private readonly int _startOffset;
private readonly int _endOffset;
public MockSymUnmanagedScope(ImmutableArray<ISymUnmanagedScope> children, ImmutableArray<ISymUnmanagedNamespace> namespaces, ISymUnmanagedConstant[] constants = null, int startOffset = 0, int endOffset = 1)
{
_children = children;
_namespaces = namespaces;
_constants = constants ?? new ISymUnmanagedConstant[0];
_startOffset = startOffset;
_endOffset = endOffset;
}
public int GetChildren(int numDesired, out int numRead, ISymUnmanagedScope[] buffer)
{
_children.TwoPhaseCopy(numDesired, out numRead, buffer);
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetNamespaces(int numDesired, out int numRead, ISymUnmanagedNamespace[] buffer)
{
_namespaces.TwoPhaseCopy(numDesired, out numRead, buffer);
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetStartOffset(out int pRetVal)
{
pRetVal = _startOffset;
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetEndOffset(out int pRetVal)
{
pRetVal = _endOffset;
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetLocalCount(out int pRetVal)
{
pRetVal = 0;
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetLocals(int cLocals, out int pcLocals, ISymUnmanagedVariable[] locals)
{
pcLocals = 0;
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetMethod(out ISymUnmanagedMethod pRetVal)
{
throw new NotImplementedException();
}
public int GetParent(out ISymUnmanagedScope pRetVal)
{
throw new NotImplementedException();
}
public int GetConstantCount(out int pRetVal)
{
pRetVal = _constants.Length;
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetConstants(int cConstants, out int pcConstants, ISymUnmanagedConstant[] constants)
{
pcConstants = _constants.Length;
if (constants != null)
{
Array.Copy(_constants, constants, constants.Length);
}
return SymUnmanagedReaderExtensions.S_OK;
}
}
internal sealed class MockSymUnmanagedNamespace : ISymUnmanagedNamespace
{
private readonly ImmutableArray<char> _nameChars;
public MockSymUnmanagedNamespace(string name)
{
if (name != null)
{
var builder = ArrayBuilder<char>.GetInstance();
builder.AddRange(name);
builder.AddRange('\0');
_nameChars = builder.ToImmutableAndFree();
}
}
int ISymUnmanagedNamespace.GetName(int numDesired, out int numRead, char[] buffer)
{
_nameChars.TwoPhaseCopy(numDesired, out numRead, buffer);
return 0;
}
int ISymUnmanagedNamespace.GetNamespaces(int cNameSpaces, out int pcNameSpaces, ISymUnmanagedNamespace[] namespaces)
{
throw new NotImplementedException();
}
int ISymUnmanagedNamespace.GetVariables(int cVars, out int pcVars, ISymUnmanagedVariable[] pVars)
{
throw new NotImplementedException();
}
}
internal delegate int GetSignatureDelegate(int bufferLength, out int count, byte[] signature);
internal sealed class MockSymUnmanagedConstant : ISymUnmanagedConstant
{
private readonly string _name;
private readonly object _value;
private readonly GetSignatureDelegate _getSignature;
public MockSymUnmanagedConstant(string name, object value, GetSignatureDelegate getSignature)
{
_name = name;
_value = value;
_getSignature = getSignature;
}
int ISymUnmanagedConstant.GetName(int bufferLength, out int count, char[] name)
{
count = _name.Length + 1; // + 1 for null terminator
Debug.Assert((bufferLength == 0) || (bufferLength == count));
for (int i = 0; i < bufferLength - 1; i++)
{
name[i] = _name[i];
}
return SymUnmanagedReaderExtensions.S_OK;
}
int ISymUnmanagedConstant.GetSignature(int bufferLength, out int count, byte[] signature)
{
return _getSignature(bufferLength, out count, signature);
}
int ISymUnmanagedConstant.GetValue(out object value)
{
value = _value;
return SymUnmanagedReaderExtensions.S_OK;
}
}
internal static class MockSymUnmanagedHelpers
{
public static void TwoPhaseCopy<T>(this ImmutableArray<T> source, int numDesired, out int numRead, T[] destination)
{
if (destination == null)
{
Assert.Equal(0, numDesired);
numRead = source.IsDefault ? 0 : source.Length;
}
else
{
Assert.False(source.IsDefault);
Assert.Equal(source.Length, numDesired);
source.CopyTo(0, destination, 0, numDesired);
numRead = numDesired;
}
}
public static void Add2(this ArrayBuilder<byte> bytes, short s)
{
var shortBytes = BitConverter.GetBytes(s);
Assert.Equal(2, shortBytes.Length);
bytes.AddRange(shortBytes);
}
public static void Add4(this ArrayBuilder<byte> bytes, int i)
{
var intBytes = BitConverter.GetBytes(i);
Assert.Equal(4, intBytes.Length);
bytes.AddRange(intBytes);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Cdn
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ProfilesOperations operations.
/// </summary>
public partial interface IProfilesOperations
{
/// <summary>
/// Lists all the CDN profiles within an Azure subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Profile>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all the CDN profiles within a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Profile>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets a CDN profile with the specified profile name under the
/// specified subscription and resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Profile>> GetWithHttpMessagesAsync(string resourceGroupName, string profileName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Creates a new CDN profile with a profile name under the specified
/// subscription and resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='profile'>
/// Profile properties needed to create a new profile.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Profile>> CreateWithHttpMessagesAsync(string resourceGroupName, string profileName, Profile profile, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Creates a new CDN profile with a profile name under the specified
/// subscription and resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='profile'>
/// Profile properties needed to create a new profile.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Profile>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string profileName, Profile profile, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates an existing CDN profile with the specified profile name
/// under the specified subscription and resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='tags'>
/// Profile tags
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Profile>> UpdateWithHttpMessagesAsync(string resourceGroupName, string profileName, System.Collections.Generic.IDictionary<string, string> tags, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates an existing CDN profile with the specified profile name
/// under the specified subscription and resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='tags'>
/// Profile tags
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Profile>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string profileName, System.Collections.Generic.IDictionary<string, string> tags, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes an existing CDN profile with the specified parameters.
/// Deleting a profile will result in the deletion of all
/// subresources including endpoints, origins and custom domains.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string profileName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes an existing CDN profile with the specified parameters.
/// Deleting a profile will result in the deletion of all
/// subresources including endpoints, origins and custom domains.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string profileName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Generates a dynamic SSO URI used to sign in to the CDN
/// supplemental portal. Supplemnetal portal is used to configure
/// advanced feature capabilities that are not yet available in the
/// Azure portal, such as core reports in a standard profile; rules
/// engine, advanced HTTP reports, and real-time stats and alerts in
/// a premium profile. The SSO URI changes approximately every 10
/// minutes.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SsoUri>> GenerateSsoUriWithHttpMessagesAsync(string resourceGroupName, string profileName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all the CDN profiles within an Azure subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Profile>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all the CDN profiles within a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Profile>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using BilSimser.GeoJson.JsonConverters;
using Newtonsoft.Json;
using Formatting = Newtonsoft.Json.Formatting;
namespace BilSimser.GeoJson.GeoJson
{
public class GeoJsonRootObject
{
private readonly string[] _geotypes = {"Polygon", "LineString", "Point", "Track"};
public string ConvertFrom(XmlDocument doc)
{
var fc = ToFeatureCollection(doc);
return JsonConvert.SerializeObject(fc, Formatting.Indented, new JsonConverter[]
{
new PositionConverter(typeof (Position)),
new LineStringConverter(typeof (LineString)),
new PropertiesConverter(typeof (Properties))
});
}
public FeatureCollection ToFeatureCollection(XmlDocument doc)
{
var fc = new FeatureCollection();
// TODO
// styleindex keeps track of hashed styles in order to match features
// styleIndex = {};
// all root placemarks in the file
var placemarks = Get(doc.DocumentElement, "Placemark");
// TODO
// get all styles
// TODO
// for each style
// create a hash in styleindex
foreach (XmlElement node in placemarks)
{
fc.features.Add(GetPlacemark(node));
}
return fc;
}
private Feature GetPlacemark(XmlElement root)
{
var geoms = GetGeometry(root);
var properties = new List<KeyValuePair<string, object>>();
var extendedData = GetOne(root, "ExtendedData");
if (geoms.Count == 0) return new Feature();
var name = NodeVal(GetOne(root, "name"));
if (name != null)
{
properties.Add(new KeyValuePair<string, object>("name", name));
}
var description = NodeVal(GetOne(root, "description"));
if (description != null)
{
properties.Add(new KeyValuePair<string, object>("description", description));
}
// TODO
// if timeSpan
// TODO
// if lineStyle
// TODO
// if polyStyle
if (extendedData != null)
{
var datas = Get(extendedData, "Data");
var simpleDatas = Get(extendedData, "SimpleData");
for (var i = 0; i < datas.Count; i++)
{
var xmlAttributeCollection = datas[i].Attributes;
if (xmlAttributeCollection != null)
{
properties.Add(new KeyValuePair<string, object>(
xmlAttributeCollection["name"].Value,
NodeVal(GetOne((XmlElement) datas[i], "value"))));
}
}
for (var i = 0; i < simpleDatas.Count; i++)
{
var xmlAttributeCollection = simpleDatas[i].Attributes;
if (xmlAttributeCollection != null)
{
properties.Add(new KeyValuePair<string, object>(
xmlAttributeCollection["name"].Value,
NodeVal(simpleDatas[i])));
}
}
}
return new Feature
{
type = "Feature",
geometry = (geoms.Count == 1)
? geoms[0]
: new Geometry
{
type = "GeometryCollection"
},
properties = new Properties
{
values = properties
}
};
}
private List<Geometry> GetGeometry(XmlElement root)
{
while (true)
{
var geoms = new List<Geometry>();
if (GetOne(root, "MultiGeometry") != null)
{
root = GetOne(root, "MultiGeometry");
continue;
}
if (GetOne(root, "MultiTrack") != null)
{
root = GetOne(root, "MultiTrack");
continue;
}
foreach (var geoType in _geotypes)
{
var geomNodes = Get(root, geoType);
if (geomNodes == null) continue;
foreach (XmlElement geomNode in geomNodes)
{
switch (geoType)
{
case "Point":
// TODO add support for PointGeometry
// Postion
geoms.Add(new Geometry
{
type = geoType
});
break;
case "LineString":
// TODO
var lines = Get(geomNode, "coordinates");
var lspos = new List<Position>();
for (var i = 0; i < lines.Count; i++)
{
var c = NodeVal(lines[i]);
lspos.Add(new Position());
}
//var pos = NodeVal(lines);
geoms.Add(new LineStringGeometry
{
type = geoType,
coordinates = lspos
});
break;
case "Polygon":
geoms.Add(GetPolygonGeometry(geomNode, geoType));
break;
case "Track":
// TODO add support for TrackGeometry
geoms.Add(new Geometry
{
type = geoType
});
break;
}
}
}
return geoms;
}
}
private static PolygonGeometry GetPolygonGeometry(XmlElement geomNode, string geoType)
{
var rings = Get(geomNode, "LinearRing");
var coords = new List<LinearRing>();
for (var j = 0; j < rings.Count; j++)
{
var linearRing = ToLinearRing(NodeVal(GetOne((XmlElement) rings[j], "coordinates")));
coords.Add(linearRing);
}
return new PolygonGeometry
{
type = geoType,
// TODO add support for multiple rings (polygons with holes)
// TODO this only selects the coordinates for the first polygon
coordinates = coords[0].coordinates
};
}
private static LinearRing ToLinearRing(string v)
{
const string trimSpace = @"(/^\s*|\s*$/g)";
const string splitSpace = @"(/\s+/)";
v = Regex.Replace(v, "\n", "");
v = Regex.Replace(v, @"[ ]{2,}", " ");
var coords = Regex.Split(v.Trim().Replace(trimSpace, ""), splitSpace);
var linestrings = coords.Select(ToLineString).ToList();
return new LinearRing
{
coordinates = linestrings
};
}
private static LineString ToLineString(string v)
{
var coords = v.Trim().Split(new[] {' '});
var positions = (from tuple in coords
select tuple.Split(new[] {','})
into split
select NumArray(split)
into item
select new Position
{
x = item[0],
y = item[1],
z = item[2]
}).ToList();
return new LineString
{
coordinates = positions
};
}
private static List<float> NumArray(IEnumerable<string> x)
{
return x.Select(float.Parse).ToList();
}
private static string NodeVal(XmlNode xmlElement)
{
if (xmlElement != null)
{
xmlElement.Normalize();
}
return (xmlElement != null && xmlElement.FirstChild != null && xmlElement.FirstChild.Value != null)
? xmlElement.FirstChild.Value
: null;
}
private static XmlElement GetOne(XmlElement item, string tagname)
{
var n = Get(item, tagname);
return (XmlElement) (n.Count > 0 ? n[0] : null);
}
private static XmlNodeList Get(XmlElement doc, string tagname)
{
return doc.GetElementsByTagName(tagname);
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
namespace FileSystemTest
{
public class DI_Constructor : IMFTestInterface
{
#region internal vars
private const string DIRA = @"DirA";
private const string DIRB = @"DirB";
private const string DIR1 = @"Dir1";
private const string DIR2 = @"Dir2";
#endregion
[SetUp]
public InitializeResult Initialize()
{
// These tests rely on underlying file system so we need to make
// sure we can format it before we start the tests. If we can't
// format it, then we assume there is no FS to test on this platform.
// delete the directory DOTNETMF_FS_EMULATION
try
{
IOTests.IntializeVolume();
Directory.CreateDirectory(GetDir(DIRA, DIR1));
Directory.CreateDirectory(GetDir(DIRA, DIR2));
Directory.CreateDirectory(GetDir(DIRB, DIR1));
Directory.CreateDirectory(GetDir(DIRB, DIR2));
}
catch (Exception ex)
{
Log.Exception("Skipping: Unable to initialize file system", ex);
return InitializeResult.Skip;
}
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
#region Helper Functions
private string GetDir(params string[] args)
{
string dir = IOTests.Volume.RootDirectory;
for (int i = 0; i < args.Length; i++)
{
dir += @"\" + args[i];
}
return dir;
}
private bool TestDirectoryInfo(string path)
{
DirectoryInfo dir = new DirectoryInfo(path);
path = RelativePath(path);
Log.Comment("Path: '" + path + "'");
if (dir.FullName != path)
{
Log.Exception("Got: '" + dir.FullName + "'");
return false;
}
return true;
}
private string RelativePath(string path)
{
// rooted
if (path.Substring(0,1) == "\\")
return path;
return Directory.GetCurrentDirectory() + "\\" + path;
}
#endregion
#region Test Cases
[TestMethod]
public MFTestResults NullArguments()
{
DirectoryInfo dir;
MFTestResults result = MFTestResults.Pass;
try
{
try
{
Log.Comment("Null Constructor");
dir = new DirectoryInfo(null);
Log.Exception( "Expected Argument exception, but got " + dir.FullName );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{ /* pass case */
Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("String.Empty Constructor");
dir = new DirectoryInfo(String.Empty);
Log.Exception( "Expected Argument exception, but got " + dir.FullName );
return MFTestResults.Fail;
}
catch (ArgumentException ae1)
{ /* pass case */
Log.Comment( "Got correct exception: " + ae1.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("White Space Constructor");
dir = new DirectoryInfo(" ");
Log.Exception( "Expected Argument exception, but got " + dir.FullName );
return MFTestResults.Fail;
}
catch (ArgumentException ae2)
{ /* pass case */
Log.Comment( "Got correct exception: " + ae2.Message );
result = MFTestResults.Pass;
}
// Try above root
Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory);
try
{
Log.Comment(".. above root Constructor");
/// .. is a valid location, while ..\\.. is not.
dir = new DirectoryInfo("..\\..");
Log.Exception( "Expected Argument exception, but got " + dir.FullName );
return MFTestResults.Fail;
}
catch (ArgumentException ae3)
{ /* pass case */
Log.Comment( "Got correct exception: " + ae3.Message );
result = MFTestResults.Pass;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults ValidCases()
{
MFTestResults result = MFTestResults.Pass;
try
{
Log.Comment("root");
if (!TestDirectoryInfo(Directory.GetCurrentDirectory()))
{
return MFTestResults.Fail;
}
Log.Comment("test created dirs");
if (!TestDirectoryInfo(GetDir(DIRA)))
{
return MFTestResults.Fail;
}
if (!TestDirectoryInfo(GetDir(DIRB)))
{
return MFTestResults.Fail;
}
if (!TestDirectoryInfo(GetDir(DIRA,DIR1)))
{
return MFTestResults.Fail;
}
if (!TestDirectoryInfo(GetDir(DIRA, DIR2)))
{
return MFTestResults.Fail;
}
if (!TestDirectoryInfo(GetDir(DIRB, DIR1)))
{
return MFTestResults.Fail;
}
if (!TestDirectoryInfo(GetDir(DIRB, DIR2)))
{
return MFTestResults.Fail;
}
Log.Comment("Case insensitive");
if (!TestDirectoryInfo(GetDir(DIRA.ToLower())))
{
return MFTestResults.Fail;
}
if (!TestDirectoryInfo(GetDir(DIRB.ToUpper())))
{
return MFTestResults.Fail;
}
Log.Comment("Relative - set current dir to DirB");
Directory.SetCurrentDirectory(GetDir(DIRB));
if (!TestDirectoryInfo(DIR1))
{
return MFTestResults.Fail;
}
if (!TestDirectoryInfo(DIR2))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults ArgumentExceptionTests()
{
MFTestResults result = MFTestResults.Pass;
DirectoryInfo dir;
try
{
foreach (char invalidChar in Path.GetInvalidPathChars())
{
try
{
Log.Comment("Invalid char ascii val = " + (int)invalidChar);
string path = new string(new char[] { 'b', 'a', 'd', '\\', invalidChar, 'p', 'a', 't', 'h', invalidChar, '.', 't', 'x', 't' });
dir = Directory.CreateDirectory(path);
if (invalidChar == 0)
{
Log.Exception("[Known issue for '\\0' char] Expected Argument exception for for '" + path + "' but got: '" + dir + "'");
}
else
{
Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir.FullName + "'");
return MFTestResults.Fail;
}
}
catch (ArgumentException ae)
{ /* Pass Case */
Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
#endregion Test Cases
public MFTestMethod[] Tests
{
get
{
return new MFTestMethod[]
{
new MFTestMethod( NullArguments, "NullArguments" ),
new MFTestMethod( ValidCases, "ValidCases" ),
new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ),
};
}
}
}
}
| |
using System;
using IdokladSdk.ApiFilters;
using IdokladSdk.ApiModels;
using IdokladSdk.ApiModels.BaseModels;
using IdokladSdk.Enums;
namespace IdokladSdk.Clients
{
/// <summary>
/// Methods for received invoice resources.
/// </summary>
public partial class ReceivedInvoiceClient : BaseClient
{
public const string ResourceUrl = "/ReceivedInvoices";
public ReceivedInvoiceClient(ApiContext apiContext) : base(apiContext)
{
}
/// <summary>
/// GET api/Receivedinvoices/Default
/// Method returns empty invoice with default values. Returned resource is suitable for new invoice creation.
/// </summary>
public ReceivedInvoice Default()
{
return Get<ReceivedInvoice>(ResourceUrl + "/Default");
}
/// <summary>
/// PUT api/Receivedinvoices/{id}/FullyPay?dateOfPayment={dateOfPayment}
/// Method sets invoice as paid.
/// </summary>
public bool FullyPay(int invoiceId, DateTime paid)
{
return Put<bool>(ResourceUrl + "/" + invoiceId + "/FullyPay" + "?dateOfPayment=" + paid.ToString(ApiContextConfiguration.DateFormat));
}
/// <summary>
/// PUT api/Receivedinvoices/{id}/FullyUnpay
/// Method sets invoice as unpaid.
/// </summary>
public bool FullyUnpay(int invoiceId)
{
return Put<bool>(ResourceUrl + "/" + invoiceId + "/FullyUnpay");
}
/// <summary>
/// GET api/Receivedinvoices/{id}/GetAttachment
/// Returns attachment for invoice. File is Base64 encoded and is returned as string.
/// </summary>
public string Attachment(int invoiceId)
{
return Get<string>(ResourceUrl + "/" + invoiceId + "/GetAttachment");
}
/// <summary>
/// GET api/Receivedinvoices/{id}/GetAttachmentCompressed
/// Returns compressed attachment for invoice. File is Base64 encoded and is returned as string.
/// </summary>
public string AttachmentCompressed(int invoiceId)
{
return Get<string>(ResourceUrl + "/" + invoiceId + "/GetAttachmentCompressed");
}
/// <summary>
/// GET api/Receivedinvoices/Expand
/// Returns Receivied invoice list with related entities such as contact information etc.
/// </summary>
public RowsResultWrapper<ReceivedInvoiceExpand> ReceivedInvoicesExpand(ApiFilter filter = null)
{
return Get<RowsResultWrapper<ReceivedInvoiceExpand>>(ResourceUrl + "/Expand", filter);
}
/// <summary>
/// GET api/Receivedinvoices/{id}/Expand
/// Returns Received invoice with related entities by Id.
/// </summary>
public ReceivedInvoiceExpand ReceivedInvoiceExpand(int invoiceId)
{
return Get<ReceivedInvoiceExpand>(ResourceUrl + "/" + invoiceId + "/Expand");
}
/// <summary>
/// GET api/Receivedinvoices/{id}/MyDocumentAddress
/// Contact information of the purchaser for invoice.
/// </summary>
public DocumentAddress MyDocumentAddress(int invoiceId)
{
return Get<DocumentAddress>(ResourceUrl + "/" + invoiceId + "/MyDocumentAddress");
}
/// <summary>
/// GET api/Receivedinvoices/{supplierId}/ReceivedInvoices
/// Returns received invoice list for specific contact.
/// </summary>
public RowsResultWrapper<ReceivedInvoice> ReceivedInvoicesBySupplier(int supplierId, ReceivedInvoiceFilter filter = null)
{
return Get<RowsResultWrapper<ReceivedInvoice>>(ResourceUrl + "/" + supplierId + "/ReceivedInvoices");
}
/// <summary>
/// GET api/Receivedinvoices/{id}/SupplierDocumentAddress
/// Contact information of the supplier for invoice.
/// </summary>
public DocumentAddress SupplierDocumentAddress(int invoiceId)
{
return Get<DocumentAddress>(ResourceUrl + "/" + invoiceId + "/SupplierDocumentAddress");
}
/// <summary>
/// PUT api/Receivedinvoices/{id}/MyDocumentAddress
/// Method Updates contact informations of the purchaser.
/// </summary>
public DocumentAddress UpdateMyDocumentAddress(int invoiceId, DocumentAddress documentAddress)
{
return Put<DocumentAddress, DocumentAddress>(ResourceUrl + "/" + invoiceId + "/MyDocumentAddress", documentAddress);
}
/// <summary>
/// PUT api/Receivedinvoices/{id}/SupplierPurchaserDocumentAddress
/// Method Updates contact informations of the supplier.
/// </summary>
public DocumentAddress UpdateSupplierPurchaserDocumentAddress(int invoiceId, DocumentAddress documentAddress)
{
return Put<DocumentAddress, DocumentAddress>(ResourceUrl + "/" + invoiceId + "/SupplierPurchaserDocumentAddress", documentAddress);
}
/// <summary>
/// POST api/Receivedinvoices/Recount
/// Method recounts summaries of the invoice model for creation.
/// </summary>
public ReceivedInvoice Recount(ReceivedInvoiceCreate invoice)
{
return Post<ReceivedInvoice, ReceivedInvoiceCreate>(ResourceUrl + "/Recount", invoice);
}
/// <summary>
/// POST api/Receivedinvoices/{id}/Recount
/// Method recounts summaries of the invoice model for update.
/// </summary>
public ReceivedInvoice Recount(int invoiceId, ReceivedInvoiceUpdate invoice)
{
return Post<ReceivedInvoice, ReceivedInvoiceUpdate>(ResourceUrl + "/" + invoiceId + "/Recount", invoice);
}
/// <summary>
/// PUT api/Receivedinvoices/{id}/Exported/{value}
/// Method updates Exported proterty of the invoice.
/// </summary>
public bool UpdateExported(int invoiceId, ExportedStateEnum state)
{
return Put<bool>(ResourceUrl + "/" + invoiceId + "/Exported" + "/" + (int)state);
}
/// <summary>
/// DELETE api/ReceivedInvoices/{id}
/// Deletes received invoice by Id.
/// </summary>
public bool Delete(int invoiceId)
{
return Delete(ResourceUrl + "/" + invoiceId);
}
/// <summary>
/// DELETE api/ReceivedInvoices/DeleteAttachment/{invoiceId}
/// Deletes a received invoice attachment.
/// </summary>
public bool DeleteAttachment(int invoiceId)
{
return Delete(ResourceUrl + "/" + "DeleteAttachment" + "/" + invoiceId);
}
/// <summary>
/// GET api/ReceivedInvoices
/// Returns list of received invoices. Filters are optional.
/// </summary>
public RowsResultWrapper<ReceivedInvoice> ReceivedInvoices(ApiFilter filter = null)
{
return Get<RowsResultWrapper<ReceivedInvoice>>(ResourceUrl, filter);
}
/// <summary>
/// api/ReceivedInvoices/{id}
/// Returns information about received invoice including summaries.
/// </summary>
/// <param name="invoiceId"></param>
/// <returns></returns>
public ReceivedInvoice ReceivedInvoice(int invoiceId)
{
return Get<ReceivedInvoice>(ResourceUrl + "/" + invoiceId);
}
/// <summary>
/// POST api/ReceivedInvoices
/// Create new Received Invoice.
/// </summary>
public ReceivedInvoice Create(ReceivedInvoiceCreate invoice)
{
return Post<ReceivedInvoice, ReceivedInvoiceCreate>(ResourceUrl, invoice);
}
/// <summary>
/// PUT api/ReceivedInvoices/{id}
/// Method updates received invoice by Id. Also possible to update single properties of invoice.
/// </summary>
public ReceivedInvoice Update(int invoiceId, ReceivedInvoiceUpdate invoice)
{
return Put<ReceivedInvoice, ReceivedInvoiceUpdate>(ResourceUrl + "/" + invoiceId, invoice);
}
/// <summary>
/// PUT api/ReceivedInvoices/SetAttachment/{invoicdId}
/// Sets an attachment to the given received invoice. If an attachment already exists, it will be overwritten.
/// </summary>
public bool SetAttachment(int invoiceId)
{
return Put<bool>(ResourceUrl + "/" + "SetAttachment" + "/" + invoiceId);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using Funq;
using ServiceStack.Common;
using ServiceStack.Configuration;
using ServiceStack.Html;
using ServiceStack.IO;
using ServiceStack.Logging;
using ServiceStack.ServiceHost;
using ServiceStack.WebHost.Endpoints.Extensions;
namespace ServiceStack.WebHost.Endpoints
{
/// <summary>
/// Inherit from this class if you want to host your web services inside an
/// ASP.NET application.
/// </summary>
public abstract class AppHostBase
: IFunqlet, IDisposable, IAppHost, IHasContainer
{
private readonly ILog log = LogManager.GetLogger(typeof(AppHostBase));
public static AppHostBase Instance { get; protected set; }
protected AppHostBase(string serviceName, params Assembly[] assembliesWithServices)
{
EndpointHost.ConfigureHost(this, serviceName, CreateServiceManager(assembliesWithServices));
}
protected virtual ServiceManager CreateServiceManager(params Assembly[] assembliesWithServices)
{
return new ServiceManager(assembliesWithServices);
//Alternative way to inject Container + Service Resolver strategy
//return new ServiceManager(new Container(),
// new ServiceController(() => assembliesWithServices.ToList().SelectMany(x => x.GetTypes())));
}
protected IServiceController ServiceController
{
get
{
return EndpointHost.Config.ServiceController;
}
}
public IServiceRoutes Routes
{
get { return EndpointHost.Config.ServiceController.Routes; }
}
public Container Container
{
get
{
return EndpointHost.Config.ServiceManager != null
? EndpointHost.Config.ServiceManager.Container : null;
}
}
public void Init()
{
if (Instance != null)
{
throw new InvalidDataException("AppHostBase.Instance has already been set");
}
Instance = this;
var serviceManager = EndpointHost.Config.ServiceManager;
if (serviceManager != null)
{
serviceManager.Init();
Configure(EndpointHost.Config.ServiceManager.Container);
}
else
{
Configure(null);
}
EndpointHost.AfterInit();
}
public abstract void Configure(Container container);
public void SetConfig(EndpointHostConfig config)
{
if (config.ServiceName == null)
config.ServiceName = EndpointHostConfig.Instance.ServiceName;
if (config.ServiceManager == null)
config.ServiceManager = EndpointHostConfig.Instance.ServiceManager;
config.ServiceManager.ServiceController.EnableAccessRestrictions = config.EnableAccessRestrictions;
EndpointHost.Config = config;
}
public void RegisterAs<T, TAs>() where T : TAs
{
this.Container.RegisterAutoWiredAs<T, TAs>();
}
public virtual void Release(object instance)
{
try
{
var iocAdapterReleases = Container.Adapter as IRelease;
if (iocAdapterReleases != null)
{
iocAdapterReleases.Release(instance);
}
else
{
var disposable = instance as IDisposable;
if (disposable != null)
disposable.Dispose();
}
}
catch {/*ignore*/}
}
public virtual void OnEndRequest()
{
foreach (var item in HostContext.Instance.Items.Values)
{
Release(item);
}
HostContext.Instance.EndRequest();
}
public void Register<T>(T instance)
{
this.Container.Register(instance);
}
public T TryResolve<T>()
{
return this.Container.TryResolve<T>();
}
/// <summary>
/// Resolves from IoC container a specified type instance.
/// </summary>
/// <typeparam name="T">Type to be resolved.</typeparam>
/// <returns>Instance of <typeparamref name="T"/>.</returns>
public static T Resolve<T>()
{
if (Instance == null) throw new InvalidOperationException("AppHostBase is not initialized.");
return Instance.Container.Resolve<T>();
}
/// <summary>
/// Resolves and auto-wires a ServiceStack Service
/// </summary>
/// <typeparam name="T">Type to be resolved.</typeparam>
/// <returns>Instance of <typeparamref name="T"/>.</returns>
public static T ResolveService<T>(HttpContext httpCtx) where T : class, IRequiresRequestContext
{
if (Instance == null) throw new InvalidOperationException("AppHostBase is not initialized.");
var service = Instance.Container.Resolve<T>();
if (service == null) return null;
service.RequestContext = httpCtx.ToRequestContext();
return service;
}
public Dictionary<Type, Func<IHttpRequest, object>> RequestBinders
{
get { return EndpointHost.ServiceManager.ServiceController.RequestTypeFactoryMap; }
}
public IContentTypeFilter ContentTypeFilters
{
get
{
return EndpointHost.ContentTypeFilter;
}
}
public List<Action<IHttpRequest, IHttpResponse>> PreRequestFilters
{
get
{
return EndpointHost.RawRequestFilters;
}
}
public List<Action<IHttpRequest, IHttpResponse, object>> RequestFilters
{
get
{
return EndpointHost.RequestFilters;
}
}
public List<Action<IHttpRequest, IHttpResponse, object>> ResponseFilters
{
get
{
return EndpointHost.ResponseFilters;
}
}
public List<IViewEngine> ViewEngines
{
get
{
return EndpointHost.ViewEngines;
}
}
public HandleUncaughtExceptionDelegate ExceptionHandler
{
get { return EndpointHost.ExceptionHandler; }
set { EndpointHost.ExceptionHandler = value; }
}
public HandleServiceExceptionDelegate ServiceExceptionHandler
{
get { return EndpointHost.ServiceExceptionHandler; }
set { EndpointHost.ServiceExceptionHandler = value; }
}
public List<HttpHandlerResolverDelegate> CatchAllHandlers
{
get { return EndpointHost.CatchAllHandlers; }
}
public EndpointHostConfig Config
{
get { return EndpointHost.Config; }
}
public List<IPlugin> Plugins
{
get { return EndpointHost.Plugins; }
}
public IVirtualPathProvider VirtualPathProvider
{
get { return EndpointHost.VirtualPathProvider; }
set { EndpointHost.VirtualPathProvider = value; }
}
public virtual IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
//cached per service action
return new ServiceRunner<TRequest>(this, actionContext);
}
public virtual string ResolveAbsoluteUrl(string virtualPath, IHttpRequest httpReq)
{
return Config.WebHostUrl == null
? VirtualPathUtility.ToAbsolute(virtualPath)
: httpReq.GetAbsoluteUrl(virtualPath);
}
public virtual void LoadPlugin(params IPlugin[] plugins)
{
foreach (var plugin in plugins)
{
try
{
plugin.Register(this);
}
catch (Exception ex)
{
log.Warn("Error loading plugin " + plugin.GetType().Name, ex);
}
}
}
public virtual object ExecuteService(object requestDto)
{
return ExecuteService(requestDto, EndpointAttributes.None);
}
public object ExecuteService(object requestDto, EndpointAttributes endpointAttributes)
{
return EndpointHost.Config.ServiceController.Execute(requestDto,
new HttpRequestContext(requestDto, endpointAttributes));
}
public void RegisterService(Type serviceType, params string[] atRestPaths)
{
var genericService = EndpointHost.Config.ServiceManager.RegisterService(serviceType);
if (genericService != null)
{
var requestType = genericService.GetGenericArguments()[0];
foreach (var atRestPath in atRestPaths)
{
this.Routes.Add(requestType, atRestPath, null);
}
}
else
{
var reqAttr = serviceType.GetCustomAttributes(true).OfType<DefaultRequestAttribute>().FirstOrDefault();
if (reqAttr != null)
{
foreach (var atRestPath in atRestPaths)
{
this.Routes.Add(reqAttr.RequestType, atRestPath, null);
}
}
}
}
public virtual void Dispose()
{
if (EndpointHost.Config.ServiceManager != null)
{
EndpointHost.Config.ServiceManager.Dispose();
}
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_ASEMAIL
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Xml;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestSuites.Common.DataStructures;
using Microsoft.Protocols.TestTools;
using Request = Microsoft.Protocols.TestSuites.Common.Request;
using Response = Microsoft.Protocols.TestSuites.Common.Response;
/// <summary>
/// A static class contains all helper methods used in test cases.
/// </summary>
internal static class TestSuiteHelper
{
/// <summary>
/// private field for seed initialize to random number.
/// </summary>
private static int seek = new Random().Next(0, 100000);
/// <summary>
/// Get client id for send mail
/// </summary>
/// <returns>The client id</returns>
public static string GetClientId()
{
return (++seek).ToString();
}
#region Create sample mime string for SendMail operation
/// <summary>
/// Create a sample plain text mime
/// </summary>
/// <param name="from">The from address of mail</param>
/// <param name="to">The to address of the mail</param>
/// <param name="cc">The cc address of the mail</param>
/// <param name="bcc">The bcc address of the mail</param>
/// <param name="subject">The subject of the mail</param>
/// <param name="body">The body content of the mail</param>
/// <param name="sender">The sender of the mail</param>
/// <param name="replyTo">The replyTo of the mail</param>
/// <returns>Returns the corresponding sample plain text mime</returns>
internal static string CreatePlainTextMime(string from, string to, string cc, string bcc, string subject, string body, string sender = null, string replyTo = null)
{
cc = string.IsNullOrEmpty(cc) ? string.Empty : string.Format("Cc: {0}\r\n", cc);
bcc = string.IsNullOrEmpty(bcc) ? string.Empty : string.Format("Bcc: {0}\r\n", bcc);
sender = string.IsNullOrEmpty(sender) ? string.Empty : string.Format("Sender: {0}\r\n", sender);
replyTo = string.IsNullOrEmpty(replyTo) ? string.Empty : string.Format("Reply-To: {0}\r\n", replyTo);
string plainTextMime =
@"From: {0}
To: {1}
"
+ sender + cc + bcc + replyTo + @"Subject: {2}
Content-Type: text/plain; charset=""us-ascii""
MIME-Version: 1.0
{3}
";
return Common.FormatString(plainTextMime, from, to, subject, body);
}
/// <summary>
/// Create a MIME with two electronic voice mail attachments.
/// Note: When writing X-AttachmentOrder header value, the attachment name retrieved from [secondVoiceAttachmentPath]
/// will be added after the name retrieved from [firstVoiceAttachmentPath].
/// </summary>
/// <param name="from">The from address of mail</param>
/// <param name="to">The to address of the mail</param>
/// <param name="subject">The subject of the mail</param>
/// <param name="body">The body content of the mail</param>
/// <param name="callNumber">The telephone number of voice mail</param>
/// <param name="firstVoiceFilePath">The path of first voice file</param>
/// <param name="secondVoiceFilePath">The path of second voice file</param>
/// <returns>Returns the corresponding sample voice email mime</returns>
internal static string CreateVoiceAttachmentMime(
string from,
string to,
string subject,
string body,
string callNumber,
string firstVoiceFilePath,
string secondVoiceFilePath)
{
// For simplicity, we don't calculate the duration of voice mp3
string voiceAttachmentMime =
@"From: {0}
To: {1}
Subject: {2}
Content-Class: voice
X-CallingTelephoneNumber: {3}
X-VoiceMessageDuration: 2
X-AttachmentOrder: {4};{5}
Content-Type: multipart/mixed;
boundary=""_001_MSASEMAIL_NextPart_""
MIME-Version: 1.0
--_001_MSASEMAIL_NextPart_
Content-Type: text/plain; charset=""us-ascii""
{6}
--_001_MSASEMAIL_NextPart_
Content-Type: audio/{7}
Content-Disposition: attachment; filename=""{8}""
Content-Transfer-Encoding: base64
{9}
--_001_MSASEMAIL_NextPart_
Content-Type: audio/{10}
Content-Disposition: attachment; filename=""{11}""
Content-Transfer-Encoding: base64
{12}
--_001_MSASEMAIL_NextPart_--
";
string firstVoiceFileName = Path.GetFileName(firstVoiceFilePath);
string firstVoiceContent = Convert.ToBase64String(File.ReadAllBytes(firstVoiceFilePath));
string firstVoiceFileExt = Path.GetExtension(firstVoiceFilePath);
string secondVoiceFileName = Path.GetFileName(secondVoiceFilePath);
string secondVoiceContent = Convert.ToBase64String(File.ReadAllBytes(secondVoiceFilePath));
string secondVoiceFileExt = Path.GetExtension(secondVoiceFilePath);
return Common.FormatString(
voiceAttachmentMime,
from,
to,
subject,
callNumber,
firstVoiceFileName,
secondVoiceFileName,
body,
firstVoiceFileExt.TrimStart('.'),
firstVoiceFileName,
firstVoiceContent,
secondVoiceFileExt.TrimStart('.'),
secondVoiceFileName,
secondVoiceContent);
}
/// <summary>
/// Create a meeting request mime
/// </summary>
/// <param name="from">The from address of mail</param>
/// <param name="to">The to address of the mail</param>
/// <param name="subject">The subject of the mail</param>
/// <param name="body">The body content of the mail</param>
/// <param name="icalendarContent">The content of iCalendar required by this meeting</param>
/// <returns>Returns the corresponding sample meeting mime</returns>
internal static string CreateMeetingRequestMime(string from, string to, string subject, string body, string icalendarContent)
{
string meetingRequestMime =
@"From: {0}
To: {1}
Subject: {2}
Content-Type: multipart/alternative;
boundary=""_001_MSASEMAIL_NextPart_""
MIME-Version: 1.0
--_001_MSASEMAIL_NextPart_
Content-Type: text/plain; charset=""us-ascii""
{3}
--_001_MSASEMAIL_NextPart_
Content-Type: text/calendar; charset=""us-ascii""; method=REQUEST
{4}
--_001_MSASEMAIL_NextPart_--
";
return Common.FormatString(meetingRequestMime, from, to, subject, body, icalendarContent);
}
/// <summary>
/// Create iCalendar format string from one calendar instance
/// </summary>
/// <param name="calendar">Calendar information</param>
/// <returns>iCalendar formatted string</returns>
internal static string CreateiCalendarFormatContent(Calendar calendar)
{
StringBuilder ical = new StringBuilder();
ical.AppendLine("BEGIN: VCALENDAR");
ical.AppendLine("PRODID:-//Microosft Protocols TestSuites");
ical.AppendLine("VERSION:2.0");
ical.AppendLine("METHOD:REQUEST");
ical.AppendLine("X-MS-OLK-FORCEINSPECTOROPEN:TRUE");
ical.AppendLine("BEGIN:VTIMEZONE");
ical.AppendLine("TZID:UTC");
ical.AppendLine("BEGIN:STANDARD");
ical.AppendLine("DTSTART:16010101T000000");
ical.AppendLine("TZOFFSETFROM:-0000");
ical.AppendLine("TZOFFSETTO:-0000");
ical.AppendLine("END:STANDARD");
ical.AppendLine("END:VTIMEZONE");
ical.AppendLine("BEGIN:VEVENT");
ical.AppendLine("UID:" + calendar.UID);
ical.AppendLine("DTSTAMP:" + ((DateTime)calendar.DtStamp).ToString("yyyyMMddTHHmmss"));
ical.AppendLine("DESCRIPTION:" + calendar.Subject);
ical.AppendLine("SUMMARY:" + calendar.Subject);
ical.AppendLine("ATTENDEE;CN=\"\";RSVP=" + (calendar.ResponseRequested == true ? "TRUE" : "FALSE") + ":mailto:" + calendar.Attendees.Attendee[0].Email);
ical.AppendLine("ORGANIZER:MAILTO:" + calendar.OrganizerEmail);
ical.AppendLine("LOCATION:" + (calendar.Location ?? "My Office"));
if (calendar.AllDayEvent == 1)
{
ical.AppendLine("DTSTART;VALUE=DATE:" + ((DateTime)calendar.StartTime).Date.ToString("yyyyMMdd"));
ical.AppendLine("DTEND;VALUE=DATE:" + ((DateTime)calendar.EndTime).Date.ToString("yyyyMMdd"));
ical.AppendLine("X-MICROSOFT-CDO-ALLDAYEVENT:TRUE");
}
else
{
ical.AppendLine("DTSTART;TZID=\"UTC\":" + ((DateTime)calendar.StartTime).ToString("yyyyMMddTHHmmss"));
ical.AppendLine("DTEND;TZID=\"UTC\":" + ((DateTime)calendar.EndTime).ToString("yyyyMMddTHHmmss"));
}
if (calendar.Recurrence != null)
{
switch (calendar.Recurrence.Type)
{
case 1:
ical.AppendLine("RRULE:FREQ=WEEKLY;BYDAY=MO;UNTIL=" + calendar.Recurrence.Until);
break;
case 2:
ical.AppendLine("RRULE:FREQ=MONTHLY;COUNT=3;BYMONTHDAY=1");
break;
case 3:
ical.AppendLine("RRULE:FREQ=MONTHLY;COUNT=3;BYDAY=1MO");
break;
case 5:
ical.AppendLine("RRULE:FREQ=YEARLY;COUNT=3;BYMONTHDAY=1;BYMONTH=1");
break;
case 6:
ical.AppendLine("RRULE:FREQ=YEARLY;COUNT=3;BYDAY=2MO;BYMONTH=1");
break;
}
}
if (calendar.Exceptions != null)
{
ical.AppendLine("EXDATE;TZID=\"UTC\":" + ((DateTime)calendar.StartTime).AddDays(7).ToString("yyyyMMddTHHmmss"));
ical.AppendLine("RECURRENCE-ID;TZID=\"UTC\":" + ((DateTime)calendar.StartTime).ToString("yyyyMMddTHHmmss"));
}
switch (calendar.BusyStatus)
{
case 0:
ical.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:FREE");
break;
case 1:
ical.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE");
break;
case 2:
ical.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:BUSY");
break;
case 3:
ical.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:OOF");
break;
}
if (calendar.DisallowNewTimeProposal == true)
{
ical.AppendLine("X-MICROSOFT-DISALLOW-COUNTER:TRUE");
}
if (!string.IsNullOrEmpty(calendar.Reminder))
{
ical.AppendLine("BEGIN:VALARM");
ical.AppendLine("TRIGGER:-PT" + calendar.Reminder + "M");
ical.AppendLine("ACTION:DISPLAY");
ical.AppendLine("END:VALARM");
}
ical.AppendLine("END:VEVENT");
ical.AppendLine("END:VCALENDAR");
return ical.ToString();
}
/// <summary>
/// Create meeting response mail iCalendarContent
/// </summary>
/// <param name="startTime">Meeting start time</param>
/// <param name="endTime">Meeting end time</param>
/// <param name="uid">Meeting uid</param>
/// <param name="subject">Meeting subject</param>
/// <param name="location">Meeting location</param>
/// <param name="replyto">Meeting organizer email to reply</param>
/// <param name="from">Meeting attendee email address </param>
/// <returns>Meeting Response content in iCalendar format</returns>
internal static string CreateMeetingResponseiCalendarFormatContent(DateTime startTime, DateTime endTime, string uid, string subject, string location, string replyto, string from)
{
StringBuilder ical = new StringBuilder();
ical.AppendLine("BEGIN: VCALENDAR");
ical.AppendLine("PRODID:-//Microosft Protocols TestSuites");
ical.AppendLine("VERSION:2.0");
ical.AppendLine("METHOD:REPLY");
ical.AppendLine("BEGIN:VEVENT");
ical.AppendLine("DTSTART:" + startTime.ToString("yyyyMMddTHHmmss"));
ical.AppendLine("DTSTAMP:" + startTime.ToString("yyyyMMddTHHmmss"));
ical.AppendLine("DTEND:" + endTime.ToString("yyyyMMddTHHmmss"));
ical.AppendLine("UID:" + uid);
ical.AppendLine("DESCRIPTION:" + subject);
ical.AppendLine("SUMMARY:" + subject);
ical.AppendLine("ORGANIZER:MAILTO:" + replyto);
ical.AppendLine("ATTENDEE;PARTSTAT=ACCEPTED;CN=\"\";RSVP=TRUE:" + from);
ical.AppendLine("LOCATION:" + location);
ical.AppendLine("END:VEVENT");
ical.AppendLine("END:VCALENDAR");
return ical.ToString();
}
#endregion
#region Create some [MS-ASCMD] request required by test case
/// <summary>
/// Builds a Search request on the Mailbox store by using the specified keyword and folder collection ID
/// In general, returns the XML formatted search request as follows:
/// <!--
/// <?xml version="1.0" encoding="utf-8"?>
/// <Search xmlns="Search" xmlns:airsync="AirSync">
/// <Store>
/// <Name>Mailbox</Name>
/// <Query>
/// <And>
/// <airsync:CollectionId>5</airsync:CollectionId>
/// <FreeText>Presentation</FreeText>
/// </And>
/// </Query>
/// <Options>
/// <RebuildResults />
/// <Range>0-4</Range>
/// <DeepTraversal/>
/// </Options>
/// </Store>
/// </Search>
/// -->
/// </summary>
/// <param name="keyword">Specify a string value for which to search. Refer to [MS-ASCMD] section 2.2.3.73</param>
/// <param name="folderCollectionId">Specify the folder in which to search. Refer to [MS-ASCMD] section 2.2.3.30.4</param>
/// <returns>Returns a SearchRequest instance</returns>
internal static SearchRequest CreateSearchRequest(string keyword, string folderCollectionId)
{
Request.SearchStore searchStore = new Request.SearchStore
{
Name = SearchName.Mailbox.ToString(),
Options = new Request.Options1
{
Items = new object[] { string.Empty, string.Empty },
ItemsElementName = new Request.ItemsChoiceType6[]
{
Request.ItemsChoiceType6.RebuildResults,
Request.ItemsChoiceType6.DeepTraversal
}
}
};
// Build up query condition by using the keyword and folder CollectionID
Request.queryType queryItem = new Request.queryType
{
Items = new object[] { folderCollectionId, keyword },
ItemsElementName = new Request.ItemsChoiceType2[]
{
Request.ItemsChoiceType2.CollectionId,
Request.ItemsChoiceType2.FreeText
}
};
searchStore.Query = new Request.queryType
{
Items = new object[] { queryItem },
ItemsElementName = new Request.ItemsChoiceType2[] { Request.ItemsChoiceType2.And }
};
return Common.CreateSearchRequest(new Request.SearchStore[] { searchStore });
}
/// <summary>
/// Builds a ItemOperations request to fetch the whole content of a single mail item
/// by using the specified collectionId, emailServerId,bodyPreference and bodyPartPreference
/// In general, returns the XML formatted ItemOperations request as follows:
/// <!--
/// <?xml version="1.0" encoding="utf-8"?>
/// <ItemOperations xmlns="ItemOperations" xmlns:airsync="AirSync" xmlns:airsyncbase="AirSyncBase">
/// <Fetch>
/// <Store>Mailbox</Store>
/// <airsync:CollectionId>5</airsync:CollectionId>
/// <airsync:ServerId>5:1</airsync:ServerId>
/// <Options>
/// <airsync:MIMESupport>2</airsync:MIMESupport>
/// <airsyncbase:BodyPreference>
/// <airsyncbase:Type>4</airsyncbase:Type>
/// </airsyncbase:BodyPreference>
/// <airsyncbase:BodyPreference>
/// <airsyncbase:Type>2</airsyncbase:Type>
/// </airsyncbase:BodyPreference>
/// </Options>
/// </Fetch>
/// </ItemOperations>
/// -->
/// </summary>
/// <param name="collectionId">Specify the folder of mailItem, which can be returned by ActiveSync FolderSync command(Refer to [MS-ASCMD]2.2.3.30.2)</param>
/// <param name="serverId">Specify a unique identifier that is assigned by the server for a mailItem, which can be returned by ActiveSync Sync command(Refer to [MS-ASCMD]2.2.3.151.5)</param>
/// <param name="bodyPreference">Sets preference information related to the type and size of information for body (Refer to [MS-ASAIRS] 2.2.2.7)</param>
/// <param name="bodyPartPreference">Sets preference information related to the type and size of information for a message part (Refer to [MS-ASAIRS] 2.2.2.6)</param>
/// <param name="schema">Sets the schema information.</param>
/// <returns>Returns the ItemOperationsRequest instance</returns>
internal static ItemOperationsRequest CreateItemOperationsFetchRequest(
string collectionId,
string serverId,
Request.BodyPreference bodyPreference,
Request.BodyPartPreference bodyPartPreference,
Request.Schema schema)
{
// Set the ItemOperations:Fetch Options (See [MS-ASCMD] 2.2.3.115.2 Options)
// :: To get the whole content of the specified mail item, just ignore Fetch and Range element.
// See [MS-ASCMD] 2.2.3.145 Schema and 2.2.3.130.1 Range
// :: UserName, Password is not required by MS-ASEMAIl test case
Request.ItemOperationsFetchOptions fetchOptions = new Request.ItemOperationsFetchOptions();
List<object> fetchOptionItems = new List<object>();
List<Request.ItemsChoiceType5> fetchOptionItemsName = new List<Request.ItemsChoiceType5>();
if (null != bodyPreference)
{
fetchOptionItemsName.Add(Request.ItemsChoiceType5.BodyPreference);
fetchOptionItems.Add(bodyPreference);
// when body format is mime (Refer to [MS-ASAIRS] 2.2.2.22 Type)
if (bodyPreference.Type == 0x4)
{
fetchOptionItemsName.Add(Request.ItemsChoiceType5.MIMESupport);
// Magic number '2' indicate server send MIME data for all messages but not S/MIME messages only
// (Refer to [MS-ASCMD] 2.2.3.100.1 MIMESupport)
fetchOptionItems.Add((byte)0x2);
}
}
if (null != bodyPartPreference)
{
fetchOptionItemsName.Add(Request.ItemsChoiceType5.BodyPartPreference);
fetchOptionItems.Add(bodyPartPreference);
}
if (null != schema)
{
fetchOptionItemsName.Add(Request.ItemsChoiceType5.Schema);
fetchOptionItems.Add(schema);
}
fetchOptions.Items = fetchOptionItems.ToArray();
fetchOptions.ItemsElementName = fetchOptionItemsName.ToArray();
// *Only to fetch email item in mailbox* by using airsync:CollectionId & ServerId
// So ignore LongId/LinkId/FileReference/RemoveRightsManagementProtection
Request.ItemOperationsFetch fetchElement = new Request.ItemOperationsFetch()
{
CollectionId = collectionId,
ServerId = serverId,
Store = SearchName.Mailbox.ToString(),
Options = fetchOptions
};
return Common.CreateItemOperationsRequest(new object[] { fetchElement });
}
/// <summary>
/// Build a generic Sync request without command references by using the specified sync key, folder collection ID and body preference option.
/// If syncKey is
/// In general, returns the XML formatted Sync request as follows:
/// <!--
/// <?xml version="1.0" encoding="utf-8"?>
/// <Sync xmlns="AirSync">
/// <Collections>
/// <Collection>
/// <SyncKey>0</SyncKey>
/// <CollectionId>5</CollectionId>
/// <DeletesAsMoves>1</DeletesAsMoves>
/// <GetChanges>1</GetChanges>
/// <WindowSize>100</WindowSize>
/// <Options>
/// <MIMESupport>0</MIMESupport>
/// <airsyncbase:BodyPreference>
/// <airsyncbase:Type>2</airsyncbase:Type>
/// <airsyncbase:TruncationSize>5120</airsyncbase:TruncationSize>
/// </airsyncbase:BodyPreference>
/// </Options>
/// </Collection>
/// </Collections>
/// </Sync>
/// -->
/// </summary>
/// <param name="syncKey">Specify the sync key obtained from the last sync response(Refer to [MS-ASCMD]2.2.3.166.4)</param>
/// <param name="collectionId">Specify the server ID of the folder to be synchronized, which can be returned by ActiveSync FolderSync command(Refer to [MS-ASCMD]2.2.3.30.5)</param>
/// <param name="bodyPreference">Sets preference information related to the type and size of information for body (Refer to [MS-ASAIRS] 2.2.2.7)</param>
/// <returns>Returns the SyncRequest instance</returns>
internal static SyncRequest CreateSyncRequest(string syncKey, string collectionId, Request.BodyPreference bodyPreference)
{
Request.SyncCollection syncCollection = new Request.SyncCollection
{
SyncKey = syncKey,
CollectionId = collectionId
};
if (syncKey != "0")
{
syncCollection.GetChanges = true;
syncCollection.GetChangesSpecified = true;
}
syncCollection.WindowSize = "100";
Request.Options syncOptions = new Request.Options();
List<object> syncOptionItems = new List<object>();
List<Request.ItemsChoiceType1> syncOptionItemsName = new List<Request.ItemsChoiceType1>();
if (null != bodyPreference)
{
syncOptionItemsName.Add(Request.ItemsChoiceType1.BodyPreference);
syncOptionItems.Add(bodyPreference);
// when body format is mime (Refer to [MS-ASAIRS] 2.2.2.22 Type)
if (bodyPreference.Type == 0x4)
{
syncOptionItemsName.Add(Request.ItemsChoiceType1.MIMESupport);
// Magic number '2' indicate server send MIME data for all messages but not S/MIME messages only
syncOptionItems.Add((byte)0x2);
}
}
syncOptions.Items = syncOptionItems.ToArray();
syncOptions.ItemsElementName = syncOptionItemsName.ToArray();
syncCollection.Options = new Request.Options[] { syncOptions };
return Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection });
}
/// <summary>
/// Builds a Sync change request by using the specified sync key, folder collection ID and change application data.
/// In general, returns the XML formatted Sync request as follows:
/// <!--
/// <?xml version="1.0" encoding="utf-8"?>
/// <Sync xmlns="AirSync">
/// <Collections>
/// <Collection>
/// <SyncKey>0</SyncKey>
/// <CollectionId>5</CollectionId>
/// <GetChanges>1</GetChanges>
/// <WindowSize>100</WindowSize>
/// <Commands>
/// <Change>
/// <ServerId>5:1</ServerId>
/// <ApplicationData>
/// ...
/// </ApplicationData>
/// </Change>
/// </Commands>
/// </Collection>
/// </Collections>
/// </Sync>
/// -->
/// </summary>
/// <param name="syncKey">Specify the sync key obtained from the last sync response(Refer to [MS-ASCMD]2.2.3.166.4)</param>
/// <param name="collectionId">Specify the server ID of the folder to be synchronized, which can be returned by ActiveSync FolderSync command(Refer to [MS-ASCMD]2.2.3.30.5)</param>
/// <param name="changeData">Contains the data used to specify the Change element for Sync command(Refer to [MS-ASCMD]2.2.3.11)</param>
/// <returns>Returns the SyncRequest instance</returns>
internal static SyncRequest CreateSyncChangeRequest(string syncKey, string collectionId, Request.SyncCollectionChange changeData)
{
Request.SyncCollection syncCollection = CreateSyncCollection(syncKey, collectionId);
syncCollection.Commands = new object[] { changeData };
return Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection });
}
/// <summary>
/// Builds a Sync add request by using the specified sync key, folder collection ID and add application data.
/// In general, returns the XMl formatted Sync request as follows:
/// <!--
/// <?xml version="1.0" encoding="utf-8"?>
/// <Sync xmlns="AirSync">
/// <Collections>
/// <Collection>
/// <SyncKey>0</SyncKey>
/// <CollectionId>5</CollectionId>
/// <GetChanges>1</GetChanges>
/// <WindowSize>100</WindowSize>
/// <Commands>
/// <Add>
/// <ServerId>5:1</ServerId>
/// <ApplicationData>
/// ...
/// </ApplicationData>
/// </Add>
/// </Commands>
/// </Collection>
/// </Collections>
/// </Sync>
/// -->
/// </summary>
/// <param name="syncKey">Specify the sync key obtained from the last sync response(Refer to [MS-ASCMD]2.2.3.166.4)</param>
/// <param name="collectionId">Specify the server ID of the folder to be synchronized, which can be returned by ActiveSync FolderSync command(Refer to [MS-ASCMD]2.2.3.30.5)</param>
/// <param name="addData">Contains the data used to specify the Add element for Sync command(Refer to [MS-ASCMD]2.2.3.7.2)</param>
/// <returns>Returns the SyncRequest instance</returns>
internal static SyncRequest CreateSyncAddRequest(string syncKey, string collectionId, Request.SyncCollectionAdd addData)
{
Request.SyncCollection syncCollection = TestSuiteHelper.CreateSyncCollection(syncKey, collectionId);
syncCollection.Commands = new object[] { addData };
return Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection });
}
/// <summary>
/// Create a sync add request.
/// </summary>
/// <param name="syncKey">Specify the sync key obtained from the last sync response</param>
/// <param name="collectionId">Specify the server ID of the folder to be synchronized, which can be returned by ActiveSync FolderSync command.</param>
/// <param name="applicationData">Contains the data used to specify the Add element for Sync command.</param>
/// <returns>Returns the SyncRequest instance.</returns>
internal static SyncRequest CreateSyncAddRequest(string syncKey, string collectionId, Request.SyncCollectionAddApplicationData applicationData)
{
SyncRequest syncAddRequest = TestSuiteHelper.CreateSyncRequest(syncKey, collectionId, null);
Request.SyncCollectionAdd add = new Request.SyncCollectionAdd
{
ClientId = GetClientId(),
ApplicationData = applicationData
};
List<object> commandList = new List<object> { add };
syncAddRequest.RequestData.Collections[0].Commands = commandList.ToArray();
return syncAddRequest;
}
/// <summary>
/// Create an instance of SyncCollection
/// </summary>
/// <param name="syncKey">Specify the synchronization key obtained from the last sync command response.</param>
/// <param name="collectionId">Specify the serverId of the folder to be synchronized, which can be returned by ActiveSync FolderSync command</param>
/// <returns>An instance of SyncCollection</returns>
internal static Request.SyncCollection CreateSyncCollection(string syncKey, string collectionId)
{
Request.SyncCollection syncCollection = new Request.SyncCollection
{
SyncKey = syncKey,
GetChanges = true,
GetChangesSpecified = true,
CollectionId = collectionId,
WindowSize = "100"
};
return syncCollection;
}
/// <summary>
/// Create an instance of SyncCollectionChange
/// </summary>
/// <param name="read">The value is TRUE indicates the email has been read; a value of FALSE indicates the email has not been read</param>
/// <param name="serverId">The server id of the email</param>
/// <param name="flag">The flag instance</param>
/// <param name="categories">The list of categories</param>
/// <returns>An instance of SyncCollectionChange</returns>
internal static Request.SyncCollectionChange CreateSyncChangeData(bool read, string serverId, Request.Flag flag, Collection<object> categories)
{
Request.SyncCollectionChange changeData = new Request.SyncCollectionChange
{
ServerId = serverId,
ApplicationData = new Request.SyncCollectionChangeApplicationData()
};
List<object> items = new List<object>();
List<Request.ItemsChoiceType7> itemsElementName = new List<Request.ItemsChoiceType7>();
items.Add(read);
itemsElementName.Add(Request.ItemsChoiceType7.Read);
if (null != flag)
{
items.Add(flag);
itemsElementName.Add(Request.ItemsChoiceType7.Flag);
}
if (null != categories)
{
Request.Categories mailCategories = new Request.Categories();
List<string> category = new List<string>();
foreach (object categoryObject in categories)
{
category.Add(categoryObject.ToString());
}
mailCategories.Category = category.ToArray();
items.Add(mailCategories);
itemsElementName.Add(Request.ItemsChoiceType7.Categories2);
}
changeData.ApplicationData.Items = items.ToArray();
changeData.ApplicationData.ItemsElementName = itemsElementName.ToArray();
return changeData;
}
/// <summary>
/// Builds a SendMail request by using the specified client Id, copyToSentItems option and mail mime content.
/// In general, returns the XML formatted Sync request as follows:
/// <!--
/// <?xml version="1.0" encoding="utf-8"?>
/// <SendMail xmlns="ComposeMail">
/// <ClientId>3</ClientId>
/// <SaveInSentItems/>
/// <Mime>....</Mime>
/// </SendMail>
/// -->
/// </summary>
/// <param name="clientId">Specify the client Id</param>
/// <param name="copyToSentItems">Specify whether needs to store a mail copy to sent items</param>
/// <param name="mime">Specify the mail mime</param>
/// <returns>Returns the SendMailRequest instance</returns>
internal static SendMailRequest CreateSendMailRequest(string clientId, bool copyToSentItems, string mime)
{
Request.SendMail sendMail = new Request.SendMail();
// If true, save a copy to sent items folder, if false, doesn't save a copy to sent items folder
if (copyToSentItems)
{
sendMail.SaveInSentItems = string.Empty;
}
sendMail.ClientId = clientId;
sendMail.Mime = mime;
SendMailRequest sendMailRequest = Common.CreateSendMailRequest();
sendMailRequest.RequestData = sendMail;
return sendMailRequest;
}
/// <summary>
/// Builds a SmartReply request by using the specified source folder Id, source server Id and reply mime information.
/// In general, returns the XML formatted Sync request as follows:
/// <!--
/// <?xml version="1.0" encoding="utf-8"?>
/// <SmartReply xmlns="ComposeMail">
/// <ClientId>d7b99822-685a-4a40-8dfb-87a114926986</ClientId>
/// <Source>
/// <FolderId>5</FolderId>
/// <ItemId>5:1</ItemId>
/// </Source>
/// <Mime>...</Mime>
/// </SmartReply>
/// -->
/// </summary>
/// <param name="sourceFolderId">Specify the folder id of original mail item being replied</param>
/// <param name="sourceServerId">Specify the server Id of original mail item being replied</param>
/// <param name="replyMime">The total reply mime</param>
/// <returns>Returns the SmartReplyRequest instance</returns>
internal static SmartReplyRequest CreateSmartReplyRequest(string sourceFolderId, string sourceServerId, string replyMime)
{
SmartReplyRequest request = new SmartReplyRequest
{
RequestData = new Request.SmartReply
{
ClientId = System.Guid.NewGuid().ToString(),
Source = new Request.Source { FolderId = sourceFolderId, ItemId = sourceServerId },
Mime = replyMime
}
};
request.SetCommandParameters(new Dictionary<CmdParameterName, object>
{
{
CmdParameterName.CollectionId, sourceFolderId
},
{
CmdParameterName.ItemId, sourceServerId
}
});
return request;
}
/// <summary>
/// Builds a SmartForward request by using the specified source folder Id, source server Id and forward mime information.
/// In general, returns the XML formatted Sync request as follows:
/// <!--
/// <?xml version="1.0" encoding="utf-8"?>
/// <SmartForward xmlns="ComposeMail">
/// <ClientId>d7b99822-685a-4a40-8dfb-87a114926986</ClientId>
/// <Source>
/// <FolderId>5</FolderId>
/// <ItemId>5:1</ItemId>
/// </Source>
/// <Mime>...</Mime>
/// </SmartForward>
/// -->
/// </summary>
/// <param name="sourceFolderId">Specify the folder id of original mail item being forwarded</param>
/// <param name="sourceServerId">Specify the server Id of original mail item being forwarded</param>
/// <param name="forwardMime">The total forward mime</param>
/// <returns>Returns the SmartReplyRequest instance</returns>
internal static SmartForwardRequest CreateSmartForwardRequest(string sourceFolderId, string sourceServerId, string forwardMime)
{
SmartForwardRequest request = new SmartForwardRequest
{
RequestData = new Request.SmartForward
{
ClientId = System.Guid.NewGuid().ToString(),
Source = new Request.Source { FolderId = sourceFolderId, ItemId = sourceServerId },
Mime = forwardMime
}
};
request.SetCommandParameters(new Dictionary<CmdParameterName, object>
{
{
CmdParameterName.CollectionId, sourceFolderId
},
{
CmdParameterName.ItemId, sourceServerId
}
});
return request;
}
#endregion
/// <summary>
/// Get the specified email item from the sync add response by using the subject as the search criteria.
/// </summary>
/// <param name="syncResult">The sync result.</param>
/// <param name="subject">The email subject.</param>
/// <returns>Return the specified email item.</returns>
internal static Sync GetSyncAddItem(SyncStore syncResult, string subject)
{
Sync item = null;
if (syncResult.AddElements != null)
{
foreach (Sync syncItem in syncResult.AddElements)
{
if (syncItem.Email.Subject == subject)
{
item = syncItem;
break;
}
if (syncItem.Calendar.Subject == subject)
{
item = syncItem;
break;
}
}
}
return item;
}
/// <summary>
/// Get the specified email item from the sync change response by using the subject as the search criteria.
/// </summary>
/// <param name="syncResult">The sync result.</param>
/// <param name="serverId">The email server id.</param>
/// <returns>Return the specified email item.</returns>
internal static Sync GetSyncChangeItem(SyncStore syncResult, string serverId)
{
Sync item = null;
if (syncResult.ChangeElements != null)
{
foreach (Sync syncItem in syncResult.ChangeElements)
{
if (syncItem.ServerId == serverId)
{
item = syncItem;
break;
}
}
}
return item;
}
/// <summary>
/// Get the Status code from the sync change response string
/// </summary>
/// <param name="changeResponseXml">Sync Response string in Xml format</param>
/// <returns>Status code from change response</returns>
internal static string GetStatusCode(string changeResponseXml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(changeResponseXml);
XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(doc.NameTable);
nameSpaceManager.AddNamespace("e", "AirSync");
// Get status code from <Change> element
XmlNode status = doc.SelectSingleNode("//e:Change/e:Status", nameSpaceManager);
if (status == null)
{
return null;
}
else
{
return status.InnerText;
}
}
/// <summary>
/// Get the email item from the ItemOperations response by using the subject as the search criteria.
/// </summary>
/// <param name="itemOperationsResult">The ItemOperations command result.</param>
/// <param name="subject">The email subject.</param>
/// <returns>Return the right email item from the sync response.</returns>
internal static ItemOperations GetItemOperationsItem(ItemOperationsStore itemOperationsResult, string subject)
{
ItemOperations item = null;
if (itemOperationsResult.Items != null)
{
foreach (ItemOperations itemOperationsItem in itemOperationsResult.Items)
{
if (itemOperationsItem.Email.Subject == subject)
{
item = itemOperationsItem;
break;
}
}
}
return item;
}
/// <summary>
/// Create a Request.Attendees instance by the attendee email address.
/// </summary>
/// <param name="attendeeEmail">The email address of the attendee</param>
/// <returns>The created Request.Attendees instance.</returns>
internal static Request.Attendees CreateAttendees(string attendeeEmail)
{
List<Request.AttendeesAttendee> attendeelist = new List<Request.AttendeesAttendee>
{
new Request.AttendeesAttendee
{
Email = attendeeEmail,
Name = attendeeEmail,
AttendeeStatus = 0,
AttendeeTypeSpecified = true,
AttendeeType = 1
}
};
Request.Attendees attendees = new Request.Attendees { Attendee = attendeelist.ToArray() };
return attendees;
}
/// <summary>
/// Convert a byte array into an equivalent hex string. E.g. [0xXX, 0xYY]=>"XXYY"
/// </summary>
/// <param name="bytes">The byte array need to be converted</param>
/// <returns>A hex string representation corresponding to the byte array</returns>
internal static string BytesToHex(byte[] bytes)
{
return BytesToHex(bytes, 0, bytes.Length);
}
/// <summary>
/// Convert a byte array into an equivalent hex string at the specified starting position and count
/// </summary>
/// <param name="bytes">The byte array need to be converted</param>
/// <param name="startIndex">start position</param>
/// <param name="count">The bytes count need to be converted</param>
/// <returns>A hex string representation corresponding to the byte array</returns>
internal static string BytesToHex(byte[] bytes, int startIndex, int count)
{
if (null == bytes || 0 == bytes.Length || startIndex < 0 || startIndex >= bytes.Length)
{
return string.Empty;
}
int endIndex = startIndex + count > bytes.Length ? bytes.Length : startIndex + count;
char[] result = new char[(endIndex - startIndex) * 2];
int resultIndex = 0;
byte nib;
// (0x1A) => (0x1, 0xA) => (0x1 + 0x30, 0xA + 0x37) => ('1','A')
for (int i = startIndex; i < endIndex; i++)
{
nib = (byte)(bytes[i] >> 4);
result[resultIndex++] = (char)(nib > 9 ? nib + 0x37 : nib + 0x30);
nib = (byte)(bytes[i] & 0xF);
result[resultIndex++] = (char)(nib > 9 ? nib + 0x37 : nib + 0x30);
}
return new string(result);
}
/// <summary>
/// Check if the response message only contains the specified element in the specified xml tag.
/// </summary>
/// <param name="rawResponseXml">The raw xml of the response returned by SUT</param>
/// <param name="tagName">The name of the specified xml tag.</param>
/// <param name="elementName">The element name that the raw xml should contain.</param>
/// <returns>If the response only contains the specified element, return true; otherwise, false.</returns>
internal static bool IsOnlySpecifiedElement(XmlElement rawResponseXml, string tagName, string elementName)
{
bool isOnlySpecifiedElement = false;
if (rawResponseXml != null)
{
XmlNodeList nodes = rawResponseXml.GetElementsByTagName(tagName);
foreach (XmlNode node in nodes)
{
if (node.HasChildNodes)
{
XmlNodeList children = node.ChildNodes;
if (children.Count > 0)
{
foreach (XmlNode child in children)
{
if (string.Equals(child.Name, elementName))
{
isOnlySpecifiedElement = true;
}
else
{
isOnlySpecifiedElement = false;
break;
}
}
}
else
{
isOnlySpecifiedElement = false;
}
}
else
{
isOnlySpecifiedElement = false;
}
}
}
return isOnlySpecifiedElement;
}
/// <summary>
/// Generate an outlook id.
/// </summary>
/// <param name="createTime">The time indicates when the outlook id is created.</param>
/// <returns>An outlook id.</returns>
internal static string GenerateOutlookID(DateTime createTime)
{
// EncodedGlobalId = Header GlobalIdData
// ThirdPartyGlobalId = 1*UTF8-octets ; Assuming UTF-8 is the encoding
//
// Header = ByteArrayID InstanceDate CreationDateTime Padding DataSize
//
// ByteArrayID = "040000008200E00074C5B7101A82E008"
// InstanceDate = InstanceYear InstanceMonth InstanceDay
// InstanceYear = 4*4HEXDIG ; UInt16
// InstanceMonth = 2*2HEXDIG ; UInt8
// InstanceDay = 2*2HEXDIG ; UInt8
// CreationDateTime = FileTime
// FileTime = 16*16HEXDIG ; UInt64
// Padding = 16*16HEXDIG ; "0000000000000000" recommended
// DataSize = 8*8HEXDIG ; UInt32 little-endian
// GlobalIdData = 2*HEXDIG
StringBuilder uidBuilder = new StringBuilder();
// ByteArrayID
uidBuilder.Append("040000008200E00074C5B7101A82E008");
// InstanceDate
uidBuilder.Append("00000000");
byte[] timeBytes = BitConverter.GetBytes(createTime.ToFileTimeUtc());
// CreationDateTime
uidBuilder.Append(TestSuiteHelper.BytesToHex(timeBytes));
// Padding
uidBuilder.Append("0000000000000000");
byte[] gloabalIdData = Guid.NewGuid().ToByteArray();
byte[] dataSizeBytes = BitConverter.GetBytes(gloabalIdData.Length);
// DataSize
uidBuilder.Append(TestSuiteHelper.BytesToHex(dataSizeBytes));
// GlobalIdData
uidBuilder.Append(TestSuiteHelper.BytesToHex(gloabalIdData));
return uidBuilder.ToString();
}
/// <summary>
/// Set the value of common meeting properties
/// </summary>
/// <param name="subject">The subject of the meeting.</param>
/// <param name="attendeeEmailAddress">The email address of attendee.</param>
/// <returns>The key and value pairs of common meeting properties.</returns>
internal static Dictionary<Request.ItemsChoiceType8, object> SetMeetingProperties(string subject, string attendeeEmailAddress, ITestSite testSite)
{
Dictionary<Request.ItemsChoiceType8, object> propertiesToValueMap = new Dictionary<Request.ItemsChoiceType8, object>
{
{
Request.ItemsChoiceType8.Subject, subject
}
};
// Set the subject element.
// MeetingStauts is set to 1, which means it is a meeting and the user is the meeting organizer.
byte meetingStatus = 1;
propertiesToValueMap.Add(Request.ItemsChoiceType8.MeetingStatus, meetingStatus);
// Set the UID
string uID = Guid.NewGuid().ToString();
if (Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", testSite).Equals("16.0"))
{
propertiesToValueMap.Add(Request.ItemsChoiceType8.ClientUid, uID);
}
else
{
propertiesToValueMap.Add(Request.ItemsChoiceType8.UID, uID);
}
// Set the TimeZone
string timeZone = Common.GetTimeZone("(UTC) Coordinated Universal Time", 0);
propertiesToValueMap.Add(Request.ItemsChoiceType8.Timezone, timeZone);
// Set the attendee to user2
Request.Attendees attendees = TestSuiteHelper.CreateAttendees(attendeeEmailAddress);
propertiesToValueMap.Add(Request.ItemsChoiceType8.Attendees, attendees);
return propertiesToValueMap;
}
/// <summary>
/// Create one sample calendar object
/// </summary>
/// <param name="subject">Meeting subject</param>
/// <param name="organizerEmailAddress">Meeting organizer email address</param>
/// <param name="attendeeEmailAddress">Meeting attendee email address</param>
/// <returns>One sample calendar object</returns>
internal static Calendar CreateDefaultCalendar(string subject, string organizerEmailAddress, string attendeeEmailAddress)
{
Calendar calendar = new Calendar
{
Timezone = Common.GetTimeZone("(UTC) Coordinated Universal Time", 0),
DtStamp = DateTime.UtcNow,
StartTime = DateTime.UtcNow.AddHours(1),
Subject = subject,
UID = Guid.NewGuid().ToString(),
OrganizerEmail = organizerEmailAddress,
OrganizerName = organizerEmailAddress,
Location = "My Office",
EndTime = DateTime.UtcNow.AddHours(2),
Sensitivity = 0,
BusyStatus = 1,
AllDayEvent = 0
};
List<Response.AttendeesAttendee> attendeelist = new List<Response.AttendeesAttendee>
{
new Response.AttendeesAttendee
{
Email = attendeeEmailAddress,
Name = attendeeEmailAddress,
AttendeeStatus = 0,
AttendeeType = 1
}
};
calendar.Attendees = new Response.Attendees { Attendee = attendeelist.ToArray() };
return calendar;
}
/// <summary>
/// Create iCalendar format string from one calendar instance for cancel one occurrence of a meeting request
/// </summary>
/// <param name="calendar">Calendar information</param>
/// <returns>iCalendar formatted string</returns>
internal static string CreateiCalendarFormatCancelContent(Calendar calendar)
{
StringBuilder ical = new StringBuilder();
ical.AppendLine("BEGIN: VCALENDAR");
ical.AppendLine("PRODID:-//Microosft Protocols TestSuites");
ical.AppendLine("VERSION:2.0");
ical.AppendLine("METHOD:CANCEL");
ical.AppendLine("X-MS-OLK-FORCEINSPECTOROPEN:TRUE");
ical.AppendLine("BEGIN:VTIMEZONE");
ical.AppendLine("TZID:UTC");
ical.AppendLine("BEGIN:STANDARD");
ical.AppendLine("DTSTART:16010101T000000");
ical.AppendLine("TZOFFSETFROM:-0000");
ical.AppendLine("TZOFFSETTO:-0000");
ical.AppendLine("END:STANDARD");
ical.AppendLine("BEGIN:DAYLIGHT");
ical.AppendLine("DTSTART:16010311T020000");
ical.AppendLine("TZOFFSETFROM:-0000");
ical.AppendLine("TZOFFSETTO:+0000");
ical.AppendLine("END:DAYLIGHT");
ical.AppendLine("END:VTIMEZONE");
ical.AppendLine("BEGIN:VEVENT");
ical.AppendLine("ATTENDEE;CN=\"\";RSVP=" + (calendar.ResponseRequested == true ? "TRUE" : "FALSE") + ":mailto:" + calendar.Attendees.Attendee[0].Email);
ical.AppendLine("PUBLIC");
ical.AppendLine("CREATED:" + ((DateTime)calendar.DtStamp).ToString("yyyyMMddTHHmmss"));
ical.AppendLine("DESCRIPTION:" + calendar.Subject);
ical.AppendLine("DTEND;TZID=\"UTC\":" + calendar.Exceptions.Exception[0].EndTime);
ical.AppendLine("DTSTART;TZID=\"UTC\":" + calendar.Exceptions.Exception[0].StartTime);
ical.AppendLine("LOCATION:" + calendar.Location);
ical.AppendLine("ORGANIZER:MAILTO:" + calendar.OrganizerEmail);
ical.AppendLine("RECURRENCE-ID;TZID=\"UTC\":" + calendar.Exceptions.Exception[0].ExceptionStartTime);
ical.AppendLine("SUMMARY: Canceled: " + calendar.Subject);
ical.AppendLine("UID:" + calendar.UID);
switch (calendar.BusyStatus)
{
case 0:
ical.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:FREE");
break;
case 1:
ical.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE");
break;
case 2:
ical.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:BUSY");
break;
case 3:
ical.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:OOF");
break;
}
if (calendar.DisallowNewTimeProposal == true)
{
ical.AppendLine("X-MICROSOFT-DISALLOW-COUNTER:TRUE");
}
if (calendar.Recurrence != null)
{
switch (calendar.Recurrence.Type)
{
case 1:
ical.AppendLine("RRULE:FREQ=WEEKLY;BYDAY=MO;UNTIL=" + calendar.Recurrence.Until);
break;
case 2:
ical.AppendLine("RRULE:FREQ=MONTHLY;COUNT=3;BYMONTHDAY=1");
break;
case 3:
ical.AppendLine("RRULE:FREQ=MONTHLY;COUNT=3;BYDAY=1MO");
break;
case 5:
ical.AppendLine("RRULE:FREQ=YEARLY;COUNT=3;BYMONTHDAY=1;BYMONTH=1");
break;
case 6:
ical.AppendLine("RRULE:FREQ=YEARLY;COUNT=3;BYDAY=2MO;BYMONTH=1");
break;
}
}
ical.AppendLine("END:VEVENT");
ical.AppendLine("END:VCALENDAR");
return ical.ToString();
}
}
}
| |
/*
* 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.
*/
// Distributed under the Thrift Software License
//
// See accompanying file LICENSE or visit the Thrift site at:
// http://developers.facebook.com/thrift/
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using Thrift.Collections;
using Thrift.Test; //generated code
using Thrift.Transport;
using Thrift.Protocol;
using Thrift.Server;
using Thrift;
using System.Threading;
using System.Text;
using System.Security.Authentication;
namespace Test
{
public class TestServer
{
public static int _clientID = -1;
public delegate void TestLogDelegate(string msg, params object[] values);
public class TradeServerEventHandler : TServerEventHandler
{
public int callCount = 0;
public void preServe()
{
callCount++;
}
public Object createContext(Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output)
{
callCount++;
return null;
}
public void deleteContext(Object serverContext, Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output)
{
callCount++;
}
public void processContext(Object serverContext, Thrift.Transport.TTransport transport)
{
callCount++;
}
};
public class TestHandler : ThriftTest.Iface, Thrift.TControllingHandler
{
public TServer server { get; set; }
private int handlerID;
private StringBuilder reusableStringBuilder = new StringBuilder();
private TestLogDelegate testLogDelegate;
public TestHandler()
{
handlerID = Interlocked.Increment(ref _clientID);
testLogDelegate += testConsoleLogger;
testLogDelegate.Invoke("New TestHandler instance created");
}
public void testConsoleLogger(string msg, params object[] values)
{
reusableStringBuilder.Clear();
reusableStringBuilder.AppendFormat("handler{0:D3}:",handlerID);
reusableStringBuilder.AppendFormat(msg, values);
reusableStringBuilder.AppendLine();
Console.Write( reusableStringBuilder.ToString() );
}
public void testVoid()
{
testLogDelegate.Invoke("testVoid()");
}
public string testString(string thing)
{
testLogDelegate.Invoke("testString({0})", thing);
return thing;
}
public bool testBool(bool thing)
{
testLogDelegate.Invoke("testBool({0})", thing);
return thing;
}
public sbyte testByte(sbyte thing)
{
testLogDelegate.Invoke("testByte({0})", thing);
return thing;
}
public int testI32(int thing)
{
testLogDelegate.Invoke("testI32({0})", thing);
return thing;
}
public long testI64(long thing)
{
testLogDelegate.Invoke("testI64({0})", thing);
return thing;
}
public double testDouble(double thing)
{
testLogDelegate.Invoke("testDouble({0})", thing);
return thing;
}
public byte[] testBinary(byte[] thing)
{
string hex = BitConverter.ToString(thing).Replace("-", string.Empty);
testLogDelegate.Invoke("testBinary({0:X})", hex);
return thing;
}
public Xtruct testStruct(Xtruct thing)
{
testLogDelegate.Invoke("testStruct({{\"{0}\", {1}, {2}, {3}}})", thing.String_thing, thing.Byte_thing, thing.I32_thing, thing.I64_thing);
return thing;
}
public Xtruct2 testNest(Xtruct2 nest)
{
Xtruct thing = nest.Struct_thing;
testLogDelegate.Invoke("testNest({{{0}, {{\"{1}\", {2}, {3}, {4}, {5}}}}})",
nest.Byte_thing,
thing.String_thing,
thing.Byte_thing,
thing.I32_thing,
thing.I64_thing,
nest.I32_thing);
return nest;
}
public Dictionary<int, int> testMap(Dictionary<int, int> thing)
{
reusableStringBuilder.Clear();
reusableStringBuilder.Append("testMap({{");
bool first = true;
foreach (int key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
reusableStringBuilder.Append(", ");
}
reusableStringBuilder.AppendFormat("{0} => {1}", key, thing[key]);
}
reusableStringBuilder.Append("}})");
testLogDelegate.Invoke(reusableStringBuilder.ToString());
return thing;
}
public Dictionary<string, string> testStringMap(Dictionary<string, string> thing)
{
reusableStringBuilder.Clear();
reusableStringBuilder.Append("testStringMap({{");
bool first = true;
foreach (string key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
reusableStringBuilder.Append(", ");
}
reusableStringBuilder.AppendFormat("{0} => {1}", key, thing[key]);
}
reusableStringBuilder.Append("}})");
testLogDelegate.Invoke(reusableStringBuilder.ToString());
return thing;
}
public THashSet<int> testSet(THashSet<int> thing)
{
reusableStringBuilder.Clear();
reusableStringBuilder.Append("testSet({{");
bool first = true;
foreach (int elem in thing)
{
if (first)
{
first = false;
}
else
{
reusableStringBuilder.Append(", ");
}
reusableStringBuilder.AppendFormat("{0}", elem);
}
reusableStringBuilder.Append("}})");
testLogDelegate.Invoke(reusableStringBuilder.ToString());
return thing;
}
public List<int> testList(List<int> thing)
{
reusableStringBuilder.Clear();
reusableStringBuilder.Append("testList({{");
bool first = true;
foreach (int elem in thing)
{
if (first)
{
first = false;
}
else
{
reusableStringBuilder.Append(", ");
}
reusableStringBuilder.AppendFormat("{0}", elem);
}
reusableStringBuilder.Append("}})");
testLogDelegate.Invoke(reusableStringBuilder.ToString());
return thing;
}
public Numberz testEnum(Numberz thing)
{
testLogDelegate.Invoke("testEnum({0})", thing);
return thing;
}
public long testTypedef(long thing)
{
testLogDelegate.Invoke("testTypedef({0})", thing);
return thing;
}
public Dictionary<int, Dictionary<int, int>> testMapMap(int hello)
{
testLogDelegate.Invoke("testMapMap({0})", hello);
Dictionary<int, Dictionary<int, int>> mapmap =
new Dictionary<int, Dictionary<int, int>>();
Dictionary<int, int> pos = new Dictionary<int, int>();
Dictionary<int, int> neg = new Dictionary<int, int>();
for (int i = 1; i < 5; i++)
{
pos[i] = i;
neg[-i] = -i;
}
mapmap[4] = pos;
mapmap[-4] = neg;
return mapmap;
}
public Dictionary<long, Dictionary<Numberz, Insanity>> testInsanity(Insanity argument)
{
testLogDelegate.Invoke("testInsanity()");
Xtruct hello = new Xtruct();
hello.String_thing = "Hello2";
hello.Byte_thing = 2;
hello.I32_thing = 2;
hello.I64_thing = 2;
Xtruct goodbye = new Xtruct();
goodbye.String_thing = "Goodbye4";
goodbye.Byte_thing = (sbyte)4;
goodbye.I32_thing = 4;
goodbye.I64_thing = (long)4;
Insanity crazy = new Insanity();
crazy.UserMap = new Dictionary<Numberz, long>();
crazy.UserMap[Numberz.EIGHT] = (long)8;
crazy.Xtructs = new List<Xtruct>();
crazy.Xtructs.Add(goodbye);
Insanity looney = new Insanity();
crazy.UserMap[Numberz.FIVE] = (long)5;
crazy.Xtructs.Add(hello);
Dictionary<Numberz, Insanity> first_map = new Dictionary<Numberz, Insanity>();
Dictionary<Numberz, Insanity> second_map = new Dictionary<Numberz, Insanity>(); ;
first_map[Numberz.TWO] = crazy;
first_map[Numberz.THREE] = crazy;
second_map[Numberz.SIX] = looney;
Dictionary<long, Dictionary<Numberz, Insanity>> insane =
new Dictionary<long, Dictionary<Numberz, Insanity>>();
insane[(long)1] = first_map;
insane[(long)2] = second_map;
return insane;
}
public Xtruct testMulti(sbyte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5)
{
testLogDelegate.Invoke("testMulti()");
Xtruct hello = new Xtruct(); ;
hello.String_thing = "Hello2";
hello.Byte_thing = arg0;
hello.I32_thing = arg1;
hello.I64_thing = arg2;
return hello;
}
/**
* Print 'testException(%s)' with arg as '%s'
* @param string arg - a string indication what type of exception to throw
* if arg == "Xception" throw Xception with errorCode = 1001 and message = arg
* elsen if arg == "TException" throw TException
* else do not throw anything
*/
public void testException(string arg)
{
testLogDelegate.Invoke("testException({0})", arg);
if (arg == "Xception")
{
Xception x = new Xception();
x.ErrorCode = 1001;
x.Message = arg;
throw x;
}
if (arg == "TException")
{
throw new Thrift.TException();
}
return;
}
public Xtruct testMultiException(string arg0, string arg1)
{
testLogDelegate.Invoke("testMultiException({0}, {1})", arg0,arg1);
if (arg0 == "Xception")
{
Xception x = new Xception();
x.ErrorCode = 1001;
x.Message = "This is an Xception";
throw x;
}
else if (arg0 == "Xception2")
{
Xception2 x = new Xception2();
x.ErrorCode = 2002;
x.Struct_thing = new Xtruct();
x.Struct_thing.String_thing = "This is an Xception2";
throw x;
}
Xtruct result = new Xtruct();
result.String_thing = arg1;
return result;
}
public void testStop()
{
if (server != null)
{
server.Stop();
}
}
public void testOneway(int arg)
{
testLogDelegate.Invoke("testOneway({0}), sleeping...", arg);
System.Threading.Thread.Sleep(arg * 1000);
testLogDelegate.Invoke("testOneway finished");
}
} // class TestHandler
private enum ServerType
{
TSimpleServer,
TThreadedServer,
TThreadPoolServer,
}
private enum ProcessorFactoryType
{
TSingletonProcessorFactory,
TPrototypeProcessorFactory,
}
public static bool Execute(string[] args)
{
try
{
bool useBufferedSockets = false, useFramed = false, useEncryption = false, compact = false, json = false;
ServerType serverType = ServerType.TSimpleServer;
ProcessorFactoryType processorFactoryType = ProcessorFactoryType.TSingletonProcessorFactory;
int port = 9090;
string pipe = null;
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-pipe") // -pipe name
{
pipe = args[++i];
}
else if (args[i].Contains("--port="))
{
port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
useBufferedSockets = true;
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
useFramed = true;
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
compact = true;
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
json = true;
}
else if (args[i] == "--threaded" || args[i] == "--server-type=threaded")
{
serverType = ServerType.TThreadedServer;
}
else if (args[i] == "--threadpool" || args[i] == "--server-type=threadpool")
{
serverType = ServerType.TThreadPoolServer;
}
else if (args[i] == "--prototype" || args[i] == "--processor=prototype")
{
processorFactoryType = ProcessorFactoryType.TPrototypeProcessorFactory;
}
else if (args[i] == "--ssl")
{
useEncryption = true;
}
}
// Transport
TServerTransport trans;
if (pipe != null)
{
trans = new TNamedPipeServerTransport(pipe);
}
else
{
if (useEncryption)
{
string certPath = "../../../../test/keys/server.p12";
trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath, "thrift"), null, null, SslProtocols.Tls);
}
else
{
trans = new TServerSocket(port, 0, useBufferedSockets);
}
}
TProtocolFactory proto;
if (compact)
proto = new TCompactProtocol.Factory();
else if (json)
proto = new TJSONProtocol.Factory();
else
proto = new TBinaryProtocol.Factory();
TProcessorFactory processorFactory;
if (processorFactoryType == ProcessorFactoryType.TPrototypeProcessorFactory)
{
processorFactory = new TPrototypeProcessorFactory<ThriftTest.Processor, TestHandler>();
}
else
{
// Processor
TestHandler testHandler = new TestHandler();
ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler);
processorFactory = new TSingletonProcessorFactory(testProcessor);
}
TTransportFactory transFactory;
if (useFramed)
transFactory = new TFramedTransport.Factory();
else
transFactory = new TTransportFactory();
TServer serverEngine;
switch (serverType)
{
case ServerType.TThreadPoolServer:
serverEngine = new TThreadPoolServer(processorFactory, trans, transFactory, proto);
break;
case ServerType.TThreadedServer:
serverEngine = new TThreadedServer(processorFactory, trans, transFactory, proto);
break;
default:
serverEngine = new TSimpleServer(processorFactory, trans, transFactory, proto);
break;
}
//Server event handler
TradeServerEventHandler serverEvents = new TradeServerEventHandler();
serverEngine.setEventHandler(serverEvents);
// Run it
string where = (pipe != null ? "on pipe " + pipe : "on port " + port);
Console.WriteLine("Starting the " + serverType.ToString() + " " + where +
(processorFactoryType == ProcessorFactoryType.TPrototypeProcessorFactory ? " with processor prototype factory " : "") +
(useBufferedSockets ? " with buffered socket" : "") +
(useFramed ? " with framed transport" : "") +
(useEncryption ? " with encryption" : "") +
(compact ? " with compact protocol" : "") +
(json ? " with json protocol" : "") +
"...");
serverEngine.Serve();
}
catch (Exception x)
{
Console.Error.Write(x);
return false;
}
Console.WriteLine("done.");
return true;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Data;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Description;
using System.Web.Services.Protocols;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Text;
using System.Reflection;
using System.IO;
using System.Net;
using Microsoft.CSharp;
namespace fyiReporting.Data
{
/// <summary>
/// WebServiceWsdl handles generation and caching of Assemblies containing WSDL proxies
/// It also will invoke proxies with the proper arguments. These arguments must be
/// provided as a WebServiceParameter.
/// </summary>
public class WebServiceWsdl
{
// Cache the compiled assemblies
const string _Namespace = "fyireporting.ws";
static Hashtable _cache = Hashtable.Synchronized(new Hashtable());
string _url; // url for this assembly
Assembly _WsdlAssembly; // Assembly ready for invokation
static internal WebServiceWsdl GetWebServiceWsdl(string url)
{
WebServiceWsdl w = _cache[url] as WebServiceWsdl;
if (w != null)
return w;
return new WebServiceWsdl(url);
}
static public void ClearCache()
{
_cache.Clear();
}
public MethodInfo GetMethodInfo(string service, string operation)
{
// Create an instance of the service object proxy
object o = _WsdlAssembly.CreateInstance(_Namespace + "." + service, false);
if (o == null)
throw new Exception(string.Format("Unable to create instance of service '{0}'.", service));
// Get information about the method
MethodInfo mi = o.GetType().GetMethod(operation);
if (mi == null)
throw new Exception(string.Format("Unable to find operation '{0}' in service '{1}'.", operation, service));
return mi;
}
// Invoke the operation for the requested service
public object Invoke(string service, string operation, DataParameterCollection dpc, int timeout)
{
// Create an instance of the service object proxy
object o = _WsdlAssembly.CreateInstance(_Namespace + "." + service, false);
if (o == null)
throw new Exception(string.Format("Unable to create instance of service '{0}'.", service));
// Get information about the method
MethodInfo mi = o.GetType().GetMethod(operation);
if (mi == null)
throw new Exception(string.Format("Unable to find operation '{0}' in service '{1}'.", operation, service));
// Go thru the parameters building up an object array with the proper parameters
ParameterInfo[] pis = mi.GetParameters();
object[] args = new object[pis.Length];
int ai=0;
foreach (ParameterInfo pi in pis)
{
BaseDataParameter dp = dpc[pi.Name] as BaseDataParameter;
if (dp == null) // retry with '@' in front!
dp = dpc["@"+pi.Name] as BaseDataParameter;
if (dp == null || dp.Value == null)
args[ai] = null;
else if (pi.ParameterType == dp.Value.GetType())
args[ai] = dp.Value;
else // we need to do conversion
args[ai] = Convert.ChangeType(dp.Value, pi.ParameterType);
ai++;
}
SoapHttpClientProtocol so = o as SoapHttpClientProtocol;
if (so != null && timeout != 0)
so.Timeout = timeout;
return mi.Invoke(o, args);
}
// constructor
private WebServiceWsdl(string url)
{
_url = url;
_WsdlAssembly = GetAssembly();
_cache.Add(url, this);
}
private Assembly GetAssembly()
{
ServiceDescription sd = GetServiceDescription();
// ServiceDescriptionImporter provide means for generating client proxy classes for XML Web services
CodeNamespace cns = new CodeNamespace(_Namespace);
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, null, null);
sdi.ProtocolName = "Soap";
sdi.Import(cns, null);
// Generate the proxy source code
CSharpCodeProvider cscp = new CSharpCodeProvider();
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
cscp.GenerateCodeFromNamespace(cns, sw, null);
string proxy = sb.ToString();
sw.Close();
// debug code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// StreamWriter tsw = File.CreateText(@"c:\temp\proxy.cs");
// tsw.Write(proxy);
// tsw.Close();
// debug code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Create Assembly
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Xml.dll");
cp.ReferencedAssemblies.Add("System.Web.Services.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = false; // just loading into memory causes problems when instantiating
cp.IncludeDebugInformation = false;
CompilerResults cr = cscp.CompileAssemblyFromSource(cp, proxy);
if(cr.Errors.Count > 0)
{
StringBuilder err = new StringBuilder(string.Format("WSDL proxy compile has {0} error(s).", cr.Errors.Count));
foreach (CompilerError ce in cr.Errors)
{
err.AppendFormat("\r\n{0} {1}", ce.ErrorNumber, ce.ErrorText);
}
throw new Exception(err.ToString());
}
return Assembly.LoadFrom(cr.PathToAssembly); // We need an assembly loaded from the file system
// or instantiation of object complains
}
public ServiceDescription GetServiceDescription()
{
ServiceDescription sd = new ServiceDescription();
Stream sr=null;
try
{
sr = GetStream();
sd = ServiceDescription.Read(sr);
}
finally
{
if (sr != null)
sr.Close();
}
return sd;
}
Stream GetStream()
{
string fname = _url;
Stream strm=null;
if (fname.StartsWith("http:") ||
fname.StartsWith("file:") ||
fname.StartsWith("https:"))
{
WebRequest wreq = WebRequest.Create(fname);
WebResponse wres = wreq.GetResponse();
strm = wres.GetResponseStream();
}
else
strm = new FileStream(fname, System.IO.FileMode.Open, FileAccess.Read);
return strm;
}
}
}
| |
using EPiServer.Commerce.Marketing;
using EPiServer.Commerce.Order;
using EPiServer.Commerce.Order.Internal;
using EPiServer.Reference.Commerce.Site.Features.AddressBook.Services;
using EPiServer.Reference.Commerce.Site.Features.Cart.Services;
using EPiServer.Reference.Commerce.Site.Features.Cart.ViewModels;
using EPiServer.Reference.Commerce.Site.Features.Market.Services;
using EPiServer.Reference.Commerce.Site.Features.Product.Services;
using EPiServer.Reference.Commerce.Site.Features.Shared.Models;
using EPiServer.Reference.Commerce.Site.Features.Shared.Services;
using EPiServer.Reference.Commerce.Site.Infrastructure.Facades;
using EPiServer.Reference.Commerce.Site.Tests.TestSupport.Fakes;
using Mediachase.Commerce;
using Mediachase.Commerce.Customers;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace EPiServer.Reference.Commerce.Site.Tests.Features.Cart.Services
{
public class CartServiceTests
{
[Fact]
public void AddCouponCode_WhenCouponCodeIsAppliedToPromotion_ShouldReturnTrue()
{
var couponCode = "IBUYALOT";
var rewardDescription = RewardDescription.CreatePercentageReward(FulfillmentStatus.Fulfilled, null, new PromotionForTest(), 10, string.Empty);
rewardDescription.AppliedCoupon = couponCode;
_promotionEngineMock
.Setup(x => x.Run(It.IsAny<IOrderGroup>(), It.IsAny<PromotionEngineSettings>()))
.Returns(new[] { rewardDescription });
var result = _subject.AddCouponCode(_cart, couponCode);
Assert.True(result);
}
[Fact]
public void AddCouponCode_WhenCouponCodeIsNotAppliedToPromotion_ShouldReturnFalse()
{
var couponCode = "IDONTEXIST";
_promotionEngineMock
.Setup(x => x.Run(It.IsAny<IOrderGroup>(), It.IsAny<PromotionEngineSettings>()))
.Returns(new[] {
RewardDescription.CreatePercentageReward(FulfillmentStatus.Fulfilled, null, new PromotionForTest(), 10, string.Empty)
});
var result = _subject.AddCouponCode(_cart, couponCode);
Assert.False(result);
}
[Fact]
public void RemoveCouponCode_ShouldRemoveCodeFromForm()
{
string couponCode = "IBUYALOT";
_cart.GetFirstForm().CouponCodes.Add(couponCode);
_subject.RemoveCouponCode(_cart, couponCode);
Assert.Empty(_cart.GetFirstForm().CouponCodes);
}
[Fact]
public void AddToCart_ShouldRunPromotionEngine()
{
var code = "EAN";
string warningMessage = null;
_subject.AddToCart(_cart, code, out warningMessage);
_promotionEngineMock.Verify(x => x.Run(_cart, It.IsAny<PromotionEngineSettings>()), Times.Once);
}
[Fact]
public void AddToCart_WhenLineItemNotInCart_ShouldAddToCart()
{
string warningMessage;
_subject.AddToCart(_cart, "code", out warningMessage);
Assert.Equal(1, _cart.GetAllLineItems().Single(x => x.Code == "code").Quantity);
}
[Fact]
public void AddToCart_WhenLineItemAlreadyInCart_ShouldIncreaseQuantity()
{
string warningMessage;
_subject.AddToCart(_cart, "code", out warningMessage);
_subject.AddToCart(_cart, "code", out warningMessage);
Assert.Equal(2, _cart.GetAllLineItems().Single(x => x.Code == "code").Quantity);
}
[Fact]
public void ChangeCartItem_ShouldChangeQuantityAccordingly()
{
var shipmentId = 0;
var quantity = 5m;
var size = "small";
var code = "EAN";
var newSize = "small";
var lineItem = new InMemoryLineItem
{
Quantity = 2,
Code = code
};
_cart.GetFirstShipment().LineItems.Add(lineItem);
_subject.ChangeCartItem(_cart, shipmentId, code, quantity, size, newSize);
Assert.Equal<decimal>(quantity, lineItem.Quantity);
}
[Fact]
public void ChangeCartItem_WhenQuantityIsZero_ShouldRemoveLineItem()
{
var shipmentId = 0;
var quantity = 0;
var size = "small";
var code = "EAN";
var newSize = "small";
var lineItem = new InMemoryLineItem
{
Quantity = 2,
Code = code
};
_cart.GetFirstShipment().LineItems.Add(lineItem);
_subject.ChangeCartItem(_cart, shipmentId, code, quantity, size, newSize);
Assert.Empty(_cart.GetAllLineItems());
}
[Fact]
public void ChangeCartItem_WhenLineItemToChangeToDoesNotExists_ShouldUpdateLineItem()
{
_productServiceMock.Setup(x => x.GetSiblingVariantCodeBySize(It.IsAny<string>(), It.IsAny<string>())).Returns("newcode");
_cart.GetFirstShipment().LineItems.Add(new InMemoryLineItem { Quantity = 1, Code = "code" });
_subject.ChangeCartItem(_cart, 0, "code", 5, "S", "M");
Assert.Equal<string>("newcode", _cart.GetFirstShipment().LineItems.Single().Code);
Assert.Equal<decimal>(5, _cart.GetFirstShipment().LineItems.Single().Quantity);
}
[Fact]
public void ChangeCartItem_WhenLineItemToChangeToAlreadyExists_ShouldUpdateLineItem()
{
_productServiceMock.Setup(x => x.GetSiblingVariantCodeBySize(It.IsAny<string>(), It.IsAny<string>())).Returns("newcode");
_cart.GetFirstShipment().LineItems.Add(new InMemoryLineItem { Quantity = 1, Code = "newcode" });
_cart.GetFirstShipment().LineItems.Add(new InMemoryLineItem { Quantity = 1, Code = "code" });
_subject.ChangeCartItem(_cart, 0, "code", 5, "S", "M");
Assert.Equal<string>("newcode", _cart.GetFirstShipment().LineItems.Single().Code);
Assert.Equal<decimal>(5 + 1, _cart.GetFirstShipment().LineItems.Single().Quantity);
}
[Fact]
public void LoadCart_WhenNotExist_ShouldReturnNUll()
{
var result = _subject.LoadCart("UNKNOWN");
Assert.Null(result);
}
[Fact]
public void LoadCart_WhenExist_ShouldReturnInstanceOfCart()
{
var result = _subject.LoadCart(_subject.DefaultCartName);
Assert.Equal<ICart>(_cart, result);
Assert.Equal(result.Currency, new Currency("USD"));
}
[Fact]
public void LoadCart_WithCurrentCurrency_WhenExist_ShouldReturnInstanceOfCart()
{
var currentCurrency = new Currency("SEK");
_currencyServiceMock.Setup(x => x.GetCurrentCurrency()).Returns(currentCurrency);
var result = _subject.LoadCart(_subject.DefaultCartName);
Assert.Equal(result.Currency, currentCurrency);
}
[Fact]
public void LoadCart_WhenAllItemsIsValid_ShouldReturnCartWithAllItems()
{
var lineItem = new InMemoryLineItem { Quantity = 2, Code = "code1" };
var lineItem2 = new InMemoryLineItem { Quantity = 2, Code = "code2" };
_cart.GetFirstShipment().LineItems.Add(lineItem);
_cart.GetFirstShipment().LineItems.Add(lineItem2);
var result = _subject.LoadCart(_subject.DefaultCartName);
Assert.Equal(2, result.GetAllLineItems().Count());
}
[Fact]
public void LoadCart_WhenExistInvalidItems_ShouldReturnCartWithOnlyValidItems()
{
var _validCode = "code1";
var _inValidCode = "code2";
var lineItem = new InMemoryLineItem { Quantity = 2, Code = _validCode };
var lineItem2 = new InMemoryLineItem { Quantity = 2, Code = _inValidCode };
_cart.GetFirstShipment().LineItems.Add(lineItem);
_cart.GetFirstShipment().LineItems.Add(lineItem2);
_lineItemValidatorMock.Setup(x => x.Validate(lineItem, It.IsAny<IMarket>(), It.IsAny<Action<ILineItem, ValidationIssue>>())).Returns(true);
_lineItemValidatorMock.Setup(x => x.Validate(lineItem2, It.IsAny<IMarket>(), It.IsAny<Action<ILineItem, ValidationIssue>>())).Returns(false);
var result = _subject.LoadCart(_subject.DefaultCartName);
Assert.True(result.GetAllLineItems().Any(l => l.Code == _validCode));
Assert.False(result.GetAllLineItems().Any(l => l.Code == _inValidCode));
}
[Fact]
public void LoadOrCreateCart_WhenExist_ShouldReturnInstanceOfCart()
{
var result = _subject.LoadOrCreateCart(_subject.DefaultCartName);
Assert.Equal<ICart>(_cart, result);
Assert.Equal(result.Currency, new Currency("USD"));
}
[Fact]
public void LoadOrCreateCart_WithCurrentCurrency_WhenExist_ShouldReturnInstanceOfCart()
{
var currentCurrency = new Currency("SEK");
_currencyServiceMock.Setup(x => x.GetCurrentCurrency()).Returns(currentCurrency);
var result = _subject.LoadOrCreateCart(_subject.DefaultCartName);
Assert.Equal(result.Currency, currentCurrency);
}
[Fact]
public void LoadOrCreateCart_WhenNoCartExists_ShouldReturnNewInstanceOfCart()
{
_orderRepositoryMock
.Setup(x => x.Create<ICart>(It.IsAny<Guid>(), It.IsAny<string>()))
.Returns(new FakeCart(_marketMock.Object, new Currency("USD")));
var result = _subject.LoadOrCreateCart("UNKNOWN");
Assert.NotNull(result);
Assert.NotEqual<ICart>(_cart, result);
}
[Fact]
public void MergeShipments()
{
_subject.MergeShipments(_cart);
}
[Fact]
public void RecreateLineItemsBasedOnShipments_WhenHavingTwoShippingAddresses_ShouldCreateTwoShipmentLineItems()
{
var shipment = _cart.GetFirstShipment();
var skuCode = "EAN";
shipment.LineItems.Add(new InMemoryLineItem
{
Code = skuCode,
Quantity = 3
});
_subject.RecreateLineItemsBasedOnShipments(_cart, new[]
{
new CartItemViewModel { Code = skuCode, AddressId = "1" },
new CartItemViewModel { Code = skuCode, AddressId = "2" },
new CartItemViewModel { Code = skuCode, AddressId = "2" }
}, new[]
{
new AddressModel { AddressId = "1", Line1 = "First street" },
new AddressModel { AddressId = "2", Line1 = "Second street" }
});
Assert.Equal<int>(2, _cart.GetAllLineItems().Count());
}
[Fact]
public void RecreateLineItemsBasedOnShipments_WhenHavingLineItemAsGift_ShouldKeepIsGift()
{
var shipment = _cart.GetFirstShipment();
var skuCode = "EAN";
var giftSkuCode = "AAA";
shipment.LineItems.Add(new InMemoryLineItem
{
Code = giftSkuCode,
Quantity = 1,
IsGift = true
});
shipment.LineItems.Add(new InMemoryLineItem
{
Code = skuCode,
Quantity = 2,
IsGift = false
});
_subject.RecreateLineItemsBasedOnShipments(_cart, new[]
{
new CartItemViewModel { Code = skuCode, AddressId = "1", IsGift = false},
new CartItemViewModel { Code = skuCode, AddressId = "2", IsGift = false},
new CartItemViewModel { Code = giftSkuCode, AddressId = "2", IsGift = true},
}, new[]
{
new AddressModel { AddressId = "1", Line1 = "First street" },
new AddressModel { AddressId = "2", Line1 = "Second street" }
});
Assert.Equal<int>(1, _cart.GetAllLineItems().Where(x => x.Code == giftSkuCode && x.IsGift).Count());
Assert.Equal<int>(2, _cart.GetAllLineItems().Where(x => x.Code == skuCode && !x.IsGift).Count());
}
[Fact]
public void RecreateLineItemsBasedOnShipments_WhenHavingLineItemWithSameCodeAsGiftAndNotGift_ShouldKeepIsGift()
{
var shipment = _cart.GetFirstShipment();
var skuCode = "EAN";
shipment.LineItems.Add(new InMemoryLineItem
{
Code = skuCode,
Quantity = 1,
IsGift = true
});
shipment.LineItems.Add(new InMemoryLineItem
{
Code = skuCode,
Quantity = 2,
IsGift = false
});
_subject.RecreateLineItemsBasedOnShipments(_cart, new[]
{
new CartItemViewModel { Code = skuCode, AddressId = "1", IsGift = false},
new CartItemViewModel { Code = skuCode, AddressId = "2" , IsGift = false},
new CartItemViewModel { Code = skuCode, AddressId = "2" , IsGift = true}
}, new[]
{
new AddressModel { AddressId = "1", Line1 = "First street" },
new AddressModel { AddressId = "2", Line1 = "Second street" }
});
Assert.Equal<int>(2, _cart.GetAllLineItems().Where(x => x.Code == skuCode && !x.IsGift).Count());
Assert.Equal<int>(1, _cart.GetAllLineItems().Where(x => x.Code == skuCode && x.IsGift).Count());
}
[Fact]
public void RequestInventory()
{
_subject.RequestInventory(_cart);
}
[Fact]
public void ValidateCart()
{
var result = _subject.ValidateCart(_cart);
}
[Fact]
public void ValidateCart_WhenIsWishList_ShouldReturnEmptyDictionary()
{
_cart.Name = _subject.DefaultWishListName;
var expectedResult = new Dictionary<ILineItem, List<ValidationIssue>>();
var result = _subject.ValidateCart(_cart);
Assert.Equal<Dictionary<ILineItem, List<ValidationIssue>>>(expectedResult, result);
}
private readonly Mock<IAddressBookService> _addressBookServiceMock;
private readonly Mock<CustomerContextFacade> _customerContextFacaceMock;
private readonly Mock<IOrderGroupFactory> _orderGroupFactoryMock;
private readonly Mock<IInventoryProcessor> _inventoryProcessorMock;
private readonly Mock<ILineItemValidator> _lineItemValidatorMock;
private readonly Mock<IOrderRepository> _orderRepositoryMock;
private readonly Mock<IPlacedPriceProcessor> _placedPriceProcessorMock;
private readonly Mock<IPricingService> _pricingServiceMock;
private readonly Mock<IProductService> _productServiceMock;
private readonly Mock<IPromotionEngine> _promotionEngineMock;
private readonly Mock<ICurrentMarket> _currentMarketMock;
private readonly Mock<IMarket> _marketMock;
private readonly Mock<ICurrencyService> _currencyServiceMock;
private readonly CartService _subject;
private readonly ICart _cart;
public CartServiceTests()
{
_addressBookServiceMock = new Mock<IAddressBookService>();
_customerContextFacaceMock = new Mock<CustomerContextFacade>();
_orderGroupFactoryMock = new Mock<IOrderGroupFactory>();
_inventoryProcessorMock = new Mock<IInventoryProcessor>();
_lineItemValidatorMock = new Mock<ILineItemValidator>();
_orderRepositoryMock = new Mock<IOrderRepository>();
_placedPriceProcessorMock = new Mock<IPlacedPriceProcessor>();
_pricingServiceMock = new Mock<IPricingService>();
_productServiceMock = new Mock<IProductService>();
_productServiceMock = new Mock<IProductService>();
_promotionEngineMock = new Mock<IPromotionEngine>();
_marketMock = new Mock<IMarket>();
_currentMarketMock = new Mock<ICurrentMarket>();
_currencyServiceMock = new Mock<ICurrencyService>();
_subject = new CartService(_productServiceMock.Object, _pricingServiceMock.Object, _orderGroupFactoryMock.Object,
_customerContextFacaceMock.Object, _placedPriceProcessorMock.Object, _inventoryProcessorMock.Object,
_lineItemValidatorMock.Object, _orderRepositoryMock.Object, _promotionEngineMock.Object,
_addressBookServiceMock.Object, _currentMarketMock.Object, _currencyServiceMock.Object);
_cart = new FakeCart(new Mock<IMarket>().Object, new Currency("USD")) { Name = _subject.DefaultCartName };
_orderGroupFactoryMock.Setup(x => x.CreateLineItem(It.IsAny<string>(), It.IsAny<IOrderGroup>())).Returns((string code, IOrderGroup group) => new FakeLineItem() { Code = code });
_orderGroupFactoryMock.Setup(x => x.CreateShipment(It.IsAny<IOrderGroup>())).Returns((IOrderGroup orderGroup) => new FakeShipment());
_orderRepositoryMock.Setup(x => x.Load<ICart>(It.IsAny<Guid>(), _subject.DefaultCartName)).Returns(new[] { _cart });
_orderRepositoryMock.Setup(x => x.Create<ICart>(It.IsAny<Guid>(), _subject.DefaultCartName)).Returns(_cart);
_currentMarketMock.Setup(x => x.GetCurrentMarket()).Returns(_marketMock.Object);
_lineItemValidatorMock.Setup(x => x.Validate(It.IsAny<ILineItem>(), It.IsAny<IMarket>(), It.IsAny<Action<ILineItem, ValidationIssue>>())).Returns(true);
_placedPriceProcessorMock.Setup(x => x.UpdatePlacedPrice(It.IsAny<ILineItem>(), It.IsAny<CustomerContact>(), It.IsAny<IMarket>(), _cart.Currency, It.IsAny<Action<ILineItem, ValidationIssue>>())).Returns(true);
}
class PromotionForTest : EntryPromotion
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall;
using FlatRedBall.Gui;
using FlatRedBall.Math;
using FlatRedBall.Math.Geometry;
using EditorObjects;
using PolygonEditor.Gui;
using FlatRedBall.Utilities;
using FlatRedBall.Input;
using FlatRedBall.Graphics;
#if FRB_MDX
using Microsoft.DirectX;
#else
using Microsoft.Xna.Framework;
using Point = FlatRedBall.Math.Geometry.Point;
using Keys = Microsoft.Xna.Framework.Input.Keys;
using EditorObjects.NodeNetworks;
#endif
namespace PolygonEditor
{
#region Enums
public enum EditingState
{
None,
AddingPointsOnEnd,
AddingPoints
}
#endregion
public class EditingLogic
{
#region Fields
PositionedObject mObjectGrabbed;
EditingState mEditingState;
ShapeCollection mCurrentShapeCollection = new ShapeCollection();
NodeNetworkEditorManager mNodeNetworkEditorManager;
ReactiveHud mReactiveHud;
#endregion
#region Properties
#region Private Properties
Polygon PolygonGrabbed
{
get { return mObjectGrabbed as Polygon; }
}
AxisAlignedRectangle AxisAlignedRectangleGrabbed
{
get { return mObjectGrabbed as AxisAlignedRectangle; }
}
Circle CircleGrabbed
{
get { return mObjectGrabbed as Circle; }
}
Sphere SphereGrabbed
{
get { return mObjectGrabbed as Sphere; }
}
AxisAlignedCube AxisAlignedCubeGrabbed
{
get { return mObjectGrabbed as AxisAlignedCube; }
}
#endregion
public EditingState EditingState
{
get { return mEditingState; }
set { mEditingState = value; }
}
public PositionedObjectList<Polygon> CurrentPolygons
{
get {return CurrentShapeCollection.Polygons; }
}
public NodeNetworkEditorManager NodeNetworkEditorManager
{
get
{
return mNodeNetworkEditorManager;
}
}
public ShapeCollection CurrentShapeCollection
{
get { return mCurrentShapeCollection; }
}
#endregion
#region Methods
#region Constructors
public EditingLogic()
{
mReactiveHud = new ReactiveHud();
mNodeNetworkEditorManager = new NodeNetworkEditorManager();
PrepareUndoManager();
}
void PrepareUndoManager()
{
UndoManager.AddAxisAlignedCubePropertyComparer();
}
#endregion
#region Public Methods
public Polygon AddRectanglePolygon()
{
Polygon polygon = Polygon.CreateRectangle(1, 1);
ShapeManager.AddPolygon(polygon);
polygon.Color = EditorProperties.PolygonColor;
polygon.X = SpriteManager.Camera.X;
polygon.Y = SpriteManager.Camera.Y;
float scale = (float)Math.Abs(
18 / SpriteManager.Camera.PixelsPerUnitAt(0));
polygon.ScaleBy(scale);
EditorData.ShapeCollection.Polygons.Add(polygon);
polygon.Name = "Polygon" + EditorData.Polygons.Count;
StringFunctions.MakeNameUnique<Polygon>(polygon, EditorData.Polygons);
return polygon;
}
public void AddAxisAlignedCube()
{
AxisAlignedCube cube = new AxisAlignedCube();
ShapeManager.AddAxisAlignedCube(cube);
cube.Color = EditorProperties.AxisAlignedCubeColor;
cube.X = SpriteManager.Camera.X;
cube.Y = SpriteManager.Camera.Y;
float scale = (float)Math.Abs(
18 / SpriteManager.Camera.PixelsPerUnitAt(0));
cube.ScaleX = scale;
cube.ScaleY = scale;
cube.ScaleZ = scale;
EditorData.ShapeCollection.AxisAlignedCubes.Add(cube);
cube.Name = "Cube" + EditorData.AxisAlignedCubes.Count;
StringFunctions.MakeNameUnique<AxisAlignedCube>(cube, EditorData.AxisAlignedCubes);
}
public void AddCapsule2D()
{
Capsule2D capsule2D = new Capsule2D();
ShapeManager.AddCapsule2D(capsule2D);
capsule2D.Color = EditorProperties.Capsule2DColor;
capsule2D.X = SpriteManager.Camera.X;
capsule2D.Y = SpriteManager.Camera.Y;
EditorData.ShapeCollection.Capsule2Ds.Add(capsule2D);
capsule2D.Name = "Capsule" + EditorData.Capsule2Ds.Count;
StringFunctions.MakeNameUnique<Capsule2D>(capsule2D, EditorData.Capsule2Ds);
}
public void AddAxisAlignedRectangle()
{
AxisAlignedRectangle rectangle = new AxisAlignedRectangle();
ShapeManager.AddAxisAlignedRectangle(rectangle);
rectangle.Color = EditorProperties.AxisAlignedRectangleColor;
rectangle.X = SpriteManager.Camera.X;
rectangle.Y = SpriteManager.Camera.Y;
float scale = (float)Math.Abs(
18 / SpriteManager.Camera.PixelsPerUnitAt(0));
rectangle.ScaleX = scale;
rectangle.ScaleY = scale;
EditorData.ShapeCollection.AxisAlignedRectangles.Add(rectangle);
rectangle.Name = "AxisAlignedRectangle" + EditorData.AxisAlignedRectangles.Count;
StringFunctions.MakeNameUnique<AxisAlignedRectangle>(rectangle, EditorData.AxisAlignedRectangles);
}
public void AddCircle()
{
Circle circle = new Circle();
ShapeManager.AddCircle(circle);
circle.Color = EditorProperties.CircleColor;
circle.X = SpriteManager.Camera.X;
circle.Y = SpriteManager.Camera.Y;
float scale = (float)Math.Abs(
18 / SpriteManager.Camera.PixelsPerUnitAt(0));
circle.Radius = scale;
EditorData.ShapeCollection.Circles.Add(circle);
circle.Name = "Circle" + EditorData.Circles.Count;
StringFunctions.MakeNameUnique<Circle>(circle, EditorData.Circles);
}
public void AddSphere()
{
Sphere sphere = new Sphere();
ShapeManager.AddSphere(sphere);
sphere.Color = EditorProperties.SphereColor;
sphere.X = SpriteManager.Camera.X;
sphere.Y = SpriteManager.Camera.Y;
float scale = (float)Math.Abs(
18 / SpriteManager.Camera.PixelsPerUnitAt(0));
sphere.Radius = scale;
EditorData.ShapeCollection.Spheres.Add(sphere);
sphere.Name = "Sphere" + EditorData.Spheres.Count;
StringFunctions.MakeNameUnique<Sphere>(sphere, EditorData.Spheres);
}
public void CopyCurrentAxisAlignedCubes()
{
foreach (AxisAlignedCube cube in CurrentShapeCollection.AxisAlignedCubes)
{
AxisAlignedCube newCube = cube.Clone<AxisAlignedCube>();
ShapeManager.AddAxisAlignedCube(newCube);
EditorData.ShapeCollection.AxisAlignedCubes.Add(newCube);
FlatRedBall.Utilities.StringFunctions.MakeNameUnique<AxisAlignedCube>(newCube, EditorData.AxisAlignedCubes);
}
}
public void CopyCurrentAxisAlignedRectangles()
{
foreach (AxisAlignedRectangle rectangle in CurrentShapeCollection.AxisAlignedRectangles)
{
AxisAlignedRectangle newRectangle = rectangle.Clone<AxisAlignedRectangle>();
ShapeManager.AddAxisAlignedRectangle(newRectangle);
EditorData.ShapeCollection.AxisAlignedRectangles.Add(newRectangle);
FlatRedBall.Utilities.StringFunctions.MakeNameUnique<AxisAlignedRectangle>(newRectangle, EditorData.AxisAlignedRectangles);
}
}
public void CopyCurrentPolygons()
{
foreach (Polygon polygon in CurrentShapeCollection.Polygons)
{
Polygon newPolygon = polygon.Clone<Polygon>();
ShapeManager.AddPolygon(newPolygon);
EditorData.ShapeCollection.Polygons.Add(newPolygon);
FlatRedBall.Utilities.StringFunctions.MakeNameUnique<Polygon>(newPolygon, EditorData.Polygons);
}
}
public void CopyCurrentCircles()
{
foreach (Circle circle in CurrentShapeCollection.Circles)
{
Circle newCircle = circle.Clone<Circle>();
ShapeManager.AddCircle(newCircle);
EditorData.ShapeCollection.Circles.Add(newCircle);
StringFunctions.MakeNameUnique<Circle>(newCircle, EditorData.Circles);
}
}
public void CopyCurrentSpheres()
{
foreach (Sphere sphere in CurrentShapeCollection.Spheres)
{
Sphere newSphere = sphere.Clone<Sphere>();
ShapeManager.AddSphere(newSphere);
EditorData.ShapeCollection.Spheres.Add(newSphere);
StringFunctions.MakeNameUnique<Sphere>(newSphere, EditorData.Spheres);
}
}
public void SelectAxisAlignedCube(AxisAlignedCube axisAlignedCube)
{
CurrentShapeCollection.AxisAlignedCubes.Clear();
GuiData.ShapeCollectionPropertyGrid.CurrentAxisAlignedCube = axisAlignedCube;
if (axisAlignedCube != null)
{
bool isNewWindow;
PropertyGrid propertyGrid = (PropertyGrid)GuiManager.ObjectDisplayManager.GetObjectDisplayerForObject(axisAlignedCube, GuiData.ShapeCollectionPropertyGrid, null, out isNewWindow);
if (isNewWindow)
{
propertyGrid.SetMemberChangeEvent("Name", GuiData.MakeAxisAlignedCubeNameUnique);
}
CurrentShapeCollection.AxisAlignedCubes.Add(axisAlignedCube);
SelectPolygon(null);
SelectCircle(null);
SelectAxisAlignedRectangle(null);
SelectSphere(null);
}
}
public void SelectAxisAlignedRectangle(AxisAlignedRectangle axisAlignedRectangle)
{
CurrentShapeCollection.AxisAlignedRectangles.Clear();
GuiData.ShapeCollectionPropertyGrid.CurrentAxisAlignedRectangle = axisAlignedRectangle;
if (axisAlignedRectangle != null)
{
bool isNewWindow;
PropertyGrid propertyGrid = (PropertyGrid)GuiManager.ObjectDisplayManager.GetObjectDisplayerForObject(axisAlignedRectangle, GuiData.ShapeCollectionPropertyGrid, null, out isNewWindow);
if (isNewWindow)
{
propertyGrid.SetMemberChangeEvent("Name", GuiData.MakeAxisAlignedRectangleNameUnique);
}
CurrentShapeCollection.AxisAlignedRectangles.Add(axisAlignedRectangle);
SelectPolygon(null);
SelectCircle(null);
SelectAxisAlignedCube(null);
SelectSphere(null);
}
}
public void SelectCircle(Circle circle)
{
CurrentShapeCollection.Circles.Clear();
GuiData.ShapeCollectionPropertyGrid.CurrentCircle = circle;
if (circle != null)
{
bool isNewWindow;
PropertyGrid propertyGrid = (PropertyGrid)GuiManager.ObjectDisplayManager.GetObjectDisplayerForObject(circle, GuiData.ShapeCollectionPropertyGrid, null, out isNewWindow);
if (isNewWindow)
{
propertyGrid.SetMemberChangeEvent("Name", GuiData.MakeCircleNameUnique);
}
CurrentShapeCollection.Circles.Add(circle);
SelectPolygon(null);
SelectAxisAlignedRectangle(null);
SelectAxisAlignedCube(null);
SelectSphere(null);
}
}
public void SelectSphere(Sphere sphere)
{
CurrentShapeCollection.Spheres.Clear();
GuiData.ShapeCollectionPropertyGrid.CurrentSphere = sphere;
if (sphere != null)
{
bool isNewWindow;
PropertyGrid propertyGrid = (PropertyGrid)GuiManager.ObjectDisplayManager.GetObjectDisplayerForObject(sphere, GuiData.ShapeCollectionPropertyGrid, null, out isNewWindow);
if (isNewWindow)
{
propertyGrid.SetMemberChangeEvent("Name", GuiData.MakeSphereNameUnique);
}
CurrentShapeCollection.Spheres.Add(sphere);
SelectPolygon(null);
SelectAxisAlignedRectangle(null);
SelectAxisAlignedCube(null);
SelectCircle(null);
}
}
public void SelectPolygon(Polygon polygon)
{
CurrentShapeCollection.Polygons.Clear();
GuiData.ShapeCollectionPropertyGrid.CurrentPolygon = polygon;
if (polygon != null)
{
bool isNewWindow;
PropertyGrid propertyGrid = (PropertyGrid)GuiManager.ObjectDisplayManager.GetObjectDisplayerForObject(polygon, GuiData.ShapeCollectionPropertyGrid, null, out isNewWindow);
if (isNewWindow)
{
propertyGrid.SetMemberChangeEvent("Name", GuiData.MakePolygonNameUnique);
}
CurrentShapeCollection.Polygons.Add(polygon);
SelectAxisAlignedRectangle(null);
SelectCircle(null);
SelectAxisAlignedCube(null);
SelectSphere(null);
}
}
public void SelectPolygonCorner(int index)
{
mReactiveHud.CornerIndexSelected = index;
}
public void Update()
{
mReactiveHud.Activity();
UpdateEditingState();
UpdateBasedOnEditingState();
PerformKeyboardShortcuts();
UndoManager.EndOfFrameActivity();
mNodeNetworkEditorManager.Activity();
}
#endregion
#region Private Methods
private void AddingPointsUpdate()
{
Cursor cursor = GuiManager.Cursor;
if (cursor.WindowOver == null)
{
Polygon polygon = CurrentShapeCollection.Polygons[0];
#region If cursor clicked, add new point
if (cursor.PrimaryClick)
{
Matrix inverseRotation = polygon.RotationMatrix;
#if FRB_MDX
inverseRotation.Invert();
#else
Matrix.Invert(ref inverseRotation, out inverseRotation);
#endif
Point newPoint = new Point(
mReactiveHud.NewPointPolygon.Position.X - polygon.Position.X,
mReactiveHud.NewPointPolygon.Position.Y - polygon.Position.Y);
FlatRedBall.Math.MathFunctions.TransformPoint(ref newPoint, ref inverseRotation);
// adding new point
polygon.Insert( mReactiveHud.IndexBeforeNewPoint + 1, newPoint);
}
#endregion
}
}
private void AddingPointsOnEndUpdate()
{
Cursor cursor = GuiManager.Cursor;
if(cursor.PrimaryClick)
{
if (CurrentShapeCollection.Polygons.Count == 0)
{
Polygon polygon = AddRectanglePolygon();
SelectPolygon(polygon);
Point[] newPoints = new Point[1];
newPoints[0].X = cursor.WorldXAt(0) - polygon.X;
newPoints[0].Y = cursor.WorldYAt(0) - polygon.Y;
polygon.Points = newPoints;
}
else
{
Polygon currentPolygon = CurrentShapeCollection.Polygons[0];
Point[] newPoints = new Point[currentPolygon.Points.Count + 1];
for (int i = 0; i < currentPolygon.Points.Count; i++)
{
newPoints[i] = currentPolygon.Points[i];
}
newPoints[currentPolygon.Points.Count].X = cursor.WorldXAt(0) -
currentPolygon.X;
newPoints[currentPolygon.Points.Count].Y = cursor.WorldYAt(0) -
currentPolygon.Y;
currentPolygon.Points = newPoints;
}
}
}
#region XML Docs
/// <summary>
/// Controls selecting new Shapes and performing move, scale, and rotate (when appropriate).
/// </summary>
#endregion
private void CursorControlOverShapes()
{
if (GuiManager.DominantWindowActive)
return;
Cursor cursor = GuiManager.Cursor;
#region Pushing selects and grabs a Shape or the corner of a Polygon
if (cursor.PrimaryPush)
{
#region If the user has not interacted with the corners then see check for grabbing any Shapes
if (mReactiveHud.HasPolygonEdgeGrabbed == false)
{
mObjectGrabbed = GetShapeOver(cursor.PrimaryDoublePush);
ShowErrorIfObjectCanNotBeGrabbed();
// If the object is not null store its original position. This will be used
// for SHIFT+drag which allows movement only on one axis.
if (mObjectGrabbed != null)
{
PositionedObjectMover.SetStartPosition(mObjectGrabbed);
}
cursor.SetObjectRelativePosition(mObjectGrabbed);
if (PolygonGrabbed != null)
{
UndoManager.AddToWatch(PolygonGrabbed);
SelectPolygon(PolygonGrabbed);
}
if (AxisAlignedCubeGrabbed != null)
{
UndoManager.AddToWatch(AxisAlignedCubeGrabbed);
SelectAxisAlignedCube(AxisAlignedCubeGrabbed);
}
if (AxisAlignedRectangleGrabbed != null)
{
UndoManager.AddToWatch(AxisAlignedRectangleGrabbed);
SelectAxisAlignedRectangle(AxisAlignedRectangleGrabbed);
}
if (CircleGrabbed != null)
{
UndoManager.AddToWatch(CircleGrabbed);
SelectCircle(CircleGrabbed);
}
if (SphereGrabbed != null)
{
UndoManager.AddToWatch(SphereGrabbed);
SelectSphere(SphereGrabbed);
}
if (mObjectGrabbed == null)
{
DeselectAll();
}
}
#endregion
}
#endregion
#region Holding the button down can be used to drag objects
if (cursor.PrimaryDown)
{
PerformDraggingUpdate();
}
#endregion
#region Clicking (releasing) the mouse lets go of grabbed Polygons
if (cursor.PrimaryClick)
{
if (PolygonGrabbed != null)
{
UndoManager.RecordUndos<Polygon>();
UndoManager.ClearObjectsWatching<Polygon>();
}
if (AxisAlignedRectangleGrabbed != null)
{
UndoManager.RecordUndos<AxisAlignedRectangle>();
UndoManager.ClearObjectsWatching<AxisAlignedRectangle>();
}
if (AxisAlignedCubeGrabbed != null)
{
UndoManager.RecordUndos<AxisAlignedCube>();
UndoManager.ClearObjectsWatching<AxisAlignedCube>();
}
if (CircleGrabbed != null)
{
UndoManager.RecordUndos<Circle>();
UndoManager.ClearObjectsWatching<Circle>();
}
if (SphereGrabbed != null)
{
UndoManager.RecordUndos<Sphere>();
UndoManager.ClearObjectsWatching<Sphere>();
}
mObjectGrabbed = null;
cursor.StaticPosition = false;
cursor.ObjectGrabbed = null;
}
#endregion
}
private void DeleteCurrentAxisAlignedRectangles()
{
while (CurrentShapeCollection.AxisAlignedRectangles.Count != 0)
{
ShapeManager.Remove(CurrentShapeCollection.AxisAlignedRectangles[0]);
}
}
private void DeleteCurrentAxisAlignedCubes()
{
while (CurrentShapeCollection.AxisAlignedCubes.Count != 0)
{
ShapeManager.Remove(CurrentShapeCollection.AxisAlignedCubes[0]);
}
}
private void DeleteCurrentCircles()
{
while (CurrentShapeCollection.Circles.Count != 0)
{
ShapeManager.Remove(CurrentShapeCollection.Circles[0]);
}
}
private void DeleteCurrentSpheres()
{
while (CurrentShapeCollection.Spheres.Count != 0)
{
ShapeManager.Remove(CurrentShapeCollection.Spheres[0]);
}
}
private void DeleteCurrentPolygons()
{
while (CurrentShapeCollection.Polygons.Count != 0)
{
ShapeManager.Remove(CurrentShapeCollection.Polygons[0]);
}
}
private void DeleteKeyPressed()
{
if (mReactiveHud.CornerIndexSelected == -1)
{
DeleteCurrentPolygons();
DeleteCurrentAxisAlignedRectangles();
DeleteCurrentCircles();
DeleteCurrentAxisAlignedCubes();
DeleteCurrentSpheres();
}
else
{
DeleteSelectedCorner();
}
}
private void DeleteSelectedCorner()
{
if (CurrentShapeCollection.Polygons[0].Points.Count > 4) // 3 points (triangle) are the minimum + 1 for repeated last point.
{
// First, get the points of the polygon. The deleted point will be removed from this
List<Point> pointList = new List<Point>(CurrentShapeCollection.Polygons[0].Points);
// Remove the point
pointList.RemoveAt(mReactiveHud.CornerIndexSelected);
if (mReactiveHud.CornerIndexSelected == 0)
{
// removed corner index 0
pointList[pointList.Count - 1] = pointList[0];
}
else if (mReactiveHud.CornerIndexSelected == pointList.Count)
{
pointList[0] = pointList[pointList.Count - 1];
}
// Since a point has been deleted, make the mCornerIndexSelected = -1
mReactiveHud.CornerIndexSelected = -1;
CurrentShapeCollection.Polygons[0].Points = pointList;
}
else
{
GuiManager.ShowMessageBox("Polygon cannot have fewer than 3 points.", "Error Deleting Point");
}
}
private PositionedObject GetShapeOver(bool skipCurrent)
{
PositionedObject positionedObject = null;
#region See if we're over any current objects
if (!skipCurrent)
{
positionedObject = GetCurrentPolygonOver();
if (positionedObject == null)
{
positionedObject = GetCurrentAxisAlignedRectangleOver();
}
if (positionedObject == null)
{
positionedObject = GetCurrentCircleOver();
}
if (positionedObject == null)
{
positionedObject = GetCurrentAxisAlignedCubeOver();
}
if (positionedObject == null)
{
positionedObject = GetCurrentSphereOver();
}
}
#endregion
#region We're not over any current shape, so see if we're over any shape that isn't selected
if (positionedObject == null && GuiData.GeometryWindow.EditingPolygons)
{
positionedObject = GetAllPolygonOver(skipCurrent);
}
if (positionedObject == null && GuiData.GeometryWindow.EditingAxisAlignedRectangles)
{
positionedObject = GetAllAxisAlignedRectangleOver(skipCurrent);
}
if (positionedObject == null && GuiData.GeometryWindow.EditingCircles)
{
positionedObject = GetAllCircleOver(skipCurrent);
}
if (positionedObject == null && GuiData.GeometryWindow.EditingAxisAlignedCubes)
{
positionedObject = GetAllAxisAlignedCubeOver(skipCurrent);
}
if (positionedObject == null && GuiData.GeometryWindow.EditingSpheres)
{
positionedObject = GetAllSphereOver(skipCurrent);
}
#endregion
return positionedObject;
}
private AxisAlignedCube GetAllAxisAlignedCubeOver(bool skipCurrent)
{
Cursor cursor = GuiManager.Cursor;
foreach (AxisAlignedCube axisAlignedCube in EditorData.AxisAlignedCubes)
{
if (cursor.IsOn3D(axisAlignedCube))
{
if (!skipCurrent || CurrentShapeCollection.AxisAlignedCubes.Contains(axisAlignedCube) == false)
{
return axisAlignedCube;
}
}
}
return null;
}
private AxisAlignedRectangle GetAllAxisAlignedRectangleOver(bool skipCurrent)
{
Cursor cursor = GuiManager.Cursor;
foreach (AxisAlignedRectangle axisAlignedRectangle in EditorData.AxisAlignedRectangles)
{
if (cursor.IsOn(axisAlignedRectangle))
{
if (!skipCurrent || CurrentShapeCollection.AxisAlignedRectangles.Contains(axisAlignedRectangle) == false)
{
return axisAlignedRectangle;
}
}
}
return null;
}
private Circle GetAllCircleOver(bool skipCurrent)
{
Cursor cursor = GuiManager.Cursor;
foreach (Circle circle in EditorData.Circles)
{
if (cursor.IsOn(circle))
{
if (!skipCurrent || CurrentShapeCollection.Circles.Contains(circle) == false)
{
return circle;
}
}
}
return null;
}
private Sphere GetAllSphereOver(bool skipCurrent)
{
Cursor cursor = GuiManager.Cursor;
if (InputManager.Keyboard.KeyPushed(Keys.D))
{
int m = 3;
}
// When fixing, also consider current
for(int i = 0; i < EditorData.Spheres.Count; i++)
{
Sphere sphere = EditorData.Spheres[i];
if (cursor.IsOn3D(sphere))
{
if (!skipCurrent || CurrentShapeCollection.Spheres.Contains(sphere) == false)
{
return sphere;
}
}
}
return null;
}
private Polygon GetAllPolygonOver(bool skipCurrent)
{
Cursor cursor = GuiManager.Cursor;
foreach (Polygon polygon in EditorData.Polygons)
{
if (cursor.IsOn3D(polygon))
{
if (!skipCurrent || CurrentShapeCollection.Polygons.Contains(polygon) == false)
{
return polygon;
}
}
}
return null;
}
private AxisAlignedCube GetCurrentAxisAlignedCubeOver()
{
Cursor cursor = GuiManager.Cursor;
// Return current shapes if over any of them
if (CurrentShapeCollection.AxisAlignedCubes.Count != 0)
{
foreach (AxisAlignedCube axisAlignedCube in CurrentShapeCollection.AxisAlignedCubes)
{
if (cursor.IsOn3D(axisAlignedCube))
{
return axisAlignedCube;
}
}
}
return null;
}
private AxisAlignedRectangle GetCurrentAxisAlignedRectangleOver()
{
Cursor cursor = GuiManager.Cursor;
// Return current shapes if over any of them
if (CurrentShapeCollection.AxisAlignedRectangles.Count != 0)
{
foreach (AxisAlignedRectangle axisAlignedRectangle in CurrentShapeCollection.AxisAlignedRectangles)
{
if (cursor.IsOn(axisAlignedRectangle))
{
return axisAlignedRectangle;
}
}
}
return null;
}
private Circle GetCurrentCircleOver()
{
Cursor cursor = GuiManager.Cursor;
// Return current shapes if over any of them
if (CurrentShapeCollection.Circles.Count != 0)
{
foreach (Circle circle in CurrentShapeCollection.Circles)
{
if (cursor.IsOn(circle))
{
return circle;
}
}
}
return null;
}
private Sphere GetCurrentSphereOver()
{
Cursor cursor = GuiManager.Cursor;
// When fixing, also consider current
for(int i = 0; i < CurrentShapeCollection.Spheres.Count; i++)
{
Sphere sphere = CurrentShapeCollection.Spheres[i];
if (cursor.IsOn3D(sphere))
{
return sphere;
}
}
return null;
}
private Polygon GetCurrentPolygonOver()
{
Cursor cursor = GuiManager.Cursor;
// Return current shapes if over any of them
if (CurrentPolygons.Count != 0)
{
foreach (Polygon polygon in CurrentPolygons)
{
if (cursor.IsOn(polygon))
{
return polygon;
}
}
}
return null;
}
private void PerformDraggingUpdate()
{
Cursor cursor = GuiManager.Cursor;
#region If a Shape is grabbed
if (mReactiveHud.HasPolygonEdgeGrabbed == false && mObjectGrabbed != null)
{
#region If Move button is down
if (GuiData.ToolsWindow.IsMoveButtonPressed)
{
PerformMoveDragging(cursor);
}
#endregion
#region If Rotate Button is down
else if (GuiData.ToolsWindow.IsRotateButtonPressed)
{
PerformRotateDragging(cursor);
}
#endregion
#region If Scale Button is down
else if (GuiData.ToolsWindow.IsScaleButtonPressed)
{
cursor.StaticPosition = true;
foreach (Polygon polygon in CurrentShapeCollection.Polygons)
{
polygon.ScaleBy(1 + cursor.XVelocity / 100.0f, 1 + cursor.YVelocity / 100.0f);
}
foreach (AxisAlignedRectangle rectangle in CurrentShapeCollection.AxisAlignedRectangles)
{
float newScaleX = rectangle.ScaleX * (1 + cursor.XVelocity / 100.0f);
float newScaleY = rectangle.ScaleY * (1 + cursor.YVelocity / 100.0f);
newScaleX = Math.Max(0, newScaleX);
newScaleY = Math.Max(0, newScaleY);
rectangle.ScaleX = newScaleX;
rectangle.ScaleY = newScaleY;
}
foreach (AxisAlignedCube cube in CurrentShapeCollection.AxisAlignedCubes)
{
float newScaleX = cube.ScaleX * (1 + cursor.XVelocity / 100.0f);
float newScaleY = cube.ScaleY * (1 + cursor.YVelocity / 100.0f);
newScaleX = Math.Max(0, newScaleX);
newScaleY = Math.Max(0, newScaleY);
cube.ScaleX = newScaleX;
cube.ScaleY = newScaleY;
}
foreach (Circle circle in CurrentShapeCollection.Circles)
{
float newRadius = circle.Radius * (1 + cursor.YVelocity / 100.0f);
newRadius = Math.Max(0, newRadius);
circle.Radius = newRadius;
}
foreach (Sphere sphere in CurrentShapeCollection.Spheres)
{
float newRadius = sphere.Radius * ( 1 + cursor.YVelocity / 100.0f);
newRadius = Math.Max(0, newRadius);
sphere.Radius = newRadius;
}
}
#endregion
}
#endregion
}
private void PerformMoveDragging(Cursor cursor)
{
PositionedObjectMover.MouseMoveObject(mObjectGrabbed);
}
private void PerformRotateDragging(Cursor cursor)
{
if (mObjectGrabbed is Circle || mObjectGrabbed is AxisAlignedRectangle ||
mObjectGrabbed is AxisAlignedCube || mObjectGrabbed is Sphere)
{
return;// GuiManager.ShowMessageBox("This shape cannot be rotated", "Error rotating");
}
PositionedObjectRotator.MouseRotateObject(mObjectGrabbed, MovementStyle.Hierarchy);
}
private void PerformKeyboardShortcuts()
{
#region Control the Camera with the Keyboard
EditorObjects.CameraMethods.KeyboardCameraControl(SpriteManager.Camera);
#endregion
GuiData.ToolsWindow.ListenForShortcuts();
GuiData.GeometryWindow.ListenForShortcuts();
#region Delete Key - delete current Shapes
if (InputManager.Keyboard.KeyPushedConsideringInputReceiver(Keys.Delete))
{
DeleteKeyPressed();
// Since all current objects are gone the PropertyGrids should disappear
// Update on 7/28/2010:
// I don't think it's a good
// idea to make this thing disappear.
// Why do we want to do this? It's annoying!
// GuiData.ShapeCollectionPropertyGrid.Visible = false;
}
#endregion
#region CTRL + C - copy current Polygons
if (InputManager.ReceivingInput == null && InputManager.Keyboard.ControlCPushed())
{
CopyCurrentPolygons();
CopyCurrentAxisAlignedRectangles();
CopyCurrentAxisAlignedCubes();
CopyCurrentCircles();
CopyCurrentSpheres();
}
#endregion
#region T key - makes the current point a right-angle
if (InputManager.ReceivingInput == null && InputManager.Keyboard.KeyDown(Keys.T) && mReactiveHud.CornerIndexSelected != -1 )
{
MakeCurrentPointRightAngle();
}
#endregion
}
private void MakeCurrentPointRightAngle()
{
Polygon currentPolygon = CurrentPolygons[0];
int indexBefore = mReactiveHud.CornerIndexSelected - 1;
if (indexBefore < 0)
{
indexBefore = CurrentPolygons[0].Points.Count - 2;
}
int indexAfter = (mReactiveHud.CornerIndexSelected + 1) % (CurrentPolygons[0].Points.Count - 1);
int m = 3;
Point grabbedPoint = currentPolygon.Points[mReactiveHud.CornerIndexSelected];
Point pointBefore = currentPolygon.Points[indexBefore];
Point pointAfter = currentPolygon.Points[indexAfter];
Point toBefore = pointBefore - grabbedPoint;
Point toAfter = pointAfter - grabbedPoint;
toBefore.Normalize();
toAfter.Normalize();
double xToSet = 0;
double yToSet = 0;
if (Math.Abs(toBefore.X) < Math.Abs(toAfter.X))
{
xToSet = pointBefore.X;
yToSet = pointAfter.Y;
}
else
{
xToSet = pointAfter.X;
yToSet = pointBefore.Y;
}
grabbedPoint.X = xToSet;
grabbedPoint.Y = yToSet;
currentPolygon.SetPoint(mReactiveHud.CornerIndexSelected, grabbedPoint);
if (mReactiveHud.CornerIndexSelected == 0)
{
currentPolygon.SetPoint(currentPolygon.Points.Count - 1, grabbedPoint);
}
}
internal void DeselectAll()
{
SelectAxisAlignedCube(null);
SelectAxisAlignedRectangle(null);
SelectCircle(null);
SelectSphere(null);
SelectPolygon(null);
}
private void ShowErrorIfObjectCanNotBeGrabbed()
{
if (GuiData.ToolsWindow.IsRotateButtonPressed)
{
if (mObjectGrabbed is Circle || mObjectGrabbed is AxisAlignedRectangle ||
mObjectGrabbed is AxisAlignedCube || mObjectGrabbed is Sphere)
{
GuiManager.ShowMessageBox("This shape cannot be rotated", "Error rotating");
mObjectGrabbed = null;
}
}
}
private void UpdateBasedOnEditingState()
{
//Moved from Update
// Don't do any logic if the cursor is over a window
Cursor cursor = GuiManager.Cursor;
if (cursor.WindowOver == null)
{
switch (mEditingState)
{
#region Case AddingPointsOnEnd
case EditingState.AddingPointsOnEnd:
AddingPointsOnEndUpdate();
break;
#endregion
#region Case AddingPoints
case EditingState.AddingPoints:
AddingPointsUpdate();
break;
#endregion
#region Case None
case EditingState.None:
CursorControlOverShapes();
break;
#endregion
}
}
// It is possible that the user clicked on an object to scale it, then a
// Window appeared on top of it. This put the cursor in a perment static
// state. Fix this:
if (cursor.PrimaryClick)
{
cursor.StaticPosition = false;
}
}
private void UpdateEditingState()
{
EditingState oldState = mEditingState;
if (GuiData.ToolsWindow.IsAddPointButtonPressed)
{
mEditingState = EditingState.AddingPoints;
}
else if (GuiData.ToolsWindow.IsDrawingPolygonButtonPressed)
{
EditingState = EditingState.AddingPointsOnEnd;
if (EditingState != oldState)
{
SelectPolygon(null);
}
}
else
{
mEditingState = EditingState.None;
}
#region If the user was adding point on end, then stopped, finish up by setting the last point and optimizing the radius
if (oldState == EditingState.AddingPointsOnEnd &&
oldState != mEditingState)
{
if (CurrentShapeCollection.Polygons.Count == 0)
{
// the user never started the polygon, so exit
}
else
{
// Finish up the polygon
Polygon currentPolygon = CurrentShapeCollection.Polygons[0];
currentPolygon.Insert(currentPolygon.Points.Count, currentPolygon.Points[0]);
currentPolygon.OptimizeRadius();
}
}
#endregion
}
#endregion
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Globalization;
namespace System.Net.WebSockets
{
internal class WinHttpWebSocket : WebSocket
{
#region Constants
// TODO: This code needs to be shared with WinHttpClientHandler
private const string HeaderNameCookie = "Cookie";
private const string HeaderNameWebSocketProtocol = "Sec-WebSocket-Protocol";
#endregion
// TODO (Issue 2503): move System.Net.* strings to resources as appropriate.
// NOTE: All WinHTTP operations must be called while holding the _operation.Lock.
// It is critical that no handle gets closed while a WinHTTP function is running.
private WebSocketCloseStatus? _closeStatus = null;
private string _closeStatusDescription = null;
private string _subProtocol = null;
private bool _disposed = false;
private WinHttpWebSocketState _operation = new WinHttpWebSocketState();
// TODO (Issue 2505): temporary pinned buffer caches of 1 item. Will be replaced by PinnableBufferCache.
private GCHandle _cachedSendPinnedBuffer;
private GCHandle _cachedReceivePinnedBuffer;
public WinHttpWebSocket()
{
}
#region Properties
public override WebSocketCloseStatus? CloseStatus
{
get
{
return _closeStatus;
}
}
public override string CloseStatusDescription
{
get
{
return _closeStatusDescription;
}
}
public override WebSocketState State
{
get
{
return _operation.State;
}
}
public override string SubProtocol
{
get
{
return _subProtocol;
}
}
#endregion
readonly static WebSocketState[] s_validConnectStates = { WebSocketState.None };
readonly static WebSocketState[] s_validConnectingStates = { WebSocketState.Connecting };
public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.Connecting, s_validConnectStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validConnectingStates);
// Must grab lock until RequestHandle is populated, otherwise we risk resource leaks on Abort.
//
// TODO (Issue 2506): Alternatively, release the lock between WinHTTP operations and check, under lock, that the
// state is still valid to continue operation.
_operation.SessionHandle = InitializeWinHttp(options);
_operation.ConnectionHandle = Interop.WinHttp.WinHttpConnectWithCallback(
_operation.SessionHandle,
uri.IdnHost,
(ushort)uri.Port,
0);
ThrowOnInvalidHandle(_operation.ConnectionHandle);
bool secureConnection = uri.Scheme == UriScheme.Https || uri.Scheme == UriScheme.Wss;
_operation.RequestHandle = Interop.WinHttp.WinHttpOpenRequestWithCallback(
_operation.ConnectionHandle,
"GET",
uri.PathAndQuery,
null,
Interop.WinHttp.WINHTTP_NO_REFERER,
null,
secureConnection ? Interop.WinHttp.WINHTTP_FLAG_SECURE : 0);
ThrowOnInvalidHandle(_operation.RequestHandle);
_operation.IncrementHandlesOpenWithCallback();
if (!Interop.WinHttp.WinHttpSetOption(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET,
IntPtr.Zero,
0))
{
WinHttpException.ThrowExceptionUsingLastError();
}
// We need the address of the IntPtr to the GCHandle.
IntPtr context = _operation.ToIntPtr();
IntPtr contextAddress;
unsafe
{
contextAddress = (IntPtr)(void*)&context;
}
if (!Interop.WinHttp.WinHttpSetOption(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_CONTEXT_VALUE,
contextAddress,
(uint)IntPtr.Size))
{
WinHttpException.ThrowExceptionUsingLastError();
}
if (Interop.WinHttp.WinHttpSetStatusCallback(
_operation.RequestHandle,
WinHttpWebSocketCallback.s_StaticCallbackDelegate,
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS,
IntPtr.Zero) == (IntPtr)Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK)
{
WinHttpException.ThrowExceptionUsingLastError();
}
_operation.RequestHandle.AttachCallback();
// We need to pin the operation object at this point in time since the WinHTTP callback
// has been fully wired to the request handle and the operation object has been set as
// the context value of the callback. Any notifications from activity on the handle will
// result in the callback being called with the context value.
_operation.Pin();
AddRequestHeaders(uri, options);
_operation.TcsUpgrade = new TaskCompletionSource<bool>();
}
await InternalSendWsUpgradeRequestAsync().ConfigureAwait(false);
await InternalReceiveWsUpgradeResponse().ConfigureAwait(false);
lock (_operation.Lock)
{
VerifyUpgradeResponse();
ThrowOnInvalidConnectState();
_operation.WebSocketHandle =
Interop.WinHttp.WinHttpWebSocketCompleteUpgrade(_operation.RequestHandle, IntPtr.Zero);
ThrowOnInvalidHandle(_operation.WebSocketHandle);
_operation.IncrementHandlesOpenWithCallback();
// We need the address of the IntPtr to the GCHandle.
IntPtr context = _operation.ToIntPtr();
IntPtr contextAddress;
unsafe
{
contextAddress = (IntPtr)(void*)&context;
}
if (!Interop.WinHttp.WinHttpSetOption(
_operation.WebSocketHandle,
Interop.WinHttp.WINHTTP_OPTION_CONTEXT_VALUE,
contextAddress,
(uint)IntPtr.Size))
{
WinHttpException.ThrowExceptionUsingLastError();
}
_operation.WebSocketHandle.AttachCallback();
_operation.UpdateState(WebSocketState.Open);
if (_operation.RequestHandle != null)
{
_operation.RequestHandle.Dispose();
// RequestHandle will be set to null in the callback.
}
_operation.TcsUpgrade = null;
ctr.Dispose();
}
}
}
// Requires lock taken.
private Interop.WinHttp.SafeWinHttpHandle InitializeWinHttp(ClientWebSocketOptions options)
{
Interop.WinHttp.SafeWinHttpHandle sessionHandle;
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
null,
null,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(sessionHandle);
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)Marshal.SizeOf<uint>()))
{
WinHttpException.ThrowExceptionUsingLastError();
}
return sessionHandle;
}
private Task<bool> InternalSendWsUpgradeRequestAsync()
{
lock (_operation.Lock)
{
ThrowOnInvalidConnectState();
if (!Interop.WinHttp.WinHttpSendRequest(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_NO_ADDITIONAL_HEADERS,
0,
IntPtr.Zero,
0,
0,
_operation.ToIntPtr()))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return _operation.TcsUpgrade.Task;
}
private Task<bool> InternalReceiveWsUpgradeResponse()
{
// TODO (Issue 2507): Potential optimization: move this in WinHttpWebSocketCallback.
lock (_operation.Lock)
{
ThrowOnInvalidConnectState();
_operation.TcsUpgrade = new TaskCompletionSource<bool>();
if (!Interop.WinHttp.WinHttpReceiveResponse(_operation.RequestHandle, IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return _operation.TcsUpgrade.Task;
}
private void ThrowOnInvalidConnectState()
{
// A special behavior for WebSocket upgrade: throws ConnectFailure instead of other Abort messages.
if (_operation.State != WebSocketState.Connecting)
{
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
}
private readonly static WebSocketState[] s_validSendStates = { WebSocketState.Open, WebSocketState.CloseReceived };
public override Task SendAsync(
ArraySegment<byte> buffer,
WebSocketMessageType messageType,
bool endOfMessage,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckValidStates(s_validSendStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
var bufferType = WebSocketMessageTypeAdapter.GetWinHttpMessageType(messageType, endOfMessage);
// TODO (Issue 2505): replace with PinnableBufferCache.
if (!_cachedSendPinnedBuffer.IsAllocated || _cachedSendPinnedBuffer.Target != buffer.Array)
{
if (_cachedSendPinnedBuffer.IsAllocated)
{
_cachedSendPinnedBuffer.Free();
}
_cachedSendPinnedBuffer = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
}
bool sendOperationAlreadyPending = false;
if (_operation.PendingWriteOperation == false)
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validSendStates);
if (_operation.PendingWriteOperation == false)
{
_operation.PendingWriteOperation = true;
_operation.TcsSend = new TaskCompletionSource<bool>();
uint ret = Interop.WinHttp.WinHttpWebSocketSend(
_operation.WebSocketHandle,
bufferType,
buffer.Count > 0 ? Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset) : IntPtr.Zero,
(uint)buffer.Count);
if (Interop.WinHttp.ERROR_SUCCESS != ret)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
else
{
sendOperationAlreadyPending = true;
}
}
}
else
{
sendOperationAlreadyPending = true;
}
if (sendOperationAlreadyPending)
{
var exception = new InvalidOperationException(
SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "SendAsync"));
_operation.TcsSend.TrySetException(exception);
Abort();
}
return _operation.TcsSend.Task;
}
}
private readonly static WebSocketState[] s_validReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent };
private readonly static WebSocketState[] s_validAfterReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent, WebSocketState.CloseReceived };
public override async Task<WebSocketReceiveResult> ReceiveAsync(
ArraySegment<byte> buffer,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckValidStates(s_validReceiveStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
// TODO (Issue 2505): replace with PinnableBufferCache.
if (!_cachedReceivePinnedBuffer.IsAllocated || _cachedReceivePinnedBuffer.Target != buffer.Array)
{
if (_cachedReceivePinnedBuffer.IsAllocated)
{
_cachedReceivePinnedBuffer.Free();
}
_cachedReceivePinnedBuffer = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
}
await InternalReceiveAsync(buffer).ConfigureAwait(false);
// Check for abort.
_operation.InterlockedCheckValidStates(s_validAfterReceiveStates);
WebSocketMessageType bufferType;
bool endOfMessage;
bufferType = WebSocketMessageTypeAdapter.GetWebSocketMessageType(_operation.BufferType, out endOfMessage);
int bytesTransferred = 0;
checked
{
bytesTransferred = (int)_operation.BytesTransferred;
}
WebSocketReceiveResult ret;
if (bufferType == WebSocketMessageType.Close)
{
UpdateServerCloseStatus();
ret = new WebSocketReceiveResult(bytesTransferred, bufferType, endOfMessage, _closeStatus, _closeStatusDescription);
}
else
{
ret = new WebSocketReceiveResult(bytesTransferred, bufferType, endOfMessage);
}
return ret;
}
}
private Task<bool> InternalReceiveAsync(ArraySegment<byte> buffer)
{
bool receiveOperationAlreadyPending = false;
if (_operation.PendingReadOperation == false)
{
lock (_operation.Lock)
{
if (_operation.PendingReadOperation == false)
{
_operation.CheckValidState(s_validReceiveStates);
_operation.TcsReceive = new TaskCompletionSource<bool>();
_operation.PendingReadOperation = true;
uint bytesRead = 0;
Interop.WinHttp.WINHTTP_WEB_SOCKET_BUFFER_TYPE winHttpBufferType = 0;
uint status = Interop.WinHttp.WinHttpWebSocketReceive(
_operation.WebSocketHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset),
(uint)buffer.Count,
out bytesRead, // Unused in async mode: ignore.
out winHttpBufferType); // Unused in async mode: ignore.
if (Interop.WinHttp.ERROR_SUCCESS != status)
{
throw WinHttpException.CreateExceptionUsingError((int)status);
}
}
else
{
receiveOperationAlreadyPending = true;
}
}
}
else
{
receiveOperationAlreadyPending = true;
}
if (receiveOperationAlreadyPending)
{
var exception = new InvalidOperationException(
SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "ReceiveAsync"));
_operation.TcsReceive.TrySetException(exception);
Abort();
}
return _operation.TcsReceive.Task;
}
private static readonly WebSocketState[] s_validCloseStates = { WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent };
public override async Task CloseAsync(
WebSocketCloseStatus closeStatus,
string statusDescription,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.CloseSent, s_validCloseStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
_operation.TcsClose = new TaskCompletionSource<bool>();
await InternalCloseAsync(closeStatus, statusDescription).ConfigureAwait(false);
UpdateServerCloseStatus();
}
}
private Task<bool> InternalCloseAsync(WebSocketCloseStatus closeStatus, string statusDescription)
{
uint ret;
_operation.TcsClose = new TaskCompletionSource<bool>();
lock (_operation.Lock)
{
_operation.CheckValidState(s_validCloseStates);
if (!string.IsNullOrEmpty(statusDescription))
{
byte[] statusDescriptionBuffer = Encoding.UTF8.GetBytes(statusDescription);
ret = Interop.WinHttp.WinHttpWebSocketClose(
_operation.WebSocketHandle,
(ushort)closeStatus,
statusDescriptionBuffer,
(uint)statusDescriptionBuffer.Length);
}
else
{
ret = Interop.WinHttp.WinHttpWebSocketClose(
_operation.WebSocketHandle,
(ushort)closeStatus,
IntPtr.Zero,
0);
}
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
return _operation.TcsClose.Task;
}
private void UpdateServerCloseStatus()
{
uint ret;
ushort serverStatus;
var closeDescription = new byte[WebSocketValidate.MaxControlFramePayloadLength];
uint closeDescriptionConsumed;
lock (_operation.Lock)
{
ret = Interop.WinHttp.WinHttpWebSocketQueryCloseStatus(
_operation.WebSocketHandle,
out serverStatus,
closeDescription,
(uint)closeDescription.Length,
out closeDescriptionConsumed);
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
_closeStatus = (WebSocketCloseStatus)serverStatus;
_closeStatusDescription = Encoding.UTF8.GetString(closeDescription, 0, (int)closeDescriptionConsumed);
}
}
private readonly static WebSocketState[] s_validCloseOutputStates = { WebSocketState.Open, WebSocketState.CloseReceived };
private readonly static WebSocketState[] s_validCloseOutputStatesAfterUpdate = { WebSocketState.CloseReceived, WebSocketState.CloseSent };
public override Task CloseOutputAsync(
WebSocketCloseStatus closeStatus,
string statusDescription,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.CloseSent, s_validCloseOutputStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validCloseOutputStatesAfterUpdate);
uint ret;
_operation.TcsCloseOutput = new TaskCompletionSource<bool>();
if (!string.IsNullOrEmpty(statusDescription))
{
byte[] statusDescriptionBuffer = Encoding.UTF8.GetBytes(statusDescription);
ret = Interop.WinHttp.WinHttpWebSocketShutdown(
_operation.WebSocketHandle,
(ushort)closeStatus,
statusDescriptionBuffer,
(uint)statusDescriptionBuffer.Length);
}
else
{
ret = Interop.WinHttp.WinHttpWebSocketShutdown(
_operation.WebSocketHandle,
(ushort)closeStatus,
IntPtr.Zero,
0);
}
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
return _operation.TcsCloseOutput.Task;
}
}
private void VerifyUpgradeResponse()
{
// Check the status code
var statusCode = GetHttpStatusCode();
if (statusCode != HttpStatusCode.SwitchingProtocols)
{
Abort();
return;
}
_subProtocol = GetResponseHeader(HeaderNameWebSocketProtocol);
}
private void AddRequestHeaders(Uri uri, ClientWebSocketOptions options)
{
var requestHeadersBuffer = new StringBuilder();
// Manually add cookies.
if (options.Cookies != null)
{
string cookieHeader = GetCookieHeader(uri, options.Cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(options.RequestHeaders.ToString());
var subProtocols = options.RequestedSubProtocols;
if (subProtocols.Count > 0)
{
requestHeadersBuffer.AppendLine(string.Format("{0}: {1}", HeaderNameWebSocketProtocol,
string.Join(", ", subProtocols)));
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
_operation.RequestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static string GetCookieHeader(Uri uri, CookieContainer cookies)
{
string cookieHeader = null;
Debug.Assert(cookies != null);
string cookieValues = cookies.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
cookieHeader = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", HeaderNameCookie, cookieValues);
}
return cookieHeader;
}
private HttpStatusCode GetHttpStatusCode()
{
uint infoLevel = Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE | Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER;
uint result = 0;
uint resultSize = sizeof(uint);
if (!Interop.WinHttp.WinHttpQueryHeaders(
_operation.RequestHandle,
infoLevel,
Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX,
ref result,
ref resultSize,
IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError();
}
return (HttpStatusCode)result;
}
private unsafe string GetResponseHeader(string headerName, char[] buffer = null)
{
const int StackLimit = 128;
Debug.Assert(buffer == null || (buffer != null && buffer.Length > StackLimit));
int bufferLength;
if (buffer == null)
{
bufferLength = StackLimit;
char* pBuffer = stackalloc char[bufferLength];
if (QueryHeaders(headerName, pBuffer, ref bufferLength))
{
return new string(pBuffer, 0, bufferLength);
}
}
else
{
bufferLength = buffer.Length;
fixed (char* pBuffer = buffer)
{
if (QueryHeaders(headerName, pBuffer, ref bufferLength))
{
return new string(pBuffer, 0, bufferLength);
}
}
}
int lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
return null;
}
if (lastError == Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER)
{
buffer = new char[bufferLength];
return GetResponseHeader(headerName, buffer);
}
throw WinHttpException.CreateExceptionUsingError(lastError);
}
private unsafe bool QueryHeaders(string headerName, char* buffer, ref int bufferLength)
{
Debug.Assert(bufferLength >= 0, "bufferLength must not be negative.");
uint index = 0;
// Convert the char buffer length to the length in bytes.
uint bufferLengthInBytes = (uint)bufferLength * sizeof(char);
// The WinHttpQueryHeaders buffer length is in bytes,
// but the API actually returns Unicode characters.
bool result = Interop.WinHttp.WinHttpQueryHeaders(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_QUERY_CUSTOM,
headerName,
new IntPtr(buffer),
ref bufferLengthInBytes,
ref index);
// Convert the byte buffer length back to the length in chars.
bufferLength = (int)bufferLengthInBytes / sizeof(char);
return result;
}
public override void Dispose()
{
if (!_disposed)
{
lock (_operation.Lock)
{
// Disposing will involve calling WinHttpClose on handles. It is critical that no other WinHttp
// function is running at the same time.
if (!_disposed)
{
_operation.Dispose();
// TODO (Issue 2508): Pinned buffers must be released in the callback, when it is guaranteed no further
// operations will be made to the send/receive buffers.
if (_cachedReceivePinnedBuffer.IsAllocated)
{
_cachedReceivePinnedBuffer.Free();
}
if (_cachedSendPinnedBuffer.IsAllocated)
{
_cachedSendPinnedBuffer.Free();
}
_disposed = true;
}
}
}
// No need to suppress finalization since the finalizer is not overridden.
}
public override void Abort()
{
lock (_operation.Lock)
{
if ((State != WebSocketState.None) && (State != WebSocketState.Connecting))
{
_operation.UpdateState(WebSocketState.Aborted);
}
else
{
// ClientWebSocket Desktop behavior: a ws that was not connected will not switch state to Aborted.
_operation.UpdateState(WebSocketState.Closed);
}
Dispose();
}
CancelAllOperations();
}
private void CancelAllOperations()
{
if (_operation.TcsClose != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsClose.TrySetException(exception);
}
if (_operation.TcsCloseOutput != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsCloseOutput.TrySetException(exception);
}
if (_operation.TcsReceive != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsReceive.TrySetException(exception);
}
if (_operation.TcsSend != null)
{
var exception = new OperationCanceledException();
_operation.TcsSend.TrySetException(exception);
}
if (_operation.TcsUpgrade != null)
{
var exception = new WebSocketException(SR.net_webstatus_ConnectFailure);
_operation.TcsUpgrade.TrySetException(exception);
}
}
private void ThrowOnInvalidHandle(Interop.WinHttp.SafeWinHttpHandle value)
{
if (value.IsInvalid)
{
Abort();
throw new WebSocketException(
SR.net_webstatus_ConnectFailure,
WinHttpException.CreateExceptionUsingLastError());
}
}
private CancellationTokenRegistration ThrowOrRegisterCancellation(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
Abort();
cancellationToken.ThrowIfCancellationRequested();
}
CancellationTokenRegistration cancellationRegistration =
cancellationToken.Register(s => ((WinHttpWebSocket)s).Abort(), this);
return cancellationRegistration;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Linq;
using ICSharpCode.SharpZipLib.Zip;
using Umbraco.Core;
using Umbraco.Core.Auditing;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Packaging;
using umbraco.cms.businesslogic.web;
using umbraco.BusinessLogic;
using System.Diagnostics;
using umbraco.cms.businesslogic.macro;
using umbraco.cms.businesslogic.template;
using umbraco.interfaces;
namespace umbraco.cms.businesslogic.packager
{
/// <summary>
/// The packager is a component which enables sharing of both data and functionality components between different umbraco installations.
///
/// The output is a .umb (a zip compressed file) which contains the exported documents/medias/macroes/documenttypes (etc.)
/// in a Xml document, along with the physical files used (images/usercontrols/xsl documents etc.)
///
/// Partly implemented, import of packages is done, the export is *under construction*.
/// </summary>
/// <remarks>
/// Ruben Verborgh 31/12/2007: I had to change some code, I marked my changes with "DATALAYER".
/// Reason: @@IDENTITY can't be used with the new datalayer.
/// I wasn't able to test the code, since I'm not aware how the code functions.
/// </remarks>
public class Installer
{
private const string PackageServer = "packages.umbraco.org";
private readonly List<string> _unsecureFiles = new List<string>();
private readonly Dictionary<string, string> _conflictingMacroAliases = new Dictionary<string, string>();
private readonly Dictionary<string, string> _conflictingTemplateAliases = new Dictionary<string, string>();
private readonly Dictionary<string, string> _conflictingStyleSheetNames = new Dictionary<string, string>();
private readonly List<string> _binaryFileErrors = new List<string>();
private int _currentUserId = -1;
public string Name { get; private set; }
public string Version { get; private set; }
public string Url { get; private set; }
public string License { get; private set; }
public string LicenseUrl { get; private set; }
public string Author { get; private set; }
public string AuthorUrl { get; private set; }
public string ReadMe { get; private set; }
public string Control { get; private set; }
public bool ContainsMacroConflict { get; private set; }
public IDictionary<string, string> ConflictingMacroAliases { get { return _conflictingMacroAliases; } }
public bool ContainsUnsecureFiles { get; private set; }
public List<string> UnsecureFiles { get { return _unsecureFiles; } }
public bool ContainsTemplateConflicts { get; private set; }
public IDictionary<string, string> ConflictingTemplateAliases { get { return _conflictingTemplateAliases; } }
/// <summary>
/// Indicates that the package contains assembly reference errors
/// </summary>
public bool ContainsBinaryFileErrors { get; private set; }
/// <summary>
/// List each assembly reference error
/// </summary>
public List<string> BinaryFileErrors { get { return _binaryFileErrors; } }
/// <summary>
/// Indicates that the package contains legacy property editors
/// </summary>
public bool ContainsLegacyPropertyEditors { get; private set; }
public bool ContainsStyleSheeConflicts { get; private set; }
public IDictionary<string, string> ConflictingStyleSheetNames { get { return _conflictingStyleSheetNames; } }
public int RequirementsMajor { get; private set; }
public int RequirementsMinor { get; private set; }
public int RequirementsPatch { get; private set; }
public RequirementsType RequirementsType { get; private set; }
public string IconUrl { get; private set; }
/// <summary>
/// The xmldocument, describing the contents of a package.
/// </summary>
public XmlDocument Config { get; private set; }
/// <summary>
/// Constructor
/// </summary>
public Installer()
{
Initialize();
}
public Installer(int currentUserId)
{
Initialize();
_currentUserId = currentUserId;
}
private void Initialize()
{
ContainsBinaryFileErrors = false;
ContainsTemplateConflicts = false;
ContainsUnsecureFiles = false;
ContainsMacroConflict = false;
ContainsStyleSheeConflicts = false;
}
[Obsolete("Use the ctor with all parameters")]
[EditorBrowsable(EditorBrowsableState.Never)]
public Installer(string name, string version, string url, string license, string licenseUrl, string author, string authorUrl, int requirementsMajor, int requirementsMinor, int requirementsPatch, string readme, string control)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">The name of the package</param>
/// <param name="version">The version of the package</param>
/// <param name="url">The url to a descriptionpage</param>
/// <param name="license">The license under which the package is released (preferably GPL ;))</param>
/// <param name="licenseUrl">The url to a licensedescription</param>
/// <param name="author">The original author of the package</param>
/// <param name="authorUrl">The url to the Authors website</param>
/// <param name="requirementsMajor">Umbraco version major</param>
/// <param name="requirementsMinor">Umbraco version minor</param>
/// <param name="requirementsPatch">Umbraco version patch</param>
/// <param name="readme">The readme text</param>
/// <param name="control">The name of the usercontrol used to configure the package after install</param>
/// <param name="requirementsType"></param>
/// <param name="iconUrl"></param>
public Installer(string name, string version, string url, string license, string licenseUrl, string author, string authorUrl, int requirementsMajor, int requirementsMinor, int requirementsPatch, string readme, string control, RequirementsType requirementsType, string iconUrl)
{
ContainsBinaryFileErrors = false;
ContainsTemplateConflicts = false;
ContainsUnsecureFiles = false;
ContainsMacroConflict = false;
ContainsStyleSheeConflicts = false;
this.Name = name;
this.Version = version;
this.Url = url;
this.License = license;
this.LicenseUrl = licenseUrl;
this.RequirementsMajor = requirementsMajor;
this.RequirementsMinor = requirementsMinor;
this.RequirementsPatch = requirementsPatch;
this.RequirementsType = requirementsType;
this.Author = author;
this.AuthorUrl = authorUrl;
this.IconUrl = iconUrl;
ReadMe = readme;
this.Control = control;
}
#region Public Methods
/// <summary>
/// Imports the specified package
/// </summary>
/// <param name="inputFile">Filename of the umbracopackage</param>
/// <param name="deleteFile">true if the input file should be deleted after import</param>
/// <returns></returns>
public string Import(string inputFile, bool deleteFile)
{
using (DisposableTimer.DebugDuration<Installer>(
() => "Importing package file " + inputFile,
() => "Package file " + inputFile + "imported"))
{
var tempDir = "";
if (File.Exists(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + inputFile)))
{
var fi = new FileInfo(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + inputFile));
// Check if the file is a valid package
if (fi.Extension.ToLower() == ".umb")
{
try
{
tempDir = UnPack(fi.FullName, deleteFile);
LoadConfig(tempDir);
}
catch (Exception exception)
{
LogHelper.Error<Installer>(string.Format("Error importing file {0}", fi.FullName), exception);
throw;
}
}
else
throw new Exception("Error - file isn't a package (doesn't have a .umb extension). Check if the file automatically got named '.zip' upon download.");
}
else
throw new Exception("Error - file not found. Could find file named '" + IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + inputFile) + "'");
return tempDir;
}
}
/// <summary>
/// Imports the specified package
/// </summary>
/// <param name="inputFile">Filename of the umbracopackage</param>
/// <returns></returns>
public string Import(string inputFile)
{
return Import(inputFile, true);
}
public int CreateManifest(string tempDir, string guid, string repoGuid)
{
//This is the new improved install rutine, which chops up the process into 3 steps, creating the manifest, moving files, and finally handling umb objects
var packName = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/name"));
var packAuthor = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/name"));
var packAuthorUrl = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/website"));
var packVersion = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/version"));
var packReadme = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/readme"));
var packLicense = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/license "));
var packUrl = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/url "));
var iconUrl = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/iconUrl"));
var enableSkins = false;
var skinRepoGuid = "";
if (Config.DocumentElement.SelectSingleNode("/umbPackage/enableSkins") != null)
{
var skinNode = Config.DocumentElement.SelectSingleNode("/umbPackage/enableSkins");
enableSkins = bool.Parse(XmlHelper.GetNodeValue(skinNode));
if (skinNode.Attributes["repository"] != null && string.IsNullOrEmpty(skinNode.Attributes["repository"].Value) == false)
skinRepoGuid = skinNode.Attributes["repository"].Value;
}
//Create a new package instance to record all the installed package adds - this is the same format as the created packages has.
//save the package meta data
var insPack = InstalledPackage.MakeNew(packName);
insPack.Data.Author = packAuthor;
insPack.Data.AuthorUrl = packAuthorUrl;
insPack.Data.Version = packVersion;
insPack.Data.Readme = packReadme;
insPack.Data.License = packLicense;
insPack.Data.Url = packUrl;
insPack.Data.IconUrl = iconUrl;
//skinning
insPack.Data.EnableSkins = enableSkins;
insPack.Data.SkinRepoGuid = string.IsNullOrEmpty(skinRepoGuid) ? Guid.Empty : new Guid(skinRepoGuid);
insPack.Data.PackageGuid = guid; //the package unique key.
insPack.Data.RepositoryGuid = repoGuid; //the repository unique key, if the package is a file install, the repository will not get logged.
insPack.Save();
return insPack.Data.Id;
}
public void InstallFiles(int packageId, string tempDir)
{
using (DisposableTimer.DebugDuration<Installer>(
() => "Installing package files for package id " + packageId + " into temp folder " + tempDir,
() => "Package file installation complete for package id " + packageId))
{
//retrieve the manifest to continue installation
var insPack = InstalledPackage.GetById(packageId);
//TODO: Depending on some files, some files should be installed differently.
//i.e. if stylsheets should probably be installed via business logic, media items should probably use the media IFileSystem!
// Move files
//string virtualBasePath = System.Web.HttpContext.Current.Request.ApplicationPath;
string basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
try
{
foreach (XmlNode n in Config.DocumentElement.SelectNodes("//file"))
{
var destPath = GetFileName(basePath, XmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")));
var sourceFile = GetFileName(tempDir, XmlHelper.GetNodeValue(n.SelectSingleNode("guid")));
var destFile = GetFileName(destPath, XmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
// Create the destination directory if it doesn't exist
if (Directory.Exists(destPath) == false)
Directory.CreateDirectory(destPath);
//If a file with this name exists, delete it
else if (File.Exists(destFile))
File.Delete(destFile);
// Copy the file
// SJ: Note - this used to do a move but some packages included the same file to be
// copied to multiple locations like so:
//
// <file>
// <guid>my-icon.png</guid>
// <orgPath>/umbraco/Images/</orgPath>
// <orgName>my-icon.png</orgName>
// </file>
// <file>
// <guid>my-icon.png</guid>
// <orgPath>/App_Plugins/MyPlugin/Images</orgPath>
// <orgName>my-icon.png</orgName>
// </file>
//
// Since this file unzips as a flat list of files, moving the file the first time means
// that when you try to do that a second time, it would result in a FileNotFoundException
File.Copy(sourceFile, destFile);
//PPH log file install
insPack.Data.Files.Add(XmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")) + "/" + XmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
}
// Once we're done copying, remove all the files
foreach (XmlNode n in Config.DocumentElement.SelectNodes("//file"))
{
var sourceFile = GetFileName(tempDir, XmlHelper.GetNodeValue(n.SelectSingleNode("guid")));
if (File.Exists(sourceFile))
File.Delete(sourceFile);
}
}
catch (Exception exception)
{
LogHelper.Error<Installer>("Package install error", exception);
throw;
}
// log that a user has install files
if (_currentUserId > -1)
{
Audit.Add(AuditTypes.PackagerInstall,
string.Format("Package '{0}' installed. Package guid: {1}", insPack.Data.Name, insPack.Data.PackageGuid),
_currentUserId, -1);
}
insPack.Save();
}
}
public void InstallBusinessLogic(int packageId, string tempDir)
{
using (DisposableTimer.DebugDuration<Installer>(
() => "Installing business logic for package id " + packageId + " into temp folder " + tempDir,
() => "Package business logic installation complete for package id " + packageId))
{
InstalledPackage insPack;
try
{
//retrieve the manifest to continue installation
insPack = InstalledPackage.GetById(packageId);
//bool saveNeeded = false;
// Get current user, with a fallback
var currentUser = new User(0);
//if there's a context, try to resolve the user - this will return null if there is a context but no
// user found when there are old/invalid cookies lying around most likely during installation.
// in that case we'll keep using the admin user
if (string.IsNullOrEmpty(BasePages.UmbracoEnsuredPage.umbracoUserContextID) == false)
{
if (BasePages.UmbracoEnsuredPage.ValidateUserContextID(BasePages.UmbracoEnsuredPage.umbracoUserContextID))
{
var userById = User.GetCurrent();
if (userById != null)
currentUser = userById;
}
}
//Xml as XElement which is used with the new PackagingService
var rootElement = Config.DocumentElement.GetXElement();
var packagingService = ApplicationContext.Current.Services.PackagingService;
//Perhaps it would have been a good idea to put the following into methods eh?!?
#region DataTypes
var dataTypeElement = rootElement.Descendants("DataTypes").FirstOrDefault();
if (dataTypeElement != null)
{
var dataTypeDefinitions = packagingService.ImportDataTypeDefinitions(dataTypeElement, currentUser.Id);
foreach (var dataTypeDefinition in dataTypeDefinitions)
{
insPack.Data.DataTypes.Add(dataTypeDefinition.Id.ToString(CultureInfo.InvariantCulture));
}
}
#endregion
#region Languages
var languageItemsElement = rootElement.Descendants("Languages").FirstOrDefault();
if (languageItemsElement != null)
{
var insertedLanguages = packagingService.ImportLanguages(languageItemsElement);
insPack.Data.Languages.AddRange(insertedLanguages.Select(l => l.Id.ToString()));
}
#endregion
#region Dictionary items
var dictionaryItemsElement = rootElement.Descendants("DictionaryItems").FirstOrDefault();
if (dictionaryItemsElement != null)
{
var insertedDictionaryItems = packagingService.ImportDictionaryItems(dictionaryItemsElement);
insPack.Data.DictionaryItems.AddRange(insertedDictionaryItems.Select(d => d.Id.ToString()));
}
#endregion
#region Macros
foreach (XmlNode n in Config.DocumentElement.SelectNodes("//macro"))
{
//TODO: Fix this, this should not use the legacy API
Macro m = Macro.Import(n);
if (m != null)
{
insPack.Data.Macros.Add(m.Id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Templates
var templateElement = rootElement.Descendants("Templates").FirstOrDefault();
if (templateElement != null)
{
var templates = packagingService.ImportTemplates(templateElement, currentUser.Id);
foreach (var template in templates)
{
insPack.Data.Templates.Add(template.Id.ToString(CultureInfo.InvariantCulture));
}
}
#endregion
#region DocumentTypes
//Check whether the root element is a doc type rather then a complete package
var docTypeElement = rootElement.Name.LocalName.Equals("DocumentType") ||
rootElement.Name.LocalName.Equals("DocumentTypes")
? rootElement
: rootElement.Descendants("DocumentTypes").FirstOrDefault();
if (docTypeElement != null)
{
var contentTypes = packagingService.ImportContentTypes(docTypeElement, currentUser.Id);
foreach (var contentType in contentTypes)
{
insPack.Data.Documenttypes.Add(contentType.Id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
#endregion
#region Stylesheets
foreach (XmlNode n in Config.DocumentElement.SelectNodes("Stylesheets/Stylesheet"))
{
StyleSheet s = StyleSheet.Import(n, currentUser);
insPack.Data.Stylesheets.Add(s.Id.ToString());
//saveNeeded = true;
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Documents
var documentElement = rootElement.Descendants("DocumentSet").FirstOrDefault();
if (documentElement != null)
{
var content = packagingService.ImportContent(documentElement, -1, currentUser.Id);
var firstContentItem = content.First();
insPack.Data.ContentNodeId = firstContentItem.Id.ToString(CultureInfo.InvariantCulture);
}
#endregion
#region Package Actions
foreach (XmlNode n in Config.DocumentElement.SelectNodes("Actions/Action"))
{
if (n.Attributes["undo"] == null || n.Attributes["undo"].Value == "true")
{
insPack.Data.Actions += n.OuterXml;
}
//Run the actions tagged only for 'install'
if (n.Attributes["runat"] != null && n.Attributes["runat"].Value == "install")
{
var alias = n.Attributes["alias"] != null ? n.Attributes["alias"].Value : "";
if (alias.IsNullOrWhiteSpace() == false)
{
PackageAction.RunPackageAction(insPack.Data.Name, alias, n);
}
}
}
#endregion
// Trigger update of Apps / Trees config.
// (These are ApplicationStartupHandlers so just instantiating them will trigger them)
new ApplicationRegistrar();
new ApplicationTreeRegistrar();
insPack.Save();
}
catch (Exception exception)
{
LogHelper.Error<Installer>("Error installing businesslogic", exception);
throw;
}
OnPackageBusinessLogicInstalled(insPack);
}
}
/// <summary>
/// Remove the temp installation folder
/// </summary>
/// <param name="packageId"></param>
/// <param name="tempDir"></param>
public void InstallCleanUp(int packageId, string tempDir)
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, true);
}
}
/// <summary>
/// Reads the configuration of the package from the configuration xmldocument
/// </summary>
/// <param name="tempDir">The folder to which the contents of the package is extracted</param>
public void LoadConfig(string tempDir)
{
Config = new XmlDocument();
Config.Load(tempDir + Path.DirectorySeparatorChar + "package.xml");
Name = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/name").FirstChild.Value;
Version = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/version").FirstChild.Value;
Url = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/url").FirstChild.Value;
License = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/license").FirstChild.Value;
LicenseUrl = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/license").Attributes.GetNamedItem("url").Value;
RequirementsMajor = int.Parse(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/major").FirstChild.Value);
RequirementsMinor = int.Parse(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/minor").FirstChild.Value);
RequirementsPatch = int.Parse(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/patch").FirstChild.Value);
var reqNode = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements");
RequirementsType = reqNode != null && reqNode.Attributes != null && reqNode.Attributes["type"] != null
? Enum<RequirementsType>.Parse(reqNode.Attributes["type"].Value, true)
: RequirementsType.Legacy;
var iconNode = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/iconUrl");
if (iconNode != null && iconNode.FirstChild != null)
{
IconUrl = iconNode.FirstChild.Value;
}
Author = Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/name").FirstChild.Value;
AuthorUrl = Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/website").FirstChild.Value;
var basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
var dllBinFiles = new List<string>();
foreach (XmlNode n in Config.DocumentElement.SelectNodes("//file"))
{
var badFile = false;
var destPath = GetFileName(basePath, XmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")));
var orgName = XmlHelper.GetNodeValue(n.SelectSingleNode("orgName"));
var destFile = GetFileName(destPath, orgName);
if (destPath.ToLower().Contains(IOHelper.DirSepChar + "app_code"))
{
badFile = true;
}
if (destPath.ToLower().Contains(IOHelper.DirSepChar + "bin"))
{
badFile = true;
}
if (destFile.ToLower().EndsWith(".dll"))
{
badFile = true;
dllBinFiles.Add(Path.Combine(tempDir, orgName));
}
if (badFile)
{
ContainsUnsecureFiles = true;
_unsecureFiles.Add(XmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
}
}
if (ContainsUnsecureFiles)
{
//Now we want to see if the DLLs contain any legacy data types since we want to warn people about that
string[] assemblyErrors;
var assembliesWithReferences = PackageBinaryInspector.ScanAssembliesForTypeReference<IDataType>(tempDir, out assemblyErrors).ToArray();
if (assemblyErrors.Any())
{
ContainsBinaryFileErrors = true;
BinaryFileErrors.AddRange(assemblyErrors);
}
if (assembliesWithReferences.Any())
{
ContainsLegacyPropertyEditors = true;
}
}
//this will check for existing macros with the same alias
//since we will not overwrite on import it's a good idea to inform the user what will be overwritten
foreach (XmlNode n in Config.DocumentElement.SelectNodes("//macro"))
{
var alias = n.SelectSingleNode("alias").InnerText;
if (!string.IsNullOrEmpty(alias))
{
var m = ApplicationContext.Current.Services.MacroService.GetByAlias(alias);
if (m != null)
{
ContainsMacroConflict = true;
if (_conflictingMacroAliases.ContainsKey(m.Name) == false)
{
_conflictingMacroAliases.Add(m.Name, alias);
}
}
}
}
foreach (XmlNode n in Config.DocumentElement.SelectNodes("Templates/Template"))
{
var alias = n.SelectSingleNode("Alias").InnerText;
if (!string.IsNullOrEmpty(alias))
{
var t = Template.GetByAlias(alias);
if (t != null)
{
ContainsTemplateConflicts = true;
if (_conflictingTemplateAliases.ContainsKey(t.Text) == false)
{
_conflictingTemplateAliases.Add(t.Text, alias);
}
}
}
}
foreach (XmlNode n in Config.DocumentElement.SelectNodes("Stylesheets/Stylesheet"))
{
var alias = n.SelectSingleNode("Name").InnerText;
if (!string.IsNullOrEmpty(alias))
{
var s = StyleSheet.GetByName(alias);
if (s != null)
{
ContainsStyleSheeConflicts = true;
if (_conflictingStyleSheetNames.ContainsKey(s.Text) == false)
{
_conflictingStyleSheetNames.Add(s.Text, alias);
}
}
}
}
var readmeNode = Config.DocumentElement.SelectSingleNode("/umbPackage/info/readme");
if (readmeNode != null)
{
ReadMe = XmlHelper.GetNodeValue(readmeNode);
}
var controlNode = Config.DocumentElement.SelectSingleNode("/umbPackage/control");
if (controlNode != null)
{
Control = XmlHelper.GetNodeValue(controlNode);
}
}
/// <summary>
/// This uses the old method of fetching and only supports the packages.umbraco.org repository.
/// </summary>
/// <param name="Package"></param>
/// <returns></returns>
public string Fetch(Guid Package)
{
// Check for package directory
if (Directory.Exists(IOHelper.MapPath(SystemDirectories.Packages)) == false)
Directory.CreateDirectory(IOHelper.MapPath(SystemDirectories.Packages));
var wc = new System.Net.WebClient();
wc.DownloadFile(
"http://" + PackageServer + "/fetch?package=" + Package.ToString(),
IOHelper.MapPath(SystemDirectories.Packages + "/" + Package + ".umb"));
return "packages\\" + Package + ".umb";
}
#endregion
#region Private Methods
/// <summary>
/// Gets the name of the file in the specified path.
/// Corrects possible problems with slashes that would result from a simple concatenation.
/// Can also be used to concatenate paths.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="fileName">Name of the file.</param>
/// <returns>The name of the file in the specified path.</returns>
private static string GetFileName(string path, string fileName)
{
// virtual dir support
fileName = IOHelper.FindFile(fileName);
if (path.Contains("[$"))
{
//this is experimental and undocumented...
path = path.Replace("[$UMBRACO]", SystemDirectories.Umbraco);
path = path.Replace("[$UMBRACOCLIENT]", SystemDirectories.UmbracoClient);
path = path.Replace("[$CONFIG]", SystemDirectories.Config);
path = path.Replace("[$DATA]", SystemDirectories.Data);
}
//to support virtual dirs we try to lookup the file...
path = IOHelper.FindFile(path);
Debug.Assert(path != null && path.Length >= 1);
Debug.Assert(fileName != null && fileName.Length >= 1);
path = path.Replace('/', '\\');
fileName = fileName.Replace('/', '\\');
// Does filename start with a slash? Does path end with one?
bool fileNameStartsWithSlash = (fileName[0] == Path.DirectorySeparatorChar);
bool pathEndsWithSlash = (path[path.Length - 1] == Path.DirectorySeparatorChar);
// Path ends with a slash
if (pathEndsWithSlash)
{
if (!fileNameStartsWithSlash)
// No double slash, just concatenate
return path + fileName;
return path + fileName.Substring(1);
}
if (fileNameStartsWithSlash)
// Required slash specified, just concatenate
return path + fileName;
return path + Path.DirectorySeparatorChar + fileName;
}
private static string UnPack(string zipName, bool deleteFile)
{
// Unzip
//the temp directory will be the package GUID - this keeps it consistent!
//the zipName is always the package Guid.umb
var packageFileName = Path.GetFileNameWithoutExtension(zipName);
var packageId = Guid.NewGuid();
Guid.TryParse(packageFileName, out packageId);
string tempDir = IOHelper.MapPath(SystemDirectories.Data) + Path.DirectorySeparatorChar + packageId.ToString();
//clear the directory if it exists
if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true);
Directory.CreateDirectory(tempDir);
var s = new ZipInputStream(File.OpenRead(zipName));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string fileName = Path.GetFileName(theEntry.Name);
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(tempDir + Path.DirectorySeparatorChar + fileName);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
// Clean up
s.Close();
if (deleteFile)
{
File.Delete(zipName);
}
return tempDir;
}
#endregion
internal static event EventHandler<InstalledPackage> PackageBusinessLogicInstalled;
private static void OnPackageBusinessLogicInstalled(InstalledPackage e)
{
EventHandler<InstalledPackage> handler = PackageBusinessLogicInstalled;
if (handler != null) handler(null, e);
}
}
}
| |
//
// Repository.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.Collections;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace Mono.Addins.Setup
{
internal class Repository
{
RepositoryEntryCollection repositories;
RepositoryEntryCollection addins;
string name;
internal string url;
public string Name {
get { return name; }
set { name = value; }
}
public string Url {
get { return url; }
set { url = value; }
}
internal string CachedFilesDir { get; set; }
[XmlElement ("Repository", Type = typeof(ReferenceRepositoryEntry))]
public RepositoryEntryCollection Repositories {
get {
if (repositories == null)
repositories = new RepositoryEntryCollection (this);
return repositories;
}
}
[XmlElement ("Addin", Type = typeof(PackageRepositoryEntry))]
public RepositoryEntryCollection Addins {
get {
if (addins == null)
addins = new RepositoryEntryCollection (this);
return addins;
}
}
public RepositoryEntry FindEntry (string url)
{
if (Repositories != null) {
foreach (RepositoryEntry e in Repositories)
if (e.Url == url) return e;
}
if (Addins != null) {
foreach (RepositoryEntry e in Addins)
if (e.Url == url) return e;
}
return null;
}
public void AddEntry (RepositoryEntry entry)
{
entry.owner = this;
if (entry is ReferenceRepositoryEntry) {
Repositories.Add (entry);
} else {
Addins.Add (entry);
}
}
public void RemoveEntry (RepositoryEntry entry)
{
if (entry is PackageRepositoryEntry)
Addins.Remove (entry);
else
Repositories.Remove (entry);
}
public IAsyncResult BeginDownloadSupportFile (string name, AsyncCallback cb, object state)
{
FileAsyncResult res = new FileAsyncResult ();
res.AsyncState = state;
res.Callback = cb;
string cachedFile = Path.Combine (CachedFilesDir, Path.GetFileName (name));
if (File.Exists (cachedFile)) {
res.FilePath = cachedFile;
res.CompletedSynchronously = true;
res.SetDone ();
return res;
}
Uri u = new Uri (new Uri (Url), name);
if (u.Scheme == "file") {
res.FilePath = u.AbsolutePath;
res.CompletedSynchronously = true;
res.SetDone ();
return res;
}
res.FilePath = cachedFile;
WebRequestHelper.GetResponseAsync (() => (HttpWebRequest)WebRequest.Create (u)).ContinueWith (t => {
try {
var resp = t.Result;
string dir = Path.GetDirectoryName (res.FilePath);
lock (this) {
if (!Directory.Exists (dir))
Directory.CreateDirectory (dir);
}
byte[] buffer = new byte [8092];
using (var s = resp.GetResponseStream ()) {
using (var f = File.OpenWrite (res.FilePath)) {
int nr = 0;
while ((nr = s.Read (buffer, 0, buffer.Length)) > 0)
f.Write (buffer, 0, nr);
}
}
} catch (Exception ex) {
res.Error = ex;
}
});
return res;
}
public Stream EndDownloadSupportFile (IAsyncResult ares)
{
FileAsyncResult res = ares as FileAsyncResult;
if (res == null)
throw new InvalidOperationException ("Invalid IAsyncResult instance");
if (res.Error != null)
throw res.Error;
return File.OpenRead (res.FilePath);
}
}
class FileAsyncResult: IAsyncResult
{
ManualResetEvent done;
public string FilePath;
public AsyncCallback Callback;
public Exception Error;
public void SetDone ()
{
lock (this) {
IsCompleted = true;
if (done != null)
done.Set ();
}
if (Callback != null)
Callback (this);
}
public object AsyncState { get; set; }
public WaitHandle AsyncWaitHandle {
get {
lock (this) {
if (done == null)
done = new ManualResetEvent (IsCompleted);
}
return done;
}
}
public bool CompletedSynchronously { get; set; }
public bool IsCompleted { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using Box2D;
using Box2D.Collision;
using Box2D.Common;
using Box2D.Collision.Shapes;
using Box2D.Dynamics;
using Box2D.Dynamics.Contacts;
using Microsoft.Xna.Framework;
using CocosSharp;
using Random = CocosSharp.CCRandom;
namespace tests
{
internal class CCPhysicsSprite : CCSprite
{
public CCPhysicsSprite(CCTexture2D f, CCRect r)
: base(f, r)
{
}
public b2Body PhysicsBody { get; set; }
public void UpdateSprite()
{
if(PhysicsBody == null)
return;
b2Vec2 pos = PhysicsBody.Position;
float x = pos.x * Box2DTestLayer.PTM_RATIO;
float y = pos.y * Box2DTestLayer.PTM_RATIO;
Position = new CCPoint(x, y);
Rotation = -CCMacros.CCRadiansToDegrees(PhysicsBody.Angle);
}
}
public class Box2DTestLayer : CCLayer
{
public class Myb2Listener : b2ContactListener
{
public override void PreSolve(b2Contact contact, b2Manifold oldManifold)
{
}
public override void PostSolve(Box2D.Dynamics.Contacts.b2Contact contact, ref b2ContactImpulse impulse)
{
}
}
public const int PTM_RATIO = 32;
private const int kTagParentNode = 1;
private readonly CCTexture2D spriteTexture;
private b2World _world;
public Box2DTestLayer()
{
spriteTexture = new CCTexture2D("Images/blocks");
}
public override void OnEnter()
{
base.OnEnter();
var listener = new CCEventListenerTouchAllAtOnce();
listener.OnTouchesEnded = onTouchesEnded;
AddEventListener(listener);
CCSize s = Layer.VisibleBoundsWorldspace.Size;
// init physics
initPhysics();
// create reset button
createResetButton();
addNewSpriteAtPosition(new CCPoint(s.Width / 2, s.Height / 2));
var label = new CCLabel("Tap screen", "MarkerFelt", 32, CCLabelFormat.SpriteFont);
AddChild(label, 0);
label.Color = new CCColor3B(0, 0, 255);
label.Position = new CCPoint(s.Width / 2, s.Height - 50);
Schedule ();
}
private void initPhysics()
{
CCSize s = Layer.VisibleBoundsWorldspace.Size;
var gravity = new b2Vec2(0.0f, -10.0f);
_world = new b2World(gravity);
float debugWidth = s.Width / PTM_RATIO * 2f;
float debugHeight = s.Height / PTM_RATIO * 2f;
//CCBox2dDraw debugDraw = new CCBox2dDraw(new b2Vec2(debugWidth / 2f + 10, s.Height - debugHeight - 10), 2);
//debugDraw.AppendFlags(b2DrawFlags.e_shapeBit);
//_world.SetDebugDraw(debugDraw);
_world.SetAllowSleeping(true);
_world.SetContinuousPhysics(true);
//m_debugDraw = new GLESDebugDraw( PTM_RATIO );
//world->SetDebugDraw(m_debugDraw);
//uint32 flags = 0;
//flags += b2Draw::e_shapeBit;
// flags += b2Draw::e_jointBit;
// flags += b2Draw::e_aabbBit;
// flags += b2Draw::e_pairBit;
// flags += b2Draw::e_centerOfMassBit;
//m_debugDraw->SetFlags(flags);
// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
b2BodyDef def = new b2BodyDef();
def.allowSleep = true;
def.position = b2Vec2.Zero;
def.type = b2BodyType.b2_staticBody;
b2Body groundBody = _world.CreateBody(def);
groundBody.SetActive(true);
// Define the ground box shape.
// bottom
b2EdgeShape groundBox = new b2EdgeShape();
groundBox.Set(b2Vec2.Zero, new b2Vec2(s.Width / PTM_RATIO, 0));
b2FixtureDef fd = new b2FixtureDef();
fd.shape = groundBox;
groundBody.CreateFixture(fd);
// top
groundBox = new b2EdgeShape();
groundBox.Set(new b2Vec2(0, s.Height / PTM_RATIO), new b2Vec2(s.Width / PTM_RATIO, s.Height / PTM_RATIO));
fd.shape = groundBox;
groundBody.CreateFixture(fd);
// left
groundBox = new b2EdgeShape();
groundBox.Set(new b2Vec2(0, s.Height / PTM_RATIO), b2Vec2.Zero);
fd.shape = groundBox;
groundBody.CreateFixture(fd);
// right
groundBox = new b2EdgeShape();
groundBox.Set(new b2Vec2(s.Width / PTM_RATIO, s.Height / PTM_RATIO), new b2Vec2(s.Width / PTM_RATIO, 0));
fd.shape = groundBox;
groundBody.CreateFixture(fd);
// _world.Dump();
}
public void createResetButton()
{
CCMenuItemImage res = new CCMenuItemImage("Images/r1", "Images/r2", reset);
CCMenu menu = new CCMenu(res);
CCSize s = Layer.VisibleBoundsWorldspace.Size;
menu.Position = new CCPoint(s.Width / 2, 30);
AddChild(menu, -1);
}
public void reset(object sender)
{
CCScene s = new Box2DTestScene();
var child = new Box2DTestLayer();
s.AddChild(child);
Director.ReplaceScene(s);
}
/*
public override void Draw()
{
//
// IMPORTANT:
// This is only for debug purposes
// It is recommend to disable it
//
base.Draw();
//ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
//kmGLPushMatrix();
CCDrawingPrimitives.Begin();
_world.DrawDebugData();
CCDrawingPrimitives.End();
//world.DrawDebugData();
//kmGLPopMatrix();
}
*/
private const int kTagForPhysicsSprite = 99999;
public void addNewSpriteAtPosition(CCPoint p)
{
//CCLog.Log("Add sprite #{2} : {0} x {1}", p.X, p.Y, _batch.ChildrenCount + 1);
//We have a 64x64 sprite sheet with 4 different 32x32 images. The following code is
//just randomly picking one of the images
int idx = (CCRandom.Float_0_1() > .5 ? 0 : 1);
int idy = (CCRandom.Float_0_1() > .5 ? 0 : 1);
var sprite = new CCPhysicsSprite(spriteTexture, new CCRect(32 * idx, 32 * idy, 32, 32));
AddChild(sprite, 0, kTagForPhysicsSprite);
sprite.Position = new CCPoint(p.X, p.Y);
// Define the dynamic body.
//Set up a 1m squared box in the physics world
b2BodyDef def = new b2BodyDef();
def.position = new b2Vec2(p.X / PTM_RATIO, p.Y / PTM_RATIO);
def.type = b2BodyType.b2_dynamicBody;
b2Body body = _world.CreateBody(def);
// Define another box shape for our dynamic body.
var dynamicBox = new b2PolygonShape();
dynamicBox.SetAsBox(.5f, .5f); //These are mid points for our 1m box
// Define the dynamic body fixture.
b2FixtureDef fd = new b2FixtureDef();
fd.shape = dynamicBox;
fd.density = 1f;
fd.friction = 0.3f;
b2Fixture fixture = body.CreateFixture(fd);
sprite.PhysicsBody = body;
//_world.SetContactListener(new Myb2Listener());
// _world.Dump();
}
public override void Update(float dt)
{
_world.Step(dt, 8, 1);
foreach (CCNode node in Children)
{
var sprite = node as CCPhysicsSprite;
if(sprite == null)
continue;
if (sprite.Visible && sprite.PhysicsBody.Position.y < 0f) {
_world.DestroyBody (sprite.PhysicsBody);
sprite.Visible = false;
} else
sprite.UpdateSprite();
}
//#if WINDOWS || WINDOWSGL || LINUX || MACOS
//
// This needs replacing with EventDispatcher
// CCInputState.Instance.Update(dt);
// PlayerIndex p;
// if (CCInputState.Instance.IsKeyPress(Microsoft.Xna.Framework.Input.Keys.D, PlayerIndex.One, out p))
// {
// _world.Dump();
//#if PROFILING
// b2Profile profile = _world.Profile;
// CCLog.Log("]-----------[{0:F4}]-----------------------[", profile.step);
// CCLog.Log("Solve Time = {0:F4}", profile.solve);
// CCLog.Log("# bodies = {0}", profile.bodyCount);
// CCLog.Log("# contacts = {0}", profile.contactCount);
// CCLog.Log("# joints = {0}", profile.jointCount);
// CCLog.Log("# toi iters = {0}", profile.toiSolverIterations);
// if (profile.step > 0f)
// {
// CCLog.Log("Solve TOI Time = {0:F4} {1:F2}%", profile.solveTOI, profile.solveTOI / profile.step * 100f);
// CCLog.Log("Solve TOI Advance Time = {0:F4} {1:F2}%", profile.solveTOIAdvance, profile.solveTOIAdvance / profile.step * 100f);
// }
//
// CCLog.Log("BroadPhase Time = {0:F4}", profile.broadphase);
// CCLog.Log("Collision Time = {0:F4}", profile.collide);
// CCLog.Log("Solve Velocity Time = {0:F4}", profile.solveVelocity);
// CCLog.Log("Solve Position Time = {0:F4}", profile.solvePosition);
// CCLog.Log("Step Time = {0:F4}", profile.step);
//#endif
// }
//#endif
}
void onTouchesEnded(List<CCTouch> touches, CCEvent touchEvent)
{
//Add a new body/atlas sprite at the touched location
foreach (CCTouch touch in touches)
{
CCPoint location = Layer.ScreenToWorldspace(touch.LocationOnScreen);
addNewSpriteAtPosition(location);
}
}
}
internal class Box2DTestScene : TestScene
{
protected override void NextTestCase()
{
}
protected override void PreviousTestCase()
{
}
protected override void RestTestCase()
{
}
public override void runThisTest()
{
CCLayer pLayer = new Box2DTestLayer();
AddChild(pLayer);
Director.ReplaceScene(this);
}
}
}
| |
// Copyright 2016 Esri
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using CoordinateConversionLibrary.Helpers;
using CoordinateConversionLibrary.Models;
using CoordinateConversionLibrary.ViewModels;
using System.Threading.Tasks;
using ArcGIS.Core.CIM;
using ProAppCoordConversionModule.Models;
using CoordinateConversionLibrary.Views;
using System.IO;
using System.Text;
using System.Linq;
using CoordinateConversionLibrary;
using System.Windows.Controls;
using System.Collections.ObjectModel;
using System.Reflection;
using ProAppCoordConversionModule.Views;
using System.Diagnostics;
using ProAppCoordConversionModule.Helpers;
using System.Windows.Threading;
namespace ProAppCoordConversionModule.ViewModels
{
public class ProTabBaseViewModel : TabBaseViewModel
{
// This name should correlate to the name specified in Config.esriaddinx - Tool id="ProAppCoordConversionModule_CoordinateMapTool"
internal const string MapPointToolName = "ProAppCoordConversionModule_CoordinateMapTool";
public ProTabBaseViewModel()
{
ActivatePointToolCommand = new CoordinateConversionLibrary.Helpers.RelayCommand(OnMapToolCommand);
FlashPointCommand = new CoordinateConversionLibrary.Helpers.RelayCommand(OnFlashPointCommandAsync);
ViewDetailCommand = new CoordinateConversionLibrary.Helpers.RelayCommand(OnViewDetailCommand);
FieldsCollection = new ObservableCollection<FieldsCollection>();
ViewDetailsTitle = string.Empty;
ListDictionary = new List<Dictionary<string, Tuple<object, bool>>>();
Mediator.Register(CoordinateConversionLibrary.Constants.RequestCoordinateBroadcast, OnBCNeeded);
Mediator.Register("FLASH_COMPLETED", OnFlashCompleted);
Mediator.NotifyColleagues(CoordinateConversionLibrary.Constants.SetCoordinateGetter, proCoordGetter);
CoordinateBase.ShowAmbiguousEventHandler += ShowAmbiguousEventHandler;
ArcGIS.Desktop.Framework.Events.ActiveToolChangedEvent.Subscribe(OnActiveToolChanged);
}
public CoordinateConversionLibrary.Helpers.RelayCommand ActivatePointToolCommand { get; set; }
public CoordinateConversionLibrary.Helpers.RelayCommand FlashPointCommand { get; set; }
public CoordinateConversionLibrary.Helpers.RelayCommand ViewDetailCommand { get; set; }
public static ProCoordinateGet proCoordGetter = new ProCoordinateGet();
public String PreviousTool { get; set; }
public static ObservableCollection<AddInPoint> CoordinateAddInPoints { get; set; }
public ObservableCollection<FieldsCollection> FieldsCollection { get; set; }
public string ViewDetailsTitle { get; set; }
public static Dictionary<string, ObservableCollection<Symbol>> AllSymbolCollection { get; set; }
public ProAdditionalFieldsView DialogView { get; set; }
public bool IsDialogViewOpen { get; set; }
public static Symbol SelectedSymbolObject { get; set; }
public static PropertyInfo SelectedColorObject { get; set; }
public static bool Is3DMap { get; set; }
public static Symbol SelectedSymbol { get; set; }
private bool isToolActive = false;
public bool IsToolActive
{
get
{
return isToolActive;
}
set
{
isSelectionToolActive = false;
RaisePropertyChanged(() => IsSelectionToolActive);
CoordinateMapTool.SelectFeatureEnable = false;
isToolActive = value;
ActivateMapTool(value);
RaisePropertyChanged(() => IsToolActive);
}
}
public bool isSelectionToolActive = false;
public bool IsSelectionToolActive
{
get
{
return isSelectionToolActive;
}
set
{
isToolActive = false;
RaisePropertyChanged(() => IsToolActive);
CoordinateMapTool.SelectFeatureEnable = true;
isSelectionToolActive = value;
ActivateMapTool(value);
RaisePropertyChanged(() => IsSelectionToolActive);
}
}
private void ActivateMapTool(bool active)
{
string toolToActivate = string.Empty;
if (active)
{
string currentTool = FrameworkApplication.CurrentTool;
if (currentTool != MapPointToolName)
{
// Save previous tool to reactivate
PreviousTool = currentTool;
toolToActivate = MapPointToolName;
}
}
else
{
// Handle case if no Previous Tool
if (string.IsNullOrEmpty(PreviousTool))
PreviousTool = "esri_mapping_exploreTool";
toolToActivate = PreviousTool;
}
if (!string.IsNullOrEmpty(toolToActivate))
{
FrameworkApplication.SetCurrentToolAsync(toolToActivate);
}
}
private static System.IDisposable _overlayObject = null;
/// <summary>
/// lists to store GUIDs of graphics, temp feedback and map graphics
/// </summary>
public static List<ProGraphic> ProGraphicsList = new List<ProGraphic>();
private void ClearOverlay()
{
if (_overlayObject != null)
{
_overlayObject.Dispose();
_overlayObject = null;
}
}
#region overrides
public override bool OnNewMapPoint(object obj)
{
if (!base.OnNewMapPoint(obj))
return false;
var input = obj as Dictionary<string, Tuple<object, bool>>;
MapPoint mp = (input != null) ? input.Where(x => x.Key == PointFieldName).Select(x => x.Value.Item1).FirstOrDefault() as MapPoint : obj as MapPoint;
if (mp == null)
return false;
proCoordGetter.Point = mp;
InputCoordinate = proCoordGetter.GetInputDisplayString();
return true;
}
public override void OnValidateMapPoint(object obj)
{
if (OnValidationSuccess(obj))
{
Mediator.NotifyColleagues(CoordinateConversionLibrary.Constants.NEW_MAP_POINT, obj);
}
}
public bool OnValidationSuccess(object obj)
{
if (!base.OnNewMapPoint(obj))
return false;
var input = obj as Dictionary<string, Tuple<object, bool>>;
MapPoint mp = (input != null) ? input.Where(x => x.Key == PointFieldName).Select(x => x.Value.Item1).FirstOrDefault() as MapPoint : obj as MapPoint;
if (mp == null)
return false;
var isValidPoint = QueuedTask.Run(async () => { return await IsValidPoint(mp); });
if (!isValidPoint.Result)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Point is out of bounds", "Point is out of bounds",
System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
return false;
}
return true;
}
public override bool OnMouseMove(object obj)
{
if (!base.OnMouseMove(obj))
return false;
var mp = obj as MapPoint;
if (mp == null)
return false;
proCoordGetter.Point = mp;
InputCoordinate = proCoordGetter.GetInputDisplayString();
return true;
}
public override void OnDisplayCoordinateTypeChanged(CoordinateConversionLibraryConfig obj)
{
base.OnDisplayCoordinateTypeChanged(obj);
if (proCoordGetter != null && proCoordGetter.Point != null)
{
InputCoordinate = proCoordGetter.GetInputDisplayString();
}
}
private string processCoordinate(CCCoordinate ccc)
{
if (ccc == null)
return string.Empty;
HasInputError = false;
string result = string.Empty;
if (ccc.Type == CoordinateType.Unknown)
{
HasInputError = true;
proCoordGetter.Point = null;
foreach (var output in CoordinateConversionLibraryConfig.AddInConfig.OutputCoordinateList)
{
output.OutputCoordinate = "";
output.Props.Clear();
}
System.Windows.Forms.MessageBox.Show(CoordinateConversionLibrary.Properties.Resources.InvalidCoordMsg,
CoordinateConversionLibrary.Properties.Resources.InvalidCoordCap);
}
else
{
proCoordGetter.Point = ccc.Point;
result = new CoordinateDD(ccc.Point.Y, ccc.Point.X).ToString("", new CoordinateDDFormatter());
if (CoordinateBase.InputFormatSelection == CoordinateTypes.Custom.ToString())
CoordinateConversionLibraryConfig.AddInConfig.IsCustomFormat = true;
else
CoordinateConversionLibraryConfig.AddInConfig.IsCustomFormat = false;
}
return result;
}
public override string ProcessInput(string input)
{
if (input == "NA") return string.Empty;
if (string.IsNullOrWhiteSpace(input))
return string.Empty;
// Must force non async here to avoid returning to base class early
var ccc = QueuedTask.Run(() =>
{
return GetCoordinateType(input);
}).Result;
return processCoordinate(ccc);
}
public string ProcessInputValue(string input)
{
if (input == "NA") return string.Empty;
if (string.IsNullOrWhiteSpace(input))
return string.Empty;
var ccc = GetCoordinateType(input);
return processCoordinate(ccc);
}
public Dictionary<string, string> GetOutputFormats(AddInPoint point)
{
var results = new Dictionary<string, string>();
results.Add(CoordinateFieldName, point.Text);
var projectedPoint = (MapPoint)GeometryEngine.Instance.Project(point.Point, SpatialReferences.WGS84);
var inputText = projectedPoint.Y + " " + projectedPoint.X;
var ccc = GetCoordinateType(inputText);
if (ccc != null && ccc.Point != null)
{
ProCoordinateGet procoordinateGetter = new ProCoordinateGet();
procoordinateGetter.Point = ccc.Point;
CoordinateGetBase coordinateGetter = procoordinateGetter as CoordinateGetBase;
CoordinateBase.IsOutputInProcess = true;
foreach (var output in CoordinateConversionLibraryConfig.AddInConfig.OutputCoordinateList)
{
var props = new Dictionary<string, string>();
string coord = string.Empty;
switch (output.CType)
{
case CoordinateType.DD:
CoordinateDD cdd;
if (coordinateGetter.CanGetDD(output.SRFactoryCode, out coord) &&
CoordinateDD.TryParse(coord, out cdd, true))
{
results.Add(output.Name, cdd.ToString(output.Format, new CoordinateDDFormatter()));
}
break;
case CoordinateType.DMS:
CoordinateDMS cdms;
if (coordinateGetter.CanGetDMS(output.SRFactoryCode, out coord) &&
CoordinateDMS.TryParse(coord, out cdms, true))
{
results.Add(output.Name, cdms.ToString(output.Format, new CoordinateDMSFormatter()));
}
break;
case CoordinateType.DDM:
CoordinateDDM ddm;
if (coordinateGetter.CanGetDDM(output.SRFactoryCode, out coord) &&
CoordinateDDM.TryParse(coord, out ddm, true))
{
results.Add(output.Name, ddm.ToString(output.Format, new CoordinateDDMFormatter()));
}
break;
case CoordinateType.GARS:
CoordinateGARS gars;
if (coordinateGetter.CanGetGARS(output.SRFactoryCode, out coord) &&
CoordinateGARS.TryParse(coord, out gars))
{
results.Add(output.Name, gars.ToString(output.Format, new CoordinateGARSFormatter()));
}
break;
case CoordinateType.MGRS:
CoordinateMGRS mgrs;
if (coordinateGetter.CanGetMGRS(output.SRFactoryCode, out coord) &&
CoordinateMGRS.TryParse(coord, out mgrs))
{
results.Add(output.Name, mgrs.ToString(output.Format, new CoordinateMGRSFormatter()));
}
break;
case CoordinateType.USNG:
CoordinateUSNG usng;
if (coordinateGetter.CanGetUSNG(output.SRFactoryCode, out coord) &&
CoordinateUSNG.TryParse(coord, out usng))
{
results.Add(output.Name, usng.ToString(output.Format, new CoordinateMGRSFormatter()));
}
break;
case CoordinateType.UTM:
CoordinateUTM utm;
if (coordinateGetter.CanGetUTM(output.SRFactoryCode, out coord) &&
CoordinateUTM.TryParse(coord, out utm))
{
results.Add(output.Name, utm.ToString(output.Format, new CoordinateUTMFormatter()));
}
break;
default:
break;
}
}
CoordinateBase.IsOutputInProcess = false;
}
return results;
}
public override void OnEditPropertiesDialogCommand(object obj)
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
{
System.Windows.Forms.MessageBox.Show(CoordinateConversionLibrary.Properties.Resources.LoadMapMsg);
return;
}
var dlg = new ProEditPropertiesView();
dlg.DataContext = new ProEditPropertiesViewModel();
try
{
dlg.ShowDialog();
}
catch (Exception e)
{
if (e.Message.ToLower() == CoordinateConversionLibrary.Properties.Resources.CoordsOutOfBoundsMsg.ToLower())
{
System.Windows.Forms.MessageBox.Show(e.Message + System.Environment.NewLine + CoordinateConversionLibrary.Properties.Resources.CoordsOutOfBoundsAddlMsg,
CoordinateConversionLibrary.Properties.Resources.CoordsoutOfBoundsCaption);
}
else
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
}
}
public bool IsView3D()
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return false;
//Return whether the viewing mode is SceneLocal or SceneGlobal
return mapView.ViewingMode == ArcGIS.Core.CIM.MapViewingMode.SceneLocal ||
mapView.ViewingMode == ArcGIS.Core.CIM.MapViewingMode.SceneGlobal;
}
public override void OnImportCSVFileCommand(object obj)
{
try
{
var fileDialog = new Microsoft.Win32.OpenFileDialog();
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "csv files|*.csv|Excel 97-2003 Workbook (*.xls)|*.xls|Excel Workbook (*.xlsx)|*.xlsx";
// attemp to import
var fieldVM = new SelectCoordinateFieldsViewModel();
var result = fileDialog.ShowDialog();
if (result.HasValue && result.Value == true)
{
var dlg = new ProSelectCoordinateFieldsView();
var coordinates = new List<string>();
var extension = Path.GetExtension(fileDialog.FileName);
switch (extension)
{
case ".csv":
ImportFromCSV(fieldVM, dlg, coordinates, fileDialog.FileName);
break;
case ".xls":
case ".xlsx":
ImportFromExcel(dlg, fileDialog, fieldVM);
break;
default:
break;
}
}
}
catch (Exception ex)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Something went wrong.");
Debug.WriteLine("Error " + ex.ToString());
}
}
private static void ImportFromCSV(SelectCoordinateFieldsViewModel fieldVM, ProSelectCoordinateFieldsView dlg, List<string> coordinates, string fileName)
{
using (Stream s = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var headers = ImportCSV.GetHeaders(s);
ImportedData = new List<Dictionary<string, Tuple<object, bool>>>();
if (headers != null)
{
foreach (var header in headers)
{
fieldVM.AvailableFields.Add(header);
fieldVM.FieldCollection.Add(new ListBoxItem() { Name = header, Content = header, IsSelected = false });
System.Diagnostics.Debug.WriteLine("header : {0}", header);
}
dlg.DataContext = fieldVM;
}
else
{
System.Windows.Forms.MessageBox.Show(CoordinateConversionLibrary.Properties.Resources.MsgNoDataFound);
return;
}
if (dlg.ShowDialog() == true)
{
var dictionary = new List<Dictionary<string, Tuple<object, bool>>>();
using (Stream str = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var lists = ImportCSV.Import<ImportCoordinatesList>(str, fieldVM.SelectedFields.ToArray(), headers, dictionary);
FieldCollection = fieldVM.FieldCollection.Where(y => y.IsSelected).Select(x => x.Content).ToList();
foreach (var item in dictionary)
{
var dict = new Dictionary<string, Tuple<object, bool>>();
foreach (var field in item)
{
if (FieldCollection.Contains(field.Key))
dict.Add(field.Key, Tuple.Create((object)field.Value.Item1, FieldCollection.Contains(field.Key)));
if (fieldVM.SelectedFields.ToArray()[0] == field.Key)
SelectedField1 = Convert.ToString(field.Key);
else if (fieldVM.UseTwoFields)
if (fieldVM.SelectedFields.ToArray()[1] == field.Key)
SelectedField2 = Convert.ToString(field.Key);
}
var lat = item.Where(x => x.Key == fieldVM.SelectedFields.ToArray()[0]).Select(x => x.Value.Item1).FirstOrDefault();
var sb = new StringBuilder();
sb.Append(lat);
if (fieldVM.UseTwoFields)
{
var lon = item.Where(x => x.Key == fieldVM.SelectedFields.ToArray()[1]).Select(x => x.Value.Item1).FirstOrDefault();
sb.Append(string.Format(" {0}", lon));
}
dict.Add(OutputFieldName, Tuple.Create((object)sb.ToString(), false));
ImportedData.Add(dict);
}
}
Mediator.NotifyColleagues(CoordinateConversionLibrary.Constants.IMPORT_COORDINATES, ImportedData);
}
}
}
public static async void ImportFromExcel(ProSelectCoordinateFieldsView dlg, Microsoft.Win32.OpenFileDialog diag, SelectCoordinateFieldsViewModel fieldVM)
{
ImportedData = new List<Dictionary<string, Tuple<object, bool>>>();
List<string> headers = new List<string>();
var filename = diag.FileName;
string selectedCol1Key = "", selectedCol2Key = "";
var selectedColumn = fieldVM.SelectedFields.ToArray();
var columnCollection = new List<string>();
var fileExt = Path.GetExtension(filename); //get the extension of uploaded excel file
var lstDictionary = await FeatureClassUtils.ImportFromExcel(filename);
var headerDict = lstDictionary.FirstOrDefault();
if (headerDict != null)
foreach (var item in headerDict)
{
if (item.Key != "OBJECTID")
headers.Add(item.Key);
}
if (headers != null)
{
foreach (var header in headers)
{
fieldVM.AvailableFields.Add(header.Replace(" ", ""));
fieldVM.FieldCollection.Add(new ListBoxItem() { Name = header.Replace(" ", ""), Content = header, IsSelected = false });
}
dlg.DataContext = fieldVM;
}
else
System.Windows.Forms.MessageBox.Show(CoordinateConversionLibrary.Properties.Resources.MsgNoDataFound);
if (dlg.ShowDialog() == true)
{
foreach (var item in headers)
{
columnCollection.Add(item);
if (item == fieldVM.SelectedFields.ToArray()[0])
{
selectedCol1Key = item;
SelectedField1 = item;
}
if (fieldVM.UseTwoFields && item == fieldVM.SelectedFields.ToArray()[1])
{
selectedCol2Key = item;
SelectedField2 = item;
}
}
for (int i = 0; i < lstDictionary.Count; i++)
{
var dict = new Dictionary<string, Tuple<object, bool>>();
dict = lstDictionary[i];
if (fieldVM.UseTwoFields)
{
if (lstDictionary[i].Where(x => x.Key == selectedCol1Key) != null && lstDictionary[i].Where(x => x.Key == selectedCol2Key) != null)
dict.Add(OutputFieldName, Tuple.Create((object)Convert.ToString(lstDictionary[i].Where(x => x.Key == selectedCol1Key).Select(x => x.Value.Item1).FirstOrDefault()
+ " " + lstDictionary[i].Where(x => x.Key == selectedCol2Key).Select(x => x.Value.Item1).FirstOrDefault()), false));
}
else
{
if (lstDictionary[i].Where(x => x.Key == selectedCol1Key) != null)
dict.Add(OutputFieldName, Tuple.Create((object)lstDictionary[i].Where(x => x.Key == selectedCol1Key).Select(x => x.Value.Item1).FirstOrDefault(), false));
}
ImportedData.Add(dict);
}
FieldCollection = fieldVM.FieldCollection.Where(y => y.IsSelected).Select(x => x.Content).ToList();
foreach (var item in ImportedData)
{
var dict = new Dictionary<string, Tuple<object, bool>>();
foreach (var field in item)
{
if (FieldCollection.Contains(field.Key) || field.Key == OutputFieldName)
dict.Add(field.Key, Tuple.Create(field.Value.Item1, FieldCollection.Contains(field.Key)));
}
ListDictionary.Add(dict);
}
Mediator.NotifyColleagues(CoordinateConversionLibrary.Constants.IMPORT_COORDINATES, ListDictionary);
}
}
#endregion overrides
#region Mediator handlers
private void OnBCNeeded(object obj)
{
if (proCoordGetter == null || proCoordGetter.Point == null)
return;
BroadcastCoordinateValues(proCoordGetter.Point);
}
private void OnFlashCompleted(object obj)
{
IsToolActive = false;
CoordinateMapTool.AllowUpdates = true;
}
#endregion Mediator handlers
private void SetAsCurrentToolAsync()
{
IsToolActive = true;
}
private void OnMapToolCommand(object obj)
{
SetAsCurrentToolAsync();
}
private void OnActiveToolChanged(ArcGIS.Desktop.Framework.Events.ToolEventArgs args)
{
// Update active tool when tool changed so Map Point Tool button push state
// stays in sync with Pro UI
if (IsSelectionToolActive)
{
IsSelectionToolActive = args.CurrentID == MapPointToolName;
RaisePropertyChanged(() => IsSelectionToolActive);
}
else
{
isToolActive = args.CurrentID == MapPointToolName;
RaisePropertyChanged(() => IsToolActive);
}
}
internal async Task<string> AddGraphicToMap(Geometry geom, CIMColor color, bool IsTempGraphic = false, double size = 1.0, string text = "", SimpleMarkerStyle markerStyle = SimpleMarkerStyle.Circle, string tag = "")
{
if (geom == null || MapView.Active == null)
return string.Empty;
CIMSymbolReference symbol = null;
if (!string.IsNullOrWhiteSpace(text) && geom.GeometryType == GeometryType.Point)
{
await QueuedTask.Run(() =>
{
// TODO add text graphic
//var tg = new CIMTextGraphic() { Placement = Anchor.CenterPoint, Text = text};
});
}
else if (geom.GeometryType == GeometryType.Point)
{
await QueuedTask.Run(() =>
{
var s = SymbolFactory.Instance.ConstructPointSymbol(color, size, markerStyle);
var haloSymbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.GreenRGB);
haloSymbol.SetOutlineColor(ColorFactory.Instance.GreenRGB);
s.HaloSymbol = haloSymbol;
s.HaloSize = 0;
if (SelectedSymbol != null)
{
if (Is3DMap)
{
var symbol3D = ((ArcGIS.Core.CIM.CIMPointSymbol)(SelectedSymbol.SymbolItem.Symbol));
symbol3D.UseRealWorldSymbolSizes = false;
symbol = new CIMSymbolReference() { Symbol = symbol3D };
}
else
{
symbol = new CIMSymbolReference() { Symbol = SelectedSymbol.SymbolItem.Symbol };
}
}
else
symbol = new CIMSymbolReference() { Symbol = s };
});
}
else if (geom.GeometryType == GeometryType.Polyline)
{
await QueuedTask.Run(() =>
{
var s = SymbolFactory.Instance.ConstructLineSymbol(color, size);
symbol = new CIMSymbolReference() { Symbol = s };
});
}
else if (geom.GeometryType == GeometryType.Polygon)
{
await QueuedTask.Run(() =>
{
var outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 1.0, SimpleLineStyle.Solid);
var s = SymbolFactory.Instance.ConstructPolygonSymbol(color, SimpleFillStyle.Solid, outline);
symbol = new CIMSymbolReference() { Symbol = s };
});
}
var result = await QueuedTask.Run(() =>
{
var disposable = MapView.Active.AddOverlay(geom, symbol);
var guid = Guid.NewGuid().ToString();
ProGraphicsList.Add(new ProGraphic(disposable, guid, geom, symbol, IsTempGraphic, tag));
return guid;
});
return result;
}
internal async virtual void OnFlashPointCommandAsync(object obj)
{
var point = obj as MapPoint;
if (point == null)
return;
IsToolActive = true;
await QueuedTask.Run(() =>
{
// zoom to point
var projectedPoint = GeometryEngine.Instance.Project(point, MapView.Active.Extent.SpatialReference);
// WORKAROUND: delay zoom by 1 sec to give Map Point Tool enough time to activate
// Note: The Map Point Tool is required to be active to enable flash overlay
MapView.Active.PanTo(projectedPoint, new TimeSpan(0, 0, 1));
Mediator.NotifyColleagues("UPDATE_FLASH", point);
});
}
internal virtual void OnViewDetailCommand(object obj)
{
var input = obj as System.Windows.Controls.ListBox;
if (input.SelectedItems.Count == 0)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No data available");
return;
}
ShowPopUp(input.SelectedItems.Cast<AddInPoint>());
}
private void ShowPopUp(IEnumerable<AddInPoint> addinPoint)
{
var pointDict = addinPoint.Select(x => x.FieldsDictionary);
var popupContentList = new List<PopupContent>();
int index = 0;
foreach (var dictionary in pointDict)
{
//popup info is not showing duplicate html content. data-attr-index attribute with an incremental number is added to workaround the issue.
var htmlString = "<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"><head>"
+ "<meta charset=\"utf-8\">"
+ "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=9\">"
+ "<title>Popup</title>"
+ "<link rel=\"Stylesheet\" type=\"text/css\" href=\"c:/program files/arcgis/pro/Resources/Popups/esri/css/Popups.css\">"
+ "</head>"
+ "<body data-attr-index=\" data-attr-index=\"" + Guid.NewGuid() + "\">"
+ "<div class=\"esriPopup\">"
+ "<div class=\"esriPopupWrapper\">"
+ "<div class=\"sizer content\">"
+ "<div class=\"contentPane\">"
+ "<div class=\"esriViewPopup\">"
+ "<div class=\"mainSection\">"
+ "<div><!--POPUP_MAIN_CONTENT_TEXT--></div>"
+ "<div><table class=\"attrTable\" cellspacing=\"0\" cellpadding=\"0\"><tbody>";
FieldsCollection = new ObservableCollection<FieldsCollection>();
if (dictionary != null)
{
foreach (var item in dictionary)
{
htmlString = htmlString + "<tr valign=\"top\">";
if (item.Value.Item2)
{
htmlString = htmlString + "<td class=\"attrName\">" + item.Key + "</td><td class=\"attrValue\">" + Convert.ToString(item.Value.Item1) + "</td>";
FieldsCollection.Add(new FieldsCollection() { FieldName = item.Key, FieldValue = Convert.ToString(item.Value.Item1) });
}
htmlString = htmlString + "</tr>";
}
var valOutput = dictionary.Where(x => x.Key == PointFieldName).Select(x => x.Value.Item1).FirstOrDefault();
ViewDetailsTitle = MapPointHelper.GetMapPointAsDisplayString(valOutput as MapPoint);
}
else
ViewDetailsTitle = addinPoint.ElementAtOrDefault(index).Text;
if (!FieldsCollection.Any())
{
htmlString = htmlString + "<tr valign=\"top\"><td class=\"attrName\">"
+ CoordinateConversionLibrary.Properties.Resources.InformationNotAvailableMsg + "</td></tr>";
}
htmlString = htmlString + "</tbody></table></div>"
+ "</div>"
+ "<script type=\"text/javascript\" src=\"c:/program files/arcgis/pro/Resources/Popups/dojo/dojo.js\"></script>"
+ "<script type=\"text/javascript\" src=\"c:/program files/arcgis/pro/Resources/Popups/esri/run.js\"></script>"
+ "</body></html>";
popupContentList.Add(new PopupContent(htmlString, ViewDetailsTitle));
index++;
}
MapView.Active.ShowCustomPopup(popupContentList);
}
private void diagView_Closed(object sender, EventArgs e)
{
IsDialogViewOpen = false;
}
internal async void UpdateHighlightedGraphics(bool reset, bool isUpdateAll = false)
{
var list = ProGraphicsList.ToList();
foreach (var proGraphic in list)
{
var aiPoint = CoordinateAddInPoints.FirstOrDefault(p => p.GUID == proGraphic.GUID);
if (aiPoint != null)
{
var s = proGraphic.SymbolRef.Symbol as CIMPointSymbol;
var doUpdate = false;
if (s == null)
continue;
if (aiPoint.IsSelected)
{
if (reset)
{
s.HaloSize = 0;
aiPoint.IsSelected = false;
}
else
s.HaloSize = 2;
doUpdate = true;
}
else if (s.HaloSize > 0)
{
s.HaloSize = 0;
doUpdate = true;
}
if (doUpdate || isUpdateAll)
{
var result = await QueuedTask.Run(() =>
{
if (SelectedSymbolObject != null)
{
if (Is3DMap)
{
var symbol3D = ((ArcGIS.Core.CIM.CIMPointSymbol)(SelectedSymbol.SymbolItem.Symbol));
symbol3D.UseRealWorldSymbolSizes = false;
proGraphic.SymbolRef.Symbol = symbol3D;
}
else
{
proGraphic.SymbolRef.Symbol = SelectedSymbolObject.SymbolItem.Symbol;
}
var symbol = proGraphic.SymbolRef.Symbol as CIMPointSymbol;
if (aiPoint.IsSelected)
{
symbol.HaloSize = 2;
var haloSymbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.GreenRGB);
haloSymbol.SetOutlineColor(ColorFactory.Instance.GreenRGB);
symbol.HaloSymbol = haloSymbol;
}
}
var temp = MapView.Active.UpdateOverlay(proGraphic.Disposable, proGraphic.Geometry, proGraphic.SymbolRef);
return temp;
});
}
}
}
}
/// <summary>
/// Method to check to see point is withing the map area of interest
/// </summary>
/// <param name="point">IPoint to validate</param>
/// <returns></returns>
internal async Task<bool> IsValidPoint(MapPoint point)
{
if ((point != null) && (MapView.Active != null) && (MapView.Active.Map != null))
{
Envelope env = null;
await QueuedTask.Run(() =>
{
env = MapView.Active.Map.CalculateFullExtent();
});
bool isValid = false;
if (env != null)
{
if (env.SpatialReference != point.SpatialReference)
{
point = GeometryEngine.Instance.Project(point, env.SpatialReference) as MapPoint;
}
isValid = GeometryEngine.Instance.Contains(env, point);
}
return isValid;
}
return false;
}
#region Private Methods
private void BroadcastCoordinateValues(MapPoint mapPoint)
{
var dict = new Dictionary<CoordinateType, string>();
if (mapPoint == null)
return;
var dd = new CoordinateDD(mapPoint.Y, mapPoint.X);
try
{
dict.Add(CoordinateType.DD, dd.ToString("", new CoordinateDDFormatter()));
}
catch { /* Conversion Failed */ }
try
{
dict.Add(CoordinateType.DDM, new CoordinateDDM(dd).ToString("", new CoordinateDDMFormatter()));
}
catch { /* Conversion Failed */ }
try
{
dict.Add(CoordinateType.DMS, new CoordinateDMS(dd).ToString("", new CoordinateDMSFormatter()));
}
catch { /* Conversion Failed */ }
Mediator.NotifyColleagues(CoordinateConversionLibrary.Constants.BroadcastCoordinateValues, dict);
}
private CoordinateType GetCoordinateType(string input, out MapPoint point)
{
point = null;
// DD
CoordinateDD dd;
if (CoordinateDD.TryParse(input, out dd, true))
{
point = QueuedTask.Run(() =>
{
ArcGIS.Core.Geometry.SpatialReference sptlRef = SpatialReferenceBuilder.CreateSpatialReference(4326);
return MapPointBuilder.CreateMapPoint(dd.Lon, dd.Lat, sptlRef);
}).Result;
return CoordinateType.DD;
}
// DDM
CoordinateDDM ddm;
if (CoordinateDDM.TryParse(input, out ddm, true))
{
dd = new CoordinateDD(ddm);
point = QueuedTask.Run(() =>
{
ArcGIS.Core.Geometry.SpatialReference sptlRef = SpatialReferenceBuilder.CreateSpatialReference(4326);
return MapPointBuilder.CreateMapPoint(dd.Lon, dd.Lat, sptlRef);
}).Result;
return CoordinateType.DDM;
}
// DMS
CoordinateDMS dms;
if (CoordinateDMS.TryParse(input, out dms, true))
{
dd = new CoordinateDD(dms);
point = QueuedTask.Run(() =>
{
ArcGIS.Core.Geometry.SpatialReference sptlRef = SpatialReferenceBuilder.CreateSpatialReference(4326);
return MapPointBuilder.CreateMapPoint(dd.Lon, dd.Lat, sptlRef);
}).Result;
return CoordinateType.DMS;
}
CoordinateGARS gars;
if (CoordinateGARS.TryParse(input, out gars))
{
try
{
point = QueuedTask.Run(() =>
{
return convertToMapPoint(gars, GeoCoordinateType.GARS);
}).Result;
return CoordinateType.GARS;
}
catch { /* Conversion Failed */ }
}
CoordinateMGRS mgrs;
if (CoordinateMGRS.TryParse(input, out mgrs))
{
try
{
point = QueuedTask.Run(() =>
{
return convertToMapPoint(mgrs, GeoCoordinateType.MGRS);
}).Result;
return CoordinateType.MGRS;
}
catch { /* Conversion Failed */ }
}
CoordinateUSNG usng;
if (CoordinateUSNG.TryParse(input, out usng))
{
try
{
point = QueuedTask.Run(() =>
{
return convertToMapPoint(usng, GeoCoordinateType.USNG);
}).Result;
return CoordinateType.USNG;
}
catch { /* Conversion Failed */ }
}
CoordinateUTM utm;
if (CoordinateUTM.TryParse(input, out utm))
{
try
{
point = QueuedTask.Run(() =>
{
return convertToMapPoint(utm, GeoCoordinateType.UTM);
}).Result;
return CoordinateType.UTM;
}
catch { /* Conversion Failed */ }
}
Regex regexMercator = new Regex(@"^(?<latitude>\-?\d+[.,]?\d*)[+,;:\s]*(?<longitude>\-?\d+[.,]?\d*)");
var matchMercator = regexMercator.Match(input);
if (matchMercator.Success && matchMercator.Length == input.Length)
{
try
{
var Lat = Double.Parse(matchMercator.Groups["latitude"].Value);
var Lon = Double.Parse(matchMercator.Groups["longitude"].Value);
var sr = proCoordGetter.Point != null ? proCoordGetter.Point.SpatialReference : SpatialReferences.WebMercator;
point = QueuedTask.Run(() =>
{
return MapPointBuilder.CreateMapPoint(Lon, Lat, sr);
}).Result;
return CoordinateType.DD;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Failed to convert coordinate: " + ex.Message);
return CoordinateType.Unknown;
}
}
return CoordinateType.Unknown;
}
private CCCoordinate GetCoordinateType(string input)
{
MapPoint point = null;
// DD
CoordinateDD dd;
if (CoordinateDD.TryParse(input, out dd, true))
{
if (dd.Lat > 90 || dd.Lat < -90 || dd.Lon > 180 || dd.Lon < -180)
return new CCCoordinate() { Type = CoordinateType.Unknown, Point = null };
point = QueuedTask.Run(() =>
{
ArcGIS.Core.Geometry.SpatialReference sptlRef = SpatialReferenceBuilder.CreateSpatialReference(4326);
return MapPointBuilder.CreateMapPoint(dd.Lon, dd.Lat, sptlRef);
}).Result;
return new CCCoordinate() { Type = CoordinateType.DD, Point = point };
}
// DDM
CoordinateDDM ddm;
if (CoordinateDDM.TryParse(input, out ddm, true))
{
dd = new CoordinateDD(ddm);
if (dd.Lat > 90 || dd.Lat < -90 || dd.Lon > 180 || dd.Lon < -180)
return new CCCoordinate() { Type = CoordinateType.Unknown, Point = null };
point = QueuedTask.Run(() =>
{
ArcGIS.Core.Geometry.SpatialReference sptlRef = SpatialReferenceBuilder.CreateSpatialReference(4326);
return MapPointBuilder.CreateMapPoint(dd.Lon, dd.Lat, sptlRef);
}).Result;
return new CCCoordinate() { Type = CoordinateType.DDM, Point = point };
}
// DMS
CoordinateDMS dms;
if (CoordinateDMS.TryParse(input, out dms, true))
{
dd = new CoordinateDD(dms);
if (dd.Lat > 90 || dd.Lat < -90 || dd.Lon > 180 || dd.Lon < -180)
return new CCCoordinate() { Type = CoordinateType.Unknown, Point = null };
point = QueuedTask.Run(() =>
{
ArcGIS.Core.Geometry.SpatialReference sptlRef = SpatialReferenceBuilder.CreateSpatialReference(4326);
return MapPointBuilder.CreateMapPoint(dd.Lon, dd.Lat, sptlRef);
}).Result;
return new CCCoordinate() { Type = CoordinateType.DMS, Point = point };
}
CoordinateGARS gars;
if (CoordinateGARS.TryParse(input, out gars))
{
try
{
point = QueuedTask.Run(() =>
{
return convertToMapPoint(gars, GeoCoordinateType.GARS);
}).Result;
return new CCCoordinate() { Type = CoordinateType.GARS, Point = point };
}
catch { /* Conversion Failed */ }
}
CoordinateMGRS mgrs;
if (CoordinateMGRS.TryParse(input, out mgrs))
{
try
{
point = QueuedTask.Run(() =>
{
return convertToMapPoint(mgrs, GeoCoordinateType.MGRS);
}).Result;
return new CCCoordinate() { Type = CoordinateType.MGRS, Point = point };
}
catch { /* Conversion Failed */ }
}
CoordinateUSNG usng;
if (CoordinateUSNG.TryParse(input, out usng))
{
try
{
point = QueuedTask.Run(() =>
{
return convertToMapPoint(usng, GeoCoordinateType.USNG);
}).Result;
return new CCCoordinate() { Type = CoordinateType.USNG, Point = point }; ;
}
catch { /* Conversion Failed */ }
}
CoordinateUTM utm;
if (CoordinateUTM.TryParse(input, out utm))
{
try
{
point = QueuedTask.Run(() =>
{
return convertToMapPoint(utm, GeoCoordinateType.UTM);
}).Result;
return new CCCoordinate() { Type = CoordinateType.UTM, Point = point };
}
catch { /* Conversion Failed */ }
}
/*
* Updated RegEx to capture invalid coordinates like 00, 45, or 456987.
*/
Regex regexMercator = new Regex(@"^(?<latitude>\-?\d+[.,]?\d*)[+,;:\s]{1,}(?<longitude>\-?\d+[.,]?\d*)");
var matchMercator = regexMercator.Match(input);
if (matchMercator.Success && matchMercator.Length == input.Length)
{
try
{
var Lat = Double.Parse(matchMercator.Groups["latitude"].Value);
var Lon = Double.Parse(matchMercator.Groups["longitude"].Value);
var sr = proCoordGetter.Point != null ? proCoordGetter.Point.SpatialReference : SpatialReferences.WebMercator;
point = QueuedTask.Run(() =>
{
return MapPointBuilder.CreateMapPoint(Lon, Lat, sr);
}).Result;
return new CCCoordinate() { Type = CoordinateType.DD, Point = point };
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Failed to convert coordinate: " + ex.Message);
return new CCCoordinate() { Type = CoordinateType.Unknown, Point = null };
}
}
return new CCCoordinate() { Type = CoordinateType.Unknown, Point = null };
}
/// <summary>
/// Helper function to convert input coordinate to display coordinate. For example, input
/// coordinate can be in MGRS and display coordinate is in DD. This function helps with that
/// conversion
/// </summary>
/// <param name="cb">Coordinate notation type</param>
/// <param name="fromCoordinateType">Input coordinate notation type</param>
/// <returns></returns>
private MapPoint convertToMapPoint(CoordinateBase cb, GeoCoordinateType fromCoordinateType)
{
MapPoint retMapPoint = null;
//Create WGS84 SR
SpatialReference sptlRef = SpatialReferenceBuilder.CreateSpatialReference(4326);
var coordType = GeoCoordinateType.DD;
var succeed = Enum.TryParse(CoordinateConversionLibraryConfig.AddInConfig.DisplayCoordinateType.ToString(), out coordType);
if (succeed)
{
try
{
//Create map point from coordinate string
var fromCoord = MapPointBuilder.FromGeoCoordinateString(cb.ToString(), sptlRef, fromCoordinateType);
var geoCoordParam = new ToGeoCoordinateParameter(coordType);
var geoStr = fromCoord.ToGeoCoordinateString(geoCoordParam);
//Convert to map point with correct coordinate notation
retMapPoint = MapPointBuilder.FromGeoCoordinateString(geoStr, sptlRef, coordType);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
else
{
IFormatProvider coordinateFormatter = null;
switch (fromCoordinateType)
{
case GeoCoordinateType.GARS:
coordinateFormatter = new CoordinateGARSFormatter();
break;
case GeoCoordinateType.MGRS:
coordinateFormatter = new CoordinateMGRSFormatter();
break;
case GeoCoordinateType.USNG:
coordinateFormatter = new CoordinateMGRSFormatter();
break;
case GeoCoordinateType.UTM:
coordinateFormatter = new CoordinateUTMFormatter();
break;
default:
Console.WriteLine("Unable to determine coordinate type");
break;
};
retMapPoint = MapPointBuilder.FromGeoCoordinateString(cb.ToString("", coordinateFormatter), sptlRef, fromCoordinateType, FromGeoCoordinateMode.Default);
}
return retMapPoint;
}
#endregion Private Methods
#region Public Static Methods
public static void ShowAmbiguousEventHandler(object sender, AmbiguousEventArgs e)
{
if (e.IsEventHandled)
{
var ambiguous = new ProAmbiguousCoordsView();
var ambiguousVM = new ProAmbiguousCoordsViewModel();
ambiguous.DataContext = ambiguousVM;
ambiguous.ShowDialog();
CoordinateConversionLibraryConfig.AddInConfig.isLatLong = ambiguousVM.CheckedLatLon;
e.IsEventHandled = false;
}
}
#endregion
}
public class CCCoordinate
{
public CCCoordinate() { }
public CoordinateType Type { get; set; }
public MapPoint Point { get; set; }
public CoordinateBase PointInformation { get; set; }
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// 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.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Egl
{
/// <summary>
/// [EGL] Value of EGL_OBJECT_THREAD_KHR symbol.
/// </summary>
[RequiredByFeature("EGL_KHR_debug")]
public const int OBJECT_THREAD_KHR = 0x33B0;
/// <summary>
/// [EGL] Value of EGL_OBJECT_DISPLAY_KHR symbol.
/// </summary>
[RequiredByFeature("EGL_KHR_debug")]
public const int OBJECT_DISPLAY_KHR = 0x33B1;
/// <summary>
/// [EGL] Value of EGL_OBJECT_CONTEXT_KHR symbol.
/// </summary>
[RequiredByFeature("EGL_KHR_debug")]
public const int OBJECT_CONTEXT_KHR = 0x33B2;
/// <summary>
/// [EGL] Value of EGL_OBJECT_SURFACE_KHR symbol.
/// </summary>
[RequiredByFeature("EGL_KHR_debug")]
public const int OBJECT_SURFACE_KHR = 0x33B3;
/// <summary>
/// [EGL] Value of EGL_OBJECT_IMAGE_KHR symbol.
/// </summary>
[RequiredByFeature("EGL_KHR_debug")]
public const int OBJECT_IMAGE_KHR = 0x33B4;
/// <summary>
/// [EGL] Value of EGL_OBJECT_SYNC_KHR symbol.
/// </summary>
[RequiredByFeature("EGL_KHR_debug")]
public const int OBJECT_SYNC_KHR = 0x33B5;
/// <summary>
/// [EGL] Value of EGL_OBJECT_STREAM_KHR symbol.
/// </summary>
[RequiredByFeature("EGL_KHR_debug")]
public const int OBJECT_STREAM_KHR = 0x33B6;
/// <summary>
/// [EGL] Value of EGL_DEBUG_MSG_CRITICAL_KHR symbol.
/// </summary>
[RequiredByFeature("EGL_KHR_debug")]
public const int DEBUG_MSG_CRITICAL_KHR = 0x33B9;
/// <summary>
/// [EGL] Value of EGL_DEBUG_MSG_ERROR_KHR symbol.
/// </summary>
[RequiredByFeature("EGL_KHR_debug")]
public const int DEBUG_MSG_ERROR_KHR = 0x33BA;
/// <summary>
/// [EGL] Value of EGL_DEBUG_MSG_WARN_KHR symbol.
/// </summary>
[RequiredByFeature("EGL_KHR_debug")]
public const int DEBUG_MSG_WARN_KHR = 0x33BB;
/// <summary>
/// [EGL] Value of EGL_DEBUG_MSG_INFO_KHR symbol.
/// </summary>
[RequiredByFeature("EGL_KHR_debug")]
public const int DEBUG_MSG_INFO_KHR = 0x33BC;
/// <summary>
/// [EGL] Value of EGL_DEBUG_CALLBACK_KHR symbol.
/// </summary>
[RequiredByFeature("EGL_KHR_debug")]
public const int DEBUG_CALLBACK_KHR = 0x33B8;
/// <summary>
/// [EGL] eglDebugMessageControlKHR: Binding for eglDebugMessageControlKHR.
/// </summary>
/// <param name="callback">
/// A <see cref="T:DebugProcKHR"/>.
/// </param>
/// <param name="attrib_list">
/// A <see cref="T:IntPtr[]"/>.
/// </param>
[RequiredByFeature("EGL_KHR_debug")]
public static int KHR(DebugProcKHR callback, IntPtr[] attrib_list)
{
int retValue;
unsafe {
fixed (IntPtr* p_attrib_list = attrib_list)
{
Debug.Assert(Delegates.peglDebugMessageControlKHR != null, "peglDebugMessageControlKHR not implemented");
retValue = Delegates.peglDebugMessageControlKHR(callback, p_attrib_list);
LogCommand("eglDebugMessageControlKHR", retValue, callback, attrib_list );
}
}
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [EGL] eglQueryDebugKHR: Binding for eglQueryDebugKHR.
/// </summary>
/// <param name="attribute">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="value">
/// A <see cref="T:IntPtr[]"/>.
/// </param>
[RequiredByFeature("EGL_KHR_debug")]
public static bool QueryKHR(int attribute, IntPtr[] value)
{
bool retValue;
unsafe {
fixed (IntPtr* p_value = value)
{
Debug.Assert(Delegates.peglQueryDebugKHR != null, "peglQueryDebugKHR not implemented");
retValue = Delegates.peglQueryDebugKHR(attribute, p_value);
LogCommand("eglQueryDebugKHR", retValue, attribute, value );
}
}
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [EGL] eglLabelObjectKHR: Binding for eglLabelObjectKHR.
/// </summary>
/// <param name="display">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="objectType">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="object">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="label">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("EGL_KHR_debug")]
public static int KHR(IntPtr display, uint objectType, IntPtr @object, IntPtr label)
{
int retValue;
Debug.Assert(Delegates.peglLabelObjectKHR != null, "peglLabelObjectKHR not implemented");
retValue = Delegates.peglLabelObjectKHR(display, objectType, @object, label);
LogCommand("eglLabelObjectKHR", retValue, display, objectType, @object, label );
DebugCheckErrors(retValue);
return (retValue);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("EGL_KHR_debug")]
[SuppressUnmanagedCodeSecurity]
internal delegate int eglDebugMessageControlKHR(DebugProcKHR callback, IntPtr* attrib_list);
[RequiredByFeature("EGL_KHR_debug")]
internal static eglDebugMessageControlKHR peglDebugMessageControlKHR;
[RequiredByFeature("EGL_KHR_debug")]
[SuppressUnmanagedCodeSecurity]
internal delegate bool eglQueryDebugKHR(int attribute, IntPtr* value);
[RequiredByFeature("EGL_KHR_debug")]
internal static eglQueryDebugKHR peglQueryDebugKHR;
[RequiredByFeature("EGL_KHR_debug")]
[SuppressUnmanagedCodeSecurity]
internal delegate int eglLabelObjectKHR(IntPtr display, uint objectType, IntPtr @object, IntPtr label);
[RequiredByFeature("EGL_KHR_debug")]
internal static eglLabelObjectKHR peglLabelObjectKHR;
}
}
}
| |
//
// UnsynchronisedLyricsFrame.cs:
//
// Author:
// Patrick Laplante
//
// Original Source:
// TagLib.Id3v2.CommentsFrame
//
// Copyright (C) 2007 Brian Nickel (Original Implementation)
// Copyright (C) 2002,2003 Scott Wheeler (Original Implementation)
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// 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
//
using System;
using System.Collections.Generic;
using System.Text;
using TagLib.Id3v2;
namespace TagLib.Id3v2
{
/// <summary>
/// This class extends <see cref="Frame" />, implementing support for
/// ID3v2 Unsynchronised Lyrics (USLT) Frames.
/// </summary>
public class UnsynchronisedLyricsFrame : Frame
{
#region Private Properties
/// <summary>
/// Contains the text encoding to use when rendering the
/// current instance.
/// </summary>
private StringType encoding = Tag.DefaultEncoding;
/// <summary>
/// Contains the ISO-639-2 language code of the current
/// instance.
/// </summary>
private string language = null;
/// <summary>
/// Contains the description of the current instance.
/// </summary>
private string description = null;
/// <summary>
/// Contains the lyrics text of the current instance.
/// </summary>
private string text = null;
#endregion
#region Constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="UnsynchronisedLyricsFrame" /> with a specified
/// description, ISO-639-2 language code, and text encoding.
/// </summary>
/// <param name="description">
/// A <see cref="string" /> containing the description of the
/// new frame.
/// </param>
/// <param name="language">
/// A <see cref="string" /> containing the ISO-639-2 language
/// code of the new frame.
/// </param>
/// <param name="encoding">
/// A <see cref="StringType" /> containing the text encoding
/// to use when rendering the new frame.
/// </param>
/// <remarks>
/// When a frame is created, it is not automatically added to
/// the tag. Consider using <see cref="Get" /> for more
/// integrated frame creation.
/// </remarks>
public UnsynchronisedLyricsFrame (string description,
string language,
StringType encoding)
: base (FrameType.USLT, 4)
{
this.encoding = encoding;
this.language = language;
this.description = description;
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="UnsynchronisedLyricsFrame" /> with a specified
/// description and ISO-639-2 language code.
/// </summary>
/// <param name="description">
/// A <see cref="string" /> containing the description of the
/// new frame.
/// </param>
/// <param name="language">
/// A <see cref="string" /> containing the ISO-639-2 language
/// code of the new frame.
/// </param>
/// <remarks>
/// When a frame is created, it is not automatically added to
/// the tag. Consider using <see cref="Get" /> for more
/// integrated frame creation.
/// </remarks>
public UnsynchronisedLyricsFrame (string description,
string language)
: this (description, language,
TagLib.Id3v2.Tag.DefaultEncoding)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="UnsynchronisedLyricsFrame" /> with a specified
/// description.
/// </summary>
/// <param name="description">
/// A <see cref="string" /> containing the description of the
/// new frame.
/// </param>
/// <remarks>
/// When a frame is created, it is not automatically added to
/// the tag. Consider using <see cref="Get" /> for more
/// integrated frame creation.
/// </remarks>
public UnsynchronisedLyricsFrame (string description)
: this (description, null)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="UnsynchronisedLyricsFrame" /> by reading its raw
/// data in a specified ID3v2 version.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object starting with the raw
/// representation of the new frame.
/// </param>
/// <param name="version">
/// A <see cref="byte" /> indicating the ID3v2 version the
/// raw frame is encoded in.
/// </param>
public UnsynchronisedLyricsFrame (ByteVector data, byte version)
: base(data, version)
{
SetData (data, 0, version, true);
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="UnsynchronisedLyricsFrame" /> by reading its raw
/// data in a specified ID3v2 version.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object containing the raw
/// representation of the new frame.
/// </param>
/// <param name="offset">
/// A <see cref="int" /> indicating at what offset in
/// <paramref name="data" /> the frame actually begins.
/// </param>
/// <param name="header">
/// A <see cref="FrameHeader" /> containing the header of the
/// frame found at <paramref name="offset" /> in the data.
/// </param>
/// <param name="version">
/// A <see cref="byte" /> indicating the ID3v2 version the
/// raw frame is encoded in.
/// </param>
protected internal UnsynchronisedLyricsFrame (ByteVector data,
int offset,
FrameHeader header,
byte version)
: base(header)
{
SetData (data, offset, version, false);
}
#endregion
#region Public Properties
/// <summary>
/// Gets and sets the text encoding to use when storing the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the text encoding to
/// use when storing the current instance.
/// </value>
/// <remarks>
/// This encoding is overridden when rendering if <see
/// cref="Tag.ForceDefaultEncoding" /> is <see
/// langword="true" /> or the render version does not support
/// it.
/// </remarks>
public StringType TextEncoding {
get {return encoding;}
set {encoding = value;}
}
/// <summary>
/// Gets and sets the ISO-639-2 language code stored in the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the ISO-639-2 language
/// code stored in the current instance.
/// </value>
/// <remarks>
/// There should only be one file with a matching description
/// and ISO-639-2 language code per tag.
/// </remarks>
public string Language {
get {
if (language != null && language.Length > 2)
return language.Substring (0, 3);
return "XXX";
}
set {language = value;}
}
/// <summary>
/// Gets and sets the description stored in the current
/// instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the description
/// stored in the current instance.
/// </value>
/// <remarks>
/// There should only be one frame with a matching
/// description and ISO-639-2 language code per tag.
/// </remarks>
public string Description {
get {
if (description != null)
return description;
return string.Empty;
}
set {description = value;}
}
/// <summary>
/// Gets and sets the lyrical text stored in the current
/// instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the lyrical text
/// stored in the current instance.
/// </value>
public string Text {
get {
if (text != null)
return text;
return string.Empty;
}
set {text = value;}
}
#endregion
#region Public Methods
/// <summary>
/// Gets a string representation of the current instance.
/// </summary>
/// <returns>
/// A <see cref="string" /> containing the lyrical text.
/// </returns>
public override string ToString ()
{
return Text;
}
#endregion
#region Public Static Methods
/// <summary>
/// Gets a specified lyrics frame from the specified tag,
/// optionally creating it if it does not exist.
/// </summary>
/// <param name="tag">
/// A <see cref="Tag" /> object to search in.
/// </param>
/// <param name="description">
/// A <see cref="string" /> specifying the description to
/// match.
/// </param>
/// <param name="language">
/// A <see cref="string" /> specifying the ISO-639-2 language
/// code to match.
/// </param>
/// <param name="create">
/// A <see cref="bool" /> specifying whether or not to create
/// and add a new frame to the tag if a match is not found.
/// </param>
/// <returns>
/// A <see cref="UnsynchronisedLyricsFrame" /> object
/// containing the matching frame, or <see langword="null" />
/// if a match wasn't found and <paramref name="create" /> is
/// <see langword="false" />.
/// </returns>
public static UnsynchronisedLyricsFrame Get (Tag tag,
string description,
string language,
bool create)
{
UnsynchronisedLyricsFrame uslt;
foreach (Frame frame in tag.GetFrames (FrameType.USLT)) {
uslt = frame as UnsynchronisedLyricsFrame;
if (uslt == null)
continue;
if (uslt.Description != description)
continue;
if (language != null && language != uslt.Language)
continue;
return uslt;
}
if (!create)
return null;
uslt = new UnsynchronisedLyricsFrame (description,
language);
tag.AddFrame (uslt);
return uslt;
}
/// <summary>
/// Gets a specified comments frame from the specified tag,
/// trying to to match the description and language but
/// accepting an incomplete match.
/// </summary>
/// <param name="tag">
/// A <see cref="Tag" /> object to search in.
/// </param>
/// <param name="description">
/// A <see cref="string" /> specifying the description to
/// match.
/// </param>
/// <param name="language">
/// A <see cref="string" /> specifying the ISO-639-2 language
/// code to match.
/// </param>
/// <returns>
/// A <see cref="UnsynchronisedLyricsFrame" /> object
/// containing the matching frame, or <see langword="null" />
/// if a match wasn't found.
/// </returns>
/// <remarks>
/// <para>The method tries matching with the following order
/// of precidence:</para>
/// <list type="number">
/// <item><term>The first frame with a matching
/// description and language.</term></item>
/// <item><term>The first frame with a matching
/// language.</term></item>
/// <item><term>The first frame with a matching
/// description.</term></item>
/// <item><term>The first frame.</term></item>
/// </list>
/// </remarks>
public static UnsynchronisedLyricsFrame GetPreferred (Tag tag,
string description,
string language)
{
// This is weird, so bear with me. The best thing we can
// have is something straightforward and in our own
// language. If it has a description, then it is
// probably used for something other than an actual
// comment. If that doesn't work, we'd still rather have
// something in our language than something in another.
// After that all we have left are things in other
// languages, so we'd rather have one with actual
// content, so we try to get one with no description
// first.
int best_value = -1;
UnsynchronisedLyricsFrame best_frame = null;
foreach (Frame frame in tag.GetFrames (FrameType.USLT)) {
UnsynchronisedLyricsFrame uslt =
frame as UnsynchronisedLyricsFrame;
if (uslt == null)
continue;
bool same_name = uslt.Description == description;
bool same_lang = uslt.Language == language;
if (same_name && same_lang)
return uslt;
int value = same_lang ? 2 : same_name ? 1 : 0;
if (value <= best_value)
continue;
best_value = value;
best_frame = uslt;
}
return best_frame;
}
#endregion
#region Protected Methods
/// <summary>
/// Populates the values in the current instance by parsing
/// its field data in a specified version.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object containing the
/// extracted field data.
/// </param>
/// <param name="version">
/// A <see cref="byte" /> indicating the ID3v2 version the
/// field data is encoded in.
/// </param>
protected override void ParseFields (ByteVector data,
byte version)
{
if (data.Count < 4)
throw new CorruptFileException (
"Not enough bytes in field.");
encoding = (StringType) data [0];
language = data.ToString (StringType.Latin1, 1, 3);
string [] split = data.ToStrings (encoding, 4, 2);
if (split.Length == 1) {
// Bad lyrics frame. Assume that it lacks a
// description.
description = String.Empty;
text = split [0];
} else {
description = split [0];
text = split [1];
}
}
/// <summary>
/// Renders the values in the current instance into field
/// data for a specified version.
/// </summary>
/// <param name="version">
/// A <see cref="byte" /> indicating the ID3v2 version the
/// field data is to be encoded in.
/// </param>
/// <returns>
/// A <see cref="ByteVector" /> object containing the
/// rendered field data.
/// </returns>
protected override ByteVector RenderFields(byte version)
{
StringType encoding = CorrectEncoding (TextEncoding,
version);
ByteVector v = new ByteVector();
v.Add ((byte) encoding);
v.Add (ByteVector.FromString (Language, StringType.Latin1));
v.Add (ByteVector.FromString (description, encoding));
v.Add (ByteVector.TextDelimiter(encoding));
v.Add (ByteVector.FromString (text, encoding));
return v;
}
#endregion
#region ICloneable
/// <summary>
/// Creates a deep copy of the current instance.
/// </summary>
/// <returns>
/// A new <see cref="Frame" /> object identical to the
/// current instance.
/// </returns>
public override Frame Clone ()
{
UnsynchronisedLyricsFrame frame =
new UnsynchronisedLyricsFrame (description,
language, encoding);
frame.text = text;
return frame;
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
using System.Text;
using log4net;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
using System.Text.RegularExpressions;
namespace PCSComUtils.Common.DS
{
/// <summary>
/// Summary description for UtilsDS.
/// </summary>
public class UtilsDS
{
private ILog _logger = LogManager.GetLogger(typeof(UtilsDS));
private const string THIS = "PCSComUtils.Common.DS.UtilsDS";
/// <summary>
/// Get comma-separated list of In stock tranaction type ID
/// </summary>
/// <returns></returns>
/// <author> Tuan TQ. 28 Dec, 2005</author>
public string GetInStockTransTypeID()
{
string strInStockIDs = "0";
string strSQL = "SELECT " + MST_TranTypeTable.TRANTYPEID_FLD + " FROM " + MST_TranTypeTable.TABLE_NAME;
strSQL += " WHERE " + MST_TranTypeTable.TYPE_FLD + "=" + (int)TransactionHistoryType.In + " OR " + MST_TranTypeTable.TYPE_FLD + "=" + (int)TransactionHistoryType.Both ;
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSQL, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, MST_TranTypeTable.TABLE_NAME);
if(dstPCS.Tables[MST_TranTypeTable.TABLE_NAME].Rows.Count != 0)
{
for(int i =0; i < dstPCS.Tables[MST_TranTypeTable.TABLE_NAME].Rows.Count; i++)
{
strInStockIDs += ", " + dstPCS.Tables[MST_TranTypeTable.TABLE_NAME].Rows[i][MST_TranTypeTable.TRANTYPEID_FLD].ToString();
}
}
return strInStockIDs;
}
/// <summary>
/// Get comma-separated list of Out stock tranaction type ID
/// </summary>
/// <returns></returns>
/// <author> Tuan TQ. 28 Dec, 2005</author>
public string GetOutStockTransTypeID()
{
string strOutStockIDs = "0";
string strSQL = "SELECT " + MST_TranTypeTable.TRANTYPEID_FLD + " FROM " + MST_TranTypeTable.TABLE_NAME;
strSQL += " WHERE " + MST_TranTypeTable.TYPE_FLD + "=" + (int)TransactionHistoryType.Out;
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSQL, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, MST_TranTypeTable.TABLE_NAME);
if(dstPCS.Tables[MST_TranTypeTable.TABLE_NAME].Rows.Count != 0)
{
for(int i =0; i < dstPCS.Tables[MST_TranTypeTable.TABLE_NAME].Rows.Count; i++)
{
strOutStockIDs += ", " + dstPCS.Tables[MST_TranTypeTable.TABLE_NAME].Rows[i][MST_TranTypeTable.TRANTYPEID_FLD].ToString();
}
}
return strOutStockIDs;
}
public DateTime GetDBDate()
{
const string METHOD_NAME = THIS + ".GetDBDate()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
string strSql = String.Empty;
strSql= " SELECT getdate() ";
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.CommandTimeout = 10000;
ocmdPCS.Connection.Open();
return (DateTime)ocmdPCS.ExecuteScalar();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public string GetNoByMask(string strTableName,string strFieldName,DateTime dtEntryDate, string strFormat)
{
const string METHOD_NAME = THIS + ".GetNoByMask()";
const string DATE_STRING_SHORT = "D";
const string DATE_STRING_FULL = "DD";
const string MONTH_STRING_SHORT = "M";
const string MONTH_STRING_FULL = "MM";
const string YEAR_STRING_SHORT = "YY";
const string YEAR_STRING_FULL = "YYYY";
if (strFormat == String.Empty)
{
strFormat ="YYYYMMDD0000";
}
else
{
//strFormat = strFormat.ToUpper();
//get FormatType from Database
Sys_ParamDS objSys_ParamDS = new Sys_ParamDS();
strFormat = objSys_ParamDS.GetNameValue(strFormat);
if (strFormat == String.Empty)
{
strFormat ="YYYYMMDD0000";
}
}
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
string strFormat_Type = strFormat.Substring(0,strFormat.IndexOf("0"));
string strFormat_Number = strFormat.Substring(strFormat.IndexOf("0"));
//Replace the format_type with real value
//1.Year
if (strFormat_Type.IndexOf(YEAR_STRING_FULL) >= 0)
{
strFormat_Type = strFormat_Type.Replace(YEAR_STRING_FULL,dtEntryDate.Year.ToString());
}
else
{
if (strFormat_Type.IndexOf(YEAR_STRING_SHORT) >= 0)
{
strFormat_Type = strFormat_Type.Replace(YEAR_STRING_SHORT,dtEntryDate.Year.ToString().Substring(2));
}
}
//2.Month
if (strFormat_Type.IndexOf(MONTH_STRING_FULL) >= 0)
{
strFormat_Type = strFormat_Type.Replace(MONTH_STRING_FULL,dtEntryDate.Month.ToString().PadLeft(2,'0'));
}
else
{
if (strFormat_Type.IndexOf(MONTH_STRING_SHORT) >= 0)
{
strFormat_Type = strFormat_Type.Replace(MONTH_STRING_SHORT,dtEntryDate.Month.ToString());
}
}
//3.Day
if (strFormat_Type.IndexOf(DATE_STRING_FULL) >= 0)
{
strFormat_Type = strFormat_Type.Replace(DATE_STRING_FULL,dtEntryDate.Day.ToString().PadLeft(2,'0'));
}
else
{
if (strFormat_Type.IndexOf(DATE_STRING_SHORT) >= 0)
{
strFormat_Type = strFormat_Type.Replace(DATE_STRING_SHORT,dtEntryDate.Day.ToString());
}
}
strFormat = strFormat_Type + strFormat_Number;
string strYearMonthDay = dtEntryDate.Year.ToString() + dtEntryDate.Month.ToString().PadLeft(2,'0') + dtEntryDate.Day.ToString().PadLeft(2,'0');
string strSql = String.Empty;
strSql = " SELECT max(" + strFieldName + ")" ;
strSql += " FROM " + strTableName ;
strSql += " WHERE " + strFieldName + " like '"+ strFormat_Type + "%'" ;
//strSql += " WHERE " + strFieldName + " like '"+ strYearMonthDay + "%'" ;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
if (objResult == DBNull.Value)
{
//return strFormat.Replace(strFormat_Number,"1".PadLeft(strFormat_Number.Length,'0'));
strFormat_Number = "1".PadLeft(strFormat_Number.Length,'0');
strFormat = strFormat_Type + strFormat_Number;
return strFormat;
}
string strMaxValue = objResult.ToString().Trim();
string strResult = strFormat_Type;
int intNumberLength = strFormat_Number.Length;
if (strMaxValue == String.Empty)
{
strResult += "1".PadLeft(intNumberLength,'0');
}
else
{
int intNextValue = 0;
try
{
intNextValue = int.Parse(strMaxValue.Substring(strFormat_Type.Length+1)) + 1;
}
catch
{
intNextValue = 1;
}
strResult += intNextValue.ToString().PadLeft(intNumberLength,'0');
}
return strResult;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// GetNoByMask new
/// </summary>
/// <param name="tableName"></param>
/// <param name="fieldName"></param>
/// <param name="prefix"></param>
/// <param name="format"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Wednesday, Dec 7 2005</date>
public string GetNoByMask(string tableName, string fieldName, string prefix, string format)
{
const string DATE_STRING_SHORT = "D";
const string DATE_STRING_FULL = "DD";
const string MONTH_STRING_SHORT = "M";
const string MONTH_STRING_FULL = "MM";
const string YEAR_STRING_SHORT = "YY";
const string YEAR_STRING_FULL = "YYYY";
format = format == String.Empty ? "YYYYMMDD####" : format.ToUpper();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
//Get Date from Server
DateTime dtEntryDate = new DateTime();
dtEntryDate = GetDBDate();
string strFormat_Type = string.Empty;
//strFormat_Type += pstrPrefix;
strFormat_Type += format.Substring(0,format.IndexOf("#"));
string strFormat_Number = format.Substring(format.IndexOf("#"));
//Replace the format_type with real value
//1.Year
if (strFormat_Type.IndexOf(YEAR_STRING_FULL) >= 0)
{
strFormat_Type = strFormat_Type.Replace(YEAR_STRING_FULL,dtEntryDate.Year.ToString());
}
else
{
if (strFormat_Type.IndexOf(YEAR_STRING_SHORT) >= 0)
{
strFormat_Type = strFormat_Type.Replace(YEAR_STRING_SHORT,dtEntryDate.Year.ToString().Substring(2));
}
}
//2.Month
if (strFormat_Type.IndexOf(MONTH_STRING_FULL) >= 0)
{
strFormat_Type = strFormat_Type.Replace(MONTH_STRING_FULL,dtEntryDate.Month.ToString().PadLeft(2,'0'));
}
else
{
if (strFormat_Type.IndexOf(MONTH_STRING_SHORT) >= 0)
{
strFormat_Type = strFormat_Type.Replace(MONTH_STRING_SHORT,dtEntryDate.Month.ToString());
}
}
//3.Day
if (strFormat_Type.IndexOf(DATE_STRING_FULL) >= 0)
{
strFormat_Type = strFormat_Type.Replace(DATE_STRING_FULL,dtEntryDate.Day.ToString().PadLeft(2,'0'));
}
else
{
if (strFormat_Type.IndexOf(DATE_STRING_SHORT) >= 0)
{
strFormat_Type = strFormat_Type.Replace(DATE_STRING_SHORT,dtEntryDate.Day.ToString());
}
}
strFormat_Type = prefix + strFormat_Type;
string strSql = String.Empty;
strSql = " SELECT max(" + fieldName + ")" ;
strSql += " FROM " + tableName ;
strSql += " WHERE " + fieldName + " like '"+ strFormat_Type + "%'" ;
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
if (objResult == DBNull.Value)
{
strFormat_Number = "1".PadLeft(strFormat_Number.Length,'0');
format = strFormat_Type + strFormat_Number;
return format;
}
string strMaxValue = objResult.ToString().Trim();
string strResult = strFormat_Type;
int intNumberLength = strFormat_Number.Length;
if (strMaxValue == String.Empty)
{
strResult += "1".PadLeft(intNumberLength,'0');
}
else
{
int intNextValue = 0;
try
{
intNextValue = int.Parse(strMaxValue.Substring(strFormat_Type.Length)) + 1;
}
catch
{
intNextValue = 1;
}
strResult += intNextValue.ToString().PadLeft(intNumberLength,'0');
}
return strResult;
}
catch
{
// Standard value incase unknown error
return DateTime.Now.ToString("yyyyMMdd") + "0001";
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// Generates transaction number from mask and entry date
/// </summary>
/// <param name="tableName"></param>
/// <param name="fieldName"></param>
/// <param name="prefix"></param>
/// <param name="format"></param>
/// <param name="entryDate"></param>
/// <returns></returns>
public string GetNoByMask(string tableName, string fieldName, string prefix, string format, DateTime entryDate, out int revision)
{
const string dateStringShort = "D";
const string dateStringFull = "DD";
const string monthStringShort = "M";
const string monthStringFull = "MM";
const string yearStringShort = "YY";
const string yearStringFull = "YYYY";
format = format == String.Empty ? "YYYYMMDD####" : format.ToUpper();
revision = 1;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS;
try
{
string formatType = format.Substring(0, format.IndexOf("#"));
string formatNumber = format.Substring(format.IndexOf("#"));
//Replace the format_type with real value
//1.Year
if (formatType.IndexOf(yearStringFull) >= 0)
{
formatType = formatType.Replace(yearStringFull, entryDate.Year.ToString());
}
else
{
if (formatType.IndexOf(yearStringShort) >= 0)
{
formatType = formatType.Replace(yearStringShort, entryDate.Year.ToString().Substring(2));
}
}
//2.Month
if (formatType.IndexOf(monthStringFull) >= 0)
{
formatType = formatType.Replace(monthStringFull, entryDate.Month.ToString().PadLeft(2, '0'));
}
else
{
if (formatType.IndexOf(monthStringShort) >= 0)
{
formatType = formatType.Replace(monthStringShort, entryDate.Month.ToString());
}
}
//3.Day
if (formatType.IndexOf(dateStringFull) >= 0)
{
formatType = formatType.Replace(dateStringFull, entryDate.Day.ToString().PadLeft(2, '0'));
}
else
{
if (formatType.IndexOf(dateStringShort) >= 0)
{
formatType = formatType.Replace(dateStringShort, entryDate.Day.ToString());
}
}
formatType = prefix + formatType;
string sql = " SELECT max(" + fieldName + ")";
sql += " FROM " + tableName;
sql += " WHERE " + fieldName + " LIKE '" + formatType + "%'";
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(sql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
if (objResult == DBNull.Value)
{
formatNumber = "1".PadLeft(formatNumber.Length, '0');
format = formatType + formatNumber;
return format;
}
string strMaxValue = objResult.ToString().Trim();
string strResult = formatType;
int intNumberLength = formatNumber.Length;
if (strMaxValue == String.Empty)
{
strResult += "1".PadLeft(intNumberLength, '0');
}
else
{
int intNextValue = 0;
try
{
intNextValue = int.Parse(strMaxValue.Substring(formatType.Length)) + 1;
}
catch
{
intNextValue = 1;
}
revision = intNextValue;
strResult += intNextValue.ToString().PadLeft(intNumberLength, '0');
}
return strResult;
}
catch
{
// Standard value incase unknown error
return DateTime.Now.ToString("yyyyMMdd") + "0001";
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public string GetNoByMask(string pstrUsername, string pstrTableName,string pstrFieldName,string pstrPrefix, string pstrFormat)
{
const string DATE_STRING_SHORT = "D";
const string DATE_STRING_FULL = "DD";
const string MONTH_STRING_SHORT = "M";
const string MONTH_STRING_FULL = "MM";
const string YEAR_STRING_SHORT = "YY";
const string YEAR_STRING_FULL = "YYYY";
pstrFormat = pstrFormat == String.Empty ? "YYYYMMDD####" : pstrFormat.ToUpper();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
//Get Date from Server
DateTime dtEntryDate = new DateTime();
dtEntryDate = GetDBDate();
string strFormat_Type = string.Empty;
//strFormat_Type += pstrPrefix;
strFormat_Type += pstrFormat.Substring(0,pstrFormat.IndexOf("#"));
string strFormat_Number = pstrFormat.Substring(pstrFormat.IndexOf("#"));
//Replace the format_type with real value
//1.Year
if (strFormat_Type.IndexOf(YEAR_STRING_FULL) >= 0)
{
strFormat_Type = strFormat_Type.Replace(YEAR_STRING_FULL,dtEntryDate.Year.ToString());
}
else
{
if (strFormat_Type.IndexOf(YEAR_STRING_SHORT) >= 0)
{
strFormat_Type = strFormat_Type.Replace(YEAR_STRING_SHORT,dtEntryDate.Year.ToString().Substring(2));
}
}
//2.Month
if (strFormat_Type.IndexOf(MONTH_STRING_FULL) >= 0)
{
strFormat_Type = strFormat_Type.Replace(MONTH_STRING_FULL,dtEntryDate.Month.ToString().PadLeft(2,'0'));
}
else
{
if (strFormat_Type.IndexOf(MONTH_STRING_SHORT) >= 0)
{
strFormat_Type = strFormat_Type.Replace(MONTH_STRING_SHORT,dtEntryDate.Month.ToString());
}
}
//3.Day
if (strFormat_Type.IndexOf(DATE_STRING_FULL) >= 0)
{
strFormat_Type = strFormat_Type.Replace(DATE_STRING_FULL,dtEntryDate.Day.ToString().PadLeft(2,'0'));
}
else
{
if (strFormat_Type.IndexOf(DATE_STRING_SHORT) >= 0)
{
strFormat_Type = strFormat_Type.Replace(DATE_STRING_SHORT,dtEntryDate.Day.ToString());
}
}
strFormat_Type = pstrUsername != ""
? pstrUsername + "-" + pstrPrefix + strFormat_Type
: pstrPrefix + strFormat_Type;
var strSql = " SELECT max(" + pstrFieldName + ")" ;
strSql += " FROM " + pstrTableName ;
strSql += " WHERE " + pstrFieldName + " like '"+ strFormat_Type + "%'" ;
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
if (objResult == DBNull.Value)
{
strFormat_Number = "1".PadLeft(strFormat_Number.Length,'0');
pstrFormat = strFormat_Type + strFormat_Number;
return pstrFormat;
}
string strMaxValue = objResult.ToString().Trim();
string strResult = strFormat_Type;
int intNumberLength = strFormat_Number.Length;
if (strMaxValue == String.Empty)
{
strResult += "1".PadLeft(intNumberLength,'0');
}
else
{
int intNextValue;
try
{
intNextValue = int.Parse(strMaxValue.Substring(strFormat_Type.Length)) + 1;
}
catch
{
intNextValue = 1;
}
strResult += intNextValue.ToString().PadLeft(intNumberLength,'0');
}
return strResult;
}
catch
{
// Standard value incase unknown error
return DateTime.Now.ToString("yyyyMMdd") + "0001";
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public bool IsTableOrViewConfigured(string pstrTableOrViewName)
{
bool blnRet = true;
return blnRet;
}
public DataTable GetRows(string pstrTableName, string pstrFieldName, string pstrFieldValue, Hashtable phashOtherConditions, string pstrConditionByRecord)
{
const string METHOD_NAME = THIS + ".GetRows()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = " SELECT * FROM " + pstrTableName + " WHERE 1=1 ";
if(pstrFieldName != null && pstrFieldValue != null)
{
if (pstrFieldName.Length > 0 && pstrFieldValue.Length > 0)
{
strSql += " AND (" + pstrFieldName + " like '" + pstrFieldValue + "%')";
}
}
if (phashOtherConditions != null)
{
IDictionaryEnumerator myEnumerator = phashOtherConditions.GetEnumerator();
while( myEnumerator.MoveNext() )
{
if(myEnumerator.Value == DBNull.Value)
{
strSql += " AND (" + pstrTableName + "." + myEnumerator.Key.ToString().Trim() + " IS NULL)";
}
else
{
strSql += " AND (" + pstrTableName + "." + myEnumerator.Key.ToString().Trim() + "='" + myEnumerator.Value + "')";
}
}
}
strSql += pstrConditionByRecord;
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,pstrTableName);
return dstPCS.Tables[0];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataTable GetRows(string pstrTableName, string pstrExpression)
{
const string METHOD_NAME = THIS + ".GetRows()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT * "
+ " FROM " + pstrTableName;
if ((pstrExpression.Trim() != string.Empty) && (pstrExpression != null))
strSql += " " + pstrExpression;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, pstrTableName);
return dstPCS.Tables[pstrTableName];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataTable GetRowsWithWhere(string pstrTableName, string pstrFieldName, string pstrFieldValue, string pstrWhereClause)
{
const string METHOD_NAME = THIS + ".GetRows()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT * "
+ " FROM " + pstrTableName;
if ((pstrWhereClause.Trim() != string.Empty) && (pstrWhereClause != null))
strSql += " " + pstrWhereClause;
if (pstrFieldName != null && pstrFieldName != String.Empty)
{
strSql += " AND " + pstrFieldName + " LIKE '" + pstrFieldValue + "%'";
}
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, pstrTableName);
return dstPCS.Tables[pstrTableName];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// Execute PO report and return data table
/// </summary>
/// <param name="pstrSql">Query string to be executed</param>
/// <returns>Result DataTable</returns>
public DataTable ExecutePOReport(ref string pstrSql, int pintPOMasterID)
{
const string METHOD_NAME = THIS + ".ExecutePOReport()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
pstrSql += " WHERE " + PO_PurchaseOrderMasterTable.TABLE_NAME + "." +
PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD + " = " + pintPOMasterID +
" ORDER BY DATEPART(d, " + PO_PurchaseOrderDetailTable.TABLE_NAME + "." + PO_PurchaseOrderDetailTable.REQUIREDDATE_FLD + ")";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(pstrSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS);
return dstPCS.Tables[0];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// Get working day in a year
/// </summary>
/// <param name="pintYear"></param>
/// <returns></returns>
public ArrayList GetWorkingDayByYear(int pintYear)
{
const string METHOD_NAME = THIS + ".GetWorkingDayByYear()";
DataSet dstPCS = new DataSet();
ArrayList arrDayOfWeek = new ArrayList();
OleDbConnection oconPCS = null;
try
{
string strSql = "SELECT "
+ MST_WorkingDayMasterTable.WORKINGDAYMASTERID_FLD + ","
+ MST_WorkingDayMasterTable.SUN_FLD + ","
+ MST_WorkingDayMasterTable.CCNID_FLD + ","
+ MST_WorkingDayMasterTable.YEAR_FLD + ","
+ MST_WorkingDayMasterTable.MON_FLD + ","
+ MST_WorkingDayMasterTable.TUE_FLD + ","
+ MST_WorkingDayMasterTable.WED_FLD + ","
+ MST_WorkingDayMasterTable.THU_FLD + ","
+ MST_WorkingDayMasterTable.FRI_FLD + ","
+ MST_WorkingDayMasterTable.SAT_FLD
+ " FROM " + MST_WorkingDayMasterTable.TABLE_NAME
+ " WHERE " + MST_WorkingDayMasterTable.YEAR_FLD + "=" + pintYear;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
OleDbCommand ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,MST_WorkingDayMasterTable.TABLE_NAME);
if(dstPCS != null)
{
if(dstPCS.Tables[0].Rows.Count != 0)
{
DataRow drow = dstPCS.Tables[0].Rows[0];
if(!bool.Parse(drow[MST_WorkingDayMasterTable.MON_FLD].ToString()))
{
arrDayOfWeek.Add(DayOfWeek.Monday);
}
if(!bool.Parse(drow[MST_WorkingDayMasterTable.TUE_FLD].ToString()))
{
arrDayOfWeek.Add(DayOfWeek.Tuesday);
}
if(!bool.Parse(drow[MST_WorkingDayMasterTable.WED_FLD].ToString()))
{
arrDayOfWeek.Add(DayOfWeek.Wednesday);
}
if(!bool.Parse(drow[MST_WorkingDayMasterTable.THU_FLD].ToString()))
{
arrDayOfWeek.Add(DayOfWeek.Thursday);
}
if(!bool.Parse(drow[MST_WorkingDayMasterTable.FRI_FLD].ToString()))
{
arrDayOfWeek.Add(DayOfWeek.Friday);
}
if(!bool.Parse(drow[MST_WorkingDayMasterTable.SAT_FLD].ToString()))
{
arrDayOfWeek.Add(DayOfWeek.Saturday);
}
if(!bool.Parse(drow[MST_WorkingDayMasterTable.SUN_FLD].ToString()))
{
arrDayOfWeek.Add(DayOfWeek.Sunday);
}
}
}
return arrDayOfWeek;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public ArrayList GetHolidaysInYear(DateTime pdtmStartDate, ScheduleMethodEnum penuSchedule)
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
try
{
string strSql = "SELECT "
+ MST_WorkingDayDetailTable.TABLE_NAME + "." + MST_WorkingDayDetailTable.WORKINGDAYDETAILID_FLD + ","
+ MST_WorkingDayDetailTable.TABLE_NAME + "." + MST_WorkingDayDetailTable.OFFDAY_FLD + ","
+ MST_WorkingDayDetailTable.TABLE_NAME + "." + MST_WorkingDayDetailTable.COMMENT_FLD + ","
+ MST_WorkingDayDetailTable.TABLE_NAME + "." + MST_WorkingDayDetailTable.WORKINGDAYMASTERID_FLD
+ " FROM " + MST_WorkingDayDetailTable.TABLE_NAME
+ " INNER JOIN " + MST_WorkingDayMasterTable.TABLE_NAME
+ " ON " + MST_WorkingDayDetailTable.TABLE_NAME + "." + MST_WorkingDayDetailTable.WORKINGDAYMASTERID_FLD + "=" + MST_WorkingDayMasterTable.TABLE_NAME + "." + MST_WorkingDayMasterTable.WORKINGDAYMASTERID_FLD
+ " WHERE " + MST_WorkingDayMasterTable.TABLE_NAME + ".[" + MST_WorkingDayMasterTable.YEAR_FLD + "]=" + pdtmStartDate.Year;
//if(penuSchedule == ScheduleMethodEnum.Backward)
//{
// strSql += " AND " + MST_WorkingDayDetailTable.TABLE_NAME + "." + MST_WorkingDayDetailTable.OFFDAY_FLD + " <= '" + pdtmStartDate.ToString("yyyy-MM-dd") + "'";
//}
//else
//{
// strSql += " AND " + MST_WorkingDayDetailTable.TABLE_NAME + "." + MST_WorkingDayDetailTable.OFFDAY_FLD + " >= '" + pdtmStartDate.ToString("yyyy-MM-dd") + "'";
//}
strSql += " ORDER BY " + MST_WorkingDayDetailTable.TABLE_NAME + "." + MST_WorkingDayDetailTable.OFFDAY_FLD;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
OleDbCommand ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, MST_WorkingDayDetailTable.TABLE_NAME);
if(dstPCS != null)
{
if(dstPCS.Tables[0].Rows.Count != 0)
{
//have data--> create new array list to add items
ArrayList arrHolidays = new ArrayList();
for(int i =0; i< dstPCS.Tables[0].Rows.Count; i++)
{
DateTime dtmTemp = DateTime.Parse(dstPCS.Tables[0].Rows[i][MST_WorkingDayDetailTable.OFFDAY_FLD].ToString());
//truncate hour, minute, second
dtmTemp = new DateTime(dtmTemp.Year, dtmTemp.Month, dtmTemp.Day);
arrHolidays.Add(dtmTemp);
}
// return holidays in a year
return arrHolidays;
}
else
{
// other else, return a blank list
return new ArrayList();
}
}
// return a bank list
return new ArrayList();
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// Get all holidays in a year
/// </summary>
/// <param name="pintYear">Year</param>
/// <returns>List of Holiday</returns>
/// <author>DungLA</author>
public ArrayList GetHolidaysInYear(int pintYear)
{
const string METHOD_NAME = THIS + ".GetHolidaysInYear()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
try
{
string strSql = "SELECT OffDay FROM dbo.MST_WorkingDayDetail WHERE DATEPART(year, OffDay) = " + pintYear
+ " ORDER BY OffDay";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
OleDbCommand ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, MST_WorkingDayDetailTable.TABLE_NAME);
if(dstPCS != null)
{
if(dstPCS.Tables[0].Rows.Count != 0)
{
//have data--> create new array list to add items
ArrayList arrHolidays = new ArrayList();
for(int i =0; i< dstPCS.Tables[0].Rows.Count; i++)
{
DateTime dtmTemp = DateTime.Parse(dstPCS.Tables[0].Rows[i][MST_WorkingDayDetailTable.OFFDAY_FLD].ToString());
//truncate hour, minute, second
dtmTemp = new DateTime(dtmTemp.Year, dtmTemp.Month, dtmTemp.Day);
arrHolidays.Add(dtmTemp);
}
// return holidays in a year
return arrHolidays;
}
else
{
// other else, return a blank list
return new ArrayList();
}
}
// return a bank list
return new ArrayList();
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// Retrieve all data from Workday Calendar Master table
/// </summary>
/// <returns></returns>
public DataTable GetWorkingDay()
{
const string METHOD_NAME = THIS + ".GetWorkingDay()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
try
{
string strSql = "SELECT "
+ MST_WorkingDayMasterTable.WORKINGDAYMASTERID_FLD + ","
+ MST_WorkingDayMasterTable.SUN_FLD + ","
+ MST_WorkingDayMasterTable.CCNID_FLD + ","
+ MST_WorkingDayMasterTable.YEAR_FLD + ","
+ MST_WorkingDayMasterTable.MON_FLD + ","
+ MST_WorkingDayMasterTable.TUE_FLD + ","
+ MST_WorkingDayMasterTable.WED_FLD + ","
+ MST_WorkingDayMasterTable.THU_FLD + ","
+ MST_WorkingDayMasterTable.FRI_FLD + ","
+ MST_WorkingDayMasterTable.SAT_FLD
+ " FROM " + MST_WorkingDayMasterTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
OleDbCommand ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,MST_WorkingDayMasterTable.TABLE_NAME);
return dstPCS.Tables[0];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// Retrieve all data from workday calendar detail table
/// </summary>
/// <returns></returns>
public DataTable GetHolidays()
{
const string METHOD_NAME = THIS + ".GetHolidays()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
try
{
string strSql = "SELECT MST_WorkingDayDetail.WorkingDayDetailID, MST_WorkingDayDetail.OffDay,"
+ " MST_WorkingDayDetail.Comment, MST_WorkingDayDetail.WorkingDayMasterID, MST_WorkingDayMaster.[Year]"
+ " FROM MST_WorkingDayDetail JOIN MST_WorkingDayMaster"
+ " ON MST_WorkingDayDetail.WorkingDayMasterID = MST_WorkingDayMaster.WorkingDayMasterID";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
OleDbCommand ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, MST_WorkingDayDetailTable.TABLE_NAME);
return dstPCS.Tables[0];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataTable GetPurPoseByTransType(int pintTransTypeID)
{
const string METHOD_NAME = THIS + ".GetObjectPurPose()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT *"
+ " FROM " + PRO_IssuePurposeTable.TABLE_NAME
+ " WHERE " + PRO_IssuePurposeTable.TRANTYPEID_FLD + "=" + (int) pintTransTypeID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter oldaPCS = new OleDbDataAdapter();
oldaPCS.SelectCommand = ocmdPCS;
oldaPCS.Fill(dstPCS, "PRO_IssuePurpose");
return dstPCS.Tables[0];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// Update selected state for multi selection form
/// </summary>
/// <param name="pstrTableName">Temp Table Name</param>
/// <param name="pstrFilter">Filter string</param>
/// <param name="pblnSelected">Select state</param>
/// <returns></returns>
public DataSet UpdateSelected(string pstrTableName, string pstrFilter, bool pblnSelected)
{
const string METHOD_NAME = THIS + ".UpdateSelected()";
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
string strSql = "UPDATE " + pstrTableName + " SET SELECTED = ?"
+ " WHERE 1=1";
if (pstrFilter != null && pstrFilter != string.Empty)
{
if (pstrFilter.ToUpper().IndexOf("LIKE") > 0)
pstrFilter = pstrFilter.Replace("*", "%");
strSql += " AND " + pstrFilter;
}
strSql += "; SELECT * FROM " + pstrTableName;
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Parameters.Add(new OleDbParameter("Selected", OleDbType.Boolean)).Value = pblnSelected;
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
DataSet dstPCS = new DataSet();
odadPCS.Fill(dstPCS, pstrTableName);
return dstPCS;
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataSet UpdateSelectedRow(string pstrTableName, string pstrFilter, bool pblnSelected,int iProductId,int iWorkOrderMasterID,int iWorkOrderDetailID,int iComponentID)
{
const string METHOD_NAME = THIS + ".UpdateSelected()";
//prepare value for parameters
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
string strSql = "UPDATE " + pstrTableName + " SET SELECTED = ?"
+ " WHERE 1=1 AND ProductID= " + iProductId
+" AND WorkOrderMasterID =" + iWorkOrderMasterID
+" AND WorkOrderDetailID =" + iWorkOrderDetailID
+" AND ComponentID=" + iComponentID;
if (pstrFilter != null && pstrFilter != string.Empty)
{
if (pstrFilter.ToUpper().IndexOf("LIKE") > 0)
pstrFilter = pstrFilter.Replace("*", "%");
strSql += " AND " + pstrFilter;
}
strSql += "; SELECT * FROM " + pstrTableName;
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Parameters.Add(new OleDbParameter("Selected", OleDbType.Boolean)).Value = pblnSelected;
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
DataSet dstPCS = new DataSet();
odadPCS.Fill(dstPCS, pstrTableName);
return dstPCS;
}
catch (OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public void UpdateTempTable(DataSet pdtbData)
{
const string METHOD_NAME = THIS + ".UpdateTempTable()";
string strSql;
OleDbConnection oconPCS = null;
OleDbCommandBuilder odcbPCS;
var odadPCS = new OleDbDataAdapter();
try
{
strSql = "SELECT * "
+ " FROM " + pdtbData.Tables[0].TableName;
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
var cmdSelect = new OleDbCommand(strSql, oconPCS);
cmdSelect.CommandTimeout = 10000;
odadPCS.SelectCommand = cmdSelect;
odcbPCS = new OleDbCommandBuilder(odadPCS);
pdtbData.EnforceConstraints = false;
int iCount = pdtbData.Tables[0].Rows.Count;
odadPCS.Update(pdtbData, pdtbData.Tables[0].TableName);
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
else
throw ex;
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// Get selected records from temp table
/// </summary>
/// <param name="pstrTableName">Temp table name</param>
/// <param name="pdstResultData">Result dataset structure</param>
/// <returns></returns>
public DataSet GetSelectedRecords(string pstrTableName, DataSet pdstResultData)
{
const string METHOD_NAME = THIS + ".GetSelectedRecords()";
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
string strSql = "SELECT * FROM " + pstrTableName
+ " WHERE Selected = 1;;Drop table " + pstrTableName;
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
string sResultTableName = pstrTableName;
if (pdstResultData.Tables.Count > 0)
sResultTableName = pdstResultData.Tables[0].TableName;
odadPCS.Fill(pdstResultData, sResultTableName);
return pdstResultData;
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
//
// DaapSource.cs
//
// Authors:
// Alexander Hixon <hixon.alexander@mediati.org>
//
// Copyright (C) 2008 Alexander Hixon
//
// 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 Hyena;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Library;
using Banshee.Sources;
using Banshee.ServiceStack;
using DAAP = Daap;
namespace Banshee.Daap
{
public class DaapSource : PrimarySource, IDurationAggregator, IUnmapableSource, IImportSource
{
private DAAP.Service service;
private DAAP.Client client;
private DAAP.Database database;
private bool connected = false;
public DAAP.Database Database {
get { return database; }
}
private bool is_activating;
public DaapSource (DAAP.Service service) : base (Catalog.GetString ("Music Share"), service.Name,
(service.Address.ToString () + service.Port).Replace (":", "").Replace (".", ""), 300, true)
{
this.service = service;
Properties.SetString ("UnmapSourceActionLabel", Catalog.GetString ("Disconnect"));
Properties.SetString ("UnmapSourceActionIconName", "gtk-disconnect");
SupportsPlaylists = false;
SavedCount = 0;
UpdateIcon ();
AfterInitialized ();
}
private void UpdateIcon ()
{
if (service != null && !service.IsProtected) {
Properties.SetStringList ("Icon.Name", "computer", "network-server");
} else {
Properties.SetStringList ("Icon.Name", "system-lock-screen", "computer", "network-server");
}
}
public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job)
{
if (track.PrimarySource == this && track.Uri.Scheme.StartsWith ("http")) {
foreach (double percent in database.DownloadTrack ((int)track.ExternalId, track.MimeType, uri.AbsolutePath)) {
job.DetailedProgress = percent;
}
}
}
public override void Activate ()
{
if (client != null || is_activating) {
return;
}
ClearErrorView ();
is_activating = true;
base.Activate ();
SetStatus (String.Format (Catalog.GetString ("Connecting to {0}"), service.Name), false);
ThreadAssist.Spawn (delegate {
try {
client = new DAAP.Client (service);
client.Updated += OnClientUpdated;
if (client.AuthenticationMethod == DAAP.AuthenticationMethod.None) {
client.Login ();
} else {
ThreadAssist.ProxyToMain (PromptLogin);
}
} catch(Exception e) {
ThreadAssist.ProxyToMain (delegate {
ShowErrorView (DaapErrorType.BrokenAuthentication);
});
Log.Error (e);
}
is_activating = false;
});
}
private void ShowErrorView (DaapErrorType error_type)
{
PurgeTracks ();
Reload ();
client = null;
DaapErrorView error_view = new DaapErrorView (this, error_type);
error_view.Show ();
Properties.Set<Banshee.Sources.Gui.ISourceContents> ("Nereid.SourceContents", error_view);
HideStatus ();
}
private void ClearErrorView ()
{
Properties.Remove ("Nereid.SourceContents");
}
internal bool Disconnect (bool logout)
{
// Stop currently playing track if its from us.
try {
if (ServiceManager.PlayerEngine.CurrentState == Banshee.MediaEngine.PlayerState.Playing) {
DatabaseTrackInfo track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (track != null && track.PrimarySource == this) {
ServiceManager.PlayerEngine.Close ();
}
}
} catch {}
connected = false;
// Remove tracks associated with this source, since we don't want
// them after we unmap - we'll refetch.
PurgeTracks ();
if (client != null) {
if (logout) {
client.Logout ();
}
client.Dispose ();
client = null;
database = null;
}
if (database != null) {
try {
DaapService.ProxyServer.UnregisterDatabase (database);
} catch {}
database.TrackAdded -= OnDatabaseTrackAdded;
database.TrackRemoved -= OnDatabaseTrackRemoved;
database = null;
}
List<Source> children = new List<Source> (Children);
foreach (Source child in children) {
if (child is Banshee.Sources.IUnmapableSource) {
(child as Banshee.Sources.IUnmapableSource).Unmap ();
}
}
ClearChildSources ();
return true;
}
public override void Dispose ()
{
Disconnect (true);
base.Dispose ();
}
private void PromptLogin ()
{
SetStatus (Catalog.GetString ("Logging in to {0}."), false);
DaapLoginDialog dialog = new DaapLoginDialog (client.Name,
client.AuthenticationMethod == DAAP.AuthenticationMethod.UserAndPassword);
if (dialog.Run () == (int) Gtk.ResponseType.Ok) {
AuthenticatedLogin (dialog.Username, dialog.Password);
} else {
ShowErrorView (DaapErrorType.UserDisconnect);
}
dialog.Destroy ();
}
private void AuthenticatedLogin (string username, string password)
{
ThreadAssist.Spawn (delegate {
try {
client.Login (username, password);
} catch (DAAP.AuthenticationException) {
ThreadAssist.ProxyToMain (delegate {
ShowErrorView (DaapErrorType.InvalidAuthentication);
});
}
});
}
private void OnClientUpdated (object o, EventArgs args)
{
try {
if (database == null && client.Databases.Count > 0) {
database = client.Databases[0];
DaapService.ProxyServer.RegisterDatabase (database);
database.TrackAdded += OnDatabaseTrackAdded;
database.TrackRemoved += OnDatabaseTrackRemoved;
SetStatus (String.Format (Catalog.GetPluralString (
"Loading {0} track", "Loading {0} tracks", database.TrackCount),
database.TrackCount), false
);
// Notify (eg reload the source before sync is done) at most 5 times
int notify_every = Math.Max (250, (database.Tracks.Count / 4));
notify_every -= notify_every % 250;
int count = 0;
DaapTrackInfo daap_track = null;
HyenaSqliteConnection conn = ServiceManager.DbConnection;
conn.BeginTransaction ();
foreach (DAAP.Track track in database.Tracks) {
daap_track = new DaapTrackInfo (track, this);
// Only notify once in a while because otherwise the source Reloading slows things way down
if (++count % notify_every == 0) {
conn.CommitTransaction ();
daap_track.Save (true);
conn.BeginTransaction ();
} else {
daap_track.Save (false);
}
}
conn.CommitTransaction ();
// Save the last track once more to trigger the NotifyTrackAdded
if (daap_track != null) {
daap_track.Save ();
}
SetStatus (Catalog.GetString ("Loading playlists"), false);
AddPlaylistSources ();
connected = true;
Reload ();
HideStatus ();
}
Name = client.Name;
UpdateIcon ();
OnUpdated ();
} catch (Exception e) {
Log.Error ("Caught exception while loading daap share", e);
ThreadAssist.ProxyToMain (delegate {
HideStatus ();
ShowErrorView (DaapErrorType.UserDisconnect);
});
}
}
private void AddPlaylistSources ()
{
foreach (DAAP.Playlist pl in database.Playlists) {
DaapPlaylistSource source = new DaapPlaylistSource (pl, this);
ThreadAssist.ProxyToMain (delegate {
if (source.Count == 0) {
source.Unmap ();
} else {
AddChildSource (source);
}
});
}
}
public void OnDatabaseTrackAdded (object o, DAAP.TrackArgs args)
{
DaapTrackInfo track = new DaapTrackInfo (args.Track, this);
track.Save ();
}
public void OnDatabaseTrackRemoved (object o, DAAP.TrackArgs args)
{
//RemoveTrack (
}
public override bool CanRemoveTracks {
get { return false; }
}
public override bool CanDeleteTracks {
get { return false; }
}
public override bool ConfirmRemoveTracks {
get { return false; }
}
public override bool HasEditableTrackProperties {
get { return false; }
}
public bool Unmap ()
{
// Disconnect and clear out our tracks and such.
Disconnect (true);
ShowErrorView (DaapErrorType.UserDisconnect);
return true;
}
public bool CanUnmap {
get { return connected; }
}
public bool ConfirmBeforeUnmap {
get { return false; }
}
public void Import ()
{
ServiceManager.SourceManager.MusicLibrary.MergeSourceInput (this, SourceMergeType.All);
}
public bool CanImport {
get { return connected; }
}
int IImportSource.SortOrder {
get { return 30; }
}
string IImportSource.ImportLabel {
get { return null; }
}
public string [] IconNames {
get { return Properties.GetStringList ("Icon.Name"); }
}
}
}
| |
// Copyright (c) Microsoft. 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.IO;
using System.Linq;
using System.Text;
string nuspecFile = args[0];
string assetsDir = args[1];
string projectDir = args[2];
string configuration = args[3];
string[] tfms = args[4].Split(';');
var metadataList = args[5].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var fileList = args[6].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var folderList = args[7].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var assemblyList = args[8].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var dependencyList = args[9].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var libraryList = args[10].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var rulesetsDir = args[11];
var editorconfigsDir = args[12];
var artifactsBinDir = args[13];
var analyzerDocumentationFileDir = args[14];
var analyzerDocumentationFileName = args[15];
var analyzerSarifFileDir = args[16];
var analyzerSarifFileName = args[17];
var analyzerConfigurationFileDir = args[18];
var analyzerConfigurationFileName = args[19];
var globalAnalyzerConfigsDir = args[20];
var result = new StringBuilder();
result.AppendLine(@"<?xml version=""1.0""?>");
result.AppendLine(@"<package xmlns=""http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"">");
result.AppendLine(@" <metadata>");
string version = string.Empty;
string repositoryType = string.Empty;
string repositoryUrl = string.Empty;
string repositoryCommit = string.Empty;
foreach (string entry in metadataList)
{
int equals = entry.IndexOf('=');
string name = entry[..equals];
string value = entry[(equals + 1)..];
switch (name)
{
case "repositoryType": repositoryType = value; continue;
case "repositoryUrl": repositoryUrl = value; continue;
case "repositoryCommit": repositoryCommit = value; continue;
case "license": result.AppendLine($" <license type=\"expression\">{value}</license>"); continue;
}
if (value.Length > 0)
{
result.AppendLine($" <{name}>{value}</{name}>");
}
#pragma warning disable CA1508 // Avoid dead conditional code - https://github.com/dotnet/roslyn-analyzers/issues/4520
if (name == "version")
#pragma warning restore CA1508
{
version = value;
}
}
if (!string.IsNullOrEmpty(repositoryType))
{
result.AppendLine($@" <repository type=""{repositoryType}"" url=""{repositoryUrl}"" commit=""{repositoryCommit}""/>");
}
if (dependencyList.Length > 0)
{
result.AppendLine(@" <dependencies>");
foreach (var dependency in dependencyList)
{
result.AppendLine($@" <dependency id=""{dependency}"" version=""{version}"" />");
}
result.AppendLine(@" </dependencies>");
}
result.AppendLine(@" </metadata>");
result.AppendLine(@" <files>");
result.AppendLine(@" $CommonFileElements$");
if (fileList.Length > 0 || assemblyList.Length > 0 || libraryList.Length > 0 || folderList.Length > 0)
{
const string csName = "CSharp";
const string vbName = "VisualBasic";
const string csTarget = @"analyzers\dotnet\cs";
const string vbTarget = @"analyzers\dotnet\vb";
const string agnosticTarget = @"analyzers\dotnet";
var allTargets = new List<string>();
if (assemblyList.Any(assembly => assembly.Contains(csName, StringComparison.Ordinal)))
{
allTargets.Add(csTarget);
}
if (assemblyList.Any(assembly => assembly.Contains(vbName, StringComparison.Ordinal)))
{
allTargets.Add(vbTarget);
}
if (allTargets.Count == 0)
{
allTargets.Add(agnosticTarget);
}
foreach (string assembly in assemblyList)
{
IEnumerable<string> targets;
if (assembly.Contains(csName, StringComparison.Ordinal))
{
targets = new[] { csTarget };
}
else if (assembly.Contains(vbName, StringComparison.Ordinal))
{
targets = new[] { vbTarget };
}
else
{
targets = allTargets;
}
string assemblyNameWithoutExtension = Path.GetFileNameWithoutExtension(assembly);
foreach (var tfm in tfms)
{
string assemblyFolder = Path.Combine(artifactsBinDir, assemblyNameWithoutExtension, configuration, tfm);
string assemblyPathForNuspec = Path.Combine(assemblyNameWithoutExtension, configuration, tfm, assembly);
foreach (string target in targets)
{
result.AppendLine(FileElement(assemblyPathForNuspec, target));
if (Directory.Exists(assemblyFolder))
{
string resourceAssemblyName = assemblyNameWithoutExtension + ".resources.dll";
foreach (var directory in Directory.EnumerateDirectories(assemblyFolder))
{
var resourceAssemblyFullPath = Path.Combine(directory, resourceAssemblyName);
if (File.Exists(resourceAssemblyFullPath))
{
var directoryName = Path.GetFileName(directory);
string resourceAssemblyPathForNuspec = Path.Combine(assemblyNameWithoutExtension, configuration, tfm, directoryName, resourceAssemblyName);
string targetForNuspec = Path.Combine(target, directoryName);
result.AppendLine(FileElement(resourceAssemblyPathForNuspec, targetForNuspec));
}
}
}
}
}
}
foreach (string file in fileList)
{
var fileWithPath = Path.IsPathRooted(file) ? file : Path.Combine(projectDir, file);
result.AppendLine(FileElement(fileWithPath, "build"));
}
foreach (string file in libraryList)
{
foreach (var tfm in tfms)
{
var fileWithPath = Path.Combine(artifactsBinDir, Path.GetFileNameWithoutExtension(file), configuration, tfm, file);
// For multi-tfm case, file may not exist for all tfms.
if (File.Exists(fileWithPath))
{
result.AppendLine(FileElement(fileWithPath, Path.Combine("lib", tfm)));
}
}
}
foreach (string folder in folderList)
{
foreach (var tfm in tfms)
{
string folderPath = Path.Combine(artifactsBinDir, folder, configuration, tfm);
foreach (var file in Directory.EnumerateFiles(folderPath))
{
var fileExtension = Path.GetExtension(file);
if (fileExtension is ".exe" or ".dll" or ".config" or ".xml")
{
var fileWithPath = Path.Combine(folderPath, file);
var targetPath = tfms.Length > 1 ? Path.Combine(folder, tfm) : folder;
result.AppendLine(FileElement(fileWithPath, targetPath));
}
}
}
}
result.AppendLine(FileElement(Path.Combine(assetsDir, "Install.ps1"), "tools"));
result.AppendLine(FileElement(Path.Combine(assetsDir, "Uninstall.ps1"), "tools"));
}
if (rulesetsDir.Length > 0 && Directory.Exists(rulesetsDir))
{
foreach (string ruleset in Directory.EnumerateFiles(rulesetsDir))
{
if (Path.GetExtension(ruleset) == ".ruleset")
{
result.AppendLine(FileElement(Path.Combine(rulesetsDir, ruleset), "rulesets"));
}
}
}
if (editorconfigsDir.Length > 0 && Directory.Exists(editorconfigsDir))
{
foreach (string directory in Directory.EnumerateDirectories(editorconfigsDir))
{
var directoryName = new DirectoryInfo(directory).Name;
foreach (string editorconfig in Directory.EnumerateFiles(directory))
{
result.AppendLine(FileElement(Path.Combine(directory, editorconfig), $"editorconfig\\{directoryName}"));
}
}
}
if (globalAnalyzerConfigsDir.Length > 0 && Directory.Exists(globalAnalyzerConfigsDir))
{
foreach (string editorconfig in Directory.EnumerateFiles(globalAnalyzerConfigsDir))
{
if (Path.GetExtension(editorconfig) == ".editorconfig")
{
result.AppendLine(FileElement(Path.Combine(globalAnalyzerConfigsDir, editorconfig), $"build\\config"));
}
else
{
throw new InvalidDataException($"Encountered a file with unexpected extension: {editorconfig}");
}
}
}
if (analyzerDocumentationFileDir.Length > 0 && Directory.Exists(analyzerDocumentationFileDir) && analyzerDocumentationFileName.Length > 0)
{
var fileWithPath = Path.Combine(analyzerDocumentationFileDir, analyzerDocumentationFileName);
if (File.Exists(fileWithPath))
{
result.AppendLine(FileElement(fileWithPath, "documentation"));
}
}
if (analyzerSarifFileDir.Length > 0 && Directory.Exists(analyzerSarifFileDir) && analyzerSarifFileName.Length > 0)
{
var fileWithPath = Path.Combine(analyzerSarifFileDir, analyzerSarifFileName);
if (File.Exists(fileWithPath))
{
result.AppendLine(FileElement(fileWithPath, "documentation"));
}
}
if (analyzerConfigurationFileDir.Length > 0 && Directory.Exists(analyzerConfigurationFileDir) && analyzerConfigurationFileName.Length > 0)
{
var fileWithPath = Path.Combine(analyzerConfigurationFileDir, analyzerConfigurationFileName);
if (File.Exists(fileWithPath))
{
result.AppendLine(FileElement(fileWithPath, "documentation"));
}
}
result.AppendLine(FileElement(Path.Combine(assetsDir, "ThirdPartyNotices.txt"), ""));
result.AppendLine(@" </files>");
result.AppendLine(@"</package>");
File.WriteAllText(nuspecFile, result.ToString());
static string FileElement(string file, string target) => $@" <file src=""{file}"" target=""{target}""/>";
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.Assemblies;
using System.Reflection.Runtime.CustomAttributes;
using Internal.Metadata.NativeFormat;
namespace Internal.Reflection.Tracing
{
public static partial class ReflectionTrace
{
//==============================================================================
// Returns the type name to emit into the ETW record.
//
// - If it returns null, skip writing the ETW record. Null returns can happen
// for the following reasons:
// - Missing metadata
// - Open type (no need to trace these - open type creations always succeed)
// - Third-party-implemented Types.
//
// The implementation does a reasonable-effort to avoid MME's to avoid an annoying
// debugger experience. However, some MME's will still get caught by the try/catch.
//
// - The format happens to match what the AssemblyQualifiedName property returns
// but we cannot invoke that here due to the risk of infinite recursion.
// The implementation must be very careful what it calls.
//==============================================================================
private static String NameString(this Type type)
{
try
{
return type.AssemblyQualifiedTypeName();
}
catch
{
return null;
}
}
//==============================================================================
// Returns the assembly name to emit into the ETW record.
//==============================================================================
private static String NameString(this Assembly assembly)
{
try
{
RuntimeAssembly runtimeAssembly = assembly as RuntimeAssembly;
if (runtimeAssembly == null)
return null;
return runtimeAssembly.Scope.Handle.ToRuntimeAssemblyName(runtimeAssembly.Scope.Reader).FullName;
}
catch
{
return null;
}
}
//==============================================================================
// Returns the custom attribute type name to emit into the ETW record.
//==============================================================================
private static String AttributeTypeNameString(this CustomAttributeData customAttributeData)
{
try
{
RuntimeCustomAttributeData runtimeCustomAttributeData = customAttributeData as RuntimeCustomAttributeData;
if (runtimeCustomAttributeData == null)
return null;
return runtimeCustomAttributeData.AttributeType.NameString();
}
catch
{
return null;
}
}
//==============================================================================
// Returns the declaring type name (without calling MemberInfo.DeclaringType) to emit into the ETW record.
//==============================================================================
private static String DeclaringTypeNameString(this MemberInfo memberInfo)
{
try
{
ITraceableTypeMember traceableTypeMember = memberInfo as ITraceableTypeMember;
if (traceableTypeMember == null)
return null;
return traceableTypeMember.ContainingType.NameString();
}
catch
{
return null;
}
}
//==============================================================================
// Returns the MemberInfo.Name value (without calling MemberInfo.Name) to emit into the ETW record.
//==============================================================================
private static String NameString(this MemberInfo memberInfo)
{
try
{
TypeInfo typeInfo = memberInfo as TypeInfo;
if (typeInfo != null)
return typeInfo.AsType().NameString();
ITraceableTypeMember traceableTypeMember = memberInfo as ITraceableTypeMember;
if (traceableTypeMember == null)
return null;
return traceableTypeMember.MemberName;
}
catch
{
return null;
}
}
//==============================================================================
// Append type argument strings.
//==============================================================================
private static String GenericTypeArgumentStrings(this Type[] typeArguments)
{
if (typeArguments == null)
return null;
String s = "";
foreach (Type typeArgument in typeArguments)
{
String typeArgumentString = typeArgument.NameString();
if (typeArgumentString == null)
return null;
s += "@" + typeArgumentString;
}
return s;
}
private static String NonQualifiedTypeName(this Type type)
{
if (!type.IsRuntimeImplemented())
return null;
RuntimeTypeInfo runtimeType = type.CastToRuntimeTypeInfo();
if (runtimeType.HasElementType)
{
String elementTypeName = runtimeType.InternalRuntimeElementType.NonQualifiedTypeName();
if (elementTypeName == null)
return null;
String suffix;
if (runtimeType.IsArray)
{
int rank = runtimeType.GetArrayRank();
if (rank == 1)
suffix = "[" + (runtimeType.InternalIsMultiDimArray ? "*" : "") + "]";
else
suffix = "[" + new String(',', rank - 1) + "]";
}
else if (runtimeType.IsByRef)
suffix = "&";
else if (runtimeType.IsPointer)
suffix = "*";
else
return null;
return elementTypeName + suffix;
}
else if (runtimeType.IsGenericParameter)
{
return null;
}
else if (runtimeType.IsConstructedGenericType)
{
StringBuilder sb = new StringBuilder();
String genericTypeDefinitionTypeName = runtimeType.GetGenericTypeDefinition().NonQualifiedTypeName();
if (genericTypeDefinitionTypeName == null)
return null;
sb.Append(genericTypeDefinitionTypeName);
sb.Append("[");
String sep = "";
foreach (RuntimeTypeInfo ga in runtimeType.InternalRuntimeGenericTypeArguments)
{
String gaTypeName = ga.AssemblyQualifiedTypeName();
if (gaTypeName == null)
return null;
sb.Append(sep + "[" + gaTypeName + "]");
sep = ",";
}
sb.Append("]");
return sb.ToString();
}
else
{
RuntimeNamedTypeInfo runtimeNamedTypeInfo = type.GetTypeInfo() as RuntimeNamedTypeInfo;
if (runtimeNamedTypeInfo == null)
return null;
MetadataReader reader = runtimeNamedTypeInfo.Reader;
String s = "";
TypeDefinitionHandle typeDefinitionHandle = runtimeNamedTypeInfo.TypeDefinitionHandle;
NamespaceDefinitionHandle namespaceDefinitionHandle;
do
{
TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader);
String name = typeDefinition.Name.GetString(reader);
if (s == "")
s = name;
else
s = name + "+" + s;
namespaceDefinitionHandle = typeDefinition.NamespaceDefinition;
typeDefinitionHandle = typeDefinition.EnclosingType;
}
while (!typeDefinitionHandle.IsNull(reader));
NamespaceChain namespaceChain = new NamespaceChain(reader, namespaceDefinitionHandle);
String ns = namespaceChain.NameSpace;
if (ns != null)
s = ns + "." + s;
return s;
}
}
private static String AssemblyQualifiedTypeName(this Type type)
{
if (!type.IsRuntimeImplemented())
return null;
RuntimeTypeInfo runtimeType = type.CastToRuntimeTypeInfo();
if (runtimeType == null)
return null;
String nonqualifiedTypeName = runtimeType.NonQualifiedTypeName();
if (nonqualifiedTypeName == null)
return null;
String assemblyName = runtimeType.ContainingAssemblyName();
if (assemblyName == null)
return assemblyName;
return nonqualifiedTypeName + ", " + assemblyName;
}
private static String ContainingAssemblyName(this Type type)
{
if (!type.IsRuntimeImplemented())
return null;
RuntimeTypeInfo runtimeTypeInfo = type.CastToRuntimeTypeInfo();
if (runtimeTypeInfo is RuntimeNoMetadataNamedTypeInfo)
return null;
return runtimeTypeInfo.Assembly.NameString();
}
}
}
| |
// 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.ComponentModel.Design;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Versions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.FindResults;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.RuleSets;
using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource;
using Microsoft.VisualStudio.LanguageServices.Utilities;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Setup
{
[Guid(Guids.RoslynPackageIdString)]
[PackageRegistration(UseManagedResourcesOnly = true)]
[ProvideMenuResource("Menus.ctmenu", version: 12)]
internal class RoslynPackage : Package
{
private LibraryManager _libraryManager;
private uint _libraryManagerCookie;
private VisualStudioWorkspace _workspace;
private WorkspaceFailureOutputPane _outputPane;
private IComponentModel _componentModel;
private RuleSetEventHandler _ruleSetEventHandler;
private IDisposable _solutionEventMonitor;
protected override void Initialize()
{
base.Initialize();
ForegroundThreadAffinitizedObject.DefaultForegroundThreadData = ForegroundThreadData.CreateDefault();
Debug.Assert(ForegroundThreadAffinitizedObject.DefaultForegroundThreadData.Kind == ForegroundThreadDataKind.Wpf);
FatalError.Handler = FailFast.OnFatalException;
FatalError.NonFatalHandler = WatsonReporter.Report;
// We also must set the FailFast handler for the compiler layer as well
var compilerAssembly = typeof(Compilation).Assembly;
var compilerFatalError = compilerAssembly.GetType("Microsoft.CodeAnalysis.FatalError", throwOnError: true);
var property = compilerFatalError.GetProperty(nameof(FatalError.Handler), BindingFlags.Static | BindingFlags.Public);
var compilerFailFast = compilerAssembly.GetType(typeof(FailFast).FullName, throwOnError: true);
var method = compilerFailFast.GetMethod(nameof(FailFast.OnFatalException), BindingFlags.Static | BindingFlags.NonPublic);
property.SetValue(null, Delegate.CreateDelegate(property.PropertyType, method));
InitializePortableShim(compilerAssembly);
RegisterFindResultsLibraryManager();
var componentModel = (IComponentModel)this.GetService(typeof(SComponentModel));
_workspace = componentModel.GetService<VisualStudioWorkspace>();
var telemetrySetupExtensions = componentModel.GetExtensions<IRoslynTelemetrySetup>();
foreach (var telemetrySetup in telemetrySetupExtensions)
{
telemetrySetup.Initialize(this);
}
// set workspace output pane
_outputPane = new WorkspaceFailureOutputPane(this, _workspace);
InitializeColors();
// load some services that have to be loaded in UI thread
LoadComponentsInUIContext();
_solutionEventMonitor = new SolutionEventMonitor(_workspace);
}
private static void InitializePortableShim(Assembly compilerAssembly)
{
// We eagerly force all of the types to be loaded within the PortableShim because there are scenarios
// in which loading types can trigger the current AppDomain's AssemblyResolve or TypeResolve events.
// If handlers of those events do anything that would cause PortableShim to be accessed recursively,
// bad things can happen. In particular, this fixes the scenario described in TFS bug #1185842.
//
// Note that the fix below is written to be as defensive as possible to do no harm if it impacts other
// scenarios.
// Initialize the PortableShim linked into the Workspaces layer.
Roslyn.Utilities.PortableShim.Initialize();
// Initialize the PortableShim linked into the Compilers layer via reflection.
var compilerPortableShim = compilerAssembly.GetType("Roslyn.Utilities.PortableShim", throwOnError: false);
var initializeMethod = compilerPortableShim?.GetMethod(nameof(Roslyn.Utilities.PortableShim.Initialize), BindingFlags.Static | BindingFlags.NonPublic);
initializeMethod?.Invoke(null, null);
}
private void InitializeColors()
{
// Use VS color keys in order to support theming.
CodeAnalysisColors.SystemCaptionTextColorKey = EnvironmentColors.SystemWindowTextColorKey;
CodeAnalysisColors.SystemCaptionTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey;
CodeAnalysisColors.CheckBoxTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey;
CodeAnalysisColors.RenameErrorTextBrushKey = VSCodeAnalysisColors.RenameErrorTextBrushKey;
CodeAnalysisColors.RenameResolvableConflictTextBrushKey = VSCodeAnalysisColors.RenameResolvableConflictTextBrushKey;
CodeAnalysisColors.BackgroundBrushKey = VsBrushes.CommandBarGradientBeginKey;
CodeAnalysisColors.ButtonStyleKey = VsResourceKeys.ButtonStyleKey;
CodeAnalysisColors.AccentBarColorKey = EnvironmentColors.FileTabInactiveDocumentBorderEdgeBrushKey;
}
private void LoadComponentsInUIContext()
{
if (KnownUIContexts.SolutionExistsAndFullyLoadedContext.IsActive)
{
// if we are already in the right UI context, load it right away
LoadComponents();
}
else
{
// load them when it is a right context.
KnownUIContexts.SolutionExistsAndFullyLoadedContext.UIContextChanged += OnSolutionExistsAndFullyLoadedContext;
}
}
private void OnSolutionExistsAndFullyLoadedContext(object sender, UIContextChangedEventArgs e)
{
if (e.Activated)
{
// unsubscribe from it
KnownUIContexts.SolutionExistsAndFullyLoadedContext.UIContextChanged -= OnSolutionExistsAndFullyLoadedContext;
// load components
LoadComponents();
}
}
private void LoadComponents()
{
// we need to load it as early as possible since we can have errors from
// package from each language very early
this.ComponentModel.GetService<VisualStudioDiagnosticListTable>();
this.ComponentModel.GetService<VisualStudioTodoListTable>();
this.ComponentModel.GetService<VisualStudioDiagnosticListTableCommandHandler>().Initialize(this);
this.ComponentModel.GetService<HACK_ThemeColorFixer>();
this.ComponentModel.GetExtensions<IReferencedSymbolsPresenter>();
this.ComponentModel.GetExtensions<INavigableItemsPresenter>();
this.ComponentModel.GetService<VisualStudioMetadataAsSourceFileSupportService>();
this.ComponentModel.GetService<VirtualMemoryNotificationListener>();
LoadAnalyzerNodeComponents();
Task.Run(() => LoadComponentsBackground());
}
private void LoadComponentsBackground()
{
// Perf: Initialize the command handlers.
var commandHandlerServiceFactory = this.ComponentModel.GetService<ICommandHandlerServiceFactory>();
commandHandlerServiceFactory.Initialize(ContentTypeNames.RoslynContentType);
this.ComponentModel.GetService<MiscellaneousTodoListTable>();
this.ComponentModel.GetService<MiscellaneousDiagnosticListTable>();
}
internal IComponentModel ComponentModel
{
get
{
if (_componentModel == null)
{
_componentModel = (IComponentModel)GetService(typeof(SComponentModel));
}
return _componentModel;
}
}
protected override void Dispose(bool disposing)
{
UnregisterFindResultsLibraryManager();
DisposeVisualStudioDocumentTrackingService();
UnregisterAnalyzerTracker();
UnregisterRuleSetEventHandler();
ReportSessionWideTelemetry();
if (_solutionEventMonitor != null)
{
_solutionEventMonitor.Dispose();
_solutionEventMonitor = null;
}
base.Dispose(disposing);
}
private void ReportSessionWideTelemetry()
{
PersistedVersionStampLogger.LogSummary();
}
private void RegisterFindResultsLibraryManager()
{
var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (objectManager != null)
{
_libraryManager = new LibraryManager(this);
if (ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(_libraryManager, out _libraryManagerCookie)))
{
_libraryManagerCookie = 0;
}
((IServiceContainer)this).AddService(typeof(LibraryManager), _libraryManager, promote: true);
}
}
private void UnregisterFindResultsLibraryManager()
{
if (_libraryManagerCookie != 0)
{
var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (objectManager != null)
{
objectManager.UnregisterLibrary(_libraryManagerCookie);
_libraryManagerCookie = 0;
}
((IServiceContainer)this).RemoveService(typeof(LibraryManager), promote: true);
_libraryManager = null;
}
}
private void DisposeVisualStudioDocumentTrackingService()
{
if (_workspace != null)
{
var documentTrackingService = _workspace.Services.GetService<IDocumentTrackingService>() as VisualStudioDocumentTrackingService;
documentTrackingService.Dispose();
}
}
private void LoadAnalyzerNodeComponents()
{
this.ComponentModel.GetService<IAnalyzerNodeSetup>().Initialize(this);
_ruleSetEventHandler = this.ComponentModel.GetService<RuleSetEventHandler>();
if (_ruleSetEventHandler != null)
{
_ruleSetEventHandler.Register();
}
}
private void UnregisterAnalyzerTracker()
{
this.ComponentModel.GetService<IAnalyzerNodeSetup>().Unregister();
}
private void UnregisterRuleSetEventHandler()
{
if (_ruleSetEventHandler != null)
{
_ruleSetEventHandler.Unregister();
_ruleSetEventHandler = null;
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using Flame.Compiler;
using Flame.Compiler.Expressions;
using Flame.Compiler.Statements;
using Flame.Ecs.Values;
using Loyc.Syntax;
using Pixie;
namespace Flame.Ecs
{
/// <summary>
/// A data structure that helps build switch statements.
/// </summary>
public sealed class SwitchBuilder
{
public SwitchBuilder(
IValue SwitchValue, SourceLocation SwitchValueLocation,
LocalScope Scope, NodeConverter Converter)
{
this.SwitchValue = SwitchValue;
this.SwitchValueLocation = SwitchValueLocation;
this.Scope = Scope;
this.Converter = Converter;
this.defaultCase = null;
this.otherCases = new List<KeyValuePair<IExpression, IStatement>>();
this.isBuildingDefaultCase = false;
this.caseConditions = new List<IExpression>();
this.caseStatements = new List<IStatement>();
this.caseValues = new Dictionary<object, SourceLocation>();
}
/// <summary>
/// Gets the value that this switch statement operates on.
/// </summary>
/// <returns>The value that this switch statement operates on.</returns>
public IValue SwitchValue { get; private set; }
/// <summary>
/// Gets the location of the value that this switch statement operates on.
/// </summary>
/// <returns>The location of the value that this switch statement operates on.
public SourceLocation SwitchValueLocation { get; private set; }
/// <summary>
/// Gets this switch builder's local scope.
/// </summary>
/// <returns>The local scope for this switch builder.</returns>
public LocalScope Scope { get; private set; }
/// <summary>
/// Gets this switch builder's node converter.
/// </summary>
/// <returns>The node converter for this switch builder.</returns>
public NodeConverter Converter { get; private set; }
private IStatement defaultCase;
private SourceLocation defaultCaseLocation;
private List<KeyValuePair<IExpression, IStatement>> otherCases;
/// <summary>
/// Tells if this switch builder already has a default case.
/// </summary>
public bool HasDefaultCase => defaultCaseLocation != null;
private bool isBuildingDefaultCase;
private List<IExpression> caseConditions;
private List<IStatement> caseStatements;
private Dictionary<object, SourceLocation> caseValues;
public void AppendCondition(LNode CaseValueNode)
{
if (caseStatements.Count > 0)
FlushCase();
var caseExpr = Converter.ConvertExpression(
CaseValueNode, Scope, SwitchValue.Type);
var caseLoc = NodeHelpers.ToSourceLocation(
CaseValueNode.Range);
var caseEval = caseExpr.EvaluateOrNull();
if (caseEval == null)
{
Scope.Log.LogError(
new LogEntry(
"cannot evaluate",
NodeHelpers.HighlightEven(
"'", "case", "' value is not a compile-time constant."),
caseLoc));
}
else
{
var caseObj = caseEval.GetObjectValue();
SourceLocation prevLoc;
if (caseValues.TryGetValue(caseObj, out prevLoc))
{
Scope.Log.LogError(
new LogEntry(
"duplicate cases",
NodeHelpers.HighlightEven(
"same '", "case",
"' appears more than once in the same '",
"switch", "' statement.").Concat(new MarkupNode[]
{
caseLoc.CreateDiagnosticsNode(),
prevLoc.CreateRemarkDiagnosticsNode("duplicate case: ")
})));
return;
}
else
{
caseValues[caseObj] = caseLoc;
}
}
caseConditions.Add(
Scope.Function.ConvertImplicit(
ExpressionConverters.CreateBinary(
Operator.CheckEquality,
SwitchValue,
new ExpressionValue(caseExpr),
Scope.Function,
SwitchValueLocation,
caseLoc),
PrimitiveTypes.Boolean,
caseLoc));
}
public void AppendDefault(LNode DefaultNode)
{
var defaultLoc = NodeHelpers.ToSourceLocation(DefaultNode.Range);
if (HasDefaultCase)
{
Scope.Log.LogError(
new LogEntry(
"syntax error",
NodeHelpers.HighlightEven(
"more than one '", "default", "' case in a single '",
"switch", "' statement.").Concat(new MarkupNode[]
{
defaultLoc.CreateDiagnosticsNode(),
defaultCaseLocation.CreateRemarkDiagnosticsNode("other default case: ")
})));
return;
}
if (caseStatements.Count > 0)
FlushCase();
isBuildingDefaultCase = true;
defaultCaseLocation = defaultLoc;
}
public void AppendStatement(LNode StatementNode)
{
if (!isBuildingDefaultCase && caseConditions.Count == 0)
{
Scope.Log.LogError(
new LogEntry(
"syntax error",
NodeHelpers.HighlightEven(
"child statements in a '", "switch",
"' statement must be preceded by a valid '",
"case", "' or '", "default", "' label.").Concat(new MarkupNode[]
{
NodeHelpers.ToSourceLocation(StatementNode.Range).CreateDiagnosticsNode(),
defaultCaseLocation.CreateRemarkDiagnosticsNode("other default case: ")
})));
}
caseStatements.Add(Converter.ConvertStatement(StatementNode, Scope));
}
public IStatement FinishSwitch()
{
FlushCase();
var switchStmt = defaultCase;
for (int i = otherCases.Count - 1; i >= 0; i--)
{
switchStmt = new IfElseStatement(
otherCases[i].Key, otherCases[i].Value, switchStmt);
}
return switchStmt;
}
private void FlushCase()
{
if (!isBuildingDefaultCase && caseConditions.Count == 0)
return;
var caseBody = new BlockStatement(caseStatements).Simplify();
if (isBuildingDefaultCase)
{
defaultCase = caseBody;
isBuildingDefaultCase = false;
}
else
{
var condition = caseConditions[0];
for (int i = 1; i < caseConditions.Count; i++)
{
condition = new LazyOrExpression(condition, caseConditions[i]);
}
otherCases.Add(new KeyValuePair<IExpression, IStatement>(condition, caseBody));
}
caseConditions = new List<IExpression>();
caseStatements = new List<IStatement>();
}
}
}
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// All public properties on Nodeproperties or derived classes are assumed to be used by Automation by default.
/// Set this attribute to false on Properties that should not be visible for Automation.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class AutomationBrowsableAttribute : System.Attribute
{
public AutomationBrowsableAttribute(bool browsable)
{
this.browsable = browsable;
}
public bool Browsable
{
get
{
return this.browsable;
}
}
private bool browsable;
}
/// <summary>
/// To create your own localizable node properties, subclass this and add public properties
/// decorated with your own localized display name, category and description attributes.
/// </summary>
public class NodeProperties : LocalizableProperties,
ISpecifyPropertyPages,
IVsGetCfgProvider,
IVsSpecifyProjectDesignerPages,
EnvDTE80.IInternalExtenderProvider,
IVsBrowseObject
{
#region fields
private HierarchyNode node;
#endregion
#region properties
[Browsable(false)]
[AutomationBrowsable(false)]
public HierarchyNode Node
{
get { return this.node; }
}
/// <summary>
/// Used by Property Pages Frame to set it's title bar. The Caption of the Hierarchy Node is returned.
/// </summary>
[Browsable(false)]
[AutomationBrowsable(false)]
public virtual string Name
{
get { return this.node.Caption; }
}
#endregion
#region ctors
public NodeProperties(HierarchyNode node)
{
if(node == null)
{
throw new ArgumentNullException("node");
}
this.node = node;
}
#endregion
#region ISpecifyPropertyPages methods
public virtual void GetPages(CAUUID[] pages)
{
this.GetCommonPropertyPages(pages);
}
#endregion
#region IVsSpecifyProjectDesignerPages
/// <summary>
/// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration independent.
/// </summary>
/// <param name="pages">The pages to return.</param>
/// <returns></returns>
public virtual int GetProjectDesignerPages(CAUUID[] pages)
{
this.GetCommonPropertyPages(pages);
return VSConstants.S_OK;
}
#endregion
#region IVsGetCfgProvider methods
public virtual int GetCfgProvider(out IVsCfgProvider p)
{
p = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsBrowseObject methods
/// <summary>
/// Maps back to the hierarchy or project item object corresponding to the browse object.
/// </summary>
/// <param name="hier">Reference to the hierarchy object.</param>
/// <param name="itemid">Reference to the project item.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid)
{
if(this.node == null)
{
throw new InvalidOperationException();
}
hier = this.node.ProjectMgr.InteropSafeIVsHierarchy;
itemid = this.node.ID;
return VSConstants.S_OK;
}
#endregion
#region overridden methods
/// <summary>
/// Get the Caption of the Hierarchy Node instance. If Caption is null or empty we delegate to base
/// </summary>
/// <returns>Caption of Hierarchy node instance</returns>
public override string GetComponentName()
{
string caption = this.Node.Caption;
if(string.IsNullOrEmpty(caption))
{
return base.GetComponentName();
}
else
{
return caption;
}
}
#endregion
#region helper methods
protected string GetProperty(string name, string def)
{
string a = this.Node.ItemNode.GetMetadata(name);
return (a == null) ? def : a;
}
protected void SetProperty(string name, string value)
{
this.Node.ItemNode.SetMetadata(name, value);
}
/// <summary>
/// Retrieves the common property pages. The NodeProperties is the BrowseObject and that will be called to support
/// configuration independent properties.
/// </summary>
/// <param name="pages">The pages to return.</param>
private void GetCommonPropertyPages(CAUUID[] pages)
{
// We do not check whether the supportsProjectDesigner is set to false on the ProjectNode.
// We rely that the caller knows what to call on us.
if(pages == null)
{
throw new ArgumentNullException("pages");
}
if(pages.Length == 0)
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "pages");
}
// Only the project should show the property page the rest should show the project properties.
if(this.node != null && (this.node is ProjectNode))
{
// Retrieve the list of guids from hierarchy properties.
// Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy
string guidsList = String.Empty;
IVsHierarchy hierarchy = this.Node.ProjectMgr.InteropSafeIVsHierarchy;
object variant = null;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList, out variant));
guidsList = (string)variant;
Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList);
if(guids == null || guids.Length == 0)
{
pages[0] = new CAUUID();
pages[0].cElems = 0;
}
else
{
pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids);
}
}
else
{
pages[0] = new CAUUID();
pages[0].cElems = 0;
}
}
#endregion
#region IInternalExtenderProvider Members
bool EnvDTE80.IInternalExtenderProvider.CanExtend(string extenderCATID, string extenderName, object extendeeObject)
{
EnvDTE80.IInternalExtenderProvider outerHierarchy = this.Node.ProjectMgr.InteropSafeIVsHierarchy as EnvDTE80.IInternalExtenderProvider;
if(outerHierarchy != null)
{
return outerHierarchy.CanExtend(extenderCATID, extenderName, extendeeObject);
}
return false;
}
object EnvDTE80.IInternalExtenderProvider.GetExtender(string extenderCATID, string extenderName, object extendeeObject, EnvDTE.IExtenderSite extenderSite, int cookie)
{
EnvDTE80.IInternalExtenderProvider outerHierarchy = this.Node.ProjectMgr.InteropSafeIVsHierarchy as EnvDTE80.IInternalExtenderProvider;
if(outerHierarchy != null)
{
return outerHierarchy.GetExtender(extenderCATID, extenderName, extendeeObject, extenderSite, cookie);
}
return null;
}
object EnvDTE80.IInternalExtenderProvider.GetExtenderNames(string extenderCATID, object extendeeObject)
{
EnvDTE80.IInternalExtenderProvider outerHierarchy = this.Node.ProjectMgr.InteropSafeIVsHierarchy as EnvDTE80.IInternalExtenderProvider;
if(outerHierarchy != null)
{
return outerHierarchy.GetExtenderNames(extenderCATID, extendeeObject);
}
return null;
}
#endregion
#region ExtenderSupport
[Browsable(false)]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CATID")]
public virtual string ExtenderCATID
{
get
{
Guid catid = this.Node.ProjectMgr.GetCATIDForType(this.GetType());
if(Guid.Empty.CompareTo(catid) == 0)
{
return null;
}
return catid.ToString("B");
}
}
[Browsable(false)]
public object ExtenderNames()
{
EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.Node.GetService(typeof(EnvDTE.ObjectExtenders));
Debug.Assert(extenderService != null, "Could not get the ObjectExtenders object from the services exposed by this property object");
if(extenderService == null)
{
throw new InvalidOperationException();
}
return extenderService.GetExtenderNames(this.ExtenderCATID, this);
}
public object Extender(string extenderName)
{
EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.Node.GetService(typeof(EnvDTE.ObjectExtenders));
Debug.Assert(extenderService != null, "Could not get the ObjectExtenders object from the services exposed by this property object");
if(extenderService == null)
{
throw new InvalidOperationException();
}
return extenderService.GetExtender(this.ExtenderCATID, extenderName, this);
}
#endregion
}
public class FileNodeProperties : NodeProperties
{
#region properties
[SRCategoryAttribute(SR.Advanced)]
[LocDisplayName(SR.BuildAction)]
[SRDescriptionAttribute(SR.BuildActionDescription)]
public virtual BuildAction BuildAction
{
get
{
string value = this.Node.ItemNode.ItemName;
if(value == null || value.Length == 0)
{
return BuildAction.None;
}
return (BuildAction)Enum.Parse(typeof(BuildAction), value);
}
set
{
this.Node.ItemNode.ItemName = value.ToString();
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.FileName)]
[SRDescriptionAttribute(SR.FileNameDescription)]
public string FileName
{
get
{
return this.Node.Caption;
}
set
{
this.Node.SetEditLabel(value);
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public string FullPath
{
get
{
return this.Node.Url;
}
}
#region non-browsable properties - used for automation only
[Browsable(false)]
public string Extension
{
get
{
return Path.GetExtension(this.Node.Caption);
}
}
#endregion
#endregion
#region ctors
public FileNodeProperties(HierarchyNode node)
: base(node)
{
}
#endregion
#region overridden methods
public override string GetClassName()
{
return SR.GetString(SR.FileProperties, CultureInfo.CurrentUICulture);
}
#endregion
}
public class DependentFileNodeProperties : NodeProperties
{
#region properties
[SRCategoryAttribute(SR.Advanced)]
[LocDisplayName(SR.BuildAction)]
[SRDescriptionAttribute(SR.BuildActionDescription)]
public virtual BuildAction BuildAction
{
get
{
string value = this.Node.ItemNode.ItemName;
if(value == null || value.Length == 0)
{
return BuildAction.None;
}
return (BuildAction)Enum.Parse(typeof(BuildAction), value);
}
set
{
this.Node.ItemNode.ItemName = value.ToString();
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.FileName)]
[SRDescriptionAttribute(SR.FileNameDescription)]
public virtual string FileName
{
get
{
return this.Node.Caption;
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public string FullPath
{
get
{
return this.Node.Url;
}
}
#endregion
#region ctors
public DependentFileNodeProperties(HierarchyNode node)
: base(node)
{
}
#endregion
#region overridden methods
public override string GetClassName()
{
return SR.GetString(SR.FileProperties, CultureInfo.CurrentUICulture);
}
#endregion
}
public class SingleFileGeneratorNodeProperties : FileNodeProperties
{
#region fields
private EventHandler<HierarchyNodeEventArgs> onCustomToolChanged;
private EventHandler<HierarchyNodeEventArgs> onCustomToolNameSpaceChanged;
#endregion
#region custom tool events
internal event EventHandler<HierarchyNodeEventArgs> OnCustomToolChanged
{
add { onCustomToolChanged += value; }
remove { onCustomToolChanged -= value; }
}
internal event EventHandler<HierarchyNodeEventArgs> OnCustomToolNameSpaceChanged
{
add { onCustomToolNameSpaceChanged += value; }
remove { onCustomToolNameSpaceChanged -= value; }
}
#endregion
#region properties
[SRCategoryAttribute(SR.Advanced)]
[LocDisplayName(SR.CustomTool)]
[SRDescriptionAttribute(SR.CustomToolDescription)]
public virtual string CustomTool
{
get
{
return this.Node.ItemNode.GetMetadata(ProjectFileConstants.Generator);
}
set
{
if (CustomTool != value)
{
this.Node.ItemNode.SetMetadata(ProjectFileConstants.Generator, value != string.Empty ? value : null);
HierarchyNodeEventArgs args = new HierarchyNodeEventArgs(this.Node);
if (onCustomToolChanged != null)
{
onCustomToolChanged(this.Node, args);
}
}
}
}
[SRCategoryAttribute(VisualStudio.Project.SR.Advanced)]
[LocDisplayName(SR.CustomToolNamespace)]
[SRDescriptionAttribute(SR.CustomToolNamespaceDescription)]
public virtual string CustomToolNamespace
{
get
{
return this.Node.ItemNode.GetMetadata(ProjectFileConstants.CustomToolNamespace);
}
set
{
if (CustomToolNamespace != value)
{
this.Node.ItemNode.SetMetadata(ProjectFileConstants.CustomToolNamespace, value != String.Empty ? value : null);
HierarchyNodeEventArgs args = new HierarchyNodeEventArgs(this.Node);
if (onCustomToolNameSpaceChanged != null)
{
onCustomToolNameSpaceChanged(this.Node, args);
}
}
}
}
#endregion
#region ctors
public SingleFileGeneratorNodeProperties(HierarchyNode node)
: base(node)
{
}
#endregion
}
public class ProjectNodeProperties : NodeProperties
{
#region properties
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.ProjectFolder)]
[SRDescriptionAttribute(SR.ProjectFolderDescription)]
[AutomationBrowsable(false)]
public string ProjectFolder
{
get
{
return this.Node.ProjectMgr.ProjectFolder;
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.ProjectFile)]
[SRDescriptionAttribute(SR.ProjectFileDescription)]
[AutomationBrowsable(false)]
public string ProjectFile
{
get
{
return this.Node.ProjectMgr.ProjectFile;
}
set
{
this.Node.ProjectMgr.ProjectFile = value;
}
}
#region non-browsable properties - used for automation only
[Browsable(false)]
public string FileName
{
get
{
return this.Node.ProjectMgr.ProjectFile;
}
set
{
this.Node.ProjectMgr.ProjectFile = value;
}
}
[Browsable(false)]
public string FullPath
{
get
{
string fullPath = this.Node.ProjectMgr.ProjectFolder;
if(!fullPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
{
return fullPath + Path.DirectorySeparatorChar;
}
else
{
return fullPath;
}
}
}
#endregion
#endregion
#region ctors
public ProjectNodeProperties(ProjectNode node)
: base(node)
{
}
#endregion
#region overridden methods
public override string GetClassName()
{
return SR.GetString(SR.ProjectProperties, CultureInfo.CurrentUICulture);
}
/// <summary>
/// ICustomTypeDescriptor.GetEditor
/// To enable the "Property Pages" button on the properties browser
/// the browse object (project properties) need to be unmanaged
/// or it needs to provide an editor of type ComponentEditor.
/// </summary>
/// <param name="editorBaseType">Type of the editor</param>
/// <returns>Editor</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification="The service provider is used by the PropertiesEditorLauncher")]
public override object GetEditor(Type editorBaseType)
{
// Override the scenario where we are asked for a ComponentEditor
// as this is how the Properties Browser calls us
if(editorBaseType == typeof(ComponentEditor))
{
IOleServiceProvider sp;
ErrorHandler.ThrowOnFailure(this.Node.GetSite(out sp));
return new PropertiesEditorLauncher(new ServiceProvider(sp));
}
return base.GetEditor(editorBaseType);
}
public override int GetCfgProvider(out IVsCfgProvider p)
{
if(this.Node != null && this.Node.ProjectMgr != null)
{
return this.Node.ProjectMgr.GetCfgProvider(out p);
}
return base.GetCfgProvider(out p);
}
#endregion
}
public class FolderNodeProperties : NodeProperties
{
#region properties
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.FolderName)]
[SRDescriptionAttribute(SR.FolderNameDescription)]
[AutomationBrowsable(false)]
public string FolderName
{
get
{
return this.Node.Caption;
}
set
{
this.Node.SetEditLabel(value);
this.Node.ReDraw(UIHierarchyElement.Caption);
}
}
#region properties - used for automation only
[Browsable(false)]
[AutomationBrowsable(true)]
public string FileName
{
get
{
return this.Node.Caption;
}
set
{
this.Node.SetEditLabel(value);
}
}
[Browsable(false)]
[AutomationBrowsable(true)]
public string FullPath
{
get
{
string fullPath = this.Node.GetMkDocument();
if(!fullPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
{
return fullPath + Path.DirectorySeparatorChar;
}
else
{
return fullPath;
}
}
}
#endregion
#endregion
#region ctors
public FolderNodeProperties(HierarchyNode node)
: base(node)
{
}
#endregion
#region overridden methods
public override string GetClassName()
{
return SR.GetString(SR.FolderProperties, CultureInfo.CurrentUICulture);
}
#endregion
}
public class ReferenceNodeProperties : NodeProperties
{
#region properties
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.RefName)]
[SRDescriptionAttribute(SR.RefNameDescription)]
[Browsable(true)]
[AutomationBrowsable(true)]
public override string Name
{
get
{
return this.Node.Caption;
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.CopyToLocal)]
[SRDescriptionAttribute(SR.CopyToLocalDescription)]
public bool CopyToLocal
{
get
{
string copyLocal = this.GetProperty(ProjectFileConstants.Private, "False");
if(copyLocal == null || copyLocal.Length == 0)
return true;
return bool.Parse(copyLocal);
}
set
{
this.SetProperty(ProjectFileConstants.Private, value.ToString());
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public virtual string FullPath
{
get
{
return this.Node.Url;
}
}
#endregion
#region ctors
public ReferenceNodeProperties(HierarchyNode node)
: base(node)
{
}
#endregion
#region overridden methods
public override string GetClassName()
{
return SR.GetString(SR.ReferenceProperties, CultureInfo.CurrentUICulture);
}
#endregion
}
[ComVisible(true)]
public class ProjectReferencesProperties : ReferenceNodeProperties
{
#region ctors
public ProjectReferencesProperties(ProjectReferenceNode node)
: base(node)
{
}
#endregion
#region overriden methods
public override string FullPath
{
get
{
return ((ProjectReferenceNode)Node).ReferencedProjectOutputPath;
}
}
#endregion
}
[ComVisible(true)]
public class ComReferenceProperties : ReferenceNodeProperties
{
public ComReferenceProperties(ComReferenceNode node)
: base(node)
{
}
[SRCategory(SR.Misc)]
[LocDisplayName(SR.EmbedInteropTypes)]
[SRDescription(SR.EmbedInteropTypesDescription)]
public virtual bool EmbedInteropTypes
{
get { return ((ComReferenceNode)this.Node).EmbedInteropTypes; }
set { ((ComReferenceNode)this.Node).EmbedInteropTypes = value; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using SIL.Data;
namespace SIL.Tests.Data
{
public class PalasoChildTestItem
{
private PalasoChildTestItem _testItem;
public PalasoChildTestItem() {}
public PalasoChildTestItem(string s, int i, DateTime d)
{
StoredInt = i;
StoredString = s;
StoredDateTime = d;
}
public PalasoChildTestItem Child
{
get { return _testItem; }
set { _testItem = value; }
}
public int Depth
{
get
{
int depth = 1;
PalasoChildTestItem item = Child;
while (item != null)
{
++depth;
item = item.Child;
}
return depth;
}
}
public int StoredInt { get; set; }
public string StoredString { get; set; }
public DateTime StoredDateTime { get; set; }
}
public class PalasoTestItem: INotifyPropertyChanged
{
private int _storedInt;
private string _storedString;
private DateTime _storedDateTime;
private PalasoChildTestItem _childTestItem;
private List<string> _storedList;
private List<PalasoChildTestItem> _childItemList;
public List<PalasoChildTestItem> ChildItemList
{
get { return _childItemList; }
set
{
_childItemList = value;
OnPropertyChanged(new PropertyChangedEventArgs("Children"));
}
}
public int OnActivateDepth { get; private set; }
public PalasoChildTestItem Child
{
get { return _childTestItem; }
set
{
_childTestItem = value;
OnPropertyChanged(new PropertyChangedEventArgs("Child"));
}
}
public int Depth
{
get
{
int depth = 1;
PalasoChildTestItem item = Child;
while (item != null)
{
++depth;
item = item.Child;
}
return depth;
}
}
public PalasoTestItem()
{
_storedDateTime = PreciseDateTime.UtcNow;
_childTestItem = new PalasoChildTestItem();
}
public PalasoTestItem(string s, int i, DateTime d)
{
_storedString = s;
_storedInt = i;
_storedDateTime = d;
}
public override string ToString()
{
return StoredInt + ". " + StoredString + " " + StoredDateTime;
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
var item = obj as PalasoTestItem;
if (item == null)
{
return false;
}
return Equals(item);
}
public bool Equals(PalasoTestItem item)
{
if (item == null)
{
return false;
}
return (_storedInt == item._storedInt) && (_storedString == item._storedString) &&
(_storedDateTime == item._storedDateTime);
}
public int StoredInt
{
get { return _storedInt; }
set
{
if (_storedInt != value)
{
_storedInt = value;
OnPropertyChanged(new PropertyChangedEventArgs("StoredInt"));
}
}
}
public string StoredString
{
get { return _storedString; }
set
{
if (_storedString != value)
{
_storedString = value;
OnPropertyChanged(new PropertyChangedEventArgs("StoredString"));
}
}
}
public DateTime StoredDateTime
{
get { return _storedDateTime; }
set
{
if (_storedDateTime != value)
{
_storedDateTime = value;
OnPropertyChanged(new PropertyChangedEventArgs("StoredDateTime"));
}
}
}
public List<string> StoredList
{
get { return _storedList; }
set
{
_storedList = value;
OnPropertyChanged(new PropertyChangedEventArgs("StoredList"));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Threading;
using Elders.Cronus.Userfull;
using Microsoft.Extensions.Caching.Memory;
namespace Elders.Cronus.AtomicAction.InMemory
{
public class InMemoryAggregateRootAtomicAction : IAggregateRootAtomicAction
{
readonly MemoryCache aggregateLock = null;
readonly MemoryCache aggregateRevisions = null;
readonly MemoryCacheEntryOptions cacheEntryOptions;
public InMemoryAggregateRootAtomicAction()
{
var aggregateLockMemoryCacheOptions = new MemoryCacheOptions()
{
SizeLimit = 500 * 1024 * 1024, //500mb
CompactionPercentage = 0.1, // 10%
ExpirationScanFrequency = new TimeSpan(0, 1, 0)
};
var aggregateRevisionsMemoryCacheOptions = new MemoryCacheOptions()
{
SizeLimit = 500 * 1024 * 1024, //500mb
CompactionPercentage = 0.1, // 10%
ExpirationScanFrequency = new TimeSpan(0, 1, 0)
};
cacheEntryOptions = new MemoryCacheEntryOptions()
{
SlidingExpiration = TimeSpan.FromSeconds(30d),
Size = 1
};
aggregateLock = new MemoryCache(aggregateLockMemoryCacheOptions);
aggregateRevisions = new MemoryCache(aggregateRevisionsMemoryCacheOptions);
}
public Result<bool> Execute(IAggregateRootId aggregateRootId, int aggregateRootRevision, Action action)
{
var result = new Result<bool>(false);
var acquired = new AtomicBoolean(false);
try
{
acquired = aggregateLock.Get(aggregateRootId.Value) as AtomicBoolean;
if (ReferenceEquals(null, acquired))
{
acquired = aggregateLock.Set(aggregateRootId.Value, new AtomicBoolean(false), cacheEntryOptions);
if (ReferenceEquals(null, acquired))
return result;
}
if (acquired.CompareAndSet(false, true))
{
try
{
AtomicInteger revision = aggregateRevisions.Get(aggregateRootId.Value) as AtomicInteger;
if (ReferenceEquals(null, revision))
{
var newRevision = new AtomicInteger(aggregateRootRevision - 1);
revision = aggregateRevisions.Set(aggregateRootId.Value, newRevision, cacheEntryOptions);
if (ReferenceEquals(null, revision))
return result;
}
var currentRevision = revision.Value;
if (revision.CompareAndSet(aggregateRootRevision - 1, aggregateRootRevision))
{
try
{
action();
return Result.Success;
}
catch (Exception)
{
revision.GetAndSet(currentRevision);
throw;
}
}
}
finally
{
acquired.GetAndSet(false);
}
}
return result;
}
catch (Exception ex)
{
return result.WithError(ex);
}
}
public void Dispose()
{
aggregateRevisions?.Dispose();
aggregateLock?.Dispose();
}
}
[Serializable]
public class AtomicBoolean : IFormattable
{
private volatile int booleanValue;
// <summary>
// Gets or sets the current value.
// </summary>
public bool Value
{
get { return this.booleanValue != 0; }
set { this.booleanValue = value ? 1 : 0; }
}
public AtomicBoolean()
: this(false)
{
}
public AtomicBoolean(bool initialValue)
{
Value = initialValue;
}
public bool CompareAndSet(bool expect, bool update)
{
int expectedIntValue = expect ? 1 : 0;
int newIntValue = update ? 1 : 0;
return Interlocked.CompareExchange(ref this.booleanValue, newIntValue, expectedIntValue) == expectedIntValue;
}
public bool GetAndSet(bool newValue)
{
return Interlocked.Exchange(ref this.booleanValue, newValue ? 1 : 0) != 0;
}
public bool WeakCompareAndSet(bool expect, bool update)
{
return CompareAndSet(expect, update);
}
public override bool Equals(object obj)
{
return obj as AtomicBoolean == this;
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override string ToString()
{
return ToString(CultureInfo.CurrentCulture);
}
public string ToString(IFormatProvider formatProvider)
{
return Value.ToString(formatProvider);
}
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
public string ToString(string format, IFormatProvider formatProvider)
{
return Value.ToString(formatProvider);
}
public static bool operator ==(AtomicBoolean left, AtomicBoolean right)
{
if (Object.ReferenceEquals(left, null) || Object.ReferenceEquals(right, null))
return false;
return left.Value == right.Value;
}
public static bool operator !=(AtomicBoolean left, AtomicBoolean right)
{
return !(left == right);
}
public static implicit operator bool(AtomicBoolean atomic)
{
if (atomic == null) { return false; }
else { return atomic.Value; }
}
}
[Serializable]
public class AtomicInteger : IFormattable
{
private volatile int integerValue;
// <summary>
// Gets or sets the current value.
// </summary>
public int Value
{
get { return this.integerValue; }
set { this.integerValue = value; }
}
public AtomicInteger()
: this(0)
{
}
public AtomicInteger(int initialValue)
{
this.integerValue = initialValue;
}
public int AddAndGet(int delta)
{
return Interlocked.Add(ref this.integerValue, delta);
}
public bool CompareAndSet(int expect, int update)
{
return Interlocked.CompareExchange(ref this.integerValue, update, expect) == expect;
}
public int DecrementAndGet()
{
return Interlocked.Decrement(ref this.integerValue);
}
public int GetAndDecrement()
{
return Interlocked.Decrement(ref this.integerValue) + 1;
}
public int GetAndIncrement()
{
return Interlocked.Increment(ref this.integerValue) - 1;
}
public int GetAndSet(int newValue)
{
return Interlocked.Exchange(ref this.integerValue, newValue);
}
public int IncrementAndGet()
{
return Interlocked.Increment(ref this.integerValue);
}
public bool WeakCompareAndSet(int expect, int update)
{
return CompareAndSet(expect, update);
}
public override bool Equals(object obj)
{
return obj as AtomicInteger == this;
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override string ToString()
{
return ToString(CultureInfo.CurrentCulture);
}
public string ToString(IFormatProvider formatProvider)
{
return Value.ToString(formatProvider);
}
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
public string ToString(string format, IFormatProvider formatProvider)
{
return Value.ToString(formatProvider);
}
public static bool operator ==(AtomicInteger left, AtomicInteger right)
{
if (Object.ReferenceEquals(left, null) || Object.ReferenceEquals(right, null))
return false;
return left.Value == right.Value;
}
public static bool operator !=(AtomicInteger left, AtomicInteger right)
{
return !(left == right);
}
public static implicit operator int(AtomicInteger atomic)
{
if (atomic == null)
{
return 0;
}
else
{
return atomic.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.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace System.Net
{
// More sophisticated password cache that stores multiple
// name-password pairs and associates these with host/realm.
public class CredentialCache : ICredentials, ICredentialsByHost, IEnumerable
{
private Dictionary<CredentialKey, NetworkCredential> _cache;
private Dictionary<CredentialHostKey, NetworkCredential> _cacheForHosts;
private int _version;
public CredentialCache()
{
}
public void Add(Uri uriPrefix, string authenticationType, NetworkCredential credential)
{
if (uriPrefix == null)
{
throw new ArgumentNullException(nameof(uriPrefix));
}
if (authenticationType == null)
{
throw new ArgumentNullException(nameof(authenticationType));
}
++_version;
var key = new CredentialKey(uriPrefix, authenticationType);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]");
}
if (_cache == null)
{
_cache = new Dictionary<CredentialKey, NetworkCredential>();
}
_cache.Add(key, credential);
}
public void Add(string host, int port, string authenticationType, NetworkCredential credential)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
if (authenticationType == null)
{
throw new ArgumentNullException(nameof(authenticationType));
}
if (host.Length == 0)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(host)), nameof(host));
}
if (port < 0)
{
throw new ArgumentOutOfRangeException(nameof(port));
}
++_version;
var key = new CredentialHostKey(host, port, authenticationType);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]");
}
if (_cacheForHosts == null)
{
_cacheForHosts = new Dictionary<CredentialHostKey, NetworkCredential>();
}
_cacheForHosts.Add(key, credential);
}
public void Remove(Uri uriPrefix, string authenticationType)
{
if (uriPrefix == null || authenticationType == null)
{
// These couldn't possibly have been inserted into
// the cache because of the test in Add().
return;
}
if (_cache == null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Remove() Short-circuiting because the dictionary is null.");
}
return;
}
++_version;
var key = new CredentialKey(uriPrefix, authenticationType);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");
}
_cache.Remove(key);
}
public void Remove(string host, int port, string authenticationType)
{
if (host == null || authenticationType == null)
{
// These couldn't possibly have been inserted into
// the cache because of the test in Add().
return;
}
if (port < 0)
{
return;
}
if (_cacheForHosts == null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Remove() Short-circuiting because the dictionary is null.");
}
return;
}
++_version;
var key = new CredentialHostKey(host, port, authenticationType);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");
}
_cacheForHosts.Remove(key);
}
public NetworkCredential GetCredential(Uri uriPrefix, string authenticationType)
{
if (uriPrefix == null)
{
throw new ArgumentNullException(nameof(uriPrefix));
}
if (authenticationType == null)
{
throw new ArgumentNullException(nameof(authenticationType));
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential(uriPrefix=\"" + uriPrefix + "\", authType=\"" + authenticationType + "\")");
}
if (_cache == null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential short-circuiting because the dictionary is null.");
}
return null;
}
int longestMatchPrefix = -1;
NetworkCredential mostSpecificMatch = null;
// Enumerate through every credential in the cache
foreach (KeyValuePair<CredentialKey, NetworkCredential> pair in _cache)
{
CredentialKey key = pair.Key;
// Determine if this credential is applicable to the current Uri/AuthType
if (key.Match(uriPrefix, authenticationType))
{
int prefixLen = key.UriPrefixLength;
// Check if the match is better than the current-most-specific match
if (prefixLen > longestMatchPrefix)
{
// Yes: update the information about currently preferred match
longestMatchPrefix = prefixLen;
mostSpecificMatch = pair.Value;
}
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential returning " + ((mostSpecificMatch == null) ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")"));
}
return mostSpecificMatch;
}
public NetworkCredential GetCredential(string host, int port, string authenticationType)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
if (authenticationType == null)
{
throw new ArgumentNullException(nameof(authenticationType));
}
if (host.Length == 0)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(host)), nameof(host));
}
if (port < 0)
{
throw new ArgumentOutOfRangeException(nameof(port));
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential(host=\"" + host + ":" + port.ToString() + "\", authenticationType=\"" + authenticationType + "\")");
}
if (_cacheForHosts == null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential short-circuiting because the dictionary is null.");
}
return null;
}
var key = new CredentialHostKey(host, port, authenticationType);
NetworkCredential match = null;
_cacheForHosts.TryGetValue(key, out match);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential returning " + ((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")"));
}
return match;
}
public IEnumerator GetEnumerator() => CredentialEnumerator.Create(this);
public static ICredentials DefaultCredentials => SystemNetworkCredential.s_defaultCredential;
public static NetworkCredential DefaultNetworkCredentials => SystemNetworkCredential.s_defaultCredential;
private class CredentialEnumerator : IEnumerator
{
internal static CredentialEnumerator Create(CredentialCache cache)
{
Debug.Assert(cache != null);
if (cache._cache != null)
{
return cache._cacheForHosts != null ?
new DoubleTableCredentialEnumerator(cache) :
new SingleTableCredentialEnumerator<CredentialKey>(cache, cache._cache);
}
else
{
return cache._cacheForHosts != null ?
new SingleTableCredentialEnumerator<CredentialHostKey>(cache, cache._cacheForHosts) :
new CredentialEnumerator(cache);
}
}
private readonly CredentialCache _cache;
private readonly int _version;
private bool _enumerating;
private NetworkCredential _current;
private CredentialEnumerator(CredentialCache cache)
{
Debug.Assert(cache != null);
_cache = cache;
_version = cache._version;
}
public object Current
{
get
{
if (!_enumerating)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
if (_version != _cache._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
return _current;
}
}
public bool MoveNext()
{
if (_version != _cache._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
return _enumerating = MoveNext(out _current);
}
protected virtual bool MoveNext(out NetworkCredential current)
{
current = null;
return false;
}
public virtual void Reset()
{
_enumerating = false;
}
private class SingleTableCredentialEnumerator<TKey> : CredentialEnumerator
{
private Dictionary<TKey, NetworkCredential>.ValueCollection.Enumerator _enumerator; // mutable struct field deliberately not readonly.
public SingleTableCredentialEnumerator(CredentialCache cache, Dictionary<TKey, NetworkCredential> table) : base(cache)
{
Debug.Assert(table != null);
// Despite the ValueCollection allocation, ValueCollection's enumerator is faster
// than Dictionary's enumerator for enumerating the values because it avoids
// KeyValuePair copying.
_enumerator = table.Values.GetEnumerator();
}
protected override bool MoveNext(out NetworkCredential current) =>
DictionaryEnumeratorHelper.MoveNext(ref _enumerator, out current);
public override void Reset()
{
DictionaryEnumeratorHelper.Reset(ref _enumerator);
base.Reset();
}
}
private sealed class DoubleTableCredentialEnumerator : SingleTableCredentialEnumerator<CredentialKey>
{
private Dictionary<CredentialHostKey, NetworkCredential>.ValueCollection.Enumerator _enumerator; // mutable struct field deliberately not readonly.
private bool _onThisEnumerator;
public DoubleTableCredentialEnumerator(CredentialCache cache) : base(cache, cache._cache)
{
Debug.Assert(cache._cacheForHosts != null);
// Despite the ValueCollection allocation, ValueCollection's enumerator is faster
// than Dictionary's enumerator for enumerating the values because it avoids
// KeyValuePair copying.
_enumerator = cache._cacheForHosts.Values.GetEnumerator();
}
protected override bool MoveNext(out NetworkCredential current)
{
if (!_onThisEnumerator)
{
if (base.MoveNext(out current))
{
return true;
}
else
{
_onThisEnumerator = true;
}
}
return DictionaryEnumeratorHelper.MoveNext(ref _enumerator, out current);
}
public override void Reset()
{
_onThisEnumerator = false;
DictionaryEnumeratorHelper.Reset(ref _enumerator);
base.Reset();
}
}
private static class DictionaryEnumeratorHelper
{
internal static bool MoveNext<TKey, TValue>(ref Dictionary<TKey, TValue>.ValueCollection.Enumerator enumerator, out TValue current)
{
bool result = enumerator.MoveNext();
current = enumerator.Current;
return result;
}
// Allows calling Reset on Dictionary's struct enumerator without a box allocation.
internal static void Reset<TEnumerator>(ref TEnumerator enumerator) where TEnumerator : IEnumerator
{
// The Dictionary enumerator's Reset method throws if the Dictionary has changed, but
// CredentialCache.Reset should not throw, so we catch and swallow the exception.
try { enumerator.Reset(); } catch (InvalidOperationException) { }
}
}
}
}
// Abstraction for credentials in password-based
// authentication schemes (basic, digest, NTLM, Kerberos).
//
// Note that this is not applicable to public-key based
// systems such as SSL client authentication.
//
// "Password" here may be the clear text password or it
// could be a one-way hash that is sufficient to
// authenticate, as in HTTP/1.1 digest.
internal sealed class SystemNetworkCredential : NetworkCredential
{
internal static readonly SystemNetworkCredential s_defaultCredential = new SystemNetworkCredential();
// We want reference equality to work. Making this private is a good way to guarantee that.
private SystemNetworkCredential() :
base(string.Empty, string.Empty, string.Empty)
{
}
}
internal struct CredentialHostKey : IEquatable<CredentialHostKey>
{
public readonly string Host;
public readonly string AuthenticationType;
public readonly int Port;
internal CredentialHostKey(string host, int port, string authenticationType)
{
Debug.Assert(!string.IsNullOrEmpty(host));
Debug.Assert(port >= 0);
Debug.Assert(authenticationType != null);
Host = host;
Port = port;
AuthenticationType = authenticationType;
}
public override int GetHashCode() =>
StringComparer.OrdinalIgnoreCase.GetHashCode(AuthenticationType) ^
StringComparer.OrdinalIgnoreCase.GetHashCode(Host) ^
Port.GetHashCode();
public bool Equals(CredentialHostKey other)
{
bool equals =
string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) &&
string.Equals(Host, other.Host, StringComparison.OrdinalIgnoreCase) &&
Port == other.Port;
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialHostKey::Equals(" + ToString() + ", " + other.ToString() + ") returns " + equals.ToString());
}
return equals;
}
public override bool Equals(object obj) =>
obj is CredentialHostKey && Equals((CredentialHostKey)obj);
public override string ToString() =>
Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + LoggingHash.ObjectToString(AuthenticationType);
}
internal sealed class CredentialKey : IEquatable<CredentialKey>
{
public readonly Uri UriPrefix;
public readonly int UriPrefixLength = -1;
public readonly string AuthenticationType;
internal CredentialKey(Uri uriPrefix, string authenticationType)
{
Debug.Assert(uriPrefix != null);
Debug.Assert(authenticationType != null);
UriPrefix = uriPrefix;
UriPrefixLength = UriPrefix.ToString().Length;
AuthenticationType = authenticationType;
}
internal bool Match(Uri uri, string authenticationType)
{
if (uri == null || authenticationType == null)
{
return false;
}
// If the protocols don't match, this credential is not applicable for the given Uri.
if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialKey::Match(" + UriPrefix.ToString() + " & " + uri.ToString() + ")");
}
return IsPrefix(uri, UriPrefix);
}
// IsPrefix (Uri)
//
// Determines whether <prefixUri> is a prefix of this URI. A prefix
// match is defined as:
//
// scheme match
// + host match
// + port match, if any
// + <prefix> path is a prefix of <URI> path, if any
//
// Returns:
// True if <prefixUri> is a prefix of this URI
private static bool IsPrefix(Uri uri, Uri prefixUri)
{
Debug.Assert(uri != null);
Debug.Assert(prefixUri != null);
if (prefixUri.Scheme != uri.Scheme || prefixUri.Host != uri.Host || prefixUri.Port != uri.Port)
{
return false;
}
int prefixLen = prefixUri.AbsolutePath.LastIndexOf('/');
if (prefixLen > uri.AbsolutePath.LastIndexOf('/'))
{
return false;
}
return string.Compare(uri.AbsolutePath, 0, prefixUri.AbsolutePath, 0, prefixLen, StringComparison.OrdinalIgnoreCase) == 0;
}
public override int GetHashCode() =>
StringComparer.OrdinalIgnoreCase.GetHashCode(AuthenticationType) ^
UriPrefix.GetHashCode();
public bool Equals(CredentialKey other)
{
if (other == null)
{
return false;
}
bool equals =
string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) &&
UriPrefix.Equals(other.UriPrefix);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + other.ToString() + ") returns " + equals.ToString());
}
return equals;
}
public override bool Equals(object obj) => Equals(obj as CredentialKey);
public override string ToString() =>
"[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + LoggingHash.ObjectToString(UriPrefix) + ":" + LoggingHash.ObjectToString(AuthenticationType);
}
}
| |
#region Copyright (c) 2003, newtelligence AG. All rights reserved.
/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com)
// 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.
// (3) Neither the name of the newtelligence AG 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.
// -------------------------------------------------------------------------
//
// Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com)
//
// newtelligence is a registered trademark of newtelligence Aktiengesellschaft.
//
// For portions of this software, the some additional copyright notices may apply
// which can either be found in the license.txt file included in the source distribution
// or following this notice.
//
*/
#endregion
using System;
using System.Collections.Generic;
namespace newtelligence.DasBlog.Runtime
{
/// <summary>
///
/// </summary>
internal class EntryIdCache
{
private EntryIdCache()
{
// empty
}
// storage
private EntryCollection entriesCache;
private Dictionary<string, DateTime> entryIDToDate = new Dictionary<string, DateTime>(StringComparer.InvariantCultureIgnoreCase);
private Dictionary<string, DateTime> compressedTitleToDate = new Dictionary<string, DateTime>(StringComparer.InvariantCultureIgnoreCase);
// used for synchronisation
private static object entriesLock = new object();
private bool booting = true;
// used for versioning the cache
private long changeNumber;
/// <summary>
/// The CurrentEntryChangeCount from the datamanager,
/// when we build the cache.
/// </summary>
public long ChangeNumber { get { return changeNumber; } }
// the instance
private static EntryIdCache instance = new EntryIdCache();
/// <summary>
/// Gets the instance of the EntryIdCache.
/// </summary>
/// <param name="data">Datamanager used to load the data.</param>
/// <returns>The instance.</returns>
public static EntryIdCache GetInstance(DataManager data)
{
// handles the thread safe loading,
// can't be moved to the constructor,
// because a change in the 'CurrentEntryChangeCount' will force a rebuild
instance.Ensure(data);
return instance;
}
/// <summary>
/// Returns a collection of 'lite' entries, with the comment and the description set to String.Empty
/// and the attached collections cleared for faster access.
/// </summary>
/// <returns></returns>
public EntryCollection GetEntries()
{
return (EntryCollection)entriesCache.Clone();
}
private void Ensure(DataManager data)
{
if (!Loaded || booting || changeNumber != data.CurrentEntryChangeCount)
{
lock (entriesLock)
{
if (!Loaded || booting || changeNumber != data.CurrentEntryChangeCount)
{
if (Build(data))
{
// if we succesfully build, we're no longer booting
booting = false;
}
}
}
}
}
private bool Build(DataManager data)
{
EntryCollection entriesCacheCopy = new EntryCollection();
Dictionary<string, DateTime> entryIdToDateCopy = new Dictionary<string, DateTime>(StringComparer.InvariantCultureIgnoreCase);
Dictionary<string, DateTime> compressedTitleToDateCopy = new Dictionary<string, DateTime>(StringComparer.InvariantCultureIgnoreCase);
try
{
foreach (DayEntry day in data.Days)
{
day.Load(data);
foreach (Entry entry in day.Entries)
{
// create a lite entry for faster searching
Entry copy = entry.Clone();
copy.Content = "";
copy.Description = "";
copy.AttachmentsArray = null;
copy.CrosspostArray = null;
entriesCacheCopy.Add(copy);
entryIdToDateCopy.Add(copy.EntryId, copy.CreatedUtc.Date);
//SDH: Only the first title is kept, in case of duplicates
// TODO: should be able to fix this, but it's a bunch of work.
string compressedTitle = copy.CompressedTitle;
compressedTitle = compressedTitle.Replace("+", "");
if (compressedTitleToDateCopy.ContainsKey(compressedTitle) == false)
{
compressedTitleToDateCopy.Add(compressedTitle, copy.CreatedUtc.Date);
}
}
}
}
//TODO: SDH: Temporary, as sometimes we get collection was modified from the EntryCollection...why does this happen? "Database" corruption?
// Misaligned Entries?
catch (InvalidOperationException) //something wrong enumerating the entries?
{
//set flags to start over to prevent getting stuck...
booting = true;
changeNumber = 0;
throw;
}
//try to be a little more "Atomic" as others have been enumerating this list...
entryIDToDate.Clear();
entryIDToDate = entryIdToDateCopy;
compressedTitleToDate.Clear();
compressedTitleToDate = compressedTitleToDateCopy;
entriesCache = entriesCacheCopy;
changeNumber = data.CurrentEntryChangeCount;
return true;
}
internal string GetTitleFromEntryId(string entryid)
{
Entry retVal = entriesCache[entryid];
if (retVal == null)
{
return null;
}
return retVal.Title;
}
internal DateTime GetDateFromEntryId(string entryid)
{
DateTime retVal;
if (entryIDToDate.TryGetValue(entryid, out retVal))
{
return retVal;
}
return DateTime.MinValue;
}
internal DateTime GetDateFromCompressedTitle(string title)
{
DateTime retVal;
if (compressedTitleToDate.TryGetValue(title, out retVal))
{
return retVal;
}
return DateTime.MinValue;
}
private bool Loaded
{
get
{
//return true if we are loaded
if (entriesCache == null)
{
return false;
}
return true;
}
}
}
}
| |
//---------------------------------------------------------------------
// Author: jachymko, Keith Hill
//
// Description: Class to implement the Get-PSSnapinHelp cmdlet.
// Generates a XML file containing all documentation data.
//
// Creation Date: Dec 23, 2006
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation;
using System.Reflection;
using System.Xml;
using Microsoft.PowerShell.Commands;
using Pscx.IO;
namespace Pscx.Commands.SnapinHelp
{
[Cmdlet(VerbsCommon.Get, "PSSnapinHelp", DefaultParameterSetName = ParameterSetPath)]
[ProviderConstraint(typeof(FileSystemProvider))]
public partial class GetSnapinHelpCommand : PscxInputObjectPathCommandBase
{
private const string NamespaceXmlSchema = "http://www.w3.org/2001/XMLSchema";
private const string NamespaceXmlSchemaInstance = "http://www.w3.org/2001/XMLSchema-instance";
private Visitor _visitor;
private XmlWriter _xmlWriter;
private List<CmdletInfo> _cmdlets;
[Parameter(Mandatory=true)]
[PscxPath(NoGlobbing = true)]
[ValidateNotNullOrEmpty]
public PscxPathInfo LocalizedHelpPath { get; set; }
[Parameter(Mandatory = true)]
[PscxPath(NoGlobbing = true)]
[ValidateNotNullOrEmpty]
public PscxPathInfo OutputPath { get; set; }
protected override void BeginProcessing()
{
_cmdlets = new List<CmdletInfo>();
_visitor = new Visitor(this);
RegisterInputType<Assembly>(ProcessAssembly);
RegisterInputType<PSSnapInInfo>(ProcessSnapIn);
base.BeginProcessing();
}
protected override void ProcessPath(PscxPathInfo pscxPath)
{
Assembly assembly = null;
string filePath = pscxPath.ProviderPath;
try
{
assembly = Assembly.LoadFrom(filePath);
}
catch (PipelineStoppedException)
{
throw;
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, "FailedAssemblyLoadFrom", ErrorCategory.InvalidArgument, filePath));
return;
}
ProcessAssembly(assembly);
}
private void ProcessSnapIn(PSSnapInInfo snapinInfo)
{
ProcessPath(PscxPathInfo.GetPscxPathInfo(this.SessionState, snapinInfo.ModuleName));
}
private void ProcessAssembly(Assembly assembly)
{
_visitor.VisitAssembly(assembly);
using (var fileStream = new FileStream(OutputPath.ProviderPath, FileMode.Create))
{
var xmlWriterSettings = new XmlWriterSettings {Indent = true};
using (_xmlWriter = XmlWriter.Create(fileStream, xmlWriterSettings))
{
_xmlWriter.WriteStartElement("Cmdlets");
_xmlWriter.WriteAttributeString("xmlns", "xsd", null, NamespaceXmlSchema);
_xmlWriter.WriteAttributeString("xmlns", "xsi", null, NamespaceXmlSchemaInstance);
foreach (CmdletInfo cmdletInfo in _cmdlets)
{
cmdletInfo.MergeWithLocalizedXml(LocalizedHelpPath.ProviderPath);
WriteCmdlet(cmdletInfo);
}
_xmlWriter.WriteEndElement(); // </Cmdlets>
_xmlWriter.WriteEndDocument();
fileStream.Flush();
}
}
}
private void WriteCmdlet(CmdletInfo cmdletInfo)
{
_xmlWriter.WriteStartElement("Cmdlet");
_xmlWriter.WriteAttributeString("TypeName", cmdletInfo.Type.FullName);
string description = cmdletInfo.Description;
string detailed = cmdletInfo.DetailedDescription;
if (string.IsNullOrEmpty(detailed)) detailed = description;
_xmlWriter.WriteElementString("Verb", cmdletInfo.Verb);
_xmlWriter.WriteElementString("Noun", cmdletInfo.Noun);
_xmlWriter.WriteElementString("Description", description);
_xmlWriter.WriteElementString("DetailedDescription", detailed);
WriteParameterSets(cmdletInfo);
WriteParameters(cmdletInfo);
WriteXmlNodeList(cmdletInfo.InputTypes, "InputType");
WriteXmlNodeList(cmdletInfo.ReturnTypes, "ReturnType");
WriteXmlNodeList(cmdletInfo.Notes, "Note");
WriteXmlNodeList(cmdletInfo.Examples, "Example");
WriteStringList(cmdletInfo.RelatedLinks, "RelatedLink");
_xmlWriter.WriteEndElement(); // </Cmdlet>
}
private void WriteParameterSets(CmdletInfo cmdletInfo)
{
_xmlWriter.WriteStartElement("ParameterSets");
if (cmdletInfo.NamedParameterSets.Count == 0)
{
WriteParameterSet(string.Empty, cmdletInfo.AllParametersParameterSet);
}
else
{
foreach(string setName in cmdletInfo.NamedParameterSets.Keys)
{
List<ParameterInfo> currentSet = new List<ParameterInfo>();
currentSet.AddRange(cmdletInfo.AllParametersParameterSet);
currentSet.AddRange(cmdletInfo.NamedParameterSets[setName]);
WriteParameterSet(setName, currentSet);
}
}
_xmlWriter.WriteEndElement(); // </ParameterSets>
}
private void WriteParameterSet(string name, List<ParameterInfo> parameters)
{
parameters.Sort(ParameterComparer);
_xmlWriter.WriteStartElement("ParameterSet");
if (!string.IsNullOrEmpty(name))
{
_xmlWriter.WriteAttributeString("Name", name);
}
foreach(ParameterInfo pi in parameters)
WriteParameter(pi);
_xmlWriter.WriteEndElement();
}
private void WriteParameter(ParameterInfo paramInfo)
{
paramInfo.WriteTo(_xmlWriter);
}
private void WriteParameters(CmdletInfo cmdletInfo)
{
_xmlWriter.WriteStartElement("Parameters");
List<ParameterInfo> all = new List<ParameterInfo>(cmdletInfo.GetAllParameters());
all.Sort(ParameterComparer);
foreach(ParameterInfo pi in all)
{
WriteParameter(pi);
}
_xmlWriter.WriteEndElement(); // </Parameters>
}
private void WriteXmlNodeList(IEnumerable<XmlNode> nodes, string singularTagName)
{
WriteList<XmlNode>(nodes, singularTagName, delegate(XmlNode xn)
{
xn.WriteTo(_xmlWriter);
});
}
private void WriteStringList(IEnumerable<String> items, string singularTagName)
{
WriteList<String>(items, singularTagName, delegate(string s)
{
_xmlWriter.WriteStartElement(singularTagName);
_xmlWriter.WriteString(s);
_xmlWriter.WriteEndElement();
});
}
private void WriteList<T>(IEnumerable<T> items, string singularTagName, Action<T> action)
{
_xmlWriter.WriteStartElement(singularTagName + 's');
foreach (T item in items)
{
action(item);
}
_xmlWriter.WriteEndElement();
}
private int ParameterComparer(ParameterInfo x, ParameterInfo y)
{
int xp = x.Position;
int yp = y.Position;
if(xp < 0 && yp < 0) return 0;
if(yp < 0) return -1;
if(xp < 0) return 1;
return xp.CompareTo(yp);
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using System.Diagnostics;
using log4net.Util;
namespace log4net.Core
{
/// <summary>
/// The internal representation of caller location information.
/// </summary>
/// <remarks>
/// <para>
/// This class uses the <c>System.Diagnostics.StackTrace</c> class to generate
/// a call stack. The caller's information is then extracted from this stack.
/// </para>
/// <para>
/// The <c>System.Diagnostics.StackTrace</c> class is not supported on the
/// .NET Compact Framework 1.0 therefore caller location information is not
/// available on that framework.
/// </para>
/// <para>
/// The <c>System.Diagnostics.StackTrace</c> class has this to say about Release builds:
/// </para>
/// <para>
/// "StackTrace information will be most informative with Debug build configurations.
/// By default, Debug builds include debug symbols, while Release builds do not. The
/// debug symbols contain most of the file, method name, line number, and column
/// information used in constructing StackFrame and StackTrace objects. StackTrace
/// might not report as many method calls as expected, due to code transformations
/// that occur during optimization."
/// </para>
/// <para>
/// This means that in a Release build the caller information may be incomplete or may
/// not exist at all! Therefore caller location information cannot be relied upon in a Release build.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
#if !NETCF
[Serializable]
#endif
public class LocationInfo
{
#region Public Instance Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is
/// the stack boundary into the logging system for this call.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="LocationInfo" />
/// class based on the current thread.
/// </para>
/// </remarks>
public LocationInfo(Type callerStackBoundaryDeclaringType)
{
// Initialize all fields
m_className = NA;
m_fileName = NA;
m_lineNumber = NA;
m_methodName = NA;
m_fullInfo = NA;
#if !NETCF
if (callerStackBoundaryDeclaringType != null)
{
try
{
StackTrace st = new StackTrace(true);
int frameIndex = 0;
// skip frames not from fqnOfCallingClass
while (frameIndex < st.FrameCount)
{
StackFrame frame = st.GetFrame(frameIndex);
if (frame != null && frame.GetMethod().DeclaringType == callerStackBoundaryDeclaringType)
{
break;
}
frameIndex++;
}
// skip frames from fqnOfCallingClass
while (frameIndex < st.FrameCount)
{
StackFrame frame = st.GetFrame(frameIndex);
if (frame != null && frame.GetMethod().DeclaringType != callerStackBoundaryDeclaringType)
{
break;
}
frameIndex++;
}
if (frameIndex < st.FrameCount)
{
// take into account the frames we skip above
int adjustedFrameCount = st.FrameCount - frameIndex;
ArrayList stackFramesList = new ArrayList(adjustedFrameCount);
m_stackFrames = new StackFrame[adjustedFrameCount];
for (int i=frameIndex; i < st.FrameCount; i++)
{
stackFramesList.Add(st.GetFrame(i));
}
stackFramesList.CopyTo(m_stackFrames, 0);
// now frameIndex is the first 'user' caller frame
StackFrame locationFrame = st.GetFrame(frameIndex);
if (locationFrame != null)
{
System.Reflection.MethodBase method = locationFrame.GetMethod();
if (method != null)
{
m_methodName = method.Name;
if (method.DeclaringType != null)
{
m_className = method.DeclaringType.FullName;
}
}
m_fileName = locationFrame.GetFileName();
m_lineNumber = locationFrame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
// Combine all location info
m_fullInfo = m_className + '.' + m_methodName + '(' + m_fileName + ':' + m_lineNumber + ')';
}
}
}
catch(System.Security.SecurityException)
{
// This security exception will occur if the caller does not have
// some undefined set of SecurityPermission flags.
LogLog.Debug(declaringType, "Security exception while trying to get caller stack frame. Error Ignored. Location Information Not Available.");
}
}
#endif
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="className">The fully qualified class name.</param>
/// <param name="methodName">The method name.</param>
/// <param name="fileName">The file name.</param>
/// <param name="lineNumber">The line number of the method within the file.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="LocationInfo" />
/// class with the specified data.
/// </para>
/// </remarks>
public LocationInfo(string className, string methodName, string fileName, string lineNumber)
{
m_className = className;
m_fileName = fileName;
m_lineNumber = lineNumber;
m_methodName = methodName;
m_fullInfo = m_className + '.' + m_methodName + '(' + m_fileName +
':' + m_lineNumber + ')';
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets the fully qualified class name of the caller making the logging
/// request.
/// </summary>
/// <value>
/// The fully qualified class name of the caller making the logging
/// request.
/// </value>
/// <remarks>
/// <para>
/// Gets the fully qualified class name of the caller making the logging
/// request.
/// </para>
/// </remarks>
public string ClassName
{
get { return m_className; }
}
/// <summary>
/// Gets the file name of the caller.
/// </summary>
/// <value>
/// The file name of the caller.
/// </value>
/// <remarks>
/// <para>
/// Gets the file name of the caller.
/// </para>
/// </remarks>
public string FileName
{
get { return m_fileName; }
}
/// <summary>
/// Gets the line number of the caller.
/// </summary>
/// <value>
/// The line number of the caller.
/// </value>
/// <remarks>
/// <para>
/// Gets the line number of the caller.
/// </para>
/// </remarks>
public string LineNumber
{
get { return m_lineNumber; }
}
/// <summary>
/// Gets the method name of the caller.
/// </summary>
/// <value>
/// The method name of the caller.
/// </value>
/// <remarks>
/// <para>
/// Gets the method name of the caller.
/// </para>
/// </remarks>
public string MethodName
{
get { return m_methodName; }
}
/// <summary>
/// Gets all available caller information
/// </summary>
/// <value>
/// All available caller information, in the format
/// <c>fully.qualified.classname.of.caller.methodName(Filename:line)</c>
/// </value>
/// <remarks>
/// <para>
/// Gets all available caller information, in the format
/// <c>fully.qualified.classname.of.caller.methodName(Filename:line)</c>
/// </para>
/// </remarks>
public string FullInfo
{
get { return m_fullInfo; }
}
#if !NETCF
/// <summary>
/// Gets the stack frames from the stack trace of the caller making the log request
/// </summary>
public StackFrame[] StackFrames
{
get { return m_stackFrames; }
}
#endif
#endregion Public Instance Properties
#region Private Instance Fields
private readonly string m_className;
private readonly string m_fileName;
private readonly string m_lineNumber;
private readonly string m_methodName;
private readonly string m_fullInfo;
#if !NETCF
private readonly StackFrame[] m_stackFrames;
#endif
#endregion Private Instance Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the LocationInfo class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(LocationInfo);
/// <summary>
/// When location information is not available the constant
/// <c>NA</c> is returned. Current value of this string
/// constant is <b>?</b>.
/// </summary>
private const string NA = "?";
#endregion Private Static Fields
}
}
| |
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq;
using System;
namespace UnityEditor.iOS.Xcode.PBX
{
enum TokenType
{
EOF,
Invalid,
String,
QuotedString,
Comment,
Semicolon, // ;
Comma, // ,
Eq, // =
LParen, // (
RParen, // )
LBrace, // {
RBrace, // }
}
class Token
{
public TokenType type;
// the line of the input stream the token starts in (0-based)
public int line;
// start and past-the-end positions of the token in the input stream
public int begin, end;
}
class TokenList : List<Token>
{
}
class Lexer
{
string text;
int pos;
int length;
int line;
public static TokenList Tokenize(string text)
{
var lexer = new Lexer();
lexer.SetText(text);
return lexer.ScanAll();
}
public void SetText(string text)
{
this.text = text + " "; // to prevent out-of-bounds access during look ahead
pos = 0;
length = text.Length;
line = 0;
}
public TokenList ScanAll()
{
var tokens = new TokenList();
while (true)
{
var tok = new Token();
ScanOne(tok);
tokens.Add(tok);
if (tok.type == TokenType.EOF)
break;
}
return tokens;
}
void UpdateNewlineStats(char ch)
{
if (ch == '\n')
line++;
}
// tokens list is modified in the case when we add BrokenLine token and need to remove already
// added tokens for the current line
void ScanOne(Token tok)
{
while (true)
{
while (pos < length && Char.IsWhiteSpace(text[pos]))
{
UpdateNewlineStats(text[pos]);
pos++;
}
if (pos >= length)
{
tok.type = TokenType.EOF;
break;
}
char ch = text[pos];
char ch2 = text[pos+1];
if (ch == '\"')
ScanQuotedString(tok);
else if (ch == '/' && ch2 == '*')
ScanMultilineComment(tok);
else if (ch == '/' && ch2 == '/')
ScanComment(tok);
else if (IsOperator(ch))
ScanOperator(tok);
else
ScanString(tok); // be more robust and accept whatever is left
return;
}
}
void ScanString(Token tok)
{
tok.type = TokenType.String;
tok.begin = pos;
while (pos < length)
{
char ch = text[pos];
char ch2 = text[pos+1];
if (Char.IsWhiteSpace(ch))
break;
else if (ch == '\"')
break;
else if (ch == '/' && ch2 == '*')
break;
else if (ch == '/' && ch2 == '/')
break;
else if (IsOperator(ch))
break;
pos++;
}
tok.end = pos;
tok.line = line;
}
void ScanQuotedString(Token tok)
{
tok.type = TokenType.QuotedString;
tok.begin = pos;
pos++;
while (pos < length)
{
// ignore escaped quotes
if (text[pos] == '\\' && text[pos+1] == '\"')
{
pos += 2;
continue;
}
// note that we close unclosed quotes
if (text[pos] == '\"')
break;
UpdateNewlineStats(text[pos]);
pos++;
}
pos++;
tok.end = pos;
tok.line = line;
}
void ScanMultilineComment(Token tok)
{
tok.type = TokenType.Comment;
tok.begin = pos;
pos += 2;
while (pos < length)
{
if (text[pos] == '*' && text[pos+1] == '/')
break;
// we support multiline comments
UpdateNewlineStats(text[pos]);
pos++;
}
pos += 2;
tok.end = pos;
tok.line = line;
}
void ScanComment(Token tok)
{
tok.type = TokenType.Comment;
tok.begin = pos;
pos += 2;
while (pos < length)
{
if (text[pos] == '\n')
break;
pos++;
}
UpdateNewlineStats(text[pos]);
pos++;
tok.end = pos;
tok.line = line;
}
bool IsOperator(char ch)
{
if (";,=(){}".Contains(ch))
return true;
return false;
}
void ScanOperator(Token tok)
{
switch (text[pos])
{
case ';': ScanOperatorSpecific(tok, TokenType.Semicolon); return;
case ',': ScanOperatorSpecific(tok, TokenType.Comma); return;
case '=': ScanOperatorSpecific(tok, TokenType.Eq); return;
case '(': ScanOperatorSpecific(tok, TokenType.LParen); return;
case ')': ScanOperatorSpecific(tok, TokenType.RParen); return;
case '{': ScanOperatorSpecific(tok, TokenType.LBrace); return;
case '}': ScanOperatorSpecific(tok, TokenType.RBrace); return;
default: return;
}
}
void ScanOperatorSpecific(Token tok, TokenType type)
{
tok.type = type;
tok.begin = pos;
pos++;
tok.end = pos;
tok.line = line;
}
}
} // namespace UnityEditor.iOS.Xcode
| |
// <copyright file="Proxy.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
namespace OpenQA.Selenium
{
/// <summary>
/// Describes the kind of proxy.
/// </summary>
/// <remarks>
/// Keep these in sync with the Firefox preferences numbers:
/// http://kb.mozillazine.org/Network.proxy.type
/// </remarks>
public enum ProxyKind
{
/// <summary>
/// Direct connection, no proxy (default on Windows).
/// </summary>
Direct = 0,
/// <summary>
/// Manual proxy settings (e.g., for httpProxy).
/// </summary>
Manual,
/// <summary>
/// Proxy automatic configuration from URL.
/// </summary>
ProxyAutoConfigure,
/// <summary>
/// Use proxy automatic detection.
/// </summary>
AutoDetect = 4,
/// <summary>
/// Use the system values for proxy settings (default on Linux).
/// </summary>
System,
/// <summary>
/// No proxy type is specified.
/// </summary>
Unspecified
}
/// <summary>
/// Describes proxy settings to be used with a driver instance.
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public class Proxy
{
private ProxyKind proxyKind = ProxyKind.Unspecified;
private bool isAutoDetect;
private string ftpProxyLocation;
private string httpProxyLocation;
private string proxyAutoConfigUrl;
private string sslProxyLocation;
private string socksProxyLocation;
private string socksUserName;
private string socksPassword;
private List<string> noProxyAddresses = new List<string>();
/// <summary>
/// Initializes a new instance of the <see cref="Proxy"/> class.
/// </summary>
public Proxy()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Proxy"/> class with the given proxy settings.
/// </summary>
/// <param name="settings">A dictionary of settings to use with the proxy.</param>
public Proxy(Dictionary<string, object> settings)
{
if (settings == null)
{
throw new ArgumentNullException("settings", "settings dictionary cannot be null");
}
if (settings.ContainsKey("proxyType"))
{
ProxyKind rawType = (ProxyKind)Enum.Parse(typeof(ProxyKind), settings["proxyType"].ToString(), true);
this.Kind = rawType;
}
if (settings.ContainsKey("ftpProxy"))
{
this.FtpProxy = settings["ftpProxy"].ToString();
}
if (settings.ContainsKey("httpProxy"))
{
this.HttpProxy = settings["httpProxy"].ToString();
}
if (settings.ContainsKey("noProxy"))
{
List<string> bypassAddresses = new List<string>();
string addressesAsString = settings["noProxy"] as string;
if (addressesAsString != null)
{
bypassAddresses.AddRange(addressesAsString.Split(';'));
}
else
{
object[] addressesAsArray = settings["noProxy"] as object[];
if (addressesAsArray != null)
{
foreach (object address in addressesAsArray)
{
bypassAddresses.Add(address.ToString());
}
}
}
this.AddBypassAddresses(bypassAddresses);
}
if (settings.ContainsKey("proxyAutoconfigUrl"))
{
this.ProxyAutoConfigUrl = settings["proxyAutoconfigUrl"].ToString();
}
if (settings.ContainsKey("sslProxy"))
{
this.SslProxy = settings["sslProxy"].ToString();
}
if (settings.ContainsKey("socksProxy"))
{
this.SocksProxy = settings["socksProxy"].ToString();
}
if (settings.ContainsKey("socksUsername"))
{
this.SocksUserName = settings["socksUsername"].ToString();
}
if (settings.ContainsKey("socksPassword"))
{
this.SocksPassword = settings["socksPassword"].ToString();
}
if (settings.ContainsKey("autodetect"))
{
this.IsAutoDetect = (bool)settings["autodetect"];
}
}
/// <summary>
/// Gets or sets the type of proxy.
/// </summary>
[JsonIgnore]
public ProxyKind Kind
{
get
{
return this.proxyKind;
}
set
{
this.VerifyProxyTypeCompatilibily(value);
this.proxyKind = value;
}
}
/// <summary>
/// Gets the type of proxy as a string for JSON serialization.
/// </summary>
[JsonProperty("proxyType")]
public string SerializableProxyKind
{
get
{
if (this.proxyKind == ProxyKind.ProxyAutoConfigure)
{
return "PAC";
}
return this.proxyKind.ToString().ToUpperInvariant();
}
}
/// <summary>
/// Gets or sets a value indicating whether the proxy uses automatic detection.
/// </summary>
[JsonIgnore]
public bool IsAutoDetect
{
get
{
return this.isAutoDetect;
}
set
{
if (this.isAutoDetect == value)
{
return;
}
this.VerifyProxyTypeCompatilibily(ProxyKind.AutoDetect);
this.proxyKind = ProxyKind.AutoDetect;
this.isAutoDetect = value;
}
}
/// <summary>
/// Gets or sets the value of the proxy for the FTP protocol.
/// </summary>
[JsonProperty("ftpProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string FtpProxy
{
get
{
return this.ftpProxyLocation;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.ftpProxyLocation = value;
}
}
/// <summary>
/// Gets or sets the value of the proxy for the HTTP protocol.
/// </summary>
[JsonProperty("httpProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string HttpProxy
{
get
{
return this.httpProxyLocation;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.httpProxyLocation = value;
}
}
/// <summary>
/// Gets or sets the value for bypass proxy addresses.
/// </summary>
[Obsolete("Add addresses to bypass with the proxy by using the AddBypassAddress method.")]
public string NoProxy
{
get
{
return this.BypassProxyAddresses;
}
set
{
this.AddBypassAddress(value);
}
}
/// <summary>
/// Gets the semicolon delimited list of address for which to bypass the proxy.
/// </summary>
[JsonProperty("noProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string BypassProxyAddresses
{
get
{
if (this.noProxyAddresses.Count == 0)
{
return null;
}
return string.Join(";", this.noProxyAddresses.ToArray());
}
}
/// <summary>
/// Gets or sets the URL used for proxy automatic configuration.
/// </summary>
[JsonProperty("proxyAutoconfigUrl", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string ProxyAutoConfigUrl
{
get
{
return this.proxyAutoConfigUrl;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.ProxyAutoConfigure);
this.proxyKind = ProxyKind.ProxyAutoConfigure;
this.proxyAutoConfigUrl = value;
}
}
/// <summary>
/// Gets or sets the value of the proxy for the SSL protocol.
/// </summary>
[JsonProperty("sslProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string SslProxy
{
get
{
return this.sslProxyLocation;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.sslProxyLocation = value;
}
}
/// <summary>
/// Gets or sets the value of the proxy for the SOCKS protocol.
/// </summary>
[JsonProperty("socksProxy", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string SocksProxy
{
get
{
return this.socksProxyLocation;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.socksProxyLocation = value;
}
}
/// <summary>
/// Gets or sets the value of username for the SOCKS proxy.
/// </summary>
[JsonProperty("socksUsername", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string SocksUserName
{
get
{
return this.socksUserName;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.socksUserName = value;
}
}
/// <summary>
/// Gets or sets the value of password for the SOCKS proxy.
/// </summary>
[JsonProperty("socksPassword", DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public string SocksPassword
{
get
{
return this.socksPassword;
}
set
{
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.socksPassword = value;
}
}
/// <summary>
/// Adds a single address to the list of addresses against which the proxy will not be used.
/// </summary>
/// <param name="address">The address to add.</param>
public void AddBypassAddress(string address)
{
if (string.IsNullOrEmpty(address))
{
throw new ArgumentException("address must not be null or empty", "address");
}
this.AddBypassAddresses(address);
}
/// <summary>
/// Adds addresses to the list of addresses against which the proxy will not be used.
/// </summary>
/// <param name="addressesToAdd">An array of addresses to add.</param>
public void AddBypassAddresses(params string[] addressesToAdd)
{
this.AddBypassAddresses(new List<string>(addressesToAdd));
}
/// <summary>
/// Adds addresses to the list of addresses against which the proxy will not be used.
/// </summary>
/// <param name="addressesToAdd">An <see cref="IEnumerable{T}"/> object of arguments to add.</param>
public void AddBypassAddresses(IEnumerable<string> addressesToAdd)
{
if (addressesToAdd == null)
{
throw new ArgumentNullException("addressesToAdd", "addressesToAdd must not be null");
}
this.VerifyProxyTypeCompatilibily(ProxyKind.Manual);
this.proxyKind = ProxyKind.Manual;
this.noProxyAddresses.AddRange(addressesToAdd);
}
/// <summary>
/// Returns a dictionary suitable for serializing to the W3C Specification
/// dialect of the wire protocol.
/// </summary>
/// <returns>A dictionary suitable for serializing to the W3C Specification
/// dialect of the wire protocol.</returns>
internal Dictionary<string, object> ToCapability()
{
Dictionary<string, object> serializedDictionary = null;
if (this.proxyKind != ProxyKind.Unspecified)
{
serializedDictionary = new Dictionary<string, object>();
if (this.proxyKind == ProxyKind.ProxyAutoConfigure)
{
serializedDictionary["proxyType"] = "pac";
}
else
{
serializedDictionary["proxyType"] = this.proxyKind.ToString().ToLowerInvariant();
}
if (!string.IsNullOrEmpty(this.httpProxyLocation))
{
serializedDictionary["httpProxy"] = this.httpProxyLocation;
}
if (!string.IsNullOrEmpty(this.sslProxyLocation))
{
serializedDictionary["sslProxy"] = this.sslProxyLocation;
}
if (!string.IsNullOrEmpty(this.ftpProxyLocation))
{
serializedDictionary["ftpProxy"] = this.ftpProxyLocation;
}
if (!string.IsNullOrEmpty(this.socksProxyLocation))
{
string socksAuth = string.Empty;
if (!string.IsNullOrEmpty(this.socksUserName) && !string.IsNullOrEmpty(this.socksPassword))
{
// TODO: this is probably inaccurate as to how this is supposed
// to look.
socksAuth = this.socksUserName + ":" + this.socksPassword + "@";
}
serializedDictionary["socksProxy"] = socksAuth + this.socksProxyLocation;
}
if (this.noProxyAddresses.Count > 0)
{
List<object> addressList = new List<object>();
foreach (string address in this.noProxyAddresses)
{
addressList.Add(address);
}
serializedDictionary["noProxy"] = addressList;
}
}
return serializedDictionary;
}
private void VerifyProxyTypeCompatilibily(ProxyKind compatibleProxy)
{
if (this.proxyKind != ProxyKind.Unspecified && this.proxyKind != compatibleProxy)
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
"Specified proxy type {0} is not compatible with current setting {1}",
compatibleProxy.ToString().ToUpperInvariant(),
this.proxyKind.ToString().ToUpperInvariant());
throw new InvalidOperationException(errorMessage);
}
}
}
}
| |
// Copyright (c) Lex Li. All rights reserved.
//
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace JexusManager.Features.Main
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Windows.Forms;
using JexusManager.Main.Properties;
using JexusManager.Services;
using Microsoft.Web.Administration;
using Microsoft.Web.Management.Client;
using Microsoft.Web.Management.Client.Win32;
using Module = Microsoft.Web.Management.Client.Module;
/// <summary>
/// Description of DefaultDocumentFeature.
/// </summary>
internal class ApplicationPoolsFeature
{
private sealed class FeatureTaskList : DefaultTaskList
{
private readonly ApplicationPoolsFeature _owner;
public FeatureTaskList(ApplicationPoolsFeature owner)
{
_owner = owner;
}
public override ICollection GetTaskItems()
{
var result = new ArrayList();
result.Add(
new MethodTaskItem("Add", "Add Application Pool...", string.Empty, string.Empty, Resources.application_pool_new_16)
.SetUsage());
result.Add(new MethodTaskItem("Set", "Set Application Pool Defaults...", string.Empty).SetUsage());
if (_owner.SelectedItem != null)
{
result.Add(new MethodTaskItem(string.Empty, "-", string.Empty).SetUsage());
result.Add(new TextTaskItem("Application Pool Tasks", string.Empty, true));
result.Add(
new MethodTaskItem("Start", "Start", string.Empty, string.Empty, Resources.start_16).SetUsage(
!_owner.IsBusy && _owner.SelectedItem.State != ObjectState.Started));
result.Add(
new MethodTaskItem("Stop", "Stop", string.Empty, string.Empty, Resources.stop_16).SetUsage(
!_owner.IsBusy && _owner.SelectedItem.State == ObjectState.Started));
result.Add(
new MethodTaskItem("Recycle", "Recycle...", string.Empty, string.Empty, Resources.restart_16)
.SetUsage(!_owner.IsBusy && _owner.SelectedItem.State == ObjectState.Started));
result.Add(new MethodTaskItem(string.Empty, "-", string.Empty).SetUsage());
result.Add(new TextTaskItem("Edit Application Pool", string.Empty, true));
result.Add(
new MethodTaskItem("Basic", "Basic Settings...", string.Empty, string.Empty,
Resources.basic_settings_16).SetUsage());
result.Add(new MethodTaskItem("Recycling", "Recycling...", string.Empty).SetUsage());
result.Add(new MethodTaskItem("Advanced", "Advanced Settings", string.Empty).SetUsage());
result.Add(new MethodTaskItem("Rename", "Rename", string.Empty).SetUsage());
result.Add(new MethodTaskItem(string.Empty, "-", string.Empty).SetUsage());
result.Add(RemoveTaskItem);
result.Add(new MethodTaskItem(string.Empty, "-", string.Empty).SetUsage());
result.Add(
new MethodTaskItem("Applications", "View Applications", string.Empty).SetUsage());
}
return result.ToArray(typeof(TaskItem)) as TaskItem[];
}
[Obfuscation(Exclude = true)]
public void Add()
{
_owner.Add();
}
[Obfuscation(Exclude = true)]
public void Set()
{
_owner.Set();
}
[Obfuscation(Exclude = true)]
public override void Remove()
{
_owner.Remove();
}
[Obfuscation(Exclude = true)]
public void Rename()
{
_owner.Rename();
}
[Obfuscation(Exclude = true)]
public void Basic()
{
_owner.Basic();
}
[Obfuscation(Exclude = true)]
public void Applications()
{
_owner.Applications();
}
[Obfuscation(Exclude = true)]
public void Recycle()
{
_owner.Recycle();
}
[Obfuscation(Exclude = true)]
public void Start()
{
_owner.Start();
}
[Obfuscation(Exclude = true)]
public void Stop()
{
_owner.Stop();
}
[Obfuscation(Exclude = true)]
public void Recycling()
{
_owner.Recycling();
}
[Obfuscation(Exclude = true)]
public void Advanced()
{
_owner.Advanced();
}
}
public ApplicationPoolsFeature(Module module)
{
Module = module;
}
protected static readonly Version FxVersion10 = new Version("1.0");
protected static readonly Version FxVersion11 = new Version("1.1");
protected static readonly Version FxVersion20 = new Version("2.0");
protected static readonly Version FxVersionNotRequired = new Version();
private FeatureTaskList _taskList;
protected void DisplayErrorMessage(Exception ex, ResourceManager resourceManager)
{
var service = (IManagementUIService)GetService(typeof(IManagementUIService));
service.ShowError(ex, resourceManager.GetString("General"), "", false);
}
protected object GetService(Type type)
{
return (Module as IServiceProvider).GetService(type);
}
public TaskList GetTaskList()
{
return _taskList ?? (_taskList = new FeatureTaskList(this));
}
public void Load()
{
var service = (IConfigurationService)GetService(typeof(IConfigurationService));
Items = service.Server.ApplicationPools;
OnApplicationPoolsSettingsSaved();
}
public ApplicationPoolCollection Items { get; set; }
public ApplicationPool SelectedItem { get; set; }
protected void OnApplicationPoolsSettingsSaved()
{
ApplicationPoolsSettingsUpdated?.Invoke();
}
public virtual bool ShowHelp()
{
DialogHelper.ProcessStart("http://go.microsoft.com/fwlink/?LinkId=210456");
return false;
}
private void Add()
{
var dialog = new ApplicationPoolBasicSettingsDialog(Module, null, Items.Parent.ApplicationPoolDefaults, Items);
if (dialog.ShowDialog() == DialogResult.OK)
{
Items.Parent.CommitChanges();
}
SelectedItem = dialog.Pool;
OnApplicationPoolsSettingsSaved();
}
private void Set()
{
var dialog = new ApplicationPoolDefaultsSettingsDialog(Module, Items.Parent.ApplicationPoolDefaults);
if (dialog.ShowDialog() == DialogResult.OK)
{
Items.Parent.CommitChanges();
}
}
private void Recycling()
{ }
internal void Remove()
{
if (SelectedItem == null)
{
return;
}
var service = (IManagementUIService)GetService(typeof(IManagementUIService));
var result = service.ShowMessage("Are you sure that you want to remove the selected application pool?", "Confirm Remove",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (result != DialogResult.Yes)
{
return;
}
var index = Items.IndexOf(SelectedItem);
Items.RemoveAt(index);
if (Items.Count == 0)
{
SelectedItem = null;
}
else
{
SelectedItem = index > Items.Count - 1 ? Items[Items.Count - 1] : Items[index];
}
Items.Parent.CommitChanges();
OnApplicationPoolsSettingsSaved();
}
private void Rename()
{
}
private void Advanced()
{
var dialog = new ApplicationPoolAdvancedSettingsDialog(Module, SelectedItem);
if (dialog.ShowDialog() == DialogResult.OK)
{
SelectedItem.Parent.Parent.CommitChanges();
}
}
private void Stop()
{
if (SelectedItem == null)
{
return;
}
IsBusy = true;
OnApplicationPoolsSettingsSaved();
SelectedItem.Stop();
IsBusy = false;
OnApplicationPoolsSettingsSaved();
}
private void Start()
{
if (SelectedItem == null)
{
return;
}
IsBusy = true;
OnApplicationPoolsSettingsSaved();
SelectedItem.Start();
IsBusy = false;
OnApplicationPoolsSettingsSaved();
}
private void Recycle()
{
if (SelectedItem == null)
{
return;
}
IsBusy = true;
OnApplicationPoolsSettingsSaved();
SelectedItem.Recycle();
IsBusy = false;
OnApplicationPoolsSettingsSaved();
}
private void Applications()
{
}
internal void Basic()
{
if (SelectedItem == null)
{
return;
}
var dialog = new ApplicationPoolBasicSettingsDialog(Module, SelectedItem, null, Items);
if (dialog.ShowDialog() == DialogResult.OK)
{
SelectedItem.Parent.Parent.CommitChanges();
}
OnApplicationPoolsSettingsSaved();
}
public bool IsBusy { get; set; }
public ApplicationPoolsSettingsSavedEventHandler ApplicationPoolsSettingsUpdated { get; set; }
public string Description { get; }
public virtual bool IsFeatureEnabled
{
get { return true; }
}
public virtual Version MinimumFrameworkVersion
{
get { return FxVersionNotRequired; }
}
public Module Module { get; }
public string Name { get; }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Xunit;
namespace System.Threading.Tasks.Dataflow.Tests
{
public partial class DataflowBlockTests : DataflowBlockTestBase
{
[Fact]
public void RunActionBlockTests()
{
Assert.True(IDataflowBlockTestHelper.TestToString(nameFormat => nameFormat != null ? new ActionBlock<int>(x => { }, new ExecutionDataflowBlockOptions() { NameFormat = nameFormat }) : new ActionBlock<int>(x => { })));
Assert.True(IDataflowBlockTestHelper.TestToString(nameFormat =>
nameFormat != null ?
new ActionBlock<int>(x => { }, new ExecutionDataflowBlockOptions() { NameFormat = nameFormat, SingleProducerConstrained = true }) :
new ActionBlock<int>(x => { }, new ExecutionDataflowBlockOptions() { SingleProducerConstrained = true })));
Assert.True(ITargetBlockTestHelper.TestArgumentsExceptions<int>(new ActionBlock<int>(i => { })));
Assert.True(ITargetBlockTestHelper.TestOfferMessage<int>(new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions { SingleProducerConstrained = true })));
Assert.True(ITargetBlockTestHelper.TestPost<int>(new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions { SingleProducerConstrained = true })));
Assert.True(ITargetBlockTestHelper.TestComplete<int>(new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions { SingleProducerConstrained = true })));
Assert.True(ITargetBlockTestHelper.TestCompletionTask<int>(new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions { SingleProducerConstrained = true })));
Assert.True(ITargetBlockTestHelper.TestNonGreedyPost(new ActionBlock<int>(x => { Task.Delay(1); }, new ExecutionDataflowBlockOptions() { BoundedCapacity = 1 })));
}
[Fact]
public void TestActionBlockConstructor()
{
// SYNC
// without option
var block = new ActionBlock<int>(i => { });
Assert.False(block.InputCount != 0, "Constructor failed! InputCount returned a non zero value for a brand new ActionBlock." + block.InputCount);
//with not cancelled token and default scheduler
block = new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 });
Assert.False(block.InputCount != 0, "Constructor failed! InputCount returned a non zero value for a brand new ActionBlock.");
//with a cancelled token and default scheduler
var token = new CancellationToken(true);
block = new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1, CancellationToken = token });
Assert.False(block.InputCount != 0, "Constructor failed! InputCount returned a non zero value for a brand new ActionBlock.");
// ASYNC (a copy of the sync but with constructors returning Task instead of void
var dummyTask = new Task(() => { });
// without option
block = new ActionBlock<int>(i => dummyTask);
Assert.False(block.InputCount != 0, "Constructor failed! InputCount returned a non zero value for a brand new ActionBlock.");
//with not cancelled token and default scheduler
block = new ActionBlock<int>(i => dummyTask, new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 });
Assert.False(block.InputCount != 0, "Constructor failed! InputCount returned a non zero value for a brand new ActionBlock.");
//with a cancelled token and default scheduler
token = new CancellationToken(true);
block = new ActionBlock<int>(i => dummyTask, new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1, CancellationToken = token });
Assert.False(block.InputCount != 0, "Constructor failed! InputCount returned a non zero value for a brand new ActionBlock.");
}
[Fact]
public void TestActionBlockInvalidArgumentValidation()
{
Assert.Throws<ArgumentNullException>(() => new ActionBlock<int>((Func<int, Task>)null));
Assert.Throws<ArgumentNullException>(() => new ActionBlock<int>((Func<int, Task>)null));
Assert.Throws<ArgumentNullException>(() => new ActionBlock<int>(i => { }, null));
Assert.Throws<ArgumentNullException>(() => new ActionBlock<int>(i => Task.Factory.StartNew(() => { }), null));
}
//[Fact(Skip = "Outerloop")]
public void RunActionBlockConformanceTests()
{
// SYNC
// Do everything twice - once through OfferMessage and Once through Post
for (FeedMethod feedMethod = FeedMethod._First; feedMethod < FeedMethod._Count; feedMethod++)
{
Func<DataflowBlockOptions, TargetProperties<int>> actionBlockFactory =
options =>
{
ITargetBlock<int> target = new ActionBlock<int>(i => TrackCaptures(i), (ExecutionDataflowBlockOptions)options);
return new TargetProperties<int> { Target = target, Capturer = target, ErrorVerifyable = true };
};
CancellationTokenSource cancellationSource = new CancellationTokenSource();
var defaultOptions = new ExecutionDataflowBlockOptions();
var dopOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
var mptOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 1 };
var cancellationOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 1, CancellationToken = cancellationSource.Token };
var spscOptions = new ExecutionDataflowBlockOptions { SingleProducerConstrained = true };
var spscMptOptions = new ExecutionDataflowBlockOptions { SingleProducerConstrained = true, MaxMessagesPerTask = 10 };
Assert.True(FeedTarget(actionBlockFactory, defaultOptions, 1, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, dopOptions, 1, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, mptOptions, 1, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, mptOptions, 1, Intervention.Complete, null, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, cancellationOptions, 1, Intervention.Cancel, cancellationSource, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, spscOptions, 1, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, spscOptions, 1, Intervention.Complete, null, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, spscMptOptions, 1, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, spscMptOptions, 1, Intervention.Complete, null, feedMethod, true));
}
// Test scheduler usage
{
bool localPassed = true;
for (int trial = 0; trial < 2; trial++)
{
var sts = new SimpleTaskScheduler();
var options = new ExecutionDataflowBlockOptions { TaskScheduler = sts, MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded, MaxMessagesPerTask = 1 };
if (trial == 0) options.SingleProducerConstrained = true;
var ab = new ActionBlock<int>(i => localPassed &= TaskScheduler.Current.Id == sts.Id, options);
for (int i = 0; i < 2; i++) ab.Post(i);
ab.Complete();
ab.Completion.Wait();
}
Assert.True(localPassed, string.Format("{0}: Correct scheduler usage", localPassed ? "Success" : "Failure"));
}
// Test count
{
bool localPassed = true;
for (int trial = 0; trial < 2; trial++)
{
var barrier1 = new Barrier(2);
var barrier2 = new Barrier(2);
var ab = new ActionBlock<int>(i =>
{
barrier1.SignalAndWait();
barrier2.SignalAndWait();
}, new ExecutionDataflowBlockOptions { SingleProducerConstrained = (trial == 0) });
for (int iter = 0; iter < 2; iter++)
{
for (int i = 1; i <= 2; i++) ab.Post(i);
for (int i = 1; i >= 0; i--)
{
barrier1.SignalAndWait();
localPassed &= i == ab.InputCount;
barrier2.SignalAndWait();
}
}
}
Assert.True(localPassed, string.Format("{0}: InputCount", localPassed ? "Success" : "Failure"));
}
// Test ordering
{
bool localPassed = true;
for (int trial = 0; trial < 2; trial++)
{
int prev = -1;
var ab = new ActionBlock<int>(i =>
{
if (prev + 1 != i) localPassed &= false;
prev = i;
}, new ExecutionDataflowBlockOptions { SingleProducerConstrained = (trial == 0) });
for (int i = 0; i < 2; i++) ab.Post(i);
ab.Complete();
ab.Completion.Wait();
}
Assert.True(localPassed, string.Format("{0}: Correct ordering", localPassed ? "Success" : "Failure"));
}
// Test non-greedy
{
bool localPassed = true;
var barrier = new Barrier(2);
var ab = new ActionBlock<int>(i =>
{
barrier.SignalAndWait();
}, new ExecutionDataflowBlockOptions { BoundedCapacity = 1 });
ab.SendAsync(1);
Task.Delay(200).Wait();
var sa2 = ab.SendAsync(2);
localPassed &= !sa2.IsCompleted;
barrier.SignalAndWait(); // for SendAsync(1)
barrier.SignalAndWait(); // for SendAsync(2)
localPassed &= sa2.Wait(100);
int total = 0;
ab = new ActionBlock<int>(i =>
{
Interlocked.Add(ref total, i);
Task.Delay(1).Wait();
}, new ExecutionDataflowBlockOptions { BoundedCapacity = 1 });
for (int i = 1; i <= 100; i++) ab.SendAsync(i);
SpinWait.SpinUntil(() => total == ((100 * 101) / 2), 30000);
localPassed &= total == ((100 * 101) / 2);
Assert.True(localPassed, string.Format("total={0} (must be {1})", total, (100 * 101) / 2));
Assert.True(localPassed, string.Format("{0}: Non-greedy support", localPassed ? "Success" : "Failure"));
}
// Test that OperationCanceledExceptions are ignored
{
bool localPassed = true;
for (int trial = 0; trial < 2; trial++)
{
int sumOfOdds = 0;
var ab = new ActionBlock<int>(i =>
{
if ((i % 2) == 0) throw new OperationCanceledException();
sumOfOdds += i;
}, new ExecutionDataflowBlockOptions { SingleProducerConstrained = (trial == 0) });
for (int i = 0; i < 4; i++) ab.Post(i);
ab.Complete();
ab.Completion.Wait();
localPassed = sumOfOdds == (1 + 3);
}
Assert.True(localPassed, string.Format("{0}: OperationCanceledExceptions are ignored", localPassed ? "Success" : "Failure"));
}
// Test using a precanceled token
{
bool localPassed = true;
try
{
var cts = new CancellationTokenSource();
cts.Cancel();
var dbo = new ExecutionDataflowBlockOptions { CancellationToken = cts.Token };
var ab = new ActionBlock<int>(i => { }, dbo);
localPassed &= ab.Post(42) == false;
localPassed &= ab.InputCount == 0;
localPassed &= ab.Completion != null;
ab.Complete();
}
catch (Exception)
{
localPassed = false;
}
Assert.True(localPassed, string.Format("{0}: Precanceled tokens work correctly", localPassed ? "Success" : "Failure"));
}
// Test faulting
{
bool localPassed = true;
for (int trial = 0; trial < 2; trial++)
{
var ab = new ActionBlock<int>(i => { throw new InvalidOperationException(); },
new ExecutionDataflowBlockOptions { SingleProducerConstrained = (trial == 0) });
ab.Post(42);
ab.Post(1);
ab.Post(2);
ab.Post(3);
try { localPassed &= ab.Completion.Wait(5000); }
catch { }
localPassed &= ab.Completion.IsFaulted;
localPassed &= SpinWait.SpinUntil(() => ab.InputCount == 0, 500);
localPassed &= ab.Post(4) == false;
}
Assert.True(localPassed, string.Format("{0}: Faulted handled correctly", localPassed ? "Success" : "Failure"));
}
// ASYNC (a copy of the sync but with constructors returning Task instead of void
// Do everything twice - once through OfferMessage and Once through Post
for (FeedMethod feedMethod = FeedMethod._First; feedMethod < FeedMethod._Count; feedMethod++)
{
Func<DataflowBlockOptions, TargetProperties<int>> actionBlockFactory =
options =>
{
ITargetBlock<int> target = new ActionBlock<int>(i => TrackCapturesAsync(i), (ExecutionDataflowBlockOptions)options);
return new TargetProperties<int> { Target = target, Capturer = target, ErrorVerifyable = true };
};
CancellationTokenSource cancellationSource = new CancellationTokenSource();
var defaultOptions = new ExecutionDataflowBlockOptions();
var dopOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
var mptOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 10 };
var cancellationOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 100, CancellationToken = cancellationSource.Token };
Assert.True(FeedTarget(actionBlockFactory, defaultOptions, 1, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, defaultOptions, 10, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, dopOptions, 1000, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, mptOptions, 10000, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, mptOptions, 10000, Intervention.Complete, null, feedMethod, true));
Assert.True(FeedTarget(actionBlockFactory, cancellationOptions, 10000, Intervention.Cancel, cancellationSource, feedMethod, true));
}
// Test scheduler usage
{
bool localPassed = true;
var sts = new SimpleTaskScheduler();
var ab = new ActionBlock<int>(i =>
{
localPassed &= TaskScheduler.Current.Id == sts.Id;
return Task.Factory.StartNew(() => { });
}, new ExecutionDataflowBlockOptions { TaskScheduler = sts, MaxDegreeOfParallelism = -1, MaxMessagesPerTask = 10 });
for (int i = 0; i < 2; i++) ab.Post(i);
ab.Complete();
ab.Completion.Wait();
Assert.True(localPassed, string.Format("{0}: Correct scheduler usage", localPassed ? "Success" : "Failure"));
}
// Test count
{
bool localPassed = true;
var barrier1 = new Barrier(2);
var barrier2 = new Barrier(2);
var ab = new ActionBlock<int>(i => Task.Factory.StartNew(() =>
{
barrier1.SignalAndWait();
barrier2.SignalAndWait();
}));
for (int iter = 0; iter < 2; iter++)
{
for (int i = 1; i <= 2; i++) ab.Post(i);
for (int i = 1; i >= 0; i--)
{
barrier1.SignalAndWait();
localPassed &= i == ab.InputCount;
barrier2.SignalAndWait();
}
}
Assert.True(localPassed, string.Format("{0}: InputCount", localPassed ? "Success" : "Failure"));
}
// Test ordering
{
bool localPassed = true;
int prev = -1;
var ab = new ActionBlock<int>(i =>
{
return Task.Factory.StartNew(() =>
{
if (prev + 1 != i) localPassed &= false;
prev = i;
});
});
for (int i = 0; i < 2; i++) ab.Post(i);
ab.Complete();
ab.Completion.Wait();
Assert.True(localPassed, string.Format("{0}: Correct ordering", localPassed ? "Success" : "Failure"));
}
// Test non-greedy
{
bool localPassed = true;
var barrier = new Barrier(2);
var ab = new ActionBlock<int>(i =>
{
return Task.Factory.StartNew(() =>
{
barrier.SignalAndWait();
});
}, new ExecutionDataflowBlockOptions { BoundedCapacity = 1 });
ab.SendAsync(1);
Task.Delay(200).Wait();
var sa2 = ab.SendAsync(2);
localPassed &= !sa2.IsCompleted;
barrier.SignalAndWait(); // for SendAsync(1)
barrier.SignalAndWait(); // for SendAsync(2)
localPassed &= sa2.Wait(100);
int total = 0;
ab = new ActionBlock<int>(i =>
{
return Task.Factory.StartNew(() =>
{
Interlocked.Add(ref total, i);
Task.Delay(1).Wait();
});
}, new ExecutionDataflowBlockOptions { BoundedCapacity = 1 });
for (int i = 1; i <= 100; i++) ab.SendAsync(i);
SpinWait.SpinUntil(() => total == ((100 * 101) / 2), 30000);
localPassed &= total == ((100 * 101) / 2);
Assert.True(localPassed, string.Format("total={0} (must be {1})", total, (100 * 101) / 2));
Assert.True(localPassed, string.Format("{0}: Non-greedy support", localPassed ? "Success" : "Failure"));
}
// Test that OperationCanceledExceptions are ignored
{
bool localPassed = true;
int sumOfOdds = 0;
var ab = new ActionBlock<int>(i =>
{
if ((i % 2) == 0) throw new OperationCanceledException();
return Task.Factory.StartNew(() => { sumOfOdds += i; });
});
for (int i = 0; i < 4; i++) ab.Post(i);
ab.Complete();
ab.Completion.Wait();
localPassed = sumOfOdds == (1 + 3);
Assert.True(localPassed, string.Format("{0}: OperationCanceledExceptions are ignored", localPassed ? "Success" : "Failure"));
}
// Test that null task is ignored
{
bool localPassed = true;
int sumOfOdds = 0;
var ab = new ActionBlock<int>(i =>
{
if ((i % 2) == 0) return null;
return Task.Factory.StartNew(() => { sumOfOdds += i; });
});
for (int i = 0; i < 4; i++) ab.Post(i);
ab.Complete();
ab.Completion.Wait();
localPassed = sumOfOdds == (1 + 3);
Assert.True(localPassed, string.Format("{0}: null tasks are ignored", localPassed ? "Success" : "Failure"));
}
// Test faulting from the delegate
{
bool localPassed = true;
var ab = new ActionBlock<int>(new Func<int, Task>(i => { throw new InvalidOperationException(); }));
ab.Post(42);
ab.Post(1);
ab.Post(2);
ab.Post(3);
try { localPassed &= ab.Completion.Wait(100); }
catch { }
localPassed &= ab.Completion.IsFaulted;
localPassed &= SpinWait.SpinUntil(() => ab.InputCount == 0, 500);
localPassed &= ab.Post(4) == false;
Assert.True(localPassed, string.Format("{0}: Faulted from delegate handled correctly", localPassed ? "Success" : "Failure"));
}
// Test faulting from the task
{
bool localPassed = true;
var ab = new ActionBlock<int>(i => Task.Factory.StartNew(() => { throw new InvalidOperationException(); }));
ab.Post(42);
ab.Post(1);
ab.Post(2);
ab.Post(3);
try { localPassed &= ab.Completion.Wait(100); }
catch { }
localPassed &= ab.Completion.IsFaulted;
localPassed &= SpinWait.SpinUntil(() => ab.InputCount == 0, 500);
localPassed &= ab.Post(4) == false;
Assert.True(localPassed, string.Format("{0}: Faulted from task handled correctly", localPassed ? "Success" : "Failure"));
}
}
//[Fact(Skip = "Outerloop")]
public void TestDynamicParallelism()
{
bool passed = false, executingFirst = false;
const int firstItem = 1;
const int secondItem = 2;
int maxDOP = Parallelism.ActualDegreeOfParallelism > 1 ? Parallelism.ActualDegreeOfParallelism : 2; // Must be >= 2
int maxMPT = Int32.MaxValue;
var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = maxDOP, MaxMessagesPerTask = maxMPT };
ActionBlock<int> action = new ActionBlock<int>((item) =>
{
if (item == firstItem)
{
executingFirst = true;
Task.Delay(100).Wait();
executingFirst = false;
}
if (item == secondItem)
{
passed = executingFirst;
}
}, options);
BufferBlock<int> buffer = new BufferBlock<int>();
buffer.LinkTo(action);
buffer.Post(firstItem);
Task.Delay(1).Wait(); // Make sure item 2 propagates after item 1 has started executing
buffer.Post(secondItem);
Task.Delay(1).Wait(); // Let item 2 get propagated to the ActionBlock
action.Complete();
action.Completion.Wait();
Assert.True(passed, "Test failed: executingFirst is false.");
}
//[Fact(Skip = "Outerloop")]
public void TestReleasingOfPostponedMessages()
{
const int excess = 5;
for (int dop = 1; dop <= Parallelism.ActualDegreeOfParallelism; dop++)
{
var localPassed = true;
var nextOfferEvent = new AutoResetEvent(true);
var releaseProcessingEvent = new ManualResetEventSlim();
var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, BoundedCapacity = dop };
var action = new ActionBlock<int>(x => { nextOfferEvent.Set(); releaseProcessingEvent.Wait(); }, options);
var sendAsyncDop = new Task<bool>[dop];
var sendAsyncExcess = new Task<bool>[excess];
// Send DOP messages
for (int i = 0; i < dop; i++)
{
// Throttle sending to make sure we saturate DOP exactly
nextOfferEvent.WaitOne();
sendAsyncDop[i] = action.SendAsync(i);
}
// Send EXCESS more messages. All of these will surely be postponed
for (int i = 0; i < excess; i++)
sendAsyncExcess[i] = action.SendAsync(dop + i);
// Wait until the tasks for the first DOP messages get completed
Task.WaitAll(sendAsyncDop, 5000);
// Complete the block. This will cause the EXCESS messages to be declined.
action.Complete();
releaseProcessingEvent.Set();
// Verify all DOP messages have been accepted
for (int i = 0; i < dop; i++) localPassed &= sendAsyncDop[i].Result;
Assert.True(localPassed, string.Format("DOP={0} : Consumed up to DOP - {1}", dop, localPassed ? "Passed" : "FAILED"));
// Verify all EXCESS messages have been declined
localPassed = true;
for (int i = 0; i < excess; i++) localPassed &= !sendAsyncExcess[i].Result;
Assert.True(localPassed, string.Format("DOP={0} : Declined excess - {1}", dop, localPassed ? "Passed" : "FAILED"));
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="TransformCollection.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Windows.Media.Converters;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media
{
/// <summary>
/// A collection of Transform objects.
/// </summary>
public sealed partial class TransformCollection : Animatable, IList, IList<Transform>
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new TransformCollection Clone()
{
return (TransformCollection)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new TransformCollection CloneCurrentValue()
{
return (TransformCollection)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region IList<T>
/// <summary>
/// Adds "value" to the list
/// </summary>
public void Add(Transform value)
{
AddHelper(value);
}
/// <summary>
/// Removes all elements from the list
/// </summary>
public void Clear()
{
WritePreamble();
// As part of Clear()'ing the collection, we will iterate it and call
// OnFreezablePropertyChanged and OnRemove for each item.
// However, OnRemove assumes that the item to be removed has already been
// pulled from the underlying collection. To statisfy this condition,
// we store the old collection and clear _collection before we call these methods.
// As Clear() semantics do not include TrimToFit behavior, we create the new
// collection storage at the same size as the previous. This is to provide
// as close as possible the same perf characteristics as less complicated collections.
FrugalStructList<Transform> oldCollection = _collection;
_collection = new FrugalStructList<Transform>(_collection.Capacity);
for (int i = oldCollection.Count - 1; i >= 0; i--)
{
OnFreezablePropertyChanged(/* oldValue = */ oldCollection[i], /* newValue = */ null);
// Fire the OnRemove handlers for each item. We're not ensuring that
// all OnRemove's get called if a resumable exception is thrown.
// At this time, these call-outs are not public, so we do not handle exceptions.
OnRemove( /* oldValue */ oldCollection[i]);
}
++_version;
WritePostscript();
}
/// <summary>
/// Determines if the list contains "value"
/// </summary>
public bool Contains(Transform value)
{
ReadPreamble();
return _collection.Contains(value);
}
/// <summary>
/// Returns the index of "value" in the list
/// </summary>
public int IndexOf(Transform value)
{
ReadPreamble();
return _collection.IndexOf(value);
}
/// <summary>
/// Inserts "value" into the list at the specified position
/// </summary>
public void Insert(int index, Transform value)
{
if (value == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
WritePreamble();
OnFreezablePropertyChanged(/* oldValue = */ null, /* newValue = */ value);
_collection.Insert(index, value);
OnInsert(value);
++_version;
WritePostscript();
}
/// <summary>
/// Removes "value" from the list
/// </summary>
public bool Remove(Transform value)
{
WritePreamble();
// By design collections "succeed silently" if you attempt to remove an item
// not in the collection. Therefore we need to first verify the old value exists
// before calling OnFreezablePropertyChanged. Since we already need to locate
// the item in the collection we keep the index and use RemoveAt(...) to do
// the work. (Windows OS #1016178)
// We use the public IndexOf to guard our UIContext since OnFreezablePropertyChanged
// is only called conditionally. IList.IndexOf returns -1 if the value is not found.
int index = IndexOf(value);
if (index >= 0)
{
Transform oldValue = _collection[index];
OnFreezablePropertyChanged(oldValue, null);
_collection.RemoveAt(index);
OnRemove(oldValue);
++_version;
WritePostscript();
return true;
}
// Collection_Remove returns true, calls WritePostscript,
// increments version, and does UpdateResource if it succeeds
return false;
}
/// <summary>
/// Removes the element at the specified index
/// </summary>
public void RemoveAt(int index)
{
RemoveAtWithoutFiringPublicEvents(index);
// RemoveAtWithoutFiringPublicEvents incremented the version
WritePostscript();
}
/// <summary>
/// Removes the element at the specified index without firing
/// the public Changed event.
/// The caller - typically a public method - is responsible for calling
/// WritePostscript if appropriate.
/// </summary>
internal void RemoveAtWithoutFiringPublicEvents(int index)
{
WritePreamble();
Transform oldValue = _collection[ index ];
OnFreezablePropertyChanged(oldValue, null);
_collection.RemoveAt(index);
OnRemove(oldValue);
++_version;
// No WritePostScript to avoid firing the Changed event.
}
/// <summary>
/// Indexer for the collection
/// </summary>
public Transform this[int index]
{
get
{
ReadPreamble();
return _collection[index];
}
set
{
if (value == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
WritePreamble();
if (!Object.ReferenceEquals(_collection[ index ], value))
{
Transform oldValue = _collection[ index ];
OnFreezablePropertyChanged(oldValue, value);
_collection[ index ] = value;
OnSet(oldValue, value);
}
++_version;
WritePostscript();
}
}
#endregion
#region ICollection<T>
/// <summary>
/// The number of elements contained in the collection.
/// </summary>
public int Count
{
get
{
ReadPreamble();
return _collection.Count;
}
}
/// <summary>
/// Copies the elements of the collection into "array" starting at "index"
/// </summary>
public void CopyTo(Transform[] array, int index)
{
ReadPreamble();
if (array == null)
{
throw new ArgumentNullException("array");
}
// This will not throw in the case that we are copying
// from an empty collection. This is consistent with the
// BCL Collection implementations. (Windows 1587365)
if (index < 0 || (index + _collection.Count) > array.Length)
{
throw new ArgumentOutOfRangeException("index");
}
_collection.CopyTo(array, index);
}
bool ICollection<Transform>.IsReadOnly
{
get
{
ReadPreamble();
return IsFrozen;
}
}
#endregion
#region IEnumerable<T>
/// <summary>
/// Returns an enumerator for the collection
/// </summary>
public Enumerator GetEnumerator()
{
ReadPreamble();
return new Enumerator(this);
}
IEnumerator<Transform> IEnumerable<Transform>.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region IList
bool IList.IsReadOnly
{
get
{
return ((ICollection<Transform>)this).IsReadOnly;
}
}
bool IList.IsFixedSize
{
get
{
ReadPreamble();
return IsFrozen;
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
// Forwards to typed implementation
this[index] = Cast(value);
}
}
int IList.Add(object value)
{
// Forward to typed helper
return AddHelper(Cast(value));
}
bool IList.Contains(object value)
{
return Contains(value as Transform);
}
int IList.IndexOf(object value)
{
return IndexOf(value as Transform);
}
void IList.Insert(int index, object value)
{
// Forward to IList<T> Insert
Insert(index, Cast(value));
}
void IList.Remove(object value)
{
Remove(value as Transform);
}
#endregion
#region ICollection
void ICollection.CopyTo(Array array, int index)
{
ReadPreamble();
if (array == null)
{
throw new ArgumentNullException("array");
}
// This will not throw in the case that we are copying
// from an empty collection. This is consistent with the
// BCL Collection implementations. (Windows 1587365)
if (index < 0 || (index + _collection.Count) > array.Length)
{
throw new ArgumentOutOfRangeException("index");
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Get(SRID.Collection_BadRank));
}
// Elsewhere in the collection we throw an AE when the type is
// bad so we do it here as well to be consistent
try
{
int count = _collection.Count;
for (int i = 0; i < count; i++)
{
array.SetValue(_collection[i], index + i);
}
}
catch (InvalidCastException e)
{
throw new ArgumentException(SR.Get(SRID.Collection_BadDestArray, this.GetType().Name), e);
}
}
bool ICollection.IsSynchronized
{
get
{
ReadPreamble();
return IsFrozen || Dispatcher != null;
}
}
object ICollection.SyncRoot
{
get
{
ReadPreamble();
return this;
}
}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Internal Helpers
/// <summary>
/// A frozen empty TransformCollection.
/// </summary>
internal static TransformCollection Empty
{
get
{
if (s_empty == null)
{
TransformCollection collection = new TransformCollection();
collection.Freeze();
s_empty = collection;
}
return s_empty;
}
}
/// <summary>
/// Helper to return read only access.
/// </summary>
internal Transform Internal_GetItem(int i)
{
return _collection[i];
}
/// <summary>
/// Freezable collections need to notify their contained Freezables
/// about the change in the InheritanceContext
/// </summary>
internal override void OnInheritanceContextChangedCore(EventArgs args)
{
base.OnInheritanceContextChangedCore(args);
for (int i=0; i<this.Count; i++)
{
DependencyObject inheritanceChild = _collection[i];
if (inheritanceChild!= null && inheritanceChild.InheritanceContext == this)
{
inheritanceChild.OnInheritanceContextChanged(args);
}
}
}
#endregion
#region Private Helpers
private Transform Cast(object value)
{
if( value == null )
{
throw new System.ArgumentNullException("value");
}
if (!(value is Transform))
{
throw new System.ArgumentException(SR.Get(SRID.Collection_BadType, this.GetType().Name, value.GetType().Name, "Transform"));
}
return (Transform) value;
}
// IList.Add returns int and IList<T>.Add does not. This
// is called by both Adds and IList<T>'s just ignores the
// integer
private int AddHelper(Transform value)
{
int index = AddWithoutFiringPublicEvents(value);
// AddAtWithoutFiringPublicEvents incremented the version
WritePostscript();
return index;
}
internal int AddWithoutFiringPublicEvents(Transform value)
{
int index = -1;
if (value == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
WritePreamble();
Transform newValue = value;
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
index = _collection.Add(newValue);
OnInsert(newValue);
++_version;
// No WritePostScript to avoid firing the Changed event.
return index;
}
internal event ItemInsertedHandler ItemInserted;
internal event ItemRemovedHandler ItemRemoved;
private void OnInsert(object item)
{
if (ItemInserted != null)
{
ItemInserted(this, item);
}
}
private void OnRemove(object oldValue)
{
if (ItemRemoved != null)
{
ItemRemoved(this, oldValue);
}
}
private void OnSet(object oldValue, object newValue)
{
OnInsert(newValue);
OnRemove(oldValue);
}
#endregion Private Helpers
private static TransformCollection s_empty;
#region Public Properties
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new TransformCollection();
}
/// <summary>
/// Implementation of Freezable.CloneCore()
/// </summary>
protected override void CloneCore(Freezable source)
{
TransformCollection sourceTransformCollection = (TransformCollection) source;
base.CloneCore(source);
int count = sourceTransformCollection._collection.Count;
_collection = new FrugalStructList<Transform>(count);
for (int i = 0; i < count; i++)
{
Transform newValue = (Transform) sourceTransformCollection._collection[i].Clone();
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
}
/// <summary>
/// Implementation of Freezable.CloneCurrentValueCore()
/// </summary>
protected override void CloneCurrentValueCore(Freezable source)
{
TransformCollection sourceTransformCollection = (TransformCollection) source;
base.CloneCurrentValueCore(source);
int count = sourceTransformCollection._collection.Count;
_collection = new FrugalStructList<Transform>(count);
for (int i = 0; i < count; i++)
{
Transform newValue = (Transform) sourceTransformCollection._collection[i].CloneCurrentValue();
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
}
/// <summary>
/// Implementation of Freezable.GetAsFrozenCore()
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
TransformCollection sourceTransformCollection = (TransformCollection) source;
base.GetAsFrozenCore(source);
int count = sourceTransformCollection._collection.Count;
_collection = new FrugalStructList<Transform>(count);
for (int i = 0; i < count; i++)
{
Transform newValue = (Transform) sourceTransformCollection._collection[i].GetAsFrozen();
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
}
/// <summary>
/// Implementation of Freezable.GetCurrentValueAsFrozenCore()
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
TransformCollection sourceTransformCollection = (TransformCollection) source;
base.GetCurrentValueAsFrozenCore(source);
int count = sourceTransformCollection._collection.Count;
_collection = new FrugalStructList<Transform>(count);
for (int i = 0; i < count; i++)
{
Transform newValue = (Transform) sourceTransformCollection._collection[i].GetCurrentValueAsFrozen();
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>.
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
int count = _collection.Count;
for (int i = 0; i < count && canFreeze; i++)
{
canFreeze &= Freezable.Freeze(_collection[i], isChecking);
}
return canFreeze;
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal FrugalStructList<Transform> _collection;
internal uint _version = 0;
#endregion Internal Fields
#region Enumerator
/// <summary>
/// Enumerates the items in a TransformCollection
/// </summary>
public struct Enumerator : IEnumerator, IEnumerator<Transform>
{
#region Constructor
internal Enumerator(TransformCollection list)
{
Debug.Assert(list != null, "list may not be null.");
_list = list;
_version = list._version;
_index = -1;
_current = default(Transform);
}
#endregion
#region Methods
void IDisposable.Dispose()
{
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element,
/// false if the enumerator has passed the end of the collection.
/// </returns>
public bool MoveNext()
{
_list.ReadPreamble();
if (_version == _list._version)
{
if (_index > -2 && _index < _list._collection.Count - 1)
{
_current = _list._collection[++_index];
return true;
}
else
{
_index = -2; // -2 indicates "past the end"
return false;
}
}
else
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged));
}
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the
/// first element in the collection.
/// </summary>
public void Reset()
{
_list.ReadPreamble();
if (_version == _list._version)
{
_index = -1;
}
else
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged));
}
}
#endregion
#region Properties
object IEnumerator.Current
{
get
{
return this.Current;
}
}
/// <summary>
/// Current element
///
/// The behavior of IEnumerable<T>.Current is undefined
/// before the first MoveNext and after we have walked
/// off the end of the list. However, the IEnumerable.Current
/// contract requires that we throw exceptions
/// </summary>
public Transform Current
{
get
{
if (_index > -1)
{
return _current;
}
else if (_index == -1)
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_NotStarted));
}
else
{
Debug.Assert(_index == -2, "expected -2, got " + _index + "\n");
throw new InvalidOperationException(SR.Get(SRID.Enumerator_ReachedEnd));
}
}
}
#endregion
#region Data
private Transform _current;
private TransformCollection _list;
private uint _version;
private int _index;
#endregion
}
#endregion
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
/// <summary>
/// Initializes a new instance that is empty.
/// </summary>
public TransformCollection()
{
_collection = new FrugalStructList<Transform>();
}
/// <summary>
/// Initializes a new instance that is empty and has the specified initial capacity.
/// </summary>
/// <param name="capacity"> int - The number of elements that the new list is initially capable of storing. </param>
public TransformCollection(int capacity)
{
_collection = new FrugalStructList<Transform>(capacity);
}
/// <summary>
/// Creates a TransformCollection with all of the same elements as collection
/// </summary>
public TransformCollection(IEnumerable<Transform> collection)
{
// The WritePreamble and WritePostscript aren't technically necessary
// in the constructor as of 1/20/05 but they are put here in case
// their behavior changes at a later date
WritePreamble();
if (collection != null)
{
bool needsItemValidation = true;
ICollection<Transform> icollectionOfT = collection as ICollection<Transform>;
if (icollectionOfT != null)
{
_collection = new FrugalStructList<Transform>(icollectionOfT);
}
else
{
ICollection icollection = collection as ICollection;
if (icollection != null) // an IC but not and IC<T>
{
_collection = new FrugalStructList<Transform>(icollection);
}
else // not a IC or IC<T> so fall back to the slower Add
{
_collection = new FrugalStructList<Transform>();
foreach (Transform item in collection)
{
if (item == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
Transform newValue = item;
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
needsItemValidation = false;
}
}
if (needsItemValidation)
{
foreach (Transform item in collection)
{
if (item == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
OnFreezablePropertyChanged(/* oldValue = */ null, item);
OnInsert(item);
}
}
WritePostscript();
}
else
{
throw new ArgumentNullException("collection");
}
}
#endregion Constructors
}
}
| |
namespace Nancy.Tests.Unit.Security
{
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using FakeItEasy;
using Nancy.Responses;
using Nancy.Security;
using Nancy.Tests.Fakes;
using Xunit;
public class ModuleSecurityFixture
{
[Fact]
public void Should_add_an_item_to_the_end_of_the_begin_pipeline_when_RequiresAuthentication_enabled()
{
var module = new FakeHookedModule(A.Fake<BeforePipeline>());
module.RequiresAuthentication();
A.CallTo(() => module.Before.AddItemToEndOfPipeline(A<Func<NancyContext, Response>>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_add_two_items_to_the_end_of_the_begin_pipeline_when_RequiresClaims_enabled()
{
var module = new FakeHookedModule(A.Fake<BeforePipeline>());
module.RequiresClaims(_ => true);
A.CallTo(() => module.Before.AddItemToEndOfPipeline(A<Func<NancyContext, Response>>.Ignored)).MustHaveHappened(Repeated.Exactly.Twice);
}
[Fact]
public void Should_return_unauthorized_response_with_RequiresAuthentication_enabled_and_no_user()
{
var module = new FakeHookedModule(new BeforePipeline());
module.RequiresAuthentication();
var result = module.Before.Invoke(new NancyContext(), new CancellationToken());
result.Result.ShouldNotBeNull();
result.Result.StatusCode.ShouldEqual(HttpStatusCode.Unauthorized);
}
[Fact]
public void Should_return_unauthorized_response_with_RequiresAuthentication_enabled_and_no_identity()
{
var module = new FakeHookedModule(new BeforePipeline());
module.RequiresAuthentication();
var context = new NancyContext
{
CurrentUser = new ClaimsPrincipal()
};
var result = module.Before.Invoke(context, new CancellationToken());
result.Result.ShouldNotBeNull();
result.Result.StatusCode.ShouldEqual(HttpStatusCode.Unauthorized);
}
[Fact]
public void Should_return_null_with_RequiresAuthentication_enabled_and_user_provided()
{
var module = new FakeHookedModule(new BeforePipeline());
module.RequiresAuthentication();
var context = new NancyContext
{
CurrentUser = GetFakeUser("Bob")
};
var result = module.Before.Invoke(context, new CancellationToken());
result.Result.ShouldBeNull();
}
[Fact]
public void Should_return_forbidden_response_with_RequiresClaims_enabled_but_nonmatching_claims()
{
var module = new FakeHookedModule(new BeforePipeline());
module.RequiresClaims(c => c.Type == "Claim1");
var context = new NancyContext
{
CurrentUser = GetFakeUser(
"username",
new Claim("Claim2", string.Empty),
new Claim("Claim3", string.Empty))
};
var result = module.Before.Invoke(context, new CancellationToken());
result.Result.ShouldNotBeNull();
result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);
}
[Fact]
public void Should_return_forbidden_response_with_RequiresClaims_enabled_but_claims_key_missing()
{
var module = new FakeHookedModule(new BeforePipeline());
module.RequiresClaims(c => c.Type == "Claim1");
var context = new NancyContext
{
CurrentUser = GetFakeUser("username")
};
var result = module.Before.Invoke(context, new CancellationToken());
result.Result.ShouldNotBeNull();
result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);
}
[Fact]
public void Should_return_forbidden_response_with_RequiresClaims_enabled_but_not_all_claims_met()
{
var module = new FakeHookedModule(new BeforePipeline());
module.RequiresClaims(c => c.Type == "Claim1", c => c.Type == "Claim2");
var context = new NancyContext
{
CurrentUser = GetFakeUser(
"username",
new Claim("Claim2", string.Empty))
};
var result = module.Before.Invoke(context, new CancellationToken());
result.Result.ShouldNotBeNull();
result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);
}
[Fact]
public void Should_return_null_with_RequiresClaims_and_all_claims_met()
{
var module = new FakeHookedModule(new BeforePipeline());
module.RequiresClaims(c => c.Type == "Claim1", c => c.Type == "Claim2");
var context = new NancyContext
{
CurrentUser = GetFakeUser("username",
new Claim("Claim1", string.Empty),
new Claim("Claim2", string.Empty),
new Claim("Claim3", string.Empty))
};
var result = module.Before.Invoke(context, new CancellationToken());
result.Result.ShouldBeNull();
}
[Fact]
public void Should_return_forbidden_response_with_RequiresAnyClaim_enabled_but_nonmatching_claims()
{
var module = new FakeHookedModule(new BeforePipeline());
module.RequiresAnyClaim(c => c.Type == "Claim1");
var context = new NancyContext
{
CurrentUser = GetFakeUser(
"username",
new Claim("Claim2", string.Empty),
new Claim("Claim3", string.Empty))
};
var result = module.Before.Invoke(context, new CancellationToken());
result.Result.ShouldNotBeNull();
result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);
}
[Fact]
public void Should_return_forbidden_response_with_RequiresAnyClaim_enabled_but_claims_key_missing()
{
var module = new FakeHookedModule(new BeforePipeline());
module.RequiresAnyClaim(c => c.Type == "Claim1");
var context = new NancyContext
{
CurrentUser = GetFakeUser("username")
};
var result = module.Before.Invoke(context, new CancellationToken());
result.Result.ShouldNotBeNull();
result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);
}
[Fact]
public void Should_return_null_with_RequiresAnyClaim_and_any_claim_met()
{
var module = new FakeHookedModule(new BeforePipeline());
module.RequiresAnyClaim(c => c.Type == "Claim1", c => c.Type == "Claim4");
var context = new NancyContext
{
CurrentUser = GetFakeUser("username",
new Claim("Claim1", string.Empty),
new Claim("Claim2", string.Empty),
new Claim("Claim3", string.Empty))
};
var result = module.Before.Invoke(context, new CancellationToken());
result.Result.ShouldBeNull();
}
[Fact]
public void Should_return_redirect_response_when_request_url_is_non_secure_method_is_get_and_requires_https()
{
// Given
var module = new FakeHookedModule(new BeforePipeline());
var url = GetFakeUrl(false);
var context = new NancyContext
{
Request = new Request("GET", url)
};
module.RequiresHttps();
// When
var result = module.Before.Invoke(context, new CancellationToken());
// Then
result.Result.ShouldNotBeNull();
result.Result.ShouldBeOfType<RedirectResponse>();
url.Scheme = "https";
url.Port = null;
result.Result.Headers["Location"].ShouldEqual(url.ToString());
}
[Fact]
public void Should_return_redirect_response_with_specific_port_number_when_request_url_is_non_secure_method_is_get_and_requires_https()
{
// Given
var module = new FakeHookedModule(new BeforePipeline());
var url = GetFakeUrl(false);
var context = new NancyContext
{
Request = new Request("GET", url)
};
module.RequiresHttps(true, 999);
// When
var result = module.Before.Invoke(context, new CancellationToken());
// Then
result.Result.ShouldNotBeNull();
result.Result.ShouldBeOfType<RedirectResponse>();
url.Scheme = "https";
url.Port = 999;
result.Result.Headers["Location"].ShouldEqual(url.ToString());
}
[Fact]
public void Should_return_forbidden_response_when_request_url_is_non_secure_method_is_post_and_requires_https()
{
// Given
var module = new FakeHookedModule(new BeforePipeline());
var url = GetFakeUrl(false);
var context = new NancyContext
{
Request = new Request("POST", url)
};
module.RequiresHttps();
// When
var result = module.Before.Invoke(context, new CancellationToken());
// Then
result.Result.ShouldNotBeNull();
result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);
}
[Fact]
public void Should_return_forbidden_response_when_request_url_is_non_secure_method_is_delete_and_requires_https()
{
// Given
var module = new FakeHookedModule(new BeforePipeline());
var url = GetFakeUrl(false);
var context = new NancyContext
{
Request = new Request("DELETE", url)
};
module.RequiresHttps();
// When
var result = module.Before.Invoke(context, new CancellationToken());
// Then
result.Result.ShouldNotBeNull();
result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);
}
[Fact]
public void Should_return_forbidden_response_when_request_url_is_non_secure_method_is_get_and_requires_https_and_redirect_is_false()
{
// Given
var module = new FakeHookedModule(new BeforePipeline());
var url = GetFakeUrl(false);
var context = new NancyContext
{
Request = new Request("GET", url)
};
module.RequiresHttps(false);
// When
var result = module.Before.Invoke(context, new CancellationToken());
// Then
result.Result.ShouldNotBeNull();
result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);
}
[Fact]
public void Should_return_forbidden_response_when_request_url_is_non_secure_method_is_post_and_requires_https_and_redirect_is_false()
{
// Given
var module = new FakeHookedModule(new BeforePipeline());
var url = GetFakeUrl(false);
var context = new NancyContext
{
Request = new Request("POST", url)
};
module.RequiresHttps(false);
// When
var result = module.Before.Invoke(context, new CancellationToken());
// Then
result.Result.ShouldNotBeNull();
result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);
}
[Fact]
public void Should_return_null_response_when_request_url_is_secure_method_is_get_and_requires_https()
{
// Given
var module = new FakeHookedModule(new BeforePipeline());
var url = GetFakeUrl(true);
var context = new NancyContext
{
Request = new Request("GET", url)
};
module.RequiresHttps();
// When
var result = module.Before.Invoke(context, new CancellationToken());
// Then
result.Result.ShouldBeNull();
}
[Fact]
public void Should_return_null_response_when_request_url_is_secure_method_is_post_and_requires_https()
{
// Given
var module = new FakeHookedModule(new BeforePipeline());
var url = GetFakeUrl(true);
var context = new NancyContext
{
Request = new Request("POST", url)
};
module.RequiresHttps();
// When
var result = module.Before.Invoke(context, new CancellationToken());
// Then
result.Result.ShouldBeNull();
}
private static ClaimsPrincipal GetFakeUser(string userName, params Claim[] claims)
{
var claimsList = claims.ToList();
claimsList.Add(new Claim(ClaimTypes.NameIdentifier, userName));
return new ClaimsPrincipal(new ClaimsIdentity(claimsList, "test"));
}
private static Url GetFakeUrl(bool https)
{
return new Url
{
BasePath = null,
HostName = "localhost",
Path = "/",
Port = 80,
Query = string.Empty,
Scheme = https ? "https" : "http"
};
}
}
}
| |
#region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
#endregion
using System;
using System.Runtime.WootzJs;
using WootzJs.Testing;
namespace WootzJs.Compiler.Tests
{
public class EventTests : TestFixture
{
[Test]
public void BasicEvent()
{
var o = new EventClass();
var success = false;
o.Foo += () => success = true;
o.OnFoo();
AssertTrue(success);
}
[Test]
public void BasicEventExplicitThis()
{
var o = new EventClass();
var success = false;
o.FooThis += () => success = true;
o.OnFooThis();
AssertTrue(success);
}
[Test]
public void MulticastEvent()
{
var o = new EventClass();
var success1 = false;
var success2 = false;
o.Foo += () => success1 = true;
o.Foo += () => success2 = true;
o.OnFoo();
AssertTrue(success1);
AssertTrue(success2);
}
[Test]
public void MulticastEventRemove()
{
var o = new EventClass();
var success1 = false;
var success2 = false;
Action foo1 = () => success1 = true;
o.Foo += foo1;
o.Foo += () => success2 = true;
o.Foo -= foo1;
o.OnFoo();
AssertTrue((!success1));
AssertTrue(success2);
}
[Test]
public void EventAccessor()
{
var eventClass = new EventClass();
var ran = false;
Action evt = () => ran = true;
eventClass.Bar += evt;
eventClass.OnBar();
AssertTrue(ran);
ran = false;
eventClass.Bar -= evt;
eventClass.OnBar();
AssertTrue((!ran));
}
[Test]
public void MulticastEventKeepsDelegateType()
{
var i = 0;
var eventClass = new EventClass();
eventClass.Foo += () => i++;
eventClass.Foo += () => i++;
var action = eventClass.GetFoo();
AssertTrue((action is Action));
}
[Test]
public void RemoveMethodHandler()
{
var eventClass = new EventClass();
var eventHandlers = new EventHandlers();
eventClass.Foo += eventHandlers.M1;
eventClass.Foo += eventHandlers.M2;
eventClass.OnFoo();
AssertEquals(eventHandlers.m1, "M1");
AssertEquals(eventHandlers.m2, "M2");
eventHandlers.m1 = null;
eventHandlers.m2 = null;
eventClass.Foo -= eventHandlers.M1;
eventClass.OnFoo();
AssertEquals(eventHandlers.m2, "M2");
AssertTrue((eventHandlers.m1 == null));
}
public class EventClass
{
public event Action Foo;
private Action bar;
public void OnFoo()
{
if (Foo != null)
Foo();
}
public Action GetFoo()
{
return Foo;
}
public event Action FooThis;
public void OnFooThis()
{
if (this.FooThis != null)
this.FooThis();
}
public event Action Bar
{
add { bar = (Action)Delegate.Combine(bar, value); }
remove { bar = null; }
}
public void OnBar()
{
if (bar != null)
bar();
}
}
public class EventHandlers
{
public string m1;
public string m2;
public void M1()
{
m1 = "M1";
}
public void M2()
{
m2 = "M2";
}
}
[Test]
public void AutoEventFieldInvoke()
{
var o = new AutoEventFieldClass();
var flag = false;
o.MyEvent += () => flag = true;
var eventInfo = o.GetType().GetEvent("MyEvent");
var @delegate = (Action)eventInfo.DelegateField.GetValue(o);
@delegate();
AssertTrue(flag);
}
[Test]
public void AutoEventFieldDelegateInvoke()
{
var o = new AutoEventFieldClass();
var flag = false;
o.MyEvent += () => flag = true;
var eventInfo = o.GetType().GetEvent("MyEvent");
var @delegate = (Delegate)eventInfo.DelegateField.GetValue(o);
@delegate.DynamicInvoke();
AssertTrue(flag);
}
[Test]
public void AutoEventFieldDelegateInvokeWithStringArg()
{
var o = new AutoEventFieldClass();
var s = "";
o.MyStringEvent += x => s = x;
var eventInfo = o.GetType().GetEvent("MyStringEvent");
var @delegate = (Delegate)eventInfo.DelegateField.GetValue(o);
@delegate.DynamicInvoke("foo");
AssertEquals(s, "foo");
}
public class AutoEventFieldClass
{
public event Action MyEvent;
public event Action<string> MyStringEvent;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Tests
{
public static class SortedListTests
{
[Fact]
public static void Ctor_Empty()
{
var sortList = new SortedList();
Assert.Equal(0, sortList.Count);
Assert.Equal(0, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Ctor_Int(int initialCapacity)
{
var sortList = new SortedList(initialCapacity);
Assert.Equal(0, sortList.Count);
Assert.Equal(initialCapacity, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCapacity", () => new SortedList(-1)); // InitialCapacity < 0
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Ctor_IComparer_Int(int initialCapacity)
{
var sortList = new SortedList(new CustomComparer(), initialCapacity);
Assert.Equal(0, sortList.Count);
Assert.Equal(initialCapacity, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IComparer_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new SortedList(new CustomComparer(), -1)); // InitialCapacity < 0
}
[Fact]
public static void Ctor_IComparer()
{
var sortList = new SortedList(new CustomComparer());
Assert.Equal(0, sortList.Count);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IComparer_Null()
{
var sortList = new SortedList((IComparer)null);
Assert.Equal(0, sortList.Count);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(0, false)]
[InlineData(1, false)]
[InlineData(10, false)]
[InlineData(100, false)]
public static void Ctor_IDictionary(int count, bool sorted)
{
var hashtable = new Hashtable();
if (sorted)
{
// Create a hashtable in the correctly sorted order
for (int i = 0; i < count; i++)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
else
{
// Create a hashtable in the wrong order and make sure it is sorted
for (int i = count - 1; i >= 0; i--)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
var sortList = new SortedList(hashtable);
Assert.Equal(count, sortList.Count);
Assert.True(sortList.Capacity >= sortList.Count);
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i.ToString("D2");
Assert.Equal(sortList.GetByIndex(i), value);
Assert.Equal(hashtable[key], sortList[key]);
}
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new SortedList((IDictionary)null)); // Dictionary is null
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(0, false)]
[InlineData(1, false)]
[InlineData(10, false)]
[InlineData(100, false)]
public static void Ctor_IDictionary_IComparer(int count, bool sorted)
{
var hashtable = new Hashtable();
if (sorted)
{
// Create a hashtable in the correctly sorted order
for (int i = count - 1; i >= 0; i--)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
else
{
// Create a hashtable in the wrong order and make sure it is sorted
for (int i = 0; i < count; i++)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
var sortList = new SortedList(hashtable, new CustomComparer());
Assert.Equal(count, sortList.Count);
Assert.True(sortList.Capacity >= sortList.Count);
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i.ToString("D2");
string expectedValue = "Value_" + (count - i - 1).ToString("D2");
Assert.Equal(sortList.GetByIndex(i), expectedValue);
Assert.Equal(hashtable[key], sortList[key]);
}
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IDictionary_IComparer_Null()
{
var sortList = new SortedList(new Hashtable(), null);
Assert.Equal(0, sortList.Count);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IDictionary_IComparer_NullDictionary_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("d", () => new SortedList(null, new CustomComparer())); // Dictionary is null
}
[Fact]
public static void DebuggerAttribute_Empty()
{
Assert.Equal("Count = 0", DebuggerAttributes.ValidateDebuggerDisplayReferences(new SortedList()));
}
[Fact]
public static void DebuggerAttribute_NormalList()
{
var list = new SortedList() { { "a", 1 }, { "b", 2 } };
DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(list);
PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items");
object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance);
Assert.Equal(list.Count, items.Length);
}
[Fact]
public static void DebuggerAttribute_SynchronizedList()
{
var list = SortedList.Synchronized(new SortedList() { { "a", 1 }, { "b", 2 } });
DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), list);
PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items");
object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance);
Assert.Equal(list.Count, items.Length);
}
[Fact]
public static void DebuggerAttribute_NullSortedList_ThrowsArgumentNullException()
{
bool threwNull = false;
try
{
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), null);
}
catch (TargetInvocationException ex)
{
threwNull = ex.InnerException is ArgumentNullException;
}
Assert.True(threwNull);
}
[Fact]
public static void EnsureCapacity_NewCapacityLessThanMin_CapsToMaxArrayLength()
{
// A situation like this occurs for very large lengths of SortedList.
// To avoid allocating several GBs of memory and making this test run for a very
// long time, we can use reflection to invoke SortedList's growth method manually.
// This is relatively brittle, as it relies on accessing a private method via reflection
// that isn't guaranteed to be stable.
const int InitialCapacity = 10;
const int MinCapacity = InitialCapacity * 2 + 1;
var sortedList = new SortedList(InitialCapacity);
MethodInfo ensureCapacity = sortedList.GetType().GetMethod("EnsureCapacity", BindingFlags.NonPublic | BindingFlags.Instance);
ensureCapacity.Invoke(sortedList, new object[] { MinCapacity });
Assert.Equal(MinCapacity, sortedList.Capacity);
}
[Fact]
public static void Add()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 100; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i;
sortList2.Add(key, value);
Assert.True(sortList2.ContainsKey(key));
Assert.True(sortList2.ContainsValue(value));
Assert.Equal(i, sortList2.IndexOfKey(key));
Assert.Equal(i, sortList2.IndexOfValue(value));
Assert.Equal(i + 1, sortList2.Count);
}
});
}
[Fact]
public static void Add_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Add(null, 101)); // Key is null
Assert.Throws<ArgumentException>(null, () => sortList2.Add(1, 101)); // Key already exists
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Clear(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
sortList2.Clear();
Assert.Equal(0, sortList2.Count);
sortList2.Clear();
Assert.Equal(0, sortList2.Count);
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Clone(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
SortedList sortListClone = (SortedList)sortList2.Clone();
Assert.Equal(sortList2.Count, sortListClone.Count);
Assert.False(sortListClone.IsSynchronized); // IsSynchronized is not copied
Assert.Equal(sortList2.IsFixedSize, sortListClone.IsFixedSize);
Assert.Equal(sortList2.IsReadOnly, sortListClone.IsReadOnly);
for (int i = 0; i < sortListClone.Count; i++)
{
Assert.Equal(sortList2[i], sortListClone[i]);
}
});
}
[Fact]
public static void Clone_IsShallowCopy()
{
var sortList = new SortedList();
for (int i = 0; i < 10; i++)
{
sortList.Add(i, new Foo());
}
SortedList sortListClone = (SortedList)sortList.Clone();
string stringValue = "Hello World";
for (int i = 0; i < 10; i++)
{
Assert.Equal(stringValue, ((Foo)sortListClone[i]).StringValue);
}
// Now we remove an object from the original list, but this should still be present in the clone
sortList.RemoveAt(9);
Assert.Equal(stringValue, ((Foo)sortListClone[9]).StringValue);
stringValue = "Good Bye";
((Foo)sortList[0]).StringValue = stringValue;
Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue);
Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue);
// If we change the object, of course, the previous should not happen
sortListClone[0] = new Foo();
Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue);
stringValue = "Hello World";
Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue);
}
[Fact]
public static void ContainsKey()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 100; i++)
{
string key = "Key_" + i;
sortList2.Add(key, i);
Assert.True(sortList2.Contains(key));
Assert.True(sortList2.ContainsKey(key));
}
Assert.False(sortList2.ContainsKey("Non_Existent_Key"));
for (int i = 0; i < sortList2.Count; i++)
{
string removedKey = "Key_" + i;
sortList2.Remove(removedKey);
Assert.False(sortList2.Contains(removedKey));
Assert.False(sortList2.ContainsKey(removedKey));
}
});
}
[Fact]
public static void ContainsKey_NullKey_ThrowsArgumentNullException()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Contains(null)); // Key is null
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.ContainsKey(null)); // Key is null
});
}
[Fact]
public static void ContainsValue()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 100; i++)
{
sortList2.Add(i, "Value_" + i);
Assert.True(sortList2.ContainsValue("Value_" + i));
}
Assert.False(sortList2.ContainsValue("Non_Existent_Value"));
for (int i = 0; i < sortList2.Count; i++)
{
sortList2.Remove(i);
Assert.False(sortList2.ContainsValue("Value_" + i));
}
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(0, 50)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
public static void CopyTo(int count, int index)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
var array = new object[index + count];
sortList2.CopyTo(array, index);
Assert.Equal(index + count, array.Length);
for (int i = index; i < index + count; i++)
{
int actualIndex = i - index;
string key = "Key_" + actualIndex.ToString("D2");
string value = "Value_" + actualIndex;
DictionaryEntry entry = (DictionaryEntry)array[i];
Assert.Equal(key, entry.Key);
Assert.Equal(value, entry.Value);
}
});
}
[Fact]
public static void CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("array", () => sortList2.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>(() => sortList2.CopyTo(new object[10, 10], 0)); // Array is multidimensional
AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => sortList2.CopyTo(new object[100], -1)); // Index < 0
Assert.Throws<ArgumentException>(null, () => sortList2.CopyTo(new object[150], 51)); // Index + list.Count > array.Count
});
}
[Fact]
public static void GetByIndex()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
Assert.Equal(i, sortList2.GetByIndex(i));
int i2 = sortList2.IndexOfKey(i);
Assert.Equal(i, i2);
i2 = sortList2.IndexOfValue(i);
Assert.Equal(i, i2);
}
});
}
[Fact]
public static void GetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(-1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(sortList2.Count)); // Index >= list.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetEnumerator_IDictionaryEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.NotSame(sortList2.GetEnumerator(), sortList2.GetEnumerator());
IDictionaryEnumerator enumerator = sortList2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
Assert.Equal(enumerator.Current, enumerator.Entry);
Assert.Equal(enumerator.Entry.Key, enumerator.Key);
Assert.Equal(enumerator.Entry.Value, enumerator.Value);
Assert.Equal(sortList2.GetKey(counter), enumerator.Entry.Key);
Assert.Equal(sortList2.GetByIndex(counter), enumerator.Entry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public static void GetEnumerator_IDictionaryEnumerator_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't
IDictionaryEnumerator enumerator = sortList2.GetEnumerator();
enumerator.MoveNext();
sortList2.Add(101, 101);
Assert.NotNull(enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current etc. throw if index < 0
enumerator = sortList2.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current etc. throw after resetting
enumerator = sortList2.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current etc. throw if the current index is >= count
enumerator = sortList2.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetEnumerator_IEnumerator(int count)
{
SortedList sortList = Helpers.CreateIntSortedList(count);
Assert.NotSame(sortList.GetEnumerator(), sortList.GetEnumerator());
IEnumerator enumerator = sortList.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
DictionaryEntry dictEntry = (DictionaryEntry)enumerator.Current;
Assert.Equal(sortList.GetKey(counter), dictEntry.Key);
Assert.Equal(sortList.GetByIndex(counter), dictEntry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
}
[Fact]
public static void GetEnumerator_StartOfEnumeration_Clone()
{
SortedList sortedList = Helpers.CreateIntSortedList(10);
IDictionaryEnumerator enumerator = sortedList.GetEnumerator();
ICloneable cloneableEnumerator = (ICloneable)enumerator;
IDictionaryEnumerator clonedEnumerator = (IDictionaryEnumerator)cloneableEnumerator.Clone();
Assert.NotSame(enumerator, clonedEnumerator);
// Cloned and original enumerators should enumerate separately.
Assert.True(enumerator.MoveNext());
Assert.Equal(sortedList[0], enumerator.Value);
Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Value);
Assert.True(clonedEnumerator.MoveNext());
Assert.Equal(sortedList[0], enumerator.Value);
Assert.Equal(sortedList[0], clonedEnumerator.Value);
// Cloned and original enumerators should enumerate in the same sequence.
for (int i = 1; i < sortedList.Count; i++)
{
Assert.True(enumerator.MoveNext());
Assert.NotEqual(enumerator.Current, clonedEnumerator.Current);
Assert.True(clonedEnumerator.MoveNext());
Assert.Equal(enumerator.Current, clonedEnumerator.Current);
}
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Equal(sortedList[sortedList.Count - 1], clonedEnumerator.Value);
Assert.False(clonedEnumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Value);
}
[Fact]
public static void GetEnumerator_InMiddleOfEnumeration_Clone()
{
SortedList sortedList = Helpers.CreateIntSortedList(10);
IEnumerator enumerator = sortedList.GetEnumerator();
enumerator.MoveNext();
ICloneable cloneableEnumerator = (ICloneable)enumerator;
// Cloned and original enumerators should start at the same spot, even
// if the original is in the middle of enumeration.
IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone();
Assert.Equal(enumerator.Current, clonedEnumerator.Current);
for (int i = 0; i < sortedList.Count - 1; i++)
{
Assert.True(clonedEnumerator.MoveNext());
}
Assert.False(clonedEnumerator.MoveNext());
}
[Fact]
public static void GetEnumerator_IEnumerator_Invalid()
{
SortedList sortList = Helpers.CreateIntSortedList(100);
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current doesn't
IEnumerator enumerator = ((IEnumerable)sortList).GetEnumerator();
enumerator.MoveNext();
sortList.Add(101, 101);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
// Current throws if index < 0
enumerator = sortList.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current throw after resetting
enumerator = sortList.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current throw if the current index is >= count
enumerator = sortList.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetKeyList(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys1 = sortList2.GetKeyList();
IList keys2 = sortList2.GetKeyList();
// Test we have copied the correct keys
Assert.Equal(count, keys1.Count);
Assert.Equal(count, keys2.Count);
for (int i = 0; i < keys1.Count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.Equal(key, keys1[i]);
Assert.Equal(key, keys2[i]);
Assert.True(sortList2.ContainsKey(keys1[i]));
}
});
}
[Fact]
public static void GetKeyList_IsSameAsKeysProperty()
{
var sortList = Helpers.CreateIntSortedList(10);
Assert.Same(sortList.GetKeyList(), sortList.Keys);
}
[Fact]
public static void GetKeyList_IListProperties()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.True(keys.IsReadOnly);
Assert.True(keys.IsFixedSize);
Assert.False(keys.IsSynchronized);
Assert.Equal(sortList2.SyncRoot, keys.SyncRoot);
});
}
[Fact]
public static void GetKeyList_Contains()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
for (int i = 0; i < keys.Count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.True(keys.Contains(key));
}
Assert.False(keys.Contains("Key_101")); // No such key
});
}
[Fact]
public static void GetKeyList_Contains_InvalidValueType_ThrowsInvalidOperationException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.Throws<InvalidOperationException>(() => keys.Contains("hello")); // Value is a different object type
});
}
[Fact]
public static void GetKeyList_IndexOf()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
for (int i = 0; i < keys.Count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.Equal(i, keys.IndexOf(key));
}
Assert.Equal(-1, keys.IndexOf("Key_101"));
});
}
[Fact]
public static void GetKeyList_IndexOf_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
AssertExtensions.Throws<ArgumentNullException>("key", () => keys.IndexOf(null)); // Value is null
Assert.Throws<InvalidOperationException>(() => keys.IndexOf("hello")); // Value is a different object type
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(0, 50)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
public static void GetKeyList_CopyTo(int count, int index)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
object[] array = new object[index + count];
IList keys = sortList2.GetKeyList();
keys.CopyTo(array, index);
Assert.Equal(index + count, array.Length);
for (int i = index; i < index + count; i++)
{
Assert.Equal(keys[i - index], array[i]);
}
});
}
[Fact]
public static void GetKeyList_CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => keys.CopyTo(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", null, () => keys.CopyTo(new object[10, 10], 0)); // Array is multidimensional -- in netfx ParamName is null
// Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => keys.CopyTo(new object[100], -1));
// Index + list.Count > array.Count
AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => keys.CopyTo(new object[150], 51));
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetKeyList_GetEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.NotSame(keys.GetEnumerator(), keys.GetEnumerator());
IEnumerator enumerator = sortList2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
object key = keys[counter];
DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
Assert.Equal(key, entry.Key);
Assert.Equal(sortList2[key], entry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public static void GetKeyList_GetEnumerator_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't
IEnumerator enumerator = keys.GetEnumerator();
enumerator.MoveNext();
sortList2.Add(101, 101);
Assert.NotNull(enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
// Current etc. throw if index < 0
enumerator = keys.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw after resetting
enumerator = keys.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw if the current index is >= count
enumerator = keys.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
});
}
[Fact]
public static void GetKeyList_TryingToModifyCollection_ThrowsNotSupportedException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.Throws<NotSupportedException>(() => keys.Add(101));
Assert.Throws<NotSupportedException>(() => keys.Clear());
Assert.Throws<NotSupportedException>(() => keys.Insert(0, 101));
Assert.Throws<NotSupportedException>(() => keys.Remove(1));
Assert.Throws<NotSupportedException>(() => keys.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => keys[0] = 101);
});
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public static void GetKey(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.Equal(key, sortList2.GetKey(sortList2.IndexOfKey(key)));
}
});
}
[Fact]
public static void GetKey_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(-1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(sortList2.Count)); // Index >= count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetValueList(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values1 = sortList2.GetValueList();
IList values2 = sortList2.GetValueList();
// Test we have copied the correct values
Assert.Equal(count, values1.Count);
Assert.Equal(count, values2.Count);
for (int i = 0; i < values1.Count; i++)
{
string value = "Value_" + i;
Assert.Equal(value, values1[i]);
Assert.Equal(value, values2[i]);
Assert.True(sortList2.ContainsValue(values2[i]));
}
});
}
[Fact]
public static void GetValueList_IsSameAsValuesProperty()
{
var sortList = Helpers.CreateIntSortedList(10);
Assert.Same(sortList.GetValueList(), sortList.Values);
}
[Fact]
public static void GetValueList_IListProperties()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.True(values.IsReadOnly);
Assert.True(values.IsFixedSize);
Assert.False(values.IsSynchronized);
Assert.Equal(sortList2.SyncRoot, values.SyncRoot);
});
}
[Fact]
public static void GetValueList_Contains()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
for (int i = 0; i < values.Count; i++)
{
string value = "Value_" + i;
Assert.True(values.Contains(value));
}
// No such value
Assert.False(values.Contains("Value_101"));
Assert.False(values.Contains(101));
Assert.False(values.Contains(null));
});
}
[Fact]
public static void GetValueList_IndexOf()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
for (int i = 0; i < values.Count; i++)
{
string value = "Value_" + i;
Assert.Equal(i, values.IndexOf(value));
}
Assert.Equal(-1, values.IndexOf(101));
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(0, 50)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
public static void GetValueList_CopyTo(int count, int index)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
object[] array = new object[index + count];
IList values = sortList2.GetValueList();
values.CopyTo(array, index);
Assert.Equal(index + count, array.Length);
for (int i = index; i < index + count; i++)
{
Assert.Equal(values[i - index], array[i]);
}
});
}
[Fact]
public static void GetValueList_CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => values.CopyTo(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", null, () => values.CopyTo(new object[10, 10], 0)); // Array is multidimensional -- in netfx ParamName is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => values.CopyTo(new object[100], -1)); // Index < 0
AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => values.CopyTo(new object[150], 51)); // Index + list.Count > array.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetValueList_GetEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.NotSame(values.GetEnumerator(), values.GetEnumerator());
IEnumerator enumerator = sortList2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
object key = values[counter];
DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
Assert.Equal(key, entry.Key);
Assert.Equal(sortList2[key], entry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public static void ValueList_GetEnumerator_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't
IEnumerator enumerator = values.GetEnumerator();
enumerator.MoveNext();
sortList2.Add(101, 101);
Assert.NotNull(enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
// Current etc. throw if index < 0
enumerator = values.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw after resetting
enumerator = values.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw if the current index is >= count
enumerator = values.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
});
}
[Fact]
public static void GetValueList_TryingToModifyCollection_ThrowsNotSupportedException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.Throws<NotSupportedException>(() => values.Add(101));
Assert.Throws<NotSupportedException>(() => values.Clear());
Assert.Throws<NotSupportedException>(() => values.Insert(0, 101));
Assert.Throws<NotSupportedException>(() => values.Remove(1));
Assert.Throws<NotSupportedException>(() => values.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => values[0] = 101);
});
}
[Fact]
public static void IndexOfKey()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i;
int index = sortList2.IndexOfKey(key);
Assert.Equal(i, index);
Assert.Equal(value, sortList2.GetByIndex(index));
}
Assert.Equal(-1, sortList2.IndexOfKey("Non Existent Key"));
string removedKey = "Key_01";
sortList2.Remove(removedKey);
Assert.Equal(-1, sortList2.IndexOfKey(removedKey));
});
}
[Fact]
public static void IndexOfKey_NullKey_ThrowsArgumentNullException()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.IndexOfKey(null)); // Key is null
});
}
[Fact]
public static void IndexOfValue()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
string value = "Value_" + i;
int index = sortList2.IndexOfValue(value);
Assert.Equal(i, index);
Assert.Equal(value, sortList2.GetByIndex(index));
}
Assert.Equal(-1, sortList2.IndexOfValue("Non Existent Value"));
string removedKey = "Key_01";
string removedValue = "Value_1";
sortList2.Remove(removedKey);
Assert.Equal(-1, sortList2.IndexOfValue(removedValue));
Assert.Equal(-1, sortList2.IndexOfValue(null));
sortList2.Add("Key_101", null);
Assert.NotEqual(-1, sortList2.IndexOfValue(null));
});
}
[Fact]
public static void IndexOfValue_SameValue()
{
var sortList1 = new SortedList();
sortList1.Add("Key_0", "Value_0");
sortList1.Add("Key_1", "Value_Same");
sortList1.Add("Key_2", "Value_Same");
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Equal(1, sortList2.IndexOfValue("Value_Same"));
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(4)]
[InlineData(5000)]
public static void Capacity_Get_Set(int capacity)
{
var sortList = new SortedList();
sortList.Capacity = capacity;
Assert.Equal(capacity, sortList.Capacity);
// Ensure nothing changes if we set capacity to the same value again
sortList.Capacity = capacity;
Assert.Equal(capacity, sortList.Capacity);
}
[Fact]
public static void Capacity_Set_ShrinkingCapacity_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = sortList2.Count - 1); // Capacity < count
});
}
[Fact]
public static void Capacity_Set_Invalid()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = -1); // Capacity < 0
Assert.Throws<OutOfMemoryException>(() => sortList2.Capacity = int.MaxValue); // Capacity is too large
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
public static void Item_Get(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i;
Assert.Equal(value, sortList2[key]);
}
Assert.Null(sortList2["No Such Key"]);
string removedKey = "Key_01";
sortList2.Remove(removedKey);
Assert.Null(sortList2[removedKey]);
});
}
[Fact]
public static void Item_Get_DifferentCulture()
{
var sortList = new SortedList();
CultureInfo currentCulture = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = new CultureInfo("en-US");
var cultureNames = new string[]
{
"cs-CZ","da-DK","de-DE","el-GR","en-US",
"es-ES","fi-FI","fr-FR","hu-HU","it-IT",
"ja-JP","ko-KR","nb-NO","nl-NL","pl-PL",
"pt-BR","pt-PT","ru-RU","sv-SE","tr-TR",
"zh-CN","zh-HK","zh-TW"
};
var installedCultures = new CultureInfo[cultureNames.Length];
var cultureDisplayNames = new string[installedCultures.Length];
int uniqueDisplayNameCount = 0;
foreach (string cultureName in cultureNames)
{
var culture = new CultureInfo(cultureName);
installedCultures[uniqueDisplayNameCount] = culture;
cultureDisplayNames[uniqueDisplayNameCount] = culture.DisplayName;
sortList.Add(cultureDisplayNames[uniqueDisplayNameCount], culture);
uniqueDisplayNameCount++;
}
// In Czech ch comes after h if the comparer changes based on the current culture of the thread
// we will not be able to find some items
CultureInfo.CurrentCulture = new CultureInfo("cs-CZ");
for (int i = 0; i < uniqueDisplayNameCount; i++)
{
Assert.Equal(installedCultures[i], sortList[installedCultures[i].DisplayName]);
}
}
catch (CultureNotFoundException)
{
}
finally
{
CultureInfo.CurrentCulture = currentCulture;
}
}
[Fact]
public static void Item_Set()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// Change existing keys
for (int i = 0; i < sortList2.Count; i++)
{
sortList2[i] = i + 1;
Assert.Equal(i + 1, sortList2[i]);
// Make sure nothing bad happens when we try to set the key to its current valeu
sortList2[i] = i + 1;
Assert.Equal(i + 1, sortList2[i]);
}
// Add new keys
sortList2[101] = 2048;
Assert.Equal(2048, sortList2[101]);
sortList2[102] = null;
Assert.Equal(null, sortList2[102]);
});
}
[Fact]
public static void Item_Set_NullKey_ThrowsArgumentNullException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2[null] = 101); // Key is null
});
}
[Fact]
public static void RemoveAt()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// Remove from end
for (int i = sortList2.Count - 1; i >= 0; i--)
{
sortList2.RemoveAt(i);
Assert.False(sortList2.ContainsKey(i));
Assert.False(sortList2.ContainsValue(i));
Assert.Equal(i, sortList2.Count);
}
});
}
[Fact]
public static void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(-1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(sortList2.Count)); // Index >= count
});
}
[Fact]
public static void Remove()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// Remove from the end
for (int i = sortList2.Count - 1; i >= 0; i--)
{
sortList2.Remove(i);
Assert.False(sortList2.ContainsKey(i));
Assert.False(sortList2.ContainsValue(i));
Assert.Equal(i, sortList2.Count);
}
sortList2.Remove(101); // No such key
});
}
[Fact]
public static void Remove_NullKey_ThrowsArgumentNullException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Remove(null)); // Key is null
});
}
[Fact]
public static void SetByIndex()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
sortList2.SetByIndex(i, i + 1);
Assert.Equal(i + 1, sortList2.GetByIndex(i));
}
});
}
[Fact]
public static void SetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeExeption()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(-1, 101)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(sortList2.Count, 101)); // Index >= list.Count
});
}
[Fact]
public static void Synchronized_IsSynchronized()
{
SortedList sortList = SortedList.Synchronized(new SortedList());
Assert.True(sortList.IsSynchronized);
}
[Fact]
public static void Synchronized_NullList_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("list", () => SortedList.Synchronized(null)); // List is null
}
[Fact]
public static void TrimToSize()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 10; i++)
{
sortList2.RemoveAt(0);
}
sortList2.TrimToSize();
Assert.Equal(sortList2.Count, sortList2.Capacity);
sortList2.Clear();
sortList2.TrimToSize();
Assert.Equal(0, sortList2.Capacity);
});
}
private class Foo
{
public string StringValue { get; set; } = "Hello World";
}
private class CustomComparer : IComparer
{
public int Compare(object obj1, object obj2) => -string.Compare(obj1.ToString(), obj2.ToString());
}
}
public class SortedList_SyncRootTests
{
private SortedList _sortListDaughter;
private SortedList _sortListGrandDaughter;
private const int NumberOfElements = 100;
[Fact]
[OuterLoop]
public void GetSyncRootBasic()
{
// Testing SyncRoot is not as simple as its implementation looks like. This is the working
// scenario we have in mind.
// 1) Create your Down to earth mother SortedList
// 2) Get a synchronized wrapper from it
// 3) Get a Synchronized wrapper from 2)
// 4) Get a synchronized wrapper of the mother from 1)
// 5) all of these should SyncRoot to the mother earth
var sortListMother = new SortedList();
for (int i = 0; i < NumberOfElements; i++)
{
sortListMother.Add("Key_" + i, "Value_" + i);
}
Assert.Equal(sortListMother.SyncRoot.GetType(), typeof(object));
SortedList sortListSon = SortedList.Synchronized(sortListMother);
_sortListGrandDaughter = SortedList.Synchronized(sortListSon);
_sortListDaughter = SortedList.Synchronized(sortListMother);
Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot);
Assert.Equal(sortListMother.SyncRoot, sortListSon.SyncRoot);
Assert.Equal(_sortListGrandDaughter.SyncRoot, sortListMother.SyncRoot);
Assert.Equal(_sortListDaughter.SyncRoot, sortListMother.SyncRoot);
Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot);
//we are going to rumble with the SortedLists with some threads
var workers = new Task[4];
for (int i = 0; i < workers.Length; i += 2)
{
var name = "Thread_worker_" + i;
var action1 = new Action(() => AddMoreElements(name));
var action2 = new Action(RemoveElements);
workers[i] = Task.Run(action1);
workers[i + 1] = Task.Run(action2);
}
Task.WaitAll(workers);
// Checking time
// Now lets see how this is done.
// Either there are some elements or none
var sortListPossible = new SortedList();
for (int i = 0; i < NumberOfElements; i++)
{
sortListPossible.Add("Key_" + i, "Value_" + i);
}
for (int i = 0; i < workers.Length; i++)
{
sortListPossible.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
}
//lets check the values if
IDictionaryEnumerator enumerator = sortListMother.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.True(sortListPossible.ContainsKey(enumerator.Key));
Assert.True(sortListPossible.ContainsValue(enumerator.Value));
}
}
private void AddMoreElements(string threadName)
{
_sortListGrandDaughter.Add("Key_" + threadName, threadName);
}
private void RemoveElements()
{
_sortListDaughter.Clear();
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudtrail-2013-11-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.CloudTrail.Model;
namespace Amazon.CloudTrail
{
/// <summary>
/// Interface for accessing CloudTrail
///
/// AWS CloudTrail
/// <para>
/// This is the CloudTrail API Reference. It provides descriptions of actions, data types,
/// common parameters, and common errors for CloudTrail.
/// </para>
///
/// <para>
/// CloudTrail is a web service that records AWS API calls for your AWS account and delivers
/// log files to an Amazon S3 bucket. The recorded information includes the identity of
/// the user, the start time of the AWS API call, the source IP address, the request parameters,
/// and the response elements returned by the service.
/// </para>
/// <note> As an alternative to using the API, you can use one of the AWS SDKs, which
/// consist of libraries and sample code for various programming languages and platforms
/// (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient way to create
/// programmatic access to AWSCloudTrail. For example, the SDKs take care of cryptographically
/// signing requests, managing errors, and retrying requests automatically. For information
/// about the AWS SDKs, including how to download and install them, see the <a href="http://aws.amazon.com/tools/">Tools
/// for Amazon Web Services page</a>. </note>
/// <para>
/// See the CloudTrail User Guide for information about the data that is included with
/// each AWS API call listed in the log files.
/// </para>
/// </summary>
public partial interface IAmazonCloudTrail : IDisposable
{
#region CreateTrail
/// <summary>
/// From the command line, use <code>create-subscription</code>.
///
///
/// <para>
/// Creates a trail that specifies the settings for delivery of log data to an Amazon
/// S3 bucket.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateTrail service method.</param>
///
/// <returns>The response from the CreateTrail service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.CloudWatchLogsDeliveryUnavailableException">
/// Cannot set a CloudWatch Logs delivery for this region.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InsufficientS3BucketPolicyException">
/// This exception is thrown when the policy on the S3 bucket is not sufficient.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InsufficientSnsTopicPolicyException">
/// This exception is thrown when the policy on the SNS topic is not sufficient.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidCloudWatchLogsLogGroupArnException">
/// This exception is thrown when the provided CloudWatch log group is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidCloudWatchLogsRoleArnException">
/// This exception is thrown when the provided role is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidS3BucketNameException">
/// This exception is thrown when the provided S3 bucket name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidS3PrefixException">
/// This exception is thrown when the provided S3 prefix is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidSnsTopicNameException">
/// This exception is thrown when the provided SNS topic name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.MaximumNumberOfTrailsExceededException">
/// This exception is thrown when the maximum number of trails is reached.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.S3BucketDoesNotExistException">
/// This exception is thrown when the specified S3 bucket does not exist.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailAlreadyExistsException">
/// This exception is thrown when the specified trail already exists.
/// </exception>
CreateTrailResponse CreateTrail(CreateTrailRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateTrail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateTrail operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateTrail
/// operation.</returns>
IAsyncResult BeginCreateTrail(CreateTrailRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateTrail operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateTrail.</param>
///
/// <returns>Returns a CreateTrailResult from CloudTrail.</returns>
CreateTrailResponse EndCreateTrail(IAsyncResult asyncResult);
#endregion
#region DeleteTrail
/// <summary>
/// Deletes a trail.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteTrail service method.</param>
///
/// <returns>The response from the DeleteTrail service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
DeleteTrailResponse DeleteTrail(DeleteTrailRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteTrail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteTrail operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteTrail
/// operation.</returns>
IAsyncResult BeginDeleteTrail(DeleteTrailRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteTrail operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteTrail.</param>
///
/// <returns>Returns a DeleteTrailResult from CloudTrail.</returns>
DeleteTrailResponse EndDeleteTrail(IAsyncResult asyncResult);
#endregion
#region DescribeTrails
/// <summary>
/// Retrieves settings for the trail associated with the current region for your account.
/// </summary>
///
/// <returns>The response from the DescribeTrails service method, as returned by CloudTrail.</returns>
DescribeTrailsResponse DescribeTrails();
/// <summary>
/// Retrieves settings for the trail associated with the current region for your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeTrails service method.</param>
///
/// <returns>The response from the DescribeTrails service method, as returned by CloudTrail.</returns>
DescribeTrailsResponse DescribeTrails(DescribeTrailsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeTrails operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeTrails operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeTrails
/// operation.</returns>
IAsyncResult BeginDescribeTrails(DescribeTrailsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeTrails operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeTrails.</param>
///
/// <returns>Returns a DescribeTrailsResult from CloudTrail.</returns>
DescribeTrailsResponse EndDescribeTrails(IAsyncResult asyncResult);
#endregion
#region GetTrailStatus
/// <summary>
/// Returns a JSON-formatted list of information about the specified trail. Fields include
/// information on delivery errors, Amazon SNS and Amazon S3 errors, and start and stop
/// logging times for each trail.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetTrailStatus service method.</param>
///
/// <returns>The response from the GetTrailStatus service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
GetTrailStatusResponse GetTrailStatus(GetTrailStatusRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetTrailStatus operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetTrailStatus operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetTrailStatus
/// operation.</returns>
IAsyncResult BeginGetTrailStatus(GetTrailStatusRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetTrailStatus operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetTrailStatus.</param>
///
/// <returns>Returns a GetTrailStatusResult from CloudTrail.</returns>
GetTrailStatusResponse EndGetTrailStatus(IAsyncResult asyncResult);
#endregion
#region LookupEvents
/// <summary>
/// Looks up API activity events captured by CloudTrail that create, update, or delete
/// resources in your account. Events for a region can be looked up for the times in which
/// you had CloudTrail turned on in that region during the last seven days. Lookup supports
/// five different attributes: time range (defined by a start time and end time), user
/// name, event name, resource type, and resource name. All attributes are optional. The
/// maximum number of attributes that can be specified in any one lookup request are time
/// range and one other attribute. The default number of results returned is 10, with
/// a maximum of 50 possible. The response includes a token that you can use to get the
/// next page of results. The rate of lookup requests is limited to one per second per
/// account.
///
/// <important>Events that occurred during the selected time range will not be available
/// for lookup if CloudTrail logging was not enabled when the events occurred.</important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the LookupEvents service method.</param>
///
/// <returns>The response from the LookupEvents service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidLookupAttributesException">
/// Occurs when an invalid lookup attribute is specified.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidMaxResultsException">
/// This exception is thrown if the limit specified is invalid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidNextTokenException">
/// Invalid token or token that was previously used in a request with different parameters.
/// This exception is thrown if the token is invalid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTimeRangeException">
/// Occurs if the timestamp values are invalid. Either the start time occurs after the
/// end time or the time range is outside the range of possible values.
/// </exception>
LookupEventsResponse LookupEvents(LookupEventsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the LookupEvents operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the LookupEvents operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndLookupEvents
/// operation.</returns>
IAsyncResult BeginLookupEvents(LookupEventsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the LookupEvents operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginLookupEvents.</param>
///
/// <returns>Returns a LookupEventsResult from CloudTrail.</returns>
LookupEventsResponse EndLookupEvents(IAsyncResult asyncResult);
#endregion
#region StartLogging
/// <summary>
/// Starts the recording of AWS API calls and log file delivery for a trail.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartLogging service method.</param>
///
/// <returns>The response from the StartLogging service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
StartLoggingResponse StartLogging(StartLoggingRequest request);
/// <summary>
/// Initiates the asynchronous execution of the StartLogging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StartLogging operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartLogging
/// operation.</returns>
IAsyncResult BeginStartLogging(StartLoggingRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the StartLogging operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartLogging.</param>
///
/// <returns>Returns a StartLoggingResult from CloudTrail.</returns>
StartLoggingResponse EndStartLogging(IAsyncResult asyncResult);
#endregion
#region StopLogging
/// <summary>
/// Suspends the recording of AWS API calls and log file delivery for the specified trail.
/// Under most circumstances, there is no need to use this action. You can update a trail
/// without stopping it first. This action is the only way to stop recording.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StopLogging service method.</param>
///
/// <returns>The response from the StopLogging service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
StopLoggingResponse StopLogging(StopLoggingRequest request);
/// <summary>
/// Initiates the asynchronous execution of the StopLogging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StopLogging operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStopLogging
/// operation.</returns>
IAsyncResult BeginStopLogging(StopLoggingRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the StopLogging operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginStopLogging.</param>
///
/// <returns>Returns a StopLoggingResult from CloudTrail.</returns>
StopLoggingResponse EndStopLogging(IAsyncResult asyncResult);
#endregion
#region UpdateTrail
/// <summary>
/// From the command line, use <code>update-subscription</code>.
///
///
/// <para>
/// Updates the settings that specify delivery of log files. Changes to a trail do not
/// require stopping the CloudTrail service. Use this action to designate an existing
/// bucket for log delivery. If the existing bucket has previously been a target for CloudTrail
/// log files, an IAM policy exists for the bucket.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateTrail service method.</param>
///
/// <returns>The response from the UpdateTrail service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.CloudWatchLogsDeliveryUnavailableException">
/// Cannot set a CloudWatch Logs delivery for this region.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InsufficientS3BucketPolicyException">
/// This exception is thrown when the policy on the S3 bucket is not sufficient.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InsufficientSnsTopicPolicyException">
/// This exception is thrown when the policy on the SNS topic is not sufficient.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidCloudWatchLogsLogGroupArnException">
/// This exception is thrown when the provided CloudWatch log group is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidCloudWatchLogsRoleArnException">
/// This exception is thrown when the provided role is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidS3BucketNameException">
/// This exception is thrown when the provided S3 bucket name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidS3PrefixException">
/// This exception is thrown when the provided S3 prefix is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidSnsTopicNameException">
/// This exception is thrown when the provided SNS topic name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.S3BucketDoesNotExistException">
/// This exception is thrown when the specified S3 bucket does not exist.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
UpdateTrailResponse UpdateTrail(UpdateTrailRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateTrail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateTrail operation on AmazonCloudTrailClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateTrail
/// operation.</returns>
IAsyncResult BeginUpdateTrail(UpdateTrailRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateTrail operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateTrail.</param>
///
/// <returns>Returns a UpdateTrailResult from CloudTrail.</returns>
UpdateTrailResponse EndUpdateTrail(IAsyncResult asyncResult);
#endregion
}
}
| |
namespace Nancy
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Nancy.Cookies;
/// <summary>
/// Provides strongly-typed access to HTTP request headers.
/// </summary>
public class RequestHeaders : IEnumerable<KeyValuePair<string, IEnumerable<string>>>
{
private readonly IDictionary<string, IEnumerable<string>> headers;
/// <summary>
/// Initializes a new instance of the <see cref="RequestHeaders"/> class.
/// </summary>
/// <param name="headers">The headers.</param>
public RequestHeaders(IDictionary<string, IEnumerable<string>> headers)
{
this.headers = new Dictionary<string, IEnumerable<string>>(headers, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Content-types that are acceptable.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<Tuple<string, decimal>> Accept
{
get { return GetWeightedValues("Accept").ToList(); }
set { this.SetHeaderValues("Accept", value, GetWeightedValuesAsStrings); }
}
/// <summary>
/// Character sets that are acceptable.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<Tuple<string, decimal>> AcceptCharset
{
get { return this.GetWeightedValues("Accept-Charset"); }
set { this.SetHeaderValues("Accept-Charset", value, GetWeightedValuesAsStrings); }
}
/// <summary>
/// Acceptable encodings.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<string> AcceptEncoding
{
get { return this.GetSplitValues("Accept-Encoding"); }
set { this.SetHeaderValues("Accept-Encoding", value, x => x); }
}
/// <summary>
/// Acceptable languages for response.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<Tuple<string, decimal>> AcceptLanguage
{
get { return this.GetWeightedValues("Accept-Language"); }
set { this.SetHeaderValues("Accept-Language", value, GetWeightedValuesAsStrings); }
}
/// <summary>
/// Acceptable languages for response.
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string Authorization
{
get { return this.GetValue("Authorization", x => x.First()); }
set { this.SetHeaderValues("Authorization", value, x => new[] { x }); }
}
/// <summary>
/// Used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<string> CacheControl
{
get { return this.GetValue("Cache-Control"); }
set { this.SetHeaderValues("Cache-Control", value, x => x); }
}
/// <summary>
/// Contains name/value pairs of information stored for that URL.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains <see cref="INancyCookie"/> instances if they are available; otherwise it will be empty.</value>
public IEnumerable<INancyCookie> Cookie
{
get { return this.GetValue("Cookie", GetNancyCookies); }
}
/// <summary>
/// What type of connection the user-agent would prefer.
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string Connection
{
get { return this.GetValue("Connection", x => x.First()); }
set { this.SetHeaderValues("Connection", value, x => new[] { x }); }
}
/// <summary>
/// The length of the request body in octets (8-bit bytes).
/// </summary>
/// <value>The lenght of the contents if it is available; otherwise 0.</value>
public long ContentLength
{
get { return this.GetValue("Content-Length", x => Convert.ToInt64(x.First())); }
set { this.SetHeaderValues("Content-Length", value, x => new[] { x.ToString(CultureInfo.InvariantCulture) }); }
}
/// <summary>
/// The mime type of the body of the request (used with POST and PUT requests).
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string ContentType
{
get { return this.GetValue("Content-Type", x => x.First()); }
set { this.SetHeaderValues("Content-Type", value, x => new[] { x }); }
}
/// <summary>
/// The date and time that the message was sent.
/// </summary>
/// <value>A <see cref="DateTime"/> instance that specifies when the message was sent. If not available then <see cref="DateTime.MinValue"/> will be returned.</value>
public DateTime? Date
{
get { return this.GetValue("Date", x => ParseDateTime(x.First())); }
set { this.SetHeaderValues("Date", value, x => new[] { GetDateAsString(value) }); }
}
/// <summary>
/// The domain name of the server (for virtual hosting), mandatory since HTTP/1.1
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string Host
{
get { return this.GetValue("Host", x => x.First()); }
set { this.SetHeaderValues("Host", value, x => new[] { x }); }
}
/// <summary>
/// Only perform the action if the client supplied entity matches the same entity on the server. This is mainly for methods like PUT to only update a resource if it has not been modified since the user last updated it.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<string> IfMatch
{
get { return this.GetValue("If-Match"); }
set { this.SetHeaderValues("If-Match", value, x => x); }
}
/// <summary>
/// Allows a 304 Not Modified to be returned if content is unchanged
/// </summary>
/// <value>A <see cref="DateTime"/> instance that specifies when the requested resource must have been changed since. If not available then <see cref="DateTime.MinValue"/> will be returned.</value>
public DateTime? IfModifiedSince
{
get { return this.GetValue("If-Modified-Since", x => ParseDateTime(x.First())); }
set { this.SetHeaderValues("If-Modified-Since", value, x => new[] { GetDateAsString(value) }); }
}
/// <summary>
/// Allows a 304 Not Modified to be returned if content is unchanged
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<string> IfNoneMatch
{
get { return this.GetValue("If-None-Match"); }
set { this.SetHeaderValues("If-None-Match", value, x => x); }
}
/// <summary>
/// If the entity is unchanged, send me the part(s) that I am missing; otherwise, send me the entire new entity.
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string IfRange
{
get { return this.GetValue("If-Range", x => x.First()); }
set { this.SetHeaderValues("If-Range", value, x => new[] { x }); }
}
/// <summary>
/// Only send the response if the entity has not been modified since a specific time.
/// </summary>
/// <value>A <see cref="DateTime"/> instance that specifies when the requested resource may not have been changed since. If not available then <see cref="DateTime.MinValue"/> will be returned.</value>
public DateTime? IfUnmodifiedSince
{
get { return this.GetValue("If-Unmodified-Since", x => ParseDateTime(x.First())); }
set { this.SetHeaderValues("If-Unmodified-Since", value, x => new[] { GetDateAsString(value) }); }
}
/// <summary>
/// Gets the names of the available request headers.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> containing the names of the headers.</value>
public IEnumerable<string> Keys
{
get { return this.headers.Keys; }
}
/// <summary>
/// Limit the number of times the message can be forwarded through proxies or gateways.
/// </summary>
/// <value>The number of the maximum allowed number of forwards if it is available; otherwise 0.</value>
public int MaxForwards
{
get { return this.GetValue("Max-Forwards", x => Convert.ToInt32(x.First())); }
set { this.SetHeaderValues("Max-Forwards", value, x => new[] { x.ToString(CultureInfo.InvariantCulture) }); }
}
/// <summary>
/// This is the address of the previous web page from which a link to the currently requested page was followed.
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string Referrer
{
get { return this.GetValue("Referer", x => x.First()); }
set { this.SetHeaderValues("Referer", value, x => new[] { x }); }
}
/// <summary>
/// The user agent string of the user agent
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string UserAgent
{
get { return this.GetValue("User-Agent", x => x.First()); }
set { this.SetHeaderValues("User-Agent", value, x => new[] { x }); }
}
/// <summary>
/// Gets all the header values.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains all the header values.</value>
public IEnumerable<IEnumerable<string>> Values
{
get { return this.headers.Values; }
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.</returns>
public IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator()
{
return this.headers.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Gets the values for the header identified by the <paramref name="name"/> parameter.
/// </summary>
/// <param name="name">The name of the header to return the values for.</param>
/// <returns>An <see cref="IEnumerable{T}"/> that contains the values for the header. If the header is not defined then <see cref="Enumerable.Empty{TResult}"/> is returned.</returns>
public IEnumerable<string> this[string name]
{
get
{
return (this.headers.ContainsKey(name)) ?
this.headers[name] :
Enumerable.Empty<string>();
}
}
private static string GetDateAsString(DateTime? value)
{
return !value.HasValue ? null : value.Value.ToString("R", CultureInfo.InvariantCulture);
}
private IEnumerable<string> GetSplitValues(string header)
{
var values = this.GetValue(header);
return values
.SelectMany(x => x.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
.Select(x => x.Trim())
.ToList();
}
private IEnumerable<Tuple<string, decimal>> GetWeightedValues(string headerName)
{
var values = this.GetSplitValues(headerName);
var parsed = values.Select(x =>
{
var sections = x.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
var mediaRange = sections[0].Trim();
var quality = 1m;
for (var index = 1; index < sections.Length; index++)
{
var trimmedValue = sections[index].Trim();
if (trimmedValue.StartsWith("q=", StringComparison.OrdinalIgnoreCase))
{
decimal temp;
var stringValue = trimmedValue.Substring(2);
if (decimal.TryParse(stringValue, NumberStyles.Number, CultureInfo.InvariantCulture, out temp))
{
quality = temp;
break;
}
}
}
return new Tuple<string, decimal>(mediaRange, quality);
});
return parsed
.OrderByDescending(x => x.Item2);
}
private static object GetDefaultValue(Type T)
{
if (IsGenericEnumerable(T))
{
var enumerableType = T.GetGenericArguments().First();
var x = typeof(List<>).MakeGenericType(new[] { enumerableType });
return Activator.CreateInstance(x);
}
if (T == typeof(DateTime))
{
return null;
}
return T == typeof(string) ?
string.Empty :
null;
}
private static IEnumerable<INancyCookie> GetNancyCookies(IEnumerable<string> cookies)
{
if (cookies == null)
{
return Enumerable.Empty<INancyCookie>();
}
return from cookie in cookies
let pair = cookie.Split('=')
select new NancyCookie(pair[0], pair[1]);
}
private IEnumerable<string> GetValue(string name)
{
return this.GetValue(name, x => x);
}
private T GetValue<T>(string name, Func<IEnumerable<string>, T> converter)
{
if (!this.headers.ContainsKey(name))
{
return (T)(GetDefaultValue(typeof(T)) ?? default(T));
}
return converter.Invoke(this.headers[name]);
}
private static IEnumerable<string> GetWeightedValuesAsStrings(IEnumerable<Tuple<string, decimal>> values)
{
return values.Select(x => string.Concat(x.Item1, ";q=", x.Item2.ToString(CultureInfo.InvariantCulture)));
}
private static bool IsGenericEnumerable(Type T)
{
return !(T == typeof(string)) && T.IsGenericType && T.GetGenericTypeDefinition() == typeof(IEnumerable<>);
}
private static DateTime? ParseDateTime(string value)
{
DateTime result;
// note CultureInfo.InvariantCulture is ignored
if (DateTime.TryParseExact(value, "R", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
return result;
}
return null;
}
private void SetHeaderValues<T>(string header, T value, Func<T, IEnumerable<string>> valueTransformer)
{
if (EqualityComparer<T>.Default.Equals(value, default(T)))
{
if (this.headers.ContainsKey(header))
{
this.headers.Remove(header);
}
}
else
{
this.headers[header] = valueTransformer.Invoke(value);
}
}
}
}
| |
using System;
using EncompassRest.Loans.Enums;
using EncompassRest.Schema;
namespace EncompassRest.Loans
{
/// <summary>
/// Contact
/// </summary>
[Entity(PropertiesToAlwaysSerialize = nameof(ContactType), SerializeWholeListWhenDirty = true)]
public sealed partial class Contact : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<string?>? _aBA;
private DirtyValue<string?>? _accountName;
private DirtyValue<string?>? _address;
private DirtyValue<string?>? _address2;
private DirtyValue<bool?>? _addToCdContactInfo;
private DirtyValue<StringEnumValue<AppraisalMade>>? _appraisalMade;
private DirtyValue<DateTime?>? _bizLicenseAuthDate;
private DirtyValue<string?>? _bizLicenseAuthName;
private DirtyValue<StringEnumValue<State>>? _bizLicenseAuthStateCode;
private DirtyValue<StringEnumValue<LicenseAuthType>>? _bizLicenseAuthType;
private DirtyValue<string?>? _bizLicenseNumber;
private DirtyValue<bool?>? _borrowerActingAsContractorIndicator;
private DirtyValue<string?>? _brokerLenderType;
private DirtyValue<bool?>? _brokerLicenseExempt;
private DirtyValue<string?>? _brokerLicenseType;
private DirtyValue<string?>? _businessPhone;
private DirtyValue<string?>? _categoryName;
private DirtyValue<string?>? _cell;
private DirtyValue<DateTime?>? _checkConfirmedDate;
private DirtyValue<string?>? _city;
private DirtyValue<string?>? _clause;
private DirtyValue<string?>? _closingAgentWebURL;
private DirtyValue<string?>? _closingCompanyWebURL;
private DirtyValue<string?>? _comments;
private DirtyValue<string?>? _companyId;
private DirtyValue<decimal?>? _completionAffidavitPunchListTotal;
private DirtyValue<int?>? _contactIndex;
private DirtyValue<string?>? _contactName;
private DirtyValue<string?>? _contactNMLSNo;
private DirtyValue<string?>? _contactTitle;
private DirtyValue<StringEnumValue<ContactType>>? _contactType;
private DirtyValue<string?>? _country;
private DirtyValue<DateTime?>? _designeeAcceptedDate;
private DirtyValue<string?>? _email;
private DirtyValue<decimal?>? _employerLiabilityInsuranceMin;
private DirtyValue<string?>? _fax;
private DirtyValue<string?>? _fax2;
private DirtyValue<string?>? _fedReferenceNumber;
private DirtyValue<string?>? _fhaLenderId;
private DirtyValue<bool?>? _foreignAddressIndicator;
private DirtyValue<DateTime?>? _fundsToTitleDate;
private DirtyValue<decimal?>? _generalLiabilityInsuranceMin;
private DirtyValue<string?>? _id;
private DirtyValue<string?>? _insuranceCertNumber;
private DirtyValue<decimal?>? _insuranceCoverageAmount;
private DirtyValue<DateTime?>? _insuranceDeterminationDate;
private DirtyValue<string?>? _insuranceDeterminationNumber;
private DirtyValue<bool?>? _insuranceFloodZone;
private DirtyValue<string?>? _insuranceMap;
private DirtyValue<int?>? _insuranceNoOfBedrooms;
private DirtyValue<decimal?>? _insurancePremium;
private DirtyValue<StringEnumValue<ProjectType>>? _insuranceProjectType;
private DirtyValue<DateTime?>? _insuranceRenewalDate;
private DirtyValue<string?>? _investorGrade1;
private DirtyValue<string?>? _investorGrade2;
private DirtyValue<string?>? _investorGrade3;
private DirtyValue<string?>? _investorLicense;
private DirtyValue<string?>? _investorLicenseType;
private DirtyValue<string?>? _investorName1;
private DirtyValue<string?>? _investorName2;
private DirtyValue<string?>? _investorName3;
private DirtyValue<string?>? _investorScore1;
private DirtyValue<string?>? _investorScore2;
private DirtyValue<string?>? _investorScore3;
private DirtyValue<string?>? _jobTitle;
private DirtyValue<string?>? _lenderType;
private DirtyValue<string?>? _license;
private DirtyValue<bool?>? _licenseExempt;
private DirtyValue<StringEnumValue<State>>? _licenseHomeState;
private DirtyValue<string?>? _licenseType;
private DirtyValue<string?>? _lineItemNumber;
private DirtyValue<string?>? _loginId;
private DirtyValue<string?>? _mortgageBrokerCompanyWebURL;
private DirtyValue<string?>? _mortgageBrokerLoanOfficerWebURL;
private DirtyValue<string?>? _mortgageLenderCompanyWebURL;
private DirtyValue<string?>? _mortgageLenderLoanOfficerWebURL;
private DirtyValue<string?>? _name;
private DirtyValue<string?>? _nmlsLicense;
private DirtyValue<bool?>? _notNaturalPersonFlag;
private DirtyValue<string?>? _organizationState;
private DirtyValue<string?>? _organizationType;
private DirtyValue<DateTime?>? _personalLicenseAuthDate;
private DirtyValue<string?>? _personalLicenseAuthName;
private DirtyValue<StringEnumValue<State>>? _personalLicenseAuthStateCode;
private DirtyValue<StringEnumValue<LicenseAuthType>>? _personalLicenseAuthType;
private DirtyValue<string?>? _personalLicenseNumber;
private DirtyValue<string?>? _phone;
private DirtyValue<string?>? _phone2;
private DirtyValue<string?>? _postalCode;
private DirtyValue<string?>? _realEstateAgencyWebURL;
private DirtyValue<string?>? _realEstateAgentWebURL;
private DirtyValue<string?>? _recCity;
private DirtyValue<string?>? _referenceNumber;
private DirtyValue<string?>? _relationship;
private DirtyValue<bool?>? _settlementAgent;
private DirtyValue<StringEnumValue<State>>? _state;
private DirtyValue<string?>? _taxID;
private DirtyValue<string?>? _tqlCommentHistory;
private DirtyValue<string?>? _tQLConsentSelection;
private DirtyValue<int?>? _tqlId;
private DirtyValue<bool?>? _tqlIsPublishingIndicator;
private DirtyValue<string?>? _tqlName;
private DirtyValue<string?>? _warehouseId;
private DirtyValue<string?>? _warehouseLender;
private DirtyValue<string?>? _warehouseUrl;
/// <summary>
/// Contact ABA
/// </summary>
public string? ABA { get => _aBA; set => SetField(ref _aBA, value); }
/// <summary>
/// Contact AccountName
/// </summary>
public string? AccountName { get => _accountName; set => SetField(ref _accountName, value); }
/// <summary>
/// Contact Address
/// </summary>
public string? Address { get => _address; set => SetField(ref _address, value); }
/// <summary>
/// File Contacts Broker Lender Address 2 [1954]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? Address2 { get => _address2; set => SetField(ref _address2, value); }
/// <summary>
/// Contact AddToCdContactInfo
/// </summary>
public bool? AddToCdContactInfo { get => _addToCdContactInfo; set => SetField(ref _addToCdContactInfo, value); }
/// <summary>
/// File Contacts Appraisal Co Appraisal Made (As Is or As Improved) [4091]
/// </summary>
public StringEnumValue<AppraisalMade> AppraisalMade { get => _appraisalMade; set => SetField(ref _appraisalMade, value); }
/// <summary>
/// Contact BizLicenseAuthDate
/// </summary>
public DateTime? BizLicenseAuthDate { get => _bizLicenseAuthDate; set => SetField(ref _bizLicenseAuthDate, value); }
/// <summary>
/// Contact BizLicenseAuthName
/// </summary>
public string? BizLicenseAuthName { get => _bizLicenseAuthName; set => SetField(ref _bizLicenseAuthName, value); }
/// <summary>
/// Contact BizLicenseAuthStateCode
/// </summary>
public StringEnumValue<State> BizLicenseAuthStateCode { get => _bizLicenseAuthStateCode; set => SetField(ref _bizLicenseAuthStateCode, value); }
/// <summary>
/// Contact BizLicenseAuthType
/// </summary>
public StringEnumValue<LicenseAuthType> BizLicenseAuthType { get => _bizLicenseAuthType; set => SetField(ref _bizLicenseAuthType, value); }
/// <summary>
/// Contact BizLicenseNumber
/// </summary>
public string? BizLicenseNumber { get => _bizLicenseNumber; set => SetField(ref _bizLicenseNumber, value); }
/// <summary>
/// File Contacts General Contractor BorrowerActingAsContractorIndicator [VEND.X1009]
/// </summary>
public bool? BorrowerActingAsContractorIndicator { get => _borrowerActingAsContractorIndicator; set => SetField(ref _borrowerActingAsContractorIndicator, value); }
/// <summary>
/// Contact BrokerLenderType
/// </summary>
public string? BrokerLenderType { get => _brokerLenderType; set => SetField(ref _brokerLenderType, value); }
/// <summary>
/// Contact BrokerLicenseExempt
/// </summary>
public bool? BrokerLicenseExempt { get => _brokerLicenseExempt; set => SetField(ref _brokerLicenseExempt, value); }
/// <summary>
/// Contact BrokerLicenseType
/// </summary>
public string? BrokerLicenseType { get => _brokerLicenseType; set => SetField(ref _brokerLicenseType, value); }
/// <summary>
/// Contact BusinessPhone
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? BusinessPhone { get => _businessPhone; set => SetField(ref _businessPhone, value); }
/// <summary>
/// Contact CategoryName
/// </summary>
public string? CategoryName { get => _categoryName; set => SetField(ref _categoryName, value); }
/// <summary>
/// Contact Cell
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? Cell { get => _cell; set => SetField(ref _cell, value); }
/// <summary>
/// File Contacts Broker Check Confirmed Date [VEND.X368]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public DateTime? CheckConfirmedDate { get => _checkConfirmedDate; set => SetField(ref _checkConfirmedDate, value); }
/// <summary>
/// Contact City
/// </summary>
public string? City { get => _city; set => SetField(ref _city, value); }
/// <summary>
/// File Contacts Mortgagee Clause [VEND.X496]
/// </summary>
public string? Clause { get => _clause; set => SetField(ref _clause, value); }
/// <summary>
/// File Contacts Settlement Agent - Closing Agent Web URL [VEND.X1041]
/// </summary>
public string? ClosingAgentWebURL { get => _closingAgentWebURL; set => SetField(ref _closingAgentWebURL, value); }
/// <summary>
/// File Contacts Settlement Agent - Closing Company Web URL [VEND.X1040]
/// </summary>
public string? ClosingCompanyWebURL { get => _closingCompanyWebURL; set => SetField(ref _closingCompanyWebURL, value); }
/// <summary>
/// Contact Comments
/// </summary>
public string? Comments { get => _comments; set => SetField(ref _comments, value); }
/// <summary>
/// File Contacts Broker Lender Company ID [3237]
/// </summary>
public string? CompanyId { get => _companyId; set => SetField(ref _companyId, value); }
/// <summary>
/// File Contacts General Contractor Completion Affidavit Punch List Total [VEND.X1024]
/// </summary>
public decimal? CompletionAffidavitPunchListTotal { get => _completionAffidavitPunchListTotal; set => SetField(ref _completionAffidavitPunchListTotal, value); }
/// <summary>
/// Contact ContactIndex
/// </summary>
public int? ContactIndex { get => _contactIndex; set => SetField(ref _contactIndex, value); }
/// <summary>
/// Contact ContactName
/// </summary>
public string? ContactName { get => _contactName; set => SetField(ref _contactName, value); }
/// <summary>
/// File Contacts Settlement Agent Contact NMLS Number [VEND.X675]
/// </summary>
public string? ContactNMLSNo { get => _contactNMLSNo; set => SetField(ref _contactNMLSNo, value); }
/// <summary>
/// Contact ContactTitle
/// </summary>
public string? ContactTitle { get => _contactTitle; set => SetField(ref _contactTitle, value); }
/// <summary>
/// Contact ContactType
/// </summary>
public StringEnumValue<ContactType> ContactType { get => _contactType; set => SetField(ref _contactType, value); }
/// <summary>
/// Contact Country
/// </summary>
public string? Country { get => _country; set => SetField(ref _country, value); }
/// <summary>
/// Appointment Of Designee DesigneeAcceptedDate [VEND.X1026]
/// </summary>
public DateTime? DesigneeAcceptedDate { get => _designeeAcceptedDate; set => SetField(ref _designeeAcceptedDate, value); }
/// <summary>
/// Contact Email
/// </summary>
public string? Email { get => _email; set => SetField(ref _email, value); }
/// <summary>
/// File Contacts General Contractor Employer Liability Insurance Min [VEND.X1018]
/// </summary>
public decimal? EmployerLiabilityInsuranceMin { get => _employerLiabilityInsuranceMin; set => SetField(ref _employerLiabilityInsuranceMin, value); }
/// <summary>
/// Contact Fax
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? Fax { get => _fax; set => SetField(ref _fax, value); }
/// <summary>
/// File Contacts Submitting Broker - Lender Fax [2844]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? Fax2 { get => _fax2; set => SetField(ref _fax2, value); }
/// <summary>
/// File Contacts Warehouse Fed Reference # [VEND.X1046]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? FedReferenceNumber { get => _fedReferenceNumber; set => SetField(ref _fedReferenceNumber, value); }
/// <summary>
/// FHA Lender ID [1059]
/// </summary>
public string? FhaLenderId { get => _fhaLenderId; set => SetField(ref _fhaLenderId, value); }
/// <summary>
/// Contact ForeignAddressIndicator
/// </summary>
public bool? ForeignAddressIndicator { get => _foreignAddressIndicator; set => SetField(ref _foreignAddressIndicator, value); }
/// <summary>
/// File Contacts Warehouse Funds to Title Date [VEND.X1045]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public DateTime? FundsToTitleDate { get => _fundsToTitleDate; set => SetField(ref _fundsToTitleDate, value); }
/// <summary>
/// File Contacts General Contractor General Liability Insurance Min [VEND.X1017]
/// </summary>
public decimal? GeneralLiabilityInsuranceMin { get => _generalLiabilityInsuranceMin; set => SetField(ref _generalLiabilityInsuranceMin, value); }
/// <summary>
/// Contact Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// Underwriting Flood Info Cert Number [2363]
/// </summary>
public string? InsuranceCertNumber { get => _insuranceCertNumber; set => SetField(ref _insuranceCertNumber, value); }
/// <summary>
/// Contact InsuranceCoverageAmount [VEND.X445], [VEND.X446]
/// </summary>
public decimal? InsuranceCoverageAmount { get => _insuranceCoverageAmount; set => SetField(ref _insuranceCoverageAmount, value); }
/// <summary>
/// Underwriting Flood Info Determination Date [2365]
/// </summary>
public DateTime? InsuranceDeterminationDate { get => _insuranceDeterminationDate; set => SetField(ref _insuranceDeterminationDate, value); }
/// <summary>
/// Underwriting Flood Info Determination Number [2364]
/// </summary>
public string? InsuranceDeterminationNumber { get => _insuranceDeterminationNumber; set => SetField(ref _insuranceDeterminationNumber, value); }
/// <summary>
/// Underwriting Flood Info Flood Zone [2366]
/// </summary>
public bool? InsuranceFloodZone { get => _insuranceFloodZone; set => SetField(ref _insuranceFloodZone, value); }
/// <summary>
/// Underwriting Property Info Map ID [2368]
/// </summary>
public string? InsuranceMap { get => _insuranceMap; set => SetField(ref _insuranceMap, value); }
/// <summary>
/// Underwriting Property Info Number of Bedrooms [2369]
/// </summary>
public int? InsuranceNoOfBedrooms { get => _insuranceNoOfBedrooms; set => SetField(ref _insuranceNoOfBedrooms, value); }
/// <summary>
/// Contact InsurancePremium [VEND.X443], [VEND.X447]
/// </summary>
public decimal? InsurancePremium { get => _insurancePremium; set => SetField(ref _insurancePremium, value); }
/// <summary>
/// Underwriting Property Info Project Type [2367]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"V_NoReviewSiteCondo\",\"ExemptFromReview\",\"FullReviewCoopProject\",\"FannieMaeReviewPERSCoopProject\"]")]
public StringEnumValue<ProjectType> InsuranceProjectType { get => _insuranceProjectType; set => SetField(ref _insuranceProjectType, value); }
/// <summary>
/// Contact InsuranceRenewalDate [VEND.X444], [VEND.X448]
/// </summary>
public DateTime? InsuranceRenewalDate { get => _insuranceRenewalDate; set => SetField(ref _insuranceRenewalDate, value); }
/// <summary>
/// Underwriting Investor Info Grade 1 [2343]
/// </summary>
public string? InvestorGrade1 { get => _investorGrade1; set => SetField(ref _investorGrade1, value); }
/// <summary>
/// Underwriting Investor Info Grade 2 [2346]
/// </summary>
public string? InvestorGrade2 { get => _investorGrade2; set => SetField(ref _investorGrade2, value); }
/// <summary>
/// Underwriting Investor Info Grade 3 [2349]
/// </summary>
public string? InvestorGrade3 { get => _investorGrade3; set => SetField(ref _investorGrade3, value); }
/// <summary>
/// File Contacts Investor License # [VEND.X650]
/// </summary>
public string? InvestorLicense { get => _investorLicense; set => SetField(ref _investorLicense, value); }
/// <summary>
/// Contact InvestorLicenseType
/// </summary>
public string? InvestorLicenseType { get => _investorLicenseType; set => SetField(ref _investorLicenseType, value); }
/// <summary>
/// Underwriting Investor Info Name 1 [2342]
/// </summary>
public string? InvestorName1 { get => _investorName1; set => SetField(ref _investorName1, value); }
/// <summary>
/// Underwriting Investor Info Name 2 [2345]
/// </summary>
public string? InvestorName2 { get => _investorName2; set => SetField(ref _investorName2, value); }
/// <summary>
/// Underwriting Investor Info Name 3 [2348]
/// </summary>
public string? InvestorName3 { get => _investorName3; set => SetField(ref _investorName3, value); }
/// <summary>
/// Underwriting Investor Info Score 1 [2344]
/// </summary>
public string? InvestorScore1 { get => _investorScore1; set => SetField(ref _investorScore1, value); }
/// <summary>
/// Underwriting Investor Info Score 2 [2347]
/// </summary>
public string? InvestorScore2 { get => _investorScore2; set => SetField(ref _investorScore2, value); }
/// <summary>
/// Underwriting Investor Info Score 3 [2350]
/// </summary>
public string? InvestorScore3 { get => _investorScore3; set => SetField(ref _investorScore3, value); }
/// <summary>
/// Contact JobTitle
/// </summary>
public string? JobTitle { get => _jobTitle; set => SetField(ref _jobTitle, value); }
/// <summary>
/// Contact LenderType [VEND.X651], [3895]
/// </summary>
public string? LenderType { get => _lenderType; set => SetField(ref _lenderType, value); }
/// <summary>
/// Contact License
/// </summary>
public string? License { get => _license; set => SetField(ref _license, value); }
/// <summary>
/// Contact LicenseExempt [VEND.X653], [3898]
/// </summary>
public bool? LicenseExempt { get => _licenseExempt; set => SetField(ref _licenseExempt, value); }
/// <summary>
/// File Contacts-Lender License Home State [3896]
/// </summary>
public StringEnumValue<State> LicenseHomeState { get => _licenseHomeState; set => SetField(ref _licenseHomeState, value); }
/// <summary>
/// Contact LicenseType
/// </summary>
public string? LicenseType { get => _licenseType; set => SetField(ref _licenseType, value); }
/// <summary>
/// Contact LineItemNumber
/// </summary>
public string? LineItemNumber { get => _lineItemNumber; set => SetField(ref _lineItemNumber, value); }
/// <summary>
/// Contact LoginId
/// </summary>
public string? LoginId { get => _loginId; set => SetField(ref _loginId, value); }
/// <summary>
/// File Contacts Broker - Mortgage Broker Company Web URL [VEND.X1036]
/// </summary>
public string? MortgageBrokerCompanyWebURL { get => _mortgageBrokerCompanyWebURL; set => SetField(ref _mortgageBrokerCompanyWebURL, value); }
/// <summary>
/// File Contacts Broker - Mortgage Broker Loan Officer Web URL [VEND.X1037]
/// </summary>
public string? MortgageBrokerLoanOfficerWebURL { get => _mortgageBrokerLoanOfficerWebURL; set => SetField(ref _mortgageBrokerLoanOfficerWebURL, value); }
/// <summary>
/// File Contacts Lender - Mortgage Lender Company Web URL [VEND.X1034]
/// </summary>
public string? MortgageLenderCompanyWebURL { get => _mortgageLenderCompanyWebURL; set => SetField(ref _mortgageLenderCompanyWebURL, value); }
/// <summary>
/// File Contacts Lender - Mortgage Lender Loan Officer Web URL [VEND.X1035]
/// </summary>
public string? MortgageLenderLoanOfficerWebURL { get => _mortgageLenderLoanOfficerWebURL; set => SetField(ref _mortgageLenderLoanOfficerWebURL, value); }
/// <summary>
/// Contact Name
/// </summary>
public string? Name { get => _name; set => SetField(ref _name, value); }
/// <summary>
/// Contact NmlsLicense
/// </summary>
public string? NmlsLicense { get => _nmlsLicense; set => SetField(ref _nmlsLicense, value); }
/// <summary>
/// Contact NotNaturalPersonFlag
/// </summary>
public bool? NotNaturalPersonFlag { get => _notNaturalPersonFlag; set => SetField(ref _notNaturalPersonFlag, value); }
/// <summary>
/// Contact OrganizationState
/// </summary>
public string? OrganizationState { get => _organizationState; set => SetField(ref _organizationState, value); }
/// <summary>
/// Contact OrganizationType
/// </summary>
public string? OrganizationType { get => _organizationType; set => SetField(ref _organizationType, value); }
/// <summary>
/// Contact PersonalLicenseAuthDate
/// </summary>
public DateTime? PersonalLicenseAuthDate { get => _personalLicenseAuthDate; set => SetField(ref _personalLicenseAuthDate, value); }
/// <summary>
/// Contact PersonalLicenseAuthName
/// </summary>
public string? PersonalLicenseAuthName { get => _personalLicenseAuthName; set => SetField(ref _personalLicenseAuthName, value); }
/// <summary>
/// Contact PersonalLicenseAuthStateCode
/// </summary>
public StringEnumValue<State> PersonalLicenseAuthStateCode { get => _personalLicenseAuthStateCode; set => SetField(ref _personalLicenseAuthStateCode, value); }
/// <summary>
/// Contact PersonalLicenseAuthType
/// </summary>
public StringEnumValue<LicenseAuthType> PersonalLicenseAuthType { get => _personalLicenseAuthType; set => SetField(ref _personalLicenseAuthType, value); }
/// <summary>
/// Contact PersonalLicenseNumber
/// </summary>
public string? PersonalLicenseNumber { get => _personalLicenseNumber; set => SetField(ref _personalLicenseNumber, value); }
/// <summary>
/// Contact Phone
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? Phone { get => _phone; set => SetField(ref _phone, value); }
/// <summary>
/// Contact Phone2 [2843], [VEND.X304]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? Phone2 { get => _phone2; set => SetField(ref _phone2, value); }
/// <summary>
/// Contact PostalCode
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)]
public string? PostalCode { get => _postalCode; set => SetField(ref _postalCode, value); }
/// <summary>
/// File Contacts Broker - Real Estate Agency Web URL [VEND.X1038]
/// </summary>
public string? RealEstateAgencyWebURL { get => _realEstateAgencyWebURL; set => SetField(ref _realEstateAgencyWebURL, value); }
/// <summary>
/// File Contacts Broker - Real Estate Agent Web URL [VEND.X1039]
/// </summary>
public string? RealEstateAgentWebURL { get => _realEstateAgentWebURL; set => SetField(ref _realEstateAgentWebURL, value); }
/// <summary>
/// File Contacts Broker Rec City [VEND.X308]
/// </summary>
public string? RecCity { get => _recCity; set => SetField(ref _recCity, value); }
/// <summary>
/// Contact ReferenceNumber
/// </summary>
public string? ReferenceNumber { get => _referenceNumber; set => SetField(ref _referenceNumber, value); }
/// <summary>
/// Contact Relationship
/// </summary>
public string? Relationship { get => _relationship; set => SetField(ref _relationship, value); }
/// <summary>
/// Contact SettlementAgent
/// </summary>
public bool? SettlementAgent { get => _settlementAgent; set => SetField(ref _settlementAgent, value); }
/// <summary>
/// Contact State
/// </summary>
public StringEnumValue<State> State { get => _state; set => SetField(ref _state, value); }
/// <summary>
/// Contact TaxID
/// </summary>
public string? TaxID { get => _taxID; set => SetField(ref _taxID, value); }
/// <summary>
/// TQL Comment History [3355]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? TqlCommentHistory { get => _tqlCommentHistory; set => SetField(ref _tqlCommentHistory, value); }
/// <summary>
/// Consent Selection in TQL Portal [CCVP.X1]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? TQLConsentSelection { get => _tQLConsentSelection; set => SetField(ref _tQLConsentSelection, value); }
/// <summary>
/// TQL InvestorID [3318]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? TqlId { get => _tqlId; set => SetField(ref _tqlId, value); }
/// <summary>
/// Is Published to Investor [3333]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public bool? TqlIsPublishingIndicator { get => _tqlIsPublishingIndicator; set => SetField(ref _tqlIsPublishingIndicator, value); }
/// <summary>
/// TQL Investor Name [3317]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? TqlName { get => _tqlName; set => SetField(ref _tqlName, value); }
/// <summary>
/// File Contacts Warehouse ID [VEND.X1043]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? WarehouseId { get => _warehouseId; set => SetField(ref _warehouseId, value); }
/// <summary>
/// File Contacts Warehouse Lender [VEND.X1042]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? WarehouseLender { get => _warehouseLender; set => SetField(ref _warehouseLender, value); }
/// <summary>
/// File Contacts Warehouse URL [VEND.X1044]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? WarehouseUrl { get => _warehouseUrl; set => SetField(ref _warehouseUrl, value); }
}
}
| |
using Esprima.Ast;
using Jint.Native;
using Jint.Native.Function;
using Jint.Native.Object;
using Jint.Runtime.Environments;
using Jint.Runtime.References;
namespace Jint.Runtime.Interpreter.Expressions
{
internal sealed class JintCallExpression : JintExpression
{
private CachedArgumentsHolder _cachedArguments;
private bool _cached;
private JintExpression _calleeExpression;
private bool _hasSpreads;
public JintCallExpression(CallExpression expression) : base(expression)
{
_initialized = false;
}
protected override void Initialize(EvaluationContext context)
{
var engine = context.Engine;
var expression = (CallExpression) _expression;
_calleeExpression = Build(engine, expression.Callee);
var cachedArgumentsHolder = new CachedArgumentsHolder
{
JintArguments = new JintExpression[expression.Arguments.Count]
};
static bool CanSpread(Node e)
{
return e?.Type == Nodes.SpreadElement
|| e is AssignmentExpression ae && ae.Right?.Type == Nodes.SpreadElement;
}
bool cacheable = true;
for (var i = 0; i < expression.Arguments.Count; i++)
{
var expressionArgument = expression.Arguments[i];
cachedArgumentsHolder.JintArguments[i] = Build(engine, expressionArgument);
cacheable &= expressionArgument.Type == Nodes.Literal;
_hasSpreads |= CanSpread(expressionArgument);
if (expressionArgument is ArrayExpression ae)
{
for (var elementIndex = 0; elementIndex < ae.Elements.Count; elementIndex++)
{
_hasSpreads |= CanSpread(ae.Elements[elementIndex]);
}
}
}
if (cacheable)
{
_cached = true;
var arguments = System.Array.Empty<JsValue>();
if (cachedArgumentsHolder.JintArguments.Length > 0)
{
arguments = new JsValue[cachedArgumentsHolder.JintArguments.Length];
BuildArguments(context, cachedArgumentsHolder.JintArguments, arguments);
}
cachedArgumentsHolder.CachedArguments = arguments;
}
_cachedArguments = cachedArgumentsHolder;
}
protected override ExpressionResult EvaluateInternal(EvaluationContext context)
{
return NormalCompletion(_calleeExpression is JintSuperExpression
? SuperCall(context)
: Call(context)
);
}
private JsValue SuperCall(EvaluationContext context)
{
var engine = context.Engine;
var thisEnvironment = (FunctionEnvironmentRecord) engine.ExecutionContext.GetThisEnvironment();
var newTarget = engine.GetNewTarget(thisEnvironment);
var func = GetSuperConstructor(thisEnvironment);
if (!func.IsConstructor)
{
ExceptionHelper.ThrowTypeError(engine.Realm, "Not a constructor");
}
var argList = ArgumentListEvaluation(context);
var result = ((IConstructor) func).Construct(argList, newTarget);
var thisER = (FunctionEnvironmentRecord) engine.ExecutionContext.GetThisEnvironment();
return thisER.BindThisValue(result);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-getsuperconstructor
/// </summary>
private static ObjectInstance GetSuperConstructor(FunctionEnvironmentRecord thisEnvironment)
{
var envRec = thisEnvironment;
var activeFunction = envRec._functionObject;
var superConstructor = activeFunction.GetPrototypeOf();
return superConstructor;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-function-calls
/// </summary>
private JsValue Call(EvaluationContext context)
{
var reference = _calleeExpression.Evaluate(context).Value;
if (ReferenceEquals(reference, Undefined.Instance))
{
return Undefined.Instance;
}
var engine = context.Engine;
var func = engine.GetValue(reference, false);
if (reference is Reference referenceRecord
&& !referenceRecord.IsPropertyReference()
&& referenceRecord.GetReferencedName() == CommonProperties.Eval
&& ReferenceEquals(func, engine.Realm.Intrinsics.Eval))
{
var argList = ArgumentListEvaluation(context);
if (argList.Length == 0)
{
return Undefined.Instance;
}
var evalFunctionInstance = (EvalFunctionInstance) func;
var evalArg = argList[0];
var strictCaller = StrictModeScope.IsStrictModeCode;
var evalRealm = evalFunctionInstance._realm;
var direct = !((CallExpression) _expression).Optional;
var value = evalFunctionInstance.PerformEval(evalArg, evalRealm, strictCaller, direct);
engine._referencePool.Return(referenceRecord);
return value;
}
var thisCall = (CallExpression) _expression;
var tailCall = IsInTailPosition(thisCall);
return EvaluateCall(context, func, reference, thisCall.Arguments, tailCall);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-evaluatecall
/// </summary>
private JsValue EvaluateCall(EvaluationContext context, JsValue func, object reference, in NodeList<Expression> arguments, bool tailPosition)
{
JsValue thisValue;
var referenceRecord = reference as Reference;
var engine = context.Engine;
if (referenceRecord is not null)
{
if (referenceRecord.IsPropertyReference())
{
thisValue = referenceRecord.GetThisValue();
}
else
{
var baseValue = referenceRecord.GetBase();
// deviation from the spec to support null-propagation helper
if (baseValue.IsNullOrUndefined()
&& engine._referenceResolver.TryUnresolvableReference(engine, referenceRecord, out var value))
{
thisValue = value;
}
else
{
var refEnv = (EnvironmentRecord) baseValue;
thisValue = refEnv.WithBaseObject();
}
}
}
else
{
thisValue = Undefined.Instance;
}
var argList = ArgumentListEvaluation(context);
if (!func.IsObject() && !engine._referenceResolver.TryGetCallable(engine, reference, out func))
{
var message = referenceRecord == null
? reference + " is not a function"
: $"Property '{referenceRecord.GetReferencedName()}' of object is not a function";
ExceptionHelper.ThrowTypeError(engine.Realm, message);
}
var callable = func as ICallable;
if (callable is null)
{
var message = $"{referenceRecord?.GetReferencedName() ?? reference} is not a function";
ExceptionHelper.ThrowTypeError(engine.Realm, message);
}
if (tailPosition)
{
// TODO tail call
// PrepareForTailCall();
}
var result = engine.Call(callable, thisValue, argList, _calleeExpression);
if (!_cached && argList.Length > 0)
{
engine._jsValueArrayPool.ReturnArray(argList);
}
engine._referencePool.Return(referenceRecord);
return result;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-isintailposition
/// </summary>
private static bool IsInTailPosition(CallExpression call)
{
// TODO tail calls
return false;
}
private JsValue[] ArgumentListEvaluation(EvaluationContext context)
{
var cachedArguments = _cachedArguments;
var arguments = System.Array.Empty<JsValue>();
if (_cached)
{
arguments = cachedArguments.CachedArguments;
}
else
{
if (cachedArguments.JintArguments.Length > 0)
{
if (_hasSpreads)
{
arguments = BuildArgumentsWithSpreads(context, cachedArguments.JintArguments);
}
else
{
arguments = context.Engine._jsValueArrayPool.RentArray(cachedArguments.JintArguments.Length);
BuildArguments(context, cachedArguments.JintArguments, arguments);
}
}
}
return arguments;
}
private class CachedArgumentsHolder
{
internal JintExpression[] JintArguments;
internal JsValue[] CachedArguments;
}
}
}
| |
namespace BizUnit.Tests.ObjectModelTests
{
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BizUnitOM;
/// <summary>
/// Summary description for TestStepBuilderTests
/// </summary>
[TestClass]
public class TestStepBuilderTests
{
[TestMethod]
public void Create_FileCreateStep_AndSetSimpleTypes()
{
TestStepBuilder tsb = new TestStepBuilder("BizUnit.FileCreateStep", null);
object[] args = new object[1];
args[0] = @"..\..\..\Test\BizUnit.Tests\Data\LoadGenScript001.xml";
tsb.SetProperty("SourcePath", args);
args = new object[1];
args[0] = @"..\..\..\Test\BizUnit.Tests\Out\Data_%Guid%.xml";
tsb.SetProperty("CreationPath", args);
string testDirectory = @"..\..\..\Test\BizUnit.Tests\Out";
FileHelper.EmptyDirectory(testDirectory, "*.xml");
Assert.AreEqual(FileHelper.NumberOfFilesInDirectory(testDirectory, "*.xml"), 0);
BizUnitTestCase testCase = new BizUnitTestCase("Create_FileCreateStep_AndSetSimpleTypes");
// Add the test step builder to the test case...
testCase.AddTestStep(tsb, TestStage.Execution);
BizUnit bizUnit = new BizUnit(testCase);
bizUnit.RunTest();
Assert.AreEqual(FileHelper.NumberOfFilesInDirectory(testDirectory, "*.xml"), 1);
}
[TestMethod]
public void Create_FileCreateStep_TakeFromCtx()
{
Context ctx = new Context();
ctx.Add("PathToWriteFileTo", @"..\..\..\Test\BizUnit.Tests\Out\Data_%Guid%.xml");
TestStepBuilder tsb = new TestStepBuilder("BizUnit.FileCreateStep", null);
object[] args = new object[1];
args[0] = @"..\..\..\Test\BizUnit.Tests\Data\LoadGenScript001.xml";
tsb.SetProperty("SourcePath", args);
args = new object[1];
args[0] = "takeFromCtx:PathToWriteFileTo";
tsb.SetProperty("CreationPath", args);
string testDirectory = @"..\..\..\Test\BizUnit.Tests\Out";
FileHelper.EmptyDirectory(testDirectory, "*.xml");
Assert.AreEqual(FileHelper.NumberOfFilesInDirectory(testDirectory, "*.xml"), 0);
BizUnitTestCase testCase = new BizUnitTestCase("Create_FileCreateStep_TakeFromCtx");
// Add the test step builder to the test case...
testCase.AddTestStep(tsb, TestStage.Execution);
BizUnit bizUnit = new BizUnit(testCase, ctx);
bizUnit.RunTest();
Assert.AreEqual(FileHelper.NumberOfFilesInDirectory(testDirectory, "*.xml"), 1);
}
[TestMethod]
public void Create_FileDeleteStep_AndSetstringArray()
{
BizUnitTestCase testCase = new BizUnitTestCase("Create_FileDeleteStep_AndSetstringArray");
// Create a file in the output dir...
TestStepBuilder tsb1 = new TestStepBuilder("BizUnit.FileCreateStep", null);
object[] args = new object[1];
args[0] = @"..\..\..\Test\BizUnit.Tests\Data\LoadGenScript001.xml";
tsb1.SetProperty("SourcePath", args);
args = new object[1];
args[0] = @"..\..\..\Test\BizUnit.Tests\Out\Data_File1.xml";
tsb1.SetProperty("CreationPath", args);
// Add the test step builder to the test case...
testCase.AddTestStep(tsb1, TestStage.Execution);
// Create a file in the output dir...
TestStepBuilder tsb2 = new TestStepBuilder("BizUnit.FileCreateStep", null);
args = new object[1];
args[0] = @"..\..\..\Test\BizUnit.Tests\Data\LoadGenScript001.xml";
tsb2.SetProperty("SourcePath", args);
args = new object[1];
args[0] = @"..\..\..\Test\BizUnit.Tests\Out\Data_File2.xml";
tsb2.SetProperty("CreationPath", args);
// Add the test step builder to the test case...
testCase.AddTestStep(tsb2, TestStage.Execution);
TestStepBuilder tsb3 = new TestStepBuilder("BizUnit.FileDeleteStep", null);
args = new object[2];
args[0] = @"..\..\..\Test\BizUnit.Tests\Out\Data_File1.xml";
args[1] = @"..\..\..\Test\BizUnit.Tests\Out\Data_File2.xml";
tsb3.SetProperty("FilesToDeletePath", args);
string testDirectory = @"..\..\..\Test\BizUnit.Tests\Out";
// Add the test step builder to the test case...
testCase.AddTestStep(tsb3, TestStage.Execution);
FileHelper.EmptyDirectory(testDirectory, "*.xml");
Assert.AreEqual(FileHelper.NumberOfFilesInDirectory(testDirectory, "*.xml"), 0);
BizUnit bizUnit = new BizUnit(testCase);
bizUnit.RunTest();
Assert.AreEqual(FileHelper.NumberOfFilesInDirectory(testDirectory, "*.xml"), 0);
}
[TestMethod]
public void Create_FileValidateStep_SetPropsAndValidation()
{
BizUnitTestCase testCase = new BizUnitTestCase("Create_FileValidateStep_SetPropsAndValidation");
// create a file...
TestStepBuilder createFileStep = new TestStepBuilder("BizUnit.FileCreateStep", null);
object[] args = new object[1];
args[0] = @"..\..\..\Test\BizUnit.Tests\Data\PurchaseOrder001.xml";
createFileStep.SetProperty("SourcePath", args);
args = new object[1];
args[0] = @"..\..\..\Test\BizUnit.Tests\Out\Data_%Guid%.xml";
createFileStep.SetProperty("CreationPath", args);
// Read and validate file...
TestStepBuilder tsb = new TestStepBuilder("BizUnit.FileValidateStep", null);
args = new object[1];
args[0] = "1000";
tsb.SetProperty("Timeout", args);
args[0] = @"..\..\..\Test\BizUnit.Tests\Out";
tsb.SetProperty("Directory", args);
args[0] = "*.*";
tsb.SetProperty("SearchPattern", args);
args[0] = "true";
tsb.SetProperty("DeleteFile", args);
ValidationStepBuilder tssb = new ValidationStepBuilder("BizUnit.XmlValidationStepEx", null);
args = new object[1];
args[0] = @"..\..\..\Test\BizUnit.Tests\Data\PurchaseOrder.xsd";
tssb.SetProperty("XmlSchemaPath", args);
args[0] = @"http://SendMail.PurchaseOrder";
tssb.SetProperty("XmlSchemaNameSpace", args);
args = new object[2];
args[0] = "*[local-name()='PurchaseOrder' and namespace-uri()='http://SendMail.PurchaseOrder']/*[local-name()='PONumber' and namespace-uri()='']";
args[1] = "PONumber_0";
tssb.SetProperty("XPathValidations", args);
// set the validation step
tsb.ValidationStepBuilder = tssb;
// Add the steps...
testCase.AddTestStep(createFileStep, TestStage.Execution);
testCase.AddTestStep(tsb, TestStage.Execution);
string testDirectory = @"..\..\..\Test\BizUnit.Tests\Out";
FileHelper.EmptyDirectory(testDirectory, "*.xml");
Assert.AreEqual(FileHelper.NumberOfFilesInDirectory(testDirectory, "*.xml"), 0);
BizUnit bizUnit = new BizUnit(testCase);
bizUnit.RunTest();
Assert.AreEqual(FileHelper.NumberOfFilesInDirectory(testDirectory, "*.xml"), 0);
}
[TestMethod]
public void Check_PropertyInfo_String()
{
TestStepBuilder tsb1 = new TestStepBuilder("BizUnit.FileCreateStep", null);
PropertyInfo pi = tsb1.GetPropertyInfo("SourcePath");
Assert.AreEqual(pi.PropertyType, typeof(System.String));
pi = tsb1.GetPropertyInfo("CreationPath");
Assert.AreEqual(pi.PropertyType, typeof(System.String));
}
[TestMethod]
public void Check_PropertyInfo_Various()
{
TestStepBuilder tsb1 = new TestStepBuilder("BizUnit.FileValidateStep", null);
PropertyInfo pi = tsb1.GetPropertyInfo("Timeout");
Assert.AreEqual(pi.PropertyType, typeof(System.Double));
pi = tsb1.GetPropertyInfo("ValidationStep");
Assert.AreEqual(pi.PropertyType, typeof(IValidationStepOM));
pi = tsb1.GetPropertyInfo("ContextLoaderStep");
Assert.AreEqual(pi.PropertyType, typeof(IContextLoaderStepOM));
pi = tsb1.GetPropertyInfo("DeleteFile");
Assert.AreEqual(pi.PropertyType, typeof(System.Boolean));
pi = tsb1.GetPropertyInfo("SearchPattern");
Assert.AreEqual(pi.PropertyType, typeof(System.String));
}
}
}
| |
using System;
using Quartz.Impl.Triggers;
using Quartz.Spi;
namespace Quartz
{
/// <summary>
/// CalendarIntervalScheduleBuilder is a <see cref="IScheduleBuilder" />
/// that defines calendar time (day, week, month, year) interval-based
/// schedules for Triggers.
/// </summary>
/// <remarks>
/// <para>
/// Quartz provides a builder-style API for constructing scheduling-related
/// entities via a Domain-Specific Language (DSL). The DSL can best be
/// utilized through the usage of static imports of the methods on the classes
/// <see cref="TriggerBuilder" />, <see cref="JobBuilder" />,
/// <see cref="DateBuilder" />, <see cref="JobKey" />, <see cref="TriggerKey" />
/// and the various <see cref="IScheduleBuilder" /> implementations.
/// </para>
/// <para>Client code can then use the DSL to write code such as this:</para>
/// <code>
/// JobDetail job = JobBuilder.Create<MyJob>()
/// .WithIdentity("myJob")
/// .Build();
/// Trigger trigger = TriggerBuilder.Create()
/// .WithIdentity("myTrigger", "myTriggerGroup")
/// .WithSimpleSchedule(x => x
/// .WithIntervalInHours(1)
/// .RepeatForever())
/// .StartAt(DateBuilder.FutureDate(10, IntervalUnit.Minute))
/// .Build();
/// scheduler.scheduleJob(job, trigger);
/// </code>
/// </remarks>
/// <seealso cref="ICalendarIntervalTrigger" />
/// <seealso cref="CronScheduleBuilder" />
/// <seealso cref="IScheduleBuilder" />
/// <seealso cref="SimpleScheduleBuilder" />
/// <seealso cref="TriggerBuilder" />
public class CalendarIntervalScheduleBuilder : ScheduleBuilder<ICalendarIntervalTrigger>
{
private int interval = 1;
private IntervalUnit intervalUnit = IntervalUnit.Day;
private int misfireInstruction = MisfireInstruction.SmartPolicy;
private TimeZoneInfo? timeZone;
private bool preserveHourOfDayAcrossDaylightSavings;
private bool skipDayIfHourDoesNotExist;
protected CalendarIntervalScheduleBuilder()
{
}
/// <summary>
/// Create a CalendarIntervalScheduleBuilder.
/// </summary>
/// <returns></returns>
public static CalendarIntervalScheduleBuilder Create()
{
return new CalendarIntervalScheduleBuilder();
}
/// <summary>
/// Build the actual Trigger -- NOT intended to be invoked by end users,
/// but will rather be invoked by a TriggerBuilder which this
/// ScheduleBuilder is given to.
/// </summary>
/// <returns></returns>
public override IMutableTrigger Build()
{
CalendarIntervalTriggerImpl st = new CalendarIntervalTriggerImpl();
st.RepeatInterval = interval;
st.RepeatIntervalUnit = intervalUnit;
st.MisfireInstruction = misfireInstruction;
st.timeZone = timeZone;
st.PreserveHourOfDayAcrossDaylightSavings = preserveHourOfDayAcrossDaylightSavings;
st.SkipDayIfHourDoesNotExist = skipDayIfHourDoesNotExist;
return st;
}
/// <summary>
/// Specify the time unit and interval for the Trigger to be produced.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="interval">the interval at which the trigger should repeat.</param>
/// <param name="unit"> the time unit (IntervalUnit) of the interval.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithInterval(int interval, IntervalUnit unit)
{
ValidateInterval(interval);
this.interval = interval;
intervalUnit = unit;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.SECOND that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInSeconds">the number of seconds at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInSeconds(int intervalInSeconds)
{
ValidateInterval(intervalInSeconds);
interval = intervalInSeconds;
intervalUnit = IntervalUnit.Second;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.MINUTE that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInMinutes">the number of minutes at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInMinutes(int intervalInMinutes)
{
ValidateInterval(intervalInMinutes);
interval = intervalInMinutes;
intervalUnit = IntervalUnit.Minute;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.HOUR that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInHours">the number of hours at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInHours(int intervalInHours)
{
ValidateInterval(intervalInHours);
interval = intervalInHours;
intervalUnit = IntervalUnit.Hour;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.DAY that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInDays">the number of days at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInDays(int intervalInDays)
{
ValidateInterval(intervalInDays);
interval = intervalInDays;
intervalUnit = IntervalUnit.Day;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.WEEK that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInWeeks">the number of weeks at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInWeeks(int intervalInWeeks)
{
ValidateInterval(intervalInWeeks);
interval = intervalInWeeks;
intervalUnit = IntervalUnit.Week;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.MONTH that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInMonths">the number of months at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInMonths(int intervalInMonths)
{
ValidateInterval(intervalInMonths);
interval = intervalInMonths;
intervalUnit = IntervalUnit.Month;
return this;
}
/// <summary>
/// Specify an interval in the IntervalUnit.YEAR that the produced
/// Trigger will repeat at.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="intervalInYears">the number of years at which the trigger should repeat.</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.RepeatInterval" />
/// <seealso cref="ICalendarIntervalTrigger.RepeatIntervalUnit" />
public CalendarIntervalScheduleBuilder WithIntervalInYears(int intervalInYears)
{
ValidateInterval(intervalInYears);
interval = intervalInYears;
intervalUnit = IntervalUnit.Year;
return this;
}
/// <summary>
/// If the Trigger misfires, use the
/// <see cref="MisfireInstruction.IgnoreMisfirePolicy" /> instruction.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated CronScheduleBuilder</returns>
/// <seealso cref="MisfireInstruction.IgnoreMisfirePolicy" />
public CalendarIntervalScheduleBuilder WithMisfireHandlingInstructionIgnoreMisfires()
{
misfireInstruction = MisfireInstruction.IgnoreMisfirePolicy;
return this;
}
/// <summary>
/// If the Trigger misfires, use the
/// <see cref="MisfireInstruction.CalendarIntervalTrigger.DoNothing" /> instruction.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="MisfireInstruction.CalendarIntervalTrigger.DoNothing" />
public CalendarIntervalScheduleBuilder WithMisfireHandlingInstructionDoNothing()
{
misfireInstruction = MisfireInstruction.CalendarIntervalTrigger.DoNothing;
return this;
}
/// <summary>
/// If the Trigger misfires, use the
/// <see cref="MisfireInstruction.CalendarIntervalTrigger.FireOnceNow" /> instruction.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="MisfireInstruction.CalendarIntervalTrigger.FireOnceNow" />
public CalendarIntervalScheduleBuilder WithMisfireHandlingInstructionFireAndProceed()
{
misfireInstruction = MisfireInstruction.CalendarIntervalTrigger.FireOnceNow;
return this;
}
/// <summary>
/// TimeZone in which to base the schedule.
/// </summary>
/// <param name="timezone">the time-zone for the schedule</param>
/// <returns>the updated CalendarIntervalScheduleBuilder</returns>
/// <seealso cref="ICalendarIntervalTrigger.TimeZone" />
public CalendarIntervalScheduleBuilder InTimeZone(TimeZoneInfo? timezone)
{
timeZone = timezone;
return this;
}
///<summary>
/// If intervals are a day or greater, this property (set to true) will
/// cause the firing of the trigger to always occur at the same time of day,
/// (the time of day of the startTime) regardless of daylight saving time
/// transitions. Default value is false.
/// </summary>
/// <remarks>
/// <para>
/// For example, without the property set, your trigger may have a start
/// time of 9:00 am on March 1st, and a repeat interval of 2 days. But
/// after the daylight saving transition occurs, the trigger may start
/// firing at 8:00 am every other day.
/// </para>
/// <para>
/// If however, the time of day does not exist on a given day to fire
/// (e.g. 2:00 am in the United States on the days of daylight saving
/// transition), the trigger will go ahead and fire one hour off on
/// that day, and then resume the normal hour on other days. If
/// you wish for the trigger to never fire at the "wrong" hour, then
/// you should set the property skipDayIfHourDoesNotExist.
/// </para>
///</remarks>
/// <seealso cref="SkipDayIfHourDoesNotExist"/>
/// <seealso cref="InTimeZone"/>
/// <seealso cref="TriggerBuilder.StartAt"/>
public CalendarIntervalScheduleBuilder PreserveHourOfDayAcrossDaylightSavings(bool preserveHourOfDay)
{
preserveHourOfDayAcrossDaylightSavings = preserveHourOfDay;
return this;
}
/// <summary>
/// If intervals are a day or greater, and
/// preserveHourOfDayAcrossDaylightSavings property is set to true, and the
/// hour of the day does not exist on a given day for which the trigger
/// would fire, the day will be skipped and the trigger advanced a second
/// interval if this property is set to true. Defaults to false.
/// </summary>
/// <remarks>
/// <b>CAUTION!</b> If you enable this property, and your hour of day happens
/// to be that of daylight savings transition (e.g. 2:00 am in the United
/// States) and the trigger's interval would have had the trigger fire on
/// that day, then you may actually completely miss a firing on the day of
/// transition if that hour of day does not exist on that day! In such a
/// case the next fire time of the trigger will be computed as double (if
/// the interval is 2 days, then a span of 4 days between firings will
/// occur).
/// </remarks>
/// <seealso cref="PreserveHourOfDayAcrossDaylightSavings"/>
public CalendarIntervalScheduleBuilder SkipDayIfHourDoesNotExist(bool skipDay)
{
skipDayIfHourDoesNotExist = skipDay;
return this;
}
// ReSharper disable once UnusedParameter.Local
private static void ValidateInterval(int interval)
{
if (interval <= 0)
{
throw new ArgumentException("Interval must be a positive value.");
}
}
internal CalendarIntervalScheduleBuilder WithMisfireHandlingInstruction(int readMisfireInstructionFromString)
{
misfireInstruction = readMisfireInstructionFromString;
return this;
}
}
/// <summary>
/// Extension methods that attach <see cref="CalendarIntervalScheduleBuilder" /> to <see cref="TriggerBuilder" />.
/// </summary>
public static class CalendarIntervalTriggerBuilderExtensions
{
public static TriggerBuilder WithCalendarIntervalSchedule(this TriggerBuilder triggerBuilder)
{
CalendarIntervalScheduleBuilder builder = CalendarIntervalScheduleBuilder.Create();
return triggerBuilder.WithSchedule(builder);
}
public static TriggerBuilder WithCalendarIntervalSchedule(this TriggerBuilder triggerBuilder, Action<CalendarIntervalScheduleBuilder> action)
{
CalendarIntervalScheduleBuilder builder = CalendarIntervalScheduleBuilder.Create();
action(builder);
return triggerBuilder.WithSchedule(builder);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using System.Collections.Immutable;
using System.Linq;
using Xunit;
using Roslyn.Test.PdbUtilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class ResultPropertiesTests : ExpressionCompilerTestBase
{
[Fact]
public void Category()
{
var source = @"
class C
{
int P { get; set; }
int F;
int M() { return 0; }
void Test(int p)
{
int l;
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
foreach (var expr in new[] { "this", "null", "1", "F", "p", "l" })
{
Assert.Equal(DkmEvaluationResultCategory.Data, GetResultProperties(context, expr).Category);
}
Assert.Equal(DkmEvaluationResultCategory.Method, GetResultProperties(context, "M()").Category);
Assert.Equal(DkmEvaluationResultCategory.Property, GetResultProperties(context, "P").Category);
}
[Fact]
public void StorageType()
{
var source = @"
class C
{
int P { get; set; }
int F;
int M() { return 0; }
static int SP { get; set; }
static int SF;
static int SM() { return 0; }
void Test(int p)
{
int l;
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
foreach (var expr in new[] { "this", "null", "1", "P", "F", "M()", "p", "l" })
{
Assert.Equal(DkmEvaluationResultStorageType.None, GetResultProperties(context, expr).StorageType);
}
foreach (var expr in new[] { "SP", "SF", "SM()" })
{
Assert.Equal(DkmEvaluationResultStorageType.Static, GetResultProperties(context, expr).StorageType);
}
}
[Fact]
public void AccessType()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field private int32 Private
.field family int32 Protected
.field assembly int32 Internal
.field public int32 Public
.field famorassem int32 ProtectedInternal
.field famandassem int32 ProtectedAndInternal
.method public hidebysig instance void
Test() cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
} // end of method C::.ctor
} // end of class C
";
ImmutableArray<byte> exeBytes;
ImmutableArray<byte> pdbBytes;
EmitILToArray(ilSource, appendDefaultHeader: true, includePdb: true, assemblyBytes: out exeBytes, pdbBytes: out pdbBytes);
var runtime = CreateRuntimeInstance(
assemblyName: GetUniqueName(),
references: ImmutableArray.Create(MscorlibRef),
exeBytes: exeBytes.ToArray(),
symReader: new SymReader(pdbBytes.ToArray()));
var context = CreateMethodContext(runtime, methodName: "C.Test");
Assert.Equal(DkmEvaluationResultAccessType.Private, GetResultProperties(context, "Private").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Protected, GetResultProperties(context, "Protected").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "Internal").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Public, GetResultProperties(context, "Public").AccessType);
// As in dev12.
Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "ProtectedInternal").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "ProtectedAndInternal").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.None, GetResultProperties(context, "null").AccessType);
}
[Fact]
public void AccessType_Nested()
{
var source = @"
using System;
internal class C
{
public int F;
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
// Used the declared accessibility, rather than the effective accessibility.
Assert.Equal(DkmEvaluationResultAccessType.Public, GetResultProperties(context, "F").AccessType);
}
[Fact]
public void ModifierFlags_Virtual()
{
var source = @"
using System;
class C
{
public int P { get; set; }
public int M() { return 0; }
public event Action E;
public virtual int VP { get; set; }
public virtual int VM() { return 0; }
public virtual event Action VE;
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "P").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "VP").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "M()").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "VM()").ModifierFlags);
// Field-like events are borderline since they bind as event accesses, but get emitted as field accesses.
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "E").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "VE").ModifierFlags);
}
[Fact]
public void ModifierFlags_Virtual_Variations()
{
var source = @"
using System;
abstract class Base
{
public abstract int Override { get; set; }
}
abstract class Derived : Base
{
public override int Override { get; set; }
public abstract int Abstract { get; set; }
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "Derived.Test");
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "Abstract").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "Override").ModifierFlags);
}
[Fact]
public void ModifierFlags_Constant()
{
var source = @"
using System;
class C
{
int F = 1;
const int CF = 1;
static readonly int SRF = 1;
void Test(int p)
{
int l = 2;
const int cl = 2;
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
foreach (var expr in new[] { "null", "1", "1 + 1", "CF", "cl" })
{
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Constant, GetResultProperties(context, expr).ModifierFlags);
}
foreach (var expr in new[] { "this", "F", "SRF", "p", "l" })
{
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, expr).ModifierFlags);
}
}
[Fact]
public void ModifierFlags_Volatile()
{
var source = @"
using System;
class C
{
int F = 1;
volatile int VF = 1;
void Test(int p)
{
int l;
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "F").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Volatile, GetResultProperties(context, "VF").ModifierFlags);
}
[Fact]
public void Assignment()
{
var source = @"
class C
{
public virtual int P { get; set; }
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
context.CompileAssignment(DefaultInspectionContext.Instance, "P", "1", DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData);
Assert.Null(error);
Assert.Empty(missingAssemblyIdentities);
Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect, resultProperties.Flags);
Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); // Not Data
Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType); // Not Public
Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType);
Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags); // Not Virtual
}
[Fact]
public void LocalDeclaration()
{
var source = @"
class C
{
public virtual int P { get; set; }
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
context.CompileExpression(
InspectionContextFactory.Empty,
"int z = 1;",
DkmEvaluationFlags.None,
DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Null(error);
Assert.Empty(missingAssemblyIdentities);
Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags);
Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); // Not Data
Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType);
Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType);
Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags);
}
[Fact]
public void Error()
{
var source = @"
class C
{
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
VerifyErrorResultProperties(context, "x => x");
VerifyErrorResultProperties(context, "Test");
VerifyErrorResultProperties(context, "Missing");
VerifyErrorResultProperties(context, "C");
}
private static ResultProperties GetResultProperties(EvaluationContext context, string expr)
{
ResultProperties resultProperties;
string error;
context.CompileExpression(expr, out resultProperties, out error);
Assert.Null(error);
return resultProperties;
}
private static void VerifyErrorResultProperties(EvaluationContext context, string expr)
{
ResultProperties resultProperties;
string error;
context.CompileExpression(expr, out resultProperties, out error);
Assert.NotNull(error);
Assert.Equal(default(ResultProperties), resultProperties);
}
}
}
| |
// 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.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.DataProtection.Internal;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.DataProtection.Repositories;
using Microsoft.AspNetCore.DataProtection.Test.Shared;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.DataProtection
{
public class DataProtectionProviderTests
{
[Fact]
public void System_UsesProvidedDirectory()
{
WithUniqueTempDirectory(directory =>
{
// Step 1: directory should be completely empty
directory.Create();
Assert.Empty(directory.GetFiles());
// Step 2: instantiate the system and round-trip a payload
var protector = DataProtectionProvider.Create(directory).CreateProtector("purpose");
Assert.Equal("payload", protector.Unprotect(protector.Protect("payload")));
// Step 3: validate that there's now a single key in the directory and that it's not protected
var allFiles = directory.GetFiles();
Assert.Single(allFiles);
Assert.StartsWith("key-", allFiles[0].Name, StringComparison.OrdinalIgnoreCase);
string fileText = File.ReadAllText(allFiles[0].FullName);
Assert.Contains("Warning: the key below is in an unencrypted form.", fileText, StringComparison.Ordinal);
Assert.DoesNotContain("Windows DPAPI", fileText, StringComparison.Ordinal);
});
}
[Fact]
public void System_NoKeysDirectoryProvided_UsesDefaultKeysDirectory()
{
var mock = new Mock<IDefaultKeyStorageDirectories>();
var keysPath = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName());
mock.Setup(m => m.GetKeyStorageDirectory()).Returns(new DirectoryInfo(keysPath));
// Step 1: Instantiate the system and round-trip a payload
var provider = DataProtectionProvider.CreateProvider(
keyDirectory: null,
certificate: null,
setupAction: builder =>
{
builder.SetApplicationName("TestApplication");
builder.Services.AddSingleton<IKeyManager>(s =>
new XmlKeyManager(
s.GetRequiredService<IOptions<KeyManagementOptions>>(),
s.GetRequiredService<IActivator>(),
NullLoggerFactory.Instance,
mock.Object));
});
var protector = provider.CreateProtector("Protector");
Assert.Equal("payload", protector.Unprotect(protector.Protect("payload")));
// Step 2: Validate that there's now a single key in the directory
var newFileName = Assert.Single(Directory.GetFiles(keysPath));
var file = new FileInfo(newFileName);
Assert.StartsWith("key-", file.Name, StringComparison.OrdinalIgnoreCase);
var fileText = File.ReadAllText(file.FullName);
// On Windows, validate that it's protected using Windows DPAPI.
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.DoesNotContain("Warning: the key below is in an unencrypted form.", fileText, StringComparison.Ordinal);
Assert.Contains("This key is encrypted with Windows DPAPI.", fileText, StringComparison.Ordinal);
}
else
{
Assert.Contains("Warning: the key below is in an unencrypted form.", fileText, StringComparison.Ordinal);
}
}
[ConditionalFact]
[ConditionalRunTestOnlyOnWindows]
public void System_UsesProvidedDirectory_WithConfigurationCallback()
{
WithUniqueTempDirectory(directory =>
{
// Step 1: directory should be completely empty
directory.Create();
Assert.Empty(directory.GetFiles());
// Step 2: instantiate the system and round-trip a payload
var protector = DataProtectionProvider.Create(directory, configure =>
{
configure.ProtectKeysWithDpapi();
}).CreateProtector("purpose");
Assert.Equal("payload", protector.Unprotect(protector.Protect("payload")));
// Step 3: validate that there's now a single key in the directory and that it's protected with DPAPI
var allFiles = directory.GetFiles();
Assert.Single(allFiles);
Assert.StartsWith("key-", allFiles[0].Name, StringComparison.OrdinalIgnoreCase);
string fileText = File.ReadAllText(allFiles[0].FullName);
Assert.DoesNotContain("Warning: the key below is in an unencrypted form.", fileText, StringComparison.Ordinal);
Assert.Contains("Windows DPAPI", fileText, StringComparison.Ordinal);
});
}
[ConditionalFact]
[X509StoreIsAvailable(StoreName.My, StoreLocation.CurrentUser)]
[SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/6720", Queues = "All.OSX")]
public void System_UsesProvidedDirectoryAndCertificate()
{
var filePath = Path.Combine(GetTestFilesPath(), "TestCert.pfx");
using (var imported = new X509Certificate2(filePath, "password", X509KeyStorageFlags.Exportable))
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadWrite);
store.Add(imported);
store.Close();
}
WithUniqueTempDirectory(directory =>
{
var certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certificateStore.Open(OpenFlags.ReadWrite);
var certificate = certificateStore.Certificates.Find(X509FindType.FindBySubjectName, "TestCert", false)[0];
Assert.True(certificate.HasPrivateKey, "Cert should have a private key");
try
{
// Step 1: directory should be completely empty
directory.Create();
Assert.Empty(directory.GetFiles());
// Step 2: instantiate the system and round-trip a payload
var protector = DataProtectionProvider.Create(directory, certificate).CreateProtector("purpose");
var data = protector.Protect("payload");
// add a cert without the private key to ensure the decryption will still fallback to the cert store
var certWithoutKey = new X509Certificate2(Path.Combine(GetTestFilesPath(), "TestCertWithoutPrivateKey.pfx"), "password");
var unprotector = DataProtectionProvider.Create(directory, o => o.UnprotectKeysWithAnyCertificate(certWithoutKey)).CreateProtector("purpose");
Assert.Equal("payload", unprotector.Unprotect(data));
// Step 3: validate that there's now a single key in the directory and that it's is protected using the certificate
var allFiles = directory.GetFiles();
Assert.Single(allFiles);
Assert.StartsWith("key-", allFiles[0].Name, StringComparison.OrdinalIgnoreCase);
string fileText = File.ReadAllText(allFiles[0].FullName);
Assert.DoesNotContain("Warning: the key below is in an unencrypted form.", fileText, StringComparison.Ordinal);
Assert.Contains("X509Certificate", fileText, StringComparison.Ordinal);
}
finally
{
certificateStore.Remove(certificate);
certificateStore.Close();
}
});
}
}
[ConditionalFact]
[X509StoreIsAvailable(StoreName.My, StoreLocation.CurrentUser)]
public void System_UsesProvidedCertificateNotFromStore()
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadWrite);
var certWithoutKey = new X509Certificate2(Path.Combine(GetTestFilesPath(), "TestCert3WithoutPrivateKey.pfx"), "password3", X509KeyStorageFlags.Exportable);
Assert.False(certWithoutKey.HasPrivateKey, "Cert should not have private key");
store.Add(certWithoutKey);
store.Close();
}
WithUniqueTempDirectory(directory =>
{
using (var certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
certificateStore.Open(OpenFlags.ReadWrite);
var certInStore = certificateStore.Certificates.Find(X509FindType.FindBySubjectName, "TestCert", false)[0];
Assert.NotNull(certInStore);
Assert.False(certInStore.HasPrivateKey, "Cert should not have private key");
try
{
var certWithKey = new X509Certificate2(Path.Combine(GetTestFilesPath(), "TestCert3.pfx"), "password3");
var protector = DataProtectionProvider.Create(directory, certWithKey).CreateProtector("purpose");
var data = protector.Protect("payload");
var keylessUnprotector = DataProtectionProvider.Create(directory).CreateProtector("purpose");
Assert.Throws<CryptographicException>(() => keylessUnprotector.Unprotect(data));
var unprotector = DataProtectionProvider.Create(directory, o => o.UnprotectKeysWithAnyCertificate(certInStore, certWithKey)).CreateProtector("purpose");
Assert.Equal("payload", unprotector.Unprotect(data));
}
finally
{
certificateStore.Remove(certInStore);
certificateStore.Close();
}
}
});
}
[Fact]
public void System_UsesInMemoryCertificate()
{
var filePath = Path.Combine(GetTestFilesPath(), "TestCert2.pfx");
var certificate = new X509Certificate2(filePath, "password");
AssetStoreDoesNotContain(certificate);
WithUniqueTempDirectory(directory =>
{
// Step 1: directory should be completely empty
directory.Create();
Assert.Empty(directory.GetFiles());
// Step 2: instantiate the system and round-trip a payload
var protector = DataProtectionProvider.Create(directory, certificate).CreateProtector("purpose");
Assert.Equal("payload", protector.Unprotect(protector.Protect("payload")));
// Step 3: validate that there's now a single key in the directory and that it's is protected using the certificate
var allFiles = directory.GetFiles();
Assert.Single(allFiles);
Assert.StartsWith("key-", allFiles[0].Name, StringComparison.OrdinalIgnoreCase);
string fileText = File.ReadAllText(allFiles[0].FullName);
Assert.DoesNotContain("Warning: the key below is in an unencrypted form.", fileText, StringComparison.Ordinal);
Assert.Contains("X509Certificate", fileText, StringComparison.Ordinal);
});
}
private static void AssetStoreDoesNotContain(X509Certificate2 certificate)
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
try
{
store.Open(OpenFlags.ReadOnly);
}
catch
{
return;
}
// ensure this cert is not in the x509 store
Assert.Empty(store.Certificates.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, false));
}
}
[Fact]
public void System_CanUnprotectWithCert()
{
var filePath = Path.Combine(GetTestFilesPath(), "TestCert2.pfx");
var certificate = new X509Certificate2(filePath, "password");
WithUniqueTempDirectory(directory =>
{
// Step 1: directory should be completely empty
directory.Create();
Assert.Empty(directory.GetFiles());
// Step 2: instantiate the system and create some data
var protector = DataProtectionProvider
.Create(directory, certificate)
.CreateProtector("purpose");
var data = protector.Protect("payload");
// Step 3: validate that there's now a single key in the directory and that it's is protected using the certificate
var allFiles = directory.GetFiles();
Assert.Single(allFiles);
Assert.StartsWith("key-", allFiles[0].Name, StringComparison.OrdinalIgnoreCase);
string fileText = File.ReadAllText(allFiles[0].FullName);
Assert.DoesNotContain("Warning: the key below is in an unencrypted form.", fileText, StringComparison.Ordinal);
Assert.Contains("X509Certificate", fileText, StringComparison.Ordinal);
// Step 4: setup a second system and validate it can decrypt keys and unprotect data
var unprotector = DataProtectionProvider.Create(directory,
b => b.UnprotectKeysWithAnyCertificate(certificate));
Assert.Equal("payload", unprotector.CreateProtector("purpose").Unprotect(data));
});
}
/// <summary>
/// Runs a test and cleans up the temp directory afterward.
/// </summary>
private static void WithUniqueTempDirectory(Action<DirectoryInfo> testCode)
{
string uniqueTempPath = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName());
var dirInfo = new DirectoryInfo(uniqueTempPath);
try
{
testCode(dirInfo);
}
finally
{
// clean up when test is done
if (dirInfo.Exists)
{
dirInfo.Delete(recursive: true);
}
}
}
private static string GetTestFilesPath()
=> Path.Combine(AppContext.BaseDirectory, "TestFiles");
}
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// 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 BuildAMation 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 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.
#endregion // License
using System.Linq;
namespace CommandLineProcessor
{
/// <summary>
/// Helper class for converting Settings to command lines.
/// </summary>
static class NativeConversion
{
private static void
HandleEnum(
Bam.Core.StringArray commandLine,
System.Reflection.PropertyInfo interfacePropertyInfo,
System.Reflection.PropertyInfo propertyInfo,
object[] attributeArray,
object propertyValue)
{
if (null == propertyValue)
{
return;
}
if (!(typeof(System.Enum).IsAssignableFrom(propertyInfo.PropertyType) ||
(propertyInfo.PropertyType.IsGenericType &&
propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(System.Nullable<>)
)
)
)
{
throw new Bam.Core.Exception(
$"Attribute expected an enum (or nullable enum), but property {propertyInfo.Name} is of type {propertyInfo.PropertyType.ToString()}"
);
}
var matching_attribute = attributeArray.FirstOrDefault(
item => (item as EnumAttribute).Key.Equals(propertyValue)
) as BaseAttribute;
if (null == matching_attribute)
{
var message = new System.Text.StringBuilder();
message.Append($"Unable to locate enumeration mapping of '{propertyValue.GetType().ToString()}.{propertyValue.ToString()}' ");
message.Append($"for property {interfacePropertyInfo.DeclaringType.FullName}.{interfacePropertyInfo.Name}");
throw new Bam.Core.Exception(message.ToString());
}
var cmd = matching_attribute.CommandSwitch;
if (!System.String.IsNullOrEmpty(cmd))
{
commandLine.Add(cmd);
}
}
private static void
HandleSinglePath(
Bam.Core.Module module,
Bam.Core.StringArray commandLine,
System.Reflection.PropertyInfo interfacePropertyInfo,
System.Reflection.PropertyInfo propertyInfo,
object[] attributeArray,
object propertyValue)
{
if (null == propertyValue)
{
return;
}
if (!typeof(Bam.Core.TokenizedString).IsAssignableFrom(propertyInfo.PropertyType))
{
if (!typeof(string).IsAssignableFrom(propertyInfo.PropertyType))
{
throw new Bam.Core.Exception(
$"Attribute expected either a Bam.Core.TokenizedString or string, but property {propertyInfo.Name} is of type {propertyInfo.PropertyType.ToString()}"
);
}
}
if (typeof(Bam.Core.TokenizedString).IsAssignableFrom(propertyInfo.PropertyType))
{
commandLine.Add(
$"{(attributeArray.First() as BaseAttribute).CommandSwitch}{(propertyValue as Bam.Core.TokenizedString).ToStringQuoteIfNecessary()}"
);
}
else
{
var path = module.GeneratedPaths[propertyValue as string];
commandLine.Add(
$"{(attributeArray.First() as BaseAttribute).CommandSwitch}{path.ToStringQuoteIfNecessary()}"
);
}
}
private static void
HandlePathArray(
Bam.Core.StringArray commandLine,
System.Reflection.PropertyInfo interfacePropertyInfo,
System.Reflection.PropertyInfo propertyInfo,
object[] attributeArray,
object propertyValue)
{
if (!typeof(Bam.Core.TokenizedStringArray).IsAssignableFrom(propertyInfo.PropertyType))
{
throw new Bam.Core.Exception(
$"Attribute expected a Bam.Core.TokenizedStringArray, but property {propertyInfo.Name} is of type {propertyInfo.PropertyType.ToString()}"
);
}
var command_switch = (attributeArray.First() as BaseAttribute).CommandSwitch;
foreach (var path in (propertyValue as Bam.Core.TokenizedStringArray).ToEnumerableWithoutDuplicates())
{
// TODO: a special case is needed for this being requested in Xcode mode
// which is done when there are overrides per source file
commandLine.Add(
$"{command_switch}{path.ToStringQuoteIfNecessary()}"
);
}
}
private static void
HandleFrameworkArray(
Bam.Core.StringArray commandLine,
System.Reflection.PropertyInfo interfacePropertyInfo,
System.Reflection.PropertyInfo propertyInfo,
object[] attributeArray,
object propertyValue)
{
if (!typeof(Bam.Core.TokenizedStringArray).IsAssignableFrom(propertyInfo.PropertyType))
{
throw new Bam.Core.Exception(
$"Attribute expected a Bam.Core.TokenizedStringArray, but property {propertyInfo.Name} is of type {propertyInfo.PropertyType.ToString()}"
);
}
var command_switch = (attributeArray.First() as BaseAttribute).CommandSwitch;
foreach (var path in (propertyValue as Bam.Core.TokenizedStringArray).ToEnumerableWithoutDuplicates())
{
commandLine.Add(
$"{command_switch}{System.IO.Path.GetFileNameWithoutExtension(path.ToStringQuoteIfNecessary())}"
);
}
}
private static void
HandleSingleString(
Bam.Core.StringArray commandLine,
System.Reflection.PropertyInfo interfacePropertyInfo,
System.Reflection.PropertyInfo propertyInfo,
object[] attributeArray,
object propertyValue)
{
if (null == propertyValue)
{
return;
}
if (!typeof(string).IsAssignableFrom(propertyInfo.PropertyType))
{
throw new Bam.Core.Exception(
$"Attribute expected a string, but property {propertyInfo.Name} is of type {propertyInfo.PropertyType.ToString()}"
);
}
var command_switch = (attributeArray.First() as BaseAttribute).CommandSwitch;
if (command_switch.EndsWith("=", System.StringComparison.Ordinal) &&
(propertyValue as string).Contains("=", System.StringComparison.Ordinal))
{
// the double quotes are needed for MakeFiles.
// escaping the equals sign in the value did not work
// and single quotes worked in MakeFiles but didn't in Native builds
commandLine.Add(
$"{command_switch}\"{propertyValue as string}\""
);
}
else
{
commandLine.Add(
$"{command_switch}{propertyValue as string}"
);
}
}
private static void
HandleStringArray(
Bam.Core.StringArray commandLine,
System.Reflection.PropertyInfo interfacePropertyInfo,
System.Reflection.PropertyInfo propertyInfo,
object[] attributeArray,
object propertyValue)
{
if (!typeof(Bam.Core.StringArray).IsAssignableFrom(propertyInfo.PropertyType))
{
throw new Bam.Core.Exception(
$"Attribute expected a Bam.Core.StringArray, but property {propertyInfo.Name} is of type {propertyInfo.PropertyType.ToString()}"
);
}
var command_switch = (attributeArray.First() as BaseAttribute).CommandSwitch;
foreach (var str in (propertyValue as Bam.Core.StringArray))
{
// TODO: a special case is needed for this being requested in Xcode mode
// which is done when there are overrides per source file
commandLine.Add(
$"{command_switch}{str}"
);
}
}
private static void
HandleBool(
Bam.Core.StringArray commandLine,
System.Reflection.PropertyInfo interfacePropertyInfo,
System.Reflection.PropertyInfo propertyInfo,
object[] attributeArray,
object propertyValue)
{
if (!(typeof(bool).IsAssignableFrom(propertyInfo.PropertyType) ||
(propertyInfo.PropertyType.IsGenericType &&
propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(System.Nullable<>)
)
)
)
{
throw new Bam.Core.Exception(
$"Attribute expected an bool (or nullable bool), but property {propertyInfo.Name} is of type {propertyInfo.PropertyType.ToString()}"
);
}
bool value = (bool)propertyValue;
var attr = attributeArray.First() as BoolAttribute;
if (value)
{
var truth_command = attr.TrueCommandSwitch;
if (!System.String.IsNullOrEmpty(truth_command))
{
commandLine.Add(truth_command);
}
}
else
{
var false_command = attr.FalseCommandSwitch;
if (!System.String.IsNullOrEmpty(false_command))
{
commandLine.Add(false_command);
}
}
}
private static void
HandlePreprocessorDefines(
Bam.Core.StringArray commandLine,
System.Reflection.PropertyInfo interfacePropertyInfo,
System.Reflection.PropertyInfo propertyInfo,
object[] attributeArray,
object propertyValue)
{
if (!typeof(C.PreprocessorDefinitions).IsAssignableFrom(propertyInfo.PropertyType))
{
throw new Bam.Core.Exception(
$"Attribute expected a C.PreprocessorDefinitions, but property {propertyInfo.Name} is of type {propertyInfo.PropertyType.ToString()}"
);
}
var command_switch = (attributeArray.First() as BaseAttribute).CommandSwitch;
foreach (var define in (propertyValue as C.PreprocessorDefinitions))
{
if (null == define.Value)
{
commandLine.Add($"-D{define.Key}");
}
else
{
var defineValue = define.Value.ToString();
if (defineValue.Contains("\""))
{
if (Bam.Core.Graph.Instance.Mode.Equals("Xcode", System.StringComparison.Ordinal))
{
// note the number of back slashes here
// required to get \\\" for each " in the original value
defineValue = defineValue.Replace("\"", "\\\\\\\"");
}
else
{
defineValue = defineValue.Replace("\"", "\\\"");
}
}
defineValue = Bam.Core.IOWrapper.EncloseSpaceContainingPathWithDoubleQuotes(defineValue);
commandLine.Add($"-D{define.Key}={defineValue}");
}
}
}
/// <summary>
/// Convert a Settings instance to command lines.
/// </summary>
/// <param name="settings">Settings instance to convert properties to command line.</param>
/// <param name="module">The Module owning the Settings.</param>
/// <param name="createDelta">Optional whether to create a delta command line (for per-file command lines). Default to false.</param>
/// <returns></returns>
public static Bam.Core.StringArray
Convert(
Bam.Core.Settings settings,
Bam.Core.Module module,
bool createDelta = false)
{
if (null == settings)
{
return new Bam.Core.StringArray();
}
if (settings.CommandLayout == Bam.Core.Settings.ELayout.Unassigned)
{
throw new Bam.Core.Exception(
$"Command layout for {settings.ToString()} settings is unassigned. Check that the constructor updates the layout on the base class"
);
}
var commandLine = new Bam.Core.StringArray();
//Bam.Core.Log.MessageAll($"Module: {module.ToString()}");
//Bam.Core.Log.MessageAll($"Settings: {settings.ToString()}");
foreach (var settings_interface in settings.Interfaces())
{
//Bam.Core.Log.MessageAll(settings_interface.ToString());
foreach (var interface_property in settings_interface.GetProperties())
{
// must use the fully qualified property name from the originating interface
// to look for the instance in the concrete settings class
// this is to allow for the same property leafname to appear in multiple interfaces
var full_property_interface_name = System.String.Join(".", new[] { interface_property.DeclaringType.FullName, interface_property.Name });
var settings_property = settings.Properties.First(
item => full_property_interface_name.Equals(item.Name, System.StringComparison.Ordinal)
);
//Bam.Core.Log.MessageAll($"\t{settings_property.ToString()}");
var attributeArray = settings_property.GetCustomAttributes(typeof(BaseAttribute), false);
if (!attributeArray.Any())
{
throw new Bam.Core.Exception(
$"No attributes available for mapping property {full_property_interface_name} to command line switches for module {module.ToString()} and settings {settings.ToString()}"
);
}
var property_value = settings_property.GetValue(settings);
if (null == property_value)
{
continue;
}
if (attributeArray.First() is EnumAttribute)
{
HandleEnum(
commandLine,
interface_property,
settings_property,
attributeArray,
property_value
);
}
else if (attributeArray.First() is PathAttribute)
{
HandleSinglePath(
module,
commandLine,
interface_property,
settings_property,
attributeArray,
property_value
);
}
else if (attributeArray.First() is PathArrayAttribute)
{
HandlePathArray(
commandLine,
interface_property,
settings_property,
attributeArray,
property_value
);
}
else if (attributeArray.First() is FrameworkArrayAttribute)
{
HandleFrameworkArray(
commandLine,
interface_property,
settings_property,
attributeArray,
property_value
);
}
else if (attributeArray.First() is StringAttribute)
{
HandleSingleString(
commandLine,
interface_property,
settings_property,
attributeArray,
property_value
);
}
else if (attributeArray.First() is StringArrayAttribute)
{
HandleStringArray(
commandLine,
interface_property,
settings_property,
attributeArray,
property_value
);
}
else if (attributeArray.First() is BoolAttribute)
{
HandleBool(
commandLine,
interface_property,
settings_property,
attributeArray,
property_value
);
}
else if (attributeArray.First() is PreprocessorDefinesAttribute)
{
HandlePreprocessorDefines(
commandLine,
interface_property,
settings_property,
attributeArray,
property_value
);
}
else
{
throw new Bam.Core.Exception(
$"Unhandled attribute {attributeArray.First().ToString()} for property {settings_property.Name} in {module.ToString()}"
);
}
}
}
//Bam.Core.Log.MessageAll($"{module.ToString()}: Executing '{commandLine.ToString(' ')}'");
if (createDelta)
{
// don't want to introduce outputs or inputs in deltas
return commandLine;
}
if (null == settings.Module)
{
throw new Bam.Core.Exception(
$"No Module was associated with the settings class {settings.ToString()}"
);
}
var output_file_attributes = settings.GetType().GetCustomAttributes(
typeof(OutputPathAttribute),
true // since generally specified in an abstract class
) as OutputPathAttribute[];
if (!output_file_attributes.Any() && module.GeneratedPaths.Any())
{
throw new Bam.Core.Exception(
$"There are no OutputPath attributes associated with the {settings.ToString()} settings class"
);
}
var input_files_attributes = settings.GetType().GetCustomAttributes(
typeof(InputPathsAttribute),
true // since generally specified in an abstract class
) as InputPathsAttribute[];
if (module.InputModulePaths.Any())
{
if (!input_files_attributes.Any())
{
var message = new System.Text.StringBuilder();
message.AppendLine(
$"There is no InputPaths attribute associated with the {settings.ToString()} settings class and module {module.ToString()}"
);
message.AppendLine("The following input paths were identified for the module:");
foreach (var (inputModule,inputPathKey) in module.InputModulePaths)
{
message.Append($"\t{inputModule.ToString()}[{inputPathKey}]");
if (inputModule.GeneratedPaths.ContainsKey(inputPathKey))
{
message.Append($" = '{inputModule.GeneratedPaths[inputPathKey].ToString()}'");
}
message.AppendLine();
}
throw new Bam.Core.Exception(message.ToString());
}
var attr = input_files_attributes.First();
var max_files = attr.MaxFileCount;
if (max_files >= 0)
{
if (max_files != module.InputModulePaths.Count())
{
throw new Bam.Core.Exception(
$"InputPaths attribute specifies a maximum of {max_files} files, but {module.InputModulePaths.Count()} are available"
);
}
}
}
switch (settings.CommandLayout)
{
case Bam.Core.Settings.ELayout.Cmds_Outputs_Inputs:
ProcessOutputPaths(settings, module, commandLine, output_file_attributes);
ProcessInputPaths(settings, module, commandLine, input_files_attributes);
break;
case Bam.Core.Settings.ELayout.Cmds_Inputs_Outputs:
ProcessInputPaths(settings, module, commandLine, input_files_attributes);
ProcessOutputPaths(settings, module, commandLine, output_file_attributes);
break;
case Bam.Core.Settings.ELayout.Inputs_Cmds_Outputs:
{
var newCommandLine = new Bam.Core.StringArray();
ProcessInputPaths(settings, module, newCommandLine, input_files_attributes);
newCommandLine.AddRange(commandLine);
ProcessOutputPaths(settings, module, newCommandLine, output_file_attributes);
commandLine = newCommandLine;
}
break;
case Bam.Core.Settings.ELayout.Inputs_Outputs_Cmds:
{
var newCommandLine = new Bam.Core.StringArray();
ProcessInputPaths(settings, module, newCommandLine, input_files_attributes);
ProcessOutputPaths(settings, module, newCommandLine, output_file_attributes);
newCommandLine.AddRange(commandLine);
commandLine = newCommandLine;
}
break;
default:
throw new Bam.Core.Exception(
$"Unhandled file layout {settings.CommandLayout.ToString()} for settings {settings.ToString()}"
);
}
return commandLine;
}
private static void
ProcessInputPaths(
Bam.Core.Settings settings,
Bam.Core.Module module,
Bam.Core.StringArray commandLine,
InputPathsAttribute[] input_files_attributes)
{
if (!input_files_attributes.Any())
{
return;
}
foreach (var (inputModule, inputPathKey) in module.InputModulePaths)
{
var matching_input_attr = input_files_attributes.FirstOrDefault(
item => inputPathKey.Equals(item.PathKey, System.StringComparison.Ordinal)
);
if (null == matching_input_attr)
{
// first look to see if there's a generic 'catch all files' attribute
// before failing
var match_any = input_files_attributes.FirstOrDefault(item => item is AnyInputFileAttribute);
if (null == match_any)
{
var message = new System.Text.StringBuilder();
message.AppendLine($"Unable to locate an InputPathsAttribute or AnyInputFileAttribute suitable for this input:");
message.AppendLine($"\tModule : {inputModule.ToString()}");
message.AppendLine($"\tPathkey: {inputPathKey}");
message.AppendLine($"while dealing with inputs on module {module.ToString()}.");
message.AppendLine("Possible reasons:");
message.AppendLine($"\tDoes module {module.ToString()} override the Dependents property?");
message.AppendLine($"\tIs settings class {settings.ToString()} missing an InputPaths attribute?");
throw new Bam.Core.Exception(message.ToString());
}
matching_input_attr = match_any;
}
var input_path = inputModule.GeneratedPaths[inputPathKey];
#if D_PACKAGE_PUBLISHER
if (matching_input_attr is AnyInputFileAttribute &&
(matching_input_attr as AnyInputFileAttribute).PathModifierIfDirectory != null &&
module is Publisher.CollatedDirectory)
{
var modifiedPath = Bam.Core.TokenizedString.Create(
(matching_input_attr as AnyInputFileAttribute).PathModifierIfDirectory,
module,
new Bam.Core.TokenizedStringArray(input_path)
);
if (!modifiedPath.IsParsed)
{
modifiedPath.Parse();
}
commandLine.Add(
$"{matching_input_attr.CommandSwitch}{modifiedPath.ToStringQuoteIfNecessary()}"
);
continue;
}
#endif
if (null != matching_input_attr.PathModifier)
{
var modifiedPath = Bam.Core.TokenizedString.Create(
matching_input_attr.PathModifier,
module,
new Bam.Core.TokenizedStringArray(input_path)
);
if (!modifiedPath.IsParsed)
{
modifiedPath.Parse();
}
commandLine.Add(
$"{matching_input_attr.CommandSwitch}{modifiedPath.ToStringQuoteIfNecessary()}"
);
}
else
{
commandLine.Add(
$"{matching_input_attr.CommandSwitch}{input_path.ToStringQuoteIfNecessary()}"
);
}
}
}
private static void
ProcessOutputPaths(
Bam.Core.Settings settings,
Bam.Core.Module module,
Bam.Core.StringArray commandLine,
OutputPathAttribute[] output_file_attributes)
{
foreach (var generatedPath in module.GeneratedPaths)
{
if (null == generatedPath.Value)
{
continue;
}
var outputKey = generatedPath.Key;
var matching_attr = output_file_attributes.FirstOrDefault(item => item.PathKey.Equals(outputKey, System.StringComparison.Ordinal));
if (null == matching_attr)
{
throw new Bam.Core.Exception(
$"Unable to locate OutputPath class attribute on {settings.ToString()} for path key {outputKey}"
);
}
if (matching_attr.Ignore)
{
continue;
}
if (null != matching_attr.PathModifier)
{
var modifiedPath = Bam.Core.TokenizedString.Create(
matching_attr.PathModifier,
module,
new Bam.Core.TokenizedStringArray(module.GeneratedPaths[outputKey])
);
if (!modifiedPath.IsParsed)
{
modifiedPath.Parse();
}
commandLine.Add(
$"{matching_attr.CommandSwitch}{modifiedPath.ToStringQuoteIfNecessary()}"
);
}
else
{
commandLine.Add(
$"{matching_attr.CommandSwitch}{module.GeneratedPaths[outputKey].ToStringQuoteIfNecessary()}"
);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
** This file exists to contain miscellaneous module-level attributes
** and other miscellaneous stuff.
**
**
**
===========================================================*/
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.StubHelpers;
using System.Threading.Tasks;
#if FEATURE_COMINTEROP
using System.Runtime.InteropServices.WindowsRuntime;
[assembly:Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D")]
// The following attribute are required to ensure COM compatibility.
[assembly:System.Runtime.InteropServices.ComCompatibleVersion(1, 0, 3300, 0)]
[assembly:System.Runtime.InteropServices.TypeLibVersion(2, 4)]
#endif // FEATURE_COMINTEROP
[assembly:DefaultDependencyAttribute(LoadHint.Always)]
// mscorlib would like to have its literal strings frozen if possible
[assembly: System.Runtime.CompilerServices.StringFreezingAttribute()]
namespace System
{
static class Internal
{
// This method is purely an aid for NGen to statically deduce which
// instantiations to save in the ngen image.
// Otherwise, the JIT-compiler gets used, which is bad for working-set.
// Note that IBC can provide this information too.
// However, this helps in keeping the JIT-compiler out even for
// test scenarios which do not use IBC.
// This can be removed after V2, when we implement other schemes
// of keeping the JIT-compiler out for generic instantiations.
static void CommonlyUsedGenericInstantiations()
{
// Make absolutely sure we include some of the most common
// instantiations here in mscorlib's ngen image.
// Note that reference type instantiations are already included
// automatically for us.
System.Array.Sort<double>(null);
System.Array.Sort<int>(null);
System.Array.Sort<IntPtr>(null);
new ArraySegment<byte>(new byte[1], 0, 0);
new Dictionary<Char, Object>();
new Dictionary<Guid, Byte>();
new Dictionary<Guid, Object>();
new Dictionary<Guid, Guid>(); // Added for Visual Studio 2010
new Dictionary<Int16, IntPtr>();
new Dictionary<Int32, Byte>();
new Dictionary<Int32, Int32>();
new Dictionary<Int32, Object>();
new Dictionary<IntPtr, Boolean>();
new Dictionary<IntPtr, Int16>();
new Dictionary<Object, Boolean>();
new Dictionary<Object, Char>();
new Dictionary<Object, Guid>();
new Dictionary<Object, Int32>();
new Dictionary<Object, Int64>(); // Added for Visual Studio 2010
new Dictionary<uint, WeakReference>(); // NCL team needs this
new Dictionary<Object, UInt32>();
new Dictionary<UInt32, Object>();
new Dictionary<Int64, Object>();
#if FEATURE_CORECLR
// to genereate mdil for Dictionary instantiation when key is user defined value type
new Dictionary<Guid, Int32>();
#endif
// Microsoft.Windows.Design
new Dictionary<System.Reflection.MemberTypes, Object>();
new EnumEqualityComparer<System.Reflection.MemberTypes>();
// Microsoft.Expression.DesignModel
new Dictionary<Object, KeyValuePair<Object,Object>>();
new Dictionary<KeyValuePair<Object,Object>, Object>();
NullableHelper<Boolean>();
NullableHelper<Byte>();
NullableHelper<Char>();
NullableHelper<DateTime>();
NullableHelper<Decimal>();
NullableHelper<Double>();
NullableHelper<Guid>();
NullableHelper<Int16>();
NullableHelper<Int32>();
NullableHelper<Int64>();
NullableHelper<Single>();
NullableHelper<TimeSpan>();
NullableHelper<DateTimeOffset>(); // For SQL
new List<Boolean>();
new List<Byte>();
new List<Char>();
new List<DateTime>();
new List<Decimal>();
new List<Double>();
new List<Guid>();
new List<Int16>();
new List<Int32>();
new List<Int64>();
new List<TimeSpan>();
new List<SByte>();
new List<Single>();
new List<UInt16>();
new List<UInt32>();
new List<UInt64>();
new List<IntPtr>();
new List<KeyValuePair<Object, Object>>();
new List<GCHandle>(); // NCL team needs this
new List<DateTimeOffset>();
new KeyValuePair<Char, UInt16>('\0', UInt16.MinValue);
new KeyValuePair<UInt16, Double>(UInt16.MinValue, Double.MinValue);
new KeyValuePair<Object, Int32>(String.Empty, Int32.MinValue);
new KeyValuePair<Int32, Int32>(Int32.MinValue, Int32.MinValue);
SZArrayHelper<Boolean>(null);
SZArrayHelper<Byte>(null);
SZArrayHelper<DateTime>(null);
SZArrayHelper<Decimal>(null);
SZArrayHelper<Double>(null);
SZArrayHelper<Guid>(null);
SZArrayHelper<Int16>(null);
SZArrayHelper<Int32>(null);
SZArrayHelper<Int64>(null);
SZArrayHelper<TimeSpan>(null);
SZArrayHelper<SByte>(null);
SZArrayHelper<Single>(null);
SZArrayHelper<UInt16>(null);
SZArrayHelper<UInt32>(null);
SZArrayHelper<UInt64>(null);
SZArrayHelper<DateTimeOffset>(null);
SZArrayHelper<CustomAttributeTypedArgument>(null);
SZArrayHelper<CustomAttributeNamedArgument>(null);
#if FEATURE_CORECLR
#pragma warning disable 4014
// This is necessary to generate MDIL for AsyncVoidMethodBuilder
AsyncHelper<int>();
AsyncHelper2<int>();
AsyncHelper3();
#pragma warning restore 4014
#endif
}
static T NullableHelper<T>() where T : struct
{
Nullable.Compare<T>(null, null);
Nullable.Equals<T>(null, null);
Nullable<T> nullable = new Nullable<T>();
return nullable.GetValueOrDefault();
}
static void SZArrayHelper<T>(SZArrayHelper oSZArrayHelper)
{
// Instantiate common methods for IList implementation on Array
oSZArrayHelper.get_Count<T>();
oSZArrayHelper.get_Item<T>(0);
oSZArrayHelper.GetEnumerator<T>();
}
#if FEATURE_CORECLR
// System.Runtime.CompilerServices.AsyncVoidMethodBuilder
// System.Runtime.CompilerServices.TaskAwaiter
static async void AsyncHelper<T>()
{
await Task.Delay(1);
}
// System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.__Canon]
// System.Runtime.CompilerServices.TaskAwaiter'[System.__Canon]
static async Task<String> AsyncHelper2<T>()
{
return await Task.FromResult<string>("");
}
// System.Runtime.CompilerServices.AsyncTaskMethodBuilder
// System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1[VoidTaskResult]
static async Task AsyncHelper3()
{
await Task.FromResult<string>("");
}
#endif
#if FEATURE_COMINTEROP
// Similar to CommonlyUsedGenericInstantiations but for instantiations of marshaling stubs used
// for WinRT redirected interfaces. Note that we do care about reference types here as well because,
// say, IList<string> and IList<object> cannot share marshaling stubs.
// The methods below "call" most commonly used stub methods on redirected interfaces and take arguments
// typed as matching instantiations of mscorlib copies of WinRT interfaces (IIterable<T>, IVector<T>,
// IMap<K, V>, ...) which is necessary to generate all required IL stubs.
[SecurityCritical]
static void CommonlyUsedWinRTRedirectedInterfaceStubs()
{
WinRT_IEnumerable<byte>(null, null, null);
WinRT_IEnumerable<char>(null, null, null);
WinRT_IEnumerable<short>(null, null, null);
WinRT_IEnumerable<ushort>(null, null, null);
WinRT_IEnumerable<int>(null, null, null);
WinRT_IEnumerable<uint>(null, null, null);
WinRT_IEnumerable<long>(null, null, null);
WinRT_IEnumerable<ulong>(null, null, null);
WinRT_IEnumerable<float>(null, null, null);
WinRT_IEnumerable<double>(null, null, null);
// The underlying WinRT types for shared instantiations have to be referenced explicitly.
// They are not guaranteeed to be created indirectly because of generic code sharing.
WinRT_IEnumerable<string>(null, null, null); typeof(IIterable<string>).ToString(); typeof(IIterator<string>).ToString();
WinRT_IEnumerable<object>(null, null, null); typeof(IIterable<object>).ToString(); typeof(IIterator<object>).ToString();
WinRT_IList<int>(null, null, null, null);
WinRT_IList<string>(null, null, null, null); typeof(IVector<string>).ToString();
WinRT_IList<object>(null, null, null, null); typeof(IVector<object>).ToString();
WinRT_IReadOnlyList<int>(null, null, null);
WinRT_IReadOnlyList<string>(null, null, null); typeof(IVectorView<string>).ToString();
WinRT_IReadOnlyList<object>(null, null, null); typeof(IVectorView<object>).ToString();
WinRT_IDictionary<string, int>(null, null, null, null); typeof(IMap<string, int>).ToString();
WinRT_IDictionary<string, string>(null, null, null, null); typeof(IMap<string, string>).ToString();
WinRT_IDictionary<string, object>(null, null, null, null); typeof(IMap<string, object>).ToString();
WinRT_IDictionary<object, object>(null, null, null, null); typeof(IMap<object, object>).ToString();
WinRT_IReadOnlyDictionary<string, int>(null, null, null, null); typeof(IMapView<string, int>).ToString();
WinRT_IReadOnlyDictionary<string, string>(null, null, null, null); typeof(IMapView<string, string>).ToString();
WinRT_IReadOnlyDictionary<string, object>(null, null, null, null); typeof(IMapView<string, object>).ToString();
WinRT_IReadOnlyDictionary<object, object>(null, null, null, null); typeof(IMapView<object, object>).ToString();
WinRT_Nullable<bool>();
WinRT_Nullable<byte>();
WinRT_Nullable<int>();
WinRT_Nullable<uint>();
WinRT_Nullable<long>();
WinRT_Nullable<ulong>();
WinRT_Nullable<float>();
WinRT_Nullable<double>();
}
[SecurityCritical]
static void WinRT_IEnumerable<T>(IterableToEnumerableAdapter iterableToEnumerableAdapter, EnumerableToIterableAdapter enumerableToIterableAdapter, IIterable<T> iterable)
{
// instantiate stubs for the one method on IEnumerable<T> and the one method on IIterable<T>
iterableToEnumerableAdapter.GetEnumerator_Stub<T>();
enumerableToIterableAdapter.First_Stub<T>();
}
[SecurityCritical]
static void WinRT_IList<T>(VectorToListAdapter vectorToListAdapter, VectorToCollectionAdapter vectorToCollectionAdapter, ListToVectorAdapter listToVectorAdapter, IVector<T> vector)
{
WinRT_IEnumerable<T>(null, null, null);
// instantiate stubs for commonly used methods on IList<T> and ICollection<T>
vectorToListAdapter.Indexer_Get<T>(0);
vectorToListAdapter.Indexer_Set<T>(0, default(T));
vectorToListAdapter.Insert<T>(0, default(T));
vectorToListAdapter.RemoveAt<T>(0);
vectorToCollectionAdapter.Count<T>();
vectorToCollectionAdapter.Add<T>(default(T));
vectorToCollectionAdapter.Clear<T>();
// instantiate stubs for commonly used methods on IVector<T>
listToVectorAdapter.GetAt<T>(0);
listToVectorAdapter.Size<T>();
listToVectorAdapter.SetAt<T>(0, default(T));
listToVectorAdapter.InsertAt<T>(0, default(T));
listToVectorAdapter.RemoveAt<T>(0);
listToVectorAdapter.Append<T>(default(T));
listToVectorAdapter.RemoveAtEnd<T>();
listToVectorAdapter.Clear<T>();
}
[SecurityCritical]
static void WinRT_IReadOnlyCollection<T>(VectorViewToReadOnlyCollectionAdapter vectorViewToReadOnlyCollectionAdapter)
{
WinRT_IEnumerable<T>(null, null, null);
// instantiate stubs for commonly used methods on IReadOnlyCollection<T>
vectorViewToReadOnlyCollectionAdapter.Count<T>();
}
[SecurityCritical]
static void WinRT_IReadOnlyList<T>(IVectorViewToIReadOnlyListAdapter vectorToListAdapter, IReadOnlyListToIVectorViewAdapter listToVectorAdapter, IVectorView<T> vectorView)
{
WinRT_IEnumerable<T>(null, null, null);
WinRT_IReadOnlyCollection<T>(null);
// instantiate stubs for commonly used methods on IReadOnlyList<T>
vectorToListAdapter.Indexer_Get<T>(0);
// instantiate stubs for commonly used methods on IVectorView<T>
listToVectorAdapter.GetAt<T>(0);
listToVectorAdapter.Size<T>();
}
[SecurityCritical]
static void WinRT_IDictionary<K, V>(MapToDictionaryAdapter mapToDictionaryAdapter, MapToCollectionAdapter mapToCollectionAdapter, DictionaryToMapAdapter dictionaryToMapAdapter, IMap<K, V> map)
{
WinRT_IEnumerable<KeyValuePair<K, V>>(null, null, null);
// instantiate stubs for commonly used methods on IDictionary<K, V> and ICollection<KeyValuePair<K, V>>
V dummy;
mapToDictionaryAdapter.Indexer_Get<K, V>(default(K));
mapToDictionaryAdapter.Indexer_Set<K, V>(default(K), default(V));
mapToDictionaryAdapter.ContainsKey<K, V>(default(K));
mapToDictionaryAdapter.Add<K, V>(default(K), default(V));
mapToDictionaryAdapter.Remove<K, V>(default(K));
mapToDictionaryAdapter.TryGetValue<K, V>(default(K), out dummy);
mapToCollectionAdapter.Count<K, V>();
mapToCollectionAdapter.Add<K, V>(new KeyValuePair<K, V>(default(K), default(V)));
mapToCollectionAdapter.Clear<K, V>();
// instantiate stubs for commonly used methods on IMap<K, V>
dictionaryToMapAdapter.Lookup<K, V>(default(K));
dictionaryToMapAdapter.Size<K, V>();
dictionaryToMapAdapter.HasKey<K, V>(default(K));
dictionaryToMapAdapter.Insert<K, V>(default(K), default(V));
dictionaryToMapAdapter.Remove<K, V>(default(K));
dictionaryToMapAdapter.Clear<K, V>();
}
[SecurityCritical]
static void WinRT_IReadOnlyDictionary<K, V>(IMapViewToIReadOnlyDictionaryAdapter mapToDictionaryAdapter, IReadOnlyDictionaryToIMapViewAdapter dictionaryToMapAdapter, IMapView<K, V> mapView, MapViewToReadOnlyCollectionAdapter mapViewToReadOnlyCollectionAdapter)
{
WinRT_IEnumerable<KeyValuePair<K, V>>(null, null, null);
WinRT_IReadOnlyCollection<KeyValuePair<K, V>>(null);
// instantiate stubs for commonly used methods on IReadOnlyDictionary<K, V>
V dummy;
mapToDictionaryAdapter.Indexer_Get<K, V>(default(K));
mapToDictionaryAdapter.ContainsKey<K, V>(default(K));
mapToDictionaryAdapter.TryGetValue<K, V>(default(K), out dummy);
// instantiate stubs for commonly used methods in IReadOnlyCollection<T>
mapViewToReadOnlyCollectionAdapter.Count<K, V>();
// instantiate stubs for commonly used methods on IMapView<K, V>
dictionaryToMapAdapter.Lookup<K, V>(default(K));
dictionaryToMapAdapter.Size<K, V>();
dictionaryToMapAdapter.HasKey<K, V>(default(K));
}
[SecurityCritical]
static void WinRT_Nullable<T>() where T : struct
{
Nullable<T> nullable = new Nullable<T>();
NullableMarshaler.ConvertToNative(ref nullable);
NullableMarshaler.ConvertToManagedRetVoid(IntPtr.Zero, ref nullable);
}
#endif // FEATURE_COMINTEROP
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Xunit;
using SetTriad = System.Tuple<System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>, bool>;
namespace System.Collections.Immutable.Tests
{
public abstract class ImmutableSetTest : ImmutablesTestBase
{
[Fact]
public void AddTest()
{
this.AddTestHelper(this.Empty<int>(), 3, 5, 4, 3);
}
[Fact]
public void AddDuplicatesTest()
{
var arrayWithDuplicates = Enumerable.Range(1, 100).Concat(Enumerable.Range(1, 100)).ToArray();
this.AddTestHelper(this.Empty<int>(), arrayWithDuplicates);
}
[Fact]
public void RemoveTest()
{
this.RemoveTestHelper(this.Empty<int>().Add(3).Add(5), 5, 3);
}
[Fact]
public void AddRemoveLoadTest()
{
var data = this.GenerateDummyFillData();
this.AddRemoveLoadTestHelper(Empty<double>(), data);
}
[Fact]
public void RemoveNonExistingTest()
{
this.RemoveNonExistingTest(this.Empty<int>());
}
[Fact]
public void AddBulkFromImmutableToEmpty()
{
var set = this.Empty<int>().Add(5);
var empty2 = this.Empty<int>();
Assert.Same(set, empty2.Union(set)); // "Filling an empty immutable set with the contents of another immutable set with the exact same comparer should return the other set."
}
[Fact]
public void ExceptTest()
{
this.ExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), 3, 7);
}
/// <summary>
/// Verifies that Except *does* enumerate its argument if the collection is empty.
/// </summary>
/// <remarks>
/// While this would seem an implementation detail and simply lack of an optimization,
/// it turns out that changing this behavior now *could* represent a breaking change
/// because if the enumerable were to throw an exception, that exception would be
/// observed previously, but would no longer be thrown if this behavior changed.
/// So this is a test to lock the behavior in place or be thoughtful if adding the optimization.
/// </remarks>
/// <seealso cref="ImmutableListTest.RemoveRangeDoesNotEnumerateSequenceIfThisIsEmpty"/>
[Fact]
public void ExceptDoesEnumerateSequenceIfThisIsEmpty()
{
bool enumerated = false;
Empty<int>().Except(Enumerable.Range(1, 1).Select(n => { enumerated = true; return n; }));
Assert.True(enumerated);
}
[Fact]
public void SymmetricExceptTest()
{
this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 9).ToArray());
this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 5).ToArray());
}
[Fact]
public void EnumeratorTest()
{
IComparer<double> comparer = null;
var set = this.Empty<double>();
var sortedSet = set as ISortKeyCollection<double>;
if (sortedSet != null)
{
comparer = sortedSet.KeyComparer;
}
this.EnumeratorTestHelper(set, comparer, 3, 5, 1);
double[] data = this.GenerateDummyFillData();
this.EnumeratorTestHelper(set, comparer, data);
}
[Fact]
public void IntersectTest()
{
this.IntersectTestHelper(Empty<int>().Union(Enumerable.Range(1, 10)), 8, 3, 5);
}
[Fact]
public void UnionTest()
{
this.UnionTestHelper(this.Empty<int>(), new[] { 1, 3, 5, 7 });
this.UnionTestHelper(this.Empty<int>().Union(new[] { 2, 4, 6 }), new[] { 1, 3, 5, 7 });
this.UnionTestHelper(this.Empty<int>().Union(new[] { 1, 2, 3 }), new int[0] { });
this.UnionTestHelper(this.Empty<int>().Union(new[] { 2 }), Enumerable.Range(0, 1000).ToArray());
}
[Fact]
public void SetEqualsTest()
{
Assert.True(this.Empty<int>().SetEquals(this.Empty<int>()));
var nonEmptySet = this.Empty<int>().Add(5);
Assert.True(nonEmptySet.SetEquals(nonEmptySet));
this.SetCompareTestHelper(s => s.SetEquals, s => s.SetEquals, this.GetSetEqualsScenarios());
}
[Fact]
public void IsProperSubsetOfTest()
{
this.SetCompareTestHelper(s => s.IsProperSubsetOf, s => s.IsProperSubsetOf, this.GetIsProperSubsetOfScenarios());
}
[Fact]
public void IsProperSupersetOfTest()
{
this.SetCompareTestHelper(s => s.IsProperSupersetOf, s => s.IsProperSupersetOf, this.GetIsProperSubsetOfScenarios().Select(Flip));
}
[Fact]
public void IsSubsetOfTest()
{
this.SetCompareTestHelper(s => s.IsSubsetOf, s => s.IsSubsetOf, this.GetIsSubsetOfScenarios());
}
[Fact]
public void IsSupersetOfTest()
{
this.SetCompareTestHelper(s => s.IsSupersetOf, s => s.IsSupersetOf, this.GetIsSubsetOfScenarios().Select(Flip));
}
[Fact]
public void OverlapsTest()
{
this.SetCompareTestHelper(s => s.Overlaps, s => s.Overlaps, this.GetOverlapsScenarios());
}
[Fact]
public void EqualsTest()
{
Assert.False(Empty<int>().Equals(null));
Assert.False(Empty<int>().Equals("hi"));
Assert.True(Empty<int>().Equals(Empty<int>()));
Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3)));
Assert.False(Empty<int>().Add(5).Equals(Empty<int>().Add(3)));
Assert.False(Empty<int>().Add(3).Add(5).Equals(Empty<int>().Add(3)));
Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3).Add(5)));
}
[Fact]
public void GetHashCodeTest()
{
// verify that get hash code is the default address based one.
Assert.Equal(EqualityComparer<object>.Default.GetHashCode(Empty<int>()), Empty<int>().GetHashCode());
}
[Fact]
public void ClearTest()
{
var originalSet = this.Empty<int>();
var nonEmptySet = originalSet.Add(5);
var clearedSet = nonEmptySet.Clear();
Assert.Same(originalSet, clearedSet);
}
[Fact]
public void ISetMutationMethods()
{
var set = (ISet<int>)this.Empty<int>();
Assert.Throws<NotSupportedException>(() => set.Add(0));
Assert.Throws<NotSupportedException>(() => set.ExceptWith(null));
Assert.Throws<NotSupportedException>(() => set.UnionWith(null));
Assert.Throws<NotSupportedException>(() => set.IntersectWith(null));
Assert.Throws<NotSupportedException>(() => set.SymmetricExceptWith(null));
}
[Fact]
public void ICollectionOfTMembers()
{
var set = (ICollection<int>)this.Empty<int>();
Assert.Throws<NotSupportedException>(() => set.Add(1));
Assert.Throws<NotSupportedException>(() => set.Clear());
Assert.Throws<NotSupportedException>(() => set.Remove(1));
Assert.True(set.IsReadOnly);
}
[Fact]
public void ICollectionMethods()
{
ICollection builder = (ICollection)this.Empty<string>();
string[] array = new string[0];
builder.CopyTo(array, 0);
builder = (ICollection)this.Empty<string>().Add("a");
array = new string[builder.Count + 1];
builder.CopyTo(array, 1);
Assert.Equal(new[] { null, "a" }, array);
Assert.True(builder.IsSynchronized);
Assert.NotNull(builder.SyncRoot);
Assert.Same(builder.SyncRoot, builder.SyncRoot);
}
protected abstract bool IncludesGetHashCodeDerivative { get; }
internal static List<T> ToListNonGeneric<T>(System.Collections.IEnumerable sequence)
{
Contract.Requires(sequence != null);
var list = new List<T>();
var enumerator = sequence.GetEnumerator();
while (enumerator.MoveNext())
{
list.Add((T)enumerator.Current);
}
return list;
}
protected abstract IImmutableSet<T> Empty<T>();
protected abstract ISet<T> EmptyMutable<T>();
internal abstract IBinaryTree GetRootNode<T>(IImmutableSet<T> set);
protected void TryGetValueTestHelper(IImmutableSet<string> set)
{
Requires.NotNull(set, "set");
string expected = "egg";
set = set.Add(expected);
string actual;
string lookupValue = expected.ToUpperInvariant();
Assert.True(set.TryGetValue(lookupValue, out actual));
Assert.Same(expected, actual);
Assert.False(set.TryGetValue("foo", out actual));
Assert.Equal("foo", actual);
Assert.False(set.Clear().TryGetValue("nonexistent", out actual));
Assert.Equal("nonexistent", actual);
}
protected IImmutableSet<T> SetWith<T>(params T[] items)
{
return this.Empty<T>().Union(items);
}
protected void CustomSortTestHelper<T>(IImmutableSet<T> emptySet, bool matchOrder, T[] injectedValues, T[] expectedValues)
{
Contract.Requires(emptySet != null);
Contract.Requires(injectedValues != null);
Contract.Requires(expectedValues != null);
var set = emptySet;
foreach (T value in injectedValues)
{
set = set.Add(value);
}
Assert.Equal(expectedValues.Length, set.Count);
if (matchOrder)
{
Assert.Equal<T>(expectedValues, set.ToList());
}
else
{
CollectionAssertAreEquivalent(expectedValues, set.ToList());
}
}
/// <summary>
/// Tests various aspects of a set. This should be called only from the unordered or sorted overloads of this method.
/// </summary>
/// <typeparam name="T">The type of element stored in the set.</typeparam>
/// <param name="emptySet">The empty set.</param>
protected void EmptyTestHelper<T>(IImmutableSet<T> emptySet)
{
Contract.Requires(emptySet != null);
Assert.Equal(0, emptySet.Count); //, "Empty set should have a Count of 0");
Assert.Equal(0, emptySet.Count()); //, "Enumeration of an empty set yielded elements.");
Assert.Same(emptySet, emptySet.Clear());
}
private IEnumerable<SetTriad> GetSetEqualsScenarios()
{
return new List<SetTriad>
{
new SetTriad(SetWith<int>(), new int[] { }, true),
new SetTriad(SetWith<int>(5), new int[] { 5 }, true),
new SetTriad(SetWith<int>(5), new int[] { 5, 5 }, true),
new SetTriad(SetWith<int>(5, 8), new int[] { 5, 5 }, false),
new SetTriad(SetWith<int>(5, 8), new int[] { 5, 7 }, false),
new SetTriad(SetWith<int>(5, 8), new int[] { 5, 8 }, true),
new SetTriad(SetWith<int>(5), new int[] { }, false),
new SetTriad(SetWith<int>(), new int[] { 5 }, false),
new SetTriad(SetWith<int>(5, 8), new int[] { 5 }, false),
new SetTriad(SetWith<int>(5), new int[] { 5, 8 }, false),
new SetTriad(SetWith<int>(5, 8), SetWith<int>(5, 8), true),
};
}
private IEnumerable<SetTriad> GetIsProperSubsetOfScenarios()
{
return new List<SetTriad>
{
new SetTriad(new int[] { }, new int[] { }, false),
new SetTriad(new int[] { 1 }, new int[] { }, false),
new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true),
new SetTriad(new int[] { }, new int[] { 1 }, true),
};
}
private IEnumerable<SetTriad> GetIsSubsetOfScenarios()
{
var results = new List<SetTriad>
{
new SetTriad(new int[] { }, new int[] { }, true),
new SetTriad(new int[] { 1 }, new int[] { 1 }, true),
new SetTriad(new int[] { 1, 2 }, new int[] { 1, 2 }, true),
new SetTriad(new int[] { 1 }, new int[] { }, false),
new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
};
// By definition, any proper subset is also a subset.
// But because a subset may not be a proper subset, we filter the proper- scenarios.
results.AddRange(this.GetIsProperSubsetOfScenarios().Where(s => s.Item3));
return results;
}
private IEnumerable<SetTriad> GetOverlapsScenarios()
{
return new List<SetTriad>
{
new SetTriad(new int[] { }, new int[] { }, false),
new SetTriad(new int[] { }, new int[] { 1 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
new SetTriad(new int[] { 1, 2 }, new int[] { 3 }, false),
new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true),
new SetTriad(new int[] { 1, 2 }, new int[] { 1 }, true),
new SetTriad(new int[] { 1 }, new int[] { 1 }, true),
new SetTriad(new int[] { 1, 2 }, new int[] { 2, 3, 4 }, true),
};
}
private void SetCompareTestHelper<T>(Func<IImmutableSet<T>, Func<IEnumerable<T>, bool>> operation, Func<ISet<T>, Func<IEnumerable<T>, bool>> baselineOperation, IEnumerable<Tuple<IEnumerable<T>, IEnumerable<T>, bool>> scenarios)
{
//const string message = "Scenario #{0}: Set 1: {1}, Set 2: {2}";
int iteration = 0;
foreach (var scenario in scenarios)
{
iteration++;
// Figure out the response expected based on the BCL mutable collections.
var baselineSet = this.EmptyMutable<T>();
baselineSet.UnionWith(scenario.Item1);
var expectedFunc = baselineOperation(baselineSet);
bool expected = expectedFunc(scenario.Item2);
Assert.Equal(expected, scenario.Item3); //, "Test scenario has an expected result that is inconsistent with BCL mutable collection behavior.");
var actualFunc = operation(this.SetWith(scenario.Item1.ToArray()));
var args = new object[] { iteration, ToStringDeferred(scenario.Item1), ToStringDeferred(scenario.Item2) };
Assert.Equal(scenario.Item3, actualFunc(this.SetWith(scenario.Item2.ToArray()))); //, message, args);
Assert.Equal(scenario.Item3, actualFunc(scenario.Item2)); //, message, args);
}
}
private static Tuple<IEnumerable<T>, IEnumerable<T>, bool> Flip<T>(Tuple<IEnumerable<T>, IEnumerable<T>, bool> scenario)
{
return new Tuple<IEnumerable<T>, IEnumerable<T>, bool>(scenario.Item2, scenario.Item1, scenario.Item3);
}
private void RemoveTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Contract.Requires(set != null);
Contract.Requires(values != null);
Assert.Same(set, set.Except(Enumerable.Empty<T>()));
int initialCount = set.Count;
int removedCount = 0;
foreach (T value in values)
{
var nextSet = set.Remove(value);
Assert.NotSame(set, nextSet);
Assert.Equal(initialCount - removedCount, set.Count);
Assert.Equal(initialCount - removedCount - 1, nextSet.Count);
Assert.Same(nextSet, nextSet.Remove(value)); //, "Removing a non-existing element should not change the set reference.");
removedCount++;
set = nextSet;
}
Assert.Equal(initialCount - removedCount, set.Count);
}
private void RemoveNonExistingTest(IImmutableSet<int> emptySet)
{
Assert.Same(emptySet, emptySet.Remove(5));
// Also fill up a set with many elements to build up the tree, then remove from various places in the tree.
const int Size = 200;
var set = emptySet;
for (int i = 0; i < Size; i += 2)
{ // only even numbers!
set = set.Add(i);
}
// Verify that removing odd numbers doesn't change anything.
for (int i = 1; i < Size; i += 2)
{
var setAfterRemoval = set.Remove(i);
Assert.Same(set, setAfterRemoval);
}
}
private void AddRemoveLoadTestHelper<T>(IImmutableSet<T> set, T[] data)
{
Contract.Requires(set != null);
Contract.Requires(data != null);
foreach (T value in data)
{
var newSet = set.Add(value);
Assert.NotSame(set, newSet);
set = newSet;
}
foreach (T value in data)
{
Assert.True(set.Contains(value));
}
foreach (T value in data)
{
var newSet = set.Remove(value);
Assert.NotSame(set, newSet);
set = newSet;
}
}
protected void EnumeratorTestHelper<T>(IImmutableSet<T> emptySet, IComparer<T> comparer, params T[] values)
{
var set = emptySet;
foreach (T value in values)
{
set = set.Add(value);
}
var nonGenericEnumerableList = ToListNonGeneric<T>(set);
CollectionAssertAreEquivalent(nonGenericEnumerableList, values);
var list = set.ToList();
CollectionAssertAreEquivalent(list, values);
if (comparer != null)
{
Array.Sort(values, comparer);
Assert.Equal<T>(values, list);
}
// Apply some less common uses to the enumerator to test its metal.
IEnumerator<T> enumerator;
using (enumerator = set.GetEnumerator())
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset(); // reset isn't usually called before MoveNext
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
ManuallyEnumerateTest(list, enumerator);
Assert.False(enumerator.MoveNext()); // call it again to make sure it still returns false
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
ManuallyEnumerateTest(list, enumerator);
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// this time only partially enumerate
enumerator.Reset();
enumerator.MoveNext();
enumerator.Reset();
ManuallyEnumerateTest(list, enumerator);
}
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
}
private void ExceptTestHelper<T>(IImmutableSet<T> set, params T[] valuesToRemove)
{
Contract.Requires(set != null);
Contract.Requires(valuesToRemove != null);
var expectedSet = new HashSet<T>(set);
expectedSet.ExceptWith(valuesToRemove);
var actualSet = set.Except(valuesToRemove);
CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
this.VerifyAvlTreeState(actualSet);
}
private void SymmetricExceptTestHelper<T>(IImmutableSet<T> set, params T[] otherCollection)
{
Contract.Requires(set != null);
Contract.Requires(otherCollection != null);
var expectedSet = new HashSet<T>(set);
expectedSet.SymmetricExceptWith(otherCollection);
var actualSet = set.SymmetricExcept(otherCollection);
CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
this.VerifyAvlTreeState(actualSet);
}
private void IntersectTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Contract.Requires(set != null);
Contract.Requires(values != null);
Assert.True(set.Intersect(Enumerable.Empty<T>()).Count == 0);
var expected = new HashSet<T>(set);
expected.IntersectWith(values);
var actual = set.Intersect(values);
CollectionAssertAreEquivalent(expected.ToList(), actual.ToList());
this.VerifyAvlTreeState(actual);
}
private void UnionTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Contract.Requires(set != null);
Contract.Requires(values != null);
var expected = new HashSet<T>(set);
expected.UnionWith(values);
var actual = set.Union(values);
CollectionAssertAreEquivalent(expected.ToList(), actual.ToList());
this.VerifyAvlTreeState(actual);
}
private void AddTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Contract.Requires(set != null);
Contract.Requires(values != null);
Assert.Same(set, set.Union(Enumerable.Empty<T>()));
int initialCount = set.Count;
var uniqueValues = new HashSet<T>(values);
var enumerateAddSet = set.Union(values);
Assert.Equal(initialCount + uniqueValues.Count, enumerateAddSet.Count);
foreach (T value in values)
{
Assert.True(enumerateAddSet.Contains(value));
}
int addedCount = 0;
foreach (T value in values)
{
bool duplicate = set.Contains(value);
var nextSet = set.Add(value);
Assert.True(nextSet.Count > 0);
Assert.Equal(initialCount + addedCount, set.Count);
int expectedCount = initialCount + addedCount;
if (!duplicate)
{
expectedCount++;
}
Assert.Equal(expectedCount, nextSet.Count);
Assert.Equal(duplicate, set.Contains(value));
Assert.True(nextSet.Contains(value));
if (!duplicate)
{
addedCount++;
}
// Next assert temporarily disabled because Roslyn's set doesn't follow this rule.
Assert.Same(nextSet, nextSet.Add(value)); //, "Adding duplicate value {0} should keep the original reference.", value);
set = nextSet;
}
}
private void VerifyAvlTreeState<T>(IImmutableSet<T> set)
{
var rootNode = this.GetRootNode(set);
rootNode.VerifyBalanced();
rootNode.VerifyHeightIsWithinTolerance(set.Count);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyComplex
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BasicOperations operations.
/// </summary>
public partial class BasicOperations : IServiceOperations<AutoRestComplexTestService>, IBasicOperations
{
/// <summary>
/// Initializes a new instance of the BasicOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BasicOperations(AutoRestComplexTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestComplexTestService
/// </summary>
public AutoRestComplexTestService Client { get; private set; }
/// <summary>
/// Get complex type {id: 2, name: 'abc', color: 'YELLOW'}
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Basic>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Please put {id: 2, name: 'abc', color: 'Magenta'}
/// </summary>
/// <param name='complexBody'>
/// Please put {id: 2, name: 'abc', color: 'Magenta'}
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Basic complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type that is invalid for the local strong type
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Basic>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/invalid").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type that is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Basic>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/empty").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type whose properties are null
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Basic>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/null").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a basic complex type while the server doesn't provide a response
/// payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Basic>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/notprovided").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Basic>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
Copyright 2012 Michael Edwards
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//-CRE-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Glass.Mapper.Pipelines.DataMapperResolver;
using Glass.Mapper.Sc.CastleWindsor;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Configuration.Attributes;
using Glass.Mapper.Sc.DataMappers;
using NUnit.Framework;
namespace Glass.Mapper.Sc.Integration.DataMappers
{
[TestFixture]
public class SitecoreQueryMapperFixture : AbstractMapperFixture
{
#region Property - ReadOnly
[Test]
public void ReadOnly_ReturnsTrue()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
//Act
var result = mapper.ReadOnly;
//Assert
Assert.IsTrue(result);
}
#endregion
#region Method - CanHandle
[Test]
public void CanHandle_CorrectConfigIEnumerableMappedClass_ReturnsTrue()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("StubMappeds");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_CorrectConfigIEnumerableNotMappedClass_ReturnsTrueOnDemand()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("StubNotMappeds");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_CorrectConfigNotMappedClass_ReturnsTrueOnDemand()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("StubNotMapped");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_CorrectConfigMappedClass_ReturnsFalse()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("StubMapped");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_IncorrectConfigMappedClass_ReturnsFalse()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("StubMapped");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsFalse(result);
}
#endregion
#region Method - MapToProperty
[Test]
public void MapToProperty_RelativeQuery_ReturnsNoResults()
{
//Assign
//Assign
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("StubMappeds");
config.Query = "../Results/DoesNotExist/*";
config.IsRelative = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Source");
var service = new SitecoreService(Database, context);
var result1 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result1");
var result2 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result2");
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(0, results.Count());
}
[Test]
public void MapToProperty_RelativeQuery_ReturnsResults()
{
//Assign
//Assign
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("StubMappeds");
config.Query = "../Results/*";
config.IsRelative = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Source");
var service = new SitecoreService(Database, context);
var result1 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result1");
var result2 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result2");
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
[Test]
public void MapToProperty_AbsoluteQuery_ReturnsResults()
{
//Assign
//Assign
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("StubMappeds");
config.Query = "/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/*";
config.IsRelative = false;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Source");
var service = new SitecoreService(Database, context);
var result1 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result1");
var result2 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result2");
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
[Test]
public void MapToProperty_RelativeQuery_ReturnsSingleResults()
{
//Assign
//Assign
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("StubMapped");
config.Query = "../Results/Result1";
config.IsRelative = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Source");
var service = new SitecoreService(Database, context);
var result1 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result1");
//Act
var result =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as StubMapped;
//Assert
Assert.AreEqual(result1.ID.Guid, result.Id);
}
[Test]
public void MapToProperty_AbsoluteQuery_ReturnsSingleResults()
{
//Assign
//Assign
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("StubMapped");
config.Query = "/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result1";
config.IsRelative = false;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Source");
var service = new SitecoreService(Database, context);
var result1 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result1");
//Act
var result =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as StubMapped;
//Assert
Assert.AreEqual(result1.ID.Guid, result.Id);
}
[Test]
public void MapToProperty_RelativeQueryWithQueryContext_ReturnsResults()
{
//Assign
//Assign
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "../Results/*";
config.IsRelative = true;
config.UseQueryContext = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Source");
var service = new SitecoreService(Database, context);
var result1 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result1");
var result2 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result2");
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
[Test]
public void MapToProperty_AbsoluteQueryWithQueryContext_ReturnsResults()
{
//Assign
//Assign
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("StubMappeds");
config.Query = "/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/*";
config.IsRelative = false;
config.UseQueryContext = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Source");
var service = new SitecoreService(Database, context);
var result1 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result1");
var result2 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result2");
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
[Test]
public void MapToProperty_AbsoluteQueryWithParameter_ReturnsResults()
{
//Assign
//Assign
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof (StubClass).GetProperty("StubMappeds");
config.Query = "{path}/../Results/*";
config.IsRelative = false;
config.UseQueryContext = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Source");
var service = new SitecoreService(Database, context);
var result1 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result1");
var result2 = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreQueryMapper/Results/Result2");
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service)) as IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
#endregion
#region Stubs
[SitecoreType]
public class StubMapped
{
[SitecoreId]
public virtual Guid Id { get; set; }
}
public class StubNotMapped { }
public class StubClass
{
public IEnumerable<StubMapped> StubMappeds { get; set; }
public IEnumerable<StubNotMapped> StubNotMappeds { get; set; }
public StubMapped StubMapped { get; set; }
public StubNotMapped StubNotMapped { get; set; }
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets.Wrappers
{
using System;
using System.ComponentModel;
using System.Threading;
using Common;
using Internal;
/// <summary>
/// A target that buffers log events and sends them in batches to the wrapped target.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/BufferingWrapper-target">Documentation on NLog Wiki</seealso>
[Target("BufferingWrapper", IsWrapper = true)]
public class BufferingTargetWrapper : WrapperTargetBase
{
private LogEventInfoBuffer _buffer;
private Timer _flushTimer;
private readonly object _lockObject = new object();
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
public BufferingTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
/// <param name="wrappedTarget">The wrapped target.</param>
public BufferingTargetWrapper(string name, Target wrappedTarget)
: this(wrappedTarget)
{
Name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public BufferingTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 100)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="bufferSize">Size of the buffer.</param>
public BufferingTargetWrapper(Target wrappedTarget, int bufferSize)
: this(wrappedTarget, bufferSize, -1)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="bufferSize">Size of the buffer.</param>
/// <param name="flushTimeout">The flush timeout.</param>
public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout)
: this(wrappedTarget, bufferSize, flushTimeout, BufferingTargetWrapperOverflowAction.Flush)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="bufferSize">Size of the buffer.</param>
/// <param name="flushTimeout">The flush timeout.</param>
/// <param name="overflowAction">The aciton to take when the buffer overflows.</param>
public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout, BufferingTargetWrapperOverflowAction overflowAction)
{
WrappedTarget = wrappedTarget;
BufferSize = bufferSize;
FlushTimeout = flushTimeout;
SlidingTimeout = true;
OverflowAction = overflowAction;
}
/// <summary>
/// Gets or sets the number of log events to be buffered.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(100)]
public int BufferSize { get; set; }
/// <summary>
/// Gets or sets the timeout (in milliseconds) after which the contents of buffer will be flushed
/// if there's no write in the specified period of time. Use -1 to disable timed flushes.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(-1)]
public int FlushTimeout { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use sliding timeout.
/// </summary>
/// <remarks>
/// This value determines how the inactivity period is determined. If sliding timeout is enabled,
/// the inactivity timer is reset after each write, if it is disabled - inactivity timer will
/// count from the first event written to the buffer.
/// </remarks>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(true)]
public bool SlidingTimeout { get; set; }
/// <summary>
/// Gets or sets the action to take if the buffer overflows.
/// </summary>
/// <remarks>
/// Setting to <see cref="BufferingTargetWrapperOverflowAction.Discard"/> will replace the
/// oldest event with new events without sending events down to the wrapped target, and
/// setting to <see cref="BufferingTargetWrapperOverflowAction.Flush"/> will flush the
/// entire buffer to the wrapped target.
/// </remarks>
[DefaultValue("Flush")]
public BufferingTargetWrapperOverflowAction OverflowAction { get; set; }
/// <summary>
/// Flushes pending events in the buffer (if any), followed by flushing the WrappedTarget.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
WriteEventsInBuffer("Flush Async");
base.FlushAsync(asyncContinuation);
}
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
_buffer = new LogEventInfoBuffer(BufferSize, false, 0);
InternalLogger.Trace("BufferingWrapper '{0}': create timer", Name);
_flushTimer = new Timer(FlushCallback, null, Timeout.Infinite, Timeout.Infinite);
}
/// <summary>
/// Closes the target by flushing pending events in the buffer (if any).
/// </summary>
protected override void CloseTarget()
{
var currentTimer = _flushTimer;
if (currentTimer != null)
{
_flushTimer = null;
if (currentTimer.WaitForDispose(TimeSpan.FromSeconds(1)))
{
lock (_lockObject)
{
WriteEventsInBuffer("Closing Target");
}
}
}
base.CloseTarget();
}
/// <summary>
/// Adds the specified log event to the buffer and flushes
/// the buffer in case the buffer gets full.
/// </summary>
/// <param name="logEvent">The log event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
MergeEventProperties(logEvent.LogEvent);
PrecalculateVolatileLayouts(logEvent.LogEvent);
int count = _buffer.Append(logEvent);
if (count >= BufferSize)
{
// If the OverflowAction action is set to "Discard", the buffer will automatically
// roll over the oldest item.
if (OverflowAction == BufferingTargetWrapperOverflowAction.Flush)
{
WriteEventsInBuffer("Exceeding BufferSize");
}
}
else
{
if (FlushTimeout > 0)
{
// reset the timer on first item added to the buffer or whenever SlidingTimeout is set to true
if (SlidingTimeout || count == 1)
{
_flushTimer.Change(FlushTimeout, -1);
}
}
}
}
private void FlushCallback(object state)
{
try
{
lock (_lockObject)
{
if (_flushTimer == null)
return;
WriteEventsInBuffer(null);
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "BufferingWrapper '{0}': Error in flush procedure.", Name);
if (exception.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
}
}
private void WriteEventsInBuffer(string reason)
{
if (WrappedTarget == null)
{
InternalLogger.Error("BufferingWrapper '{0}': WrappedTarget is NULL", Name);
return;
}
lock (_lockObject)
{
AsyncLogEventInfo[] logEvents = _buffer.GetEventsAndClear();
if (logEvents.Length > 0)
{
if (reason != null)
InternalLogger.Trace("BufferingWrapper '{0}': writing {1} events ({2})", Name, logEvents.Length, reason);
WrappedTarget.WriteAsyncLogEvents(logEvents);
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.