context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// <copyright file="IEnumerableExtensions.SequenceEquals.StandardTypes.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace IX.StandardExtensions.Extensions;
/// <summary>
/// Extensions for IEnumerable.
/// </summary>
[SuppressMessage(
"ReSharper",
"InconsistentNaming",
Justification = "These are extensions for IEnumerable, so we must allow this.")]
public static partial class IEnumerableExtensions
{
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<byte>? left, IEnumerable<byte>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<byte> e1 = left.GetEnumerator();
using IEnumerator<byte> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<sbyte>? left, IEnumerable<sbyte>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<sbyte> e1 = left.GetEnumerator();
using IEnumerator<sbyte> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<short>? left, IEnumerable<short>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<short> e1 = left.GetEnumerator();
using IEnumerator<short> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<ushort>? left, IEnumerable<ushort>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<ushort> e1 = left.GetEnumerator();
using IEnumerator<ushort> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<char>? left, IEnumerable<char>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<char> e1 = left.GetEnumerator();
using IEnumerator<char> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<int>? left, IEnumerable<int>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<int> e1 = left.GetEnumerator();
using IEnumerator<int> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<uint>? left, IEnumerable<uint>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<uint> e1 = left.GetEnumerator();
using IEnumerator<uint> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<long>? left, IEnumerable<long>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<long> e1 = left.GetEnumerator();
using IEnumerator<long> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<ulong>? left, IEnumerable<ulong>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<ulong> e1 = left.GetEnumerator();
using IEnumerator<ulong> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<float>? left, IEnumerable<float>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<float> e1 = left.GetEnumerator();
using IEnumerator<float> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<double>? left, IEnumerable<double>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<double> e1 = left.GetEnumerator();
using IEnumerator<double> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<decimal>? left, IEnumerable<decimal>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<decimal> e1 = left.GetEnumerator();
using IEnumerator<decimal> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<DateTime>? left, IEnumerable<DateTime>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<DateTime> e1 = left.GetEnumerator();
using IEnumerator<DateTime> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<bool>? left, IEnumerable<bool>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<bool> e1 = left.GetEnumerator();
using IEnumerator<bool> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<TimeSpan>? left, IEnumerable<TimeSpan>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<TimeSpan> e1 = left.GetEnumerator();
using IEnumerator<TimeSpan> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
/// <summary>
/// Determines whether two enumerable objects have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand enumerable.</param>
/// <param name="right">The right operand enumerable.</param>
/// <returns><see langword="true"/> if the two enumerable objects have the same length and each element at each position
/// in one enumerable is equal to the equivalent in the other, <see langword="false"/> otherwise.</returns>
public static bool SequenceEquals(this IEnumerable<string>? left, IEnumerable<string>? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
using IEnumerator<string> e1 = left.GetEnumerator();
using IEnumerator<string> e2 = right.GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
if (b1 != b2)
{
return false;
}
if (b1)
{
if (e1.Current != e2.Current)
{
return false;
}
}
else
{
return true;
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Provides access to all native methods provided by <c>NativeExtension</c>.
/// An extra level of indirection is added to P/Invoke calls to allow intelligent loading
/// of the right configuration of the native extension based on current platform, architecture etc.
/// </summary>
internal class NativeMethods
{
#region Native methods
public readonly Delegates.grpcsharp_init_delegate grpcsharp_init;
public readonly Delegates.grpcsharp_shutdown_delegate grpcsharp_shutdown;
public readonly Delegates.grpcsharp_version_string_delegate grpcsharp_version_string;
public readonly Delegates.grpcsharp_batch_context_create_delegate grpcsharp_batch_context_create;
public readonly Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate grpcsharp_batch_context_recv_initial_metadata;
public readonly Delegates.grpcsharp_batch_context_recv_message_length_delegate grpcsharp_batch_context_recv_message_length;
public readonly Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate grpcsharp_batch_context_recv_message_to_buffer;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate grpcsharp_batch_context_recv_status_on_client_status;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate grpcsharp_batch_context_recv_status_on_client_details;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate grpcsharp_batch_context_recv_status_on_client_trailing_metadata;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_call_delegate grpcsharp_batch_context_server_rpc_new_call;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_method_delegate grpcsharp_batch_context_server_rpc_new_method;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_host_delegate grpcsharp_batch_context_server_rpc_new_host;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_deadline_delegate grpcsharp_batch_context_server_rpc_new_deadline;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_request_metadata_delegate grpcsharp_batch_context_server_rpc_new_request_metadata;
public readonly Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate grpcsharp_batch_context_recv_close_on_server_cancelled;
public readonly Delegates.grpcsharp_batch_context_destroy_delegate grpcsharp_batch_context_destroy;
public readonly Delegates.grpcsharp_composite_call_credentials_create_delegate grpcsharp_composite_call_credentials_create;
public readonly Delegates.grpcsharp_call_credentials_release_delegate grpcsharp_call_credentials_release;
public readonly Delegates.grpcsharp_call_cancel_delegate grpcsharp_call_cancel;
public readonly Delegates.grpcsharp_call_cancel_with_status_delegate grpcsharp_call_cancel_with_status;
public readonly Delegates.grpcsharp_call_start_unary_delegate grpcsharp_call_start_unary;
public readonly Delegates.grpcsharp_call_start_client_streaming_delegate grpcsharp_call_start_client_streaming;
public readonly Delegates.grpcsharp_call_start_server_streaming_delegate grpcsharp_call_start_server_streaming;
public readonly Delegates.grpcsharp_call_start_duplex_streaming_delegate grpcsharp_call_start_duplex_streaming;
public readonly Delegates.grpcsharp_call_send_message_delegate grpcsharp_call_send_message;
public readonly Delegates.grpcsharp_call_send_close_from_client_delegate grpcsharp_call_send_close_from_client;
public readonly Delegates.grpcsharp_call_send_status_from_server_delegate grpcsharp_call_send_status_from_server;
public readonly Delegates.grpcsharp_call_recv_message_delegate grpcsharp_call_recv_message;
public readonly Delegates.grpcsharp_call_recv_initial_metadata_delegate grpcsharp_call_recv_initial_metadata;
public readonly Delegates.grpcsharp_call_start_serverside_delegate grpcsharp_call_start_serverside;
public readonly Delegates.grpcsharp_call_send_initial_metadata_delegate grpcsharp_call_send_initial_metadata;
public readonly Delegates.grpcsharp_call_set_credentials_delegate grpcsharp_call_set_credentials;
public readonly Delegates.grpcsharp_call_get_peer_delegate grpcsharp_call_get_peer;
public readonly Delegates.grpcsharp_call_destroy_delegate grpcsharp_call_destroy;
public readonly Delegates.grpcsharp_channel_args_create_delegate grpcsharp_channel_args_create;
public readonly Delegates.grpcsharp_channel_args_set_string_delegate grpcsharp_channel_args_set_string;
public readonly Delegates.grpcsharp_channel_args_set_integer_delegate grpcsharp_channel_args_set_integer;
public readonly Delegates.grpcsharp_channel_args_destroy_delegate grpcsharp_channel_args_destroy;
public readonly Delegates.grpcsharp_override_default_ssl_roots grpcsharp_override_default_ssl_roots;
public readonly Delegates.grpcsharp_ssl_credentials_create_delegate grpcsharp_ssl_credentials_create;
public readonly Delegates.grpcsharp_composite_channel_credentials_create_delegate grpcsharp_composite_channel_credentials_create;
public readonly Delegates.grpcsharp_channel_credentials_release_delegate grpcsharp_channel_credentials_release;
public readonly Delegates.grpcsharp_insecure_channel_create_delegate grpcsharp_insecure_channel_create;
public readonly Delegates.grpcsharp_secure_channel_create_delegate grpcsharp_secure_channel_create;
public readonly Delegates.grpcsharp_channel_create_call_delegate grpcsharp_channel_create_call;
public readonly Delegates.grpcsharp_channel_check_connectivity_state_delegate grpcsharp_channel_check_connectivity_state;
public readonly Delegates.grpcsharp_channel_watch_connectivity_state_delegate grpcsharp_channel_watch_connectivity_state;
public readonly Delegates.grpcsharp_channel_get_target_delegate grpcsharp_channel_get_target;
public readonly Delegates.grpcsharp_channel_destroy_delegate grpcsharp_channel_destroy;
public readonly Delegates.grpcsharp_sizeof_grpc_event_delegate grpcsharp_sizeof_grpc_event;
public readonly Delegates.grpcsharp_completion_queue_create_delegate grpcsharp_completion_queue_create;
public readonly Delegates.grpcsharp_completion_queue_shutdown_delegate grpcsharp_completion_queue_shutdown;
public readonly Delegates.grpcsharp_completion_queue_next_delegate grpcsharp_completion_queue_next;
public readonly Delegates.grpcsharp_completion_queue_pluck_delegate grpcsharp_completion_queue_pluck;
public readonly Delegates.grpcsharp_completion_queue_destroy_delegate grpcsharp_completion_queue_destroy;
public readonly Delegates.gprsharp_free_delegate gprsharp_free;
public readonly Delegates.grpcsharp_metadata_array_create_delegate grpcsharp_metadata_array_create;
public readonly Delegates.grpcsharp_metadata_array_add_delegate grpcsharp_metadata_array_add;
public readonly Delegates.grpcsharp_metadata_array_count_delegate grpcsharp_metadata_array_count;
public readonly Delegates.grpcsharp_metadata_array_get_key_delegate grpcsharp_metadata_array_get_key;
public readonly Delegates.grpcsharp_metadata_array_get_value_delegate grpcsharp_metadata_array_get_value;
public readonly Delegates.grpcsharp_metadata_array_get_value_length_delegate grpcsharp_metadata_array_get_value_length;
public readonly Delegates.grpcsharp_metadata_array_destroy_full_delegate grpcsharp_metadata_array_destroy_full;
public readonly Delegates.grpcsharp_redirect_log_delegate grpcsharp_redirect_log;
public readonly Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate grpcsharp_metadata_credentials_create_from_plugin;
public readonly Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate grpcsharp_metadata_credentials_notify_from_plugin;
public readonly Delegates.grpcsharp_ssl_server_credentials_create_delegate grpcsharp_ssl_server_credentials_create;
public readonly Delegates.grpcsharp_server_credentials_release_delegate grpcsharp_server_credentials_release;
public readonly Delegates.grpcsharp_server_create_delegate grpcsharp_server_create;
public readonly Delegates.grpcsharp_server_add_insecure_http2_port_delegate grpcsharp_server_add_insecure_http2_port;
public readonly Delegates.grpcsharp_server_add_secure_http2_port_delegate grpcsharp_server_add_secure_http2_port;
public readonly Delegates.grpcsharp_server_start_delegate grpcsharp_server_start;
public readonly Delegates.grpcsharp_server_request_call_delegate grpcsharp_server_request_call;
public readonly Delegates.grpcsharp_server_cancel_all_calls_delegate grpcsharp_server_cancel_all_calls;
public readonly Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate grpcsharp_server_shutdown_and_notify_callback;
public readonly Delegates.grpcsharp_server_destroy_delegate grpcsharp_server_destroy;
public readonly Delegates.gprsharp_now_delegate gprsharp_now;
public readonly Delegates.gprsharp_inf_future_delegate gprsharp_inf_future;
public readonly Delegates.gprsharp_inf_past_delegate gprsharp_inf_past;
public readonly Delegates.gprsharp_convert_clock_type_delegate gprsharp_convert_clock_type;
public readonly Delegates.gprsharp_sizeof_timespec_delegate gprsharp_sizeof_timespec;
public readonly Delegates.grpcsharp_test_callback_delegate grpcsharp_test_callback;
public readonly Delegates.grpcsharp_test_nop_delegate grpcsharp_test_nop;
#endregion
public NativeMethods(UnmanagedLibrary library)
{
if (PlatformApis.IsLinux || PlatformApis.IsMacOSX)
{
this.grpcsharp_init = GetMethodDelegate<Delegates.grpcsharp_init_delegate>(library);
this.grpcsharp_shutdown = GetMethodDelegate<Delegates.grpcsharp_shutdown_delegate>(library);
this.grpcsharp_version_string = GetMethodDelegate<Delegates.grpcsharp_version_string_delegate>(library);
this.grpcsharp_batch_context_create = GetMethodDelegate<Delegates.grpcsharp_batch_context_create_delegate>(library);
this.grpcsharp_batch_context_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate>(library);
this.grpcsharp_batch_context_recv_message_length = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_length_delegate>(library);
this.grpcsharp_batch_context_recv_message_to_buffer = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_status = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_details = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_call = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_call_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_method = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_method_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_host = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_host_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_deadline = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_deadline_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_request_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_request_metadata_delegate>(library);
this.grpcsharp_batch_context_recv_close_on_server_cancelled = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate>(library);
this.grpcsharp_batch_context_destroy = GetMethodDelegate<Delegates.grpcsharp_batch_context_destroy_delegate>(library);
this.grpcsharp_composite_call_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_call_credentials_create_delegate>(library);
this.grpcsharp_call_credentials_release = GetMethodDelegate<Delegates.grpcsharp_call_credentials_release_delegate>(library);
this.grpcsharp_call_cancel = GetMethodDelegate<Delegates.grpcsharp_call_cancel_delegate>(library);
this.grpcsharp_call_cancel_with_status = GetMethodDelegate<Delegates.grpcsharp_call_cancel_with_status_delegate>(library);
this.grpcsharp_call_start_unary = GetMethodDelegate<Delegates.grpcsharp_call_start_unary_delegate>(library);
this.grpcsharp_call_start_client_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_client_streaming_delegate>(library);
this.grpcsharp_call_start_server_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_server_streaming_delegate>(library);
this.grpcsharp_call_start_duplex_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_duplex_streaming_delegate>(library);
this.grpcsharp_call_send_message = GetMethodDelegate<Delegates.grpcsharp_call_send_message_delegate>(library);
this.grpcsharp_call_send_close_from_client = GetMethodDelegate<Delegates.grpcsharp_call_send_close_from_client_delegate>(library);
this.grpcsharp_call_send_status_from_server = GetMethodDelegate<Delegates.grpcsharp_call_send_status_from_server_delegate>(library);
this.grpcsharp_call_recv_message = GetMethodDelegate<Delegates.grpcsharp_call_recv_message_delegate>(library);
this.grpcsharp_call_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_recv_initial_metadata_delegate>(library);
this.grpcsharp_call_start_serverside = GetMethodDelegate<Delegates.grpcsharp_call_start_serverside_delegate>(library);
this.grpcsharp_call_send_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_send_initial_metadata_delegate>(library);
this.grpcsharp_call_set_credentials = GetMethodDelegate<Delegates.grpcsharp_call_set_credentials_delegate>(library);
this.grpcsharp_call_get_peer = GetMethodDelegate<Delegates.grpcsharp_call_get_peer_delegate>(library);
this.grpcsharp_call_destroy = GetMethodDelegate<Delegates.grpcsharp_call_destroy_delegate>(library);
this.grpcsharp_channel_args_create = GetMethodDelegate<Delegates.grpcsharp_channel_args_create_delegate>(library);
this.grpcsharp_channel_args_set_string = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_string_delegate>(library);
this.grpcsharp_channel_args_set_integer = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_integer_delegate>(library);
this.grpcsharp_channel_args_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_args_destroy_delegate>(library);
this.grpcsharp_override_default_ssl_roots = GetMethodDelegate<Delegates.grpcsharp_override_default_ssl_roots>(library);
this.grpcsharp_ssl_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_credentials_create_delegate>(library);
this.grpcsharp_composite_channel_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_channel_credentials_create_delegate>(library);
this.grpcsharp_channel_credentials_release = GetMethodDelegate<Delegates.grpcsharp_channel_credentials_release_delegate>(library);
this.grpcsharp_insecure_channel_create = GetMethodDelegate<Delegates.grpcsharp_insecure_channel_create_delegate>(library);
this.grpcsharp_secure_channel_create = GetMethodDelegate<Delegates.grpcsharp_secure_channel_create_delegate>(library);
this.grpcsharp_channel_create_call = GetMethodDelegate<Delegates.grpcsharp_channel_create_call_delegate>(library);
this.grpcsharp_channel_check_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_check_connectivity_state_delegate>(library);
this.grpcsharp_channel_watch_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_watch_connectivity_state_delegate>(library);
this.grpcsharp_channel_get_target = GetMethodDelegate<Delegates.grpcsharp_channel_get_target_delegate>(library);
this.grpcsharp_channel_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_destroy_delegate>(library);
this.grpcsharp_sizeof_grpc_event = GetMethodDelegate<Delegates.grpcsharp_sizeof_grpc_event_delegate>(library);
this.grpcsharp_completion_queue_create = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_delegate>(library);
this.grpcsharp_completion_queue_shutdown = GetMethodDelegate<Delegates.grpcsharp_completion_queue_shutdown_delegate>(library);
this.grpcsharp_completion_queue_next = GetMethodDelegate<Delegates.grpcsharp_completion_queue_next_delegate>(library);
this.grpcsharp_completion_queue_pluck = GetMethodDelegate<Delegates.grpcsharp_completion_queue_pluck_delegate>(library);
this.grpcsharp_completion_queue_destroy = GetMethodDelegate<Delegates.grpcsharp_completion_queue_destroy_delegate>(library);
this.gprsharp_free = GetMethodDelegate<Delegates.gprsharp_free_delegate>(library);
this.grpcsharp_metadata_array_create = GetMethodDelegate<Delegates.grpcsharp_metadata_array_create_delegate>(library);
this.grpcsharp_metadata_array_add = GetMethodDelegate<Delegates.grpcsharp_metadata_array_add_delegate>(library);
this.grpcsharp_metadata_array_count = GetMethodDelegate<Delegates.grpcsharp_metadata_array_count_delegate>(library);
this.grpcsharp_metadata_array_get_key = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_key_delegate>(library);
this.grpcsharp_metadata_array_get_value = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_value_delegate>(library);
this.grpcsharp_metadata_array_get_value_length = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_value_length_delegate>(library);
this.grpcsharp_metadata_array_destroy_full = GetMethodDelegate<Delegates.grpcsharp_metadata_array_destroy_full_delegate>(library);
this.grpcsharp_redirect_log = GetMethodDelegate<Delegates.grpcsharp_redirect_log_delegate>(library);
this.grpcsharp_metadata_credentials_create_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate>(library);
this.grpcsharp_metadata_credentials_notify_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate>(library);
this.grpcsharp_ssl_server_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_server_credentials_create_delegate>(library);
this.grpcsharp_server_credentials_release = GetMethodDelegate<Delegates.grpcsharp_server_credentials_release_delegate>(library);
this.grpcsharp_server_create = GetMethodDelegate<Delegates.grpcsharp_server_create_delegate>(library);
this.grpcsharp_server_add_insecure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_insecure_http2_port_delegate>(library);
this.grpcsharp_server_add_secure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_secure_http2_port_delegate>(library);
this.grpcsharp_server_start = GetMethodDelegate<Delegates.grpcsharp_server_start_delegate>(library);
this.grpcsharp_server_request_call = GetMethodDelegate<Delegates.grpcsharp_server_request_call_delegate>(library);
this.grpcsharp_server_cancel_all_calls = GetMethodDelegate<Delegates.grpcsharp_server_cancel_all_calls_delegate>(library);
this.grpcsharp_server_shutdown_and_notify_callback = GetMethodDelegate<Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate>(library);
this.grpcsharp_server_destroy = GetMethodDelegate<Delegates.grpcsharp_server_destroy_delegate>(library);
this.gprsharp_now = GetMethodDelegate<Delegates.gprsharp_now_delegate>(library);
this.gprsharp_inf_future = GetMethodDelegate<Delegates.gprsharp_inf_future_delegate>(library);
this.gprsharp_inf_past = GetMethodDelegate<Delegates.gprsharp_inf_past_delegate>(library);
this.gprsharp_convert_clock_type = GetMethodDelegate<Delegates.gprsharp_convert_clock_type_delegate>(library);
this.gprsharp_sizeof_timespec = GetMethodDelegate<Delegates.gprsharp_sizeof_timespec_delegate>(library);
this.grpcsharp_test_callback = GetMethodDelegate<Delegates.grpcsharp_test_callback_delegate>(library);
this.grpcsharp_test_nop = GetMethodDelegate<Delegates.grpcsharp_test_nop_delegate>(library);
}
else
{
// Windows or fallback
this.grpcsharp_init = PInvokeMethods.grpcsharp_init;
this.grpcsharp_shutdown = PInvokeMethods.grpcsharp_shutdown;
this.grpcsharp_version_string = PInvokeMethods.grpcsharp_version_string;
this.grpcsharp_batch_context_create = PInvokeMethods.grpcsharp_batch_context_create;
this.grpcsharp_batch_context_recv_initial_metadata = PInvokeMethods.grpcsharp_batch_context_recv_initial_metadata;
this.grpcsharp_batch_context_recv_message_length = PInvokeMethods.grpcsharp_batch_context_recv_message_length;
this.grpcsharp_batch_context_recv_message_to_buffer = PInvokeMethods.grpcsharp_batch_context_recv_message_to_buffer;
this.grpcsharp_batch_context_recv_status_on_client_status = PInvokeMethods.grpcsharp_batch_context_recv_status_on_client_status;
this.grpcsharp_batch_context_recv_status_on_client_details = PInvokeMethods.grpcsharp_batch_context_recv_status_on_client_details;
this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = PInvokeMethods.grpcsharp_batch_context_recv_status_on_client_trailing_metadata;
this.grpcsharp_batch_context_server_rpc_new_call = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_call;
this.grpcsharp_batch_context_server_rpc_new_method = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_method;
this.grpcsharp_batch_context_server_rpc_new_host = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_host;
this.grpcsharp_batch_context_server_rpc_new_deadline = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_deadline;
this.grpcsharp_batch_context_server_rpc_new_request_metadata = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_request_metadata;
this.grpcsharp_batch_context_recv_close_on_server_cancelled = PInvokeMethods.grpcsharp_batch_context_recv_close_on_server_cancelled;
this.grpcsharp_batch_context_destroy = PInvokeMethods.grpcsharp_batch_context_destroy;
this.grpcsharp_composite_call_credentials_create = PInvokeMethods.grpcsharp_composite_call_credentials_create;
this.grpcsharp_call_credentials_release = PInvokeMethods.grpcsharp_call_credentials_release;
this.grpcsharp_call_cancel = PInvokeMethods.grpcsharp_call_cancel;
this.grpcsharp_call_cancel_with_status = PInvokeMethods.grpcsharp_call_cancel_with_status;
this.grpcsharp_call_start_unary = PInvokeMethods.grpcsharp_call_start_unary;
this.grpcsharp_call_start_client_streaming = PInvokeMethods.grpcsharp_call_start_client_streaming;
this.grpcsharp_call_start_server_streaming = PInvokeMethods.grpcsharp_call_start_server_streaming;
this.grpcsharp_call_start_duplex_streaming = PInvokeMethods.grpcsharp_call_start_duplex_streaming;
this.grpcsharp_call_send_message = PInvokeMethods.grpcsharp_call_send_message;
this.grpcsharp_call_send_close_from_client = PInvokeMethods.grpcsharp_call_send_close_from_client;
this.grpcsharp_call_send_status_from_server = PInvokeMethods.grpcsharp_call_send_status_from_server;
this.grpcsharp_call_recv_message = PInvokeMethods.grpcsharp_call_recv_message;
this.grpcsharp_call_recv_initial_metadata = PInvokeMethods.grpcsharp_call_recv_initial_metadata;
this.grpcsharp_call_start_serverside = PInvokeMethods.grpcsharp_call_start_serverside;
this.grpcsharp_call_send_initial_metadata = PInvokeMethods.grpcsharp_call_send_initial_metadata;
this.grpcsharp_call_set_credentials = PInvokeMethods.grpcsharp_call_set_credentials;
this.grpcsharp_call_get_peer = PInvokeMethods.grpcsharp_call_get_peer;
this.grpcsharp_call_destroy = PInvokeMethods.grpcsharp_call_destroy;
this.grpcsharp_channel_args_create = PInvokeMethods.grpcsharp_channel_args_create;
this.grpcsharp_channel_args_set_string = PInvokeMethods.grpcsharp_channel_args_set_string;
this.grpcsharp_channel_args_set_integer = PInvokeMethods.grpcsharp_channel_args_set_integer;
this.grpcsharp_channel_args_destroy = PInvokeMethods.grpcsharp_channel_args_destroy;
this.grpcsharp_override_default_ssl_roots = PInvokeMethods.grpcsharp_override_default_ssl_roots;
this.grpcsharp_ssl_credentials_create = PInvokeMethods.grpcsharp_ssl_credentials_create;
this.grpcsharp_composite_channel_credentials_create = PInvokeMethods.grpcsharp_composite_channel_credentials_create;
this.grpcsharp_channel_credentials_release = PInvokeMethods.grpcsharp_channel_credentials_release;
this.grpcsharp_insecure_channel_create = PInvokeMethods.grpcsharp_insecure_channel_create;
this.grpcsharp_secure_channel_create = PInvokeMethods.grpcsharp_secure_channel_create;
this.grpcsharp_channel_create_call = PInvokeMethods.grpcsharp_channel_create_call;
this.grpcsharp_channel_check_connectivity_state = PInvokeMethods.grpcsharp_channel_check_connectivity_state;
this.grpcsharp_channel_watch_connectivity_state = PInvokeMethods.grpcsharp_channel_watch_connectivity_state;
this.grpcsharp_channel_get_target = PInvokeMethods.grpcsharp_channel_get_target;
this.grpcsharp_channel_destroy = PInvokeMethods.grpcsharp_channel_destroy;
this.grpcsharp_sizeof_grpc_event = PInvokeMethods.grpcsharp_sizeof_grpc_event;
this.grpcsharp_completion_queue_create = PInvokeMethods.grpcsharp_completion_queue_create;
this.grpcsharp_completion_queue_shutdown = PInvokeMethods.grpcsharp_completion_queue_shutdown;
this.grpcsharp_completion_queue_next = PInvokeMethods.grpcsharp_completion_queue_next;
this.grpcsharp_completion_queue_pluck = PInvokeMethods.grpcsharp_completion_queue_pluck;
this.grpcsharp_completion_queue_destroy = PInvokeMethods.grpcsharp_completion_queue_destroy;
this.gprsharp_free = PInvokeMethods.gprsharp_free;
this.grpcsharp_metadata_array_create = PInvokeMethods.grpcsharp_metadata_array_create;
this.grpcsharp_metadata_array_add = PInvokeMethods.grpcsharp_metadata_array_add;
this.grpcsharp_metadata_array_count = PInvokeMethods.grpcsharp_metadata_array_count;
this.grpcsharp_metadata_array_get_key = PInvokeMethods.grpcsharp_metadata_array_get_key;
this.grpcsharp_metadata_array_get_value = PInvokeMethods.grpcsharp_metadata_array_get_value;
this.grpcsharp_metadata_array_get_value_length = PInvokeMethods.grpcsharp_metadata_array_get_value_length;
this.grpcsharp_metadata_array_destroy_full = PInvokeMethods.grpcsharp_metadata_array_destroy_full;
this.grpcsharp_redirect_log = PInvokeMethods.grpcsharp_redirect_log;
this.grpcsharp_metadata_credentials_create_from_plugin = PInvokeMethods.grpcsharp_metadata_credentials_create_from_plugin;
this.grpcsharp_metadata_credentials_notify_from_plugin = PInvokeMethods.grpcsharp_metadata_credentials_notify_from_plugin;
this.grpcsharp_ssl_server_credentials_create = PInvokeMethods.grpcsharp_ssl_server_credentials_create;
this.grpcsharp_server_credentials_release = PInvokeMethods.grpcsharp_server_credentials_release;
this.grpcsharp_server_create = PInvokeMethods.grpcsharp_server_create;
this.grpcsharp_server_add_insecure_http2_port = PInvokeMethods.grpcsharp_server_add_insecure_http2_port;
this.grpcsharp_server_add_secure_http2_port = PInvokeMethods.grpcsharp_server_add_secure_http2_port;
this.grpcsharp_server_start = PInvokeMethods.grpcsharp_server_start;
this.grpcsharp_server_request_call = PInvokeMethods.grpcsharp_server_request_call;
this.grpcsharp_server_cancel_all_calls = PInvokeMethods.grpcsharp_server_cancel_all_calls;
this.grpcsharp_server_shutdown_and_notify_callback = PInvokeMethods.grpcsharp_server_shutdown_and_notify_callback;
this.grpcsharp_server_destroy = PInvokeMethods.grpcsharp_server_destroy;
this.gprsharp_now = PInvokeMethods.gprsharp_now;
this.gprsharp_inf_future = PInvokeMethods.gprsharp_inf_future;
this.gprsharp_inf_past = PInvokeMethods.gprsharp_inf_past;
this.gprsharp_convert_clock_type = PInvokeMethods.gprsharp_convert_clock_type;
this.gprsharp_sizeof_timespec = PInvokeMethods.gprsharp_sizeof_timespec;
this.grpcsharp_test_callback = PInvokeMethods.grpcsharp_test_callback;
this.grpcsharp_test_nop = PInvokeMethods.grpcsharp_test_nop;
}
}
/// <summary>
/// Gets singleton instance of this class.
/// </summary>
public static NativeMethods Get()
{
return NativeExtension.Get().NativeMethods;
}
static T GetMethodDelegate<T>(UnmanagedLibrary library)
where T : class
{
var methodName = RemoveStringSuffix(typeof(T).Name, "_delegate");
return library.GetNativeMethodDelegate<T>(methodName);
}
static string RemoveStringSuffix(string str, string toRemove)
{
if (!str.EndsWith(toRemove))
{
return str;
}
return str.Substring(0, str.Length - toRemove.Length);
}
/// <summary>
/// Delegate types for all published native methods. Declared under inner class to prevent scope pollution.
/// </summary>
public class Delegates
{
public delegate void grpcsharp_init_delegate();
public delegate void grpcsharp_shutdown_delegate();
public delegate IntPtr grpcsharp_version_string_delegate(); // returns not-owned const char*
public delegate BatchContextSafeHandle grpcsharp_batch_context_create_delegate();
public delegate IntPtr grpcsharp_batch_context_recv_initial_metadata_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_recv_message_length_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_recv_message_to_buffer_delegate(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen);
public delegate StatusCode grpcsharp_batch_context_recv_status_on_client_status_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_details_delegate(BatchContextSafeHandle ctx); // returns const char*
public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate(BatchContextSafeHandle ctx);
public delegate CallSafeHandle grpcsharp_batch_context_server_rpc_new_call_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_server_rpc_new_method_delegate(BatchContextSafeHandle ctx); // returns const char*
public delegate IntPtr grpcsharp_batch_context_server_rpc_new_host_delegate(BatchContextSafeHandle ctx); // returns const char*
public delegate Timespec grpcsharp_batch_context_server_rpc_new_deadline_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_server_rpc_new_request_metadata_delegate(BatchContextSafeHandle ctx);
public delegate int grpcsharp_batch_context_recv_close_on_server_cancelled_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_destroy_delegate(IntPtr ctx);
public delegate CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create_delegate(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2);
public delegate void grpcsharp_call_credentials_release_delegate(IntPtr credentials);
public delegate GRPCCallError grpcsharp_call_cancel_delegate(CallSafeHandle call);
public delegate GRPCCallError grpcsharp_call_cancel_with_status_delegate(CallSafeHandle call, StatusCode status, string description);
public delegate GRPCCallError grpcsharp_call_start_unary_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
public delegate GRPCCallError grpcsharp_call_start_client_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
public delegate GRPCCallError grpcsharp_call_start_server_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen,
MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
public delegate GRPCCallError grpcsharp_call_start_duplex_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
public delegate GRPCCallError grpcsharp_call_send_message_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, bool sendEmptyInitialMetadata);
public delegate GRPCCallError grpcsharp_call_send_close_from_client_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate GRPCCallError grpcsharp_call_send_status_from_server_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, StatusCode statusCode, string statusMessage, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata,
byte[] optionalSendBuffer, UIntPtr optionalSendBufferLen, WriteFlags writeFlags);
public delegate GRPCCallError grpcsharp_call_recv_message_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate GRPCCallError grpcsharp_call_recv_initial_metadata_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate GRPCCallError grpcsharp_call_start_serverside_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate GRPCCallError grpcsharp_call_send_initial_metadata_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
public delegate GRPCCallError grpcsharp_call_set_credentials_delegate(CallSafeHandle call, CallCredentialsSafeHandle credentials);
public delegate CStringSafeHandle grpcsharp_call_get_peer_delegate(CallSafeHandle call);
public delegate void grpcsharp_call_destroy_delegate(IntPtr call);
public delegate ChannelArgsSafeHandle grpcsharp_channel_args_create_delegate(UIntPtr numArgs);
public delegate void grpcsharp_channel_args_set_string_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, string value);
public delegate void grpcsharp_channel_args_set_integer_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, int value);
public delegate void grpcsharp_channel_args_destroy_delegate(IntPtr args);
public delegate void grpcsharp_override_default_ssl_roots(string pemRootCerts);
public delegate ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create_delegate(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey);
public delegate ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create_delegate(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds);
public delegate void grpcsharp_channel_credentials_release_delegate(IntPtr credentials);
public delegate ChannelSafeHandle grpcsharp_insecure_channel_create_delegate(string target, ChannelArgsSafeHandle channelArgs);
public delegate ChannelSafeHandle grpcsharp_secure_channel_create_delegate(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs);
public delegate CallSafeHandle grpcsharp_channel_create_call_delegate(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline);
public delegate ChannelState grpcsharp_channel_check_connectivity_state_delegate(ChannelSafeHandle channel, int tryToConnect);
public delegate void grpcsharp_channel_watch_connectivity_state_delegate(ChannelSafeHandle channel, ChannelState lastObservedState,
Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate CStringSafeHandle grpcsharp_channel_get_target_delegate(ChannelSafeHandle call);
public delegate void grpcsharp_channel_destroy_delegate(IntPtr channel);
public delegate int grpcsharp_sizeof_grpc_event_delegate();
public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_delegate();
public delegate void grpcsharp_completion_queue_shutdown_delegate(CompletionQueueSafeHandle cq);
public delegate CompletionQueueEvent grpcsharp_completion_queue_next_delegate(CompletionQueueSafeHandle cq);
public delegate CompletionQueueEvent grpcsharp_completion_queue_pluck_delegate(CompletionQueueSafeHandle cq, IntPtr tag);
public delegate void grpcsharp_completion_queue_destroy_delegate(IntPtr cq);
public delegate void gprsharp_free_delegate(IntPtr ptr);
public delegate MetadataArraySafeHandle grpcsharp_metadata_array_create_delegate(UIntPtr capacity);
public delegate void grpcsharp_metadata_array_add_delegate(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength);
public delegate UIntPtr grpcsharp_metadata_array_count_delegate(IntPtr metadataArray);
public delegate IntPtr grpcsharp_metadata_array_get_key_delegate(IntPtr metadataArray, UIntPtr index);
public delegate IntPtr grpcsharp_metadata_array_get_value_delegate(IntPtr metadataArray, UIntPtr index);
public delegate UIntPtr grpcsharp_metadata_array_get_value_length_delegate(IntPtr metadataArray, UIntPtr index);
public delegate void grpcsharp_metadata_array_destroy_full_delegate(IntPtr array);
public delegate void grpcsharp_redirect_log_delegate(GprLogDelegate callback);
public delegate CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin_delegate(NativeMetadataInterceptor interceptor);
public delegate void grpcsharp_metadata_credentials_notify_from_plugin_delegate(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails);
public delegate ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create_delegate(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, bool forceClientAuth);
public delegate void grpcsharp_server_credentials_release_delegate(IntPtr credentials);
public delegate ServerSafeHandle grpcsharp_server_create_delegate(CompletionQueueSafeHandle cq, ChannelArgsSafeHandle args);
public delegate int grpcsharp_server_add_insecure_http2_port_delegate(ServerSafeHandle server, string addr);
public delegate int grpcsharp_server_add_secure_http2_port_delegate(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds);
public delegate void grpcsharp_server_start_delegate(ServerSafeHandle server);
public delegate GRPCCallError grpcsharp_server_request_call_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate void grpcsharp_server_cancel_all_calls_delegate(ServerSafeHandle server);
public delegate void grpcsharp_server_shutdown_and_notify_callback_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate void grpcsharp_server_destroy_delegate(IntPtr server);
public delegate Timespec gprsharp_now_delegate(GPRClockType clockType);
public delegate Timespec gprsharp_inf_future_delegate(GPRClockType clockType);
public delegate Timespec gprsharp_inf_past_delegate(GPRClockType clockType);
public delegate Timespec gprsharp_convert_clock_type_delegate(Timespec t, GPRClockType targetClock);
public delegate int gprsharp_sizeof_timespec_delegate();
public delegate GRPCCallError grpcsharp_test_callback_delegate([MarshalAs(UnmanagedType.FunctionPtr)] OpCompletionDelegate callback);
public delegate IntPtr grpcsharp_test_nop_delegate(IntPtr ptr);
}
/// <summary>
/// Default PInvoke bindings for native methods that are used on Windows.
/// Alternatively, they can also be used as a fallback on Mono
/// (if libgrpc_csharp_ext is installed on your system, or is made accessible through e.g. LD_LIBRARY_PATH environment variable
/// or using Mono's dllMap feature).
/// </summary>
private class PInvokeMethods
{
// Environment
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_init();
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_shutdown();
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_version_string(); // returns not-owned const char*
// BatchContextSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern BatchContextSafeHandle grpcsharp_batch_context_create();
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_recv_initial_metadata(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_recv_message_length(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_batch_context_recv_message_to_buffer(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen);
[DllImport("grpc_csharp_ext.dll")]
public static extern StatusCode grpcsharp_batch_context_recv_status_on_client_status(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_recv_status_on_client_details(BatchContextSafeHandle ctx); // returns const char*
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallSafeHandle grpcsharp_batch_context_server_rpc_new_call(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_server_rpc_new_method(BatchContextSafeHandle ctx); // returns const char*
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_server_rpc_new_host(BatchContextSafeHandle ctx); // returns const char*
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec grpcsharp_batch_context_server_rpc_new_deadline(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_server_rpc_new_request_metadata(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern int grpcsharp_batch_context_recv_close_on_server_cancelled(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_batch_context_destroy(IntPtr ctx);
// CallCredentialsSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_call_credentials_release(IntPtr credentials);
// CallSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_cancel(CallSafeHandle call);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_cancel_with_status(CallSafeHandle call, StatusCode status, string description);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_start_unary(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_start_client_streaming(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_start_server_streaming(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen,
MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_start_duplex_streaming(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_send_message(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, bool sendEmptyInitialMetadata);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_send_close_from_client(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_send_status_from_server(CallSafeHandle call,
BatchContextSafeHandle ctx, StatusCode statusCode, string statusMessage, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata,
byte[] optionalSendBuffer, UIntPtr optionalSendBufferLen, WriteFlags writeFlags);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_recv_message(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_recv_initial_metadata(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_start_serverside(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_send_initial_metadata(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_set_credentials(CallSafeHandle call, CallCredentialsSafeHandle credentials);
[DllImport("grpc_csharp_ext.dll")]
public static extern CStringSafeHandle grpcsharp_call_get_peer(CallSafeHandle call);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_call_destroy(IntPtr call);
// ChannelArgsSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelArgsSafeHandle grpcsharp_channel_args_create(UIntPtr numArgs);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_channel_args_set_string(ChannelArgsSafeHandle args, UIntPtr index, string key, string value);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_channel_args_set_integer(ChannelArgsSafeHandle args, UIntPtr index, string key, int value);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_channel_args_destroy(IntPtr args);
// ChannelCredentialsSafeHandle
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_override_default_ssl_roots(string pemRootCerts);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey);
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_channel_credentials_release(IntPtr credentials);
// ChannelSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelSafeHandle grpcsharp_insecure_channel_create(string target, ChannelArgsSafeHandle channelArgs);
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelSafeHandle grpcsharp_secure_channel_create(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallSafeHandle grpcsharp_channel_create_call(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline);
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelState grpcsharp_channel_check_connectivity_state(ChannelSafeHandle channel, int tryToConnect);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_channel_watch_connectivity_state(ChannelSafeHandle channel, ChannelState lastObservedState,
Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern CStringSafeHandle grpcsharp_channel_get_target(ChannelSafeHandle call);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_channel_destroy(IntPtr channel);
// CompletionQueueEvent
[DllImport("grpc_csharp_ext.dll")]
public static extern int grpcsharp_sizeof_grpc_event();
// CompletionQueueSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern CompletionQueueSafeHandle grpcsharp_completion_queue_create();
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_completion_queue_shutdown(CompletionQueueSafeHandle cq);
[DllImport("grpc_csharp_ext.dll")]
public static extern CompletionQueueEvent grpcsharp_completion_queue_next(CompletionQueueSafeHandle cq);
[DllImport("grpc_csharp_ext.dll")]
public static extern CompletionQueueEvent grpcsharp_completion_queue_pluck(CompletionQueueSafeHandle cq, IntPtr tag);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_completion_queue_destroy(IntPtr cq);
// CStringSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern void gprsharp_free(IntPtr ptr);
// MetadataArraySafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern MetadataArraySafeHandle grpcsharp_metadata_array_create(UIntPtr capacity);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_metadata_array_add(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength);
[DllImport("grpc_csharp_ext.dll")]
public static extern UIntPtr grpcsharp_metadata_array_count(IntPtr metadataArray);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_metadata_array_get_key(IntPtr metadataArray, UIntPtr index);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_metadata_array_get_value(IntPtr metadataArray, UIntPtr index);
[DllImport("grpc_csharp_ext.dll")]
public static extern UIntPtr grpcsharp_metadata_array_get_value_length(IntPtr metadataArray, UIntPtr index);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_metadata_array_destroy_full(IntPtr array);
// NativeLogRedirector
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_redirect_log(GprLogDelegate callback);
// NativeMetadataCredentialsPlugin
[DllImport("grpc_csharp_ext.dll")]
public static extern CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin(NativeMetadataInterceptor interceptor);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_metadata_credentials_notify_from_plugin(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails);
// ServerCredentialsSafeHandle
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, bool forceClientAuth);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_credentials_release(IntPtr credentials);
// ServerSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern ServerSafeHandle grpcsharp_server_create(CompletionQueueSafeHandle cq, ChannelArgsSafeHandle args);
[DllImport("grpc_csharp_ext.dll")]
public static extern int grpcsharp_server_add_insecure_http2_port(ServerSafeHandle server, string addr);
[DllImport("grpc_csharp_ext.dll")]
public static extern int grpcsharp_server_add_secure_http2_port(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_start(ServerSafeHandle server);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_server_request_call(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_cancel_all_calls(ServerSafeHandle server);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_shutdown_and_notify_callback(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_destroy(IntPtr server);
// Timespec
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec gprsharp_now(GPRClockType clockType);
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec gprsharp_inf_future(GPRClockType clockType);
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec gprsharp_inf_past(GPRClockType clockType);
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec gprsharp_convert_clock_type(Timespec t, GPRClockType targetClock);
[DllImport("grpc_csharp_ext.dll")]
public static extern int gprsharp_sizeof_timespec();
// Testing
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_test_callback([MarshalAs(UnmanagedType.FunctionPtr)] OpCompletionDelegate callback);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_test_nop(IntPtr ptr);
}
}
}
| |
using log4net;
using Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Services.Interfaces;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using System.Xml;
[assembly: Addin("OpenSimProfile", "0.3")]
[assembly: AddinDependency("OpenSim", "0.5")]
namespace OpenSimProfile.Modules.OpenProfile
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
public class OpenSimProfile : IProfileModule, ISharedRegionModule
{
//
// Log module
//
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//
// Module vars
//
private ThreadedClasses.RwLockedList<Scene> m_Scenes = new ThreadedClasses.RwLockedList<Scene>();
private string m_ProfileServer = "";
private bool m_Enabled = true;
IUserManagement m_uMan;
IUserManagement UserManagementModule
{
get
{
if (m_uMan == null)
m_uMan = m_Scenes[0].RequestModuleInterface<IUserManagement>();
return m_uMan;
}
}
#region IRegionModuleBase implementation
public void Initialise(IConfigSource config)
{
IConfig profileConfig = config.Configs["Profile"];
if (profileConfig == null)
{
m_Enabled = false;
return;
}
if (profileConfig.GetString("Module", "OpenSimProfile") != "OpenSimProfile")
{
m_Enabled = false;
return;
}
m_ProfileServer = profileConfig.GetString("ProfileURL", "");
if (m_ProfileServer == "")
{
m_Enabled = false;
return;
}
m_log.Info("[PROFILE] OpenSimProfile module is active");
m_Enabled = true;
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
// Take ownership of the IProfileModule service
scene.RegisterModuleInterface<IProfileModule>(this);
// Add our scene to our list...
m_Scenes.Add(scene);
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.UnregisterModuleInterface<IProfileModule>(this);
m_Scenes.Remove(scene);
}
public void RegionLoaded(Scene scene)
{
if(!m_Enabled)
{
return;
}
// Hook up events
scene.EventManager.OnNewClient += OnNewClient;
}
public Type ReplaceableInterface
{
get { return null; }
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "ProfileModule"; }
}
#endregion
private ScenePresence FindPresence(UUID clientID)
{
ScenePresence p;
foreach (Scene s in m_Scenes)
{
p = s.GetScenePresence(clientID);
if (p != null && !p.IsChildAgent)
return p;
}
return null;
}
/// New Client Event Handler
private void OnNewClient(IClientAPI client)
{
// Subscribe to messages
// Classifieds
client.AddGenericPacketHandler("avatarclassifiedsrequest", HandleAvatarClassifiedsRequest);
client.OnClassifiedInfoUpdate += ClassifiedInfoUpdate;
client.OnClassifiedDelete += ClassifiedDelete;
// Picks
client.AddGenericPacketHandler("avatarpicksrequest", HandleAvatarPicksRequest);
client.AddGenericPacketHandler("pickinforequest", HandlePickInfoRequest);
client.OnPickInfoUpdate += PickInfoUpdate;
client.OnPickDelete += PickDelete;
// Notes
client.AddGenericPacketHandler("avatarnotesrequest", HandleAvatarNotesRequest);
client.OnAvatarNotesUpdate += AvatarNotesUpdate;
//Profile
client.OnRequestAvatarProperties += RequestAvatarProperties;
client.OnUpdateAvatarProperties += UpdateAvatarProperties;
client.OnAvatarInterestUpdate += AvatarInterestsUpdate;
client.OnUserInfoRequest += UserPreferencesRequest;
client.OnUpdateUserInfo += UpdateUserPreferences;
}
//
// Make external XMLRPC request
//
private Hashtable GenericXMLRPCRequest(Hashtable ReqParams, string method, string server)
{
ArrayList SendParams = new ArrayList();
SendParams.Add(ReqParams);
// Send Request
XmlRpcResponse Resp;
try
{
XmlRpcRequest Req = new XmlRpcRequest(method, SendParams);
Resp = Req.Send(server, 30000);
}
catch (WebException ex)
{
m_log.ErrorFormat("[PROFILE]: Unable to connect to Profile " +
"Server {0}. Exception {1}", m_ProfileServer, ex);
Hashtable ErrorHash = new Hashtable();
ErrorHash["success"] = false;
ErrorHash["errorMessage"] = "Unable to fetch profile data at this time. ";
ErrorHash["errorURI"] = "";
return ErrorHash;
}
catch (SocketException ex)
{
m_log.ErrorFormat(
"[PROFILE]: Unable to connect to Profile Server {0}. Method {1}, params {2}. " +
"Exception {3}", m_ProfileServer, method, ReqParams, ex);
Hashtable ErrorHash = new Hashtable();
ErrorHash["success"] = false;
ErrorHash["errorMessage"] = "Unable to fetch profile data at this time. ";
ErrorHash["errorURI"] = "";
return ErrorHash;
}
catch (XmlException ex)
{
m_log.ErrorFormat(
"[PROFILE]: Unable to connect to Profile Server {0}. Method {1}, params {2}. " +
"Exception {3}", m_ProfileServer, method, ReqParams.ToString(), ex);
Hashtable ErrorHash = new Hashtable();
ErrorHash["success"] = false;
ErrorHash["errorMessage"] = "Unable to fetch profile data at this time. ";
ErrorHash["errorURI"] = "";
return ErrorHash;
}
if (Resp.IsFault)
{
Hashtable ErrorHash = new Hashtable();
ErrorHash["success"] = false;
ErrorHash["errorMessage"] = "Unable to fetch profile data at this time. ";
ErrorHash["errorURI"] = "";
return ErrorHash;
}
Hashtable RespData = (Hashtable)Resp.Value;
return RespData;
}
// Classifieds Handler
public void HandleAvatarClassifiedsRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID targetID;
UUID.TryParse(args[0], out targetID);
// Can't handle NPC yet...
ScenePresence p = FindPresence(targetID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
GetUserProfileServerURI(targetID, out serverURI);
Hashtable ReqHash = new Hashtable();
ReqHash["uuid"] = args[0];
Hashtable result = GenericXMLRPCRequest(ReqHash,
method, serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
return;
}
ArrayList dataArray = (ArrayList)result["data"];
Dictionary<UUID, string> classifieds = new Dictionary<UUID, string>();
foreach (Object o in dataArray)
{
Hashtable d = (Hashtable)o;
classifieds[new UUID(d["classifiedid"].ToString())] = d["name"].ToString();
}
remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
}
// Classifieds Update
public void ClassifiedInfoUpdate(UUID queryclassifiedID, uint queryCategory, string queryName, string queryDescription, UUID queryParcelID,
uint queryParentEstate, UUID querySnapshotID, Vector3 queryGlobalPos, byte queryclassifiedFlags,
int queryclassifiedPrice, IClientAPI remoteClient)
{
Hashtable ReqHash = new Hashtable();
Scene s = (Scene) remoteClient.Scene;
Vector3 pos = remoteClient.SceneAgent.AbsolutePosition;
ILandObject land = s.LandChannel.GetLandObject(pos.X, pos.Y);
if (land == null)
ReqHash["parcelname"] = String.Empty;
else
ReqHash["parcelname"] = land.LandData.Name;
ReqHash["creatorUUID"] = remoteClient.AgentId.ToString();
ReqHash["classifiedUUID"] = queryclassifiedID.ToString();
ReqHash["category"] = queryCategory.ToString();
ReqHash["name"] = queryName;
ReqHash["description"] = queryDescription;
ReqHash["parentestate"] = queryParentEstate.ToString();
ReqHash["snapshotUUID"] = querySnapshotID.ToString();
ReqHash["sim_name"] = remoteClient.Scene.RegionInfo.RegionName;
ReqHash["globalpos"] = queryGlobalPos.ToString();
ReqHash["classifiedFlags"] = queryclassifiedFlags.ToString();
ReqHash["classifiedPrice"] = queryclassifiedPrice.ToString();
ScenePresence p = FindPresence(remoteClient.AgentId);
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
Vector3 avaPos = p.AbsolutePosition;
// Getting the parceluuid for this parcel
ReqHash["parcelUUID"] = p.currentParcelUUID.ToString();
// Getting the global position for the Avatar
Vector3 posGlobal = new Vector3(remoteClient.Scene.RegionInfo.RegionLocX * Constants.RegionSize + avaPos.X,
remoteClient.Scene.RegionInfo.RegionLocY * Constants.RegionSize + avaPos.Y,
avaPos.Z);
ReqHash["pos_global"] = posGlobal.ToString();
//Check available funds if there is a money module present
IMoneyModule money = s.RequestModuleInterface<IMoneyModule>();
if (money != null)
{
if (!money.AmountCovered(remoteClient.AgentId, queryclassifiedPrice))
{
remoteClient.SendCreateGroupReply(UUID.Zero, false, "Insufficient funds to create a classified ad.");
return;
}
}
Hashtable result = GenericXMLRPCRequest(ReqHash,
"classified_update", serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
return;
}
if (money != null && Convert.ToBoolean(result["created"]))
{
money.ApplyCharge(remoteClient.AgentId, queryclassifiedPrice,
MoneyTransactionType.ClassifiedCharge,
queryName);
}
}
// Classifieds Delete
public void ClassifiedDelete(UUID queryClassifiedID, IClientAPI remoteClient)
{
Hashtable ReqHash = new Hashtable();
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
ReqHash["classifiedID"] = queryClassifiedID.ToString();
Hashtable result = GenericXMLRPCRequest(ReqHash,
"classified_delete", serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
}
}
// Picks Handler
public void HandleAvatarPicksRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID targetID;
UUID.TryParse(args[0], out targetID);
// Can't handle NPC yet...
ScenePresence p = FindPresence(targetID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
GetUserProfileServerURI(targetID, out serverURI);
Hashtable ReqHash = new Hashtable();
ReqHash["uuid"] = args[0];
Hashtable result = GenericXMLRPCRequest(ReqHash,
method, serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
return;
}
ArrayList dataArray = (ArrayList)result["data"];
Dictionary<UUID, string> picks = new Dictionary<UUID, string>();
if (dataArray != null)
{
foreach (Object o in dataArray)
{
Hashtable d = (Hashtable)o;
if (d["name"] == null)
picks[new UUID(d["pickid"].ToString())] = String.Empty;
else
picks[new UUID(d["pickid"].ToString())] = d["name"].ToString();
}
}
remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks);
}
// Picks Request
public void HandlePickInfoRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
Hashtable ReqHash = new Hashtable();
UUID targetID;
UUID.TryParse(args[0], out targetID);
string serverURI = string.Empty;
GetUserProfileServerURI(targetID, out serverURI);
ReqHash["avatar_id"] = args[0];
ReqHash["pick_id"] = args[1];
Hashtable result = GenericXMLRPCRequest(ReqHash,
method, serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
return;
}
ArrayList dataArray = (ArrayList)result["data"];
Hashtable d = (Hashtable)dataArray[0];
Vector3 globalPos = new Vector3();
Vector3.TryParse(d["posglobal"].ToString(), out globalPos);
if (d["name"] == null)
d["name"] = String.Empty;
if (d["description"] == null)
d["description"] = String.Empty;
if (d["originalname"] == null)
d["originalname"] = String.Empty;
remoteClient.SendPickInfoReply(
new UUID(d["pickuuid"].ToString()),
new UUID(d["creatoruuid"].ToString()),
Convert.ToBoolean(d["toppick"]),
new UUID(d["parceluuid"].ToString()),
d["name"].ToString(),
d["description"].ToString(),
new UUID(d["snapshotuuid"].ToString()),
d["user"].ToString(),
d["originalname"].ToString(),
d["simname"].ToString(),
globalPos,
Convert.ToInt32(d["sortorder"]),
Convert.ToBoolean(d["enabled"]));
}
// Picks Update
public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, UUID snapshotID, int sortOrder, bool enabled)
{
Hashtable ReqHash = new Hashtable();
ReqHash["agent_id"] = remoteClient.AgentId.ToString();
ReqHash["pick_id"] = pickID.ToString();
ReqHash["creator_id"] = creatorID.ToString();
ReqHash["top_pick"] = topPick.ToString();
ReqHash["name"] = name;
ReqHash["desc"] = desc;
ReqHash["snapshot_id"] = snapshotID.ToString();
ReqHash["sort_order"] = sortOrder.ToString();
ReqHash["enabled"] = enabled.ToString();
ReqHash["sim_name"] = remoteClient.Scene.RegionInfo.RegionName;
ScenePresence p = FindPresence(remoteClient.AgentId);
Vector3 avaPos = p.AbsolutePosition;
// Getting the parceluuid for this parcel
ReqHash["parcel_uuid"] = p.currentParcelUUID.ToString();
// Getting the global position for the Avatar
Vector3 posGlobal = new Vector3(remoteClient.Scene.RegionInfo.RegionLocX * Constants.RegionSize + avaPos.X,
remoteClient.Scene.RegionInfo.RegionLocY * Constants.RegionSize + avaPos.Y,
avaPos.Z);
ReqHash["pos_global"] = posGlobal.ToString();
// Getting the owner of the parcel
ReqHash["user"] = ""; //FIXME: Get avatar/group who owns parcel
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
// Do the request
Hashtable result = GenericXMLRPCRequest(ReqHash,
"picks_update", serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
}
}
// Picks Delete
public void PickDelete(IClientAPI remoteClient, UUID queryPickID)
{
Hashtable ReqHash = new Hashtable();
ReqHash["pick_id"] = queryPickID.ToString();
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
Hashtable result = GenericXMLRPCRequest(ReqHash,
"picks_delete", serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
}
}
// Notes Handler
public void HandleAvatarNotesRequest(Object sender, string method, List<String> args)
{
string targetid;
string notes = "";
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
Hashtable ReqHash = new Hashtable();
ReqHash["avatar_id"] = remoteClient.AgentId.ToString();
ReqHash["uuid"] = args[0];
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
Hashtable result = GenericXMLRPCRequest(ReqHash,
method, serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
return;
}
ArrayList dataArray = (ArrayList)result["data"];
if (dataArray != null && dataArray[0] != null)
{
Hashtable d = (Hashtable)dataArray[0];
targetid = d["targetid"].ToString();
if (d["notes"] != null)
notes = d["notes"].ToString();
remoteClient.SendAvatarNotesReply(new UUID(targetid), notes);
}
}
// Notes Update
public void AvatarNotesUpdate(IClientAPI remoteClient, UUID queryTargetID, string queryNotes)
{
Hashtable ReqHash = new Hashtable();
ReqHash["avatar_id"] = remoteClient.AgentId.ToString();
ReqHash["target_id"] = queryTargetID.ToString();
ReqHash["notes"] = queryNotes;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
Hashtable result = GenericXMLRPCRequest(ReqHash,
"avatar_notes_update", serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
}
}
// Standard Profile bits
public void AvatarInterestsUpdate(IClientAPI remoteClient, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages)
{
Hashtable ReqHash = new Hashtable();
ReqHash["avatar_id"] = remoteClient.AgentId.ToString();
ReqHash["wantmask"] = wantmask.ToString();
ReqHash["wanttext"] = wanttext;
ReqHash["skillsmask"] = skillsmask.ToString();
ReqHash["skillstext"] = skillstext;
ReqHash["languages"] = languages;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
Hashtable result = GenericXMLRPCRequest(ReqHash,
"avatar_interests_update", serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
}
}
public void UserPreferencesRequest(IClientAPI remoteClient)
{
Hashtable ReqHash = new Hashtable();
ReqHash["avatar_id"] = remoteClient.AgentId.ToString();
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
Hashtable result = GenericXMLRPCRequest(ReqHash,
"user_preferences_request", serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
return;
}
ArrayList dataArray = (ArrayList)result["data"];
if (dataArray != null && dataArray[0] != null)
{
Hashtable d = (Hashtable)dataArray[0];
string mail = "";
if (d["email"] != null)
mail = d["email"].ToString();
remoteClient.SendUserInfoReply(
Convert.ToBoolean(d["imviaemail"]),
Convert.ToBoolean(d["visible"]),
mail);
}
}
public void UpdateUserPreferences(bool imViaEmail, bool visible, IClientAPI remoteClient)
{
Hashtable ReqHash = new Hashtable();
ReqHash["avatar_id"] = remoteClient.AgentId.ToString();
ReqHash["imViaEmail"] = imViaEmail.ToString();
ReqHash["visible"] = visible.ToString();
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
Hashtable result = GenericXMLRPCRequest(ReqHash,
"user_preferences_update", serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
}
}
// Profile data like the WebURL
private Hashtable GetProfileData(UUID userID)
{
Hashtable ReqHash = new Hashtable();
// Can't handle NPC yet...
ScenePresence p = FindPresence(userID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
{
Hashtable npc =new Hashtable();
npc["success"] = "false";
npc["errorMessage"] = "Presence is NPC. ";
return npc;
}
}
ReqHash["avatar_id"] = userID.ToString();
string serverURI = string.Empty;
GetUserProfileServerURI(userID, out serverURI);
// This is checking a friend on the home grid
// Not HG friend
if ( String.IsNullOrEmpty(serverURI))
{
Hashtable nop =new Hashtable();
nop["success"] = "false";
nop["errorMessage"] = "No Presence - foreign friend";
return nop;
}
Hashtable result = GenericXMLRPCRequest(ReqHash,
"avatar_properties_request", serverURI);
ArrayList dataArray = (ArrayList)result["data"];
if (dataArray != null && dataArray[0] != null)
{
Hashtable d = (Hashtable)dataArray[0];
return d;
}
return result;
}
public void RequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
{
if ( String.IsNullOrEmpty(avatarID.ToString()) || String.IsNullOrEmpty(remoteClient.AgentId.ToString()))
{
// Looking for a reason that some viewers are sending null Id's
m_log.InfoFormat("[PROFILE]: This should not happen remoteClient.AgentId {0} - avatarID {1}", remoteClient.AgentId, avatarID);
return;
}
// Can't handle NPC yet...
ScenePresence p = FindPresence(avatarID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
IScene s = remoteClient.Scene;
if (!(s is Scene))
return;
Scene scene = (Scene)s;
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(avatarID, out serverURI);
UserAccount account = null;
Dictionary<string,object> userInfo;
if (!foreign)
{
account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, avatarID);
}
else
{
userInfo = new Dictionary<string, object>();
}
Byte[] charterMember = new Byte[1];
string born = String.Empty;
uint flags = 0x00;
if (null != account)
{
if (account.UserTitle == "")
{
charterMember[0] = (Byte)((account.UserFlags & 0xf00) >> 8);
}
else
{
charterMember = Utils.StringToBytes(account.UserTitle);
}
born = Util.ToDateTime(account.Created).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
flags = (uint)(account.UserFlags & 0xff);
}
else
{
if (GetUserProfileData(avatarID, out userInfo) == true)
{
if ((string)userInfo["user_title"] == "")
{
charterMember[0] = (Byte)(((Byte)userInfo["user_flags"] & 0xf00) >> 8);
}
else
{
charterMember = Utils.StringToBytes((string)userInfo["user_title"]);
}
int val_born = (int)userInfo["user_created"];
born = Util.ToDateTime(val_born).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
// picky, picky
int val_flags = (int)userInfo["user_flags"];
flags = (uint)(val_flags & 0xff);
}
}
Hashtable profileData = GetProfileData(avatarID);
string profileUrl = string.Empty;
string aboutText = String.Empty;
string firstLifeAboutText = String.Empty;
UUID image = UUID.Zero;
UUID firstLifeImage = UUID.Zero;
UUID partner = UUID.Zero;
uint wantMask = 0;
string wantText = String.Empty;
uint skillsMask = 0;
string skillsText = String.Empty;
string languages = String.Empty;
if (profileData["ProfileUrl"] != null)
profileUrl = profileData["ProfileUrl"].ToString();
if (profileData["AboutText"] != null)
aboutText = profileData["AboutText"].ToString();
if (profileData["FirstLifeAboutText"] != null)
firstLifeAboutText = profileData["FirstLifeAboutText"].ToString();
if (profileData["Image"] != null)
image = new UUID(profileData["Image"].ToString());
if (profileData["FirstLifeImage"] != null)
firstLifeImage = new UUID(profileData["FirstLifeImage"].ToString());
if (profileData["Partner"] != null)
partner = new UUID(profileData["Partner"].ToString());
// The PROFILE information is no longer stored in the user
// account. It now needs to be taken from the XMLRPC
//
remoteClient.SendAvatarProperties(avatarID, aboutText,born,
charterMember, firstLifeAboutText,
flags,
firstLifeImage, image, profileUrl, partner);
//Viewer expects interest data when it asks for properties.
if (profileData["wantmask"] != null)
wantMask = Convert.ToUInt32(profileData["wantmask"].ToString());
if (profileData["wanttext"] != null)
wantText = profileData["wanttext"].ToString();
if (profileData["skillsmask"] != null)
skillsMask = Convert.ToUInt32(profileData["skillsmask"].ToString());
if (profileData["skillstext"] != null)
skillsText = profileData["skillstext"].ToString();
if (profileData["languages"] != null)
languages = profileData["languages"].ToString();
remoteClient.SendAvatarInterestsReply(avatarID, wantMask, wantText,
skillsMask, skillsText, languages);
}
public void UpdateAvatarProperties(IClientAPI remoteClient, UserProfileData newProfile)
{
// if it's the profile of the user requesting the update, then we change only a few things.
if (remoteClient.AgentId == newProfile.ID)
{
Hashtable ReqHash = new Hashtable();
ReqHash["avatar_id"] = remoteClient.AgentId.ToString();
ReqHash["ProfileUrl"] = newProfile.ProfileUrl;
ReqHash["Image"] = newProfile.Image.ToString();
ReqHash["AboutText"] = newProfile.AboutText;
ReqHash["FirstLifeImage"] = newProfile.FirstLifeImage.ToString();
ReqHash["FirstLifeAboutText"] = newProfile.FirstLifeAboutText;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
Hashtable result = GenericXMLRPCRequest(ReqHash,
"avatar_properties_update", serverURI);
if (!Convert.ToBoolean(result["success"]))
{
remoteClient.SendAgentAlertMessage(
result["errorMessage"].ToString(), false);
}
RequestAvatarProperties(remoteClient, newProfile.ID);
}
}
private bool GetUserProfileServerURI(UUID userID, out string serverURI)
{
IUserManagement uManage = UserManagementModule;
if (!uManage.IsLocalGridUser(userID))
{
serverURI = uManage.GetUserServerURL(userID, "ProfileServerURI");
// Is Foreign
return true;
}
else
{
serverURI = m_ProfileServer;
// Is local
return false;
}
}
//
// Get the UserAccountBits
//
private bool GetUserProfileData(UUID userID, out Dictionary<string, object> userInfo)
{
IUserManagement uManage = UserManagementModule;
Dictionary<string,object> info = new Dictionary<string, object>();
if (!uManage.IsLocalGridUser(userID))
{
// Is Foreign
string home_url = uManage.GetUserServerURL(userID, "HomeURI");
if (String.IsNullOrEmpty(home_url))
{
info["user_flags"] = 0;
info["user_created"] = 0;
info["user_title"] = "Unavailable";
userInfo = info;
return true;
}
UserAgentServiceConnector uConn = new UserAgentServiceConnector(home_url);
Dictionary<string, object> account = uConn.GetUserInfo(userID);
if (account.Count > 0)
{
if (account.ContainsKey("user_flags"))
info["user_flags"] = account["user_flags"];
else
info["user_flags"] = "";
if (account.ContainsKey("user_created"))
info["user_created"] = account["user_created"];
else
info["user_created"] = "";
info["user_title"] = "HG Visitor";
}
else
{
info["user_flags"] = 0;
info["user_created"] = 0;
info["user_title"] = "HG Visitor";
}
userInfo = info;
return true;
}
else
{
// Is local
Scene scene = m_Scenes[0];
IUserAccountService uas = scene.UserAccountService;
UserAccount account = uas.GetUserAccount(scene.RegionInfo.ScopeID, userID);
info["user_flags"] = account.UserFlags;
info["user_created"] = account.Created;
if (!String.IsNullOrEmpty(account.UserTitle))
info["user_title"] = account.UserTitle;
else
info["user_title"] = "";
userInfo = info;
return false;
}
}
}
}
| |
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using MvvmDialogs.ViewModels;
using Perfy.Behaviors;
using Perfy.Dialogs;
using Perfy.Model;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using System.Xml.Serialization;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Controls;
namespace Perfy.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase, IMouseCaptureProxy
{
private IDialogViewModelCollection _Dialogs = new DialogViewModelCollection();
public IDialogViewModelCollection Dialogs { get { return _Dialogs; } }
private CircuitViewModel _Board;
public CircuitViewModel Board
{
get { return this._Board; }
set { this._Board = value; RaisePropertyChanged(() => this.Board); }
}
/* todo:
private PadViewModel CurrentPad = null;
* */
private bool Capturing = false;
private object CaptureSender;
public event EventHandler Capture;
public event EventHandler Release;
private string LastFilename = null;
private Point TraceStart;
private Point TraceEnd;
private EditMode _EditMode = EditMode.Traces;
public EditMode EditMode
{
get { return this._EditMode; }
set
{
if (this._EditMode != value)
{
CancelCurrentTrace();
this._EditMode = value;
RaisePropertyChanged(() => this.EditMode);
}
}
}
private ViewMode _ViewMode = ViewMode.Normal;
public ViewMode ViewMode
{
get { return this._ViewMode; }
set
{
if (this._ViewMode != value)
{
this.Board.DeselectHighlights();
CancelCurrentTrace();
this._ViewMode = value;
RaisePropertyChanged(() => this.ViewMode);
}
}
}
private Perspective _Perspective = Perspective.Front;
public Perspective Perspective
{
get { return this._Perspective; }
set
{
if (this._Perspective != value)
{
this.Board.DeselectHighlights();
CancelCurrentTrace();
this._Perspective = value;
RaisePropertyChanged(() => this.Perspective);
}
}
}
private double _Zoom = 1;
public double Zoom
{
get { return this._Zoom; }
set { this._Zoom = value; RaisePropertyChanged(() => this.Zoom); }
}
private double _ZoomLevel;
private double ZoomLevel
{
get { return this._ZoomLevel; }
set
{
this._ZoomLevel = value;
this.Zoom = Math.Pow(Math.Sqrt(2), value);
}
}
public ICommand ZoomInCommand { get { return new RelayCommand(OnZoomIn); } }
private void OnZoomIn()
{
this.ZoomLevel++;
if (this.ZoomLevel > 16)
this.ZoomLevel = 16;
}
public ICommand ZoomOutCommand { get { return new RelayCommand(OnZoomOut); } }
private void OnZoomOut()
{
this.ZoomLevel--;
if (this.ZoomLevel < 1)
this.ZoomLevel = 1;
}
public ICommand SetEditModeCommand { get { return new RelayCommand<EditMode>(OnSetEditMode); } }
private void OnSetEditMode(EditMode mode)
{
CancelCurrentTrace();
this.EditMode = mode;
}
public ICommand UndoCommand { get { return new RelayCommand(OnUndo); } }
private void OnUndo()
{
this.Board.Undo();
}
public ICommand RedoCommand { get { return new RelayCommand(OnRedo); } }
private void OnRedo()
{
this.Board.Redo();
}
const string CaptionPrefix = "Perfy Circuit Designer";
private string _Caption = CaptionPrefix;
public string Caption
{
get { return this._Caption; }
set { this._Caption = value; RaisePropertyChanged(() => this.Caption); }
}
public ICommand PreviewKeyDownCommand { get { return new RelayCommand<System.Windows.Input.KeyEventArgs>(OnPreviewKeyDown); } }
private void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs args)
{
if (args.Key == Key.Add)
{
ZoomInCommand.Execute(null);
args.Handled = true;
}
else if (args.Key == Key.Subtract)
{
ZoomOutCommand.Execute(null);
args.Handled = true;
}
#if DEBUG
if (args.Key == Key.Escape)
ExitCommand.Execute(null);
#endif
}
public MainViewModel()
{
this.LastFilename = null;
this.ZoomLevel = 10;
this.Board = new CircuitViewModel { Circuit = new Circuit() };
this.Board.SaveForUndo(true);
}
public ICommand NewCommand { get { return new RelayCommand(OnNew); } }
private void OnNew()
{
CancelCurrentTrace();
this.LastFilename = null;
this.ZoomLevel = 10;
// todo: this.CurrentPad = null;
this.Board.Circuit = new Circuit();
// todo remove UpdateSelections();
this.Board.SaveForUndo(true);
}
public ICommand OpenCommand { get { return new RelayCommand(OnOpen); } }
private void OnOpen()
{
CancelCurrentTrace();
var dlg = new OpenFileDialogViewModel
{
Title = "Load Perfy Layout",
Filter = "Perfy files (*.pfp)|*.pfp|All files (*.*)|*.*",
FileName = "*.pfp",
Multiselect = false
};
if (dlg.Show(this.Dialogs))
{
this.Caption = CaptionPrefix + " - " + Path.GetFileName(dlg.FileName);
this.LastFilename = dlg.FileName;
Load(dlg.FileName);
}
}
public ICommand SaveCommand { get { return new RelayCommand(OnSave); } }
private void OnSave()
{
CancelCurrentTrace();
if (String.IsNullOrEmpty(this.LastFilename))
{
OnSaveAs();
return;
}
try
{
Save(this.LastFilename);
}
catch (Exception e)
{
new MessageBoxViewModel("Error saving perfy file: " + e.Message, "Error").Show(this.Dialogs);
}
}
public ICommand SaveAsCommand { get { return new RelayCommand(OnSaveAs); } }
private void OnSaveAs()
{
CancelCurrentTrace();
try
{
var dlg = new SaveFileDialogViewModel
{
Title = "Save Perfy Layout",
Filter = "Perfy files (*.pfp)|*.pfp|All files (*.*)|*.*",
FileName = "*.pfp"
};
if (dlg.Show(this.Dialogs) == System.Windows.Forms.DialogResult.OK)
{
this.Caption = CaptionPrefix + " - " + Path.GetFileName(dlg.FileName);
this.LastFilename = dlg.FileName;
Save(dlg.FileName);
}
}
catch (Exception e)
{
new MessageBoxViewModel("Error saving perfy file: " + e.Message, "Error").Show(this.Dialogs);
}
}
public ICommand ExitCommand { get { return new RelayCommand(ExitCommand_Execute); } }
private void ExitCommand_Execute()
{
CancelCurrentTrace();
//#if !DEBUG
if (this.Board.Changed)
{
if (new MessageBoxViewModel("Quit without saving?", "Quit", MessageBoxButton.YesNo, MessageBoxImage.Question).Show(this.Dialogs) != MessageBoxResult.Yes)
return;
}
//#endif
App.Current.MainWindow.Close();
}
public ICommand SummaryCommand { get { return new RelayCommand(SummaryCommand_Execute); } }
private void SummaryCommand_Execute()
{
CancelCurrentTrace();
var msg = String.Format(
"Horizontal pad solders:\t{0}\n" +
"Vertical pad solders:\t\t{1}\n" +
"Isolated pad solders:\t\t{2}\n" +
"Horizontal trace cuts:\t{3}\n" +
"Vertical trace cuts:\t\t{4}\n" +
"Total board utilization:\t{5}%",
this.Board.NumHorzPads,
this.Board.NumVertPads,
this.Board.NumIsolatedPads,
this.Board.NumHorzCuts,
this.Board.NumVertCuts,
this.Board.Utilization);
new MessageBoxViewModel(msg, "Circuit Summary", MessageBoxButton.OK, MessageBoxImage.Information).Show(this.Dialogs);
}
public ICommand HelpCommand { get { return new RelayCommand(OnHelp); } }
private void OnHelp()
{
CancelCurrentTrace();
foreach (var dlg in this.Dialogs)
if (dlg is HelpDialogViewModel)
return;
this.Dialogs.Add(new HelpDialogViewModel());
}
public ICommand AboutCommand { get { return new RelayCommand(OnAbout); } }
private void OnAbout()
{
CancelCurrentTrace();
Assembly assembly = Assembly.GetEntryAssembly();
var fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
var version = fvi.FileVersion;
var copyright = fvi.LegalCopyright;
new MessageBoxViewModel("Perfy v" + version + " The Perf+ Circuit Editor" + Environment.NewLine + Environment.NewLine + copyright, "About Perfy").Show(this.Dialogs);
}
public void Load(string filename)
{
XmlSerializer x = new XmlSerializer(typeof(Circuit));
using (var fs = new FileStream(filename, FileMode.Open))
this.Board.Circuit = x.Deserialize(fs) as Circuit;
this.Board.SaveForUndo(true);
}
public void Save(string filename)
{
XmlSerializer x = new XmlSerializer(typeof(Circuit));
using (var writer = new StreamWriter(filename))
x.Serialize(writer, this.Board.Circuit);
}
public void OnMouseDown(object sender, MouseCaptureArgs e)
{
if (this.ViewMode != ViewMode.Normal)
return;
if (this.EditMode == EditMode.Pads)
OnMouseDownPads(sender, e);
else if (this.EditMode == EditMode.Traces)
OnMouseDownTraces(sender, e);
}
public void OnMouseDownPads(object sender, MouseCaptureArgs e)
{
int x = (int)(e.X - 1.0);
int y = (int)(e.Y - 1.0);
if (!ValidPosition(x, y))
return;
if (e.LeftButton)
this.Board.PadArray[y, x].Component = true;
else
this.Board.PadArray[y, x].Component = false;
this.Board.SaveForUndo();
}
public void OnMouseDownTraces(object sender, MouseCaptureArgs e)
{
int x = (int)(e.X - 1.0);
int y = (int)(e.Y - 1.0);
if (!ValidPosition(x, y))
return;
if (this.Capturing)
{
if (e.RightButton)
CancelCurrentTrace();
else if ((this.TraceStart.X == this.TraceEnd.X) && (this.TraceStart.Y == this.TraceEnd.Y) && e.LeftButton)
CancelCurrentTrace();
else
{
this.TraceEnd = new Point(x, y);
var dx = Math.Abs(this.TraceStart.X - this.TraceEnd.X);
var dy = Math.Abs(this.TraceStart.Y - this.TraceEnd.Y);
if (dx >= dy)
this.TraceEnd.Y = this.TraceStart.Y;
else
this.TraceEnd.X = this.TraceStart.X;
this.Board.SetTrace(this.TraceStart, this.TraceEnd);
this.Board.SaveForUndo();
this.TraceStart = this.TraceEnd;
this.TraceEnd = new Point(x, y);
dx = Math.Abs(this.TraceStart.X - this.TraceEnd.X);
dy = Math.Abs(this.TraceStart.Y - this.TraceEnd.Y);
if (dx >= dy)
this.TraceEnd.Y = this.TraceStart.Y;
else
this.TraceEnd.X = this.TraceStart.X;
this.Board.SetHighlight(this.TraceStart, this.TraceEnd);
}
}
else if (e.RightButton)
DeleteTraces(x, y);
else
{
this.TraceStart = this.TraceEnd = new Point(x, y);
this.Board.SetHighlight(this.TraceStart, this.TraceEnd);
this.Capturing = true;
this.CaptureSender = sender;
if (this.Capture != null)
this.Capture(sender, null);
}
}
public void OnMouseMove(object sender, MouseCaptureArgs e)
{
if (this.ViewMode != ViewMode.Normal)
return;
var x = (int)(e.X - 1.0);
var y = (int)(e.Y - 1.0);
if (!ValidPosition(x, y))
return;
if (this.Capturing)
{
this.TraceEnd = new Point(x, y);
var dx = Math.Abs(this.TraceStart.X - this.TraceEnd.X);
var dy = Math.Abs(this.TraceStart.Y - this.TraceEnd.Y);
if (dx >= dy)
this.TraceEnd.Y = this.TraceStart.Y;
else
this.TraceEnd.X = this.TraceStart.X;
this.Board.SetHighlight(this.TraceStart, this.TraceEnd);
}
else
this.Board.HighlightNode(x, y);
}
public void OnMouseUp(object sender, MouseCaptureArgs e)
{
}
private void CancelCurrentTrace()
{
if (this.Capturing)
{
this.Capturing = false;
this.Board.DeselectHighlights();
if (this.Release != null)
this.Release(this.CaptureSender, null);
}
}
private void DeleteTraces(int x, int y)
{
if (this.Board.PadArray[y, x].HorzPad)
{
this.Board.PadArray[y, x].HorzPad = false;
this.Board.PadArray[y, x].HorzTrace = false;
this.Board.PadArray[y, x].HorzJunction = false;
int tx = x;
do
{
this.Board.PadArray[y, tx].HorzTrace = false;
this.Board.PadArray[y, tx].HorzJunction = false;
tx--;
} while ((tx > 0) && !this.Board.PadArray[y, tx].HorzPad);
tx = x;
do
{
this.Board.PadArray[y, tx].HorzTrace = false;
this.Board.PadArray[y, tx].HorzJunction = false;
tx++;
} while ((tx < Circuit.WIDTH) && !this.Board.PadArray[y, tx].HorzPad);
if (tx < Circuit.WIDTH)
this.Board.PadArray[y, tx].HorzJunction = false;
}
if (this.Board.PadArray[y, x].VertPad)
{
this.Board.PadArray[y, x].VertPad = false;
this.Board.PadArray[y, x].VertTrace = false;
this.Board.PadArray[y, x].VertJunction = false;
int ty = y;
do
{
this.Board.PadArray[ty, x].VertTrace = false;
this.Board.PadArray[ty, x].VertJunction = false;
ty--;
} while ((ty > 0) && !this.Board.PadArray[ty, x].VertPad);
ty = y;
do
{
this.Board.PadArray[ty, x].VertTrace = false;
this.Board.PadArray[ty, x].VertJunction = false;
ty++;
} while ((ty < Circuit.HEIGHT) && !this.Board.PadArray[ty, x].VertPad);
if (ty < Circuit.HEIGHT)
this.Board.PadArray[ty, x].VertJunction = false;
}
this.Board.Clean();
this.Board.SaveForUndo();
}
private bool ValidPosition(int x, int y)
{
return (x >= 0) && (x < Circuit.WIDTH) && (y >= 0) && (y < Circuit.HEIGHT);
}
// todo: finish implementing this
public ICommand PrintCommand { get { return new RelayCommand<Visual>(OnPrint); } }
private void OnPrint(Visual visual)
{
PrintDialog dlg = new PrintDialog();
if (dlg.ShowDialog().Value)
dlg.PrintVisual(visual, "Perfy Circuit");
}
public ICommand ExportImageCommand { get { return new RelayCommand<Visual>(OnExportImage); } }
private void OnExportImage(Visual visual)
{
var dlg = new SaveFileDialogViewModel
{
Title = "Export Circuit",
FileName = "",
//Filter = "All Image Files (*.bmp;*.gif;*.jpg;*.jpeg;*.jpe;*.jfif;*.png;*.tiff;*.tga)|*.bmp;*.gif;*.jpg;*.jpeg;*.jpe;*.jfif;*.png;*.tiff;*.tga|BMP (*.bmp)|*.bmp|GIF (*.gif)|*.gif|JPG (*.jpg;*.jpeg;*.jpe;*.jfif)|*.jpg;*.jpeg;*.jpe;*.jfif|PNG (*.png)|*.png|TIFF (*.tiff)|*.tiff|TGA (*.tga)|*.tga",
Filter = "PNG FIle (*.png)|*.png",
};
if (dlg.Show(this.Dialogs) != System.Windows.Forms.DialogResult.OK)
return;
try
{
using (var memstream = GenerateImage(visual))
using (FileStream fstream = File.OpenWrite(dlg.FileName))
{
memstream.WriteTo(fstream);
fstream.Flush();
fstream.Close();
}
}
catch (Exception e)
{
new MessageBoxViewModel("Error exporting image: " + e.Message, "Error").Show(this.Dialogs);
}
}
public MemoryStream GenerateImage(Visual visual)
{
BitmapEncoder encoder = new PngBitmapEncoder();
RenderTargetBitmap rtb = CaptureScreen(visual);
MemoryStream file = new MemoryStream();
encoder.Frames.Add(BitmapFrame.Create(rtb));
encoder.Save(file);
return file;
}
// standard pcb pitch is 0.1 inch, so a Perfy+ board is 3.8 x 2.6 inches. in reality it's larger but in Perfy board is 38 x 26 squares, and we're only concerned about the holes
// lining up. this routine generates an appropriately sized image at 32 pixels per inch.
private static RenderTargetBitmap CaptureScreen(Visual target)
{
if (target == null)
{
return null;
}
Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
RenderTargetBitmap rtb = new RenderTargetBitmap(38 * 96, 26 * 96, 96, 96, PixelFormats.Pbgra32);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(target);
ctx.DrawRectangle(vb, null, new Rect(new Point(), new Point(38 * 96, 26 * 96)));
}
rtb.Render(dv);
return rtb;
}
}
}
| |
// 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.Text;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System
{
internal static class UriHelper
{
internal static ReadOnlySpan<byte> HexUpperChars => new byte[16]
{
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',
(byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F'
};
internal static readonly Encoding s_noFallbackCharUTF8 = Encoding.GetEncoding(
Encoding.UTF8.CodePage, new EncoderReplacementFallback(""), new DecoderReplacementFallback(""));
// http://host/Path/Path/File?Query is the base of
// - http://host/Path/Path/File/ ... (those "File" words may be different in semantic but anyway)
// - http://host/Path/Path/#Fragment
// - http://host/Path/Path/?Query
// - http://host/Path/Path/MoreDir/ ...
// - http://host/Path/Path/OtherFile?Query
// - http://host/Path/Path/Fl
// - http://host/Path/Path/
//
// It is not a base for
// - http://host/Path/Path (that last "Path" is not considered as a directory)
// - http://host/Path/Path?Query
// - http://host/Path/Path#Fragment
// - http://host/Path/Path2/
// - http://host/Path/Path2/MoreDir
// - http://host/Path/File
//
// ASSUMES that strings like http://host/Path/Path/MoreDir/../../ have been canonicalized before going to this method.
// ASSUMES that back slashes already have been converted if applicable.
//
internal static unsafe bool TestForSubPath(char* selfPtr, ushort selfLength, char* otherPtr, ushort otherLength,
bool ignoreCase)
{
ushort i = 0;
char chSelf;
char chOther;
bool AllSameBeforeSlash = true;
for (; i < selfLength && i < otherLength; ++i)
{
chSelf = *(selfPtr + i);
chOther = *(otherPtr + i);
if (chSelf == '?' || chSelf == '#')
{
// survived so far and selfPtr does not have any more path segments
return true;
}
// If selfPtr terminates a path segment, so must otherPtr
if (chSelf == '/')
{
if (chOther != '/')
{
// comparison has failed
return false;
}
// plus the segments must be the same
if (!AllSameBeforeSlash)
{
// comparison has failed
return false;
}
//so far so good
AllSameBeforeSlash = true;
continue;
}
// if otherPtr terminates then selfPtr must not have any more path segments
if (chOther == '?' || chOther == '#')
{
break;
}
if (!ignoreCase)
{
if (chSelf != chOther)
{
AllSameBeforeSlash = false;
}
}
else
{
if (char.ToLowerInvariant(chSelf) != char.ToLowerInvariant(chOther))
{
AllSameBeforeSlash = false;
}
}
}
// If self is longer then it must not have any more path segments
for (; i < selfLength; ++i)
{
if ((chSelf = *(selfPtr + i)) == '?' || chSelf == '#')
{
return true;
}
if (chSelf == '/')
{
return false;
}
}
//survived by getting to the end of selfPtr
return true;
}
internal static string EscapeString(
string stringToEscape, // same name as public API
bool checkExistingEscaped, ReadOnlySpan<bool> unreserved, char forceEscape1 = '\0', char forceEscape2 = '\0')
{
if (stringToEscape is null)
{
throw new ArgumentNullException(nameof(stringToEscape));
}
if (stringToEscape.Length == 0)
{
return string.Empty;
}
// Get the table of characters that do not need to be escaped.
Debug.Assert(unreserved.Length == 0x80);
ReadOnlySpan<bool> noEscape = stackalloc bool[0];
if ((forceEscape1 | forceEscape2) == 0)
{
noEscape = unreserved;
}
else
{
Span<bool> tmp = stackalloc bool[0x80];
unreserved.CopyTo(tmp);
tmp[forceEscape1] = false;
tmp[forceEscape2] = false;
noEscape = tmp;
}
// If the whole string is made up of ASCII unreserved chars, just return it.
Debug.Assert(!noEscape['%'], "Need to treat % specially; it should be part of any escaped set");
int i = 0;
char c;
for (; i < stringToEscape.Length && (c = stringToEscape[i]) <= 0x7F && noEscape[c]; i++) ;
if (i == stringToEscape.Length)
{
return stringToEscape;
}
// Otherwise, create a ValueStringBuilder to store the escaped data into,
// append to it all of the noEscape chars we already iterated through,
// escape the rest, and return the result as a string.
var vsb = new ValueStringBuilder(stackalloc char[256]);
vsb.Append(stringToEscape.AsSpan(0, i));
EscapeStringToBuilder(stringToEscape.AsSpan(i), ref vsb, noEscape, checkExistingEscaped);
return vsb.ToString();
}
// forceX characters are always escaped if found
// destPos - starting offset in dest for output, on return this will be an exclusive "end" in the output.
// In case "dest" has lack of space it will be reallocated by preserving the _whole_ content up to current destPos
// Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos
[return: NotNullIfNotNull("dest")]
internal static char[]? EscapeString(
ReadOnlySpan<char> stringToEscape,
char[]? dest, ref int destPos,
bool checkExistingEscaped, char forceEscape1 = '\0', char forceEscape2 = '\0')
{
// Get the table of characters that do not need to be escaped.
ReadOnlySpan<bool> noEscape = stackalloc bool[0];
if ((forceEscape1 | forceEscape2) == 0)
{
noEscape = UnreservedReservedTable;
}
else
{
Span<bool> tmp = stackalloc bool[0x80];
UnreservedReservedTable.CopyTo(tmp);
tmp[forceEscape1] = false;
tmp[forceEscape2] = false;
noEscape = tmp;
}
// If the whole string is made up of ASCII unreserved chars, take a fast pasth. Per the contract, if
// dest is null, just return it. If it's not null, copy everything to it and update destPos accordingly;
// if that requires resizing it, do so.
Debug.Assert(!noEscape['%'], "Need to treat % specially in case checkExistingEscaped is true");
int i = 0;
char c;
for (; i < stringToEscape.Length && (c = stringToEscape[i]) <= 0x7F && noEscape[c]; i++) ;
if (i == stringToEscape.Length)
{
if (dest != null)
{
EnsureCapacity(dest, destPos, stringToEscape.Length);
stringToEscape.CopyTo(dest.AsSpan(destPos));
destPos += stringToEscape.Length;
}
return dest;
}
// Otherwise, create a ValueStringBuilder to store the escaped data into,
// append to it all of the noEscape chars we already iterated through, and
// escape the rest into the ValueStringBuilder.
var vsb = new ValueStringBuilder(stackalloc char[256]);
vsb.Append(stringToEscape.Slice(0, i));
EscapeStringToBuilder(stringToEscape.Slice(i), ref vsb, noEscape, checkExistingEscaped);
// Finally update dest with the result.
EnsureCapacity(dest, destPos, vsb.Length);
vsb.TryCopyTo(dest.AsSpan(destPos), out int charsWritten);
destPos += charsWritten;
return dest;
static void EnsureCapacity(char[]? dest, int destSize, int requiredSize)
{
if (dest == null || dest.Length - destSize < requiredSize)
{
Array.Resize(ref dest, destSize + requiredSize + 120); // 120 == arbitrary minimum-empty space copied from previous implementation
}
}
}
private static void EscapeStringToBuilder(
ReadOnlySpan<char> stringToEscape, ref ValueStringBuilder vsb,
ReadOnlySpan<bool> noEscape, bool checkExistingEscaped)
{
// Allocate enough stack space to hold any Rune's UTF8 encoding.
Span<byte> utf8Bytes = stackalloc byte[4];
// Then enumerate every rune in the input.
SpanRuneEnumerator e = stringToEscape.EnumerateRunes();
while (e.MoveNext())
{
Rune r = e.Current;
if (!r.IsAscii)
{
// The rune is non-ASCII, so encode it as UTF8, and escape each UTF8 byte.
r.TryEncodeToUtf8(utf8Bytes, out int bytesWritten);
foreach (byte b in utf8Bytes.Slice(0, bytesWritten))
{
vsb.Append('%');
vsb.Append((char)HexUpperChars[(b & 0xf0) >> 4]);
vsb.Append((char)HexUpperChars[b & 0xf]);
}
continue;
}
// If the value doesn't need to be escaped, append it and continue.
byte value = (byte)r.Value;
if (noEscape[value])
{
vsb.Append((char)value);
continue;
}
// If we're checking for existing escape sequences, then if this is the beginning of
// one, check the next two characters in the sequence. This is a little tricky to do
// as we're using an enumerator, but luckily it's a ref struct-based enumerator: we can
// make a copy and iterate through the copy without impacting the original, and then only
// push the original ahead if we find what we're looking for in the copy.
if (checkExistingEscaped && value == '%')
{
// If the next two characters are valid escaped ASCII, then just output them as-is.
SpanRuneEnumerator tmpEnumerator = e;
if (tmpEnumerator.MoveNext())
{
Rune r1 = tmpEnumerator.Current;
if (r1.IsAscii && IsHexDigit((char)r1.Value) && tmpEnumerator.MoveNext())
{
Rune r2 = tmpEnumerator.Current;
if (r2.IsAscii && IsHexDigit((char)r2.Value))
{
vsb.Append('%');
vsb.Append((char)r1.Value);
vsb.Append((char)r2.Value);
e = tmpEnumerator;
continue;
}
}
}
}
// Otherwise, append the escaped character.
vsb.Append('%');
vsb.Append((char)HexUpperChars[(value & 0xf0) >> 4]);
vsb.Append((char)HexUpperChars[value & 0xf]);
}
}
//
// This method will assume that any good Escaped Sequence will be unescaped in the output
// - Assumes Dest.Length - detPosition >= end-start
// - UnescapeLevel controls various modes of operation
// - Any "bad" escape sequence will remain as is or '%' will be escaped.
// - destPosition tells the starting index in dest for placing the result.
// On return destPosition tells the last character + 1 position in the "dest" array.
// - The control chars and chars passed in rsdvX parameters may be re-escaped depending on UnescapeLevel
// - It is a RARE case when Unescape actually needs escaping some characters mentioned above.
// For this reason it returns a char[] that is usually the same ref as the input "dest" value.
//
internal static unsafe char[] UnescapeString(string input, int start, int end, char[] dest,
ref int destPosition, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser? syntax,
bool isQuery)
{
fixed (char* pStr = input)
{
return UnescapeString(pStr, start, end, dest, ref destPosition, rsvd1, rsvd2, rsvd3, unescapeMode,
syntax, isQuery);
}
}
internal static unsafe char[] UnescapeString(char* pStr, int start, int end, char[] dest, ref int destPosition,
char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser? syntax, bool isQuery)
{
byte[]? bytes = null;
byte escapedReallocations = 0;
bool escapeReserved = false;
int next = start;
bool iriParsing = Uri.IriParsingStatic(syntax)
&& ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.EscapeUnescape);
char[]? unescapedChars = null;
while (true)
{
// we may need to re-pin dest[]
fixed (char* pDest = dest)
{
if ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.CopyOnly)
{
while (start < end)
pDest[destPosition++] = pStr[start++];
return dest;
}
while (true)
{
char ch = (char)0;
for (; next < end; ++next)
{
if ((ch = pStr[next]) == '%')
{
if ((unescapeMode & UnescapeMode.Unescape) == 0)
{
// re-escape, don't check anything else
escapeReserved = true;
}
else if (next + 2 < end)
{
ch = EscapedAscii(pStr[next + 1], pStr[next + 2]);
// Unescape a good sequence if full unescape is requested
if (unescapeMode >= UnescapeMode.UnescapeAll)
{
if (ch == Uri.c_DummyChar)
{
if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow)
{
// Should be a rare case where the app tries to feed an invalid escaped sequence
throw new UriFormatException(SR.net_uri_BadString);
}
continue;
}
}
// re-escape % from an invalid sequence
else if (ch == Uri.c_DummyChar)
{
if ((unescapeMode & UnescapeMode.Escape) != 0)
escapeReserved = true;
else
continue; // we should throw instead but since v1.0 would just print '%'
}
// Do not unescape '%' itself unless full unescape is requested
else if (ch == '%')
{
next += 2;
continue;
}
// Do not unescape a reserved char unless full unescape is requested
else if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3)
{
next += 2;
continue;
}
// Do not unescape a dangerous char unless it's V1ToStringFlags mode
else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0 && IsNotSafeForUnescape(ch))
{
next += 2;
continue;
}
else if (iriParsing && ((ch <= '\x9F' && IsNotSafeForUnescape(ch)) ||
(ch > '\x9F' && !IriHelper.CheckIriUnicodeRange(ch, isQuery))))
{
// check if unenscaping gives a char outside iri range
// if it does then keep it escaped
next += 2;
continue;
}
// unescape escaped char or escape %
break;
}
else if (unescapeMode >= UnescapeMode.UnescapeAll)
{
if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow)
{
// Should be a rare case where the app tries to feed an invalid escaped sequence
throw new UriFormatException(SR.net_uri_BadString);
}
// keep a '%' as part of a bogus sequence
continue;
}
else
{
escapeReserved = true;
}
// escape (escapeReserved==true) or otherwise unescape the sequence
break;
}
else if ((unescapeMode & (UnescapeMode.Unescape | UnescapeMode.UnescapeAll))
== (UnescapeMode.Unescape | UnescapeMode.UnescapeAll))
{
continue;
}
else if ((unescapeMode & UnescapeMode.Escape) != 0)
{
// Could actually escape some of the characters
if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3)
{
// found an unescaped reserved character -> escape it
escapeReserved = true;
break;
}
else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0
&& (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F')))
{
// found an unescaped reserved character -> escape it
escapeReserved = true;
break;
}
}
}
//copy off previous characters from input
while (start < next)
pDest[destPosition++] = pStr[start++];
if (next != end)
{
if (escapeReserved)
{
//escape that char
// Since this should be _really_ rare case, reallocate with constant size increase of 30 rsvd-type characters.
if (escapedReallocations == 0)
{
escapedReallocations = 30;
char[] newDest = new char[dest.Length + escapedReallocations * 3];
fixed (char* pNewDest = &newDest[0])
{
for (int i = 0; i < destPosition; ++i)
pNewDest[i] = pDest[i];
}
dest = newDest;
// re-pin new dest[] array
goto dest_fixed_loop_break;
}
else
{
--escapedReallocations;
EscapeAsciiChar(pStr[next], dest, ref destPosition);
escapeReserved = false;
start = ++next;
continue;
}
}
// unescaping either one Ascii or possibly multiple Unicode
if (ch <= '\x7F')
{
//ASCII
dest[destPosition++] = ch;
next += 3;
start = next;
continue;
}
// Unicode
int byteCount = 1;
// lazy initialization of max size, will reuse the array for next sequences
if ((object?)bytes == null)
bytes = new byte[end - next];
bytes[0] = (byte)ch;
next += 3;
while (next < end)
{
// Check on exit criterion
if ((ch = pStr[next]) != '%' || next + 2 >= end)
break;
// already made sure we have 3 characters in str
ch = EscapedAscii(pStr[next + 1], pStr[next + 2]);
//invalid hex sequence ?
if (ch == Uri.c_DummyChar)
break;
// character is not part of a UTF-8 sequence ?
else if (ch < '\x80')
break;
else
{
//a UTF-8 sequence
bytes[byteCount++] = (byte)ch;
next += 3;
}
}
if (unescapedChars == null || unescapedChars.Length < bytes.Length)
{
unescapedChars = new char[bytes.Length];
}
int charCount = s_noFallbackCharUTF8.GetChars(bytes, 0, byteCount, unescapedChars, 0);
start = next;
// match exact bytes
// Do not unescape chars not allowed by Iri
// need to check for invalid utf sequences that may not have given any chars
MatchUTF8Sequence(pDest, dest, ref destPosition, unescapedChars.AsSpan(0, charCount), charCount, bytes,
byteCount, isQuery, iriParsing);
}
if (next == end)
goto done;
}
dest_fixed_loop_break:;
}
}
done: return dest;
}
//
// Need to check for invalid utf sequences that may not have given any chars.
// We got the unescaped chars, we then re-encode them and match off the bytes
// to get the invalid sequence bytes that we just copy off
//
internal static unsafe void MatchUTF8Sequence(char* pDest, char[] dest, ref int destOffset, Span<char> unescapedChars,
int charCount, byte[] bytes, int byteCount, bool isQuery, bool iriParsing)
{
Span<byte> maxUtf8EncodedSpan = stackalloc byte[4];
int count = 0;
fixed (char* unescapedCharsPtr = unescapedChars)
{
for (int j = 0; j < charCount; ++j)
{
bool isHighSurr = char.IsHighSurrogate(unescapedCharsPtr[j]);
Span<byte> encodedBytes = maxUtf8EncodedSpan;
int bytesWritten = Encoding.UTF8.GetBytes(unescapedChars.Slice(j, isHighSurr ? 2 : 1), encodedBytes);
encodedBytes = encodedBytes.Slice(0, bytesWritten);
// we have to keep unicode chars outside Iri range escaped
bool inIriRange = false;
if (iriParsing)
{
if (!isHighSurr)
inIriRange = IriHelper.CheckIriUnicodeRange(unescapedChars[j], isQuery);
else
{
bool surrPair = false;
inIriRange = IriHelper.CheckIriUnicodeRange(unescapedChars[j], unescapedChars[j + 1],
ref surrPair, isQuery);
}
}
while (true)
{
// Escape any invalid bytes that were before this character
while (bytes[count] != encodedBytes[0])
{
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
EscapeAsciiChar((char)bytes[count++], dest, ref destOffset);
}
// check if all bytes match
bool allBytesMatch = true;
int k = 0;
for (; k < encodedBytes.Length; ++k)
{
if (bytes[count + k] != encodedBytes[k])
{
allBytesMatch = false;
break;
}
}
if (allBytesMatch)
{
count += encodedBytes.Length;
if (iriParsing)
{
if (!inIriRange)
{
// need to keep chars not allowed as escaped
for (int l = 0; l < encodedBytes.Length; ++l)
{
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
EscapeAsciiChar((char)encodedBytes[l], dest, ref destOffset);
}
}
else if (!UriHelper.IsBidiControlCharacter(unescapedCharsPtr[j]) || !UriParser.DontKeepUnicodeBidiFormattingCharacters)
{
//copy chars
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
pDest[destOffset++] = unescapedCharsPtr[j];
if (isHighSurr)
{
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
pDest[destOffset++] = unescapedCharsPtr[j + 1];
}
}
}
else
{
//copy chars
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
pDest[destOffset++] = unescapedCharsPtr[j];
if (isHighSurr)
{
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
pDest[destOffset++] = unescapedCharsPtr[j + 1];
}
}
break; // break out of while (true) since we've matched this char bytes
}
else
{
// copy bytes till place where bytes don't match
for (int l = 0; l < k; ++l)
{
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
EscapeAsciiChar((char)bytes[count++], dest, ref destOffset);
}
}
}
if (isHighSurr) j++;
}
}
// Include any trailing invalid sequences
while (count < byteCount)
{
Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset.");
EscapeAsciiChar((char)bytes[count++], dest, ref destOffset);
}
}
internal static void EscapeAsciiChar(char ch, char[] to, ref int pos)
{
to[pos++] = '%';
to[pos++] = (char)HexUpperChars[(ch & 0xf0) >> 4];
to[pos++] = (char)HexUpperChars[ch & 0xf];
}
internal static char EscapedAscii(char digit, char next)
{
if (!(((digit >= '0') && (digit <= '9'))
|| ((digit >= 'A') && (digit <= 'F'))
|| ((digit >= 'a') && (digit <= 'f'))))
{
return Uri.c_DummyChar;
}
int res = (digit <= '9')
? ((int)digit - (int)'0')
: (((digit <= 'F')
? ((int)digit - (int)'A')
: ((int)digit - (int)'a'))
+ 10);
if (!(((next >= '0') && (next <= '9'))
|| ((next >= 'A') && (next <= 'F'))
|| ((next >= 'a') && (next <= 'f'))))
{
return Uri.c_DummyChar;
}
return (char)((res << 4) + ((next <= '9')
? ((int)next - (int)'0')
: (((next <= 'F')
? ((int)next - (int)'A')
: ((int)next - (int)'a'))
+ 10)));
}
internal const string RFC3986ReservedMarks = @";/?:@&=+$,#[]!'()*";
private const string RFC2396ReservedMarks = @";/?:@&=+$,";
private const string AdditionalUnsafeToUnescape = @"%\#"; // While not specified as reserved, these are still unsafe to unescape.
// When unescaping in safe mode, do not unescape the RFC 3986 reserved set:
// gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
// / "*" / "+" / "," / ";" / "="
//
// In addition, do not unescape the following unsafe characters:
// excluded = "%" / "\"
//
// This implementation used to use the following variant of the RFC 2396 reserved set.
// That behavior is now disabled by default, and is controlled by a UriSyntax property.
// reserved = ";" | "/" | "?" | "@" | "&" | "=" | "+" | "$" | ","
// excluded = control | "#" | "%" | "\"
internal static bool IsNotSafeForUnescape(char ch)
{
if (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F'))
{
return true;
}
else if (UriParser.DontEnableStrictRFC3986ReservedCharacterSets)
{
if ((ch != ':' && (RFC2396ReservedMarks.IndexOf(ch) >= 0) || (AdditionalUnsafeToUnescape.IndexOf(ch) >= 0)))
{
return true;
}
}
else if ((RFC3986ReservedMarks.IndexOf(ch) >= 0) || (AdditionalUnsafeToUnescape.IndexOf(ch) >= 0))
{
return true;
}
return false;
}
// "Reserved" and "Unreserved" characters are based on RFC 3986.
internal static ReadOnlySpan<bool> UnreservedReservedTable => new bool[0x80]
{
// true for all ASCII letters and digits, as well as the RFC3986 reserved characters, unreserved characters, and hash
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, true, false, true, true, false, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, true,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, true,
false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, false, false, false, true, false,
};
internal static bool IsUnreserved(int c) => c < 0x80 && UnreservedTable[c];
internal static ReadOnlySpan<bool> UnreservedTable => new bool[0x80]
{
// true for all ASCII letters and digits, as well as the RFC3986 unreserved marks '-', '_', '.', and '~'
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, false,
true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false,
false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, true,
false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, false, false, false, true, false,
};
//
// Is this a gen delim char from RFC 3986
//
internal static bool IsGenDelim(char ch)
{
return (ch == ':' || ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']' || ch == '@');
}
internal static readonly char[] s_WSchars = new char[] { ' ', '\n', '\r', '\t' };
internal static bool IsLWS(char ch)
{
return (ch <= ' ') && (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t');
}
internal static bool IsAsciiLetter(char character) =>
(((uint)character - 'A') & ~0x20) < 26;
internal static bool IsAsciiLetterOrDigit(char character) =>
((((uint)character - 'A') & ~0x20) < 26) ||
(((uint)character - '0') < 10);
internal static bool IsHexDigit(char character) =>
((((uint)character - 'A') & ~0x20) < 6) ||
(((uint)character - '0') < 10);
//
// Is this a Bidirectional control char.. These get stripped
//
internal static bool IsBidiControlCharacter(char ch)
{
return (ch == '\u200E' /*LRM*/ || ch == '\u200F' /*RLM*/ || ch == '\u202A' /*LRE*/ ||
ch == '\u202B' /*RLE*/ || ch == '\u202C' /*PDF*/ || ch == '\u202D' /*LRO*/ ||
ch == '\u202E' /*RLO*/);
}
//
// Strip Bidirectional control characters from this string
//
internal static unsafe string StripBidiControlCharacter(char* strToClean, int start, int length)
{
if (length <= 0) return "";
char[] cleanStr = new char[length];
int count = 0;
for (int i = 0; i < length; ++i)
{
char c = strToClean[start + i];
if (c < '\u200E' || c > '\u202E' || !IsBidiControlCharacter(c))
{
cleanStr[count++] = c;
}
}
return new string(cleanStr, 0, count);
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Candles.Algo
File: CandleManagerContainer.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Candles
{
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using Ecng.ComponentModel;
using MoreLinq;
using StockSharp.Logging;
using StockSharp.Localization;
/// <summary>
/// The standard container that stores candles data.
/// </summary>
public class CandleManagerContainer : Disposable, ICandleManagerContainer
{
private static readonly MemoryStatisticsValue<Candle> _candleStat = new MemoryStatisticsValue<Candle>(LocalizedStrings.Candles);
static CandleManagerContainer()
{
MemoryStatistics.Instance.Values.Add(_candleStat);
}
private sealed class SeriesInfo
{
private readonly CandleManagerContainer _container;
private const int _candlesCapacity = 10000;
private readonly SynchronizedDictionary<long, SynchronizedSet<Candle>> _byTime = new SynchronizedDictionary<long, SynchronizedSet<Candle>>(_candlesCapacity);
private readonly SynchronizedLinkedList<Candle> _allCandles = new SynchronizedLinkedList<Candle>();
private long _firstCandleTime;
private long _lastCandleTime;
public SeriesInfo(CandleManagerContainer container)
{
if (container == null)
throw new ArgumentNullException(nameof(container));
_container = container;
}
public int CandleCount => _allCandles.Count;
public void Reset(DateTimeOffset from)
{
_firstCandleTime = from.UtcTicks;
_byTime.Clear();
lock (_allCandles.SyncRoot)
{
_candleStat.Remove(_allCandles);
_allCandles.Clear();
}
}
public bool AddCandle(Candle candle)
{
if (candle == null)
throw new ArgumentNullException(nameof(candle));
var ticks = candle.OpenTime.UtcTicks;
if (!_byTime.SafeAdd(ticks).TryAdd(candle))
return false;
_allCandles.AddLast(candle);
_candleStat.Add(candle);
_lastCandleTime = ticks;
RecycleCandles();
return true;
}
public void RecycleCandles()
{
if (_container.CandlesKeepTime == TimeSpan.Zero)
return;
var diff = _lastCandleTime - _firstCandleTime;
if (diff <= _container._maxCandlesKeepTime)
return;
_firstCandleTime = _lastCandleTime - _container.CandlesKeepTime.Ticks;
_allCandles.SyncDo(list =>
{
while (list.Count > 0)
{
if (list.First.Value.OpenTime.UtcTicks >= _firstCandleTime)
break;
_candleStat.Remove(list.First.Value);
list.RemoveFirst();
}
});
_byTime.SyncGet(d => d.RemoveWhere(p => p.Key < _firstCandleTime));
}
public IEnumerable<Candle> GetCandles(DateTimeOffset time)
{
var candles = _byTime.TryGetValue(time.UtcTicks);
return candles != null ? candles.SyncGet(c => c.ToArray()) : Enumerable.Empty<Candle>();
}
public IEnumerable<Candle> GetCandles()
{
return _allCandles.SyncGet(c => c.ToArray());
}
public Candle GetCandle(int candleIndex)
{
return _allCandles.SyncGet(c => c.ElementAtFromEndOrDefault(candleIndex));
}
}
private readonly SynchronizedDictionary<CandleSeries, SeriesInfo> _info = new SynchronizedDictionary<CandleSeries, SeriesInfo>();
private long _maxCandlesKeepTime;
/// <summary>
/// Initializes a new instance of the <see cref="CandleManagerContainer"/>.
/// </summary>
public CandleManagerContainer()
{
CandlesKeepTime = TimeSpan.FromDays(2);
}
private TimeSpan _candlesKeepTime;
/// <summary>
/// Candles storage time in memory. The default is 2 days.
/// </summary>
/// <remarks>
/// If the value is set to <see cref="TimeSpan.Zero"/> then candles will not be deleted.
/// </remarks>
public TimeSpan CandlesKeepTime
{
get { return _candlesKeepTime; }
set
{
if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str647);
_candlesKeepTime = value;
_maxCandlesKeepTime = (long)(value.Ticks * 1.5);
_info.SyncDo(d => d.ForEach(p => p.Value.RecycleCandles()));
}
}
/// <summary>
/// To add a candle for the series.
/// </summary>
/// <param name="series">Candles series.</param>
/// <param name="candle">Candle.</param>
/// <returns><see langword="true" /> if the candle is not added previously, otherwise, <see langword="false" />.</returns>
public bool AddCandle(CandleSeries series, Candle candle)
{
var info = GetInfo(series);
if (info == null)
throw new InvalidOperationException(LocalizedStrings.Str648Params.Put(series));
return info.AddCandle(candle);
}
/// <summary>
/// To get all associated with the series candles for the <paramref name="time" /> period.
/// </summary>
/// <param name="series">Candles series.</param>
/// <param name="time">The candle period.</param>
/// <returns>Candles.</returns>
public IEnumerable<Candle> GetCandles(CandleSeries series, DateTimeOffset time)
{
var info = GetInfo(series);
return info != null ? info.GetCandles(time) : Enumerable.Empty<Candle>();
}
/// <summary>
/// To get all associated with the series candles.
/// </summary>
/// <param name="series">Candles series.</param>
/// <returns>Candles.</returns>
public IEnumerable<Candle> GetCandles(CandleSeries series)
{
var info = GetInfo(series);
return info != null ? info.GetCandles() : Enumerable.Empty<Candle>();
}
/// <summary>
/// To get a candle by the index.
/// </summary>
/// <param name="series">Candles series.</param>
/// <param name="candleIndex">The candle's position number from the end.</param>
/// <returns>The found candle. If the candle does not exist, then <see langword="null" /> will be returned.</returns>
public Candle GetCandle(CandleSeries series, int candleIndex)
{
if (candleIndex < 0)
throw new ArgumentOutOfRangeException(nameof(candleIndex));
var info = GetInfo(series);
return info != null ? info.GetCandle(candleIndex) : null;
}
/// <summary>
/// To get candles by the series and date range.
/// </summary>
/// <param name="series">Candles series.</param>
/// <param name="timeRange">The date range which should include candles. The <see cref="Candle.OpenTime"/> value is taken into consideration.</param>
/// <returns>Found candles.</returns>
public IEnumerable<Candle> GetCandles(CandleSeries series, Range<DateTimeOffset> timeRange)
{
return GetCandles(series)
.Where(c => timeRange.Contains(c.OpenTime))
.OrderBy(c => c.OpenTime);
}
/// <summary>
/// To get candles by the series and the total number.
/// </summary>
/// <param name="series">Candles series.</param>
/// <param name="candleCount">The number of candles that should be returned.</param>
/// <returns>Found candles.</returns>
public IEnumerable<Candle> GetCandles(CandleSeries series, int candleCount)
{
if (candleCount <= 0)
throw new ArgumentOutOfRangeException(nameof(candleCount));
return GetCandles(series)
.OrderByDescending(c => c.OpenTime)
.Take(candleCount)
.OrderBy(c => c.OpenTime);
}
/// <summary>
/// To get the number of candles.
/// </summary>
/// <param name="series">Candles series.</param>
/// <returns>Number of candles.</returns>
public int GetCandleCount(CandleSeries series)
{
var info = GetInfo(series);
return info == null ? 0 : info.CandleCount;
}
/// <summary>
/// To notify the container about the start of the candles getting for the series.
/// </summary>
/// <param name="series">Candles series.</param>
/// <param name="from">The initial date from which the candles will be get.</param>
/// <param name="to">The final date by which the candles will be get.</param>
public void Start(CandleSeries series, DateTimeOffset from, DateTimeOffset to)
{
if (series == null)
throw new ArgumentNullException(nameof(series));
var info = _info.SafeAdd(series, key => new SeriesInfo(this));
info.Reset(from);
}
private SeriesInfo GetInfo(CandleSeries series)
{
if (series == null)
throw new ArgumentNullException(nameof(series));
return _info.TryGetValue(series);
}
/// <summary>
/// Release resources.
/// </summary>
protected override void DisposeManaged()
{
lock (_info.SyncRoot)
_info.Values.ForEach(i => i.Reset(default(DateTimeOffset)));
base.DisposeManaged();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Xml.Linq;
using Umbraco.Core.Auditing;
using Umbraco.Core.Events;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Publishing;
namespace Umbraco.Core.Services
{
/// <summary>
/// Represents the Media Service, which is an easy access to operations involving <see cref="IMedia"/>
/// </summary>
public class MediaService : IMediaService
{
private readonly IDatabaseUnitOfWorkProvider _uowProvider;
private readonly RepositoryFactory _repositoryFactory;
//Support recursive locks because some of the methods that require locking call other methods that require locking.
//for example, the Move method needs to be locked but this calls the Save method which also needs to be locked.
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
public MediaService(RepositoryFactory repositoryFactory)
: this(new PetaPocoUnitOfWorkProvider(), repositoryFactory)
{
}
public MediaService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory)
{
_uowProvider = provider;
_repositoryFactory = repositoryFactory;
}
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IMedia without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new media objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parentId">Id of Parent for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
public IMedia CreateMedia(string name, int parentId, string mediaTypeAlias, int userId = 0)
{
var mediaType = FindMediaTypeByAlias(mediaTypeAlias);
var media = new Models.Media(name, parentId, mediaType);
if (Creating.IsRaisedEventCancelled(new NewEventArgs<IMedia>(media, mediaTypeAlias, parentId), this))
{
media.WasCancelled = true;
return media;
}
media.CreatorId = userId;
Created.RaiseEvent(new NewEventArgs<IMedia>(media, false, mediaTypeAlias, parentId), this);
Audit.Add(AuditTypes.New, string.Format("Media '{0}' was created", name), media.CreatorId, media.Id);
return media;
}
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IMedia without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new media objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
public IMedia CreateMedia(string name, IMedia parent, string mediaTypeAlias, int userId = 0)
{
var mediaType = FindMediaTypeByAlias(mediaTypeAlias);
var media = new Models.Media(name, parent, mediaType);
if (Creating.IsRaisedEventCancelled(new NewEventArgs<IMedia>(media, mediaTypeAlias, parent), this))
{
media.WasCancelled = true;
return media;
}
media.CreatorId = userId;
Created.RaiseEvent(new NewEventArgs<IMedia>(media, false, mediaTypeAlias, parent), this);
Audit.Add(AuditTypes.New, string.Format("Media '{0}' was created", name), media.CreatorId, media.Id);
return media;
}
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// This method returns an <see cref="IMedia"/> object that has been persisted to the database
/// and therefor has an identity.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parentId">Id of Parent for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
public IMedia CreateMediaWithIdentity(string name, int parentId, string mediaTypeAlias, int userId = 0)
{
var mediaType = FindMediaTypeByAlias(mediaTypeAlias);
var media = new Models.Media(name, parentId, mediaType);
//NOTE: I really hate the notion of these Creating/Created events - they are so inconsistent, I've only just found
// out that in these 'WithIdentity' methods, the Saving/Saved events were not fired, wtf. Anyways, they're added now.
if (Creating.IsRaisedEventCancelled(new NewEventArgs<IMedia>(media, mediaTypeAlias, parentId), this))
{
media.WasCancelled = true;
return media;
}
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IMedia>(media), this))
{
media.WasCancelled = true;
return media;
}
//TODO: Once we fix up the transaction logic, these write locks should be replaced with
// an outter transaction instead.
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
media.CreatorId = userId;
repository.AddOrUpdate(media);
uow.Commit();
var xml = media.ToXml();
CreateAndSaveMediaXml(xml, media.Id, uow.Database);
}
}
Saved.RaiseEvent(new SaveEventArgs<IMedia>(media, false), this);
Created.RaiseEvent(new NewEventArgs<IMedia>(media, false, mediaTypeAlias, parentId), this);
Audit.Add(AuditTypes.New, string.Format("Media '{0}' was created with Id {1}", name, media.Id), media.CreatorId, media.Id);
return media;
}
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// This method returns an <see cref="IMedia"/> object that has been persisted to the database
/// and therefor has an identity.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
public IMedia CreateMediaWithIdentity(string name, IMedia parent, string mediaTypeAlias, int userId = 0)
{
var mediaType = FindMediaTypeByAlias(mediaTypeAlias);
var media = new Models.Media(name, parent, mediaType);
//NOTE: I really hate the notion of these Creating/Created events - they are so inconsistent, I've only just found
// out that in these 'WithIdentity' methods, the Saving/Saved events were not fired, wtf. Anyways, they're added now.
if (Creating.IsRaisedEventCancelled(new NewEventArgs<IMedia>(media, mediaTypeAlias, parent), this))
{
media.WasCancelled = true;
return media;
}
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IMedia>(media), this))
{
media.WasCancelled = true;
return media;
}
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
media.CreatorId = userId;
repository.AddOrUpdate(media);
uow.Commit();
var xml = media.ToXml();
CreateAndSaveMediaXml(xml, media.Id, uow.Database);
}
}
Saved.RaiseEvent(new SaveEventArgs<IMedia>(media, false), this);
Created.RaiseEvent(new NewEventArgs<IMedia>(media, false, mediaTypeAlias, parent), this);
Audit.Add(AuditTypes.New, string.Format("Media '{0}' was created with Id {1}", name, media.Id), media.CreatorId, media.Id);
return media;
}
/// <summary>
/// Gets an <see cref="IMedia"/> object by Id
/// </summary>
/// <param name="id">Id of the Content to retrieve</param>
/// <returns><see cref="IMedia"/></returns>
public IMedia GetById(int id)
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets an <see cref="IMedia"/> object by Id
/// </summary>
/// <param name="ids">Ids of the Media to retrieve</param>
/// <returns><see cref="IMedia"/></returns>
public IEnumerable<IMedia> GetByIds(IEnumerable<int> ids)
{
using (var repository = _repositoryFactory.CreateMediaRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids.ToArray());
}
}
/// <summary>
/// Gets an <see cref="IMedia"/> object by its 'UniqueId'
/// </summary>
/// <param name="key">Guid key of the Media to retrieve</param>
/// <returns><see cref="IMedia"/></returns>
public IMedia GetById(Guid key)
{
using (var repository = _repositoryFactory.CreateMediaRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IMedia>.Builder.Where(x => x.Key == key);
var contents = repository.GetByQuery(query);
return contents.SingleOrDefault();
}
}
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by Level
/// </summary>
/// <param name="level">The level to retrieve Media from</param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetByLevel(int level)
{
using (var repository = _repositoryFactory.CreateMediaRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IMedia>.Builder.Where(x => x.Level == level && !x.Path.StartsWith("-21"));
var contents = repository.GetByQuery(query);
return contents;
}
}
/// <summary>
/// Gets a specific version of an <see cref="IMedia"/> item.
/// </summary>
/// <param name="versionId">Id of the version to retrieve</param>
/// <returns>An <see cref="IMedia"/> item</returns>
public IMedia GetByVersion(Guid versionId)
{
using (var repository = _repositoryFactory.CreateMediaRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetByVersion(versionId);
}
}
/// <summary>
/// Gets a collection of an <see cref="IMedia"/> objects versions by Id
/// </summary>
/// <param name="id"></param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetVersions(int id)
{
using (var repository = _repositoryFactory.CreateMediaRepository(_uowProvider.GetUnitOfWork()))
{
var versions = repository.GetAllVersions(id);
return versions;
}
}
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media.
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetAncestors(int id)
{
var media = GetById(id);
return GetAncestors(media);
}
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media.
/// </summary>
/// <param name="media"><see cref="IMedia"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetAncestors(IMedia media)
{
var ids = media.Path.Split(',').Where(x => x != "-1" && x != media.Id.ToString(CultureInfo.InvariantCulture)).Select(int.Parse).ToArray();
if (ids.Any() == false)
return new List<IMedia>();
using (var repository = _repositoryFactory.CreateMediaRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetChildren(int id)
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
var query = Query<IMedia>.Builder.Where(x => x.ParentId == id);
var medias = repository.GetByQuery(query);
return medias;
}
}
/// <summary>
/// Gets descendants of a <see cref="IMedia"/> object by its Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve descendants from</param>
/// <returns>An Enumerable flat list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetDescendants(int id)
{
var media = GetById(id);
return GetDescendants(media);
}
/// <summary>
/// Gets descendants of a <see cref="IMedia"/> object by its Id
/// </summary>
/// <param name="media">The Parent <see cref="IMedia"/> object to retrieve descendants from</param>
/// <returns>An Enumerable flat list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetDescendants(IMedia media)
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
var query = Query<IMedia>.Builder.Where(x => x.Path.StartsWith(media.Path) && x.Id != media.Id);
var medias = repository.GetByQuery(query);
return medias;
}
}
/// <summary>
/// Gets the parent of the current media as an <see cref="IMedia"/> item.
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/> to retrieve the parent from</param>
/// <returns>Parent <see cref="IMedia"/> object</returns>
public IMedia GetParent(int id)
{
var media = GetById(id);
return GetParent(media);
}
/// <summary>
/// Gets the parent of the current media as an <see cref="IMedia"/> item.
/// </summary>
/// <param name="media"><see cref="IMedia"/> to retrieve the parent from</param>
/// <returns>Parent <see cref="IMedia"/> object</returns>
public IMedia GetParent(IMedia media)
{
if (media.ParentId == -1 || media.ParentId == -21)
return null;
return GetById(media.ParentId);
}
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by the Id of the <see cref="IContentType"/>
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetMediaOfMediaType(int id)
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
var query = Query<IMedia>.Builder.Where(x => x.ContentTypeId == id);
var medias = repository.GetByQuery(query);
return medias;
}
}
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects, which reside at the first level / root
/// </summary>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetRootMedia()
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
var query = Query<IMedia>.Builder.Where(x => x.ParentId == -1);
var medias = repository.GetByQuery(query);
return medias;
}
}
/// <summary>
/// Gets a collection of an <see cref="IMedia"/> objects, which resides in the Recycle Bin
/// </summary>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
public IEnumerable<IMedia> GetMediaInRecycleBin()
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
var query = Query<IMedia>.Builder.Where(x => x.Path.Contains("-21"));
var medias = repository.GetByQuery(query);
return medias;
}
}
/// <summary>
/// Gets an <see cref="IMedia"/> object from the path stored in the 'umbracoFile' property.
/// </summary>
/// <param name="mediaPath">Path of the media item to retrieve (for example: /media/1024/koala_403x328.jpg)</param>
/// <returns><see cref="IMedia"/></returns>
public IMedia GetMediaByPath(string mediaPath)
{
var umbracoFileValue = mediaPath;
var isResized = mediaPath.Contains("_") && mediaPath.Contains("x");
// If the image has been resized we strip the "_403x328" of the original "/media/1024/koala_403x328.jpg" url.
if (isResized)
{
var underscoreIndex = mediaPath.LastIndexOf('_');
var dotIndex = mediaPath.LastIndexOf('.');
umbracoFileValue = string.Concat(mediaPath.Substring(0, underscoreIndex), mediaPath.Substring(dotIndex));
}
var sql = new Sql()
.Select("*")
.From<PropertyDataDto>()
.InnerJoin<PropertyTypeDto>()
.On<PropertyDataDto, PropertyTypeDto>(left => left.PropertyTypeId, right => right.Id)
.Where<PropertyTypeDto>(x => x.Alias == "umbracoFile")
.Where<PropertyDataDto>(x => x.VarChar == umbracoFileValue);
using (var uow = _uowProvider.GetUnitOfWork())
{
var propertyDataDto = uow.Database.Fetch<PropertyDataDto, PropertyTypeDto>(sql).FirstOrDefault();
return propertyDataDto == null ? null : GetById(propertyDataDto.NodeId);
}
}
/// <summary>
/// Checks whether an <see cref="IMedia"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/></param>
/// <returns>True if the media has any children otherwise False</returns>
public bool HasChildren(int id)
{
using (var repository = _repositoryFactory.CreateMediaRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IMedia>.Builder.Where(x => x.ParentId == id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// Moves an <see cref="IMedia"/> object to a new location
/// </summary>
/// <param name="media">The <see cref="IMedia"/> to move</param>
/// <param name="parentId">Id of the Media's new Parent</param>
/// <param name="userId">Id of the User moving the Media</param>
public void Move(IMedia media, int parentId, int userId = 0)
{
if (media == null) throw new ArgumentNullException("media");
using (new WriteLock(Locker))
{
//This ensures that the correct method is called if this method is used to Move to recycle bin.
if (parentId == -21)
{
MoveToRecycleBin(media, userId);
return;
}
if (Moving.IsRaisedEventCancelled(new MoveEventArgs<IMedia>(media, parentId), this))
return;
media.ParentId = parentId;
if (media.Trashed)
{
media.ChangeTrashedState(false, parentId);
}
Save(media, userId);
//Ensure that relevant properties are updated on children
var children = GetChildren(media.Id).ToArray();
if (children.Any())
{
var parentPath = media.Path;
var parentLevel = media.Level;
var parentTrashed = media.Trashed;
var updatedDescendants = UpdatePropertiesOnChildren(children, parentPath, parentLevel, parentTrashed);
Save(updatedDescendants, userId);
}
Moved.RaiseEvent(new MoveEventArgs<IMedia>(media, false, parentId), this);
Audit.Add(AuditTypes.Move, "Move Media performed by user", userId, media.Id);
}
}
/// <summary>
/// Deletes an <see cref="IMedia"/> object by moving it to the Recycle Bin
/// </summary>
/// <param name="media">The <see cref="IMedia"/> to delete</param>
/// <param name="userId">Id of the User deleting the Media</param>
public void MoveToRecycleBin(IMedia media, int userId = 0)
{
if (media == null) throw new ArgumentNullException("media");
if (Trashing.IsRaisedEventCancelled(new MoveEventArgs<IMedia>(media, -21), this))
return;
//Find Descendants, which will be moved to the recycle bin along with the parent/grandparent.
var descendants = GetDescendants(media).OrderBy(x => x.Level).ToList();
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
//Remove 'published' xml from the cmsContentXml table for the unpublished media
uow.Database.Delete<ContentXmlDto>("WHERE nodeId = @Id", new { Id = media.Id });
media.ChangeTrashedState(true, -21);
repository.AddOrUpdate(media);
//Loop through descendants to update their trash state, but ensuring structure by keeping the ParentId
foreach (var descendant in descendants)
{
//Remove 'published' xml from the cmsContentXml table for the unpublished media
uow.Database.Delete<ContentXmlDto>("WHERE nodeId = @Id", new { Id = descendant.Id });
descendant.ChangeTrashedState(true, descendant.ParentId);
repository.AddOrUpdate(descendant);
}
uow.Commit();
}
Trashed.RaiseEvent(new MoveEventArgs<IMedia>(media, false, -21), this);
Audit.Add(AuditTypes.Move, "Move Media to Recycle Bin performed by user", userId, media.Id);
}
/// <summary>
/// Empties the Recycle Bin by deleting all <see cref="IMedia"/> that resides in the bin
/// </summary>
public void EmptyRecycleBin()
{
using (new WriteLock(Locker))
{
List<int> ids;
List<string> files;
bool success;
var nodeObjectType = new Guid(Constants.ObjectTypes.Media);
using (var repository = _repositoryFactory.CreateRecycleBinRepository(_uowProvider.GetUnitOfWork()))
{
ids = repository.GetIdsOfItemsInRecycleBin(nodeObjectType);
files = repository.GetFilesInRecycleBin(nodeObjectType);
if (EmptyingRecycleBin.IsRaisedEventCancelled(new RecycleBinEventArgs(nodeObjectType, ids, files), this))
return;
success = repository.EmptyRecycleBin(nodeObjectType);
if (success)
repository.DeleteFiles(files);
}
EmptiedRecycleBin.RaiseEvent(new RecycleBinEventArgs(nodeObjectType, ids, files, success), this);
}
Audit.Add(AuditTypes.Delete, "Empty Media Recycle Bin performed by user", 0, -21);
}
/// <summary>
/// Deletes all media of specified type. All children of deleted media is moved to Recycle Bin.
/// </summary>
/// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks>
/// <param name="mediaTypeId">Id of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user deleting the media</param>
public void DeleteMediaOfType(int mediaTypeId, int userId = 0)
{
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
//NOTE What about media that has the contenttype as part of its composition?
//The ContentType has to be removed from the composition somehow as it would otherwise break
//Dbl.check+test that the ContentType's Id is removed from the ContentType2ContentType table
var query = Query<IMedia>.Builder.Where(x => x.ContentTypeId == mediaTypeId);
var contents = repository.GetByQuery(query).ToArray();
if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IMedia>(contents), this))
return;
foreach (var content in contents.OrderByDescending(x => x.ParentId))
{
//Look for children of current content and move that to trash before the current content is deleted
var c = content;
var childQuery = Query<IMedia>.Builder.Where(x => x.Path.StartsWith(c.Path));
var children = repository.GetByQuery(childQuery);
foreach (var child in children)
{
if (child.ContentType.Id != mediaTypeId)
MoveToRecycleBin(child, userId);
}
//Permantly delete the content
Delete(content, userId);
}
}
Audit.Add(AuditTypes.Delete, "Delete Media items by Type performed by user", userId, -1);
}
}
/// <summary>
/// Permanently deletes an <see cref="IMedia"/> object as well as all of its Children.
/// </summary>
/// <remarks>
/// Please note that this method will completely remove the Media from the database,
/// as well as associated media files from the file system.
/// </remarks>
/// <param name="media">The <see cref="IMedia"/> to delete</param>
/// <param name="userId">Id of the User deleting the Media</param>
public void Delete(IMedia media, int userId = 0)
{
if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IMedia>(media), this))
return;
//Delete children before deleting the 'possible parent'
var children = GetChildren(media.Id);
foreach (var child in children)
{
Delete(child, userId);
}
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
repository.Delete(media);
uow.Commit();
}
Deleted.RaiseEvent(new DeleteEventArgs<IMedia>(media, false), this);
Audit.Add(AuditTypes.Delete, "Delete Media performed by user", userId, media.Id);
}
/// <summary>
/// Permanently deletes versions from an <see cref="IMedia"/> object prior to a specific date.
/// This method will never delete the latest version of a content item.
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/> object to delete versions from</param>
/// <param name="versionDate">Latest version date</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
public void DeleteVersions(int id, DateTime versionDate, int userId = 0)
{
if (DeletingVersions.IsRaisedEventCancelled(new DeleteRevisionsEventArgs(id, dateToRetain: versionDate), this))
return;
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
repository.DeleteVersions(id, versionDate);
uow.Commit();
}
DeletedVersions.RaiseEvent(new DeleteRevisionsEventArgs(id, false, dateToRetain: versionDate), this);
Audit.Add(AuditTypes.Delete, "Delete Media by version date performed by user", userId, -1);
}
/// <summary>
/// Permanently deletes specific version(s) from an <see cref="IMedia"/> object.
/// This method will never delete the latest version of a content item.
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/> object to delete a version from</param>
/// <param name="versionId">Id of the version to delete</param>
/// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
public void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0)
{
if (DeletingVersions.IsRaisedEventCancelled(new DeleteRevisionsEventArgs(id, specificVersion: versionId), this))
return;
if (deletePriorVersions)
{
var content = GetByVersion(versionId);
DeleteVersions(id, content.UpdateDate, userId);
}
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
repository.DeleteVersion(versionId);
uow.Commit();
}
DeletedVersions.RaiseEvent(new DeleteRevisionsEventArgs(id, false, specificVersion: versionId), this);
Audit.Add(AuditTypes.Delete, "Delete Media by version performed by user", userId, -1);
}
/// <summary>
/// Saves a single <see cref="IMedia"/> object
/// </summary>
/// <param name="media">The <see cref="IMedia"/> to save</param>
/// <param name="userId">Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
public void Save(IMedia media, int userId = 0, bool raiseEvents = true)
{
if (raiseEvents)
{
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IMedia>(media), this))
return;
}
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
media.CreatorId = userId;
repository.AddOrUpdate(media);
uow.Commit();
var xml = media.ToXml();
CreateAndSaveMediaXml(xml, media.Id, uow.Database);
}
}
if (raiseEvents)
Saved.RaiseEvent(new SaveEventArgs<IMedia>(media, false), this);
Audit.Add(AuditTypes.Save, "Save Media performed by user", userId, media.Id);
}
/// <summary>
/// Saves a collection of <see cref="IMedia"/> objects
/// </summary>
/// <param name="medias">Collection of <see cref="IMedia"/> to save</param>
/// <param name="userId">Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
public void Save(IEnumerable<IMedia> medias, int userId = 0, bool raiseEvents = true)
{
if (raiseEvents)
{
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IMedia>(medias), this))
return;
}
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
foreach (var media in medias)
{
media.CreatorId = userId;
repository.AddOrUpdate(media);
}
//commit the whole lot in one go
uow.Commit();
foreach (var media in medias)
{
CreateAndSaveMediaXml(media.ToXml(), media.Id, uow.Database);
}
}
if (raiseEvents)
Saved.RaiseEvent(new SaveEventArgs<IMedia>(medias, false), this);
Audit.Add(AuditTypes.Save, "Save Media items performed by user", userId, -1);
}
}
/// <summary>
/// Sorts a collection of <see cref="IMedia"/> objects by updating the SortOrder according
/// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="items"></param>
/// <param name="userId"></param>
/// <param name="raiseEvents"></param>
/// <returns>True if sorting succeeded, otherwise False</returns>
public bool Sort(IEnumerable<IMedia> items, int userId = 0, bool raiseEvents = true)
{
if (raiseEvents)
{
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IMedia>(items), this))
return false;
}
var shouldBeCached = new List<IMedia>();
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaRepository(uow))
{
int i = 0;
foreach (var media in items)
{
//If the current sort order equals that of the media
//we don't need to update it, so just increment the sort order
//and continue.
if (media.SortOrder == i)
{
i++;
continue;
}
media.SortOrder = i;
i++;
repository.AddOrUpdate(media);
shouldBeCached.Add(media);
}
uow.Commit();
foreach (var content in shouldBeCached)
{
//Create and Save ContentXml DTO
var xml = content.ToXml();
CreateAndSaveMediaXml(xml, content.Id, uow.Database);
}
}
}
if (raiseEvents)
Saved.RaiseEvent(new SaveEventArgs<IMedia>(items, false), this);
Audit.Add(AuditTypes.Sort, "Sorting Media performed by user", userId, 0);
return true;
}
/// <summary>
/// Rebuilds all xml content in the cmsContentXml table for all media
/// </summary>
/// <param name="contentTypeIds">
/// Only rebuild the xml structures for the content type ids passed in, if none then rebuilds the structures
/// for all media
/// </param>
/// <returns>True if publishing succeeded, otherwise False</returns>
internal void RebuildXmlStructures(params int[] contentTypeIds)
{
using (new WriteLock(Locker))
{
var list = new List<IMedia>();
var uow = _uowProvider.GetUnitOfWork();
//First we're going to get the data that needs to be inserted before clearing anything, this
//ensures that we don't accidentally leave the content xml table empty if something happens
//during the lookup process.
if (contentTypeIds.Any() == false)
{
var rootMedia = GetRootMedia();
foreach (var media in rootMedia)
{
list.Add(media);
list.AddRange(GetDescendants(media));
}
}
else
{
list.AddRange(contentTypeIds.SelectMany(i => GetMediaOfMediaType(i).Where(media => media.Trashed == false)));
}
var xmlItems = new List<ContentXmlDto>();
foreach (var c in list)
{
var xml = c.ToXml();
xmlItems.Add(new ContentXmlDto { NodeId = c.Id, Xml = xml.ToString(SaveOptions.None) });
}
//Ok, now we need to remove the data and re-insert it, we'll do this all in one transaction too.
using (var tr = uow.Database.GetTransaction())
{
if (contentTypeIds.Any() == false)
{
var mediaObjectType = Guid.Parse(Constants.ObjectTypes.Media);
var subQuery = new Sql()
.Select("DISTINCT cmsContentXml.nodeId")
.From<ContentXmlDto>()
.InnerJoin<NodeDto>()
.On<ContentXmlDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.Where<NodeDto>(dto => dto.NodeObjectType == mediaObjectType);
var deleteSql = SqlSyntaxContext.SqlSyntaxProvider.GetDeleteSubquery("cmsContentXml", "nodeId", subQuery);
uow.Database.Execute(deleteSql);
}
else
{
foreach (var id in contentTypeIds)
{
var id1 = id;
var mediaObjectType = Guid.Parse(Constants.ObjectTypes.Media);
var subQuery = new Sql()
.Select("DISTINCT cmsContentXml.nodeId")
.From<ContentXmlDto>()
.InnerJoin<NodeDto>()
.On<ContentXmlDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.InnerJoin<ContentDto>()
.On<ContentDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.Where<NodeDto>(dto => dto.NodeObjectType == mediaObjectType)
.Where<ContentDto>(dto => dto.ContentTypeId == id1);
var deleteSql = SqlSyntaxContext.SqlSyntaxProvider.GetDeleteSubquery("cmsContentXml", "nodeId", subQuery);
uow.Database.Execute(deleteSql);
}
}
//bulk insert it into the database
uow.Database.BulkInsertRecords(xmlItems, tr);
tr.Complete();
}
Audit.Add(AuditTypes.Publish, "RebuildXmlStructures completed, the xml has been regenerated in the database", 0, -1);
}
}
/// <summary>
/// Updates the Path and Level on a collection of <see cref="IMedia"/> objects
/// based on the Parent's Path and Level. Also change the trashed state if relevant.
/// </summary>
/// <param name="children">Collection of <see cref="IMedia"/> objects to update</param>
/// <param name="parentPath">Path of the Parent media</param>
/// <param name="parentLevel">Level of the Parent media</param>
/// <param name="parentTrashed">Indicates whether the Parent is trashed or not</param>
/// <returns>Collection of updated <see cref="IMedia"/> objects</returns>
private IEnumerable<IMedia> UpdatePropertiesOnChildren(IEnumerable<IMedia> children, string parentPath, int parentLevel, bool parentTrashed)
{
var list = new List<IMedia>();
foreach (var child in children)
{
child.Path = string.Concat(parentPath, ",", child.Id);
child.Level = parentLevel + 1;
if (parentTrashed != child.Trashed)
{
child.ChangeTrashedState(parentTrashed, child.ParentId);
}
list.Add(child);
var grandkids = GetChildren(child.Id).ToArray();
if (grandkids.Any())
{
list.AddRange(UpdatePropertiesOnChildren(grandkids, child.Path, child.Level, child.Trashed));
}
}
return list;
}
private void CreateAndSaveMediaXml(XElement xml, int id, UmbracoDatabase db)
{
var poco = new ContentXmlDto { NodeId = id, Xml = xml.ToString(SaveOptions.None) };
var exists = db.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = id }) != null;
int result = exists ? db.Update(poco) : Convert.ToInt32(db.Insert(poco));
}
private IMediaType FindMediaTypeByAlias(string mediaTypeAlias)
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaTypeRepository(uow))
{
var query = Query<IMediaType>.Builder.Where(x => x.Alias == mediaTypeAlias);
var mediaTypes = repository.GetByQuery(query);
if (mediaTypes.Any() == false)
throw new Exception(string.Format("No MediaType matching the passed in Alias: '{0}' was found",
mediaTypeAlias));
var mediaType = mediaTypes.First();
if (mediaType == null)
throw new Exception(string.Format("MediaType matching the passed in Alias: '{0}' was null",
mediaTypeAlias));
return mediaType;
}
}
#region Event Handlers
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IMediaService, DeleteRevisionsEventArgs> DeletingVersions;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IMediaService, DeleteRevisionsEventArgs> DeletedVersions;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IMediaService, DeleteEventArgs<IMedia>> Deleting;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IMediaService, DeleteEventArgs<IMedia>> Deleted;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IMediaService, SaveEventArgs<IMedia>> Saving;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IMediaService, SaveEventArgs<IMedia>> Saved;
/// <summary>
/// Occurs before Create
/// </summary>
[Obsolete("Use the Created event instead, the Creating and Created events both offer the same functionality, Creating event has been deprecated.")]
public static event TypedEventHandler<IMediaService, NewEventArgs<IMedia>> Creating;
/// <summary>
/// Occurs after Create
/// </summary>
/// <remarks>
/// Please note that the Media object has been created, but not saved
/// so it does not have an identity yet (meaning no Id has been set).
/// </remarks>
public static event TypedEventHandler<IMediaService, NewEventArgs<IMedia>> Created;
/// <summary>
/// Occurs before Content is moved to Recycle Bin
/// </summary>
public static event TypedEventHandler<IMediaService, MoveEventArgs<IMedia>> Trashing;
/// <summary>
/// Occurs after Content is moved to Recycle Bin
/// </summary>
public static event TypedEventHandler<IMediaService, MoveEventArgs<IMedia>> Trashed;
/// <summary>
/// Occurs before Move
/// </summary>
public static event TypedEventHandler<IMediaService, MoveEventArgs<IMedia>> Moving;
/// <summary>
/// Occurs after Move
/// </summary>
public static event TypedEventHandler<IMediaService, MoveEventArgs<IMedia>> Moved;
/// <summary>
/// Occurs before the Recycle Bin is emptied
/// </summary>
public static event TypedEventHandler<IMediaService, RecycleBinEventArgs> EmptyingRecycleBin;
/// <summary>
/// Occurs after the Recycle Bin has been Emptied
/// </summary>
public static event TypedEventHandler<IMediaService, RecycleBinEventArgs> EmptiedRecycleBin;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.Runtime.Serialization
{
internal class SchemaExporter
{
private readonly XmlSchemaSet _schemas;
private XmlDocument _xmlDoc;
private DataContractSet _dataContractSet;
internal SchemaExporter(XmlSchemaSet schemas, DataContractSet dataContractSet)
{
_schemas = schemas;
_dataContractSet = dataContractSet;
}
private XmlSchemaSet Schemas
{
get { return _schemas; }
}
private XmlDocument XmlDoc
{
get
{
if (_xmlDoc == null)
_xmlDoc = new XmlDocument();
return _xmlDoc;
}
}
internal void Export()
{
try
{
// Remove this if we decide to publish serialization schema at well-known location
ExportSerializationSchema();
foreach (KeyValuePair<XmlQualifiedName, DataContract> pair in _dataContractSet)
{
DataContract dataContract = pair.Value;
if (!_dataContractSet.IsContractProcessed(dataContract))
{
ExportDataContract(dataContract);
_dataContractSet.SetContractProcessed(dataContract);
}
}
}
finally
{
_xmlDoc = null;
_dataContractSet = null;
}
}
private void ExportSerializationSchema()
{
if (!Schemas.Contains(Globals.SerializationNamespace))
{
StringReader reader = new StringReader(Globals.SerializationSchema);
XmlSchema schema = XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null);
if (schema == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.CouldNotReadSerializationSchema, Globals.SerializationNamespace)));
Schemas.Add(schema);
}
}
private void ExportDataContract(DataContract dataContract)
{
if (dataContract.IsBuiltInDataContract)
return;
else if (dataContract is XmlDataContract)
ExportXmlDataContract((XmlDataContract)dataContract);
else
{
XmlSchema schema = GetSchema(dataContract.StableName.Namespace);
if (dataContract is ClassDataContract)
{
ClassDataContract classDataContract = (ClassDataContract)dataContract;
if (classDataContract.IsISerializable)
ExportISerializableDataContract(classDataContract, schema);
else
ExportClassDataContract(classDataContract, schema);
}
else if (dataContract is CollectionDataContract)
ExportCollectionDataContract((CollectionDataContract)dataContract, schema);
else if (dataContract is EnumDataContract)
ExportEnumDataContract((EnumDataContract)dataContract, schema);
ExportTopLevelElement(dataContract, schema);
Schemas.Reprocess(schema);
}
}
private XmlSchemaElement ExportTopLevelElement(DataContract dataContract, XmlSchema schema)
{
if (schema == null || dataContract.StableName.Namespace != dataContract.TopLevelElementNamespace.Value)
schema = GetSchema(dataContract.TopLevelElementNamespace.Value);
XmlSchemaElement topLevelElement = new XmlSchemaElement();
topLevelElement.Name = dataContract.TopLevelElementName.Value;
SetElementType(topLevelElement, dataContract, schema);
topLevelElement.IsNillable = true;
schema.Items.Add(topLevelElement);
return topLevelElement;
}
private void ExportClassDataContract(ClassDataContract classDataContract, XmlSchema schema)
{
XmlSchemaComplexType type = new XmlSchemaComplexType();
type.Name = classDataContract.StableName.Name;
schema.Items.Add(type);
XmlElement genericInfoElement = null;
if (classDataContract.UnderlyingType.IsGenericType)
genericInfoElement = ExportGenericInfo(classDataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace);
XmlSchemaSequence rootSequence = new XmlSchemaSequence();
for (int i = 0; i < classDataContract.Members.Count; i++)
{
DataMember dataMember = classDataContract.Members[i];
XmlSchemaElement element = new XmlSchemaElement();
element.Name = dataMember.Name;
XmlElement actualTypeElement = null;
DataContract memberTypeContract = _dataContractSet.GetMemberTypeDataContract(dataMember);
if (CheckIfMemberHasConflict(dataMember))
{
element.SchemaTypeName = AnytypeQualifiedName;
actualTypeElement = ExportActualType(memberTypeContract.StableName);
SchemaHelper.AddSchemaImport(memberTypeContract.StableName.Namespace, schema);
}
else
SetElementType(element, memberTypeContract, schema);
SchemaHelper.AddElementForm(element, schema);
if (dataMember.IsNullable)
element.IsNillable = true;
if (!dataMember.IsRequired)
element.MinOccurs = 0;
element.Annotation = GetSchemaAnnotation(actualTypeElement, ExportSurrogateData(dataMember), ExportEmitDefaultValue(dataMember));
rootSequence.Items.Add(element);
}
XmlElement isValueTypeElement = null;
if (classDataContract.BaseContract != null)
{
XmlSchemaComplexContentExtension extension = CreateTypeContent(type, classDataContract.BaseContract.StableName, schema);
extension.Particle = rootSequence;
if (classDataContract.IsReference && !classDataContract.BaseContract.IsReference)
{
AddReferenceAttributes(extension.Attributes, schema);
}
}
else
{
type.Particle = rootSequence;
if (classDataContract.IsValueType)
isValueTypeElement = GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(classDataContract.IsValueType), schema);
if (classDataContract.IsReference)
AddReferenceAttributes(type.Attributes, schema);
}
type.Annotation = GetSchemaAnnotation(genericInfoElement, ExportSurrogateData(classDataContract), isValueTypeElement);
}
private void AddReferenceAttributes(XmlSchemaObjectCollection attributes, XmlSchema schema)
{
SchemaHelper.AddSchemaImport(Globals.SerializationNamespace, schema);
schema.Namespaces.Add(Globals.SerPrefixForSchema, Globals.SerializationNamespace);
attributes.Add(IdAttribute);
attributes.Add(RefAttribute);
}
private void SetElementType(XmlSchemaElement element, DataContract dataContract, XmlSchema schema)
{
XmlDataContract xmlDataContract = dataContract as XmlDataContract;
if (xmlDataContract != null && xmlDataContract.IsAnonymous)
{
element.SchemaType = xmlDataContract.XsdType;
}
else
{
element.SchemaTypeName = dataContract.StableName;
if (element.SchemaTypeName.Namespace.Equals(Globals.SerializationNamespace))
schema.Namespaces.Add(Globals.SerPrefixForSchema, Globals.SerializationNamespace);
SchemaHelper.AddSchemaImport(dataContract.StableName.Namespace, schema);
}
}
private bool CheckIfMemberHasConflict(DataMember dataMember)
{
if (dataMember.HasConflictingNameAndType)
return true;
DataMember conflictingMember = dataMember.ConflictingMember;
while (conflictingMember != null)
{
if (conflictingMember.HasConflictingNameAndType)
return true;
conflictingMember = conflictingMember.ConflictingMember;
}
return false;
}
private XmlElement ExportEmitDefaultValue(DataMember dataMember)
{
if (dataMember.EmitDefaultValue)
return null;
XmlElement defaultValueElement = XmlDoc.CreateElement(DefaultValueAnnotation.Name, DefaultValueAnnotation.Namespace);
XmlAttribute emitDefaultValueAttribute = XmlDoc.CreateAttribute(Globals.EmitDefaultValueAttribute);
emitDefaultValueAttribute.Value = Globals.False;
defaultValueElement.Attributes.Append(emitDefaultValueAttribute);
return defaultValueElement;
}
private XmlElement ExportActualType(XmlQualifiedName typeName)
{
return ExportActualType(typeName, XmlDoc);
}
private static XmlElement ExportActualType(XmlQualifiedName typeName, XmlDocument xmlDoc)
{
XmlElement actualTypeElement = xmlDoc.CreateElement(ActualTypeAnnotationName.Name, ActualTypeAnnotationName.Namespace);
XmlAttribute nameAttribute = xmlDoc.CreateAttribute(Globals.ActualTypeNameAttribute);
nameAttribute.Value = typeName.Name;
actualTypeElement.Attributes.Append(nameAttribute);
XmlAttribute nsAttribute = xmlDoc.CreateAttribute(Globals.ActualTypeNamespaceAttribute);
nsAttribute.Value = typeName.Namespace;
actualTypeElement.Attributes.Append(nsAttribute);
return actualTypeElement;
}
private XmlElement ExportGenericInfo(Type clrType, string elementName, string elementNs)
{
Type itemType;
int nestedCollectionLevel = 0;
while (CollectionDataContract.IsCollection(clrType, out itemType))
{
if (DataContract.GetBuiltInDataContract(clrType) != null
|| CollectionDataContract.IsCollectionDataContract(clrType))
{
break;
}
clrType = itemType;
nestedCollectionLevel++;
}
Type[] genericArguments = null;
IList<int> genericArgumentCounts = null;
if (clrType.IsGenericType)
{
genericArguments = clrType.GetGenericArguments();
string typeName;
if (clrType.DeclaringType == null)
typeName = clrType.Name;
else
{
int nsLen = (clrType.Namespace == null) ? 0 : clrType.Namespace.Length;
if (nsLen > 0)
nsLen++; //include the . following namespace
typeName = DataContract.GetClrTypeFullName(clrType).Substring(nsLen).Replace('+', '.');
}
int iParam = typeName.IndexOf('[');
if (iParam >= 0)
typeName = typeName.Substring(0, iParam);
genericArgumentCounts = DataContract.GetDataContractNameForGenericName(typeName, null);
clrType = clrType.GetGenericTypeDefinition();
}
XmlQualifiedName dcqname = DataContract.GetStableName(clrType);
if (nestedCollectionLevel > 0)
{
string collectionName = dcqname.Name;
for (int n = 0; n < nestedCollectionLevel; n++)
collectionName = Globals.ArrayPrefix + collectionName;
dcqname = new XmlQualifiedName(collectionName, DataContract.GetCollectionNamespace(dcqname.Namespace));
}
XmlElement typeElement = XmlDoc.CreateElement(elementName, elementNs);
XmlAttribute nameAttribute = XmlDoc.CreateAttribute(Globals.GenericNameAttribute);
nameAttribute.Value = genericArguments != null ? XmlConvert.DecodeName(dcqname.Name) : dcqname.Name;
//nameAttribute.Value = dcqname.Name;
typeElement.Attributes.Append(nameAttribute);
XmlAttribute nsAttribute = XmlDoc.CreateAttribute(Globals.GenericNamespaceAttribute);
nsAttribute.Value = dcqname.Namespace;
typeElement.Attributes.Append(nsAttribute);
if (genericArguments != null)
{
int argIndex = 0;
int nestedLevel = 0;
foreach (int genericArgumentCount in genericArgumentCounts)
{
for (int i = 0; i < genericArgumentCount; i++, argIndex++)
{
XmlElement argumentElement = ExportGenericInfo(genericArguments[argIndex], Globals.GenericParameterLocalName, Globals.SerializationNamespace);
if (nestedLevel > 0)
{
XmlAttribute nestedLevelAttribute = XmlDoc.CreateAttribute(Globals.GenericParameterNestedLevelAttribute);
nestedLevelAttribute.Value = nestedLevel.ToString(CultureInfo.InvariantCulture);
argumentElement.Attributes.Append(nestedLevelAttribute);
}
typeElement.AppendChild(argumentElement);
}
nestedLevel++;
}
if (genericArgumentCounts[nestedLevel - 1] == 0)
{
XmlAttribute typeNestedLevelsAttribute = XmlDoc.CreateAttribute(Globals.GenericParameterNestedLevelAttribute);
typeNestedLevelsAttribute.Value = genericArgumentCounts.Count.ToString(CultureInfo.InvariantCulture);
typeElement.Attributes.Append(typeNestedLevelsAttribute);
}
}
return typeElement;
}
private XmlElement ExportSurrogateData(object key)
{
// IDataContractSurrogate is not available on NetCore.
return null;
}
private void ExportCollectionDataContract(CollectionDataContract collectionDataContract, XmlSchema schema)
{
XmlSchemaComplexType type = new XmlSchemaComplexType();
type.Name = collectionDataContract.StableName.Name;
schema.Items.Add(type);
XmlElement genericInfoElement = null, isDictionaryElement = null;
if (collectionDataContract.UnderlyingType.IsGenericType && CollectionDataContract.IsCollectionDataContract(collectionDataContract.UnderlyingType))
genericInfoElement = ExportGenericInfo(collectionDataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace);
if (collectionDataContract.IsDictionary)
isDictionaryElement = ExportIsDictionary();
type.Annotation = GetSchemaAnnotation(isDictionaryElement, genericInfoElement, ExportSurrogateData(collectionDataContract));
XmlSchemaSequence rootSequence = new XmlSchemaSequence();
XmlSchemaElement element = new XmlSchemaElement();
element.Name = collectionDataContract.ItemName;
element.MinOccurs = 0;
element.MaxOccursString = Globals.OccursUnbounded;
if (collectionDataContract.IsDictionary)
{
ClassDataContract keyValueContract = collectionDataContract.ItemContract as ClassDataContract;
XmlSchemaComplexType keyValueType = new XmlSchemaComplexType();
XmlSchemaSequence keyValueSequence = new XmlSchemaSequence();
foreach (DataMember dataMember in keyValueContract.Members)
{
XmlSchemaElement keyValueElement = new XmlSchemaElement();
keyValueElement.Name = dataMember.Name;
SetElementType(keyValueElement, _dataContractSet.GetMemberTypeDataContract(dataMember), schema);
SchemaHelper.AddElementForm(keyValueElement, schema);
if (dataMember.IsNullable)
keyValueElement.IsNillable = true;
keyValueElement.Annotation = GetSchemaAnnotation(ExportSurrogateData(dataMember));
keyValueSequence.Items.Add(keyValueElement);
}
keyValueType.Particle = keyValueSequence;
element.SchemaType = keyValueType;
}
else
{
if (collectionDataContract.IsItemTypeNullable)
element.IsNillable = true;
DataContract itemContract = _dataContractSet.GetItemTypeDataContract(collectionDataContract);
SetElementType(element, itemContract, schema);
}
SchemaHelper.AddElementForm(element, schema);
rootSequence.Items.Add(element);
type.Particle = rootSequence;
if (collectionDataContract.IsReference)
AddReferenceAttributes(type.Attributes, schema);
}
private XmlElement ExportIsDictionary()
{
XmlElement isDictionaryElement = XmlDoc.CreateElement(IsDictionaryAnnotationName.Name, IsDictionaryAnnotationName.Namespace);
isDictionaryElement.InnerText = Globals.True;
return isDictionaryElement;
}
private void ExportEnumDataContract(EnumDataContract enumDataContract, XmlSchema schema)
{
XmlSchemaSimpleType type = new XmlSchemaSimpleType();
type.Name = enumDataContract.StableName.Name;
XmlElement actualTypeElement = (enumDataContract.BaseContractName == DefaultEnumBaseTypeName) ? null : ExportActualType(enumDataContract.BaseContractName);
type.Annotation = GetSchemaAnnotation(actualTypeElement, ExportSurrogateData(enumDataContract));
schema.Items.Add(type);
XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
restriction.BaseTypeName = StringQualifiedName;
SchemaHelper.AddSchemaImport(enumDataContract.BaseContractName.Namespace, schema);
if (enumDataContract.Values != null)
{
for (int i = 0; i < enumDataContract.Values.Count; i++)
{
XmlSchemaEnumerationFacet facet = new XmlSchemaEnumerationFacet();
facet.Value = enumDataContract.Members[i].Name;
if (enumDataContract.Values[i] != GetDefaultEnumValue(enumDataContract.IsFlags, i))
facet.Annotation = GetSchemaAnnotation(EnumerationValueAnnotationName, enumDataContract.GetStringFromEnumValue(enumDataContract.Values[i]), schema);
restriction.Facets.Add(facet);
}
}
if (enumDataContract.IsFlags)
{
XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList();
XmlSchemaSimpleType anonymousType = new XmlSchemaSimpleType();
anonymousType.Content = restriction;
list.ItemType = anonymousType;
type.Content = list;
}
else
type.Content = restriction;
}
internal static long GetDefaultEnumValue(bool isFlags, int index)
{
return isFlags ? (long)Math.Pow(2, index) : index;
}
private void ExportISerializableDataContract(ClassDataContract dataContract, XmlSchema schema)
{
XmlSchemaComplexType type = new XmlSchemaComplexType();
type.Name = dataContract.StableName.Name;
schema.Items.Add(type);
XmlElement genericInfoElement = null;
if (dataContract.UnderlyingType.IsGenericType)
genericInfoElement = ExportGenericInfo(dataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace);
XmlElement isValueTypeElement = null;
if (dataContract.BaseContract != null)
{
XmlSchemaComplexContentExtension extension = CreateTypeContent(type, dataContract.BaseContract.StableName, schema);
}
else
{
schema.Namespaces.Add(Globals.SerPrefixForSchema, Globals.SerializationNamespace);
type.Particle = ISerializableSequence;
XmlSchemaAttribute iSerializableFactoryTypeAttribute = ISerializableFactoryTypeAttribute;
type.Attributes.Add(iSerializableFactoryTypeAttribute);
SchemaHelper.AddSchemaImport(ISerializableFactoryTypeAttribute.RefName.Namespace, schema);
if (dataContract.IsValueType)
isValueTypeElement = GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(dataContract.IsValueType), schema);
}
type.Annotation = GetSchemaAnnotation(genericInfoElement, ExportSurrogateData(dataContract), isValueTypeElement);
}
private XmlSchemaComplexContentExtension CreateTypeContent(XmlSchemaComplexType type, XmlQualifiedName baseTypeName, XmlSchema schema)
{
SchemaHelper.AddSchemaImport(baseTypeName.Namespace, schema);
XmlSchemaComplexContentExtension extension = new XmlSchemaComplexContentExtension();
extension.BaseTypeName = baseTypeName;
type.ContentModel = new XmlSchemaComplexContent();
type.ContentModel.Content = extension;
return extension;
}
private void ExportXmlDataContract(XmlDataContract dataContract)
{
XmlQualifiedName typeQName;
bool hasRoot;
XmlSchemaType xsdType;
Type clrType = dataContract.UnderlyingType;
if (!IsSpecialXmlType(clrType, out typeQName, out xsdType, out hasRoot))
if (!InvokeSchemaProviderMethod(clrType, _schemas, out typeQName, out xsdType, out hasRoot))
InvokeGetSchemaMethod(clrType, _schemas, typeQName);
if (hasRoot)
{
if (!(typeQName.Equals(dataContract.StableName)))
{
Fx.Assert("XML data contract type name does not match schema name");
}
XmlSchema schema;
if (SchemaHelper.GetSchemaElement(Schemas,
new XmlQualifiedName(dataContract.TopLevelElementName.Value, dataContract.TopLevelElementNamespace.Value),
out schema) == null)
{
XmlSchemaElement topLevelElement = ExportTopLevelElement(dataContract, schema);
topLevelElement.IsNillable = dataContract.IsTopLevelElementNullable;
ReprocessAll(_schemas);
}
XmlSchemaType anonymousType = xsdType;
xsdType = SchemaHelper.GetSchemaType(_schemas, typeQName, out schema);
if (anonymousType == null && xsdType == null && typeQName.Namespace != XmlSchema.Namespace)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingSchemaType, typeQName, DataContract.GetClrTypeFullName(clrType))));
}
if (xsdType != null)
{
xsdType.Annotation = GetSchemaAnnotation(
ExportSurrogateData(dataContract),
dataContract.IsValueType ?
GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(dataContract.IsValueType), schema) :
null
);
}
}
}
private static void ReprocessAll(XmlSchemaSet schemas)// and remove duplicate items
{
Hashtable elements = new Hashtable();
Hashtable types = new Hashtable();
XmlSchema[] schemaArray = new XmlSchema[schemas.Count];
schemas.CopyTo(schemaArray, 0);
for (int i = 0; i < schemaArray.Length; i++)
{
XmlSchema schema = schemaArray[i];
XmlSchemaObject[] itemArray = new XmlSchemaObject[schema.Items.Count];
schema.Items.CopyTo(itemArray, 0);
for (int j = 0; j < itemArray.Length; j++)
{
XmlSchemaObject item = itemArray[j];
Hashtable items;
XmlQualifiedName qname;
if (item is XmlSchemaElement)
{
items = elements;
qname = new XmlQualifiedName(((XmlSchemaElement)item).Name, schema.TargetNamespace);
}
else if (item is XmlSchemaType)
{
items = types;
qname = new XmlQualifiedName(((XmlSchemaType)item).Name, schema.TargetNamespace);
}
else
continue;
object otherItem = items[qname];
if (otherItem != null)
{
schema.Items.Remove(item);
}
else
items.Add(qname, item);
}
schemas.Reprocess(schema);
}
}
internal static void GetXmlTypeInfo(Type type, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot)
{
if (IsSpecialXmlType(type, out stableName, out xsdType, out hasRoot))
return;
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.XmlResolver = null;
InvokeSchemaProviderMethod(type, schemas, out stableName, out xsdType, out hasRoot);
if (stableName.Name == null || stableName.Name.Length == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidXmlDataContractName, DataContract.GetClrTypeFullName(type))));
}
private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schemas, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot)
{
xsdType = null;
hasRoot = true;
object[] attrs = clrType.GetCustomAttributes(Globals.TypeOfXmlSchemaProviderAttribute, false);
if (attrs == null || attrs.Length == 0)
{
stableName = DataContract.GetDefaultStableName(clrType);
return false;
}
XmlSchemaProviderAttribute provider = (XmlSchemaProviderAttribute)attrs[0];
if (provider.IsAny)
{
xsdType = CreateAnyElementType();
hasRoot = false;
}
string methodName = provider.MethodName;
if (methodName == null || methodName.Length == 0)
{
if (!provider.IsAny)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidGetSchemaMethod, DataContract.GetClrTypeFullName(clrType))));
stableName = DataContract.GetDefaultStableName(clrType);
}
else
{
MethodInfo getMethod = clrType.GetMethod(methodName, /*BindingFlags.DeclaredOnly |*/ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[] { typeof(XmlSchemaSet) }, null);
if (getMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName)));
if (!(Globals.TypeOfXmlQualifiedName.IsAssignableFrom(getMethod.ReturnType)) && !(Globals.TypeOfXmlSchemaType.IsAssignableFrom(getMethod.ReturnType)))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidReturnTypeOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName, DataContract.GetClrTypeFullName(getMethod.ReturnType), DataContract.GetClrTypeFullName(Globals.TypeOfXmlQualifiedName), typeof(XmlSchemaType))));
object typeInfo = getMethod.Invoke(null, new object[] { schemas });
if (provider.IsAny)
{
if (typeInfo != null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidNonNullReturnValueByIsAny, DataContract.GetClrTypeFullName(clrType), methodName)));
stableName = DataContract.GetDefaultStableName(clrType);
}
else if (typeInfo == null)
{
xsdType = CreateAnyElementType();
hasRoot = false;
stableName = DataContract.GetDefaultStableName(clrType);
}
else
{
XmlSchemaType providerXsdType = typeInfo as XmlSchemaType;
if (providerXsdType != null)
{
string typeName = providerXsdType.Name;
string typeNs = null;
if (typeName == null || typeName.Length == 0)
{
DataContract.GetDefaultStableName(DataContract.GetClrTypeFullName(clrType), out typeName, out typeNs);
stableName = new XmlQualifiedName(typeName, typeNs);
providerXsdType.Annotation = GetSchemaAnnotation(ExportActualType(stableName, new XmlDocument()));
xsdType = providerXsdType;
}
else
{
foreach (XmlSchema schema in schemas.Schemas())
{
foreach (XmlSchemaObject schemaItem in schema.Items)
{
if ((object)schemaItem == (object)providerXsdType)
{
typeNs = schema.TargetNamespace;
if (typeNs == null)
typeNs = string.Empty;
break;
}
}
if (typeNs != null)
break;
}
if (typeNs == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingSchemaType, typeName, DataContract.GetClrTypeFullName(clrType))));
stableName = new XmlQualifiedName(typeName, typeNs);
}
}
else
stableName = (XmlQualifiedName)typeInfo;
}
}
return true;
}
private static void InvokeGetSchemaMethod(Type clrType, XmlSchemaSet schemas, XmlQualifiedName stableName)
{
IXmlSerializable ixmlSerializable = (IXmlSerializable)Activator.CreateInstance(clrType);
XmlSchema schema = ixmlSerializable.GetSchema();
if (schema == null)
{
AddDefaultDatasetType(schemas, stableName.Name, stableName.Namespace);
}
else
{
if (schema.Id == null || schema.Id.Length == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidReturnSchemaOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType))));
AddDefaultTypedDatasetType(schemas, schema, stableName.Name, stableName.Namespace);
}
}
internal static void AddDefaultXmlType(XmlSchemaSet schemas, string localName, string ns)
{
XmlSchemaComplexType defaultXmlType = CreateAnyType();
defaultXmlType.Name = localName;
XmlSchema schema = SchemaHelper.GetSchema(ns, schemas);
schema.Items.Add(defaultXmlType);
schemas.Reprocess(schema);
}
private static XmlSchemaComplexType CreateAnyType()
{
XmlSchemaComplexType anyType = new XmlSchemaComplexType();
anyType.IsMixed = true;
anyType.Particle = new XmlSchemaSequence();
XmlSchemaAny any = new XmlSchemaAny();
any.MinOccurs = 0;
any.MaxOccurs = decimal.MaxValue;
any.ProcessContents = XmlSchemaContentProcessing.Lax;
((XmlSchemaSequence)anyType.Particle).Items.Add(any);
anyType.AnyAttribute = new XmlSchemaAnyAttribute();
return anyType;
}
private static XmlSchemaComplexType CreateAnyElementType()
{
XmlSchemaComplexType anyElementType = new XmlSchemaComplexType();
anyElementType.IsMixed = false;
anyElementType.Particle = new XmlSchemaSequence();
XmlSchemaAny any = new XmlSchemaAny();
any.MinOccurs = 0;
any.ProcessContents = XmlSchemaContentProcessing.Lax;
((XmlSchemaSequence)anyElementType.Particle).Items.Add(any);
return anyElementType;
}
internal static bool IsSpecialXmlType(Type type, out XmlQualifiedName typeName, out XmlSchemaType xsdType, out bool hasRoot)
{
xsdType = null;
hasRoot = true;
if (type == Globals.TypeOfXmlElement || type == Globals.TypeOfXmlNodeArray)
{
string name = null;
if (type == Globals.TypeOfXmlElement)
{
xsdType = CreateAnyElementType();
name = "XmlElement";
hasRoot = false;
}
else
{
xsdType = CreateAnyType();
name = "ArrayOfXmlNode";
hasRoot = true;
}
typeName = new XmlQualifiedName(name, DataContract.GetDefaultStableNamespace(type));
return true;
}
typeName = null;
return false;
}
private static void AddDefaultDatasetType(XmlSchemaSet schemas, string localName, string ns)
{
XmlSchemaComplexType type = new XmlSchemaComplexType();
type.Name = localName;
type.Particle = new XmlSchemaSequence();
XmlSchemaElement schemaRefElement = new XmlSchemaElement();
schemaRefElement.RefName = new XmlQualifiedName(Globals.SchemaLocalName, XmlSchema.Namespace);
((XmlSchemaSequence)type.Particle).Items.Add(schemaRefElement);
XmlSchemaAny any = new XmlSchemaAny();
((XmlSchemaSequence)type.Particle).Items.Add(any);
XmlSchema schema = SchemaHelper.GetSchema(ns, schemas);
schema.Items.Add(type);
schemas.Reprocess(schema);
}
private static void AddDefaultTypedDatasetType(XmlSchemaSet schemas, XmlSchema datasetSchema, string localName, string ns)
{
XmlSchemaComplexType type = new XmlSchemaComplexType();
type.Name = localName;
type.Particle = new XmlSchemaSequence();
XmlSchemaAny any = new XmlSchemaAny();
any.Namespace = (datasetSchema.TargetNamespace == null) ? string.Empty : datasetSchema.TargetNamespace;
((XmlSchemaSequence)type.Particle).Items.Add(any);
schemas.Add(datasetSchema);
XmlSchema schema = SchemaHelper.GetSchema(ns, schemas);
schema.Items.Add(type);
schemas.Reprocess(datasetSchema);
schemas.Reprocess(schema);
}
private XmlSchemaAnnotation GetSchemaAnnotation(XmlQualifiedName annotationQualifiedName, string innerText, XmlSchema schema)
{
XmlSchemaAnnotation annotation = new XmlSchemaAnnotation();
XmlSchemaAppInfo appInfo = new XmlSchemaAppInfo();
XmlElement annotationElement = GetAnnotationMarkup(annotationQualifiedName, innerText, schema);
appInfo.Markup = new XmlNode[1] { annotationElement };
annotation.Items.Add(appInfo);
return annotation;
}
private static XmlSchemaAnnotation GetSchemaAnnotation(params XmlNode[] nodes)
{
if (nodes == null || nodes.Length == 0)
return null;
bool hasAnnotation = false;
for (int i = 0; i < nodes.Length; i++)
if (nodes[i] != null)
{
hasAnnotation = true;
break;
}
if (!hasAnnotation)
return null;
XmlSchemaAnnotation annotation = new XmlSchemaAnnotation();
XmlSchemaAppInfo appInfo = new XmlSchemaAppInfo();
annotation.Items.Add(appInfo);
appInfo.Markup = nodes;
return annotation;
}
private XmlElement GetAnnotationMarkup(XmlQualifiedName annotationQualifiedName, string innerText, XmlSchema schema)
{
XmlElement annotationElement = XmlDoc.CreateElement(annotationQualifiedName.Name, annotationQualifiedName.Namespace);
SchemaHelper.AddSchemaImport(annotationQualifiedName.Namespace, schema);
annotationElement.InnerText = innerText;
return annotationElement;
}
private XmlSchema GetSchema(string ns)
{
return SchemaHelper.GetSchema(ns, Schemas);
}
// Property is not stored in a local because XmlSchemaSequence is mutable.
// The schema export process should not expose objects that may be modified later.
internal static XmlSchemaSequence ISerializableSequence
{
get
{
XmlSchemaSequence iSerializableSequence = new XmlSchemaSequence();
iSerializableSequence.Items.Add(ISerializableWildcardElement);
return iSerializableSequence;
}
}
// Property is not stored in a local because XmlSchemaAny is mutable.
// The schema export process should not expose objects that may be modified later.
internal static XmlSchemaAny ISerializableWildcardElement
{
get
{
XmlSchemaAny iSerializableWildcardElement = new XmlSchemaAny();
iSerializableWildcardElement.MinOccurs = 0;
iSerializableWildcardElement.MaxOccursString = Globals.OccursUnbounded;
iSerializableWildcardElement.Namespace = "##local";
iSerializableWildcardElement.ProcessContents = XmlSchemaContentProcessing.Skip;
return iSerializableWildcardElement;
}
}
private static XmlQualifiedName s_anytypeQualifiedName;
internal static XmlQualifiedName AnytypeQualifiedName
{
get
{
if (s_anytypeQualifiedName == null)
s_anytypeQualifiedName = new XmlQualifiedName(Globals.AnyTypeLocalName, Globals.SchemaNamespace);
return s_anytypeQualifiedName;
}
}
private static XmlQualifiedName s_stringQualifiedName;
internal static XmlQualifiedName StringQualifiedName
{
get
{
if (s_stringQualifiedName == null)
s_stringQualifiedName = new XmlQualifiedName(Globals.StringLocalName, Globals.SchemaNamespace);
return s_stringQualifiedName;
}
}
private static XmlQualifiedName s_defaultEnumBaseTypeName;
internal static XmlQualifiedName DefaultEnumBaseTypeName
{
get
{
if (s_defaultEnumBaseTypeName == null)
s_defaultEnumBaseTypeName = new XmlQualifiedName(Globals.IntLocalName, Globals.SchemaNamespace);
return s_defaultEnumBaseTypeName;
}
}
private static XmlQualifiedName s_enumerationValueAnnotationName;
internal static XmlQualifiedName EnumerationValueAnnotationName
{
get
{
if (s_enumerationValueAnnotationName == null)
s_enumerationValueAnnotationName = new XmlQualifiedName(Globals.EnumerationValueLocalName, Globals.SerializationNamespace);
return s_enumerationValueAnnotationName;
}
}
private static XmlQualifiedName s_surrogateDataAnnotationName;
internal static XmlQualifiedName SurrogateDataAnnotationName
{
get
{
if (s_surrogateDataAnnotationName == null)
s_surrogateDataAnnotationName = new XmlQualifiedName(Globals.SurrogateDataLocalName, Globals.SerializationNamespace);
return s_surrogateDataAnnotationName;
}
}
private static XmlQualifiedName s_defaultValueAnnotation;
internal static XmlQualifiedName DefaultValueAnnotation
{
get
{
if (s_defaultValueAnnotation == null)
s_defaultValueAnnotation = new XmlQualifiedName(Globals.DefaultValueLocalName, Globals.SerializationNamespace);
return s_defaultValueAnnotation;
}
}
private static XmlQualifiedName s_actualTypeAnnotationName;
internal static XmlQualifiedName ActualTypeAnnotationName
{
get
{
if (s_actualTypeAnnotationName == null)
s_actualTypeAnnotationName = new XmlQualifiedName(Globals.ActualTypeLocalName, Globals.SerializationNamespace);
return s_actualTypeAnnotationName;
}
}
private static XmlQualifiedName s_isDictionaryAnnotationName;
internal static XmlQualifiedName IsDictionaryAnnotationName
{
get
{
if (s_isDictionaryAnnotationName == null)
s_isDictionaryAnnotationName = new XmlQualifiedName(Globals.IsDictionaryLocalName, Globals.SerializationNamespace);
return s_isDictionaryAnnotationName;
}
}
private static XmlQualifiedName s_isValueTypeName;
internal static XmlQualifiedName IsValueTypeName
{
get
{
if (s_isValueTypeName == null)
s_isValueTypeName = new XmlQualifiedName(Globals.IsValueTypeLocalName, Globals.SerializationNamespace);
return s_isValueTypeName;
}
}
// Property is not stored in a local because XmlSchemaAttribute is mutable.
// The schema export process should not expose objects that may be modified later.
internal static XmlSchemaAttribute ISerializableFactoryTypeAttribute
{
get
{
XmlSchemaAttribute iSerializableFactoryTypeAttribute = new XmlSchemaAttribute();
iSerializableFactoryTypeAttribute.RefName = new XmlQualifiedName(Globals.ISerializableFactoryTypeLocalName, Globals.SerializationNamespace);
return iSerializableFactoryTypeAttribute;
}
}
// Property is not stored in a local because XmlSchemaAttribute is mutable.
// The schema export process should not expose objects that may be modified later.
internal static XmlSchemaAttribute RefAttribute
{
get
{
XmlSchemaAttribute refAttribute = new XmlSchemaAttribute();
refAttribute.RefName = Globals.RefQualifiedName;
return refAttribute;
}
}
// Property is not stored in a local because XmlSchemaAttribute is mutable.
// The schema export process should not expose objects that may be modified later.
internal static XmlSchemaAttribute IdAttribute
{
get
{
XmlSchemaAttribute idAttribute = new XmlSchemaAttribute();
idAttribute.RefName = Globals.IdQualifiedName;
return idAttribute;
}
}
}
}
| |
using System;
namespace GUID_WinForm_V4
{
public class Ifc_Guid
{
#region Static Fields (IFC-REVIT)
/// <summary>
/// The replacement table
/// </summary>
private static readonly char[] Base64Chars =
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '_', '$'
};
#endregion
#region Internal functions (IFC-REVIT)
/// <summary>
/// The reverse function to calculate the number from the characters
/// </summary>
/// <param name="str">
/// The char array to convert from
/// </param>
/// <param name="start">
/// Position in array to start read
/// </param>
/// <param name="len">
/// The length to read
/// </param>
/// <returns>
/// The calculated nuber
/// </returns>
private static uint CvFrom64(char[] str, int start, int len)
{
int i;
uint res = 0;
//Debug.Assert(len <= 4, "Length must be equal or less than 4");
if (len > 4) throw new Exception("Length must be equal or less than 4");
for (i = 0; i < len; i++)
{
int index = -1;
int j;
for (j = 0; j < 64; j++)
{
if (Base64Chars[j] == str[start + i])
{
index = j;
break;
}
}
//Debug.Assert(index >= 0, "Index is less than 0");
if (len < 0) throw new Exception("Index is less than 0");
res = (res * 64) + ((uint)index);
}
return res;
}
/// <summary>
/// Conversion of an integer into a characters with base 64
/// using the table Base64Chars
/// </summary>
/// <param name="number">
/// The number to convert
/// </param>
/// <param name="result">
/// The result char array to write to
/// </param>
/// <param name="start">
/// The position in the char array to start writing
/// </param>
/// <param name="len">
/// The length to write
/// </param>
private static void CvTo64(uint number, ref char[] result, int start, int len)
{
int digit;
//Debug.Assert(len <= 4, "Length must be equal or less than 4");
if (len > 4) throw new Exception("Length must be equal or less than 4");
uint act = number;
int digits = len;
for (digit = 0; digit < digits; digit++)
{
result[start + len - digit - 1] = Base64Chars[(int)(act % 64)];
act /= 64;
}
//Debug.Assert(act == 0, "Logic failed, act was not null: " + act);
if (act != 0) throw new Exception("Logic failed, act was not null: " + act);
}
/// <summary>
/// Reconstruction of the GUID from an IFC GUID string (base64)
/// </summary>
/// <param name="guid">
/// The GUID string to convert. Must be 22 characters long
/// </param>
/// <returns>
/// GUID correspondig to the string
/// </returns>
private static Guid FromIfcGuid(string guid)
{
//Debug.Assert(guid.Length == 22, "Input string must not be longer than 22 chars");
if (guid.Length > 22) throw new Exception("Input string must not be longer than 22 chars");
var num = new uint[6];
char[] str = guid.ToCharArray();
int n = 2, pos = 0, i;
for (i = 0; i < 6; i++)
{
num[i] = CvFrom64(str, pos, n);
pos += n;
n = 4;
}
var a = (int)((num[0] * 16777216) + num[1]);
var b = (short)(num[2] / 256);
var c = (short)(((num[2] % 256) * 256) + (num[3] / 65536));
var d = new byte[8];
d[0] = Convert.ToByte((num[3] / 256) % 256);
d[1] = Convert.ToByte(num[3] % 256);
d[2] = Convert.ToByte(num[4] / 65536);
d[3] = Convert.ToByte((num[4] / 256) % 256);
d[4] = Convert.ToByte(num[4] % 256);
d[5] = Convert.ToByte(num[5] / 65536);
d[6] = Convert.ToByte((num[5] / 256) % 256);
d[7] = Convert.ToByte(num[5] % 256);
return new Guid(a, b, c, d);
}
/// <summary>
/// Conversion of a GUID to a string representing the GUID
/// </summary>
/// <param name="guid">
/// The GUID to convert
/// </param>
/// <returns>
/// IFC (base64) encoded GUID string
/// </returns>
private static string ToIfcGuid(Guid guid)
{
var num = new uint[6];
var str = new char[22];
byte[] b = guid.ToByteArray();
// Creation of six 32 Bit integers from the components of the GUID structure
num[0] = BitConverter.ToUInt32(b, 0) / 16777216;
num[1] = BitConverter.ToUInt32(b, 0) % 16777216;
num[2] = (uint)((BitConverter.ToUInt16(b, 4) * 256) + (BitConverter.ToUInt16(b, 6) / 256));
num[3] = (uint)(((BitConverter.ToUInt16(b, 6) % 256) * 65536) + (b[8] * 256) + b[9]);
num[4] = (uint)((b[10] * 65536) + (b[11] * 256) + b[12]);
num[5] = (uint)((b[13] * 65536) + (b[14] * 256) + b[15]);
// Conversion of the numbers into a system using a base of 64
int n = 2;
int pos = 0;
for (int i = 0; i < 6; i++)
{
CvTo64(num[i], ref str, pos, n);
pos += n;
n = 4;
}
return new string(str);
}
#endregion
#region Static Fields (BYTE-HEX)
private static readonly uint[] _lookup32 = CreateLookup32();
private static uint[] CreateLookup32()
{
var result = new uint[256];
for (int i = 0; i < 256; i++)
{
string s = i.ToString("X2");
result[i] = ((uint)s[0]) + ((uint)s[1] << 16);
}
return result;
}
#endregion
#region Internal functions (BYTE-HEX)
private static string ByteArrayToHexViaLookup32(byte[] bytes)
{
var lookup32 = _lookup32;
var result = new char[bytes.Length * 2];
for (int i = 0; i < bytes.Length; i++)
{
var val = lookup32[bytes[i]];
result[2 * i] = (char)val;
result[2 * i + 1] = (char)(val >> 16);
}
return new string(result);
}
private static byte[] HexToByteArrayViaNybble(string hexString)
{
if ((hexString.Length & 1) != 0)
{
throw new ArgumentException("Input must have even number of characters");
}
byte[] ret = new byte[hexString.Length / 2];
for (int i = 0; i < ret.Length; i++)
{
int high = ParseNybble(hexString[i * 2]);
int low = ParseNybble(hexString[i * 2 + 1]);
ret[i] = (byte)((high << 4) | low);
}
return ret;
}
private static int ParseNybble(char c)
{
unchecked
{
uint i = (uint)(c - '0');
if (i < 10)
return (int)i;
i = ((uint)c & ~0x20u) - 'A';
if (i < 6)
return (int)i + 10;
throw new ArgumentException("Invalid nybble: " + c);
}
}
private static string ExclusiveOR(byte[] key, byte[] PAN)
{
if (key.Length == PAN.Length)
{
byte[] result = new byte[key.Length];
for (int i = 0; i < key.Length; i++)
{
result[i] = (byte)(key[i] ^ PAN[i]);
}
string hex = BitConverter.ToString(result).Replace("-", "");
return hex;
}
else
{
throw new ArgumentException();
}
}
#endregion
#region Internal functions (UUID-GUID)
private static string uuid_to_guid(string input)
{
string bytstr_0 = input.Replace("-", "");
string bytstr_1 = bytstr_0.Substring(24, 8);
string bytstr_2 = bytstr_0.Substring(32, 8);
string revit_guid_suffix = ExclusiveOR(HexToByteArrayViaNybble(bytstr_1), HexToByteArrayViaNybble(bytstr_2));
string revit_guid = input.Substring(0, 28) + revit_guid_suffix;
return revit_guid;
}
private static string guid_to_uuid(string uuid, string euid)
{
string bytstr_0 = uuid.Replace("-", "");
string bytstr_1 = bytstr_0.Substring(24, 8);
byte[] b_arr = BitConverter.GetBytes(UInt32.Parse(euid));
Array.Reverse(b_arr);
string bytstr_2 = ByteArrayToHexViaLookup32(b_arr).ToLower();
string revit_guid_suffix = ExclusiveOR(HexToByteArrayViaNybble(bytstr_1), HexToByteArrayViaNybble(bytstr_2)).ToLower();
string revit_guid = String.Join("-", new string[] {
bytstr_0.Substring(0, 8), bytstr_0.Substring(8, 4), bytstr_0.Substring(12, 4), bytstr_0.Substring(16, 4), bytstr_0.Substring(20, 4) + revit_guid_suffix, bytstr_2
});
return revit_guid;
}
#endregion
#region Public functions (UUID-GUID)
public static string IFC2REVIT(string IFC_UUID, uint IFC_EUID)
{
return guid_to_uuid(FromIfcGuid(IFC_UUID).ToString(), IFC_EUID.ToString());
}
public static string REVIT2IFC(string a)
{
return ToIfcGuid(new Guid(uuid_to_guid(a))).ToString();
}
public static String TestAlgorithm()
{
string[] Raw = {
"60f91daf-3dd7-4283-a86d-24137b73f3da-0001fd0b" ,
"7f62d588-71b3-428c-9f26-87d6e2a167c0-000755f0",
"60f91daf-3dd7-4283-a86d-24137b73f3da-0001fd1f"
};
string[] Expected = {
"1W_HslFTT2WwXj91DxSWxH",
"1$OjM8SRD2Z9ycXzRYfZ8m",
"1W_HslFTT2WwXj91DxSWx5"
};
string result = "";
for (int i = 0; i < Raw.Length; i++)
{
result += String.Join("\n", new string[] {
Raw[i], Expected[i], REVIT2IFC(Raw[i]), IFC2REVIT(Expected[i], BitConverter.ToUInt32(HexToByteArrayViaNybble(Raw[i].Substring(37,8)),0))
}) + "\n";
}
return result;
}
#endregion
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Preview.Sync.Service.SyncMap
{
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact [email protected].
///
/// Fetch a specific Sync Map Permission.
/// </summary>
public class FetchSyncMapPermissionOptions : IOptions<SyncMapPermissionResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// Sync Map SID or unique name.
/// </summary>
public string PathMapSid { get; }
/// <summary>
/// Identity of the user to whom the Sync Map Permission applies.
/// </summary>
public string PathIdentity { get; }
/// <summary>
/// Construct a new FetchSyncMapPermissionOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> Sync Map SID or unique name. </param>
/// <param name="pathIdentity"> Identity of the user to whom the Sync Map Permission applies. </param>
public FetchSyncMapPermissionOptions(string pathServiceSid, string pathMapSid, string pathIdentity)
{
PathServiceSid = pathServiceSid;
PathMapSid = pathMapSid;
PathIdentity = pathIdentity;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact [email protected].
///
/// Delete a specific Sync Map Permission.
/// </summary>
public class DeleteSyncMapPermissionOptions : IOptions<SyncMapPermissionResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// Sync Map SID or unique name.
/// </summary>
public string PathMapSid { get; }
/// <summary>
/// Identity of the user to whom the Sync Map Permission applies.
/// </summary>
public string PathIdentity { get; }
/// <summary>
/// Construct a new DeleteSyncMapPermissionOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> Sync Map SID or unique name. </param>
/// <param name="pathIdentity"> Identity of the user to whom the Sync Map Permission applies. </param>
public DeleteSyncMapPermissionOptions(string pathServiceSid, string pathMapSid, string pathIdentity)
{
PathServiceSid = pathServiceSid;
PathMapSid = pathMapSid;
PathIdentity = pathIdentity;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact [email protected].
///
/// Retrieve a list of all Permissions applying to a Sync Map.
/// </summary>
public class ReadSyncMapPermissionOptions : ReadOptions<SyncMapPermissionResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// Sync Map SID or unique name.
/// </summary>
public string PathMapSid { get; }
/// <summary>
/// Construct a new ReadSyncMapPermissionOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> Sync Map SID or unique name. </param>
public ReadSyncMapPermissionOptions(string pathServiceSid, string pathMapSid)
{
PathServiceSid = pathServiceSid;
PathMapSid = pathMapSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact [email protected].
///
/// Update an identity's access to a specific Sync Map.
/// </summary>
public class UpdateSyncMapPermissionOptions : IOptions<SyncMapPermissionResource>
{
/// <summary>
/// Sync Service Instance SID.
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// Sync Map SID or unique name.
/// </summary>
public string PathMapSid { get; }
/// <summary>
/// Identity of the user to whom the Sync Map Permission applies.
/// </summary>
public string PathIdentity { get; }
/// <summary>
/// Read access.
/// </summary>
public bool? Read { get; }
/// <summary>
/// Write access.
/// </summary>
public bool? Write { get; }
/// <summary>
/// Manage access.
/// </summary>
public bool? Manage { get; }
/// <summary>
/// Construct a new UpdateSyncMapPermissionOptions
/// </summary>
/// <param name="pathServiceSid"> Sync Service Instance SID. </param>
/// <param name="pathMapSid"> Sync Map SID or unique name. </param>
/// <param name="pathIdentity"> Identity of the user to whom the Sync Map Permission applies. </param>
/// <param name="read"> Read access. </param>
/// <param name="write"> Write access. </param>
/// <param name="manage"> Manage access. </param>
public UpdateSyncMapPermissionOptions(string pathServiceSid,
string pathMapSid,
string pathIdentity,
bool? read,
bool? write,
bool? manage)
{
PathServiceSid = pathServiceSid;
PathMapSid = pathMapSid;
PathIdentity = pathIdentity;
Read = read;
Write = write;
Manage = manage;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Read != null)
{
p.Add(new KeyValuePair<string, string>("Read", Read.Value.ToString().ToLower()));
}
if (Write != null)
{
p.Add(new KeyValuePair<string, string>("Write", Write.Value.ToString().ToLower()));
}
if (Manage != null)
{
p.Add(new KeyValuePair<string, string>("Manage", Manage.Value.ToString().ToLower()));
}
return p;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="CampaignAssetServiceClient"/> instances.</summary>
public sealed partial class CampaignAssetServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CampaignAssetServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CampaignAssetServiceSettings"/>.</returns>
public static CampaignAssetServiceSettings GetDefault() => new CampaignAssetServiceSettings();
/// <summary>Constructs a new <see cref="CampaignAssetServiceSettings"/> object with default settings.</summary>
public CampaignAssetServiceSettings()
{
}
private CampaignAssetServiceSettings(CampaignAssetServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetCampaignAssetSettings = existing.GetCampaignAssetSettings;
MutateCampaignAssetsSettings = existing.MutateCampaignAssetsSettings;
OnCopy(existing);
}
partial void OnCopy(CampaignAssetServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CampaignAssetServiceClient.GetCampaignAsset</c> and <c>CampaignAssetServiceClient.GetCampaignAssetAsync</c>
/// .
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetCampaignAssetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CampaignAssetServiceClient.MutateCampaignAssets</c> and
/// <c>CampaignAssetServiceClient.MutateCampaignAssetsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateCampaignAssetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CampaignAssetServiceSettings"/> object.</returns>
public CampaignAssetServiceSettings Clone() => new CampaignAssetServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CampaignAssetServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class CampaignAssetServiceClientBuilder : gaxgrpc::ClientBuilderBase<CampaignAssetServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CampaignAssetServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CampaignAssetServiceClientBuilder()
{
UseJwtAccessWithScopes = CampaignAssetServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CampaignAssetServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CampaignAssetServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CampaignAssetServiceClient Build()
{
CampaignAssetServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CampaignAssetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CampaignAssetServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CampaignAssetServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CampaignAssetServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CampaignAssetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CampaignAssetServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CampaignAssetServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CampaignAssetServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CampaignAssetServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CampaignAssetService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage campaign assets.
/// </remarks>
public abstract partial class CampaignAssetServiceClient
{
/// <summary>
/// The default endpoint for the CampaignAssetService service, which is a host of "googleads.googleapis.com" and
/// a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CampaignAssetService scopes.</summary>
/// <remarks>
/// The default CampaignAssetService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CampaignAssetServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="CampaignAssetServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CampaignAssetServiceClient"/>.</returns>
public static stt::Task<CampaignAssetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CampaignAssetServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CampaignAssetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="CampaignAssetServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CampaignAssetServiceClient"/>.</returns>
public static CampaignAssetServiceClient Create() => new CampaignAssetServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CampaignAssetServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CampaignAssetServiceSettings"/>.</param>
/// <returns>The created <see cref="CampaignAssetServiceClient"/>.</returns>
internal static CampaignAssetServiceClient Create(grpccore::CallInvoker callInvoker, CampaignAssetServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CampaignAssetService.CampaignAssetServiceClient grpcClient = new CampaignAssetService.CampaignAssetServiceClient(callInvoker);
return new CampaignAssetServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CampaignAssetService client</summary>
public virtual CampaignAssetService.CampaignAssetServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested campaign asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CampaignAsset GetCampaignAsset(GetCampaignAssetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested campaign asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignAsset> GetCampaignAssetAsync(GetCampaignAssetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested campaign asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignAsset> GetCampaignAssetAsync(GetCampaignAssetRequest request, st::CancellationToken cancellationToken) =>
GetCampaignAssetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested campaign asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign asset to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CampaignAsset GetCampaignAsset(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignAsset(new GetCampaignAssetRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested campaign asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign asset to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignAsset> GetCampaignAssetAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignAssetAsync(new GetCampaignAssetRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested campaign asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign asset to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignAsset> GetCampaignAssetAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetCampaignAssetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested campaign asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign asset to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CampaignAsset GetCampaignAsset(gagvr::CampaignAssetName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignAsset(new GetCampaignAssetRequest
{
ResourceNameAsCampaignAssetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested campaign asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign asset to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignAsset> GetCampaignAssetAsync(gagvr::CampaignAssetName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignAssetAsync(new GetCampaignAssetRequest
{
ResourceNameAsCampaignAssetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested campaign asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the campaign asset to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignAsset> GetCampaignAssetAsync(gagvr::CampaignAssetName resourceName, st::CancellationToken cancellationToken) =>
GetCampaignAssetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCampaignAssetsResponse MutateCampaignAssets(MutateCampaignAssetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignAssetsResponse> MutateCampaignAssetsAsync(MutateCampaignAssetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignAssetsResponse> MutateCampaignAssetsAsync(MutateCampaignAssetsRequest request, st::CancellationToken cancellationToken) =>
MutateCampaignAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign assets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual campaign assets.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCampaignAssetsResponse MutateCampaignAssets(string customerId, scg::IEnumerable<CampaignAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCampaignAssets(new MutateCampaignAssetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign assets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual campaign assets.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignAssetsResponse> MutateCampaignAssetsAsync(string customerId, scg::IEnumerable<CampaignAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCampaignAssetsAsync(new MutateCampaignAssetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign assets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual campaign assets.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignAssetsResponse> MutateCampaignAssetsAsync(string customerId, scg::IEnumerable<CampaignAssetOperation> operations, st::CancellationToken cancellationToken) =>
MutateCampaignAssetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CampaignAssetService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage campaign assets.
/// </remarks>
public sealed partial class CampaignAssetServiceClientImpl : CampaignAssetServiceClient
{
private readonly gaxgrpc::ApiCall<GetCampaignAssetRequest, gagvr::CampaignAsset> _callGetCampaignAsset;
private readonly gaxgrpc::ApiCall<MutateCampaignAssetsRequest, MutateCampaignAssetsResponse> _callMutateCampaignAssets;
/// <summary>
/// Constructs a client wrapper for the CampaignAssetService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="CampaignAssetServiceSettings"/> used within this client.</param>
public CampaignAssetServiceClientImpl(CampaignAssetService.CampaignAssetServiceClient grpcClient, CampaignAssetServiceSettings settings)
{
GrpcClient = grpcClient;
CampaignAssetServiceSettings effectiveSettings = settings ?? CampaignAssetServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetCampaignAsset = clientHelper.BuildApiCall<GetCampaignAssetRequest, gagvr::CampaignAsset>(grpcClient.GetCampaignAssetAsync, grpcClient.GetCampaignAsset, effectiveSettings.GetCampaignAssetSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetCampaignAsset);
Modify_GetCampaignAssetApiCall(ref _callGetCampaignAsset);
_callMutateCampaignAssets = clientHelper.BuildApiCall<MutateCampaignAssetsRequest, MutateCampaignAssetsResponse>(grpcClient.MutateCampaignAssetsAsync, grpcClient.MutateCampaignAssets, effectiveSettings.MutateCampaignAssetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCampaignAssets);
Modify_MutateCampaignAssetsApiCall(ref _callMutateCampaignAssets);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetCampaignAssetApiCall(ref gaxgrpc::ApiCall<GetCampaignAssetRequest, gagvr::CampaignAsset> call);
partial void Modify_MutateCampaignAssetsApiCall(ref gaxgrpc::ApiCall<MutateCampaignAssetsRequest, MutateCampaignAssetsResponse> call);
partial void OnConstruction(CampaignAssetService.CampaignAssetServiceClient grpcClient, CampaignAssetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CampaignAssetService client</summary>
public override CampaignAssetService.CampaignAssetServiceClient GrpcClient { get; }
partial void Modify_GetCampaignAssetRequest(ref GetCampaignAssetRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateCampaignAssetsRequest(ref MutateCampaignAssetsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested campaign asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::CampaignAsset GetCampaignAsset(GetCampaignAssetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCampaignAssetRequest(ref request, ref callSettings);
return _callGetCampaignAsset.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested campaign asset in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::CampaignAsset> GetCampaignAssetAsync(GetCampaignAssetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCampaignAssetRequest(ref request, ref callSettings);
return _callGetCampaignAsset.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateCampaignAssetsResponse MutateCampaignAssets(MutateCampaignAssetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCampaignAssetsRequest(ref request, ref callSettings);
return _callMutateCampaignAssets.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateCampaignAssetsResponse> MutateCampaignAssetsAsync(MutateCampaignAssetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCampaignAssetsRequest(ref request, ref callSettings);
return _callMutateCampaignAssets.Async(request, callSettings);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Management.Automation;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the implementation of the 'Protect-CmsMessage' cmdlet.
///
/// This cmdlet generates a new encrypted CMS message given the
/// recipient and content supplied.
/// </summary>
[Cmdlet(VerbsSecurity.Protect, "CmsMessage", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096826", DefaultParameterSetName = "ByContent")]
[OutputType(typeof(string))]
public sealed class ProtectCmsMessageCommand : PSCmdlet
{
/// <summary>
/// Gets or sets the recipient of the CMS Message.
/// </summary>
[Parameter(Position = 0, Mandatory = true)]
public CmsMessageRecipient[] To
{
get; set;
}
/// <summary>
/// Gets or sets the content of the CMS Message.
/// </summary>
[Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByContent")]
[AllowNull()]
[AllowEmptyString()]
public PSObject Content
{
get;
set;
}
private readonly PSDataCollection<PSObject> _inputObjects = new();
/// <summary>
/// Gets or sets the content of the CMS Message by path.
/// </summary>
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "ByPath")]
public string Path
{
get;
set;
}
/// <summary>
/// Gets or sets the content of the CMS Message by literal path.
/// </summary>
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "ByLiteralPath")]
public string LiteralPath
{
get;
set;
}
private string _resolvedPath = null;
/// <summary>
/// Emits the protected message to a file path.
/// </summary>
[Parameter(Position = 2)]
public string OutFile
{
get;
set;
}
private string _resolvedOutFile = null;
/// <summary>
/// Validate / convert arguments.
/// </summary>
protected override void BeginProcessing()
{
// Validate Path
if (!string.IsNullOrEmpty(Path))
{
ProviderInfo provider = null;
Collection<string> resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out provider);
// Ensure the path is a single path from the file system provider
if ((resolvedPaths.Count > 1) ||
(!string.Equals(provider.Name, "FileSystem", StringComparison.OrdinalIgnoreCase)))
{
ErrorRecord error = new(
new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
CmsCommands.FilePathMustBeFileSystemPath,
Path)),
"FilePathMustBeFileSystemPath",
ErrorCategory.ObjectNotFound,
provider);
ThrowTerminatingError(error);
}
_resolvedPath = resolvedPaths[0];
}
if (!string.IsNullOrEmpty(LiteralPath))
{
// Validate that the path exists
SessionState.InvokeProvider.Item.Get(new string[] { LiteralPath }, false, true);
_resolvedPath = LiteralPath;
}
// Validate OutFile
if (!string.IsNullOrEmpty(OutFile))
{
_resolvedOutFile = GetUnresolvedProviderPathFromPSPath(OutFile);
}
}
/// <summary>
/// Processes records from the input pipeline.
/// For each input object, the command encrypts
/// and exports the object.
/// </summary>
protected override void ProcessRecord()
{
if (string.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase))
{
_inputObjects.Add(Content);
}
}
/// <summary>
/// Encrypts and outputs the message.
/// </summary>
protected override void EndProcessing()
{
byte[] contentBytes = null;
if (_inputObjects.Count > 0)
{
StringBuilder outputString = new();
Collection<PSObject> output = System.Management.Automation.PowerShell.Create()
.AddCommand("Microsoft.PowerShell.Utility\\Out-String")
.AddParameter("Stream")
.Invoke(_inputObjects);
foreach (PSObject outputObject in output)
{
if (outputString.Length > 0)
{
outputString.AppendLine();
}
outputString.Append(outputObject);
}
contentBytes = System.Text.Encoding.UTF8.GetBytes(outputString.ToString());
}
else
{
contentBytes = System.IO.File.ReadAllBytes(_resolvedPath);
}
ErrorRecord terminatingError = null;
string encodedContent = CmsUtils.Encrypt(contentBytes, To, this.SessionState, out terminatingError);
if (terminatingError != null)
{
ThrowTerminatingError(terminatingError);
}
if (string.IsNullOrEmpty(_resolvedOutFile))
{
WriteObject(encodedContent);
}
else
{
System.IO.File.WriteAllText(_resolvedOutFile, encodedContent);
}
}
}
/// <summary>
/// Defines the implementation of the 'Get-CmsMessage' cmdlet.
///
/// This cmdlet retrieves information about an encrypted CMS
/// message.
/// </summary>
[Cmdlet(VerbsCommon.Get, "CmsMessage", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096598")]
[OutputType(typeof(EnvelopedCms))]
public sealed class GetCmsMessageCommand : PSCmdlet
{
/// <summary>
/// Gets or sets the content of the CMS Message.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByContent")]
[AllowNull()]
[AllowEmptyString()]
public string Content
{
get;
set;
}
private readonly StringBuilder _contentBuffer = new();
/// <summary>
/// Gets or sets the CMS Message by path.
/// </summary>
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "ByPath")]
public string Path
{
get;
set;
}
/// <summary>
/// Gets or sets the CMS Message by literal path.
/// </summary>
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "ByLiteralPath")]
public string LiteralPath
{
get;
set;
}
private string _resolvedPath = null;
/// <summary>
/// Validate / convert arguments.
/// </summary>
protected override void BeginProcessing()
{
// Validate Path
if (!string.IsNullOrEmpty(Path))
{
ProviderInfo provider = null;
Collection<string> resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out provider);
// Ensure the path is a single path from the file system provider
if ((resolvedPaths.Count > 1) ||
(!string.Equals(provider.Name, "FileSystem", StringComparison.OrdinalIgnoreCase)))
{
ErrorRecord error = new(
new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
CmsCommands.FilePathMustBeFileSystemPath,
Path)),
"FilePathMustBeFileSystemPath",
ErrorCategory.ObjectNotFound,
provider);
ThrowTerminatingError(error);
}
_resolvedPath = resolvedPaths[0];
}
if (!string.IsNullOrEmpty(LiteralPath))
{
// Validate that the path exists
SessionState.InvokeProvider.Item.Get(new string[] { LiteralPath }, false, true);
_resolvedPath = LiteralPath;
}
}
/// <summary>
/// Processes records from the input pipeline.
/// For each input object, the command gets the information
/// about the protected message and exports the object.
/// </summary>
protected override void ProcessRecord()
{
if (string.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase))
{
if (_contentBuffer.Length > 0)
{
_contentBuffer.Append(System.Environment.NewLine);
}
_contentBuffer.Append(Content);
}
}
/// <summary>
/// Gets the CMS Message object.
/// </summary>
protected override void EndProcessing()
{
string actualContent = null;
// Read in the content
if (string.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase))
{
actualContent = _contentBuffer.ToString();
}
else
{
actualContent = System.IO.File.ReadAllText(_resolvedPath);
}
// Extract out the bytes and Base64 decode them
int startIndex, endIndex;
byte[] contentBytes = CmsUtils.RemoveAsciiArmor(actualContent, CmsUtils.BEGIN_CMS_SIGIL, CmsUtils.END_CMS_SIGIL, out startIndex, out endIndex);
if (contentBytes == null)
{
ErrorRecord error = new(
new ArgumentException(CmsCommands.InputContainedNoEncryptedContent),
"InputContainedNoEncryptedContent", ErrorCategory.ObjectNotFound, null);
ThrowTerminatingError(error);
}
EnvelopedCms cms = new();
cms.Decode(contentBytes);
PSObject result = new(cms);
List<object> recipients = new();
foreach (RecipientInfo recipient in cms.RecipientInfos)
{
recipients.Add(recipient.RecipientIdentifier.Value);
}
result.Properties.Add(
new PSNoteProperty("Recipients", recipients));
result.Properties.Add(
new PSNoteProperty("Content", actualContent));
WriteObject(result);
}
}
/// <summary>
/// Defines the implementation of the 'Unprotect-CmsMessage' cmdlet.
///
/// This cmdlet retrieves the clear text content of an encrypted CMS
/// message.
/// </summary>
[Cmdlet(VerbsSecurity.Unprotect, "CmsMessage", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096701", DefaultParameterSetName = "ByWinEvent")]
[OutputType(typeof(string))]
public sealed class UnprotectCmsMessageCommand : PSCmdlet
{
/// <summary>
/// Gets or sets the content of the CMS Message.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")]
[AllowNull()]
[AllowEmptyString()]
public string Content
{
get;
set;
}
private readonly StringBuilder _contentBuffer = new();
/// <summary>
/// Gets or sets the Windows Event Log Message with contents to be decrypted.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByWinEvent")]
[PSTypeName("System.Diagnostics.Eventing.Reader.EventLogRecord")]
public PSObject EventLogRecord
{
get;
set;
}
/// <summary>
/// Gets or sets the CMS Message by path.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = "ByPath")]
public string Path
{
get;
set;
}
/// <summary>
/// Gets or sets the CMS Message by literal path.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = "ByLiteralPath")]
public string LiteralPath
{
get;
set;
}
private string _resolvedPath = null;
/// <summary>
/// Determines whether to include the decrypted content in its original context,
/// rather than just output the decrypted content itself.
/// </summary>
[Parameter()]
public SwitchParameter IncludeContext
{
get;
set;
}
/// <summary>
/// Gets or sets the recipient of the CMS Message.
/// </summary>
[Parameter(Position = 1)]
public CmsMessageRecipient[] To
{
get;
set;
}
/// <summary>
/// Validate / convert arguments.
/// </summary>
protected override void BeginProcessing()
{
// Validate Path
if (!string.IsNullOrEmpty(Path))
{
ProviderInfo provider = null;
Collection<string> resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out provider);
// Ensure the path is a single path from the file system provider
if ((resolvedPaths.Count > 1) ||
(!string.Equals(provider.Name, "FileSystem", StringComparison.OrdinalIgnoreCase)))
{
ErrorRecord error = new(
new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
CmsCommands.FilePathMustBeFileSystemPath,
Path)),
"FilePathMustBeFileSystemPath",
ErrorCategory.ObjectNotFound,
provider);
ThrowTerminatingError(error);
}
_resolvedPath = resolvedPaths[0];
}
if (!string.IsNullOrEmpty(LiteralPath))
{
// Validate that the path exists
SessionState.InvokeProvider.Item.Get(new string[] { LiteralPath }, false, true);
_resolvedPath = LiteralPath;
}
}
/// <summary>
/// Processes records from the input pipeline.
/// For each input object, the command gets the information
/// about the protected message and exports the object.
/// </summary>
protected override void ProcessRecord()
{
// If we're process by content, collect it.
if (string.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase))
{
if (_contentBuffer.Length > 0)
{
_contentBuffer.Append(System.Environment.NewLine);
}
_contentBuffer.Append(Content);
}
// If we're processing event log records, decrypt those inline.
if (string.Equals("ByWinEvent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase))
{
string actualContent = EventLogRecord.Properties["Message"].Value.ToString();
string decrypted = Decrypt(actualContent);
if (!IncludeContext)
{
WriteObject(decrypted);
}
else
{
EventLogRecord.Properties["Message"].Value = decrypted;
WriteObject(EventLogRecord);
}
}
}
/// <summary>
/// Processes records from the input pipeline.
/// For each input object, the command gets the information
/// about the protected message and exports the object.
/// </summary>
protected override void EndProcessing()
{
if (string.Equals("ByWinEvent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase))
{
return;
}
string actualContent = null;
// Read in the content
if (string.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase))
{
actualContent = _contentBuffer.ToString();
}
else
{
actualContent = System.IO.File.ReadAllText(_resolvedPath);
}
string decrypted = Decrypt(actualContent);
WriteObject(decrypted);
}
private string Decrypt(string actualContent)
{
// Extract out the bytes and Base64 decode them
int startIndex, endIndex;
byte[] messageBytes = CmsUtils.RemoveAsciiArmor(actualContent, CmsUtils.BEGIN_CMS_SIGIL, CmsUtils.END_CMS_SIGIL, out startIndex, out endIndex);
if ((messageBytes == null) && (!IncludeContext))
{
ErrorRecord error = new(
new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
CmsCommands.InputContainedNoEncryptedContentIncludeContext,
"-IncludeContext")),
"InputContainedNoEncryptedContentIncludeContext",
ErrorCategory.ObjectNotFound,
targetObject: null);
ThrowTerminatingError(error);
}
// Capture the pre and post context, if there was any
string preContext = null;
string postContext = null;
if (IncludeContext)
{
if (startIndex > -1)
{
preContext = actualContent.Substring(0, startIndex);
}
if (endIndex > -1)
{
postContext = actualContent.Substring(endIndex);
}
}
EnvelopedCms cms = new();
X509Certificate2Collection certificates = new();
if ((To != null) && (To.Length > 0))
{
ErrorRecord error = null;
foreach (CmsMessageRecipient recipient in To)
{
recipient.Resolve(this.SessionState, ResolutionPurpose.Decryption, out error);
if (error != null)
{
ThrowTerminatingError(error);
return null;
}
foreach (X509Certificate2 certificate in recipient.Certificates)
{
certificates.Add(certificate);
}
}
}
string resultString = actualContent;
if (messageBytes != null)
{
cms.Decode(messageBytes);
cms.Decrypt(certificates);
resultString = System.Text.Encoding.UTF8.GetString(cms.ContentInfo.Content);
}
if (IncludeContext)
{
if (preContext != null)
{
resultString = preContext + resultString;
}
if (postContext != null)
{
resultString += postContext;
}
}
return resultString;
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Autodiscover
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml;
using Microsoft.Exchange.WebServices.Data;
/// <summary>
/// Represents the response to a GetUsersSettings call for an individual user.
/// </summary>
public sealed class GetUserSettingsResponse : AutodiscoverResponse
{
/// <summary>
/// Initializes a new instance of the <see cref="GetUserSettingsResponse"/> class.
/// </summary>
public GetUserSettingsResponse()
: base()
{
this.SmtpAddress = string.Empty;
this.Settings = new Dictionary<UserSettingName, object>();
this.UserSettingErrors = new Collection<UserSettingError>();
}
/// <summary>
/// Tries the get the user setting value.
/// </summary>
/// <typeparam name="T">Type of user setting.</typeparam>
/// <param name="setting">The setting.</param>
/// <param name="value">The setting value.</param>
/// <returns>True if setting was available.</returns>
public bool TryGetSettingValue<T>(UserSettingName setting, out T value)
{
object objValue;
if (this.Settings.TryGetValue(setting, out objValue))
{
value = (T)objValue;
return true;
}
else
{
value = default(T);
return false;
}
}
/// <summary>
/// Gets the SMTP address this response applies to.
/// </summary>
public string SmtpAddress
{
get; internal set;
}
/// <summary>
/// Gets the redirectionTarget (URL or email address)
/// </summary>
public string RedirectTarget
{
get; internal set;
}
/// <summary>
/// Gets the requested settings for the user.
/// </summary>
public IDictionary<UserSettingName, object> Settings
{
get; internal set;
}
/// <summary>
/// Gets error information for settings that could not be returned.
/// </summary>
public Collection<UserSettingError> UserSettingErrors
{
get; internal set;
}
/// <summary>
/// Loads response from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="endElementName">End element name.</param>
internal override void LoadFromXml(EwsXmlReader reader, string endElementName)
{
do
{
reader.Read();
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case XmlElementNames.RedirectTarget:
this.RedirectTarget = reader.ReadElementValue();
break;
case XmlElementNames.UserSettingErrors:
this.LoadUserSettingErrorsFromXml(reader);
break;
case XmlElementNames.UserSettings:
this.LoadUserSettingsFromXml(reader);
break;
default:
base.LoadFromXml(reader, endElementName);
break;
}
}
}
while (!reader.IsEndElement(XmlNamespace.Autodiscover, endElementName));
}
/// <summary>
/// Loads from XML.
/// </summary>
/// <param name="reader">The reader.</param>
internal void LoadUserSettingsFromXml(EwsXmlReader reader)
{
if (!reader.IsEmptyElement)
{
do
{
reader.Read();
if ((reader.NodeType == XmlNodeType.Element) && (reader.LocalName == XmlElementNames.UserSetting))
{
string settingClass = reader.ReadAttributeValue(XmlNamespace.XmlSchemaInstance, XmlAttributeNames.Type);
switch (settingClass)
{
case XmlElementNames.StringSetting:
case XmlElementNames.WebClientUrlCollectionSetting:
case XmlElementNames.AlternateMailboxCollectionSetting:
case XmlElementNames.ProtocolConnectionCollectionSetting:
case XmlElementNames.DocumentSharingLocationCollectionSetting:
this.ReadSettingFromXml(reader);
break;
default:
EwsUtilities.Assert(
false,
"GetUserSettingsResponse.LoadUserSettingsFromXml",
string.Format("Invalid setting class '{0}' returned", settingClass));
break;
}
}
}
while (!reader.IsEndElement(XmlNamespace.Autodiscover, XmlElementNames.UserSettings));
}
}
/// <summary>
/// Reads user setting from XML.
/// </summary>
/// <param name="reader">The reader.</param>
private void ReadSettingFromXml(EwsXmlReader reader)
{
string name = null;
object value = null;
do
{
reader.Read();
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case XmlElementNames.Name:
name = reader.ReadElementValue<string>();
break;
case XmlElementNames.Value:
value = reader.ReadElementValue();
break;
case XmlElementNames.WebClientUrls:
value = WebClientUrlCollection.LoadFromXml(reader);
break;
case XmlElementNames.ProtocolConnections:
value = ProtocolConnectionCollection.LoadFromXml(reader);
break;
case XmlElementNames.AlternateMailboxes:
value = AlternateMailboxCollection.LoadFromXml(reader);
break;
case XmlElementNames.DocumentSharingLocations:
value = DocumentSharingLocationCollection.LoadFromXml(reader);
break;
}
}
}
while (!reader.IsEndElement(XmlNamespace.Autodiscover, XmlElementNames.UserSetting));
// EWS Managed API is broken with AutoDSvc endpoint in RedirectUrl scenario
try
{
UserSettingName userSettingName = EwsUtilities.Parse<UserSettingName>(name);
this.Settings.Add(userSettingName, value);
}
catch (ArgumentException)
{
// ignore unexpected UserSettingName in the response (due to the server-side bugs).
// it'd be better if this is hooked into ITraceListener, but that is unavailable here.
//
// in case "name" is null, EwsUtilities.Parse throws ArgumentNullException
// (which derives from ArgumentException).
//
EwsUtilities.Assert(
false,
"GetUserSettingsResponse.ReadSettingFromXml",
"Unexpected or empty name element in user setting");
}
}
/// <summary>
/// Loads the user setting errors.
/// </summary>
/// <param name="reader">The reader.</param>
private void LoadUserSettingErrorsFromXml(EwsXmlReader reader)
{
if (!reader.IsEmptyElement)
{
do
{
reader.Read();
if ((reader.NodeType == XmlNodeType.Element) && (reader.LocalName == XmlElementNames.UserSettingError))
{
UserSettingError error = new UserSettingError();
error.LoadFromXml(reader);
this.UserSettingErrors.Add(error);
}
}
while (!reader.IsEndElement(XmlNamespace.Autodiscover, XmlElementNames.UserSettingErrors));
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Interop.Windows;
using OpenLiveWriter.Localization;
namespace OpenLiveWriter.CoreServices.Diagnostics
{
/// <summary>
/// Dialog that is displayed when an unhandled exception occurs
/// </summary>
public class UnexpectedErrorDialog : BaseForm
{
private Panel panel1;
private Label labelTitle;
private Label labelMessage;
private LinkLabel labelClickHere;
private Button buttonExit;
private Button buttonContinue;
private System.Windows.Forms.Label labelDescription;
private Button buttonSendError;
/// <summary>
/// Required designer variable.
/// </summary>
private readonly Container components = null;
public UnexpectedErrorDialog()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
labelTitle.Font = Res.GetFont(FontSize.Large, FontStyle.Bold);
buttonExit.Text = Res.Get(StringId.UnexpectedErrorExit);
buttonContinue.Text = Res.Get(StringId.UnexpectedErrorContinue);
buttonSendError.Text = Res.Get(StringId.UnexpectedErrorSendError);
labelClickHere.Text = Res.Get(StringId.UnexpectedErrorClickHere);
labelDescription.Text = Res.Get(StringId.UnexpectedErrorDescription);
Text = Res.Get(StringId.UnexpectedErrorTitle);
Icon = ApplicationEnvironment.ProductIcon;
}
protected override void OnLoad(EventArgs e)
{
Form owner = this.Owner;
if (owner != null)
this.TopMost = owner.TopMost;
base.OnLoad (e);
DisplayHelper.AutoFitSystemButton(buttonContinue, buttonContinue.Width, int.MaxValue);
DisplayHelper.AutoFitSystemButton(buttonExit, buttonExit.Width, int.MaxValue);
}
/// <summary>
/// Creates a new dialog
/// </summary>
/// <param name="title">The title to display</param>
/// <param name="text">The text to display</param>
/// <param name="rootCause">The Exception that is the root cause</param>
public UnexpectedErrorDialog(string title, string text, Exception rootCause) : this()
{
labelTitle.Text = title;
labelMessage.Text = text;
m_rootCause = rootCause;
}
/// <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.panel1 = new System.Windows.Forms.Panel();
this.labelTitle = new System.Windows.Forms.Label();
this.labelMessage = new System.Windows.Forms.Label();
this.buttonExit = new System.Windows.Forms.Button();
this.buttonContinue = new System.Windows.Forms.Button();
this.labelClickHere = new System.Windows.Forms.LinkLabel();
this.labelDescription = new System.Windows.Forms.Label();
this.buttonSendError = new System.Windows.Forms.Button();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel1.BackColor = System.Drawing.Color.White;
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Controls.Add(this.labelTitle);
this.panel1.Location = new System.Drawing.Point(-1, -1);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(399, 71);
this.panel1.TabIndex = 0;
//
// labelTitle
//
this.labelTitle.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelTitle.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Bold);
this.labelTitle.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.labelTitle.Location = new System.Drawing.Point(17, 27);
this.labelTitle.Name = "labelTitle";
this.labelTitle.Size = new System.Drawing.Size(390, 27);
this.labelTitle.TabIndex = 1;
this.labelTitle.Text = "Title goes here.";
//
// labelMessage
//
this.labelMessage.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.labelMessage.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelMessage.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.labelMessage.Location = new System.Drawing.Point(41, 82);
this.labelMessage.Name = "labelMessage";
this.labelMessage.Size = new System.Drawing.Size(309, 27);
this.labelMessage.TabIndex = 1;
this.labelMessage.Text = "Message goes here.";
//
// buttonExit
//
this.buttonExit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonExit.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonExit.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.buttonExit.Location = new System.Drawing.Point(-35, 211);
this.buttonExit.Name = "buttonExit";
this.buttonExit.Size = new System.Drawing.Size(77, 26);
this.buttonExit.TabIndex = 4;
this.buttonExit.Text = "Exit";
this.buttonExit.Visible = false;
this.buttonExit.Click += new System.EventHandler(this.buttonExit_Click);
//
// buttonContinue
//
this.buttonContinue.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonContinue.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonContinue.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonContinue.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.buttonContinue.Location = new System.Drawing.Point(293, 211);
this.buttonContinue.Name = "buttonContinue";
this.buttonContinue.Size = new System.Drawing.Size(90, 26);
this.buttonContinue.TabIndex = 5;
this.buttonContinue.Text = "&Continue";
this.buttonContinue.Click += new System.EventHandler(this.buttonContinue_Click);
//
// labelClickHere
//
this.labelClickHere.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.labelClickHere.AutoSize = true;
this.labelClickHere.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelClickHere.ForeColor = System.Drawing.SystemColors.HotTrack;
this.labelClickHere.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.labelClickHere.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.labelClickHere.LinkColor = System.Drawing.SystemColors.HotTrack;
this.labelClickHere.Location = new System.Drawing.Point(41, 159);
this.labelClickHere.Name = "labelClickHere";
this.labelClickHere.Size = new System.Drawing.Size(158, 15);
this.labelClickHere.TabIndex = 7;
this.labelClickHere.TabStop = true;
this.labelClickHere.Text = "Click here to see error details";
this.labelClickHere.Click += new System.EventHandler(this.labelClickHere_Click);
//
// labelDescription
//
this.labelDescription.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.labelDescription.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelDescription.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.labelDescription.Location = new System.Drawing.Point(41, 119);
this.labelDescription.Name = "labelDescription";
this.labelDescription.Size = new System.Drawing.Size(383, 34);
this.labelDescription.TabIndex = 2;
this.labelDescription.Text = "We have created an error summary that you can view.";
//
// buttonSendError
//
this.buttonSendError.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonSendError.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonSendError.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonSendError.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.buttonSendError.Location = new System.Drawing.Point(41, 211);
this.buttonSendError.Name = "buttonSendError";
this.buttonSendError.Size = new System.Drawing.Size(90, 26);
this.buttonSendError.TabIndex = 8;
this.buttonSendError.Text = "&Send Error";
this.buttonSendError.Click += new System.EventHandler(this.buttonSendError_Click);
//
// UnexpectedErrorDialog
//
this.ClientSize = new System.Drawing.Size(390, 249);
this.ControlBox = false;
this.Controls.Add(this.buttonSendError);
this.Controls.Add(this.labelClickHere);
this.Controls.Add(this.buttonContinue);
this.Controls.Add(this.buttonExit);
this.Controls.Add(this.labelDescription);
this.Controls.Add(this.labelMessage);
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "UnexpectedErrorDialog";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Unexpected Error";
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void buttonExit_Click(object sender, EventArgs e)
{
Process.GetCurrentProcess().Kill();
}
private void buttonContinue_Click(object sender, EventArgs e)
{
Close();
}
private void buttonSendError_Click(object sender, EventArgs e)
{
HockeyAppProxy.Current.UploadExceptionAsync(m_rootCause);
Close();
}
private void labelClickHere_Click(object sender, EventArgs e)
{
try
{
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo(DiagnosticsFilePath);
psi.UseShellExecute = true;
p.StartInfo = psi;
p.Start();
}
catch (Exception ex)
{
Trace.Fail("Unable to report error.\r\n\r\n" + ex.Message);
}
}
private string DiagnosticsFilePath
{
get
{
if (m_diagnosticsFilePath == null)
{
string fileName = "ErrorReport.txt";
string filePath = Path.Combine(Path.GetTempPath(), fileName);
int i = 1;
while (File.Exists(filePath))
{
string newfileName = Path.GetFileNameWithoutExtension(fileName) + i + Path.GetExtension(fileName);
filePath = Path.Combine(Path.GetTempPath(), newfileName);
i++;
}
m_diagnosticsFilePath = filePath;
using (StreamWriter writer = new StreamWriter(File.Create(m_diagnosticsFilePath)))
{
writer.WriteLine(DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString());
writer.WriteLine();
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Version: {0}", ApplicationEnvironment.ProductVersion)) ;
writer.WriteLine();
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "OS Version: {0}", Environment.OSVersion));
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Runtime version: {0}", Environment.Version));
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Shutdown started: {0}", Environment.HasShutdownStarted));
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Program: {0}", ReadExecutable()));
writer.WriteLine() ;
WriteMemoryStatus(writer) ;
writer.WriteLine();
writer.WriteLine(labelTitle.Text);
writer.WriteLine(labelMessage.Text);
writer.WriteLine();
WriteException(m_rootCause, writer);
}
}
return m_diagnosticsFilePath;
}
}
private string m_diagnosticsFilePath = null;
private static void WriteMemoryStatus(TextWriter writer)
{
try
{
GlobalMemoryStatus memoryStatus = new GlobalMemoryStatus() ;
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Memory Load: {0}%", memoryStatus.MemoryLoad ));
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Total Physical: {0} MB", (memoryStatus.TotalPhysical/1048576) ));
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Available Physical: {0} MB", (memoryStatus.AvailablePhysical/1048576) ));
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Total Page File: {0} MB", (memoryStatus.TotalPageFile/1048576) ));
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Available Page File: {0} MB", (memoryStatus.AvailablePageFile/1048576) ));
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Total Virtual: {0} MB", (memoryStatus.TotalVirtual/1048576) ));
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Available Virtual: {0} MB", (memoryStatus.AvailableVirtual/1048576) ));
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Available Extented Virtual: {0} MB", (memoryStatus.AvailableExtendedVirtual/1048576) ));
}
catch(Exception ex)
{
Debug.Write("Unexpected exception attempting to get global memory status: " + ex.ToString()) ;
}
}
private static string ReadExecutable()
{
string executable = string.Empty;
try
{
executable = Environment.CommandLine;
}
catch{}
return executable;
}
private void WriteException(Exception ex, StreamWriter writer)
{
writer.WriteLine();
writer.WriteLine(ex.ToString());
if (ex.InnerException != null && (m_exceptionDepth++ < MAX_EXCEPTION_DEPTH))
{
WriteException(ex.InnerException, writer);
}
}
private int m_exceptionDepth = 0;
private static readonly int MAX_EXCEPTION_DEPTH = 25;
private readonly Exception m_rootCause;
}
}
| |
using Microsoft.Deployment.WindowsInstaller;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace WixSharp.UI.Forms
{
/// <summary>
/// Set of extension methods for working with ManagedUI dialogs
/// </summary>
public static class Extensions
{
/// <summary>
/// Determines whether the feature checkbox is checked.
/// </summary>
/// <param name="feature">The feature.</param>
/// <returns></returns>
public static bool IsViewChecked(this FeatureItem feature)
{
if (feature.View is TreeNode)
return (feature.View as TreeNode).Checked;
return false;
}
/// <summary>
/// Resets the whether the feature checkbox checked state to the initial stat.
/// </summary>
/// <param name="feature">The feature.</param>
public static void ResetViewChecked(this FeatureItem feature)
{
if (feature.View is TreeNode)
(feature.View as TreeNode).Checked = feature.DefaultIsToBeInstalled();
}
/// <summary>
/// Returns default 'is to be installed' state of teh feature.
/// </summary>
/// <param name="feature">The feature.</param>
/// <returns></returns>
public static bool DefaultIsToBeInstalled(this FeatureItem feature)
{
return feature.RequestedState != InstallState.Absent;
}
/// <summary>
/// Returns the FeatireItem bound to the TreeNode.
/// </summary>
/// <param name="node">The node.</param>
/// <returns></returns>
public static FeatureItem FeatureItem(this TreeNode node)
{
return node.Tag as FeatureItem;
}
/// <summary>
/// Converts TreeNodeCollection into the TreeNode array.
/// </summary>
/// <param name="nodes">The nodes.</param>
/// <returns></returns>
public static TreeNode[] ToArray(this TreeNodeCollection nodes)
{
return nodes.Cast<TreeNode>().ToArray();
}
/// <summary>
/// Aggregates all nodes of the TreeView control.
/// </summary>
/// <param name="treeView">The tree view.</param>
/// <returns></returns>
public static TreeNode[] AllNodes(this TreeView treeView)
{
var result = new List<TreeNode>();
var queue = new Queue<TreeNode>(treeView.Nodes.Cast<TreeNode>());
while (queue.Any())
{
TreeNode node = queue.Dequeue();
result.Add(node);
foreach (TreeNode child in node.Nodes)
queue.Enqueue(child);
}
return result.ToArray();
}
}
#pragma warning disable 1591
public class ReadOnlyTreeNode : TreeNode
{
public bool IsReadOnly { get; set; }
public class Behavior
{
public static void AttachTo(TreeView treeView, bool drawTextOnly = false)
{
if (drawTextOnly)
{
treeView.DrawMode = TreeViewDrawMode.OwnerDrawText;
treeView.DrawNode += treeView_DrawNodeText;
}
else
{
treeView.DrawMode = TreeViewDrawMode.OwnerDrawAll;
treeView.DrawNode += treeView_DrawNode;
}
treeView.BeforeCheck += treeView_BeforeCheck;
}
static void treeView_BeforeCheck(object sender, TreeViewCancelEventArgs e)
{
if (IsReadOnly(e.Node))
{
e.Cancel = true;
}
}
static Pen dotPen = new Pen(Color.FromArgb(128, 128, 128)) { DashStyle = DashStyle.Dot };
static Brush selectionModeBrush = new SolidBrush(Color.FromArgb(51, 153, 255));
static bool IsReadOnly(TreeNode node)
{
return (node is ReadOnlyTreeNode) && (node as ReadOnlyTreeNode).IsReadOnly;
}
static int cIndentBy = -1;
static int cMargin = -1;
static void treeView_DrawNodeText(object sender, DrawTreeNodeEventArgs e)
{
//Loosely based on Jason Williams solution (http://stackoverflow.com/questions/1003459/c-treeview-owner-drawing-with-ownerdrawtext-and-the-weird-black-highlighting-w)
if (e.Bounds.Height < 1 || e.Bounds.Width < 1)
return;
var treeView = (TreeView)sender;
if (e.Node.IsSelected)
{
e.Graphics.FillRectangle(selectionModeBrush, e.Bounds);
e.Graphics.DrawString(e.Node.Text, treeView.Font, Brushes.White, e.Bounds);
}
else
{
if (IsReadOnly(e.Node))
e.Graphics.DrawString(e.Node.Text, treeView.Font, Brushes.Gray, e.Bounds);
else
e.Graphics.DrawString(e.Node.Text, treeView.Font, Brushes.Black, e.Bounds);
}
}
static void treeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
//Loosely based on Jason Williams solution (http://stackoverflow.com/questions/1003459/c-treeview-owner-drawing-with-ownerdrawtext-and-the-weird-black-highlighting-w)
if (e.Bounds.Height < 1 || e.Bounds.Width < 1)
return;
if (cIndentBy == -1)
{
cIndentBy = e.Bounds.Height;
cMargin = e.Bounds.Height / 2;
}
var treeView = (TreeView)sender;
Rectangle itemRect = e.Bounds;
e.Graphics.FillRectangle(Brushes.White, itemRect);
//e.Graphics.FillRectangle(Brushes.WhiteSmoke, itemRect);
int cTwoMargins = cMargin * 2;
int midY = (itemRect.Top + itemRect.Bottom) / 2;
int iconWidth = itemRect.Height + 2;
int checkboxWidth = itemRect.Height + 2;
int indent = (e.Node.Level * cIndentBy) + cMargin;
int iconLeft = indent; // lines left position
int checkboxLeft = iconLeft + iconWidth; // +/- icon left position
int textLeft = checkboxLeft + checkboxWidth; // text left position
if (!treeView.CheckBoxes)
textLeft = checkboxLeft;
// Draw parentage lines
if (treeView.ShowLines)
{
int x = cMargin * 2;
if (e.Node.Level == 0 && e.Node.PrevNode == null)
{
// The very first node in the tree has a half-height line
e.Graphics.DrawLine(dotPen, x, midY, x, itemRect.Bottom);
}
else
{
TreeNode testNode = e.Node; // Used to only draw lines to nodes with Next Siblings, as in normal TreeViews
for (int iLine = e.Node.Level; iLine >= 0; iLine--)
{
if (testNode.NextNode != null)
{
x = (iLine * cIndentBy) + (cMargin * 2);
e.Graphics.DrawLine(dotPen, x, itemRect.Top, x, itemRect.Bottom);
}
testNode = testNode.Parent;
}
x = (e.Node.Level * cIndentBy) + (cMargin * 2);
e.Graphics.DrawLine(dotPen, x, itemRect.Top, x, midY);
}
e.Graphics.DrawLine(dotPen, iconLeft + cMargin, midY, iconLeft + cMargin + 10, midY);
}
// Draw (plus/minus) icon if required
if (e.Node.Nodes.Count > 0)
{
var element = e.Node.IsExpanded ? VisualStyleElement.TreeView.Glyph.Opened : VisualStyleElement.TreeView.Glyph.Closed;
var renderer = new VisualStyleRenderer(element);
var iconTrueSize = renderer.GetPartSize(e.Graphics, ThemeSizeType.True);
var bounds = new Rectangle(itemRect.Left + iconLeft, itemRect.Top, iconWidth, iconWidth);
//e.Graphics.FillRectangle(Brushes.Salmon, bounds);
//deflate (resize and center) icon within bounds
var dif = (iconWidth - iconTrueSize.Height) / 2 - 1; //-1 is to compensate for rounding as icon is not getting rendered if the bounds is too small
bounds.Inflate(-dif, -dif);
renderer.DrawBackground(e.Graphics, bounds);
}
//Checkbox
if (treeView.CheckBoxes)
{
var element = e.Node.Checked ? VisualStyleElement.Button.CheckBox.CheckedNormal : VisualStyleElement.Button.CheckBox.UncheckedNormal;
if (IsReadOnly(e.Node))
element = e.Node.Checked ? VisualStyleElement.Button.CheckBox.CheckedDisabled : VisualStyleElement.Button.CheckBox.UncheckedDisabled;
var renderer = new VisualStyleRenderer(element);
var bounds = new Rectangle(itemRect.Left + checkboxLeft, itemRect.Top, checkboxWidth, itemRect.Height);
//e.Graphics.FillRectangle(Brushes.Bisque, bounds);
renderer.DrawBackground(e.Graphics, bounds);
}
//Text
if (!string.IsNullOrEmpty(e.Node.Text))
{
SizeF textSize = e.Graphics.MeasureString(e.Node.Text, treeView.Font);
var drawFormat = new StringFormat
{
Alignment = StringAlignment.Near,
LineAlignment = StringAlignment.Center,
FormatFlags = StringFormatFlags.NoWrap,
};
var bounds = new Rectangle(itemRect.Left + textLeft, itemRect.Top, (int)(textSize.Width + 2), itemRect.Height);
if (e.Node.IsSelected)
{
e.Graphics.FillRectangle(selectionModeBrush, bounds);
e.Graphics.DrawString(e.Node.Text, treeView.Font, Brushes.White, bounds, drawFormat);
}
else
{
//e.Graphics.FillRectangle(Brushes.Pink, bounds);
e.Graphics.DrawString(e.Node.Text, treeView.Font, Brushes.Black, bounds, drawFormat);
}
}
// Focus rectangle around the text
if (e.State == TreeNodeStates.Focused)
{
var r = itemRect;
r.Width -= 2;
r.Height -= 2;
r.Offset(indent, 0);
r.Width -= indent;
e.Graphics.DrawRectangle(dotPen, r);
}
}
}
}
#pragma warning restore 1591
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/devtools/cloudtrace/v1/trace.proto
// Original file comments:
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace Google.Cloud.Trace.V1 {
/// <summary>
/// This file describes an API for collecting and viewing traces and spans
/// within a trace. A Trace is a collection of spans corresponding to a single
/// operation or set of operations for an application. A span is an individual
/// timed event which forms a node of the trace tree. Spans for a single trace
/// may span multiple services.
/// </summary>
public static partial class TraceService
{
static readonly string __ServiceName = "google.devtools.cloudtrace.v1.TraceService";
static readonly grpc::Marshaller<global::Google.Cloud.Trace.V1.ListTracesRequest> __Marshaller_ListTracesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Trace.V1.ListTracesRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Trace.V1.ListTracesResponse> __Marshaller_ListTracesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Trace.V1.ListTracesResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Trace.V1.GetTraceRequest> __Marshaller_GetTraceRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Trace.V1.GetTraceRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Trace.V1.Trace> __Marshaller_Trace = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Trace.V1.Trace.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Trace.V1.PatchTracesRequest> __Marshaller_PatchTracesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Trace.V1.PatchTracesRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Cloud.Trace.V1.ListTracesRequest, global::Google.Cloud.Trace.V1.ListTracesResponse> __Method_ListTraces = new grpc::Method<global::Google.Cloud.Trace.V1.ListTracesRequest, global::Google.Cloud.Trace.V1.ListTracesResponse>(
grpc::MethodType.Unary,
__ServiceName,
"ListTraces",
__Marshaller_ListTracesRequest,
__Marshaller_ListTracesResponse);
static readonly grpc::Method<global::Google.Cloud.Trace.V1.GetTraceRequest, global::Google.Cloud.Trace.V1.Trace> __Method_GetTrace = new grpc::Method<global::Google.Cloud.Trace.V1.GetTraceRequest, global::Google.Cloud.Trace.V1.Trace>(
grpc::MethodType.Unary,
__ServiceName,
"GetTrace",
__Marshaller_GetTraceRequest,
__Marshaller_Trace);
static readonly grpc::Method<global::Google.Cloud.Trace.V1.PatchTracesRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_PatchTraces = new grpc::Method<global::Google.Cloud.Trace.V1.PatchTracesRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"PatchTraces",
__Marshaller_PatchTracesRequest,
__Marshaller_Empty);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.Trace.V1.TraceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of TraceService</summary>
public abstract partial class TraceServiceBase
{
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Trace.V1.ListTracesResponse> ListTraces(global::Google.Cloud.Trace.V1.ListTracesRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Trace.V1.Trace> GetTrace(global::Google.Cloud.Trace.V1.GetTraceRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> PatchTraces(global::Google.Cloud.Trace.V1.PatchTracesRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for TraceService</summary>
public partial class TraceServiceClient : grpc::ClientBase<TraceServiceClient>
{
/// <summary>Creates a new client for TraceService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public TraceServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for TraceService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public TraceServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected TraceServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected TraceServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Trace.V1.ListTracesResponse ListTraces(global::Google.Cloud.Trace.V1.ListTracesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListTraces(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Trace.V1.ListTracesResponse ListTraces(global::Google.Cloud.Trace.V1.ListTracesRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListTraces, null, options, request);
}
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Trace.V1.ListTracesResponse> ListTracesAsync(global::Google.Cloud.Trace.V1.ListTracesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListTracesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Trace.V1.ListTracesResponse> ListTracesAsync(global::Google.Cloud.Trace.V1.ListTracesRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListTraces, null, options, request);
}
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Trace.V1.Trace GetTrace(global::Google.Cloud.Trace.V1.GetTraceRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetTrace(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Trace.V1.Trace GetTrace(global::Google.Cloud.Trace.V1.GetTraceRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetTrace, null, options, request);
}
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Trace.V1.Trace> GetTraceAsync(global::Google.Cloud.Trace.V1.GetTraceRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetTraceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Trace.V1.Trace> GetTraceAsync(global::Google.Cloud.Trace.V1.GetTraceRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetTrace, null, options, request);
}
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Protobuf.WellKnownTypes.Empty PatchTraces(global::Google.Cloud.Trace.V1.PatchTracesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PatchTraces(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Protobuf.WellKnownTypes.Empty PatchTraces(global::Google.Cloud.Trace.V1.PatchTracesRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_PatchTraces, null, options, request);
}
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PatchTracesAsync(global::Google.Cloud.Trace.V1.PatchTracesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PatchTracesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PatchTracesAsync(global::Google.Cloud.Trace.V1.PatchTracesRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_PatchTraces, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override TraceServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new TraceServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(TraceServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_ListTraces, serviceImpl.ListTraces)
.AddMethod(__Method_GetTrace, serviceImpl.GetTrace)
.AddMethod(__Method_PatchTraces, serviceImpl.PatchTraces).Build();
}
}
}
#endregion
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web;
using DotNetOpenId;
using DotNetOpenId.Provider;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using Nini.Config;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Authentication
{
/// <summary>
/// Temporary, in-memory store for OpenID associations
/// </summary>
public class ProviderMemoryStore : IAssociationStore<AssociationRelyingPartyType>
{
private class AssociationItem
{
public AssociationRelyingPartyType DistinguishingFactor;
public string Handle;
public DateTime Expires;
public byte[] PrivateData;
}
Dictionary<string, AssociationItem> m_store = new Dictionary<string, AssociationItem>();
SortedList<DateTime, AssociationItem> m_sortedStore = new SortedList<DateTime, AssociationItem>();
object m_syncRoot = new object();
#region IAssociationStore<AssociationRelyingPartyType> Members
public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc)
{
AssociationItem item = new AssociationItem();
item.DistinguishingFactor = distinguishingFactor;
item.Handle = assoc.Handle;
item.Expires = assoc.Expires.ToLocalTime();
item.PrivateData = assoc.SerializePrivateData();
lock (m_syncRoot)
{
m_store[item.Handle] = item;
m_sortedStore[item.Expires] = item;
}
}
public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor)
{
lock (m_syncRoot)
{
if (m_sortedStore.Count > 0)
{
AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1];
return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
}
else
{
return null;
}
}
}
public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
{
AssociationItem item;
bool success = false;
lock (m_syncRoot)
success = m_store.TryGetValue(handle, out item);
if (success)
return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
else
return null;
}
public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
{
lock (m_syncRoot)
{
for (int i = 0; i < m_sortedStore.Values.Count; i++)
{
AssociationItem item = m_sortedStore.Values[i];
if (item.Handle == handle)
{
m_sortedStore.RemoveAt(i);
break;
}
}
return m_store.Remove(handle);
}
}
public void ClearExpiredAssociations()
{
lock (m_syncRoot)
{
List<AssociationItem> itemsCopy = new List<AssociationItem>(m_sortedStore.Values);
DateTime now = DateTime.Now;
for (int i = 0; i < itemsCopy.Count; i++)
{
AssociationItem item = itemsCopy[i];
if (item.Expires <= now)
{
m_sortedStore.RemoveAt(i);
m_store.Remove(item.Handle);
}
}
}
}
#endregion
}
public class OpenIdStreamHandler : IStreamHandler
{
#region HTML
/// <summary>Login form used to authenticate OpenID requests</summary>
const string LOGIN_PAGE =
@"<html>
<head><title>OpenSim OpenID Login</title></head>
<body>
<h3>OpenSim Login</h3>
<form method=""post"">
<label for=""first"">First Name:</label> <input readonly type=""text"" name=""first"" id=""first"" value=""{0}""/>
<label for=""last"">Last Name:</label> <input readonly type=""text"" name=""last"" id=""last"" value=""{1}""/>
<label for=""pass"">Password:</label> <input type=""password"" name=""pass"" id=""pass""/>
<input type=""submit"" value=""Login"">
</form>
</body>
</html>";
/// <summary>Page shown for a valid OpenID identity</summary>
const string OPENID_PAGE =
@"<html>
<head>
<title>{2} {3}</title>
<link rel=""openid2.provider openid.server"" href=""{0}://{1}/openid/server/""/>
</head>
<body>OpenID identifier for {2} {3}</body>
</html>
";
/// <summary>Page shown for an invalid OpenID identity</summary>
const string INVALID_OPENID_PAGE =
@"<html><head><title>Identity not found</title></head>
<body>Invalid OpenID identity</body></html>";
/// <summary>Page shown if the OpenID endpoint is requested directly</summary>
const string ENDPOINT_PAGE =
@"<html><head><title>OpenID Endpoint</title></head><body>
This is an OpenID server endpoint, not a human-readable resource.
For more information, see <a href='http://openid.net/'>http://openid.net/</a>.
</body></html>";
#endregion HTML
public string ContentType { get { return m_contentType; } }
public string HttpMethod { get { return m_httpMethod; } }
public string Path { get { return m_path; } }
string m_contentType;
string m_httpMethod;
string m_path;
IAuthenticationService m_authenticationService;
IUserAccountService m_userAccountService;
ProviderMemoryStore m_openidStore = new ProviderMemoryStore();
/// <summary>
/// Constructor
/// </summary>
public OpenIdStreamHandler(string httpMethod, string path, IUserAccountService userService, IAuthenticationService authService)
{
m_authenticationService = authService;
m_userAccountService = userService;
m_httpMethod = httpMethod;
m_path = path;
m_contentType = "text/html";
}
/// <summary>
/// Handles all GET and POST requests for OpenID identifier pages and endpoint
/// server communication
/// </summary>
public void Handle(string path, Stream request, Stream response, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath));
// Defult to returning HTML content
m_contentType = "text/html";
try
{
NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd());
NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query);
NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery);
OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery);
if (provider.Request != null)
{
if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest)
{
IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request;
string[] passwordValues = postQuery.GetValues("pass");
UserAccount account;
if (TryGetAccount(new Uri(authRequest.ClaimedIdentifier.ToString()), out account))
{
// Check for form POST data
if (passwordValues != null && passwordValues.Length == 1)
{
if (account != null &&
(m_authenticationService.Authenticate(account.PrincipalID, passwordValues[0], 30) != string.Empty))
authRequest.IsAuthenticated = true;
else
authRequest.IsAuthenticated = false;
}
else
{
// Authentication was requested, send the client a login form
using (StreamWriter writer = new StreamWriter(response))
writer.Write(String.Format(LOGIN_PAGE, account.FirstName, account.LastName));
return;
}
}
else
{
// Cannot find an avatar matching the claimed identifier
authRequest.IsAuthenticated = false;
}
}
// Add OpenID headers to the response
foreach (string key in provider.Request.Response.Headers.Keys)
httpResponse.AddHeader(key, provider.Request.Response.Headers[key]);
string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type");
if (contentTypeValues != null && contentTypeValues.Length == 1)
m_contentType = contentTypeValues[0];
// Set the response code and document body based on the OpenID result
httpResponse.StatusCode = (int)provider.Request.Response.Code;
response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length);
response.Close();
}
else if (httpRequest.Url.AbsolutePath.Contains("/openid/server"))
{
// Standard HTTP GET was made on the OpenID endpoint, send the client the default error page
using (StreamWriter writer = new StreamWriter(response))
writer.Write(ENDPOINT_PAGE);
}
else
{
// Try and lookup this avatar
UserAccount account;
if (TryGetAccount(httpRequest.Url, out account))
{
using (StreamWriter writer = new StreamWriter(response))
{
// TODO: Print out a full profile page for this avatar
writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme,
httpRequest.Url.Authority, account.FirstName, account.LastName));
}
}
else
{
// Couldn't parse an avatar name, or couldn't find the avatar in the user server
using (StreamWriter writer = new StreamWriter(response))
writer.Write(INVALID_OPENID_PAGE);
}
}
}
catch (Exception ex)
{
httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
using (StreamWriter writer = new StreamWriter(response))
writer.Write(ex.Message);
}
}
/// <summary>
/// Parse a URL with a relative path of the form /users/First_Last and try to
/// retrieve the profile matching that avatar name
/// </summary>
/// <param name="requestUrl">URL to parse for an avatar name</param>
/// <param name="profile">Profile data for the avatar</param>
/// <returns>True if the parse and lookup were successful, otherwise false</returns>
bool TryGetAccount(Uri requestUrl, out UserAccount account)
{
if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/")
{
// Parse the avatar name from the path
string username = requestUrl.Segments[requestUrl.Segments.Length - 1];
string[] name = username.Split('_');
if (name.Length == 2)
{
account = m_userAccountService.GetUserAccount(UUID.Zero, name[0], name[1]);
return (account != null);
}
}
account = null;
return false;
}
}
}
| |
/*
Matali Physics Demo
Copyright (c) 2013 KOMIRES Sp. z o. o.
*/
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using Komires.MataliPhysics;
namespace MataliPhysicsDemo
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Building2
{
Demo demo;
PhysicsScene scene;
string instanceIndexName;
public Building2(Demo demo, int instanceIndex)
{
this.demo = demo;
instanceIndexName = " " + instanceIndex.ToString();
}
public void Initialize(PhysicsScene scene)
{
this.scene = scene;
}
public static void CreateShapes(Demo demo, PhysicsScene scene)
{
}
public void Create(Vector3 objectPosition, Vector3 objectScale, Quaternion objectOrientation)
{
Shape box = scene.Factory.ShapeManager.Find("Box");
PhysicsObject objectRoot = null;
PhysicsObject objectBase = null;
PhysicsObject objectA = null;
PhysicsObject objectB = null;
objectRoot = scene.Factory.PhysicsObjectManager.Create("Building 2" + instanceIndexName);
objectA = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectA);
objectA.Material.RigidGroup = true;
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Floor" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, -8.0f, 100.0f);
objectBase.InitLocalTransform.SetScale(100.0f, 1.0f, 100.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Wall 1" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 21.0f, 201.0f);
objectBase.InitLocalTransform.SetScale(100.0f, 1.0f, 30.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Wall 2" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(101.0f, 21.0f, 100.0f);
objectBase.InitLocalTransform.SetScale(30.0f, 1.0f, 102.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(90.0f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Wall 3" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(-101.0f, 21.0f, 100.0f);
objectBase.InitLocalTransform.SetScale(30.0f, 1.0f, 102.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(90.0f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Wall 41" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(-60.0f, 21.0f, -1.0f);
objectBase.InitLocalTransform.SetScale(40.0f, 1.0f, 30.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Wall 42" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 21.0f + 15.0f, -1.0f);
objectBase.InitLocalTransform.SetScale(20.0f, 1.0f, 15.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Wall 43" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 21.0f - 29.0f, -1.0f);
objectBase.InitLocalTransform.SetScale(20.0f, 1.0f, 1.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Wall 44" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(60.0f, 21.0f, -1.0f);
objectBase.InitLocalTransform.SetScale(40.0f, 1.0f, 30.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Wall 45" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 21.0f - 29.0f, -6.9f);
objectBase.InitLocalTransform.SetScale(20.0f, 0.1f, 5.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(10.4f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Ceiling 11" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 50.0f, 120.0f);
objectBase.InitLocalTransform.SetScale(100.0f, 1.0f, 40.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Ceiling 12" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 50.0f, 40.0f);
objectBase.InitLocalTransform.SetScale(100.0f, 1.0f, 40.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Ceiling 13" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(-40.0f, 50.0f, 180.0f);
objectBase.InitLocalTransform.SetScale(60.0f, 1.0f, 20.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Ceiling 14" + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(80.0f, 50.0f, 180.0f);
objectBase.InitLocalTransform.SetScale(20.0f, 1.0f, 20.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
for (int i = 0; i < 29; i++)
{
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 1 Stair " + i.ToString() + instanceIndexName);
objectA.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(2.5f * i - 12.5f, -7.0f + i * 2.0f * 1.0f + 1.0f, 180.0f);
objectBase.InitLocalTransform.SetScale(2.5f, 1.0f, 20.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
}
objectB = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectB);
objectB.Material.RigidGroup = true;
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2 Wall 1" + instanceIndexName);
objectB.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 21.0f + 60.0f, 201.0f);
objectBase.InitLocalTransform.SetScale(100.0f, 1.0f, 30.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2 Wall 2" + instanceIndexName);
objectB.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(101.0f, 21.0f + 60.0f, 100.0f);
objectBase.InitLocalTransform.SetScale(30.0f, 1.0f, 102.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(90.0f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2 Wall 3" + instanceIndexName);
objectB.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(-101.0f, 21.0f + 60.0f, 100.0f);
objectBase.InitLocalTransform.SetScale(30.0f, 1.0f, 102.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(90.0f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2 Wall 41" + instanceIndexName);
objectB.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(-60.0f, 21.0f + 60.0f, -1.0f);
objectBase.InitLocalTransform.SetScale(40.0f, 1.0f, 30.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2 Wall 42" + instanceIndexName);
objectB.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 21.0f + 15.0f + 60.0f, -1.0f);
objectBase.InitLocalTransform.SetScale(20.0f, 1.0f, 15.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2 Wall 43" + instanceIndexName);
objectB.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 21.0f - 29.0f + 60.0f, -1.0f);
objectBase.InitLocalTransform.SetScale(20.0f, 1.0f, 1.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2 Wall 44" + instanceIndexName);
objectB.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(60.0f, 21.0f + 60.0f, -1.0f);
objectBase.InitLocalTransform.SetScale(40.0f, 1.0f, 30.0f);
objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f)));
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2 Ceiling 11" + instanceIndexName);
objectB.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 50.0f + 60.0f, 160.0f);
objectBase.InitLocalTransform.SetScale(100.0f, 1.0f, 40.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2 Ceiling 12" + instanceIndexName);
objectB.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 50.0f + 60.0f, 40.0f);
objectBase.InitLocalTransform.SetScale(100.0f, 1.0f, 40.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2 Ceiling 13" + instanceIndexName);
objectB.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(40.0f, 50.0f + 60.0f, 100.0f);
objectBase.InitLocalTransform.SetScale(60.0f, 1.0f, 20.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2 Ceiling 14" + instanceIndexName);
objectB.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(-80.0f, 50.0f + 60.0f, 100.0f);
objectBase.InitLocalTransform.SetScale(20.0f, 1.0f, 20.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
for (int i = 0; i < 29; i++)
{
objectBase = scene.Factory.PhysicsObjectManager.Create("Building 2 Level 2 Stair " + i.ToString() + instanceIndexName);
objectB.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.Material.UserDataStr = "Wood2";
objectBase.Material.RigidGroup = true;
objectBase.Material.MinBreakRigidGroupVelocity = 200.0f;
objectBase.InitLocalTransform.SetPosition(-2.5f * i + 12.5f, 51.0f + i * 2.0f * 1.0f + 1.0f, 100.0f);
objectBase.InitLocalTransform.SetScale(2.5f, 1.0f, 20.0f);
objectBase.Integral.SetDensity(1.0f);
objectBase.CreateSound(true);
}
objectRoot.InitLocalTransform.SetOrientation(ref objectOrientation);
objectRoot.InitLocalTransform.SetScale(ref objectScale);
objectRoot.InitLocalTransform.SetPosition(ref objectPosition);
scene.UpdateFromInitLocalTransform(objectRoot);
}
}
}
| |
// 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.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Threading;
using System.Security;
using System.Globalization;
using System.Collections.Generic;
namespace System.ServiceModel.Diagnostics
{
public static class TraceUtility
{
private const string ActivityIdKey = "ActivityId";
private const string AsyncOperationActivityKey = "AsyncOperationActivity";
private const string AsyncOperationStartTimeKey = "AsyncOperationStartTime";
private static long s_messageNumber = 0;
public const string E2EActivityId = "E2EActivityId";
public const string TraceApplicationReference = "TraceApplicationReference";
static internal void AddActivityHeader(Message message)
{
try
{
ActivityIdHeader activityIdHeader = new ActivityIdHeader(TraceUtility.ExtractActivityId(message));
activityIdHeader.AddTo(message);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
}
}
static internal void AddAmbientActivityToMessage(Message message)
{
try
{
ActivityIdHeader activityIdHeader = new ActivityIdHeader(DiagnosticTraceBase.ActivityId);
activityIdHeader.AddTo(message);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
}
}
static internal void CopyActivity(Message source, Message destination)
{
if (DiagnosticUtility.ShouldUseActivity)
{
TraceUtility.SetActivity(destination, TraceUtility.ExtractActivity(source));
}
}
internal static long GetUtcBasedDurationForTrace(long startTicks)
{
if (startTicks > 0)
{
TimeSpan elapsedTime = new TimeSpan(DateTime.UtcNow.Ticks - startTicks);
return (long)elapsedTime.TotalMilliseconds;
}
return 0;
}
internal static ServiceModelActivity ExtractActivity(Message message)
{
ServiceModelActivity retval = null;
if ((DiagnosticUtility.ShouldUseActivity || TraceUtility.ShouldPropagateActivityGlobal) &&
(message != null) &&
(message.State != MessageState.Closed))
{
object property;
if (message.Properties.TryGetValue(TraceUtility.ActivityIdKey, out property))
{
retval = property as ServiceModelActivity;
}
}
return retval;
}
internal static Guid ExtractActivityId(Message message)
{
if (TraceUtility.MessageFlowTracingOnly)
{
return ActivityIdHeader.ExtractActivityId(message);
}
ServiceModelActivity activity = ExtractActivity(message);
return activity == null ? Guid.Empty : activity.Id;
}
internal static Guid GetReceivedActivityId(OperationContext operationContext)
{
object activityIdFromProprties;
if (!operationContext.IncomingMessageProperties.TryGetValue(E2EActivityId, out activityIdFromProprties))
{
return TraceUtility.ExtractActivityId(operationContext.IncomingMessage);
}
else
{
return (Guid)activityIdFromProprties;
}
}
internal static ServiceModelActivity ExtractAndRemoveActivity(Message message)
{
ServiceModelActivity retval = TraceUtility.ExtractActivity(message);
if (retval != null)
{
// If the property is just removed, the item is disposed and we don't want the thing
// to be disposed of.
message.Properties[TraceUtility.ActivityIdKey] = false;
}
return retval;
}
internal static void ProcessIncomingMessage(Message message, EventTraceActivity eventTraceActivity)
{
ServiceModelActivity activity = ServiceModelActivity.Current;
if (activity != null && DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity incomingActivity = TraceUtility.ExtractActivity(message);
if (null != incomingActivity && incomingActivity.Id != activity.Id)
{
using (ServiceModelActivity.BoundOperation(incomingActivity))
{
if (null != FxTrace.Trace)
{
FxTrace.Trace.TraceTransfer(activity.Id);
}
}
}
TraceUtility.SetActivity(message, activity);
}
TraceUtility.MessageFlowAtMessageReceived(message, null, eventTraceActivity, true);
if (MessageLogger.LogMessagesAtServiceLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelReceiveReply | MessageLoggingSource.LastChance);
}
}
internal static void ProcessOutgoingMessage(Message message, EventTraceActivity eventTraceActivity)
{
ServiceModelActivity activity = ServiceModelActivity.Current;
if (DiagnosticUtility.ShouldUseActivity)
{
TraceUtility.SetActivity(message, activity);
}
if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
{
TraceUtility.AddAmbientActivityToMessage(message);
}
TraceUtility.MessageFlowAtMessageSent(message, eventTraceActivity);
if (MessageLogger.LogMessagesAtServiceLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelSendRequest | MessageLoggingSource.LastChance);
}
}
internal static void SetActivity(Message message, ServiceModelActivity activity)
{
if (DiagnosticUtility.ShouldUseActivity && message != null && message.State != MessageState.Closed)
{
message.Properties[TraceUtility.ActivityIdKey] = activity;
}
}
internal static void TraceDroppedMessage(Message message, EndpointDispatcher dispatcher)
{
}
private static string GenerateMsdnTraceCode(int traceCode)
{
int group = (int)(traceCode & 0xFFFF0000);
string terminatorUri = null;
switch (group)
{
case TraceCode.Administration:
terminatorUri = "System.ServiceModel.Administration";
break;
case TraceCode.Channels:
terminatorUri = "System.ServiceModel.Channels";
break;
case TraceCode.ComIntegration:
terminatorUri = "System.ServiceModel.ComIntegration";
break;
case TraceCode.Diagnostics:
terminatorUri = "System.ServiceModel.Diagnostics";
break;
case TraceCode.PortSharing:
terminatorUri = "System.ServiceModel.PortSharing";
break;
case TraceCode.Security:
terminatorUri = "System.ServiceModel.Security";
break;
case TraceCode.Serialization:
terminatorUri = "System.Runtime.Serialization";
break;
case TraceCode.ServiceModel:
case TraceCode.ServiceModelTransaction:
terminatorUri = "System.ServiceModel";
break;
default:
terminatorUri = string.Empty;
break;
}
return string.Empty;
}
internal static Exception ThrowHelperError(Exception exception, Message message)
{
return exception;
}
internal static Exception ThrowHelperError(Exception exception, Guid activityId, object source)
{
return exception;
}
internal static Exception ThrowHelperWarning(Exception exception, Message message)
{
return exception;
}
internal static ArgumentException ThrowHelperArgument(string paramName, string message, Message msg)
{
return (ArgumentException)TraceUtility.ThrowHelperError(new ArgumentException(message, paramName), msg);
}
internal static ArgumentNullException ThrowHelperArgumentNull(string paramName, Message message)
{
return (ArgumentNullException)TraceUtility.ThrowHelperError(new ArgumentNullException(paramName), message);
}
internal static string CreateSourceString(object source)
{
return source.GetType().ToString() + "/" + source.GetHashCode().ToString(CultureInfo.CurrentCulture);
}
internal static void TraceHttpConnectionInformation(string localEndpoint, string remoteEndpoint, object source)
{
}
internal static void TraceUserCodeException(Exception e, MethodInfo method)
{
}
static TraceUtility()
{
//Maintain the order of calls
TraceUtility.SetEtwProviderId();
TraceUtility.SetEndToEndTracingFlags();
}
[Fx.Tag.SecurityNote(Critical = "Calls critical method DiagnosticSection.UnsafeGetSection.",
Safe = "Doesn't leak config section instance, just reads and stores bool values.")]
[SecuritySafeCritical]
private static void SetEndToEndTracingFlags()
{
}
static public long RetrieveMessageNumber()
{
return Interlocked.Increment(ref TraceUtility.s_messageNumber);
}
static public bool PropagateUserActivity
{
get
{
return TraceUtility.ShouldPropagateActivity &&
TraceUtility.PropagateUserActivityCore;
}
}
// Most of the time, shouldPropagateActivity will be false.
// This property will rarely be executed as a result.
private static bool PropagateUserActivityCore
{
[MethodImpl(MethodImplOptions.NoInlining)]
get
{
return false;
}
}
static internal string GetCallerInfo(OperationContext context)
{
return "null";
}
[Fx.Tag.SecurityNote(Critical = "Calls critical method DiagnosticSection.UnsafeGetSection.",
Safe = "Doesn't leak config section instance, just reads and stores string values for Guid")]
[SecuritySafeCritical]
static internal void SetEtwProviderId()
{
}
static internal void SetActivityId(MessageProperties properties)
{
Guid activityId;
if ((null != properties) && properties.TryGetValue(TraceUtility.E2EActivityId, out activityId))
{
DiagnosticTraceBase.ActivityId = activityId;
}
}
static internal bool ShouldPropagateActivity
{
get
{
return false;
}
}
static internal bool ShouldPropagateActivityGlobal
{
get
{
return false;
}
}
static internal bool ActivityTracing
{
get
{
return false;
}
}
static internal bool MessageFlowTracing
{
get
{
return false;
}
}
static internal bool MessageFlowTracingOnly
{
get
{
return false;
}
}
static internal void MessageFlowAtMessageSent(Message message, EventTraceActivity eventTraceActivity)
{
if (TraceUtility.MessageFlowTracing)
{
Guid activityId;
Guid correlationId;
bool activityIdFound = ActivityIdHeader.ExtractActivityAndCorrelationId(message, out activityId, out correlationId);
if (TraceUtility.MessageFlowTracingOnly)
{
if (activityIdFound && activityId != DiagnosticTraceBase.ActivityId)
{
DiagnosticTraceBase.ActivityId = activityId;
}
}
if (WcfEventSource.Instance.MessageSentToTransportIsEnabled())
{
WcfEventSource.Instance.MessageSentToTransport(eventTraceActivity, correlationId);
}
}
}
static internal void MessageFlowAtMessageReceived(Message message, OperationContext context, EventTraceActivity eventTraceActivity, bool createNewActivityId)
{
if (TraceUtility.MessageFlowTracing)
{
Guid activityId;
Guid correlationId;
bool activityIdFound = ActivityIdHeader.ExtractActivityAndCorrelationId(message, out activityId, out correlationId);
if (TraceUtility.MessageFlowTracingOnly)
{
if (createNewActivityId)
{
if (!activityIdFound)
{
activityId = Guid.NewGuid();
activityIdFound = true;
}
//message flow tracing only - start fresh
DiagnosticTraceBase.ActivityId = Guid.Empty;
}
if (activityIdFound)
{
FxTrace.Trace.SetAndTraceTransfer(activityId, !createNewActivityId);
}
}
if (WcfEventSource.Instance.MessageReceivedFromTransportIsEnabled())
{
if (context == null)
{
context = OperationContext.Current;
}
WcfEventSource.Instance.MessageReceivedFromTransport(eventTraceActivity, correlationId, TraceUtility.GetAnnotation(context));
}
}
}
internal static string GetAnnotation(OperationContext context)
{
// Desktop obtains annotation from host
return String.Empty;
}
internal static void TransferFromTransport(Message message)
{
if (message != null && DiagnosticUtility.ShouldUseActivity)
{
Guid guid = Guid.Empty;
// Only look if we are allowing user propagation
if (TraceUtility.ShouldPropagateActivity)
{
guid = ActivityIdHeader.ExtractActivityId(message);
}
if (guid == Guid.Empty)
{
guid = Guid.NewGuid();
}
ServiceModelActivity activity = null;
bool emitStart = true;
if (ServiceModelActivity.Current != null)
{
if ((ServiceModelActivity.Current.Id == guid) ||
(ServiceModelActivity.Current.ActivityType == ActivityType.ProcessAction))
{
activity = ServiceModelActivity.Current;
emitStart = false;
}
else if (ServiceModelActivity.Current.PreviousActivity != null &&
ServiceModelActivity.Current.PreviousActivity.Id == guid)
{
activity = ServiceModelActivity.Current.PreviousActivity;
emitStart = false;
}
}
if (activity == null)
{
activity = ServiceModelActivity.CreateActivity(guid);
}
if (DiagnosticUtility.ShouldUseActivity)
{
if (emitStart)
{
if (null != FxTrace.Trace)
{
FxTrace.Trace.TraceTransfer(guid);
}
ServiceModelActivity.Start(activity, SR.Format(SR.ActivityProcessAction, message.Headers.Action), ActivityType.ProcessAction);
}
}
message.Properties[TraceUtility.ActivityIdKey] = activity;
}
}
static internal void UpdateAsyncOperationContextWithActivity(object activity)
{
if (OperationContext.Current != null && activity != null)
{
OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationActivityKey] = activity;
}
}
static internal object ExtractAsyncOperationContextActivity()
{
object data = null;
if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue(TraceUtility.AsyncOperationActivityKey, out data))
{
OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationActivityKey);
}
return data;
}
static internal void UpdateAsyncOperationContextWithStartTime(EventTraceActivity eventTraceActivity, long startTime)
{
if (OperationContext.Current != null)
{
OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationStartTimeKey] = new EventTraceActivityTimeProperty(eventTraceActivity, startTime);
}
}
static internal void ExtractAsyncOperationStartTime(out EventTraceActivity eventTraceActivity, out long startTime)
{
EventTraceActivityTimeProperty data = null;
eventTraceActivity = null;
startTime = 0;
if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue<EventTraceActivityTimeProperty>(TraceUtility.AsyncOperationStartTimeKey, out data))
{
OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationStartTimeKey);
eventTraceActivity = data.EventTraceActivity;
startTime = data.StartTime;
}
}
internal class TracingAsyncCallbackState
{
private object _innerState;
private Guid _activityId;
internal TracingAsyncCallbackState(object innerState)
{
_innerState = innerState;
_activityId = DiagnosticTraceBase.ActivityId;
}
internal object InnerState
{
get { return _innerState; }
}
internal Guid ActivityId
{
get { return _activityId; }
}
}
internal static AsyncCallback WrapExecuteUserCodeAsyncCallback(AsyncCallback callback)
{
return (DiagnosticUtility.ShouldUseActivity && callback != null) ?
(new ExecuteUserCodeAsync(callback)).Callback
: callback;
}
internal sealed class ExecuteUserCodeAsync
{
private AsyncCallback _callback;
public ExecuteUserCodeAsync(AsyncCallback callback)
{
_callback = callback;
}
public AsyncCallback Callback
{
get
{
return Fx.ThunkCallback(new AsyncCallback(this.ExecuteUserCode));
}
}
private void ExecuteUserCode(IAsyncResult result)
{
using (ServiceModelActivity activity = ServiceModelActivity.CreateBoundedActivity())
{
ServiceModelActivity.Start(activity, SR.ActivityCallback, ActivityType.ExecuteUserCode);
_callback(result);
}
}
}
internal class EventTraceActivityTimeProperty
{
private long _startTime;
private EventTraceActivity _eventTraceActivity;
public EventTraceActivityTimeProperty(EventTraceActivity eventTraceActivity, long startTime)
{
_eventTraceActivity = eventTraceActivity;
_startTime = startTime;
}
internal long StartTime
{
get { return _startTime; }
}
internal EventTraceActivity EventTraceActivity
{
get { return _eventTraceActivity; }
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
/// Blends between the scene and the tone mapped scene.
$HDRPostFX::enableToneMapping = 1.0;
/// The tone mapping middle grey or exposure value used
/// to adjust the overall "balance" of the image.
///
/// 0.18 is fairly common value.
///
$HDRPostFX::keyValue = 0.18;
/// The minimum luninace value to allow when tone mapping
/// the scene. Is particularly useful if your scene very
/// dark or has a black ambient color in places.
$HDRPostFX::minLuminace = 0.001;
/// The lowest luminance value which is mapped to white. This
/// is usually set to the highest visible luminance in your
/// scene. By setting this to smaller values you get a contrast
/// enhancement.
$HDRPostFX::whiteCutoff = 1.0;
/// The rate of adaptation from the previous and new
/// average scene luminance.
$HDRPostFX::adaptRate = 2.0;
/// Blends between the scene and the blue shifted version
/// of the scene for a cinematic desaturated night effect.
$HDRPostFX::enableBlueShift = 0.0;
/// The blue shift color value.
$HDRPostFX::blueShiftColor = "1.05 0.97 1.27";
/// Blends between the scene and the bloomed scene.
$HDRPostFX::enableBloom = 1.0;
/// The threshold luminace value for pixels which are
/// considered "bright" and need to be bloomed.
$HDRPostFX::brightPassThreshold = 1.0;
/// These are used in the gaussian blur of the
/// bright pass for the bloom effect.
$HDRPostFX::gaussMultiplier = 0.3;
$HDRPostFX::gaussMean = 0.0;
$HDRPostFX::gaussStdDev = 0.8;
singleton ShaderData( HDR_BrightPassShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/postFx/hdr/brightPassFilterP.hlsl";
pixVersion = 3.0;
};
singleton ShaderData( HDR_DownScale4x4Shader )
{
DXVertexShaderFile = "shaders/common/postFx/hdr/downScale4x4V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/hdr/downScale4x4P.hlsl";
pixVersion = 2.0;
};
singleton ShaderData( HDR_BloomGaussBlurHShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/postFx/hdr/bloomGaussBlurHP.hlsl";
pixVersion = 3.0;
};
singleton ShaderData( HDR_BloomGaussBlurVShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/postFx/hdr/bloomGaussBlurVP.hlsl";
pixVersion = 3.0;
};
singleton ShaderData( HDR_SampleLumShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/postFx/hdr/sampleLumInitialP.hlsl";
pixVersion = 3.0;
};
singleton ShaderData( HDR_DownSampleLumShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/postFx/hdr/sampleLumIterativeP.hlsl";
pixVersion = 3.0;
};
singleton ShaderData( HDR_CalcAdaptedLumShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/postFx/hdr/calculateAdaptedLumP.hlsl";
pixVersion = 3.0;
};
singleton ShaderData( HDR_CombineShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/postFx/hdr/finalPassCombineP.hlsl";
pixVersion = 3.0;
};
singleton GFXStateBlockData( HDR_SampleStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerClampPoint;
};
singleton GFXStateBlockData( HDR_DownSampleStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
};
singleton GFXStateBlockData( HDR_CombineStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerClampLinear;
samplerStates[2] = SamplerClampLinear;
};
singleton GFXStateBlockData( HDRStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
samplerStates[2] = SamplerClampLinear;
samplerStates[3] = SamplerClampLinear;
blendDefined = true;
blendDest = GFXBlendOne;
blendSrc = GFXBlendZero;
zDefined = true;
zEnable = false;
zWriteEnable = false;
cullDefined = true;
cullMode = GFXCullNone;
};
function HDRPostFX::setShaderConsts( %this )
{
%this.setShaderConst( "$brightPassThreshold", $HDRPostFX::brightPassThreshold );
%this.setShaderConst( "$g_fMiddleGray", $HDRPostFX::keyValue );
%bloomH = %this-->bloomH;
%bloomH.setShaderConst( "$gaussMultiplier", $HDRPostFX::gaussMultiplier );
%bloomH.setShaderConst( "$gaussMean", $HDRPostFX::gaussMean );
%bloomH.setShaderConst( "$gaussStdDev", $HDRPostFX::gaussStdDev );
%bloomV = %this-->bloomV;
%bloomV.setShaderConst( "$gaussMultiplier", $HDRPostFX::gaussMultiplier );
%bloomV.setShaderConst( "$gaussMean", $HDRPostFX::gaussMean );
%bloomV.setShaderConst( "$gaussStdDev", $HDRPostFX::gaussStdDev );
%minLuminace = $HDRPostFX::minLuminace;
if ( %minLuminace <= 0.0 )
{
// The min should never be pure zero else the
// log() in the shader will generate INFs.
%minLuminace = 0.00001;
}
%this-->adaptLum.setShaderConst( "$g_fMinLuminace", %minLuminace );
%this-->finalLum.setShaderConst( "$adaptRate", $HDRPostFX::adaptRate );
%combinePass = %this-->combinePass;
%combinePass.setShaderConst( "$g_fEnableToneMapping", $HDRPostFX::enableToneMapping );
%combinePass.setShaderConst( "$g_fMiddleGray", $HDRPostFX::keyValue );
%combinePass.setShaderConst( "$g_fBloomScale", $HDRPostFX::enableBloom );
%combinePass.setShaderConst( "$g_fEnableBlueShift", $HDRPostFX::enableBlueShift );
%combinePass.setShaderConst( "$g_fBlueShiftColor", $HDRPostFX::blueShiftColor );
%whiteCutoff = ( $HDRPostFX::whiteCutoff * $HDRPostFX::whiteCutoff ) *
( $HDRPostFX::whiteCutoff * $HDRPostFX::whiteCutoff );
%combinePass.setShaderConst( "$g_fWhiteCutoff", %whiteCutoff );
}
function HDRPostFX::onEnabled( %this )
{
// We don't allow hdr on OSX yet.
if ( $platform $= "macos" )
return false;
// See what HDR format would be best.
%format = getBestHDRFormat();
if ( %format $= "" || %format $= "GFXFormatR8G8B8A8" )
{
// We didn't get a valid HDR format... so fail.
return false;
}
// Set the right global shader define for HDR.
if ( %format $= "GFXFormatR10G10B10A2" )
addGlobalShaderMacro( "TORQUE_HDR_RGB10" );
else if ( %format $= "GFXFormatR16G16B16A16" )
addGlobalShaderMacro( "TORQUE_HDR_RGB16" );
echo( "HDR FORMAT: " @ %format );
// Change the format of the offscreen surface
// to an HDR compatible format.
AL_FormatToken.format = %format;
setReflectFormat( %format );
// Reset the light manager which will ensure the new
// hdr encoding takes effect in all the shaders and
// that the offscreen surface is enabled.
resetLightManager();
return true;
}
function HDRPostFX::onDisabled( %this )
{
// Restore the non-HDR offscreen surface format.
%format = "GFXFormatR8G8B8A8";
AL_FormatToken.format = %format;
setReflectFormat( %format );
removeGlobalShaderMacro( "TORQUE_HDR_RGB10" );
removeGlobalShaderMacro( "TORQUE_HDR_RGB16" );
// Reset the light manager which will ensure the new
// hdr encoding takes effect in all the shaders.
resetLightManager();
}
singleton PostEffect( HDRPostFX )
{
isEnabled = false;
allowReflectPass = false;
// Resolve the HDR before we render any editor stuff
// and before we resolve the scene to the backbuffer.
renderTime = "PFXBeforeBin";
renderBin = "EditorBin";
renderPriority = 9999;
// The bright pass generates a bloomed version of
// the scene for pixels which are brighter than a
// fixed threshold value.
//
// This is then used in the final HDR combine pass
// at the end of this post effect chain.
//
shader = HDR_BrightPassShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$backBuffer";
texture[1] = "#adaptedLum";
target = "$outTex";
targetFormat = "GFXFormatR16G16B16A16F";
targetScale = "0.5 0.5";
new PostEffect()
{
shader = HDR_DownScale4x4Shader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
target = "$outTex";
targetFormat = "GFXFormatR16G16B16A16F";
targetScale = "0.25 0.25";
};
new PostEffect()
{
internalName = "bloomH";
shader = HDR_BloomGaussBlurHShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
target = "$outTex";
targetFormat = "GFXFormatR16G16B16A16F";
};
new PostEffect()
{
internalName = "bloomV";
shader = HDR_BloomGaussBlurVShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
target = "#bloomFinal";
targetFormat = "GFXFormatR16G16B16A16F";
};
// BrightPass End
// Now calculate the adapted luminance.
new PostEffect()
{
internalName = "adaptLum";
shader = HDR_SampleLumShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$backBuffer";
target = "$outTex";
targetScale = "0.0625 0.0625"; // 1/16th
targetFormat = "GFXFormatR16F";
new PostEffect()
{
shader = HDR_DownSampleLumShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
target = "$outTex";
targetScale = "0.25 0.25"; // 1/4
targetFormat = "GFXFormatR16F";
};
new PostEffect()
{
shader = HDR_DownSampleLumShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
target = "$outTex";
targetScale = "0.25 0.25"; // 1/4
targetFormat = "GFXFormatR16F";
};
new PostEffect()
{
shader = HDR_DownSampleLumShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
target = "$outTex";
targetScale = "0.25 0.25"; // At this point the target should be 1x1.
targetFormat = "GFXFormatR16F";
};
// Note that we're reading the adapted luminance
// from the previous frame when generating this new
// one... PostEffect takes care to manage that.
new PostEffect()
{
internalName = "finalLum";
shader = HDR_CalcAdaptedLumShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
texture[1] = "#adaptedLum";
target = "#adaptedLum";
targetFormat = "GFXFormatR16F";
targetClear = "PFXTargetClear_OnCreate";
targetClearColor = "1 1 1 1";
};
};
// Output the combined bloom and toned mapped
// version of the scene.
new PostEffect()
{
internalName = "combinePass";
shader = HDR_CombineShader;
stateBlock = HDR_CombineStateBlock;
texture[0] = "$backBuffer";
texture[1] = "#adaptedLum";
texture[2] = "#bloomFinal";
target = "$backBuffer";
};
};
singleton ShaderData( LuminanceVisShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/postFx/hdr/luminanceVisP.hlsl";
pixVersion = 3.0;
};
singleton GFXStateBlockData( LuminanceVisStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
};
function LuminanceVisPostFX::setShaderConsts( %this )
{
%this.setShaderConst( "$brightPassThreshold", $HDRPostFX::brightPassThreshold );
}
singleton PostEffect( LuminanceVisPostFX )
{
isEnabled = false;
allowReflectPass = false;
// Render before we do any editor rendering.
renderTime = "PFXBeforeBin";
renderBin = "EditorBin";
renderPriority = 9999;
shader = LuminanceVisShader;
stateBlock = LuminanceVisStateBlock;
texture[0] = "$backBuffer";
target = "$backBuffer";
//targetScale = "0.0625 0.0625"; // 1/16th
//targetFormat = "GFXFormatR16F";
};
function LuminanceVisPostFX::onEnabled( %this )
{
if ( !HDRPostFX.isEnabled() )
{
HDRPostFX.enable();
}
HDRPostFX.skip = true;
return true;
}
function LuminanceVisPostFX::onDisabled( %this )
{
HDRPostFX.skip = false;
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Debugger.Interop;
using MICore;
using System.Diagnostics;
using System.Globalization;
// This file contains the various event objects that are sent to the debugger from the sample engine via IDebugEventCallback2::Event.
// These are used in EngineCallback.cs.
// The events are how the engine tells the debugger about what is happening in the debuggee process.
// There are three base classe the other events derive from: AD7AsynchronousEvent, AD7StoppingEvent, and AD7SynchronousEvent. These
// each implement the IDebugEvent2.GetAttributes method for the type of event they represent.
// Most events sent the debugger are asynchronous events.
namespace Microsoft.MIDebugEngine
{
#region Event base classes
internal class AD7AsynchronousEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return Constants.S_OK;
}
}
internal class AD7StoppingEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return Constants.S_OK;
}
}
internal class AD7SynchronousEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return Constants.S_OK;
}
}
internal class AD7SynchronousStoppingEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_STOPPING | (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return Constants.S_OK;
}
}
#endregion
// The debug engine (DE) sends this interface to the session debug manager (SDM) when an instance of the DE is created.
internal sealed class AD7EngineCreateEvent : AD7AsynchronousEvent, IDebugEngineCreateEvent2
{
public const string IID = "FE5B734C-759D-4E59-AB04-F103343BDD06";
private IDebugEngine2 _engine;
private AD7EngineCreateEvent(AD7Engine engine)
{
_engine = engine;
}
public static void Send(AD7Engine engine)
{
AD7EngineCreateEvent eventObject = new AD7EngineCreateEvent(engine);
engine.Callback.Send(eventObject, IID, null, null);
}
int IDebugEngineCreateEvent2.GetEngine(out IDebugEngine2 engine)
{
engine = _engine;
return Constants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to.
internal sealed class AD7ProgramCreateEvent : AD7SynchronousEvent, IDebugProgramCreateEvent2
{
public const string IID = "96CD11EE-ECD4-4E89-957E-B5D496FC4139";
internal static void Send(AD7Engine engine)
{
AD7ProgramCreateEvent eventObject = new AD7ProgramCreateEvent();
engine.Callback.Send(eventObject, IID, engine, null);
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a module is loaded or unloaded.
internal sealed class AD7ModuleLoadEvent : AD7AsynchronousEvent, IDebugModuleLoadEvent2
{
public const string IID = "989DB083-0D7C-40D1-A9D9-921BF611A4B2";
private readonly AD7Module _module;
private readonly bool _fLoad;
public AD7ModuleLoadEvent(AD7Module module, bool fLoad)
{
_module = module;
_fLoad = fLoad;
}
int IDebugModuleLoadEvent2.GetModule(out IDebugModule2 module, ref string debugMessage, ref int fIsLoad)
{
module = _module;
if (_fLoad)
{
string symbolLoadStatus = _module.DebuggedModule.SymbolsLoaded ?
ResourceStrings.ModuleLoadedWithSymbols :
ResourceStrings.ModuleLoadedWithoutSymbols;
debugMessage = string.Format(CultureInfo.CurrentUICulture, ResourceStrings.ModuleLoadMessage, _module.DebuggedModule.Name, symbolLoadStatus);
fIsLoad = 1;
}
else
{
debugMessage = string.Format(CultureInfo.CurrentUICulture, ResourceStrings.ModuleUnloadMessage, _module.DebuggedModule.Name);
fIsLoad = 0;
}
return Constants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program has run to completion
// or is otherwise destroyed.
internal sealed class AD7ProgramDestroyEvent : AD7SynchronousEvent, IDebugProgramDestroyEvent2
{
public const string IID = "E147E9E3-6440-4073-A7B7-A65592C714B5";
private readonly uint _exitCode;
public AD7ProgramDestroyEvent(uint exitCode)
{
_exitCode = exitCode;
}
#region IDebugProgramDestroyEvent2 Members
int IDebugProgramDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = _exitCode;
return Constants.S_OK;
}
#endregion
}
internal sealed class AD7MessageEvent : IDebugEvent2, IDebugMessageEvent2
{
public const string IID = "3BDB28CF-DBD2-4D24-AF03-01072B67EB9E";
private readonly OutputMessage _outputMessage;
private readonly bool _isAsync;
public AD7MessageEvent(OutputMessage outputMessage, bool isAsync)
{
_outputMessage = outputMessage;
_isAsync = isAsync;
}
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
if (_isAsync)
eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
else
eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_IMMEDIATE;
return Constants.S_OK;
}
int IDebugMessageEvent2.GetMessage(enum_MESSAGETYPE[] pMessageType, out string pbstrMessage, out uint pdwType, out string pbstrHelpFileName, out uint pdwHelpId)
{
return ConvertMessageToAD7(_outputMessage, pMessageType, out pbstrMessage, out pdwType, out pbstrHelpFileName, out pdwHelpId);
}
internal static int ConvertMessageToAD7(OutputMessage outputMessage, enum_MESSAGETYPE[] pMessageType, out string pbstrMessage, out uint pdwType, out string pbstrHelpFileName, out uint pdwHelpId)
{
const uint MB_ICONERROR = 0x00000010;
const uint MB_ICONWARNING = 0x00000030;
pMessageType[0] = outputMessage.MessageType;
pbstrMessage = outputMessage.Message;
pdwType = 0;
if ((outputMessage.MessageType & enum_MESSAGETYPE.MT_TYPE_MASK) == enum_MESSAGETYPE.MT_MESSAGEBOX)
{
switch (outputMessage.SeverityValue)
{
case OutputMessage.Severity.Error:
pdwType |= MB_ICONERROR;
break;
case OutputMessage.Severity.Warning:
pdwType |= MB_ICONWARNING;
break;
}
}
pbstrHelpFileName = null;
pdwHelpId = 0;
return Constants.S_OK;
}
int IDebugMessageEvent2.SetResponse(uint dwResponse)
{
return Constants.S_OK;
}
}
internal sealed class AD7ErrorEvent : IDebugEvent2, IDebugErrorEvent2
{
public const string IID = "FDB7A36C-8C53-41DA-A337-8BD86B14D5CB";
private readonly OutputMessage _outputMessage;
private readonly bool _isAsync;
public AD7ErrorEvent(OutputMessage outputMessage, bool isAsync)
{
_outputMessage = outputMessage;
_isAsync = isAsync;
}
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
if (_isAsync)
eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
else
eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_IMMEDIATE;
return Constants.S_OK;
}
int IDebugErrorEvent2.GetErrorMessage(enum_MESSAGETYPE[] pMessageType, out string errorFormat, out int hrErrorReason, out uint pdwType, out string helpFilename, out uint pdwHelpId)
{
hrErrorReason = unchecked((int)_outputMessage.ErrorCode);
return AD7MessageEvent.ConvertMessageToAD7(_outputMessage, pMessageType, out errorFormat, out pdwType, out helpFilename, out pdwHelpId);
}
}
internal sealed class AD7BreakpointErrorEvent : AD7AsynchronousEvent, IDebugBreakpointErrorEvent2
{
public const string IID = "ABB0CA42-F82B-4622-84E4-6903AE90F210";
private AD7ErrorBreakpoint _error;
public AD7BreakpointErrorEvent(AD7ErrorBreakpoint error)
{
_error = error;
}
public int GetErrorBreakpoint(out IDebugErrorBreakpoint2 ppErrorBP)
{
ppErrorBP = _error;
return Constants.S_OK;
}
}
internal sealed class AD7BreakpointUnboundEvent : AD7AsynchronousEvent, IDebugBreakpointUnboundEvent2
{
public const string IID = "78d1db4f-c557-4dc5-a2dd-5369d21b1c8c";
private readonly enum_BP_UNBOUND_REASON _reason;
private AD7BoundBreakpoint _bp;
public AD7BreakpointUnboundEvent(AD7BoundBreakpoint bp, enum_BP_UNBOUND_REASON reason)
{
_reason = reason;
_bp = bp;
}
public int GetBreakpoint(out IDebugBoundBreakpoint2 ppBP)
{
ppBP = _bp;
return Constants.S_OK;
}
public int GetReason(enum_BP_UNBOUND_REASON[] pdwUnboundReason)
{
pdwUnboundReason[0] = _reason;
return Constants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread is created in a program being debugged.
internal sealed class AD7ThreadCreateEvent : AD7AsynchronousEvent, IDebugThreadCreateEvent2
{
public const string IID = "2090CCFC-70C5-491D-A5E8-BAD2DD9EE3EA";
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread has exited.
internal sealed class AD7ThreadDestroyEvent : AD7AsynchronousEvent, IDebugThreadDestroyEvent2
{
public const string IID = "2C3B7532-A36F-4A6E-9072-49BE649B8541";
private readonly uint _exitCode;
public AD7ThreadDestroyEvent(uint exitCode)
{
_exitCode = exitCode;
}
#region IDebugThreadDestroyEvent2 Members
int IDebugThreadDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = _exitCode;
return Constants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but before any code is executed.
internal sealed class AD7LoadCompleteEvent : AD7StoppingEvent, IDebugLoadCompleteEvent2
{
public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B";
public AD7LoadCompleteEvent()
{
}
}
internal sealed class AD7EntryPointEvent : AD7StoppingEvent, IDebugEntryPointEvent2
{
public const string IID = "E8414A3E-1642-48EC-829E-5F4040E16DA9";
public AD7EntryPointEvent()
{
}
}
internal sealed class AD7ExpressionCompleteEvent : AD7AsynchronousEvent, IDebugExpressionEvaluationCompleteEvent2
{
private AD7Engine _engine;
public const string IID = "C0E13A85-238A-4800-8315-D947C960A843";
public AD7ExpressionCompleteEvent(AD7Engine engine, IVariableInformation var, IDebugProperty2 prop = null)
{
_engine = engine;
_var = var;
_prop = prop;
}
public int GetExpression(out IDebugExpression2 expr)
{
expr = new AD7Expression(_engine, _var);
return Constants.S_OK;
}
public int GetResult(out IDebugProperty2 prop)
{
prop = _prop != null ? _prop : new AD7Property(_engine, _var);
return Constants.S_OK;
}
private IVariableInformation _var;
private IDebugProperty2 _prop;
}
// This interface tells the session debug manager (SDM) that an exception has occurred in the debuggee.
internal sealed class AD7ExceptionEvent : AD7StoppingEvent, IDebugExceptionEvent2
{
public const string IID = "51A94113-8788-4A54-AE15-08B74FF922D0";
public AD7ExceptionEvent(string name, string description, uint code, Guid? exceptionCategory, ExceptionBreakpointState state)
{
_name = name;
_code = code;
_description = description ?? name;
_category = exceptionCategory ?? EngineConstants.EngineId;
switch (state)
{
case ExceptionBreakpointState.None:
_state = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE;
break;
case ExceptionBreakpointState.BreakThrown:
_state = enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE | enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_FIRST_CHANCE;
break;
case ExceptionBreakpointState.BreakUserHandled:
_state = enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT;
break;
default:
Debug.Fail("Unexpected state value");
_state = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE;
break;
}
}
#region IDebugExceptionEvent2 Members
public int CanPassToDebuggee()
{
// Cannot pass it on
return Constants.S_FALSE;
}
public int GetException(EXCEPTION_INFO[] pExceptionInfo)
{
EXCEPTION_INFO ex = new EXCEPTION_INFO();
ex.bstrExceptionName = _name;
ex.dwCode = _code;
ex.dwState = _state;
ex.guidType = _category;
pExceptionInfo[0] = ex;
return Constants.S_OK;
}
public int GetExceptionDescription(out string pbstrDescription)
{
pbstrDescription = _description;
return Constants.S_OK;
}
public int PassToDebuggee(int fPass)
{
return Constants.S_OK;
}
private string _name;
private uint _code;
private string _description;
private Guid _category;
private enum_EXCEPTION_STATE _state;
#endregion
}
// This interface tells the session debug manager (SDM) that a step has completed
internal sealed class AD7StepCompleteEvent : AD7StoppingEvent, IDebugStepCompleteEvent2
{
public const string IID = "0f7f24c1-74d9-4ea6-a3ea-7edb2d81441d";
}
// This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed.
internal sealed class AD7AsyncBreakCompleteEvent : AD7StoppingEvent, IDebugBreakEvent2
{
public const string IID = "c7405d1d-e24b-44e0-b707-d8a5a4e1641b";
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) to output a string for debug tracing.
internal sealed class AD7OutputDebugStringEvent : AD7AsynchronousEvent, IDebugOutputStringEvent2
{
public const string IID = "569c4bb1-7b82-46fc-ae28-4536ddad753e";
private string _str;
public AD7OutputDebugStringEvent(string str)
{
_str = str;
}
#region IDebugOutputStringEvent2 Members
int IDebugOutputStringEvent2.GetString(out string pbstrString)
{
pbstrString = _str;
return Constants.S_OK;
}
#endregion
}
// This interface is sent when a pending breakpoint has been bound in the debuggee.
internal sealed class AD7BreakpointBoundEvent : AD7AsynchronousEvent, IDebugBreakpointBoundEvent2
{
public const string IID = "1dddb704-cf99-4b8a-b746-dabb01dd13a0";
private AD7PendingBreakpoint _pendingBreakpoint;
private AD7BoundBreakpoint _boundBreakpoint;
public AD7BreakpointBoundEvent(AD7PendingBreakpoint pendingBreakpoint, AD7BoundBreakpoint boundBreakpoint)
{
_pendingBreakpoint = pendingBreakpoint;
_boundBreakpoint = boundBreakpoint;
}
#region IDebugBreakpointBoundEvent2 Members
int IDebugBreakpointBoundEvent2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[1];
boundBreakpoints[0] = _boundBreakpoint;
ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
return Constants.S_OK;
}
int IDebugBreakpointBoundEvent2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBP)
{
ppPendingBP = _pendingBreakpoint;
return Constants.S_OK;
}
#endregion
}
// This Event is sent when a breakpoint is hit in the debuggee
internal sealed class AD7BreakpointEvent : AD7StoppingEvent, IDebugBreakpointEvent2
{
public const string IID = "501C1E21-C557-48B8-BA30-A1EAB0BC4A74";
private IEnumDebugBoundBreakpoints2 _boundBreakpoints;
public AD7BreakpointEvent(IEnumDebugBoundBreakpoints2 boundBreakpoints)
{
_boundBreakpoints = boundBreakpoints;
}
#region IDebugBreakpointEvent2 Members
int IDebugBreakpointEvent2.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
ppEnum = _boundBreakpoints;
return Constants.S_OK;
}
#endregion
}
internal sealed class AD7StopCompleteEvent : AD7StoppingEvent, IDebugStopCompleteEvent2
{
public const string IID = "3DCA9DCD-FB09-4AF1-A926-45F293D48B2D";
}
internal sealed class AD7CustomDebugEvent : AD7AsynchronousEvent, IDebugCustomEvent110
{
public const string IID = "2615D9BC-1948-4D21-81EE-7A963F20CF59";
private readonly Guid _guidVSService;
private readonly Guid _sourceId;
private readonly int _messageCode;
private readonly object _parameter1;
private readonly object _parameter2;
public AD7CustomDebugEvent(Guid guidVSService, Guid sourceId, int messageCode, object parameter1, object parameter2)
{
_guidVSService = guidVSService;
_sourceId = sourceId;
_messageCode = messageCode;
_parameter1 = parameter1;
_parameter2 = parameter2;
}
int IDebugCustomEvent110.GetCustomEventInfo(out Guid guidVSService, VsComponentMessage[] message)
{
guidVSService = _guidVSService;
message[0].SourceId = _sourceId;
message[0].MessageCode = (uint)_messageCode;
message[0].Parameter1 = _parameter1;
message[0].Parameter2 = _parameter2;
return Constants.S_OK;
}
}
}
| |
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
//using System.Data.OracleClient;
using System.Reflection;
using System.Threading;
namespace MWS.Data
{
/// <summary>
/// Summary description for DBWrapper.
/// </summary>
public class DBWrapper : IDisposable
{
#region Constructors / finalizer methods
public enum PROVIDER_TYPE { PROVIDER_OLEDB, PROVIDER_SQLCLIENT, PROVIDER_ODBC, PROVIDER_ORACLE, PROVIDER_OTHER, PROVIDER_NONE }
// Do not allow constructing the object directly
protected DBWrapper()
{
m_oConnection = null;
m_oCommand = null;
m_oTransaction = null;
m_sConnectionString = null;
m_nCommandTimeout = 0;
m_nRetryConnect = 3;
m_bDisposed = false;
m_bConnected = false;
m_sProviderAssembly = null;
m_sProviderConnectionClass = null;
m_sProviderCommandBuilderClass = null;
m_eProvider = PROVIDER_TYPE.PROVIDER_NONE;
}
~DBWrapper()
{
this.Dispose(false);
}
#endregion
#region Private / protected members
protected System.Data.IDbConnection m_oConnection;
protected System.Data.IDbCommand m_oCommand;
protected System.Data.IDbTransaction m_oTransaction;
protected string m_sConnectionString;
protected int m_nCommandTimeout;
protected int m_nRetryConnect;
protected bool m_bDisposed;
protected bool m_bConnected;
protected string m_sProviderAssembly;
protected string m_sProviderConnectionClass;
protected string m_sProviderCommandBuilderClass;
protected PROVIDER_TYPE m_eProvider;
#endregion
#region Database connect / disconnect / transaction methods
public bool ValidateConnection()
{
if (m_bConnected)
return true;
else
{
ConnectionString = DBConstants.GetDatabaseUrl();
return Connect();
}
}
public bool Connect()
{
// Check for valid connection string
if(m_sConnectionString == null || m_sConnectionString.Length == 0)
throw( new Exception("Invalid database connection string"));
// Disconnect if already connected
Disconnect();
// Get ADONET connection object
m_oConnection = GetConnection();
m_oConnection.ConnectionString = this.ConnectionString;
// Implement connection retries
for(int i=0; i <= m_nRetryConnect; i++)
{
try
{
m_oConnection.Open();
if(m_oConnection.State == ConnectionState.Open)
{
m_bConnected = true;
break;
}
}
catch
{
if(i == m_nRetryConnect)
throw;
// Wait for 1 second and try again
Thread.Sleep(1000);
}
}
// Get command object
m_oCommand = m_oConnection.CreateCommand();
m_oCommand.CommandTimeout = m_nCommandTimeout;
return m_bConnected;
}
public void Disconnect()
{
// Disconnect can be called from Dispose and should guarantee no errors
if(!m_bConnected)
return;
if(m_oTransaction != null)
RollbackTransaction(false);
if(m_oCommand != null)
{
m_oCommand.Dispose();
m_oCommand = null;
}
if(m_oConnection != null)
{
try
{
m_oConnection.Close();
}
catch
{
}
m_oConnection.Dispose();
m_oConnection = null;
}
m_bConnected = false;
}
public void BeginTransaction()
{
ValidateConnection();
m_oTransaction = m_oConnection.BeginTransaction();
m_oCommand.Transaction = m_oTransaction;
return;
}
public void CommitTransaction()
{
if(m_oTransaction == null)
throw(new Exception("BeginTransaction must be called before commit or rollback. No open transactions found"));
m_oTransaction.Commit();
m_oTransaction.Dispose();
m_oTransaction = null;
}
public void RollbackTransaction()
{
RollbackTransaction(true);
}
public void RollbackTransaction(bool bThrowError)
{
if(m_oTransaction == null)
{
if(bThrowError)
throw(new Exception("BeginTransaction must be called before commit or rollback. No open transactions found"));
}
try
{
m_oTransaction.Rollback();
}
catch
{
if(bThrowError)
throw;
}
finally
{
if(m_oTransaction != null)
m_oTransaction.Dispose();
m_oTransaction = null;
}
}
public string GetDataSource()
{
ValidateConnection();
if (m_oConnection is DbConnection)
{
DbConnection dbc = m_oConnection as DbConnection;
return dbc.DataSource;
}
return null;
}
#endregion
#region Wraper methods for ADO.NET
public IDataReader ExecuteReader(string sSQL)
{
return this.ExecuteReader(sSQL, CommandType.Text);
}
public IDataReader ExecuteReader(string sSQL, CommandType oType)
{
ValidateConnection();
m_oCommand.CommandText = sSQL;
m_oCommand.CommandType = oType;
return m_oCommand.ExecuteReader();
}
public DataSet GetDataSet(string sSQL)
{
DataSet oData = new DataSet();
return GetDataSet(sSQL, CommandType.Text, oData);
}
public DataSet GetDataSet(string sSQL, CommandType oType)
{
DataSet oData = new DataSet();
return GetDataSet(sSQL, oType, oData);
}
public DataSet GetDataSet(string sSQL, CommandType oType, DataSet oData)
{
ValidateConnection();
m_oCommand.CommandType = oType;
m_oCommand.CommandText = sSQL;
IDataAdapter oAdpt = GetDataAdapter(sSQL);
oAdpt.Fill(oData);
return oData;
}
public object ExecuteScalar(string sSQL)
{
return ExecuteScalar(sSQL, CommandType.Text);
}
public object ExecuteScalar(string sSQL, CommandType oType)
{
ValidateConnection();
m_oCommand.CommandText = sSQL;
m_oCommand.CommandType = oType;
return m_oCommand.ExecuteScalar();
}
public object ExecuteNonQuery(string sSQL)
{
return ExecuteNonQuery(sSQL, CommandType.Text);
}
public object ExecuteNonQuery(string sSQL, CommandType oType)
{
ValidateConnection();
m_oCommand.CommandText = sSQL;
m_oCommand.CommandType = oType;
return m_oCommand.ExecuteNonQuery();
}
public IDataParameterCollection GetParameters()
{
ValidateConnection();
return m_oCommand.Parameters;
}
public void AddParameter(IDataParameter oParam)
{
ValidateConnection();
m_oCommand.Parameters.Add(oParam);
}
public void ClearParameters()
{
if(m_oCommand != null)
m_oCommand.Parameters.Clear();
}
#endregion
#region DBWrapper Create methods for various providers
public static DBWrapper GetOleDbWrapper()
{
DBWrapper oDB = new DBWrapper();
oDB.m_eProvider = PROVIDER_TYPE.PROVIDER_OLEDB;
return oDB;
}
public static DBWrapper GetSqlClientWrapper()
{
DBWrapper oDB = new DBWrapper();
oDB.m_eProvider = PROVIDER_TYPE.PROVIDER_SQLCLIENT;
return oDB;
}
public static DBWrapper GetOdbcWrapper()
{
DBWrapper oDB = new DBWrapper();
oDB.m_eProvider = PROVIDER_TYPE.PROVIDER_ODBC;
return oDB;
}
public static DBWrapper GetOracleWrapper()
{
DBWrapper oDB = new DBWrapper();
oDB.m_eProvider = PROVIDER_TYPE.PROVIDER_ORACLE;
return oDB;
}
public static DBWrapper GetADONETWrapper()
{
DBWrapper oDB = new DBWrapper();
oDB.ProviderAssemblyName = System.Configuration.ConfigurationManager.AppSettings["ADONET_ASSEMBLY"];
oDB.ProviderConnectionClassName = System.Configuration.ConfigurationManager.AppSettings["ADONET_CONNECTION_CLASS"];
oDB.ProviderCommandBuilderClassName = System.Configuration.ConfigurationManager.AppSettings["ADONET_COMMANDBUILDER_CLASS"];
oDB.m_eProvider = PROVIDER_TYPE.PROVIDER_OTHER;
return oDB;
}
public static DBWrapper GetADONETWrapper(string sProviderName)
{
DBWrapper oDB = null;
switch(sProviderName.Trim().ToUpper())
{
case "OLEDB":
oDB = DBWrapper.GetOleDbWrapper();
break;
case "SQLCLIENT":
oDB = DBWrapper.GetSqlClientWrapper();
break;
case "ODBC":
oDB = DBWrapper.GetOdbcWrapper();
break;
case "ORACLECLIENT":
oDB = DBWrapper.GetOracleWrapper();
break;
default:
oDB = DBWrapper.GetADONETWrapper();
break;
}
return oDB;
}
public static DBWrapper GetADONETWrapper(string sProviderAssembly, string sConnectionClass, string sCommandBuilderClass)
{
DBWrapper oDB = new DBWrapper();
oDB.ProviderAssemblyName = sProviderAssembly;
oDB.ProviderConnectionClassName = sConnectionClass;
oDB.ProviderCommandBuilderClassName = sCommandBuilderClass;
oDB.m_eProvider = PROVIDER_TYPE.PROVIDER_OTHER;
return oDB;
}
#endregion
#region Implementation of IDisposable
public void Dispose()
{
Dispose(true);
}
// Following is not IDisposable interface method. But added in this
// region/section as it is more related to Dispose
protected void Dispose(bool bDisposing)
{
if(!m_bDisposed)
{
// Dispose in thie block, only managed resources
if(bDisposing)
{
}
// Free only un-managed resources here
}
m_bDisposed = true;
}
#endregion
#region Properties (get / set methods)
public string ConnectionString
{
get
{
return m_sConnectionString;
}
set
{
m_sConnectionString = value;
}
}
public int CommandTimeout
{
get
{
return m_nCommandTimeout;
}
set
{
m_nCommandTimeout = value;
}
}
public int ConnectionRetryCount
{
get
{
return m_nRetryConnect;
}
set
{
m_nRetryConnect = value;
if(m_nRetryConnect <= 0)
m_nRetryConnect = 0;
}
}
public string ProviderAssemblyName
{
get
{
return m_sProviderAssembly;
}
set
{
m_sProviderAssembly = value;
}
}
public string ProviderConnectionClassName
{
get
{
return m_sProviderConnectionClass;
}
set
{
m_sProviderConnectionClass = value;
}
}
public string ProviderCommandBuilderClassName
{
get
{
return m_sProviderCommandBuilderClass;
}
set
{
m_sProviderCommandBuilderClass = value;
}
}
public PROVIDER_TYPE PROVIDER
{
get
{
return m_eProvider;
}
}
#endregion
#region Utility functions
protected IDbConnection GetConnection()
{
IDbConnection oReturn = null;
switch(this.PROVIDER)
{
case PROVIDER_TYPE.PROVIDER_SQLCLIENT:
oReturn = new SqlConnection();
break;
case PROVIDER_TYPE.PROVIDER_OLEDB:
oReturn = new OleDbConnection();
break;
case PROVIDER_TYPE.PROVIDER_ODBC:
oReturn = new OdbcConnection();
break;
/*case PROVIDER_TYPE.PROVIDER_ORACLE:
oReturn = new OracleConnection();
break;*/
case PROVIDER_TYPE.PROVIDER_OTHER:
oReturn = (IDbConnection) GetADONETProviderObject(ProviderAssemblyName, ProviderCommandBuilderClassName, null);
break;
default:
throw(new Exception("Invalid provider type"));
}
if(oReturn == null)
throw(new Exception("Failed to get ADONET Connection object [IDbConnection]"));
return oReturn;
}
protected IDataAdapter GetDataAdapter(string sSQL)
{
IDataAdapter oReturn = null;
switch(this.PROVIDER)
{
case PROVIDER_TYPE.PROVIDER_SQLCLIENT:
oReturn = new SqlDataAdapter(sSQL,(SqlConnection)m_oConnection);
((SqlDataAdapter)oReturn).SelectCommand = (SqlCommand)m_oCommand;
break;
case PROVIDER_TYPE.PROVIDER_OLEDB:
oReturn = new OleDbDataAdapter(sSQL,(OleDbConnection)m_oConnection);
((OleDbDataAdapter)oReturn).SelectCommand = (OleDbCommand)m_oCommand;
break;
case PROVIDER_TYPE.PROVIDER_ODBC:
oReturn = new OdbcDataAdapter(sSQL,(OdbcConnection)m_oConnection);
((OdbcDataAdapter)oReturn).SelectCommand = (OdbcCommand)m_oCommand;
break;
/*case PROVIDER_TYPE.PROVIDER_ORACLE:
oReturn = new OracleDataAdapter(sSQL,(OracleConnection)m_oConnection);
((OracleDataAdapter)oReturn).SelectCommand = (OracleCommand)m_oCommand;
break;*/
case PROVIDER_TYPE.PROVIDER_OTHER:
{
object[] oArgs = new Object[2];
oArgs[0] = sSQL;
oArgs[1] = m_oConnection;
oReturn = (IDbDataAdapter) GetADONETProviderObject(ProviderAssemblyName, ProviderCommandBuilderClassName, oArgs);
break;
}
default:
throw(new Exception("Invalid provider type"));
}
if(oReturn == null)
throw(new Exception("Failed to get ADONET Data Adapter object [IDataAdapter]"));
return oReturn;
}
public IDataParameterCollection DeriveParameters(string sStoredProcedure)
{
return DeriveParameters(sStoredProcedure, CommandType.StoredProcedure);
}
public IDataParameterCollection DeriveParameters(string sSql, CommandType oType)
{
ValidateConnection();
ClearParameters();
m_oCommand.CommandText = sSql;
m_oCommand.CommandType = oType;
switch(this.PROVIDER)
{
case PROVIDER_TYPE.PROVIDER_SQLCLIENT:
SqlCommandBuilder.DeriveParameters((SqlCommand)m_oCommand);
break;
case PROVIDER_TYPE.PROVIDER_OLEDB:
OleDbCommandBuilder.DeriveParameters((OleDbCommand)m_oCommand);
break;
case PROVIDER_TYPE.PROVIDER_ODBC:
OdbcCommandBuilder.DeriveParameters((OdbcCommand)m_oCommand);
break;
/*case PROVIDER_TYPE.PROVIDER_ORACLE:
OracleCommandBuilder.DeriveParameters((OracleCommand)m_oCommand);
break;*/
case PROVIDER_TYPE.PROVIDER_OTHER:
{
Type oCmdBuilderType = Type.GetType(ProviderCommandBuilderClassName);
MethodInfo oMth = oCmdBuilderType.GetMethod("DeriveParameters");
if(oMth == null)
throw(new Exception("DeriveParameters method is not suppored by the selected provider"));
object[] oParams = new Object[1];
oParams[0] = m_oCommand;
// DeriveParameters is static method
oMth.Invoke(null,oParams);
break;
}
default:
throw(new Exception("Invalid provider type"));
}
return m_oCommand.Parameters;
}
protected object GetADONETProviderObject(string sAssembly, string sClass, object[] oArgs)
{
if(sAssembly == null || sAssembly.Trim().Length == 0)
throw(new Exception("Invalid provider assembly name"));
if(sClass == null || sClass.Trim().Length == 0)
throw(new Exception("Invalid provider connection class name"));
//Assembly oSrc = Assembly.LoadWithPartialName(sAssembly);
Assembly oSrc = Assembly.Load(sAssembly);
if(oArgs == null)
{
return oSrc.CreateInstance(sClass,true);
}
else
{
Type oType = oSrc.GetType(sClass,true,true);
Type[] arTypes = new Type[oArgs.Length];
for(int i=0; i < oArgs.Length; i++)
{
arTypes[i] = oArgs[0].GetType();
}
ConstructorInfo oConstr = oType.GetConstructor(arTypes);
return oConstr.Invoke(oArgs);
}
}
#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;
/// <summary>
/// MakeArrayType(System.Int32)
/// </summary>
public class TypeMakeArrayType2
{
#region Private Members
private const int c_DEFAULT_MULTIPLE_ARRAY_DIMENSION = 4;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
int desiredDimension = 0;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call MakeArrayType to make 1 dimension value type array");
try
{
desiredDimension = 1;
Type type = typeof(Int32);
Type arrayType = type.MakeArrayType(desiredDimension);
do
{
if (!arrayType.IsArray)
{
TestLibrary.TestFramework.LogError("001", "Call MakeArrayType for value type does not make a array type");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString());
retVal = false;
break;
}
int actualDimension = arrayType.GetArrayRank();
if (actualDimension != desiredDimension)
{
TestLibrary.TestFramework.LogError("002", "Call MakeArrayType for value type does not make a one dimension array type");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString() + "; actualDimension = " + actualDimension.ToString());
retVal = false;
break;
}
} while (false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString());
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
int desiredDimension = 0;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call MakeArrayType to make multiple dimensions value type array");
try
{
desiredDimension = c_DEFAULT_MULTIPLE_ARRAY_DIMENSION;
Type type = typeof(Int32);
Type arrayType = type.MakeArrayType(desiredDimension);
do
{
if (!arrayType.IsArray)
{
TestLibrary.TestFramework.LogError("004", "Call MakeArrayType for value type does not make a array type");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString());
retVal = false;
break;
}
int actualDimension = arrayType.GetArrayRank();
if (actualDimension != desiredDimension)
{
TestLibrary.TestFramework.LogError("005", "Call MakeArrayType for value type does not make a one dimension array type");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString() + "; actualDimension = " + actualDimension.ToString());
retVal = false;
break;
}
} while (false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString());
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
int desiredDimension = 0;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call MakeArrayType to make multiple dimensions reference type array");
try
{
desiredDimension = c_DEFAULT_MULTIPLE_ARRAY_DIMENSION;
Type type = typeof(String);
Type arrayType = type.MakeArrayType(desiredDimension);
do
{
if (!arrayType.IsArray)
{
TestLibrary.TestFramework.LogError("007", "Call MakeArrayType for reference type does not make a array type");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString());
retVal = false;
break;
}
int actualDimension = arrayType.GetArrayRank();
if (actualDimension != desiredDimension)
{
TestLibrary.TestFramework.LogError("008", "Call MakeArrayType for reference type does not make a multiple dimensions array type");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString() + "; actualDimension = " + actualDimension.ToString());
retVal = false;
break;
}
} while (false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString());
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
int desiredDimension = 0;
TestLibrary.TestFramework.BeginScenario("PosTest4: Call MakeArrayType to make multiple dimensions pointer type array");
try
{
desiredDimension = c_DEFAULT_MULTIPLE_ARRAY_DIMENSION;
Type type = typeof(char *);
Type arrayType = type.MakeArrayType(desiredDimension);
do
{
if (!arrayType.IsArray)
{
TestLibrary.TestFramework.LogError("010", "Call MakeArrayType for pointer type does not make a array type");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString());
retVal = false;
break;
}
int actualDimension = arrayType.GetArrayRank();
if (actualDimension != desiredDimension)
{
TestLibrary.TestFramework.LogError("011", "Call MakeArrayType for pointer type does not make a multiple dimensions array type");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString() + "; actualDimension = " + actualDimension.ToString());
retVal = false;
break;
}
} while (false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString());
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
int desiredDimension = 0;
TestLibrary.TestFramework.BeginScenario("PosTest5: Call MakeArrayType to make multiple dimensions reference array type array");
try
{
desiredDimension = c_DEFAULT_MULTIPLE_ARRAY_DIMENSION;
Type type = typeof(String[]);
Type arrayType = type.MakeArrayType(desiredDimension);
do
{
if (!arrayType.IsArray)
{
TestLibrary.TestFramework.LogError("013", "Call MakeArrayType for reference array type does not make a array type");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString());
retVal = false;
break;
}
int actualDimension = arrayType.GetArrayRank();
if (actualDimension != desiredDimension)
{
TestLibrary.TestFramework.LogError("014", "Call MakeArrayType for reference array type does not make a multiple dimensions array type");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString() + "; actualDimension = " + actualDimension.ToString());
retVal = false;
break;
}
} while (false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("015", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString());
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
int desiredDimension = 0;
TestLibrary.TestFramework.BeginScenario("PosTest6: Call MakeArrayType to make multiple dimensions value array type array");
try
{
desiredDimension = c_DEFAULT_MULTIPLE_ARRAY_DIMENSION;
Type type = typeof(int[]);
Type arrayType = type.MakeArrayType(desiredDimension);
do
{
if (!arrayType.IsArray)
{
TestLibrary.TestFramework.LogError("016", "Call MakeArrayType for value array type does not make a array type");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString());
retVal = false;
break;
}
int actualDimension = arrayType.GetArrayRank();
if (actualDimension != desiredDimension)
{
TestLibrary.TestFramework.LogError("017", "Call MakeArrayType for value array type does not make a multiple dimensions array type");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString() + "; actualDimension = " + actualDimension.ToString());
retVal = false;
break;
}
} while (false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredDimension = " + desiredDimension.ToString());
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
int rank = 0;
TestLibrary.TestFramework.BeginScenario("NegTest1: IndexOutOfRangeException will be thrown when rank is invalid");
try
{
rank = TestLibrary.Generator.GetByte(-55);
if (rank > 0)
rank = 0 - rank;
Type type = typeof(Object);
Type arrayType = type.MakeArrayType(rank);
TestLibrary.TestFramework.LogError("101", "IndexOutOfRangeException is not thrown when rank is invalid");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] rank = " + rank.ToString());
retVal = false;
}
catch (IndexOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] rank = " + rank.ToString());
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: IndexOutOfRangeException will be thrown when rank is 0");
try
{
Type type = typeof(Object);
Type arrayType = type.MakeArrayType(0);
TestLibrary.TestFramework.LogError("103", "IndexOutOfRangeException is not thrown when rank is 0");
retVal = false;
}
catch (IndexOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
TypeMakeArrayType2 test = new TypeMakeArrayType2();
TestLibrary.TestFramework.BeginTestCase("TypeMakeArrayType2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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;
#if CLR_2_0 || CLR_4_0
using System.Collections.Generic;
#endif
using System.IO;
using System.Reflection;
using Microsoft.Win32;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Enumeration identifying a common language
/// runtime implementation.
/// </summary>
public enum RuntimeType
{
/// <summary>Any supported runtime framework</summary>
Any,
/// <summary>Microsoft .NET Framework</summary>
Net,
/// <summary>Microsoft .NET Compact Framework</summary>
NetCF,
/// <summary>Microsoft Shared Source CLI</summary>
SSCLI,
/// <summary>Mono</summary>
Mono,
/// <summary>Silverlight</summary>
Silverlight,
/// <summary>MonoTouch</summary>
MonoTouch
}
/// <summary>
/// RuntimeFramework represents a particular version
/// of a common language runtime implementation.
/// </summary>
[Serializable]
public sealed class RuntimeFramework
{
#region Static and Instance Fields
/// <summary>
/// DefaultVersion is an empty Version, used to indicate that
/// NUnit should select the CLR version to use for the test.
/// </summary>
public static readonly Version DefaultVersion = new Version(0,0);
private static RuntimeFramework currentFramework;
private RuntimeType runtime;
private Version frameworkVersion;
private Version clrVersion;
private string displayName;
#endregion
#region Constructor
/// <summary>
/// Construct from a runtime type and version. If the version has
/// two parts, it is taken as a framework version. If it has three
/// or more, it is taken as a CLR version. In either case, the other
/// version is deduced based on the runtime type and provided version.
/// </summary>
/// <param name="runtime">The runtime type of the framework</param>
/// <param name="version">The version of the framework</param>
public RuntimeFramework( RuntimeType runtime, Version version)
{
this.runtime = runtime;
this.frameworkVersion = runtime == RuntimeType.Mono && version.Major == 1
? new Version(1, 0)
: new Version(version.Major, version.Minor);
this.clrVersion = version;
if (version.Build < 0)
this.clrVersion = GetClrVersion(runtime, version);
this.displayName = GetDefaultDisplayName(runtime, version);
}
private static Version GetClrVersion(RuntimeType runtime, Version version)
{
switch (runtime)
{
case RuntimeType.Silverlight:
return version.Major >= 4
? new Version(4, 0, 60310)
: new Version(2, 0, 50727);
default:
switch (version.Major)
{
case 4:
return new Version(4, 0, 30319);
case 2:
case 3:
return new Version(2, 0, 50727);
case 1:
return version.Minor == 0 && runtime != RuntimeType.Mono
? new Version(1, 0, 3705)
: new Version(1, 1, 4322);
default:
return version;
}
}
}
#endregion
#region Properties
/// <summary>
/// Static method to return a RuntimeFramework object
/// for the framework that is currently in use.
/// </summary>
public static RuntimeFramework CurrentFramework
{
get
{
if (currentFramework == null)
{
#if SILVERLIGHT
currentFramework = new RuntimeFramework(
RuntimeType.Silverlight,
new Version(Environment.Version.Major, Environment.Version.Minor));
#else
Type monoRuntimeType = Type.GetType("Mono.Runtime", false);
Type monoTouchType = Type.GetType("MonoTouch.UIKit.UIApplicationDelegate, monotouch");
bool isMonoTouch = monoTouchType != null;
bool isMono = monoRuntimeType != null;
RuntimeType runtime = isMonoTouch
? RuntimeType.MonoTouch
: isMono
? RuntimeType.Mono
: Environment.OSVersion.Platform == PlatformID.WinCE
? RuntimeType.NetCF
: RuntimeType.Net;
int major = Environment.Version.Major;
int minor = Environment.Version.Minor;
if (isMono)
{
switch (major)
{
case 1:
minor = 0;
break;
case 2:
major = 3;
minor = 5;
break;
}
}
else /* It's windows */
if (major == 2)
{
#if !XAMMAC
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework");
if (key != null)
{
string installRoot = key.GetValue("InstallRoot") as string;
if (installRoot != null)
{
if (Directory.Exists(Path.Combine(installRoot, "v3.5")))
{
major = 3;
minor = 5;
}
else if (Directory.Exists(Path.Combine(installRoot, "v3.0")))
{
major = 3;
minor = 0;
}
}
}
#endif
}
currentFramework = new RuntimeFramework(runtime, new Version(major, minor));
currentFramework.clrVersion = Environment.Version;
if (isMono)
{
MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod(
"GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding);
if (getDisplayNameMethod != null)
currentFramework.displayName = (string)getDisplayNameMethod.Invoke(null, new object[0]);
}
#endif
}
return currentFramework;
}
}
/// <summary>
/// The type of this runtime framework
/// </summary>
public RuntimeType Runtime
{
get { return runtime; }
}
/// <summary>
/// The framework version for this runtime framework
/// </summary>
public Version FrameworkVersion
{
get { return frameworkVersion; }
}
/// <summary>
/// The CLR version for this runtime framework
/// </summary>
public Version ClrVersion
{
get { return clrVersion; }
}
/// <summary>
/// Return true if any CLR version may be used in
/// matching this RuntimeFramework object.
/// </summary>
public bool AllowAnyVersion
{
get { return this.clrVersion == DefaultVersion; }
}
/// <summary>
/// Returns the Display name for this framework
/// </summary>
public string DisplayName
{
get { return displayName; }
}
#if !NUNITLITE
private static RuntimeFramework[] availableFrameworks;
/// <summary>
/// Gets an array of all available frameworks
/// </summary>
// TODO: Special handling for netcf
public static RuntimeFramework[] AvailableFrameworks
{
get
{
if (availableFrameworks == null)
{
FrameworkList frameworks = new FrameworkList();
AppendDotNetFrameworks(frameworks);
AppendDefaultMonoFramework(frameworks);
// NYI
//AppendMonoFrameworks(frameworks);
availableFrameworks = frameworks.ToArray();
}
return availableFrameworks;
}
}
/// <summary>
/// Returns true if the current RuntimeFramework is available.
/// In the current implementation, only Mono and Microsoft .NET
/// are supported.
/// </summary>
/// <returns>True if it's available, false if not</returns>
public bool IsAvailable
{
get
{
foreach (RuntimeFramework framework in AvailableFrameworks)
if (this.Supports(framework))
return true;
return false;
}
}
#endif
#endregion
#region Public Methods
/// <summary>
/// Parses a string representing a RuntimeFramework.
/// The string may be just a RuntimeType name or just
/// a Version or a hyphentated RuntimeType-Version or
/// a Version prefixed by 'v'.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static RuntimeFramework Parse(string s)
{
RuntimeType runtime = RuntimeType.Any;
Version version = DefaultVersion;
string[] parts = s.Split(new char[] { '-' });
if (parts.Length == 2)
{
runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), parts[0], true);
string vstring = parts[1];
if (vstring != "")
version = new Version(vstring);
}
else if (char.ToLower(s[0]) == 'v')
{
version = new Version(s.Substring(1));
}
else if (IsRuntimeTypeName(s))
{
runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), s, true);
}
else
{
version = new Version(s);
}
return new RuntimeFramework(runtime, version);
}
#if !NUNITLITE
/// <summary>
/// Returns the best available framework that matches a target framework.
/// If the target framework has a build number specified, then an exact
/// match is needed. Otherwise, the matching framework with the highest
/// build number is used.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static RuntimeFramework GetBestAvailableFramework(RuntimeFramework target)
{
RuntimeFramework result = target;
if (target.ClrVersion.Build < 0)
{
foreach (RuntimeFramework framework in AvailableFrameworks)
if (framework.Supports(target) &&
framework.ClrVersion.Build > result.ClrVersion.Build)
{
result = framework;
}
}
return result;
}
#endif
/// <summary>
/// Overridden to return the short name of the framework
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (this.AllowAnyVersion)
{
return runtime.ToString().ToLower();
}
else
{
string vstring = frameworkVersion.ToString();
if (runtime == RuntimeType.Any)
return "v" + vstring;
else
return runtime.ToString().ToLower() + "-" + vstring;
}
}
/// <summary>
/// Returns true if the current framework matches the
/// one supplied as an argument. Two frameworks match
/// if their runtime types are the same or either one
/// is RuntimeType.Any and all specified version components
/// are equal. Negative (i.e. unspecified) version
/// components are ignored.
/// </summary>
/// <param name="target">The RuntimeFramework to be matched.</param>
/// <returns>True on match, otherwise false</returns>
public bool Supports(RuntimeFramework target)
{
if (this.Runtime != RuntimeType.Any
&& target.Runtime != RuntimeType.Any
&& this.Runtime != target.Runtime)
return false;
if (this.AllowAnyVersion || target.AllowAnyVersion)
return true;
if (!VersionsMatch(this.ClrVersion, target.ClrVersion))
return false;
return Runtime == RuntimeType.Silverlight
? this.frameworkVersion.Major == target.FrameworkVersion.Major && this.frameworkVersion.Minor == target.FrameworkVersion.Minor
: this.FrameworkVersion.Major >= target.FrameworkVersion.Major && this.FrameworkVersion.Minor >= target.FrameworkVersion.Minor;
}
#endregion
#region Helper Methods
private static bool IsRuntimeTypeName(string name)
{
foreach (string item in TypeHelper.GetEnumNames(typeof(RuntimeType)))
if (item.ToLower() == name.ToLower())
return true;
return false;
}
private static string GetDefaultDisplayName(RuntimeType runtime, Version version)
{
if (version == DefaultVersion)
return runtime.ToString();
else if (runtime == RuntimeType.Any)
return "v" + version.ToString();
else
return runtime.ToString() + " " + version.ToString();
}
private static bool VersionsMatch(Version v1, Version v2)
{
return v1.Major == v2.Major &&
v1.Minor == v2.Minor &&
(v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) &&
(v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision);
}
#if !NUNITLITE
private static void AppendMonoFrameworks(FrameworkList frameworks)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
AppendAllMonoFrameworks(frameworks);
else
AppendDefaultMonoFramework(frameworks);
}
private static void AppendAllMonoFrameworks(FrameworkList frameworks)
{
// TODO: Find multiple installed Mono versions under Linux
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
// Use registry to find alternate versions
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono");
if (key == null) return;
foreach (string version in key.GetSubKeyNames())
{
RegistryKey subKey = key.OpenSubKey(version);
string monoPrefix = subKey.GetValue("SdkInstallRoot") as string;
AppendMonoFramework(frameworks, monoPrefix, version);
}
}
else
AppendDefaultMonoFramework(frameworks);
}
// This method works for Windows and Linux but currently
// is only called under Linux.
private static void AppendDefaultMonoFramework(FrameworkList frameworks)
{
string monoPrefix = null;
string version = null;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono");
if (key != null)
{
version = key.GetValue("DefaultCLR") as string;
if (version != null && version != "")
{
key = key.OpenSubKey(version);
if (key != null)
monoPrefix = key.GetValue("SdkInstallRoot") as string;
}
}
}
else // Assuming we're currently running Mono - change if more runtimes are added
{
string libMonoDir = Path.GetDirectoryName(typeof(object).Assembly.Location);
monoPrefix = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(libMonoDir)));
}
AppendMonoFramework(frameworks, monoPrefix, version);
}
private static void AppendMonoFramework(FrameworkList frameworks, string monoPrefix, string version)
{
if (monoPrefix != null)
{
string displayFmt = version != null
? "Mono " + version + " - {0} Profile"
: "Mono {0} Profile";
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/1.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(1, 1, 4322));
framework.displayName = string.Format(displayFmt, "1.0");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/2.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727));
framework.displayName = string.Format(displayFmt, "2.0");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/4.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319));
framework.displayName = string.Format(displayFmt, "4.0");
frameworks.Add(framework);
}
}
}
private static void AppendDotNetFrameworks(FrameworkList frameworks)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\.NETFramework\policy");
if (key != null)
{
foreach (string name in key.GetSubKeyNames())
{
if (name.StartsWith("v"))
{
RegistryKey key2 = key.OpenSubKey(name);
foreach (string build in key2.GetValueNames())
frameworks.Add(new RuntimeFramework(RuntimeType.Net, new Version(name.Substring(1) + "." + build)));
}
}
}
}
}
#endif
#if CLR_2_0 || CLR_4_0
class FrameworkList : System.Collections.Generic.List<RuntimeFramework> { }
#else
class FrameworkList : System.Collections.ArrayList
{
public new RuntimeFramework[] ToArray()
{
return (RuntimeFramework[])base.ToArray(typeof(RuntimeFramework));
}
}
#endif
#endregion
}
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using Mono.Cecil.Metadata;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public sealed class TypeDefinition : TypeReference, IMemberDefinition, ISecurityDeclarationProvider {
uint attributes;
TypeReference base_type;
internal Range fields_range;
internal Range methods_range;
short packing_size = Mixin.NotResolvedMarker;
int class_size = Mixin.NotResolvedMarker;
Collection<TypeReference> interfaces;
Collection<TypeDefinition> nested_types;
Collection<MethodDefinition> methods;
Collection<FieldDefinition> fields;
Collection<EventDefinition> events;
Collection<PropertyDefinition> properties;
Collection<CustomAttribute> custom_attributes;
Collection<SecurityDeclaration> security_declarations;
public TypeAttributes Attributes {
get { return (TypeAttributes) attributes; }
set { attributes = (uint) value; }
}
public TypeReference BaseType {
get { return base_type; }
set { base_type = value; }
}
void ResolveLayout ()
{
if (packing_size != Mixin.NotResolvedMarker || class_size != Mixin.NotResolvedMarker)
return;
if (!HasImage) {
packing_size = Mixin.NoDataMarker;
class_size = Mixin.NoDataMarker;
return;
}
var row = Module.Read (this, (type, reader) => reader.ReadTypeLayout (type));
packing_size = row.Col1;
class_size = row.Col2;
}
public bool HasLayoutInfo {
get {
if (packing_size >= 0 || class_size >= 0)
return true;
ResolveLayout ();
return packing_size >= 0 || class_size >= 0;
}
}
public short PackingSize {
get {
if (packing_size >= 0)
return packing_size;
ResolveLayout ();
return packing_size >= 0 ? packing_size : (short) -1;
}
set { packing_size = value; }
}
public int ClassSize {
get {
if (class_size >= 0)
return class_size;
ResolveLayout ();
return class_size >= 0 ? class_size : -1;
}
set { class_size = value; }
}
public bool HasInterfaces {
get {
if (interfaces != null)
return interfaces.Count > 0;
return HasImage && Module.Read (this, (type, reader) => reader.HasInterfaces (type));
}
}
public Collection<TypeReference> Interfaces {
get {
if (interfaces != null)
return interfaces;
if (HasImage)
return Module.Read (ref interfaces, this, (type, reader) => reader.ReadInterfaces (type));
return interfaces = new Collection<TypeReference> ();
}
}
public bool HasNestedTypes {
get {
if (nested_types != null)
return nested_types.Count > 0;
return HasImage && Module.Read (this, (type, reader) => reader.HasNestedTypes (type));
}
}
public Collection<TypeDefinition> NestedTypes {
get {
if (nested_types != null)
return nested_types;
if (HasImage)
return Module.Read (ref nested_types, this, (type, reader) => reader.ReadNestedTypes (type));
return nested_types = new MemberDefinitionCollection<TypeDefinition> (this);
}
}
public bool HasMethods {
get {
if (methods != null)
return methods.Count > 0;
return HasImage && methods_range.Length > 0;
}
}
public Collection<MethodDefinition> Methods {
get {
if (methods != null)
return methods;
if (HasImage)
return Module.Read (ref methods, this, (type, reader) => reader.ReadMethods (type));
return methods = new MemberDefinitionCollection<MethodDefinition> (this);
}
}
public bool HasFields {
get {
if (fields != null)
return fields.Count > 0;
return HasImage && fields_range.Length > 0;
}
}
public Collection<FieldDefinition> Fields {
get {
if (fields != null)
return fields;
if (HasImage)
return Module.Read (ref fields, this, (type, reader) => reader.ReadFields (type));
return fields = new MemberDefinitionCollection<FieldDefinition> (this);
}
}
public bool HasEvents {
get {
if (events != null)
return events.Count > 0;
return HasImage && Module.Read (this, (type, reader) => reader.HasEvents (type));
}
}
public Collection<EventDefinition> Events {
get {
if (events != null)
return events;
if (HasImage)
return Module.Read (ref events, this, (type, reader) => reader.ReadEvents (type));
return events = new MemberDefinitionCollection<EventDefinition> (this);
}
}
public bool HasProperties {
get {
if (properties != null)
return properties.Count > 0;
return HasImage && Module.Read (this, (type, reader) => reader.HasProperties (type));
}
}
public Collection<PropertyDefinition> Properties {
get {
if (properties != null)
return properties;
if (HasImage)
return Module.Read (ref properties, this, (type, reader) => reader.ReadProperties (type));
return properties = new MemberDefinitionCollection<PropertyDefinition> (this);
}
}
public bool HasSecurityDeclarations {
get {
if (security_declarations != null)
return security_declarations.Count > 0;
return this.GetHasSecurityDeclarations (Module);
}
}
public Collection<SecurityDeclaration> SecurityDeclarations {
get { return security_declarations ?? (this.GetSecurityDeclarations (ref security_declarations, Module)); }
}
public bool HasCustomAttributes {
get {
if (custom_attributes != null)
return custom_attributes.Count > 0;
return this.GetHasCustomAttributes (Module);
}
}
public Collection<CustomAttribute> CustomAttributes {
get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); }
}
public override bool HasGenericParameters {
get {
if (generic_parameters != null)
return generic_parameters.Count > 0;
return this.GetHasGenericParameters (Module);
}
}
public override Collection<GenericParameter> GenericParameters {
get { return generic_parameters ?? (this.GetGenericParameters (ref generic_parameters, Module)); }
}
#region TypeAttributes
public bool IsNotPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); }
}
public bool IsPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); }
}
public bool IsNestedPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); }
}
public bool IsNestedPrivate {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); }
}
public bool IsNestedFamily {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); }
}
public bool IsNestedAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); }
}
public bool IsNestedFamilyAndAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); }
}
public bool IsNestedFamilyOrAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); }
}
public bool IsAutoLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); }
}
public bool IsSequentialLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); }
}
public bool IsExplicitLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); }
}
public bool IsClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); }
}
public bool IsInterface {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); }
}
public bool IsAbstract {
get { return attributes.GetAttributes ((uint) TypeAttributes.Abstract); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Abstract, value); }
}
public bool IsSealed {
get { return attributes.GetAttributes ((uint) TypeAttributes.Sealed); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Sealed, value); }
}
public bool IsSpecialName {
get { return attributes.GetAttributes ((uint) TypeAttributes.SpecialName); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.SpecialName, value); }
}
public bool IsImport {
get { return attributes.GetAttributes ((uint) TypeAttributes.Import); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Import, value); }
}
public bool IsSerializable {
get { return attributes.GetAttributes ((uint) TypeAttributes.Serializable); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Serializable, value); }
}
public bool IsWindowsRuntime {
get { return attributes.GetAttributes ((uint) TypeAttributes.WindowsRuntime); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.WindowsRuntime, value); }
}
public bool IsAnsiClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); }
}
public bool IsUnicodeClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); }
}
public bool IsAutoClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); }
}
public bool IsBeforeFieldInit {
get { return attributes.GetAttributes ((uint) TypeAttributes.BeforeFieldInit); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.BeforeFieldInit, value); }
}
public bool IsRuntimeSpecialName {
get { return attributes.GetAttributes ((uint) TypeAttributes.RTSpecialName); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.RTSpecialName, value); }
}
public bool HasSecurity {
get { return attributes.GetAttributes ((uint) TypeAttributes.HasSecurity); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.HasSecurity, value); }
}
#endregion
public bool IsEnum {
get { return base_type != null && base_type.IsTypeOf ("System", "Enum"); }
}
public override bool IsValueType {
get {
if (base_type == null)
return false;
return base_type.IsTypeOf ("System", "Enum") || (base_type.IsTypeOf ("System", "ValueType") && !this.IsTypeOf ("System", "Enum"));
}
}
public override bool IsPrimitive {
get {
ElementType primitive_etype;
return MetadataSystem.TryGetPrimitiveElementType (this, out primitive_etype);
}
}
public override MetadataType MetadataType {
get {
ElementType primitive_etype;
if (MetadataSystem.TryGetPrimitiveElementType (this, out primitive_etype))
return (MetadataType) primitive_etype;
return base.MetadataType;
}
}
public override bool IsDefinition {
get { return true; }
}
public new TypeDefinition DeclaringType {
get { return (TypeDefinition) base.DeclaringType; }
set { base.DeclaringType = value; }
}
public TypeDefinition (string @namespace, string name, TypeAttributes attributes)
: base (@namespace, name)
{
this.attributes = (uint) attributes;
this.token = new MetadataToken (TokenType.TypeDef);
}
public TypeDefinition (string @namespace, string name, TypeAttributes attributes, TypeReference baseType) :
this (@namespace, name, attributes)
{
this.BaseType = baseType;
}
public override TypeDefinition Resolve ()
{
return this;
}
}
static partial class Mixin {
public static TypeReference GetEnumUnderlyingType (this TypeDefinition self)
{
var fields = self.Fields;
for (int i = 0; i < fields.Count; i++) {
var field = fields [i];
if (!field.IsStatic)
return field.FieldType;
}
throw new ArgumentException ();
}
public static TypeDefinition GetNestedType (this TypeDefinition self, string fullname)
{
if (!self.HasNestedTypes)
return null;
var nested_types = self.NestedTypes;
for (int i = 0; i < nested_types.Count; i++) {
var nested_type = nested_types [i];
if (nested_type.TypeFullName () == fullname)
return nested_type;
}
return null;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Interactive
{
/// <summary>
/// Represents a process that hosts an interactive session.
/// </summary>
/// <remarks>
/// Handles spawning of the host process and communication between the local callers and the remote session.
/// </remarks>
internal sealed partial class InteractiveHost : MarshalByRefObject
{
private readonly Type _replServiceProviderType;
private readonly string _hostPath;
private readonly string _initialWorkingDirectory;
// adjustable for testing purposes
private readonly int _millisecondsTimeout;
private const int MaxAttemptsToCreateProcess = 2;
private LazyRemoteService _lazyRemoteService;
private int _remoteServiceInstanceId;
// Remoting channel to communicate with the remote service.
private IpcServerChannel _serverChannel;
private TextWriter _output;
private TextWriter _errorOutput;
internal event Action<bool> ProcessStarting;
public InteractiveHost(
Type replServiceProviderType,
string hostPath,
string workingDirectory,
int millisecondsTimeout = 5000)
{
_millisecondsTimeout = millisecondsTimeout;
_output = TextWriter.Null;
_errorOutput = TextWriter.Null;
_replServiceProviderType = replServiceProviderType;
_hostPath = hostPath;
_initialWorkingDirectory = workingDirectory;
var serverProvider = new BinaryServerFormatterSinkProvider { TypeFilterLevel = TypeFilterLevel.Full };
_serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), "ReplChannel-" + Guid.NewGuid(), serverProvider);
ChannelServices.RegisterChannel(_serverChannel, ensureSecurity: false);
}
#region Test hooks
internal event Action<char[], int> OutputReceived;
internal event Action<char[], int> ErrorOutputReceived;
internal Process TryGetProcess()
{
InitializedRemoteService initializedService;
return (_lazyRemoteService?.InitializedService != null &&
_lazyRemoteService.InitializedService.TryGetValue(out initializedService)) ? initializedService.ServiceOpt.Process : null;
}
internal Service TryGetService()
{
var initializedService = TryGetOrCreateRemoteServiceAsync().Result;
return initializedService.ServiceOpt?.Service;
}
// Triggered whenever we create a fresh process.
// The ProcessExited event is not hooked yet.
internal event Action<Process> InteractiveHostProcessCreated;
internal IpcServerChannel _ServerChannel
{
get { return _serverChannel; }
}
internal void Dispose(bool joinThreads)
{
Dispose(joinThreads, disposing: true);
}
#endregion
private static string GenerateUniqueChannelLocalName()
{
return typeof(InteractiveHost).FullName + Guid.NewGuid();
}
public override object InitializeLifetimeService()
{
return null;
}
private RemoteService TryStartProcess(CancellationToken cancellationToken)
{
Process newProcess = null;
int newProcessId = -1;
Semaphore semaphore = null;
try
{
int currentProcessId = Process.GetCurrentProcess().Id;
bool semaphoreCreated;
string semaphoreName;
while (true)
{
semaphoreName = "InteractiveHostSemaphore-" + Guid.NewGuid();
semaphore = new Semaphore(0, 1, semaphoreName, out semaphoreCreated);
if (semaphoreCreated)
{
break;
}
semaphore.Close();
cancellationToken.ThrowIfCancellationRequested();
}
var remoteServerPort = "InteractiveHostChannel-" + Guid.NewGuid();
var processInfo = new ProcessStartInfo(_hostPath);
processInfo.Arguments = remoteServerPort + " " + semaphoreName + " " + currentProcessId;
processInfo.WorkingDirectory = _initialWorkingDirectory;
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardError = true;
processInfo.StandardErrorEncoding = Encoding.UTF8;
processInfo.StandardOutputEncoding = Encoding.UTF8;
newProcess = new Process();
newProcess.StartInfo = processInfo;
// enables Process.Exited event to be raised:
newProcess.EnableRaisingEvents = true;
newProcess.Start();
// test hook:
var processCreated = InteractiveHostProcessCreated;
if (processCreated != null)
{
processCreated(newProcess);
}
cancellationToken.ThrowIfCancellationRequested();
try
{
newProcessId = newProcess.Id;
}
catch
{
newProcessId = 0;
}
// sync:
while (!semaphore.WaitOne(_millisecondsTimeout))
{
if (!CheckAlive(newProcess))
{
return null;
}
_output.WriteLine(FeaturesResources.AttemptToConnectToProcess, newProcessId);
cancellationToken.ThrowIfCancellationRequested();
}
// instantiate remote service:
Service newService;
try
{
newService = (Service)Activator.GetObject(
typeof(Service),
"ipc://" + remoteServerPort + "/" + Service.ServiceName);
cancellationToken.ThrowIfCancellationRequested();
newService.Initialize(_replServiceProviderType);
}
catch (RemotingException) when (!CheckAlive(newProcess))
{
return null;
}
return new RemoteService(this, newProcess, newProcessId, newService);
}
catch (OperationCanceledException)
{
if (newProcess != null)
{
RemoteService.InitiateTermination(newProcess, newProcessId);
}
return null;
}
finally
{
if (semaphore != null)
{
semaphore.Close();
}
}
}
private bool CheckAlive(Process process)
{
bool alive = process.IsAlive();
if (!alive)
{
_errorOutput.WriteLine(FeaturesResources.FailedToLaunchProcess, _hostPath, process.ExitCode);
_errorOutput.WriteLine(process.StandardError.ReadToEnd());
}
return alive;
}
~InteractiveHost()
{
Dispose(joinThreads: false, disposing: false);
}
public void Dispose()
{
Dispose(joinThreads: false, disposing: true);
}
private void Dispose(bool joinThreads, bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
DisposeChannel();
}
if (_lazyRemoteService != null)
{
_lazyRemoteService.Dispose(joinThreads);
_lazyRemoteService = null;
}
}
private void DisposeChannel()
{
if (_serverChannel != null)
{
ChannelServices.UnregisterChannel(_serverChannel);
_serverChannel = null;
}
}
public TextWriter Output
{
get
{
return _output;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
var oldOutput = Interlocked.Exchange(ref _output, value);
oldOutput.Flush();
}
}
public TextWriter ErrorOutput
{
get
{
return _errorOutput;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
var oldOutput = Interlocked.Exchange(ref _errorOutput, value);
oldOutput.Flush();
}
}
internal void OnOutputReceived(bool error, char[] buffer, int count)
{
var notification = error ? ErrorOutputReceived : OutputReceived;
if (notification != null)
{
notification(buffer, count);
}
var writer = error ? ErrorOutput : Output;
writer.Write(buffer, 0, count);
}
private LazyRemoteService CreateRemoteService(InteractiveHostOptions options, bool skipInitialization)
{
return new LazyRemoteService(this, options, Interlocked.Increment(ref _remoteServiceInstanceId), skipInitialization);
}
private Task OnProcessExited(Process process)
{
ReportProcessExited(process);
return TryGetOrCreateRemoteServiceAsync();
}
private void ReportProcessExited(Process process)
{
int? exitCode;
try
{
exitCode = process.HasExited ? process.ExitCode : (int?)null;
}
catch
{
exitCode = null;
}
if (exitCode.HasValue)
{
_errorOutput.WriteLine(FeaturesResources.HostingProcessExitedWithExitCode, exitCode.Value);
}
}
private async Task<InitializedRemoteService> TryGetOrCreateRemoteServiceAsync()
{
try
{
LazyRemoteService currentRemoteService = _lazyRemoteService;
// disposed or not reset:
Debug.Assert(currentRemoteService != null);
for (int attempt = 0; attempt < MaxAttemptsToCreateProcess; attempt++)
{
var initializedService = await currentRemoteService.InitializedService.GetValueAsync(currentRemoteService.CancellationSource.Token).ConfigureAwait(false);
if (initializedService.ServiceOpt != null && initializedService.ServiceOpt.Process.IsAlive())
{
return initializedService;
}
// Service failed to start or initialize or the process died.
var newService = CreateRemoteService(currentRemoteService.Options, skipInitialization: !initializedService.InitializationResult.Success);
var previousService = Interlocked.CompareExchange(ref _lazyRemoteService, newService, currentRemoteService);
if (previousService == currentRemoteService)
{
// we replaced the service whose process we know is dead:
currentRemoteService.Dispose(joinThreads: false);
currentRemoteService = newService;
}
else
{
// the process was reset in between our checks, try to use the new service:
newService.Dispose(joinThreads: false);
currentRemoteService = previousService;
}
}
_errorOutput.WriteLine(FeaturesResources.UnableToCreateHostingProcess);
}
catch (OperationCanceledException)
{
// The user reset the process during initialization.
// The reset operation will recreate the process.
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
return default(InitializedRemoteService);
}
private async Task<TResult> Async<TResult>(Action<Service, RemoteAsyncOperation<TResult>> action)
{
try
{
var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false);
if (initializedService.ServiceOpt == null)
{
return default(TResult);
}
return await new RemoteAsyncOperation<TResult>(initializedService.ServiceOpt).AsyncExecute(action).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private static async Task<TResult> Async<TResult>(RemoteService remoteService, Action<Service, RemoteAsyncOperation<TResult>> action)
{
try
{
return await new RemoteAsyncOperation<TResult>(remoteService).AsyncExecute(action).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
#region Operations
/// <summary>
/// Restarts and reinitializes the host process (or starts a new one if it is not running yet).
/// </summary>
/// <param name="optionsOpt">The options to initialize the new process with, or null to use the current options (or default options if the process isn't running yet).</param>
public async Task<RemoteExecutionResult> ResetAsync(InteractiveHostOptions optionsOpt)
{
try
{
// replace the existing service with a new one:
var newService = CreateRemoteService(optionsOpt ?? _lazyRemoteService?.Options ?? InteractiveHostOptions.Default, skipInitialization: false);
LazyRemoteService oldService = Interlocked.Exchange(ref _lazyRemoteService, newService);
if (oldService != null)
{
oldService.Dispose(joinThreads: false);
}
var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false);
if (initializedService.ServiceOpt == null)
{
return default(RemoteExecutionResult);
}
return initializedService.InitializationResult;
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Asynchronously executes given code in the remote interactive session.
/// </summary>
/// <param name="code">The code to execute.</param>
/// <remarks>
/// This method is thread safe but operations are sent to the remote process
/// asynchronously so tasks should be executed serially if order is important.
/// </remarks>
public Task<RemoteExecutionResult> ExecuteAsync(string code)
{
Debug.Assert(code != null);
return Async<RemoteExecutionResult>((service, operation) => service.ExecuteAsync(operation, code));
}
/// <summary>
/// Asynchronously executes given code in the remote interactive session.
/// </summary>
/// <param name="path">The file to execute.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <remarks>
/// This method is thread safe but operations are sent to the remote process
/// asynchronously so tasks should be executed serially if order is important.
/// </remarks>
public Task<RemoteExecutionResult> ExecuteFileAsync(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
return Async<RemoteExecutionResult>((service, operation) => service.ExecuteFileAsync(operation, path));
}
/// <summary>
/// Asynchronously adds a reference to the set of available references for next submission.
/// </summary>
/// <param name="reference">The reference to add.</param>
/// <remarks>
/// This method is thread safe but operations are sent to the remote process
/// asynchronously so tasks should be executed serially if order is important.
/// </remarks>
public Task<bool> AddReferenceAsync(string reference)
{
Debug.Assert(reference != null);
return Async<bool>((service, operation) => service.AddReferenceAsync(operation, reference));
}
/// <summary>
/// Sets the current session's search paths and base directory.
/// </summary>
public Task<RemoteExecutionResult> SetPathsAsync(string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory)
{
Debug.Assert(referenceSearchPaths != null);
Debug.Assert(sourceSearchPaths != null);
Debug.Assert(baseDirectory != null);
return Async<RemoteExecutionResult>((service, operation) => service.SetPathsAsync(operation, referenceSearchPaths, sourceSearchPaths, baseDirectory));
}
#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.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Diagnostics.CodeAnalysis;
namespace System.Data.Common
{
public class DbConnectionStringBuilder : IDictionary, ICustomTypeDescriptor
{
// keyword->value currently listed in the connection string
private Dictionary<string, object> _currentValues;
// cached connectionstring to avoid constant rebuilding
// and to return a user's connectionstring as is until editing occurs
private string _connectionString = string.Empty;
private PropertyDescriptorCollection _propertyDescriptors;
private bool _browsableConnectionString = true;
private readonly bool _useOdbcRules;
private static int s_objectTypeCount; // Bid counter
internal readonly int _objectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount);
public DbConnectionStringBuilder()
{
}
public DbConnectionStringBuilder(bool useOdbcRules)
{
_useOdbcRules = useOdbcRules;
}
private ICollection Collection
{
get { return CurrentValues; }
}
private IDictionary Dictionary
{
get { return CurrentValues; }
}
private Dictionary<string, object> CurrentValues
{
get
{
Dictionary<string, object> values = _currentValues;
if (null == values)
{
values = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
_currentValues = values;
}
return values;
}
}
object IDictionary.this[object keyword]
{
// delegate to this[string keyword]
get { return this[ObjectToString(keyword)]; }
set { this[ObjectToString(keyword)] = value; }
}
[Browsable(false)]
public virtual object this[string keyword]
{
get
{
DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.get_Item|API> {0}, keyword='{1}'", ObjectID, keyword);
ADP.CheckArgumentNull(keyword, nameof(keyword));
object value;
if (CurrentValues.TryGetValue(keyword, out value))
{
return value;
}
throw ADP.KeywordNotSupported(keyword);
}
set
{
ADP.CheckArgumentNull(keyword, nameof(keyword));
bool flag = false;
if (null != value)
{
string keyvalue = DbConnectionStringBuilderUtil.ConvertToString(value);
DbConnectionOptions.ValidateKeyValuePair(keyword, keyvalue);
flag = CurrentValues.ContainsKey(keyword);
// store keyword/value pair
CurrentValues[keyword] = keyvalue;
}
else
{
flag = Remove(keyword);
}
_connectionString = null;
if (flag)
{
_propertyDescriptors = null;
}
}
}
[Browsable(false)]
[DesignOnly(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[EditorBrowsable(EditorBrowsableState.Never)]
public bool BrowsableConnectionString
{
get
{
return _browsableConnectionString;
}
set
{
_browsableConnectionString = value;
_propertyDescriptors = null;
}
}
[RefreshPropertiesAttribute(RefreshProperties.All)]
public string ConnectionString
{
get
{
DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.get_ConnectionString|API> {0}", ObjectID);
string connectionString = _connectionString;
if (null == connectionString)
{
StringBuilder builder = new StringBuilder();
foreach (string keyword in Keys)
{
object value;
if (ShouldSerialize(keyword) && TryGetValue(keyword, out value))
{
string keyvalue = ConvertValueToString(value);
AppendKeyValuePair(builder, keyword, keyvalue, _useOdbcRules);
}
}
connectionString = builder.ToString();
_connectionString = connectionString;
}
return connectionString;
}
set
{
DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.set_ConnectionString|API> {0}", ObjectID);
DbConnectionOptions constr = new DbConnectionOptions(value, null, _useOdbcRules);
string originalValue = ConnectionString;
Clear();
try
{
for (NameValuePair pair = constr._keyChain; null != pair; pair = pair.Next)
{
if (null != pair.Value)
{
this[pair.Name] = pair.Value;
}
else
{
Remove(pair.Name);
}
}
_connectionString = null;
}
catch (ArgumentException)
{ // restore original string
ConnectionString = originalValue;
_connectionString = originalValue;
throw;
}
}
}
[Browsable(false)]
public virtual int Count
{
get { return CurrentValues.Count; }
}
[Browsable(false)]
public bool IsReadOnly
{
get { return false; }
}
[Browsable(false)]
public virtual bool IsFixedSize
{
get { return false; }
}
bool ICollection.IsSynchronized
{
get { return Collection.IsSynchronized; }
}
[Browsable(false)]
public virtual ICollection Keys
{
get
{
DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.Keys|API> {0}", ObjectID);
return Dictionary.Keys;
}
}
internal int ObjectID
{
get
{
return _objectID;
}
}
object ICollection.SyncRoot
{
get { return Collection.SyncRoot; }
}
[Browsable(false)]
public virtual ICollection Values
{
get
{
DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.Values|API> {0}", ObjectID);
ICollection<string> keys = (ICollection<string>)Keys;
IEnumerator<string> keylist = keys.GetEnumerator();
object[] values = new object[keys.Count];
for (int i = 0; i < values.Length; ++i)
{
keylist.MoveNext();
values[i] = this[keylist.Current];
Debug.Assert(null != values[i], "null value " + keylist.Current);
}
return new ReadOnlyCollection<object>(values);
}
}
internal virtual string ConvertValueToString(object value)
{
return (value == null) ? null : Convert.ToString(value, CultureInfo.InvariantCulture);
}
void IDictionary.Add(object keyword, object value)
{
Add(ObjectToString(keyword), value);
}
public void Add(string keyword, object value)
{
this[keyword] = value;
}
public static void AppendKeyValuePair(StringBuilder builder, string keyword, string value)
{
DbConnectionOptions.AppendKeyValuePairBuilder(builder, keyword, value, false);
}
public static void AppendKeyValuePair(StringBuilder builder, string keyword, string value, bool useOdbcRules)
{
DbConnectionOptions.AppendKeyValuePairBuilder(builder, keyword, value, useOdbcRules);
}
public virtual void Clear()
{
DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.Clear|API>");
_connectionString = string.Empty;
_propertyDescriptors = null;
CurrentValues.Clear();
}
protected internal void ClearPropertyDescriptors()
{
_propertyDescriptors = null;
}
// does the keyword exist as a strongly typed keyword or as a stored value
bool IDictionary.Contains(object keyword)
{
return ContainsKey(ObjectToString(keyword));
}
public virtual bool ContainsKey(string keyword)
{
ADP.CheckArgumentNull(keyword, nameof(keyword));
return CurrentValues.ContainsKey(keyword);
}
void ICollection.CopyTo(Array array, int index)
{
DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.ICollection.CopyTo|API> {0}", ObjectID);
Collection.CopyTo(array, index);
}
public virtual bool EquivalentTo(DbConnectionStringBuilder connectionStringBuilder)
{
ADP.CheckArgumentNull(connectionStringBuilder, nameof(connectionStringBuilder));
DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.EquivalentTo|API> {0}, connectionStringBuilder={1}", ObjectID, connectionStringBuilder.ObjectID);
if ((GetType() != connectionStringBuilder.GetType()) || (CurrentValues.Count != connectionStringBuilder.CurrentValues.Count))
{
return false;
}
object value;
foreach (KeyValuePair<string, object> entry in CurrentValues)
{
if (!connectionStringBuilder.CurrentValues.TryGetValue(entry.Key, out value) || !entry.Value.Equals(value))
{
return false;
}
}
return true;
}
IEnumerator IEnumerable.GetEnumerator()
{
DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.IEnumerable.GetEnumerator|API> {0}", ObjectID);
return Collection.GetEnumerator();
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.IDictionary.GetEnumerator|API> {0}", ObjectID);
return Dictionary.GetEnumerator();
}
private string ObjectToString(object keyword)
{
try
{
return (string)keyword;
}
catch (InvalidCastException)
{
// BUGBUG: the message is not localized.
throw new ArgumentException("not a string", nameof(keyword));
}
}
void IDictionary.Remove(object keyword)
{
Remove(ObjectToString(keyword));
}
public virtual bool Remove(string keyword)
{
DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.Remove|API> {0}, keyword='{1}'", ObjectID, keyword);
ADP.CheckArgumentNull(keyword, nameof(keyword));
if (CurrentValues.Remove(keyword))
{
_connectionString = null;
_propertyDescriptors = null;
return true;
}
return false;
}
// does the keyword exist as a stored value or something that should always be persisted
public virtual bool ShouldSerialize(string keyword)
{
ADP.CheckArgumentNull(keyword, nameof(keyword));
return CurrentValues.ContainsKey(keyword);
}
public override string ToString()
{
return ConnectionString;
}
public virtual bool TryGetValue(string keyword, out object value)
{
ADP.CheckArgumentNull(keyword, nameof(keyword));
return CurrentValues.TryGetValue(keyword, out value);
}
internal Attribute[] GetAttributesFromCollection(AttributeCollection collection)
{
Attribute[] attributes = new Attribute[collection.Count];
collection.CopyTo(attributes, 0);
return attributes;
}
private PropertyDescriptorCollection GetProperties()
{
PropertyDescriptorCollection propertyDescriptors = _propertyDescriptors;
if (null == propertyDescriptors)
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<comm.DbConnectionStringBuilder.GetProperties|INFO> {0}", ObjectID);
try
{
Hashtable descriptors = new Hashtable(StringComparer.OrdinalIgnoreCase);
GetProperties(descriptors);
PropertyDescriptor[] properties = new PropertyDescriptor[descriptors.Count];
descriptors.Values.CopyTo(properties, 0);
propertyDescriptors = new PropertyDescriptorCollection(properties);
_propertyDescriptors = propertyDescriptors;
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
return propertyDescriptors;
}
protected virtual void GetProperties(Hashtable propertyDescriptors)
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<comm.DbConnectionStringBuilder.GetProperties|API> {0}", ObjectID);
try
{
// show all strongly typed properties (not already added)
// except ConnectionString iff BrowsableConnectionString
Attribute[] attributes;
foreach (PropertyDescriptor reflected in TypeDescriptor.GetProperties(this, true))
{
if (ADP.ConnectionString != reflected.Name)
{
string displayName = reflected.DisplayName;
if (!propertyDescriptors.ContainsKey(displayName))
{
attributes = GetAttributesFromCollection(reflected.Attributes);
PropertyDescriptor descriptor = new DbConnectionStringBuilderDescriptor(reflected.Name,
reflected.ComponentType, reflected.PropertyType, reflected.IsReadOnly, attributes);
propertyDescriptors[displayName] = descriptor;
}
// else added by derived class first
}
else if (BrowsableConnectionString)
{
propertyDescriptors[ADP.ConnectionString] = reflected;
}
else
{
propertyDescriptors.Remove(ADP.ConnectionString);
}
}
// all keywords in Keys list that do not have strongly typed property, ODBC case
if (!IsFixedSize)
{
attributes = null;
foreach (string keyword in Keys)
{
if (!propertyDescriptors.ContainsKey(keyword))
{
object value = this[keyword];
Type vtype;
if (null != value)
{
vtype = value.GetType();
if (typeof(string) == vtype)
{
int tmp1;
if (int.TryParse((string)value, out tmp1))
{
vtype = typeof(int);
}
else
{
bool tmp2;
if (bool.TryParse((string)value, out tmp2))
{
vtype = typeof(bool);
}
}
}
}
else
{
vtype = typeof(string);
}
Attribute[] useAttributes = attributes;
if (StringComparer.OrdinalIgnoreCase.Equals(DbConnectionStringKeywords.Password, keyword) ||
StringComparer.OrdinalIgnoreCase.Equals(DbConnectionStringSynonyms.Pwd, keyword))
{
useAttributes = new Attribute[] {
BrowsableAttribute.Yes,
PasswordPropertyTextAttribute.Yes,
RefreshPropertiesAttribute.All,
};
}
else if (null == attributes)
{
attributes = new Attribute[] {
BrowsableAttribute.Yes,
RefreshPropertiesAttribute.All,
};
useAttributes = attributes;
}
PropertyDescriptor descriptor = new DbConnectionStringBuilderDescriptor(keyword,
GetType(), vtype, false, useAttributes);
propertyDescriptors[keyword] = descriptor;
}
}
}
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
private PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
PropertyDescriptorCollection propertyDescriptors = GetProperties();
if ((null == attributes) || (0 == attributes.Length))
{
// Basic case has no filtering
return propertyDescriptors;
}
// Create an array that is guaranteed to hold all attributes
PropertyDescriptor[] propertiesArray = new PropertyDescriptor[propertyDescriptors.Count];
// Create an index to reference into this array
int index = 0;
// Iterate over each property
foreach (PropertyDescriptor property in propertyDescriptors)
{
// Identify if this property's attributes match the specification
bool match = true;
foreach (Attribute attribute in attributes)
{
Attribute attr = property.Attributes[attribute.GetType()];
if ((attr == null && !attribute.IsDefaultAttribute()) || !attr.Match(attribute))
{
match = false;
break;
}
}
// If this property matches, add it to the array
if (match)
{
propertiesArray[index] = property;
index++;
}
}
// Create a new array that only contains the filtered properties
PropertyDescriptor[] filteredPropertiesArray = new PropertyDescriptor[index];
Array.Copy(propertiesArray, 0, filteredPropertiesArray, 0, index);
return new PropertyDescriptorCollection(filteredPropertiesArray);
}
string ICustomTypeDescriptor.GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
string ICustomTypeDescriptor.GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(this, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return GetProperties();
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
return GetProperties(attributes);
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using ClientDependency.Core.Config;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Web.Features;
using Umbraco.Web.HealthCheck;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Mvc;
using Umbraco.Web.PropertyEditors;
using Umbraco.Web.Trees;
using Umbraco.Web.WebServices;
using Constants = Umbraco.Core.Constants;
namespace Umbraco.Web.Editors
{
/// <summary>
/// Used to collect the server variables for use in the back office angular app
/// </summary>
internal class BackOfficeServerVariables
{
private readonly UrlHelper _urlHelper;
private readonly ApplicationContext _applicationContext;
private readonly HttpContextBase _httpContext;
private readonly IOwinContext _owinContext;
public BackOfficeServerVariables(UrlHelper urlHelper, ApplicationContext applicationContext, IUmbracoSettingsSection umbracoSettings)
{
_urlHelper = urlHelper;
_applicationContext = applicationContext;
_httpContext = _urlHelper.RequestContext.HttpContext;
_owinContext = _httpContext.GetOwinContext();
}
/// <summary>
/// Returns the server variables for non-authenticated users
/// </summary>
/// <returns></returns>
internal Dictionary<string, object> BareMinimumServerVariables()
{
//this is the filter for the keys that we'll keep based on the full version of the server vars
var keepOnlyKeys = new Dictionary<string, string[]>
{
{"umbracoUrls", new[] {"authenticationApiBaseUrl", "serverVarsJs", "externalLoginsUrl", "currentUserApiBaseUrl"}},
{"umbracoSettings", new[] {"allowPasswordReset", "imageFileTypes", "maxFileSize", "loginBackgroundImage", "canSendRequiredEmail"}},
{"application", new[] {"applicationPath", "cacheBuster"}},
{"isDebuggingEnabled", new string[] { }},
{"features", new [] {"disabledFeatures"}}
};
//now do the filtering...
var defaults = GetServerVariables();
foreach (var key in defaults.Keys.ToArray())
{
if (keepOnlyKeys.ContainsKey(key) == false)
{
defaults.Remove(key);
}
else
{
var asDictionary = defaults[key] as IDictionary;
if (asDictionary != null)
{
var toKeep = keepOnlyKeys[key];
foreach (var k in asDictionary.Keys.Cast<string>().ToArray())
{
if (toKeep.Contains(k) == false)
{
asDictionary.Remove(k);
}
}
}
}
}
//TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
// so based on compat and how things are currently working we need to replace the serverVarsJs one
((Dictionary<string, object>)defaults["umbracoUrls"])["serverVarsJs"] = _urlHelper.Action("ServerVariables", "BackOffice");
return defaults;
}
/// <summary>
/// Returns the server variables for authenticated users
/// </summary>
/// <returns></returns>
internal Dictionary<string, object> GetServerVariables()
{
var defaultVals = new Dictionary<string, object>
{
{
"umbracoUrls", new Dictionary<string, object>
{
//TODO: Add 'umbracoApiControllerBaseUrl' which people can use in JS
// to prepend their URL. We could then also use this in our own resources instead of
// having each url defined here explicitly - we can do that in v8! for now
// for umbraco services we'll stick to explicitly defining the endpoints.
{"externalLoginsUrl", _urlHelper.Action("ExternalLogin", "BackOffice")},
{"externalLinkLoginsUrl", _urlHelper.Action("LinkLogin", "BackOffice")},
{"legacyTreeJs", _urlHelper.Action("LegacyTreeJs", "BackOffice")},
{"manifestAssetList", _urlHelper.Action("GetManifestAssetList", "BackOffice")},
{"gridConfig", _urlHelper.Action("GetGridConfig", "BackOffice")},
//TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
{"serverVarsJs", _urlHelper.Action("Application", "BackOffice")},
//API URLs
{
"packagesRestApiBaseUrl", Constants.PackageRepository.RestApiBaseUrl
},
{
"redirectUrlManagementApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RedirectUrlManagementController>(
controller => controller.GetEnableState())
},
{
"tourApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TourController>(
controller => controller.GetTours())
},
{
"embedApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RteEmbedController>(
controller => controller.GetEmbed("", 0, 0))
},
{
"userApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UsersController>(
controller => controller.PostSaveUser(null))
},
{
"userGroupsApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UserGroupsController>(
controller => controller.PostSaveUserGroup(null))
},
{
"contentApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentController>(
controller => controller.PostSave(null))
},
{
"mediaApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaController>(
controller => controller.GetRootMedia())
},
{
"imagesApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ImagesController>(
controller => controller.GetBigThumbnail(0))
},
{
"sectionApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<SectionController>(
controller => controller.GetSections())
},
{
"treeApplicationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ApplicationTreeController>(
controller => controller.GetApplicationTrees(null, null, null, true))
},
{
"contentTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentTypeController>(
controller => controller.GetAllowedChildren(0))
},
{
"mediaTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaTypeController>(
controller => controller.GetAllowedChildren(0))
},
{
"macroApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MacroController>(
controller => controller.GetMacroParameters(0))
},
{
"authenticationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<AuthenticationController>(
controller => controller.PostLogin(null))
},
{
"currentUserApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<CurrentUserController>(
controller => controller.PostChangePassword(null))
},
{
"legacyApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<LegacyController>(
controller => controller.DeleteLegacyItem(null, null, null))
},
{
"entityApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<EntityController>(
controller => controller.GetById(0, UmbracoEntityTypes.Media))
},
{
"dataTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DataTypeController>(
controller => controller.GetById(0))
},
{
"dashboardApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DashboardController>(
controller => controller.GetDashboard(null))
},
{
"logApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<LogController>(
controller => controller.GetEntityLog(0))
},
{
"memberApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberController>(
controller => controller.GetByKey(Guid.Empty))
},
{
"packageInstallApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<PackageInstallController>(
controller => controller.Fetch(string.Empty))
},
{
"relationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RelationController>(
controller => controller.GetById(0))
},
{
"rteApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RichTextPreValueController>(
controller => controller.GetConfiguration())
},
{
"stylesheetApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<StylesheetController>(
controller => controller.GetAll())
},
{
"memberTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberTypeController>(
controller => controller.GetAllTypes())
},
{
"updateCheckApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UpdateCheckController>(
controller => controller.GetCheck())
},
{
"tagApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TagsController>(
controller => controller.GetAllTags(null))
},
{
"templateApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TemplateController>(
controller => controller.GetById(0))
},
{
"memberTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"mediaTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"contentTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"tagsDataBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TagsDataController>(
controller => controller.GetTags(""))
},
{
"examineMgmtBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ExamineManagementApiController>(
controller => controller.GetIndexerDetails())
},
{
"xmlDataIntegrityBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<XmlDataIntegrityController>(
controller => controller.CheckContentXmlTable())
},
{
"healthCheckBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<HealthCheckController>(
controller => controller.GetAllHealthChecks())
},
{
"templateQueryApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TemplateQueryController>(
controller => controller.PostTemplateQuery(null))
},
{
"codeFileApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<CodeFileController>(
controller => controller.GetByPath("", ""))
},
{
"dictionaryApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DictionaryController>(
controller => controller.DeleteById(int.MaxValue))
},
{
"helpApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<HelpController>(
controller => controller.GetContextHelpForPage("","",""))
},
{
"backOfficeAssetsApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<BackOfficeAssetsController>(
controller => controller.GetSupportedMomentLocales())
}
}
},
{
"umbracoSettings", new Dictionary<string, object>
{
{"umbracoPath", GlobalSettings.Path},
{"mediaPath", IOHelper.ResolveUrl(SystemDirectories.Media).TrimEnd('/')},
{"appPluginsPath", IOHelper.ResolveUrl(SystemDirectories.AppPlugins).TrimEnd('/')},
{
"imageFileTypes",
string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes)
},
{
"disallowedUploadFiles",
string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles)
},
{
"allowedUploadFiles",
string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.AllowedUploadFiles)
},
{
"maxFileSize",
GetMaxRequestLength()
},
{"keepUserLoggedIn", UmbracoConfig.For.UmbracoSettings().Security.KeepUserLoggedIn},
{"usernameIsEmail", UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail},
{"cssPath", IOHelper.ResolveUrl(SystemDirectories.Css).TrimEnd('/')},
{"allowPasswordReset", UmbracoConfig.For.UmbracoSettings().Security.AllowPasswordReset},
{"loginBackgroundImage", UmbracoConfig.For.UmbracoSettings().Content.LoginBackgroundImage},
{"showUserInvite", EmailSender.CanSendRequiredEmail},
{"canSendRequiredEmail", EmailSender.CanSendRequiredEmail},
}
},
{
"umbracoPlugins", new Dictionary<string, object>
{
{"trees", GetTreePluginsMetaData()}
}
},
{
"isDebuggingEnabled", _httpContext.IsDebuggingEnabled
},
{
"application", GetApplicationState()
},
{
"externalLogins", new Dictionary<string, object>
{
{
"providers", _owinContext.Authentication.GetExternalAuthenticationTypes()
.Where(p => p.Properties.ContainsKey("UmbracoBackOffice"))
.Select(p => new
{
authType = p.AuthenticationType, caption = p.Caption,
//TODO: Need to see if this exposes any sensitive data!
properties = p.Properties
})
.ToArray()
}
}
},
{
"features", new Dictionary<string,object>
{
{
"disabledFeatures", new Dictionary<string,object>
{
{ "disableTemplates", FeaturesResolver.Current.Features.Disabled.DisableTemplates}
}
}
}
}
};
return defaultVals;
}
private IEnumerable<Dictionary<string, string>> GetTreePluginsMetaData()
{
var treeTypes = TreeControllerTypes.Value;
//get all plugin trees with their attributes
var treesWithAttributes = treeTypes.Select(x => new
{
tree = x,
attributes =
x.GetCustomAttributes(false)
}).ToArray();
var pluginTreesWithAttributes = treesWithAttributes
//don't resolve any tree decorated with CoreTreeAttribute
.Where(x => x.attributes.All(a => (a is CoreTreeAttribute) == false))
//we only care about trees with the PluginControllerAttribute
.Where(x => x.attributes.Any(a => a is PluginControllerAttribute))
.ToArray();
return (from p in pluginTreesWithAttributes
let treeAttr = p.attributes.OfType<TreeAttribute>().Single()
let pluginAttr = p.attributes.OfType<PluginControllerAttribute>().Single()
select new Dictionary<string, string>
{
{"alias", treeAttr.Alias}, {"packageFolder", pluginAttr.AreaName}
}).ToArray();
}
/// <summary>
/// A lazy reference to all tree controller types
/// </summary>
/// <remarks>
/// We are doing this because if we constantly resolve the tree controller types from the PluginManager it will re-scan and also re-log that
/// it's resolving which is unecessary and annoying.
/// </remarks>
private static readonly Lazy<IEnumerable<Type>> TreeControllerTypes = new Lazy<IEnumerable<Type>>(() => PluginManager.Current.ResolveAttributedTreeControllers().ToArray());
/// <summary>
/// Returns the server variables regarding the application state
/// </summary>
/// <returns></returns>
private Dictionary<string, object> GetApplicationState()
{
var app = new Dictionary<string, object>
{
{"assemblyVersion", UmbracoVersion.AssemblyVersion}
};
var version = UmbracoVersion.GetSemanticVersion().ToSemanticString();
//the value is the hash of the version, cdf version and the configured state
app.Add("cacheBuster", $"{version}.{_applicationContext.IsConfigured}.{ClientDependencySettings.Instance.Version}".GenerateHash());
app.Add("version", version);
//useful for dealing with virtual paths on the client side when hosted in virtual directories especially
app.Add("applicationPath", _httpContext.Request.ApplicationPath.EnsureEndsWith('/'));
//add the server's GMT time offset in minutes
app.Add("serverTimeOffset", Convert.ToInt32(DateTimeOffset.Now.Offset.TotalMinutes));
return app;
}
private string GetMaxRequestLength()
{
var section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
if (section == null) return string.Empty;
return section.MaxRequestLength.ToString();
}
}
}
| |
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Xml;
namespace AlchemyAPI
{
public class AlchemyAPI
{
private string _apiKey;
private string _requestUri;
public AlchemyAPI()
{
_apiKey = "";
_requestUri = "http://access.alchemyapi.com/calls/";
}
public void SetAPIHost(string apiHost)
{
if (apiHost.Length < 2)
{
System.ApplicationException ex =
new System.ApplicationException("Error setting API host.");
throw ex;
}
_requestUri = "http://" + apiHost + ".alchemyapi.com/calls/";
}
public void SetAPIKey(string apiKey)
{
_apiKey = apiKey;
if (_apiKey.Length < 5)
{
System.ApplicationException ex =
new System.ApplicationException("Error setting API key.");
throw ex;
}
}
public void LoadAPIKey(string filename)
{
StreamReader reader;
reader = File.OpenText(filename);
string line = reader.ReadLine();
reader.Close();
_apiKey = line.Trim();
if (_apiKey.Length < 5)
{
System.ApplicationException ex =
new System.ApplicationException("Error loading API key.");
throw ex;
}
}
#region GetAuthor
public string URLGetAuthor(string url)
{
CheckURL(url);
return URLGetAuthor(url, new AlchemyAPI_BaseParams());
}
public string URLGetAuthor(string url, AlchemyAPI_BaseParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetAuthor", "url", parameters);
}
public string HTMLGetAuthor(string html,string url)
{
CheckHTML(html, url);
return HTMLGetAuthor(html, url, new AlchemyAPI_BaseParams());
}
public string HTMLGetAuthor(string html, string url, AlchemyAPI_BaseParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetAuthor", "html", parameters);
}
#endregion
#region GetRankedNamedEntities
public string URLGetRankedNamedEntities(string url)
{
CheckURL(url);
return URLGetRankedNamedEntities(url, new AlchemyAPI_EntityParams());
}
public string URLGetRankedNamedEntities(string url, AlchemyAPI_EntityParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetRankedNamedEntities", "url", parameters);
}
public string HTMLGetRankedNamedEntities(string html, string url)
{
CheckHTML(html, url);
return HTMLGetRankedNamedEntities(html, url, new AlchemyAPI_EntityParams());
}
public string HTMLGetRankedNamedEntities(string html, string url, AlchemyAPI_EntityParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetRankedNamedEntities", "html", parameters);
}
public string TextGetRankedNamedEntities(string text)
{
CheckText(text);
return TextGetRankedNamedEntities(text,new AlchemyAPI_EntityParams());
}
public string TextGetRankedNamedEntities(string text, AlchemyAPI_EntityParams parameters)
{
CheckText(text);
parameters.setText(text);
return POST("TextGetRankedNamedEntities", "text", parameters);
}
#endregion
#region GetRankedConcepts
public string URLGetRankedConcepts(string url)
{
CheckURL(url);
return URLGetRankedConcepts(url, new AlchemyAPI_ConceptParams());
}
public string URLGetRankedConcepts(string url, AlchemyAPI_ConceptParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetRankedConcepts", "url", parameters);
}
public string HTMLGetRankedConcepts(string html, string url)
{
CheckHTML(html, url);
return HTMLGetRankedConcepts(html, url, new AlchemyAPI_ConceptParams());
}
public string HTMLGetRankedConcepts(string html, string url, AlchemyAPI_ConceptParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetRankedConcepts", "html", parameters);
}
public string TextGetRankedConcepts(string text)
{
CheckText(text);
return TextGetRankedConcepts(text,new AlchemyAPI_ConceptParams());
}
public string TextGetRankedConcepts(string text, AlchemyAPI_ConceptParams parameters)
{
CheckText(text);
parameters.setText(text);
return POST("TextGetRankedConcepts", "text", parameters);
}
#endregion
#region GetRankedKeywords
public string URLGetRankedKeywords(string url)
{
CheckURL(url);
return URLGetRankedKeywords(url, new AlchemyAPI_KeywordParams());
}
public string URLGetRankedKeywords(string url, AlchemyAPI_KeywordParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetRankedKeywords", "url", parameters);
}
public string HTMLGetRankedKeywords(string html, string url)
{
CheckHTML(html, url);
return HTMLGetRankedKeywords(html, url, new AlchemyAPI_KeywordParams());
}
public string HTMLGetRankedKeywords(string html, string url, AlchemyAPI_KeywordParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetRankedKeywords", "html", parameters);
}
public string TextGetRankedKeywords(string text)
{
CheckText(text);
return TextGetRankedKeywords(text,new AlchemyAPI_KeywordParams());
}
public string TextGetRankedKeywords(string text, AlchemyAPI_KeywordParams parameters)
{
CheckText(text);
parameters.setText(text);
return POST("TextGetRankedKeywords", "text", parameters);
}
#endregion
#region GetLanguage
public string URLGetLanguage(string url)
{
CheckURL(url);
return URLGetLanguage(url,new AlchemyAPI_LanguageParams());
}
public string URLGetLanguage(string url, AlchemyAPI_LanguageParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetLanguage", "url", parameters);
}
public string HTMLGetLanguage(string html, string url)
{
CheckHTML(html, url);
return HTMLGetLanguage(html,url,new AlchemyAPI_LanguageParams());
}
public string HTMLGetLanguage(string html, string url, AlchemyAPI_LanguageParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetLanguage", "html", parameters);
}
public string TextGetLanguage(string text)
{
CheckText(text);
return TextGetLanguage(text, new AlchemyAPI_LanguageParams());
}
public string TextGetLanguage(string text, AlchemyAPI_LanguageParams parameters)
{
CheckText(text);
parameters.setText(text);
return POST("TextGetLanguage", "text", parameters);
}
#endregion
#region GetCategory
public string URLGetCategory(string url)
{
CheckURL(url);
return URLGetCategory(url, new AlchemyAPI_CategoryParams() );
}
public string URLGetCategory(string url, AlchemyAPI_CategoryParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetCategory", "url", parameters);
}
public string HTMLGetCategory(string html, string url)
{
CheckHTML(html, url);
return HTMLGetCategory(html, url, new AlchemyAPI_CategoryParams());
}
public string HTMLGetCategory(string html, string url, AlchemyAPI_CategoryParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetCategory", "html", parameters);
}
public string TextGetCategory(string text)
{
CheckText(text);
return TextGetCategory(text, new AlchemyAPI_CategoryParams());
}
public string TextGetCategory(string text, AlchemyAPI_CategoryParams parameters)
{
CheckText(text);
parameters.setText(text);
return POST("TextGetCategory", "text", parameters);
}
#endregion
#region GetText
public string URLGetText(string url)
{
CheckURL(url);
return URLGetText(url, new AlchemyAPI_TextParams());
}
public string URLGetText(string url, AlchemyAPI_TextParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetText", "url", parameters);
}
public string HTMLGetText(string html, string url)
{
CheckHTML(html, url);
return HTMLGetText(html,url, new AlchemyAPI_TextParams());
}
public string HTMLGetText(string html, string url,AlchemyAPI_TextParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetText", "html", parameters);
}
#endregion
#region GetRawText
public string URLGetRawText(string url)
{
CheckURL(url);
return URLGetRawText(url, new AlchemyAPI_BaseParams());
}
public string URLGetRawText(string url, AlchemyAPI_BaseParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetRawText", "url", parameters);
}
public string HTMLGetRawText(string html, string url)
{
CheckHTML(html, url);
return HTMLGetRawText(html, url, new AlchemyAPI_BaseParams());
}
public string HTMLGetRawText(string html, string url, AlchemyAPI_BaseParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetRawText", "html", parameters);
}
#endregion
#region GetTitle
public string URLGetTitle(string url)
{
CheckURL(url);
return URLGetTitle(url, new AlchemyAPI_BaseParams());
}
public string URLGetTitle(string url, AlchemyAPI_BaseParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetTitle", "url", parameters);
}
public string HTMLGetTitle(string html, string url)
{
CheckHTML(html, url);
return HTMLGetTitle(html, url, new AlchemyAPI_BaseParams());
}
public string HTMLGetTitle(string html, string url, AlchemyAPI_BaseParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetTitle", "html", parameters);
}
#endregion
#region GetFeedLinks
public string URLGetFeedLinks(string url)
{
CheckURL(url);
return URLGetFeedLinks(url, new AlchemyAPI_BaseParams());
}
public string URLGetFeedLinks(string url, AlchemyAPI_BaseParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetFeedLinks", "url", parameters);
}
public string HTMLGetFeedLinks(string html, string url)
{
CheckHTML(html, url);
return HTMLGetFeedLinks(html,url, new AlchemyAPI_BaseParams());
}
public string HTMLGetFeedLinks(string html, string url, AlchemyAPI_BaseParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetFeedLinks", "html", parameters);
}
#endregion
#region GetMicroformats
public string URLGetMicroformats(string url)
{
CheckURL(url);
return URLGetMicroformats(url, new AlchemyAPI_BaseParams());
}
public string URLGetMicroformats(string url, AlchemyAPI_BaseParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetMicroformatData", "url", parameters);
}
public string HTMLGetMicroformats(string html, string url)
{
CheckHTML(html, url);
return HTMLGetMicroformats(html,url, new AlchemyAPI_BaseParams());
}
public string HTMLGetMicroformats(string html, string url, AlchemyAPI_BaseParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetMicroformatData", "html", parameters);
}
#endregion
#region GetConstraintQuery
public string URLGetConstraintQuery(string url, string query)
{
CheckURL(url);
if (query.Length < 2)
{
System.ApplicationException ex =
new System.ApplicationException("Invalid constraint query specified.");
throw ex;
}
AlchemyAPI_ConstraintQueryParams cqParams = new AlchemyAPI_ConstraintQueryParams();
cqParams.setCQuery(query);
return URLGetConstraintQuery(url,cqParams);
}
public string URLGetConstraintQuery(string url, AlchemyAPI_ConstraintQueryParams parameters)
{
CheckURL(url);
if (parameters.getCQuery().Length < 2)
{
System.ApplicationException ex =
new System.ApplicationException("Invalid constraint query specified.");
throw ex;
}
parameters.setUrl(url);
return POST("URLGetConstraintQuery", "url", parameters);
}
public string HTMLGetConstraintQuery(string html, string url, string query)
{
CheckHTML(html, url);
if (query.Length < 2)
{
System.ApplicationException ex =
new System.ApplicationException("Invalid constraint query specified.");
throw ex;
}
AlchemyAPI_ConstraintQueryParams cqParams = new AlchemyAPI_ConstraintQueryParams();
cqParams.setCQuery(query);
return HTMLGetConstraintQuery(html, url, cqParams);
}
public string HTMLGetConstraintQuery(string html, string url, AlchemyAPI_ConstraintQueryParams parameters)
{
CheckHTML(html, url);
if (parameters.getCQuery().Length < 2)
{
System.ApplicationException ex =
new System.ApplicationException("Invalid constraint query specified.");
throw ex;
}
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetConstraintQuery", "html", parameters);
}
#endregion
#region GetTextSentiment
public string URLGetTextSentiment(string url)
{
CheckURL(url);
return URLGetTextSentiment(url, new AlchemyAPI_BaseParams());
}
public string URLGetTextSentiment(string url, AlchemyAPI_BaseParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetTextSentiment", "url", parameters);
}
public string HTMLGetTextSentiment(string html, string url)
{
CheckHTML(html, url);
return HTMLGetTextSentiment(html, url, new AlchemyAPI_BaseParams());
}
public string HTMLGetTextSentiment(string html, string url, AlchemyAPI_BaseParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetTextSentiment", "html", parameters);
}
public string TextGetTextSentiment(string text)
{
CheckText(text);
return TextGetTextSentiment(text,new AlchemyAPI_BaseParams());
}
public string TextGetTextSentiment(string text, AlchemyAPI_BaseParams parameters)
{
CheckText(text);
parameters.setText(text);
return POST("TextGetTextSentiment", "text", parameters);
}
#endregion
#region GetTargetedSentiment
public string URLGetTargetedSentiment(string url, string target)
{
CheckURL(url);
CheckText(target);
return URLGetTargetedSentiment(url, target, new AlchemyAPI_TargetedSentimentParams());
}
public string URLGetTargetedSentiment(string url, string target, AlchemyAPI_TargetedSentimentParams parameters)
{
CheckURL(url);
CheckText(target);
parameters.setUrl(url);
parameters.setTarget(target);
return GET("URLGetTargetedSentiment", "url", parameters);
}
public string HTMLGetTargetedSentiment(string html, string url, string target)
{
CheckHTML(html, url);
CheckText(target);
return HTMLGetTargetedSentiment(html, url, target, new AlchemyAPI_TargetedSentimentParams());
}
public string HTMLGetTargetedSentiment(string html, string url, string target, AlchemyAPI_TargetedSentimentParams parameters)
{
CheckHTML(html, url);
CheckText(target);
parameters.setHtml(html);
parameters.setUrl(url);
parameters.setTarget(target);
return POST("HTMLGetTargetedSentiment", "html", parameters);
}
public string TextGetTargetedSentiment(string text, string target)
{
CheckText(text);
CheckText(target);
return TextGetTargetedSentiment(text, target, new AlchemyAPI_TargetedSentimentParams());
}
public string TextGetTargetedSentiment(string text, string target, AlchemyAPI_TargetedSentimentParams parameters)
{
CheckText(text);
CheckText(target);
parameters.setText(text);
parameters.setTarget(target);
return POST("TextGetTargetedSentiment", "text", parameters);
}
#endregion
#region GetRelations
public string URLGetRelations(string url)
{
CheckURL(url);
return URLGetRelations(url, new AlchemyAPI_RelationParams());
}
public string URLGetRelations(string url, AlchemyAPI_RelationParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET("URLGetRelations", "url", parameters);
}
public string HTMLGetRelations(string html, string url)
{
CheckHTML(html, url);
return HTMLGetRelations(html, url, new AlchemyAPI_RelationParams());
}
public string HTMLGetRelations(string html, string url, AlchemyAPI_RelationParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST("HTMLGetRelations", "html", parameters);
}
public string TextGetRelations(string text)
{
CheckText(text);
return TextGetRelations(text,new AlchemyAPI_RelationParams());
}
public string TextGetRelations(string text, AlchemyAPI_RelationParams parameters)
{
CheckText(text);
parameters.setText(text);
return POST("TextGetRelations", "text", parameters);
}
#endregion
#region GetCombinedData
public string URLGetCombinedData(string url, AlchemyAPI_CombinedDataParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET ("URLGetCombinedData", "url", parameters);
}
public string TextGetCombinedData(string text, AlchemyAPI_CombinedDataParams parameters)
{
CheckText(text);
parameters.setText(text);
return POST ("TextGetCombinedData", "text", parameters);
}
#endregion
#region GetRankedTaxonomy
public string URLGetRankedTaxonomy (string url)
{
return URLGetRankedTaxonomy(url, new AlchemyAPI_TaxonomyParams());
}
public string URLGetRankedTaxonomy (string url, AlchemyAPI_TaxonomyParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET ("URLGetRankedTaxonomy", "url", parameters);
}
public string HTMLGetRankedTaxonomy (string html, string url)
{
return HTMLGetRankedTaxonomy(html, url, new AlchemyAPI_TaxonomyParams());
}
public string HTMLGetRankedTaxonomy (string html, string url, AlchemyAPI_TaxonomyParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST ("HTMLGetRankedTaxonomy", "html", parameters);
}
public string TextGetRankedTaxonomy (string text)
{
return TextGetRankedTaxonomy(text, new AlchemyAPI_TaxonomyParams());
}
public string TextGetRankedTaxonomy (string text, AlchemyAPI_TaxonomyParams parameters)
{
CheckText(text);
parameters.setText(text);
return POST ("TextGetRankedTaxonomy", "text", parameters);
}
#endregion
#region GetImage
public string HTMLGetImage (string html, string url)
{
return HTMLGetImage(html, url, new AlchemyAPI_ImageParams());
}
public string HTMLGetImage (string html, string url, AlchemyAPI_ImageParams parameters)
{
CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return POST ("HTMLGetImage", "html", parameters);
}
public string URLGetImage (string url)
{
return URLGetImage (url, new AlchemyAPI_ImageParams());
}
public string URLGetImage (string url, AlchemyAPI_ImageParams parameters)
{
CheckURL(url);
parameters.setUrl(url);
return GET ("URLGetImage", "url", parameters);
}
#endregion
#region GetRankedImageKeywords
public string URLGetRankedImageKeywords(string url)
{
AlchemyAPI_RankedImageKeywords pms = new AlchemyAPI_RankedImageKeywords
{
ImageURL = url
};
return URLGetRankedImageKeywords(pms);
}
public string URLGetRankedImageKeywords(AlchemyAPI_RankedImageKeywords parameters)
{
CheckURL(parameters.ImageURL);
return GET("URLGetRankedImageKeywords", "url", parameters);
}
public string ImageGetRankedImageKeywords(AlchemyAPI_RankedImageKeywords parameters)
{
return GET("ImageGetRankedImageKeywords", "image", parameters);
}
#endregion
private void CheckHTML(string html, string url)
{
if (html.Length < 10)
{
System.ApplicationException ex =
new System.ApplicationException ("Enter a HTML document to analyze.");
throw ex;
}
if (url.Length < 10)
{
System.ApplicationException ex =
new System.ApplicationException ("Enter a web URL to analyze.");
throw ex;
}
}
private void CheckText(string text)
{
if (text.Length < 5)
{
System.ApplicationException ex =
new System.ApplicationException ("Enter some text to analyze.");
throw ex;
}
}
private void CheckURL(string url)
{
if (url.Length < 10)
{
System.ApplicationException ex =
new System.ApplicationException ("Enter a web URL to analyze.");
throw ex;
}
}
private string GET(string callName, string callPrefix, AlchemyAPI_BaseParams parameters)
{ // callMethod, callPrefix, ... params
StringBuilder uri = new StringBuilder ();
uri.Append(_requestUri).Append(callPrefix).Append("/").Append(callName);
uri.Append("?apikey=").Append(_apiKey).Append(parameters.getParameterString());
parameters.resetBaseParams();
Uri address = new Uri (uri.ToString());
HttpWebRequest wreq = WebRequest.Create(address) as HttpWebRequest;
wreq.Proxy = null; // GlobalProxySelection.GetEmptyWebProxy();
byte[] postData = parameters.GetPostData();
if (postData == null)
{
wreq.Method = "GET";
}
else
{
wreq.Method = "POST";
using (var ps = wreq.GetRequestStream())
{
ps.Write(postData, 0, postData.Length);
}
}
return DoRequest(wreq, parameters.getOutputMode());
}
private string POST(string callName, string callPrefix, AlchemyAPI_BaseParams parameters)
{ // callMethod, callPrefix, ... params
Uri address = new Uri (_requestUri + callPrefix + "/" + callName);
HttpWebRequest wreq = WebRequest.Create(address) as HttpWebRequest;
wreq.Proxy = null; // GlobalProxySelection.GetEmptyWebProxy();
wreq.Method = "POST";
wreq.ContentType = "application/x-www-form-urlencoded";
StringBuilder d = new StringBuilder ();
d.Append("apikey=").Append(_apiKey).Append(parameters.getParameterString());
parameters.resetBaseParams();
byte[] bd = UTF8Encoding.UTF8.GetBytes(d.ToString());
wreq.ContentLength = bd.Length;
using (Stream ps = wreq.GetRequestStream())
{
ps.Write(bd, 0, bd.Length);
}
return DoRequest(wreq, parameters.getOutputMode());
}
private string DoRequest(HttpWebRequest wreq, AlchemyAPI_BaseParams.OutputMode outputMode)
{
using (HttpWebResponse wres = wreq.GetResponse() as HttpWebResponse)
{
StreamReader r = new StreamReader (wres.GetResponseStream());
string xml = r.ReadToEnd();
if (string.IsNullOrEmpty(xml))
throw new XmlException ("The API request returned back an empty response. Please verify that the url is correct.");
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml(xml);
XmlElement root = xmlDoc.DocumentElement;
if (AlchemyAPI_BaseParams.OutputMode.XML == outputMode)
{
XmlNode status = root.SelectSingleNode("/results/status");
if (status.InnerText != "OK")
{
string errorMessage = "Error making API call.";
try
{
XmlNode statusInfo = root.SelectSingleNode("/results/statusInfo");
errorMessage = statusInfo.InnerText;
}
catch
{
// some problem with the statusInfo. Return the generic message.
}
System.ApplicationException ex = new System.ApplicationException (errorMessage);
throw ex;
}
}
else if (AlchemyAPI_BaseParams.OutputMode.RDF == outputMode)
{
XmlNamespaceManager nm = new XmlNamespaceManager (xmlDoc.NameTable);
nm.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
nm.AddNamespace("aapi", "http://rdf.alchemyapi.com/rdf/v1/s/aapi-schema#");
XmlNode status = root.SelectSingleNode("/rdf:RDF/rdf:Description/aapi:ResultStatus", nm);
if (status.InnerText != "OK")
{
System.ApplicationException ex =
new System.ApplicationException ("Error making API call.");
throw ex;
}
}
return xml;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding.WindowsStore;
#if UNITY_WINRT && !UNITY_EDITOR
//using MarkerMetro.Unity.WinLegacy.IO;
//using MarkerMetro.Unity.WinLegacy.Reflection;
#endif
namespace Pathfinding {
[System.Serializable]
/** Stores the navigation graphs for the A* Pathfinding System.
* \ingroup relevant
*
* An instance of this class is assigned to AstarPath.data, from it you can access all graphs loaded through the #graphs variable.\n
* This class also handles a lot of the high level serialization.
*/
public class AstarData {
/** Shortcut to AstarPath.active */
public static AstarPath active {
get {
return AstarPath.active;
}
}
#region Fields
/** Shortcut to the first NavMeshGraph.
* Updated at scanning time
*/
public NavMeshGraph navmesh { get; private set; }
/** Shortcut to the first GridGraph.
* Updated at scanning time
*/
public GridGraph gridGraph { get; private set; }
/** Shortcut to the first PointGraph.
* Updated at scanning time
*/
public PointGraph pointGraph { get; private set; }
/** All supported graph types.
* Populated through reflection search
*/
public System.Type[] graphTypes { get; private set; }
#if ASTAR_FAST_NO_EXCEPTIONS || UNITY_WINRT || UNITY_WEBGL
/** Graph types to use when building with Fast But No Exceptions for iPhone.
* If you add any custom graph types, you need to add them to this hard-coded list.
*/
public static readonly System.Type[] DefaultGraphTypes = new System.Type[] {
typeof(GridGraph),
typeof(PointGraph),
typeof(NavMeshGraph),
};
#endif
/** All graphs this instance holds.
* This will be filled only after deserialization has completed.
* May contain null entries if graph have been removed.
*/
[System.NonSerialized]
public NavGraph[] graphs = new NavGraph[0];
//Serialization Settings
/** Serialized data for all graphs and settings.
* Stored as a base64 encoded string because otherwise Unity's Undo system would sometimes corrupt the byte data (because it only stores deltas).
*
* This can be accessed as a byte array from the #data property.
*
* \since 3.6.1
*/
[SerializeField]
string dataString;
/** Data from versions from before 3.6.1.
* Used for handling upgrades
* \since 3.6.1
*/
[SerializeField]
[UnityEngine.Serialization.FormerlySerializedAs("data")]
private byte[] upgradeData;
/** Serialized data for all graphs and settings */
private byte[] data {
get {
// Handle upgrading from earlier versions than 3.6.1
if (upgradeData != null && upgradeData.Length > 0) {
data = upgradeData;
upgradeData = null;
}
return dataString != null ? System.Convert.FromBase64String(dataString) : null;
}
set {
dataString = value != null ? System.Convert.ToBase64String(value) : null;
}
}
/** Backup data if deserialization failed.
*/
public byte[] data_backup;
/** Serialized data for cached startup.
* If set, on start the graphs will be deserialized from this file.
*/
public TextAsset file_cachedStartup;
/** Serialized data for cached startup.
*
* \deprecated Deprecated since 3.6, AstarData.file_cachedStartup is now used instead
*/
public byte[] data_cachedStartup;
/** Should graph-data be cached.
* Caching the startup means saving the whole graphs, not only the settings to an internal array (#data_cachedStartup) which can
* be loaded faster than scanning all graphs at startup. This is setup from the editor.
*/
[SerializeField]
public bool cacheStartup;
//End Serialization Settings
List<bool> graphStructureLocked = new List<bool>();
#endregion
public byte[] GetData () {
return data;
}
public void SetData (byte[] data) {
this.data = data;
}
/** Loads the graphs from memory, will load cached graphs if any exists */
public void Awake () {
graphs = new NavGraph[0];
if (cacheStartup && file_cachedStartup != null) {
LoadFromCache();
} else {
DeserializeGraphs();
}
}
/** Prevent the graph structure from changing during the time this lock is held.
* This prevents graphs from being added or removed and also prevents graphs from being serialized or deserialized.
* This is used when e.g an async scan is happening to ensure that for example a graph that is being scanned is not destroyed.
*
* Each call to this method *must* be paired with exactly one call to #UnlockGraphStructure.
* The calls may be nested.
*/
internal void LockGraphStructure (bool allowAddingGraphs = false) {
graphStructureLocked.Add(allowAddingGraphs);
}
/** Allows the graph structure to change again.
* \see #LockGraphStructure
*/
internal void UnlockGraphStructure () {
if (graphStructureLocked.Count == 0) throw new System.InvalidOperationException();
graphStructureLocked.RemoveAt(graphStructureLocked.Count - 1);
}
PathProcessor.GraphUpdateLock AssertSafe (bool onlyAddingGraph = false) {
if (graphStructureLocked.Count > 0) {
bool allowAdding = true;
for (int i = 0; i < graphStructureLocked.Count; i++) allowAdding &= graphStructureLocked[i];
if (!(onlyAddingGraph && allowAdding)) throw new System.InvalidOperationException("Graphs cannot be added, removed or serialized while the graph structure is locked. This is the case when a graph is currently being scanned and when executing graph updates and work items.\nHowever as a special case, graphs can be added inside work items.");
}
// Pause the pathfinding threads
var graphLock = active.PausePathfinding();
if (!active.IsInsideWorkItem) {
// Make sure all graph updates and other callbacks are done
// Only do this if this code is not being called from a work item itself as that would cause a recursive wait that could never complete.
// There are some valid cases when this can happen. For example it may be necessary to add a new graph inside a work item.
active.FlushWorkItems();
// Paths that are already calculated and waiting to be returned to the Seeker component need to be
// processed immediately as their results usually depend on graphs that currently exist. If this was
// not done then after destroying a graph one could get a path result with destroyed nodes in it.
active.pathReturnQueue.ReturnPaths(false);
}
return graphLock;
}
/** Updates shortcuts to the first graph of different types.
* Hard coding references to some graph types is not really a good thing imo. I want to keep it dynamic and flexible.
* But these references ease the use of the system, so I decided to keep them.\n
*/
public void UpdateShortcuts () {
navmesh = (NavMeshGraph)FindGraphOfType(typeof(NavMeshGraph));
gridGraph = (GridGraph)FindGraphOfType(typeof(GridGraph));
pointGraph = (PointGraph)FindGraphOfType(typeof(PointGraph));
}
/** Load from data from #file_cachedStartup */
public void LoadFromCache () {
var graphLock = AssertSafe();
if (file_cachedStartup != null) {
var bytes = file_cachedStartup.bytes;
DeserializeGraphs(bytes);
GraphModifier.TriggerEvent(GraphModifier.EventType.PostCacheLoad);
} else {
Debug.LogError("Can't load from cache since the cache is empty");
}
graphLock.Release();
}
#region Serialization
/** Serializes all graphs settings to a byte array.
* \see DeserializeGraphs(byte[])
*/
public byte[] SerializeGraphs () {
return SerializeGraphs(Pathfinding.Serialization.SerializeSettings.Settings);
}
/** Serializes all graphs settings and optionally node data to a byte array.
* \see DeserializeGraphs(byte[])
* \see Pathfinding.Serialization.SerializeSettings
*/
public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings) {
uint checksum;
return SerializeGraphs(settings, out checksum);
}
/** Main serializer function.
* Serializes all graphs to a byte array
* A similar function exists in the AstarPathEditor.cs script to save additional info */
public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings, out uint checksum) {
var graphLock = AssertSafe();
var sr = new Pathfinding.Serialization.AstarSerializer(this, settings);
sr.OpenSerialize();
SerializeGraphsPart(sr);
byte[] bytes = sr.CloseSerialize();
checksum = sr.GetChecksum();
graphLock.Release();
return bytes;
}
/** Serializes common info to the serializer.
* Common info is what is shared between the editor serialization and the runtime serializer.
* This is mostly everything except the graph inspectors which serialize some extra data in the editor
*/
public void SerializeGraphsPart (Pathfinding.Serialization.AstarSerializer sr) {
sr.SerializeGraphs(graphs);
sr.SerializeExtraInfo();
}
/** Deserializes graphs from #data */
public void DeserializeGraphs () {
if (data != null) {
DeserializeGraphs(data);
}
}
/** Destroys all graphs and sets graphs to null */
void ClearGraphs () {
if (graphs == null) return;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] != null) {
graphs[i].OnDestroy();
graphs[i].active = null;
}
}
graphs = null;
UpdateShortcuts();
}
public void OnDestroy () {
ClearGraphs();
}
/** Deserializes graphs from the specified byte array.
* An error will be logged if deserialization fails.
*/
public void DeserializeGraphs (byte[] bytes) {
var graphLock = AssertSafe();
ClearGraphs();
DeserializeGraphsAdditive(bytes);
graphLock.Release();
}
/** Deserializes graphs from the specified byte array additively.
* An error will be logged if deserialization fails.
* This function will add loaded graphs to the current ones.
*/
public void DeserializeGraphsAdditive (byte[] bytes) {
var graphLock = AssertSafe();
try {
if (bytes != null) {
var sr = new Pathfinding.Serialization.AstarSerializer(this);
if (sr.OpenDeserialize(bytes)) {
DeserializeGraphsPartAdditive(sr);
sr.CloseDeserialize();
} else {
Debug.Log("Invalid data file (cannot read zip).\nThe data is either corrupt or it was saved using a 3.0.x or earlier version of the system");
}
} else {
throw new System.ArgumentNullException("bytes");
}
active.VerifyIntegrity();
} catch (System.Exception e) {
Debug.LogError("Caught exception while deserializing data.\n"+e);
graphs = new NavGraph[0];
data_backup = bytes;
}
UpdateShortcuts();
graphLock.Release();
}
/** Deserializes common info.
* Common info is what is shared between the editor serialization and the runtime serializer.
* This is mostly everything except the graph inspectors which serialize some extra data in the editor
*
* In most cases you should use the DeserializeGraphs or DeserializeGraphsAdditive method instead.
*/
public void DeserializeGraphsPart (Pathfinding.Serialization.AstarSerializer sr) {
var graphLock = AssertSafe();
ClearGraphs();
DeserializeGraphsPartAdditive(sr);
graphLock.Release();
}
/** Deserializes common info additively
* Common info is what is shared between the editor serialization and the runtime serializer.
* This is mostly everything except the graph inspectors which serialize some extra data in the editor
*
* In most cases you should use the DeserializeGraphs or DeserializeGraphsAdditive method instead.
*/
public void DeserializeGraphsPartAdditive (Pathfinding.Serialization.AstarSerializer sr) {
if (graphs == null) graphs = new NavGraph[0];
var gr = new List<NavGraph>(graphs);
// Set an offset so that the deserializer will load
// the graphs with the correct graph indexes
sr.SetGraphIndexOffset(gr.Count);
gr.AddRange(sr.DeserializeGraphs());
graphs = gr.ToArray();
sr.DeserializeExtraInfo();
//Assign correct graph indices.
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] == null) continue;
graphs[i].GetNodes(node => node.GraphIndex = (uint)i);
}
for (int i = 0; i < graphs.Length; i++) {
for (int j = i+1; j < graphs.Length; j++) {
if (graphs[i] != null && graphs[j] != null && graphs[i].guid == graphs[j].guid) {
Debug.LogWarning("Guid Conflict when importing graphs additively. Imported graph will get a new Guid.\nThis message is (relatively) harmless.");
graphs[i].guid = Pathfinding.Util.Guid.NewGuid();
break;
}
}
}
sr.PostDeserialization();
}
#endregion
/** Find all graph types supported in this build.
* Using reflection, the assembly is searched for types which inherit from NavGraph. */
public void FindGraphTypes () {
#if !ASTAR_FAST_NO_EXCEPTIONS && !UNITY_WINRT && !UNITY_WEBGL
var assembly = WindowsStoreCompatibility.GetTypeInfo(typeof(AstarPath)).Assembly;
System.Type[] types = assembly.GetTypes();
var graphList = new List<System.Type>();
foreach (System.Type type in types) {
#if NETFX_CORE && !UNITY_EDITOR
System.Type baseType = type.GetTypeInfo().BaseType;
#else
System.Type baseType = type.BaseType;
#endif
while (baseType != null) {
if (System.Type.Equals(baseType, typeof(NavGraph))) {
graphList.Add(type);
break;
}
#if NETFX_CORE && !UNITY_EDITOR
baseType = baseType.GetTypeInfo().BaseType;
#else
baseType = baseType.BaseType;
#endif
}
}
graphTypes = graphList.ToArray();
#else
graphTypes = DefaultGraphTypes;
#endif
}
#region GraphCreation
/**
* \returns A System.Type which matches the specified \a type string. If no mathing graph type was found, null is returned
*
* \deprecated
*/
[System.Obsolete("If really necessary. Use System.Type.GetType instead.")]
public System.Type GetGraphType (string type) {
for (int i = 0; i < graphTypes.Length; i++) {
if (graphTypes[i].Name == type) {
return graphTypes[i];
}
}
return null;
}
/** Creates a new instance of a graph of type \a type. If no matching graph type was found, an error is logged and null is returned
* \returns The created graph
* \see CreateGraph(System.Type)
*
* \deprecated
*/
[System.Obsolete("Use CreateGraph(System.Type) instead")]
public NavGraph CreateGraph (string type) {
Debug.Log("Creating Graph of type '"+type+"'");
for (int i = 0; i < graphTypes.Length; i++) {
if (graphTypes[i].Name == type) {
return CreateGraph(graphTypes[i]);
}
}
Debug.LogError("Graph type ("+type+") wasn't found");
return null;
}
/** Creates a new graph instance of type \a type
* \see CreateGraph(string)
*/
internal NavGraph CreateGraph (System.Type type) {
var graph = System.Activator.CreateInstance(type) as NavGraph;
graph.active = active;
return graph;
}
/** Adds a graph of type \a type to the #graphs array
*
* \deprecated
*/
[System.Obsolete("Use AddGraph(System.Type) instead")]
public NavGraph AddGraph (string type) {
NavGraph graph = null;
for (int i = 0; i < graphTypes.Length; i++) {
if (graphTypes[i].Name == type) {
graph = CreateGraph(graphTypes[i]);
}
}
if (graph == null) {
Debug.LogError("No NavGraph of type '"+type+"' could be found");
return null;
}
AddGraph(graph);
return graph;
}
/** Adds a graph of type \a type to the #graphs array */
public NavGraph AddGraph (System.Type type) {
NavGraph graph = null;
for (int i = 0; i < graphTypes.Length; i++) {
if (System.Type.Equals(graphTypes[i], type)) {
graph = CreateGraph(graphTypes[i]);
}
}
if (graph == null) {
Debug.LogError("No NavGraph of type '"+type+"' could be found, "+graphTypes.Length+" graph types are avaliable");
return null;
}
AddGraph(graph);
return graph;
}
/** Adds the specified graph to the #graphs array */
void AddGraph (NavGraph graph) {
// Make sure to not interfere with pathfinding
var graphLock = AssertSafe(true);
// Try to fill in an empty position
bool foundEmpty = false;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] == null) {
graphs[i] = graph;
graph.graphIndex = (uint)i;
foundEmpty = true;
break;
}
}
if (!foundEmpty) {
if (graphs != null && graphs.Length >= GraphNode.MaxGraphIndex) {
throw new System.Exception("Graph Count Limit Reached. You cannot have more than " + GraphNode.MaxGraphIndex + " graphs.");
}
// Add a new entry to the list
var graphList = new List<NavGraph>(graphs ?? new NavGraph[0]);
graphList.Add(graph);
graphs = graphList.ToArray();
graph.graphIndex = (uint)(graphs.Length-1);
}
UpdateShortcuts();
graph.active = active;
graphLock.Release();
}
/** Removes the specified graph from the #graphs array and Destroys it in a safe manner.
* To avoid changing graph indices for the other graphs, the graph is simply nulled in the array instead
* of actually removing it from the array.
* The empty position will be reused if a new graph is added.
*
* \returns True if the graph was sucessfully removed (i.e it did exist in the #graphs array). False otherwise.
*
* \version Changed in 3.2.5 to call SafeOnDestroy before removing
* and nulling it in the array instead of removing the element completely in the #graphs array.
*/
public bool RemoveGraph (NavGraph graph) {
// Make sure the pathfinding threads are stopped
// If we don't wait until pathfinding that is potentially running on
// this graph right now we could end up with NullReferenceExceptions
var graphLock = AssertSafe();
graph.OnDestroy();
graph.active = null;
int i = System.Array.IndexOf(graphs, graph);
if (i != -1) graphs[i] = null;
UpdateShortcuts();
graphLock.Release();
return i != -1;
}
#endregion
#region GraphUtility
/** Returns the graph which contains the specified node.
* The graph must be in the #graphs array.
*
* \returns Returns the graph which contains the node. Null if the graph wasn't found
*/
public static NavGraph GetGraph (GraphNode node) {
if (node == null) return null;
AstarPath script = AstarPath.active;
if (script == null) return null;
AstarData data = script.data;
if (data == null || data.graphs == null) return null;
uint graphIndex = node.GraphIndex;
if (graphIndex >= data.graphs.Length) {
return null;
}
return data.graphs[(int)graphIndex];
}
/** Returns the first graph of type \a type found in the #graphs array. Returns null if none was found */
public NavGraph FindGraphOfType (System.Type type) {
if (graphs != null) {
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] != null && System.Type.Equals(graphs[i].GetType(), type)) {
return graphs[i];
}
}
}
return null;
}
/** Loop through this function to get all graphs of type 'type'
* \code
* foreach (GridGraph graph in AstarPath.data.FindGraphsOfType (typeof(GridGraph))) {
* //Do something with the graph
* }
* \endcode
* \see AstarPath.RegisterSafeNodeUpdate */
public IEnumerable FindGraphsOfType (System.Type type) {
if (graphs == null) yield break;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] != null && System.Type.Equals(graphs[i].GetType(), type)) {
yield return graphs[i];
}
}
}
/** All graphs which implements the UpdateableGraph interface
* \code foreach (IUpdatableGraph graph in AstarPath.data.GetUpdateableGraphs ()) {
* //Do something with the graph
* } \endcode
* \see AstarPath.RegisterSafeNodeUpdate
* \see Pathfinding.IUpdatableGraph */
public IEnumerable GetUpdateableGraphs () {
if (graphs == null) yield break;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] is IUpdatableGraph) {
yield return graphs[i];
}
}
}
/** All graphs which implements the UpdateableGraph interface
* \code foreach (IRaycastableGraph graph in AstarPath.data.GetRaycastableGraphs ()) {
* //Do something with the graph
* } \endcode
* \see Pathfinding.IRaycastableGraph
* \deprecated Deprecated because it is not used by the package internally and the use cases are few. Iterate through the #graphs array instead.
*/
[System.Obsolete("Obsolete because it is not used by the package internally and the use cases are few. Iterate through the graphs array instead.")]
public IEnumerable GetRaycastableGraphs () {
if (graphs == null) yield break;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] is IRaycastableGraph) {
yield return graphs[i];
}
}
}
/** Gets the index of the NavGraph in the #graphs array */
public int GetGraphIndex (NavGraph graph) {
if (graph == null) throw new System.ArgumentNullException("graph");
var index = -1;
if (graphs != null) {
index = System.Array.IndexOf(graphs, graph);
if (index == -1) Debug.LogError("Graph doesn't exist");
}
return index;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
using Orleans.Runtime;
using Orleans.Serialization;
using TestExtensions;
using Xunit;
namespace UnitTests.Serialization
{
[TestCategory("BVT"), TestCategory("Serialization")]
[Collection(TestEnvironmentFixture.DefaultCollection)]
public class ILSerializerTests
{
private readonly TestEnvironmentFixture fixture;
public ILSerializerTests(TestEnvironmentFixture fixture)
{
this.fixture = fixture;
}
/// <summary>
/// Tests that <see cref="ILSerializerGenerator"/> supports distinct field selection for serialization
/// versus copy operations.
/// </summary>
[Fact]
public void ILSerializer_AllowCopiedFieldsToDifferFromSerializedFields()
{
var input = new FieldTest
{
One = 1,
Two = 2,
Three = 3
};
var generator = new ILSerializerGenerator();
var serializers = generator.GenerateSerializer(input.GetType(), f => f.Name != "One", f => f.Name != "Three");
var writer = new BinaryTokenStreamWriter();
var context = new SerializationContext(this.fixture.SerializationManager)
{
StreamWriter = writer
};
var copy = (FieldTest)serializers.DeepCopy(input, context);
Assert.Equal(1, copy.One);
Assert.Equal(2, copy.Two);
Assert.Equal(0, copy.Three);
serializers.Serialize(input, context, input.GetType());
var reader = new DeserializationContext(this.fixture.SerializationManager)
{
StreamReader = new BinaryTokenStreamReader(writer.ToByteArray())
};
var deserialized = (FieldTest)serializers.Deserialize(input.GetType(), reader);
Assert.Equal(0, deserialized.One);
Assert.Equal(2, deserialized.Two);
Assert.Equal(3, deserialized.Three);
}
/// <summary>
/// Tests that <see cref="ILSerializerGenerator"/> supports the <see cref="IOnDeserialized"/> lifecycle hook.
/// </summary>
[Fact]
public void ILSerializer_LifecycleHooksAreCalled()
{
var input = new FieldTest();
var generator = new ILSerializerGenerator();
var serializers = generator.GenerateSerializer(input.GetType());
var writer = new BinaryTokenStreamWriter();
var context = new SerializationContext(this.fixture.SerializationManager)
{
StreamWriter = writer
};
serializers.Serialize(input, context, input.GetType());
var reader = new DeserializationContext(this.fixture.SerializationManager)
{
StreamReader = new BinaryTokenStreamReader(writer.ToByteArray())
};
var deserialized = (FieldTest)serializers.Deserialize(input.GetType(), reader);
Assert.Null(input.Context);
Assert.NotNull(deserialized.Context);
Assert.Equal(this.fixture.SerializationManager, deserialized.Context.GetSerializationManager());
}
/// <summary>
/// Tests that <see cref="ILSerializerGenerator"/> does not serialize fields marked as [NonSerialized].
/// </summary>
[Fact]
public void ILSerializer_NonSerializedFields()
{
var input = new FieldTest
{
One = 1,
Two = 2,
NonSerializedInt = 1098
};
var generator = new ILSerializerGenerator();
var serializers = generator.GenerateSerializer(input.GetType());
var writer = new BinaryTokenStreamWriter();
var context = new SerializationContext(this.fixture.SerializationManager)
{
StreamWriter = writer
};
serializers.Serialize(input, context, input.GetType());
var reader = new DeserializationContext(this.fixture.SerializationManager)
{
StreamReader = new BinaryTokenStreamReader(writer.ToByteArray())
};
var deserialized = (FieldTest) serializers.Deserialize(input.GetType(), reader);
Assert.Equal(input.One, deserialized.One);
Assert.Equal(input.Two, deserialized.Two);
Assert.NotEqual(input.NonSerializedInt, deserialized.NonSerializedInt);
Assert.Equal(default(int), deserialized.NonSerializedInt);
}
/// <summary>
/// Tests that <see cref="ILBasedSerializer"/> can correctly serialize objects which have serialization lifecycle hooks.
/// </summary>
[Fact]
public void ILSerializer_SerializesObjectWithHooks()
{
var input = new SimpleISerializableObject
{
Payload = "pyjamas"
};
// Verify that our behavior conforms to our expected behavior.
var result = SerializerLoop(input);
Assert.Equal(
new[]
{
"default_ctor",
"serializing",
"serialized"
},
input.History);
Assert.Equal(2, input.Contexts.Count);
Assert.All(input.Contexts,
ctx => Assert.True(ctx.Context is ICopyContext || ctx.Context is ISerializationContext));
Assert.Equal(
new[]
{
"default_ctor",
"deserializing",
"deserialized",
"deserialization"
},
result.History);
Assert.Equal(input.Payload, result.Payload, StringComparer.Ordinal);
Assert.Equal(2, result.Contexts.Count);
Assert.All(result.Contexts, ctx => Assert.True(ctx.Context is IDeserializationContext));
// Verify that our behavior conforms to the behavior of BinaryFormatter.
var input2 = new SimpleISerializableObject
{
Payload = "pyjamas"
};
var result2 = (SimpleISerializableObject) BuiltInSerializerTests.DotNetSerializationLoop(
input2,
this.fixture.SerializationManager);
Assert.Equal(input2.History, input.History);
Assert.Equal(result2.History, result.History.Skip(1).ToList());
}
/// <summary>
/// Tests that <see cref="ILBasedSerializer"/> can correctly serialize structs which have serialization lifecycle hooks.
/// </summary>
[Fact]
public void ILSerializer_SerializesStructWithHooks()
{
var input = new SimpleISerializableStruct
{
Payload = "pyjamas"
};
// Verify that our behavior conforms to our expected behavior.
var result = SerializerLoop(input);
Assert.Equal(
new[]
{
"deserializing",
"deserialized",
"deserialization"
},
result.History);
Assert.Equal(input.Payload, result.Payload, StringComparer.Ordinal);
Assert.Equal(2, result.Contexts.Count);
Assert.All(result.Contexts, ctx => Assert.True(ctx.Context is IDeserializationContext));
// Verify that our behavior conforms to the behavior of BinaryFormatter.
var input2 = new SimpleISerializableStruct
{
Payload = "pyjamas"
};
var result2 = (SimpleISerializableStruct) BuiltInSerializerTests.DotNetSerializationLoop(
input2,
this.fixture.SerializationManager);
Assert.Equal(input2.History, input.History);
Assert.Equal(result2.History, result.History);
}
private T SerializerLoop<T>(T input)
{
#pragma warning disable CS0618 // Type or member is obsolete
var serializer = new ILBasedSerializer(new CachedTypeResolver());
#pragma warning restore CS0618 // Type or member is obsolete
Assert.True(serializer.IsSupportedType(input.GetType()));
var writer = new BinaryTokenStreamWriter();
var serializationContext =
new SerializationContext(this.fixture.SerializationManager)
{
StreamWriter = writer
};
serializer.Serialize(input, serializationContext, typeof(T));
var deserializationContext = new DeserializationContext(this.fixture.SerializationManager)
{
StreamReader = new BinaryTokenStreamReader(writer.ToBytes())
};
return (T) serializer.Deserialize(typeof(T), deserializationContext);
}
[Serializable]
public class SimpleISerializableObject : IDeserializationCallback
{
[NonSerialized]
private List<string> history;
[NonSerialized]
private List<StreamingContext> contexts;
public SimpleISerializableObject()
{
this.History.Add("default_ctor");
}
public List<string> History => this.history ?? (this.history = new List<string>());
public List<StreamingContext> Contexts => this.contexts ?? (this.contexts = new List<StreamingContext>());
public string Payload { get; set; }
[OnSerializing]
internal void OnSerializingMethod(StreamingContext context)
{
this.History.Add("serializing");
this.Contexts.Add(context);
}
[OnSerialized]
internal void OnSerializedMethod(StreamingContext context)
{
this.History.Add("serialized");
this.Contexts.Add(context);
}
[OnDeserializing]
internal void OnDeserializingMethod(StreamingContext context)
{
this.History.Add("deserializing");
this.Contexts.Add(context);
}
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
this.History.Add("deserialized");
this.Contexts.Add(context);
}
void IDeserializationCallback.OnDeserialization(object sender)
{
this.History.Add("deserialization");
}
}
[Serializable]
public struct SimpleISerializableStruct : IDeserializationCallback
{
[NonSerialized]
private List<string> history;
[NonSerialized]
private List<StreamingContext> contexts;
public List<string> History => this.history ?? (this.history = new List<string>());
public List<StreamingContext> Contexts => this.contexts ?? (this.contexts = new List<StreamingContext>());
public string Payload { get; set; }
[OnSerializing]
internal void OnSerializingMethod(StreamingContext context)
{
this.History.Add("serializing");
this.Contexts.Add(context);
}
[OnSerialized]
internal void OnSerializedMethod(StreamingContext context)
{
this.History.Add("serialized");
this.Contexts.Add(context);
}
[OnDeserializing]
internal void OnDeserializingMethod(StreamingContext context)
{
this.History.Add("deserializing");
this.Contexts.Add(context);
}
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
this.History.Add("deserialized");
this.Contexts.Add(context);
}
void IDeserializationCallback.OnDeserialization(object sender)
{
this.History.Add("deserialization");
}
}
[SuppressMessage("ReSharper", "StyleCop.SA1401", Justification = "This is for testing purposes.")]
private class FieldTest : IOnDeserialized
{
#pragma warning disable 169
public int One;
public int Two;
public int Three;
[NonSerialized]
public int NonSerializedInt;
[NonSerialized]
public ISerializerContext Context;
public void OnDeserialized(ISerializerContext context)
{
this.Context = context;
}
#pragma warning restore 169
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableArrayBuilderTest : SimpleElementImmutablesTestBase
{
[Fact]
public void CreateBuilderDefaultCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>();
Assert.NotNull(builder);
Assert.NotSame(builder, ImmutableArray.CreateBuilder<int>());
}
[Fact]
public void CreateBuilderInvalidCapacity()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => ImmutableArray.CreateBuilder<int>(-1));
}
[Fact]
public void NormalConstructionValueType()
{
var builder = ImmutableArray.CreateBuilder<int>(3);
Assert.Equal(0, builder.Count);
Assert.False(((ICollection<int>)builder).IsReadOnly);
for (int i = 0; i < builder.Count; i++)
{
Assert.Equal(0, builder[i]);
}
builder.Add(5);
builder.Add(6);
builder.Add(7);
Assert.Equal(5, builder[0]);
Assert.Equal(6, builder[1]);
Assert.Equal(7, builder[2]);
}
[Fact]
public void NormalConstructionRefType()
{
var builder = new ImmutableArray<GenericParameterHelper>.Builder(3);
Assert.Equal(0, builder.Count);
Assert.False(((ICollection<GenericParameterHelper>)builder).IsReadOnly);
for (int i = 0; i < builder.Count; i++)
{
Assert.Null(builder[i]);
}
builder.Add(new GenericParameterHelper(5));
builder.Add(new GenericParameterHelper(6));
builder.Add(new GenericParameterHelper(7));
Assert.Equal(5, builder[0].Data);
Assert.Equal(6, builder[1].Data);
Assert.Equal(7, builder[2].Data);
}
[Fact]
public void AddRangeIEnumerable()
{
var builder = new ImmutableArray<int>.Builder(2);
builder.AddRange((IEnumerable<int>)new[] { 1 });
Assert.Equal(1, builder.Count);
builder.AddRange((IEnumerable<int>)new[] { 2 });
Assert.Equal(2, builder.Count);
builder.AddRange((IEnumerable<int>)new int[0]);
Assert.Equal(2, builder.Count);
// Exceed capacity
builder.AddRange(Enumerable.Range(3, 2)); // use an enumerable without a breakable Count
Assert.Equal(4, builder.Count);
Assert.Equal(Enumerable.Range(1, 4), builder);
}
[Fact]
public void Add()
{
var builder = ImmutableArray.CreateBuilder<int>(0);
builder.Add(1);
builder.Add(2);
Assert.Equal(new int[] { 1, 2 }, builder);
Assert.Equal(2, builder.Count);
builder = ImmutableArray.CreateBuilder<int>(1);
builder.Add(1);
builder.Add(2);
Assert.Equal(new int[] { 1, 2 }, builder);
Assert.Equal(2, builder.Count);
builder = ImmutableArray.CreateBuilder<int>(2);
builder.Add(1);
builder.Add(2);
Assert.Equal(new int[] { 1, 2 }, builder);
Assert.Equal(2, builder.Count);
}
[Fact]
public void AddRangeBuilder()
{
var builder1 = new ImmutableArray<int>.Builder(2);
var builder2 = new ImmutableArray<int>.Builder(2);
builder1.AddRange(builder2);
Assert.Equal(0, builder1.Count);
Assert.Equal(0, builder2.Count);
builder2.Add(1);
builder2.Add(2);
builder1.AddRange(builder2);
Assert.Equal(2, builder1.Count);
Assert.Equal(2, builder2.Count);
Assert.Equal(new[] { 1, 2 }, builder1);
}
[Fact]
public void AddRangeImmutableArray()
{
var builder1 = new ImmutableArray<int>.Builder(2);
var array = ImmutableArray.Create(1, 2, 3);
builder1.AddRange(array);
Assert.Equal(new[] { 1, 2, 3 }, builder1);
AssertExtensions.Throws<ArgumentNullException>("items", () => builder1.AddRange((int[])null));
AssertExtensions.Throws<ArgumentNullException>("items", () => builder1.AddRange(null, 42));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder1.AddRange(new int[0], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder1.AddRange(new int[0], 42));
AssertExtensions.Throws<ArgumentNullException>("items", () => builder1.AddRange((ImmutableArray<int>.Builder)null));
AssertExtensions.Throws<ArgumentNullException>("items", () => builder1.AddRange((IEnumerable<int>)null));
Assert.Throws<NullReferenceException>(() => builder1.AddRange(default(ImmutableArray<int>)));
builder1.AddRange(default(ImmutableArray<int>), 42);
var builder2 = new ImmutableArray<object>.Builder();
builder2.AddRange(default(ImmutableArray<string>));
AssertExtensions.Throws<ArgumentNullException>("items", () => builder2.AddRange((ImmutableArray<string>.Builder)null));
}
[Fact]
public void AddRangeDerivedArray()
{
var builder = new ImmutableArray<object>.Builder();
builder.AddRange(new[] { "a", "b" });
Assert.Equal(new[] { "a", "b" }, builder);
}
[Fact]
public void AddRangeDerivedImmutableArray()
{
var builder = new ImmutableArray<object>.Builder();
builder.AddRange(new[] { "a", "b" }.ToImmutableArray());
Assert.Equal(new[] { "a", "b" }, builder);
}
[Fact]
public void AddRangeDerivedBuilder()
{
var builder = new ImmutableArray<string>.Builder();
builder.AddRange(new[] { "a", "b" });
var builderBase = new ImmutableArray<object>.Builder();
builderBase.AddRange(builder);
Assert.Equal(new[] { "a", "b" }, builderBase);
}
[Fact]
public void Contains()
{
var builder = new ImmutableArray<int>.Builder();
Assert.False(builder.Contains(1));
builder.Add(1);
Assert.True(builder.Contains(1));
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => (ImmutableArray<int>.Builder)this.GetEnumerableOf(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => (ImmutableArray<int>.Builder)this.GetEnumerableOf(seq),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void Insert()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3);
builder.Insert(1, 4);
builder.Insert(4, 5);
Assert.Equal(new[] { 1, 4, 2, 3, 5 }, builder);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Count + 1, 0));
}
[Fact]
public void Remove()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3, 4);
Assert.True(builder.Remove(1));
Assert.False(builder.Remove(6));
Assert.Equal(new[] { 2, 3, 4 }, builder);
Assert.True(builder.Remove(3));
Assert.Equal(new[] { 2, 4 }, builder);
Assert.True(builder.Remove(4));
Assert.Equal(new[] { 2 }, builder);
Assert.True(builder.Remove(2));
Assert.Equal(0, builder.Count);
}
[Fact]
public void RemoveAt()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3, 4);
builder.RemoveAt(0);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.RemoveAt(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.RemoveAt(3));
Assert.Equal(new[] { 2, 3, 4 }, builder);
builder.RemoveAt(1);
Assert.Equal(new[] { 2, 4 }, builder);
builder.RemoveAt(1);
Assert.Equal(new[] { 2 }, builder);
builder.RemoveAt(0);
Assert.Equal(0, builder.Count);
}
[Fact]
public void ReverseContents()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3, 4);
builder.Reverse();
Assert.Equal(new[] { 4, 3, 2, 1 }, builder);
builder.RemoveAt(0);
builder.Reverse();
Assert.Equal(new[] { 1, 2, 3 }, builder);
builder.RemoveAt(0);
builder.Reverse();
Assert.Equal(new[] { 3, 2 }, builder);
builder.RemoveAt(0);
builder.Reverse();
Assert.Equal(new[] { 2 }, builder);
builder.RemoveAt(0);
builder.Reverse();
Assert.Equal(new int[0], builder);
}
[Fact]
public void Sort()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(2, 4, 1, 3);
builder.Sort();
Assert.Equal(new[] { 1, 2, 3, 4 }, builder);
}
[Fact]
public void Sort_Comparison()
{
var builder = new ImmutableArray<int>.Builder(4);
builder.Sort((x, y) => y.CompareTo(x));
Assert.Equal(Array.Empty<int>(), builder);
builder.AddRange(2, 4, 1, 3);
builder.Sort((x, y) => y.CompareTo(x));
Assert.Equal(new[] { 4, 3, 2, 1 }, builder);
builder.Add(5);
builder.Sort((x, y) => x.CompareTo(y));
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, builder);
}
[Fact]
public void Sort_NullComparison_Throws()
{
AssertExtensions.Throws<ArgumentNullException>("comparison", () => ImmutableArray.CreateBuilder<int>().Sort((Comparison<int>)null));
}
[Fact]
public void SortNullComparer()
{
var template = ImmutableArray.Create(2, 4, 1, 3);
var builder = template.ToBuilder();
builder.Sort((IComparer<int>)null);
Assert.Equal(new[] { 1, 2, 3, 4 }, builder);
builder = template.ToBuilder();
builder.Sort(1, 2, null);
Assert.Equal(new[] { 2, 1, 4, 3 }, builder);
}
[Fact]
public void SortOneElementArray()
{
int[] resultantArray = new[] { 4 };
var builder1 = new ImmutableArray<int>.Builder();
builder1.Add(4);
builder1.Sort();
Assert.Equal(resultantArray, builder1);
var builder2 = new ImmutableArray<int>.Builder();
builder2.Add(4);
builder2.Sort(Comparer<int>.Default);
Assert.Equal(resultantArray, builder2);
var builder3 = new ImmutableArray<int>.Builder();
builder3.Add(4);
builder3.Sort(0, 1, Comparer<int>.Default);
Assert.Equal(resultantArray, builder3);
}
[Fact]
public void SortRange()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(2, 4, 1, 3);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Sort(-1, 2, Comparer<int>.Default));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Sort(1, 4, Comparer<int>.Default));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Sort(0, -1, Comparer<int>.Default));
builder.Sort(builder.Count, 0, Comparer<int>.Default);
Assert.Equal(new int[] { 2, 4, 1, 3 }, builder);
builder.Sort(1, 2, Comparer<int>.Default);
Assert.Equal(new[] { 2, 1, 4, 3 }, builder);
}
[Fact]
public void SortComparer()
{
var builder1 = new ImmutableArray<string>.Builder();
var builder2 = new ImmutableArray<string>.Builder();
builder1.AddRange("c", "B", "a");
builder2.AddRange("c", "B", "a");
builder1.Sort(StringComparer.OrdinalIgnoreCase);
builder2.Sort(StringComparer.Ordinal);
Assert.Equal(new[] { "a", "B", "c" }, builder1);
Assert.Equal(new[] { "B", "a", "c" }, builder2);
}
[Fact]
public void Count()
{
var builder = new ImmutableArray<int>.Builder(3);
// Initial count is at zero, which is less than capacity.
Assert.Equal(0, builder.Count);
// Expand the accessible region of the array by increasing the count, but still below capacity.
builder.Count = 2;
Assert.Equal(2, builder.Count);
Assert.Equal(2, builder.ToList().Count);
Assert.Equal(0, builder[0]);
Assert.Equal(0, builder[1]);
Assert.Throws<IndexOutOfRangeException>(() => builder[2]);
// Expand the accessible region of the array beyond the current capacity.
builder.Count = 4;
Assert.Equal(4, builder.Count);
Assert.Equal(4, builder.ToList().Count);
Assert.Equal(0, builder[0]);
Assert.Equal(0, builder[1]);
Assert.Equal(0, builder[2]);
Assert.Equal(0, builder[3]);
Assert.Throws<IndexOutOfRangeException>(() => builder[4]);
}
[Fact]
public void CountContract()
{
var builder = new ImmutableArray<int>.Builder(100);
builder.AddRange(Enumerable.Range(1, 100));
builder.Count = 10;
Assert.Equal(Enumerable.Range(1, 10), builder);
builder.Count = 100;
Assert.Equal(Enumerable.Range(1, 10).Concat(new int[90]), builder);
}
[Fact]
public void IndexSetter()
{
var builder = new ImmutableArray<int>.Builder();
Assert.Throws<IndexOutOfRangeException>(() => builder[0] = 1);
Assert.Throws<IndexOutOfRangeException>(() => builder[-1] = 1);
builder.Count = 1;
builder[0] = 2;
Assert.Equal(2, builder[0]);
builder.Count = 10;
builder[9] = 3;
Assert.Equal(3, builder[9]);
builder.Count = 2;
Assert.Equal(2, builder[0]);
Assert.Throws<IndexOutOfRangeException>(() => builder[2]);
}
[Fact]
public void ToImmutable()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3);
ImmutableArray<int> array = builder.ToImmutable();
Assert.Equal(1, array[0]);
Assert.Equal(2, array[1]);
Assert.Equal(3, array[2]);
// Make sure that subsequent mutation doesn't impact the immutable array.
builder[1] = 5;
Assert.Equal(5, builder[1]);
Assert.Equal(2, array[1]);
builder.Clear();
Assert.True(builder.ToImmutable().IsEmpty);
}
[Fact]
public void CopyTo()
{
var builder = ImmutableArray.Create(1, 2, 3).ToBuilder();
var target = new int[4];
builder.CopyTo(target, 1);
Assert.Equal(new[] { 0, 1, 2, 3 }, target);
AssertExtensions.Throws<ArgumentNullException>("array", () => builder.CopyTo(null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.CopyTo(target, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.CopyTo(target, 2));
}
[Fact]
public void Clear()
{
var builder = new ImmutableArray<int>.Builder(2);
builder.Add(1);
builder.Add(1);
builder.Clear();
Assert.Equal(0, builder.Count);
Assert.Throws<IndexOutOfRangeException>(() => builder[0]);
}
[Fact]
public void MutationsSucceedAfterToImmutable()
{
var builder = new ImmutableArray<int>.Builder(1);
builder.Add(1);
var immutable = builder.ToImmutable();
builder[0] = 0;
Assert.Equal(0, builder[0]);
Assert.Equal(1, immutable[0]);
}
[Fact]
public void Enumerator()
{
var empty = new ImmutableArray<int>.Builder(0);
var enumerator = empty.GetEnumerator();
Assert.False(enumerator.MoveNext());
var manyElements = new ImmutableArray<int>.Builder(3);
manyElements.AddRange(1, 2, 3);
enumerator = manyElements.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(1, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(2, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(3, enumerator.Current);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void IEnumerator()
{
var empty = new ImmutableArray<int>.Builder(0);
var enumerator = ((IEnumerable<int>)empty).GetEnumerator();
Assert.False(enumerator.MoveNext());
var manyElements = new ImmutableArray<int>.Builder(3);
manyElements.AddRange(1, 2, 3);
enumerator = ((IEnumerable<int>)manyElements).GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(1, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(2, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(3, enumerator.Current);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void MoveToImmutableNormal()
{
var builder = CreateBuilderWithCount<string>(2);
Assert.Equal(2, builder.Count);
Assert.Equal(2, builder.Capacity);
builder[1] = "b";
builder[0] = "a";
var array = builder.MoveToImmutable();
Assert.Equal(new[] { "a", "b" }, array);
Assert.Equal(0, builder.Count);
Assert.Equal(0, builder.Capacity);
}
[Fact]
public void MoveToImmutableRepeat()
{
var builder = CreateBuilderWithCount<string>(2);
builder[0] = "a";
builder[1] = "b";
var array1 = builder.MoveToImmutable();
var array2 = builder.MoveToImmutable();
Assert.Equal(new[] { "a", "b" }, array1);
Assert.Equal(0, array2.Length);
}
[Fact]
public void MoveToImmutablePartialFill()
{
var builder = ImmutableArray.CreateBuilder<int>(4);
builder.Add(42);
builder.Add(13);
Assert.Equal(4, builder.Capacity);
Assert.Equal(2, builder.Count);
Assert.Throws<InvalidOperationException>(() => builder.MoveToImmutable());
}
[Fact]
public void MoveToImmutablePartialFillWithCountUpdate()
{
var builder = ImmutableArray.CreateBuilder<int>(4);
builder.Add(42);
builder.Add(13);
Assert.Equal(4, builder.Capacity);
Assert.Equal(2, builder.Count);
builder.Count = builder.Capacity;
var array = builder.MoveToImmutable();
Assert.Equal(new[] { 42, 13, 0, 0 }, array);
}
[Fact]
public void MoveToImmutableThenUse()
{
var builder = CreateBuilderWithCount<string>(2);
Assert.Equal(2, builder.MoveToImmutable().Length);
Assert.Equal(0, builder.Capacity);
builder.Add("a");
builder.Add("b");
Assert.Equal(2, builder.Count);
Assert.True(builder.Capacity >= 2);
Assert.Equal(new[] { "a", "b" }, builder.MoveToImmutable());
}
[Fact]
public void MoveToImmutableAfterClear()
{
var builder = CreateBuilderWithCount<string>(2);
builder[0] = "a";
builder[1] = "b";
builder.Clear();
Assert.Throws<InvalidOperationException>(() => builder.MoveToImmutable());
}
[Fact]
public void MoveToImmutableAddToCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3);
for (int i = 0; i < builder.Capacity; i++)
{
builder.Add(i);
}
Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable());
}
[Fact]
public void MoveToImmutableInsertToCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3);
for (int i = 0; i < builder.Capacity; i++)
{
builder.Insert(i, i);
}
Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable());
}
[Fact]
public void MoveToImmutableAddRangeToCapcity()
{
var array = new[] { 1, 2, 3, 4, 5 };
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: array.Length);
builder.AddRange(array);
Assert.Equal(array, builder.MoveToImmutable());
}
[Fact]
public void MoveToImmutableAddRemoveAddToCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3);
for (int i = 0; i < builder.Capacity; i++)
{
builder.Add(i);
builder.RemoveAt(i);
builder.Add(i);
}
Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable());
}
[Fact]
public void CapacitySetToZero()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10);
builder.Capacity = 0;
Assert.Equal(0, builder.Capacity);
Assert.Equal(new int[] { }, builder.ToArray());
}
[Fact]
public void CapacitySetToLessThanCount()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10);
builder.Add(1);
builder.Add(1);
Assert.Throws(typeof(ArgumentException), () => builder.Capacity = 1);
}
[Fact]
public void CapacitySetToCount()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10);
builder.Add(1);
builder.Add(2);
builder.Capacity = builder.Count;
Assert.Equal(2, builder.Capacity);
Assert.Equal(new[] { 1, 2 }, builder.ToArray());
}
[Fact]
public void CapacitySetToCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10);
builder.Add(1);
builder.Add(2);
builder.Capacity = builder.Capacity;
Assert.Equal(10, builder.Capacity);
Assert.Equal(new[] { 1, 2 }, builder.ToArray());
}
[Fact]
public void CapacitySetToBiggerCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10);
builder.Add(1);
builder.Add(2);
builder.Capacity = 20;
Assert.Equal(20, builder.Capacity);
Assert.Equal(2, builder.Count);
Assert.Equal(new[] { 1, 2 }, builder.ToArray());
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableArray.CreateBuilder<int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableArray.CreateBuilder<string>(4));
}
private static ImmutableArray<T>.Builder CreateBuilderWithCount<T>(int count)
{
var builder = ImmutableArray.CreateBuilder<T>(count);
builder.Count = count;
return builder;
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
var builder = new ImmutableArray<T>.Builder(contents.Length);
builder.AddRange(contents);
return builder;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Table;
using Orleans.AzureUtils;
namespace Orleans.Runtime.ReminderService
{
internal class ReminderTableEntry : TableEntity
{
public string GrainReference { get; set; } // Part of RowKey
public string ReminderName { get; set; } // Part of RowKey
public string ServiceId { get; set; } // Part of PartitionKey
public string DeploymentId { get; set; }
public string StartAt { get; set; }
public string Period { get; set; }
public string GrainRefConsistentHash { get; set; } // Part of PartitionKey
public static string ConstructRowKey(GrainReference grainRef, string reminderName)
{
var key = String.Format("{0}-{1}", grainRef.ToKeyString(), reminderName); //grainRef.ToString(), reminderName);
return AzureStorageUtils.SanitizeTableProperty(key);
}
public static string ConstructPartitionKey(Guid serviceId, GrainReference grainRef)
{
return ConstructPartitionKey(serviceId, grainRef.GetUniformHashCode());
}
public static string ConstructPartitionKey(Guid serviceId, uint number)
{
// IMPORTANT NOTE: Other code using this return data is very sensitive to format changes,
// so take great care when making any changes here!!!
// this format of partition key makes sure that the comparisons in FindReminderEntries(begin, end) work correctly
// the idea is that when converting to string, negative numbers start with 0, and positive start with 1. Now,
// when comparisons will be done on strings, this will ensure that positive numbers are always greater than negative
// string grainHash = number < 0 ? string.Format("0{0}", number.ToString("X")) : string.Format("1{0:d16}", number);
var grainHash = String.Format("{0:X8}", number);
return String.Format("{0}_{1}", ConstructServiceIdStr(serviceId), grainHash);
}
public static string ConstructServiceIdStr(Guid serviceId)
{
return serviceId.ToString();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("Reminder [");
sb.Append(" PartitionKey=").Append(PartitionKey);
sb.Append(" RowKey=").Append(RowKey);
sb.Append(" GrainReference=").Append(GrainReference);
sb.Append(" ReminderName=").Append(ReminderName);
sb.Append(" Deployment=").Append(DeploymentId);
sb.Append(" ServiceId=").Append(ServiceId);
sb.Append(" StartAt=").Append(StartAt);
sb.Append(" Period=").Append(Period);
sb.Append(" GrainRefConsistentHash=").Append(GrainRefConsistentHash);
sb.Append("]");
return sb.ToString();
}
}
internal class RemindersTableManager : AzureTableDataManager<ReminderTableEntry>
{
private const string REMINDERS_TABLE_NAME = "OrleansReminders";
public Guid ServiceId { get; private set; }
public string DeploymentId { get; private set; }
private static readonly TimeSpan initTimeout = AzureTableDefaultPolicies.TableCreationTimeout;
public static async Task<RemindersTableManager> GetManager(Guid serviceId, string deploymentId, string storageConnectionString)
{
var singleton = new RemindersTableManager(serviceId, deploymentId, storageConnectionString);
try
{
singleton.Logger.Info("Creating RemindersTableManager for service id {0} and deploymentId {1}.", serviceId, deploymentId);
await singleton.InitTableAsync()
.WithTimeout(initTimeout);
}
catch (TimeoutException te)
{
string errorMsg = $"Unable to create or connect to the Azure table in {initTimeout}";
singleton.Logger.Error(ErrorCode.AzureTable_38, errorMsg, te);
throw new OrleansException(errorMsg, te);
}
catch (Exception ex)
{
string errorMsg = $"Exception trying to create or connect to the Azure table: {ex.Message}";
singleton.Logger.Error(ErrorCode.AzureTable_39, errorMsg, ex);
throw new OrleansException(errorMsg, ex);
}
return singleton;
}
private RemindersTableManager(Guid serviceId, string deploymentId, string storageConnectionString)
: base(REMINDERS_TABLE_NAME, storageConnectionString)
{
DeploymentId = deploymentId;
ServiceId = serviceId;
}
internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(uint begin, uint end)
{
string sBegin = ReminderTableEntry.ConstructPartitionKey(ServiceId, begin);
string sEnd = ReminderTableEntry.ConstructPartitionKey(ServiceId, end);
string serviceIdStr = ReminderTableEntry.ConstructServiceIdStr(ServiceId);
if (begin < end)
{
Expression<Func<ReminderTableEntry, bool>> query =
e => String.Compare(e.PartitionKey, serviceIdStr + '_') > 0
&& String.Compare(e.PartitionKey, serviceIdStr + (char)('_' + 1)) <= 0
&& String.Compare(e.PartitionKey, sBegin) > 0
&& String.Compare(e.PartitionKey, sEnd) <= 0;
var queryResults = await ReadTableEntriesAndEtagsAsync(query);
return queryResults.ToList();
}
if (begin == end)
{
Expression<Func<ReminderTableEntry, bool>> query =
e => String.Compare(e.PartitionKey, serviceIdStr + '_') > 0
&& String.Compare(e.PartitionKey, serviceIdStr + (char)('_' + 1)) <= 0;
var queryResults = await ReadTableEntriesAndEtagsAsync(query);
return queryResults.ToList();
}
// (begin > end)
Expression<Func<ReminderTableEntry, bool>> p1Query =
e => String.Compare(e.PartitionKey, serviceIdStr + '_') > 0
&& String.Compare(e.PartitionKey, serviceIdStr + (char)('_' + 1)) <= 0
&& String.Compare(e.PartitionKey, sBegin) > 0;
Expression<Func<ReminderTableEntry, bool>> p2Query =
e => String.Compare(e.PartitionKey, serviceIdStr + '_') > 0
&& String.Compare(e.PartitionKey, serviceIdStr + (char)('_' + 1)) <= 0
&& String.Compare(e.PartitionKey, sEnd) <= 0;
var p1 = ReadTableEntriesAndEtagsAsync(p1Query);
var p2 = ReadTableEntriesAndEtagsAsync(p2Query);
IEnumerable<Tuple<ReminderTableEntry, string>>[] arr = await Task.WhenAll(p1, p2);
return arr[0].Concat(arr[1]).ToList();
}
internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(GrainReference grainRef)
{
var partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef);
Expression<Func<ReminderTableEntry, bool>> query =
e => e.PartitionKey == partitionKey
&& String.Compare(e.RowKey, grainRef.ToKeyString() + '-') > 0
&& String.Compare(e.RowKey, grainRef.ToKeyString() + (char)('-' + 1)) <= 0;
var queryResults = await ReadTableEntriesAndEtagsAsync(query);
return queryResults.ToList();
}
internal async Task<Tuple<ReminderTableEntry, string>> FindReminderEntry(GrainReference grainRef, string reminderName)
{
string partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef);
string rowKey = ReminderTableEntry.ConstructRowKey(grainRef, reminderName);
return await ReadSingleTableEntryAsync(partitionKey, rowKey);
}
private Task<List<Tuple<ReminderTableEntry, string>>> FindAllReminderEntries()
{
return FindReminderEntries(0, 0);
}
internal async Task<string> UpsertRow(ReminderTableEntry reminderEntry)
{
try
{
return await UpsertTableEntryAsync(reminderEntry);
}
catch(Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus))
{
if (Logger.IsVerbose2) Logger.Verbose2("UpsertRow failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return null; // false;
}
throw;
}
}
internal async Task<bool> DeleteReminderEntryConditionally(ReminderTableEntry reminderEntry, string eTag)
{
try
{
await DeleteTableEntryAsync(reminderEntry, eTag);
return true;
}catch(Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus))
{
if (Logger.IsVerbose2) Logger.Verbose2("DeleteReminderEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false;
}
throw;
}
}
#region Table operations
internal async Task DeleteTableEntries()
{
if (ServiceId.Equals(Guid.Empty) && DeploymentId == null)
{
await DeleteTableAsync();
}
else
{
List<Tuple<ReminderTableEntry, string>> entries = await FindAllReminderEntries();
// return manager.DeleteTableEntries(entries); // this doesnt work as entries can be across partitions, which is not allowed
// group by grain hashcode so each query goes to different partition
var tasks = new List<Task>();
var groupedByHash = entries
.Where(tuple => tuple.Item1.ServiceId.Equals(ReminderTableEntry.ConstructServiceIdStr(ServiceId)))
.Where(tuple => tuple.Item1.DeploymentId.Equals(DeploymentId)) // delete only entries that belong to our DeploymentId.
.GroupBy(x => x.Item1.GrainRefConsistentHash).ToDictionary(g => g.Key, g => g.ToList());
foreach (var entriesPerPartition in groupedByHash.Values)
{
foreach (var batch in entriesPerPartition.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS))
{
tasks.Add(DeleteTableEntriesAsync(batch));
}
}
await Task.WhenAll(tasks);
}
}
#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.ComponentModel;
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Threading;
namespace System.ServiceModel
{
public abstract class ClientBase<TChannel> : ICommunicationObject, IDisposable
where TChannel : class
{
private TChannel _channel;
private ChannelFactory<TChannel> _channelFactory;
private object _syncRoot = new object();
private static AsyncCallback s_onAsyncCallCompleted = Fx.ThunkCallback(new AsyncCallback(OnAsyncCallCompleted));
protected ClientBase()
{
throw new PlatformNotSupportedException(SRServiceModel.ConfigurationFilesNotSupported);
}
protected ClientBase(string endpointConfigurationName)
{
throw new PlatformNotSupportedException(SRServiceModel.ConfigurationFilesNotSupported);
}
protected ClientBase(string endpointConfigurationName, string remoteAddress)
{
throw new PlatformNotSupportedException(SRServiceModel.ConfigurationFilesNotSupported);
}
protected ClientBase(string endpointConfigurationName, EndpointAddress remoteAddress)
{
throw new PlatformNotSupportedException(SRServiceModel.ConfigurationFilesNotSupported);
}
protected ClientBase(Binding binding, EndpointAddress remoteAddress)
{
if (binding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding");
if (remoteAddress == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("remoteAddress");
_channelFactory = new ChannelFactory<TChannel>(binding, remoteAddress);
_channelFactory.TraceOpenAndClose = false;
}
protected ClientBase(InstanceContext callbackInstance, Binding binding, EndpointAddress remoteAddress)
{
if (callbackInstance == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackInstance");
if (binding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding");
if (remoteAddress == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("remoteAddress");
_channelFactory = new DuplexChannelFactory<TChannel>(callbackInstance, binding, remoteAddress);
_channelFactory.TraceOpenAndClose = false;
}
protected T GetDefaultValueForInitialization<T>()
{
return default(T);
}
private object ThisLock
{
get
{
return _syncRoot;
}
}
protected TChannel Channel
{
get
{
// created on demand, so that Mort can modify .Endpoint before calling methods on the client
if (_channel == null)
{
lock (ThisLock)
{
if (_channel == null)
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, string.Format(SRServiceModel.ActivityOpenClientBase, typeof(TChannel).FullName), ActivityType.OpenClient);
}
CreateChannelInternal();
}
}
}
}
return _channel;
}
}
public ChannelFactory<TChannel> ChannelFactory
{
get
{
return _channelFactory;
}
}
public ClientCredentials ClientCredentials
{
get
{
return _channelFactory.Credentials;
}
}
public CommunicationState State
{
get
{
IChannel channel = (IChannel)_channel;
if (channel != null)
{
return channel.State;
}
else
{
// we may have failed to create the channel under open, in which case we our factory wouldn't be open
return _channelFactory.State;
}
}
}
public IClientChannel InnerChannel
{
get
{
return (IClientChannel)Channel;
}
}
public ServiceEndpoint Endpoint
{
get
{
return _channelFactory.Endpoint;
}
}
public void Open()
{
((ICommunicationObject)this).Open(_channelFactory.InternalOpenTimeout);
}
public void Abort()
{
IChannel channel = (IChannel)_channel;
if (channel != null)
{
channel.Abort();
}
_channelFactory.Abort();
}
public void Close()
{
((ICommunicationObject)this).Close(_channelFactory.InternalCloseTimeout);
}
private void CreateChannelInternal()
{
_channel = CreateChannel();
}
protected virtual TChannel CreateChannel()
{
return _channelFactory.CreateChannel();
}
void IDisposable.Dispose()
{
Close();
}
void ICommunicationObject.Open(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
_channelFactory.Open(timeoutHelper.RemainingTime());
InnerChannel.Open(timeoutHelper.RemainingTime());
}
void ICommunicationObject.Close(TimeSpan timeout)
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, string.Format(SRServiceModel.ActivityCloseClientBase, typeof(TChannel).FullName), ActivityType.Close);
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (_channel != null)
{
InnerChannel.Close(timeoutHelper.RemainingTime());
}
_channelFactory.Close(timeoutHelper.RemainingTime());
}
}
event EventHandler ICommunicationObject.Closed
{
add
{
InnerChannel.Closed += value;
}
remove
{
InnerChannel.Closed -= value;
}
}
event EventHandler ICommunicationObject.Closing
{
add
{
InnerChannel.Closing += value;
}
remove
{
InnerChannel.Closing -= value;
}
}
event EventHandler ICommunicationObject.Faulted
{
add
{
InnerChannel.Faulted += value;
}
remove
{
InnerChannel.Faulted -= value;
}
}
event EventHandler ICommunicationObject.Opened
{
add
{
InnerChannel.Opened += value;
}
remove
{
InnerChannel.Opened -= value;
}
}
event EventHandler ICommunicationObject.Opening
{
add
{
InnerChannel.Opening += value;
}
remove
{
InnerChannel.Opening -= value;
}
}
IAsyncResult ICommunicationObject.BeginClose(AsyncCallback callback, object state)
{
return ((ICommunicationObject)this).BeginClose(_channelFactory.InternalCloseTimeout, callback, state);
}
IAsyncResult ICommunicationObject.BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedAsyncResult(timeout, callback, state, BeginChannelClose, EndChannelClose, BeginFactoryClose, EndFactoryClose);
}
void ICommunicationObject.EndClose(IAsyncResult result)
{
ChainedAsyncResult.End(result);
}
IAsyncResult ICommunicationObject.BeginOpen(AsyncCallback callback, object state)
{
return ((ICommunicationObject)this).BeginOpen(_channelFactory.InternalOpenTimeout, callback, state);
}
IAsyncResult ICommunicationObject.BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedAsyncResult(timeout, callback, state, BeginFactoryOpen, EndFactoryOpen, BeginChannelOpen, EndChannelOpen);
}
void ICommunicationObject.EndOpen(IAsyncResult result)
{
ChainedAsyncResult.End(result);
}
//ChainedAsyncResult methods for opening and closing ChannelFactory<T>
internal IAsyncResult BeginFactoryOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return _channelFactory.BeginOpen(timeout, callback, state);
}
internal void EndFactoryOpen(IAsyncResult result)
{
_channelFactory.EndOpen(result);
}
internal IAsyncResult BeginChannelOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return InnerChannel.BeginOpen(timeout, callback, state);
}
internal void EndChannelOpen(IAsyncResult result)
{
InnerChannel.EndOpen(result);
}
internal IAsyncResult BeginFactoryClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return _channelFactory.BeginClose(timeout, callback, state);
}
internal void EndFactoryClose(IAsyncResult result)
{
if (typeof(CompletedAsyncResult).IsAssignableFrom(result.GetType()))
{
CompletedAsyncResult.End(result);
}
else
{
_channelFactory.EndClose(result);
}
}
internal IAsyncResult BeginChannelClose(TimeSpan timeout, AsyncCallback callback, object state)
{
if (_channel != null)
{
return InnerChannel.BeginClose(timeout, callback, state);
}
else
{
return new CompletedAsyncResult(callback, state);
}
}
internal void EndChannelClose(IAsyncResult result)
{
if (typeof(CompletedAsyncResult).IsAssignableFrom(result.GetType()))
{
CompletedAsyncResult.End(result);
}
else
{
InnerChannel.EndClose(result);
}
}
// WARNING: changes in the signature/name of the following delegates must be applied to the
// ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code.
protected delegate IAsyncResult BeginOperationDelegate(object[] inValues, AsyncCallback asyncCallback, object state);
protected delegate object[] EndOperationDelegate(IAsyncResult result);
// WARNING: Any changes in the signature/name of the following type and its ctor must be applied to the
// ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code.
protected class InvokeAsyncCompletedEventArgs : AsyncCompletedEventArgs
{
private object[] _results;
internal InvokeAsyncCompletedEventArgs(object[] results, Exception error, bool cancelled, object userState)
: base(error, cancelled, userState)
{
_results = results;
}
public object[] Results
{
get
{
return _results;
}
}
}
// WARNING: Any changes in the signature/name of the following method ctor must be applied to the
// ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code.
protected void InvokeAsync(BeginOperationDelegate beginOperationDelegate, object[] inValues,
EndOperationDelegate endOperationDelegate, SendOrPostCallback operationCompletedCallback, object userState)
{
if (beginOperationDelegate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("beginOperationDelegate");
}
if (endOperationDelegate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endOperationDelegate");
}
AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(userState);
AsyncOperationContext context = new AsyncOperationContext(asyncOperation, endOperationDelegate, operationCompletedCallback);
Exception error = null;
object[] results = null;
IAsyncResult result = null;
try
{
result = beginOperationDelegate(inValues, s_onAsyncCallCompleted, context);
if (result.CompletedSynchronously)
{
results = endOperationDelegate(result);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
error = e;
}
if (error != null || result.CompletedSynchronously) /* result cannot be null if error == null */
{
CompleteAsyncCall(context, results, error);
}
}
private static void OnAsyncCallCompleted(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
AsyncOperationContext context = (AsyncOperationContext)result.AsyncState;
Exception error = null;
object[] results = null;
try
{
results = context.EndDelegate(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
error = e;
}
CompleteAsyncCall(context, results, error);
}
private static void CompleteAsyncCall(AsyncOperationContext context, object[] results, Exception error)
{
if (context.CompletionCallback != null)
{
InvokeAsyncCompletedEventArgs e = new InvokeAsyncCompletedEventArgs(results, error, false, context.AsyncOperation.UserSuppliedState);
context.AsyncOperation.PostOperationCompleted(context.CompletionCallback, e);
}
else
{
context.AsyncOperation.OperationCompleted();
}
}
protected class AsyncOperationContext
{
private AsyncOperation _asyncOperation;
private EndOperationDelegate _endDelegate;
private SendOrPostCallback _completionCallback;
internal AsyncOperationContext(AsyncOperation asyncOperation, EndOperationDelegate endDelegate, SendOrPostCallback completionCallback)
{
_asyncOperation = asyncOperation;
_endDelegate = endDelegate;
_completionCallback = completionCallback;
}
internal AsyncOperation AsyncOperation
{
get
{
return _asyncOperation;
}
}
internal EndOperationDelegate EndDelegate
{
get
{
return _endDelegate;
}
}
internal SendOrPostCallback CompletionCallback
{
get
{
return _completionCallback;
}
}
}
protected class ChannelBase<T> : IClientChannel, IOutputChannel, IRequestChannel, IChannelBaseProxy
where T : class
{
private ServiceChannel _channel;
private System.ServiceModel.Dispatcher.ImmutableClientRuntime _runtime;
protected ChannelBase(ClientBase<T> client)
{
if (client.Endpoint.Address == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.SFxChannelFactoryEndpointAddressUri));
}
ChannelFactory<T> cf = client._channelFactory;
cf.EnsureOpened(); // to prevent the NullReferenceException that is thrown if the ChannelFactory is not open when cf.ServiceChannelFactory is accessed.
_channel = cf.ServiceChannelFactory.CreateServiceChannel(client.Endpoint.Address, client.Endpoint.Address.Uri);
_channel.InstanceContext = cf.CallbackInstance;
_runtime = _channel.ClientRuntime.GetRuntime();
}
protected IAsyncResult BeginInvoke(string methodName, object[] args, AsyncCallback callback, object state)
{
object[] inArgs = new object[args.Length + 2];
Array.Copy(args, inArgs, args.Length);
inArgs[inArgs.Length - 2] = callback;
inArgs[inArgs.Length - 1] = state;
MethodCall methodCall = new MethodCall(inArgs);
ProxyOperationRuntime op = GetOperationByName(methodName);
object[] ins = op.MapAsyncBeginInputs(methodCall, out callback, out state);
return _channel.BeginCall(op.Action, op.IsOneWay, op, ins, callback, state);
}
protected object EndInvoke(string methodName, object[] args, IAsyncResult result)
{
object[] inArgs = new object[args.Length + 1];
Array.Copy(args, inArgs, args.Length);
inArgs[inArgs.Length - 1] = result;
MethodCall methodCall = new MethodCall(inArgs);
ProxyOperationRuntime op = GetOperationByName(methodName);
object[] outs;
op.MapAsyncEndInputs(methodCall, out result, out outs);
object ret = _channel.EndCall(op.Action, outs, result);
object[] retArgs = op.MapAsyncOutputs(methodCall, outs, ref ret);
if (retArgs != null)
{
Fx.Assert(retArgs.Length == inArgs.Length, "retArgs.Length should be equal to inArgs.Length");
Array.Copy(retArgs, args, args.Length);
}
return ret;
}
private System.ServiceModel.Dispatcher.ProxyOperationRuntime GetOperationByName(string methodName)
{
ProxyOperationRuntime op = _runtime.GetOperationByName(methodName);
if (op == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(string.Format(SRServiceModel.SFxMethodNotSupported1, methodName)));
}
return op;
}
bool IClientChannel.AllowInitializationUI
{
get { return ((IClientChannel)_channel).AllowInitializationUI; }
set { ((IClientChannel)_channel).AllowInitializationUI = value; }
}
bool IClientChannel.DidInteractiveInitialization
{
get { return ((IClientChannel)_channel).DidInteractiveInitialization; }
}
Uri IClientChannel.Via
{
get { return ((IClientChannel)_channel).Via; }
}
event EventHandler<UnknownMessageReceivedEventArgs> IClientChannel.UnknownMessageReceived
{
add { ((IClientChannel)_channel).UnknownMessageReceived += value; }
remove { ((IClientChannel)_channel).UnknownMessageReceived -= value; }
}
void IClientChannel.DisplayInitializationUI()
{
((IClientChannel)_channel).DisplayInitializationUI();
}
IAsyncResult IClientChannel.BeginDisplayInitializationUI(AsyncCallback callback, object state)
{
return ((IClientChannel)_channel).BeginDisplayInitializationUI(callback, state);
}
void IClientChannel.EndDisplayInitializationUI(IAsyncResult result)
{
((IClientChannel)_channel).EndDisplayInitializationUI(result);
}
bool IContextChannel.AllowOutputBatching
{
get { return ((IContextChannel)_channel).AllowOutputBatching; }
set { ((IContextChannel)_channel).AllowOutputBatching = value; }
}
IInputSession IContextChannel.InputSession
{
get { return ((IContextChannel)_channel).InputSession; }
}
EndpointAddress IContextChannel.LocalAddress
{
get { return ((IContextChannel)_channel).LocalAddress; }
}
TimeSpan IContextChannel.OperationTimeout
{
get { return ((IContextChannel)_channel).OperationTimeout; }
set { ((IContextChannel)_channel).OperationTimeout = value; }
}
IOutputSession IContextChannel.OutputSession
{
get { return ((IContextChannel)_channel).OutputSession; }
}
EndpointAddress IContextChannel.RemoteAddress
{
get { return ((IContextChannel)_channel).RemoteAddress; }
}
string IContextChannel.SessionId
{
get { return ((IContextChannel)_channel).SessionId; }
}
TProperty IChannel.GetProperty<TProperty>()
{
return ((IChannel)_channel).GetProperty<TProperty>();
}
CommunicationState ICommunicationObject.State
{
get { return ((ICommunicationObject)_channel).State; }
}
event EventHandler ICommunicationObject.Closed
{
add { ((ICommunicationObject)_channel).Closed += value; }
remove { ((ICommunicationObject)_channel).Closed -= value; }
}
event EventHandler ICommunicationObject.Closing
{
add { ((ICommunicationObject)_channel).Closing += value; }
remove { ((ICommunicationObject)_channel).Closing -= value; }
}
event EventHandler ICommunicationObject.Faulted
{
add { ((ICommunicationObject)_channel).Faulted += value; }
remove { ((ICommunicationObject)_channel).Faulted -= value; }
}
event EventHandler ICommunicationObject.Opened
{
add { ((ICommunicationObject)_channel).Opened += value; }
remove { ((ICommunicationObject)_channel).Opened -= value; }
}
event EventHandler ICommunicationObject.Opening
{
add { ((ICommunicationObject)_channel).Opening += value; }
remove { ((ICommunicationObject)_channel).Opening -= value; }
}
void ICommunicationObject.Abort()
{
((ICommunicationObject)_channel).Abort();
}
void ICommunicationObject.Close()
{
((ICommunicationObject)_channel).Close();
}
void ICommunicationObject.Close(TimeSpan timeout)
{
((ICommunicationObject)_channel).Close(timeout);
}
IAsyncResult ICommunicationObject.BeginClose(AsyncCallback callback, object state)
{
return ((ICommunicationObject)_channel).BeginClose(callback, state);
}
IAsyncResult ICommunicationObject.BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return ((ICommunicationObject)_channel).BeginClose(timeout, callback, state);
}
void ICommunicationObject.EndClose(IAsyncResult result)
{
((ICommunicationObject)_channel).EndClose(result);
}
void ICommunicationObject.Open()
{
((ICommunicationObject)_channel).Open();
}
void ICommunicationObject.Open(TimeSpan timeout)
{
((ICommunicationObject)_channel).Open(timeout);
}
IAsyncResult ICommunicationObject.BeginOpen(AsyncCallback callback, object state)
{
return ((ICommunicationObject)_channel).BeginOpen(callback, state);
}
IAsyncResult ICommunicationObject.BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return ((ICommunicationObject)_channel).BeginOpen(timeout, callback, state);
}
void ICommunicationObject.EndOpen(IAsyncResult result)
{
((ICommunicationObject)_channel).EndOpen(result);
}
IExtensionCollection<IContextChannel> IExtensibleObject<IContextChannel>.Extensions
{
get { return ((IExtensibleObject<IContextChannel>)_channel).Extensions; }
}
void IDisposable.Dispose()
{
((IDisposable)_channel).Dispose();
}
Uri IOutputChannel.Via
{
get { return ((IOutputChannel)_channel).Via; }
}
EndpointAddress IOutputChannel.RemoteAddress
{
get { return ((IOutputChannel)_channel).RemoteAddress; }
}
void IOutputChannel.Send(Message message)
{
((IOutputChannel)_channel).Send(message);
}
void IOutputChannel.Send(Message message, TimeSpan timeout)
{
((IOutputChannel)_channel).Send(message, timeout);
}
IAsyncResult IOutputChannel.BeginSend(Message message, AsyncCallback callback, object state)
{
return ((IOutputChannel)_channel).BeginSend(message, callback, state);
}
IAsyncResult IOutputChannel.BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
return ((IOutputChannel)_channel).BeginSend(message, timeout, callback, state);
}
void IOutputChannel.EndSend(IAsyncResult result)
{
((IOutputChannel)_channel).EndSend(result);
}
Uri IRequestChannel.Via
{
get { return ((IRequestChannel)_channel).Via; }
}
EndpointAddress IRequestChannel.RemoteAddress
{
get { return ((IRequestChannel)_channel).RemoteAddress; }
}
Message IRequestChannel.Request(Message message)
{
return ((IRequestChannel)_channel).Request(message);
}
Message IRequestChannel.Request(Message message, TimeSpan timeout)
{
return ((IRequestChannel)_channel).Request(message, timeout);
}
IAsyncResult IRequestChannel.BeginRequest(Message message, AsyncCallback callback, object state)
{
return ((IRequestChannel)_channel).BeginRequest(message, callback, state);
}
IAsyncResult IRequestChannel.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
return ((IRequestChannel)_channel).BeginRequest(message, timeout, callback, state);
}
Message IRequestChannel.EndRequest(IAsyncResult result)
{
return ((IRequestChannel)_channel).EndRequest(result);
}
ServiceChannel IChannelBaseProxy.GetServiceChannel()
{
return _channel;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace System.Reflection.Context.Virtual
{
// Provides the base class for func-based properties and indexers
internal abstract partial class VirtualPropertyBase : PropertyInfo
{
private readonly string _name;
private readonly Type _propertyType;
private Type _declaringType;
private ParameterInfo[] _indexedParameters;
protected VirtualPropertyBase(Type propertyType, string name, CustomReflectionContext context)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException("", nameof(name));
if (propertyType == null)
throw new ArgumentNullException(nameof(propertyType));
Debug.Assert(context != null);
_propertyType = propertyType;
_name = name;
ReflectionContext = context;
}
public CustomReflectionContext ReflectionContext { get; }
public override sealed PropertyAttributes Attributes
{
get { return PropertyAttributes.None; }
}
public override sealed Type DeclaringType
{
get { return _declaringType; }
}
public override sealed string Name
{
get { return _name; }
}
public override sealed Type PropertyType
{
get { return _propertyType; }
}
public override sealed bool CanRead
{
get { return GetGetMethod(true) != null; }
}
public override sealed bool CanWrite
{
get { return GetSetMethod(true) != null; }
}
public override sealed int MetadataToken
{
get { throw new InvalidOperationException(); }
}
public override sealed Module Module
{
get { return DeclaringType.Module; }
}
public override sealed Type ReflectedType
{
get { return DeclaringType; }
}
public override sealed MethodInfo[] GetAccessors(bool nonPublic)
{
MethodInfo getMethod = GetGetMethod(nonPublic);
MethodInfo setMethod = GetSetMethod(nonPublic);
Debug.Assert(getMethod != null || setMethod != null);
if (getMethod == null || setMethod == null)
{
return new MethodInfo[] { getMethod ?? setMethod };
}
return new MethodInfo[] { getMethod, setMethod };
}
public override sealed ParameterInfo[] GetIndexParameters()
{
return (ParameterInfo[])GetIndexParametersNoCopy().Clone();
}
public override sealed object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
{
MethodInfo getMethod = GetGetMethod(true);
if (getMethod == null)
throw new ArgumentException(SR.Argument_GetMethNotFnd);
return getMethod.Invoke(obj, invokeAttr, binder, index, culture);
}
public override sealed void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
{
MethodInfo setMethod = GetSetMethod(true);
if (setMethod == null)
throw new ArgumentException(SR.Argument_GetMethNotFnd);
object[] args = null;
if (index != null)
{
args = new object[index.Length + 1];
Array.Copy(index, 0, args, 0, index.Length);
args[index.Length] = value;
}
else
{
args = new object[1];
args[0] = value;
}
setMethod.Invoke(obj, invokeAttr, binder, args, culture);
}
public override sealed object GetConstantValue()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumLitValueNotFound);
}
public override sealed object GetRawConstantValue()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumLitValueNotFound);
}
public override sealed Type[] GetOptionalCustomModifiers()
{
return CollectionServices.Empty<Type>();
}
public override sealed Type[] GetRequiredCustomModifiers()
{
return CollectionServices.Empty<Type>();
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return CollectionServices.Empty<Attribute>();
}
public override object[] GetCustomAttributes(bool inherit)
{
return CollectionServices.Empty<Attribute>();
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CollectionServices.Empty<CustomAttributeData>();
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return false;
}
public override bool Equals(object obj)
{
// We don't need to compare the getters and setters.
// But do we need to compare the contexts and return types?
return obj is VirtualPropertyBase other &&
_name == other._name &&
_declaringType.Equals(other._declaringType) &&
_propertyType == other._propertyType &&
CollectionServices.CompareArrays(GetIndexParametersNoCopy(), other.GetIndexParametersNoCopy());
}
public override int GetHashCode()
{
return _name.GetHashCode() ^
_declaringType.GetHashCode() ^
_propertyType.GetHashCode() ^
CollectionServices.GetArrayHashCode(GetIndexParametersNoCopy());
}
public override string ToString()
{
return base.ToString();
}
internal void SetDeclaringType(Type declaringType)
{
_declaringType = declaringType;
}
private ParameterInfo[] GetIndexParametersNoCopy()
{
if (_indexedParameters == null)
{
MethodInfo method = GetGetMethod(true);
if (method != null)
{
_indexedParameters = VirtualParameter.CloneParameters(this, method.GetParameters(), skipLastParameter: false);
}
else
{
method = GetSetMethod(true);
Debug.Assert(null != method);
_indexedParameters = VirtualParameter.CloneParameters(this, method.GetParameters(), skipLastParameter: true);
}
}
return _indexedParameters;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcdv = Google.Cloud.Dataproc.V1;
using sys = System;
namespace Google.Cloud.Dataproc.V1
{
/// <summary>Resource name for the <c>WorkflowTemplate</c> resource.</summary>
public sealed partial class WorkflowTemplateName : gax::IResourceName, sys::IEquatable<WorkflowTemplateName>
{
/// <summary>The possible contents of <see cref="WorkflowTemplateName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/regions/{region}/workflowTemplates/{workflow_template}</c>.
/// </summary>
ProjectRegionWorkflowTemplate = 1,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/workflowTemplates/{workflow_template}</c>.
/// </summary>
ProjectLocationWorkflowTemplate = 2,
}
private static gax::PathTemplate s_projectRegionWorkflowTemplate = new gax::PathTemplate("projects/{project}/regions/{region}/workflowTemplates/{workflow_template}");
private static gax::PathTemplate s_projectLocationWorkflowTemplate = new gax::PathTemplate("projects/{project}/locations/{location}/workflowTemplates/{workflow_template}");
/// <summary>Creates a <see cref="WorkflowTemplateName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="WorkflowTemplateName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static WorkflowTemplateName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new WorkflowTemplateName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="WorkflowTemplateName"/> with the pattern
/// <c>projects/{project}/regions/{region}/workflowTemplates/{workflow_template}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="regionId">The <c>Region</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workflowTemplateId">The <c>WorkflowTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="WorkflowTemplateName"/> constructed from the provided ids.</returns>
public static WorkflowTemplateName FromProjectRegionWorkflowTemplate(string projectId, string regionId, string workflowTemplateId) =>
new WorkflowTemplateName(ResourceNameType.ProjectRegionWorkflowTemplate, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), regionId: gax::GaxPreconditions.CheckNotNullOrEmpty(regionId, nameof(regionId)), workflowTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(workflowTemplateId, nameof(workflowTemplateId)));
/// <summary>
/// Creates a <see cref="WorkflowTemplateName"/> with the pattern
/// <c>projects/{project}/locations/{location}/workflowTemplates/{workflow_template}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workflowTemplateId">The <c>WorkflowTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="WorkflowTemplateName"/> constructed from the provided ids.</returns>
public static WorkflowTemplateName FromProjectLocationWorkflowTemplate(string projectId, string locationId, string workflowTemplateId) =>
new WorkflowTemplateName(ResourceNameType.ProjectLocationWorkflowTemplate, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), workflowTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(workflowTemplateId, nameof(workflowTemplateId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WorkflowTemplateName"/> with pattern
/// <c>projects/{project}/regions/{region}/workflowTemplates/{workflow_template}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="regionId">The <c>Region</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workflowTemplateId">The <c>WorkflowTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WorkflowTemplateName"/> with pattern
/// <c>projects/{project}/regions/{region}/workflowTemplates/{workflow_template}</c>.
/// </returns>
public static string Format(string projectId, string regionId, string workflowTemplateId) =>
FormatProjectRegionWorkflowTemplate(projectId, regionId, workflowTemplateId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WorkflowTemplateName"/> with pattern
/// <c>projects/{project}/regions/{region}/workflowTemplates/{workflow_template}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="regionId">The <c>Region</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workflowTemplateId">The <c>WorkflowTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WorkflowTemplateName"/> with pattern
/// <c>projects/{project}/regions/{region}/workflowTemplates/{workflow_template}</c>.
/// </returns>
public static string FormatProjectRegionWorkflowTemplate(string projectId, string regionId, string workflowTemplateId) =>
s_projectRegionWorkflowTemplate.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(regionId, nameof(regionId)), gax::GaxPreconditions.CheckNotNullOrEmpty(workflowTemplateId, nameof(workflowTemplateId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WorkflowTemplateName"/> with pattern
/// <c>projects/{project}/locations/{location}/workflowTemplates/{workflow_template}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workflowTemplateId">The <c>WorkflowTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WorkflowTemplateName"/> with pattern
/// <c>projects/{project}/locations/{location}/workflowTemplates/{workflow_template}</c>.
/// </returns>
public static string FormatProjectLocationWorkflowTemplate(string projectId, string locationId, string workflowTemplateId) =>
s_projectLocationWorkflowTemplate.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(workflowTemplateId, nameof(workflowTemplateId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="WorkflowTemplateName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/regions/{region}/workflowTemplates/{workflow_template}</c></description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/workflowTemplates/{workflow_template}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="workflowTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="WorkflowTemplateName"/> if successful.</returns>
public static WorkflowTemplateName Parse(string workflowTemplateName) => Parse(workflowTemplateName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="WorkflowTemplateName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/regions/{region}/workflowTemplates/{workflow_template}</c></description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/workflowTemplates/{workflow_template}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="workflowTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="WorkflowTemplateName"/> if successful.</returns>
public static WorkflowTemplateName Parse(string workflowTemplateName, bool allowUnparsed) =>
TryParse(workflowTemplateName, allowUnparsed, out WorkflowTemplateName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="WorkflowTemplateName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/regions/{region}/workflowTemplates/{workflow_template}</c></description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/workflowTemplates/{workflow_template}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="workflowTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="WorkflowTemplateName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string workflowTemplateName, out WorkflowTemplateName result) =>
TryParse(workflowTemplateName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="WorkflowTemplateName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/regions/{region}/workflowTemplates/{workflow_template}</c></description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/workflowTemplates/{workflow_template}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="workflowTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="WorkflowTemplateName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string workflowTemplateName, bool allowUnparsed, out WorkflowTemplateName result)
{
gax::GaxPreconditions.CheckNotNull(workflowTemplateName, nameof(workflowTemplateName));
gax::TemplatedResourceName resourceName;
if (s_projectRegionWorkflowTemplate.TryParseName(workflowTemplateName, out resourceName))
{
result = FromProjectRegionWorkflowTemplate(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_projectLocationWorkflowTemplate.TryParseName(workflowTemplateName, out resourceName))
{
result = FromProjectLocationWorkflowTemplate(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(workflowTemplateName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private WorkflowTemplateName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string regionId = null, string workflowTemplateId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
RegionId = regionId;
WorkflowTemplateId = workflowTemplateId;
}
/// <summary>
/// Constructs a new instance of a <see cref="WorkflowTemplateName"/> class from the component parts of pattern
/// <c>projects/{project}/regions/{region}/workflowTemplates/{workflow_template}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="regionId">The <c>Region</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workflowTemplateId">The <c>WorkflowTemplate</c> ID. Must not be <c>null</c> or empty.</param>
public WorkflowTemplateName(string projectId, string regionId, string workflowTemplateId) : this(ResourceNameType.ProjectRegionWorkflowTemplate, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), regionId: gax::GaxPreconditions.CheckNotNullOrEmpty(regionId, nameof(regionId)), workflowTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(workflowTemplateId, nameof(workflowTemplateId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Region</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string RegionId { get; }
/// <summary>
/// The <c>WorkflowTemplate</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string WorkflowTemplateId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectRegionWorkflowTemplate: return s_projectRegionWorkflowTemplate.Expand(ProjectId, RegionId, WorkflowTemplateId);
case ResourceNameType.ProjectLocationWorkflowTemplate: return s_projectLocationWorkflowTemplate.Expand(ProjectId, LocationId, WorkflowTemplateId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as WorkflowTemplateName);
/// <inheritdoc/>
public bool Equals(WorkflowTemplateName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(WorkflowTemplateName a, WorkflowTemplateName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(WorkflowTemplateName a, WorkflowTemplateName b) => !(a == b);
}
public partial class WorkflowTemplate
{
/// <summary>
/// <see cref="gcdv::WorkflowTemplateName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::WorkflowTemplateName WorkflowTemplateName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::WorkflowTemplateName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateWorkflowTemplateRequest
{
/// <summary><see cref="RegionName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public RegionName ParentAsRegionName
{
get => string.IsNullOrEmpty(Parent) ? null : RegionName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (RegionName.TryParse(Parent, out RegionName region))
{
return region;
}
if (gagr::LocationName.TryParse(Parent, out gagr::LocationName location))
{
return location;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetWorkflowTemplateRequest
{
/// <summary>
/// <see cref="gcdv::WorkflowTemplateName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::WorkflowTemplateName WorkflowTemplateName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::WorkflowTemplateName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class InstantiateWorkflowTemplateRequest
{
/// <summary>
/// <see cref="gcdv::WorkflowTemplateName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::WorkflowTemplateName WorkflowTemplateName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::WorkflowTemplateName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class InstantiateInlineWorkflowTemplateRequest
{
/// <summary><see cref="RegionName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public RegionName ParentAsRegionName
{
get => string.IsNullOrEmpty(Parent) ? null : RegionName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (RegionName.TryParse(Parent, out RegionName region))
{
return region;
}
if (gagr::LocationName.TryParse(Parent, out gagr::LocationName location))
{
return location;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class ListWorkflowTemplatesRequest
{
/// <summary><see cref="RegionName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public RegionName ParentAsRegionName
{
get => string.IsNullOrEmpty(Parent) ? null : RegionName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (RegionName.TryParse(Parent, out RegionName region))
{
return region;
}
if (gagr::LocationName.TryParse(Parent, out gagr::LocationName location))
{
return location;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteWorkflowTemplateRequest
{
/// <summary>
/// <see cref="gcdv::WorkflowTemplateName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::WorkflowTemplateName WorkflowTemplateName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::WorkflowTemplateName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.Tests
{
public class File_Copy_str_str : FileSystemTest
{
#region Utilities
public static string[] WindowsInvalidUnixValid = new string[] { " ", " ", "\n", ">", "<", "\t" };
public virtual void Copy(string source, string dest)
{
File.Copy(source, dest);
}
#endregion
#region UniversalTests
[Fact]
public void NullFileName()
{
Assert.Throws<ArgumentNullException>(() => Copy(null, "."));
Assert.Throws<ArgumentNullException>(() => Copy(".", null));
}
[Fact]
public void EmptyFileName()
{
Assert.Throws<ArgumentException>(() => Copy(string.Empty, "."));
Assert.Throws<ArgumentException>(() => Copy(".", string.Empty));
}
[Fact]
public void CopyOntoDirectory()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
Assert.Throws<IOException>(() => Copy(testFile, TestDirectory));
}
[Fact]
public void CopyOntoSelf()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
Assert.Throws<IOException>(() => Copy(testFile, testFile));
}
[Fact]
public void NonExistentPath()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Throws<FileNotFoundException>(() => Copy(GetTestFilePath(), testFile.FullName));
Assert.Throws<DirectoryNotFoundException>(() => Copy(testFile.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName())));
Assert.Throws<DirectoryNotFoundException>(() => Copy(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()), testFile.FullName));
}
else
{
Assert.Throws<FileNotFoundException>(() => Copy(GetTestFilePath(), testFile.FullName));
Assert.Throws<DirectoryNotFoundException>(() => Copy(testFile.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName())));
Assert.Throws<FileNotFoundException>(() => Copy(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()), testFile.FullName));
}
}
[Fact]
public void CopyValid()
{
string testFileSource = GetTestFilePath();
string testFileDest = GetTestFilePath();
File.Create(testFileSource).Dispose();
Copy(testFileSource, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.True(File.Exists(testFileSource));
}
[Fact]
public void ShortenLongPath()
{
string testFileSource = GetTestFilePath();
string testFileDest = Path.GetDirectoryName(testFileSource) + string.Concat(Enumerable.Repeat(Path.DirectorySeparatorChar + ".", 90).ToArray()) + Path.DirectorySeparatorChar + Path.GetFileName(testFileSource);
File.Create(testFileSource).Dispose();
Assert.Throws<IOException>(() => Copy(testFileSource, testFileDest));
}
[Fact]
public void InvalidFileNames()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
Assert.Throws<ArgumentException>(() => Copy(testFile, "\0"));
Assert.Throws<ArgumentException>(() => Copy(testFile, "*\0*"));
Assert.Throws<ArgumentException>(() => Copy("*\0*", testFile));
Assert.Throws<ArgumentException>(() => Copy("\0", testFile));
}
public static IEnumerable<object[]> CopyFileWithData_MemberData()
{
var rand = new Random();
foreach (bool readOnly in new[] { true, false })
{
foreach (int length in new[] { 0, 1, 3, 4096, 1024 * 80, 1024 * 1024 * 10 })
{
char[] data = new char[length];
for (int i = 0; i < data.Length; i++)
{
data[i] = (char)rand.Next(0, 256);
}
yield return new object[] { data, readOnly};
}
}
}
[Theory]
[MemberData(nameof(CopyFileWithData_MemberData))]
public void CopyFileWithData_MemberData(char[] data, bool readOnly)
{
string testFileSource = GetTestFilePath();
string testFileDest = GetTestFilePath();
// Write and copy file
using (StreamWriter stream = new StreamWriter(File.Create(testFileSource)))
{
stream.Write(data, 0, data.Length);
}
// Set the last write time of the source file to something a while ago
DateTime lastWriteTime = DateTime.UtcNow.Subtract(TimeSpan.FromHours(1));
File.SetLastWriteTime(testFileSource, lastWriteTime);
if (readOnly)
{
File.SetAttributes(testFileSource, FileAttributes.ReadOnly);
}
// Copy over the data
Copy(testFileSource, testFileDest);
// Ensure copy transferred written data
using (StreamReader stream = new StreamReader(File.OpenRead(testFileDest)))
{
char[] readData = new char[data.Length];
stream.Read(readData, 0, data.Length);
Assert.Equal(data, readData);
}
// Ensure last write/access time on the new file is appropriate
Assert.InRange(File.GetLastWriteTimeUtc(testFileDest), lastWriteTime.AddSeconds(-1), lastWriteTime.AddSeconds(1));
Assert.Equal(readOnly, (File.GetAttributes(testFileDest) & FileAttributes.ReadOnly) != 0);
if (readOnly)
{
File.SetAttributes(testFileSource, FileAttributes.Normal);
File.SetAttributes(testFileDest, FileAttributes.Normal);
}
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Whitespace path throws ArgumentException
public void WindowsWhitespacePath()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
foreach (string invalid in WindowsInvalidUnixValid)
{
Assert.Throws<ArgumentException>(() => Copy(testFile, invalid));
Assert.Throws<ArgumentException>(() => Copy(invalid, testFile));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace path allowed
public void UnixWhitespacePath()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
foreach (string valid in WindowsInvalidUnixValid)
{
Copy(testFile, Path.Combine(TestDirectory, valid));
Assert.True(File.Exists(testFile));
Assert.True(File.Exists(Path.Combine(TestDirectory, valid)));
}
}
#endregion
}
public class File_Copy_str_str_b : File_Copy_str_str
{
#region Utilities
public override void Copy(string source, string dest)
{
File.Copy(source, dest, false);
}
public virtual void Copy(string source, string dest, bool overwrite)
{
File.Copy(source, dest, overwrite);
}
#endregion
#region UniversalTests
[Fact]
public void OverwriteTrue()
{
string testFileSource = GetTestFilePath();
string testFileDest = GetTestFilePath();
char[] sourceData = { 'a', 'A', 'b' };
char[] destData = { 'x', 'X', 'y' };
// Write and copy file
using (StreamWriter sourceStream = new StreamWriter(File.Create(testFileSource)))
using (StreamWriter destStream = new StreamWriter(File.Create(testFileDest)))
{
sourceStream.Write(sourceData, 0, sourceData.Length);
destStream.Write(destData, 0, destData.Length);
}
Copy(testFileSource, testFileDest, true);
// Ensure copy transferred written data
using (StreamReader stream = new StreamReader(File.OpenRead(testFileDest)))
{
char[] readData = new char[sourceData.Length];
stream.Read(readData, 0, sourceData.Length);
Assert.Equal(sourceData, readData);
}
}
[Fact]
public void OverwriteFalse()
{
string testFileSource = GetTestFilePath();
string testFileDest = GetTestFilePath();
char[] sourceData = { 'a', 'A', 'b' };
char[] destData = { 'x', 'X', 'y' };
// Write and copy file
using (StreamWriter sourceStream = new StreamWriter(File.Create(testFileSource)))
using (StreamWriter destStream = new StreamWriter(File.Create(testFileDest)))
{
sourceStream.Write(sourceData, 0, sourceData.Length);
destStream.Write(destData, 0, destData.Length);
}
Assert.Throws<IOException>(() => Copy(testFileSource, testFileDest, false));
// Ensure copy didn't overwrite existing data
using (StreamReader stream = new StreamReader(File.OpenRead(testFileDest)))
{
char[] readData = new char[sourceData.Length];
stream.Read(readData, 0, sourceData.Length);
Assert.Equal(destData, readData);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void PopCount_Vector128_SByte()
{
var test = new SimpleUnaryOpTest__PopCount_Vector128_SByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__PopCount_Vector128_SByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<SByte> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__PopCount_Vector128_SByte testClass)
{
var result = AdvSimd.PopCount(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__PopCount_Vector128_SByte testClass)
{
fixed (Vector128<SByte>* pFld1 = &_fld1)
{
var result = AdvSimd.PopCount(
AdvSimd.LoadVector128((SByte*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static Vector128<SByte> _clsVar1;
private Vector128<SByte> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__PopCount_Vector128_SByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
}
public SimpleUnaryOpTest__PopCount_Vector128_SByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, new SByte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.PopCount(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.PopCount(
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.PopCount), new Type[] { typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.PopCount), new Type[] { typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.PopCount(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<SByte>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.PopCount(
AdvSimd.LoadVector128((SByte*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var result = AdvSimd.PopCount(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var result = AdvSimd.PopCount(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__PopCount_Vector128_SByte();
var result = AdvSimd.PopCount(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__PopCount_Vector128_SByte();
fixed (Vector128<SByte>* pFld1 = &test._fld1)
{
var result = AdvSimd.PopCount(
AdvSimd.LoadVector128((SByte*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.PopCount(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<SByte>* pFld1 = &_fld1)
{
var result = AdvSimd.PopCount(
AdvSimd.LoadVector128((SByte*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.PopCount(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.PopCount(
AdvSimd.LoadVector128((SByte*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<SByte> op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.BitCount(firstOp[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (Helpers.BitCount(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.PopCount)}<SByte>(Vector128<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/*
* 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 System;
using System.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client.Tests;
using Apache.Geode.Client;
[TestFixture]
[Category("group3")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientCqTest : ThinClientRegionSteps
{
public class MyCqListener<TKey, TResult> : ICqListener<TKey, TResult>
{
#region Private members
private bool m_failedOver = false;
private UInt32 m_eventCountBefore = 0;
private UInt32 m_errorCountBefore = 0;
private UInt32 m_eventCountAfter = 0;
private UInt32 m_errorCountAfter = 0;
#endregion
#region Public accessors
public void failedOver()
{
m_failedOver = true;
}
public UInt32 getEventCountBefore()
{
return m_eventCountBefore;
}
public UInt32 getErrorCountBefore()
{
return m_errorCountBefore;
}
public UInt32 getEventCountAfter()
{
return m_eventCountAfter;
}
public UInt32 getErrorCountAfter()
{
return m_errorCountAfter;
}
#endregion
public virtual void OnEvent(CqEvent<TKey, TResult> ev)
{
Util.Log("MyCqListener::OnEvent called");
if (m_failedOver == true)
m_eventCountAfter++;
else
m_eventCountBefore++;
//ISerializable val = ev.getNewValue();
//ICacheableKey key = ev.getKey();
TResult val = (TResult)ev.getNewValue();
/*ICacheableKey*/
TKey key = ev.getKey();
CqOperation opType = ev.getQueryOperation();
//CacheableString keyS = key as CacheableString;
string keyS = key.ToString(); //as string;
Portfolio pval = val as Portfolio;
PortfolioPdx pPdxVal = val as PortfolioPdx;
Assert.IsTrue((pPdxVal != null) || (pval != null));
//string opStr = "DESTROY";
/*if (opType == CqOperation.OP_TYPE_CREATE)
opStr = "CREATE";
else if (opType == CqOperation.OP_TYPE_UPDATE)
opStr = "UPDATE";*/
//Util.Log("key {0}, value ({1},{2}), op {3}.", keyS,
// pval.ID, pval.Pkid, opStr);
}
public virtual void OnError(CqEvent<TKey, TResult> ev)
{
Util.Log("MyCqListener::OnError called");
if (m_failedOver == true)
m_errorCountAfter++;
else
m_errorCountBefore++;
}
public virtual void Close()
{
Util.Log("MyCqListener::close called");
}
public virtual void Clear()
{
Util.Log("MyCqListener::Clear called");
m_eventCountBefore = 0;
m_errorCountBefore = 0;
m_eventCountAfter = 0;
m_errorCountAfter = 0;
}
}
public class MyCqListener1<TKey, TResult> : ICqListener<TKey, TResult>
{
public static UInt32 m_cntEvents = 0;
public virtual void OnEvent(CqEvent<TKey, TResult> ev)
{
m_cntEvents++;
Util.Log("MyCqListener1::OnEvent called");
Object val = (Object)ev.getNewValue();
Object pkey = (Object)ev.getKey();
int value = (int)val;
int key = (int)pkey;
CqOperation opType = ev.getQueryOperation();
String opStr = "Default";
if (opType == CqOperation.OP_TYPE_CREATE)
opStr = "CREATE";
else if (opType == CqOperation.OP_TYPE_UPDATE)
opStr = "UPDATE";
Util.Log("MyCqListener1::OnEvent called with {0} , key = {1}, value = {2} ",
opStr, key, value);
}
public virtual void OnError(CqEvent<TKey, TResult> ev)
{
Util.Log("MyCqListener1::OnError called");
}
public virtual void Close()
{
Util.Log("MyCqListener1::close called");
}
}
public class MyCqStatusListener<TKey, TResult> : ICqStatusListener<TKey, TResult>
{
#region Private members
private bool m_failedOver = false;
private UInt32 m_eventCountBefore = 0;
private UInt32 m_errorCountBefore = 0;
private UInt32 m_eventCountAfter = 0;
private UInt32 m_errorCountAfter = 0;
private UInt32 m_CqConnectedCount = 0;
private UInt32 m_CqDisConnectedCount = 0;
#endregion
#region Public accessors
public MyCqStatusListener(int id)
{
}
public void failedOver()
{
m_failedOver = true;
}
public UInt32 getEventCountBefore()
{
return m_eventCountBefore;
}
public UInt32 getErrorCountBefore()
{
return m_errorCountBefore;
}
public UInt32 getEventCountAfter()
{
return m_eventCountAfter;
}
public UInt32 getErrorCountAfter()
{
return m_errorCountAfter;
}
public UInt32 getCqConnectedCount()
{
return m_CqConnectedCount;
}
public UInt32 getCqDisConnectedCount()
{
return m_CqDisConnectedCount;
}
#endregion
public virtual void OnEvent(CqEvent<TKey, TResult> ev)
{
Util.Log("MyCqStatusListener::OnEvent called");
if (m_failedOver == true)
m_eventCountAfter++;
else
m_eventCountBefore++;
TResult val = (TResult)ev.getNewValue();
TKey key = ev.getKey();
CqOperation opType = ev.getQueryOperation();
string keyS = key.ToString(); //as string;
}
public virtual void OnError(CqEvent<TKey, TResult> ev)
{
Util.Log("MyCqStatusListener::OnError called");
if (m_failedOver == true)
m_errorCountAfter++;
else
m_errorCountBefore++;
}
public virtual void Close()
{
Util.Log("MyCqStatusListener::close called");
}
public virtual void OnCqConnected()
{
m_CqConnectedCount++;
Util.Log("MyCqStatusListener::OnCqConnected called");
}
public virtual void OnCqDisconnected()
{
m_CqDisConnectedCount++;
Util.Log("MyCqStatusListener::OnCqDisconnected called");
}
public virtual void Clear()
{
Util.Log("MyCqStatusListener::Clear called");
m_eventCountBefore = 0;
m_errorCountBefore = 0;
m_eventCountAfter = 0;
m_errorCountAfter = 0;
m_CqConnectedCount = 0;
m_CqDisConnectedCount = 0;
}
}
#region Private members
private static bool m_usePdxObjects = false;
private UnitProcess m_client1;
private UnitProcess m_client2;
private static string[] QueryRegionNames = { "Portfolios", "Positions", "Portfolios2",
"Portfolios3" };
private static string QERegionName = "Portfolios";
private static string CqName = "MyCq";
private static string CqName1 = "testCQAllServersLeave";
private static string CqName2 = "testCQAllServersLeave1";
private static string CqQuery1 = "select * from /DistRegionAck";
private static string CqQuery2 = "select * from /DistRegionAck1";
//private static string CqName1 = "MyCq1";
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
return new ClientBase[] { m_client1, m_client2 };
}
[TestFixtureSetUp]
public override void InitTests()
{
base.InitTests();
m_client1.Call(InitClient);
m_client2.Call(InitClient);
}
[TearDown]
public override void EndTest()
{
CacheHelper.StopJavaServers();
base.EndTest();
}
public void InitClient()
{
CacheHelper.Init();
try
{
CacheHelper.DCache.TypeRegistry.RegisterType(Portfolio.CreateDeserializable, 8);
CacheHelper.DCache.TypeRegistry.RegisterType(Position.CreateDeserializable, 7);
}
catch (IllegalStateException)
{
// ignore since we run multiple iterations for pool and non pool configs
}
}
public void StepOne(string locators)
{
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[0], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[1], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[2], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[3], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>("DistRegionAck", true, true,
null, locators, "__TESTPOOL1_", true);
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
Apache.Geode.Client.RegionAttributes<object, object> regattrs = region.Attributes;
region.CreateSubRegion(QueryRegionNames[1], regattrs);
}
public void StepTwo(bool usePdxObject)
{
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
IRegion<object, object> subRegion0 = region0.GetSubRegion(QueryRegionNames[1]);
IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(QueryRegionNames[1]);
IRegion<object, object> region2 = CacheHelper.GetRegion<object, object>(QueryRegionNames[2]);
IRegion<object, object> region3 = CacheHelper.GetRegion<object, object>(QueryRegionNames[3]);
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
Util.Log("Object type is pdx = " + m_usePdxObjects);
Util.Log("SetSize {0}, NumSets {1}.", qh.PortfolioSetSize,
qh.PortfolioNumSets);
if (!usePdxObject)
{
qh.PopulatePortfolioData(region0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePositionData(subRegion0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePositionData(region1, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioData(region2, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioData(region3, qh.PortfolioSetSize,
qh.PortfolioNumSets);
}
else
{
CacheHelper.DCache.TypeRegistry.RegisterPdxType(PortfolioPdx.CreateDeserializable);
CacheHelper.DCache.TypeRegistry.RegisterPdxType(PositionPdx.CreateDeserializable);
qh.PopulatePortfolioPdxData(region0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioPdxData(subRegion0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioPdxData(region1, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioPdxData(region2, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioPdxData(region3, qh.PortfolioSetSize,
qh.PortfolioNumSets);
}
}
public void StepTwoQT()
{
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
IRegion<object, object> subRegion0 = region0.GetSubRegion(QueryRegionNames[1]);
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
qh.PopulatePortfolioData(region0, 100, 20, 100);
qh.PopulatePositionData(subRegion0, 100, 20);
}
public void StepOneQE(string locators)
{
CacheHelper.CreateTCRegion_Pool<object, object>(QERegionName, true, true,
null, locators, "__TESTPOOL1_", true);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QERegionName);
Portfolio p1 = new Portfolio(1, 100);
Portfolio p2 = new Portfolio(2, 100);
Portfolio p3 = new Portfolio(3, 100);
Portfolio p4 = new Portfolio(4, 100);
region["1"] = p1;
region["2"] = p2;
region["3"] = p3;
region["4"] = p4;
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>();
ICqListener<object, object> cqLstner = new MyCqListener<object, object>();
cqFac.AddCqListener(cqLstner);
CqAttributes<object, object> cqAttr = cqFac.Create();
CqQuery<object, object> qry = qs.NewCq(CqName, "select * from /" + QERegionName + " p where p.ID!=2", cqAttr, false);
qry.Execute();
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
region["4"] = p1;
region["3"] = p2;
region["2"] = p3;
region["1"] = p4;
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry = qs.GetCq<object, object>(CqName);
CqServiceStatistics cqSvcStats = qs.GetCqStatistics();
Assert.AreEqual(1, cqSvcStats.numCqsActive());
Assert.AreEqual(1, cqSvcStats.numCqsCreated());
Assert.AreEqual(1, cqSvcStats.numCqsOnClient());
cqAttr = qry.GetCqAttributes();
ICqListener<object, object>[] vl = cqAttr.getCqListeners();
Assert.IsNotNull(vl);
Assert.AreEqual(1, vl.Length);
cqLstner = vl[0];
Assert.IsNotNull(cqLstner);
MyCqListener<object, object> myLisner = (MyCqListener<object, object>)cqLstner;// as MyCqListener<object, object>;
Util.Log("event count:{0}, error count {1}.", myLisner.getEventCountBefore(), myLisner.getErrorCountBefore());
CqStatistics cqStats = qry.GetStatistics();
Assert.AreEqual(cqStats.numEvents(), myLisner.getEventCountBefore());
if (myLisner.getEventCountBefore() + myLisner.getErrorCountBefore() == 0)
{
Assert.Fail("cq before count zero");
}
qry.Stop();
Assert.AreEqual(1, cqSvcStats.numCqsStopped());
qry.Close();
Assert.AreEqual(1, cqSvcStats.numCqsClosed());
// Bring down the region
region.GetLocalView().DestroyRegion();
}
public void StepOnePdxQE(string locators)
{
CacheHelper.CreateTCRegion_Pool<object, object>(QERegionName, true, true,
null, locators, "__TESTPOOL1_", true);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QERegionName);
PortfolioPdx p1 = new PortfolioPdx(1, 100);
PortfolioPdx p2 = new PortfolioPdx(2, 100);
PortfolioPdx p3 = new PortfolioPdx(3, 100);
PortfolioPdx p4 = new PortfolioPdx(4, 100);
region["1"] = p1;
region["2"] = p2;
region["3"] = p3;
region["4"] = p4;
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>();
ICqListener<object, object> cqLstner = new MyCqListener<object, object>();
cqFac.AddCqListener(cqLstner);
CqAttributes<object, object> cqAttr = cqFac.Create();
CqQuery<object, object> qry = qs.NewCq(CqName, "select * from /" + QERegionName + " p where p.ID!=2", cqAttr, false);
qry.Execute();
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
region["4"] = p1;
region["3"] = p2;
region["2"] = p3;
region["1"] = p4;
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry = qs.GetCq<object, object>(CqName);
CqServiceStatistics cqSvcStats = qs.GetCqStatistics();
Assert.AreEqual(1, cqSvcStats.numCqsActive());
Assert.AreEqual(1, cqSvcStats.numCqsCreated());
Assert.AreEqual(1, cqSvcStats.numCqsOnClient());
cqAttr = qry.GetCqAttributes();
ICqListener<object, object>[] vl = cqAttr.getCqListeners();
Assert.IsNotNull(vl);
Assert.AreEqual(1, vl.Length);
cqLstner = vl[0];
Assert.IsNotNull(cqLstner);
MyCqListener<object, object> myLisner = (MyCqListener<object, object>)cqLstner;// as MyCqListener<object, object>;
Util.Log("event count:{0}, error count {1}.", myLisner.getEventCountBefore(), myLisner.getErrorCountBefore());
CqStatistics cqStats = qry.GetStatistics();
Assert.AreEqual(cqStats.numEvents(), myLisner.getEventCountBefore());
if (myLisner.getEventCountBefore() + myLisner.getErrorCountBefore() == 0)
{
Assert.Fail("cq before count zero");
}
qry.Stop();
Assert.AreEqual(1, cqSvcStats.numCqsStopped());
qry.Close();
Assert.AreEqual(1, cqSvcStats.numCqsClosed());
// Bring down the region
region.GetLocalView().DestroyRegion();
}
public void KillServer()
{
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
}
public delegate void KillServerDelegate();
/*
public void StepOneFailover()
{
// This is here so that Client1 registers information of the cacheserver
// that has been already started
CacheHelper.SetupJavaServers("remotequery.xml",
"cqqueryfailover.xml");
CacheHelper.StartJavaServer(1, "GFECS1");
Util.Log("Cacheserver 1 started.");
CacheHelper.CreateTCRegion(QueryRegionNames[0], true, true, null, true);
Region region = CacheHelper.GetVerifyRegion(QueryRegionNames[0]);
Portfolio p1 = new Portfolio(1, 100);
Portfolio p2 = new Portfolio(2, 200);
Portfolio p3 = new Portfolio(3, 300);
Portfolio p4 = new Portfolio(4, 400);
region.Put("1", p1);
region.Put("2", p2);
region.Put("3", p3);
region.Put("4", p4);
}
*/
/*
public void StepTwoFailover()
{
CacheHelper.StartJavaServer(2, "GFECS2");
Util.Log("Cacheserver 2 started.");
IAsyncResult killRes = null;
KillServerDelegate ksd = new KillServerDelegate(KillServer);
CacheHelper.CreateTCRegion(QueryRegionNames[0], true, true, null, true);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QueryRegionNames[0]);
var qs = CacheHelper.DCache.GetQueryService();
CqAttributesFactory cqFac = new CqAttributesFactory();
ICqListener cqLstner = new MyCqListener();
cqFac.AddCqListener(cqLstner);
CqAttributes cqAttr = cqFac.Create();
CqQuery qry = qs.NewCq(CqName1, "select * from /" + QERegionName + " p where p.ID!<4", cqAttr, true);
qry.Execute();
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry = qs.GetCq(CqName1);
cqAttr = qry.GetCqAttributes();
ICqListener[] vl = cqAttr.getCqListeners();
Assert.IsNotNull(vl);
Assert.AreEqual(1, vl.Length);
cqLstner = vl[0];
Assert.IsNotNull(cqLstner);
MyCqListener myLisner = cqLstner as MyCqListener;
if (myLisner.getEventCountAfter() + myLisner.getErrorCountAfter() != 0)
{
Assert.Fail("cq after count not zero");
}
killRes = ksd.BeginInvoke(null, null);
Thread.Sleep(18000); // sleep 0.3min to allow failover complete
myLisner.failedOver();
Portfolio p1 = new Portfolio(1, 100);
Portfolio p2 = new Portfolio(2, 200);
Portfolio p3 = new Portfolio(3, 300);
Portfolio p4 = new Portfolio(4, 400);
region.Put("4", p1);
region.Put("3", p2);
region.Put("2", p3);
region.Put("1", p4);
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry = qs.GetCq(CqName1);
cqAttr = qry.GetCqAttributes();
vl = cqAttr.getCqListeners();
cqLstner = vl[0];
Assert.IsNotNull(vl);
Assert.AreEqual(1, vl.Length);
cqLstner = vl[0];
Assert.IsNotNull(cqLstner);
myLisner = cqLstner as MyCqListener;
if (myLisner.getEventCountAfter() + myLisner.getErrorCountAfter() == 0)
{
Assert.Fail("no cq after failover");
}
killRes.AsyncWaitHandle.WaitOne();
ksd.EndInvoke(killRes);
qry.Stop();
qry.Close();
}
*/
public void ProcessCQ(string locators)
{
CacheHelper.CreateTCRegion_Pool<object, object>(QERegionName, true, true,
null, locators, "__TESTPOOL1_", true);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QERegionName);
Portfolio p1 = new Portfolio(1, 100);
Portfolio p2 = new Portfolio(2, 100);
Portfolio p3 = new Portfolio(3, 100);
Portfolio p4 = new Portfolio(4, 100);
region["1"] = p1;
region["2"] = p2;
region["3"] = p3;
region["4"] = p4;
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>();
ICqListener<object, object> cqLstner = new MyCqListener<object, object>();
ICqStatusListener<object, object> cqStatusLstner = new MyCqStatusListener<object, object>(1);
ICqListener<object, object>[] v = new ICqListener<object, object>[2];
cqFac.AddCqListener(cqLstner);
v[0] = cqLstner;
v[1] = cqStatusLstner;
cqFac.InitCqListeners(v);
Util.Log("InitCqListeners called");
CqAttributes<object, object> cqAttr = cqFac.Create();
CqQuery<object, object> qry1 = qs.NewCq("CQ1", "select * from /" + QERegionName + " p where p.ID >= 1", cqAttr, false);
qry1.Execute();
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
region["4"] = p1;
region["3"] = p2;
region["2"] = p3;
region["1"] = p4;
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry1 = qs.GetCq<object, object>("CQ1");
cqAttr = qry1.GetCqAttributes();
ICqListener<object, object>[] vl = cqAttr.getCqListeners();
Assert.IsNotNull(vl);
Assert.AreEqual(2, vl.Length);
cqLstner = vl[0];
Assert.IsNotNull(cqLstner);
MyCqListener<object, object> myLisner = (MyCqListener<object, object>)cqLstner;// as MyCqListener<object, object>;
Util.Log("event count:{0}, error count {1}.", myLisner.getEventCountBefore(), myLisner.getErrorCountBefore());
Assert.AreEqual(4, myLisner.getEventCountBefore());
cqStatusLstner = (ICqStatusListener<object, object>)vl[1];
Assert.IsNotNull(cqStatusLstner);
MyCqStatusListener<object, object> myStatLisner = (MyCqStatusListener<object, object>)cqStatusLstner;// as MyCqStatusListener<object, object>;
Util.Log("event count:{0}, error count {1}.", myStatLisner.getEventCountBefore(), myStatLisner.getErrorCountBefore());
Assert.AreEqual(1, myStatLisner.getCqConnectedCount());
Assert.AreEqual(4, myStatLisner.getEventCountBefore());
CqAttributesMutator<object, object> mutator = qry1.GetCqAttributesMutator();
mutator.RemoveCqListener(cqLstner);
cqAttr = qry1.GetCqAttributes();
Util.Log("cqAttr.getCqListeners().Length = {0}", cqAttr.getCqListeners().Length);
Assert.AreEqual(1, cqAttr.getCqListeners().Length);
mutator.RemoveCqListener(cqStatusLstner);
cqAttr = qry1.GetCqAttributes();
Util.Log("1 cqAttr.getCqListeners().Length = {0}", cqAttr.getCqListeners().Length);
Assert.AreEqual(0, cqAttr.getCqListeners().Length);
ICqListener<object, object>[] v2 = new ICqListener<object, object>[2];
v2[0] = cqLstner;
v2[1] = cqStatusLstner;
MyCqListener<object, object> myLisner2 = (MyCqListener<object, object>)cqLstner;
myLisner2.Clear();
MyCqStatusListener<object, object> myStatLisner2 = (MyCqStatusListener<object, object>)cqStatusLstner;
myStatLisner2.Clear();
mutator.SetCqListeners(v2);
cqAttr = qry1.GetCqAttributes();
Assert.AreEqual(2, cqAttr.getCqListeners().Length);
region["4"] = p1;
region["3"] = p2;
region["2"] = p3;
region["1"] = p4;
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry1 = qs.GetCq<object, object>("CQ1");
cqAttr = qry1.GetCqAttributes();
ICqListener<object, object>[] v3 = cqAttr.getCqListeners();
Assert.IsNotNull(v3);
Assert.AreEqual(2, vl.Length);
cqLstner = v3[0];
Assert.IsNotNull(cqLstner);
myLisner2 = (MyCqListener<object, object>)cqLstner;// as MyCqListener<object, object>;
Util.Log("event count:{0}, error count {1}.", myLisner2.getEventCountBefore(), myLisner2.getErrorCountBefore());
Assert.AreEqual(4, myLisner2.getEventCountBefore());
cqStatusLstner = (ICqStatusListener<object, object>)v3[1];
Assert.IsNotNull(cqStatusLstner);
myStatLisner2 = (MyCqStatusListener<object, object>)cqStatusLstner;// as MyCqStatusListener<object, object>;
Util.Log("event count:{0}, error count {1}.", myStatLisner2.getEventCountBefore(), myStatLisner2.getErrorCountBefore());
Assert.AreEqual(0, myStatLisner2.getCqConnectedCount());
Assert.AreEqual(4, myStatLisner2.getEventCountBefore());
mutator = qry1.GetCqAttributesMutator();
mutator.RemoveCqListener(cqLstner);
cqAttr = qry1.GetCqAttributes();
Util.Log("cqAttr.getCqListeners().Length = {0}", cqAttr.getCqListeners().Length);
Assert.AreEqual(1, cqAttr.getCqListeners().Length);
mutator.RemoveCqListener(cqStatusLstner);
cqAttr = qry1.GetCqAttributes();
Util.Log("1 cqAttr.getCqListeners().Length = {0}", cqAttr.getCqListeners().Length);
Assert.AreEqual(0, cqAttr.getCqListeners().Length);
region["4"] = p1;
region["3"] = p2;
region["2"] = p3;
region["1"] = p4;
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry1 = qs.GetCq<object, object>("CQ1");
cqAttr = qry1.GetCqAttributes();
ICqListener<object, object>[] v4 = cqAttr.getCqListeners();
Assert.IsNotNull(v4);
Assert.AreEqual(0, v4.Length);
Util.Log("cqAttr.getCqListeners() done");
}
public void CreateAndExecuteCQ_StatusListener(string poolName, string cqName, string cqQuery, int id)
{
var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService();
CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>();
cqFac.AddCqListener(new MyCqStatusListener<object, object>(id));
CqAttributes<object, object> cqAttr = cqFac.Create();
CqQuery<object, object> qry = qs.NewCq(cqName, cqQuery, cqAttr, false);
qry.Execute();
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
}
public void CreateAndExecuteCQ_Listener(string poolName, string cqName, string cqQuery, int id)
{
var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService();
CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>();
cqFac.AddCqListener(new MyCqListener<object, object>(/*id*/));
CqAttributes<object, object> cqAttr = cqFac.Create();
CqQuery<object, object> qry = qs.NewCq(cqName, cqQuery, cqAttr, false);
qry.Execute();
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
}
public void CheckCQStatusOnConnect(string poolName, string cqName, int onCqStatusConnect)
{
var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService();
CqQuery<object, object> query = qs.GetCq<object, object>(cqName);
CqAttributes<object, object> cqAttr = query.GetCqAttributes();
ICqListener<object, object>[] vl = cqAttr.getCqListeners();
MyCqStatusListener<object, object> myCqStatusLstr = (MyCqStatusListener<object, object>) vl[0];
Util.Log("CheckCQStatusOnConnect = {0} ", myCqStatusLstr.getCqConnectedCount());
Assert.AreEqual(onCqStatusConnect, myCqStatusLstr.getCqConnectedCount());
}
public void CheckCQStatusOnDisConnect(string poolName, string cqName, int onCqStatusDisConnect)
{
var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService();
CqQuery<object, object> query = qs.GetCq<object, object>(cqName);
CqAttributes<object, object> cqAttr = query.GetCqAttributes();
ICqListener<object, object>[] vl = cqAttr.getCqListeners();
MyCqStatusListener<object, object> myCqStatusLstr = (MyCqStatusListener<object, object>)vl[0];
Util.Log("CheckCQStatusOnDisConnect = {0} ", myCqStatusLstr.getCqDisConnectedCount());
Assert.AreEqual(onCqStatusDisConnect, myCqStatusLstr.getCqDisConnectedCount());
}
public void PutEntries(string regionName)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
for (int i = 1; i <= 10; i++) {
region["key-" + i] = "val-" + i;
}
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
}
public void CheckCQStatusOnPutEvent(string poolName, string cqName, int onCreateCount)
{
var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService();
CqQuery<object, object> query = qs.GetCq<object, object>(cqName);
CqAttributes<object, object> cqAttr = query.GetCqAttributes();
ICqListener<object, object>[] vl = cqAttr.getCqListeners();
MyCqStatusListener<object, object> myCqStatusLstr = (MyCqStatusListener<object, object>)vl[0];
Util.Log("CheckCQStatusOnPutEvent = {0} ", myCqStatusLstr.getEventCountBefore());
Assert.AreEqual(onCreateCount, myCqStatusLstr.getEventCountBefore());
}
public void CreateRegion(string locators, string servergroup, string regionName, string poolName)
{
CacheHelper.CreateTCRegion_Pool<object, object>(regionName, true, true,
null, locators, poolName, true, servergroup);
}
void runCqQueryTest()
{
CacheHelper.SetupJavaServers(true, "remotequeryN.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(StepOne, CacheHelper.Locators);
Util.Log("StepOne complete.");
m_client1.Call(StepTwo, m_usePdxObjects);
Util.Log("StepTwo complete.");
if (!m_usePdxObjects)
m_client1.Call(StepOneQE, CacheHelper.Locators);
else
m_client1.Call(StepOnePdxQE, CacheHelper.Locators);
Util.Log("StepOne complete.");
m_client1.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
[Test]
public void CqQueryTest()
{
runCqQueryTest();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type T with 2 columns and 4 rows.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct gmat2x4<T> : IEnumerable<T>, IEquatable<gmat2x4<T>>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
public T m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
public T m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
public T m02;
/// <summary>
/// Column 0, Rows 3
/// </summary>
public T m03;
/// <summary>
/// Column 1, Rows 0
/// </summary>
public T m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
public T m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
public T m12;
/// <summary>
/// Column 1, Rows 3
/// </summary>
public T m13;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public gmat2x4(T m00, T m01, T m02, T m03, T m10, T m11, T m12, T m13)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m03 = m03;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
this.m13 = m13;
}
/// <summary>
/// Constructs this matrix from a gmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2x4(gmat2<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = default(T);
this.m03 = default(T);
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = default(T);
this.m13 = default(T);
}
/// <summary>
/// Constructs this matrix from a gmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2x4(gmat3x2<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = default(T);
this.m03 = default(T);
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = default(T);
this.m13 = default(T);
}
/// <summary>
/// Constructs this matrix from a gmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2x4(gmat4x2<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = default(T);
this.m03 = default(T);
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = default(T);
this.m13 = default(T);
}
/// <summary>
/// Constructs this matrix from a gmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2x4(gmat2x3<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = default(T);
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = default(T);
}
/// <summary>
/// Constructs this matrix from a gmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2x4(gmat3<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = default(T);
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = default(T);
}
/// <summary>
/// Constructs this matrix from a gmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2x4(gmat4x3<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = default(T);
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = default(T);
}
/// <summary>
/// Constructs this matrix from a gmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2x4(gmat2x4<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a gmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2x4(gmat3x4<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a gmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2x4(gmat4<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2x4(gvec2<T> c0, gvec2<T> c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = default(T);
this.m03 = default(T);
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = default(T);
this.m13 = default(T);
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2x4(gvec3<T> c0, gvec3<T> c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = default(T);
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = default(T);
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2x4(gvec4<T> c0, gvec4<T> c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = c0.w;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = c1.w;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public T[,] Values => new[,] { { m00, m01, m02, m03 }, { m10, m11, m12, m13 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public T[] Values1D => new[] { m00, m01, m02, m03, m10, m11, m12, m13 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public gvec4<T> Column0
{
get
{
return new gvec4<T>(m00, m01, m02, m03);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
m03 = value.w;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public gvec4<T> Column1
{
get
{
return new gvec4<T>(m10, m11, m12, m13);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
m13 = value.w;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public gvec2<T> Row0
{
get
{
return new gvec2<T>(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public gvec2<T> Row1
{
get
{
return new gvec2<T>(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public gvec2<T> Row2
{
get
{
return new gvec2<T>(m02, m12);
}
set
{
m02 = value.x;
m12 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 3
/// </summary>
public gvec2<T> Row3
{
get
{
return new gvec2<T>(m03, m13);
}
set
{
m03 = value.x;
m13 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static gmat2x4<T> Zero { get; } = new gmat2x4<T>(default(T), default(T), default(T), default(T), default(T), default(T), default(T), default(T));
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<T> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m03;
yield return m10;
yield return m11;
yield return m12;
yield return m13;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 4 = 8).
/// </summary>
public int Count => 8;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public T this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m03;
case 4: return m10;
case 5: return m11;
case 6: return m12;
case 7: return m13;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m03 = value; break;
case 4: this.m10 = value; break;
case 5: this.m11 = value; break;
case 6: this.m12 = value; break;
case 7: this.m13 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public T this[int col, int row]
{
get
{
return this[col * 4 + row];
}
set
{
this[col * 4 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(gmat2x4<T> rhs) => (((EqualityComparer<T>.Default.Equals(m00, rhs.m00) && EqualityComparer<T>.Default.Equals(m01, rhs.m01)) && (EqualityComparer<T>.Default.Equals(m02, rhs.m02) && EqualityComparer<T>.Default.Equals(m03, rhs.m03))) && ((EqualityComparer<T>.Default.Equals(m10, rhs.m10) && EqualityComparer<T>.Default.Equals(m11, rhs.m11)) && (EqualityComparer<T>.Default.Equals(m12, rhs.m12) && EqualityComparer<T>.Default.Equals(m13, rhs.m13))));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is gmat2x4<T> && Equals((gmat2x4<T>) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(gmat2x4<T> lhs, gmat2x4<T> rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(gmat2x4<T> lhs, gmat2x4<T> rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((((((EqualityComparer<T>.Default.GetHashCode(m00)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m01)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m02)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m03)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m10)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m11)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m12)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m13);
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public gmat4x2<T> Transposed => new gmat4x2<T>(m00, m10, m01, m11, m02, m12, m03, m13);
}
}
| |
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
using Parse.Core.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Parse.Common.Internal;
namespace Parse {
/// <summary>
/// Represents a user for a Parse application.
/// </summary>
[ParseClassName("_User")]
public class ParseUser : ParseObject {
private static readonly IDictionary<string, IParseAuthenticationProvider> authProviders =
new Dictionary<string, IParseAuthenticationProvider>();
private static readonly HashSet<string> readOnlyKeys = new HashSet<string> {
"sessionToken", "isNew"
};
internal static IParseUserController UserController {
get {
return ParseCorePlugins.Instance.UserController;
}
}
internal static IParseCurrentUserController CurrentUserController {
get {
return ParseCorePlugins.Instance.CurrentUserController;
}
}
/// <summary>
/// Whether the ParseUser has been authenticated on this device. Only an authenticated
/// ParseUser can be saved and deleted.
/// </summary>
public bool IsAuthenticated {
get {
lock (mutex) {
return SessionToken != null &&
CurrentUser != null &&
CurrentUser.ObjectId == ObjectId;
}
}
}
/// <summary>
/// Removes a key from the object's data if it exists.
/// </summary>
/// <param name="key">The key to remove.</param>
/// <exception cref="System.ArgumentException">Cannot remove the username key.</exception>
public override void Remove(string key) {
if (key == "username") {
throw new ArgumentException("Cannot remove the username key.");
}
base.Remove(key);
}
protected override bool IsKeyMutable(string key) {
return !readOnlyKeys.Contains(key);
}
internal override void HandleSave(IObjectState serverState) {
base.HandleSave(serverState);
SynchronizeAllAuthData();
CleanupAuthData();
MutateState(mutableClone => {
mutableClone.ServerData.Remove("password");
});
}
public string SessionToken {
get {
if (State.ContainsKey("sessionToken")) {
return State["sessionToken"] as string;
}
return null;
}
}
internal static string CurrentSessionToken {
get {
Task<string> sessionTokenTask = GetCurrentSessionTokenAsync();
sessionTokenTask.Wait();
return sessionTokenTask.Result;
}
}
internal static Task<string> GetCurrentSessionTokenAsync(CancellationToken cancellationToken = default(CancellationToken)) {
return CurrentUserController.GetCurrentSessionTokenAsync(cancellationToken);
}
internal Task SetSessionTokenAsync(string newSessionToken) {
return SetSessionTokenAsync(newSessionToken, CancellationToken.None);
}
internal Task SetSessionTokenAsync(string newSessionToken, CancellationToken cancellationToken) {
MutateState(mutableClone => {
mutableClone.ServerData["sessionToken"] = newSessionToken;
});
return SaveCurrentUserAsync(this);
}
/// <summary>
/// Gets or sets the username.
/// </summary>
[ParseFieldName("username")]
public string Username {
get { return GetProperty<string>(null, "Username"); }
set { SetProperty(value, "Username"); }
}
/// <summary>
/// Sets the password.
/// </summary>
[ParseFieldName("password")]
public string Password {
private get { return GetProperty<string>(null, "Password"); }
set { SetProperty(value, "Password"); }
}
/// <summary>
/// Sets the email address.
/// </summary>
[ParseFieldName("email")]
public string Email {
get { return GetProperty<string>(null, "Email"); }
set { SetProperty(value, "Email"); }
}
internal Task SignUpAsync(Task toAwait, CancellationToken cancellationToken) {
if (AuthData == null) {
// TODO (hallucinogen): make an Extension of Task to create Task with exception/canceled.
if (string.IsNullOrEmpty(Username)) {
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.TrySetException(new InvalidOperationException("Cannot sign up user with an empty name."));
return tcs.Task;
}
if (string.IsNullOrEmpty(Password)) {
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.TrySetException(new InvalidOperationException("Cannot sign up user with an empty password."));
return tcs.Task;
}
}
if (!string.IsNullOrEmpty(ObjectId)) {
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.TrySetException(new InvalidOperationException("Cannot sign up a user that already exists."));
return tcs.Task;
}
IDictionary<string, IParseFieldOperation> currentOperations = StartSave();
return toAwait.OnSuccess(_ => {
return UserController.SignUpAsync(State, currentOperations, cancellationToken);
}).Unwrap().ContinueWith(t => {
if (t.IsFaulted || t.IsCanceled) {
HandleFailedSave(currentOperations);
} else {
var serverState = t.Result;
HandleSave(serverState);
}
return t;
}).Unwrap().OnSuccess(_ => SaveCurrentUserAsync(this)).Unwrap();
}
/// <summary>
/// Signs up a new user. This will create a new ParseUser on the server and will also persist the
/// session on disk so that you can access the user using <see cref="CurrentUser"/>. A username and
/// password must be set before calling SignUpAsync.
/// </summary>
public Task SignUpAsync() {
return SignUpAsync(CancellationToken.None);
}
/// <summary>
/// Signs up a new user. This will create a new ParseUser on the server and will also persist the
/// session on disk so that you can access the user using <see cref="CurrentUser"/>. A username and
/// password must be set before calling SignUpAsync.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
public Task SignUpAsync(CancellationToken cancellationToken) {
return taskQueue.Enqueue(toAwait => SignUpAsync(toAwait, cancellationToken),
cancellationToken);
}
/// <summary>
/// Logs in a user with a username and password. On success, this saves the session to disk so you
/// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
/// </summary>
/// <param name="username">The username to log in with.</param>
/// <param name="password">The password to log in with.</param>
/// <returns>The newly logged-in user.</returns>
public static Task<ParseUser> LogInAsync(string username, string password) {
return LogInAsync(username, password, CancellationToken.None);
}
/// <summary>
/// Logs in a user with a username and password. On success, this saves the session to disk so you
/// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
/// </summary>
/// <param name="username">The username to log in with.</param>
/// <param name="password">The password to log in with.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The newly logged-in user.</returns>
public static Task<ParseUser> LogInAsync(string username,
string password,
CancellationToken cancellationToken) {
return UserController.LogInAsync(username, password, cancellationToken).OnSuccess(t => {
ParseUser user = ParseObject.FromState<ParseUser>(t.Result, "_User");
return SaveCurrentUserAsync(user).OnSuccess(_ => user);
}).Unwrap();
}
/// <summary>
/// Logs in a user with a username and password. On success, this saves the session to disk so you
/// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
/// </summary>
/// <param name="sessionToken">The session token to authorize with</param>
/// <returns>The user if authorization was successful</returns>
public static Task<ParseUser> BecomeAsync(string sessionToken) {
return BecomeAsync(sessionToken, CancellationToken.None);
}
/// <summary>
/// Logs in a user with a username and password. On success, this saves the session to disk so you
/// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
/// </summary>
/// <param name="sessionToken">The session token to authorize with</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The user if authorization was successful</returns>
public static Task<ParseUser> BecomeAsync(string sessionToken, CancellationToken cancellationToken) {
return UserController.GetUserAsync(sessionToken, cancellationToken).OnSuccess(t => {
ParseUser user = ParseObject.FromState<ParseUser>(t.Result, "_User");
return SaveCurrentUserAsync(user).OnSuccess(_ => user);
}).Unwrap();
}
protected override Task SaveAsync(Task toAwait, CancellationToken cancellationToken) {
lock (mutex) {
if (ObjectId == null) {
throw new InvalidOperationException("You must call SignUpAsync before calling SaveAsync.");
}
return base.SaveAsync(toAwait, cancellationToken).OnSuccess(_ => {
if (!CurrentUserController.IsCurrent(this)) {
return Task.FromResult(0);
}
return SaveCurrentUserAsync(this);
}).Unwrap();
}
}
internal override Task<ParseObject> FetchAsyncInternal(Task toAwait, CancellationToken cancellationToken) {
return base.FetchAsyncInternal(toAwait, cancellationToken).OnSuccess(t => {
if (!CurrentUserController.IsCurrent(this)) {
return Task<ParseObject>.FromResult(t.Result);
}
// If this is already the current user, refresh its state on disk.
return SaveCurrentUserAsync(this).OnSuccess(_ => t.Result);
}).Unwrap();
}
/// <summary>
/// Logs out the currently logged in user session. This will remove the session from disk, log out of
/// linked services, and future calls to <see cref="CurrentUser"/> will return <c>null</c>.
/// </summary>
/// <remarks>
/// Typically, you should use <see cref="LogOutAsync()"/>, unless you are managing your own threading.
/// </remarks>
public static void LogOut() {
// TODO (hallucinogen): this will without a doubt fail in Unity. But what else can we do?
LogOutAsync().Wait();
}
/// <summary>
/// Logs out the currently logged in user session. This will remove the session from disk, log out of
/// linked services, and future calls to <see cref="CurrentUser"/> will return <c>null</c>.
/// </summary>
/// <remarks>
/// This is preferable to using <see cref="LogOut()"/>, unless your code is already running from a
/// background thread.
/// </remarks>
public static Task LogOutAsync() {
return LogOutAsync(CancellationToken.None);
}
/// <summary>
/// Logs out the currently logged in user session. This will remove the session from disk, log out of
/// linked services, and future calls to <see cref="CurrentUser"/> will return <c>null</c>.
///
/// This is preferable to using <see cref="LogOut()"/>, unless your code is already running from a
/// background thread.
/// </summary>
public static Task LogOutAsync(CancellationToken cancellationToken) {
return GetCurrentUserAsync().OnSuccess(t => {
LogOutWithProviders();
ParseUser user = t.Result;
if (user == null) {
return Task.FromResult(0);
}
return user.taskQueue.Enqueue(toAwait => user.LogOutAsync(toAwait, cancellationToken), cancellationToken);
}).Unwrap();
}
internal Task LogOutAsync(Task toAwait, CancellationToken cancellationToken) {
string oldSessionToken = SessionToken;
if (oldSessionToken == null) {
return Task.FromResult(0);
}
// Cleanup in-memory session.
MutateState(mutableClone => {
mutableClone.ServerData.Remove("sessionToken");
});
var revokeSessionTask = ParseSession.RevokeAsync(oldSessionToken, cancellationToken);
return Task.WhenAll(revokeSessionTask, CurrentUserController.LogOutAsync(cancellationToken));
}
private static void LogOutWithProviders() {
foreach (var provider in authProviders.Values) {
provider.Deauthenticate();
}
}
/// <summary>
/// Gets the currently logged in ParseUser with a valid session, either from memory or disk
/// if necessary.
/// </summary>
public static ParseUser CurrentUser {
get {
var userTask = GetCurrentUserAsync();
// TODO (hallucinogen): this will without a doubt fail in Unity. How should we fix it?
userTask.Wait();
return userTask.Result;
}
}
/// <summary>
/// Gets the currently logged in ParseUser with a valid session, either from memory or disk
/// if necessary, asynchronously.
/// </summary>
internal static Task<ParseUser> GetCurrentUserAsync() {
return GetCurrentUserAsync(CancellationToken.None);
}
/// <summary>
/// Gets the currently logged in ParseUser with a valid session, either from memory or disk
/// if necessary, asynchronously.
/// </summary>
internal static Task<ParseUser> GetCurrentUserAsync(CancellationToken cancellationToken) {
return CurrentUserController.GetAsync(cancellationToken);
}
private static Task SaveCurrentUserAsync(ParseUser user) {
return SaveCurrentUserAsync(user, CancellationToken.None);
}
private static Task SaveCurrentUserAsync(ParseUser user, CancellationToken cancellationToken) {
return CurrentUserController.SetAsync(user, cancellationToken);
}
internal static void ClearInMemoryUser() {
CurrentUserController.ClearFromMemory();
}
/// <summary>
/// Constructs a <see cref="ParseQuery{ParseUser}"/> for ParseUsers.
/// </summary>
public static ParseQuery<ParseUser> Query {
get {
return new ParseQuery<ParseUser>();
}
}
#region Legacy / Revocable Session Tokens
private static readonly object isRevocableSessionEnabledMutex = new object();
private static bool isRevocableSessionEnabled;
/// <summary>
/// Tells server to use revocable session on LogIn and SignUp, even when App's Settings
/// has "Require Revocable Session" turned off. Issues network request in background to
/// migrate the sessionToken on disk to revocable session.
/// </summary>
/// <returns>The Task that upgrades the session.</returns>
public static Task EnableRevocableSessionAsync() {
return EnableRevocableSessionAsync(CancellationToken.None);
}
/// <summary>
/// Tells server to use revocable session on LogIn and SignUp, even when App's Settings
/// has "Require Revocable Session" turned off. Issues network request in background to
/// migrate the sessionToken on disk to revocable session.
/// </summary>
/// <returns>The Task that upgrades the session.</returns>
public static Task EnableRevocableSessionAsync(CancellationToken cancellationToken) {
lock (isRevocableSessionEnabledMutex) {
isRevocableSessionEnabled = true;
}
return GetCurrentUserAsync(cancellationToken).OnSuccess(t => {
var user = t.Result;
return user.UpgradeToRevocableSessionAsync(cancellationToken);
});
}
internal static void DisableRevocableSession() {
lock (isRevocableSessionEnabledMutex) {
isRevocableSessionEnabled = false;
}
}
internal static bool IsRevocableSessionEnabled {
get {
lock (isRevocableSessionEnabledMutex) {
return isRevocableSessionEnabled;
}
}
}
internal Task UpgradeToRevocableSessionAsync() {
return UpgradeToRevocableSessionAsync(CancellationToken.None);
}
internal Task UpgradeToRevocableSessionAsync(CancellationToken cancellationToken) {
return taskQueue.Enqueue(toAwait => UpgradeToRevocableSessionAsync(toAwait, cancellationToken),
cancellationToken);
}
internal Task UpgradeToRevocableSessionAsync(Task toAwait, CancellationToken cancellationToken) {
string sessionToken = SessionToken;
return toAwait.OnSuccess(_ => {
return ParseSession.UpgradeToRevocableSessionAsync(sessionToken, cancellationToken);
}).Unwrap().OnSuccess(t => {
return SetSessionTokenAsync(t.Result);
}).Unwrap();
}
#endregion
/// <summary>
/// Requests a password reset email to be sent to the specified email address associated with the
/// user account. This email allows the user to securely reset their password on the Parse site.
/// </summary>
/// <param name="email">The email address associated with the user that forgot their password.</param>
public static Task RequestPasswordResetAsync(string email) {
return RequestPasswordResetAsync(email, CancellationToken.None);
}
/// <summary>
/// Requests a password reset email to be sent to the specified email address associated with the
/// user account. This email allows the user to securely reset their password on the Parse site.
/// </summary>
/// <param name="email">The email address associated with the user that forgot their password.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public static Task RequestPasswordResetAsync(string email,
CancellationToken cancellationToken) {
return UserController.RequestPasswordResetAsync(email, cancellationToken);
}
/// <summary>
/// Gets the authData for this user.
/// </summary>
internal IDictionary<string, IDictionary<string, object>> AuthData {
get {
IDictionary<string, IDictionary<string, object>> authData;
if (this.TryGetValue<IDictionary<string, IDictionary<string, object>>>(
"authData", out authData)) {
return authData;
}
return null;
}
private set {
this["authData"] = value;
}
}
private static IParseAuthenticationProvider GetProvider(string providerName) {
IParseAuthenticationProvider provider;
if (authProviders.TryGetValue(providerName, out provider)) {
return provider;
}
return null;
}
/// <summary>
/// Removes null values from authData (which exist temporarily for unlinking)
/// </summary>
private void CleanupAuthData() {
lock (mutex) {
if (!CurrentUserController.IsCurrent(this)) {
return;
}
var authData = AuthData;
if (authData == null) {
return;
}
foreach (var pair in new Dictionary<string, IDictionary<string, object>>(authData)) {
if (pair.Value == null) {
authData.Remove(pair.Key);
}
}
}
}
/// <summary>
/// Synchronizes authData for all providers.
/// </summary>
private void SynchronizeAllAuthData() {
lock (mutex) {
var authData = AuthData;
if (authData == null) {
return;
}
foreach (var pair in authData) {
SynchronizeAuthData(GetProvider(pair.Key));
}
}
}
private void SynchronizeAuthData(IParseAuthenticationProvider provider) {
bool restorationSuccess = false;
lock (mutex) {
var authData = AuthData;
if (authData == null || provider == null) {
return;
}
IDictionary<string, object> data;
if (authData.TryGetValue(provider.AuthType, out data)) {
restorationSuccess = provider.RestoreAuthentication(data);
}
}
if (!restorationSuccess) {
this.UnlinkFromAsync(provider.AuthType, CancellationToken.None);
}
}
internal Task LinkWithAsync(string authType, IDictionary<string, object> data, CancellationToken cancellationToken) {
return taskQueue.Enqueue(toAwait => {
var authData = AuthData;
if (authData == null) {
authData = AuthData = new Dictionary<string, IDictionary<string, object>>();
}
authData[authType] = data;
AuthData = authData;
return SaveAsync(cancellationToken);
}, cancellationToken);
}
internal Task LinkWithAsync(string authType, CancellationToken cancellationToken) {
var provider = GetProvider(authType);
return provider.AuthenticateAsync(cancellationToken)
.OnSuccess(t => LinkWithAsync(authType, t.Result, cancellationToken))
.Unwrap();
}
/// <summary>
/// Unlinks a user from a service.
/// </summary>
internal Task UnlinkFromAsync(string authType, CancellationToken cancellationToken) {
return LinkWithAsync(authType, null, cancellationToken);
}
/// <summary>
/// Checks whether a user is linked to a service.
/// </summary>
internal bool IsLinked(string authType) {
lock (mutex) {
return AuthData != null && AuthData.ContainsKey(authType) && AuthData[authType] != null;
}
}
internal static Task<ParseUser> LogInWithAsync(string authType,
IDictionary<string, object> data,
CancellationToken cancellationToken) {
ParseUser user = null;
return UserController.LogInAsync(authType, data, cancellationToken).OnSuccess(t => {
user = ParseObject.FromState<ParseUser>(t.Result, "_User");
lock (user.mutex) {
if (user.AuthData == null) {
user.AuthData = new Dictionary<string, IDictionary<string, object>>();
}
user.AuthData[authType] = data;
user.SynchronizeAllAuthData();
}
return SaveCurrentUserAsync(user);
}).Unwrap().OnSuccess(t => user);
}
internal static Task<ParseUser> LogInWithAsync(string authType,
CancellationToken cancellationToken) {
var provider = GetProvider(authType);
return provider.AuthenticateAsync(cancellationToken)
.OnSuccess(authData => LogInWithAsync(authType, authData.Result, cancellationToken))
.Unwrap();
}
internal static void RegisterProvider(IParseAuthenticationProvider provider) {
authProviders[provider.AuthType] = provider;
var curUser = ParseUser.CurrentUser;
if (curUser != null) {
curUser.SynchronizeAuthData(provider);
}
}
}
}
| |
using CommandLine;
using CommandLine.Text;
using Newtonsoft.Json;
using Microsoft.Xunit.Performance.Api;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace SoDBench
{
// A simple tree node for tracking file and directory names and sizes
// Does not have to accurately represent the true file system; only what we care about
class SizeReportingNode
{
public SizeReportingNode(string name, long? size=null, bool expand=true)
{
Name = name;
_size = size;
Expanded = expand;
}
public SizeReportingNode(FileInfo file, bool expand=true)
{
Name = file.Name;
_size = file.Length;
Expanded = expand;
}
// Builds out the tree starting from a directory
public SizeReportingNode(DirectoryInfo dir, int? reportingDepth=null)
{
Name = dir.Name;
foreach (var childDir in dir.EnumerateDirectories())
{
AddChild(new SizeReportingNode(childDir));
}
foreach (var childFile in dir.EnumerateFiles())
{
AddChild(new SizeReportingNode(childFile));
}
if (reportingDepth != null)
{
LimitReportingDepth(reportingDepth ?? 0);
}
}
// The directory containing this node
public SizeReportingNode Parent { get; set; }
// All the directories and files this node contains
public List<SizeReportingNode> Children {get; private set;} = new List<SizeReportingNode>();
// The file or directory name
public string Name { get; set; }
public bool Expanded { get; set; } = true;
// A list version of the path up to the root level we care about
public List<string> SegmentedPath {
get
{
if (Parent != null)
{
var path = Parent.SegmentedPath;
path.Add(Name);
return path;
}
return new List<string> { Name };
}
}
// The size of the file or directory
public long Size {
get
{
if (_size == null)
{
_size = 0;
foreach (var node in Children)
{
_size += node.Size;
}
}
return _size ?? 0;
}
private set
{
_size = value;
}
}
// Add the adoptee node as a child and set the adoptee's parent
public void AddChild(SizeReportingNode adoptee)
{
Children.Add(adoptee);
adoptee.Parent = this;
_size = null;
}
public void LimitReportingDepth(int depth)
{
if (depth <= 0)
{
Expanded = false;
}
foreach (var childNode in Children)
{
childNode.LimitReportingDepth(depth-1);
}
}
// Return a CSV formatted string representation of the tree
public string FormatAsCsv()
{
return FormatAsCsv(new StringBuilder()).ToString();
}
// Add to the string build a csv formatted representation of the tree
public StringBuilder FormatAsCsv(StringBuilder builder)
{
string path = String.Join(",", SegmentedPath.Select(s => Csv.Escape(s)));
builder.AppendLine($"{path},{Size}");
if (Expanded)
{
foreach (var childNode in Children)
{
childNode.FormatAsCsv(builder);
}
}
return builder;
}
private long? _size = null;
}
class Program
{
public static readonly string NugetConfig =
@"<?xml version='1.0' encoding='utf-8'?>
<configuration>
<packageSources>
<add key='nuget.org' value='https://api.nuget.org/v3/index.json' protocolVersion='3' />
<add key='myget.org/dotnet-core' value='https://dotnet.myget.org/F/dotnet-core/api/v3/index.json' protocolVersion='3' />
<add key='myget.org/aspnet-core' value='https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json' protocolVersion='3' />
</packageSources>
</configuration>";
public static readonly string[] NewTemplates = new string[] {
"console",
"classlib",
"mstest",
"xunit",
"web",
"mvc",
"razor",
"webapi",
"nugetconfig",
"webconfig",
"sln",
"page",
"viewimports",
"viewstart"
};
public static readonly string[] OperatingSystems = new string[] {
"win10-x64",
"win10-x86",
"ubuntu.16.10-x64",
"rhel.7-x64"
};
static FileInfo s_dotnetExe;
static DirectoryInfo s_sandboxDir;
static DirectoryInfo s_fallbackDir;
static DirectoryInfo s_corelibsDir;
static bool s_keepArtifacts;
static string s_targetArchitecture;
static string s_dotnetChannel;
static void Main(string[] args)
{
try
{
var options = SoDBenchOptions.Parse(args);
s_targetArchitecture = options.TargetArchitecture;
s_dotnetChannel = options.DotnetChannel;
s_keepArtifacts = options.KeepArtifacts;
if (!String.IsNullOrWhiteSpace(options.DotnetExecutable))
{
s_dotnetExe = new FileInfo(options.DotnetExecutable);
}
if (s_sandboxDir == null)
{
// Truncate the Guid used for anti-collision because a full Guid results in expanded paths over 260 chars (the Windows max)
s_sandboxDir = new DirectoryInfo(Path.Combine(Path.GetTempPath(), $"sod{Guid.NewGuid().ToString().Substring(0,13)}"));
s_sandboxDir.Create();
Console.WriteLine($"** Running inside sandbox directory: {s_sandboxDir}");
}
if (s_dotnetExe == null)
{
if(!String.IsNullOrEmpty(options.CoreLibariesDirectory))
{
Console.WriteLine($"** Using core libraries found at {options.CoreLibariesDirectory}");
s_corelibsDir = new DirectoryInfo(options.CoreLibariesDirectory);
}
else
{
var coreroot = Environment.GetEnvironmentVariable("CORE_ROOT");
if (!String.IsNullOrEmpty(coreroot) && Directory.Exists(coreroot))
{
Console.WriteLine($"** Using core libraries from CORE_ROOT at {coreroot}");
s_corelibsDir = new DirectoryInfo(coreroot);
}
else
{
Console.WriteLine("** Using default dotnet-cli core libraries");
}
}
PrintHeader("Installing Dotnet CLI");
s_dotnetExe = SetupDotnet();
}
if (s_fallbackDir == null)
{
s_fallbackDir = new DirectoryInfo(Path.Combine(s_sandboxDir.FullName, "fallback"));
s_fallbackDir.Create();
}
Console.WriteLine($"** Path to dotnet executable: {s_dotnetExe.FullName}");
PrintHeader("Starting acquisition size test");
var acquisition = GetAcquisitionSize();
PrintHeader("Running deployment size test");
var deployment = GetDeploymentSize();
var root = new SizeReportingNode("Dotnet Total");
root.AddChild(acquisition);
root.AddChild(deployment);
var formattedStr = root.FormatAsCsv();
File.WriteAllText(options.OutputFilename, formattedStr);
if (options.Verbose)
Console.WriteLine($"** CSV Output:\n{formattedStr}");
}
finally
{
if (!s_keepArtifacts && s_sandboxDir != null)
{
PrintHeader("Cleaning up sandbox directory");
s_sandboxDir.Delete(true);
s_sandboxDir = null;
}
}
}
private static void PrintHeader(string message)
{
Console.WriteLine();
Console.WriteLine("**********************************************************************");
Console.WriteLine($"** {message}");
Console.WriteLine("**********************************************************************");
}
private static SizeReportingNode GetAcquisitionSize()
{
var result = new SizeReportingNode("Acquisition Size");
// Arbitrary command to trigger first time setup
ProcessStartInfo dotnet = new ProcessStartInfo()
{
WorkingDirectory = s_sandboxDir.FullName,
FileName = s_dotnetExe.FullName,
Arguments = "new"
};
// Used to set where the packages will be unpacked to.
// There is a no gaurentee that this is a stable method, but is the only way currently to set the fallback folder location
dotnet.Environment["DOTNET_CLI_TEST_FALLBACKFOLDER"] = s_fallbackDir.FullName;
LaunchProcess(dotnet, 180000);
Console.WriteLine("\n** Measuring total size of acquired files");
result.AddChild(new SizeReportingNode(s_fallbackDir, 1));
var dotnetNode = new SizeReportingNode(s_dotnetExe.Directory);
var reportingDepths = new Dictionary<string, int>
{
{"additionalDeps", 1},
{"host", 0},
{"sdk", 2},
{"shared", 2},
{"store", 3}
};
foreach (var childNode in dotnetNode.Children)
{
int depth = 0;
if (reportingDepths.TryGetValue(childNode.Name, out depth))
{
childNode.LimitReportingDepth(depth);
}
}
result.AddChild(dotnetNode);
return result;
}
private static SizeReportingNode GetDeploymentSize()
{
// Write the NuGet.Config file
var nugetConfFile = new FileInfo(Path.Combine(s_sandboxDir.FullName, "NuGet.Config"));
File.WriteAllText(nugetConfFile.FullName, NugetConfig);
var result = new SizeReportingNode("Deployment Size");
foreach (string template in NewTemplates)
{
var templateNode = new SizeReportingNode(template);
result.AddChild(templateNode);
foreach (var os in OperatingSystems)
{
Console.WriteLine($"\n\n** Deploying {template}/{os}");
var deploymentSandbox = new DirectoryInfo(Path.Combine(s_sandboxDir.FullName, template, os));
var publishDir = new DirectoryInfo(Path.Combine(deploymentSandbox.FullName, "publish"));
deploymentSandbox.Create();
ProcessStartInfo dotnetNew = new ProcessStartInfo()
{
FileName = s_dotnetExe.FullName,
Arguments = $"new {template}",
UseShellExecute = false,
WorkingDirectory = deploymentSandbox.FullName
};
dotnetNew.Environment["DOTNET_CLI_TEST_FALLBACKFOLDER"] = s_fallbackDir.FullName;
ProcessStartInfo dotnetRestore = new ProcessStartInfo()
{
FileName = s_dotnetExe.FullName,
Arguments = $"restore --runtime {os}",
UseShellExecute = false,
WorkingDirectory = deploymentSandbox.FullName
};
dotnetRestore.Environment["DOTNET_CLI_TEST_FALLBACKFOLDER"] = s_fallbackDir.FullName;
ProcessStartInfo dotnetPublish = new ProcessStartInfo()
{
FileName = s_dotnetExe.FullName,
Arguments = $"publish -c Release --runtime {os} --output {publishDir.FullName}", // "out" is an arbitrary project name
UseShellExecute = false,
WorkingDirectory = deploymentSandbox.FullName
};
dotnetPublish.Environment["DOTNET_CLI_TEST_FALLBACKFOLDER"] = s_fallbackDir.FullName;
try
{
LaunchProcess(dotnetNew, 180000);
if (deploymentSandbox.EnumerateFiles().Any(f => f.Name.EndsWith("proj")))
{
LaunchProcess(dotnetRestore, 180000);
LaunchProcess(dotnetPublish, 180000);
}
else
{
Console.WriteLine($"** {template} does not have a project file to restore or publish");
}
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
continue;
}
// If we published this project, only report published it's size
if (publishDir.Exists)
{
var publishNode = new SizeReportingNode(publishDir, 0);
publishNode.Name = deploymentSandbox.Name;
templateNode.AddChild(publishNode);
}
else
{
templateNode.AddChild(new SizeReportingNode(deploymentSandbox, 0));
}
}
}
return result;
}
private static void DownloadDotnetInstaller()
{
var psi = new ProcessStartInfo() {
WorkingDirectory = s_sandboxDir.FullName,
FileName = @"powershell.exe",
Arguments = $"wget https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain/dotnet-install.ps1 -OutFile Dotnet-Install.ps1"
};
LaunchProcess(psi, 180000);
}
private static void InstallSharedRuntime()
{
var psi = new ProcessStartInfo() {
WorkingDirectory = s_sandboxDir.FullName,
FileName = @"powershell.exe",
Arguments = $".\\Dotnet-Install.ps1 -SharedRuntime -InstallDir .dotnet -Channel {s_dotnetChannel} -Architecture {s_targetArchitecture}"
};
LaunchProcess(psi, 180000);
}
private static void InstallDotnet()
{
var psi = new ProcessStartInfo() {
WorkingDirectory = s_sandboxDir.FullName,
FileName = @"powershell.exe",
Arguments = $".\\Dotnet-Install.ps1 -InstallDir .dotnet -Channel {s_dotnetChannel} -Architecture {s_targetArchitecture}"
};
LaunchProcess(psi, 180000);
}
private static void ModifySharedFramework()
{
// Current working directory is the <coreclr repo root>/sandbox directory.
Console.WriteLine($"** Modifying the shared framework.");
var sourcedi = s_corelibsDir;
// Get the directory containing the newest version of Microsodt.NETCore.App libraries
var targetdi = new DirectoryInfo(
new DirectoryInfo(Path.Combine(s_sandboxDir.FullName, ".dotnet", "shared", "Microsoft.NETCore.App"))
.GetDirectories("*")
.OrderBy(s => s.Name)
.Last()
.FullName);
Console.WriteLine($"| Source : {sourcedi.FullName}");
Console.WriteLine($"| Target : {targetdi.FullName}");
var compiledBinariesOfInterest = new string[] {
"clretwrc.dll",
"clrjit.dll",
"coreclr.dll",
"mscordaccore.dll",
"mscordbi.dll",
"mscorrc.debug.dll",
"mscorrc.dll",
"sos.dll",
"SOS.NETCore.dll",
"System.Private.CoreLib.dll"
};
foreach (var compiledBinaryOfInterest in compiledBinariesOfInterest)
{
foreach (FileInfo fi in targetdi.GetFiles(compiledBinaryOfInterest))
{
var sourceFilePath = Path.Combine(sourcedi.FullName, fi.Name);
var targetFilePath = Path.Combine(targetdi.FullName, fi.Name);
if (File.Exists(sourceFilePath))
{
File.Copy(sourceFilePath, targetFilePath, true);
Console.WriteLine($"| Copied file - '{fi.Name}'");
}
}
}
}
private static FileInfo SetupDotnet()
{
DownloadDotnetInstaller();
InstallSharedRuntime();
InstallDotnet();
if (s_corelibsDir != null)
{
ModifySharedFramework();
}
var dotnetExe = new FileInfo(Path.Combine(s_sandboxDir.FullName, ".dotnet", "dotnet.exe"));
Debug.Assert(dotnetExe.Exists);
return dotnetExe;
}
private static void LaunchProcess(ProcessStartInfo processStartInfo, int timeoutMilliseconds, IDictionary<string, string> environment = null)
{
Console.WriteLine();
Console.WriteLine($"{System.Security.Principal.WindowsIdentity.GetCurrent().Name}@{Environment.MachineName} \"{processStartInfo.WorkingDirectory}\"");
Console.WriteLine($"[{DateTime.Now}] $ {processStartInfo.FileName} {processStartInfo.Arguments}");
if (environment != null)
{
foreach (KeyValuePair<string, string> pair in environment)
{
if (!processStartInfo.Environment.ContainsKey(pair.Key))
processStartInfo.Environment.Add(pair.Key, pair.Value);
else
processStartInfo.Environment[pair.Key] = pair.Value;
}
}
using (var p = new Process() { StartInfo = processStartInfo })
{
p.Start();
if (p.WaitForExit(timeoutMilliseconds) == false)
{
// FIXME: What about clean/kill child processes?
p.Kill();
throw new TimeoutException($"The process '{processStartInfo.FileName} {processStartInfo.Arguments}' timed out.");
}
if (p.ExitCode != 0)
throw new Exception($"{processStartInfo.FileName} exited with error code {p.ExitCode}");
}
}
/// <summary>
/// Provides an interface to parse the command line arguments passed to the SoDBench.
/// </summary>
private sealed class SoDBenchOptions
{
public SoDBenchOptions() { }
private static string NormalizePath(string path)
{
if (String.IsNullOrWhiteSpace(path))
throw new InvalidOperationException($"'{path}' is an invalid path: cannot be null or whitespace");
if (path.Any(c => Path.GetInvalidPathChars().Contains(c)))
throw new InvalidOperationException($"'{path}' is an invalid path: contains invalid characters");
return Path.IsPathRooted(path) ? path : Path.GetFullPath(path);
}
[Option('o', Required = false, HelpText = "Specifies the output file name for the csv document")]
public string OutputFilename
{
get { return _outputFilename; }
set
{
_outputFilename = NormalizePath(value);
}
}
[Option("dotnet", Required = false, HelpText = "Specifies the location of dotnet cli to use.")]
public string DotnetExecutable
{
get { return _dotnetExe; }
set
{
_dotnetExe = NormalizePath(value);
}
}
[Option("corelibs", Required = false, HelpText = "Specifies the location of .NET Core libaries to patch into dotnet. Cannot be used with --dotnet")]
public string CoreLibariesDirectory
{
get { return _corelibsDir; }
set
{
_corelibsDir = NormalizePath(value);
}
}
[Option("architecture", Required = false, Default = "x64", HelpText = "JitBench target architecture (It must match the built product that was copied into sandbox).")]
public string TargetArchitecture { get; set; }
[Option("channel", Required = false, Default = "master", HelpText = "Specifies the channel to use when installing the dotnet-cli")]
public string DotnetChannel { get; set; }
[Option('v', Required = false, HelpText = "Sets output to verbose")]
public bool Verbose { get; set; }
[Option("keep-artifacts", Required = false, HelpText = "Specifies that artifacts of this run should be kept")]
public bool KeepArtifacts { get; set; }
public static SoDBenchOptions Parse(string[] args)
{
using (var parser = new Parser((settings) => {
settings.CaseInsensitiveEnumValues = true;
settings.CaseSensitive = false;
settings.HelpWriter = new StringWriter();
settings.IgnoreUnknownArguments = true;
}))
{
SoDBenchOptions options = null;
parser.ParseArguments<SoDBenchOptions>(args)
.WithParsed(parsed => options = parsed)
.WithNotParsed(errors => {
foreach (Error error in errors)
{
switch (error.Tag)
{
case ErrorType.MissingValueOptionError:
throw new ArgumentException(
$"Missing value option for command line argument '{(error as MissingValueOptionError).NameInfo.NameText}'");
case ErrorType.HelpRequestedError:
Console.WriteLine(Usage());
Environment.Exit(0);
break;
case ErrorType.VersionRequestedError:
Console.WriteLine(new AssemblyName(typeof(SoDBenchOptions).GetTypeInfo().Assembly.FullName).Version);
Environment.Exit(0);
break;
case ErrorType.BadFormatTokenError:
case ErrorType.UnknownOptionError:
case ErrorType.MissingRequiredOptionError:
case ErrorType.MutuallyExclusiveSetError:
case ErrorType.BadFormatConversionError:
case ErrorType.SequenceOutOfRangeError:
case ErrorType.RepeatedOptionError:
case ErrorType.NoVerbSelectedError:
case ErrorType.BadVerbSelectedError:
case ErrorType.HelpVerbRequestedError:
break;
}
}
});
if (options != null && !String.IsNullOrEmpty(options.DotnetExecutable) && !String.IsNullOrEmpty(options.CoreLibariesDirectory))
{
throw new ArgumentException("--dotnet and --corlibs cannot be used together");
}
return options;
}
}
public static string Usage()
{
var parser = new Parser((parserSettings) =>
{
parserSettings.CaseInsensitiveEnumValues = true;
parserSettings.CaseSensitive = false;
parserSettings.EnableDashDash = true;
parserSettings.HelpWriter = new StringWriter();
parserSettings.IgnoreUnknownArguments = true;
});
var helpTextString = new HelpText
{
AddDashesToOption = true,
AddEnumValuesToHelpText = true,
AdditionalNewLineAfterOption = false,
Heading = "SoDBench",
MaximumDisplayWidth = 80,
}.AddOptions(parser.ParseArguments<SoDBenchOptions>(new string[] { "--help" })).ToString();
return helpTextString;
}
private string _dotnetExe;
private string _corelibsDir;
private string _outputFilename = "measurement.csv";
}
}
// A simple class for escaping strings for CSV writing
// https://stackoverflow.com/a/769713
// Used instead of a package because only these < 20 lines of code are needed
public static class Csv
{
public static string Escape( string s )
{
if ( s.Contains( QUOTE ) )
s = s.Replace( QUOTE, ESCAPED_QUOTE );
if ( s.IndexOfAny( CHARACTERS_THAT_MUST_BE_QUOTED ) > -1 )
s = QUOTE + s + QUOTE;
return s;
}
private const string QUOTE = "\"";
private const string ESCAPED_QUOTE = "\"\"";
private static char[] CHARACTERS_THAT_MUST_BE_QUOTED = { ',', '"', '\n' };
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Security;
namespace System.Runtime.InteropServices.WindowsRuntime
{
internal sealed class CLRIReferenceImpl<T> : CLRIPropertyValueImpl, IReference<T>, IGetProxyTarget
{
private T _value;
public CLRIReferenceImpl(PropertyType type, T obj)
: base(type, obj)
{
BCLDebug.Assert(obj != null, "Must not be null");
_value = obj;
}
public T Value {
get { return _value; }
}
public override string ToString()
{
if (_value != null)
{
return _value.ToString();
}
else
{
return base.ToString();
}
}
object IGetProxyTarget.GetTarget()
{
return (object)_value;
}
// We have T in an IReference<T>. Need to QI for IReference<T> with the appropriate GUID, call
// the get_Value property, allocate an appropriately-sized managed object, marshal the native object
// to the managed object, and free the native method. Also we want the return value boxed (aka normal value type boxing).
//
// This method is called by VM. Mark the method with FriendAccessAllowed attribute to ensure that the unreferenced method
// optimization skips it and the code will be saved into NGen image.
[System.Runtime.CompilerServices.FriendAccessAllowed]
internal static Object UnboxHelper(Object wrapper)
{
Contract.Requires(wrapper != null);
IReference<T> reference = (IReference<T>) wrapper;
Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed.");
return reference.Value;
}
}
// T can be any WinRT-compatible type
internal sealed class CLRIReferenceArrayImpl<T> : CLRIPropertyValueImpl,
IGetProxyTarget,
IReferenceArray<T>,
IList // Jupiter data binding needs IList/IEnumerable
{
private T[] _value;
private IList _list;
public CLRIReferenceArrayImpl(PropertyType type, T[] obj)
: base(type, obj)
{
BCLDebug.Assert(obj != null, "Must not be null");
_value = obj;
_list = (IList) _value;
}
public T[] Value {
get { return _value; }
}
public override string ToString()
{
if (_value != null)
{
return _value.ToString();
}
else
{
return base.ToString();
}
}
//
// IEnumerable methods. Used by data-binding in Jupiter when you try to data bind
// against a managed array
//
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_value).GetEnumerator();
}
//
// IList & ICollection methods.
// This enables two-way data binding and index access in Jupiter
//
Object IList.this[int index] {
get
{
return _list[index];
}
set
{
_list[index] = value;
}
}
int IList.Add(Object value)
{
return _list.Add(value);
}
bool IList.Contains(Object value)
{
return _list.Contains(value);
}
void IList.Clear()
{
_list.Clear();
}
bool IList.IsReadOnly
{
get
{
return _list.IsReadOnly;
}
}
bool IList.IsFixedSize
{
get
{
return _list.IsFixedSize;
}
}
int IList.IndexOf(Object value)
{
return _list.IndexOf(value);
}
void IList.Insert(int index, Object value)
{
_list.Insert(index, value);
}
void IList.Remove(Object value)
{
_list.Remove(value);
}
void IList.RemoveAt(int index)
{
_list.RemoveAt(index);
}
void ICollection.CopyTo(Array array, int index)
{
_list.CopyTo(array, index);
}
int ICollection.Count
{
get
{
return _list.Count;
}
}
Object ICollection.SyncRoot
{
get
{
return _list.SyncRoot;
}
}
bool ICollection.IsSynchronized
{
get
{
return _list.IsSynchronized;
}
}
object IGetProxyTarget.GetTarget()
{
return (object)_value;
}
// We have T in an IReferenceArray<T>. Need to QI for IReferenceArray<T> with the appropriate GUID, call
// the get_Value property, allocate an appropriately-sized managed object, marshal the native object
// to the managed object, and free the native method.
//
// This method is called by VM. Mark the method with FriendAccessAllowed attribute to ensure that the unreferenced method
// optimization skips it and the code will be saved into NGen image.
[System.Runtime.CompilerServices.FriendAccessAllowed]
internal static Object UnboxHelper(Object wrapper)
{
Contract.Requires(wrapper != null);
IReferenceArray<T> reference = (IReferenceArray<T>)wrapper;
Debug.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed.");
T[] marshaled = reference.Value;
return marshaled;
}
}
// For creating instances of Windows Runtime's IReference<T> and IReferenceArray<T>.
internal static class IReferenceFactory
{
internal static readonly Type s_pointType = Type.GetType("Windows.Foundation.Point, " + AssemblyRef.SystemRuntimeWindowsRuntime);
internal static readonly Type s_rectType = Type.GetType("Windows.Foundation.Rect, " + AssemblyRef.SystemRuntimeWindowsRuntime);
internal static readonly Type s_sizeType = Type.GetType("Windows.Foundation.Size, " + AssemblyRef.SystemRuntimeWindowsRuntime);
internal static Object CreateIReference(Object obj)
{
Contract.Requires(obj != null, "Null should not be boxed.");
Contract.Ensures(Contract.Result<Object>() != null);
Type type = obj.GetType();
if (type.IsArray)
return CreateIReferenceArray((Array) obj);
if (type == typeof(int))
return new CLRIReferenceImpl<int>(PropertyType.Int32, (int)obj);
if (type == typeof(String))
return new CLRIReferenceImpl<String>(PropertyType.String, (String)obj);
if (type == typeof(byte))
return new CLRIReferenceImpl<byte>(PropertyType.UInt8, (byte)obj);
if (type == typeof(short))
return new CLRIReferenceImpl<short>(PropertyType.Int16, (short)obj);
if (type == typeof(ushort))
return new CLRIReferenceImpl<ushort>(PropertyType.UInt16, (ushort)obj);
if (type == typeof(uint))
return new CLRIReferenceImpl<uint>(PropertyType.UInt32, (uint)obj);
if (type == typeof(long))
return new CLRIReferenceImpl<long>(PropertyType.Int64, (long)obj);
if (type == typeof(ulong))
return new CLRIReferenceImpl<ulong>(PropertyType.UInt64, (ulong)obj);
if (type == typeof(float))
return new CLRIReferenceImpl<float>(PropertyType.Single, (float)obj);
if (type == typeof(double))
return new CLRIReferenceImpl<double>(PropertyType.Double, (double)obj);
if (type == typeof(char))
return new CLRIReferenceImpl<char>(PropertyType.Char16, (char)obj);
if (type == typeof(bool))
return new CLRIReferenceImpl<bool>(PropertyType.Boolean, (bool)obj);
if (type == typeof(Guid))
return new CLRIReferenceImpl<Guid>(PropertyType.Guid, (Guid)obj);
if (type == typeof(DateTimeOffset))
return new CLRIReferenceImpl<DateTimeOffset>(PropertyType.DateTime, (DateTimeOffset)obj);
if (type == typeof(TimeSpan))
return new CLRIReferenceImpl<TimeSpan>(PropertyType.TimeSpan, (TimeSpan)obj);
if (type == typeof(Object))
return new CLRIReferenceImpl<Object>(PropertyType.Inspectable, (Object)obj);
if (type == typeof(RuntimeType))
{ // If the type is System.RuntimeType, we want to use System.Type marshaler (it's parent of the type)
return new CLRIReferenceImpl<Type>(PropertyType.Other, (Type)obj);
}
// Handle arbitrary WinRT-compatible value types, and recognize a few special types.
PropertyType? propType = null;
if (type == s_pointType)
{
propType = PropertyType.Point;
}
else if (type == s_rectType)
{
propType = PropertyType.Rect;
}
else if (type == s_sizeType)
{
propType = PropertyType.Size;
}
else if (type.IsValueType || obj is Delegate)
{
propType = PropertyType.Other;
}
if (propType.HasValue)
{
Type specificType = typeof(CLRIReferenceImpl<>).MakeGenericType(type);
return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj });
}
Debug.Assert(false, "We should not see non-WinRT type here");
return null;
}
internal static Object CreateIReferenceArray(Array obj)
{
Contract.Requires(obj != null);
Contract.Requires(obj.GetType().IsArray);
Contract.Ensures(Contract.Result<Object>() != null);
Type type = obj.GetType().GetElementType();
Debug.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray);
if (type == typeof(int))
return new CLRIReferenceArrayImpl<int>(PropertyType.Int32Array, (int[])obj);
if (type == typeof(String))
return new CLRIReferenceArrayImpl<String>(PropertyType.StringArray, (String[])obj);
if (type == typeof(byte))
return new CLRIReferenceArrayImpl<byte>(PropertyType.UInt8Array, (byte[])obj);
if (type == typeof(short))
return new CLRIReferenceArrayImpl<short>(PropertyType.Int16Array, (short[])obj);
if (type == typeof(ushort))
return new CLRIReferenceArrayImpl<ushort>(PropertyType.UInt16Array, (ushort[])obj);
if (type == typeof(uint))
return new CLRIReferenceArrayImpl<uint>(PropertyType.UInt32Array, (uint[])obj);
if (type == typeof(long))
return new CLRIReferenceArrayImpl<long>(PropertyType.Int64Array, (long[])obj);
if (type == typeof(ulong))
return new CLRIReferenceArrayImpl<ulong>(PropertyType.UInt64Array, (ulong[])obj);
if (type == typeof(float))
return new CLRIReferenceArrayImpl<float>(PropertyType.SingleArray, (float[])obj);
if (type == typeof(double))
return new CLRIReferenceArrayImpl<double>(PropertyType.DoubleArray, (double[])obj);
if (type == typeof(char))
return new CLRIReferenceArrayImpl<char>(PropertyType.Char16Array, (char[])obj);
if (type == typeof(bool))
return new CLRIReferenceArrayImpl<bool>(PropertyType.BooleanArray, (bool[])obj);
if (type == typeof(Guid))
return new CLRIReferenceArrayImpl<Guid>(PropertyType.GuidArray, (Guid[])obj);
if (type == typeof(DateTimeOffset))
return new CLRIReferenceArrayImpl<DateTimeOffset>(PropertyType.DateTimeArray, (DateTimeOffset[])obj);
if (type == typeof(TimeSpan))
return new CLRIReferenceArrayImpl<TimeSpan>(PropertyType.TimeSpanArray, (TimeSpan[])obj);
if (type == typeof(Type))
{ // Note: The array type will be System.Type, not System.RuntimeType
return new CLRIReferenceArrayImpl<Type>(PropertyType.OtherArray, (Type[])obj);
}
PropertyType? propType = null;
if (type == s_pointType)
{
propType = PropertyType.PointArray;
}
else if (type == s_rectType)
{
propType = PropertyType.RectArray;
}
else if (type == s_sizeType)
{
propType = PropertyType.SizeArray;
}
else if (type.IsValueType)
{
// note that KeyValuePair`2 is a reference type on the WinRT side so the array
// must be wrapped with CLRIReferenceArrayImpl<Object>
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>))
{
Object[] objArray = new Object[obj.Length];
for (int i = 0; i < objArray.Length; i++)
{
objArray[i] = obj.GetValue(i);
}
obj = objArray;
}
else
{
propType = PropertyType.OtherArray;
}
}
else if (typeof(Delegate).IsAssignableFrom(type))
{
propType = PropertyType.OtherArray;
}
if (propType.HasValue)
{
// All WinRT value type will be Property.Other
Type specificType = typeof(CLRIReferenceArrayImpl<>).MakeGenericType(type);
return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj });
}
else
{
// All WinRT reference type (including arbitary managed type) will be PropertyType.ObjectArray
return new CLRIReferenceArrayImpl<Object>(PropertyType.InspectableArray, (Object[])obj);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
public partial class Socket
{
partial void ValidateForMultiConnect(bool isMultiEndpoint)
{
// ValidateForMultiConnect is called before any {Begin}Connect{Async} call,
// regardless of whether it's targeting an endpoint with multiple addresses.
// If it is targeting such an endpoint, then any exposure of the socket's handle
// or configuration of the socket we haven't tracked would prevent us from
// replicating the socket's file descriptor appropriately. Similarly, if it's
// only targeting a single address, but it already experienced a failure in a
// previous connect call, then this is logically part of a multi endpoint connect,
// and the same logic applies. Either way, in such a situation we throw.
if (_handle.ExposedHandleOrUntrackedConfiguration && (isMultiEndpoint || _handle.LastConnectFailed))
{
ThrowMultiConnectNotSupported();
}
// If the socket was already used for a failed connect attempt, replace it
// with a fresh one, copying over all of the state we've tracked.
ReplaceHandleIfNecessaryAfterFailedConnect();
Debug.Assert(!_handle.LastConnectFailed);
}
internal void ReplaceHandleIfNecessaryAfterFailedConnect()
{
if (!_handle.LastConnectFailed)
{
return;
}
// Copy out values from key options. The copied values should be kept in sync with the
// handling in SafeCloseSocket.TrackOption. Note that we copy these values out first, before
// we change _handle, so that we can use the helpers on Socket which internally access _handle.
// Then once _handle is switched to the new one, we can call the setters to propagate the retrieved
// values back out to the new underlying socket.
bool broadcast = false, dontFragment = false, noDelay = false;
int receiveSize = -1, receiveTimeout = -1, sendSize = -1, sendTimeout = -1;
short ttl = -1;
LingerOption linger = null;
if (_handle.IsTrackedOption(TrackedSocketOptions.DontFragment)) dontFragment = DontFragment;
if (_handle.IsTrackedOption(TrackedSocketOptions.EnableBroadcast)) broadcast = EnableBroadcast;
if (_handle.IsTrackedOption(TrackedSocketOptions.LingerState)) linger = LingerState;
if (_handle.IsTrackedOption(TrackedSocketOptions.NoDelay)) noDelay = NoDelay;
if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveBufferSize)) receiveSize = ReceiveBufferSize;
if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveTimeout)) receiveTimeout = ReceiveTimeout;
if (_handle.IsTrackedOption(TrackedSocketOptions.SendBufferSize)) sendSize = SendBufferSize;
if (_handle.IsTrackedOption(TrackedSocketOptions.SendTimeout)) sendTimeout = SendTimeout;
if (_handle.IsTrackedOption(TrackedSocketOptions.Ttl)) ttl = Ttl;
// Then replace the handle with a new one
SafeCloseSocket oldHandle = _handle;
SocketError errorCode = SocketPal.CreateSocket(_addressFamily, _socketType, _protocolType, out _handle);
oldHandle.TransferTrackedState(_handle);
oldHandle.Dispose();
if (errorCode != SocketError.Success)
{
throw new SocketException((int)errorCode);
}
// And put back the copied settings. For DualMode, we use the value stored in the _handle
// rather than querying the socket itself, as on Unix stacks binding a dual-mode socket to
// an IPv6 address may cause the IPv6Only setting to revert to true.
if (_handle.IsTrackedOption(TrackedSocketOptions.DualMode)) DualMode = _handle.DualMode;
if (_handle.IsTrackedOption(TrackedSocketOptions.DontFragment)) DontFragment = dontFragment;
if (_handle.IsTrackedOption(TrackedSocketOptions.EnableBroadcast)) EnableBroadcast = broadcast;
if (_handle.IsTrackedOption(TrackedSocketOptions.LingerState)) LingerState = linger;
if (_handle.IsTrackedOption(TrackedSocketOptions.NoDelay)) NoDelay = noDelay;
if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveBufferSize)) ReceiveBufferSize = receiveSize;
if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveTimeout)) ReceiveTimeout = receiveTimeout;
if (_handle.IsTrackedOption(TrackedSocketOptions.SendBufferSize)) SendBufferSize = sendSize;
if (_handle.IsTrackedOption(TrackedSocketOptions.SendTimeout)) SendTimeout = sendTimeout;
if (_handle.IsTrackedOption(TrackedSocketOptions.Ttl)) Ttl = ttl;
_handle.LastConnectFailed = false;
}
private static void ThrowMultiConnectNotSupported()
{
throw new PlatformNotSupportedException(SR.net_sockets_connect_multiconnect_notsupported);
}
private Socket GetOrCreateAcceptSocket(Socket acceptSocket, bool unused, string propertyName, out SafeCloseSocket handle)
{
// AcceptSocket is not supported on Unix.
if (acceptSocket != null)
{
throw new PlatformNotSupportedException();
}
handle = null;
return null;
}
private static void CheckTransmitFileOptions(TransmitFileOptions flags)
{
// Note, UseDefaultWorkerThread is the default and is == 0.
// Unfortunately there is no TransmitFileOptions.None.
if (flags != TransmitFileOptions.UseDefaultWorkerThread)
{
throw new PlatformNotSupportedException(SR.net_sockets_transmitfileoptions_notsupported);
}
}
private void SendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
{
CheckTransmitFileOptions(flags);
// Open the file, if any
// Open it before we send the preBuffer so that any exception happens first
FileStream fileStream = OpenFile(fileName);
SocketError errorCode = SocketError.Success;
using (fileStream)
{
// Send the preBuffer, if any
// This will throw on error
if (preBuffer != null && preBuffer.Length > 0)
{
Send(preBuffer);
}
// Send the file, if any
if (fileStream != null)
{
// This can throw ObjectDisposedException.
errorCode = SocketPal.SendFile(_handle, fileStream);
}
}
if (errorCode != SocketError.Success)
{
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, socketException);
throw socketException;
}
// Send the postBuffer, if any
// This will throw on error
if (postBuffer != null && postBuffer.Length > 0)
{
Send(postBuffer);
}
}
private async Task SendFileInternalAsync(FileStream fileStream, byte[] preBuffer, byte[] postBuffer)
{
SocketError errorCode = SocketError.Success;
using (fileStream)
{
// Send the preBuffer, if any
// This will throw on error
if (preBuffer != null && preBuffer.Length > 0)
{
// Using "this." makes the extension method kick in
await this.SendAsync(new ArraySegment<byte>(preBuffer), SocketFlags.None).ConfigureAwait(false);
}
// Send the file, if any
if (fileStream != null)
{
var tcs = new TaskCompletionSource<bool>();
// This can throw ObjectDisposedException.
errorCode = SocketPal.SendFileAsync(_handle, fileStream, (bytesTransferred, socketError) =>
{
if (socketError != SocketError.Success)
{
// Synchronous exception from SendFileAsync
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, socketException);
tcs.SetException(socketException);
}
tcs.SetResult(true);
});
await tcs.Task.ConfigureAwait(false);
}
}
if (errorCode != SocketError.Success)
{
// Synchronous exception from SendFileAsync
SocketException socketException = new SocketException((int)errorCode);
UpdateStatusAfterSocketError(socketException);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, socketException);
throw socketException;
}
// Send the postBuffer, if any
// This will throw on error
if (postBuffer != null && postBuffer.Length > 0)
{
// Using "this." makes the extension method kick in
await this.SendAsync(new ArraySegment<byte>(postBuffer), SocketFlags.None).ConfigureAwait(false);
}
}
private IAsyncResult BeginSendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
{
CheckTransmitFileOptions(flags);
// Open the file, if any
// Open it before we send the preBuffer so that any exception happens first
FileStream fileStream = OpenFile(fileName);
return TaskToApm.Begin(SendFileInternalAsync(fileStream, preBuffer, postBuffer), callback, state);
}
private void EndSendFileInternal(IAsyncResult asyncResult)
{
TaskToApm.End(asyncResult);
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting.Client;
using System.Management.Automation.Runspaces.Internal;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// Executes methods on the client.
/// </summary>
internal class ClientMethodExecutor
{
/// <summary>
/// Transport manager.
/// </summary>
private BaseClientTransportManager _transportManager;
/// <summary>
/// Client host.
/// </summary>
private PSHost _clientHost;
/// <summary>
/// Client runspace pool id.
/// </summary>
private Guid _clientRunspacePoolId;
/// <summary>
/// Client power shell id.
/// </summary>
private Guid _clientPowerShellId;
/// <summary>
/// Remote host call.
/// </summary>
private RemoteHostCall _remoteHostCall;
/// <summary>
/// Remote host call.
/// </summary>
internal RemoteHostCall RemoteHostCall
{
get
{
return _remoteHostCall;
}
}
/// <summary>
/// Constructor for ClientMethodExecutor.
/// </summary>
private ClientMethodExecutor(BaseClientTransportManager transportManager, PSHost clientHost, Guid clientRunspacePoolId, Guid clientPowerShellId, RemoteHostCall remoteHostCall)
{
Dbg.Assert(transportManager != null, "Expected transportManager != null");
Dbg.Assert(remoteHostCall != null, "Expected remoteHostCall != null");
_transportManager = transportManager;
_remoteHostCall = remoteHostCall;
_clientHost = clientHost;
_clientRunspacePoolId = clientRunspacePoolId;
_clientPowerShellId = clientPowerShellId;
}
/// <summary>
/// Create a new ClientMethodExecutor object and then dispatch it.
/// </summary>
internal static void Dispatch(
BaseClientTransportManager transportManager,
PSHost clientHost,
PSDataCollectionStream<ErrorRecord> errorStream,
ObjectStream methodExecutorStream,
bool isMethodExecutorStreamEnabled,
RemoteRunspacePoolInternal runspacePool,
Guid clientPowerShellId,
RemoteHostCall remoteHostCall)
{
ClientMethodExecutor methodExecutor =
new ClientMethodExecutor(transportManager, clientHost, runspacePool.InstanceId,
clientPowerShellId, remoteHostCall);
// If the powershell id is not specified, this message is for the runspace pool, execute
// it immediately and return
if (clientPowerShellId == Guid.Empty)
{
methodExecutor.Execute(errorStream);
return;
}
// Check client host to see if SetShouldExit should be allowed
bool hostAllowSetShouldExit = false;
if (clientHost != null)
{
PSObject hostPrivateData = clientHost.PrivateData as PSObject;
if (hostPrivateData != null)
{
PSNoteProperty allowSetShouldExit = hostPrivateData.Properties["AllowSetShouldExitFromRemote"] as PSNoteProperty;
hostAllowSetShouldExit = (allowSetShouldExit != null && allowSetShouldExit.Value is bool) ?
(bool)allowSetShouldExit.Value : false;
}
}
// Should we kill remote runspace? Check if "SetShouldExit" and if we are in the
// cmdlet case. In the API case (when we are invoked from an API not a cmdlet) we
// should not interpret "SetShouldExit" but should pass it on to the host. The
// variable IsMethodExecutorStreamEnabled is only true in the cmdlet case. In the
// API case it is false.
if (remoteHostCall.IsSetShouldExit && isMethodExecutorStreamEnabled && !hostAllowSetShouldExit)
{
runspacePool.Close();
return;
}
// Cmdlet case: queue up the executor in the pipeline stream.
if (isMethodExecutorStreamEnabled)
{
Dbg.Assert(!isMethodExecutorStreamEnabled ||
(isMethodExecutorStreamEnabled && methodExecutorStream != null),
"method executor stream can't be null when enabled");
methodExecutorStream.Write(methodExecutor);
}
// API case: execute it immediately.
else
{
methodExecutor.Execute(errorStream);
}
}
/// <summary>
/// Is runspace pushed.
/// </summary>
private bool IsRunspacePushed(PSHost host)
{
IHostSupportsInteractiveSession host2 = host as IHostSupportsInteractiveSession;
if (host2 == null) { return false; }
// IsRunspacePushed can throw (not implemented exception)
try
{
return host2.IsRunspacePushed;
}
catch (PSNotImplementedException) { }
return false;
}
/// <summary>
/// Execute.
/// </summary>
internal void Execute(PSDataCollectionStream<ErrorRecord> errorStream)
{
Action<ErrorRecord> writeErrorAction = null;
// If error-stream is null or we are in pushed-runspace - then write error directly to console.
if (errorStream == null || IsRunspacePushed(_clientHost))
{
writeErrorAction = delegate (ErrorRecord errorRecord)
{
try
{
if (_clientHost.UI != null)
{
_clientHost.UI.WriteErrorLine(errorRecord.ToString());
}
}
catch (Exception e)
{
// Catch-all OK, 3rd party callout.
CommandProcessorBase.CheckForSevereException(e);
}
};
}
// Otherwise write it to error-stream.
else
{
writeErrorAction = delegate (ErrorRecord errorRecord)
{
errorStream.Write(errorRecord);
};
}
this.Execute(writeErrorAction);
}
/// <summary>
/// Execute.
/// </summary>
internal void Execute(Cmdlet cmdlet)
{
this.Execute(cmdlet.WriteError);
}
/// <summary>
/// Execute.
/// </summary>
internal void Execute(Action<ErrorRecord> writeErrorAction)
{
if (_remoteHostCall.IsVoidMethod)
{
ExecuteVoid(writeErrorAction);
}
else
{
RemotingDataType remotingDataType =
_clientPowerShellId == Guid.Empty ? RemotingDataType.RemoteRunspaceHostResponseData : RemotingDataType.RemotePowerShellHostResponseData;
RemoteHostResponse remoteHostResponse = _remoteHostCall.ExecuteNonVoidMethod(_clientHost);
RemoteDataObject<PSObject> dataToBeSent = RemoteDataObject<PSObject>.CreateFrom(
RemotingDestination.Server, remotingDataType, _clientRunspacePoolId,
_clientPowerShellId, remoteHostResponse.Encode());
_transportManager.DataToBeSentCollection.Add<PSObject>(dataToBeSent, DataPriorityType.PromptResponse);
}
}
/// <summary>
/// Execute void.
/// </summary>
internal void ExecuteVoid(Action<ErrorRecord> writeErrorAction)
{
try
{
_remoteHostCall.ExecuteVoidMethod(_clientHost);
}
catch (Exception exception)
{
// Catch-all OK, 3rd party callout.
CommandProcessorBase.CheckForSevereException(exception);
// Extract inner exception.
if (exception.InnerException != null)
{
exception = exception.InnerException;
}
// Create an error record and write it to the stream.
ErrorRecord errorRecord = new ErrorRecord(
exception,
PSRemotingErrorId.RemoteHostCallFailed.ToString(),
ErrorCategory.InvalidArgument,
_remoteHostCall.MethodName);
writeErrorAction(errorRecord);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
#else
using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
#endif
#if ES_BUILD_AGAINST_DOTNET_V35
using Microsoft.Internal; // for Tuple (can't define alias for open generic types so we "use" the whole namespace)
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
// New in CLR4.0
internal enum ControllerCommand
{
// Strictly Positive numbers are for provider-specific commands, negative number are for 'shared' commands. 256
// The first 256 negative numbers are reserved for the framework.
Update = 0, // Not used by EventPrividerBase.
SendManifest = -1,
Enable = -2,
Disable = -3,
};
/// <summary>
/// Only here because System.Diagnostics.EventProvider needs one more extensibility hook (when it gets a
/// controller callback)
/// </summary>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
internal class EventProvider : IDisposable
{
// This is the windows EVENT_DATA_DESCRIPTOR structure. We expose it because this is what
// subclasses of EventProvider use when creating efficient (but unsafe) version of
// EventWrite. We do make it a nested type because we really don't expect anyone to use
// it except subclasses (and then only rarely).
public struct EventData
{
internal unsafe ulong Ptr;
internal uint Size;
internal uint Reserved;
}
/// <summary>
/// A struct characterizing ETW sessions (identified by the etwSessionId) as
/// activity-tracing-aware or legacy. A session that's activity-tracing-aware
/// has specified one non-zero bit in the reserved range 44-47 in the
/// 'allKeywords' value it passed in for a specific EventProvider.
/// </summary>
public struct SessionInfo
{
internal int sessionIdBit; // the index of the bit used for tracing in the "reserved" field of AllKeywords
internal int etwSessionId; // the machine-wide ETW session ID
internal SessionInfo(int sessionIdBit_, int etwSessionId_)
{ sessionIdBit = sessionIdBit_; etwSessionId = etwSessionId_; }
}
private static bool m_setInformationMissing;
[SecurityCritical]
UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function
private long m_regHandle; // Trace Registration Handle
private byte m_level; // Tracing Level
private long m_anyKeywordMask; // Trace Enable Flags
private long m_allKeywordMask; // Match all keyword
private List<SessionInfo> m_liveSessions; // current live sessions (Tuple<sessionIdBit, etwSessionId>)
private bool m_enabled; // Enabled flag from Trace callback
private Guid m_providerId; // Control Guid
internal bool m_disposed; // when true provider has unregistered
[ThreadStatic]
private static WriteEventErrorCode s_returnCode; // The last return code
private const int s_basicTypeAllocationBufferSize = 16;
private const int s_etwMaxNumberArguments = 32;
private const int s_etwAPIMaxRefObjCount = 8;
private const int s_maxEventDataDescriptors = 128;
private const int s_traceEventMaximumSize = 65482;
private const int s_traceEventMaximumStringSize = 32724;
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public enum WriteEventErrorCode : int
{
//check mapping to runtime codes
NoError = 0,
NoFreeBuffers = 1,
EventTooBig = 2,
NullInput = 3,
TooManyArgs = 4,
Other = 5,
};
// <SecurityKernel Critical="True" Ring="1">
// <ReferencesCritical Name="Method: Register():Void" Ring="1" />
// </SecurityKernel>
/// <summary>
/// Constructs a new EventProvider. This causes the class to be registered with the OS and
/// if an ETW controller turns on the logging then logging will start.
/// </summary>
/// <param name="providerGuid">The GUID that identifies this provider to the system.</param>
[System.Security.SecurityCritical]
#pragma warning disable 618
[PermissionSet(SecurityAction.Demand, Unrestricted = true)]
#pragma warning restore 618
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")]
protected EventProvider(Guid providerGuid)
{
m_providerId = providerGuid;
//
// Register the ProviderId with ETW
//
Register(providerGuid);
}
internal EventProvider()
{
}
/// <summary>
/// This method registers the controlGuid of this class with ETW. We need to be running on
/// Vista or above. If not a PlatformNotSupported exception will be thrown. If for some
/// reason the ETW Register call failed a NotSupported exception will be thrown.
/// </summary>
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventRegister(System.Guid&,Microsoft.Win32.UnsafeNativeMethods.ManifestEtw+EtwEnableCallback,System.Void*,System.Int64&):System.UInt32" />
// <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" />
// <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" />
// </SecurityKernel>
[System.Security.SecurityCritical]
internal unsafe void Register(Guid providerGuid)
{
m_providerId = providerGuid;
uint status;
m_etwCallback = new UnsafeNativeMethods.ManifestEtw.EtwEnableCallback(EtwEnableCallBack);
status = EventRegister(ref m_providerId, m_etwCallback);
if (status != 0)
{
throw new ArgumentException(Win32Native.GetMessage(unchecked((int)status)));
}
else
{
// if we registered successfully ensure we unregister on ProcessExit
DisposeOnProcessExit(new WeakReference(this));
}
}
[System.Security.SecurityCritical]
internal unsafe int SetInformation(
UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS eventInfoClass,
void* data,
int dataSize)
{
int status = UnsafeNativeMethods.ManifestEtw.ERROR_NOT_SUPPORTED;
if (!m_setInformationMissing)
{
try
{
status = UnsafeNativeMethods.ManifestEtw.EventSetInformation(
m_regHandle,
eventInfoClass,
data,
dataSize);
}
catch (TypeLoadException)
{
m_setInformationMissing = true;
}
}
return status;
}
private static void DisposeOnProcessExit(WeakReference wrThis)
{
#if !ES_BUILD_PCL && !FEATURE_CORECLR
EventHandler doDispose = (sender, e) => {
EventProvider ep = wrThis.Target as EventProvider;
if (ep != null)
ep.Dispose(true);
};
AppDomain.CurrentDomain.ProcessExit += doDispose;
AppDomain.CurrentDomain.DomainUnload += doDispose;
#endif
}
//
// implement Dispose Pattern to early deregister from ETW insted of waiting for
// the finalizer to call deregistration.
// Once the user is done with the provider it needs to call Close() or Dispose()
// If neither are called the finalizer will unregister the provider anyway
//
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1">
// <ReferencesCritical Name="Method: Deregister():Void" Ring="1" />
// </SecurityKernel>
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
//
// explicit cleanup is done by calling Dispose with true from
// Dispose() or Close(). The disposing arguement is ignored because there
// are no unmanaged resources.
// The finalizer calls Dispose with false.
//
//
// check if the object has been allready disposed
//
if (m_disposed) return;
// Disable the provider.
m_enabled = false;
// Do most of the work under a lock to avoid shutdown race condition.
lock (EventListener.EventListenersLock)
{
// Double check
if (m_disposed)
return;
Deregister();
m_disposed = true;
}
}
/// <summary>
/// This method deregisters the controlGuid of this class with ETW.
///
/// </summary>
public virtual void Close()
{
Dispose();
}
~EventProvider()
{
Dispose(false);
}
/// <summary>
/// This method un-registers from ETW.
/// </summary>
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64):System.Int32" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Win32.UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64)"), System.Security.SecurityCritical]
private unsafe void Deregister()
{
//
// Unregister from ETW using the RegHandle saved from
// the register call.
//
if (m_regHandle != 0)
{
EventUnregister();
m_regHandle = 0;
}
}
// <SecurityKernel Critical="True" Ring="0">
// <UsesUnsafeCode Name="Parameter filterData of type: Void*" />
// <UsesUnsafeCode Name="Parameter callbackContext of type: Void*" />
// </SecurityKernel>
[System.Security.SecurityCritical]
unsafe void EtwEnableCallBack(
[In] ref System.Guid sourceId,
[In] int controlCode,
[In] byte setLevel,
[In] long anyKeyword,
[In] long allKeyword,
[In] UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData,
[In] void* callbackContext
)
{
// This is an optional callback API. We will therefore ignore any failures that happen as a
// result of turning on this provider as to not crash the app.
// EventSource has code to validate whther initialization it expected to occur actually occurred
try
{
ControllerCommand command = ControllerCommand.Update;
IDictionary<string, string> args = null;
byte[] data;
int keyIndex;
bool skipFinalOnControllerCommand = false;
EventSource.OutputDebugString(string.Format("EtwEnableCallBack(ctrl {0}, lvl {1}, any {2:x}, all {3:x})",
controlCode, setLevel, anyKeyword, allKeyword));
if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_ENABLE_PROVIDER)
{
m_enabled = true;
m_level = setLevel;
m_anyKeywordMask = anyKeyword;
m_allKeywordMask = allKeyword;
List<Tuple<SessionInfo, bool>> sessionsChanged = GetSessions();
foreach (var session in sessionsChanged)
{
int sessionChanged = session.Item1.sessionIdBit;
int etwSessionId = session.Item1.etwSessionId;
bool bEnabling = session.Item2;
EventSource.OutputDebugString(string.Format(CultureInfo.InvariantCulture, "EtwEnableCallBack: session changed {0}:{1}:{2}",
sessionChanged, etwSessionId, bEnabling));
skipFinalOnControllerCommand = true;
args = null; // reinitialize args for every session...
// if we get more than one session changed we have no way
// of knowing which one "filterData" belongs to
if (sessionsChanged.Count > 1)
filterData = null;
// read filter data only when a session is being *added*
if (bEnabling &&
GetDataFromController(etwSessionId, filterData, out command, out data, out keyIndex))
{
args = new Dictionary<string, string>(4);
while (keyIndex < data.Length)
{
int keyEnd = FindNull(data, keyIndex);
int valueIdx = keyEnd + 1;
int valueEnd = FindNull(data, valueIdx);
if (valueEnd < data.Length)
{
string key = System.Text.Encoding.UTF8.GetString(data, keyIndex, keyEnd - keyIndex);
string value = System.Text.Encoding.UTF8.GetString(data, valueIdx, valueEnd - valueIdx);
args[key] = value;
}
keyIndex = valueEnd + 1;
}
}
// execute OnControllerCommand once for every session that has changed.
OnControllerCommand(command, args, (bEnabling ? sessionChanged : -sessionChanged), etwSessionId);
}
}
else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_DISABLE_PROVIDER)
{
m_enabled = false;
m_level = 0;
m_anyKeywordMask = 0;
m_allKeywordMask = 0;
m_liveSessions = null;
}
else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_CAPTURE_STATE)
{
command = ControllerCommand.SendManifest;
}
else
return; // per spec you ignore commands you don't recognise.
if (!skipFinalOnControllerCommand)
OnControllerCommand(command, args, 0, 0);
}
catch (Exception)
{
// We want to ignore any failures that happen as a result of turning on this provider as to
// not crash the app.
}
}
// New in CLR4.0
protected virtual void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments, int sessionId, int etwSessionId) { }
protected EventLevel Level { get { return (EventLevel)m_level; } set { m_level = (byte)value; } }
protected EventKeywords MatchAnyKeyword { get { return (EventKeywords)m_anyKeywordMask; } set { m_anyKeywordMask = unchecked((long)value); } }
protected EventKeywords MatchAllKeyword { get { return (EventKeywords)m_allKeywordMask; } set { m_allKeywordMask = unchecked((long)value); } }
static private int FindNull(byte[] buffer, int idx)
{
while (idx < buffer.Length && buffer[idx] != 0)
idx++;
return idx;
}
/// <summary>
/// Determines the ETW sessions that have been added and/or removed to the set of
/// sessions interested in the current provider. It does so by (1) enumerating over all
/// ETW sessions that enabled 'this.m_Guid' for the current process ID, and (2)
/// comparing the current list with a list it cached on the previous invocation.
///
/// The return value is a list of tuples, where the SessionInfo specifies the
/// ETW session that was added or remove, and the bool specifies whether the
/// session was added or whether it was removed from the set.
/// </summary>
[System.Security.SecuritySafeCritical]
private List<Tuple<SessionInfo, bool>> GetSessions()
{
List<SessionInfo> liveSessionList = null;
GetSessionInfo((Action<int, long>)
((etwSessionId, matchAllKeywords) =>
GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref liveSessionList)));
List<Tuple<SessionInfo, bool>> changedSessionList = new List<Tuple<SessionInfo, bool>>();
// first look for sessions that have gone away (or have changed)
// (present in the m_liveSessions but not in the new liveSessionList)
if (m_liveSessions != null)
{
foreach(SessionInfo s in m_liveSessions)
{
int idx;
if ((idx = IndexOfSessionInList(liveSessionList, s.etwSessionId)) < 0 ||
(liveSessionList[idx].sessionIdBit != s.sessionIdBit))
changedSessionList.Add(Tuple.Create(s, false));
}
}
// next look for sessions that were created since the last callback (or have changed)
// (present in the new liveSessionList but not in m_liveSessions)
if (liveSessionList != null)
{
foreach (SessionInfo s in liveSessionList)
{
int idx;
if ((idx = IndexOfSessionInList(m_liveSessions, s.etwSessionId)) < 0 ||
(m_liveSessions[idx].sessionIdBit != s.sessionIdBit))
changedSessionList.Add(Tuple.Create(s, true));
}
}
m_liveSessions = liveSessionList;
return changedSessionList;
}
/// <summary>
/// This method is the callback used by GetSessions() when it calls into GetSessionInfo().
/// It updates a List{SessionInfo} based on the etwSessionId and matchAllKeywords that
/// GetSessionInfo() passes in.
/// </summary>
private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywords,
ref List<SessionInfo> sessionList)
{
uint sessionIdBitMask = (uint)SessionMask.FromEventKeywords(unchecked((ulong)matchAllKeywords));
// an ETW controller that specifies more than the mandated bit for our EventSource
// will be ignored...
if (bitcount(sessionIdBitMask) > 1)
return;
if (sessionList == null)
sessionList = new List<SessionInfo>(8);
if (bitcount(sessionIdBitMask) == 1)
{
// activity-tracing-aware etw session
sessionList.Add(new SessionInfo(bitindex(sessionIdBitMask)+1, etwSessionId));
}
else
{
// legacy etw session
sessionList.Add(new SessionInfo(bitcount((uint)SessionMask.All)+1, etwSessionId));
}
}
/// <summary>
/// This method enumerates over all active ETW sessions that have enabled 'this.m_Guid'
/// for the current process ID, calling 'action' for each session, and passing it the
/// ETW session and the 'AllKeywords' the session enabled for the current provider.
/// </summary>
[System.Security.SecurityCritical]
private unsafe void GetSessionInfo(Action<int, long> action)
{
int buffSize = 256; // An initial guess that probably works most of the time.
byte* buffer;
for (; ; )
{
var space = stackalloc byte[buffSize];
buffer = space;
var hr = 0;
fixed (Guid* provider = &m_providerId)
{
hr = UnsafeNativeMethods.ManifestEtw.EnumerateTraceGuidsEx(UnsafeNativeMethods.ManifestEtw.TRACE_QUERY_INFO_CLASS.TraceGuidQueryInfo,
provider, sizeof(Guid), buffer, buffSize, ref buffSize);
}
if (hr == 0)
break;
if (hr != 122 /* ERROR_INSUFFICIENT_BUFFER */)
return;
}
var providerInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_GUID_INFO*)buffer;
var providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&providerInfos[1];
int processId = unchecked((int)Win32Native.GetCurrentProcessId());
// iterate over the instances of the EventProvider in all processes
for (int i = 0; i < providerInfos->InstanceCount; i++)
{
if (providerInstance->Pid == processId)
{
var enabledInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_ENABLE_INFO*)&providerInstance[1];
// iterate over the list of active ETW sessions "listening" to the current provider
for (int j = 0; j < providerInstance->EnableCount; j++)
action(enabledInfos[j].LoggerId, enabledInfos[j].MatchAllKeyword);
}
if (providerInstance->NextOffset == 0)
break;
Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize);
var structBase = (byte*)providerInstance;
providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset];
}
}
/// <summary>
/// Returns the index of the SesisonInfo from 'sessions' that has the specified 'etwSessionId'
/// or -1 if the value is not present.
/// </summary>
private static int IndexOfSessionInList(List<SessionInfo> sessions, int etwSessionId)
{
if (sessions == null)
return -1;
// for non-coreclr code we could use List<T>.FindIndex(Predicate<T>), but we need this to compile
// on coreclr as well
for (int i = 0; i < sessions.Count; ++i)
if (sessions[i].etwSessionId == etwSessionId)
return i;
return -1;
}
/// <summary>
/// Gets any data to be passed from the controller to the provider. It starts with what is passed
/// into the callback, but unfortunately this data is only present for when the provider is active
/// at the time the controller issues the command. To allow for providers to activate after the
/// controller issued a command, we also check the registry and use that to get the data. The function
/// returns an array of bytes representing the data, the index into that byte array where the data
/// starts, and the command being issued associated with that data.
/// </summary>
[System.Security.SecurityCritical]
private unsafe bool GetDataFromController(int etwSessionId,
UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart)
{
data = null;
dataStart = 0;
if (filterData == null)
{
#if !ES_BUILD_PCL && !FEATURE_PAL
string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}";
if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey;
else
regKey = @"HKEY_LOCAL_MACHINE\Software" + regKey;
string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture);
// we need to assert this permission for partial trust scenarios
(new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert();
data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[];
if (data != null)
{
// We only used the persisted data from the registry for updates.
command = ControllerCommand.Update;
return true;
}
#endif
}
else
{
if (filterData->Ptr != 0 && 0 < filterData->Size && filterData->Size <= 1024)
{
data = new byte[filterData->Size];
Marshal.Copy((IntPtr)filterData->Ptr, data, 0, data.Length);
}
command = (ControllerCommand) filterData->Type;
return true;
}
command = ControllerCommand.Update;
return false;
}
/// <summary>
/// IsEnabled, method used to test if provider is enabled
/// </summary>
public bool IsEnabled()
{
return m_enabled;
}
/// <summary>
/// IsEnabled, method used to test if event is enabled
/// </summary>
/// <param name="level">
/// Level to test
/// </param>
/// <param name="keywords">
/// Keyword to test
/// </param>
public bool IsEnabled(byte level, long keywords)
{
//
// If not enabled at all, return false.
//
if (!m_enabled)
{
return false;
}
// This also covers the case of Level == 0.
if ((level <= m_level) ||
(m_level == 0))
{
//
// Check if Keyword is enabled
//
if ((keywords == 0) ||
(((keywords & m_anyKeywordMask) != 0) &&
((keywords & m_allKeywordMask) == m_allKeywordMask)))
{
return true;
}
}
return false;
}
// There's a small window of time in EventSource code where m_provider is non-null but the
// m_regHandle has not been set yet. This method allows EventSource to check if this is the case...
internal bool IsValid()
{ return m_regHandle != 0; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public static WriteEventErrorCode GetLastWriteEventError()
{
return s_returnCode;
}
//
// Helper function to set the last error on the thread
//
private static void SetLastError(int error)
{
switch (error)
{
case UnsafeNativeMethods.ManifestEtw.ERROR_ARITHMETIC_OVERFLOW:
case UnsafeNativeMethods.ManifestEtw.ERROR_MORE_DATA:
s_returnCode = WriteEventErrorCode.EventTooBig;
break;
case UnsafeNativeMethods.ManifestEtw.ERROR_NOT_ENOUGH_MEMORY:
s_returnCode = WriteEventErrorCode.NoFreeBuffers;
break;
}
}
// <SecurityKernel Critical="True" Ring="0">
// <UsesUnsafeCode Name="Local intptrPtr of type: IntPtr*" />
// <UsesUnsafeCode Name="Local intptrPtr of type: Int32*" />
// <UsesUnsafeCode Name="Local longptr of type: Int64*" />
// <UsesUnsafeCode Name="Local uintptr of type: UInt32*" />
// <UsesUnsafeCode Name="Local ulongptr of type: UInt64*" />
// <UsesUnsafeCode Name="Local charptr of type: Char*" />
// <UsesUnsafeCode Name="Local byteptr of type: Byte*" />
// <UsesUnsafeCode Name="Local shortptr of type: Int16*" />
// <UsesUnsafeCode Name="Local sbyteptr of type: SByte*" />
// <UsesUnsafeCode Name="Local ushortptr of type: UInt16*" />
// <UsesUnsafeCode Name="Local floatptr of type: Single*" />
// <UsesUnsafeCode Name="Local doubleptr of type: Double*" />
// <UsesUnsafeCode Name="Local boolptr of type: Boolean*" />
// <UsesUnsafeCode Name="Local guidptr of type: Guid*" />
// <UsesUnsafeCode Name="Local decimalptr of type: Decimal*" />
// <UsesUnsafeCode Name="Local booleanptr of type: Boolean*" />
// <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" />
// <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" />
// </SecurityKernel>
[System.Security.SecurityCritical]
private static unsafe object EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize)
/*++
Routine Description:
This routine is used by WriteEvent to unbox the object type and
to fill the passed in ETW data descriptor.
Arguments:
data - argument to be decoded
dataDescriptor - pointer to the descriptor to be filled (updated to point to the next empty entry)
dataBuffer - storage buffer for storing user data, needed because cant get the address of the object
(updated to point to the next empty entry)
Return Value:
null if the object is a basic type other than string or byte[]. String otherwise
--*/
{
Again:
dataDescriptor->Reserved = 0;
string sRet = data as string;
byte[] blobRet = null;
if (sRet != null)
{
dataDescriptor->Size = ((uint)sRet.Length + 1) * 2;
}
else if ((blobRet = data as byte[]) != null)
{
// first store array length
*(int*)dataBuffer = blobRet.Length;
dataDescriptor->Ptr = (ulong)dataBuffer;
dataDescriptor->Size = 4;
totalEventSize += dataDescriptor->Size;
// then the array parameters
dataDescriptor++;
dataBuffer += s_basicTypeAllocationBufferSize;
dataDescriptor->Size = (uint)blobRet.Length;
}
else if (data is IntPtr)
{
dataDescriptor->Size = (uint)sizeof(IntPtr);
IntPtr* intptrPtr = (IntPtr*)dataBuffer;
*intptrPtr = (IntPtr)data;
dataDescriptor->Ptr = (ulong)intptrPtr;
}
else if (data is int)
{
dataDescriptor->Size = (uint)sizeof(int);
int* intptr = (int*)dataBuffer;
*intptr = (int)data;
dataDescriptor->Ptr = (ulong)intptr;
}
else if (data is long)
{
dataDescriptor->Size = (uint)sizeof(long);
long* longptr = (long*)dataBuffer;
*longptr = (long)data;
dataDescriptor->Ptr = (ulong)longptr;
}
else if (data is uint)
{
dataDescriptor->Size = (uint)sizeof(uint);
uint* uintptr = (uint*)dataBuffer;
*uintptr = (uint)data;
dataDescriptor->Ptr = (ulong)uintptr;
}
else if (data is UInt64)
{
dataDescriptor->Size = (uint)sizeof(ulong);
UInt64* ulongptr = (ulong*)dataBuffer;
*ulongptr = (ulong)data;
dataDescriptor->Ptr = (ulong)ulongptr;
}
else if (data is char)
{
dataDescriptor->Size = (uint)sizeof(char);
char* charptr = (char*)dataBuffer;
*charptr = (char)data;
dataDescriptor->Ptr = (ulong)charptr;
}
else if (data is byte)
{
dataDescriptor->Size = (uint)sizeof(byte);
byte* byteptr = (byte*)dataBuffer;
*byteptr = (byte)data;
dataDescriptor->Ptr = (ulong)byteptr;
}
else if (data is short)
{
dataDescriptor->Size = (uint)sizeof(short);
short* shortptr = (short*)dataBuffer;
*shortptr = (short)data;
dataDescriptor->Ptr = (ulong)shortptr;
}
else if (data is sbyte)
{
dataDescriptor->Size = (uint)sizeof(sbyte);
sbyte* sbyteptr = (sbyte*)dataBuffer;
*sbyteptr = (sbyte)data;
dataDescriptor->Ptr = (ulong)sbyteptr;
}
else if (data is ushort)
{
dataDescriptor->Size = (uint)sizeof(ushort);
ushort* ushortptr = (ushort*)dataBuffer;
*ushortptr = (ushort)data;
dataDescriptor->Ptr = (ulong)ushortptr;
}
else if (data is float)
{
dataDescriptor->Size = (uint)sizeof(float);
float* floatptr = (float*)dataBuffer;
*floatptr = (float)data;
dataDescriptor->Ptr = (ulong)floatptr;
}
else if (data is double)
{
dataDescriptor->Size = (uint)sizeof(double);
double* doubleptr = (double*)dataBuffer;
*doubleptr = (double)data;
dataDescriptor->Ptr = (ulong)doubleptr;
}
else if (data is bool)
{
// WIN32 Bool is 4 bytes
dataDescriptor->Size = 4;
int* intptr = (int*)dataBuffer;
if (((bool)data))
{
*intptr = 1;
}
else
{
*intptr = 0;
}
dataDescriptor->Ptr = (ulong)intptr;
}
else if (data is Guid)
{
dataDescriptor->Size = (uint)sizeof(Guid);
Guid* guidptr = (Guid*)dataBuffer;
*guidptr = (Guid)data;
dataDescriptor->Ptr = (ulong)guidptr;
}
else if (data is decimal)
{
dataDescriptor->Size = (uint)sizeof(decimal);
decimal* decimalptr = (decimal*)dataBuffer;
*decimalptr = (decimal)data;
dataDescriptor->Ptr = (ulong)decimalptr;
}
else if (data is DateTime)
{
const long UTCMinTicks = 504911232000000000;
long dateTimeTicks = 0;
// We cannot translate dates sooner than 1/1/1601 in UTC.
// To avoid getting an ArgumentOutOfRangeException we compare with 1/1/1601 DateTime ticks
if (((DateTime)data).Ticks > UTCMinTicks)
dateTimeTicks = ((DateTime)data).ToFileTimeUtc();
dataDescriptor->Size = (uint)sizeof(long);
long* longptr = (long*)dataBuffer;
*longptr = dateTimeTicks;
dataDescriptor->Ptr = (ulong)longptr;
}
else
{
if (data is System.Enum)
{
Type underlyingType = Enum.GetUnderlyingType(data.GetType());
if (underlyingType == typeof(int))
{
#if !ES_BUILD_PCL
data = ((IConvertible)data).ToInt32(null);
#else
data = (int)data;
#endif
goto Again;
}
else if (underlyingType == typeof(long))
{
#if !ES_BUILD_PCL
data = ((IConvertible)data).ToInt64(null);
#else
data = (long)data;
#endif
goto Again;
}
}
// To our eyes, everything else is a just a string
if (data == null)
sRet = "";
else
sRet = data.ToString();
dataDescriptor->Size = ((uint)sRet.Length + 1) * 2;
}
totalEventSize += dataDescriptor->Size;
// advance buffers
dataDescriptor++;
dataBuffer += s_basicTypeAllocationBufferSize;
return (object)sRet ?? (object)blobRet;
}
/// <summary>
/// WriteEvent, method to write a parameters with event schema properties
/// </summary>
/// <param name="eventDescriptor">
/// Event Descriptor for this event.
/// </param>
/// <param name="childActivityID">
/// childActivityID is marked as 'related' to the current activity ID.
/// </param>
/// <param name="eventPayload">
/// Payload for the ETW event.
/// </param>
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" />
// <UsesUnsafeCode Name="Local dataBuffer of type: Byte*" />
// <UsesUnsafeCode Name="Local pdata of type: Char*" />
// <UsesUnsafeCode Name="Local userData of type: EventData*" />
// <UsesUnsafeCode Name="Local userDataPtr of type: EventData*" />
// <UsesUnsafeCode Name="Local currentBuffer of type: Byte*" />
// <UsesUnsafeCode Name="Local v0 of type: Char*" />
// <UsesUnsafeCode Name="Local v1 of type: Char*" />
// <UsesUnsafeCode Name="Local v2 of type: Char*" />
// <UsesUnsafeCode Name="Local v3 of type: Char*" />
// <UsesUnsafeCode Name="Local v4 of type: Char*" />
// <UsesUnsafeCode Name="Local v5 of type: Char*" />
// <UsesUnsafeCode Name="Local v6 of type: Char*" />
// <UsesUnsafeCode Name="Local v7 of type: Char*" />
// <ReferencesCritical Name="Method: EncodeObject(Object&, EventData*, Byte*):String" Ring="1" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
[System.Security.SecurityCritical]
internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, params object[] eventPayload)
{
int status = 0;
if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords))
{
int argCount = 0;
unsafe
{
argCount = eventPayload.Length;
if (argCount > s_etwMaxNumberArguments)
{
s_returnCode = WriteEventErrorCode.TooManyArgs;
return false;
}
uint totalEventSize = 0;
int index;
int refObjIndex = 0;
List<int> refObjPosition = new List<int>(s_etwAPIMaxRefObjCount);
List<object> dataRefObj = new List<object>(s_etwAPIMaxRefObjCount);
EventData* userData = stackalloc EventData[2 * argCount];
EventData* userDataPtr = (EventData*)userData;
byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * 2 * argCount]; // Assume 16 chars for non-string argument
byte* currentBuffer = dataBuffer;
//
// The loop below goes through all the arguments and fills in the data
// descriptors. For strings save the location in the dataString array.
// Calculates the total size of the event by adding the data descriptor
// size value set in EncodeObject method.
//
bool hasNonStringRefArgs = false;
for (index = 0; index < eventPayload.Length; index++)
{
if (eventPayload[index] != null)
{
object supportedRefObj;
supportedRefObj = EncodeObject(ref eventPayload[index], ref userDataPtr, ref currentBuffer, ref totalEventSize);
if (supportedRefObj != null)
{
// EncodeObject advanced userDataPtr to the next empty slot
int idx = (int)(userDataPtr - userData - 1);
if (!(supportedRefObj is string))
{
if (eventPayload.Length + idx + 1 - index > s_etwMaxNumberArguments)
{
s_returnCode = WriteEventErrorCode.TooManyArgs;
return false;
}
hasNonStringRefArgs = true;
}
dataRefObj.Add(supportedRefObj);
refObjPosition.Add(idx);
refObjIndex++;
}
}
else
{
s_returnCode = WriteEventErrorCode.NullInput;
return false;
}
}
// update argCount based on ctual number of arguments written to 'userData'
argCount = (int)(userDataPtr - userData);
if (totalEventSize > s_traceEventMaximumSize)
{
s_returnCode = WriteEventErrorCode.EventTooBig;
return false;
}
// the optimized path (using "fixed" instead of allocating pinned GCHandles
if (!hasNonStringRefArgs && (refObjIndex < s_etwAPIMaxRefObjCount))
{
// Fast path: at most 8 string arguments
// ensure we have at least s_etwAPIMaxStringCount in dataString, so that
// the "fixed" statement below works
while (refObjIndex < s_etwAPIMaxRefObjCount)
{
dataRefObj.Add(null);
++refObjIndex;
}
//
// now fix any string arguments and set the pointer on the data descriptor
//
fixed (char* v0 = (string)dataRefObj[0], v1 = (string)dataRefObj[1], v2 = (string)dataRefObj[2], v3 = (string)dataRefObj[3],
v4 = (string)dataRefObj[4], v5 = (string)dataRefObj[5], v6 = (string)dataRefObj[6], v7 = (string)dataRefObj[7])
{
userDataPtr = (EventData*)userData;
if (dataRefObj[0] != null)
{
userDataPtr[refObjPosition[0]].Ptr = (ulong)v0;
}
if (dataRefObj[1] != null)
{
userDataPtr[refObjPosition[1]].Ptr = (ulong)v1;
}
if (dataRefObj[2] != null)
{
userDataPtr[refObjPosition[2]].Ptr = (ulong)v2;
}
if (dataRefObj[3] != null)
{
userDataPtr[refObjPosition[3]].Ptr = (ulong)v3;
}
if (dataRefObj[4] != null)
{
userDataPtr[refObjPosition[4]].Ptr = (ulong)v4;
}
if (dataRefObj[5] != null)
{
userDataPtr[refObjPosition[5]].Ptr = (ulong)v5;
}
if (dataRefObj[6] != null)
{
userDataPtr[refObjPosition[6]].Ptr = (ulong)v6;
}
if (dataRefObj[7] != null)
{
userDataPtr[refObjPosition[7]].Ptr = (ulong)v7;
}
status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData);
}
}
else
{
// Slow path: use pinned handles
userDataPtr = (EventData*)userData;
GCHandle[] rgGCHandle = new GCHandle[refObjIndex];
for (int i = 0; i < refObjIndex; ++i)
{
// below we still use "fixed" to avoid taking dependency on the offset of the first field
// in the object (the way we would need to if we used GCHandle.AddrOfPinnedObject)
rgGCHandle[i] = GCHandle.Alloc(dataRefObj[i], GCHandleType.Pinned);
if (dataRefObj[i] is string)
{
fixed (char* p = (string)dataRefObj[i])
userDataPtr[refObjPosition[i]].Ptr = (ulong)p;
}
else
{
fixed (byte* p = (byte[])dataRefObj[i])
userDataPtr[refObjPosition[i]].Ptr = (ulong)p;
}
}
status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData);
for (int i = 0; i < refObjIndex; ++i)
{
rgGCHandle[i].Free();
}
}
}
}
if (status != 0)
{
SetLastError((int)status);
return false;
}
return true;
}
/// <summary>
/// WriteEvent, method to be used by generated code on a derived class
/// </summary>
/// <param name="eventDescriptor">
/// Event Descriptor for this event.
/// </param>
/// <param name="childActivityID">
/// If this event is generating a child activity (WriteEventTransfer related activity) this is child activity
/// This can be null for events that do not generate a child activity.
/// </param>
/// <param name="dataCount">
/// number of event descriptors
/// </param>
/// <param name="data">
/// pointer do the event data
/// </param>
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
[System.Security.SecurityCritical]
internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data)
{
if (childActivityID != null)
{
// activity transfers are supported only for events that specify the Send or Receive opcode
Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Start ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop);
}
int status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, dataCount, (EventData*)data);
if (status != 0)
{
SetLastError(status);
return false;
}
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
[System.Security.SecurityCritical]
internal unsafe bool WriteEventRaw(
ref EventDescriptor eventDescriptor,
Guid* activityID,
Guid* relatedActivityID,
int dataCount,
IntPtr data)
{
int status;
status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(
m_regHandle,
ref eventDescriptor,
activityID,
relatedActivityID,
dataCount,
(EventData*)data);
if (status != 0)
{
SetLastError(status);
return false;
}
return true;
}
// These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work
// either with Manifest ETW or Classic ETW (if Manifest based ETW is not available).
[SecurityCritical]
private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback)
{
m_providerId = providerId;
m_etwCallback = enableCallback;
return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle);
}
[SecurityCritical]
private uint EventUnregister()
{
uint status = UnsafeNativeMethods.ManifestEtw.EventUnregister(m_regHandle);
m_regHandle = 0;
return status;
}
static int[] nibblebits = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
private static int bitcount(uint n)
{
int count = 0;
for(; n != 0; n = n >> 4)
count += nibblebits[n & 0x0f];
return count;
}
private static int bitindex(uint n)
{
Contract.Assert(bitcount(n) == 1);
int idx = 0;
while ((n & (1 << idx)) == 0)
idx++;
return idx;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void DivideDouble()
{
var test = new SimpleBinaryOpTest__DivideDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__DivideDouble
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int Op2ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable;
static SimpleBinaryOpTest__DivideDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__DivideDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.Divide(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.Divide(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.Divide(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Divide), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Divide), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Divide), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.Divide(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.Divide(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Divide(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Divide(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__DivideDouble();
var result = Avx.Divide(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.Divide(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(left[0] / right[0]) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(left[i] / right[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Divide)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// 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.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System.Reflection.Emit
{
public sealed class GenericTypeParameterBuilder : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Private Data Members
internal TypeBuilder m_type;
#endregion
#region Constructor
internal GenericTypeParameterBuilder(TypeBuilder type)
{
m_type = type;
}
#endregion
#region Object Overrides
public override String ToString()
{
return m_type.Name;
}
public override bool Equals(object o)
{
GenericTypeParameterBuilder g = o as GenericTypeParameterBuilder;
if (g == null)
return false;
return object.ReferenceEquals(g.m_type, m_type);
}
public override int GetHashCode() { return m_type.GetHashCode(); }
#endregion
#region MemberInfo Overrides
public override Type DeclaringType { get { return m_type.DeclaringType; } }
public override Type ReflectedType { get { return m_type.ReflectedType; } }
public override String Name { get { return m_type.Name; } }
public override Module Module { get { return m_type.Module; } }
internal int MetadataTokenInternal { get { return m_type.MetadataTokenInternal; } }
#endregion
#region Type Overrides
public override Type MakePointerType()
{
return SymbolType.FormCompoundType("*", this, 0);
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&", this, 0);
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]", this, 0);
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
string szrank = "";
if (rank == 1)
{
szrank = "*";
}
else
{
for (int i = 1; i < rank; i++)
szrank += ",";
}
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
SymbolType st = SymbolType.FormCompoundType(s, this, 0) as SymbolType;
return st;
}
public override Guid GUID { get { throw new NotSupportedException(); } }
public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly { get { return m_type.Assembly; } }
public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
public override String FullName { get { return null; } }
public override String Namespace { get { return null; } }
public override String AssemblyQualifiedName { get { return null; } }
public override Type BaseType { get { return m_type.BaseType; } }
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetInterface(String name, bool ignoreCase) { throw new NotSupportedException(); }
public override Type[] GetInterfaces() { throw new NotSupportedException(); }
public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents() { throw new NotSupportedException(); }
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Public; }
public override bool IsTypeDefinition => false;
public override bool IsSZArray => false;
protected override bool IsArrayImpl() { return false; }
protected override bool IsByRefImpl() { return false; }
protected override bool IsPointerImpl() { return false; }
protected override bool IsPrimitiveImpl() { return false; }
protected override bool IsCOMObjectImpl() { return false; }
public override Type GetElementType() { throw new NotSupportedException(); }
protected override bool HasElementTypeImpl() { return false; }
public override Type UnderlyingSystemType { get { return this; } }
public override Type[] GetGenericArguments() { throw new InvalidOperationException(); }
public override bool IsGenericTypeDefinition { get { return false; } }
public override bool IsGenericType { get { return false; } }
public override bool IsGenericParameter { get { return true; } }
public override bool IsConstructedGenericType { get { return false; } }
public override int GenericParameterPosition { get { return m_type.GenericParameterPosition; } }
public override bool ContainsGenericParameters { get { return m_type.ContainsGenericParameters; } }
public override GenericParameterAttributes GenericParameterAttributes { get { return m_type.GenericParameterAttributes; } }
public override MethodBase DeclaringMethod { get { return m_type.DeclaringMethod; } }
public override Type GetGenericTypeDefinition() { throw new InvalidOperationException(); }
public override Type MakeGenericType(params Type[] typeArguments) { throw new InvalidOperationException(SR.Arg_NotGenericTypeDefinition); }
protected override bool IsValueTypeImpl() { return false; }
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
[Pure]
public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); }
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); }
public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); }
#endregion
#region Public Members
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_type.SetGenParamCustomAttribute(con, binaryAttribute);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
m_type.SetGenParamCustomAttribute(customBuilder);
}
public void SetBaseTypeConstraint(Type baseTypeConstraint)
{
m_type.CheckContext(baseTypeConstraint);
m_type.SetParent(baseTypeConstraint);
}
public void SetInterfaceConstraints(params Type[] interfaceConstraints)
{
m_type.CheckContext(interfaceConstraints);
m_type.SetInterfaces(interfaceConstraints);
}
public void SetGenericParameterAttributes(GenericParameterAttributes genericParameterAttributes)
{
m_type.SetGenParamAttributes(genericParameterAttributes);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Friends;
using OpenSim.Server.Base;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.Avatar.Friends
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FriendsModule")]
public class FriendsModule : ISharedRegionModule, IFriendsModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_Enabled = false;
protected class UserFriendData
{
public UUID PrincipalID;
public FriendInfo[] Friends;
public int Refcount;
public bool IsFriend(string friend)
{
foreach (FriendInfo fi in Friends)
{
if (fi.Friend == friend)
return true;
}
return false;
}
}
protected static readonly FriendInfo[] EMPTY_FRIENDS = new FriendInfo[0];
protected List<Scene> m_Scenes = new List<Scene>();
protected IPresenceService m_PresenceService = null;
protected IFriendsService m_FriendsService = null;
protected FriendsSimConnector m_FriendsSimConnector;
/// <summary>
/// Cache friends lists for users.
/// </summary>
/// <remarks>
/// This is a complex and error-prone thing to do. At the moment, we assume that the efficiency gained in
/// permissions checks outweighs the disadvantages of that complexity.
/// </remarks>
protected Dictionary<UUID, UserFriendData> m_Friends = new Dictionary<UUID, UserFriendData>();
/// <summary>
/// Maintain a record of viewers that need to be sent notifications for friends that are online. This only
/// needs to be done on login. Subsequent online/offline friend changes are sent by a different mechanism.
/// </summary>
protected HashSet<UUID> m_NeedsListOfOnlineFriends = new HashSet<UUID>();
protected IPresenceService PresenceService
{
get
{
if (m_PresenceService == null)
{
if (m_Scenes.Count > 0)
m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
}
return m_PresenceService;
}
}
public IFriendsService FriendsService
{
get
{
if (m_FriendsService == null)
{
if (m_Scenes.Count > 0)
m_FriendsService = m_Scenes[0].RequestModuleInterface<IFriendsService>();
}
return m_FriendsService;
}
}
protected IGridService GridService
{
get { return m_Scenes[0].GridService; }
}
public IUserAccountService UserAccountService
{
get { return m_Scenes[0].UserAccountService; }
}
public IScene Scene
{
get
{
if (m_Scenes.Count > 0)
return m_Scenes[0];
else
return null;
}
}
#region ISharedRegionModule
public void Initialise(IConfigSource config)
{
IConfig moduleConfig = config.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("FriendsModule", "FriendsModule");
if (name == Name)
{
InitModule(config);
m_Enabled = true;
m_log.DebugFormat("[FRIENDS MODULE]: {0} enabled.", Name);
}
}
}
protected virtual void InitModule(IConfigSource config)
{
IConfig friendsConfig = config.Configs["Friends"];
if (friendsConfig != null)
{
int mPort = friendsConfig.GetInt("Port", 0);
string connector = friendsConfig.GetString("Connector", String.Empty);
Object[] args = new Object[] { config };
m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(connector, args);
m_FriendsSimConnector = new FriendsSimConnector();
// Instantiate the request handler
IHttpServer server = MainServer.GetHttpServer((uint)mPort);
if (server != null)
server.AddStreamHandler(new FriendsRequestHandler(this));
}
if (m_FriendsService == null)
{
m_log.Error("[FRIENDS]: No Connector defined in section Friends, or failed to load, cannot continue");
throw new Exception("Connector load error");
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
// m_log.DebugFormat("[FRIENDS MODULE]: AddRegion on {0}", Name);
m_Scenes.Add(scene);
scene.RegisterModuleInterface<IFriendsModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnClientClosed += OnClientClosed;
scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
scene.EventManager.OnClientLogin += OnClientLogin;
}
public virtual void RegionLoaded(Scene scene) {}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenes.Remove(scene);
}
public virtual string Name
{
get { return "FriendsModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
public virtual int GetRightsGrantedByFriend(UUID principalID, UUID friendID)
{
FriendInfo[] friends = GetFriendsFromCache(principalID);
FriendInfo finfo = GetFriend(friends, friendID);
if (finfo != null)
{
return finfo.TheirFlags;
}
return 0;
}
private void OnNewClient(IClientAPI client)
{
client.OnInstantMessage += OnInstantMessage;
client.OnApproveFriendRequest += OnApproveFriendRequest;
client.OnDenyFriendRequest += OnDenyFriendRequest;
client.OnTerminateFriendship += RemoveFriendship;
client.OnGrantUserRights += GrantRights;
// We need to cache information for child agents as well as root agents so that friend edit/move/delete
// permissions will work across borders where both regions are on different simulators.
//
// Do not do this asynchronously. If we do, then subsequent code can outrace CacheFriends() and
// return misleading results from the still empty friends cache.
// If we absolutely need to do this asynchronously, then a signalling mechanism is needed so that calls
// to GetFriends() will wait until CacheFriends() completes. Locks are insufficient.
CacheFriends(client);
}
/// <summary>
/// Cache the friends list or increment the refcount for the existing friends list.
/// </summary>
/// <param name="client">
/// </param>
/// <returns>
/// Returns true if the list was fetched, false if it wasn't
/// </returns>
protected virtual bool CacheFriends(IClientAPI client)
{
UUID agentID = client.AgentId;
lock (m_Friends)
{
UserFriendData friendsData;
if (m_Friends.TryGetValue(agentID, out friendsData))
{
friendsData.Refcount++;
return false;
}
else
{
friendsData = new UserFriendData();
friendsData.PrincipalID = agentID;
friendsData.Friends = GetFriendsFromService(client);
friendsData.Refcount = 1;
m_Friends[agentID] = friendsData;
return true;
}
}
}
private void OnClientClosed(UUID agentID, Scene scene)
{
ScenePresence sp = scene.GetScenePresence(agentID);
if (sp != null && !sp.IsChildAgent)
{
// do this for root agents closing out
StatusChange(agentID, false);
}
lock (m_Friends)
{
UserFriendData friendsData;
if (m_Friends.TryGetValue(agentID, out friendsData))
{
friendsData.Refcount--;
if (friendsData.Refcount <= 0)
m_Friends.Remove(agentID);
}
}
}
private void OnMakeRootAgent(ScenePresence sp)
{
RecacheFriends(sp.ControllingClient);
}
private void OnClientLogin(IClientAPI client)
{
UUID agentID = client.AgentId;
//m_log.DebugFormat("[XXX]: OnClientLogin!");
// Inform the friends that this user is online
StatusChange(agentID, true);
// Register that we need to send the list of online friends to this user
lock (m_NeedsListOfOnlineFriends)
m_NeedsListOfOnlineFriends.Add(agentID);
}
public virtual bool SendFriendsOnlineIfNeeded(IClientAPI client)
{
UUID agentID = client.AgentId;
// Check if the online friends list is needed
lock (m_NeedsListOfOnlineFriends)
{
if (!m_NeedsListOfOnlineFriends.Remove(agentID))
return false;
}
// Send the friends online
List<UUID> online = GetOnlineFriends(agentID);
if (online.Count > 0)
client.SendAgentOnline(online.ToArray());
// Send outstanding friendship offers
List<string> outstanding = new List<string>();
FriendInfo[] friends = GetFriendsFromCache(agentID);
foreach (FriendInfo fi in friends)
{
if (fi.TheirFlags == -1)
outstanding.Add(fi.Friend);
}
GridInstantMessage im = new GridInstantMessage(client.Scene, UUID.Zero, String.Empty, agentID, (byte)InstantMessageDialog.FriendshipOffered,
"Will you be my friend?", true, Vector3.Zero);
foreach (string fid in outstanding)
{
UUID fromAgentID;
string firstname = "Unknown", lastname = "UserFMSFOIN";
if (!GetAgentInfo(client.Scene.RegionInfo.ScopeID, fid, out fromAgentID, out firstname, out lastname))
{
m_log.DebugFormat("[FRIENDS MODULE]: skipping malformed friend {0}", fid);
continue;
}
im.offline = 0;
im.fromAgentID = fromAgentID.Guid;
im.fromAgentName = firstname + " " + lastname;
im.imSessionID = im.fromAgentID;
im.message = FriendshipMessage(fid);
LocalFriendshipOffered(agentID, im);
}
return true;
}
protected virtual string FriendshipMessage(string friendID)
{
return "Will you be my friend?";
}
protected virtual bool GetAgentInfo(UUID scopeID, string fid, out UUID agentID, out string first, out string last)
{
first = "Unknown"; last = "UserFMGAI";
if (!UUID.TryParse(fid, out agentID))
return false;
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(scopeID, agentID);
if (account != null)
{
first = account.FirstName;
last = account.LastName;
}
return true;
}
List<UUID> GetOnlineFriends(UUID userID)
{
List<string> friendList = new List<string>();
FriendInfo[] friends = GetFriendsFromCache(userID);
foreach (FriendInfo fi in friends)
{
if (((fi.TheirFlags & (int)FriendRights.CanSeeOnline) != 0) && (fi.TheirFlags != -1))
friendList.Add(fi.Friend);
}
List<UUID> online = new List<UUID>();
if (friendList.Count > 0)
GetOnlineFriends(userID, friendList, online);
// m_log.DebugFormat(
// "[FRIENDS MODULE]: User {0} has {1} friends online", userID, online.Count);
return online;
}
protected virtual void GetOnlineFriends(UUID userID, List<string> friendList, /*collector*/ List<UUID> online)
{
// m_log.DebugFormat(
// "[FRIENDS MODULE]: Looking for online presence of {0} users for {1}", friendList.Count, userID);
PresenceInfo[] presence = PresenceService.GetAgents(friendList.ToArray());
foreach (PresenceInfo pi in presence)
{
UUID presenceID;
if (UUID.TryParse(pi.UserID, out presenceID))
online.Add(presenceID);
}
}
/// <summary>
/// Find the client for a ID
/// </summary>
public IClientAPI LocateClientObject(UUID agentID)
{
lock (m_Scenes)
{
foreach (Scene scene in m_Scenes)
{
ScenePresence presence = scene.GetScenePresence(agentID);
if (presence != null && !presence.IsChildAgent)
return presence.ControllingClient;
}
}
return null;
}
/// <summary>
/// Caller beware! Call this only for root agents.
/// </summary>
/// <param name="agentID"></param>
/// <param name="online"></param>
private void StatusChange(UUID agentID, bool online)
{
FriendInfo[] friends = GetFriendsFromCache(agentID);
if (friends.Length > 0)
{
List<FriendInfo> friendList = new List<FriendInfo>();
foreach (FriendInfo fi in friends)
{
if (((fi.MyFlags & (int)FriendRights.CanSeeOnline) != 0) && (fi.TheirFlags != -1))
friendList.Add(fi);
}
Util.FireAndForget(
delegate
{
// m_log.DebugFormat(
// "[FRIENDS MODULE]: Notifying {0} friends of {1} of online status {2}",
// friendList.Count, agentID, online);
// Notify about this user status
StatusNotify(friendList, agentID, online);
}
);
}
}
protected virtual void StatusNotify(List<FriendInfo> friendList, UUID userID, bool online)
{
//m_log.DebugFormat("[FRIENDS]: Entering StatusNotify for {0}", userID);
List<string> friendStringIds = friendList.ConvertAll<string>(friend => friend.Friend);
List<string> remoteFriendStringIds = new List<string>();
foreach (string friendStringId in friendStringIds)
{
UUID friendUuid;
if (UUID.TryParse(friendStringId, out friendUuid))
{
if (LocalStatusNotification(userID, friendUuid, online))
continue;
remoteFriendStringIds.Add(friendStringId);
}
else
{
m_log.WarnFormat("[FRIENDS]: Error parsing friend ID {0}", friendStringId);
}
}
// We do this regrouping so that we can efficiently send a single request rather than one for each
// friend in what may be a very large friends list.
PresenceInfo[] friendSessions = PresenceService.GetAgents(remoteFriendStringIds.ToArray());
foreach (PresenceInfo friendSession in friendSessions)
{
// let's guard against sessions-gone-bad
if (friendSession != null && friendSession.RegionID != UUID.Zero)
{
//m_log.DebugFormat("[FRIENDS]: Get region {0}", friendSession.RegionID);
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
if (region != null)
{
m_FriendsSimConnector.StatusNotify(region, userID, friendSession.UserID, online);
}
}
//else
// m_log.DebugFormat("[FRIENDS]: friend session is null or the region is UUID.Zero");
}
}
protected virtual void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
if ((InstantMessageDialog)im.dialog == InstantMessageDialog.FriendshipOffered)
{
// we got a friendship offer
UUID principalID = new UUID(im.fromAgentID);
UUID friendID = new UUID(im.toAgentID);
m_log.DebugFormat("[FRIENDS]: {0} ({1}) offered friendship to {2} ({3})", principalID, client.FirstName + client.LastName, friendID, im.fromAgentName);
// Check that the friendship doesn't exist yet
FriendInfo[] finfos = GetFriendsFromCache(principalID);
if (finfos != null)
{
FriendInfo f = GetFriend(finfos, friendID);
if (f != null)
{
client.SendAgentAlertMessage("This person is already your friend. Please delete it first if you want to reestablish the friendship.", false);
return;
}
}
// This user wants to be friends with the other user.
// Let's add the relation backwards, in case the other is not online
StoreBackwards(friendID, principalID);
// Now let's ask the other user to be friends with this user
ForwardFriendshipOffer(principalID, friendID, im);
}
}
protected virtual bool ForwardFriendshipOffer(UUID agentID, UUID friendID, GridInstantMessage im)
{
// !!!!!!!! This is a hack so that we don't have to keep state (transactionID/imSessionID)
// We stick this agent's ID as imSession, so that it's directly available on the receiving end
im.imSessionID = im.fromAgentID;
im.fromAgentName = GetFriendshipRequesterName(agentID);
// Try the local sim
if (LocalFriendshipOffered(friendID, im))
return true;
// The prospective friend is not here [as root]. Let's forward.
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipOffered(region, agentID, friendID, im.message);
return true;
}
}
// If the prospective friend is not online, he'll get the message upon login.
return false;
}
protected virtual string GetFriendshipRequesterName(UUID agentID)
{
UserAccount account = UserAccountService.GetUserAccount(UUID.Zero, agentID);
return (account == null) ? "Unknown" : account.FirstName + " " + account.LastName;
}
protected virtual void OnApproveFriendRequest(IClientAPI client, UUID friendID, List<UUID> callingCardFolders)
{
m_log.DebugFormat("[FRIENDS]: {0} accepted friendship from {1}", client.AgentId, friendID);
AddFriendship(client, friendID);
}
public void AddFriendship(IClientAPI client, UUID friendID)
{
StoreFriendships(client.AgentId, friendID);
ICallingCardModule ccm = client.Scene.RequestModuleInterface<ICallingCardModule>();
if (ccm != null)
{
ccm.CreateCallingCard(client.AgentId, friendID, UUID.Zero);
}
// Update the local cache.
RecacheFriends(client);
//
// Notify the friend
//
// Try Local
if (LocalFriendshipApproved(client.AgentId, client.Name, friendID))
{
client.SendAgentOnline(new UUID[] { friendID });
return;
}
// The friend is not here
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipApproved(region, client.AgentId, client.Name, friendID);
client.SendAgentOnline(new UUID[] { friendID });
}
}
}
private void OnDenyFriendRequest(IClientAPI client, UUID friendID, List<UUID> callingCardFolders)
{
m_log.DebugFormat("[FRIENDS]: {0} denied friendship to {1}", client.AgentId, friendID);
DeleteFriendship(client.AgentId, friendID);
//
// Notify the friend
//
// Try local
if (LocalFriendshipDenied(client.AgentId, client.Name, friendID))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
if (region != null)
m_FriendsSimConnector.FriendshipDenied(region, client.AgentId, client.Name, friendID);
else
m_log.WarnFormat("[FRIENDS]: Could not find region {0} in locating {1}", friendSession.RegionID, friendID);
}
}
}
public void RemoveFriendship(IClientAPI client, UUID exfriendID)
{
if (!DeleteFriendship(client.AgentId, exfriendID))
client.SendAlertMessage("Unable to terminate friendship on this sim.");
// Update local cache
RecacheFriends(client);
client.SendTerminateFriend(exfriendID);
//
// Notify the friend
//
// Try local
if (LocalFriendshipTerminated(client.AgentId, exfriendID))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { exfriendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipTerminated(region, client.AgentId, exfriendID);
}
}
}
public void GrantRights(IClientAPI remoteClient, UUID friendID, int rights)
{
UUID requester = remoteClient.AgentId;
m_log.DebugFormat(
"[FRIENDS MODULE]: User {0} changing rights to {1} for friend {2}",
requester, rights, friendID);
FriendInfo[] friends = GetFriendsFromCache(requester);
if (friends.Length == 0)
{
return;
}
// Let's find the friend in this user's friend list
FriendInfo friend = GetFriend(friends, friendID);
if (friend != null) // Found it
{
// Store it on the DB
if (!StoreRights(requester, friendID, rights))
{
remoteClient.SendAlertMessage("Unable to grant rights.");
return;
}
// Store it in the local cache
int myFlags = friend.MyFlags;
friend.MyFlags = rights;
// Always send this back to the original client
remoteClient.SendChangeUserRights(requester, friendID, rights);
//
// Notify the friend
//
// Try local
if (LocalGrantRights(requester, friendID, myFlags, rights))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
// TODO: You might want to send the delta to save the lookup
// on the other end!!
m_FriendsSimConnector.GrantRights(region, requester, friendID, myFlags, rights);
}
}
}
else
{
m_log.DebugFormat("[FRIENDS MODULE]: friend {0} not found for {1}", friendID, requester);
}
}
protected virtual FriendInfo GetFriend(FriendInfo[] friends, UUID friendID)
{
foreach (FriendInfo fi in friends)
{
if (fi.Friend == friendID.ToString())
return fi;
}
return null;
}
#region Local
public virtual bool LocalFriendshipOffered(UUID toID, GridInstantMessage im)
{
IClientAPI friendClient = LocateClientObject(toID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
friendClient.SendInstantMessage(im);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipApproved(UUID userID, string userName, UUID friendID)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
(byte)OpenMetaverse.InstantMessageDialog.FriendshipAccepted, userID.ToString(), false, Vector3.Zero);
friendClient.SendInstantMessage(im);
ICallingCardModule ccm = friendClient.Scene.RequestModuleInterface<ICallingCardModule>();
if (ccm != null)
{
ccm.CreateCallingCard(friendID, userID, UUID.Zero);
}
// Update the local cache
RecacheFriends(friendClient);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipDenied(UUID userID, string userName, UUID friendID)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
(byte)OpenMetaverse.InstantMessageDialog.FriendshipDeclined, userID.ToString(), false, Vector3.Zero);
friendClient.SendInstantMessage(im);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipTerminated(UUID userID, UUID exfriendID)
{
IClientAPI friendClient = LocateClientObject(exfriendID);
if (friendClient != null)
{
// the friend in this sim as root agent
friendClient.SendTerminateFriend(userID);
// update local cache
RecacheFriends(friendClient);
// we're done
return true;
}
return false;
}
public bool LocalGrantRights(UUID userID, UUID friendID, int userFlags, int rights)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
bool onlineBitChanged = ((rights ^ userFlags) & (int)FriendRights.CanSeeOnline) != 0;
if (onlineBitChanged)
{
if ((rights & (int)FriendRights.CanSeeOnline) == 1)
friendClient.SendAgentOnline(new UUID[] { userID });
else
friendClient.SendAgentOffline(new UUID[] { userID });
}
else
{
bool canEditObjectsChanged = ((rights ^ userFlags) & (int)FriendRights.CanModifyObjects) != 0;
if (canEditObjectsChanged)
friendClient.SendChangeUserRights(userID, friendID, rights);
}
// Update local cache
UpdateLocalCache(userID, friendID, rights);
return true;
}
return false;
}
public bool LocalStatusNotification(UUID userID, UUID friendID, bool online)
{
//m_log.DebugFormat("[FRIENDS]: Local Status Notify {0} that user {1} is {2}", friendID, userID, online);
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the friend in this sim as root agent
if (online)
friendClient.SendAgentOnline(new UUID[] { userID });
else
friendClient.SendAgentOffline(new UUID[] { userID });
// we're done
return true;
}
return false;
}
#endregion
#region Get / Set friends in several flavours
public FriendInfo[] GetFriendsFromCache(UUID userID)
{
UserFriendData friendsData;
lock (m_Friends)
{
if (m_Friends.TryGetValue(userID, out friendsData))
return friendsData.Friends;
}
return EMPTY_FRIENDS;
}
/// <summary>
/// Update local cache only
/// </summary>
/// <param name="userID"></param>
/// <param name="friendID"></param>
/// <param name="rights"></param>
protected void UpdateLocalCache(UUID userID, UUID friendID, int rights)
{
// Update local cache
lock (m_Friends)
{
FriendInfo[] friends = GetFriendsFromCache(friendID);
FriendInfo finfo = GetFriend(friends, userID);
finfo.TheirFlags = rights;
}
}
public virtual FriendInfo[] GetFriendsFromService(IClientAPI client)
{
return FriendsService.GetFriends(client.AgentId);
}
protected void RecacheFriends(IClientAPI client)
{
// FIXME: Ideally, we want to avoid doing this here since it sits the EventManager.OnMakeRootAgent event
// is on the critical path for transferring an avatar from one region to another.
UUID agentID = client.AgentId;
lock (m_Friends)
{
UserFriendData friendsData;
if (m_Friends.TryGetValue(agentID, out friendsData))
friendsData.Friends = GetFriendsFromService(client);
}
}
public bool AreFriendsCached(UUID userID)
{
lock (m_Friends)
return m_Friends.ContainsKey(userID);
}
protected virtual bool StoreRights(UUID agentID, UUID friendID, int rights)
{
FriendsService.StoreFriend(agentID.ToString(), friendID.ToString(), rights);
return true;
}
protected virtual void StoreBackwards(UUID friendID, UUID agentID)
{
FriendsService.StoreFriend(friendID.ToString(), agentID.ToString(), 0);
}
protected virtual void StoreFriendships(UUID agentID, UUID friendID)
{
FriendsService.StoreFriend(agentID.ToString(), friendID.ToString(), (int)FriendRights.CanSeeOnline);
FriendsService.StoreFriend(friendID.ToString(), agentID.ToString(), (int)FriendRights.CanSeeOnline);
}
protected virtual bool DeleteFriendship(UUID agentID, UUID exfriendID)
{
FriendsService.Delete(agentID, exfriendID.ToString());
FriendsService.Delete(exfriendID, agentID.ToString());
return true;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
// The Windows implementation of PipeStream sets the stream's handle during
// creation, and as such should always have a handle, but the Unix implementation
// sometimes sets the handle not during creation but later during connection.
// As such, validation during member access needs to verify a valid handle on
// Windows, but can't assume a valid handle on Unix.
internal const bool CheckOperationsRequiresSetHandle = false;
internal static string GetPipePath(string serverName, string pipeName)
{
if (serverName != "." && serverName != Interop.libc.gethostname())
{
// Cross-machine pipes are not supported.
throw new PlatformNotSupportedException();
}
if (pipeName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
{
// Since pipes are stored as files in the file system, we don't support
// pipe names that are actually paths or that otherwise have invalid
// filename characters in them.
throw new PlatformNotSupportedException();
}
// Return the pipe path
return Path.Combine(EnsurePipeDirectoryPath(), pipeName);
}
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
SysCall(safePipeHandle, (fd, _, __, ___) =>
{
Interop.Sys.FileStatus status;
int result = Interop.Sys.FStat(fd, out status);
if (result == 0)
{
if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
return result;
});
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
[SecurityCritical]
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// nop
}
private void UninitializeAsyncHandle()
{
// nop
}
private int ReadCore(byte[] buffer, int offset, int count)
{
return ReadCoreNoCancellation(buffer, offset, count);
}
private void WriteCore(byte[] buffer, int offset, int count)
{
WriteCoreNoCancellation(buffer, offset, count);
}
private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
SemaphoreSlim activeAsync = EnsureAsyncActiveSemaphoreInitialized();
await activeAsync.WaitAsync(cancellationToken).ForceAsync();
try
{
return cancellationToken.CanBeCanceled ?
ReadCoreWithCancellation(buffer, offset, count, cancellationToken) :
ReadCoreNoCancellation(buffer, offset, count);
}
finally
{
activeAsync.Release();
}
}
private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
SemaphoreSlim activeAsync = EnsureAsyncActiveSemaphoreInitialized();
await activeAsync.WaitAsync(cancellationToken).ForceAsync();
try
{
if (cancellationToken.CanBeCanceled)
WriteCoreWithCancellation(buffer, offset, count, cancellationToken);
else
WriteCoreNoCancellation(buffer, offset, count);
}
finally
{
activeAsync.Release();
}
}
// Blocks until the other end of the pipe has read in all written buffer.
[SecurityCritical]
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
throw new PlatformNotSupportedException(); // no mechanism for this on Unix
}
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public virtual PipeTransmissionMode TransmissionMode
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public virtual int InBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
return GetPipeBufferSize();
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public virtual int OutBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
return GetPipeBufferSize();
}
}
public virtual PipeTransmissionMode ReadMode
{
[SecurityCritical]
get
{
CheckPipePropertyOperations();
return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
}
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based
{
throw new PlatformNotSupportedException();
}
// nop, since it's already the only valid value
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private static string s_pipeDirectoryPath;
/// <summary>
/// We want to ensure that only one asynchronous operation is actually in flight
/// at a time. The base Stream class ensures this by serializing execution via a
/// semaphore. Since we don't delegate to the base stream for Read/WriteAsync due
/// to having specialized support for cancellation, we do the same serialization here.
/// </summary>
private SemaphoreSlim _asyncActiveSemaphore;
private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
private static string EnsurePipeDirectoryPath()
{
const string PipesFeatureName = "pipes";
// Ideally this would simply use PersistedFiles.GetTempFeatureDirectory(PipesFeatureName) and then
// Directory.CreateDirectory to ensure it exists. But this assembly doesn't reference System.IO.FileSystem.
// As such, we'd be calling GetTempFeatureDirectory, only to then need to parse it in order
// to create each of the individual directories as part of the path. We instead access the named portions
// of the path directly and do the building of the path and directory structure manually.
// First ensure we know what the full path should be, e.g. /tmp/.dotnet/corefx/pipes/
string fullPath = s_pipeDirectoryPath;
string tempPath = null;
if (fullPath == null)
{
tempPath = Path.GetTempPath();
fullPath = Path.Combine(tempPath, PersistedFiles.TopLevelHiddenDirectory, PersistedFiles.SecondLevelDirectory, PipesFeatureName);
s_pipeDirectoryPath = fullPath;
}
// Then create the directory if it doesn't already exist. If we get any error back from stat,
// just proceed to build up the directory, failing in the CreateDirectory calls if there's some
// problem. Similarly, it's possible stat succeeds but the path is a file rather than directory; we'll
// call that success for now and let this fail later when the code tries to create a file in this "directory"
// (we don't want to overwrite/delete whatever that unknown file may be, and this is similar to other cases
// we can't control where the file system is manipulated concurrently with and separately from this code).
Interop.Sys.FileStatus ignored;
bool pathExists = Interop.Sys.Stat(fullPath, out ignored) == 0;
if (!pathExists)
{
// We need to build up the directory manually. Ensure we have the temp directory in which
// we'll create the structure, e.g. /tmp/
if (tempPath == null)
{
tempPath = Path.GetTempPath();
}
Debug.Assert(Interop.Sys.Stat(tempPath, out ignored) == 0, "Path.GetTempPath() directory could not be accessed");
// Create /tmp/.dotnet/ if it doesn't exist.
string partialPath = Path.Combine(tempPath, PersistedFiles.TopLevelHiddenDirectory);
CreateDirectory(partialPath);
// Create /tmp/.dotnet/corefx/ if it doesn't exist
partialPath = Path.Combine(partialPath, PersistedFiles.SecondLevelDirectory);
CreateDirectory(partialPath);
// Create /tmp/.dotnet/corefx/pipes/ if it doesn't exist
CreateDirectory(fullPath);
}
return fullPath;
}
private static void CreateDirectory(string directoryPath)
{
while (true)
{
int result = Interop.Sys.MkDir(directoryPath, (int)Interop.Sys.Permissions.S_IRWXU);
// If successful created, we're done.
if (result >= 0)
return;
// If the directory already exists, consider it a success.
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EEXIST)
return;
// If the I/O was interrupted, try again.
if (errorInfo.Error == Interop.Error.EINTR)
continue;
// Otherwise, fail.
throw Interop.GetExceptionForIoErrno(errorInfo, directoryPath, isDirectory: true);
}
}
internal static Interop.Sys.OpenFlags TranslateFlags(PipeDirection direction, PipeOptions options, HandleInheritability inheritability)
{
// Translate direction
Interop.Sys.OpenFlags flags =
direction == PipeDirection.InOut ? Interop.Sys.OpenFlags.O_RDWR :
direction == PipeDirection.Out ? Interop.Sys.OpenFlags.O_WRONLY :
Interop.Sys.OpenFlags.O_RDONLY;
// Translate options
if ((options & PipeOptions.WriteThrough) != 0)
{
flags |= Interop.Sys.OpenFlags.O_SYNC;
}
// Translate inheritability.
if ((inheritability & HandleInheritability.Inheritable) == 0)
{
flags |= Interop.Sys.OpenFlags.O_CLOEXEC;
}
// PipeOptions.Asynchronous is ignored, at least for now. Asynchronous processing
// is handling just by queueing a work item to do the work synchronously on a pool thread.
return flags;
}
private unsafe int ReadCoreNoCancellation(byte[] buffer, int offset, int count)
{
DebugAssertReadWriteArgs(buffer, offset, count, _handle);
fixed (byte* bufPtr = buffer)
{
return (int)SysCall(_handle, (fd, ptr, len, _) =>
{
int result = Interop.Sys.Read(fd, (byte*)ptr, len);
Debug.Assert(result <= len);
return result;
}, (IntPtr)(bufPtr + offset), count);
}
}
private unsafe int ReadCoreWithCancellation(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
DebugAssertReadWriteArgs(buffer, offset, count, _handle);
Debug.Assert(cancellationToken.CanBeCanceled, "ReadCoreNoCancellation should be used if cancellation can't happen");
// Register for a cancellation request. This will throw if cancellation has already been requested,
// and otherwise will write to the cancellation pipe if/when cancellation has been requested.
using (DescriptorCancellationRegistration cancellation = RegisterForCancellation(cancellationToken))
{
bool gotRef = false;
try
{
cancellation.Poll.DangerousAddRef(ref gotRef);
fixed (byte* bufPtr = buffer)
{
const int CancellationSentinel = -42;
int rv = (int)SysCall(_handle, (fd, ptr, len, cancellationFd) =>
{
// We want to wait for data to be available on either the pipe we want to read from
// or on the cancellation pipe, which would signal a cancellation request.
Interop.Sys.PollFD* fds = stackalloc Interop.Sys.PollFD[2];
fds[0] = new Interop.Sys.PollFD { FD = fd, Events = Interop.Sys.PollFlags.POLLIN, REvents = 0 };
fds[1] = new Interop.Sys.PollFD { FD = (int)cancellationFd, Events = Interop.Sys.PollFlags.POLLIN, REvents = 0 };
// Some systems (at least OS X) appear to have a race condition in poll with FIFOs where the poll can
// end up not noticing writes of greater than the internal buffer size. Restarting the poll causes it
// to notice. To deal with that, we loop around poll, first starting with a small timeout and backing off
// to a larger one. This ensures we'll at least eventually notice such changes in these corner
// cases, while not adding too much overhead on systems that don't suffer from the problem.
const int InitialMsTimeout = 30, MaxMsTimeout = 2000;
for (int timeout = InitialMsTimeout; ; timeout = Math.Min(timeout * 2, MaxMsTimeout))
{
// Do the poll.
int signaledFdCount;
while (Interop.CheckIo(signaledFdCount = Interop.Sys.Poll(fds, 2, timeout))) ;
if (cancellationToken.IsCancellationRequested)
{
// Cancellation occurred. Bail by returning the cancellation sentinel.
return CancellationSentinel;
}
else if (signaledFdCount == 0)
{
// Timeout occurred. Loop around to poll again.
continue;
}
else
{
// Our pipe is ready. Break out of the loop to read from it.
Debug.Assert((fds[0].REvents & Interop.Sys.PollFlags.POLLIN) != 0, "Expected revents on read fd to have POLLIN set");
break;
}
}
// Read it.
Debug.Assert((fds[0].REvents & Interop.Sys.PollFlags.POLLIN) != 0);
int result = Interop.Sys.Read(fd, (byte*)ptr, len);
Debug.Assert(result <= len);
return result;
}, (IntPtr)(bufPtr + offset), count, cancellation.Poll.DangerousGetHandle());
Debug.Assert(rv >= 0 || rv == CancellationSentinel);
// If cancellation was requested, waking up the read, throw.
if (rv == CancellationSentinel)
{
Debug.Assert(cancellationToken.IsCancellationRequested);
throw new OperationCanceledException(cancellationToken);
}
// Otherwise return what we read.
return rv;
}
}
finally
{
if (gotRef)
cancellation.Poll.DangerousRelease();
}
}
}
private unsafe void WriteCoreNoCancellation(byte[] buffer, int offset, int count)
{
DebugAssertReadWriteArgs(buffer, offset, count, _handle);
fixed (byte* bufPtr = buffer)
{
while (count > 0)
{
int bytesWritten = (int)SysCall(_handle, (fd, ptr, len, _) =>
{
int result = Interop.Sys.Write(fd, (byte*)ptr, len);
Debug.Assert(result <= len);
return result;
}, (IntPtr)(bufPtr + offset), count);
count -= bytesWritten;
offset += bytesWritten;
}
}
}
private void WriteCoreWithCancellation(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
DebugAssertReadWriteArgs(buffer, offset, count, _handle);
// NOTE:
// We currently ignore cancellationToken. Unlike on Windows, writes to pipes on Unix are likely to succeed
// immediately, even if no reader is currently listening, as long as there's room in the kernel buffer.
// However it's still possible for write to block if the buffer is full. We could try using a poll mechanism
// like we do for read, but checking for POLLOUT is only going to tell us that there's room to write at least
// one byte to the pipe, not enough room to write enough that we won't block. The only way to guarantee
// that would seem to be writing one byte at a time, which has huge overheads when writing large chunks of data.
// Given all this, at least for now we just do an initial check for cancellation and then call to the
// non -cancelable version.
cancellationToken.ThrowIfCancellationRequested();
WriteCoreNoCancellation(buffer, offset, count);
}
/// <summary>Creates an anonymous pipe.</summary>
/// <param name="inheritability">The inheritability to try to use. This may not always be honored, depending on platform.</param>
/// <param name="reader">The resulting reader end of the pipe.</param>
/// <param name="writer">The resulting writer end of the pipe.</param>
internal static unsafe void CreateAnonymousPipe(
HandleInheritability inheritability, out SafePipeHandle reader, out SafePipeHandle writer)
{
// Allocate the safe handle objects prior to calling pipe/pipe2, in order to help slightly in low-mem situations
reader = new SafePipeHandle();
writer = new SafePipeHandle();
// Create the OS pipe
int* fds = stackalloc int[2];
CreateAnonymousPipe(inheritability, fds);
// Store the file descriptors into our safe handles
reader.SetHandle(fds[Interop.Sys.ReadEndOfPipe]);
writer.SetHandle(fds[Interop.Sys.WriteEndOfPipe]);
}
/// <summary>
/// Creates a cancellation registration. This creates a pipe that'll have one end written to
/// when cancellation is requested. The other end can be poll'd to see when cancellation has occurred.
/// </summary>
private static unsafe DescriptorCancellationRegistration RegisterForCancellation(CancellationToken cancellationToken)
{
Debug.Assert(cancellationToken.CanBeCanceled);
// Fast path: before doing any real work, throw if cancellation has already been requested
cancellationToken.ThrowIfCancellationRequested();
// Create a pipe we can use to send a signal to the reader/writer
// to wake it up if blocked.
SafePipeHandle poll, send;
CreateAnonymousPipe(HandleInheritability.None, out poll, out send);
// Register a cancellation callback to send a byte to the cancellation pipe
CancellationTokenRegistration reg = cancellationToken.Register(s =>
{
SafePipeHandle sendRef = (SafePipeHandle)s;
bool gotSendRef = false;
try
{
sendRef.DangerousAddRef(ref gotSendRef);
int fd = (int)sendRef.DangerousGetHandle();
byte b = 1;
while (Interop.CheckIo((int)Interop.Sys.Write(fd, &b, 1))) ;
}
finally
{
if (gotSendRef)
sendRef.DangerousRelease();
}
}, send);
// Return a disposable struct that will unregister the cancellation registration
// and dispose of the pipe.
return new DescriptorCancellationRegistration(reg, poll, send);
}
/// <summary>Disposable struct that'll clean up the results of a RegisterForCancellation operation.</summary>
private struct DescriptorCancellationRegistration : IDisposable
{
private CancellationTokenRegistration _registration;
private readonly SafePipeHandle _poll;
private readonly SafePipeHandle _send;
internal DescriptorCancellationRegistration(
CancellationTokenRegistration registration,
SafePipeHandle poll, SafePipeHandle send)
{
Debug.Assert(poll != null);
Debug.Assert(send != null);
_registration = registration;
_poll = poll;
_send = send;
}
internal SafePipeHandle Poll { get { return _poll; } }
public void Dispose()
{
// Dispose the registration prior to disposing of the pipe handles.
// Otherwise a concurrent cancellation request could try to use
// the already disposed pipe.
_registration.Dispose();
if (_send != null)
_send.Dispose();
if (_poll != null)
_poll.Dispose();
}
}
/// <summary>
/// Helper for making system calls that involve the stream's file descriptor.
/// System calls are expected to return greather than or equal to zero on success,
/// and less than zero on failure. In the case of failure, errno is expected to
/// be set to the relevant error code.
/// </summary>
/// <param name="sysCall">A delegate that invokes the system call.</param>
/// <param name="arg1">The first argument to be passed to the system call, after the file descriptor.</param>
/// <param name="arg2">The second argument to be passed to the system call.</param>
/// <param name="arg3">The third argument to be passed to the system call.</param>
/// <returns>The return value of the system call.</returns>
/// <remarks>
/// Arguments are expected to be passed via <paramref name="arg1"/> and <paramref name="arg2"/>
/// so as to avoid delegate and closure allocations at the call sites.
/// </remarks>
private long SysCall(
SafePipeHandle handle,
Func<int, IntPtr, int, IntPtr, long> sysCall,
IntPtr arg1 = default(IntPtr), int arg2 = default(int), IntPtr arg3 = default(IntPtr))
{
bool gotRefOnHandle = false;
try
{
// Get the file descriptor from the handle. We increment the ref count to help
// ensure it's not closed out from under us.
handle.DangerousAddRef(ref gotRefOnHandle);
Debug.Assert(gotRefOnHandle);
int fd = (int)handle.DangerousGetHandle();
Debug.Assert(fd >= 0);
while (true)
{
long result = sysCall(fd, arg1, arg2, arg3);
if (result == -1)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EINTR)
continue;
if (errorInfo.Error == Interop.Error.EPIPE)
State = PipeState.Broken;
throw Interop.GetExceptionForIoErrno(errorInfo);
}
return result;
}
}
finally
{
if (gotRefOnHandle)
{
handle.DangerousRelease();
}
}
}
internal void InitializeBufferSize(SafePipeHandle handle, int bufferSize)
{
// bufferSize is just advisory and ignored if platform does not support setting pipe capacity via fcntl.
if (bufferSize > 0 && Interop.Sys.Fcntl.CanGetSetPipeSz)
{
SysCall(handle, (fd, _, size, __) => Interop.Sys.Fcntl.SetPipeSz(fd, size),
IntPtr.Zero, bufferSize);
}
}
private int GetPipeBufferSize()
{
if (!Interop.Sys.Fcntl.CanGetSetPipeSz)
{
throw new PlatformNotSupportedException();
}
// If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction).
// If we don't, the pipe has been created but not yet connected (in the case of named pipes),
// so just return the buffer size that was passed to the constructor.
return _handle != null ?
(int)SysCall(_handle, (fd, _, __, ___) => Interop.Sys.Fcntl.GetPipeSz(fd)) :
_outBufferSize;
}
internal static unsafe void CreateAnonymousPipe(HandleInheritability inheritability, int* fdsptr)
{
var flags = (inheritability & HandleInheritability.Inheritable) == 0 ?
Interop.Sys.PipeFlags.O_CLOEXEC : 0;
while (Interop.CheckIo(Interop.Sys.Pipe(fdsptr, flags))) ;
}
}
}
| |
/*
Copyright 2006-2017 Cryptany, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Messaging;
using System.Net;
using System.Security.Principal;
using System.ServiceProcess;
using Cryptany.Core;
namespace Cryptany.Core.ConnectorServices
{
class ConnectorLoader
{
private static int _code;
// The main entry point for the process
[LoaderOptimization( LoaderOptimization.SingleDomain)]
public static void Main(string[] args)
{
Console.WriteLine(Process.GetCurrentProcess().MainModule.FileName);
Console.ReadLine();
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
// Load all services into memory
if (args.Length > 0)
{
if (args[0] == "-i")
{
ConnectorSettings cs;
if (args.Length > 1)
{
try
{
cs = SMSProxy.LoadSettingsFromDB(int.Parse(args[1]));
}
catch (Exception e)
{
Console.WriteLine(e);
Console.Read();
return;
}
if (cs == null)
{
Console.WriteLine("SMSC not found!");
Console.Read();
return;
}
try
{
Installer inst = new Installer();
inst.InstallService(Process.GetCurrentProcess().MainModule.FileName + " /svc " + args[1],
"Cryptany.ConnectorService" + args[1], "Cryptany.ConnectorService" + args[1],
cs.Name);
CreateOutputQueue(cs.ID);
InstallPerformanceCounters();
if (!EventLog.SourceExists("Cryptany.ConnectorService" + args[1]))
{
EventLog.CreateEventSource("Cryptany.ConnectorService" + args[1], "Application");
}
}
catch (Exception e)
{
Console.WriteLine("Exception while trying to install service: {0}", e);
}
}
}
else if (args[0] == "-u")
{
if (args.Length > 1)
{
ConnectorSettings cs;
try
{
cs = SMSProxy.LoadSettingsFromDB(int.Parse(args[1]));
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadKey();
return;
}
if (cs == null)
{
Console.WriteLine("SMSC not found!");
Console.ReadKey();
return;
}
Installer inst = new Installer();
inst.UnInstallService("Cryptany.ConnectorService" + args[1]);
DeleteOutputQueue(cs.ID);
}
else
{
ServiceController[] scs= ServiceController.GetServices();
Installer inst = new Installer();
foreach(ServiceController sc in scs)
{
if (sc.ServiceName.StartsWith("Cryptany.ConnectorService"))
{
inst.UnInstallService(sc.ServiceName);
}
}
DeleteOutputQueues();
UninstallPerformanceCounters();
}
}
else if (args[0].Equals("/svc"))
{
_code = int.Parse(args[1]);
ServiceBase sb = new ConnectorService(_code);
ServiceBase.Run(sb);
}
}
}
static void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
if (_code>0)
EventLog.WriteEntry("Cryptany.ConnectorService" + _code, "AppDomain is about to unload.", EventLogEntryType.Information);
}
private static void InstallPerformanceCounters()
{
if (PerformanceCounterCategory.Exists("Connector Service"))
{
PerformanceCounterCategory.Delete("Connector Service");
}
{
CounterCreationDataCollection counters = new CounterCreationDataCollection();
CounterCreationData opsPerSecond1 = new CounterCreationData();
opsPerSecond1.CounterName = "# incoming messages / sec";
opsPerSecond1.CounterHelp = "Number of incoming messages from SMSC per second";
opsPerSecond1.CounterType = PerformanceCounterType.RateOfCountsPerSecond32;
counters.Add(opsPerSecond1);
CounterCreationData opsPerSecond2 = new CounterCreationData();
opsPerSecond2.CounterName = "# outgoing messages / sec";
opsPerSecond2.CounterHelp = "Number of outgoing messages to SMSC per second";
opsPerSecond2.CounterType = PerformanceCounterType.RateOfCountsPerSecond32;
counters.Add(opsPerSecond2);
CounterCreationData ConnectionState = new CounterCreationData();
ConnectionState.CounterName = "Connection State";
ConnectionState.CounterHelp = "State of the SMSC connection (1-connected, 0-disconnected)";
ConnectionState.CounterType = PerformanceCounterType.NumberOfItems32;
counters.Add(ConnectionState);
CounterCreationData SmsProcessing = new CounterCreationData();
SmsProcessing.CounterName = "SMS processing time, ms";
SmsProcessing.CounterHelp = "SMS processing time";
SmsProcessing.CounterType = PerformanceCounterType.NumberOfItems32;
counters.Add(SmsProcessing);
CounterCreationData SmsLoading = new CounterCreationData();
SmsLoading.CounterName = "Time in outgoing queue (average)";
SmsLoading.CounterHelp = "Time in outgoing queue";
SmsLoading.CounterType = PerformanceCounterType.RateOfCountsPerSecond32;
counters.Add(SmsLoading);
CounterCreationData SmsResendCount = new CounterCreationData();
SmsResendCount.CounterName = "SMS resend to SMSC count/sec";
SmsResendCount.CounterHelp = "SMS resend to SMSC count";
SmsResendCount.CounterType = PerformanceCounterType.RateOfCountsPerSecond32;
counters.Add(SmsResendCount);
CounterCreationData OutSmsAverage = new CounterCreationData();
OutSmsAverage.CounterName = "sended sms";
OutSmsAverage.CounterHelp = "average sended sms/hour";
OutSmsAverage.CounterType = PerformanceCounterType.NumberOfItems32;
counters.Add(OutSmsAverage);
CounterCreationData InSmsAverage = new CounterCreationData();
InSmsAverage.CounterName = "received sms";
InSmsAverage.CounterHelp = "average sended sms/hour";
InSmsAverage.CounterType = PerformanceCounterType.NumberOfItems32;
counters.Add(InSmsAverage);
CounterCreationData MsgswaitingReceits = new CounterCreationData();
MsgswaitingReceits.CounterName = "waiting receits messages cache";
MsgswaitingReceits.CounterHelp = "number of sent and waiting receits messages ";
MsgswaitingReceits.CounterType = PerformanceCounterType.NumberOfItems32;
counters.Add(MsgswaitingReceits);
// create new category with the counters above
PerformanceCounterCategory.Create("Connector Service", "Connector Service category ", PerformanceCounterCategoryType. MultiInstance, counters);
}
if (PerformanceCounterCategory.Exists("Connector Service:SMPP"))
{
PerformanceCounterCategory.Delete("Connector Service:SMPP");
}
{
CounterCreationDataCollection counters = new CounterCreationDataCollection();
CounterCreationData opsPerSecond1 = new CounterCreationData();
opsPerSecond1.CounterName = "Incoming PDU response time, ms";
opsPerSecond1.CounterHelp = "Incoming PDU response time";
opsPerSecond1.CounterType = PerformanceCounterType.NumberOfItems32;
counters.Add(opsPerSecond1);
CounterCreationData opsPerSecond2 = new CounterCreationData();
opsPerSecond2.CounterName = "Outgoing PDU response time, ms";
opsPerSecond2.CounterHelp = "Outgoing PDU response time";
opsPerSecond2.CounterType = PerformanceCounterType.NumberOfItems32;
counters.Add(opsPerSecond2);
// create new category with the counters above
PerformanceCounterCategory.Create("Connector Service:SMPP",
"Connector Service:SMPP category ", PerformanceCounterCategoryType.MultiInstance, counters);
}
}
private static void UninstallPerformanceCounters()
{
if (PerformanceCounterCategory.Exists("Connector Service"))
{
PerformanceCounterCategory.Delete("Connector Service");
}
if (PerformanceCounterCategory.Exists("Connector Service:SMPP"))
{
PerformanceCounterCategory.Delete("Connector Service:SMPP");
}
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
EventLog.WriteEntry("Cryptany.ConnectorService" + _code, "Unhandled exception in connector " + _code + ": " + ex ?? "", EventLogEntryType.Error);
}
private static void CreateOutputQueue(Guid id)
{
if (!MessageQueue.Exists(@".\private$\cryptany_outputqueue" + id))
{
MessageQueue mq = MessageQueue.Create(@".\private$\cryptany_outputqueue" + id);
mq.SetPermissions("NT AUTHORITY\\NETWORK SERVICE", MessageQueueAccessRights.FullControl);
}
}
private static void DeleteOutputQueue(Guid id)
{
if (MessageQueue.Exists(@".\private$\cryptany_outputqueue" + id))
{
MessageQueue q = new MessageQueue(@".\private$\cryptany_outputqueue" + id);
q.SetPermissions(WindowsIdentity.GetCurrent().Name, MessageQueueAccessRights.FullControl);
MessageQueue.Delete(@".\private$\cryptany_outputqueue" + id);
}
}
private static void DeleteOutputQueues()
{
MessageQueue[] mqs = MessageQueue.GetPrivateQueuesByMachine(".");
foreach(MessageQueue mq in mqs)
{
if (mq.Path.Contains("cryptany_outputqueue"))
{
MessageQueue.Delete(mq.Path);
}
}
}
}
[RunInstaller(false)]
public class ConnectorInstaller : System.Configuration.Install.Installer
{
private ServiceProcessInstaller serviceProcessInstaller;
private Container components = null;
public ConnectorInstaller()
{
InitializeComponent();
}
private void InitializeComponent()
{
serviceProcessInstaller = new ServiceProcessInstaller();
serviceProcessInstaller.Account = ServiceAccount.User;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Security;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Versioning;
namespace System.Diagnostics
{
// 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.
internal class StackFrameHelper : IDisposable
{
private Thread targetThread;
private int[] rgiOffset;
private int[] rgiILOffset;
#pragma warning disable 414
// dynamicMethods is an array of System.Resolver objects, used to keep
// DynamicMethodDescs alive for the lifetime of StackFrameHelper.
private Object dynamicMethods; // Field is not used from managed.
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;
private bool[] rgiLastFrameFromForeignExceptionStackTrace;
private GetSourceLineInfoDelegate getSourceLineInfo;
private int iFrameCount;
#pragma warning restore 414
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;
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;
rgiLastFrameFromForeignExceptionStackTrace = null;
// 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=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
throwOnError: false);
if (s_symbolsType == null)
return;
s_symbolsMethodInfo = s_symbolsType.GetMethod("GetSourceLineInfo", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
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 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]);
}
}
}
catch
{
}
finally
{
t_reentrancy--;
}
}
void IDisposable.Dispose()
{
if (getSourceLineInfo != null)
{
IDisposable disposable = getSourceLineInfo.Target as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
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 == IntPtr.Zero)
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]; }
public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i)
{
return (rgiLastFrameFromForeignExceptionStackTrace == null) ? false : rgiLastFrameFromForeignExceptionStackTrace[i];
}
public virtual int GetNumberOfFrames() { return iFrameCount; }
}
// Class which represents a description of a stack trace
// There is no good reason for the methods of this class to be virtual.
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.
public StackTrace()
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, false, null, null);
}
// Constructs a stack trace from the current location.
//
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
//
public StackTrace(int skipFrames)
{
if (skipFrames < 0)
throw new ArgumentOutOfRangeException(nameof(skipFrames),
SR.ArgumentOutOfRange_NeedNonNegNum);
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
//
public StackTrace(int skipFrames, bool fNeedFileInfo)
{
if (skipFrames < 0)
throw new ArgumentOutOfRangeException(nameof(skipFrames),
SR.ArgumentOutOfRange_NeedNonNegNum);
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(nameof(e));
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, false, null, e);
}
// Constructs a stack trace from the current location.
//
public StackTrace(Exception e, bool fNeedFileInfo)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
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
//
public StackTrace(Exception e, int skipFrames)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (skipFrames < 0)
throw new ArgumentOutOfRangeException(nameof(skipFrames),
SR.ArgumentOutOfRange_NeedNonNegNum);
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
//
public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (skipFrames < 0)
throw new ArgumentOutOfRangeException(nameof(skipFrames),
SR.ArgumentOutOfRange_NeedNonNegNum);
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;
}
[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));
sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i));
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.
//
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
//
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.
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 = SR.Word_At;
inFileLineNum = SR.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 && (ShowInStackTrace(mb) ||
(iFrameIndex == m_iNumOfFrames - 1))) // Don't filter last frame
{
// 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);
bool isAsync = false;
Type declaringType = mb.DeclaringType;
string methodName = mb.Name;
bool methodChanged = false;
if (declaringType != null && declaringType.IsDefined(typeof(CompilerGeneratedAttribute)))
{
isAsync = typeof(IAsyncStateMachine).IsAssignableFrom(declaringType);
if (isAsync || typeof(IEnumerator).IsAssignableFrom(declaringType))
{
methodChanged = TryResolveStateMachineMethod(ref mb, out declaringType);
}
}
// if there is a type (non global method) print it
// ResolveStateMachineMethod may have set declaringType to null
if (declaringType != null)
{
// Append t.FullName, replacing '+' with '.'
string fullName = declaringType.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;
try
{
pi = mb.GetParameters();
}
catch
{
// The parameter info cannot be loaded, so we don't
// append the parameter list.
}
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(')');
}
if (methodChanged)
{
// Append original method name e.g. +MoveNext()
sb.Append("+");
sb.Append(methodName);
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();
}
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 (sf.GetIsLastFrameFromForeignExceptionStackTrace() &&
!isAsync) // Skip EDI boundary for async
{
sb.Append(Environment.NewLine);
sb.Append(SR.Exception_EndStackTraceFromPreviousThrow);
}
}
}
if (traceFormat == TraceFormat.TrailingNewLine)
sb.Append(Environment.NewLine);
return sb.ToString();
}
private static bool ShowInStackTrace(MethodBase mb)
{
Debug.Assert(mb != null);
return !(mb.IsDefined(typeof(StackTraceHiddenAttribute)) || (mb.DeclaringType?.IsDefined(typeof(StackTraceHiddenAttribute)) ?? false));
}
private static bool TryResolveStateMachineMethod(ref MethodBase method, out Type declaringType)
{
Debug.Assert(method != null);
Debug.Assert(method.DeclaringType != null);
declaringType = method.DeclaringType;
Type parentType = declaringType.DeclaringType;
if (parentType == null)
{
return false;
}
MethodInfo[] methods = parentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
if (methods == null)
{
return false;
}
foreach (MethodInfo candidateMethod in methods)
{
IEnumerable<StateMachineAttribute> attributes = candidateMethod.GetCustomAttributes<StateMachineAttribute>();
if (attributes == null)
{
continue;
}
foreach (StateMachineAttribute asma in attributes)
{
if (asma.StateMachineType == declaringType)
{
method = candidateMethod;
declaringType = candidateMethod.DeclaringType;
// Mark the iterator as changed; so it gets the + annotation of the original method
// async statemachines resolve directly to their builder methods so aren't marked as changed
return asma is IteratorStateMachineAttribute;
}
}
}
return false;
}
}
}
| |
//
// InternetAddressList.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013 Jeffrey Stedfast
//
// 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.Text;
using System.Collections;
using System.Collections.Generic;
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// A list of <see cref="MimeKit.InternetAddress"/>es.
/// </summary>
public sealed class InternetAddressList : IList<InternetAddress>, IEquatable<InternetAddressList>
{
readonly List<InternetAddress> list = new List<InternetAddress> ();
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.InternetAddressList"/> class.
/// </summary>
/// <param name="addresses">An initial list of addresses.</param>
public InternetAddressList (IEnumerable<InternetAddress> addresses)
{
foreach (var address in addresses) {
address.Changed += AddressChanged;
list.Add (address);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.InternetAddressList"/> class.
/// </summary>
public InternetAddressList ()
{
}
/// <summary>
/// Recursively gets all of the mailboxes contained within the <see cref="MimeKit.InternetAddressList"/>.
/// </summary>
/// <remarks>
/// This API is useful for collecting a flattened list of <see cref="MimeKit.MailboxAddress"/>
/// recipients for use with sending via SMTP or for encrypting via S/MIME or PGP/MIME.
/// </remarks>
/// <value>The mailboxes.</value>
public IEnumerable<MailboxAddress> Mailboxes {
get {
foreach (var address in list) {
var group = address as GroupAddress;
if (group != null) {
foreach (var mailbox in group.Members.Mailboxes)
yield return mailbox;
} else {
yield return (MailboxAddress) address;
}
}
yield break;
}
}
#region IList implementation
/// <summary>
/// Gets the index of the specified address.
/// </summary>
/// <returns>The index of the specified address if found; otherwise <c>-1</c>.</returns>
/// <param name="address">The address to get the index of.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="address"/> is <c>null</c>.
/// </exception>
public int IndexOf (InternetAddress address)
{
if (address == null)
throw new ArgumentNullException ("address");
return list.IndexOf (address);
}
/// <summary>
/// Inserts the address at the specified index.
/// </summary>
/// <param name="index">The index to insert the address.</param>
/// <param name="address">The address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="address"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of range.
/// </exception>
public void Insert (int index, InternetAddress address)
{
if (address == null)
throw new ArgumentNullException ("address");
address.Changed += AddressChanged;
list.Insert (index, address);
OnChanged ();
}
/// <summary>
/// Removes the address at the specified index.
/// </summary>
/// <param name="index">The index of the address to remove.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of range.
/// </exception>
public void RemoveAt (int index)
{
if (index < 0 || index >= list.Count)
throw new ArgumentOutOfRangeException ("index");
list[index].Changed -= AddressChanged;
list.RemoveAt (index);
OnChanged ();
}
/// <summary>
/// Gets or sets the <see cref="MimeKit.InternetAddressList"/> at the specified index.
/// </summary>
/// <param name="index">The idnex of the addres to get or set.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="value"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of range.
/// </exception>
public InternetAddress this [int index] {
get { return list[index]; }
set {
if (value == null)
throw new ArgumentNullException ("value");
if (list[index] == value)
return;
list[index] = value;
OnChanged ();
}
}
#endregion
#region ICollection implementation
/// <summary>
/// Adds the specified address.
/// </summary>
/// <param name="address">The address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="address"/> is <c>null</c>.
/// </exception>
public void Add (InternetAddress address)
{
if (address == null)
throw new ArgumentNullException ("address");
address.Changed += AddressChanged;
list.Add (address);
OnChanged ();
}
/// <summary>
/// Adds a collection of addresses.
/// </summary>
/// <param name="addresses">A colelction of addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="addresses"/> is <c>null</c>.
/// </exception>
public void AddRange (IEnumerable<InternetAddress> addresses)
{
if (addresses == null)
throw new ArgumentNullException ("addresses");
foreach (var address in addresses) {
address.Changed += AddressChanged;
list.Add (address);
}
OnChanged ();
}
/// <summary>
/// Clears the <see cref="MimeKit.InternetAddressList"/>.
/// </summary>
public void Clear ()
{
foreach (var address in list)
address.Changed -= AddressChanged;
list.Clear ();
OnChanged ();
}
/// <summary>
/// Checks if the <see cref="MimeKit.InternetAddressList"/> contains the specified address.
/// </summary>
/// <returns><value>true</value> if the requested address exists;
/// otherwise <value>false</value>.</returns>
/// <param name="address">The address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="address"/> is <c>null</c>.
/// </exception>
public bool Contains (InternetAddress address)
{
if (address == null)
throw new ArgumentNullException ("address");
return list.Contains (address);
}
/// <summary>
/// Copies all of the addresses in the <see cref="MimeKit.InternetAddressList"/> to the specified array.
/// </summary>
/// <param name="array">The array to copy the addresses to.</param>
/// <param name="arrayIndex">The index into the array.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="array"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="arrayIndex"/> is out of range.
/// </exception>
public void CopyTo (InternetAddress[] array, int arrayIndex)
{
list.CopyTo (array, arrayIndex);
}
/// <summary>
/// Removes the specified address.
/// </summary>
/// <param name="address">The address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="address"/> is <c>null</c>.
/// </exception>
public bool Remove (InternetAddress address)
{
if (address == null)
throw new ArgumentNullException ("address");
if (list.Remove (address)) {
address.Changed -= AddressChanged;
OnChanged ();
return true;
}
return false;
}
/// <summary>
/// Gets the number of addresses in the <see cref="MimeKit.InternetAddressList"/>.
/// </summary>
/// <value>The number of addresses.</value>
public int Count {
get { return list.Count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value>
public bool IsReadOnly {
get { return false; }
}
#endregion
#region IEnumerable implementation
/// <summary>
/// Gets an enumerator for the list of addresses.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<InternetAddress> GetEnumerator ()
{
return list.GetEnumerator ();
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator ()
{
return list.GetEnumerator ();
}
#endregion
#region IEquatable implementation
/// <summary>
/// Determines whether the specified <see cref="MimeKit.InternetAddressList"/> is equal to the current <see cref="MimeKit.InternetAddressList"/>.
/// </summary>
/// <param name="other">The <see cref="MimeKit.InternetAddressList"/> to compare with the current <see cref="MimeKit.InternetAddressList"/>.</param>
/// <returns><c>true</c> if the specified <see cref="MimeKit.InternetAddressList"/> is equal to the current
/// <see cref="MimeKit.InternetAddressList"/>; otherwise, <c>false</c>.</returns>
public bool Equals (InternetAddressList other)
{
if (other == null)
return false;
if (other.Count != Count)
return false;
for (int i = 0; i < Count; i++) {
if (!list[i].Equals (other[i]))
return false;
}
return true;
}
#endregion
internal void Encode (FormatOptions options, StringBuilder builder, ref int lineLength)
{
foreach (var addr in list)
addr.Encode (options, builder, ref lineLength);
}
/// <summary>
/// Serializes the <see cref="MimeKit.InternetAddressList"/> to a string, optionally encoding it for transport.
/// </summary>
/// <returns>A string representing the <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="options">The formatting options.</param>
/// <param name="encode">If set to <c>true</c>, the <see cref="MimeKit.InternetAddressList"/> will be encoded.</param>
public string ToString (FormatOptions options, bool encode)
{
var builder = new StringBuilder ();
if (encode) {
int lineLength = 0;
Encode (options, builder, ref lineLength);
return builder.ToString ();
}
for (int i = 0; i < list.Count; i++) {
if (i > 0)
builder.Append (", ");
builder.Append (list[i].ToString ());
}
return builder.ToString ();
}
/// <summary>
/// Serializes the <see cref="MimeKit.InternetAddressList"/> to a string, optionally encoding it for transport.
/// </summary>
/// <returns>A string representing the <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="encode">If set to <c>true</c>, the <see cref="MimeKit.InternetAddressList"/> will be encoded.</param>
public string ToString (bool encode)
{
return ToString (FormatOptions.Default, encode);
}
/// <summary>
/// Serializes the <see cref="MimeKit.InternetAddressList"/> to a string suitable for display.
/// </summary>
/// <returns>A string representing the <see cref="MimeKit.InternetAddressList"/>.</returns>
public override string ToString ()
{
return ToString (FormatOptions.Default, false);
}
internal event EventHandler Changed;
void OnChanged ()
{
if (Changed != null)
Changed (this, EventArgs.Empty);
}
void AddressChanged (object sender, EventArgs e)
{
OnChanged ();
}
internal static bool TryParse (ParserOptions options, byte[] text, ref int index, int endIndex, bool isGroup, bool throwOnError, out List<InternetAddress> addresses)
{
List<InternetAddress> list = new List<InternetAddress> ();
InternetAddress address;
addresses = null;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
while (index < endIndex) {
if (isGroup && text[index] == (byte) ';')
break;
if (!InternetAddress.TryParse (options, text, ref index, endIndex, throwOnError, out address)) {
// skip this address...
while (index < endIndex && text[index] != (byte) ',' && (!isGroup || text[index] != (byte) ';'))
index++;
} else {
list.Add (address);
}
// Note: we loop here in case there are any null addresses between commas
do {
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex || text[index] != (byte) ',')
break;
index++;
} while (true);
}
addresses = list;
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, int length, out InternetAddressList addresses)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex >= buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || startIndex + length >= buffer.Length)
throw new ArgumentOutOfRangeException ("length");
List<InternetAddress> addrlist;
int index = startIndex;
if (!TryParse (options, buffer, ref index, startIndex + length, false, false, out addrlist)) {
addresses = null;
return false;
}
addresses = new InternetAddressList (addrlist);
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, int length, out InternetAddressList addresses)
{
return TryParse (ParserOptions.Default, buffer, startIndex, length, out addresses);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, out InternetAddressList addresses)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex >= buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
List<InternetAddress> addrlist;
int index = startIndex;
if (!TryParse (options, buffer, ref index, buffer.Length, false, false, out addrlist)) {
addresses = null;
return false;
}
addresses = new InternetAddressList (addrlist);
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, out InternetAddressList addresses)
{
return TryParse (ParserOptions.Default, buffer, startIndex, out addresses);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, out InternetAddressList addresses)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
List<InternetAddress> addrlist;
int index = 0;
if (!TryParse (options, buffer, ref index, buffer.Length, false, false, out addrlist)) {
addresses = null;
return false;
}
addresses = new InternetAddressList (addrlist);
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
public static bool TryParse (byte[] buffer, out InternetAddressList addresses)
{
return TryParse (ParserOptions.Default, buffer, out addresses);
}
/// <summary>
/// Tries to parse the given text into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="text">The text.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="text"/> is <c>null</c>.</para>
/// </exception>
public static bool TryParse (ParserOptions options, string text, out InternetAddressList addresses)
{
if (options == null)
throw new ArgumentNullException ("options");
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
List<InternetAddress> addrlist;
int index = 0;
if (!TryParse (options, buffer, ref index, buffer.Length, false, false, out addrlist)) {
addresses = null;
return false;
}
addresses = new InternetAddressList (addrlist);
return true;
}
/// <summary>
/// Tries to parse the given text into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="text">The text.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static bool TryParse (string text, out InternetAddressList addresses)
{
return TryParse (ParserOptions.Default, text, out addresses);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (ParserOptions options, byte[] buffer, int startIndex, int length)
{
List<InternetAddress> addrlist;
int index = startIndex;
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex > buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || startIndex + length > buffer.Length)
throw new ArgumentOutOfRangeException ("length");
TryParse (options, buffer, ref index, startIndex + length, false, true, out addrlist);
return new InternetAddressList (addrlist);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (byte[] buffer, int startIndex, int length)
{
return Parse (ParserOptions.Default, buffer, startIndex, length);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/>is out of range.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (ParserOptions options, byte[] buffer, int startIndex)
{
List<InternetAddress> addrlist;
int index = startIndex;
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex > buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
TryParse (options, buffer, ref index, buffer.Length, false, true, out addrlist);
return new InternetAddressList (addrlist);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (byte[] buffer, int startIndex)
{
return Parse (ParserOptions.Default, buffer, startIndex);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (ParserOptions options, byte[] buffer)
{
List<InternetAddress> addrlist;
int index = 0;
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
TryParse (options, buffer, ref index, buffer.Length, false, true, out addrlist);
return new InternetAddressList (addrlist);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (byte[] buffer)
{
return Parse (ParserOptions.Default, buffer);
}
/// <summary>
/// Parses the given text into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="text">The text.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="text"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="text"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (ParserOptions options, string text)
{
if (options == null)
throw new ArgumentNullException ("options");
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
List<InternetAddress> addrlist;
int index = 0;
TryParse (options, buffer, ref index, buffer.Length, false, true, out addrlist);
return new InternetAddressList (addrlist);
}
/// <summary>
/// Parses the given text into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="text">The text.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="text"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (string text)
{
return Parse (ParserOptions.Default, text);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AndNotUInt32()
{
var test = new SimpleBinaryOpTest__AndNotUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndNotUInt32
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt32);
private const int Op2ElementCount = VectorSize / sizeof(UInt32);
private const int RetElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector128<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector128<UInt32> _fld1;
private Vector128<UInt32> _fld2;
private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable;
static SimpleBinaryOpTest__AndNotUInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AndNotUInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.AndNot(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.AndNot(
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.AndNot(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = Sse2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndNotUInt32();
var result = Sse2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.AndNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt32> left, Vector128<UInt32> right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
if ((uint)(~left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((uint)(~left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus
{
/// <summary>
/// An IVisualStudioDocument which represents the secondary buffer to the workspace API.
/// </summary>
internal sealed class ContainedDocument : ForegroundThreadAffinitizedObject, IVisualStudioHostDocument
{
private const string ReturnReplacementString = @"{|r|}";
private const string NewLineReplacementString = @"{|n|}";
private const string HTML = "HTML";
private const string HTMLX = "HTMLX";
private const string Razor = "Razor";
private const string XOML = "XOML";
private const char RazorExplicit = '@';
private const string CSharpRazorBlock = "{";
private const string VBRazorBlock = "code";
private const string HelperRazor = "helper";
private const string FunctionsRazor = "functions";
private static readonly EditOptions s_venusEditOptions = new EditOptions(new StringDifferenceOptions
{
DifferenceType = StringDifferenceTypes.Character,
IgnoreTrimWhiteSpace = false
});
private readonly AbstractContainedLanguage _containedLanguage;
private readonly SourceCodeKind _sourceCodeKind;
private readonly IComponentModel _componentModel;
private readonly Workspace _workspace;
private readonly ITextDifferencingSelectorService _differenceSelectorService;
private readonly IOptionService _optionService;
private readonly HostType _hostType;
private readonly ReiteratedVersionSnapshotTracker _snapshotTracker;
private readonly IFormattingRule _vbHelperFormattingRule;
private readonly string _itemMoniker;
public AbstractProject Project { get { return _containedLanguage.Project; } }
public bool SupportsRename { get { return _hostType == HostType.Razor; } }
public DocumentId Id { get; }
public IReadOnlyList<string> Folders { get; }
public TextLoader Loader { get; }
public DocumentKey Key { get; }
public ContainedDocument(
AbstractContainedLanguage containedLanguage,
SourceCodeKind sourceCodeKind,
Workspace workspace,
IVsHierarchy hierarchy,
uint itemId,
IComponentModel componentModel,
IFormattingRule vbHelperFormattingRule)
{
Contract.ThrowIfNull(containedLanguage);
_containedLanguage = containedLanguage;
_sourceCodeKind = sourceCodeKind;
_componentModel = componentModel;
_workspace = workspace;
_optionService = _workspace.Services.GetService<IOptionService>();
_hostType = GetHostType();
var rdt = (IVsRunningDocumentTable)componentModel.GetService<SVsServiceProvider>().GetService(typeof(SVsRunningDocumentTable));
IVsHierarchy sharedHierarchy;
uint itemIdInSharedHierarchy;
var isSharedHierarchy = LinkedFileUtilities.TryGetSharedHierarchyAndItemId(hierarchy, itemId, out sharedHierarchy, out itemIdInSharedHierarchy);
var filePath = isSharedHierarchy
? rdt.GetMonikerForHierarchyAndItemId(sharedHierarchy, itemIdInSharedHierarchy)
: rdt.GetMonikerForHierarchyAndItemId(hierarchy, itemId);
// we couldn't look up the document moniker in RDT for a hierarchy/item pair
// Since we only use this moniker as a key, we could fall back to something else, like the document name.
if (filePath == null)
{
Debug.Assert(false, "Could not get the document moniker for an item in its hierarchy.");
filePath = hierarchy.GetDocumentNameForHierarchyAndItemId(itemId);
}
if (Project.Hierarchy != null)
{
string moniker;
Project.Hierarchy.GetCanonicalName(itemId, out moniker);
_itemMoniker = moniker;
}
this.Key = new DocumentKey(Project, filePath);
this.Id = DocumentId.CreateNewId(Project.Id, filePath);
this.Folders = containedLanguage.Project.GetFolderNames(itemId);
this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
_differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>();
_snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
_vbHelperFormattingRule = vbHelperFormattingRule;
}
private HostType GetHostType()
{
var projectionBuffer = _containedLanguage.DataBuffer as IProjectionBuffer;
if (projectionBuffer != null)
{
// For TypeScript hosted in HTML the source buffers will have type names
// HTMLX and TypeScript. RazorCSharp has an HTMLX base type but should
// not be associated with the HTML host type. Use ContentType.TypeName
// instead of ContentType.IsOfType for HTMLX to ensure the Razor host
// type is identified correctly.
if (projectionBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(HTML) ||
string.Compare(HTMLX, b.ContentType.TypeName, StringComparison.OrdinalIgnoreCase) == 0))
{
return HostType.HTML;
}
if (projectionBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(Razor)))
{
return HostType.Razor;
}
}
else
{
// XOML is set up differently. For XOML, the secondary buffer (i.e. SubjectBuffer)
// is a projection buffer, while the primary buffer (i.e. DataBuffer) is not. Instead,
// the primary buffer is a regular unprojected ITextBuffer with the HTML content type.
if (_containedLanguage.DataBuffer.CurrentSnapshot.ContentType.IsOfType(HTML))
{
return HostType.XOML;
}
}
throw ExceptionUtilities.Unreachable;
}
public DocumentInfo GetInitialState()
{
return DocumentInfo.Create(
this.Id,
this.Name,
folders: this.Folders,
sourceCodeKind: _sourceCodeKind,
loader: this.Loader,
filePath: this.Key.Moniker);
}
public bool IsOpen
{
get
{
return true;
}
}
#pragma warning disable 67
public event EventHandler UpdatedOnDisk;
public event EventHandler<bool> Opened;
public event EventHandler<bool> Closing;
#pragma warning restore 67
IVisualStudioHostProject IVisualStudioHostDocument.Project { get { return this.Project; } }
public ITextBuffer GetOpenTextBuffer()
{
return _containedLanguage.SubjectBuffer;
}
public SourceTextContainer GetOpenTextContainer()
{
return this.GetOpenTextBuffer().AsTextContainer();
}
public IContentType ContentType
{
get
{
return _containedLanguage.SubjectBuffer.ContentType;
}
}
public string Name
{
get
{
try
{
return Path.GetFileName(this.FilePath);
}
catch (ArgumentException)
{
return this.FilePath;
}
}
}
public SourceCodeKind SourceCodeKind
{
get
{
return _sourceCodeKind;
}
}
public string FilePath
{
get
{
return Key.Moniker;
}
}
public AbstractContainedLanguage ContainedLanguage
{
get
{
return _containedLanguage;
}
}
public void Dispose()
{
_snapshotTracker.StopTracking(_containedLanguage.SubjectBuffer);
this.ContainedLanguage.Dispose();
}
public DocumentId FindProjectDocumentIdWithItemId(uint itemidInsertionPoint)
{
return Project.GetCurrentDocuments().SingleOrDefault(d => d.GetItemId() == itemidInsertionPoint).Id;
}
public uint FindItemIdOfDocument(Document document)
{
return Project.GetDocumentOrAdditionalDocument(document.Id).GetItemId();
}
public void UpdateText(SourceText newText)
{
var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer();
var originalSnapshot = subjectBuffer.CurrentSnapshot;
var originalText = originalSnapshot.AsText();
var changes = newText.GetTextChanges(originalText);
IEnumerable<int> affectedVisibleSpanIndices = null;
var editorVisibleSpansInOriginal = SharedPools.Default<List<TextSpan>>().AllocateAndClear();
try
{
var originalDocument = _workspace.CurrentSolution.GetDocument(this.Id);
editorVisibleSpansInOriginal.AddRange(GetEditorVisibleSpans());
var newChanges = FilterTextChanges(originalText, editorVisibleSpansInOriginal, changes).ToList();
if (newChanges.Count == 0)
{
// no change to apply
return;
}
ApplyChanges(subjectBuffer, newChanges, editorVisibleSpansInOriginal, out affectedVisibleSpanIndices);
AdjustIndentation(subjectBuffer, affectedVisibleSpanIndices);
}
finally
{
SharedPools.Default<HashSet<int>>().ClearAndFree((HashSet<int>)affectedVisibleSpanIndices);
SharedPools.Default<List<TextSpan>>().ClearAndFree(editorVisibleSpansInOriginal);
}
}
private IEnumerable<TextChange> FilterTextChanges(SourceText originalText, List<TextSpan> editorVisibleSpansInOriginal, IReadOnlyList<TextChange> changes)
{
// no visible spans or changes
if (editorVisibleSpansInOriginal.Count == 0 || changes.Count == 0)
{
// return empty one
yield break;
}
using (var pooledObject = SharedPools.Default<List<TextChange>>().GetPooledObject())
{
var changeQueue = pooledObject.Object;
changeQueue.AddRange(changes);
var spanIndex = 0;
var changeIndex = 0;
for (; spanIndex < editorVisibleSpansInOriginal.Count; spanIndex++)
{
var visibleSpan = editorVisibleSpansInOriginal[spanIndex];
var visibleTextSpan = GetVisibleTextSpan(originalText, visibleSpan, uptoFirstAndLastLine: true);
for (; changeIndex < changeQueue.Count; changeIndex++)
{
var change = changeQueue[changeIndex];
// easy case first
if (change.Span.End < visibleSpan.Start)
{
// move to next change
continue;
}
if (visibleSpan.End < change.Span.Start)
{
// move to next visible span
break;
}
// make sure we are not replacing whitespace around start and at the end of visible span
if (WhitespaceOnEdges(originalText, visibleTextSpan, change))
{
continue;
}
if (visibleSpan.Contains(change.Span))
{
yield return change;
continue;
}
// now it is complex case where things are intersecting each other
var subChanges = GetSubTextChanges(originalText, change, visibleSpan).ToList();
if (subChanges.Count > 0)
{
if (subChanges.Count == 1 && subChanges[0] == change)
{
// we can't break it. not much we can do here. just don't touch and ignore this change
continue;
}
changeQueue.InsertRange(changeIndex + 1, subChanges);
continue;
}
}
}
}
}
private bool WhitespaceOnEdges(SourceText text, TextSpan visibleTextSpan, TextChange change)
{
if (!string.IsNullOrWhiteSpace(change.NewText))
{
return false;
}
if (change.Span.End <= visibleTextSpan.Start)
{
return true;
}
if (visibleTextSpan.End <= change.Span.Start)
{
return true;
}
return false;
}
private IEnumerable<TextChange> GetSubTextChanges(SourceText originalText, TextChange changeInOriginalText, TextSpan visibleSpanInOriginalText)
{
using (var changes = SharedPools.Default<List<TextChange>>().GetPooledObject())
{
var leftText = originalText.ToString(changeInOriginalText.Span);
var rightText = changeInOriginalText.NewText;
var offsetInOriginalText = changeInOriginalText.Span.Start;
if (TryGetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText, changes.Object))
{
return changes.Object.ToList();
}
return GetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText);
}
}
private bool TryGetSubTextChanges(
SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText, List<TextChange> changes)
{
// these are expensive. but hopefully we don't hit this as much except the boundary cases.
using (var leftPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
using (var rightPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
{
var spansInLeftText = leftPool.Object;
var spansInRightText = rightPool.Object;
if (TryGetWhitespaceOnlyChanges(leftText, rightText, spansInLeftText, spansInRightText))
{
for (var i = 0; i < spansInLeftText.Count; i++)
{
var spanInLeftText = spansInLeftText[i];
var spanInRightText = spansInRightText[i];
if (spanInLeftText.IsEmpty && spanInRightText.IsEmpty)
{
continue;
}
var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length);
TextChange textChange;
if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText, out textChange))
{
changes.Add(textChange);
}
}
return true;
}
return false;
}
}
private IEnumerable<TextChange> GetSubTextChanges(
SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText)
{
// these are expensive. but hopefully we don't hit this as much except the boundary cases.
using (var leftPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject())
using (var rightPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject())
{
var leftReplacementMap = leftPool.Object;
var rightReplacementMap = rightPool.Object;
string leftTextWithReplacement, rightTextWithReplacement;
GetTextWithReplacements(leftText, rightText, leftReplacementMap, rightReplacementMap, out leftTextWithReplacement, out rightTextWithReplacement);
var diffResult = DiffStrings(leftTextWithReplacement, rightTextWithReplacement);
foreach (var difference in diffResult)
{
var spanInLeftText = AdjustSpan(diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left), leftReplacementMap);
var spanInRightText = AdjustSpan(diffResult.RightDecomposition.GetSpanInOriginal(difference.Right), rightReplacementMap);
var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length);
TextChange textChange;
if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText.ToTextSpan(), out textChange))
{
yield return textChange;
}
}
}
}
private bool TryGetWhitespaceOnlyChanges(string leftText, string rightText, List<TextSpan> spansInLeftText, List<TextSpan> spansInRightText)
{
return TryGetWhitespaceGroup(leftText, spansInLeftText) && TryGetWhitespaceGroup(rightText, spansInRightText) && spansInLeftText.Count == spansInRightText.Count;
}
private bool TryGetWhitespaceGroup(string text, List<TextSpan> groups)
{
if (text.Length == 0)
{
groups.Add(new TextSpan(0, 0));
return true;
}
var start = 0;
for (var i = 0; i < text.Length; i++)
{
var ch = text[i];
switch (ch)
{
case ' ':
if (!TextAt(text, i - 1, ' '))
{
start = i;
}
break;
case '\r':
case '\n':
if (i == 0)
{
groups.Add(TextSpan.FromBounds(0, 0));
}
else if (TextAt(text, i - 1, ' '))
{
groups.Add(TextSpan.FromBounds(start, i));
}
else if (TextAt(text, i - 1, '\n'))
{
groups.Add(TextSpan.FromBounds(start, i));
}
start = i + 1;
break;
default:
return false;
}
}
if (start <= text.Length)
{
groups.Add(TextSpan.FromBounds(start, text.Length));
}
return true;
}
private bool TextAt(string text, int index, char ch)
{
if (index < 0 || text.Length <= index)
{
return false;
}
return text[index] == ch;
}
private bool TryGetSubTextChange(
SourceText originalText, TextSpan visibleSpanInOriginalText,
string rightText, TextSpan spanInOriginalText, TextSpan spanInRightText, out TextChange textChange)
{
textChange = default(TextChange);
var visibleFirstLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.Start);
var visibleLastLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.End);
// skip easy case
// 1. things are out of visible span
if (!visibleSpanInOriginalText.IntersectsWith(spanInOriginalText))
{
return false;
}
// 2. there are no intersects
var snippetInRightText = rightText.Substring(spanInRightText.Start, spanInRightText.Length);
if (visibleSpanInOriginalText.Contains(spanInOriginalText) && visibleSpanInOriginalText.End != spanInOriginalText.End)
{
textChange = new TextChange(spanInOriginalText, snippetInRightText);
return true;
}
// okay, more complex case. things are intersecting boundaries.
var firstLineOfRightTextSnippet = snippetInRightText.GetFirstLineText();
var lastLineOfRightTextSnippet = snippetInRightText.GetLastLineText();
// there are 4 complex cases - these are all heuristic. not sure what better way I have. and the heuristic is heavily based on
// text differ's behavior.
// 1. it is a single line
if (visibleFirstLineInOriginalText.LineNumber == visibleLastLineInOriginalText.LineNumber)
{
// don't do anything
return false;
}
// 2. replacement contains visible spans
if (spanInOriginalText.Contains(visibleSpanInOriginalText))
{
// header
// don't do anything
// body
textChange = new TextChange(
TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, visibleLastLineInOriginalText.Start),
snippetInRightText.Substring(firstLineOfRightTextSnippet.Length, snippetInRightText.Length - firstLineOfRightTextSnippet.Length - lastLineOfRightTextSnippet.Length));
// footer
// don't do anything
return true;
}
// 3. replacement intersects with start
if (spanInOriginalText.Start < visibleSpanInOriginalText.Start &&
visibleSpanInOriginalText.Start <= spanInOriginalText.End &&
spanInOriginalText.End < visibleSpanInOriginalText.End)
{
// header
// don't do anything
// body
if (visibleFirstLineInOriginalText.EndIncludingLineBreak <= spanInOriginalText.End)
{
textChange = new TextChange(
TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, spanInOriginalText.End),
snippetInRightText.Substring(firstLineOfRightTextSnippet.Length));
return true;
}
return false;
}
// 4. replacement intersects with end
if (visibleSpanInOriginalText.Start < spanInOriginalText.Start &&
spanInOriginalText.Start <= visibleSpanInOriginalText.End &&
visibleSpanInOriginalText.End <= spanInOriginalText.End)
{
// body
if (spanInOriginalText.Start <= visibleLastLineInOriginalText.Start)
{
textChange = new TextChange(
TextSpan.FromBounds(spanInOriginalText.Start, visibleLastLineInOriginalText.Start),
snippetInRightText.Substring(0, snippetInRightText.Length - lastLineOfRightTextSnippet.Length));
return true;
}
// footer
// don't do anything
return false;
}
// if it got hit, then it means there is a missing case
throw ExceptionUtilities.Unreachable;
}
private IHierarchicalDifferenceCollection DiffStrings(string leftTextWithReplacement, string rightTextWithReplacement)
{
var diffService = _differenceSelectorService.GetTextDifferencingService(
_workspace.Services.GetLanguageServices(this.Project.Language).GetService<IContentTypeLanguageService>().GetDefaultContentType());
diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService;
return diffService.DiffStrings(leftTextWithReplacement, rightTextWithReplacement, s_venusEditOptions.DifferenceOptions);
}
private void GetTextWithReplacements(
string leftText, string rightText,
List<ValueTuple<int, int>> leftReplacementMap, List<ValueTuple<int, int>> rightReplacementMap,
out string leftTextWithReplacement, out string rightTextWithReplacement)
{
// to make diff works better, we choose replacement strings that don't appear in both texts.
var returnReplacement = GetReplacementStrings(leftText, rightText, ReturnReplacementString);
var newLineReplacement = GetReplacementStrings(leftText, rightText, NewLineReplacementString);
leftTextWithReplacement = GetTextWithReplacementMap(leftText, returnReplacement, newLineReplacement, leftReplacementMap);
rightTextWithReplacement = GetTextWithReplacementMap(rightText, returnReplacement, newLineReplacement, rightReplacementMap);
}
private static string GetReplacementStrings(string leftText, string rightText, string initialReplacement)
{
if (leftText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0)
{
return initialReplacement;
}
// okay, there is already one in the given text.
const string format = "{{|{0}|{1}|{0}|}}";
for (var i = 0; true; i++)
{
var replacement = string.Format(format, i.ToString(), initialReplacement);
if (leftText.IndexOf(replacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(replacement, StringComparison.Ordinal) < 0)
{
return replacement;
}
}
}
private string GetTextWithReplacementMap(string text, string returnReplacement, string newLineReplacement, List<ValueTuple<int, int>> replacementMap)
{
var delta = 0;
var returnLength = returnReplacement.Length;
var newLineLength = newLineReplacement.Length;
var sb = StringBuilderPool.Allocate();
for (var i = 0; i < text.Length; i++)
{
var ch = text[i];
if (ch == '\r')
{
sb.Append(returnReplacement);
delta += returnLength - 1;
replacementMap.Add(ValueTuple.Create(i + delta, delta));
continue;
}
else if (ch == '\n')
{
sb.Append(newLineReplacement);
delta += newLineLength - 1;
replacementMap.Add(ValueTuple.Create(i + delta, delta));
continue;
}
sb.Append(ch);
}
return StringBuilderPool.ReturnAndFree(sb);
}
private Span AdjustSpan(Span span, List<ValueTuple<int, int>> replacementMap)
{
var start = span.Start;
var end = span.End;
for (var i = 0; i < replacementMap.Count; i++)
{
var positionAndDelta = replacementMap[i];
if (positionAndDelta.Item1 <= span.Start)
{
start = span.Start - positionAndDelta.Item2;
}
if (positionAndDelta.Item1 <= span.End)
{
end = span.End - positionAndDelta.Item2;
}
if (positionAndDelta.Item1 > span.End)
{
break;
}
}
return Span.FromBounds(start, end);
}
public IEnumerable<TextSpan> GetEditorVisibleSpans()
{
var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer();
var projectionDataBuffer = _containedLanguage.DataBuffer as IProjectionBuffer;
if (projectionDataBuffer != null)
{
return projectionDataBuffer.CurrentSnapshot
.GetSourceSpans()
.Where(ss => ss.Snapshot.TextBuffer == subjectBuffer)
.Select(s => s.Span.ToTextSpan())
.OrderBy(s => s.Start);
}
else
{
return SpecializedCollections.EmptyEnumerable<TextSpan>();
}
}
private static void ApplyChanges(
IProjectionBuffer subjectBuffer,
IEnumerable<TextChange> changes,
IList<TextSpan> visibleSpansInOriginal,
out IEnumerable<int> affectedVisibleSpansInNew)
{
using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null))
{
var affectedSpans = SharedPools.Default<HashSet<int>>().AllocateAndClear();
affectedVisibleSpansInNew = affectedSpans;
var currentVisibleSpanIndex = 0;
foreach (var change in changes)
{
// Find the next visible span that either overlaps or intersects with
while (currentVisibleSpanIndex < visibleSpansInOriginal.Count &&
visibleSpansInOriginal[currentVisibleSpanIndex].End < change.Span.Start)
{
currentVisibleSpanIndex++;
}
// no more place to apply text changes
if (currentVisibleSpanIndex >= visibleSpansInOriginal.Count)
{
break;
}
var newText = change.NewText;
var span = change.Span.ToSpan();
edit.Replace(span, newText);
affectedSpans.Add(currentVisibleSpanIndex);
}
edit.Apply();
}
}
private void AdjustIndentation(IProjectionBuffer subjectBuffer, IEnumerable<int> visibleSpanIndex)
{
if (!visibleSpanIndex.Any())
{
return;
}
var snapshot = subjectBuffer.CurrentSnapshot;
var document = _workspace.CurrentSolution.GetDocument(this.Id);
if (!document.SupportsSyntaxTree)
{
return;
}
var originalText = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
Contract.Requires(object.ReferenceEquals(originalText, snapshot.AsText()));
var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>();
var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer);
var options = _workspace.Options
.WithChangedOption(FormattingOptions.UseTabs, root.Language, !editorOptions.IsConvertTabsToSpacesEnabled())
.WithChangedOption(FormattingOptions.TabSize, root.Language, editorOptions.GetTabSize())
.WithChangedOption(FormattingOptions.IndentationSize, root.Language, editorOptions.GetIndentSize());
using (var pooledObject = SharedPools.Default<List<TextSpan>>().GetPooledObject())
{
var spans = pooledObject.Object;
spans.AddRange(this.GetEditorVisibleSpans());
using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null))
{
foreach (var spanIndex in visibleSpanIndex)
{
var rule = GetBaseIndentationRule(root, originalText, spans, spanIndex);
var visibleSpan = spans[spanIndex];
AdjustIndentationForSpan(document, edit, visibleSpan, rule, options);
}
edit.Apply();
}
}
}
private void AdjustIndentationForSpan(
Document document, ITextEdit edit, TextSpan visibleSpan, IFormattingRule baseIndentationRule, OptionSet options)
{
var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
using (var rulePool = SharedPools.Default<List<IFormattingRule>>().GetPooledObject())
using (var spanPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
{
var venusFormattingRules = rulePool.Object;
var visibleSpans = spanPool.Object;
venusFormattingRules.Add(baseIndentationRule);
venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance);
var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document));
var workspace = document.Project.Solution.Workspace;
var changes = Formatter.GetFormattedTextChanges(
root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) },
workspace, options, formattingRules, CancellationToken.None);
visibleSpans.Add(visibleSpan);
var newChanges = FilterTextChanges(document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span));
foreach (var change in newChanges)
{
edit.Replace(change.Span.ToSpan(), change.NewText);
}
}
}
public BaseIndentationFormattingRule GetBaseIndentationRule(SyntaxNode root, SourceText text, List<TextSpan> spans, int spanIndex)
{
if (_hostType == HostType.Razor)
{
var currentSpanIndex = spanIndex;
TextSpan visibleSpan;
TextSpan visibleTextSpan;
GetVisibleAndTextSpan(text, spans, currentSpanIndex, out visibleSpan, out visibleTextSpan);
var end = visibleSpan.End;
var current = root.FindToken(visibleTextSpan.Start).Parent;
while (current != null)
{
if (current.Span.Start == visibleTextSpan.Start)
{
var blockType = GetRazorCodeBlockType(visibleSpan.Start);
if (blockType == RazorCodeBlockType.Explicit)
{
var baseIndentation = GetBaseIndentation(root, text, visibleSpan);
return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule);
}
}
if (current.Span.Start < visibleSpan.Start)
{
var blockType = GetRazorCodeBlockType(visibleSpan.Start);
if (blockType == RazorCodeBlockType.Block || blockType == RazorCodeBlockType.Helper)
{
var baseIndentation = GetBaseIndentation(root, text, visibleSpan);
return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule);
}
if (currentSpanIndex == 0)
{
break;
}
GetVisibleAndTextSpan(text, spans, --currentSpanIndex, out visibleSpan, out visibleTextSpan);
continue;
}
current = current.Parent;
}
}
var span = spans[spanIndex];
var indentation = GetBaseIndentation(root, text, span);
return new BaseIndentationFormattingRule(root, span, indentation, _vbHelperFormattingRule);
}
private void GetVisibleAndTextSpan(SourceText text, List<TextSpan> spans, int spanIndex, out TextSpan visibleSpan, out TextSpan visibleTextSpan)
{
visibleSpan = spans[spanIndex];
visibleTextSpan = GetVisibleTextSpan(text, visibleSpan);
if (visibleTextSpan.IsEmpty)
{
// span has no text in them
visibleTextSpan = visibleSpan;
}
}
private int GetBaseIndentation(SyntaxNode root, SourceText text, TextSpan span)
{
// Is this right? We should probably get this from the IVsContainedLanguageHost instead.
var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>();
var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer);
var additionalIndentation = GetAdditionalIndentation(root, text, span);
string baseIndentationString;
int parent, indentSize, useTabs = 0, tabSize = 0;
// Skip over the first line, since it's in "Venus space" anyway.
var startingLine = text.Lines.GetLineFromPosition(span.Start);
for (var line = startingLine; line.Start < span.End; line = text.Lines[line.LineNumber + 1])
{
Marshal.ThrowExceptionForHR(
this.ContainedLanguage.ContainedLanguageHost.GetLineIndent(
line.LineNumber,
out baseIndentationString,
out parent,
out indentSize,
out useTabs,
out tabSize));
if (!string.IsNullOrEmpty(baseIndentationString))
{
return baseIndentationString.GetColumnFromLineOffset(baseIndentationString.Length, editorOptions.GetTabSize()) + additionalIndentation;
}
}
return additionalIndentation;
}
private TextSpan GetVisibleTextSpan(SourceText text, TextSpan visibleSpan, bool uptoFirstAndLastLine = false)
{
var start = visibleSpan.Start;
for (; start < visibleSpan.End; start++)
{
if (!char.IsWhiteSpace(text[start]))
{
break;
}
}
var end = visibleSpan.End - 1;
if (start <= end)
{
for (; start <= end; end--)
{
if (!char.IsWhiteSpace(text[end]))
{
break;
}
}
}
if (uptoFirstAndLastLine)
{
var firstLine = text.Lines.GetLineFromPosition(visibleSpan.Start);
var lastLine = text.Lines.GetLineFromPosition(visibleSpan.End);
if (firstLine.LineNumber < lastLine.LineNumber)
{
start = (start < firstLine.End) ? start : firstLine.End;
end = (lastLine.Start < end + 1) ? end : lastLine.Start - 1;
}
}
return (start <= end) ? TextSpan.FromBounds(start, end + 1) : default(TextSpan);
}
private int GetAdditionalIndentation(SyntaxNode root, SourceText text, TextSpan span)
{
if (_hostType == HostType.HTML)
{
return _optionService.GetOption(FormattingOptions.IndentationSize, this.Project.Language);
}
if (_hostType == HostType.Razor)
{
var type = GetRazorCodeBlockType(span.Start);
// razor block
if (type == RazorCodeBlockType.Block)
{
// more workaround for csharp razor case. when } for csharp razor code block is just typed, "}" exist
// in both subject and surface buffer and there is no easy way to figure out who owns } just typed.
// in this case, we let razor owns it. later razor will remove } from subject buffer if it is something
// razor owns.
if (this.Project.Language == LanguageNames.CSharp)
{
var textSpan = GetVisibleTextSpan(text, span);
var end = textSpan.End - 1;
if (end >= 0 && text[end] == '}')
{
var token = root.FindToken(end);
var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>();
if (token.Span.Start == end && syntaxFact != null)
{
SyntaxToken openBrace;
if (syntaxFact.TryGetCorrespondingOpenBrace(token, out openBrace) && !textSpan.Contains(openBrace.Span))
{
return 0;
}
}
}
}
// same as C#, but different text is in the buffer
if (this.Project.Language == LanguageNames.VisualBasic)
{
var textSpan = GetVisibleTextSpan(text, span);
var subjectSnapshot = _containedLanguage.SubjectBuffer.CurrentSnapshot;
var end = textSpan.End - 1;
if (end >= 0)
{
var ch = subjectSnapshot[end];
if (CheckCode(subjectSnapshot, textSpan.End, ch, VBRazorBlock, checkAt: false) ||
CheckCode(subjectSnapshot, textSpan.End, ch, FunctionsRazor, checkAt: false))
{
var token = root.FindToken(end, findInsideTrivia: true);
var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>();
if (token.Span.End == textSpan.End && syntaxFact != null)
{
if (syntaxFact.IsSkippedTokensTrivia(token.Parent))
{
return 0;
}
}
}
}
}
return _optionService.GetOption(FormattingOptions.IndentationSize, this.Project.Language);
}
}
return 0;
}
private RazorCodeBlockType GetRazorCodeBlockType(int position)
{
Debug.Assert(_hostType == HostType.Razor);
var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer();
var subjectSnapshot = subjectBuffer.CurrentSnapshot;
var surfaceSnapshot = ((IProjectionBuffer)_containedLanguage.DataBuffer).CurrentSnapshot;
var surfacePoint = surfaceSnapshot.MapFromSourceSnapshot(new SnapshotPoint(subjectSnapshot, position), PositionAffinity.Predecessor);
if (!surfacePoint.HasValue)
{
// how this can happen?
return RazorCodeBlockType.Implicit;
}
var ch = char.ToLower(surfaceSnapshot[Math.Max(surfacePoint.Value - 1, 0)]);
// razor block
if (IsCodeBlock(surfaceSnapshot, surfacePoint.Value, ch))
{
return RazorCodeBlockType.Block;
}
if (ch == RazorExplicit)
{
return RazorCodeBlockType.Explicit;
}
if (CheckCode(surfaceSnapshot, surfacePoint.Value, HelperRazor))
{
return RazorCodeBlockType.Helper;
}
return RazorCodeBlockType.Implicit;
}
private bool IsCodeBlock(ITextSnapshot surfaceSnapshot, int position, char ch)
{
if (this.Project.Language == LanguageNames.CSharp)
{
return CheckCode(surfaceSnapshot, position, ch, CSharpRazorBlock) ||
CheckCode(surfaceSnapshot, position, ch, FunctionsRazor, CSharpRazorBlock);
}
if (this.Project.Language == LanguageNames.VisualBasic)
{
return CheckCode(surfaceSnapshot, position, ch, VBRazorBlock) ||
CheckCode(surfaceSnapshot, position, ch, FunctionsRazor);
}
return false;
}
private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag, bool checkAt = true)
{
if (ch != tag[tag.Length - 1] || position < tag.Length)
{
return false;
}
var start = position - tag.Length;
var razorTag = snapshot.GetText(start, tag.Length);
return string.Equals(razorTag, tag, StringComparison.OrdinalIgnoreCase) && (!checkAt || snapshot[start - 1] == RazorExplicit);
}
private bool CheckCode(ITextSnapshot snapshot, int position, string tag)
{
int i = position - 1;
if (i < 0)
{
return false;
}
for (; i >= 0; i--)
{
if (!char.IsWhiteSpace(snapshot[i]))
{
break;
}
}
var ch = snapshot[i];
position = i + 1;
return CheckCode(snapshot, position, ch, tag);
}
private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag1, string tag2)
{
if (!CheckCode(snapshot, position, ch, tag2, checkAt: false))
{
return false;
}
return CheckCode(snapshot, position - tag2.Length, tag1);
}
public ITextUndoHistory GetTextUndoHistory()
{
// In Venus scenarios, the undo history is associated with the data buffer
return _componentModel.GetService<ITextUndoHistoryRegistry>().GetHistory(_containedLanguage.DataBuffer);
}
public uint GetItemId()
{
AssertIsForeground();
if (_itemMoniker == null)
{
return (uint)VSConstants.VSITEMID.Nil;
}
uint itemId;
return Project.Hierarchy.ParseCanonicalName(_itemMoniker, out itemId) == VSConstants.S_OK
? itemId
: (uint)VSConstants.VSITEMID.Nil;
}
private enum RazorCodeBlockType
{
Block,
Explicit,
Implicit,
Helper
}
private enum HostType
{
HTML,
Razor,
XOML
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Chip.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using System.Diagnostics;
#endregion
namespace Pickture
{
class Chip
{
#region Enums
public enum RevolveDirection
{
Up = 0,
Down = 1,
Left = 2,
Right = 3
};
#endregion
#region Fields
// These values are used to track when the puzzle is completed
int xPosition;
int yPosition;
bool horizontalRotationCorrect = true;
bool verticalRotationCorrect = true;
// Rendering
float colorOverride = 1f;
float glowScale;
Vector2 texCoordScale;
Vector2 texCoordTranslationFront;
Vector2 texCoordTranslationBack;
// Animation
bool isRevolving;
Matrix orientationMatrix = Matrix.Identity;
RevolveDirection revolutionDirection;
float revolutionDuration;
float currentRevolutionTime;
float currentRevolutionY;
float targetRevolutionY;
float currentRevolutionX;
float targetRevolutionX;
public const float FlipDuration = 0.65f;
#endregion
#region Properties
public Matrix OrientationMatrix
{
get { return orientationMatrix; }
}
public bool HorizontalRotationCorrect
{
get { return horizontalRotationCorrect; }
}
public bool VerticalRotationCorrect
{
get { return verticalRotationCorrect; }
}
public int XPosition
{
get { return xPosition; }
set { xPosition = value; }
}
public int YPosition
{
get { return yPosition; }
set { yPosition = value; }
}
public float ColorOverride
{
get { return colorOverride; }
set { colorOverride = value; }
}
public float GlowScale
{
get { return glowScale; }
set { glowScale = value; }
}
public Vector2 TexCoordScale
{
get { return texCoordScale; }
set { texCoordScale = value; }
}
public Vector2 TexCoordTranslationFront
{
get { return texCoordTranslationFront; }
set { texCoordTranslationFront = value; }
}
public Vector2 TexCoordTranslationBack
{
get { return texCoordTranslationBack; }
set { texCoordTranslationBack = value; }
}
#endregion
#region Interaction
/// <summary>
/// Returns a random revolution direction.
/// </summary>
public static RevolveDirection GetRandomDirection()
{
return (RevolveDirection)RandomHelper.Random.Next(4);
}
/// <summary>
/// Causes the chip to revolve one half revolution in a specified direction.
/// </summary>
/// <param name="direction">Direction to revolve.</param>
/// <param name="amount">Amount to revolve in radians. Values other than
/// MathHelpers.Pi or MathHelpers.TwoPi may break other behaviors.</param>
/// <param name="revolutionDuration">Duration of the animation.</param>
public void Flip(RevolveDirection direction)
{
// Do nothing if we are already revolving
if (isRevolving)
return;
float amount = MathHelper.Pi;
Audio.Play("Flip Chip");
// Select a new target rotation
switch (direction)
{
case RevolveDirection.Up:
if (!horizontalRotationCorrect)
amount = -amount;
targetRevolutionX = currentRevolutionX - amount;
break;
case RevolveDirection.Down:
if (!horizontalRotationCorrect)
amount = -amount;
targetRevolutionX = currentRevolutionX + amount;
break;
case RevolveDirection.Left:
targetRevolutionY = currentRevolutionY - amount;
break;
case RevolveDirection.Right:
targetRevolutionY = currentRevolutionY + amount;
break;
}
// Begin the animation
this.revolutionDirection = direction;
this.revolutionDuration = FlipDuration;
this.currentRevolutionTime = 0.0f;
this.isRevolving = true;
}
#endregion
#region Update and Draw
/// <summary>
/// Animates the chip.
/// </summary>
public void Update(GameTime gameTime)
{
if (!isRevolving)
return;
currentRevolutionTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (currentRevolutionTime >= revolutionDuration)
{
// Done animating
currentRevolutionTime = 0.0f;
isRevolving = false;
// Redetermine if the orientation is correct
switch (revolutionDirection)
{
case RevolveDirection.Left:
case RevolveDirection.Right:
{
currentRevolutionY = targetRevolutionY;
horizontalRotationCorrect = !horizontalRotationCorrect;
}
break;
case RevolveDirection.Up:
case RevolveDirection.Down:
{
currentRevolutionX = targetRevolutionX;
verticalRotationCorrect = !verticalRotationCorrect;
}
break;
}
// Rebuild the orientation matrix
orientationMatrix = Matrix.CreateRotationX(currentRevolutionX) *
Matrix.CreateRotationY(currentRevolutionY);
}
else
{
// The animation is the chip rotating a little bit too far, then back
// Use a stretch factor to scale the revolution time
const float stretchFactor = 0.2f;
float revolutionFraction =
currentRevolutionTime / revolutionDuration;
revolutionFraction *= (1.0f + (2.0f * stretchFactor));
revolutionFraction -= stretchFactor;
revolutionFraction *= MathHelper.Pi;
// and use a Sin curve to give a nice smooth swing past and back
float rotationValue = (revolutionFraction - MathHelper.PiOver2);
rotationValue = (float)Math.Sin(rotationValue);
float overflowFactor = (float)Math.Sin(MathHelper.PiOver2 +
(MathHelper.Pi * stretchFactor));
rotationValue =
((rotationValue * (1.0f / overflowFactor)) + 1.0f) / 2.0f;
// Givin the rotation value, animate in the correct direction
switch (revolutionDirection)
{
case RevolveDirection.Left:
case RevolveDirection.Right:
{
float tempRevolutionY = MathHelper.Lerp(currentRevolutionY,
targetRevolutionY, rotationValue);
orientationMatrix = Matrix.CreateRotationX(currentRevolutionX) *
Matrix.CreateRotationY(tempRevolutionY);
}
break;
case RevolveDirection.Up:
case RevolveDirection.Down:
{
float tempRevolutionX = MathHelper.Lerp(currentRevolutionX,
targetRevolutionX, rotationValue);
orientationMatrix = Matrix.CreateRotationX(tempRevolutionX) *
Matrix.CreateRotationY(currentRevolutionY);
}
break;
}
}
}
public void Draw(Board board, Model chipModel, Matrix baseTransform,
Matrix[] chipTransforms)
{
Matrix world = OrientationMatrix * baseTransform;
LightingEffect lightingEffect = board.LightingEffect;
// Set model level render states
lightingEffect.GlowScale.SetValue(GlowScale);
lightingEffect.ColorOverride.SetValue(ColorOverride);
lightingEffect.TexCoordScale.SetValue(TexCoordScale);
foreach (ModelMesh mesh in chipModel.Meshes)
{
// Calculate matricies
Matrix modelWorld = chipTransforms[mesh.ParentBone.Index] * world;
Matrix modelWorldView = modelWorld * board.Camera.ViewMatrix;
Matrix modelWorldViewProjection =
modelWorldView * board.Camera.ProjectionMatrix;
// Set matricies
lightingEffect.World.SetValue(modelWorld);
lightingEffect.WorldView.SetValue(modelWorldView);
lightingEffect.WorldViewProjection.SetValue(modelWorldViewProjection);
foreach (ModelMeshPart meshPart in mesh.MeshParts)
{
// Get the material identifier out of the mesh part tag
bool textureSet = false;
string materialIdentifier = meshPart.Tag as string;
if (materialIdentifier != null)
{
// The material identifier is used to determine which textures
// to draw with
switch (materialIdentifier)
{
case "Front":
lightingEffect.TexCoordTranslation.SetValue(
this.TexCoordTranslationFront);
textureSet = SetTexture(board, 0);
break;
case "Back":
lightingEffect.TexCoordTranslation.SetValue(
this.TexCoordTranslationBack);
// Reuse the front side texture on single sided boards
if (board.TwoSided)
textureSet = SetTexture(board, 1);
else
textureSet = SetTexture(board, 0);
break;
default:
lightingEffect.DiffuseTexture.SetValue((Texture2D)null);
break;
}
}
// set the appropriate technique, depending on how many textures
// are being rendered
if (textureSet)
{
lightingEffect.Effect.CurrentTechnique =
lightingEffect.SingleTextureTechnique;
}
else
{
lightingEffect.Effect.CurrentTechnique =
lightingEffect.NoTextureTechnique;
}
// draw the mesh
lightingEffect.Effect.Begin();
DrawHelper.DrawMeshPart(mesh, meshPart, lightingEffect.Effect);
lightingEffect.Effect.End();
}
}
}
/// <summary>
/// Sets the texture parameter from the appropriate picture sets.
/// </summary>
/// <returns>
/// If true, a valid texture was set on the device by this function.
/// </returns>
static bool SetTexture(Board board, int textureIndex)
{
LightingEffect lightingEffect = board.LightingEffect;
Texture2D texture = null;
if (board.CurrentPictureSet != null)
{
texture = board.CurrentPictureSet.GetTexture(textureIndex);
}
if ((texture == null) && (board.NextPictureSet != null))
{
texture = board.NextPictureSet.GetTexture(textureIndex);
}
lightingEffect.DiffuseTexture.SetValue(texture);
return (texture != null);
}
#endregion
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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.Diagnostics;
namespace SharpDX.Direct3D10
{
public partial class EffectVectorVariable
{
private const string VectorInvalidSize = "Invalid Vector size: Must be 16 bytes or 4 x 4 bytes";
/// <summary>
/// Get a four-component vector that contains integer data.
/// </summary>
/// <returns>Returns a four-component vector that contains integer data </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetIntVector([Out] int* pData)</unmanaged>
public SharpDX.Int4 GetIntVector()
{
Int4 temp;
GetIntVector(out temp);
return temp;
}
/// <summary>
/// Get a four-component vector that contains floating-point data.
/// </summary>
/// <returns>Returns a four-component vector that contains floating-point data.</returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetFloatVector([Out] float* pData)</unmanaged>
public SharpDX.Vector4 GetFloatVector()
{
SharpDX.Vector4 temp;
GetFloatVector(out temp);
return temp;
}
/// <summary>
/// Get a four-component vector that contains boolean data.
/// </summary>
/// <returns>a four-component vector that contains boolean data. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetBoolVector([Out, Buffer] BOOL* pData)</unmanaged>
public Bool4 GetBoolVector()
{
Bool4 temp;
GetBoolVector(out temp);
return temp;
}
/// <summary>
/// Get a four-component vector.
/// </summary>
/// <typeparam name="T">Type of the four-component vector</typeparam>
/// <returns>a four-component vector. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetFloatVector([Out, Buffer] BOOL* pData)</unmanaged>
public unsafe T GetVector<T>() where T : struct
{
T temp;
GetIntVector(out *(Int4*)Interop.CastOut(out temp));
return temp;
}
/// <summary>
/// Set an array of four-component vectors that contain integer data.
/// </summary>
/// <param name="array">A reference to the start of the data to set. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetIntVectorArray([In, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(SharpDX.Int4[] array)
{
Set(array, 0, array.Length);
}
/// <summary>
/// Set an array of four-component vectors that contain floating-point data.
/// </summary>
/// <param name="array">A reference to the start of the data to set. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVectorArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(SharpDX.Vector4[] array)
{
Set(array, 0, array.Length);
}
/// <summary>
/// Set an array of four-component vectors that contain floating-point data.
/// </summary>
/// <typeparam name="T">Type of the four-component vector</typeparam>
/// <param name="array">A reference to the start of the data to set.</param>
/// <returns>
/// Returns one of the following {{Direct3D 10 Return Codes}}.
/// </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVectorArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set<T>(T[] array) where T : struct
{
Trace.Assert(Utilities.SizeOf<T>() == 16, VectorInvalidSize);
Set(Interop.CastArray<Vector4, T>(array), 0, array.Length);
}
/// <summary>
/// Set a x-component vector.
/// </summary>
/// <param name="value">A reference to the first component. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged>
public void Set<T>(T value) where T : struct
{
Set(ref value);
}
/// <summary>
/// Set a x-component vector.
/// </summary>
/// <param name="value">A reference to the first component. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged>
public unsafe void Set<T>(ref T value) where T : struct
{
Trace.Assert(Utilities.SizeOf<T>() <= 16, VectorInvalidSize);
SetRawValue(new IntPtr(Interop.Fixed(ref value)), 0, Utilities.SizeOf<T>());
}
/// <summary>
/// Set a two-component vector that contains floating-point data.
/// </summary>
/// <param name="value">A reference to the first component. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged>
public void Set(SharpDX.Vector2 value)
{
unsafe
{
SetRawValue(new IntPtr(&value), 0, Utilities.SizeOf<SharpDX.Vector2>());
}
}
/// <summary>
/// Set a three-component vector that contains floating-point data.
/// </summary>
/// <param name="value">A reference to the first component. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged>
public void Set(SharpDX.Vector3 value)
{
unsafe
{
SetRawValue(new IntPtr(&value), 0, Utilities.SizeOf<SharpDX.Vector3>());
}
}
/// <summary>
/// Set a four-component color that contains floating-point data.
/// </summary>
/// <param name="value">A reference to the first component. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged>
public void Set(SharpDX.Color4 value)
{
unsafe
{
SetRawValue(new IntPtr(&value), 0, Utilities.SizeOf<SharpDX.Color4>());
}
}
/// <summary>
/// Set an array of four-component color that contain floating-point data.
/// </summary>
/// <param name="array">A reference to the start of the data to set. </param>
/// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVectorArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged>
public void Set(SharpDX.Color4[] array)
{
unsafe
{
fixed (void* pArray = &array[0]) SetRawValue((IntPtr)pArray, 0, array.Length * Utilities.SizeOf<SharpDX.Color4>());
}
}
/// <summary>
/// Get an array of four-component vectors that contain integer data.
/// </summary>
/// <param name="count">The number of array elements to set. </param>
/// <returns>Returns an array of four-component vectors that contain integer data. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetIntVectorArray([Out, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged>
public SharpDX.Int4[] GetIntVectorArray(int count)
{
var temp = new Int4[count];
GetIntVectorArray(temp, 0, count);
return temp;
}
/// <summary>
/// Get an array of four-component vectors that contain floating-point data.
/// </summary>
/// <param name="count">The number of array elements to set. </param>
/// <returns>Returns an array of four-component vectors that contain floating-point data. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetFloatVectorArray([None] float* pData,[None] int Offset,[None] int Count)</unmanaged>
public SharpDX.Vector4[] GetFloatVectorArray(int count)
{
var temp = new SharpDX.Vector4[count];
GetFloatVectorArray(temp, 0, count);
return temp;
}
/// <summary>
/// Get an array of four-component vectors that contain boolean data.
/// </summary>
/// <param name="count">The number of array elements to set. </param>
/// <returns>an array of four-component vectors that contain boolean data. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetBoolVectorArray([Out, Buffer] BOOL* pData,[None] int Offset,[None] int Count)</unmanaged>
public Bool4[] GetBoolVectorArray(int count)
{
var temp = new Bool4[count];
GetBoolVectorArray(temp, 0, count);
return temp;
}
/// <summary>
/// Get an array of four-component vectors that contain boolean data.
/// </summary>
/// <param name="count">The number of array elements to set. </param>
/// <returns>an array of four-component vectors that contain boolean data. </returns>
/// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetBoolVectorArray([Out, Buffer] BOOL* pData,[None] int Offset,[None] int Count)</unmanaged>
public T[] GetVectorArray<T>(int count) where T : struct
{
var temp = new T[count];
GetIntVectorArray(Interop.CastArray<Int4, T>(temp), 0, count);
return temp;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlQueryRuntime.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.IlGen;
using System.ComponentModel;
using MS.Internal.Xml.XPath;
using System.Runtime.Versioning;
namespace System.Xml.Xsl.Runtime {
using Res = System.Xml.Utils.Res;
/// <summary>
/// XmlQueryRuntime is passed as the first parameter to all generated query methods.
///
/// XmlQueryRuntime contains runtime support for generated ILGen queries:
/// 1. Stack of output writers (stack handles nested document construction)
/// 2. Manages list of all xml types that are used within the query
/// 3. Manages list of all atomized names that are used within the query
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class XmlQueryRuntime {
// Early-Bound Library Objects
private XmlQueryContext ctxt;
private XsltLibrary xsltLib;
private EarlyBoundInfo[] earlyInfo;
private object[] earlyObjects;
// Global variables and parameters
private string[] globalNames;
private object[] globalValues;
// Names, prefix mappings, and name filters
private XmlNameTable nameTableQuery;
private string[] atomizedNames; // Names after atomization
private XmlNavigatorFilter[] filters; // Name filters (contain atomized names)
private StringPair[][] prefixMappingsList; // Lists of prefix mappings (used to resolve computed names)
// Xml types
private XmlQueryType[] types;
// Collations
private XmlCollation[] collations;
// Document ordering
private DocumentOrderComparer docOrderCmp;
// Indexes
private ArrayList[] indexes;
// Output construction
private XmlQueryOutput output;
private Stack<XmlQueryOutput> stkOutput;
//-----------------------------------------------
// Constructors
//-----------------------------------------------
/// <summary>
/// This constructor is internal so that external users cannot construct it (and therefore we do not have to test it separately).
/// </summary>
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
internal XmlQueryRuntime(XmlQueryStaticData data, object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt) {
Debug.Assert(data != null);
string[] names = data.Names;
Int32Pair[] filters = data.Filters;
WhitespaceRuleLookup wsRules;
int i;
// Early-Bound Library Objects
wsRules = (data.WhitespaceRules != null && data.WhitespaceRules.Count != 0) ? new WhitespaceRuleLookup(data.WhitespaceRules) : null;
this.ctxt = new XmlQueryContext(this, defaultDataSource, dataSources, argList, wsRules);
this.xsltLib = null;
this.earlyInfo = data.EarlyBound;
this.earlyObjects = (this.earlyInfo != null) ? new object[earlyInfo.Length] : null;
// Global variables and parameters
this.globalNames = data.GlobalNames;
this.globalValues = (this.globalNames != null) ? new object[this.globalNames.Length] : null;
// Names
this.nameTableQuery = this.ctxt.QueryNameTable;
this.atomizedNames = null;
if (names != null) {
// Atomize all names in "nameTableQuery". Use names from the default data source's
// name table when possible.
XmlNameTable nameTableDefault = ctxt.DefaultNameTable;
this.atomizedNames = new string[names.Length];
if (nameTableDefault != this.nameTableQuery && nameTableDefault != null) {
// Ensure that atomized names from the default data source are added to the
// name table used in this query
for (i = 0; i < names.Length; i++) {
string name = nameTableDefault.Get(names[i]);
this.atomizedNames[i] = this.nameTableQuery.Add(name ?? names[i]);
}
}
else {
// Enter names into nametable used in this query
for (i = 0; i < names.Length; i++)
this.atomizedNames[i] = this.nameTableQuery.Add(names[i]);
}
}
// Name filters
this.filters = null;
if (filters != null) {
// Construct name filters. Each pair of integers in the filters[] array specifies the
// (localName, namespaceUri) of the NameFilter to be created.
this.filters = new XmlNavigatorFilter[filters.Length];
for (i = 0; i < filters.Length; i++)
this.filters[i] = XmlNavNameFilter.Create(this.atomizedNames[filters[i].Left], this.atomizedNames[filters[i].Right]);
}
// Prefix maping lists
this.prefixMappingsList = data.PrefixMappingsList;
// Xml types
this.types = data.Types;
// Xml collations
this.collations = data.Collations;
// Document ordering
this.docOrderCmp = new DocumentOrderComparer();
// Indexes
this.indexes = null;
// Output construction
this.stkOutput = new Stack<XmlQueryOutput>(16);
this.output = new XmlQueryOutput(this, seqWrt);
}
//-----------------------------------------------
// Debugger Utility Methods
//-----------------------------------------------
/// <summary>
/// Return array containing the names of all the global variables and parameters used in this query, in this format:
/// {namespace}prefix:local-name
/// </summary>
public string[] DebugGetGlobalNames() {
return this.globalNames;
}
/// <summary>
/// Get the value of a global value having the specified name. Always return the global value as a list of XPathItem.
/// Return null if there is no global value having the specified name.
/// </summary>
public IList DebugGetGlobalValue(string name) {
for (int idx = 0; idx < this.globalNames.Length; idx++) {
if (this.globalNames[idx] == name) {
Debug.Assert(IsGlobalComputed(idx), "Cannot get the value of a global value until it has been computed.");
Debug.Assert(this.globalValues[idx] is IList<XPathItem>, "Only debugger should call this method, and all global values should have type item* in debugging scenarios.");
return (IList) this.globalValues[idx];
}
}
return null;
}
/// <summary>
/// Set the value of a global value having the specified name. If there is no such value, this method is a no-op.
/// </summary>
public void DebugSetGlobalValue(string name, object value) {
for (int idx = 0; idx < this.globalNames.Length; idx++) {
if (this.globalNames[idx] == name) {
Debug.Assert(IsGlobalComputed(idx), "Cannot get the value of a global value until it has been computed.");
Debug.Assert(this.globalValues[idx] is IList<XPathItem>, "Only debugger should call this method, and all global values should have type item* in debugging scenarios.");
// Always convert "value" to a list of XPathItem using the item* converter
this.globalValues[idx] = (IList<XPathItem>) XmlAnyListConverter.ItemList.ChangeType(value, typeof(XPathItem[]), null);
break;
}
}
}
/// <summary>
/// Convert sequence to it's appropriate XSLT type and return to caller.
/// </summary>
public object DebugGetXsltValue(IList seq) {
if (seq != null && seq.Count == 1) {
XPathItem item = seq[0] as XPathItem;
if (item != null && !item.IsNode) {
return item.TypedValue;
}
else if (item is RtfNavigator) {
return ((RtfNavigator) item).ToNavigator();
}
}
return seq;
}
//-----------------------------------------------
// Early-Bound Library Objects
//-----------------------------------------------
internal const BindingFlags EarlyBoundFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
internal const BindingFlags LateBoundFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
/// <summary>
/// Return the object that manages external user context information such as data sources, parameters, extension objects, etc.
/// </summary>
public XmlQueryContext ExternalContext {
get { return this.ctxt; }
}
/// <summary>
/// Return the object that manages the state needed to implement various Xslt functions.
/// </summary>
public XsltLibrary XsltFunctions {
get {
if (this.xsltLib == null) {
this.xsltLib = new XsltLibrary(this);
}
return this.xsltLib;
}
}
/// <summary>
/// Get the early-bound extension object identified by "index". If it does not yet exist, create an instance using the
/// corresponding ConstructorInfo.
/// </summary>
public object GetEarlyBoundObject(int index) {
object obj;
Debug.Assert(this.earlyObjects != null && index < this.earlyObjects.Length, "Early bound object does not exist");
obj = this.earlyObjects[index];
if (obj == null) {
// Early-bound object does not yet exist, so create it now
obj = this.earlyInfo[index].CreateObject();
this.earlyObjects[index] = obj;
}
return obj;
}
/// <summary>
/// Return true if the early bound object identified by "namespaceUri" contains a method that matches "name".
/// </summary>
public bool EarlyBoundFunctionExists(string name, string namespaceUri) {
if (this.earlyInfo == null)
return false;
for (int idx = 0; idx < this.earlyInfo.Length; idx++) {
if (namespaceUri == this.earlyInfo[idx].NamespaceUri)
return new XmlExtensionFunction(name, namespaceUri, -1, this.earlyInfo[idx].EarlyBoundType, EarlyBoundFlags).CanBind();
}
return false;
}
//-----------------------------------------------
// Global variables and parameters
//-----------------------------------------------
/// <summary>
/// Return true if the global value specified by idxValue was previously computed.
/// </summary>
public bool IsGlobalComputed(int index) {
return this.globalValues[index] != null;
}
/// <summary>
/// Return the value that is bound to the global variable or parameter specified by idxValue.
/// If the value has not yet been computed, then compute it now and store it in this.globalValues.
/// </summary>
public object GetGlobalValue(int index) {
Debug.Assert(IsGlobalComputed(index), "Cannot get the value of a global value until it has been computed.");
return this.globalValues[index];
}
/// <summary>
/// Return the value that is bound to the global variable or parameter specified by idxValue.
/// If the value has not yet been computed, then compute it now and store it in this.globalValues.
/// </summary>
public void SetGlobalValue(int index, object value) {
Debug.Assert(!IsGlobalComputed(index), "Global value should only be set once.");
this.globalValues[index] = value;
}
//-----------------------------------------------
// Names, prefix mappings, and name filters
//-----------------------------------------------
/// <summary>
/// Return the name table used to atomize all names used by the query.
/// </summary>
public XmlNameTable NameTable {
get { return this.nameTableQuery; }
}
/// <summary>
/// Get the atomized name at the specified index in the array of names.
/// </summary>
public string GetAtomizedName(int index) {
Debug.Assert(this.atomizedNames != null);
return this.atomizedNames[index];
}
/// <summary>
/// Get the name filter at the specified index in the array of filters.
/// </summary>
public XmlNavigatorFilter GetNameFilter(int index) {
Debug.Assert(this.filters != null);
return this.filters[index];
}
/// <summary>
/// XPathNodeType.All: Filters all nodes
/// XPathNodeType.Attribute: Filters attributes
/// XPathNodeType.Namespace: Not allowed
/// XPathNodeType.XXX: Filters all nodes *except* those having XPathNodeType.XXX
/// </summary>
public XmlNavigatorFilter GetTypeFilter(XPathNodeType nodeType) {
if (nodeType == XPathNodeType.All)
return XmlNavNeverFilter.Create();
if (nodeType == XPathNodeType.Attribute)
return XmlNavAttrFilter.Create();
return XmlNavTypeFilter.Create(nodeType);
}
/// <summary>
/// Parse the specified tag name (foo:bar) and resolve the resulting prefix. If the prefix cannot be resolved,
/// then throw an error. Return an XmlQualifiedName.
/// </summary>
public XmlQualifiedName ParseTagName(string tagName, int indexPrefixMappings) {
string prefix, localName, ns;
// Parse the tagName as a prefix, localName pair and resolve the prefix
ParseTagName(tagName, indexPrefixMappings, out prefix, out localName, out ns);
return new XmlQualifiedName(localName, ns);
}
/// <summary>
/// Parse the specified tag name (foo:bar). Return an XmlQualifiedName consisting of the parsed local name
/// and the specified namespace.
/// </summary>
public XmlQualifiedName ParseTagName(string tagName, string ns) {
string prefix, localName;
// Parse the tagName as a prefix, localName pair
ValidateNames.ParseQNameThrow(tagName, out prefix, out localName);
return new XmlQualifiedName(localName, ns);
}
/// <summary>
/// Parse the specified tag name (foo:bar) and resolve the resulting prefix. If the prefix cannot be resolved,
/// then throw an error. Return the prefix, localName, and namespace URI.
/// </summary>
internal void ParseTagName(string tagName, int idxPrefixMappings, out string prefix, out string localName, out string ns) {
Debug.Assert(this.prefixMappingsList != null);
// Parse the tagName as a prefix, localName pair
ValidateNames.ParseQNameThrow(tagName, out prefix, out localName);
// Map the prefix to a namespace URI
ns = null;
foreach (StringPair pair in this.prefixMappingsList[idxPrefixMappings]) {
if (prefix == pair.Left) {
ns = pair.Right;
break;
}
}
// Throw exception if prefix could not be resolved
if (ns == null) {
// Check for mappings that are always in-scope
if (prefix.Length == 0)
ns = "";
else if (prefix.Equals("xml"))
ns = XmlReservedNs.NsXml;
// It is not correct to resolve xmlns prefix in XPath but removing it would be a breaking change.
else if (prefix.Equals("xmlns"))
ns = XmlReservedNs.NsXmlNs;
else
throw new XslTransformException(Res.Xslt_InvalidPrefix, prefix);
}
}
/// <summary>
/// Return true if the nav1's LocalName and NamespaceURI properties equal nav2's corresponding properties.
/// </summary>
public bool IsQNameEqual(XPathNavigator n1, XPathNavigator n2) {
if ((object) n1.NameTable == (object) n2.NameTable) {
// Use atomized comparison
return (object) n1.LocalName == (object) n2.LocalName && (object) n1.NamespaceURI == (object) n2.NamespaceURI;
}
return (n1.LocalName == n2.LocalName) && (n1.NamespaceURI == n2.NamespaceURI);
}
/// <summary>
/// Return true if the specified navigator's LocalName and NamespaceURI properties equal the argument names.
/// </summary>
public bool IsQNameEqual(XPathNavigator navigator, int indexLocalName, int indexNamespaceUri) {
if ((object) navigator.NameTable == (object) this.nameTableQuery) {
// Use atomized comparison
return ((object) GetAtomizedName(indexLocalName) == (object) navigator.LocalName &&
(object) GetAtomizedName(indexNamespaceUri) == (object) navigator.NamespaceURI);
}
// Use string comparison
return (GetAtomizedName(indexLocalName) == navigator.LocalName) && (GetAtomizedName(indexNamespaceUri) == navigator.NamespaceURI);
}
//-----------------------------------------------
// Xml types
//-----------------------------------------------
/// <summary>
/// Get the array of xml types that are used within this query.
/// </summary>
internal XmlQueryType[] XmlTypes {
get { return this.types; }
}
/// <summary>
/// Get the Xml query type at the specified index in the array of types.
/// </summary>
internal XmlQueryType GetXmlType(int idxType) {
Debug.Assert(this.types != null);
return this.types[idxType];
}
/// <summary>
/// Forward call to ChangeTypeXsltArgument(XmlQueryType, object, Type).
/// </summary>
public object ChangeTypeXsltArgument(int indexType, object value, Type destinationType) {
return ChangeTypeXsltArgument(GetXmlType(indexType), value, destinationType);
}
/// <summary>
/// Convert from the Clr type of "value" to Clr type "destinationType" using V1 Xslt rules.
/// These rules include converting any Rtf values to Nodes.
/// </summary>
internal object ChangeTypeXsltArgument(XmlQueryType xmlType, object value, Type destinationType) {
Debug.Assert(XmlILTypeHelper.GetStorageType(xmlType).IsAssignableFrom(value.GetType()),
"Values passed to ChangeTypeXsltArgument should be in ILGen's default Clr representation.");
Debug.Assert(destinationType == XsltConvert.ObjectType || !destinationType.IsAssignableFrom(value.GetType()),
"No need to call ChangeTypeXsltArgument since value is already assignable to destinationType " + destinationType);
switch (xmlType.TypeCode) {
case XmlTypeCode.String:
if (destinationType == XsltConvert.DateTimeType)
value = XsltConvert.ToDateTime((string) value);
break;
case XmlTypeCode.Double:
if (destinationType != XsltConvert.DoubleType)
value = Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture);
break;
case XmlTypeCode.Node:
Debug.Assert(xmlType != XmlQueryTypeFactory.Node && xmlType != XmlQueryTypeFactory.NodeS,
"Rtf values should have been eliminated by caller.");
if (destinationType == XsltConvert.XPathNodeIteratorType) {
value = new XPathArrayIterator((IList) value);
}
else if (destinationType == XsltConvert.XPathNavigatorArrayType) {
// Copy sequence to XPathNavigator[]
IList<XPathNavigator> seq = (IList<XPathNavigator>) value;
XPathNavigator[] navArray = new XPathNavigator[seq.Count];
for (int i = 0; i < seq.Count; i++)
navArray[i] = seq[i];
value = navArray;
}
break;
case XmlTypeCode.Item: {
// Only typeof(object) is supported as a destination type
if (destinationType != XsltConvert.ObjectType)
throw new XslTransformException(Res.Xslt_UnsupportedClrType, destinationType.Name);
// Convert to default, backwards-compatible representation
// 1. NodeSet: System.Xml.XPath.XPathNodeIterator
// 2. Rtf: System.Xml.XPath.XPathNavigator
// 3. Other: Default V1 representation
IList<XPathItem> seq = (IList<XPathItem>) value;
if (seq.Count == 1) {
XPathItem item = seq[0];
if (item.IsNode) {
// Node or Rtf
RtfNavigator rtf = item as RtfNavigator;
if (rtf != null)
value = rtf.ToNavigator();
else
value = new XPathArrayIterator((IList) value);
}
else {
// Atomic value
value = item.TypedValue;
}
}
else {
// Nodeset
value = new XPathArrayIterator((IList) value);
}
break;
}
}
Debug.Assert(destinationType.IsAssignableFrom(value.GetType()), "ChangeType from type " + value.GetType().Name + " to type " + destinationType.Name + " failed");
return value;
}
/// <summary>
/// Forward call to ChangeTypeXsltResult(XmlQueryType, object)
/// </summary>
public object ChangeTypeXsltResult(int indexType, object value) {
return ChangeTypeXsltResult(GetXmlType(indexType), value);
}
/// <summary>
/// Convert from the Clr type of "value" to the default Clr type that ILGen uses to represent the xml type, using
/// the conversion rules of the xml type.
/// </summary>
internal object ChangeTypeXsltResult(XmlQueryType xmlType, object value) {
if (value == null)
throw new XslTransformException(Res.Xslt_ItemNull, string.Empty);
switch (xmlType.TypeCode) {
case XmlTypeCode.String:
if (value.GetType() == XsltConvert.DateTimeType)
value = XsltConvert.ToString((DateTime) value);
break;
case XmlTypeCode.Double:
if (value.GetType() != XsltConvert.DoubleType)
value = ((IConvertible) value).ToDouble(null);
break;
case XmlTypeCode.Node:
if (!xmlType.IsSingleton) {
XPathArrayIterator iter = value as XPathArrayIterator;
// Special-case XPathArrayIterator in order to avoid copies
if (iter != null && iter.AsList is XmlQueryNodeSequence) {
value = iter.AsList as XmlQueryNodeSequence;
}
else {
// Iterate over list and ensure it only contains nodes
XmlQueryNodeSequence seq = new XmlQueryNodeSequence();
IList list = value as IList;
if (list != null) {
for (int i = 0; i < list.Count; i++)
seq.Add(EnsureNavigator(list[i]));
}
else {
foreach (object o in (IEnumerable) value)
seq.Add(EnsureNavigator(o));
}
value = seq;
}
// Always sort node-set by document order
value = ((XmlQueryNodeSequence) value).DocOrderDistinct(this.docOrderCmp);
}
break;
case XmlTypeCode.Item: {
Type sourceType = value.GetType();
IXPathNavigable navigable;
// If static type is item, then infer type based on dynamic value
switch (XsltConvert.InferXsltType(sourceType).TypeCode) {
case XmlTypeCode.Boolean:
value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean), value));
break;
case XmlTypeCode.Double:
value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), ((IConvertible) value).ToDouble(null)));
break;
case XmlTypeCode.String:
if (sourceType == XsltConvert.DateTimeType)
value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), XsltConvert.ToString((DateTime) value)));
else
value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), value));
break;
case XmlTypeCode.Node:
// Support XPathNavigator[]
value = ChangeTypeXsltResult(XmlQueryTypeFactory.NodeS, value);
break;
case XmlTypeCode.Item:
// Support XPathNodeIterator
if (value is XPathNodeIterator) {
value = ChangeTypeXsltResult(XmlQueryTypeFactory.NodeS, value);
break;
}
// Support IXPathNavigable and XPathNavigator
navigable = value as IXPathNavigable;
if (navigable != null) {
if (value is XPathNavigator)
value = new XmlQueryNodeSequence((XPathNavigator) value);
else
value = new XmlQueryNodeSequence(navigable.CreateNavigator());
break;
}
throw new XslTransformException(Res.Xslt_UnsupportedClrType, sourceType.Name);
}
break;
}
}
Debug.Assert(XmlILTypeHelper.GetStorageType(xmlType).IsAssignableFrom(value.GetType()), "Xml type " + xmlType + " is not represented in ILGen as " + value.GetType().Name);
return value;
}
/// <summary>
/// Ensure that "value" is a navigator and not null.
/// </summary>
private static XPathNavigator EnsureNavigator(object value) {
XPathNavigator nav = value as XPathNavigator;
if (nav == null)
throw new XslTransformException(Res.Xslt_ItemNull, string.Empty);
return nav;
}
/// <summary>
/// Return true if the type of every item in "seq" matches the xml type identified by "idxType".
/// </summary>
public bool MatchesXmlType(IList<XPathItem> seq, int indexType) {
XmlQueryType typBase = GetXmlType(indexType);
XmlQueryCardinality card;
switch (seq.Count) {
case 0: card = XmlQueryCardinality.Zero; break;
case 1: card = XmlQueryCardinality.One; break;
default: card = XmlQueryCardinality.More; break;
}
if (!(card <= typBase.Cardinality))
return false;
typBase = typBase.Prime;
for (int i = 0; i < seq.Count; i++) {
if (!CreateXmlType(seq[0]).IsSubtypeOf(typBase))
return false;
}
return true;
}
/// <summary>
/// Return true if the type of "item" matches the xml type identified by "idxType".
/// </summary>
public bool MatchesXmlType(XPathItem item, int indexType) {
return CreateXmlType(item).IsSubtypeOf(GetXmlType(indexType));
}
/// <summary>
/// Return true if the type of "seq" is a subtype of a singleton type identified by "code".
/// </summary>
public bool MatchesXmlType(IList<XPathItem> seq, XmlTypeCode code) {
if (seq.Count != 1)
return false;
return MatchesXmlType(seq[0], code);
}
/// <summary>
/// Return true if the type of "item" is a subtype of the type identified by "code".
/// </summary>
public bool MatchesXmlType(XPathItem item, XmlTypeCode code) {
// All atomic type codes appear after AnyAtomicType
if (code > XmlTypeCode.AnyAtomicType)
return !item.IsNode && item.XmlType.TypeCode == code;
// Handle node code and AnyAtomicType
switch (code) {
case XmlTypeCode.AnyAtomicType: return !item.IsNode;
case XmlTypeCode.Node: return item.IsNode;
case XmlTypeCode.Item: return true;
default:
if (!item.IsNode)
return false;
switch (((XPathNavigator) item).NodeType) {
case XPathNodeType.Root: return code == XmlTypeCode.Document;
case XPathNodeType.Element: return code == XmlTypeCode.Element;
case XPathNodeType.Attribute: return code == XmlTypeCode.Attribute;
case XPathNodeType.Namespace: return code == XmlTypeCode.Namespace;
case XPathNodeType.Text: return code == XmlTypeCode.Text;
case XPathNodeType.SignificantWhitespace: return code == XmlTypeCode.Text;
case XPathNodeType.Whitespace: return code == XmlTypeCode.Text;
case XPathNodeType.ProcessingInstruction: return code == XmlTypeCode.ProcessingInstruction;
case XPathNodeType.Comment: return code == XmlTypeCode.Comment;
}
break;
}
Debug.Fail("XmlTypeCode " + code + " was not fully handled.");
return false;
}
/// <summary>
/// Create an XmlQueryType that represents the type of "item".
/// </summary>
private XmlQueryType CreateXmlType(XPathItem item) {
if (item.IsNode) {
// Rtf
RtfNavigator rtf = item as RtfNavigator;
if (rtf != null)
return XmlQueryTypeFactory.Node;
// Node
XPathNavigator nav = (XPathNavigator) item;
switch (nav.NodeType) {
case XPathNodeType.Root:
case XPathNodeType.Element:
if (nav.XmlType == null)
return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), XmlSchemaComplexType.UntypedAnyType, false);
return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), nav.XmlType, nav.SchemaInfo.SchemaElement.IsNillable);
case XPathNodeType.Attribute:
if (nav.XmlType == null)
return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), DatatypeImplementation.UntypedAtomicType, false);
return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), nav.XmlType, false);
}
return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.Wildcard, XmlSchemaComplexType.AnyType, false);
}
// Atomic value
return XmlQueryTypeFactory.Type((XmlSchemaSimpleType)item.XmlType, true);
}
//-----------------------------------------------
// Xml collations
//-----------------------------------------------
/// <summary>
/// Get a collation that was statically created.
/// </summary>
public XmlCollation GetCollation(int index) {
Debug.Assert(this.collations != null);
return this.collations[index];
}
/// <summary>
/// Create a collation from a string.
/// </summary>
public XmlCollation CreateCollation(string collation) {
return XmlCollation.Create(collation);
}
//-----------------------------------------------
// Document Ordering and Identity
//-----------------------------------------------
/// <summary>
/// Compare the relative positions of two navigators. Return -1 if navThis is before navThat, 1 if after, and
/// 0 if they are positioned to the same node.
/// </summary>
public int ComparePosition(XPathNavigator navigatorThis, XPathNavigator navigatorThat) {
return this.docOrderCmp.Compare(navigatorThis, navigatorThat);
}
/// <summary>
/// Get a comparer which guarantees a stable ordering among nodes, even those from different documents.
/// </summary>
public IList<XPathNavigator> DocOrderDistinct(IList<XPathNavigator> seq) {
if (seq.Count <= 1)
return seq;
XmlQueryNodeSequence nodeSeq = (XmlQueryNodeSequence) seq;
if (nodeSeq == null)
nodeSeq = new XmlQueryNodeSequence(seq);
return nodeSeq.DocOrderDistinct(this.docOrderCmp);
}
/// <summary>
/// Generate a unique string identifier for the specified node. Do this by asking the navigator for an identifier
/// that is unique within the document, and then prepend a document index.
/// </summary>
public string GenerateId(XPathNavigator navigator) {
return string.Concat("ID", this.docOrderCmp.GetDocumentIndex(navigator).ToString(CultureInfo.InvariantCulture), navigator.UniqueId);
}
//-----------------------------------------------
// Indexes
//-----------------------------------------------
/// <summary>
/// If an index having the specified Id has already been created over the "context" document, then return it
/// in "index" and return true. Otherwise, create a new, empty index and return false.
/// </summary>
public bool FindIndex(XPathNavigator context, int indexId, out XmlILIndex index) {
XPathNavigator navRoot;
ArrayList docIndexes;
Debug.Assert(context != null);
// Get root of document
navRoot = context.Clone();
navRoot.MoveToRoot();
// Search pre-existing indexes in order to determine whether the specified index has already been created
if (this.indexes != null && indexId < this.indexes.Length) {
docIndexes = (ArrayList) this.indexes[indexId];
if (docIndexes != null) {
// Search for an index defined over the specified document
for (int i = 0; i < docIndexes.Count; i += 2) {
// If we find a matching document, then return the index saved in the next slot
if (((XPathNavigator) docIndexes[i]).IsSamePosition(navRoot)) {
index = (XmlILIndex) docIndexes[i + 1];
return true;
}
}
}
}
// Return a new, empty index
index = new XmlILIndex();
return false;
}
/// <summary>
/// Add a newly built index over the specified "context" document to the existing collection of indexes.
/// </summary>
public void AddNewIndex(XPathNavigator context, int indexId, XmlILIndex index) {
XPathNavigator navRoot;
ArrayList docIndexes;
Debug.Assert(context != null);
// Get root of document
navRoot = context.Clone();
navRoot.MoveToRoot();
// Ensure that a slot exists for the new index
if (this.indexes == null) {
this.indexes = new ArrayList[indexId + 4];
}
else if (indexId >= this.indexes.Length) {
// Resize array
ArrayList[] indexesNew = new ArrayList[indexId + 4];
Array.Copy(this.indexes, 0, indexesNew, 0, this.indexes.Length);
this.indexes = indexesNew;
}
docIndexes = (ArrayList) this.indexes[indexId];
if (docIndexes == null) {
docIndexes = new ArrayList();
this.indexes[indexId] = docIndexes;
}
docIndexes.Add(navRoot);
docIndexes.Add(index);
}
//-----------------------------------------------
// Output construction
//-----------------------------------------------
/// <summary>
/// Get output writer object.
/// </summary>
public XmlQueryOutput Output {
get { return this.output; }
}
/// <summary>
/// Start construction of a nested sequence of items. Return a new XmlQueryOutput that will be
/// used to construct this new sequence.
/// </summary>
public void StartSequenceConstruction(out XmlQueryOutput output) {
// Push current writer
this.stkOutput.Push(this.output);
// Create new writers
output = this.output = new XmlQueryOutput(this, new XmlCachedSequenceWriter());
}
/// <summary>
/// End construction of a nested sequence of items and return the items as an IList<XPathItem>
/// internal class. Return previous XmlQueryOutput.
/// </summary>
public IList<XPathItem> EndSequenceConstruction(out XmlQueryOutput output) {
IList<XPathItem> seq = ((XmlCachedSequenceWriter) this.output.SequenceWriter).ResultSequence;
// Restore previous XmlQueryOutput
output = this.output = this.stkOutput.Pop();
return seq;
}
/// <summary>
/// Start construction of an Rtf. Return a new XmlQueryOutput object that will be used to construct this Rtf.
/// </summary>
public void StartRtfConstruction(string baseUri, out XmlQueryOutput output) {
// Push current writer
this.stkOutput.Push(this.output);
// Create new XmlQueryOutput over an Rtf writer
output = this.output = new XmlQueryOutput(this, new XmlEventCache(baseUri, true));
}
/// <summary>
/// End construction of an Rtf and return it as an RtfNavigator. Return previous XmlQueryOutput object.
/// </summary>
public XPathNavigator EndRtfConstruction(out XmlQueryOutput output) {
XmlEventCache events;
events = (XmlEventCache) this.output.Writer;
// Restore previous XmlQueryOutput
output = this.output = this.stkOutput.Pop();
// Return Rtf as an RtfNavigator
events.EndEvents();
return new RtfTreeNavigator(events, this.nameTableQuery);
}
/// <summary>
/// Construct a new RtfTextNavigator from the specified "text". This is much more efficient than calling
/// StartNodeConstruction(), StartRtf(), WriteString(), EndRtf(), and EndNodeConstruction().
/// </summary>
public XPathNavigator TextRtfConstruction(string text, string baseUri) {
return new RtfTextNavigator(text, baseUri);
}
//-----------------------------------------------
// Miscellaneous
//-----------------------------------------------
/// <summary>
/// Report query execution information to event handler.
/// </summary>
public void SendMessage(string message) {
this.ctxt.OnXsltMessageEncountered(message);
}
/// <summary>
/// Throw an Xml exception having the specified message text.
/// </summary>
public void ThrowException(string text) {
throw new XslTransformException(text);
}
/// <summary>
/// Position navThis to the same location as navThat.
/// </summary>
internal static XPathNavigator SyncToNavigator(XPathNavigator navigatorThis, XPathNavigator navigatorThat) {
if (navigatorThis == null || !navigatorThis.MoveTo(navigatorThat))
return navigatorThat.Clone();
return navigatorThis;
}
/// <summary>
/// Function is called in Debug mode on each time context node change.
/// </summary>
public static int OnCurrentNodeChanged(XPathNavigator currentNode) {
IXmlLineInfo lineInfo = currentNode as IXmlLineInfo;
// In case of a namespace node, check whether it is inherited or locally defined
if (lineInfo != null && ! (currentNode.NodeType == XPathNodeType.Namespace && IsInheritedNamespace(currentNode))) {
OnCurrentNodeChanged2(currentNode.BaseURI, lineInfo.LineNumber, lineInfo.LinePosition);
}
return 0;
}
// 'true' if current Namespace "inherited" from it's parent. Not defined localy.
private static bool IsInheritedNamespace(XPathNavigator node) {
Debug.Assert(node.NodeType == XPathNodeType.Namespace);
XPathNavigator nav = node.Clone();
if (nav.MoveToParent()) {
if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local)) {
do {
if ((object)nav.LocalName == (object)node.LocalName) {
return false;
}
} while (nav.MoveToNextNamespace(XPathNamespaceScope.Local));
}
}
return true;
}
private static void OnCurrentNodeChanged2(string baseUri, int lineNumber, int linePosition) {}
}
}
| |
//----------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace Microsoft.IdentityModel.Clients.ActiveDirectory
{
internal class MexPolicy
{
public string Id { get; set; }
public UserAuthType AuthType { get; set; }
public Uri Url { get; set; }
}
internal class MexParser
{
private const string WsTrustSoapTransport = "http://schemas.xmlsoap.org/soap/http";
public static async Task<Uri> FetchWsTrustAddressFromMexAsync(string federationMetadataUrl, UserAuthType userAuthType, CallState callState)
{
XDocument mexDocument = await FetchMexAsync(federationMetadataUrl, callState);
return ExtractWsTrustAddressFromMex(mexDocument, userAuthType, callState);
}
internal static async Task<XDocument> FetchMexAsync(string federationMetadataUrl, CallState callState)
{
XDocument mexDocument;
try
{
IHttpWebRequest request = PlatformPlugin.HttpWebRequestFactory.Create(federationMetadataUrl);
request.Method = "GET";
using (var response = await request.GetResponseSyncOrAsync(callState))
{
mexDocument = XDocument.Load(response.GetResponseStream(), LoadOptions.None);
}
}
catch (WebException ex)
{
var serviceEx = new AdalServiceException(AdalError.AccessingWsMetadataExchangeFailed, ex);
PlatformPlugin.Logger.LogException(callState, serviceEx);
throw serviceEx;
}
catch (XmlException ex)
{
var adalEx = new AdalException(AdalError.ParsingWsMetadataExchangeFailed, ex);
PlatformPlugin.Logger.LogException(callState, adalEx);
throw adalEx;
}
return mexDocument;
}
internal static Uri ExtractWsTrustAddressFromMex(XDocument mexDocument, UserAuthType userAuthType, CallState callState)
{
Uri url;
try
{
Dictionary<string, MexPolicy> policies = ReadPolicies(mexDocument);
Dictionary<string, MexPolicy> bindings = ReadPolicyBindings(mexDocument, policies);
SetPolicyEndpointAddresses(mexDocument, bindings);
Random random = new Random();
MexPolicy policy = policies.Values.Where(p => p.Url != null && p.AuthType == userAuthType).OrderBy(p => random.Next()).FirstOrDefault();
if (policy != null)
{
url = policy.Url;
}
else if (userAuthType == UserAuthType.IntegratedAuth)
{
var ex = new AdalException(AdalError.IntegratedAuthFailed, new AdalException(AdalError.WsTrustEndpointNotFoundInMetadataDocument));
PlatformPlugin.Logger.LogException(callState, ex);
throw ex;
}
else
{
var ex = new AdalException(AdalError.WsTrustEndpointNotFoundInMetadataDocument);
PlatformPlugin.Logger.LogException(callState, ex);
throw ex;
}
}
catch (XmlException ex)
{
var adalEx = new AdalException(AdalError.ParsingWsMetadataExchangeFailed, ex);
PlatformPlugin.Logger.LogException(callState, adalEx);
throw adalEx;
}
return url;
}
private static Dictionary<string, MexPolicy> ReadPolicies(XContainer mexDocument)
{
var policies = new Dictionary<string, MexPolicy>();
IEnumerable<XElement> policyElements = mexDocument.Elements().First().Elements(XmlNamespace.Wsp + "Policy");
foreach (XElement policy in policyElements)
{
XElement exactlyOnePolicy = policy.Elements(XmlNamespace.Wsp + "ExactlyOne").FirstOrDefault();
if (exactlyOnePolicy == null)
{
continue;
}
IEnumerable<XElement> all = exactlyOnePolicy.Descendants(XmlNamespace.Wsp + "All");
foreach (XElement element in all)
{
XElement auth = element.Elements(XmlNamespace.Http + "NegotiateAuthentication").FirstOrDefault();
if (auth != null)
{
AddPolicy(policies, policy, UserAuthType.IntegratedAuth);
}
auth = element.Elements(XmlNamespace.Sp + "SignedEncryptedSupportingTokens").FirstOrDefault();
if (auth == null)
{
continue;
}
XElement wspPolicy = auth.Elements(XmlNamespace.Wsp + "Policy").FirstOrDefault();
if (wspPolicy == null)
{
continue;
}
XElement usernameToken = wspPolicy.Elements(XmlNamespace.Sp + "UsernameToken").FirstOrDefault();
if (usernameToken == null)
{
continue;
}
XElement wspPolicy2 = usernameToken.Elements(XmlNamespace.Wsp + "Policy").FirstOrDefault();
if (wspPolicy2 == null)
{
continue;
}
XElement wssUsernameToken10 = wspPolicy2.Elements(XmlNamespace.Sp + "WssUsernameToken10").FirstOrDefault();
if (wssUsernameToken10 != null)
{
AddPolicy(policies, policy, UserAuthType.UsernamePassword);
}
}
}
return policies;
}
private static Dictionary<string, MexPolicy> ReadPolicyBindings(XContainer mexDocument, IReadOnlyDictionary<string, MexPolicy> policies)
{
var bindings = new Dictionary<string, MexPolicy>();
IEnumerable<XElement> bindingElements = mexDocument.Elements().First().Elements(XmlNamespace.Wsdl + "binding");
foreach (XElement binding in bindingElements)
{
IEnumerable<XElement> policyReferences = binding.Elements(XmlNamespace.Wsp + "PolicyReference");
foreach (XElement policyReference in policyReferences)
{
XAttribute policyUri = policyReference.Attribute("URI");
if (policyUri == null || !policies.ContainsKey(policyUri.Value))
{
continue;
}
XAttribute bindingName = binding.Attribute("name");
if (bindingName == null)
{
continue;
}
XElement bindingOperation = binding.Elements(XmlNamespace.Wsdl + "operation").FirstOrDefault();
if (bindingOperation == null)
{
continue;
}
XElement soapOperation = bindingOperation.Elements(XmlNamespace.Soap12 + "operation").FirstOrDefault();
if (soapOperation == null)
{
continue;
}
XAttribute soapAction = soapOperation.Attribute("soapAction");
if (soapAction == null || string.Compare(XmlNamespace.Issue.ToString(), soapAction.Value, StringComparison.OrdinalIgnoreCase) != 0)
{
continue;
}
XElement soapBinding = binding.Elements(XmlNamespace.Soap12 + "binding").FirstOrDefault();
if (soapBinding == null)
{
continue;
}
XAttribute soapBindingTransport = soapBinding.Attribute("transport");
if (soapBindingTransport != null && string.Compare(WsTrustSoapTransport, soapBindingTransport.Value, StringComparison.OrdinalIgnoreCase) == 0)
{
bindings.Add(bindingName.Value, policies[policyUri.Value]);
}
}
}
return bindings;
}
private static void SetPolicyEndpointAddresses(XContainer mexDocument, IReadOnlyDictionary<string, MexPolicy> bindings)
{
XElement serviceElement = mexDocument.Elements().First().Elements(XmlNamespace.Wsdl + "service").First();
IEnumerable<XElement> portElements = serviceElement.Elements(XmlNamespace.Wsdl + "port");
foreach (XElement port in portElements)
{
XAttribute portBinding = port.Attribute("binding");
if (portBinding == null)
{
continue;
}
string portBindingName = portBinding.Value;
string[] portBindingNameSegments = portBindingName.Split(new[] { ':' }, 2);
if (portBindingNameSegments.Length < 2 || !bindings.ContainsKey(portBindingNameSegments[1]))
{
continue;
}
XElement endpointReference = port.Elements(XmlNamespace.Wsa10 + "EndpointReference").FirstOrDefault();
if (endpointReference == null)
{
continue;
}
XElement endpointAddress = endpointReference.Elements(XmlNamespace.Wsa10 + "Address").FirstOrDefault();
if (endpointAddress != null && Uri.IsWellFormedUriString(endpointAddress.Value, UriKind.Absolute))
{
bindings[portBindingNameSegments[1]].Url = new Uri(endpointAddress.Value);
}
}
}
private static void AddPolicy(IDictionary<string, MexPolicy> policies, XElement policy, UserAuthType policyAuthType)
{
XElement binding = policy.Descendants(XmlNamespace.Sp + "TransportBinding").FirstOrDefault()
?? policy.Descendants(XmlNamespace.Sp2005 + "TransportBinding").FirstOrDefault();
if (binding != null)
{
XAttribute id = policy.Attribute(XmlNamespace.Wsu + "Id");
if (id != null)
{
policies.Add("#" + id.Value, new MexPolicy { Id = id.Value, AuthType = policyAuthType });
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using BTDB.FieldHandler;
using BTDB.IL;
using BTDB.KVDBLayer;
using BTDB.StreamLayer;
// ReSharper disable ParameterOnlyUsedForPreconditionCheck.Local
namespace BTDB.ODBLayer
{
public class RelationBuilder
{
readonly Type _relationDbManipulatorType;
readonly string _name;
public readonly Type InterfaceType;
public readonly Type ItemType;
public readonly object PristineItemInstance;
public readonly RelationVersionInfo ClientRelationVersionInfo;
public readonly List<Type> LoadTypes = new List<Type>();
public readonly IRelationInfoResolver RelationInfoResolver;
public IILDynamicMethodWithThis DelegateCreator { get; }
static readonly MethodInfo SpanWriterGetSpanMethodInfo =
typeof(SpanWriter).GetMethod(nameof(SpanWriter.GetSpan))!;
static readonly MethodInfo SpanWriterGetPersistentSpanAndResetMethodInfo =
typeof(SpanWriter).GetMethod(nameof(SpanWriter.GetPersistentSpanAndReset))!;
static Dictionary<Type, RelationBuilder> _relationBuilderCache = new Dictionary<Type, RelationBuilder>();
static readonly object RelationBuilderCacheLock = new object();
internal static void Reset()
{
_relationBuilderCache = new Dictionary<Type, RelationBuilder>();
}
internal static RelationBuilder GetFromCache(Type interfaceType, IRelationInfoResolver relationInfoResolver)
{
if (_relationBuilderCache.TryGetValue(interfaceType, out var res))
{
return res;
}
lock (RelationBuilderCacheLock)
{
if (_relationBuilderCache.TryGetValue(interfaceType, out res))
{
return res;
}
_relationBuilderCache = new Dictionary<Type, RelationBuilder>(_relationBuilderCache)
{
{ interfaceType, res = new RelationBuilder(interfaceType, relationInfoResolver) }
};
}
return res;
}
public RelationBuilder(Type interfaceType, IRelationInfoResolver relationInfoResolver)
{
RelationInfoResolver = relationInfoResolver;
InterfaceType = interfaceType;
ItemType = interfaceType.SpecializationOf(typeof(ICovariantRelation<>))!.GenericTypeArguments[0];
PristineItemInstance = CreatePristineInstance();
_name = InterfaceType.ToSimpleName();
ClientRelationVersionInfo = CreateVersionInfoByReflection();
_relationDbManipulatorType = typeof(RelationDBManipulator<>).MakeGenericType(ItemType);
LoadTypes.Add(ItemType);
DelegateCreator = Build();
}
object CreatePristineInstance()
{
var container = RelationInfoResolver.Container;
var res = container?.ResolveOptional(ItemType);
return (res ?? Activator.CreateInstance(ItemType, nonPublic: true))!;
}
RelationVersionInfo CreateVersionInfoByReflection()
{
var props = ItemType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var primaryKeys = new Dictionary<uint, TableFieldInfo>(1); //PK order->fieldInfo
var secondaryKeyFields = new List<TableFieldInfo>();
var secondaryKeys = new List<Tuple<int, IList<SecondaryKeyAttribute>>>(); //positive: sec key field idx, negative: pk order, attrs
var publicFields = ItemType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (var field in publicFields)
{
if (field.GetCustomAttribute<NotStoredAttribute>(true) != null) continue;
throw new BTDBException($"Public field {_name}.{field.Name} must have NotStoredAttribute. It is just intermittent, until they can start to be supported.");
}
var fields = new List<TableFieldInfo>(props.Length);
foreach (var pi in props)
{
if (pi.GetCustomAttribute<NotStoredAttribute>(true) != null) continue;
if (pi.GetIndexParameters().Length != 0) continue;
var pks = pi.GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
PrimaryKeyAttribute actualPKAttribute = null;
if (pks.Length != 0)
{
actualPKAttribute = (PrimaryKeyAttribute)pks[0];
var fieldInfo = TableFieldInfo.Build(_name, pi, RelationInfoResolver.FieldHandlerFactory,
FieldHandlerOptions.Orderable);
if (fieldInfo.Handler!.NeedsCtx())
throw new BTDBException($"Unsupported key field {fieldInfo.Name} type.");
primaryKeys.Add(actualPKAttribute.Order, fieldInfo);
}
var sks = pi.GetCustomAttributes(typeof(SecondaryKeyAttribute), true);
var id = (int)(-actualPKAttribute?.Order ?? secondaryKeyFields.Count);
List<SecondaryKeyAttribute> currentList = null;
for (var i = 0; i < sks.Length; i++)
{
if (i == 0)
{
currentList = new List<SecondaryKeyAttribute>(sks.Length);
secondaryKeys.Add(new Tuple<int, IList<SecondaryKeyAttribute>>(id, currentList));
if (actualPKAttribute == null)
secondaryKeyFields.Add(TableFieldInfo.Build(_name, pi,
RelationInfoResolver.FieldHandlerFactory, FieldHandlerOptions.Orderable));
}
var key = (SecondaryKeyAttribute)sks[i];
if (key.Name == "Id")
throw new BTDBException(
"'Id' is invalid name for secondary key, it is reserved for primary key identification.");
currentList!.Add(key);
}
if (actualPKAttribute == null)
fields.Add(TableFieldInfo.Build(_name, pi, RelationInfoResolver.FieldHandlerFactory,
FieldHandlerOptions.None));
}
return new RelationVersionInfo(primaryKeys, secondaryKeys, secondaryKeyFields.ToArray(), fields.ToArray());
}
int RegisterLoadType(Type itemType)
{
for (var i = 0; i < LoadTypes.Count; i++)
{
if (LoadTypes[i] == itemType)
{
return i;
}
}
LoadTypes.Add(itemType);
return LoadTypes.Count - 1;
}
IILDynamicMethodWithThis Build()
{
var interfaceType = InterfaceType;
var relationName = interfaceType!.ToSimpleName();
var classImpl = ILBuilder.Instance.NewType("Relation" + relationName, _relationDbManipulatorType,
new[] { interfaceType });
var constructorMethod =
classImpl.DefineConstructor(new[] { typeof(IObjectDBTransaction), typeof(RelationInfo) });
var il = constructorMethod.Generator;
// super.ctor(transaction, relationInfo);
il.Ldarg(0).Ldarg(1).Ldarg(2)
.Call(_relationDbManipulatorType.GetConstructor(new[]
{typeof(IObjectDBTransaction), typeof(RelationInfo)})!)
.Ret();
var methods = RelationInfo.GetMethods(interfaceType);
foreach (var method in methods)
{
if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
continue;
var reqMethod = classImpl.DefineMethod("_R_" + method.Name, method.ReturnType,
method.GetParameters().Select(pi => pi.ParameterType).ToArray(),
MethodAttributes.Virtual | MethodAttributes.Public);
reqMethod.InitLocals = false;
if (method.Name.StartsWith("RemoveBy") || method.Name.StartsWith("ShallowRemoveBy"))
{
var methodParameters = method.GetParameters();
if (method.Name == "RemoveByIdPartial")
BuildRemoveByIdPartialMethod(method, methodParameters, reqMethod);
else
{
if (StripVariant(SubstringAfterBy(method.Name), false) == "Id")
{
if (ParametersEndsWithAdvancedEnumeratorParam(methodParameters))
BuildRemoveByIdAdvancedParamMethod(method, methodParameters, reqMethod);
else
BuildRemoveByMethod(method, methodParameters, reqMethod);
}
else
{
throw new BTDBException($"Remove by secondary key in {_name}.{method.Name} is unsupported. Instead use ListBy and remove enumerated.");
}
}
}
else if (method.Name.StartsWith("FindBy"))
{
BuildFindByMethod(method, reqMethod);
}
else if (method.Name == "Contains")
{
BuildContainsMethod(method, reqMethod);
}
else if (method.Name == "CountById") //count by primary key
{
BuildCountByIdMethod(method, reqMethod);
}
else if (method.Name == "AnyById") //any by primary key
{
BuildAnyByIdMethod(method, reqMethod);
}
else if (method.Name.StartsWith("ListBy", StringComparison.Ordinal)
) //ListBy{Name}(tenantId, .., AdvancedEnumeratorParam)
{
if (StripVariant(method.Name.Substring(6), false) == "Id")
{
// List by primary key
BuildListByIdMethod(method, reqMethod);
}
else
{
BuildListByMethod(method, reqMethod);
}
}
else if (method.Name.StartsWith("CountBy", StringComparison.Ordinal)
) //CountBy{Name}(tenantId, ..[, AdvancedEnumeratorParam])
{
BuildCountByMethod(method, reqMethod);
}
else if (method.Name.StartsWith("AnyBy", StringComparison.Ordinal)
) //AnyBy{Name}(tenantId, ..[, AdvancedEnumeratorParam])
{
BuildAnyByMethod(method, reqMethod);
}
else if (method.Name == "Insert")
{
BuildInsertMethod(method, reqMethod);
}
else
{
BuildManipulatorCallWithSameParameters(method, reqMethod);
}
reqMethod.Generator.Ret();
classImpl.DefineMethodOverride(reqMethod, method);
}
var classImplType = classImpl.CreateType();
var methodBuilder = ILBuilder.Instance.NewMethod("RelationFactory" + relationName,
typeof(Func<IObjectDBTransaction, IRelation>), typeof(RelationInfo));
var ilGenerator = methodBuilder.Generator;
ilGenerator
.Ldarg(1)
.Ldarg(0)
.Newobj(classImplType.GetConstructor(new[] { typeof(IObjectDBTransaction), typeof(RelationInfo) })!)
.Castclass(typeof(IRelation))
.Ret();
return methodBuilder;
}
static string SubstringAfterBy(string name)
{
var byIndex = name.IndexOf("By", StringComparison.Ordinal);
return name.Substring(byIndex + 2);
}
static bool ParametersEndsWithAdvancedEnumeratorParam(ParameterInfo[] methodParameters)
{
return methodParameters.Length > 0 && methodParameters[^1].ParameterType
.InheritsOrImplements(typeof(AdvancedEnumeratorParam<>));
}
void BuildContainsMethod(MethodInfo method, IILMethod reqMethod)
{
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
WriteRelationPKPrefix(reqMethod.Generator, pushWriter);
var primaryKeyFields = ClientRelationVersionInfo.PrimaryKeyFields;
var count = SaveMethodParameters(reqMethod.Generator, "Contains", method.GetParameters(), primaryKeyFields.Span, pushWriter, ctxLocFactory);
if (count != primaryKeyFields.Length)
throw new BTDBException(
$"Number of parameters in Contains does not match primary key count {primaryKeyFields.Length}.");
var localSpan = reqMethod.Generator.DeclareLocal(typeof(ReadOnlySpan<byte>));
//call manipulator.Contains
reqMethod.Generator
.Ldarg(0) //manipulator
.Do(pushWriter)
.Call(SpanWriterGetSpanMethodInfo)
.Stloc(localSpan)
.Ldloca(localSpan)
.Callvirt(_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>.Contains))!);
}
void BuildFindByMethod(MethodInfo method, IILMethod reqMethod)
{
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
var nameWithoutVariants = StripVariant(method.Name.Substring(6), true);
if (nameWithoutVariants == "Id" || nameWithoutVariants == "IdOrDefault")
{
CreateMethodFindById(reqMethod.Generator, method.Name,
method.GetParameters(), method.ReturnType, pushWriter, ctxLocFactory);
}
else
{
CreateMethodFindBy(reqMethod.Generator, method.Name, method.GetParameters(),
method.ReturnType, pushWriter, ctxLocFactory);
}
}
void BuildRemoveByMethod(MethodInfo method, ParameterInfo[] methodParameters, IILMethod reqMethod)
{
var isPrefixBased = method.ReturnType == typeof(int); //returns number of removed items
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
WriteRelationPKPrefix(reqMethod.Generator, pushWriter);
var primaryKeyFields = ClientRelationVersionInfo.PrimaryKeyFields;
var count = SaveMethodParameters(reqMethod.Generator, method.Name, methodParameters, primaryKeyFields.Span, pushWriter, ctxLocFactory);
if (!isPrefixBased && count != primaryKeyFields.Length)
throw new BTDBException(
$"Number of parameters in {method.Name} does not match primary key count {primaryKeyFields.Length}.");
//call manipulator.RemoveBy_
reqMethod.Generator
.Ldarg(0); //manipulator
var localSpan = reqMethod.Generator.DeclareLocal(typeof(ReadOnlySpan<byte>));
reqMethod.Generator
.Do(pushWriter)
.Call(SpanWriterGetSpanMethodInfo)
.Stloc(localSpan)
.Ldloca(localSpan);
if (isPrefixBased)
{
reqMethod.Generator.Callvirt(
(AllKeyPrefixesAreSame(ClientRelationVersionInfo, count)
? _relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>
.RemoveByKeyPrefixWithoutIterate))
: _relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>
.RemoveByPrimaryKeyPrefix))!)!);
}
else
{
reqMethod.Generator.LdcI4(ShouldThrowWhenKeyNotFound(method.Name, method.ReturnType) ? 1 : 0);
reqMethod.Generator.Callvirt(_relationDbManipulatorType.GetMethod(method.Name)!);
if (method.ReturnType == typeof(void))
reqMethod.Generator.Pop();
}
}
void BuildRemoveByIdAdvancedParamMethod(MethodInfo method, ParameterInfo[] parameters, IILMethod reqMethod)
{
if (method.ReturnType != typeof(int))
throw new BTDBException($"Return value in {method.Name} must be int.");
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
var advEnumParamOrder = (ushort)parameters.Length;
var advEnumParam = parameters[advEnumParamOrder - 1].ParameterType;
var advEnumParamType = advEnumParam.GenericTypeArguments[0];
var prefixParamCount = parameters.Length - 1;
var primaryKeyFields = ClientRelationVersionInfo.PrimaryKeyFields.Span;
var field = primaryKeyFields[prefixParamCount];
if (parameters.Length != primaryKeyFields.Length)
ForbidExcludePropositionInDebug(reqMethod.Generator, advEnumParamOrder, advEnumParam);
ValidateAdvancedEnumParameter(field, advEnumParamType, method.Name);
reqMethod.Generator.Ldarg(0); //manipulator for call RemoveByIdAdvancedParam
WritePrimaryKeyPrefixFinishedByAdvancedEnumerator(method, parameters, reqMethod, prefixParamCount,
advEnumParamOrder, advEnumParam, field, pushWriter, ctxLocFactory);
reqMethod.Generator.Call(
_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>
.RemoveByIdAdvancedParam))!);
}
void WritePrimaryKeyPrefixFinishedByAdvancedEnumerator(MethodInfo method,
ReadOnlySpan<ParameterInfo> parameters,
IILMethod reqMethod, int prefixParamCount, ushort advEnumParamOrder, Type advEnumParam,
TableFieldInfo field, Action<IILGen> pushWriter, Func<IILLocal> ctxLocFactory)
{
reqMethod.Generator
.LdcI4(prefixParamCount)
.Ldarg(advEnumParamOrder).Ldfld(advEnumParam.GetField(nameof(AdvancedEnumeratorParam<int>.Order))!);
KeyPropositionStartBefore(advEnumParamOrder, reqMethod.Generator, advEnumParam);
SerializePKListPrefixBytes(reqMethod.Generator, method.Name,
parameters[..^1], pushWriter, ctxLocFactory);
KeyPropositionStartAfter(advEnumParamOrder, reqMethod.Generator, advEnumParam, field, pushWriter);
var label = KeyPropositionEndBefore(advEnumParamOrder, reqMethod.Generator, advEnumParam);
SerializePKListPrefixBytes(reqMethod.Generator, method.Name,
parameters[..^1], pushWriter, ctxLocFactory);
KeyPropositionEndAfter(advEnumParamOrder, reqMethod.Generator, advEnumParam, field, pushWriter, label);
}
void WritePrimaryKeyPrefixFinishedByAdvancedEnumeratorWithoutOrder(MethodInfo method,
ReadOnlySpan<ParameterInfo> parameters,
IILMethod reqMethod, ushort advEnumParamOrder, Type advEnumParam, TableFieldInfo field)
{
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
reqMethod.Generator.Ldarg(0);
KeyPropositionStartBefore(advEnumParamOrder, reqMethod.Generator, advEnumParam);
SerializePKListPrefixBytes(reqMethod.Generator, method.Name,
parameters[..^1], pushWriter, ctxLocFactory);
KeyPropositionStartAfter(advEnumParamOrder, reqMethod.Generator, advEnumParam, field, pushWriter);
var label = KeyPropositionEndBefore(advEnumParamOrder, reqMethod.Generator, advEnumParam);
SerializePKListPrefixBytes(reqMethod.Generator, method.Name,
parameters[..^1], pushWriter, ctxLocFactory);
KeyPropositionEndAfter(advEnumParamOrder, reqMethod.Generator, advEnumParam, field, pushWriter, label);
}
void BuildRemoveByIdPartialMethod(MethodInfo method, ParameterInfo[] methodParameters, IILMethod reqMethod)
{
var isPrefixBased = method.ReturnType == typeof(int); //returns number of removed items
if (!isPrefixBased || methodParameters.Length == 0 ||
methodParameters[^1].ParameterType != typeof(int) ||
methodParameters[^1].Name!
.IndexOf("max", StringComparison.InvariantCultureIgnoreCase) == -1)
{
throw new BTDBException("Invalid shape of RemoveByIdPartial.");
}
var il = reqMethod.Generator;
var (pushWriter, ctxLocFactory) = WriterPushers(il);
WriteRelationPKPrefix(il, pushWriter);
var primaryKeyFields = ClientRelationVersionInfo.PrimaryKeyFields.Span;
SaveMethodParameters(il, method.Name, methodParameters[..^1], primaryKeyFields, pushWriter, ctxLocFactory);
var localSpan = il.DeclareLocal(typeof(ReadOnlySpan<byte>));
il
.Ldarg(0) //manipulator
.Do(pushWriter)
.Call(SpanWriterGetSpanMethodInfo)
.Stloc(localSpan)
.Ldloca(localSpan)
.Ldarg((ushort)methodParameters.Length)
.Callvirt(_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>
.RemoveByPrimaryKeyPrefixPartial))!);
}
static bool AllKeyPrefixesAreSame(RelationVersionInfo relationInfo, ushort count)
{
foreach (var sk in relationInfo.SecondaryKeys)
{
var skFields = sk.Value;
var idx = 0;
foreach (var field in skFields.Fields)
{
if (!field.IsFromPrimaryKey)
return false;
if (field.Index != idx)
return false;
if (++idx == count)
break;
}
}
return true;
}
void BuildListByIdMethod(MethodInfo method, IILMethod reqMethod)
{
var parameters = method.GetParameters();
if (ParametersEndsWithAdvancedEnumeratorParam(parameters))
{
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
var advEnumParamOrder = (ushort)parameters.Length;
var advEnumParam = parameters[advEnumParamOrder - 1].ParameterType;
var advEnumParamType = advEnumParam.GenericTypeArguments[0];
var prefixParamCount = parameters.Length - 1;
var primaryKeyFields = ClientRelationVersionInfo.PrimaryKeyFields.Span;
var field = primaryKeyFields[prefixParamCount];
if (parameters.Length != primaryKeyFields.Length)
ForbidExcludePropositionInDebug(reqMethod.Generator, advEnumParamOrder, advEnumParam);
ValidateAdvancedEnumParameter(field, advEnumParamType, method.Name);
reqMethod.Generator.Ldarg(0).Castclass(typeof(IRelationDbManipulator));
WritePrimaryKeyPrefixFinishedByAdvancedEnumerator(method, parameters, reqMethod, prefixParamCount,
advEnumParamOrder, advEnumParam, field, pushWriter, ctxLocFactory);
if (ReturnTypeIsEnumeratorOrEnumerable(method, out var itemType))
{
//return new RelationAdvancedEnumerator<T>(relationManipulator,
// prefixBytes, prefixFieldCount,
// order,
// startKeyProposition, startKeyBytes,
// endKeyProposition, endKeyBytes, loaderIndex);
var enumType = typeof(RelationAdvancedEnumerator<>).MakeGenericType(itemType);
var advancedEnumeratorCtor =
enumType.GetConstructors().Single(ci => ci.GetParameters().Length == 9);
reqMethod.Generator
.LdcI4(RegisterLoadType(itemType))
.Newobj(advancedEnumeratorCtor);
}
else if (ReturnTypeIsIOrderedDictionaryEnumerator(method, advEnumParamType, out itemType))
{
reqMethod.Generator
.LdcI4(1); //init key reader
//return new RelationAdvancedOrderedEnumerator<T>(relationManipulator,
// prefixBytes, prefixFieldCount,
// order,
// startKeyProposition, startKeyBytes,
// endKeyProposition, endKeyBytes, initKeyReader, loaderIndex);
var enumType =
typeof(RelationAdvancedOrderedEnumerator<,>).MakeGenericType(advEnumParamType,
itemType);
var advancedEnumeratorCtor =
enumType.GetConstructors().Single(ci => ci.GetParameters().Length == 10);
reqMethod.Generator
.LdcI4(RegisterLoadType(itemType))
.Newobj(advancedEnumeratorCtor);
}
else
{
throw new BTDBException("Invalid method " + method.Name);
}
}
else
{
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
reqMethod.Generator.Ldarg(0).Castclass(typeof(IRelationDbManipulator));
SavePKListPrefixBytes(reqMethod.Generator, method.Name, parameters, pushWriter, ctxLocFactory);
reqMethod.Generator.LdcI4(parameters.Length);
if (ReturnTypeIsEnumeratorOrEnumerable(method, out var itemType))
{
//return new RelationAdvancedEnumerator<T>(relationManipulator,
// prefixBytes, prefixFieldCount, loaderIndex);
var enumType = typeof(RelationAdvancedEnumerator<>).MakeGenericType(itemType);
var advancedEnumeratorCtor =
enumType.GetConstructors().Single(ci => ci.GetParameters().Length == 4);
reqMethod.Generator
.LdcI4(RegisterLoadType(itemType))
.Newobj(advancedEnumeratorCtor);
}
else
{
throw new BTDBException("Invalid method " + method.Name);
}
}
}
static bool TypeIsEnumeratorOrEnumerable(Type type, [NotNullWhen(true)] out Type? itemType)
{
itemType = type.SpecializationOf(typeof(IEnumerator<>)) ??
type.SpecializationOf(typeof(IEnumerable<>));
if (itemType != null)
{
itemType = itemType.GenericTypeArguments[0];
}
return itemType != null;
}
static bool ReturnTypeIsEnumeratorOrEnumerable(MethodInfo method, [NotNullWhen(true)] out Type? itemType)
{
return TypeIsEnumeratorOrEnumerable(method.ReturnType, out itemType);
}
static bool ReturnTypeIsIOrderedDictionaryEnumerator(MethodInfo method, Type advEnumParamType,
[NotNullWhen(true)] out Type? itemType)
{
itemType = method.ReturnType.SpecializationOf(typeof(IOrderedDictionaryEnumerator<,>));
if (itemType != null)
{
var ta = itemType.GenericTypeArguments;
if (ta[0] != advEnumParamType)
{
itemType = null;
return false;
}
itemType = ta[1];
return true;
}
return false;
}
void BuildCountByIdMethod(MethodInfo method, IILMethod reqMethod)
{
var parameters = method.GetParameters();
var resultConversion = CheckLongLikeResult(method);
if (ParametersEndsWithAdvancedEnumeratorParam(parameters))
{
PrepareAnyCountByIdWithAep(method, reqMethod, parameters);
//return relationManipulator.CountWithProposition(prefixBytes,
// startKeyProposition, startKeyBytes, endKeyProposition, endKeyBytes);
var calcCountMethod =
_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>.CountWithProposition));
reqMethod.Generator.Call(calcCountMethod!);
}
else
{
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
reqMethod.Generator.Ldarg(0);
SavePKListPrefixBytes(reqMethod.Generator, method.Name, parameters, pushWriter, ctxLocFactory);
//return relationManipulator.CountWithPrefix(prefixBytes);
var calcCountMethod =
_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>.CountWithPrefix));
reqMethod.Generator.Call(calcCountMethod!);
}
resultConversion(reqMethod.Generator);
}
void BuildAnyByIdMethod(MethodInfo method, IILMethod reqMethod)
{
var parameters = method.GetParameters();
CheckReturnType(method.Name, typeof(bool), method.ReturnType);
if (ParametersEndsWithAdvancedEnumeratorParam(parameters))
{
PrepareAnyCountByIdWithAep(method, reqMethod, parameters);
//return relationManipulator.AnyWithProposition(prefixBytes,
// startKeyProposition, startKeyBytes, endKeyProposition, endKeyBytes);
var calcCountMethod =
_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>.AnyWithProposition));
reqMethod.Generator.Call(calcCountMethod!);
}
else
{
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
reqMethod.Generator.Ldarg(0);
SavePKListPrefixBytes(reqMethod.Generator, method.Name, parameters, pushWriter, ctxLocFactory);
//return relationManipulator.AnyWithPrefix(prefixBytes);
var calcCountMethod =
_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>.AnyWithPrefix));
reqMethod.Generator.Call(calcCountMethod!);
}
}
void PrepareAnyCountByIdWithAep(MethodInfo method, IILMethod reqMethod, ParameterInfo[] parameters)
{
var advEnumParamOrder = (ushort)parameters.Length;
var advEnumParam = parameters[advEnumParamOrder - 1].ParameterType;
var advEnumParamType = advEnumParam.GenericTypeArguments[0];
var prefixParamCount = parameters.Length - 1;
var primaryKeyFields = ClientRelationVersionInfo.PrimaryKeyFields.Span;
var field = primaryKeyFields[prefixParamCount];
if (parameters.Length != primaryKeyFields.Length)
ForbidExcludePropositionInDebug(reqMethod.Generator, advEnumParamOrder, advEnumParam);
ValidateAdvancedEnumParameter(field, advEnumParamType, method.Name);
WritePrimaryKeyPrefixFinishedByAdvancedEnumeratorWithoutOrder(method, parameters, reqMethod,
advEnumParamOrder, advEnumParam, field);
}
void BuildListByMethod(MethodInfo method, IILMethod reqMethod)
{
var parameters = method.GetParameters();
if (ParametersEndsWithAdvancedEnumeratorParam(parameters))
{
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
var advEnumParamOrder = (ushort)parameters.Length;
var advEnumParam = parameters[advEnumParamOrder - 1].ParameterType;
var advEnumParamType = advEnumParam.GenericTypeArguments[0];
var secondaryKeyIndex =
ClientRelationVersionInfo.GetSecondaryKeyIndex(
StripVariant(method.Name.Substring(6), false));
var prefixParamCount = parameters.Length - 1;
var skFields = ClientRelationVersionInfo.GetSecondaryKeyFields(secondaryKeyIndex);
var field = skFields[prefixParamCount];
if (parameters.Length != skFields.Length)
ForbidExcludePropositionInDebug(reqMethod.Generator, advEnumParamOrder, advEnumParam);
ValidateAdvancedEnumParameter(field, advEnumParamType, method.Name);
reqMethod.Generator
.Ldarg(0).Castclass(typeof(IRelationDbManipulator));
reqMethod.Generator
.LdcI4(prefixParamCount)
.Ldarg(advEnumParamOrder).Ldfld(advEnumParam.GetField(nameof(AdvancedEnumeratorParam<int>.Order))!);
var localRemapped = RemapSecondaryKeyIndex(reqMethod.Generator, secondaryKeyIndex);
KeyPropositionStartBefore(advEnumParamOrder, reqMethod.Generator, advEnumParam);
SerializeListPrefixBytes(secondaryKeyIndex, reqMethod.Generator, method.Name,
parameters[..^1], pushWriter, ctxLocFactory, localRemapped);
KeyPropositionStartAfter(advEnumParamOrder, reqMethod.Generator, advEnumParam, field, pushWriter);
var label = KeyPropositionEndBefore(advEnumParamOrder, reqMethod.Generator, advEnumParam);
SerializeListPrefixBytes(secondaryKeyIndex, reqMethod.Generator, method.Name,
parameters[..^1], pushWriter, ctxLocFactory, localRemapped);
KeyPropositionEndAfter(advEnumParamOrder, reqMethod.Generator, advEnumParam, field, pushWriter, label);
reqMethod.Generator
.Ldloc(localRemapped);
if (ReturnTypeIsEnumeratorOrEnumerable(method, out var itemType))
{
//return new RelationAdvancedSecondaryKeyEnumerator<T>(relationManipulator,
// prefixLen, prefixFieldCount,
// order,
// startKeyProposition, startKeyBytes,
// endKeyProposition, endKeyBytes, secondaryKeyIndex, loaderIndex);
var enumType =
typeof(RelationAdvancedSecondaryKeyEnumerator<>).MakeGenericType(itemType);
var advancedEnumeratorCtor =
enumType.GetConstructors().Single(ci => ci.GetParameters().Length == 10);
reqMethod.Generator
.LdcI4(RegisterLoadType(itemType))
.Newobj(advancedEnumeratorCtor);
}
else if (ReturnTypeIsIOrderedDictionaryEnumerator(method, advEnumParamType, out itemType))
{
//return new RelationAdvancedOrderedSecondaryKeyEnumerator<T>(relationManipulator,
// prefixLen, prefixFieldCount,
// order,
// startKeyProposition, startKeyBytes,
// endKeyProposition, endKeyBytes, secondaryKeyIndex, loaderIndex);
var enumType =
typeof(RelationAdvancedOrderedSecondaryKeyEnumerator<,>).MakeGenericType(advEnumParamType,
itemType);
var advancedEnumeratorCtor = enumType.GetConstructors()[0];
reqMethod.Generator
.LdcI4(RegisterLoadType(itemType))
.Newobj(advancedEnumeratorCtor);
}
else
{
throw new BTDBException("Invalid method " + method.Name);
}
}
else
{
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
var secondaryKeyIndex =
ClientRelationVersionInfo.GetSecondaryKeyIndex(
StripVariant(method.Name.Substring(6), false));
reqMethod.Generator
.Ldarg(0).Castclass(typeof(IRelationDbManipulator));
var localRemapped = SaveListPrefixBytes(secondaryKeyIndex, reqMethod.Generator, method.Name,
parameters, pushWriter, ctxLocFactory);
reqMethod.Generator
.LdcI4(parameters.Length)
.Ldloc(localRemapped);
if (ReturnTypeIsEnumeratorOrEnumerable(method, out var itemType))
{
//return new RelationAdvancedSecondaryKeyEnumerator<T>(relationManipulator,
// prefixBytes, prefixFieldCount, secondaryKeyIndex, loaderIndex);
var enumType =
typeof(RelationAdvancedSecondaryKeyEnumerator<>).MakeGenericType(itemType);
var advancedEnumeratorCtor =
enumType.GetConstructors().Single(ci => ci.GetParameters().Length == 5);
reqMethod.Generator
.LdcI4(RegisterLoadType(itemType))
.Newobj(advancedEnumeratorCtor);
}
else
{
throw new BTDBException("Invalid method " + method.Name);
}
}
}
[Conditional("DEBUG")]
void ForbidExcludePropositionInDebug(IILGen ilGenerator, ushort advEnumParamOrder, Type advEnumParamType)
{
var propositionCheckFinished = ilGenerator.DefineLabel();
ilGenerator
.LdcI4((int) KeyProposition.Excluded)
.Ldarg(advEnumParamOrder)
.Ldfld(advEnumParamType.GetField(nameof(AdvancedEnumeratorParam<int>.StartProposition))!)
.Ceq()
.Brfalse(propositionCheckFinished)
.Ldstr("Not supported Excluded proposition when listing by partial key.")
.Newobj(() => new InvalidOperationException(null))
.Throw()
.Mark(propositionCheckFinished);
}
void BuildCountByMethod(MethodInfo method, IILMethod reqMethod)
{
var parameters = method.GetParameters();
var secondaryKeyIndex =
ClientRelationVersionInfo.GetSecondaryKeyIndex(method.Name.Substring(7));
var resultConversion = CheckLongLikeResult(method);
if (ParametersEndsWithAdvancedEnumeratorParam(parameters))
{
PrepareAnyCountByWithAep(method, reqMethod, parameters, secondaryKeyIndex);
//return relationManipulator.CountWithProposition(prefixBytes,
// startKeyProposition, startKeyBytes, endKeyProposition, endKeyBytes);
var calcCountMethod =
_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>.CountWithProposition));
reqMethod.Generator.Call(calcCountMethod!);
}
else
{
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
reqMethod.Generator
.Ldarg(0);
var _ = SaveListPrefixBytes(secondaryKeyIndex, reqMethod.Generator, method.Name,
parameters, pushWriter, ctxLocFactory);
//return relationManipulator.CountWithPrefix(prefixBytes);
var calcCountMethod =
_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>.CountWithPrefix));
reqMethod.Generator.Call(calcCountMethod!);
}
resultConversion(reqMethod.Generator);
}
void BuildAnyByMethod(MethodInfo method, IILMethod reqMethod)
{
var parameters = method.GetParameters();
var secondaryKeyIndex =
ClientRelationVersionInfo.GetSecondaryKeyIndex(method.Name.Substring(5));
CheckReturnType(method.Name, typeof(bool), method.ReturnType);
if (ParametersEndsWithAdvancedEnumeratorParam(parameters))
{
PrepareAnyCountByWithAep(method, reqMethod, parameters, secondaryKeyIndex);
//return relationManipulator.AnyWithProposition(prefixBytes,
// startKeyProposition, startKeyBytes, endKeyProposition, endKeyBytes);
var calcAnyMethod =
_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>.AnyWithProposition));
reqMethod.Generator.Call(calcAnyMethod!);
}
else
{
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
reqMethod.Generator
.Ldarg(0);
var _ = SaveListPrefixBytes(secondaryKeyIndex, reqMethod.Generator, method.Name,
parameters, pushWriter, ctxLocFactory);
//return relationManipulator.AnyWithPrefix(prefixBytes);
var calcAnyMethod =
_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>.AnyWithPrefix));
reqMethod.Generator.Call(calcAnyMethod!);
}
}
void PrepareAnyCountByWithAep(MethodInfo method, IILMethod reqMethod, ParameterInfo[] parameters,
uint secondaryKeyIndex)
{
var advEnumParamOrder = (ushort)parameters.Length;
var advEnumParam = parameters[advEnumParamOrder - 1].ParameterType;
var advEnumParamType = advEnumParam.GenericTypeArguments[0];
var prefixParamCount = parameters.Length - 1;
var skFields = ClientRelationVersionInfo.GetSecondaryKeyFields(secondaryKeyIndex);
var field = skFields[prefixParamCount];
if (parameters.Length != skFields.Length)
ForbidExcludePropositionInDebug(reqMethod.Generator, advEnumParamOrder, advEnumParam);
ValidateAdvancedEnumParameter(field, advEnumParamType, method.Name);
var (pushWriter, ctxLocFactory) = WriterPushers(reqMethod.Generator);
var localRemapped = RemapSecondaryKeyIndex(reqMethod.Generator, secondaryKeyIndex);
reqMethod.Generator
.Ldarg(0);
KeyPropositionStartBefore(advEnumParamOrder, reqMethod.Generator, advEnumParam);
SerializeListPrefixBytes(secondaryKeyIndex, reqMethod.Generator, method.Name,
parameters[..^1], pushWriter, ctxLocFactory, localRemapped);
KeyPropositionStartAfter(advEnumParamOrder, reqMethod.Generator, advEnumParam, field, pushWriter);
var label = KeyPropositionEndBefore(advEnumParamOrder, reqMethod.Generator, advEnumParam);
SerializeListPrefixBytes(secondaryKeyIndex, reqMethod.Generator, method.Name,
parameters[..^1], pushWriter, ctxLocFactory, localRemapped);
KeyPropositionEndAfter(advEnumParamOrder, reqMethod.Generator, advEnumParam, field, pushWriter, label);
}
static Action<IILGen> CheckLongLikeResult(MethodInfo method)
{
var resultConversion =
DefaultTypeConvertorGenerator.Instance.GenerateConversion(typeof(long), method.ReturnType);
if (resultConversion == null)
{
throw new BTDBException("Invalid return type in method " + method.Name);
}
return resultConversion;
}
static void ValidateAdvancedEnumParameter(TableFieldInfo field, Type advEnumParamType, string methodName)
{
if (!field.Handler!.IsCompatibleWith(advEnumParamType, FieldHandlerOptions.Orderable))
{
throw new BTDBException(
$"Parameter type mismatch in {methodName} (expected '{field.Handler.HandledType().ToSimpleName()}' but '{advEnumParamType.ToSimpleName()}' found).");
}
}
void BuildInsertMethod(MethodInfo method, IILMethod reqMethod)
{
var methodInfo = _relationDbManipulatorType.GetMethod(method.Name);
bool returningBoolVariant;
var returnType = method.ReturnType;
if (returnType == typeof(void))
returningBoolVariant = false;
else if (returnType == typeof(bool))
returningBoolVariant = true;
else
throw new BTDBException("Method Insert should be defined with void or bool return type.");
var methodParams = method.GetParameters();
CheckParameterCount(method.Name, 1, methodParams.Length);
CheckParameterType(method.Name, 0, methodInfo!.GetParameters()[0].ParameterType,
methodParams[0].ParameterType);
reqMethod.Generator
.Ldarg(0) //this
.Ldarg(1)
.Callvirt(methodInfo);
if (!returningBoolVariant)
{
var returnedTrueLabel = reqMethod.Generator.DefineLabel("returnedTrueLabel");
reqMethod.Generator
.Brtrue(returnedTrueLabel)
.Ldstr("Trying to insert duplicate key.")
.Newobj(() => new BTDBException(null))
.Throw()
.Mark(returnedTrueLabel);
}
}
void BuildManipulatorCallWithSameParameters(MethodInfo method, IILMethod reqMethod)
{
var methodParams = method.GetParameters();
var paramCount = methodParams.Length;
var methodInfo = _relationDbManipulatorType.GetMethod(method.Name);
if (methodInfo == null)
throw new BTDBException($"Method {method} is not supported.");
CheckReturnType(method.Name, methodInfo.ReturnType, method.ReturnType);
var calledMethodParams = methodInfo.GetParameters();
CheckParameterCount(method.Name, calledMethodParams.Length, methodParams.Length);
for (var i = 0; i < methodParams.Length; i++)
{
CheckParameterType(method.Name, i, calledMethodParams[i].ParameterType, methodParams[i].ParameterType);
}
for (ushort i = 0; i <= paramCount; i++)
reqMethod.Generator.Ldarg(i);
reqMethod.Generator.Callvirt(methodInfo);
}
static void CheckParameterType(string name, int parIdx, Type expectedType, Type actualType)
{
if (expectedType != actualType)
throw new BTDBException($"Method {name} expects {parIdx}th parameter of type {expectedType.Name}.");
}
static void CheckParameterCount(string name, int expectedParameterCount, int actualParameterCount)
{
if (expectedParameterCount != actualParameterCount)
throw new BTDBException($"Method {name} expects {expectedParameterCount} parameters count.");
}
static void CheckReturnType(string name, Type expectedReturnType, Type returnType)
{
if (returnType != expectedReturnType)
throw new BTDBException($"Method {name} should be defined with {expectedReturnType.Name} return type.");
}
void CreateMethodFindById(IILGen ilGenerator, string methodName,
ParameterInfo[] methodParameters, Type methodReturnType,
Action<IILGen> pushWriter, Func<IILLocal> ctxLocFactory)
{
var spanLocal = ilGenerator.DeclareLocal(typeof(ReadOnlySpan<byte>));
var isPrefixBased = TypeIsEnumeratorOrEnumerable(methodReturnType, out var itemType);
WriteRelationPKPrefix(ilGenerator, pushWriter);
var primaryKeyFields = ClientRelationVersionInfo.PrimaryKeyFields;
var count = SaveMethodParameters(ilGenerator, methodName, methodParameters, primaryKeyFields.Span, pushWriter, ctxLocFactory);
if (!isPrefixBased && count != primaryKeyFields.Length)
throw new BTDBException(
$"Number of parameters in {methodName} does not match primary key count {primaryKeyFields.Length}.");
//call manipulator.FindBy_
ilGenerator
.Ldarg(0) //manipulator
.Do(pushWriter)
.Call(SpanWriterGetSpanMethodInfo)
.Stloc(spanLocal)
.Ldloca(spanLocal);
if (isPrefixBased)
{
ilGenerator.LdcI4(RegisterLoadType(itemType));
ilGenerator.Callvirt(
_relationDbManipulatorType.GetMethod(
nameof(RelationDBManipulator<IRelation>.FindByPrimaryKeyPrefix))!.MakeGenericMethod(itemType));
ilGenerator.Castclass(methodReturnType);
}
else
{
itemType = methodReturnType == typeof(void) ? ItemType : methodReturnType;
ilGenerator.LdcI4(ShouldThrowWhenKeyNotFound(methodName, methodReturnType) ? 1 : 0);
ilGenerator.LdcI4(RegisterLoadType(itemType));
ilGenerator.Callvirt(
_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>.FindByIdOrDefault))!
.MakeGenericMethod(itemType));
if (methodReturnType == typeof(void))
ilGenerator.Pop();
}
}
void CreateMethodFindBy(IILGen ilGenerator, string methodName,
ParameterInfo[] methodParameters, Type methodReturnType,
Action<IILGen> pushWriter, Func<IILLocal> ctxLocFactory)
{
var allowDefault = false;
var skName = StripVariant(methodName.Substring(6), true);
if (skName.EndsWith("OrDefault"))
{
skName = skName.Substring(0, skName.Length - 9);
allowDefault = true;
}
var skIndex = ClientRelationVersionInfo.GetSecondaryKeyIndex(skName);
var localRemapped = RemapSecondaryKeyIndex(ilGenerator, skIndex);
WriteRelationSKPrefix(ilGenerator, pushWriter, localRemapped);
var secondaryKeyFields = ClientRelationVersionInfo.GetSecondaryKeyFields(skIndex);
SaveMethodParameters(ilGenerator, methodName, methodParameters, secondaryKeyFields, pushWriter, ctxLocFactory);
var localSpan = ilGenerator.DeclareLocal(typeof(ReadOnlySpan<byte>));
//call public T FindBySecondaryKeyOrDefault<T>(uint secondaryKeyIndex, uint prefixParametersCount, ByteBuffer secKeyBytes, bool throwWhenNotFound, int loaderIndex)
ilGenerator
.Ldarg(0) //manipulator
.Ldloc(localRemapped)
.LdcI4(methodParameters.Length)
.Do(pushWriter)
.Call(SpanWriterGetSpanMethodInfo)
.Stloc(localSpan)
.Ldloca(localSpan);
if (TypeIsEnumeratorOrEnumerable(methodReturnType, out var itemType))
{
ilGenerator.LdcI4(RegisterLoadType(itemType));
ilGenerator.Callvirt(
_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>.FindBySecondaryKey))!
.MakeGenericMethod(itemType));
ilGenerator.Castclass(methodReturnType);
}
else
{
ilGenerator.LdcI4(allowDefault ? 0 : 1); //? should throw
ilGenerator.LdcI4(RegisterLoadType(methodReturnType));
ilGenerator.Callvirt(
_relationDbManipulatorType.GetMethod(nameof(RelationDBManipulator<IRelation>
.FindBySecondaryKeyOrDefault))!.MakeGenericMethod(
methodReturnType));
}
}
string StripVariant(string name, bool withOrDefault)
{
var result = "";
void Check(string id)
{
if (!name.StartsWith(id)) return;
if (withOrDefault)
{
if (name.Substring(id.Length).StartsWith("OrDefault"))
{
if (result.Length < id.Length + 9)
{
result = id + "OrDefault";
}
}
}
if (result.Length < id.Length)
{
result = id;
}
}
Check("Id");
foreach (var secondaryKeyName in ClientRelationVersionInfo.SecondaryKeys.Values.Select(s =>
s.Name))
{
Check(secondaryKeyName);
}
return result.Length == 0 ? name : result;
}
static ushort SaveMethodParameters(IILGen ilGenerator, string methodName,
ReadOnlySpan<ParameterInfo> methodParameters,
ReadOnlySpan<TableFieldInfo> fields, Action<IILGen> pushWriter, Func<IILLocal> ctxLocFactory)
{
var idx = 0;
foreach (var field in fields)
{
if (idx == methodParameters.Length)
{
break;
}
var par = methodParameters[idx++];
if (string.Compare(field.Name, par.Name!.ToLower(), StringComparison.OrdinalIgnoreCase) != 0)
{
throw new BTDBException($"Parameter and key mismatch in {methodName}, {field.Name}!={par.Name}.");
}
if (!field.Handler!.IsCompatibleWith(par.ParameterType, FieldHandlerOptions.Orderable))
{
throw new BTDBException(
$"Parameter type mismatch in {methodName} (expected '{field.Handler.HandledType().ToSimpleName()}' but '{par.ParameterType.ToSimpleName()}' found).");
}
SaveKeyFieldFromArgument(ilGenerator, field, idx, par.ParameterType, pushWriter, ctxLocFactory);
}
return (ushort)idx;
}
bool ShouldThrowWhenKeyNotFound(string methodName, Type methodReturnType)
{
if (methodName.StartsWith("RemoveBy") || methodName.StartsWith("ShallowRemoveBy"))
return methodReturnType == typeof(void);
if (StripVariant(methodName.Substring(6), true) == "IdOrDefault")
return false;
return true;
}
static void KeyPropositionStartBefore(ushort advEnumParamOrder, IILGen ilGenerator, Type advEnumParamType)
{
ilGenerator
.Ldarg(advEnumParamOrder)
.Ldfld(advEnumParamType.GetField(nameof(AdvancedEnumeratorParam<int>.StartProposition))!);
}
static void KeyPropositionStartAfter(ushort advEnumParamOrder, IILGen ilGenerator, Type advEnumParamType, TableFieldInfo field, Action<IILGen> pushWriter)
{
var instField = advEnumParamType.GetField(nameof(AdvancedEnumeratorParam<int>.Start));
var ignoreLabel = ilGenerator.DefineLabel("start_ignore");
var localSpan = ilGenerator.DeclareLocal(typeof(ReadOnlySpan<byte>));
ilGenerator
.Do(pushWriter)
.Call(typeof(SpanWriter).GetMethod(nameof(SpanWriter.GetCurrentPosition))!)
.ConvI4()
.Ldarg(advEnumParamOrder)
.Ldfld(advEnumParamType.GetField(nameof(AdvancedEnumeratorParam<int>.StartProposition))!)
.LdcI4((int)KeyProposition.Ignored)
.BeqS(ignoreLabel);
field.Handler!.SpecializeSaveForType(instField!.FieldType).Save(ilGenerator,
pushWriter, null,
il => il.Ldarg(advEnumParamOrder).Ldfld(instField));
ilGenerator
.Mark(ignoreLabel)
.Do(pushWriter)
.Call(SpanWriterGetPersistentSpanAndResetMethodInfo)
.Stloc(localSpan)
.Ldloca(localSpan);
}
static IILLabel KeyPropositionEndBefore(ushort advEnumParamOrder, IILGen ilGenerator, Type advEnumParamType)
{
var ignoreLabel = ilGenerator.DefineLabel("end_ignore");
ilGenerator
.Ldarg(advEnumParamOrder)
.Ldfld(advEnumParamType.GetField(nameof(AdvancedEnumeratorParam<int>.EndProposition))!)
.Dup()
.LdcI4((int)KeyProposition.Ignored)
.Beq(ignoreLabel);
return ignoreLabel;
}
static void KeyPropositionEndAfter(ushort advEnumParamOrder, IILGen ilGenerator, Type advEnumParamType, TableFieldInfo field, Action<IILGen> pushWriter, IILLabel ignoreLabel)
{
var instField = advEnumParamType.GetField(nameof(AdvancedEnumeratorParam<int>.End));
var localSpan = ilGenerator.DeclareLocal(typeof(ReadOnlySpan<byte>));
field.Handler!.SpecializeSaveForType(instField!.FieldType).Save(ilGenerator,
pushWriter, null,
il => il.Ldarg(advEnumParamOrder).Ldfld(instField));
ilGenerator
.Mark(ignoreLabel)
.Do(pushWriter)
.Call(SpanWriterGetSpanMethodInfo)
.Stloc(localSpan)
.Ldloca(localSpan);
}
IILLocal SaveListPrefixBytes(uint secondaryKeyIndex, IILGen ilGenerator, string methodName,
ReadOnlySpan<ParameterInfo> methodParameters, Action<IILGen> pushWriter, Func<IILLocal> ctxLocFactory)
{
var localRemapped = RemapSecondaryKeyIndex(ilGenerator, secondaryKeyIndex);
SerializeListPrefixBytes(secondaryKeyIndex, ilGenerator, methodName, methodParameters, pushWriter, ctxLocFactory, localRemapped);
var localSpan = ilGenerator.DeclareLocal(typeof(ReadOnlySpan<byte>));
ilGenerator
.Do(pushWriter)
.Call(SpanWriterGetSpanMethodInfo)
.Stloc(localSpan)
.Ldloca(localSpan);
return localRemapped;
}
void SerializeListPrefixBytes(uint secondaryKeyIndex, IILGen ilGenerator, string methodName,
ReadOnlySpan<ParameterInfo> methodParameters,
Action<IILGen> pushWriter, Func<IILLocal> ctxLocFactory, IILLocal localRemapped)
{
WriteRelationSKPrefix(ilGenerator, pushWriter, localRemapped);
var secondaryKeyFields = ClientRelationVersionInfo.GetSecondaryKeyFields(secondaryKeyIndex);
SaveMethodParameters(ilGenerator, methodName, methodParameters,
secondaryKeyFields, pushWriter, ctxLocFactory);
}
static (Action<IILGen>, Func<IILLocal>) WriterPushers(IILGen ilGenerator)
{
var bufPtrLoc = ilGenerator.DeclareLocal(typeof(byte*));
var writerLoc = ilGenerator.DeclareLocal(typeof(SpanWriter));
ilGenerator
.Localloc(512)
.Stloc(bufPtrLoc)
.Ldloca(writerLoc)
.Ldloc(bufPtrLoc)
.LdcI4(512)
.Call(typeof(SpanWriter).GetConstructor(new [] { typeof(void *), typeof(int) })!);
void PushWriter(IILGen il) => il.Ldloca(writerLoc);
IILLocal? ctxLoc = null;
IILLocal PushCtx()
{
if (ctxLoc == null)
{
ctxLoc = ilGenerator.DeclareLocal(typeof(IDBWriterCtx));
ilGenerator
.Ldarg(0)
.Callvirt(() => ((IRelationDbManipulator)null).Transaction)
.Newobj(() => new DBWriterCtx(null))
.Stloc(ctxLoc);
}
return ctxLoc;
}
return (PushWriter, PushCtx);
}
void SavePKListPrefixBytes(IILGen ilGenerator, string methodName, ReadOnlySpan<ParameterInfo> methodParameters, Action<IILGen> pushWriter, Func<IILLocal> ctxLocFactory)
{
SerializePKListPrefixBytes(ilGenerator, methodName, methodParameters, pushWriter, ctxLocFactory);
var localSpan = ilGenerator.DeclareLocal(typeof(ReadOnlySpan<byte>));
ilGenerator
.Do(pushWriter)
.Call(SpanWriterGetSpanMethodInfo)
.Stloc(localSpan)
.Ldloca(localSpan);
}
void SerializePKListPrefixBytes(IILGen ilGenerator, string methodName, ReadOnlySpan<ParameterInfo> methodParameters, Action<IILGen> pushWriter, Func<IILLocal> ctxLocFactory)
{
WriteRelationPKPrefix(ilGenerator, pushWriter);
var keyFields = ClientRelationVersionInfo.PrimaryKeyFields;
SaveMethodParameters(ilGenerator, methodName, methodParameters,
keyFields.Span, pushWriter, ctxLocFactory);
}
static void SaveKeyFieldFromArgument(IILGen ilGenerator, TableFieldInfo field, int parameterId,
Type parameterType, Action<IILGen> pushWriter, Func<IILLocal> ctxLocFactory)
{
var specialized = field.Handler!.SpecializeSaveForType(parameterType);
specialized
.Save(ilGenerator,
pushWriter, il => il.Ldloc(ctxLocFactory()),
il => il.Ldarg((ushort)parameterId));
}
static void SaveKeyFieldFromApartField(IILGen ilGenerator, TableFieldInfo field, MethodInfo fieldGetter,
Action<IILGen> pushWriter, Func<IILLocal> ctxLocFactory)
{
var specialized = field.Handler!.SpecializeSaveForType(fieldGetter.ReturnType);
specialized.Save(ilGenerator, pushWriter, il => il.Ldloc(ctxLocFactory()),
il => il.Ldarg(0).Callvirt(fieldGetter));
}
void WriteRelationPKPrefix(IILGen ilGenerator, Action<IILGen> pushWriter)
{
ilGenerator
.Ldarg(0)
.Do(pushWriter)
.Call(_relationDbManipulatorType.GetMethod(
nameof(RelationDBManipulator<IRelation>.WriteRelationPKPrefix))!);
}
IILLocal RemapSecondaryKeyIndex(IILGen ilGenerator, uint secondaryKeyIndex)
{
var local = ilGenerator.DeclareLocal(typeof(uint));
ilGenerator
.Ldarg(0)
.LdcI4((int)secondaryKeyIndex)
.Call(_relationDbManipulatorType.GetMethod(
nameof(RelationDBManipulator<IRelation>.RemapPrimeSK))!)
.Stloc(local);
return local;
}
void WriteRelationSKPrefix(IILGen ilGenerator, Action<IILGen> pushWriter, IILLocal localRemapped)
{
ilGenerator
.Ldarg(0)
.Do(pushWriter)
.Ldloc(localRemapped)
.Call(_relationDbManipulatorType.GetMethod(
nameof(RelationDBManipulator<IRelation>.WriteRelationSKPrefix))!);
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Runtime.InteropServices;
namespace SharpDX.DirectInput
{
public partial class EffectParameters
{
/// <summary>
/// Initializes a new instance of the <see cref="EffectParameters"/> class.
/// </summary>
public EffectParameters()
{
unsafe
{
Size = sizeof(__Native);
}
}
/// <summary>
/// Optional Envelope structure that describes the envelope to be used by this effect. Not all effect types use envelope. If no envelope is to be applied, the member should be set to null.
/// </summary>
public Envelope Envelope { get; set; }
/// <summary>
/// Gets or sets an array containing identifiers or offsets identifying the axes to which the effect is to be applied.
/// The flags <see cref="EffectFlags.ObjectIds"/> and <see cref="EffectFlags.ObjectOffsets"/> determine the semantics of the values in the array.
/// The list of axes associated with an effect cannot be changed once it has been set.
/// No more than 32 axes can be associated with a single effect.
/// </summary>
/// <value>The axes.</value>
public int[] Axes { get; set; }
/// <summary>
/// Gets or sets an array containing either Cartesian coordinates, polar coordinates, or spherical coordinates.
/// The flags <see cref="EffectFlags.Cartesian"/>, <see cref="EffectFlags.Polar"/>, and <see cref="EffectFlags.Spherical"/> determine the semantics of the values in the array.
/// If Cartesian, each value in Directions is associated with the corresponding axis in Axes.
/// If polar, the angle is measured in hundredths of degrees from the (0, - 1) direction, rotated in the direction of (1, 0). This usually means that north is away from the user, and east is to the user's right. The last element is not used.
/// If spherical, the first angle is measured in hundredths of a degree from the (1, 0) direction, rotated in the direction of (0, 1). The second angle (if the number of axes is three or more) is measured in hundredths of a degree toward (0, 0, 1). The third angle (if the number of axes is four or more) is measured in hundredths of a degree toward (0, 0, 0, 1), and so on. The last element is not used.
/// </summary>
/// <value>The directions.</value>
public int[] Directions { get; set; }
/// <summary>
/// Gets the axes. See <see cref="Axes"/> and <see cref="Directions"/>.
/// </summary>
/// <param name="axes">The axes.</param>
/// <param name="directions">The directions.</param>
public void GetAxes(out int[] axes, out int[] directions)
{
axes = Axes;
directions = Directions;
}
/// <summary>
/// Sets the axes. See <see cref="Axes"/> and <see cref="Directions"/>.
/// </summary>
/// <param name="axes">The axes.</param>
/// <param name="directions">The directions.</param>
public void SetAxes(int[] axes, int[] directions)
{
Axes = axes;
Directions = directions;
}
/// <summary>
/// Gets or sets the type specific parameter.
/// Reference to a type-specific parameters, or null if there are no type-specific parameters.
/// If the effect is of type <see cref="EffectType.Condition"/>, this member contains an indirect reference to a ConditionSet structures that define the parameters for the condition. A single structure may be used, in which case the condition is applied in the direction specified in the Directions array. Otherwise, there must be one structure for each axis, in the same order as the axes in rgdwAxes array. If a structure is supplied for each axis, the effect should not be rotated; you should use the following values in the Directions array: <see cref="EffectFlags.Spherical"/> : 0, 0, ... / <see cref="EffectFlags.Polar"/>: 9000, 0, ... / <see cref="EffectFlags.Cartesian"/>: 1, 0, ...
/// If the effect is of type <see cref="EffectType.CustomForce"/>, this member contains an indirect reference to a <see cref="CustomForce"/> that defines the parameters for the custom force.
/// If the effect is of type <see cref="EffectType.Periodic"/>, this member contains a pointer to a <see cref="PeriodicForce"/> that defines the parameters for the effect.
/// If the effect is of type <see cref="EffectType.ConstantForce"/>, this member contains a pointer to a <see cref="ConstantForce"/> that defines the parameters for the constant force.
/// If the effect is of type <see cref="EffectType.RampForce"/>, this member contains a pointer to a <see cref="RampForce"/> that defines the parameters for the ramp force.
/// To gain access to the underlying structure, you need to call the method <see cref="TypeSpecificParameters.As{T}"/>.
/// </summary>
/// <value>The type specific parameter.</value>
public TypeSpecificParameters Parameters { get; set; }
internal static __Native __NewNative()
{
unsafe
{
__Native temp = default(__Native);
temp.Size = sizeof(__Native);
return temp;
}
}
// Internal native struct used for marshalling
[StructLayout(LayoutKind.Sequential, Pack = 0)]
internal partial struct __Native
{
public int Size;
public SharpDX.DirectInput.EffectFlags Flags;
public int Duration;
public int SamplePeriod;
public int Gain;
public int TriggerButton;
public int TriggerRepeatInterval;
public int AxeCount;
public System.IntPtr AxePointer;
public System.IntPtr DirectionPointer;
public System.IntPtr EnvelopePointer;
public int TypeSpecificParamCount;
public System.IntPtr TypeSpecificParamPointer;
public int StartDelay;
// Method to free native struct
internal unsafe void __MarshalFree()
{
if (AxePointer != IntPtr.Zero)
Marshal.FreeHGlobal(AxePointer);
if (DirectionPointer != IntPtr.Zero)
Marshal.FreeHGlobal(DirectionPointer);
if (EnvelopePointer != IntPtr.Zero)
Marshal.FreeHGlobal(EnvelopePointer);
//if (TypeSpecificParamPointer != IntPtr.Zero)
// Marshal.FreeHGlobal(TypeSpecificParamPointer);
}
}
// Method to free native struct
internal unsafe void __MarshalFree(ref __Native @ref)
{
if (Parameters != null && @ref.TypeSpecificParamPointer != IntPtr.Zero)
Parameters.MarshalFree(@ref.TypeSpecificParamPointer);
@ref.__MarshalFree();
}
// Method to marshal from native to managed struct
internal unsafe void __MarshalFrom(ref __Native @ref)
{
this.Size = @ref.Size;
this.Flags = @ref.Flags;
this.Duration = @ref.Duration;
this.SamplePeriod = @ref.SamplePeriod;
this.Gain = @ref.Gain;
this.TriggerButton = @ref.TriggerButton;
this.TriggerRepeatInterval = @ref.TriggerRepeatInterval;
this.AxeCount = @ref.AxeCount;
this.StartDelay = @ref.StartDelay;
// Marshal Axes and Directions
if (AxeCount > 0)
{
if (@ref.AxePointer != IntPtr.Zero)
{
Axes = new int[AxeCount];
Marshal.Copy(@ref.AxePointer, Axes, 0, AxeCount);
}
if (@ref.DirectionPointer != IntPtr.Zero)
{
Directions = new int[AxeCount];
Marshal.Copy(@ref.DirectionPointer, Directions, 0, AxeCount);
}
}
// Marshal Envelope
if (@ref.EnvelopePointer != IntPtr.Zero)
{
var envelopeNative = *((Envelope.__Native*) @ref.EnvelopePointer);
Envelope = new Envelope();
Envelope.__MarshalFrom(ref envelopeNative);
}
// Marshal TypeSpecificParameters
if (@ref.TypeSpecificParamCount > 0 && @ref.TypeSpecificParamPointer != IntPtr.Zero)
Parameters = new TypeSpecificParameters(@ref.TypeSpecificParamCount, @ref.TypeSpecificParamPointer);
}
// Method to marshal from managed struct tot native
internal unsafe void __MarshalTo(ref __Native @ref)
{
@ref.Size = this.Size;
@ref.Flags = this.Flags;
@ref.Duration = this.Duration;
@ref.SamplePeriod = this.SamplePeriod;
@ref.Gain = this.Gain;
@ref.TriggerButton = this.TriggerButton;
@ref.TriggerRepeatInterval = this.TriggerRepeatInterval;
@ref.StartDelay = this.StartDelay;
// Marshal Axes and Directions
@ref.AxeCount = 0;
@ref.AxePointer = IntPtr.Zero;
@ref.DirectionPointer = IntPtr.Zero;
if (Axes != null && Axes.Length > 0)
{
@ref.AxeCount = Axes.Length;
@ref.AxePointer = Marshal.AllocHGlobal(Axes.Length * sizeof(int));
Utilities.Write(@ref.AxePointer, Axes, 0, Axes.Length);
if (Directions != null && Directions.Length == Axes.Length)
{
@ref.DirectionPointer = Marshal.AllocHGlobal(Directions.Length * sizeof(int));
Utilities.Write(@ref.DirectionPointer, Directions, 0, Directions.Length);
}
}
// Marshal Envelope
@ref.EnvelopePointer = IntPtr.Zero;
if (Envelope != null)
{
@ref.EnvelopePointer = Marshal.AllocHGlobal(sizeof(Envelope.__Native));
var envelopeNative = SharpDX.DirectInput.Envelope.__NewNative();
Envelope.__MarshalTo(ref envelopeNative);
Utilities.Write(@ref.EnvelopePointer, ref envelopeNative);
}
// Marshal TypeSpecificParameters
@ref.TypeSpecificParamCount = 0;
@ref.TypeSpecificParamPointer = IntPtr.Zero;
if (Parameters != null)
{
@ref.TypeSpecificParamCount = Parameters.Size;
@ref.TypeSpecificParamPointer = Parameters.MarshalTo();
}
}
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, 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.Layouts
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using NLog.Config;
using NLog.Internal;
using NLog.Common;
/// <summary>
/// Abstract interface that layouts must implement.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces", Justification = "Few people will see this conflict.")]
[NLogConfigurationItem]
public abstract class Layout : ISupportsInitialize, IRenderable
{
/// <summary>
/// Is this layout initialized? See <see cref="Initialize(NLog.Config.LoggingConfiguration)"/>
/// </summary>
private bool _isInitialized;
private bool _scannedForObjects;
/// <summary>
/// Gets a value indicating whether this layout is thread-agnostic (can be rendered on any thread).
/// </summary>
/// <remarks>
/// Layout is thread-agnostic if it has been marked with [ThreadAgnostic] attribute and all its children are
/// like that as well.
///
/// Thread-agnostic layouts only use contents of <see cref="LogEventInfo"/> for its output.
/// </remarks>
internal bool ThreadAgnostic { get; set; }
internal bool ThreadSafe { get; set; }
internal bool MutableUnsafe { get; set; }
/// <summary>
/// Gets the level of stack trace information required for rendering.
/// </summary>
internal StackTraceUsage StackTraceUsage { get; private set; }
private const int MaxInitialRenderBufferLength = 16384;
private int _maxRenderedLength;
/// <summary>
/// Gets the logging configuration this target is part of.
/// </summary>
protected LoggingConfiguration LoggingConfiguration { get; private set; }
/// <summary>
/// Converts a given text to a <see cref="Layout" />.
/// </summary>
/// <param name="text">Text to be converted.</param>
/// <returns><see cref="SimpleLayout"/> object represented by the text.</returns>
public static implicit operator Layout([Localizable(false)] string text)
{
return FromString(text);
}
/// <summary>
/// Implicitly converts the specified string to a <see cref="SimpleLayout"/>.
/// </summary>
/// <param name="layoutText">The layout string.</param>
/// <returns>Instance of <see cref="SimpleLayout"/>.</returns>
public static Layout FromString(string layoutText)
{
return FromString(layoutText, ConfigurationItemFactory.Default);
}
/// <summary>
/// Implicitly converts the specified string to a <see cref="SimpleLayout"/>.
/// </summary>
/// <param name="layoutText">The layout string.</param>
/// <param name="configurationItemFactory">The NLog factories to use when resolving layout renderers.</param>
/// <returns>Instance of <see cref="SimpleLayout"/>.</returns>
public static Layout FromString(string layoutText, ConfigurationItemFactory configurationItemFactory)
{
return new SimpleLayout(layoutText, configurationItemFactory);
}
/// <summary>
/// Precalculates the layout for the specified log event and stores the result
/// in per-log event cache.
///
/// Only if the layout doesn't have [ThreadAgnostic] and doens't contain layouts with [ThreadAgnostic].
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <remarks>
/// Calling this method enables you to store the log event in a buffer
/// and/or potentially evaluate it in another thread even though the
/// layout may contain thread-dependent renderer.
/// </remarks>
public virtual void Precalculate(LogEventInfo logEvent)
{
if (!ThreadAgnostic || MutableUnsafe)
{
Render(logEvent);
}
}
/// <summary>
/// Renders the event info in layout.
/// </summary>
/// <param name="logEvent">The event info.</param>
/// <returns>String representing log event.</returns>
public string Render(LogEventInfo logEvent)
{
if (!_isInitialized)
{
Initialize(LoggingConfiguration);
}
if (!ThreadAgnostic || MutableUnsafe)
{
object cachedValue;
if (logEvent.TryGetCachedLayoutValue(this, out cachedValue))
{
return cachedValue?.ToString() ?? string.Empty;
}
}
string layoutValue = GetFormattedMessage(logEvent) ?? string.Empty;
if (!ThreadAgnostic || MutableUnsafe)
{
// Would be nice to only do this in Precalculate(), but we need to ensure internal cache
// is updated for for custom Layouts that overrides Precalculate (without calling base.Precalculate)
logEvent.AddCachedLayoutValue(this, layoutValue);
}
return layoutValue;
}
internal virtual void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target)
{
Precalculate(logEvent); // Allow custom Layouts to work with OptimizeBufferReuse
}
/// <summary>
/// Optimized version of <see cref="Render(LogEventInfo)"/> for internal Layouts. Works best
/// when override of <see cref="RenderFormattedMessage(LogEventInfo, StringBuilder)"/> is available.
/// </summary>
/// <param name="logEvent">The event info.</param>
/// <param name="target">Appends the string representing log event to target</param>
/// <param name="cacheLayoutResult">Should rendering result be cached on LogEventInfo</param>
internal void RenderAppendBuilder(LogEventInfo logEvent, StringBuilder target, bool cacheLayoutResult = false)
{
if (!_isInitialized)
{
Initialize(LoggingConfiguration);
}
if (!ThreadAgnostic || MutableUnsafe)
{
object cachedValue;
if (logEvent.TryGetCachedLayoutValue(this, out cachedValue))
{
target.Append(cachedValue?.ToString() ?? string.Empty);
return;
}
}
cacheLayoutResult = cacheLayoutResult && !ThreadAgnostic;
using (var localTarget = new AppendBuilderCreator(target, cacheLayoutResult))
{
RenderFormattedMessage(logEvent, localTarget.Builder);
if (cacheLayoutResult)
{
// when needed as it generates garbage
logEvent.AddCachedLayoutValue(this, localTarget.Builder.ToString());
}
}
}
/// <summary>
/// Valid default implementation of <see cref="GetFormattedMessage" />, when having implemented the optimized <see cref="RenderFormattedMessage"/>
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <param name="reusableBuilder">StringBuilder to help minimize allocations [optional].</param>
/// <returns>The rendered layout.</returns>
internal string RenderAllocateBuilder(LogEventInfo logEvent, StringBuilder reusableBuilder = null)
{
int initialLength = _maxRenderedLength;
if (initialLength > MaxInitialRenderBufferLength)
{
initialLength = MaxInitialRenderBufferLength;
}
var sb = reusableBuilder ?? new StringBuilder(initialLength);
RenderFormattedMessage(logEvent, sb);
if (sb.Length > _maxRenderedLength)
{
_maxRenderedLength = sb.Length;
}
return sb.ToString();
}
/// <summary>
/// Renders the layout for the specified logging event by invoking layout renderers.
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <param name="target"><see cref="StringBuilder"/> for the result</param>
protected virtual void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target)
{
target.Append(GetFormattedMessage(logEvent) ?? string.Empty);
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
{
Initialize(configuration);
}
/// <summary>
/// Closes this instance.
/// </summary>
void ISupportsInitialize.Close()
{
Close();
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal void Initialize(LoggingConfiguration configuration)
{
if (!_isInitialized)
{
LoggingConfiguration = configuration;
_isInitialized = true;
_scannedForObjects = false;
InitializeLayout();
if (!_scannedForObjects)
{
InternalLogger.Debug("Initialized Layout done but not scanned for objects");
PerformObjectScanning();
}
}
}
internal void PerformObjectScanning()
{
var objectGraphScannerList = ObjectGraphScanner.FindReachableObjects<object>(true, this);
// determine whether the layout is thread-agnostic
// layout is thread agnostic if it is thread-agnostic and
// all its nested objects are thread-agnostic.
ThreadAgnostic = objectGraphScannerList.All(item => item.GetType().IsDefined(typeof(ThreadAgnosticAttribute), true));
ThreadSafe = objectGraphScannerList.All(item => item.GetType().IsDefined(typeof(ThreadSafeAttribute), true));
MutableUnsafe = objectGraphScannerList.Any(item => item.GetType().IsDefined(typeof(MutableUnsafeAttribute), true));
// determine the max StackTraceUsage, to decide if Logger needs to capture callsite
StackTraceUsage = StackTraceUsage.None; // Incase this Layout should implement IUsesStackTrace
StackTraceUsage = objectGraphScannerList.OfType<IUsesStackTrace>().DefaultIfEmpty().Max(item => item?.StackTraceUsage ?? StackTraceUsage.None);
_scannedForObjects = true;
}
/// <summary>
/// Closes this instance.
/// </summary>
internal void Close()
{
if (_isInitialized)
{
LoggingConfiguration = null;
_isInitialized = false;
CloseLayout();
}
}
/// <summary>
/// Initializes the layout.
/// </summary>
protected virtual void InitializeLayout()
{
PerformObjectScanning();
}
/// <summary>
/// Closes the layout.
/// </summary>
protected virtual void CloseLayout()
{
}
/// <summary>
/// Renders the layout for the specified logging event by invoking layout renderers.
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <returns>The rendered layout.</returns>
protected abstract string GetFormattedMessage(LogEventInfo logEvent);
/// <summary>
/// Register a custom Layout.
/// </summary>
/// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks>
/// <typeparam name="T"> Type of the Layout.</typeparam>
/// <param name="name"> Name of the Layout.</param>
public static void Register<T>(string name)
where T : Layout
{
var layoutRendererType = typeof(T);
Register(name, layoutRendererType);
}
/// <summary>
/// Register a custom Layout.
/// </summary>
/// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks>
/// <param name="layoutType"> Type of the Layout.</param>
/// <param name="name"> Name of the Layout.</param>
public static void Register(string name, Type layoutType)
{
ConfigurationItemFactory.Default.Layouts
.RegisterDefinition(name, layoutType);
}
/// <summary>
/// Optimized version of <see cref="Precalculate(LogEventInfo)"/> for internal Layouts, when
/// override of <see cref="RenderFormattedMessage(LogEventInfo, StringBuilder)"/> is available.
/// </summary>
internal void PrecalculateBuilderInternal(LogEventInfo logEvent, StringBuilder target)
{
if (!ThreadAgnostic || MutableUnsafe)
{
RenderAppendBuilder(logEvent, target, true);
}
}
internal string ToStringWithNestedItems<T>(IList<T> nestedItems, Func<T, string> nextItemToString)
{
if (nestedItems?.Count > 0)
{
var nestedNames = nestedItems.Select(c => nextItemToString(c)).ToArray();
return string.Concat(GetType().Name, "=", string.Join("|", nestedNames));
}
return base.ToString();
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.PythonTools.Analysis.Values;
using Microsoft.PythonTools.Interpreter;
namespace Microsoft.PythonTools.Analysis {
public struct MemberResult {
private readonly string _name;
private string _completion;
private readonly Func<IEnumerable<AnalysisValue>> _vars;
private readonly Func<PythonMemberType> _type;
internal MemberResult(string name, IEnumerable<AnalysisValue> vars) {
_name = _completion = name;
_vars = () => vars ?? Empty;
_type = null;
_type = GetMemberType;
}
public MemberResult(string name, PythonMemberType type) {
_name = _completion = name;
_type = () => type;
_vars = () => Empty;
}
public MemberResult(string name, string completion, IEnumerable<AnalysisValue> vars, PythonMemberType? type) {
_name = name;
_vars = () => vars ?? Empty;
_completion = completion;
if (type != null) {
_type = () => type.Value;
} else {
_type = null;
_type = GetMemberType;
}
}
internal MemberResult(string name, Func<IEnumerable<AnalysisValue>> vars, Func<PythonMemberType> type) {
_name = _completion = name;
Func<IEnumerable<AnalysisValue>> empty = () => Empty;
_vars = vars ?? empty;
_type = type;
}
public MemberResult FilterCompletion(string completion) {
return new MemberResult(Name, completion, Values, MemberType);
}
private static AnalysisValue[] Empty = new AnalysisValue[0];
public string Name {
get { return _name; }
}
public string Completion {
get { return _completion; }
}
public string Documentation {
get {
var docSeen = new HashSet<string>();
var typeSeen = new HashSet<string>();
var docs = new List<string>();
var types = new List<string>();
var doc = new StringBuilder();
foreach (var ns in _vars()) {
var docString = ns.Description ?? string.Empty;
if (docSeen.Add(docString)) {
docs.Add(docString);
}
var typeString = ns.ShortDescription ?? string.Empty;
if (typeSeen.Add(typeString)) {
types.Add(typeString);
}
}
var mt = MemberType;
if (mt == PythonMemberType.Instance || mt == PythonMemberType.Constant) {
switch (mt) {
case PythonMemberType.Instance:
doc.Append("Instance of ");
break;
case PythonMemberType.Constant:
doc.Append("Constant ");
break;
default:
doc.Append("Value of ");
break;
}
if (types.Count == 0) {
doc.AppendLine("unknown type");
} else if (types.Count == 1) {
doc.AppendLine(types[0]);
} else {
var orStr = types.Count == 2 ? " or " : ", or ";
doc.AppendLine(string.Join(", ", types.Take(types.Count - 1)) + orStr + types.Last());
}
doc.AppendLine();
}
foreach (var str in docs.OrderBy(s => s)) {
doc.AppendLine(str);
doc.AppendLine();
}
return Utils.CleanDocumentation(doc.ToString());
}
}
public PythonMemberType MemberType {
get {
return _type();
}
}
private PythonMemberType GetMemberType() {
bool includesNone = false;
PythonMemberType result = PythonMemberType.Unknown;
var allVars = _vars().SelectMany(ns => {
var mmi = ns as MultipleMemberInfo;
if (mmi != null) {
return mmi.Members;
} else {
return Enumerable.Repeat(ns, 1);
}
});
foreach (var ns in allVars) {
if (ns == null) {
Debug.Fail("Unexpected null AnalysisValue");
continue;
}
var nsType = ns.MemberType;
var ci = ns as ConstantInfo;
if (ci != null) {
if (ci.ClassInfo == ci.ProjectState.ClassInfos[BuiltinTypeId.Function]) {
nsType = PythonMemberType.Function;
} else if (ci.ClassInfo == ci.ProjectState.ClassInfos[BuiltinTypeId.Type]) {
nsType = PythonMemberType.Class;
}
}
if (ns.TypeId == BuiltinTypeId.NoneType) {
includesNone = true;
} else if (result == PythonMemberType.Unknown) {
result = nsType;
} else if (result == nsType) {
// No change
} else if (result == PythonMemberType.Constant && nsType == PythonMemberType.Instance) {
// Promote from Constant to Instance
result = PythonMemberType.Instance;
} else {
return PythonMemberType.Multiple;
}
}
if (result == PythonMemberType.Unknown) {
return includesNone ? PythonMemberType.Constant : PythonMemberType.Instance;
}
return result;
}
internal IEnumerable<AnalysisValue> Values {
get {
return _vars();
}
}
/// <summary>
/// Gets the location(s) for the member(s) if they are available.
///
/// New in 1.5.
/// </summary>
public IEnumerable<LocationInfo> Locations {
get {
foreach (var ns in _vars()) {
foreach (var location in ns.Locations) {
yield return location;
}
}
}
}
public override bool Equals(object obj) {
if (!(obj is MemberResult)) {
return false;
}
return Name == ((MemberResult)obj).Name;
}
public static bool operator ==(MemberResult x, MemberResult y) {
return x.Name == y.Name;
}
public static bool operator !=(MemberResult x, MemberResult y) {
return x.Name != y.Name;
}
public override int GetHashCode() {
return Name.GetHashCode();
}
}
}
| |
// Copyright (c) 2007-2014 Joe White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Text;
using DGrok.Framework;
using NUnit.Framework;
using NUnit.Framework.Constraints;
namespace DGrok.Tests
{
[TestFixture]
public class LexerTests
{
private Constraint LexesAs(params string[] expected)
{
return new LexesAsConstraint(expected, delegate(IEnumerable<Token> tokens)
{
return tokens;
});
}
// Baseline tests
[Test]
public void BlankSource()
{
Assert.That("", LexesAs());
}
[Test]
public void OnlyWhitespace()
{
Assert.That(" \r\n ", LexesAs());
}
[Test]
public void TwoTimesSigns()
{
Assert.That("**", LexesAs("TimesSign |*|", "TimesSign |*|"));
}
[Test]
public void LeadingWhitespaceIsIgnored()
{
Assert.That(" \r\n *", LexesAs("TimesSign |*|"));
}
// Comment tests
[Test]
public void SingleLineCommentAtEof()
{
Assert.That("// Foo", LexesAs("SingleLineComment |// Foo|"));
}
[Test]
public void SingleLineCommentFollowedByCrlf()
{
Assert.That("// Foo\r\n", LexesAs("SingleLineComment |// Foo|"));
}
[Test]
public void SingleLineCommentFollowedByLf()
{
Assert.That("// Foo\n", LexesAs("SingleLineComment |// Foo|"));
}
[Test]
public void TwoSingleLineComments()
{
Assert.That("// Foo\r\n// Bar", LexesAs(
"SingleLineComment |// Foo|",
"SingleLineComment |// Bar|"));
}
[Test]
public void CurlyBraceComment()
{
Assert.That("{ Foo }", LexesAs("CurlyBraceComment |{ Foo }|"));
}
[Test]
public void CurlyBraceCommentWithEmbeddedNewline()
{
Assert.That("{ Foo\r\n Bar }", LexesAs("CurlyBraceComment |{ Foo\r\n Bar }|"));
}
[Test]
public void TwoCurlyBraceComments()
{
Assert.That("{Foo}{Bar}", LexesAs(
"CurlyBraceComment |{Foo}|",
"CurlyBraceComment |{Bar}|"));
}
[Test]
public void ParenStarComment()
{
Assert.That("(* Foo *)", LexesAs("ParenStarComment |(* Foo *)|"));
}
[Test]
public void ParenStarCommentWithEmbeddedNewline()
{
Assert.That("(* Foo\r\n Bar *)", LexesAs("ParenStarComment |(* Foo\r\n Bar *)|"));
}
[Test]
public void TwoParenStarComments()
{
Assert.That("(*Foo*)(*Bar*)", LexesAs(
"ParenStarComment |(*Foo*)|",
"ParenStarComment |(*Bar*)|"));
}
// Compiler-directive tests
[Test]
public void CurlyBraceCompilerDirective()
{
Assert.That("{$DEFINE FOO}", LexesAs(
"CompilerDirective |{$DEFINE FOO}|, parsed=|DEFINE FOO|"));
}
[Test]
public void CurlyBraceCompilerDirectiveTrimsTrailing()
{
Assert.That("{$DEFINE FOO }", LexesAs(
"CompilerDirective |{$DEFINE FOO }|, parsed=|DEFINE FOO|"));
}
[Test]
public void ParenStarCompilerDirective()
{
Assert.That("(*$DEFINE FOO*)", LexesAs(
"CompilerDirective |(*$DEFINE FOO*)|, parsed=|DEFINE FOO|"));
}
[Test]
public void ParenStarCompilerDirectiveTrimsTrailing()
{
Assert.That("(*$DEFINE FOO *)", LexesAs(
"CompilerDirective |(*$DEFINE FOO *)|, parsed=|DEFINE FOO|"));
}
// Number tests
[Test]
public void Digit()
{
Assert.That("0", LexesAs("Number |0|"));
}
[Test]
public void Integer()
{
Assert.That("42", LexesAs("Number |42|"));
}
[Test]
public void Float()
{
Assert.That("42.42", LexesAs("Number |42.42|"));
}
[Test]
public void FloatWithNoDigitsAfterDecimalPoint()
{
Assert.That("42.", LexesAs("Number |42.|"));
}
[Test]
public void ScientificNotation()
{
Assert.That("42e42", LexesAs("Number |42e42|"));
}
[Test]
public void ScientificNotationWithCapitalLetter()
{
Assert.That("42E42", LexesAs("Number |42E42|"));
}
[Test]
public void NegativeExponent()
{
Assert.That("42e-42", LexesAs("Number |42e-42|"));
}
[Test]
public void ExplicitlyPositiveExponent()
{
Assert.That("42e+42", LexesAs("Number |42e+42|"));
}
[Test]
public void ExplicitlyPositiveNumberLexesAsUnaryOperator()
{
Assert.That("+42", LexesAs("PlusSign |+|", "Number |42|"));
}
[Test]
public void NegativeNumberLexesAsUnaryOperator()
{
Assert.That("-42", LexesAs("MinusSign |-|", "Number |42|"));
}
[Test]
public void Hex()
{
Assert.That("$2A", LexesAs("Number |$2A|"));
}
// String literal tests
[Test]
public void EmptyString()
{
Assert.That("''", LexesAs("StringLiteral |''|"));
}
[Test]
public void SimpleString()
{
Assert.That("'abc'", LexesAs("StringLiteral |'abc'|"));
}
[Test]
public void StringWithEmbeddedApostrophe()
{
Assert.That("'Bob''s'", LexesAs("StringLiteral |'Bob''s'|"));
}
[Test]
public void Character()
{
Assert.That("#32", LexesAs("StringLiteral |#32|"));
}
[Test]
public void HexCharacter()
{
Assert.That("#$1A", LexesAs("StringLiteral |#$1A|"));
}
[Test]
public void Mixed()
{
Assert.That("'Foo'#13#10'Bar'", LexesAs("StringLiteral |'Foo'#13#10'Bar'|"));
}
[Test]
public void DoubleQuotedCharacter()
{
// This is valid only in asm blocks, but valid nonetheless.
Assert.That("\"'\"", LexesAs("StringLiteral |\"'\"|"));
}
// Identifier tests
[Test]
public void Identifier()
{
Assert.That("Foo", LexesAs("Identifier |Foo|"));
}
[Test]
public void LeadingUnderscore()
{
Assert.That("_Foo", LexesAs("Identifier |_Foo|"));
}
[Test]
public void EmbeddedUnderscore()
{
Assert.That("Foo_Bar", LexesAs("Identifier |Foo_Bar|"));
}
[Test]
public void EmbeddedDigits()
{
Assert.That("Foo42", LexesAs("Identifier |Foo42|"));
}
[Test]
public void AmpersandIdentifier()
{
Assert.That("&Foo", LexesAs("Identifier |&Foo|"));
}
[Test]
public void AmpersandSemikeyword()
{
Assert.That("&Absolute", LexesAs("Identifier |&Absolute|"));
}
[Test]
public void AmpersandKeyword()
{
Assert.That("&And", LexesAs("Identifier |&And|"));
}
// Keyword tests
#region Semikeyword tests
[Test]
public void SemikeywordsAreCaseInsensitive()
{
Assert.That("Absolute", LexesAs("AbsoluteSemikeyword |Absolute|"));
}
[Test]
public void AbsoluteSemikeyword()
{
Assert.That("absolute", LexesAs("AbsoluteSemikeyword |absolute|"));
}
[Test]
public void AbstractSemikeyword()
{
Assert.That("abstract", LexesAs("AbstractSemikeyword |abstract|"));
}
[Test]
public void AssemblerSemikeyword()
{
Assert.That("assembler", LexesAs("AssemblerSemikeyword |assembler|"));
}
[Test]
public void AssemblySemikeyword()
{
Assert.That("assembly", LexesAs("AssemblySemikeyword |assembly|"));
}
[Test]
public void AtSemikeyword()
{
Assert.That("at", LexesAs("AtSemikeyword |at|"));
}
[Test]
public void AutomatedSemikeyword()
{
Assert.That("automated", LexesAs("AutomatedSemikeyword |automated|"));
}
[Test]
public void CdeclSemikeyword()
{
Assert.That("cdecl", LexesAs("CdeclSemikeyword |cdecl|"));
}
[Test]
public void ContainsSemikeyword()
{
Assert.That("contains", LexesAs("ContainsSemikeyword |contains|"));
}
[Test]
public void DefaultSemikeyword()
{
Assert.That("default", LexesAs("DefaultSemikeyword |default|"));
}
[Test]
public void DeprecatedSemikeyword()
{
Assert.That("deprecated", LexesAs("DeprecatedSemikeyword |deprecated|"));
}
[Test]
public void DispIdSemikeyword()
{
Assert.That("dispid", LexesAs("DispIdSemikeyword |dispid|"));
}
[Test]
public void DynamicSemikeyword()
{
Assert.That("dynamic", LexesAs("DynamicSemikeyword |dynamic|"));
}
[Test]
public void ExportSemikeyword()
{
Assert.That("export", LexesAs("ExportSemikeyword |export|"));
}
[Test]
public void ExternalSemikeyword()
{
Assert.That("external", LexesAs("ExternalSemikeyword |external|"));
}
[Test]
public void FarSemikeyword()
{
Assert.That("far", LexesAs("FarSemikeyword |far|"));
}
[Test]
public void FinalSemikeyword()
{
Assert.That("final", LexesAs("FinalSemikeyword |final|"));
}
[Test]
public void ForwardSemikeyword()
{
Assert.That("forward", LexesAs("ForwardSemikeyword |forward|"));
}
[Test]
public void HelperSemikeyword()
{
Assert.That("helper", LexesAs("HelperSemikeyword |helper|"));
}
[Test]
public void ImplementsSemikeyword()
{
Assert.That("implements", LexesAs("ImplementsSemikeyword |implements|"));
}
[Test]
public void IndexSemikeyword()
{
Assert.That("index", LexesAs("IndexSemikeyword |index|"));
}
[Test]
public void LocalSemikeyword()
{
Assert.That("local", LexesAs("LocalSemikeyword |local|"));
}
[Test]
public void MessageSemikeyword()
{
Assert.That("message", LexesAs("MessageSemikeyword |message|"));
}
[Test]
public void NameSemikeyword()
{
Assert.That("name", LexesAs("NameSemikeyword |name|"));
}
[Test]
public void NearSemikeyword()
{
Assert.That("near", LexesAs("NearSemikeyword |near|"));
}
[Test]
public void NoDefaultSemikeyword()
{
Assert.That("nodefault", LexesAs("NoDefaultSemikeyword |nodefault|"));
}
[Test]
public void OnSemikeyword()
{
Assert.That("on", LexesAs("OnSemikeyword |on|"));
}
[Test]
public void OperatorSemikeyword()
{
Assert.That("operator", LexesAs("OperatorSemikeyword |operator|"));
}
[Test]
public void OutSemikeyword()
{
Assert.That("out", LexesAs("OutSemikeyword |out|"));
}
[Test]
public void OverloadSemikeyword()
{
Assert.That("overload", LexesAs("OverloadSemikeyword |overload|"));
}
[Test]
public void OverrideSemikeyword()
{
Assert.That("override", LexesAs("OverrideSemikeyword |override|"));
}
[Test]
public void PackageSemikeyword()
{
Assert.That("package", LexesAs("PackageSemikeyword |package|"));
}
[Test]
public void PascalSemikeyword()
{
Assert.That("pascal", LexesAs("PascalSemikeyword |pascal|"));
}
[Test]
public void PlatformSemikeyword()
{
Assert.That("platform", LexesAs("PlatformSemikeyword |platform|"));
}
[Test]
public void PrivateSemikeyword()
{
Assert.That("private", LexesAs("PrivateSemikeyword |private|"));
}
[Test]
public void ProtectedSemikeyword()
{
Assert.That("protected", LexesAs("ProtectedSemikeyword |protected|"));
}
[Test]
public void PublicSemikeyword()
{
Assert.That("public", LexesAs("PublicSemikeyword |public|"));
}
[Test]
public void PublishedSemikeyword()
{
Assert.That("published", LexesAs("PublishedSemikeyword |published|"));
}
[Test]
public void ReadSemikeyword()
{
Assert.That("read", LexesAs("ReadSemikeyword |read|"));
}
[Test]
public void ReadOnlySemikeyword()
{
Assert.That("readonly", LexesAs("ReadOnlySemikeyword |readonly|"));
}
[Test]
public void RegisterSemikeyword()
{
Assert.That("register", LexesAs("RegisterSemikeyword |register|"));
}
[Test]
public void ReintroduceSemikeyword()
{
Assert.That("reintroduce", LexesAs("ReintroduceSemikeyword |reintroduce|"));
}
[Test]
public void RequiresSemikeyword()
{
Assert.That("requires", LexesAs("RequiresSemikeyword |requires|"));
}
[Test]
public void ResidentSemikeyword()
{
Assert.That("resident", LexesAs("ResidentSemikeyword |resident|"));
}
[Test]
public void SafecallSemikeyword()
{
Assert.That("safecall", LexesAs("SafecallSemikeyword |safecall|"));
}
[Test]
public void SealedSemikeyword()
{
Assert.That("sealed", LexesAs("SealedSemikeyword |sealed|"));
}
[Test]
public void StdcallSemikeyword()
{
Assert.That("stdcall", LexesAs("StdcallSemikeyword |stdcall|"));
}
[Test]
public void StoredSemikeyword()
{
Assert.That("stored", LexesAs("StoredSemikeyword |stored|"));
}
[Test]
public void StrictSemikeyword()
{
Assert.That("strict", LexesAs("StrictSemikeyword |strict|"));
}
[Test]
public void VarArgsSemikeyword()
{
Assert.That("varargs", LexesAs("VarArgsSemikeyword |varargs|"));
}
[Test]
public void VirtualSemikeyword()
{
Assert.That("virtual", LexesAs("VirtualSemikeyword |virtual|"));
}
[Test]
public void WriteSemikeyword()
{
Assert.That("write", LexesAs("WriteSemikeyword |write|"));
}
[Test]
public void WriteOnlySemikeyword()
{
Assert.That("writeonly", LexesAs("WriteOnlySemikeyword |writeonly|"));
}
#endregion
#region Keyword tests
[Test]
public void KeywordsAreCaseInsensitive()
{
Assert.That("And", LexesAs("AndKeyword |And|"));
}
[Test]
public void AndKeyword()
{
Assert.That("and", LexesAs("AndKeyword |and|"));
}
[Test]
public void ArrayKeyword()
{
Assert.That("array", LexesAs("ArrayKeyword |array|"));
}
[Test]
public void AsKeyword()
{
Assert.That("as", LexesAs("AsKeyword |as|"));
}
[Test]
public void AsmKeyword()
{
Assert.That("asm", LexesAs("AsmKeyword |asm|"));
}
[Test]
public void BeginKeyword()
{
Assert.That("begin", LexesAs("BeginKeyword |begin|"));
}
[Test]
public void CaseKeyword()
{
Assert.That("case", LexesAs("CaseKeyword |case|"));
}
[Test]
public void ClassKeyword()
{
Assert.That("class", LexesAs("ClassKeyword |class|"));
}
[Test]
public void ConstKeyword()
{
Assert.That("const", LexesAs("ConstKeyword |const|"));
}
[Test]
public void ConstructorKeyword()
{
Assert.That("constructor", LexesAs("ConstructorKeyword |constructor|"));
}
[Test]
public void DestructorKeyword()
{
Assert.That("destructor", LexesAs("DestructorKeyword |destructor|"));
}
[Test]
public void DispInterfaceKeyword()
{
Assert.That("dispinterface", LexesAs("DispInterfaceKeyword |dispinterface|"));
}
[Test]
public void DivKeyword()
{
Assert.That("div", LexesAs("DivKeyword |div|"));
}
[Test]
public void DoKeyword()
{
Assert.That("do", LexesAs("DoKeyword |do|"));
}
[Test]
public void DownToKeyword()
{
Assert.That("downto", LexesAs("DownToKeyword |downto|"));
}
[Test]
public void ElseKeyword()
{
Assert.That("else", LexesAs("ElseKeyword |else|"));
}
[Test]
public void EndKeyword()
{
Assert.That("end", LexesAs("EndKeyword |end|"));
}
[Test]
public void ExceptKeyword()
{
Assert.That("except", LexesAs("ExceptKeyword |except|"));
}
[Test]
public void ExportsKeyword()
{
Assert.That("exports", LexesAs("ExportsKeyword |exports|"));
}
[Test]
public void FileKeyword()
{
Assert.That("file", LexesAs("FileKeyword |file|"));
}
[Test]
public void FinalizationKeyword()
{
Assert.That("finalization", LexesAs("FinalizationKeyword |finalization|"));
}
[Test]
public void FinallyKeyword()
{
Assert.That("finally", LexesAs("FinallyKeyword |finally|"));
}
[Test]
public void ForKeyword()
{
Assert.That("for", LexesAs("ForKeyword |for|"));
}
[Test]
public void FunctionKeyword()
{
Assert.That("function", LexesAs("FunctionKeyword |function|"));
}
[Test]
public void GotoKeyword()
{
Assert.That("goto", LexesAs("GotoKeyword |goto|"));
}
[Test]
public void IfKeyword()
{
Assert.That("if", LexesAs("IfKeyword |if|"));
}
[Test]
public void ImplementationKeyword()
{
Assert.That("implementation", LexesAs("ImplementationKeyword |implementation|"));
}
[Test]
public void InKeyword()
{
Assert.That("in", LexesAs("InKeyword |in|"));
}
[Test]
public void InheritedKeyword()
{
Assert.That("inherited", LexesAs("InheritedKeyword |inherited|"));
}
[Test]
public void InitializationKeyword()
{
Assert.That("initialization", LexesAs("InitializationKeyword |initialization|"));
}
[Test]
public void InlineKeyword()
{
Assert.That("inline", LexesAs("InlineKeyword |inline|"));
}
[Test]
public void InterfaceKeyword()
{
Assert.That("interface", LexesAs("InterfaceKeyword |interface|"));
}
[Test]
public void IsKeyword()
{
Assert.That("is", LexesAs("IsKeyword |is|"));
}
[Test]
public void LabelKeyword()
{
Assert.That("label", LexesAs("LabelKeyword |label|"));
}
[Test]
public void LibraryKeyword()
{
Assert.That("library", LexesAs("LibraryKeyword |library|"));
}
[Test]
public void ModKeyword()
{
Assert.That("mod", LexesAs("ModKeyword |mod|"));
}
[Test]
public void NilKeyword()
{
Assert.That("nil", LexesAs("NilKeyword |nil|"));
}
[Test]
public void NotKeyword()
{
Assert.That("not", LexesAs("NotKeyword |not|"));
}
[Test]
public void ObjectKeyword()
{
Assert.That("object", LexesAs("ObjectKeyword |object|"));
}
[Test]
public void OfKeyword()
{
Assert.That("of", LexesAs("OfKeyword |of|"));
}
[Test]
public void OrKeyword()
{
Assert.That("or", LexesAs("OrKeyword |or|"));
}
[Test]
public void PackedKeyword()
{
Assert.That("packed", LexesAs("PackedKeyword |packed|"));
}
[Test]
public void ProcedureKeyword()
{
Assert.That("procedure", LexesAs("ProcedureKeyword |procedure|"));
}
[Test]
public void ProgramKeyword()
{
Assert.That("program", LexesAs("ProgramKeyword |program|"));
}
[Test]
public void PropertyKeyword()
{
Assert.That("property", LexesAs("PropertyKeyword |property|"));
}
[Test]
public void RaiseKeyword()
{
Assert.That("raise", LexesAs("RaiseKeyword |raise|"));
}
[Test]
public void RecordKeyword()
{
Assert.That("record", LexesAs("RecordKeyword |record|"));
}
[Test]
public void RepeatKeyword()
{
Assert.That("repeat", LexesAs("RepeatKeyword |repeat|"));
}
[Test]
public void ResourceStringKeyword()
{
Assert.That("resourcestring", LexesAs("ResourceStringKeyword |resourcestring|"));
}
[Test]
public void SetKeyword()
{
Assert.That("set", LexesAs("SetKeyword |set|"));
}
[Test]
public void ShlKeyword()
{
Assert.That("shl", LexesAs("ShlKeyword |shl|"));
}
[Test]
public void ShrKeyword()
{
Assert.That("shr", LexesAs("ShrKeyword |shr|"));
}
[Test]
public void StringKeyword()
{
Assert.That("string", LexesAs("StringKeyword |string|"));
}
[Test]
public void ThenKeyword()
{
Assert.That("then", LexesAs("ThenKeyword |then|"));
}
[Test]
public void ThreadVarKeyword()
{
Assert.That("threadvar", LexesAs("ThreadVarKeyword |threadvar|"));
}
[Test]
public void ToKeyword()
{
Assert.That("to", LexesAs("ToKeyword |to|"));
}
[Test]
public void TryKeyword()
{
Assert.That("try", LexesAs("TryKeyword |try|"));
}
[Test]
public void TypeKeyword()
{
Assert.That("type", LexesAs("TypeKeyword |type|"));
}
[Test]
public void UnitKeyword()
{
Assert.That("unit", LexesAs("UnitKeyword |unit|"));
}
[Test]
public void UntilKeyword()
{
Assert.That("until", LexesAs("UntilKeyword |until|"));
}
[Test]
public void UsesKeyword()
{
Assert.That("uses", LexesAs("UsesKeyword |uses|"));
}
[Test]
public void VarKeyword()
{
Assert.That("var", LexesAs("VarKeyword |var|"));
}
[Test]
public void WhileKeyword()
{
Assert.That("while", LexesAs("WhileKeyword |while|"));
}
[Test]
public void WithKeyword()
{
Assert.That("with", LexesAs("WithKeyword |with|"));
}
[Test]
public void XorKeyword()
{
Assert.That("xor", LexesAs("XorKeyword |xor|"));
}
#endregion
// Equality / inequality / assignment tests
[Test]
public void ColonEquals()
{
Assert.That(":=", LexesAs("ColonEquals |:=|"));
}
[Test]
public void EqualSign()
{
Assert.That("=", LexesAs("EqualSign |=|"));
}
[Test]
public void GreaterThan()
{
Assert.That(">", LexesAs("GreaterThan |>|"));
}
[Test]
public void LessThan()
{
Assert.That("<", LexesAs("LessThan |<|"));
}
[Test]
public void LessOrEqual()
{
Assert.That("<=", LexesAs("LessOrEqual |<=|"));
}
[Test]
public void GreaterOrEqual()
{
Assert.That(">=", LexesAs("GreaterOrEqual |>=|"));
}
[Test]
public void NotEqual()
{
Assert.That("<>", LexesAs("NotEqual |<>|"));
}
// Punctuation tests
[Test]
public void AtSign()
{
Assert.That("@", LexesAs("AtSign |@|"));
}
[Test]
public void Caret()
{
Assert.That("^", LexesAs("Caret |^|"));
}
[Test]
public void CloseBracket()
{
Assert.That("]", LexesAs("CloseBracket |]|"));
}
[Test]
public void CloseParenthesis()
{
Assert.That(")", LexesAs("CloseParenthesis |)|"));
}
[Test]
public void Colon()
{
Assert.That(":", LexesAs("Colon |:|"));
}
[Test]
public void Comma()
{
Assert.That(",", LexesAs("Comma |,|"));
}
[Test]
public void DivideBySign()
{
Assert.That("/", LexesAs("DivideBySign |/|"));
}
[Test]
public void Dot()
{
Assert.That(".", LexesAs("Dot |.|"));
}
[Test]
public void DotDot()
{
Assert.That("..", LexesAs("DotDot |..|"));
}
[Test]
public void MinusSign()
{
Assert.That("-", LexesAs("MinusSign |-|"));
}
[Test]
public void OpenBracket()
{
Assert.That("[", LexesAs("OpenBracket |[|"));
}
[Test]
public void OpenParenthesis()
{
Assert.That("(", LexesAs("OpenParenthesis |(|"));
}
[Test]
public void PlusSign()
{
Assert.That("+", LexesAs("PlusSign |+|"));
}
[Test]
public void Semicolon()
{
Assert.That(";", LexesAs("Semicolon |;|"));
}
[Test]
public void TimesSign()
{
Assert.That("*", LexesAs("TimesSign |*|"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using FluentAssertions;
using RavuAlHemio.BarcodeSharp;
using RavuAlHemio.BarcodeSharp.Mapping.Symbologies;
using Xunit;
namespace BarcodeSharpTests.Mapping.Symbologies
{
public class Code128MappingTests
{
[Fact]
public void CheckDigitCalculationPJJ123C()
{
// (Wikipedia example)
ImmutableList<int> values = ImmutableList.Create(
103, // start A
48, // P
42, // J
42, // J
17, // 1
18, // 2
19, // 3
35 // C
);
var c128 = new Code128Mapping();
int checksum = c128.CalculateChecksum(values);
checksum.Should().Be(54);
}
[Fact]
public void NaiveEncodingPJJ123C()
{
// (Wikipedia example)
var barcodePJJ123C = new[]
{
// start A = 103
true, true, false, true, false, false, false, false, true, false, false,
// A(P) = 48
true, true, true, false, true, true, true, false, true, true, false,
// A(J) = 42 (x2)
true, false, true, true, false, true, true, true, false, false, false,
true, false, true, true, false, true, true, true, false, false, false,
// A(1) = 17
true, false, false, true, true, true, false, false, true, true, false,
// A(2) = 18
true, true, false, false, true, true, true, false, false, true, false,
// A(3) = 19
true, true, false, false, true, false, true, true, true, false, false,
// A(C) = 35
true, false, false, false, true, false, false, false, true, true, false,
// check character = 54
true, true, true, false, true, false, true, true, false, false, false,
// stop = 106
true, true, false, false, false, true, true, true, false, true, false,
// final bar
true, true
};
string s = "PJJ123C";
var c128 = new Code128Mapping
{
Optimize = false
};
c128.IsEncodable(s).Should().BeTrue();
ImmutableArray<bool> bars = c128.EncodeString(s);
bars.Should().Equal(barcodePJJ123C);
}
[Fact]
public void NaiveEncoding12345678()
{
var barcode12345678 = new[]
{
// start A = 103
true, true, false, true, false, false, false, false, true, false, false,
// A(1) = 17
true, false, false, true, true, true, false, false, true, true, false,
// A(2) = 18
true, true, false, false, true, true, true, false, false, true, false,
// A(3) = 19
true, true, false, false, true, false, true, true, true, false, false,
// A(4) = 20
true, true, false, false, true, false, false, true, true, true, false,
// A(5) = 21
true, true, false, true, true, true, false, false, true, false, false,
// A(6) = 22
true, true, false, false, true, true, true, false, true, false, false,
// A(7) = 23
true, true, true, false, true, true, false, true, true, true, false,
// A(8) = 24
true, true, true, false, true, false, false, true, true, false, false,
// check character = 59
true, true, true, false, false, false, true, true, false, true, false,
// stop = 106
true, true, false, false, false, true, true, true, false, true, false,
// final bar
true, true
};
string s = "12345678";
var c128 = new Code128Mapping
{
Optimize = false
};
c128.IsEncodable(s).Should().BeTrue();
ImmutableArray<bool> bars = c128.EncodeString(s);
bars.Should().Equal(barcode12345678);
}
[Fact]
public void NaiveEncodingOneTabTwoTabThree()
{
var barcode = new[]
{
// start B = 104
true, true, false, true, false, false, true, false, false, false, false,
// B(O) = 47
true, false, false, false, true, true, true, false, true, true, false,
// B(n) = 78
true, true, false, false, false, false, true, false, true, false, false,
// B(e) = 69
true, false, true, true, false, false, true, false, false, false, false,
// B(SwitchA) = 101
true, true, true, false, true, false, true, true, true, true, false,
// A(\t) = 73
true, false, false, false, false, true, true, false, true, false, false,
// A(T) = 52
true, true, false, true, true, true, false, false, false, true, false,
// A(SwitchB) = 100
true, false, true, true, true, true, false, true, true, true, false,
// B(w) = 87
true, true, true, true, false, false, true, false, true, false, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(SwitchA) = 101
true, true, true, false, true, false, true, true, true, true, false,
// A(\t) = 73
true, false, false, false, false, true, true, false, true, false, false,
// A(T) = 52
true, true, false, true, true, true, false, false, false, true, false,
// A(SwitchB) = 100
true, false, true, true, true, true, false, true, true, true, false,
// B(h) = 72
true, false, false, true, true, false, false, false, false, true, false,
// B(r) = 82
true, false, false, true, false, false, true, true, true, true, false,
// B(e) = 69
true, false, true, true, false, false, true, false, false, false, false,
// B(e) = 69
true, false, true, true, false, false, true, false, false, false, false,
// check character = 6
true, false, false, true, true, false, false, true, false, false, false,
// stop = 106
true, true, false, false, false, true, true, true, false, true, false,
// final bar
true, true
};
string s = "One\tTwo\tThree";
var c128 = new Code128Mapping
{
Optimize = false
};
c128.IsEncodable(s).Should().BeTrue();
ImmutableArray<bool> bars = c128.EncodeString(s);
bars.Should().Equal(barcode);
}
[Fact]
public void Optimized12345678()
{
var barcode12345678 = new[]
{
// start C = 105
true, true, false, true, false, false, true, true, true, false, false,
// C(12) = 12
true, false, true, true, false, false, true, true, true, false, false,
// C(34) = 34
true, false, false, false, true, false, true, true, false, false, false,
// C(56) = 56
true, true, true, false, false, false, true, false, true, true, false,
// C(78) = 78
true, true, false, false, false, false, true, false, true, false, false,
// check character = 47
true, false, false, false, true, true, true, false, true, true, false,
// stop = 106
true, true, false, false, false, true, true, true, false, true, false,
// final bar
true, true
};
string s = "12345678";
var c128 = new Code128Mapping
{
Optimize = true
};
c128.IsEncodable(s).Should().BeTrue();
ImmutableArray<bool> bars = c128.EncodeString(s);
bars.Should().Equal(barcode12345678);
}
[Fact]
public void OptimizedOneTabTwoTabThree()
{
var barcode = new[]
{
// start B = 104
true, true, false, true, false, false, true, false, false, false, false,
// B(O) = 47
true, false, false, false, true, true, true, false, true, true, false,
// B(n) = 78
true, true, false, false, false, false, true, false, true, false, false,
// B(e) = 69
true, false, true, true, false, false, true, false, false, false, false,
// B(ShiftA) = 98
true, true, true, true, false, true, false, false, false, true, false,
// A(\t) = 73
true, false, false, false, false, true, true, false, true, false, false,
// B(T) = 52
true, true, false, true, true, true, false, false, false, true, false,
// B(w) = 87
true, true, true, true, false, false, true, false, true, false, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(ShiftA) = 98
true, true, true, true, false, true, false, false, false, true, false,
// A(\t) = 73
true, false, false, false, false, true, true, false, true, false, false,
// B(T) = 52
true, true, false, true, true, true, false, false, false, true, false,
// B(h) = 72
true, false, false, true, true, false, false, false, false, true, false,
// B(r) = 82
true, false, false, true, false, false, true, true, true, true, false,
// B(e) = 69
true, false, true, true, false, false, true, false, false, false, false,
// B(e) = 69
true, false, true, true, false, false, true, false, false, false, false,
// check character = 81
true, false, false, true, false, true, true, true, true, false, false,
// stop = 106
true, true, false, false, false, true, true, true, false, true, false,
// final bar
true, true
};
string s = "One\tTwo\tThree";
var c128 = new Code128Mapping
{
Optimize = true
};
c128.IsEncodable(s).Should().BeTrue();
ImmutableArray<bool> bars = c128.EncodeString(s);
bars.Should().Equal(barcode);
}
[Fact]
public void OptimizedLol9Lol()
{
// single digit: switch pointless
var barcode = new[]
{
// start B = 104
true, true, false, true, false, false, true, false, false, false, false,
// B(L) = 44
true, false, false, false, true, true, false, true, true, true, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(l) = 76
true, true, false, false, true, false, true, false, false, false, false,
// B(9) = 25
true, true, true, false, false, true, false, true, true, false, false,
// B(L) = 44
true, false, false, false, true, true, false, true, true, true, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(l) = 76
true, true, false, false, true, false, true, false, false, false, false,
// check character = 6
true, false, false, true, true, false, false, true, false, false, false,
// stop = 106
true, true, false, false, false, true, true, true, false, true, false,
// final bar
true, true
};
string s = "Lol9Lol";
var c128 = new Code128Mapping
{
Optimize = true
};
c128.IsEncodable(s).Should().BeTrue();
ImmutableArray<bool> bars = c128.EncodeString(s);
bars.Should().Equal(barcode);
}
[Fact]
public void OptimizedLol98Lol()
{
// two digits: switch there and back has too much overhead
var barcode = new[]
{
// start B = 104
true, true, false, true, false, false, true, false, false, false, false,
// B(L) = 44
true, false, false, false, true, true, false, true, true, true, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(l) = 76
true, true, false, false, true, false, true, false, false, false, false,
// B(9) = 25
true, true, true, false, false, true, false, true, true, false, false,
// B(8) = 24
true, true, true, false, true, false, false, true, true, false, false,
// B(L) = 44
true, false, false, false, true, true, false, true, true, true, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(l) = 76
true, true, false, false, true, false, true, false, false, false, false,
// check character = 16
true, false, false, true, true, true, false, true, true, false, false,
// stop = 106
true, true, false, false, false, true, true, true, false, true, false,
// final bar
true, true
};
string s = "Lol98Lol";
var c128 = new Code128Mapping
{
Optimize = true
};
c128.IsEncodable(s).Should().BeTrue();
ImmutableArray<bool> bars = c128.EncodeString(s);
bars.Should().Equal(barcode);
}
[Fact]
public void OptimizedLol987Lol()
{
// three digits: switch there and back has too much overhead
var barcode = new[]
{
// start B = 104
true, true, false, true, false, false, true, false, false, false, false,
// B(L) = 44
true, false, false, false, true, true, false, true, true, true, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(l) = 76
true, true, false, false, true, false, true, false, false, false, false,
// B(9) = 25
true, true, true, false, false, true, false, true, true, false, false,
// B(8) = 24
true, true, true, false, true, false, false, true, true, false, false,
// B(7) = 23
true, true, true, false, true, true, false, true, true, true, false,
// B(L) = 44
true, false, false, false, true, true, false, true, true, true, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(l) = 76
true, true, false, false, true, false, true, false, false, false, false,
// check character = 44
true, false, false, false, true, true, false, true, true, true, false,
// stop = 106
true, true, false, false, false, true, true, true, false, true, false,
// final bar
true, true
};
string s = "Lol987Lol";
var c128 = new Code128Mapping
{
Optimize = true
};
c128.IsEncodable(s).Should().BeTrue();
ImmutableArray<bool> bars = c128.EncodeString(s);
bars.Should().Equal(barcode);
}
[Fact]
public void OptimizedLol9876Lol()
{
// four digits: switching makes as much sense as not
var barcode = new[]
{
// start B = 104
true, true, false, true, false, false, true, false, false, false, false,
// B(L) = 44
true, false, false, false, true, true, false, true, true, true, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(l) = 76
true, true, false, false, true, false, true, false, false, false, false,
// B(9) = 25
true, true, true, false, false, true, false, true, true, false, false,
// B(8) = 24
true, true, true, false, true, false, false, true, true, false, false,
// B(7) = 23
true, true, true, false, true, true, false, true, true, true, false,
// B(6) = 22
true, true, false, false, true, true, true, false, true, false, false,
// B(L) = 44
true, false, false, false, true, true, false, true, true, true, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(l) = 76
true, true, false, false, true, false, true, false, false, false, false,
// check character = 88
true, true, true, true, false, false, true, false, false, true, false,
// stop = 106
true, true, false, false, false, true, true, true, false, true, false,
// final bar
true, true
};
string s = "Lol9876Lol";
var c128 = new Code128Mapping
{
Optimize = true
};
c128.IsEncodable(s).Should().BeTrue();
ImmutableArray<bool> bars = c128.EncodeString(s);
bars.Should().Equal(barcode);
}
[Fact]
public void OptimizedLol98765Lol()
{
// five digits: switching makes as much sense as not
var barcode = new[]
{
// start B = 104
true, true, false, true, false, false, true, false, false, false, false,
// B(L) = 44
true, false, false, false, true, true, false, true, true, true, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(l) = 76
true, true, false, false, true, false, true, false, false, false, false,
// B(9) = 25
true, true, true, false, false, true, false, true, true, false, false,
// B(8) = 24
true, true, true, false, true, false, false, true, true, false, false,
// B(7) = 23
true, true, true, false, true, true, false, true, true, true, false,
// B(6) = 22
true, true, false, false, true, true, true, false, true, false, false,
// B(5) = 21
true, true, false, true, true, true, false, false, true, false, false,
// B(L) = 44
true, false, false, false, true, true, false, true, true, true, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(l) = 76
true, true, false, false, true, false, true, false, false, false, false,
// check character = 43
true, false, true, true, false, false, false, true, true, true, false,
// stop = 106
true, true, false, false, false, true, true, true, false, true, false,
// final bar
true, true
};
string s = "Lol98765Lol";
var c128 = new Code128Mapping
{
Optimize = true
};
c128.IsEncodable(s).Should().BeTrue();
ImmutableArray<bool> bars = c128.EncodeString(s);
bars.Should().Equal(barcode);
}
[Fact]
public void OptimizedLol987654Lol()
{
// six digits: switching makes sense
var barcode = new[]
{
// start B = 104
true, true, false, true, false, false, true, false, false, false, false,
// B(L) = 44
true, false, false, false, true, true, false, true, true, true, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(l) = 76
true, true, false, false, true, false, true, false, false, false, false,
// B(SwitchC) = 99
true, false, true, true, true, false, true, true, true, true, false,
// C(98) = 98
true, true, true, true, false, true, false, false, false, true, false,
// C(76) = 76
true, true, false, false, true, false, true, false, false, false, false,
// C(54) = 54
true, true, true, false, true, false, true, true, false, false, false,
// C(SwitchB) = 100
true, false, true, true, true, true, false, true, true, true, false,
// B(L) = 44
true, false, false, false, true, true, false, true, true, true, false,
// B(o) = 79
true, false, false, false, true, true, true, true, false, true, false,
// B(l) = 76
true, true, false, false, true, false, true, false, false, false, false,
// check character = 29
true, true, true, false, false, true, true, false, false, true, false,
// stop = 106
true, true, false, false, false, true, true, true, false, true, false,
// final bar
true, true
};
string s = "Lol987654Lol";
var c128 = new Code128Mapping
{
Optimize = true
};
c128.IsEncodable(s).Should().BeTrue();
ImmutableArray<bool> bars = c128.EncodeString(s);
bars.Should().Equal(barcode);
}
[Fact]
public void OptimizationEarlyStopFuzz()
{
var optimized128 = new Code128Mapping { Optimize = true };
var exhaustive128 = new Code128Mapping { Optimize = true, ForceExhaustiveOptimization = true };
var mappableCharSet = new HashSet<char>();
mappableCharSet.UnionWith(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_");
mappableCharSet.UnionWith("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009\u000A\u000B\u000C\u000D\u000E\u000F");
mappableCharSet.UnionWith("\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001A\u001B\u001C\u001D\u001E\u001F");
mappableCharSet.UnionWith("`abcdefghijklmnopqrstuvwxyz{|}~\u007F");
var mappableCharList = new List<char>(mappableCharSet);
var rnd = new Random();
int length = rnd.Next(19, 21);
var buf = new StringBuilder(length);
for (int character = 0; character < length; ++character)
{
buf.Append(mappableCharList[rnd.Next(mappableCharList.Count)]);
}
string encodeMe = buf.ToString();
string hexy = string.Join(" ", encodeMe.Select(c => ((int)c).ToString("x2")));
ImmutableArray<bool> optimizedBars = optimized128.EncodeString(encodeMe);
ImmutableArray<bool> exhaustiveBars = exhaustive128.EncodeString(encodeMe);
optimizedBars.Should().Equal(exhaustiveBars, $"because the optimized Code128 representation of 0x'{hexy}' should match the exhaustive one");
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 3/12/2009 5:30:52 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using GeoAPI.Geometries;
namespace DotSpatial.Data
{
/// <summary>
/// A new model, now that we support 3.5 framework and extension methods that are essentially
/// derived characteristics away from the IRaster interface, essentially reducing it
/// to the simplest interface possible for future implementers, while extending the most
/// easy-to-find functionality to the users.
/// </summary>
public static class RasterExt
{
#region Methods
/// <summary>
/// determine if the shape is partially inside grid extents
/// </summary>
/// <returns>false, if the shape is completely outside grid extents
/// true, if it's at least partially inside </returns>
public static bool ContainsFeature(this IRaster raster, IFeature shape)
{
IRasterBounds bounds = raster.Bounds;
Extent shapeExtent = shape.Geometry.EnvelopeInternal.ToExtent();
return !(shapeExtent.MinX > bounds.Extent.MaxX) && !(shapeExtent.MinY > bounds.Extent.MaxY) && !(shapeExtent.MaxX < bounds.Extent.MinX) && !(shapeExtent.MaxY < bounds.Extent.MinY);
}
/// <summary>
/// Gets a boolean that is true if the Window extents contain are all the information for the raster.
/// In otherwords, StartRow = StartColumn = 0, EndRow = NumRowsInFile - 1, and EndColumn = NumColumnsInFile - 1
/// </summary>
public static bool IsFullyWindowed(this IRaster raster)
{
if (raster.StartRow != 0) return false;
if (raster.StartColumn != 0) return false;
if (raster.EndRow != raster.NumRowsInFile - 1) return false;
if (raster.EndColumn != raster.NumColumnsInFile - 1) return false;
return true;
}
#region GeoReference
/// <summary>
/// This doesn't change the data, but instead performs a translation where the upper left coordinate
/// is specified in world coordinates.
/// </summary>
/// <param name="raster">Moves this raster so that the upper left coordinate will match the specified position. The skew and cellsize will remain unaltered</param>
/// <param name="position">The location to move the upper left corner of the raster to in world coordinates.</param>
public static void MoveTo(this IRaster raster, Coordinate position)
{
double[] vals = raster.Bounds.AffineCoefficients;
vals[0] = position.X;
vals[3] = position.Y;
}
/// <summary>
/// Rotates the geospatial reference points for this image by rotating the affine coordinates.
/// The center for this rotation will be the center of the image.
/// </summary>
/// <param name="raster">The raster to rotate</param>
/// <param name="degrees">The angle in degrees to rotate the image counter clockwise.</param>
public static void Rotate(this IRaster raster, float degrees)
{
Matrix m = raster.Bounds.Get_AffineMatrix();
m.Rotate(degrees);
raster.Bounds.Set_AffineMatrix(m);
}
/// <summary>
/// Rotates the geospatial reference points for this image by rotating the affine coordinates.
/// The center for this rotation will be the center of the image.
/// </summary>
/// <param name="raster">The raster to rotate about the specified coordinate</param>
/// <param name="degrees">The angle in degrees to rotate the image counterclockwise.</param>
/// <param name="center">The point that marks the center of the desired rotation in geographic coordiantes.</param>
public static void RotateAt(this IRaster raster, float degrees, Coordinate center)
{
Matrix m = raster.Bounds.Get_AffineMatrix();
m.RotateAt(degrees, new PointF(Convert.ToSingle(center.X), Convert.ToSingle(center.Y)));
raster.Bounds.Set_AffineMatrix(m);
}
/// <summary>
/// This method uses a matrix transform to adjust the scale. The precision of using
/// a Drawing2D transform is float precision, so some accuracy may be lost.
/// </summary>
/// <param name="raster">The raster to apply the scale transform to</param>
/// <param name="scaleX">The multiplier to adjust the geographic extents of the raster in the X direction</param>
/// <param name="scaleY">The multiplier to adjust the geographic extents of the raster in the Y direction</param>
public static void Scale(this IRaster raster, float scaleX, float scaleY)
{
Matrix m = raster.Bounds.Get_AffineMatrix();
m.Scale(scaleX, scaleY);
raster.Bounds.Set_AffineMatrix(m);
}
/// <summary>
/// This method uses a matrix transform to adjust the shear. The precision of using
/// a Drawing2D transform is float precision, so some accuracy may be lost.
/// </summary>
/// <param name="raster">The raster to apply the transform to</param>
/// <param name="shearX">The floating point horizontal shear factor</param>
/// <param name="shearY">The floating ponit vertical shear factor</param>
public static void Shear(this IRaster raster, float shearX, float shearY)
{
Matrix m = raster.Bounds.Get_AffineMatrix();
m.Shear(shearX, shearY);
raster.Bounds.Set_AffineMatrix(m);
}
/// <summary>
/// Applies a translation transform to the georeferenced coordinates on this raster.
/// </summary>
/// <param name="raster">The raster to apply the translation to</param>
/// <param name="shift">An ICoordinate with shear values</param>
public static void Translate(this IRaster raster, Coordinate shift)
{
double[] affine = raster.Bounds.AffineCoefficients;
affine[0] += shift.X;
affine[3] += shift.Y;
}
#endregion
#region Nearest Values
/// <summary>
/// Retrieves the data from the cell that is closest to the specified coordinates. This will
/// return a No-Data value if the specified coordintes are outside of the grid.
/// </summary>
/// <param name="raster">The raster to get the value from</param>
/// <param name="location">A valid implementation of Icoordinate specifying the geographic location.</param>
/// <returns>The value of type T of the cell that has a center closest to the specified coordinates</returns>
public static double GetNearestValue(this IRaster raster, Coordinate location)
{
RcIndex position = raster.ProjToCell(location.X, location.Y);
if (position.Row < 0 || position.Row >= raster.NumRows) return raster.NoDataValue;
if (position.Column < 0 || position.Column >= raster.NumColumns) return raster.NoDataValue;
return raster.Value[position.Row, position.Column];
}
/// <summary>
/// Retrieves the data from the cell that is closest to the specified coordinates. This will
/// return a No-Data value if the specified coordintes are outside of the grid.
/// </summary>
/// <param name="raster">The raster to get the value from</param>
/// <param name="x">The longitude or horizontal coordinate</param>
/// <param name="y">The latitude or vertical coordinate</param>
/// <returns>The double value of the cell that has a center closest to the specified coordinates</returns>
public static double GetNearestValue(this IRaster raster, double x, double y)
{
RcIndex position = raster.ProjToCell(x, y);
if (position.Row < 0 || position.Row >= raster.NumRows) return raster.NoDataValue;
if (position.Column < 0 || position.Column >= raster.NumColumns) return raster.NoDataValue;
return raster.Value[position.Row, position.Column];
}
/// <summary>
/// Retrieves the location from the cell that is closest to the specified coordinates. This will
/// do nothing if the specified coordinates are outside of the raster.
/// </summary>
/// <param name="raster">The IRaster to set the value for</param>
/// <param name="x">The longitude or horizontal coordinate</param>
/// <param name="y">The latitude or vertical coordinate</param>
/// <param name="value">The value to assign to the nearest cell to the specified location</param>
public static void SetNearestValue(this IRaster raster, double x, double y, double value)
{
RcIndex position = raster.ProjToCell(x, y);
if (position.Row < 0 || position.Row >= raster.NumRows) return;
if (position.Column < 0 || position.Column >= raster.NumColumns) return;
raster.Value[position.Row, position.Column] = value;
}
/// <summary>
/// Retrieves the location from the cell that is closest to the specified coordinates. This will
/// do nothing if the specified coordinates are outside of the raster.
/// </summary>
/// <param name="raster">The IRaster to set the value for</param>
/// <param name="location">An Icoordinate specifying the location</param>
/// <param name="value">The value to assign to the nearest cell to the specified location</param>
public static void SetNearestValue(this IRaster raster, Coordinate location, double value)
{
RcIndex position = raster.ProjToCell(location.X, location.Y);
if (position.Row < 0 || position.Row >= raster.NumRows) return;
if (position.Column < 0 || position.Column >= raster.NumColumns) return;
raster.Value[position.Row, position.Column] = value;
}
#endregion
#region Projection
/// <summary>
/// Extends the IRaster interface to return the coordinate of the center of a row column position.
/// </summary>
/// <param name="raster">The raster interface to extend</param>
/// <param name="position">The zero based integer index of the row and column of the cell to locate</param>
/// <returns>The geographic location of the center of the specified cell</returns>
public static Coordinate CellToProj(this IRaster raster, RcIndex position)
{
if (raster == null) return null;
if (raster.Bounds == null) return null;
return raster.Bounds.CellCenter_ToProj(position.Row, position.Column);
}
/// <summary>
/// Extends the IRaster interface to return the coordinate of the center of a row column position.
/// </summary>
/// <param name="raster">The raster interface to extend</param>
/// <param name="row">The zero based integer index of the row of the cell to locate</param>
/// <param name="col">The zero based integer index of the column of the cell to locate</param>
/// <returns>The geographic location of the center of the specified cell</returns>
public static Coordinate CellToProj(this IRaster raster, int row, int col)
{
if (raster == null) return null;
if (raster.Bounds == null) return null;
return raster.Bounds.CellCenter_ToProj(row, col);
}
/// <summary>
/// Extends the IRaster interface to return the zero based integer row and column indices
/// </summary>
/// <param name="raster">The raster interface to extend</param>
/// <param name="location">The geographic coordinate describing the latitude and longitude</param>
/// <returns>The RcIndex that describes the zero based integer row and column indices</returns>
public static RcIndex ProjToCell(this IRaster raster, Coordinate location)
{
if (raster == null) return RcIndex.Empty;
if (raster.Bounds == null) return RcIndex.Empty;
return raster.Bounds.ProjToCell(location);
}
/// <summary>
/// Extends the IRaster interface to return the zero based integer row and column indices
/// </summary>
/// <param name="raster">The raster interface to extend</param>
/// <param name="x">A double precision floating point describing the longitude</param>
/// <param name="y">A double precision floating point describing the latitude</param>
/// <returns>The RcIndex that describes the zero based integer row and column indices</returns>
public static RcIndex ProjToCell(this IRaster raster, double x, double y)
{
if (raster == null) return RcIndex.Empty;
if (raster.Bounds == null) return RcIndex.Empty;
return raster.Bounds.ProjToCell(new Coordinate(x, y));
}
#endregion
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="PrologCodeGenerator.cs" company="Axiom">
//
// Copyright (c) 2006 Ali Hodroj. All rights reserved.
//
// The use and distribution terms for this source code are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
// </copyright>
//------------------------------------------------------------------------------
using System;
using Axiom.Compiler.CodeObjectModel;
using System.Collections;
using Axiom.Compiler.Framework.Generators;
using Axiom.Runtime;
namespace Axiom.Compiler.Framework
{
public class PrologCodeGenerator : IPrologCodeGenerator
{
private PrologVariableDictionary _dictionary = null;
private ArrayList _methods = new ArrayList();
private int headArity = 0;
private AMGenerator _generator = null;
private int _currArgN = 0;
public PrologCodeGenerator ()
{
}
public void GenerateCodeFromUnit (PrologCodeUnit unit, ArrayList instructions)
{
_generator = new AMGenerator(instructions);
foreach (PrologCodeTerm term in unit.Terms)
{
ArrayList inst = new ArrayList();
if (term is PrologCodeClause)
{
GenerateCodeFromClause((PrologCodeClause)term, inst);
instructions.AddRange(inst);
}
else if (term is PrologCodePredicate)
{
PrologCodeClause c = new PrologCodeClause((PrologCodePredicate)term);
GenerateCodeFromClause(c, inst);
instructions.AddRange(inst);
}
else
{
throw new PrologCompilerException("Unknown term type: " + term.ToString());
}
}
}
public void GenerateCodeFromClause (PrologCodeClause clause, ArrayList instructions)
{
/* Do we need to allocate an environment? */
bool hasEnvironment = clause.Goals.Count > 1;
/* Initialize variable dictionary */
_dictionary = new PrologVariableDictionary();
/* Build the variable dictionary for this clause */
_dictionary.Build(clause);
/* Free all registers */
PrologRegisterTable registers = PrologRegisterTable.Instance;
registers.FreeAllRegisters();
/* Prepare head variables for code generation */
int reg = 0;
if (clause.Head.Arity > 0)
{
headArity = clause.Head.Arity;
foreach (PrologCodeTerm argument in clause.Head.Arguments)
{
if (argument is PrologCodeVariable)
{
PrologCodeVariable var = (PrologCodeVariable)argument;
PrologVariableDictionaryEntry entry = _dictionary.GetVariable(var.Name);
if (entry != null)
{
if (entry.IsTemporary && entry.TemporaryIndex == -1)
{
entry.IsReferenced = true;
_dictionary.AllocateTemporaryVariable(entry, reg);
}
}
//BUG: reg++;
}
reg++;
}
}
/* Prepare first goal variables */
int xreg = 0;
PrologCodeTerm fg = null;
if (clause.Goals.Count > 0)
{
fg = (PrologCodeTerm)clause.Goals[0];
}
if (fg is PrologCodePredicate)
{
PrologCodePredicate firstGoal = (PrologCodePredicate)fg;
if (firstGoal.Name == "!")
{
hasEnvironment = true;
}
if (firstGoal.Arity > 0)
{
foreach (PrologCodeTerm variable in firstGoal.Arguments)
{
if (variable is PrologCodeVariable)
{
PrologVariableDictionaryEntry entry = _dictionary.GetVariable(((PrologCodeVariable)variable).Name);
if (entry != null)
{
if (entry.IsTemporary && entry.TemporaryIndex == -1)
{
if (!registers.InUse(xreg))
{
_dictionary.AllocateTemporaryVariable(entry, xreg);
}
}
}
}
xreg++;
}
}
}
/* Reserve required registers */
for (int i = 0; i < Math.Max(reg, xreg); i++)
{
registers.AllocateRegister(i);
}
/* Emit predicate label */
_generator.DeclareProcedure(clause.Head.Name, clause.Head.Arity);
/* Allocate an environment if needed */
if (hasEnvironment)
{
_generator.Emit(OpCodes.Allocate);
}
/* Compile clause head */
CompileClauseHead(clause.Head, instructions);
/* Set current goal to 1 */
_dictionary.CurrentGoalIndex = 1;
if (clause.Goals.Count == 0)
{
_generator.EndProcedure();
/* Reset variable dictionary */
_dictionary.Reset();
instructions = _generator.Instructions;
return;
}
/* Compile first goal */
CompileGoal(fg, instructions);
_dictionary.CurrentGoalIndex++;
/* Compile the rest of the goals */
for (int goalIndex = 1; goalIndex < clause.Goals.Count; goalIndex++)
{
PrologCodeTerm goal = (PrologCodeTerm)clause.Goals[goalIndex];
InitializeGoalTemporaryVariables(goal);
/* reserve registers */
for (int i = 0; i < reg; i++)
{
registers.AllocateRegister(i);
}
/* Clear temporary index of permanent variables */
_dictionary.ClearTempIndexOfPermanentVariables();
/* Compile goal */
CompileGoal(goal, instructions);
/* Advance to next goal */
_dictionary.CurrentGoalIndex += 1;
}
/* Reset instruction set, code pointer, and variable
* dictionary.
*/
_dictionary.Reset();
}
public void GenerateCodeFromPredicate(PrologCodePredicate p, ArrayList a)
{
PrologCodeClause clause = new PrologCodeClause(p);
GenerateCodeFromClause(clause, a);
}
#region Head compilation helper methods
private void CompileClauseHead(PrologCodeTerm head, ArrayList instructions)
{
if (head is PrologCodePredicate)
{
PrologCodePredicate headPredicate = (PrologCodePredicate)head;
if (headPredicate.Arity == 0)
{
/* Do nothing */
}
else
{
CompileHeadArguments(((PrologCodePredicate)head).Arguments);
}
}
else if (head is PrologCodeNonEmptyList)
{
ArrayList headListArguments = new ArrayList();
PrologCodeNonEmptyList NEList = (PrologCodeNonEmptyList)head;
headListArguments.Add(NEList.Head);
headListArguments.Add(NEList.Tail);
CompileHeadArguments(headListArguments);
}
else if (head is PrologCodeVariable)
{
throw new PrologCompilerException("Clause head cannot be a variable.");
}
else if (head is PrologCodeIntegerAtom || head is PrologCodeFloatAtom)
{
throw new PrologCompilerException("Clause head cannot be a number.");
}
}
private void CompileHeadArguments(ArrayList arguments)
{
for (int i = 0; i < arguments.Count; i++)
{
_currArgN = i;
PrologCodeTerm arg = (PrologCodeTerm)arguments[i];
if (arg is PrologCodeNilAtom || arg is PrologCodeEmptyList)
{
_generator.Emit(OpCodes.Get_Constant, "[]", X(i));
}
else if (arg is PrologCodeAtom)
{
if (arg is PrologCodeConstantAtom)
{
_generator.Emit(OpCodes.Get_Constant, ((PrologCodeConstantAtom)arg).Value, X(i));
}
else if (arg is PrologCodeIntegerAtom)
{
_generator.Emit(OpCodes.Get_Constant, ((PrologCodeIntegerAtom)arg).Value.ToString(), X(i));
}
else if (arg is PrologCodeFloatAtom)
{
_generator.Emit(OpCodes.Get_Constant, ((PrologCodeFloatAtom)arg).Value.ToString(), X(i));
}
else if (arg is PrologCodeStringAtom)
{
_generator.Emit(OpCodes.Get_Constant, ((PrologCodeStringAtom)arg).Value, X(i));
}
}
else if (arg is PrologCodeVariable)
{
if (_dictionary.GoalCount == 0)
{
// warning: singleton variable
}
PrologVariableDictionaryEntry entry = _dictionary.GetVariable(((PrologCodeVariable)arg).Name);
if (entry.IsTemporary)
{
if (entry.IsReferenced && entry.TemporaryIndex != i)
{
_generator.Emit(OpCodes.Get_Value, X(entry.TemporaryIndex), X(i));
}
}
else
{
if (entry.IsReferenced)
{
_generator.Emit(OpCodes.Get_Value, Y(entry.PermanentIndex), X(i));
}
else
{
_generator.Emit(OpCodes.Get_Variable, Y(entry.PermanentIndex), X(i));
}
}
}
else if (arg is PrologCodeNonEmptyList)
{
_generator.Emit(OpCodes.Get_List, X(i));
ArrayList listArguments = new ArrayList();
PrologCodeNonEmptyList NEList = (PrologCodeNonEmptyList)arg;
listArguments.Add(NEList.Head);
listArguments.Add(NEList.Tail);
CompileStructArguments(listArguments);
}
else if (arg is PrologCodePredicate)
{
PrologCodePredicate structure = (PrologCodePredicate)arg;
_generator.Emit(OpCodes.Get_Structure, structure.Name + "/" + structure.Arity, X(i));
CompileStructArguments(structure.Arguments);
}
else
{
throw new PrologCompilerException("Unknown argument type (" + arg.GetType().ToString() + ") in head arguments");
}
}
}
private void CompileStructArguments(ArrayList arguments)
{
ArrayList records = new ArrayList();
// TODO: Why is it 20 here? was there a maximum number of records originally.
for (int i = 0; i < 20; i++)
{
records.Add(new Record());
}
int nRecs = 0;
for (int i = 0; i < arguments.Count; i++)
{
PrologCodeTerm term = (PrologCodeTerm)arguments[i];
if (term is PrologCodeNilAtom)
{
_generator.Emit(OpCodes.Unify_Constant, "[]");
}
else if (term is PrologCodeAtom)
{
if (term is PrologCodeConstantAtom)
{
_generator.Emit(OpCodes.Unify_Constant, ((PrologCodeConstantAtom)term).Value);
}
else if (term is PrologCodeIntegerAtom)
{
_generator.Emit(OpCodes.Unify_Constant, ((PrologCodeIntegerAtom)term).Value.ToString());
}
else if (term is PrologCodeFloatAtom)
{
_generator.Emit(OpCodes.Unify_Constant, ((PrologCodeFloatAtom)term).Value.ToString());
}
else if (term is PrologCodeStringAtom)
{
_generator.Emit(OpCodes.Unify_Constant, ((PrologCodeStringAtom)term).Value);
}
}
else if (term is PrologCodeVariable)
{
PrologVariableDictionaryEntry entry = _dictionary.GetVariable(((PrologCodeVariable)term).Name);
if (entry.IsReferenced)
{
if (entry.IsTemporary)
{
if (entry.IsGlobal)
{
_generator.Emit(OpCodes.Unify_Value, X(entry.TemporaryIndex));
}
else
{
// TODO: maybe this should be unify_variable
_generator.Emit(OpCodes.Unify_Local_Value, X(entry.TemporaryIndex));
entry.IsGlobal = true;
}
}
else
{
if (entry.IsGlobal)
{
_generator.Emit(OpCodes.Unify_Value, Y(entry.PermanentIndex));
}
else
{
_generator.Emit(OpCodes.Unify_Local_Value, Y(entry.PermanentIndex));
}
}
}
// not referenced
else
{
if (entry.IsTemporary)
{
if (entry.Occurrences == 1)
{
_generator.Emit(OpCodes.Unify_Void, "1");
}
else
{ // used to be i < entry.TemporaryIndex
if (_currArgN < entry.TemporaryIndex && entry.TemporaryIndex < headArity)
{
entry.TemporaryIndex = PrologRegisterTable.Instance.FindRegister();
}
_generator.Emit(OpCodes.Unify_Variable, X(entry.TemporaryIndex));
}
}
else
{
_generator.Emit(OpCodes.Unify_Variable, Y(entry.PermanentIndex));
}
entry.IsGlobal = true;
}
}
else if (term is PrologCodeEmptyList)
{
_generator.Emit(OpCodes.Unify_Constant, "[]");
}
else
{
((Record)records[nRecs]).Term = term;
((Record)records[nRecs]).TemporaryIndex = PrologRegisterTable.Instance.FindRegister();
_generator.Emit(OpCodes.Unify_Variable, X(((Record)records[nRecs]).TemporaryIndex));
nRecs++;
}
}
for (int i = 0; i < nRecs; i++)
{
Record r = (Record)records[i];
if (r.Term is PrologCodeNonEmptyList)
{
_generator.Emit(OpCodes.Get_List, X(r.TemporaryIndex));
PrologRegisterTable.Instance.FreeRegister(r.TemporaryIndex);
ArrayList listArguments = new ArrayList();
PrologCodeNonEmptyList NEList = (PrologCodeNonEmptyList)r.Term;
listArguments.Add(NEList.Head);
listArguments.Add(NEList.Tail);
CompileStructArguments(listArguments);
}
else if (r.Term is PrologCodePredicate)
{
PrologCodePredicate structure = (PrologCodePredicate)r.Term;
_generator.Emit(OpCodes.Get_Structure, structure.Name + "/" + structure.Arity, X(r.TemporaryIndex));
CompileStructArguments(structure.Arguments);
}
else
{
throw new PrologCompilerException("Unknown argument type (" + r.Term.GetType().ToString() + ") in structure arguments");
}
}
}
internal class Record
{
public PrologCodeTerm Term;
public int TemporaryIndex;
public Record()
{
Term = null;
TemporaryIndex = -1;
}
}
private string X(int i)
{
return "X" + i;
}
private string Y(int i)
{
return "Y" + i;
}
#endregion
#region Goal compilation helper methods
private void CompileGoal(PrologCodeTerm goal, ArrayList instructions)
{
if (goal is PrologCodePredicate && ((PrologCodePredicate)goal).Arity == 0)
{
PrologCodePredicate goalPredicate = (PrologCodePredicate)goal;
if (goalPredicate.Arity == 0)
{
if (goalPredicate.Name == "!")
{
_generator.Emit(OpCodes.Cut);
if (_dictionary.InLastGoal)
{
_generator.Emit(OpCodes.Deallocate);
_generator.EndProcedure();
}
return;
}
if (goalPredicate.Name == "fail")
{
_generator.Emit(OpCodes.Fail);
_generator.EndProcedure();
return;
}
// TODO: handle methods here...
CompileCall(goalPredicate);
}
}
else if (goal is PrologCodeVariable)
{
CompileGoalVariable((PrologCodeVariable)goal, 0);
if (_dictionary.InLastGoal)
{
if (_dictionary.CurrentGoalIndex > 1)
{
_generator.Emit(OpCodes.Deallocate);
}
_generator.EmitExecuteVar(((PrologCodeVariable)goal).Name, 0);
}
else
{
_generator.EmitCallVar(((PrologCodeVariable)goal).Name, 0);
}
}
else if (goal is PrologCodeNonEmptyList)
{
// TODO: compile list arguments, then call ./2
}
else if (goal is PrologCodeIntegerAtom || goal is PrologCodeFloatAtom)
{
throw new PrologCompilerException("Clause goal cannot be a number.");
}
else if (goal is PrologCodePredicate)
{
CompileGoalArguments(((PrologCodePredicate)goal).Arguments);
CompileCall(goal);
}
}
private void CompileMethod(PrologCodeTerm method)
{
PrologCodePredicate predicate = (PrologCodePredicate)method;
_generator.EmitFCall(predicate.MethodInfo.PredicateName,
predicate.MethodInfo.MethodName,
predicate.MethodInfo.AssemblyName,
predicate.MethodInfo.Class);
if (_dictionary.InLastGoal)
{
if (_dictionary.GoalCount > 2)
{
_generator.Emit(OpCodes.Deallocate);
}
// Emit 'proceed'
_generator.EndProcedure();
}
}
private void CompileGoalVariable(PrologCodeVariable var, int i)
{
PrologVariableDictionaryEntry entry = _dictionary.GetVariable(var.Name);
if (entry.IsTemporary)
{
if (entry.TemporaryIndex != i)
{
ResolveConflicts(var, i);
}
if (entry.IsReferenced)
{
if (entry.TemporaryIndex != i)
{
_generator.Emit(OpCodes.Put_Value, X(entry.TemporaryIndex), X(i));
}
}
else
{
if (entry.TemporaryIndex != i)
{
_generator.Emit(OpCodes.Put_Variable, X(entry.TemporaryIndex), X(i));
}
else
{
_generator.Emit(OpCodes.Put_Variable, X(i), X(i));
}
entry.IsGlobal = true;
}
}
else
{
ResolveConflicts(var, i);
if (entry.IsReferenced)
{
if (entry.IsUnsafe && !entry.IsGlobal &&
_dictionary.InLastGoal)
{
_generator.Emit(OpCodes.Put_Unsafe_Value, Y(entry.PermanentIndex), X(i));
entry.IsUnsafe = false;
}
else
{
if (entry.TemporaryIndex != -1)
{
_generator.Emit(OpCodes.Put_Value, X(entry.TemporaryIndex), X(i));
}
else
{
_generator.Emit(OpCodes.Put_Value, Y(entry.PermanentIndex), X(i));
}
}
}
else
{
_generator.Emit(OpCodes.Put_Variable, Y(entry.PermanentIndex), X(i));
}
if (entry.TemporaryIndex == -1)
{
entry.TemporaryIndex = i;
}
else
{
// No
}
}
}
private void CompileGoalArguments(ArrayList arguments)
{
for (int i = 0; i < arguments.Count; i++)
{
PrologCodeTerm term = (PrologCodeTerm)arguments[i];
// TODO: check it's a nil atom then handle put conflicts
if (term is PrologCodeEmptyList)
{
ResolveConflicts(term, i);
_generator.Emit(OpCodes.Put_Constant, "[]", X(i));
}
else if (term is PrologCodeAtom)
{
// Handle put conflicts here...
ResolveConflicts(term, i);
if (term is PrologCodeConstantAtom)
{
_generator.Emit(OpCodes.Put_Constant, ((PrologCodeConstantAtom)term).Value, X(i));
}
else if (term is PrologCodeStringAtom)
{
_generator.Emit(OpCodes.Put_Constant, ((PrologCodeStringAtom)term).Value, X(i));
}
else if (term is PrologCodeIntegerAtom)
{
_generator.Emit(OpCodes.Put_Constant, ((PrologCodeIntegerAtom)term).Value.ToString(), X(i));
}
else if (term is PrologCodeFloatAtom)
{
_generator.Emit(OpCodes.Put_Constant, ((PrologCodeFloatAtom)term).Value.ToString(), X(i));
}
}
else if (term is PrologCodeVariable)
{
CompileGoalVariable((PrologCodeVariable)term, i);
}
else if (term is PrologCodePredicate || term is PrologCodeNonEmptyList)
{
ResolveConflicts(term, i);
CompileGoalRecord(term, i);
}
}
}
private bool ResolveConflicts(PrologCodeTerm term, int index)
{
PrologVariableDictionaryEntry entry = _dictionary.GetVariable(index);
if (_dictionary.CurrentGoalIndex != 1 || entry == null || entry.LastGoalArgument < index)
{
PrologRegisterTable.Instance.AllocateRegister(index);
return false;
}
if (term is PrologCodePredicate)
{
PrologCodePredicate predicate = (PrologCodePredicate)term;
for (int i = index + 1; i < entry.LastGoalArgument; i++)
{
if (predicate.Name == entry.Name &&
(_dictionary.GetVariable(i) == null || ResolveConflicts(term, i)))
{
entry.TemporaryIndex = i;
_generator.Emit(OpCodes.Put_Value, X(index), X(i));
return true;
}
}
// I WAS HERE
}
//return true; THIS WAS THERE
entry.TemporaryIndex = PrologRegisterTable.Instance.FindRegister();
_generator.Emit(OpCodes.Put_Value, X(index), X(entry.TemporaryIndex));
return true;
}
private int CompileGoalRecord(PrologCodeTerm term, int index)
{
ArrayList recs = new ArrayList();
int nRecs = 0;
ArrayList arguments = new ArrayList();
if (term is PrologCodeNonEmptyList)
{
PrologCodeNonEmptyList NEList = (PrologCodeNonEmptyList)term;
arguments.Add(NEList.Head);
arguments.Add(NEList.Tail);
}
else if (term is PrologCodePredicate)
{
arguments = ((PrologCodePredicate)term).Arguments;
}
for (int i = 0; i < arguments.Count; i++)
{
PrologCodeTerm r = (PrologCodeTerm)arguments[i];
if (r is PrologCodeNonEmptyList || r is PrologCodePredicate)
{
nRecs = recs.Add(CompileGoalRecord(r, -1));
}
}
if (index == -1)
{
index = PrologRegisterTable.Instance.FindRegister();
}
if (term is PrologCodeNonEmptyList)
{
_generator.Emit(OpCodes.Put_List, X(index));
}
else if(term is PrologCodePredicate)
{
PrologCodePredicate s = (PrologCodePredicate)term;
_generator.Emit(OpCodes.Put_Structure, s.Name + "/" + s.Arity, X(index));
}
nRecs = 0;
for (int i = 0; i < arguments.Count; i++)
{
PrologCodeTerm t = (PrologCodeTerm)arguments[i];
if (t is PrologCodeNilAtom || t is PrologCodeEmptyList)
{
_generator.Emit(OpCodes.Set_Constant, "[]");
}
else if (t is PrologCodeAtom)
{
if (t is PrologCodeConstantAtom)
{
_generator.Emit(OpCodes.Set_Constant, ((PrologCodeConstantAtom)t).Value);
}
else if (t is PrologCodeStringAtom)
{
_generator.Emit(OpCodes.Set_Constant, ((PrologCodeStringAtom)t).Value);
}
else if (t is PrologCodeIntegerAtom)
{
_generator.Emit(OpCodes.Set_Constant, ((PrologCodeIntegerAtom)t).Value.ToString());
}
else if (t is PrologCodeFloatAtom)
{
_generator.Emit(OpCodes.Set_Constant, ((PrologCodeFloatAtom)t).Value.ToString());
}
}
else if (t is PrologCodeVariable)
{
/* Compile Goal record variable */
CompileGoalRecordVariable((PrologCodeVariable)t);
}
else if (t is PrologCodePredicate || t is PrologCodeNonEmptyList)
{
_generator.Emit(OpCodes.Set_Value, X((int)recs[nRecs]));
PrologRegisterTable.Instance.FreeRegister((int)recs[nRecs]);
nRecs++;
}
}
return index;
}
private void CompileGoalRecordVariable(PrologCodeVariable var)
{
PrologVariableDictionaryEntry entry = _dictionary.GetVariable(var.Name);
if (entry.IsReferenced)
{
/* Compile build value here ... */
if (entry.IsTemporary)
{
if (entry.IsGlobal)
{
_generator.Emit(OpCodes.Set_Value, X(entry.TemporaryIndex));
}
else
{
_generator.Emit(OpCodes.Set_Local_Value, X(entry.TemporaryIndex));
entry.IsGlobal = true;
}
}
else
{
if (entry.IsGlobal)
{
if (entry.TemporaryIndex != -1)
{
_generator.Emit(OpCodes.Set_Value, X(entry.TemporaryIndex));
}
else
{
_generator.Emit(OpCodes.Set_Value, Y(entry.PermanentIndex));
}
}
else
{
if (entry.TemporaryIndex != -1)
{
_generator.Emit(OpCodes.Set_Local_Value, X(entry.TemporaryIndex));
}
else
{
_generator.Emit(OpCodes.Set_Local_Value, Y(entry.PermanentIndex));
}
}
}
}
else
{
if (entry.IsTemporary)
{
if (entry.Occurrences == 1)
{
_generator.Emit(OpCodes.Set_Void, "1");
}
else
{
_generator.Emit(OpCodes.Set_Variable, X(entry.TemporaryIndex));
}
}
else
{
_generator.Emit(OpCodes.Set_Variable, Y(entry.PermanentIndex));
}
entry.IsGlobal = true;
}
}
#endregion
#region predicate compilation
private void CompileCall(PrologCodeTerm p)
{
AMPredicateSet builtins = AMPredicateSet.Instance;
PrologCodePredicate predicate = (PrologCodePredicate)p;
if (builtins.IsBuiltin(predicate.Name, predicate.Arity))
{
CompileBuiltinPredicateCall(predicate);
}
else if (predicate.IsMethod)
{
CompileMethod(predicate);
}
else
{
CompilePrologPredicateCall(predicate);
}
}
private void CompileBuiltinPredicateCall(PrologCodePredicate p)
{
AMPredicateSet pset = AMPredicateSet.Instance;
_generator.EmitBCall((IAbstractMachinePredicate)pset.CreatePredicate(p.Name, p.Arity));
if (_dictionary.InLastGoal)
{
if (_dictionary.GoalCount > 2)
{
_generator.Emit(OpCodes.Deallocate);
}
// Emit 'proceed'
_generator.EndProcedure();
}
}
private void CompilePrologPredicateCall(PrologCodePredicate p)
{
if (_dictionary.InLastGoal)
{
if (_dictionary.GoalCount > 2)
{
_generator.Emit(OpCodes.Deallocate);
}
_generator.EmitExecute(p.Name, p.Arity);
}
else
{
_generator.EmitCall(p.Name, p.Arity);
}
}
#endregion
#region Helper methods
/* Initialize temporary goal variables in the dictionary */
private void InitializeGoalTemporaryVariables(PrologCodeTerm goal)
{
/* Free all registers */
PrologRegisterTable.Instance.FreeAllRegisters();
int reg = 0;
if (goal is PrologCodePredicate)
{
PrologCodePredicate g = (PrologCodePredicate)goal;
if (g.Arity > 0)
{
foreach (PrologCodeTerm var in g.Arguments)
{
if (var is PrologCodeVariable)
{
PrologVariableDictionaryEntry entry = _dictionary.GetVariable(((PrologCodeVariable)var).Name);
if (entry != null)
{
if (entry.IsTemporary && entry.TemporaryIndex == -1)
{
_dictionary.AllocateTemporaryVariable(entry, reg);
}
}
reg++;
}
}
}
}
}
#endregion
}
}
| |
#define SQLITE_ASCII
#define SQLITE_DISABLE_LFS
#define SQLITE_ENABLE_OVERSIZE_CELL_CHECK
#define SQLITE_MUTEX_OMIT
#define SQLITE_OMIT_AUTHORIZATION
#define SQLITE_OMIT_DEPRECATED
#define SQLITE_OMIT_GET_TABLE
#define SQLITE_OMIT_INCRBLOB
#define SQLITE_OMIT_LOOKASIDE
#define SQLITE_OMIT_SHARED_CACHE
#define SQLITE_OMIT_UTF16
#define SQLITE_OMIT_WAL
#define SQLITE_OS_WIN
#define SQLITE_SYSTEM_MALLOC
#define VDBE_PROFILE_OFF
#define WINDOWS_MOBILE
#define NDEBUG
#define _MSC_VER
#define YYFALLBACK
#define SQLITE_HAS_CODEC
#define NET_2_0
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
using u16 = System.UInt16;
using Pgno = System.UInt32;
namespace Community.CsharpSqlite
{
using sqlite3_int64 = System.Int64;
using sqlite3_stmt = Sqlite3.Vdbe;
using System.Security.Cryptography;
using System.IO;
public partial class Sqlite3
{
/*
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2010 Noah B Hart, Diego Torres
** C#-SQLite is an independent reimplementation of the SQLite software library
**
*************************************************************************
*/
/*
** SQLCipher
** crypto.c developed by Stephen Lombardo (Zetetic LLC)
** sjlombardo at zetetic dot net
** http://zetetic.net
**
** Copyright (c) 2009, ZETETIC LLC
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the ZETETIC LLC nor the
** names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''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 ZETETIC LLC BE LIABLE FOR ANY
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
*/
/* BEGIN CRYPTO */
#if SQLITE_HAS_CODEC
//#include <assert.h>
//#include <openssl/evp.h>
//#include <openssl/rand.h>
//#include <openssl/hmac.h>
//#include "sqliteInt.h"
//#include "btreeInt.h"
//#include "crypto.h"
#if CODEC_DEBUG || TRACE
//#define CODEC_TRACE(X) {printf X;fflush(stdout);}
static void CODEC_TRACE( string T, params object[] ap ) { if ( sqlite3PagerTrace )sqlite3DebugPrintf( T, ap ); }
#else
//#define CODEC_TRACE(X)
static void CODEC_TRACE( string T, params object[] ap )
{
}
#endif
//void sqlite3FreeCodecArg(void *pCodecArg);
public class cipher_ctx
{//typedef struct {
public string pass;
public int pass_sz;
public bool derive_key;
public byte[] key;
public int key_sz;
public byte[] iv;
public int iv_sz;
public ICryptoTransform encryptor;
public ICryptoTransform decryptor;
public cipher_ctx Copy()
{
cipher_ctx c = new cipher_ctx();
c.derive_key = derive_key;
c.pass = pass;
c.pass_sz = pass_sz;
if ( key != null )
{
c.key = new byte[key.Length];
key.CopyTo( c.key, 0 );
}
c.key_sz = key_sz;
if ( iv != null )
{
c.iv = new byte[iv.Length];
iv.CopyTo( c.iv, 0 );
}
c.iv_sz = iv_sz;
c.encryptor = encryptor;
c.decryptor = decryptor;
return c;
}
public void CopyTo( cipher_ctx ct )
{
ct.derive_key = derive_key;
ct.pass = pass;
ct.pass_sz = pass_sz;
if ( key != null )
{
ct.key = new byte[key.Length];
key.CopyTo( ct.key, 0 );
}
ct.key_sz = key_sz;
if ( iv != null )
{
ct.iv = new byte[iv.Length];
iv.CopyTo( ct.iv, 0 );
}
ct.iv_sz = iv_sz;
ct.encryptor = encryptor;
ct.decryptor = decryptor;
}
}
public class codec_ctx
{//typedef struct {
public int mode_rekey;
public byte[] buffer;
public Btree pBt;
public cipher_ctx read_ctx;
public cipher_ctx write_ctx;
public codec_ctx Copy()
{
codec_ctx c = new codec_ctx();
c.mode_rekey = mode_rekey;
c.buffer = sqlite3MemMalloc( buffer.Length );
c.pBt = pBt;
if ( read_ctx != null )
c.read_ctx = read_ctx.Copy();
if ( write_ctx != null )
c.write_ctx = write_ctx.Copy();
return c;
}
}
const int FILE_HEADER_SZ = 16; //#define FILE_HEADER_SZ 16
const string CIPHER = "aes-256-cbc"; //#define CIPHER "aes-256-cbc"
const int CIPHER_DECRYPT = 0; //#define CIPHER_DECRYPT 0
const int CIPHER_ENCRYPT = 1; //#define CIPHER_ENCRYPT 1
#if NET_2_0
static RijndaelManaged Aes = new RijndaelManaged();
#else
static AesManaged Aes = new AesManaged();
#endif
/* BEGIN CRYPTO */
static void sqlite3pager_get_codec( Pager pPager, ref codec_ctx ctx )
{
ctx = pPager.pCodec;
}
static int sqlite3pager_is_mj_pgno( Pager pPager, Pgno pgno )
{
return ( PAGER_MJ_PGNO( pPager ) == pgno ) ? 1 : 0;
}
static sqlite3_file sqlite3Pager_get_fd( Pager pPager )
{
return ( isOpen( pPager.fd ) ) ? pPager.fd : null;
}
static void sqlite3pager_sqlite3PagerSetCodec(
Pager pPager,
dxCodec xCodec,
dxCodecSizeChng xCodecSizeChng,
dxCodecFree xCodecFree,
codec_ctx pCodec
)
{
sqlite3PagerSetCodec( pPager, xCodec, xCodecSizeChng, xCodecFree, pCodec );
}
/* END CRYPTO */
//static void activate_openssl() {
// if(EVP_get_cipherbyname(CIPHER) == null) {
// OpenSSL_add_all_algorithms();
// }
//}
/**
* Free and wipe memory
* If ptr is not null memory will be freed.
* If sz is greater than zero, the memory will be overwritten with zero before it is freed
*/
static void codec_free( ref byte[] ptr, int sz )
{
if ( ptr != null )
{
if ( sz > 0 )
Array.Clear( ptr, 0, sz );//memset( ptr, 0, sz );
sqlite3_free( ref ptr );
}
}
/**
* Set the raw password / key data for a cipher context
*
* returns SQLITE_OK if assignment was successfull
* returns SQLITE_NOMEM if an error occured allocating memory
* returns SQLITE_ERROR if the key couldn't be set because the pass was null or size was zero
*/
static int cipher_ctx_set_pass( cipher_ctx ctx, string zKey, int nKey )
{
ctx.pass = null; // codec_free( ctx.pass, ctx.pass_sz );
ctx.pass_sz = nKey;
if ( !String.IsNullOrEmpty( zKey ) && nKey > 0 )
{
//ctx.pass = sqlite3Malloc(nKey);
//if(ctx.pass == null) return SQLITE_NOMEM;
ctx.pass = zKey;//memcpy(ctx.pass, zKey, nKey);
return SQLITE_OK;
}
return SQLITE_ERROR;
}
/**
* Initialize a new cipher_ctx struct. This function will allocate memory
* for the cipher context and for the key
*
* returns SQLITE_OK if initialization was successful
* returns SQLITE_NOMEM if an error occured allocating memory
*/
static int cipher_ctx_init( ref cipher_ctx iCtx )
{
iCtx = new cipher_ctx();
//iCtx = sqlite3Malloc( sizeof( cipher_ctx ) );
//ctx = *iCtx;
//if ( ctx == null ) return SQLITE_NOMEM;
//memset( ctx, 0, sizeof( cipher_ctx ) );
//ctx.key = sqlite3Malloc( EVP_MAX_KEY_LENGTH );
//if ( ctx.key == null ) return SQLITE_NOMEM;
return SQLITE_OK;
}
/**
* free and wipe memory associated with a cipher_ctx
*/
static void cipher_ctx_free( ref cipher_ctx ictx )
{
cipher_ctx ctx = ictx;
CODEC_TRACE( "cipher_ctx_free: entered ictx=%d\n", ictx );
ctx.pass = null;//codec_free(ctx.pass, ctx.pass_sz);
if ( ctx.key != null )
Array.Clear( ctx.key, 0, ctx.key.Length );//codec_free(ctx.key, ctx.key_sz);
if ( ctx.iv != null )
Array.Clear( ctx.iv, 0, ctx.iv.Length );
ictx = new cipher_ctx();// codec_free( ref ctx, sizeof( cipher_ctx ) );
}
/**
* Copy one cipher_ctx to another. For instance, assuming that read_ctx is a
* fully initialized context, you could copy it to write_ctx and all yet data
* and pass information across
*
* returns SQLITE_OK if initialization was successful
* returns SQLITE_NOMEM if an error occured allocating memory
*/
static int cipher_ctx_copy( cipher_ctx target, cipher_ctx source )
{
//byte[] key = target.key;
CODEC_TRACE( "cipher_ctx_copy: entered target=%d, source=%d\n", target, source );
//codec_free(target.pass, target.pass_sz);
source.CopyTo( target );//memcpy(target, source, sizeof(cipher_ctx);
//target.key = key; //restore pointer to previously allocated key data
//memcpy(target.key, source.key, EVP_MAX_KEY_LENGTH);
//target.pass = sqlite3Malloc(source.pass_sz);
//if(target.pass == null) return SQLITE_NOMEM;
//memcpy(target.pass, source.pass, source.pass_sz);
return SQLITE_OK;
}
/**
* Compare one cipher_ctx to another.
*
* returns 0 if all the parameters (except the derived key data) are the same
* returns 1 otherwise
*/
static int cipher_ctx_cmp( cipher_ctx c1, cipher_ctx c2 )
{
CODEC_TRACE( "cipher_ctx_cmp: entered c1=%d c2=%d\n", c1, c2 );
if ( c1.key_sz == c2.key_sz
&& c1.pass_sz == c2.pass_sz
&& c1.pass == c2.pass
)
return 0;
return 1;
}
/**
* Free and wipe memory associated with a cipher_ctx, including the allocated
* read_ctx and write_ctx.
*/
static void codec_ctx_free( ref codec_ctx iCtx )
{
codec_ctx ctx = iCtx;
CODEC_TRACE( "codec_ctx_free: entered iCtx=%d\n", iCtx );
cipher_ctx_free( ref ctx.read_ctx );
cipher_ctx_free( ref ctx.write_ctx );
iCtx = new codec_ctx();//codec_free(ctx, sizeof(codec_ctx);
}
/**
* Derive an encryption key for a cipher contex key based on the raw password.
*
* If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill
* the key space (i.e 64 hex chars for a 256 bit key) then the key data will be used directly.
*
* Otherwise, a key data will be derived using PBKDF2
*
* returns SQLITE_OK if initialization was successful
* returns SQLITE_NOMEM if the key could't be derived (for instance if pass is null or pass_sz is 0)
*/
static int codec_key_derive( codec_ctx ctx, cipher_ctx c_ctx )
{
CODEC_TRACE( "codec_key_derive: entered c_ctx.pass=%s, c_ctx.pass_sz=%d ctx.iv=%d ctx.iv_sz=%d c_ctx.kdf_iter=%d c_ctx.key_sz=%d\n",
c_ctx.pass, c_ctx.pass_sz, c_ctx.iv, c_ctx.iv_sz, c_ctx.key_sz );
if ( c_ctx.pass != null && c_ctx.pass_sz > 0 )
{ // if pass is not null
if ( ( c_ctx.pass_sz == ( c_ctx.key_sz * 2 ) + 3 ) && c_ctx.pass.StartsWith( "x'", StringComparison.InvariantCultureIgnoreCase ) )
{
int n = c_ctx.pass_sz - 3; /* adjust for leading x' and tailing ' */
string z = c_ctx.pass.Substring( 2 );// + 2; /* adjust lead offset of x' */
CODEC_TRACE( "codec_key_derive: deriving key from hex\n" );
c_ctx.key = sqlite3HexToBlob( null, z, n );
}
else
{
CODEC_TRACE( "codec_key_derive: deriving key using AES256\n" );
Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes( c_ctx.pass, c_ctx.iv, 2010 );
c_ctx.key_sz = 32;
c_ctx.key = k1.GetBytes( c_ctx.key_sz );
}
#if NET_2_0
Aes.BlockSize = 0x80;
Aes.FeedbackSize = 8;
Aes.KeySize = 0x100;
Aes.Mode = CipherMode.CBC;
#endif
c_ctx.encryptor = Aes.CreateEncryptor( c_ctx.key, c_ctx.iv );
c_ctx.decryptor = Aes.CreateDecryptor( c_ctx.key, c_ctx.iv );
return SQLITE_OK;
};
return SQLITE_ERROR;
}
/*
* ctx - codec context
* pgno - page number in database
* size - size in bytes of input and output buffers
* mode - 1 to encrypt, 0 to decrypt
* in - pointer to input bytes
* out - pouter to output bytes
*/
static int codec_cipher( cipher_ctx ctx, Pgno pgno, int mode, int size, byte[] bIn, byte[] bOut )
{
//int iv;
//int tmp_csz, csz;
CODEC_TRACE( "codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size );
/* just copy raw data from in to out when key size is 0
* i.e. during a rekey of a plaintext database */
if ( ctx.key_sz == 0 )
{
Array.Copy( bIn, bOut, bIn.Length );//memcpy(out, in, size);
return SQLITE_OK;
}
MemoryStream dataStream = new MemoryStream();
CryptoStream encryptionStream;
if ( mode == CIPHER_ENCRYPT )
{
encryptionStream = new CryptoStream( dataStream, Aes.CreateEncryptor( ctx.key, ctx.iv ), CryptoStreamMode.Write );
}
else
{
encryptionStream = new CryptoStream( dataStream, Aes.CreateDecryptor( ctx.key, ctx.iv ), CryptoStreamMode.Write );
}
/* Fix for .... :)
if ( mode == CIPHER_ENCRYPT )
{
encryptionStream = new CryptoStream( dataStream, ctx.encryptor, CryptoStreamMode.Write );
}
else
{
encryptionStream = new CryptoStream( dataStream, ctx.decryptor, CryptoStreamMode.Write );
}
*/
encryptionStream.Write( bIn, 0, size );
encryptionStream.FlushFinalBlock();
dataStream.Position = 0;
dataStream.Read( bOut, 0, (int)dataStream.Length );
encryptionStream.Close();
dataStream.Close();
/**/
// Thanks for [email protected]
/*
if ( mode == CIPHER_ENCRYPT ) {
exor(bIn, bOut, ctx.key);
}else{
dxor(bIn, bOut, ctx.key);
}
/**/
return SQLITE_OK;
}
public static void exor(byte[] data, byte[] result, byte[] Keys)
{
for(int i = 0; i < data.Length; i++)
{
result[i] = (byte) (data[i] ^ Keys[i % Keys.Length]);
}
}
public static void dxor(byte[] data, byte[] result, byte[] Keys)
{
for (int i = 0; i < data.Length; i++)
{
result[i] = (byte)(Keys[i % Keys.Length] ^ data[i]);
}
}
/**
*
* when for_ctx == 0 then it will change for read
* when for_ctx == 1 then it will change for write
* when for_ctx == 2 then it will change for both
*/
static int codec_set_cipher_name( sqlite3 db, int nDb, string cipher_name, int for_ctx )
{
Db pDb = db.aDb[nDb];
CODEC_TRACE( "codec_set_cipher_name: entered db=%d nDb=%d cipher_name=%s for_ctx=%d\n", db, nDb, cipher_name, for_ctx );
if ( pDb.pBt != null )
{
codec_ctx ctx = null;
cipher_ctx c_ctx;
sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx );
c_ctx = for_ctx != 0 ? ctx.write_ctx : ctx.read_ctx;
c_ctx.derive_key = true;
if ( for_ctx == 2 )
cipher_ctx_copy( for_ctx != 0 ? ctx.read_ctx : ctx.write_ctx, c_ctx );
return SQLITE_OK;
}
return SQLITE_ERROR;
}
static int codec_set_pass_key( sqlite3 db, int nDb, string zKey, int nKey, int for_ctx )
{
Db pDb = db.aDb[nDb];
CODEC_TRACE( "codec_set_pass_key: entered db=%d nDb=%d cipher_name=%s nKey=%d for_ctx=%d\n", db, nDb, zKey, nKey, for_ctx );
if ( pDb.pBt != null )
{
codec_ctx ctx = null;
cipher_ctx c_ctx;
sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx );
c_ctx = for_ctx != 0 ? ctx.write_ctx : ctx.read_ctx;
cipher_ctx_set_pass( c_ctx, zKey, nKey );
c_ctx.derive_key = true;
if ( for_ctx == 2 )
cipher_ctx_copy( for_ctx != 0 ? ctx.read_ctx : ctx.write_ctx, c_ctx );
return SQLITE_OK;
}
return SQLITE_ERROR;
}
/*
* sqlite3Codec can be called in multiple modes.
* encrypt mode - expected to return a pointer to the
* encrypted data without altering pData.
* decrypt mode - expected to return a pointer to pData, with
* the data decrypted in the input buffer
*/
static byte[] sqlite3Codec( codec_ctx iCtx, byte[] data, Pgno pgno, int mode )
{
codec_ctx ctx = (codec_ctx)iCtx;
int pg_sz = sqlite3BtreeGetPageSize( ctx.pBt );
int offset = 0;
byte[] pData = data;
CODEC_TRACE( "sqlite3Codec: entered pgno=%d, mode=%d, ctx.mode_rekey=%d, pg_sz=%d\n", pgno, mode, ctx.mode_rekey, pg_sz );
/* derive key on first use if necessary */
if ( ctx.read_ctx.derive_key )
{
codec_key_derive( ctx, ctx.read_ctx );
ctx.read_ctx.derive_key = false;
}
if ( ctx.write_ctx.derive_key )
{
if ( cipher_ctx_cmp( ctx.write_ctx, ctx.read_ctx ) == 0 )
{
cipher_ctx_copy( ctx.write_ctx, ctx.read_ctx ); // the relevant parameters are the same, just copy read key
}
else
{
codec_key_derive( ctx, ctx.write_ctx );
ctx.write_ctx.derive_key = false;
}
}
// bug from csharp project port
// fix from original: https://github.com/sqlcipher/sqlcipher/blob/master/src/crypto.c
// original
// if(pgno == 1) offset = FILE_HEADER_SZ; /* adjust starting pointers in data page for header offset on first page*/
CODEC_TRACE( "sqlite3Codec: switch mode=%d offset=%d\n", mode, offset );
if ( ctx.buffer.Length != pg_sz )
ctx.buffer = sqlite3MemMalloc( pg_sz );
switch ( mode )
{
case SQLITE_DECRYPT:
// original
// if(pgno == 1) memcpy(buffer, SQLITE_FILE_HEADER, FILE_HEADER_SZ); /* copy file header to the first 16 bytes of the page */
// rc = sqlcipher_page_cipher(ctx, CIPHER_READ_CTX, pgno, CIPHER_DECRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
// if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
// memcpy(pData, buffer, page_sz); /* copy buffer data back to pData and return */
// return pData;
// c-sharp project
// codec_cipher( ctx.read_ctx, pgno, CIPHER_DECRYPT, pg_sz, pData, ctx.buffer );
// if ( pgno == 1 )
// Buffer.BlockCopy( Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER ), 0, ctx.buffer, 0, FILE_HEADER_SZ );// memcpy( ctx.buffer, SQLITE_FILE_HEADER, FILE_HEADER_SZ ); /* copy file header to the first 16 bytes of the page */
// Buffer.BlockCopy( ctx.buffer, 0, pData, 0, pg_sz ); //memcpy( pData, ctx.buffer, pg_sz ); /* copy buffer data back to pData and return */
// return pData;
// my fix:
if ( pgno == 1 ){
byte[] hdr = Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER );
Buffer.BlockCopy( hdr, 0, ctx.buffer, 0, FILE_HEADER_SZ );// memcpy( ctx.buffer, SQLITE_FILE_HEADER, FILE_HEADER_SZ ); /* copy file header to the first 16 bytes of the page */
byte[] tmpOut = new byte[pg_sz-FILE_HEADER_SZ];
byte[] tmpData = new byte[pg_sz-FILE_HEADER_SZ];
Buffer.BlockCopy( pData, FILE_HEADER_SZ, tmpData, 0, pg_sz-FILE_HEADER_SZ );
codec_cipher( ctx.read_ctx, pgno, CIPHER_DECRYPT, pg_sz-FILE_HEADER_SZ, tmpData, tmpOut );
Buffer.BlockCopy( tmpOut, 0, ctx.buffer, FILE_HEADER_SZ, pg_sz-FILE_HEADER_SZ );
Buffer.BlockCopy( ctx.buffer, 0, pData, 0, pg_sz );
}
else{
codec_cipher( ctx.read_ctx, pgno, CIPHER_DECRYPT, pg_sz, pData, ctx.buffer );
Buffer.BlockCopy( ctx.buffer, 0, pData, 0, pg_sz );
}
return pData;
case SQLITE_ENCRYPT_WRITE_CTX: /* encrypt */
// original
// if(pgno == 1) memcpy(buffer, kdf_salt, FILE_HEADER_SZ); /* copy salt to output buffer */
// rc = sqlcipher_page_cipher(ctx, CIPHER_WRITE_CTX, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
// if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
// return buffer; /* return persistent buffer data, pData remains intact */
// c-sharp project
// if ( pgno == 1 )
// Buffer.BlockCopy( ctx.write_ctx.iv, 0, ctx.buffer, 0, FILE_HEADER_SZ );//memcpy( ctx.buffer, ctx.iv, FILE_HEADER_SZ ); /* copy salt to output buffer */
// codec_cipher( ctx.write_ctx, pgno, CIPHER_ENCRYPT, pg_sz, pData, ctx.buffer );
// return ctx.buffer; /* return persistent buffer data, pData remains intact */
// my fix
if ( pgno == 1 ){
Buffer.BlockCopy( ctx.write_ctx.iv, 0, ctx.buffer, 0, FILE_HEADER_SZ );//memcpy( ctx.buffer, ctx.iv, FILE_HEADER_SZ ); /* copy salt to output buffer */
byte[] tmpOut = new byte[pg_sz-FILE_HEADER_SZ];
byte[] tmpData = new byte[pg_sz-FILE_HEADER_SZ];
Buffer.BlockCopy( pData, FILE_HEADER_SZ, tmpData, 0, pg_sz-FILE_HEADER_SZ );
codec_cipher( ctx.write_ctx, pgno, CIPHER_ENCRYPT, pg_sz-FILE_HEADER_SZ, tmpData, tmpOut );
Buffer.BlockCopy( tmpOut, 0, ctx.buffer, FILE_HEADER_SZ, pg_sz-FILE_HEADER_SZ );
}
else{
codec_cipher( ctx.write_ctx, pgno, CIPHER_ENCRYPT, pg_sz, pData, ctx.buffer );
}
return ctx.buffer; /* return persistent buffer data, pData remains intact */
case SQLITE_ENCRYPT_READ_CTX:
// original
// if(pgno == 1) memcpy(buffer, kdf_salt, FILE_HEADER_SZ); /* copy salt to output buffer */
// rc = sqlcipher_page_cipher(ctx, CIPHER_READ_CTX, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
// if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
// return buffer; /* return persistent buffer data, pData remains intact */
// c-sharp project
// if ( pgno == 1 )
// Buffer.BlockCopy( ctx.read_ctx.iv, 0, ctx.buffer, 0, FILE_HEADER_SZ );//memcpy( ctx.buffer, ctx.iv, FILE_HEADER_SZ ); /* copy salt to output buffer */
// codec_cipher( ctx.read_ctx, pgno, CIPHER_ENCRYPT, pg_sz, pData, ctx.buffer );
// return ctx.buffer; /* return persistent buffer data, pData remains intact */
// my fix
if ( pgno == 1 ){
Buffer.BlockCopy( ctx.read_ctx.iv, 0, ctx.buffer, 0, FILE_HEADER_SZ );//memcpy( ctx.buffer, ctx.iv, FILE_HEADER_SZ ); /* copy salt to output buffer */
byte[] tmpOut = new byte[pg_sz-FILE_HEADER_SZ];
byte[] tmpData = new byte[pg_sz-FILE_HEADER_SZ];
Buffer.BlockCopy( pData, FILE_HEADER_SZ, tmpData, 0, pg_sz-FILE_HEADER_SZ );
codec_cipher( ctx.read_ctx, pgno, CIPHER_ENCRYPT, pg_sz-FILE_HEADER_SZ, tmpData, tmpOut );
Buffer.BlockCopy( tmpOut, 0, ctx.buffer, FILE_HEADER_SZ, pg_sz-FILE_HEADER_SZ );
}
else{
codec_cipher( ctx.read_ctx, pgno, CIPHER_ENCRYPT, pg_sz, pData, ctx.buffer );
}
return ctx.buffer; /* return persistent buffer data, pData remains intact */
default:
return pData;
}
}
static int sqlite3CodecAttach( sqlite3 db, int nDb, string zKey, int nKey )
{
Db pDb = db.aDb[nDb];
CODEC_TRACE( "sqlite3CodecAttach: entered nDb=%d zKey=%s, nKey=%d\n", nDb, zKey, nKey );
//activate_openssl();
if ( zKey != null && pDb.pBt != null )
{
Aes.KeySize = 256;
#if !SQLITE_SILVERLIGHT
Aes.Padding = PaddingMode.None;
#endif
codec_ctx ctx;
int rc;
//Pager pPager = pDb.pBt.pBt.pPager;
//sqlite3_file fd;
ctx = new codec_ctx();//sqlite3Malloc(sizeof(codec_ctx);
//if(ctx == null) return SQLITE_NOMEM;
//memset(ctx, 0, sizeof(codec_ctx); /* initialize all pointers and values to 0 */
ctx.pBt = pDb.pBt; /* assign pointer to database btree structure */
if ( ( rc = cipher_ctx_init( ref ctx.read_ctx ) ) != SQLITE_OK )
return rc;
if ( ( rc = cipher_ctx_init( ref ctx.write_ctx ) ) != SQLITE_OK )
return rc;
/* pre-allocate a page buffer of PageSize bytes. This will
be used as a persistent buffer for encryption and decryption
operations to avoid overhead of multiple memory allocations*/
ctx.buffer = sqlite3MemMalloc( sqlite3BtreeGetPageSize( ctx.pBt ) );//sqlite3Malloc(sqlite3BtreeGetPageSize(ctx.pBt);
//if(ctx.buffer == null) return SQLITE_NOMEM;
/* allocate space for salt data. Then read the first 16 bytes header as the salt for the key derivation */
ctx.read_ctx.iv_sz = FILE_HEADER_SZ;
ctx.read_ctx.iv = new byte[ctx.read_ctx.iv_sz];//sqlite3Malloc( ctx.iv_sz );
Buffer.BlockCopy( Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER ), 0, ctx.read_ctx.iv, 0, FILE_HEADER_SZ );
sqlite3pager_sqlite3PagerSetCodec( sqlite3BtreePager( pDb.pBt ), sqlite3Codec, null, sqlite3FreeCodecArg, ctx );
codec_set_cipher_name( db, nDb, CIPHER, 0 );
codec_set_pass_key( db, nDb, zKey, nKey, 0 );
cipher_ctx_copy( ctx.write_ctx, ctx.read_ctx );
//sqlite3BtreeSetPageSize( ctx.pBt, sqlite3BtreeGetPageSize( ctx.pBt ), MAX_IV_LENGTH, 0 );
}
return SQLITE_OK;
}
static void sqlite3FreeCodecArg( ref codec_ctx pCodecArg )
{
if ( pCodecArg == null )
return;
codec_ctx_free( ref pCodecArg ); // wipe and free allocated memory for the context
}
static void sqlite3_activate_see( string zPassword )
{
/* do nothing, security enhancements are always active */
}
static public int sqlite3_key( sqlite3 db, string pKey, int nKey )
{
CODEC_TRACE( "sqlite3_key: entered db=%d pKey=%s nKey=%d\n", db, pKey, nKey );
/* attach key if db and pKey are not null and nKey is > 0 */
if ( db != null && pKey != null )
{
sqlite3CodecAttach( db, 0, pKey, nKey ); // operate only on the main db
//
// If we are reopening an existing database, redo the header information setup
//
BtShared pBt = db.aDb[0].pBt.pBt;
byte[] zDbHeader = sqlite3MemMalloc( (int)pBt.pageSize );// pBt.pPager.pCodec.buffer;
sqlite3PagerReadFileheader( pBt.pPager, zDbHeader.Length, zDbHeader );
if ( sqlite3Get4byte( zDbHeader ) > 0 ) // Existing Database, need to reset some values
{
CODEC2( pBt.pPager, zDbHeader, 1, SQLITE_DECRYPT, ref zDbHeader );
byte nReserve = zDbHeader[20];
pBt.pageSize = (uint)( ( zDbHeader[16] << 8 ) | ( zDbHeader[17] << 16 ) );
if ( pBt.pageSize < 512 || pBt.pageSize > SQLITE_MAX_PAGE_SIZE
|| ( ( pBt.pageSize - 1 ) & pBt.pageSize ) != 0 )
pBt.pageSize = 0;
pBt.pageSizeFixed = true;
#if !SQLITE_OMIT_AUTOVACUUM
pBt.autoVacuum = sqlite3Get4byte( zDbHeader, 36 + 4 * 4 ) != 0;
pBt.incrVacuum = sqlite3Get4byte( zDbHeader, 36 + 7 * 4 ) != 0;
#endif
sqlite3PagerSetPagesize( pBt.pPager, ref pBt.pageSize, nReserve );
pBt.usableSize = (u16)( pBt.pageSize - nReserve );
}
return SQLITE_OK;
}
return SQLITE_ERROR;
}
/* sqlite3_rekey
** Given a database, this will reencrypt the database using a new key.
** There are two possible modes of operation. The first is rekeying
** an existing database that was not previously encrypted. The second
** is to change the key on an existing database.
**
** The proposed logic for this function follows:
** 1. Determine if there is already a key present
** 2. If there is NOT already a key present, create one and attach a codec (key would be null)
** 3. Initialize a ctx.rekey parameter of the codec
**
** Note: this will require modifications to the sqlite3Codec to support rekey
**
*/
public static int sqlite3_rekey( sqlite3 db, string pKey, int nKey )
{
CODEC_TRACE( "sqlite3_rekey: entered db=%d pKey=%s, nKey=%d\n", db, pKey, nKey );
//activate_openssl();
if ( db != null && pKey != null )
{
Db pDb = db.aDb[0];
CODEC_TRACE( "sqlite3_rekey: database pDb=%d\n", pDb );
if ( pDb.pBt != null )
{
codec_ctx ctx = null;
int rc;
Pgno page_count = 0;
Pgno pgno;
PgHdr page = null;
Pager pPager = pDb.pBt.pBt.pPager;
sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx );
if ( ctx == null )
{
CODEC_TRACE( "sqlite3_rekey: no codec attached to db, attaching now\n" );
/* there was no codec attached to this database,so attach one now with a null password */
sqlite3CodecAttach( db, 0, pKey, nKey );
sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx );
/* prepare this setup as if it had already been initialized */
Buffer.BlockCopy( Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER ), 0, ctx.read_ctx.iv, 0, FILE_HEADER_SZ );
ctx.read_ctx.key_sz = ctx.read_ctx.iv_sz = ctx.read_ctx.pass_sz = 0;
}
//if ( ctx.read_ctx.iv_sz != ctx.write_ctx.iv_sz )
//{
// string error = "";
// CODEC_TRACE( "sqlite3_rekey: updating page size for iv_sz change from %d to %d\n", ctx.read_ctx.iv_sz, ctx.write_ctx.iv_sz );
// db.nextPagesize = sqlite3BtreeGetPageSize( pDb.pBt );
// pDb.pBt.pBt.pageSizeFixed = false; /* required for sqlite3BtreeSetPageSize to modify pagesize setting */
// sqlite3BtreeSetPageSize( pDb.pBt, db.nextPagesize, MAX_IV_LENGTH, 0 );
// sqlite3RunVacuum( ref error, db );
//}
codec_set_pass_key( db, 0, pKey, nKey, 1 );
ctx.mode_rekey = 1;
/* do stuff here to rewrite the database
** 1. Create a transaction on the database
** 2. Iterate through each page, reading it and then writing it.
** 3. If that goes ok then commit and put ctx.rekey into ctx.key
** note: don't deallocate rekey since it may be used in a subsequent iteration
*/
rc = sqlite3BtreeBeginTrans( pDb.pBt, 1 ); /* begin write transaction */
sqlite3PagerPagecount( pPager, out page_count );
for ( pgno = 1; rc == SQLITE_OK && pgno <= page_count; pgno++ )
{ /* pgno's start at 1 see pager.c:pagerAcquire */
if ( 0 == sqlite3pager_is_mj_pgno( pPager, pgno ) )
{ /* skip this page (see pager.c:pagerAcquire for reasoning) */
rc = sqlite3PagerGet( pPager, pgno, ref page );
if ( rc == SQLITE_OK )
{ /* write page see pager_incr_changecounter for example */
rc = sqlite3PagerWrite( page );
//printf("sqlite3PagerWrite(%d)\n", pgno);
if ( rc == SQLITE_OK )
{
sqlite3PagerUnref( page );
}
}
}
}
/* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */
if ( rc == SQLITE_OK )
{
CODEC_TRACE( "sqlite3_rekey: committing\n" );
db.nextPagesize = sqlite3BtreeGetPageSize( pDb.pBt );
rc = sqlite3BtreeCommit( pDb.pBt );
if ( ctx != null )
cipher_ctx_copy( ctx.read_ctx, ctx.write_ctx );
}
else
{
CODEC_TRACE( "sqlite3_rekey: rollback\n" );
sqlite3BtreeRollback( pDb.pBt );
}
ctx.mode_rekey = 0;
}
return SQLITE_OK;
}
return SQLITE_ERROR;
}
static void sqlite3CodecGetKey( sqlite3 db, int nDb, out string zKey, out int nKey )
{
Db pDb = db.aDb[nDb];
CODEC_TRACE( "sqlite3CodecGetKey: entered db=%d, nDb=%d\n", db, nDb );
if ( pDb.pBt != null )
{
codec_ctx ctx = null;
sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx );
if ( ctx != null )
{ /* if the codec has an attached codec_context user the raw key data */
zKey = ctx.read_ctx.pass;
nKey = ctx.read_ctx.pass_sz;
return;
}
}
zKey = null;
nKey = 0;
}
/* END CRYPTO */
#endif
const int SQLITE_ENCRYPT_WRITE_CTX = 6; /* Encode page */
const int SQLITE_ENCRYPT_READ_CTX = 7; /* Encode page */
const int SQLITE_DECRYPT = 3; /* Decode page */
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.TextToSpeech.V1Beta1
{
/// <summary>Settings for <see cref="TextToSpeechClient"/> instances.</summary>
public sealed partial class TextToSpeechSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="TextToSpeechSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="TextToSpeechSettings"/>.</returns>
public static TextToSpeechSettings GetDefault() => new TextToSpeechSettings();
/// <summary>Constructs a new <see cref="TextToSpeechSettings"/> object with default settings.</summary>
public TextToSpeechSettings()
{
}
private TextToSpeechSettings(TextToSpeechSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListVoicesSettings = existing.ListVoicesSettings;
SynthesizeSpeechSettings = existing.SynthesizeSpeechSettings;
OnCopy(existing);
}
partial void OnCopy(TextToSpeechSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TextToSpeechClient.ListVoices</c> and <c>TextToSpeechClient.ListVoicesAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 300 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListVoicesSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(300000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TextToSpeechClient.SynthesizeSpeech</c> and <c>TextToSpeechClient.SynthesizeSpeechAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 300 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings SynthesizeSpeechSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(300000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="TextToSpeechSettings"/> object.</returns>
public TextToSpeechSettings Clone() => new TextToSpeechSettings(this);
}
/// <summary>
/// Builder class for <see cref="TextToSpeechClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class TextToSpeechClientBuilder : gaxgrpc::ClientBuilderBase<TextToSpeechClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public TextToSpeechSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public TextToSpeechClientBuilder()
{
UseJwtAccessWithScopes = TextToSpeechClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref TextToSpeechClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<TextToSpeechClient> task);
/// <summary>Builds the resulting client.</summary>
public override TextToSpeechClient Build()
{
TextToSpeechClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<TextToSpeechClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<TextToSpeechClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private TextToSpeechClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return TextToSpeechClient.Create(callInvoker, Settings);
}
private async stt::Task<TextToSpeechClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return TextToSpeechClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => TextToSpeechClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => TextToSpeechClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => TextToSpeechClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>TextToSpeech client wrapper, for convenient use.</summary>
/// <remarks>
/// Service that implements Google Cloud Text-to-Speech API.
/// </remarks>
public abstract partial class TextToSpeechClient
{
/// <summary>
/// The default endpoint for the TextToSpeech service, which is a host of "texttospeech.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "texttospeech.googleapis.com:443";
/// <summary>The default TextToSpeech scopes.</summary>
/// <remarks>
/// The default TextToSpeech scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="TextToSpeechClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="TextToSpeechClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="TextToSpeechClient"/>.</returns>
public static stt::Task<TextToSpeechClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new TextToSpeechClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="TextToSpeechClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="TextToSpeechClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="TextToSpeechClient"/>.</returns>
public static TextToSpeechClient Create() => new TextToSpeechClientBuilder().Build();
/// <summary>
/// Creates a <see cref="TextToSpeechClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="TextToSpeechSettings"/>.</param>
/// <returns>The created <see cref="TextToSpeechClient"/>.</returns>
internal static TextToSpeechClient Create(grpccore::CallInvoker callInvoker, TextToSpeechSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
TextToSpeech.TextToSpeechClient grpcClient = new TextToSpeech.TextToSpeechClient(callInvoker);
return new TextToSpeechClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC TextToSpeech client</summary>
public virtual TextToSpeech.TextToSpeechClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ListVoicesResponse ListVoices(ListVoicesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListVoicesResponse> ListVoicesAsync(ListVoicesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListVoicesResponse> ListVoicesAsync(ListVoicesRequest request, st::CancellationToken cancellationToken) =>
ListVoicesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="languageCode">
/// Optional. Recommended.
/// [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
/// If not specified, the API will return all supported voices.
/// If specified, the ListVoices call will only return voices that can be used
/// to synthesize this language_code. For example, if you specify `"en-NZ"`,
/// all `"en-NZ"` voices will be returned. If you specify `"no"`, both
/// `"no-\*"` (Norwegian) and `"nb-\*"` (Norwegian Bokmal) voices will be
/// returned.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ListVoicesResponse ListVoices(string languageCode, gaxgrpc::CallSettings callSettings = null) =>
ListVoices(new ListVoicesRequest
{
LanguageCode = languageCode ?? "",
}, callSettings);
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="languageCode">
/// Optional. Recommended.
/// [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
/// If not specified, the API will return all supported voices.
/// If specified, the ListVoices call will only return voices that can be used
/// to synthesize this language_code. For example, if you specify `"en-NZ"`,
/// all `"en-NZ"` voices will be returned. If you specify `"no"`, both
/// `"no-\*"` (Norwegian) and `"nb-\*"` (Norwegian Bokmal) voices will be
/// returned.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListVoicesResponse> ListVoicesAsync(string languageCode, gaxgrpc::CallSettings callSettings = null) =>
ListVoicesAsync(new ListVoicesRequest
{
LanguageCode = languageCode ?? "",
}, callSettings);
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="languageCode">
/// Optional. Recommended.
/// [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
/// If not specified, the API will return all supported voices.
/// If specified, the ListVoices call will only return voices that can be used
/// to synthesize this language_code. For example, if you specify `"en-NZ"`,
/// all `"en-NZ"` voices will be returned. If you specify `"no"`, both
/// `"no-\*"` (Norwegian) and `"nb-\*"` (Norwegian Bokmal) voices will be
/// returned.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListVoicesResponse> ListVoicesAsync(string languageCode, st::CancellationToken cancellationToken) =>
ListVoicesAsync(languageCode, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual SynthesizeSpeechResponse SynthesizeSpeech(SynthesizeSpeechRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<SynthesizeSpeechResponse> SynthesizeSpeechAsync(SynthesizeSpeechRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<SynthesizeSpeechResponse> SynthesizeSpeechAsync(SynthesizeSpeechRequest request, st::CancellationToken cancellationToken) =>
SynthesizeSpeechAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="input">
/// Required. The Synthesizer requires either plain text or SSML as input.
/// </param>
/// <param name="voice">
/// Required. The desired voice of the synthesized audio.
/// </param>
/// <param name="audioConfig">
/// Required. The configuration of the synthesized audio.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual SynthesizeSpeechResponse SynthesizeSpeech(SynthesisInput input, VoiceSelectionParams voice, AudioConfig audioConfig, gaxgrpc::CallSettings callSettings = null) =>
SynthesizeSpeech(new SynthesizeSpeechRequest
{
Input = gax::GaxPreconditions.CheckNotNull(input, nameof(input)),
Voice = gax::GaxPreconditions.CheckNotNull(voice, nameof(voice)),
AudioConfig = gax::GaxPreconditions.CheckNotNull(audioConfig, nameof(audioConfig)),
}, callSettings);
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="input">
/// Required. The Synthesizer requires either plain text or SSML as input.
/// </param>
/// <param name="voice">
/// Required. The desired voice of the synthesized audio.
/// </param>
/// <param name="audioConfig">
/// Required. The configuration of the synthesized audio.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<SynthesizeSpeechResponse> SynthesizeSpeechAsync(SynthesisInput input, VoiceSelectionParams voice, AudioConfig audioConfig, gaxgrpc::CallSettings callSettings = null) =>
SynthesizeSpeechAsync(new SynthesizeSpeechRequest
{
Input = gax::GaxPreconditions.CheckNotNull(input, nameof(input)),
Voice = gax::GaxPreconditions.CheckNotNull(voice, nameof(voice)),
AudioConfig = gax::GaxPreconditions.CheckNotNull(audioConfig, nameof(audioConfig)),
}, callSettings);
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="input">
/// Required. The Synthesizer requires either plain text or SSML as input.
/// </param>
/// <param name="voice">
/// Required. The desired voice of the synthesized audio.
/// </param>
/// <param name="audioConfig">
/// Required. The configuration of the synthesized audio.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<SynthesizeSpeechResponse> SynthesizeSpeechAsync(SynthesisInput input, VoiceSelectionParams voice, AudioConfig audioConfig, st::CancellationToken cancellationToken) =>
SynthesizeSpeechAsync(input, voice, audioConfig, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>TextToSpeech client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service that implements Google Cloud Text-to-Speech API.
/// </remarks>
public sealed partial class TextToSpeechClientImpl : TextToSpeechClient
{
private readonly gaxgrpc::ApiCall<ListVoicesRequest, ListVoicesResponse> _callListVoices;
private readonly gaxgrpc::ApiCall<SynthesizeSpeechRequest, SynthesizeSpeechResponse> _callSynthesizeSpeech;
/// <summary>
/// Constructs a client wrapper for the TextToSpeech service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="TextToSpeechSettings"/> used within this client.</param>
public TextToSpeechClientImpl(TextToSpeech.TextToSpeechClient grpcClient, TextToSpeechSettings settings)
{
GrpcClient = grpcClient;
TextToSpeechSettings effectiveSettings = settings ?? TextToSpeechSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callListVoices = clientHelper.BuildApiCall<ListVoicesRequest, ListVoicesResponse>(grpcClient.ListVoicesAsync, grpcClient.ListVoices, effectiveSettings.ListVoicesSettings);
Modify_ApiCall(ref _callListVoices);
Modify_ListVoicesApiCall(ref _callListVoices);
_callSynthesizeSpeech = clientHelper.BuildApiCall<SynthesizeSpeechRequest, SynthesizeSpeechResponse>(grpcClient.SynthesizeSpeechAsync, grpcClient.SynthesizeSpeech, effectiveSettings.SynthesizeSpeechSettings);
Modify_ApiCall(ref _callSynthesizeSpeech);
Modify_SynthesizeSpeechApiCall(ref _callSynthesizeSpeech);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ListVoicesApiCall(ref gaxgrpc::ApiCall<ListVoicesRequest, ListVoicesResponse> call);
partial void Modify_SynthesizeSpeechApiCall(ref gaxgrpc::ApiCall<SynthesizeSpeechRequest, SynthesizeSpeechResponse> call);
partial void OnConstruction(TextToSpeech.TextToSpeechClient grpcClient, TextToSpeechSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC TextToSpeech client</summary>
public override TextToSpeech.TextToSpeechClient GrpcClient { get; }
partial void Modify_ListVoicesRequest(ref ListVoicesRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_SynthesizeSpeechRequest(ref SynthesizeSpeechRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ListVoicesResponse ListVoices(ListVoicesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListVoicesRequest(ref request, ref callSettings);
return _callListVoices.Sync(request, callSettings);
}
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ListVoicesResponse> ListVoicesAsync(ListVoicesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListVoicesRequest(ref request, ref callSettings);
return _callListVoices.Async(request, callSettings);
}
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override SynthesizeSpeechResponse SynthesizeSpeech(SynthesizeSpeechRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SynthesizeSpeechRequest(ref request, ref callSettings);
return _callSynthesizeSpeech.Sync(request, callSettings);
}
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<SynthesizeSpeechResponse> SynthesizeSpeechAsync(SynthesizeSpeechRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SynthesizeSpeechRequest(ref request, ref callSettings);
return _callSynthesizeSpeech.Async(request, callSettings);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using ruibarbo.core.Common;
using ruibarbo.core.Debug;
using ruibarbo.core.ElementFactory;
using ruibarbo.core.Utils;
namespace ruibarbo.core.Search
{
public static class SearchSourceElementFindExtensions
{
// TODO: Make configurable. And perhaps overridable in method API.
private const int MaxSearchDepth = 20;
public static TElement FindFirstChild<TElement>(this ISearchSourceElement parent)
where TElement : class, ISearchSourceElement
{
return parent.FindFirstChild<TElement>(By.Empty);
}
public static TElement FindFirstChild<TElement>(this ISearchSourceElement parent, params Func<IByBuilder<TElement>, By>[] byBuilders)
where TElement : class, ISearchSourceElement
{
return parent.FindFirstChild<TElement>(byBuilders.Build());
}
public static TElement FindFirstChild<TElement>(this ISearchSourceElement parent, params By[] bys)
where TElement : class, ISearchSourceElement
{
// TODO: Control output verbosity in configuration
//var bysWithClass = bys.AppendByClass<TElement>();
//Console.WriteLine("Find child from {0} by <{1}>", parent.GetType().FullName, bysWithClass.Select(by => by.ToString()).Join("; "));
var found = parent.TryRepeatedlyToFindFirstChild<TElement>(bys);
if (found == null)
{
var controlToStringCreator = new ByControlToStringCreator<TElement>(bys.RemoveByName().ToArray());
string byAsString = bys
.AppendByClass<TElement>()
.Select(by => by.ToString())
.Join("; ");
throw RuibarboException.FindFailed("child", parent, byAsString, parent.ControlTreeAsString(controlToStringCreator, 8));
}
return found;
}
public static TElement TryRepeatedlyToFindFirstChild<TElement>(this ISearchSourceElement parent, params By[] bys)
where TElement : class, ISearchSourceElement
{
return Wait.UntilNotNull(() => parent.TryOnceToFindFirstChild<TElement>(bys));
}
public static TElement TryOnceToFindFirstChild<TElement>(this ISearchSourceElement parent, params By[] bys)
where TElement : class, ISearchSourceElement
{
var breadthFirstQueue = new Queue<ElementAndDepth>();
breadthFirstQueue.EnqueueAll(parent.NativeChildren.Select(c => new ElementAndDepth(c, parent, 0)));
while (breadthFirstQueue.Count > 0)
{
var current = breadthFirstQueue.Dequeue();
ISearchSourceElement nextParent = null;
foreach (var element in ElementFactory.ElementFactory.CreateElements(current.Parent, current.NativeElement))
{
nextParent = element;
var asTElement = element as TElement;
if (asTElement != null && asTElement.GetType() == typeof(TElement) && bys.All(by => by.Matches(asTElement)))
{
asTElement.UpdateFoundBy(bys);
return asTElement;
}
}
if (current.Depth < MaxSearchDepth && nextParent != null)
{
breadthFirstQueue.EnqueueAll(nextParent.NativeChildren.Select(c => new ElementAndDepth(c, nextParent, current.Depth + 1)));
}
}
return null;
}
public static IEnumerable<TElement> FindAllChildren<TElement>(this ISearchSourceElement parent)
where TElement : class, ISearchSourceElement
{
return parent.FindAllChildren<TElement>(By.Empty);
}
public static IEnumerable<TElement> FindAllChildren<TElement>(this ISearchSourceElement parent, params Func<IByBuilder<TElement>, By>[] byBuilders)
where TElement : class, ISearchSourceElement
{
return parent.FindAllChildren<TElement>(byBuilders.Build());
}
public static IEnumerable<TElement> FindAllChildren<TElement>(this ISearchSourceElement parent, params By[] bys)
where TElement : class, ISearchSourceElement
{
var breadthFirstQueue = new Queue<ElementAndDepth>();
breadthFirstQueue.EnqueueAll(parent.NativeChildren.Select(c => new ElementAndDepth(c, parent, 0)));
while (breadthFirstQueue.Count > 0)
{
var current = breadthFirstQueue.Dequeue();
ISearchSourceElement nextParent = null;
foreach (var element in ElementFactory.ElementFactory.CreateElements(current.Parent, current.NativeElement))
{
nextParent = element;
var asTElement = element as TElement;
if (asTElement != null && asTElement.GetType() == typeof(TElement) && bys.All(by => by.Matches(asTElement)))
{
asTElement.UpdateFoundBy(bys);
yield return asTElement;
}
}
if (current.Depth < MaxSearchDepth && nextParent != null)
{
breadthFirstQueue.EnqueueAll(nextParent.NativeChildren.Select(c => new ElementAndDepth(c, nextParent, current.Depth + 1)));
}
}
}
public static TElement FindFirstAncestor<TElement>(this ISearchSourceElement child)
where TElement : class, ISearchSourceElement
{
return child.FindFirstAncestor<TElement>(By.Empty);
}
public static TElement FindFirstAncestor<TElement>(this ISearchSourceElement child, params Func<IByBuilder<TElement>, By>[] byBuilders)
where TElement : class, ISearchSourceElement
{
return child.FindFirstAncestor<TElement>(byBuilders.Build());
}
public static TElement FindFirstAncestor<TElement>(this ISearchSourceElement child, params By[] bys)
where TElement : class, ISearchSourceElement
{
//Console.WriteLine("Find ancestor from {0} by <{1}>", child.GetType().FullName, bysWithClass.Select(by => by.ToString()).Join("; "));
var found = child.TryOnceToFindFirstAncestor<TElement>(bys);
if (found == null)
{
var controlToStringCreator = new ByControlToStringCreator<TElement>(bys.RemoveByName().ToArray());
string byAsString = bys
.AppendByClass<TElement>()
.Select(by => by.ToString())
.Join("; ");
throw RuibarboException.FindFailed("ancestor", child, byAsString, child.ControlAncestorsAsString(controlToStringCreator));
}
return found;
}
public static TElement TryOnceToFindFirstAncestor<TElement>(this ISearchSourceElement child)
where TElement : class, ISearchSourceElement
{
return child.TryOnceToFindFirstAncestor<TElement>(By.Empty);
}
public static TElement TryOnceToFindFirstAncestor<TElement>(this ISearchSourceElement child, params Func<IByBuilder<TElement>, By>[] byBuilders)
where TElement : class, ISearchSourceElement
{
return child.TryOnceToFindFirstAncestor<TElement>(byBuilders.Build());
}
public static TElement TryOnceToFindFirstAncestor<TElement>(this ISearchSourceElement child, By[] bys)
where TElement : class, ISearchSourceElement
{
var current = child;
while (true)
{
var parents = current.Parents().ToArray();
if (!parents.Any())
{
return null;
}
var matching = parents
.OfType<TElement>()
.Where(e => e.GetType() == typeof(TElement))
.Where(e => bys.All(by => by.Matches(e)))
.ToArray();
if (matching.Any())
{
var element = matching.First();
element.UpdateFoundBy(bys);
return element;
}
current = parents.First(); // All have the same underlying FrameworkElement
}
}
/// <summary>
/// Return a list of possible parents. They all represent the same FrameworkElement, but are wrapped in different
/// WpfElements.
/// </summary>
private static IEnumerable<ISearchSourceElement> Parents(this ISearchSourceElement me)
{
var nativeParent = me.NativeParent;
return nativeParent != null
? ElementFactory.ElementFactory.CreateElements(null, nativeParent)
: new ISearchSourceElement[] { };
}
private static void UpdateFoundBy<TElement>(this TElement element, IEnumerable<By> bys)
where TElement : class, ISearchSourceElement
{
var asUpdateable = element as IAmFoundByUpdatable;
if (asUpdateable != null)
{
var bysAsString = bys.AppendByClass(element.Class).Select(by => by.ToString()).Join(", ");
asUpdateable.UpdateFoundBy(bysAsString);
}
}
private class ElementAndDepth
{
public object NativeElement { get; private set; }
public ISearchSourceElement Parent { get; private set; }
public int Depth { get; private set; }
public ElementAndDepth(object nativeElement, ISearchSourceElement parent, int depth)
{
NativeElement = nativeElement;
Parent = parent;
Depth = depth;
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Protos.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Proto {
/// <summary>Holder for reflection information generated from Protos.proto</summary>
public static partial class ProtosReflection {
#region Descriptor
/// <summary>File descriptor for Protos.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ProtosReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgxQcm90b3MucHJvdG8SBWFjdG9yIiIKA1BJRBIPCgdBZGRyZXNzGAEgASgJ",
"EgoKAklkGAIgASgJIgwKClBvaXNvblBpbGwiJAoFV2F0Y2gSGwoHd2F0Y2hl",
"chgBIAEoCzIKLmFjdG9yLlBJRCImCgdVbndhdGNoEhsKB3dhdGNoZXIYASAB",
"KAsyCi5hY3Rvci5QSUQiQAoKVGVybWluYXRlZBIXCgN3aG8YASABKAsyCi5h",
"Y3Rvci5QSUQSGQoRQWRkcmVzc1Rlcm1pbmF0ZWQYAiABKAgiBgoEU3RvcEII",
"qgIFUHJvdG9iBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Proto.PID), global::Proto.PID.Parser, new[]{ "Address", "Id" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Proto.PoisonPill), global::Proto.PoisonPill.Parser, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Proto.Watch), global::Proto.Watch.Parser, new[]{ "Watcher" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Proto.Unwatch), global::Proto.Unwatch.Parser, new[]{ "Watcher" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Proto.Terminated), global::Proto.Terminated.Parser, new[]{ "Who", "AddressTerminated" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Proto.Stop), global::Proto.Stop.Parser, null, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class PID : pb::IMessage<PID> {
private static readonly pb::MessageParser<PID> _parser = new pb::MessageParser<PID>(() => new PID());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PID> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Proto.ProtosReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PID() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PID(PID other) : this() {
address_ = other.address_;
id_ = other.id_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PID Clone() {
return new PID(this);
}
/// <summary>Field number for the "Address" field.</summary>
public const int AddressFieldNumber = 1;
private string address_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Address {
get { return address_; }
set {
address_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "Id" field.</summary>
public const int IdFieldNumber = 2;
private string id_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Id {
get { return id_; }
set {
id_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PID);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PID other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Address != other.Address) return false;
if (Id != other.Id) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Address.Length != 0) hash ^= Address.GetHashCode();
if (Id.Length != 0) hash ^= Id.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Address.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Address);
}
if (Id.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Id);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Address.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Address);
}
if (Id.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Id);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PID other) {
if (other == null) {
return;
}
if (other.Address.Length != 0) {
Address = other.Address;
}
if (other.Id.Length != 0) {
Id = other.Id;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Address = input.ReadString();
break;
}
case 18: {
Id = input.ReadString();
break;
}
}
}
}
}
/// <summary>
///user messages
/// </summary>
public sealed partial class PoisonPill : pb::IMessage<PoisonPill> {
private static readonly pb::MessageParser<PoisonPill> _parser = new pb::MessageParser<PoisonPill>(() => new PoisonPill());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PoisonPill> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Proto.ProtosReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PoisonPill() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PoisonPill(PoisonPill other) : this() {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PoisonPill Clone() {
return new PoisonPill(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PoisonPill);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PoisonPill other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PoisonPill other) {
if (other == null) {
return;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
/// <summary>
///system messages
/// </summary>
public sealed partial class Watch : pb::IMessage<Watch> {
private static readonly pb::MessageParser<Watch> _parser = new pb::MessageParser<Watch>(() => new Watch());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Watch> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Proto.ProtosReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Watch() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Watch(Watch other) : this() {
Watcher = other.watcher_ != null ? other.Watcher.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Watch Clone() {
return new Watch(this);
}
/// <summary>Field number for the "watcher" field.</summary>
public const int WatcherFieldNumber = 1;
private global::Proto.PID watcher_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Proto.PID Watcher {
get { return watcher_; }
set {
watcher_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Watch);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Watch other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Watcher, other.Watcher)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (watcher_ != null) hash ^= Watcher.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (watcher_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Watcher);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (watcher_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Watcher);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Watch other) {
if (other == null) {
return;
}
if (other.watcher_ != null) {
if (watcher_ == null) {
watcher_ = new global::Proto.PID();
}
Watcher.MergeFrom(other.Watcher);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (watcher_ == null) {
watcher_ = new global::Proto.PID();
}
input.ReadMessage(watcher_);
break;
}
}
}
}
}
public sealed partial class Unwatch : pb::IMessage<Unwatch> {
private static readonly pb::MessageParser<Unwatch> _parser = new pb::MessageParser<Unwatch>(() => new Unwatch());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Unwatch> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Proto.ProtosReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Unwatch() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Unwatch(Unwatch other) : this() {
Watcher = other.watcher_ != null ? other.Watcher.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Unwatch Clone() {
return new Unwatch(this);
}
/// <summary>Field number for the "watcher" field.</summary>
public const int WatcherFieldNumber = 1;
private global::Proto.PID watcher_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Proto.PID Watcher {
get { return watcher_; }
set {
watcher_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Unwatch);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Unwatch other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Watcher, other.Watcher)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (watcher_ != null) hash ^= Watcher.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (watcher_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Watcher);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (watcher_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Watcher);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Unwatch other) {
if (other == null) {
return;
}
if (other.watcher_ != null) {
if (watcher_ == null) {
watcher_ = new global::Proto.PID();
}
Watcher.MergeFrom(other.Watcher);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (watcher_ == null) {
watcher_ = new global::Proto.PID();
}
input.ReadMessage(watcher_);
break;
}
}
}
}
}
public sealed partial class Terminated : pb::IMessage<Terminated> {
private static readonly pb::MessageParser<Terminated> _parser = new pb::MessageParser<Terminated>(() => new Terminated());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Terminated> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Proto.ProtosReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Terminated() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Terminated(Terminated other) : this() {
Who = other.who_ != null ? other.Who.Clone() : null;
addressTerminated_ = other.addressTerminated_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Terminated Clone() {
return new Terminated(this);
}
/// <summary>Field number for the "who" field.</summary>
public const int WhoFieldNumber = 1;
private global::Proto.PID who_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Proto.PID Who {
get { return who_; }
set {
who_ = value;
}
}
/// <summary>Field number for the "AddressTerminated" field.</summary>
public const int AddressTerminatedFieldNumber = 2;
private bool addressTerminated_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool AddressTerminated {
get { return addressTerminated_; }
set {
addressTerminated_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Terminated);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Terminated other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Who, other.Who)) return false;
if (AddressTerminated != other.AddressTerminated) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (who_ != null) hash ^= Who.GetHashCode();
if (AddressTerminated != false) hash ^= AddressTerminated.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (who_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Who);
}
if (AddressTerminated != false) {
output.WriteRawTag(16);
output.WriteBool(AddressTerminated);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (who_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Who);
}
if (AddressTerminated != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Terminated other) {
if (other == null) {
return;
}
if (other.who_ != null) {
if (who_ == null) {
who_ = new global::Proto.PID();
}
Who.MergeFrom(other.Who);
}
if (other.AddressTerminated != false) {
AddressTerminated = other.AddressTerminated;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (who_ == null) {
who_ = new global::Proto.PID();
}
input.ReadMessage(who_);
break;
}
case 16: {
AddressTerminated = input.ReadBool();
break;
}
}
}
}
}
public sealed partial class Stop : pb::IMessage<Stop> {
private static readonly pb::MessageParser<Stop> _parser = new pb::MessageParser<Stop>(() => new Stop());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Stop> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Proto.ProtosReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Stop() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Stop(Stop other) : this() {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Stop Clone() {
return new Stop(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Stop);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Stop other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Stop other) {
if (other == null) {
return;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
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 WebAPIDI.Areas.HelpPage.ModelDescriptions;
using WebAPIDI.Areas.HelpPage.Models;
namespace WebAPIDI.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);
}
}
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Utilities;
namespace Org.BouncyCastle.Crypto.Engines
{
/**
* A Noekeon engine, using direct-key mode.
*/
public class NoekeonEngine
: IBlockCipher
{
private const int GenericSize = 16; // Block and key size, as well as the amount of rounds.
private static readonly uint[] nullVector =
{
0x00, 0x00, 0x00, 0x00 // Used in decryption
};
private static readonly uint[] roundConstants =
{
0x80, 0x1b, 0x36, 0x6c,
0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63,
0xc6, 0x97, 0x35, 0x6a,
0xd4
};
private uint[] state = new uint[4], // a
subKeys = new uint[4], // k
decryptKeys = new uint[4];
private bool _initialised, _forEncryption;
/**
* Create an instance of the Noekeon encryption algorithm
* and set some defaults
*/
public NoekeonEngine()
{
_initialised = false;
}
public virtual string AlgorithmName
{
get { return "Noekeon"; }
}
public virtual bool IsPartialBlockOkay
{
get { return false; }
}
public virtual int GetBlockSize()
{
return GenericSize;
}
/**
* initialise
*
* @param forEncryption whether or not we are for encryption.
* @param params the parameters required to set up the cipher.
* @exception ArgumentException if the params argument is
* inappropriate.
*/
public virtual void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is KeyParameter))
throw new ArgumentException("Invalid parameters passed to Noekeon init - " + parameters.GetType().Name, "parameters");
_forEncryption = forEncryption;
_initialised = true;
KeyParameter p = (KeyParameter) parameters;
setKey(p.GetKey());
}
public virtual int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (!_initialised)
throw new InvalidOperationException(AlgorithmName + " not initialised");
Check.DataLength(input, inOff, GenericSize, "input buffer too short");
Check.OutputLength(output, outOff, GenericSize, "output buffer too short");
return _forEncryption
? encryptBlock(input, inOff, output, outOff)
: decryptBlock(input, inOff, output, outOff);
}
public virtual void Reset()
{
// TODO This should do something in case the encryption is aborted
}
/**
* Re-key the cipher.
*
* @param key the key to be used
*/
private void setKey(byte[] key)
{
subKeys[0] = Pack.BE_To_UInt32(key, 0);
subKeys[1] = Pack.BE_To_UInt32(key, 4);
subKeys[2] = Pack.BE_To_UInt32(key, 8);
subKeys[3] = Pack.BE_To_UInt32(key, 12);
}
private int encryptBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
state[0] = Pack.BE_To_UInt32(input, inOff);
state[1] = Pack.BE_To_UInt32(input, inOff+4);
state[2] = Pack.BE_To_UInt32(input, inOff+8);
state[3] = Pack.BE_To_UInt32(input, inOff+12);
int i;
for (i = 0; i < GenericSize; i++)
{
state[0] ^= roundConstants[i];
theta(state, subKeys);
pi1(state);
gamma(state);
pi2(state);
}
state[0] ^= roundConstants[i];
theta(state, subKeys);
Pack.UInt32_To_BE(state[0], output, outOff);
Pack.UInt32_To_BE(state[1], output, outOff+4);
Pack.UInt32_To_BE(state[2], output, outOff+8);
Pack.UInt32_To_BE(state[3], output, outOff+12);
return GenericSize;
}
private int decryptBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
state[0] = Pack.BE_To_UInt32(input, inOff);
state[1] = Pack.BE_To_UInt32(input, inOff+4);
state[2] = Pack.BE_To_UInt32(input, inOff+8);
state[3] = Pack.BE_To_UInt32(input, inOff+12);
Array.Copy(subKeys, 0, decryptKeys, 0, subKeys.Length);
theta(decryptKeys, nullVector);
int i;
for (i = GenericSize; i > 0; i--)
{
theta(state, decryptKeys);
state[0] ^= roundConstants[i];
pi1(state);
gamma(state);
pi2(state);
}
theta(state, decryptKeys);
state[0] ^= roundConstants[i];
Pack.UInt32_To_BE(state[0], output, outOff);
Pack.UInt32_To_BE(state[1], output, outOff+4);
Pack.UInt32_To_BE(state[2], output, outOff+8);
Pack.UInt32_To_BE(state[3], output, outOff+12);
return GenericSize;
}
private void gamma(uint[] a)
{
a[1] ^= ~a[3] & ~a[2];
a[0] ^= a[2] & a[1];
uint tmp = a[3];
a[3] = a[0];
a[0] = tmp;
a[2] ^= a[0]^a[1]^a[3];
a[1] ^= ~a[3] & ~a[2];
a[0] ^= a[2] & a[1];
}
private void theta(uint[] a, uint[] k)
{
uint tmp;
tmp = a[0]^a[2];
tmp ^= rotl(tmp,8)^rotl(tmp,24);
a[1] ^= tmp;
a[3] ^= tmp;
for (int i = 0; i < 4; i++)
{
a[i] ^= k[i];
}
tmp = a[1]^a[3];
tmp ^= rotl(tmp,8)^rotl(tmp,24);
a[0] ^= tmp;
a[2] ^= tmp;
}
private void pi1(uint[] a)
{
a[1] = rotl(a[1], 1);
a[2] = rotl(a[2], 5);
a[3] = rotl(a[3], 2);
}
private void pi2(uint[] a)
{
a[1] = rotl(a[1], 31);
a[2] = rotl(a[2], 27);
a[3] = rotl(a[3], 30);
}
// Helpers
private uint rotl(uint x, int y)
{
return (x << y) | (x >> (32-y));
}
}
}
| |
// 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.Reflection.Metadata.Ecma335
{
public static class MetadataTokens
{
/// <summary>
/// Maximum number of tables that can be present in Ecma335 metadata.
/// </summary>
public static readonly int TableCount = TableIndexExtensions.Count;
/// <summary>
/// Maximum number of tables that can be present in Ecma335 metadata.
/// </summary>
public static readonly int HeapCount = HeapIndexExtensions.Count;
/// <summary>
/// Returns the row number of a metadata table entry that corresponds
/// to the specified <paramref name="handle"/> in the context of <paramref name="reader"/>.
/// </summary>
/// <returns>One based row number.</returns>
/// <exception cref="ArgumentException">The <paramref name="handle"/> is not a valid metadata table handle.</exception>
public static int GetRowNumber(this MetadataReader reader, EntityHandle handle)
{
if (handle.IsVirtual)
{
return MapVirtualHandleRowId(reader, handle);
}
return handle.RowId;
}
/// <summary>
/// Returns the offset of metadata heap data that corresponds
/// to the specified <paramref name="handle"/> in the context of <paramref name="reader"/>.
/// </summary>
/// <returns>Zero based offset, or -1 if <paramref name="handle"/> isn't a metadata heap handle.</returns>
/// <exception cref="NotSupportedException">The operation is not supported for the specified <paramref name="handle"/>.</exception>
/// <exception cref="ArgumentException">The <paramref name="handle"/> is invalid.</exception>
public static int GetHeapOffset(this MetadataReader reader, Handle handle)
{
if (!handle.IsHeapHandle)
{
Throw.HeapHandleRequired();
}
if (handle.IsVirtual)
{
return MapVirtualHandleRowId(reader, handle);
}
return handle.Offset;
}
/// <summary>
/// Returns the metadata token of the specified <paramref name="handle"/> in the context of <paramref name="reader"/>.
/// </summary>
/// <returns>Metadata token.</returns>
/// <exception cref="NotSupportedException">The operation is not supported for the specified <paramref name="handle"/>.</exception>
public static int GetToken(this MetadataReader reader, EntityHandle handle)
{
if (handle.IsVirtual)
{
return (int)handle.Type | MapVirtualHandleRowId(reader, handle);
}
return handle.Token;
}
/// <summary>
/// Returns the metadata token of the specified <paramref name="handle"/> in the context of <paramref name="reader"/>.
/// </summary>
/// <returns>Metadata token.</returns>
/// <exception cref="ArgumentException">
/// Handle represents a metadata entity that doesn't have a token.
/// A token can only be retrieved for a metadata table handle or a heap handle of type <see cref="HandleKind.UserString"/>.
/// </exception>
/// <exception cref="NotSupportedException">The operation is not supported for the specified <paramref name="handle"/>.</exception>
public static int GetToken(this MetadataReader reader, Handle handle)
{
if (!handle.IsEntityOrUserStringHandle)
{
Throw.EntityOrUserStringHandleRequired();
}
if (handle.IsVirtual)
{
return (int)handle.EntityHandleType | MapVirtualHandleRowId(reader, handle);
}
return handle.Token;
}
private static int MapVirtualHandleRowId(MetadataReader reader, Handle handle)
{
switch (handle.Kind)
{
case HandleKind.AssemblyReference:
// pretend that virtual rows immediately follow real rows:
return reader.AssemblyRefTable.NumberOfNonVirtualRows + 1 + handle.RowId;
case HandleKind.String:
case HandleKind.Blob:
// We could precalculate offsets for virtual strings and blobs as we are creating them
// if we wanted to implement this.
throw new NotSupportedException(SR.CantGetOffsetForVirtualHeapHandle);
default:
throw new ArgumentException(SR.InvalidHandle, nameof(handle));
}
}
/// <summary>
/// Returns the row number of a metadata table entry that corresponds
/// to the specified <paramref name="handle"/>.
/// </summary>
/// <returns>
/// One based row number, or -1 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>.
/// See <see cref="GetRowNumber(MetadataReader, EntityHandle)"/>.
/// </returns>
public static int GetRowNumber(EntityHandle handle)
{
return handle.IsVirtual ? -1 : handle.RowId;
}
/// <summary>
/// Returns the offset of metadata heap data that corresponds
/// to the specified <paramref name="handle"/>.
/// </summary>
/// <returns>
/// An offset in the corresponding heap, or -1 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/> or <see cref="MetadataBuilder"/>.
/// See <see cref="GetHeapOffset(MetadataReader, Handle)"/>.
/// </returns>
public static int GetHeapOffset(Handle handle)
{
if (!handle.IsHeapHandle)
{
Throw.HeapHandleRequired();
}
if (handle.IsVirtual)
{
return -1;
}
return handle.Offset;
}
/// <summary>
/// Returns the offset of metadata heap data that corresponds
/// to the specified <paramref name="handle"/>.
/// </summary>
/// <returns>
/// Zero based offset, or -1 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/> or <see cref="MetadataBuilder"/>.
/// See <see cref="GetHeapOffset(MetadataReader, Handle)"/>.
/// </returns>
public static int GetHeapOffset(BlobHandle handle) => handle.IsVirtual ? -1 : handle.GetHeapOffset();
/// <summary>
/// Returns the offset of metadata heap data that corresponds
/// to the specified <paramref name="handle"/>.
/// </summary>
/// <returns>
/// Zero based offset, or -1 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/> or <see cref="MetadataBuilder"/>.
/// See <see cref="GetHeapOffset(MetadataReader, Handle)"/>.
/// </returns>
public static int GetHeapOffset(GuidHandle handle) => handle.Index;
/// <summary>
/// Returns the offset of metadata heap data that corresponds
/// to the specified <paramref name="handle"/>.
/// </summary>
/// <returns>
/// Zero based offset, or -1 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/> or <see cref="MetadataBuilder"/>.
/// See <see cref="GetHeapOffset(MetadataReader, Handle)"/>.
/// </returns>
public static int GetHeapOffset(UserStringHandle handle) => handle.GetHeapOffset();
/// <summary>
/// Returns the offset of metadata heap data that corresponds
/// to the specified <paramref name="handle"/>.
/// </summary>
/// <returns>
/// Zero based offset, or -1 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/> or <see cref="MetadataBuilder"/>.
/// See <see cref="GetHeapOffset(MetadataReader, Handle)"/>.
/// </returns>
public static int GetHeapOffset(StringHandle handle) => handle.IsVirtual ? -1 : handle.GetHeapOffset();
/// <summary>
/// Returns the metadata token of the specified <paramref name="handle"/>.
/// </summary>
/// <returns>
/// Metadata token, or 0 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>.
/// See <see cref="GetToken(MetadataReader, Handle)"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// Handle represents a metadata entity that doesn't have a token.
/// A token can only be retrieved for a metadata table handle or a heap handle of type <see cref="HandleKind.UserString"/>.
/// </exception>
public static int GetToken(Handle handle)
{
if (!handle.IsEntityOrUserStringHandle)
{
Throw.EntityOrUserStringHandleRequired();
}
if (handle.IsVirtual)
{
return 0;
}
return handle.Token;
}
/// <summary>
/// Returns the metadata token of the specified <paramref name="handle"/>.
/// </summary>
/// <returns>
/// Metadata token, or 0 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>.
/// See <see cref="GetToken(MetadataReader, EntityHandle)"/>.
/// </returns>
public static int GetToken(EntityHandle handle)
{
return handle.IsVirtual ? 0 : handle.Token;
}
/// <summary>
/// Gets the <see cref="TableIndex"/> of the table corresponding to the specified <see cref="HandleKind"/>.
/// </summary>
/// <param name="type">Handle type.</param>
/// <param name="index">Table index.</param>
/// <returns>True if the handle type corresponds to an Ecma335 table, false otherwise.</returns>
public static bool TryGetTableIndex(HandleKind type, out TableIndex index)
{
if ((int)type < TableIndexExtensions.Count)
{
index = (TableIndex)type;
return true;
}
index = 0;
return false;
}
/// <summary>
/// Gets the <see cref="HeapIndex"/> of the heap corresponding to the specified <see cref="HandleKind"/>.
/// </summary>
/// <param name="type">Handle type.</param>
/// <param name="index">Heap index.</param>
/// <returns>True if the handle type corresponds to an Ecma335 heap, false otherwise.</returns>
public static bool TryGetHeapIndex(HandleKind type, out HeapIndex index)
{
switch (type)
{
case HandleKind.UserString:
index = HeapIndex.UserString;
return true;
case HandleKind.String:
case HandleKind.NamespaceDefinition:
index = HeapIndex.String;
return true;
case HandleKind.Blob:
index = HeapIndex.Blob;
return true;
case HandleKind.Guid:
index = HeapIndex.Guid;
return true;
default:
index = 0;
return false;
}
}
#region Handle Factories
/// <summary>
/// Creates a handle from a token value.
/// </summary>
/// <exception cref="ArgumentException">
/// <paramref name="token"/> is not a valid metadata token.
/// It must encode a metadata table entity or an offset in <see cref="HandleKind.UserString"/> heap.
/// </exception>
public static Handle Handle(int token)
{
if (!TokenTypeIds.IsEntityOrUserStringToken(unchecked((uint)token)))
{
Throw.InvalidToken();
}
return Metadata.Handle.FromVToken((uint)token);
}
/// <summary>
/// Creates an entity handle from a token value.
/// </summary>
/// <exception cref="ArgumentException"><paramref name="token"/> is not a valid metadata entity token.</exception>
public static EntityHandle EntityHandle(int token)
{
if (!TokenTypeIds.IsEntityToken(unchecked((uint)token)))
{
Throw.InvalidToken();
}
return new EntityHandle((uint)token);
}
/// <summary>
/// Creates an <see cref="Metadata.EntityHandle"/> from a token value.
/// </summary>
/// <exception cref="ArgumentException">
/// <paramref name="tableIndex"/> is not a valid table index.</exception>
public static EntityHandle EntityHandle(TableIndex tableIndex, int rowNumber)
{
return Handle(tableIndex, rowNumber);
}
/// <summary>
/// Creates an <see cref="Metadata.EntityHandle"/> from a token value.
/// </summary>
/// <exception cref="ArgumentException">
/// <paramref name="tableIndex"/> is not a valid table index.</exception>
public static EntityHandle Handle(TableIndex tableIndex, int rowNumber)
{
int token = ((int)tableIndex << TokenTypeIds.RowIdBitCount) | rowNumber;
if (!TokenTypeIds.IsEntityOrUserStringToken(unchecked((uint)token)))
{
Throw.TableIndexOutOfRange();
}
return new EntityHandle((uint)token);
}
private static int ToRowId(int rowNumber)
{
return rowNumber & (int)TokenTypeIds.RIDMask;
}
public static MethodDefinitionHandle MethodDefinitionHandle(int rowNumber)
{
return Metadata.MethodDefinitionHandle.FromRowId(ToRowId(rowNumber));
}
public static MethodImplementationHandle MethodImplementationHandle(int rowNumber)
{
return Metadata.MethodImplementationHandle.FromRowId(ToRowId(rowNumber));
}
public static MethodSpecificationHandle MethodSpecificationHandle(int rowNumber)
{
return Metadata.MethodSpecificationHandle.FromRowId(ToRowId(rowNumber));
}
public static TypeDefinitionHandle TypeDefinitionHandle(int rowNumber)
{
return Metadata.TypeDefinitionHandle.FromRowId(ToRowId(rowNumber));
}
public static ExportedTypeHandle ExportedTypeHandle(int rowNumber)
{
return Metadata.ExportedTypeHandle.FromRowId(ToRowId(rowNumber));
}
public static TypeReferenceHandle TypeReferenceHandle(int rowNumber)
{
return Metadata.TypeReferenceHandle.FromRowId(ToRowId(rowNumber));
}
public static TypeSpecificationHandle TypeSpecificationHandle(int rowNumber)
{
return Metadata.TypeSpecificationHandle.FromRowId(ToRowId(rowNumber));
}
public static InterfaceImplementationHandle InterfaceImplementationHandle(int rowNumber)
{
return Metadata.InterfaceImplementationHandle.FromRowId(ToRowId(rowNumber));
}
public static MemberReferenceHandle MemberReferenceHandle(int rowNumber)
{
return Metadata.MemberReferenceHandle.FromRowId(ToRowId(rowNumber));
}
public static FieldDefinitionHandle FieldDefinitionHandle(int rowNumber)
{
return Metadata.FieldDefinitionHandle.FromRowId(ToRowId(rowNumber));
}
public static EventDefinitionHandle EventDefinitionHandle(int rowNumber)
{
return Metadata.EventDefinitionHandle.FromRowId(ToRowId(rowNumber));
}
public static PropertyDefinitionHandle PropertyDefinitionHandle(int rowNumber)
{
return Metadata.PropertyDefinitionHandle.FromRowId(ToRowId(rowNumber));
}
public static StandaloneSignatureHandle StandaloneSignatureHandle(int rowNumber)
{
return Metadata.StandaloneSignatureHandle.FromRowId(ToRowId(rowNumber));
}
public static ParameterHandle ParameterHandle(int rowNumber)
{
return Metadata.ParameterHandle.FromRowId(ToRowId(rowNumber));
}
public static GenericParameterHandle GenericParameterHandle(int rowNumber)
{
return Metadata.GenericParameterHandle.FromRowId(ToRowId(rowNumber));
}
public static GenericParameterConstraintHandle GenericParameterConstraintHandle(int rowNumber)
{
return Metadata.GenericParameterConstraintHandle.FromRowId(ToRowId(rowNumber));
}
public static ModuleReferenceHandle ModuleReferenceHandle(int rowNumber)
{
return Metadata.ModuleReferenceHandle.FromRowId(ToRowId(rowNumber));
}
public static AssemblyReferenceHandle AssemblyReferenceHandle(int rowNumber)
{
return Metadata.AssemblyReferenceHandle.FromRowId(ToRowId(rowNumber));
}
public static CustomAttributeHandle CustomAttributeHandle(int rowNumber)
{
return Metadata.CustomAttributeHandle.FromRowId(ToRowId(rowNumber));
}
public static DeclarativeSecurityAttributeHandle DeclarativeSecurityAttributeHandle(int rowNumber)
{
return Metadata.DeclarativeSecurityAttributeHandle.FromRowId(ToRowId(rowNumber));
}
public static ConstantHandle ConstantHandle(int rowNumber)
{
return Metadata.ConstantHandle.FromRowId(ToRowId(rowNumber));
}
public static ManifestResourceHandle ManifestResourceHandle(int rowNumber)
{
return Metadata.ManifestResourceHandle.FromRowId(ToRowId(rowNumber));
}
public static AssemblyFileHandle AssemblyFileHandle(int rowNumber)
{
return Metadata.AssemblyFileHandle.FromRowId(ToRowId(rowNumber));
}
// debug
public static DocumentHandle DocumentHandle(int rowNumber)
{
return Metadata.DocumentHandle.FromRowId(ToRowId(rowNumber));
}
public static MethodDebugInformationHandle MethodDebugInformationHandle(int rowNumber)
{
return Metadata.MethodDebugInformationHandle.FromRowId(ToRowId(rowNumber));
}
public static LocalScopeHandle LocalScopeHandle(int rowNumber)
{
return Metadata.LocalScopeHandle.FromRowId(ToRowId(rowNumber));
}
public static LocalVariableHandle LocalVariableHandle(int rowNumber)
{
return Metadata.LocalVariableHandle.FromRowId(ToRowId(rowNumber));
}
public static LocalConstantHandle LocalConstantHandle(int rowNumber)
{
return Metadata.LocalConstantHandle.FromRowId(ToRowId(rowNumber));
}
public static ImportScopeHandle ImportScopeHandle(int rowNumber)
{
return Metadata.ImportScopeHandle.FromRowId(ToRowId(rowNumber));
}
public static CustomDebugInformationHandle CustomDebugInformationHandle(int rowNumber)
{
return Metadata.CustomDebugInformationHandle.FromRowId(ToRowId(rowNumber));
}
// heaps
public static UserStringHandle UserStringHandle(int offset)
{
return Metadata.UserStringHandle.FromOffset(offset & (int)TokenTypeIds.RIDMask);
}
public static StringHandle StringHandle(int offset)
{
return Metadata.StringHandle.FromOffset(offset);
}
public static BlobHandle BlobHandle(int offset)
{
return Metadata.BlobHandle.FromOffset(offset);
}
public static GuidHandle GuidHandle(int offset)
{
return Metadata.GuidHandle.FromIndex(offset);
}
public static DocumentNameBlobHandle DocumentNameBlobHandle(int offset)
{
return Metadata.DocumentNameBlobHandle.FromOffset(offset);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class UIntKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStackAlloc()
{
await VerifyKeywordAsync(
@"class C {
int* foo = stackalloc $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFixedStatement()
{
await VerifyKeywordAsync(
@"fixed ($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOuterConst()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInnerConst()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEnumBaseTypes()
{
await VerifyKeywordAsync(
@"enum E : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType4()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IFoo<int?,byte*>,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = foo is $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = foo as $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
{
await VerifyAbsenceAsync(@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLocalVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"for ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForeachVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUsingVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"using ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFromVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInJoinVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from a in b
join $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Foo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Foo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Foo(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Foo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Foo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Foo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Foo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Foo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Foo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInImplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNewInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTypeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefault()
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInSizeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContext()
{
await VerifyKeywordAsync(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContextNotAfterDot()
{
await VerifyAbsenceAsync(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
{
await VerifyKeywordAsync(@"class c { async $$ }");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
{
await VerifyAbsenceAsync(@"class c { async async $$ }");
}
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInCrefTypeParameter()
{
await VerifyAbsenceAsync(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task Preselection()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
Helper($$)
}
static void Helper(uint x) { }
}
", matchPriority: SymbolMatchPriority.Keyword);
}
}
}
| |
#if NET20
// Taken and adapted from: https://github.com/mono/mono/blob/mono-3.12.1/mcs/class/System.Core/System.Collections.Generic/HashSet.cs
//
// Authors:
// Jb Evain <[email protected]>
//
// 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.CodeDom.Compiler;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Security.Permissions;
// ReSharper disable All
namespace System.Collections.Generic
{
/// <summary>
/// Backport of <c>System.Collections.Generic.HashSet{T}</c>.
/// </summary>
[GeneratedCode("Mono BCL", "3.2")] // ignore in code analysis
[Serializable]
[DebuggerDisplay("Count={Count}")]
public class HashSet<T> : ICollection<T>, ISerializable, IDeserializationCallback
{
const int INITIAL_SIZE = 10;
const float DEFAULT_LOAD_FACTOR = (90f / 100);
const int NO_SLOT = -1;
const int HASH_FLAG = -2147483648;
struct Link
{
public int HashCode;
public int Next;
}
// The hash table contains indices into the "links" array
int[] table;
Link[] links;
T[] slots;
// The number of slots in "links" and "slots" that
// are in use (i.e. filled with data) or have been used and marked as
// "empty" later on.
int touched;
// The index of the first slot in the "empty slots chain".
// "Remove ()" prepends the cleared slots to the empty chain.
// "Add ()" fills the first slot in the empty slots chain with the
// added item (or increases "touched" if the chain itself is empty).
int empty_slot;
// The number of items in this set.
int count;
// The number of items the set can hold without
// resizing the hash table and the slots arrays.
int threshold;
IEqualityComparer<T> comparer;
SerializationInfo si;
// The number of changes made to this set. Used by enumerators
// to detect changes and invalidate themselves.
int generation;
public int Count
{
get { return count; }
}
public HashSet()
{
Init(INITIAL_SIZE, null);
}
public HashSet(IEqualityComparer<T> comparer)
{
Init(INITIAL_SIZE, comparer);
}
public HashSet(IEnumerable<T> collection) : this(collection, null)
{
}
public HashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)
{
if (collection == null)
throw new ArgumentNullException("collection");
int capacity = 0;
var col = collection as ICollection<T>;
if (col != null)
capacity = col.Count;
Init(capacity, comparer);
foreach (var item in collection)
Add(item);
}
protected HashSet(SerializationInfo info, StreamingContext context)
{
si = info;
}
void Init(int capacity, IEqualityComparer<T> comparer)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException("capacity");
this.comparer = comparer ?? EqualityComparer<T>.Default;
if (capacity == 0)
capacity = INITIAL_SIZE;
/* Modify capacity so 'capacity' elements can be added without resizing */
capacity = (int)(capacity / DEFAULT_LOAD_FACTOR) + 1;
InitArrays(capacity);
generation = 0;
}
void InitArrays(int size)
{
table = new int[size];
links = new Link[size];
empty_slot = NO_SLOT;
slots = new T[size];
touched = 0;
threshold = (int)(table.Length * DEFAULT_LOAD_FACTOR);
if (threshold == 0 && table.Length > 0)
threshold = 1;
}
bool SlotsContainsAt(int index, int hash, T item)
{
int current = table[index] - 1;
while (current != NO_SLOT)
{
Link link = links[current];
if (link.HashCode == hash && ((hash == HASH_FLAG && (item == null || null == slots[current])) ? (item == null && null == slots[current]) : comparer.Equals(item, slots[current])))
return true;
current = link.Next;
}
return false;
}
public void CopyTo(T[] array)
{
CopyTo(array, 0, count);
}
public void CopyTo(T[] array, int arrayIndex)
{
CopyTo(array, arrayIndex, count);
}
public void CopyTo(T[] array, int arrayIndex, int count)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex");
if (arrayIndex > array.Length)
throw new ArgumentException("index larger than largest valid index of array");
if (array.Length - arrayIndex < count)
throw new ArgumentException("Destination array cannot hold the requested elements!");
for (int i = 0, items = 0; i < touched && items < count; i++)
{
if (GetLinkHashCode(i) != 0)
array[arrayIndex++] = slots[i];
}
}
void Resize(int size)
{
int newSize = HashPrimeNumbers.ToPrime(size);
// allocate new hash table and link slots array
var newTable = new int[newSize];
var newLinks = new Link[newSize];
for (int i = 0; i < table.Length; i++)
{
int current = table[i] - 1;
while (current != NO_SLOT)
{
int hashCode = newLinks[current].HashCode = GetItemHashCode(slots[current]);
int index = (hashCode & int.MaxValue) % newSize;
newLinks[current].Next = newTable[index] - 1;
newTable[index] = current + 1;
current = links[current].Next;
}
}
table = newTable;
links = newLinks;
// allocate new data slots, copy data
var newSlots = new T[newSize];
Array.Copy(slots, 0, newSlots, 0, touched);
slots = newSlots;
threshold = (int)(newSize * DEFAULT_LOAD_FACTOR);
}
int GetLinkHashCode(int index)
{
return links[index].HashCode & HASH_FLAG;
}
int GetItemHashCode(T item)
{
if (item == null)
return HASH_FLAG;
return comparer.GetHashCode(item) | HASH_FLAG;
}
public bool Add(T item)
{
int hashCode = GetItemHashCode(item);
int index = (hashCode & int.MaxValue) % table.Length;
if (SlotsContainsAt(index, hashCode, item))
return false;
if (++count > threshold)
{
Resize((table.Length << 1) | 1);
index = (hashCode & int.MaxValue) % table.Length;
}
// find an empty slot
int current = empty_slot;
if (current == NO_SLOT)
current = touched++;
else
empty_slot = links[current].Next;
// store the hash code of the added item,
// prepend the added item to its linked list,
// update the hash table
links[current].HashCode = hashCode;
links[current].Next = table[index] - 1;
table[index] = current + 1;
// store item
slots[current] = item;
generation++;
return true;
}
public IEqualityComparer<T> Comparer
{
get { return comparer; }
}
public void Clear()
{
count = 0;
Array.Clear(table, 0, table.Length);
Array.Clear(slots, 0, slots.Length);
Array.Clear(links, 0, links.Length);
// empty the "empty slots chain"
empty_slot = NO_SLOT;
touched = 0;
generation++;
}
public bool Contains(T item)
{
int hashCode = GetItemHashCode(item);
int index = (hashCode & int.MaxValue) % table.Length;
return SlotsContainsAt(index, hashCode, item);
}
public bool Remove(T item)
{
// get first item of linked list corresponding to given key
int hashCode = GetItemHashCode(item);
int index = (hashCode & int.MaxValue) % table.Length;
int current = table[index] - 1;
// if there is no linked list, return false
if (current == NO_SLOT)
return false;
// walk linked list until right slot (and its predecessor) is
// found or end is reached
int prev = NO_SLOT;
do
{
Link link = links[current];
if (link.HashCode == hashCode && ((hashCode == HASH_FLAG && (item == null || null == slots[current])) ? (item == null && null == slots[current]) : comparer.Equals(slots[current], item)))
break;
prev = current;
current = link.Next;
} while (current != NO_SLOT);
// if we reached the end of the chain, return false
if (current == NO_SLOT)
return false;
count--;
// remove slot from linked list
// is slot at beginning of linked list?
if (prev == NO_SLOT)
table[index] = links[current].Next + 1;
else
links[prev].Next = links[current].Next;
// mark slot as empty and prepend it to "empty slots chain"
links[current].Next = empty_slot;
empty_slot = current;
// clear slot
links[current].HashCode = 0;
slots[current] = default(T);
generation++;
return true;
}
public int RemoveWhere(Predicate<T> match)
{
if (match == null)
throw new ArgumentNullException("match");
var candidates = new List<T>();
foreach (var item in this)
if (match(item))
candidates.Add(item);
foreach (var item in candidates)
Remove(item);
return candidates.Count;
}
public void TrimExcess()
{
Resize(count);
}
// set operations
public void IntersectWith(IEnumerable<T> other)
{
if (other == null)
throw new ArgumentNullException("other");
var other_set = ToSet(other);
RemoveWhere(item => !other_set.Contains(item));
}
public void ExceptWith(IEnumerable<T> other)
{
if (other == null)
throw new ArgumentNullException("other");
foreach (var item in other)
Remove(item);
}
public bool Overlaps(IEnumerable<T> other)
{
if (other == null)
throw new ArgumentNullException("other");
foreach (var item in other)
if (Contains(item))
return true;
return false;
}
public bool SetEquals(IEnumerable<T> other)
{
if (other == null)
throw new ArgumentNullException("other");
var other_set = ToSet(other);
if (count != other_set.Count)
return false;
foreach (var item in this)
if (!other_set.Contains(item))
return false;
return true;
}
public void SymmetricExceptWith(IEnumerable<T> other)
{
if (other == null)
throw new ArgumentNullException("other");
foreach (var item in ToSet(other))
if (!Add(item))
Remove(item);
}
HashSet<T> ToSet(IEnumerable<T> enumerable)
{
var set = enumerable as HashSet<T>;
if (set == null || !Comparer.Equals(set.Comparer))
set = new HashSet<T>(enumerable, Comparer);
return set;
}
public void UnionWith(IEnumerable<T> other)
{
if (other == null)
throw new ArgumentNullException("other");
foreach (var item in other)
Add(item);
}
bool CheckIsSubsetOf(HashSet<T> other)
{
if (other == null)
throw new ArgumentNullException("other");
foreach (var item in this)
if (!other.Contains(item))
return false;
return true;
}
public bool IsSubsetOf(IEnumerable<T> other)
{
if (other == null)
throw new ArgumentNullException("other");
if (count == 0)
return true;
var other_set = ToSet(other);
if (count > other_set.Count)
return false;
return CheckIsSubsetOf(other_set);
}
public bool IsProperSubsetOf(IEnumerable<T> other)
{
if (other == null)
throw new ArgumentNullException("other");
if (count == 0)
return true;
var other_set = ToSet(other);
if (count >= other_set.Count)
return false;
return CheckIsSubsetOf(other_set);
}
bool CheckIsSupersetOf(HashSet<T> other)
{
if (other == null)
throw new ArgumentNullException("other");
foreach (var item in other)
if (!Contains(item))
return false;
return true;
}
public bool IsSupersetOf(IEnumerable<T> other)
{
if (other == null)
throw new ArgumentNullException("other");
var other_set = ToSet(other);
if (count < other_set.Count)
return false;
return CheckIsSupersetOf(other_set);
}
public bool IsProperSupersetOf(IEnumerable<T> other)
{
if (other == null)
throw new ArgumentNullException("other");
var other_set = ToSet(other);
if (count <= other_set.Count)
return false;
return CheckIsSupersetOf(other_set);
}
public static IEqualityComparer<HashSet<T>> CreateSetComparer()
{
return HashSetEqualityComparer<T>.Instance;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
info.AddValue("Version", generation);
info.AddValue("Comparer", comparer, typeof(IEqualityComparer<T>));
info.AddValue("Capacity", (table == null) ? 0 : table.Length);
if (table != null)
{
T[] tableArray = new T[count];
CopyTo(tableArray);
info.AddValue("Elements", tableArray, typeof(T[]));
}
}
public virtual void OnDeserialization(object sender)
{
if (si != null)
{
generation = (int)si.GetValue("Version", typeof(int));
comparer = (IEqualityComparer<T>)si.GetValue("Comparer",
typeof(IEqualityComparer<T>));
int capacity = (int)si.GetValue("Capacity", typeof(int));
empty_slot = NO_SLOT;
if (capacity > 0)
{
InitArrays(capacity);
T[] tableArray = (T[])si.GetValue("Elements", typeof(T[]));
if (tableArray == null)
throw new SerializationException("Missing Elements");
for (int iElement = 0; iElement < tableArray.Length; iElement++)
{
Add(tableArray[iElement]);
}
}
else
table = null;
si = null;
}
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
void ICollection<T>.Add(T item)
{
Add(item);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
[Serializable]
public struct Enumerator : IEnumerator<T>, IDisposable
{
HashSet<T> hashset;
int next;
int stamp;
T current;
internal Enumerator(HashSet<T> hashset)
: this()
{
this.hashset = hashset;
this.stamp = hashset.generation;
}
public bool MoveNext()
{
CheckState();
if (next < 0)
return false;
while (next < hashset.touched)
{
int cur = next++;
if (hashset.GetLinkHashCode(cur) != 0)
{
current = hashset.slots[cur];
return true;
}
}
next = NO_SLOT;
return false;
}
public T Current
{
get { return current; }
}
object IEnumerator.Current
{
get
{
CheckState();
if (next <= 0)
throw new InvalidOperationException("Current is not valid");
return current;
}
}
void IEnumerator.Reset()
{
CheckState();
next = 0;
}
public void Dispose()
{
hashset = null;
}
void CheckState()
{
if (hashset == null)
throw new ObjectDisposedException(null);
if (hashset.generation != stamp)
throw new InvalidOperationException("HashSet have been modified while it was iterated over");
}
}
}
sealed class HashSetEqualityComparer<T> : IEqualityComparer<HashSet<T>>
{
public static readonly HashSetEqualityComparer<T> Instance = new HashSetEqualityComparer<T>();
public bool Equals(HashSet<T> lhs, HashSet<T> rhs)
{
if (lhs == rhs)
return true;
if (lhs == null || rhs == null || lhs.Count != rhs.Count)
return false;
foreach (var item in lhs)
if (!rhs.Contains(item))
return false;
return true;
}
public int GetHashCode(HashSet<T> hashset)
{
if (hashset == null)
return 0;
IEqualityComparer<T> comparer = EqualityComparer<T>.Default;
int hash = 0;
foreach (var item in hashset)
hash ^= comparer.GetHashCode(item);
return hash;
}
}
}
#else
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.HashSet<>))]
#endif
| |
using Avalonia.Media.Transformation;
using Avalonia.Utilities;
using Xunit;
namespace Avalonia.Visuals.UnitTests.Media
{
public class TransformOperationsTests
{
[Theory]
[InlineData("translate(10px)", 10d, 0d)]
[InlineData("translate(10px, 10px)", 10d, 10d)]
[InlineData("translate(0px, 10px)", 0d, 10d)]
[InlineData("translate(10px, 0px)", 10d, 0d)]
[InlineData("translateX(10px)", 10d, 0d)]
[InlineData("translateY(10px)", 0d, 10d)]
public void Can_Parse_Translation(string data, double x, double y)
{
var transform = TransformOperations.Parse(data);
var operations = transform.Operations;
Assert.Single(operations);
Assert.Equal(TransformOperation.OperationType.Translate, operations[0].Type);
Assert.Equal(x, operations[0].Data.Translate.X);
Assert.Equal(y, operations[0].Data.Translate.Y);
}
[Theory]
[InlineData("rotate(90deg)", 90d)]
[InlineData("rotate(0.5turn)", 180d)]
[InlineData("rotate(200grad)", 180d)]
[InlineData("rotate(3.14159265rad)", 180d)]
public void Can_Parse_Rotation(string data, double angleDeg)
{
var transform = TransformOperations.Parse(data);
var operations = transform.Operations;
Assert.Single(operations);
Assert.Equal(TransformOperation.OperationType.Rotate, operations[0].Type);
Assert.Equal(MathUtilities.Deg2Rad(angleDeg), operations[0].Data.Rotate.Angle, 4);
}
[Theory]
[InlineData("scale(10)", 10d, 10d)]
[InlineData("scale(10, 10)", 10d, 10d)]
[InlineData("scale(0, 10)", 0d, 10d)]
[InlineData("scale(10, 0)", 10d, 0d)]
[InlineData("scaleX(10)", 10d, 1d)]
[InlineData("scaleY(10)", 1d, 10d)]
public void Can_Parse_Scale(string data, double x, double y)
{
var transform = TransformOperations.Parse(data);
var operations = transform.Operations;
Assert.Single(operations);
Assert.Equal(TransformOperation.OperationType.Scale, operations[0].Type);
Assert.Equal(x, operations[0].Data.Scale.X);
Assert.Equal(y, operations[0].Data.Scale.Y);
}
[Theory]
[InlineData("skew(90deg)", 90d, 0d)]
[InlineData("skew(0.5turn)", 180d, 0d)]
[InlineData("skew(200grad)", 180d, 0d)]
[InlineData("skew(3.14159265rad)", 180d, 0d)]
[InlineData("skewX(90deg)", 90d, 0d)]
[InlineData("skewX(0.5turn)", 180d, 0d)]
[InlineData("skewX(200grad)", 180d, 0d)]
[InlineData("skewX(3.14159265rad)", 180d, 0d)]
[InlineData("skew(0, 90deg)", 0d, 90d)]
[InlineData("skew(0, 0.5turn)", 0d, 180d)]
[InlineData("skew(0, 200grad)", 0d, 180d)]
[InlineData("skew(0, 3.14159265rad)", 0d, 180d)]
[InlineData("skewY(90deg)", 0d, 90d)]
[InlineData("skewY(0.5turn)", 0d, 180d)]
[InlineData("skewY(200grad)", 0d, 180d)]
[InlineData("skewY(3.14159265rad)", 0d, 180d)]
[InlineData("skew(90deg, 90deg)", 90d, 90d)]
[InlineData("skew(0.5turn, 0.5turn)", 180d, 180d)]
[InlineData("skew(200grad, 200grad)", 180d, 180d)]
[InlineData("skew(3.14159265rad, 3.14159265rad)", 180d, 180d)]
public void Can_Parse_Skew(string data, double x, double y)
{
var transform = TransformOperations.Parse(data);
var operations = transform.Operations;
Assert.Single(operations);
Assert.Equal(TransformOperation.OperationType.Skew, operations[0].Type);
Assert.Equal(MathUtilities.Deg2Rad(x), operations[0].Data.Skew.X, 4);
Assert.Equal(MathUtilities.Deg2Rad(y), operations[0].Data.Skew.Y, 4);
}
[Fact]
public void Can_Parse_Compound_Operations()
{
var data = "scale(1,2) translate(3px,4px) rotate(5deg) skew(6deg,7deg)";
var transform = TransformOperations.Parse(data);
var operations = transform.Operations;
Assert.Equal(TransformOperation.OperationType.Scale, operations[0].Type);
Assert.Equal(1, operations[0].Data.Scale.X);
Assert.Equal(2, operations[0].Data.Scale.Y);
Assert.Equal(TransformOperation.OperationType.Translate, operations[1].Type);
Assert.Equal(3, operations[1].Data.Translate.X);
Assert.Equal(4, operations[1].Data.Translate.Y);
Assert.Equal(TransformOperation.OperationType.Rotate, operations[2].Type);
Assert.Equal(MathUtilities.Deg2Rad(5), operations[2].Data.Rotate.Angle);
Assert.Equal(TransformOperation.OperationType.Skew, operations[3].Type);
Assert.Equal(MathUtilities.Deg2Rad(6), operations[3].Data.Skew.X);
Assert.Equal(MathUtilities.Deg2Rad(7), operations[3].Data.Skew.Y);
}
[Fact]
public void Can_Parse_Matrix_Operation()
{
var data = "matrix(1,2,3,4,5,6)";
var transform = TransformOperations.Parse(data);
var operations = transform.Operations;
Assert.Single(operations);
Assert.Equal(TransformOperation.OperationType.Matrix, operations[0].Type);
var expectedMatrix = new Matrix(1, 2, 3, 4, 5, 6);
Assert.Equal(expectedMatrix, operations[0].Matrix);
}
[Theory]
[InlineData(0d, 10d, 0d)]
[InlineData(0.5d, 5d, 10d)]
[InlineData(1d, 0d, 20d)]
public void Can_Interpolate_Translation(double progress, double x, double y)
{
var from = TransformOperations.Parse("translateX(10px)");
var to = TransformOperations.Parse("translateY(20px)");
var interpolated = TransformOperations.Interpolate(from, to, progress);
var operations = interpolated.Operations;
Assert.Single(operations);
Assert.Equal(TransformOperation.OperationType.Translate, operations[0].Type);
Assert.Equal(x, operations[0].Data.Translate.X);
Assert.Equal(y, operations[0].Data.Translate.Y);
}
[Theory]
[InlineData(0d, 10d, 1d)]
[InlineData(0.5d, 5.5d, 10.5d)]
[InlineData(1d, 1d, 20d)]
public void Can_Interpolate_Scale(double progress, double x, double y)
{
var from = TransformOperations.Parse("scaleX(10)");
var to = TransformOperations.Parse("scaleY(20)");
var interpolated = TransformOperations.Interpolate(from, to, progress);
var operations = interpolated.Operations;
Assert.Single(operations);
Assert.Equal(TransformOperation.OperationType.Scale, operations[0].Type);
Assert.Equal(x, operations[0].Data.Scale.X);
Assert.Equal(y, operations[0].Data.Scale.Y);
}
[Theory]
[InlineData(0d, 10d, 0d)]
[InlineData(0.5d, 5d, 10d)]
[InlineData(1d, 0d, 20d)]
public void Can_Interpolate_Skew(double progress, double x, double y)
{
var from = TransformOperations.Parse("skewX(10deg)");
var to = TransformOperations.Parse("skewY(20deg)");
var interpolated = TransformOperations.Interpolate(from, to, progress);
var operations = interpolated.Operations;
Assert.Single(operations);
Assert.Equal(TransformOperation.OperationType.Skew, operations[0].Type);
Assert.Equal(MathUtilities.Deg2Rad(x), operations[0].Data.Skew.X);
Assert.Equal(MathUtilities.Deg2Rad(y), operations[0].Data.Skew.Y);
}
[Theory]
[InlineData(0d, 10d)]
[InlineData(0.5d, 15d)]
[InlineData(1d,20d)]
public void Can_Interpolate_Rotation(double progress, double angle)
{
var from = TransformOperations.Parse("rotate(10deg)");
var to = TransformOperations.Parse("rotate(20deg)");
var interpolated = TransformOperations.Interpolate(from, to, progress);
var operations = interpolated.Operations;
Assert.Single(operations);
Assert.Equal(TransformOperation.OperationType.Rotate, operations[0].Type);
Assert.Equal(MathUtilities.Deg2Rad(angle), operations[0].Data.Rotate.Angle);
}
[Fact]
public void Interpolation_Fallback_To_Matrix()
{
double progress = 0.5d;
var from = TransformOperations.Parse("rotate(45deg)");
var to = TransformOperations.Parse("translate(100px, 100px) rotate(1215deg)");
var interpolated = TransformOperations.Interpolate(from, to, progress);
var operations = interpolated.Operations;
Assert.Single(operations);
Assert.Equal(TransformOperation.OperationType.Matrix, operations[0].Type);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using InvasionWar.GameEntities.Visible;
using InvasionWar.GameEntities.Invisible;
using InvasionWar.GameEntities;
using System.Timers;
using InvasionWar.Effects;
using InvasionWar.Effects.Animations;
using InvasionWar.Styles;
using InvasionWar.GameEntities.Invisible.Effects.GraphFunctions;
using InvasionWar.Styles.UI;
using Quobject.SocketIoClientDotNet.Client;
namespace InvasionWar
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
public enum GameState
{
NotStarted, Started, Lost, Won
}
public enum ConnectionState
{
NotConnected, RoomFull, DuplicateID, OtherDisconnected, Connected, Waiting
}
public enum TurnState
{
Ready, Waiting
}
public TurnState turnState = TurnState.Ready;
public ConnectionState connectionState = ConnectionState.NotConnected;
public enum PlayerState
{
Red, Blue, Both
}
public enum GameMode
{
Single, Multiplayer
}
public GameMode gameMode = GameMode.Single;
Timer gameStateChanged = new Timer();
public GameState CurrentGameState = GameState.NotStarted;
public GameState NextGameState = GameState.NotStarted;
public PlayerState playerState = PlayerState.Both;
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public Vector2 OriginScreenSize;
public Vector2 ScreenSize;
public Vector2 ScreenScaleFactor;
public HexagonMap hexMap;
public Socket HexagonServer;
public bool ServerReady;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.IsFullScreen = false;
OriginScreenSize = new Vector2(1024, 768);
ScreenSize = new Vector2(768, 576);
ScreenScaleFactor = new Vector2();
ScreenScaleFactor.X = ScreenSize.X / OriginScreenSize.X;
ScreenScaleFactor.Y = ScreenSize.Y / OriginScreenSize.Y;
graphics.PreferredBackBufferWidth = 768;
graphics.PreferredBackBufferHeight = 576;
Content.RootDirectory = "Content";
Global.thisGame = this;
HexagonServer = IO.Socket(GameSettings.HexagonServer);
HexagonServer.On(Socket.EVENT_CONNECT, () =>
{
ServerReady = true;
});
HexagonServer.On("sendMove", (data) =>
{
if (hexMap != null)
{
int i,j;
string[] d = ((string)data).Split(',');
i = Convert.ToInt32(d[0]);
j = Convert.ToInt32(d[1]);
hexMap.SelectCell(i, j, true);
}
});
HexagonServer.On("registerResult", (data) =>
{
var result = Convert.ToInt32(data);
switch (result)
{
case -1:
connectionState = ConnectionState.DuplicateID;
break;
case 0:
connectionState = ConnectionState.RoomFull;
break;
case 1:
connectionState = ConnectionState.Connected;
playerState = PlayerState.Blue;
turnState = TurnState.Waiting;
break;
case 2:
connectionState = ConnectionState.Waiting;
playerState = PlayerState.Red;
turnState = TurnState.Ready;
break;
}
});
HexagonServer.On("otherQuit", (data) =>
{
var username = (string)data;
connectionState = ConnectionState.OtherDisconnected;
});
HexagonServer.On("otherJoin", (data) =>
{
var username = (string)data;
connectionState = ConnectionState.Connected;
});
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
public Sprite2D btnPlaySingle, GameTitle, Panel, TextPlayerName, TextRoomID, btnShop, btnHelp, btnSetting, btnExit, btnPlayMulti, background, btnSound;
public Sprite2D scoreBoard;
public TextBox TextBoxName, TextBoxRoom;
public List<Sprite2D> sprites = new List<Sprite2D>();
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
Global.Content = this.Content; // export this one to every component
this.IsMouseVisible = true;
sprites = new List<Sprite2D>();
new ModernUI().ApplyUI(this);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
private void UpdateSprites(GameTime gameTime)
{
if (sprites == null) return;
for (int i = 0; i < sprites.Count; i++)
if (sprites[i] != null)
sprites[i].Update(gameTime);
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
Global.UpdateAll(gameTime);
UpdateSprites(gameTime);
if (hexMap != null)
{
hexMap.Update(gameTime);
}
base.Update(gameTime);
}
private void SelectSprite(int idx)
{
for (int i = 0; i < sprites.Count; i++)
sprites[i].State = (idx == i) ? 1 : 0;
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin(SpriteSortMode.BackToFront,
BlendState.AlphaBlend,
null,
DepthStencilState.None,
RasterizerState.CullNone,
null,
Global.gMainCamera.WVP );
// TODO: Add your drawing code here
for (int i = 0; i < sprites.Count; i++)
{
if (sprites[i] != null)
sprites[i].Draw(gameTime, this.spriteBatch);
}
if (hexMap != null)
hexMap.Draw(gameTime, spriteBatch);
base.Draw(gameTime);
spriteBatch.End();
}
private void TransitionStartedToNotStarted(object sender)
{
}
public void StartGameSingle()
{
Global.UnfocusAllTextBox();
gameMode = GameMode.Single;
CurrentGameState = GameState.Started;
if (hexMap == null)
{
string[] textures = new string[3];
textures[0] = "Hexa";
textures[1] = "hexa_near";
textures[2] = "hexa_far";
hexMap = new HexagonMap((int)(375.0f * ScreenScaleFactor.X), (int)(110.0f * ScreenScaleFactor.Y), 9, 45, 26, textures);
}
hexMap.StartSingle();
}
public void StartGameMultiplayer()
{
Global.UnfocusAllTextBox();
gameMode = GameMode.Multiplayer;
CurrentGameState = GameState.Started;
if (hexMap == null)
{
string[] textures = new string[3];
textures[0] = "Hexa";
textures[1] = "hexa_near";
textures[2] = "hexa_far";
hexMap = new HexagonMap((int)(375.0f * ScreenScaleFactor.X), (int)(110.0f * ScreenScaleFactor.Y), 9, 45, 26, textures);
}
var username = TextBoxName.GetText();
var roomid = TextBoxRoom.GetText();
if (ServerReady) {
HexagonServer.Emit("register", username +"|"+ roomid);
}
hexMap.StartMultiplayer();
}
public void ResetGame()
{
CurrentGameState = GameState.NotStarted;
if (gameMode == GameMode.Multiplayer)
{
if (connectionState == ConnectionState.Waiting || connectionState == ConnectionState.Connected)
{
HexagonServer.Emit("unregister");
}
connectionState = ConnectionState.NotConnected;
}
hexMap = null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
namespace System.Diagnostics
{
/// <summary>
/// Provides interaction with Windows event logs.
/// </summary>
[DefaultEvent("EntryWritten")]
public class EventLog : Component, ISupportInitialize
{
private const string EventLogKey = "SYSTEM\\CurrentControlSet\\Services\\EventLog";
internal const string DllName = "EventLogMessages.dll";
private const string eventLogMutexName = "netfxeventlog.1.0";
private const int DefaultMaxSize = 512 * 1024;
private const int DefaultRetention = 7 * SecondsPerDay;
private const int SecondsPerDay = 60 * 60 * 24;
private EventLogInternal _underlyingEventLog;
public EventLog() : this(string.Empty, ".", string.Empty)
{
}
public EventLog(string logName) : this(logName, ".", string.Empty)
{
}
public EventLog(string logName, string machineName) : this(logName, machineName, string.Empty)
{
}
public EventLog(string logName, string machineName, string source)
{
_underlyingEventLog = new EventLogInternal(logName, machineName, source, this);
}
/// <summary>
/// The contents of the log.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public EventLogEntryCollection Entries
{
get
{
return _underlyingEventLog.Entries;
}
}
[Browsable(false)]
public string LogDisplayName
{
get
{
return _underlyingEventLog.LogDisplayName;
}
}
/// <summary>
/// Gets or sets the name of the log to read from and write to.
/// </summary>
[ReadOnly(true)]
[DefaultValue("")]
[SettingsBindable(true)]
public string Log
{
get
{
return _underlyingEventLog.Log;
}
set
{
EventLogInternal newLog = new EventLogInternal(value, _underlyingEventLog.MachineName, _underlyingEventLog.Source, this);
EventLogInternal oldLog = _underlyingEventLog;
if (oldLog.EnableRaisingEvents)
{
newLog.onEntryWrittenHandler = oldLog.onEntryWrittenHandler;
newLog.EnableRaisingEvents = true;
}
_underlyingEventLog = newLog;
oldLog.Close();
}
}
/// <summary>
/// The machine on which this event log resides.
/// </summary>
[ReadOnly(true)]
[DefaultValue(".")]
[SettingsBindable(true)]
public string MachineName
{
get
{
return _underlyingEventLog.MachineName;
}
set
{
EventLogInternal newLog = new EventLogInternal(_underlyingEventLog.logName, value, _underlyingEventLog.sourceName, this);
EventLogInternal oldLog = _underlyingEventLog;
if (oldLog.EnableRaisingEvents)
{
newLog.onEntryWrittenHandler = oldLog.onEntryWrittenHandler;
newLog.EnableRaisingEvents = true;
}
_underlyingEventLog = newLog;
oldLog.Close();
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public long MaximumKilobytes
{
get => _underlyingEventLog.MaximumKilobytes;
set => _underlyingEventLog.MaximumKilobytes = value;
}
[Browsable(false)]
public OverflowAction OverflowAction
{
get => _underlyingEventLog.OverflowAction;
}
[Browsable(false)]
public int MinimumRetentionDays
{
get => _underlyingEventLog.MinimumRetentionDays;
}
internal bool ComponentDesignMode
{
get => this.DesignMode;
}
internal object ComponentGetService(Type service)
{
return GetService(service);
}
/// <summary>
/// Indicates if the component monitors the event log for changes.
/// </summary>
[Browsable(false)]
[DefaultValue(false)]
public bool EnableRaisingEvents
{
get => _underlyingEventLog.EnableRaisingEvents;
set => _underlyingEventLog.EnableRaisingEvents = value;
}
/// <summary>
/// The object used to marshal the event handler calls issued as a result of an EventLog change.
/// </summary>
[Browsable(false)]
[DefaultValue(null)]
public ISynchronizeInvoke SynchronizingObject
{
get => _underlyingEventLog.SynchronizingObject;
set => _underlyingEventLog.SynchronizingObject = value;
}
/// <summary>
/// The application name (source name) to use when writing to the event log.
/// </summary>
[ReadOnly(true)]
[DefaultValue("")]
[SettingsBindable(true)]
public string Source
{
get => _underlyingEventLog.Source;
set
{
EventLogInternal newLog = new EventLogInternal(_underlyingEventLog.Log, _underlyingEventLog.MachineName, CheckAndNormalizeSourceName(value), this);
EventLogInternal oldLog = _underlyingEventLog;
if (oldLog.EnableRaisingEvents)
{
newLog.onEntryWrittenHandler = oldLog.onEntryWrittenHandler;
newLog.EnableRaisingEvents = true;
}
_underlyingEventLog = newLog;
oldLog.Close();
}
}
/// <summary>
/// Raised each time any application writes an entry to the event log.
/// </summary>
public event EntryWrittenEventHandler EntryWritten
{
add
{
_underlyingEventLog.EntryWritten += value;
}
remove
{
_underlyingEventLog.EntryWritten -= value;
}
}
public void BeginInit()
{
_underlyingEventLog.BeginInit();
}
public void Clear()
{
_underlyingEventLog.Clear();
}
public void Close()
{
_underlyingEventLog.Close();
}
public static void CreateEventSource(string source, string logName)
{
CreateEventSource(new EventSourceCreationData(source, logName, "."));
}
[Obsolete("This method has been deprecated. Please use System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static void CreateEventSource(string source, string logName, string machineName)
{
CreateEventSource(new EventSourceCreationData(source, logName, machineName));
}
public static void CreateEventSource(EventSourceCreationData sourceData)
{
if (sourceData == null)
throw new ArgumentNullException(nameof(sourceData));
string logName = sourceData.LogName;
string source = sourceData.Source;
string machineName = sourceData.MachineName;
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Checking arguments");
if (!SyntaxCheck.CheckMachineName(machineName))
{
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName));
}
if (logName == null || logName.Length == 0)
logName = "Application";
if (!ValidLogName(logName, false))
throw new ArgumentException(SR.BadLogName);
if (source == null || source.Length == 0)
throw new ArgumentException(SR.Format(SR.MissingParameter, nameof(source)));
if (source.Length + EventLogKey.Length > 254)
throw new ArgumentException(SR.Format(SR.ParameterTooLong, nameof(source), 254 - EventLogKey.Length));
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
NetFrameworkUtils.EnterMutex(eventLogMutexName, ref mutex);
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Calling SourceExists");
if (SourceExists(source, machineName, true))
{
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: SourceExists returned true");
if (".".Equals(machineName))
throw new ArgumentException(SR.Format(SR.LocalSourceAlreadyExists, source));
else
throw new ArgumentException(SR.Format(SR.SourceAlreadyExists, source, machineName));
}
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Getting DllPath");
RegistryKey baseKey = null;
RegistryKey eventKey = null;
RegistryKey logKey = null;
RegistryKey sourceLogKey = null;
RegistryKey sourceKey = null;
try
{
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Getting local machine regkey");
if (machineName == ".")
baseKey = Registry.LocalMachine;
else
baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName);
eventKey = baseKey.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\EventLog", true);
if (eventKey == null)
{
if (!".".Equals(machineName))
throw new InvalidOperationException(SR.Format(SR.RegKeyMissing, "SYSTEM\\CurrentControlSet\\Services\\EventLog", logName, source, machineName));
else
throw new InvalidOperationException(SR.Format(SR.LocalRegKeyMissing, "SYSTEM\\CurrentControlSet\\Services\\EventLog", logName, source));
}
logKey = eventKey.OpenSubKey(logName, true);
if (logKey == null)
{
if (logName.Length == 8 && (
string.Equals(logName, "AppEvent", StringComparison.OrdinalIgnoreCase) ||
string.Equals(logName, "SecEvent", StringComparison.OrdinalIgnoreCase) ||
string.Equals(logName, "SysEvent", StringComparison.OrdinalIgnoreCase)))
throw new ArgumentException(SR.Format(SR.InvalidCustomerLogName, logName));
}
bool createLogKey = (logKey == null);
if (createLogKey)
{
if (SourceExists(logName, machineName, true))
{
if (".".Equals(machineName))
throw new ArgumentException(SR.Format(SR.LocalLogAlreadyExistsAsSource, logName));
else
throw new ArgumentException(SR.Format(SR.LogAlreadyExistsAsSource, logName, machineName));
}
logKey = eventKey.CreateSubKey(logName);
SetSpecialLogRegValues(logKey, logName);
// A source with the same name as the log has to be created
// by default. It is the behavior expected by EventLog API.
sourceLogKey = logKey.CreateSubKey(logName);
SetSpecialSourceRegValues(sourceLogKey, sourceData);
}
if (logName != source)
{
if (!createLogKey)
{
SetSpecialLogRegValues(logKey, logName);
}
sourceKey = logKey.CreateSubKey(source);
SetSpecialSourceRegValues(sourceKey, sourceData);
}
}
finally
{
baseKey?.Close();
eventKey?.Close();
logKey?.Close();
sourceLogKey?.Close();
sourceKey?.Close();
}
}
finally
{
mutex?.ReleaseMutex();
mutex?.Close();
}
}
public static void Delete(string logName)
{
Delete(logName, ".");
}
public static void Delete(string logName, string machineName)
{
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.InvalidParameterFormat, nameof(machineName)), nameof(machineName));
if (logName == null || logName.Length == 0)
throw new ArgumentException(SR.NoLogName);
if (!ValidLogName(logName, false))
throw new InvalidOperationException(SR.BadLogName);
RegistryKey eventlogkey = null;
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
NetFrameworkUtils.EnterMutex(eventLogMutexName, ref mutex);
try
{
eventlogkey = GetEventLogRegKey(machineName, true);
if (eventlogkey == null)
{
throw new InvalidOperationException(SR.Format(SR.RegKeyNoAccess, "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog", machineName));
}
using (RegistryKey logKey = eventlogkey.OpenSubKey(logName))
{
if (logKey == null)
throw new InvalidOperationException(SR.Format(SR.MissingLog, logName, machineName));
//clear out log before trying to delete it
//that way, if we can't delete the log file, no entries will persist because it has been cleared
EventLog logToClear = new EventLog(logName, machineName);
try
{
logToClear.Clear();
}
finally
{
logToClear.Close();
}
string filename = null;
try
{
//most of the time, the "File" key does not exist, but we'll still give it a whirl
filename = (string)logKey.GetValue("File");
}
catch { }
if (filename != null)
{
try
{
File.Delete(filename);
}
catch { }
}
}
// now delete the registry entry
eventlogkey.DeleteSubKeyTree(logName);
}
finally
{
eventlogkey?.Close();
}
}
finally
{
mutex?.ReleaseMutex();
}
}
public static void DeleteEventSource(string source)
{
DeleteEventSource(source, ".");
}
public static void DeleteEventSource(string source, string machineName)
{
if (!SyntaxCheck.CheckMachineName(machineName))
{
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName));
}
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
NetFrameworkUtils.EnterMutex(eventLogMutexName, ref mutex);
RegistryKey key = null;
// First open the key read only so we can do some checks. This is important so we get the same
// exceptions even if we don't have write access to the reg key.
using (key = FindSourceRegistration(source, machineName, true))
{
if (key == null)
{
if (machineName == null)
throw new ArgumentException(SR.Format(SR.LocalSourceNotRegistered, source));
else
throw new ArgumentException(SR.Format(SR.SourceNotRegistered, source, machineName, "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog"));
}
// Check parent registry key (Event Log Name) and if it's equal to source, then throw an exception.
// The reason: each log registry key must always contain subkey (i.e. source) with the same name.
string keyname = key.Name;
int index = keyname.LastIndexOf('\\');
if (string.Compare(keyname, index + 1, source, 0, keyname.Length - index, StringComparison.Ordinal) == 0)
throw new InvalidOperationException(SR.Format(SR.CannotDeleteEqualSource, source));
}
try
{
key = FindSourceRegistration(source, machineName, false);
key.DeleteSubKeyTree(source);
}
finally
{
key?.Close();
}
}
finally
{
mutex?.ReleaseMutex();
}
}
protected override void Dispose(bool disposing)
{
_underlyingEventLog?.Dispose(disposing);
base.Dispose(disposing);
}
public void EndInit()
{
_underlyingEventLog.EndInit();
}
public static bool Exists(string logName)
{
return Exists(logName, ".");
}
public static bool Exists(string logName, string machineName)
{
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.InvalidParameterFormat, nameof(machineName)));
if (logName == null || logName.Length == 0)
return false;
RegistryKey eventkey = null;
RegistryKey logKey = null;
try
{
eventkey = GetEventLogRegKey(machineName, false);
if (eventkey == null)
return false;
logKey = eventkey.OpenSubKey(logName, false); // try to find log file key immediately.
return (logKey != null);
}
finally
{
eventkey?.Close();
logKey?.Close();
}
}
private static RegistryKey FindSourceRegistration(string source, string machineName, bool readOnly)
{
return FindSourceRegistration(source, machineName, readOnly, false);
}
private static RegistryKey FindSourceRegistration(string source, string machineName, bool readOnly, bool wantToCreate)
{
if (source != null && source.Length != 0)
{
RegistryKey eventkey = null;
try
{
eventkey = GetEventLogRegKey(machineName, !readOnly);
if (eventkey == null)
{
// there's not even an event log service on the machine.
// or, more likely, we don't have the access to read the registry.
return null;
}
StringBuilder inaccessibleLogs = null;
// Most machines will return only { "Application", "System", "Security" },
// but you can create your own if you want.
string[] logNames = eventkey.GetSubKeyNames();
for (int i = 0; i < logNames.Length; i++)
{
// see if the source is registered in this log.
// NOTE: A source name must be unique across ALL LOGS!
RegistryKey sourceKey = null;
try
{
RegistryKey logKey = eventkey.OpenSubKey(logNames[i], /*writable*/!readOnly);
if (logKey != null)
{
sourceKey = logKey.OpenSubKey(source, /*writable*/!readOnly);
if (sourceKey != null)
{
// found it
return logKey;
}
else
{
logKey.Close();
}
}
// else logKey is null, so we don't need to Close it
}
catch (UnauthorizedAccessException)
{
if (inaccessibleLogs == null)
{
inaccessibleLogs = new StringBuilder(logNames[i]);
}
else
{
inaccessibleLogs.Append(", ");
inaccessibleLogs.Append(logNames[i]);
}
}
catch (SecurityException)
{
if (inaccessibleLogs == null)
{
inaccessibleLogs = new StringBuilder(logNames[i]);
}
else
{
inaccessibleLogs.Append(", ");
inaccessibleLogs.Append(logNames[i]);
}
}
finally
{
sourceKey?.Close();
}
}
if (inaccessibleLogs != null)
throw new SecurityException(SR.Format(wantToCreate ? SR.SomeLogsInaccessibleToCreate : SR.SomeLogsInaccessible, inaccessibleLogs));
}
finally
{
eventkey?.Close();
}
}
return null;
}
public static EventLog[] GetEventLogs()
{
return GetEventLogs(".");
}
public static EventLog[] GetEventLogs(string machineName)
{
if (!SyntaxCheck.CheckMachineName(machineName))
{
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName));
}
string[] logNames = null;
RegistryKey eventkey = null;
try
{
// we figure out what logs are on the machine by looking in the registry.
eventkey = GetEventLogRegKey(machineName, false);
if (eventkey == null)
// there's not even an event log service on the machine.
// or, more likely, we don't have the access to read the registry.
throw new InvalidOperationException(SR.Format(SR.RegKeyMissingShort, EventLogKey, machineName));
// Most machines will return only { "Application", "System", "Security" },
// but you can create your own if you want.
logNames = eventkey.GetSubKeyNames();
}
finally
{
eventkey?.Close();
}
// now create EventLog objects that point to those logs
List<EventLog> logs = new List<EventLog>(logNames.Length);
for (int i = 0; i < logNames.Length; i++)
{
EventLog log = new EventLog(logNames[i], machineName);
SafeEventLogReadHandle handle = Interop.Advapi32.OpenEventLog(machineName, logNames[i]);
if (!handle.IsInvalid)
{
handle.Close();
logs.Add(log);
}
else if (Marshal.GetLastWin32Error() != Interop.Errors.ERROR_INVALID_PARAMETER)
{
// This api should return the list of all event logs present on the system even if the current user can't open the log.
// Windows returns ERROR_INVALID_PARAMETER for special keys which were added in RS5+ but do not represent actual event logs.
logs.Add(log);
}
}
return logs.ToArray();
}
internal static RegistryKey GetEventLogRegKey(string machine, bool writable)
{
RegistryKey lmkey = null;
try
{
if (machine.Equals("."))
{
lmkey = Registry.LocalMachine;
}
else
{
lmkey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine);
}
if (lmkey != null)
return lmkey.OpenSubKey(EventLogKey, writable);
}
finally
{
lmkey?.Close();
}
return null;
}
internal static string GetDllPath(string machineName)
{
return Path.Combine(NetFrameworkUtils.GetLatestBuildDllDirectory(machineName), DllName);
}
public static bool SourceExists(string source)
{
return SourceExists(source, ".");
}
public static bool SourceExists(string source, string machineName)
{
return SourceExists(source, machineName, false);
}
internal static bool SourceExists(string source, string machineName, bool wantToCreate)
{
if (!SyntaxCheck.CheckMachineName(machineName))
{
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName));
}
using (RegistryKey keyFound = FindSourceRegistration(source, machineName, true, wantToCreate))
{
return (keyFound != null);
}
}
public static string LogNameFromSourceName(string source, string machineName)
{
return _InternalLogNameFromSourceName(source, machineName);
}
internal static string _InternalLogNameFromSourceName(string source, string machineName)
{
using (RegistryKey key = FindSourceRegistration(source, machineName, true))
{
if (key == null)
return string.Empty;
else
{
string name = key.Name;
int whackPos = name.LastIndexOf('\\');
// this will work even if whackPos is -1
return name.Substring(whackPos + 1);
}
}
}
public void ModifyOverflowPolicy(OverflowAction action, int retentionDays)
{
_underlyingEventLog.ModifyOverflowPolicy(action, retentionDays);
}
public void RegisterDisplayName(string resourceFile, long resourceId)
{
_underlyingEventLog.RegisterDisplayName(resourceFile, resourceId);
}
private static void SetSpecialLogRegValues(RegistryKey logKey, string logName)
{
// Set all the default values for this log. AutoBackupLogfiles only makes sense in
// Win2000 SP4, WinXP SP1, and Win2003, but it should alright elsewhere.
// Since we use this method on the existing system logs as well as our own,
// we need to make sure we don't overwrite any existing values.
if (logKey.GetValue("MaxSize") == null)
logKey.SetValue("MaxSize", DefaultMaxSize, RegistryValueKind.DWord);
if (logKey.GetValue("AutoBackupLogFiles") == null)
logKey.SetValue("AutoBackupLogFiles", 0, RegistryValueKind.DWord);
}
private static void SetSpecialSourceRegValues(RegistryKey sourceLogKey, EventSourceCreationData sourceData)
{
if (string.IsNullOrEmpty(sourceData.MessageResourceFile))
sourceLogKey.SetValue("EventMessageFile", GetDllPath(sourceData.MachineName), RegistryValueKind.ExpandString);
else
sourceLogKey.SetValue("EventMessageFile", FixupPath(sourceData.MessageResourceFile), RegistryValueKind.ExpandString);
if (!string.IsNullOrEmpty(sourceData.ParameterResourceFile))
sourceLogKey.SetValue("ParameterMessageFile", FixupPath(sourceData.ParameterResourceFile), RegistryValueKind.ExpandString);
if (!string.IsNullOrEmpty(sourceData.CategoryResourceFile))
{
sourceLogKey.SetValue("CategoryMessageFile", FixupPath(sourceData.CategoryResourceFile), RegistryValueKind.ExpandString);
sourceLogKey.SetValue("CategoryCount", sourceData.CategoryCount, RegistryValueKind.DWord);
}
}
private static string FixupPath(string path)
{
if (path[0] == '%')
return path;
else
return Path.GetFullPath(path);
}
internal static string TryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings)
{
if (insertionStrings.Length == 0)
{
return UnsafeTryFormatMessage(hModule, messageNum, insertionStrings);
}
// If you pass in an empty array UnsafeTryFormatMessage will just pull out the message.
string formatString = UnsafeTryFormatMessage(hModule, messageNum, Array.Empty<string>());
if (formatString == null)
{
return null;
}
int largestNumber = 0;
for (int i = 0; i < formatString.Length; i++)
{
if (formatString[i] == '%')
{
if (formatString.Length > i + 1)
{
StringBuilder sb = new StringBuilder();
while (i + 1 < formatString.Length && char.IsDigit(formatString[i + 1]))
{
sb.Append(formatString[i + 1]);
i++;
}
// move over the non number character that broke us out of the loop
i++;
if (sb.Length > 0)
{
int num = -1;
if (int.TryParse(sb.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out num))
{
largestNumber = Math.Max(largestNumber, num);
}
}
}
}
}
// Replacement strings are 1 indexed.
if (largestNumber > insertionStrings.Length)
{
string[] newStrings = new string[largestNumber];
Array.Copy(insertionStrings, 0, newStrings, 0, insertionStrings.Length);
for (int i = insertionStrings.Length; i < newStrings.Length; i++)
{
newStrings[i] = "%" + (i + 1);
}
insertionStrings = newStrings;
}
return UnsafeTryFormatMessage(hModule, messageNum, insertionStrings);
}
// FormatMessageW will AV if you don't pass in enough format strings. If you call TryFormatMessage we ensure insertionStrings
// is long enough. You don't want to call this directly unless you're sure insertionStrings is long enough!
internal static string UnsafeTryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings)
{
string msg = null;
int msgLen = 0;
var buf = new char[1024];
int flags = Interop.Kernel32.FORMAT_MESSAGE_FROM_HMODULE | Interop.Kernel32.FORMAT_MESSAGE_ARGUMENT_ARRAY;
IntPtr[] addresses = new IntPtr[insertionStrings.Length];
GCHandle[] handles = new GCHandle[insertionStrings.Length];
GCHandle stringsRoot = GCHandle.Alloc(addresses, GCHandleType.Pinned);
if (insertionStrings.Length == 0)
{
flags |= Interop.Kernel32.FORMAT_MESSAGE_IGNORE_INSERTS;
}
try
{
for (int i = 0; i < handles.Length; i++)
{
handles[i] = GCHandle.Alloc(insertionStrings[i], GCHandleType.Pinned);
addresses[i] = handles[i].AddrOfPinnedObject();
}
int lastError = Interop.Errors.ERROR_INSUFFICIENT_BUFFER;
while (msgLen == 0 && lastError == Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
{
msgLen = Interop.Kernel32.FormatMessage(
flags,
hModule,
messageNum,
0,
buf,
buf.Length,
addresses);
if (msgLen == 0)
{
lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
buf = new char[buf.Length * 2];
}
}
}
catch
{
msgLen = 0; // return empty on failure
}
finally
{
for (int i = 0; i < handles.Length; i++)
{
if (handles[i].IsAllocated)
handles[i].Free();
}
stringsRoot.Free();
}
if (msgLen > 0)
{
msg = msgLen > 1 && buf[msgLen - 1] == '\n' ?
new string(buf, 0, msgLen - 2) : // chop off a single CR/LF pair from the end if there is one. FormatMessage always appends one extra.
new string(buf, 0, msgLen);
}
return msg;
}
// CharIsPrintable used to be Char.IsPrintable, but Jay removed it and
// is forcing people to use the Unicode categories themselves. Copied
// the code here.
private static bool CharIsPrintable(char c)
{
UnicodeCategory uc = char.GetUnicodeCategory(c);
return (!(uc == UnicodeCategory.Control) || (uc == UnicodeCategory.Format) ||
(uc == UnicodeCategory.LineSeparator) || (uc == UnicodeCategory.ParagraphSeparator) ||
(uc == UnicodeCategory.OtherNotAssigned));
}
internal static bool ValidLogName(string logName, bool ignoreEmpty)
{
// No need to trim here since the next check will verify that there are no spaces.
// We need to ignore the empty string as an invalid log name sometimes because it can
// be passed in from our default constructor.
if (logName.Length == 0 && !ignoreEmpty)
return false;
//any space, backslash, asterisk, or question mark is bad
//any non-printable characters are also bad
foreach (char c in logName)
if (!CharIsPrintable(c) || (c == '\\') || (c == '*') || (c == '?'))
return false;
return true;
}
public void WriteEntry(string message)
{
WriteEntry(message, EventLogEntryType.Information, (short)0, 0, null);
}
public static void WriteEntry(string source, string message)
{
WriteEntry(source, message, EventLogEntryType.Information, (short)0, 0, null);
}
public void WriteEntry(string message, EventLogEntryType type)
{
WriteEntry(message, type, (short)0, 0, null);
}
public static void WriteEntry(string source, string message, EventLogEntryType type)
{
WriteEntry(source, message, type, (short)0, 0, null);
}
public void WriteEntry(string message, EventLogEntryType type, int eventID)
{
WriteEntry(message, type, eventID, 0, null);
}
public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID)
{
WriteEntry(source, message, type, eventID, 0, null);
}
public void WriteEntry(string message, EventLogEntryType type, int eventID, short category)
{
WriteEntry(message, type, eventID, category, null);
}
public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category)
{
WriteEntry(source, message, type, eventID, category, null);
}
public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category, byte[] rawData)
{
using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source)))
{
log.WriteEntry(message, type, eventID, category, rawData);
}
}
public void WriteEntry(string message, EventLogEntryType type, int eventID, short category, byte[] rawData)
{
_underlyingEventLog.WriteEntry(message, type, eventID, category, rawData);
}
public void WriteEvent(EventInstance instance, params object[] values)
{
WriteEvent(instance, null, values);
}
public void WriteEvent(EventInstance instance, byte[] data, params object[] values)
{
_underlyingEventLog.WriteEvent(instance, data, values);
}
public static void WriteEvent(string source, EventInstance instance, params object[] values)
{
using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source)))
{
log.WriteEvent(instance, null, values);
}
}
public static void WriteEvent(string source, EventInstance instance, byte[] data, params object[] values)
{
using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source)))
{
log.WriteEvent(instance, data, values);
}
}
// The EventLog.set_Source used to do some normalization and throw some exceptions. We mimic that behavior here.
private static string CheckAndNormalizeSourceName(string source)
{
if (source == null)
source = string.Empty;
// this 254 limit is the max length of a registry key.
if (source.Length + EventLogKey.Length > 254)
throw new ArgumentException(SR.Format(SR.ParameterTooLong, nameof(source), 254 - EventLogKey.Length));
return source;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareEqualSByte()
{
var test = new SimpleBinaryOpTest__CompareEqualSByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareEqualSByte
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(SByte);
private const int Op2ElementCount = VectorSize / sizeof(SByte);
private const int RetElementCount = VectorSize / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector256<SByte> _clsVar1;
private static Vector256<SByte> _clsVar2;
private Vector256<SByte> _fld1;
private Vector256<SByte> _fld2;
private SimpleBinaryOpTest__DataTable<SByte, SByte, SByte> _dataTable;
static SimpleBinaryOpTest__CompareEqualSByte()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareEqualSByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<SByte, SByte, SByte>(_data1, _data2, new SByte[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.CompareEqual(
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.CompareEqual(
Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.CompareEqual(
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) })
.Invoke(null, new object[] {
Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.CompareEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr);
var result = Avx2.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr));
var result = Avx2.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr));
var result = Avx2.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareEqualSByte();
var result = Avx2.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.CompareEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<SByte> left, Vector256<SByte> right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
if (result[0] != ((left[0] == right[0]) ? unchecked((sbyte)(-1)) : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] == right[i]) ? unchecked((sbyte)(-1)) : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.CompareEqual)}<SByte>(Vector256<SByte>, Vector256<SByte>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// 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;
namespace System.Net
{
// CookieCollection
//
// A list of cookies maintained in Sorted order. Only one cookie with matching Name/Domain/Path
public class CookieCollection : ICollection
{
internal enum Stamp
{
Check = 0,
Set = 1,
SetToUnused = 2,
SetToMaxUsed = 3,
}
private readonly List<Cookie> _list = new List<Cookie>();
private DateTime _timeStamp = DateTime.MinValue;
private bool _hasOtherVersions;
public CookieCollection()
{
}
public Cookie this[int index]
{
get
{
if (index < 0 || index >= _list.Count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
return _list[index];
}
}
public Cookie this[string name]
{
get
{
foreach (Cookie c in _list)
{
if (string.Equals(c.Name, name, StringComparison.OrdinalIgnoreCase))
{
return c;
}
}
return null;
}
}
public void Add(Cookie cookie)
{
if (cookie == null)
{
throw new ArgumentNullException(nameof(cookie));
}
int idx = IndexOf(cookie);
if (idx == -1)
{
_list.Add(cookie);
}
else
{
_list[idx] = cookie;
}
}
public void Add(CookieCollection cookies)
{
if (cookies == null)
{
throw new ArgumentNullException(nameof(cookies));
}
foreach (Cookie cookie in cookies._list)
{
Add(cookie);
}
}
public int Count
{
get
{
return _list.Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
void ICollection.CopyTo(Array array, int index)
{
((ICollection)_list).CopyTo(array, index);
}
internal DateTime TimeStamp(Stamp how)
{
switch (how)
{
case Stamp.Set:
_timeStamp = DateTime.Now;
break;
case Stamp.SetToMaxUsed:
_timeStamp = DateTime.MaxValue;
break;
case Stamp.SetToUnused:
_timeStamp = DateTime.MinValue;
break;
case Stamp.Check:
default:
break;
}
return _timeStamp;
}
// This is for internal cookie container usage.
// For others not that _hasOtherVersions gets changed ONLY in InternalAdd
internal bool IsOtherVersionSeen
{
get
{
return _hasOtherVersions;
}
}
// If isStrict == false, assumes that incoming cookie is unique.
// If isStrict == true, replace the cookie if found same with newest Variant.
// Returns 1 if added, 0 if replaced or rejected.
internal int InternalAdd(Cookie cookie, bool isStrict)
{
int ret = 1;
if (isStrict)
{
int idx = 0;
foreach (Cookie c in _list)
{
if (CookieComparer.Compare(cookie, c) == 0)
{
ret = 0; // Will replace or reject
// Cookie2 spec requires that new Variant cookie overwrite the old one.
if (c.Variant <= cookie.Variant)
{
_list[idx] = cookie;
}
break;
}
++idx;
}
if (idx == _list.Count)
{
_list.Add(cookie);
}
}
else
{
_list.Add(cookie);
}
if (cookie.Version != Cookie.MaxSupportedVersion)
{
_hasOtherVersions = true;
}
return ret;
}
internal int IndexOf(Cookie cookie)
{
int idx = 0;
foreach (Cookie c in _list)
{
if (CookieComparer.Compare(cookie, c) == 0)
{
return idx;
}
++idx;
}
return -1;
}
internal void RemoveAt(int idx)
{
_list.RemoveAt(idx);
}
public IEnumerator GetEnumerator()
{
return _list.GetEnumerator();
}
#if DEBUG
internal void Dump()
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CookieCollection:");
foreach (Cookie cookie in this)
{
cookie.Dump();
}
}
}
#endif
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
namespace Microsoft.Live
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Web;
/// <summary>
/// A utility class that handles read and write operations on current web session.
/// </summary>
internal static class HttpContextUtility
{
private const string AuthCookie = "wl_auth";
/// <summary>
/// Reads authorization code from current session.
/// </summary>
public static bool ReadAuthCodeRequest(
HttpContextBase webContext,
out string code,
out string state,
out string requestTs,
out LiveAuthException error)
{
Debug.Assert(webContext != null);
NameValueCollection queryString = webContext.Request.QueryString;
code = queryString[AuthConstants.Code];
bool isCodeRequest = !string.IsNullOrEmpty(code);
string clientState = queryString[AuthConstants.ClientState];
IDictionary<string, string> states = LiveAuthUtility.DecodeAppRequestStates(clientState);
state = states.ContainsKey(AuthConstants.AppState) ? states[AuthConstants.AppState] : null;
requestTs = states.ContainsKey(AuthConstants.ClientRequestTs) ? states[AuthConstants.ClientRequestTs] : null;
string errorCode = queryString[AuthConstants.Error];
string errorDescription = queryString[AuthConstants.ErrorDescription];
error = string.IsNullOrEmpty(errorCode) ? null : new LiveAuthException(errorCode, errorDescription, state);
return isCodeRequest;
}
/// <summary>
/// Check if current session has a token request.
/// </summary>
public static bool ReadRefreshTokenRequest(
HttpContextBase webContext,
out string clientId,
out IEnumerable<string> scopes)
{
clientId = null;
scopes = null;
bool isTokenRequest = false;
if (webContext != null)
{
NameValueCollection queryString = webContext.Request.QueryString;
string requestToken = queryString[AuthConstants.ResponseType];
isTokenRequest = (requestToken == AuthConstants.Token);
if (isTokenRequest)
{
clientId = queryString[AuthConstants.ClientId];
// If this is sent by the client library, the token response should honor the scope parameter.
scopes = LiveAuthUtility.ParseScopeString(queryString[AuthConstants.Scope]);
}
}
return isTokenRequest;
}
/// <summary>
/// Reads current user session.
/// </summary>
public static LiveLoginResult GetUserLoginStatus(HttpContextBase webContext)
{
Debug.Assert(webContext != null);
HttpCookie cookie = webContext.Request.Cookies[AuthCookie];
LiveConnectSession session = null;
LiveConnectSessionStatus status = LiveConnectSessionStatus.Unknown;
if (cookie != null && cookie.Values != null)
{
string accessToken = cookie[AuthConstants.AccessToken];
if (!string.IsNullOrEmpty(accessToken))
{
session = new LiveConnectSession();
session.AccessToken = UrlDataDecode(accessToken);
session.AuthenticationToken = UrlDataDecode(cookie[AuthConstants.AuthenticationToken]);
session.RefreshToken = UrlDataDecode(cookie[AuthConstants.RefreshToken]);
session.Scopes = LiveAuthUtility.ParseScopeString(UrlDataDecode(cookie[AuthConstants.Scope]));
session.Expires = LiveAuthWebUtility.ParseExpiresValue(UrlDataDecode(cookie[AuthConstants.Expires]));
status = session.IsValid ? LiveConnectSessionStatus.Connected : LiveConnectSessionStatus.Expired;
}
else
{
// If we previously recorded NotConnected, take that value.
// Ignore other values that may be set by JS library.
LiveConnectSessionStatus statusFromCookie;
if (Enum.TryParse<LiveConnectSessionStatus>(cookie[AuthConstants.Status],
true/*ignore case*/,
out statusFromCookie))
{
if (statusFromCookie == LiveConnectSessionStatus.NotConnected)
{
status = statusFromCookie;
}
}
}
}
return new LiveLoginResult(status, session);
}
/// <summary>
/// Writes the user current session.
/// </summary>
public static void UpdateUserSession(HttpContextBase context, LiveLoginResult loginResult, string requestTs)
{
if (context == null)
{
return;
}
Debug.Assert(loginResult != null);
Dictionary<string, string> cookieValues = new Dictionary<string, string>();
HttpCookie cookie = context.Request.Cookies[AuthCookie];
HttpCookie newCookie = new HttpCookie(AuthCookie);
newCookie.Path = "/";
string host = context.Request.Headers["Host"];
newCookie.Domain = host.Split(':')[0];
if (cookie != null && cookie.Values != null)
{
foreach (string key in cookie.Values.AllKeys)
{
newCookie.Values[key] = cookie[key];
}
}
LiveConnectSession session = loginResult.Session;
if (session != null)
{
newCookie.Values[AuthConstants.AccessToken] = Uri.EscapeDataString(session.AccessToken);
newCookie.Values[AuthConstants.AuthenticationToken] = Uri.EscapeDataString(session.AuthenticationToken);
newCookie.Values[AuthConstants.Scope] = Uri.EscapeDataString(LiveAuthUtility.BuildScopeString(session.Scopes));
newCookie.Values[AuthConstants.ExpiresIn] = Uri.EscapeDataString(LiveAuthWebUtility.GetExpiresInString(session.Expires));
newCookie.Values[AuthConstants.Expires] = Uri.EscapeDataString(LiveAuthWebUtility.GetExpiresString(session.Expires));
}
LiveConnectSessionStatus status;
if (!string.IsNullOrEmpty(newCookie[AuthConstants.AccessToken]))
{
// We have an access token, so it is connected, regardless expired or not
// since it is handled after loading the session in both Asp.Net and JS library.
status = LiveConnectSessionStatus.Connected;
}
else
{
status = loginResult.Status;
if (loginResult.Status == LiveConnectSessionStatus.Unknown)
{
// If we recorded NotConnected previously, keep it.
LiveConnectSessionStatus statusFromCookie;
if (Enum.TryParse<LiveConnectSessionStatus>(
newCookie[AuthConstants.Status],
true/*ignore case*/,
out statusFromCookie))
{
if (statusFromCookie == LiveConnectSessionStatus.NotConnected)
{
status = statusFromCookie;
}
}
}
}
newCookie.Values[AuthConstants.Status] = GetStatusString(status);
// Needs to write error to inform the JS library.
LiveAuthException authError = loginResult.Error as LiveAuthException;
if (authError != null)
{
newCookie.Values[AuthConstants.Error] = Uri.EscapeDataString(authError.ErrorCode);
newCookie.Values[AuthConstants.ErrorDescription] = HttpUtility.UrlPathEncode(authError.Message);
}
else if (status != LiveConnectSessionStatus.Connected)
{
newCookie.Values[AuthConstants.Error] = Uri.EscapeDataString(AuthErrorCodes.AccessDenied);
newCookie.Values[AuthConstants.ErrorDescription] = HttpUtility.UrlPathEncode("Cannot retrieve access token.");
}
if (!string.IsNullOrEmpty(requestTs))
{
newCookie.Values[AuthConstants.ClientRequestTs] = requestTs;
}
context.Response.Cookies.Add(newCookie);
}
/// <summary>
/// Clear current user session from the auth cookie.
/// </summary>
public static void ClearUserSession(HttpContextBase context)
{
Debug.Assert(context != null);
if (context.Request.Cookies[AuthCookie] != null)
{
HttpCookie authCookie = new HttpCookie(AuthCookie);
authCookie.Expires = DateTime.Now.AddDays(-1d);
context.Response.Cookies.Add(authCookie);
}
}
private static string UrlDataDecode(string value)
{
if (value == null)
{
return null;
}
return Uri.UnescapeDataString(value);
}
private static string GetStatusString(LiveConnectSessionStatus status)
{
// We need to write cookie status values that conform to the JS library format.
switch (status)
{
case LiveConnectSessionStatus.NotConnected:
return "notConnected";
default:
return status.ToString().ToLowerInvariant();
}
}
}
}
| |
// 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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class IntersectTests
{
private const int DuplicateFactor = 4;
public static IEnumerable<object[]> IntersectUnorderedData(int[] leftCounts, int[] rightCounts)
{
foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts.Cast<int>(), (l, r) => 0 - r / 2, rightCounts.Cast<int>()))
{
parms[4] = Math.Min((int)parms[1], ((int)parms[3] + 1) / 2);
yield return parms;
}
}
public static IEnumerable<object[]> IntersectData(int[] leftCounts, int[] rightCounts)
{
foreach (object[] parms in IntersectUnorderedData(leftCounts, rightCounts))
{
parms[0] = ((Labeled<ParallelQuery<int>>)parms[0]).Order();
yield return parms;
}
}
public static IEnumerable<object[]> IntersectSourceMultipleData(int[] counts)
{
foreach (int leftCount in counts.Cast<int>())
{
ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel().AsOrdered();
foreach (int rightCount in new int[] { 0, 1, Math.Max(DuplicateFactor * 2, leftCount), 2 * Math.Max(DuplicateFactor, leftCount * 2) })
{
int rightStart = 0 - rightCount / 2;
yield return new object[] { left, leftCount,
ParallelEnumerable.Range(rightStart, rightCount), rightCount, Math.Min(leftCount, (rightCount + 1) / 2) };
}
}
}
//
// Intersect
//
[Theory]
[MemberData("IntersectUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (int i in leftQuery.Intersect(rightQuery))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("IntersectUnorderedData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Unordered(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (int i in leftQuery.Intersect(rightQuery))
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("IntersectData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(leftQuery.Intersect(rightQuery).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("IntersectUnorderedData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Unordered_NotPipelined(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
Assert.All(leftQuery.Intersect(rightQuery).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("IntersectData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_NotPipelined(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Unordered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, rightCount));
foreach (int i in leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)))
{
seen.Add(i % (DuplicateFactor * 2));
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("IntersectUnorderedData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Unordered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Unordered_Distinct(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
int seen = 0;
foreach (int i in leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Min(leftCount, rightCount), seen);
}
[Theory]
[OuterLoop]
[MemberData("IntersectData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Distinct(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Unordered_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, rightCount));
Assert.All(leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => seen.Add(x % (DuplicateFactor * 2)));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("IntersectUnorderedData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Unordered_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Unordered_Distinct_NotPipelined(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
int seen = 0;
Assert.All(leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Min(leftCount, rightCount), seen);
}
[Theory]
[OuterLoop]
[MemberData("IntersectData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Distinct_NotPipelined(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Intersect_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
// The difference between this test and the previous, is that it's not possible to
// get non-unique results from ParallelEnumerable.Range()...
// Those tests either need modification of source (via .Select(x => x /DuplicateFactor) or similar,
// or via a comparator that considers some elements equal.
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(leftQuery.AsUnordered().Intersect(rightQuery), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("IntersectSourceMultipleData", (object)(new int[] { 512, 1024 * 16 }))]
public static void Intersect_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Intersect_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData("IntersectSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Intersect_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
int seen = 0;
Assert.All(leftQuery.Intersect(rightQuery), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("IntersectSourceMultipleData", (object)(new int[] { 512, 1024 * 16 }))]
public static void Intersect_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Intersect_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Fact]
public static void Intersect_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Intersect(Enumerable.Range(0, 1)));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Intersect(Enumerable.Range(0, 1), null));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void Intersect_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Intersect(ParallelEnumerable.Range(0, 1).WithCancellation(t)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Intersect(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Intersect(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Intersect(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default)));
}
[Fact]
public static void Intersect_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Intersect(ParallelEnumerable.Range(0, 1)));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Intersect(null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Intersect(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Intersect(null, EqualityComparer<int>.Default));
}
}
}
| |
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 Planru.DistributedServices.WebAPI.Areas.HelpPage.ModelDescriptions;
using Planru.DistributedServices.WebAPI.Areas.HelpPage.Models;
namespace Planru.DistributedServices.WebAPI.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) 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 Microsoft.Azure.Management.TrafficManager
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ProfilesOperations operations.
/// </summary>
internal partial class ProfilesOperations : IServiceOperations<TrafficManagerManagementClient>, IProfilesOperations
{
/// <summary>
/// Initializes a new instance of the ProfilesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ProfilesOperations(TrafficManagerManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the TrafficManagerManagementClient
/// </summary>
public TrafficManagerManagementClient Client { get; private set; }
/// <summary>
/// Checks the availability of a Traffic Manager Relative DNS name.
/// </summary>
/// <param name='parameters'>
/// The Traffic Manager name parameters supplied to the
/// CheckTrafficManagerNameAvailability operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<TrafficManagerNameAvailability>> CheckTrafficManagerRelativeDnsNameAvailabilityWithHttpMessagesAsync(CheckTrafficManagerRelativeDnsNameAvailabilityParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CheckTrafficManagerRelativeDnsNameAvailability", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Network/checkTrafficManagerNameAvailability").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 += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<TrafficManagerNameAvailability>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<TrafficManagerNameAvailability>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all Traffic Manager profiles within a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager profiles to
/// be listed.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Profile>>> ListAllInResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllInResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
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 += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<Profile>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Profile>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all Traffic Manager profiles within a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Profile>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// 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, "ListAll", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficmanagerprofiles").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
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 += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<Profile>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Profile>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a Traffic Manager profile.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager profile.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Profile>> GetWithHttpMessagesAsync(string resourceGroupName, string profileName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (profileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("profileName", profileName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{profileName}", System.Uri.EscapeDataString(profileName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
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 += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Profile>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Profile>(_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>
/// Create or update a Traffic Manager profile.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager profile.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager profile parameters supplied to the CreateOrUpdate
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Profile>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string profileName, Profile parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (profileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("profileName", profileName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{profileName}", System.Uri.EscapeDataString(profileName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
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 += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Profile>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Profile>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Profile>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a Traffic Manager profile.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager profile to be
/// deleted.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile to be deleted.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DeleteOperationResult>> DeleteWithHttpMessagesAsync(string resourceGroupName, string profileName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (profileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("profileName", profileName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{profileName}", System.Uri.EscapeDataString(profileName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
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 += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DeleteOperationResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<DeleteOperationResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 204)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<DeleteOperationResult>(_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>
/// Update a Traffic Manager profile.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager profile.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager profile parameters supplied to the Update operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Profile>> UpdateWithHttpMessagesAsync(string resourceGroupName, string profileName, Profile parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (profileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("profileName", profileName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{profileName}", System.Uri.EscapeDataString(profileName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
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 += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Profile>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Profile>(_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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
public static class HashCodeTests
{
[Fact]
public static void HashCode_Add()
{
// The version of xUnit used by corefx does not support params theories.
void Theory(uint expected, params uint[] vector)
{
var hc = new HashCode();
for (int i = 0; i < vector.Length; i++)
hc.Add(vector[i]);
#if SYSTEM_HASHCODE_TESTVECTORS
// HashCode is not deterministic across AppDomains by design. This means
// that these tests can not be executed against the version that exists
// within CoreCLR. Copy HashCode and set m_seed to 0 in order to execute
// these tests.
Assert.Equal(expected, (uint)hc.ToHashCode());
#else
// Validate that the HashCode.m_seed is randomized. This has a 1 in 4
// billion chance of resulting in a false negative, as HashCode.m_seed
// can be 0.
Assert.NotEqual(expected, (uint)hc.ToHashCode());
#endif
}
// These test vectors were created using https://asecuritysite.com/encryption/xxHash
// 1. Find the hash for "".
// 2. Find the hash for "abcd". ASCII "abcd" and bit convert to uint.
// 3. Find the hash for "abcd1234". ASCII [ "abcd", "1234"] and bit convert to 2 uints.
// n. Continue until "abcd0123efgh4567ijkl8901mnop2345qrst6789uvwx0123yzab".
Theory(0x02cc5d05U);
Theory(0xa3643705U, 0x64636261U );
Theory(0x4603e94cU, 0x64636261U, 0x33323130U );
Theory(0xd8a1e80fU, 0x64636261U, 0x33323130U, 0x68676665U );
Theory(0x4b62a7cfU, 0x64636261U, 0x33323130U, 0x68676665U, 0x37363534U );
Theory(0xc33a7641U, 0x64636261U, 0x33323130U, 0x68676665U, 0x37363534U, 0x6c6b6a69U );
Theory(0x1a794705U, 0x64636261U, 0x33323130U, 0x68676665U, 0x37363534U, 0x6c6b6a69U, 0x31303938U );
Theory(0x4d79177dU, 0x64636261U, 0x33323130U, 0x68676665U, 0x37363534U, 0x6c6b6a69U, 0x31303938U, 0x706f6e6dU );
Theory(0x59d79205U, 0x64636261U, 0x33323130U, 0x68676665U, 0x37363534U, 0x6c6b6a69U, 0x31303938U, 0x706f6e6dU, 0x35343332U );
Theory(0x49585aaeU, 0x64636261U, 0x33323130U, 0x68676665U, 0x37363534U, 0x6c6b6a69U, 0x31303938U, 0x706f6e6dU, 0x35343332U, 0x74737271U );
Theory(0x2f005ff1U, 0x64636261U, 0x33323130U, 0x68676665U, 0x37363534U, 0x6c6b6a69U, 0x31303938U, 0x706f6e6dU, 0x35343332U, 0x74737271U, 0x39383736U );
Theory(0x0ce339bdU, 0x64636261U, 0x33323130U, 0x68676665U, 0x37363534U, 0x6c6b6a69U, 0x31303938U, 0x706f6e6dU, 0x35343332U, 0x74737271U, 0x39383736U, 0x78777675U );
Theory(0xb31bd2ffU, 0x64636261U, 0x33323130U, 0x68676665U, 0x37363534U, 0x6c6b6a69U, 0x31303938U, 0x706f6e6dU, 0x35343332U, 0x74737271U, 0x39383736U, 0x78777675U, 0x33323130U );
Theory(0xa821efa3U, 0x64636261U, 0x33323130U, 0x68676665U, 0x37363534U, 0x6c6b6a69U, 0x31303938U, 0x706f6e6dU, 0x35343332U, 0x74737271U, 0x39383736U, 0x78777675U, 0x33323130U, 0x62617a79U );
}
[Fact]
public static void HashCode_Add_HashCode()
{
var hc1 = new HashCode();
hc1.Add("Hello");
var hc2 = new HashCode();
hc2.Add("Hello".GetHashCode());
Assert.Equal(hc1.ToHashCode(), hc2.ToHashCode());
}
[Fact]
public static void HashCode_Add_Generic()
{
var hc = new HashCode();
hc.Add(1);
hc.Add(new ConstHashCodeType());
var expected = new HashCode();
expected.Add(1);
expected.Add(ConstComparer.ConstantValue);
Assert.Equal(expected.ToHashCode(), hc.ToHashCode());
}
[Fact]
public static void HashCode_Add_Null()
{
var hc = new HashCode();
hc.Add<string>(null);
var expected = new HashCode();
expected.Add(EqualityComparer<string>.Default.GetHashCode(null));
Assert.Equal(expected.ToHashCode(), hc.ToHashCode());
}
[Fact]
public static void HashCode_Add_GenericEqualityComparer()
{
var hc = new HashCode();
hc.Add(1);
hc.Add("Hello", new ConstComparer());
var expected = new HashCode();
expected.Add(1);
expected.Add(ConstComparer.ConstantValue);
Assert.Equal(expected.ToHashCode(), hc.ToHashCode());
}
[Fact]
public static void HashCode_Add_NullEqualityComparer()
{
var hc = new HashCode();
hc.Add(1);
hc.Add("Hello", null);
var expected = new HashCode();
expected.Add(1);
expected.Add("Hello");
Assert.Equal(expected.ToHashCode(), hc.ToHashCode());
}
[Fact]
public static void HashCode_Combine()
{
var hcs = new int[]
{
HashCode.Combine(1),
HashCode.Combine(1, 2),
HashCode.Combine(1, 2, 3),
HashCode.Combine(1, 2, 3, 4),
HashCode.Combine(1, 2, 3, 4, 5),
HashCode.Combine(1, 2, 3, 4, 5, 6),
HashCode.Combine(1, 2, 3, 4, 5, 6, 7),
HashCode.Combine(1, 2, 3, 4, 5, 6, 7, 8),
HashCode.Combine(2),
HashCode.Combine(2, 3),
HashCode.Combine(2, 3, 4),
HashCode.Combine(2, 3, 4, 5),
HashCode.Combine(2, 3, 4, 5, 6),
HashCode.Combine(2, 3, 4, 5, 6, 7),
HashCode.Combine(2, 3, 4, 5, 6, 7, 8),
HashCode.Combine(2, 3, 4, 5, 6, 7, 8, 9),
};
for (int i = 0; i < hcs.Length; i++)
for (int j = 0; j < hcs.Length; j++)
{
if (i == j) continue;
Assert.NotEqual(hcs[i], hcs[j]);
}
}
[Fact]
public static void HashCode_Combine_Add_1()
{
var hc = new HashCode();
hc.Add(1);
Assert.Equal(hc.ToHashCode(), HashCode.Combine(1));
}
[Fact]
public static void HashCode_Combine_Add_2()
{
var hc = new HashCode();
hc.Add(1);
hc.Add(2);
Assert.Equal(hc.ToHashCode(), HashCode.Combine(1, 2));
}
[Fact]
public static void HashCode_Combine_Add_3()
{
var hc = new HashCode();
hc.Add(1);
hc.Add(2);
hc.Add(3);
Assert.Equal(hc.ToHashCode(), HashCode.Combine(1, 2, 3));
}
[Fact]
public static void HashCode_Combine_Add_4()
{
var hc = new HashCode();
hc.Add(1);
hc.Add(2);
hc.Add(3);
hc.Add(4);
Assert.Equal(hc.ToHashCode(), HashCode.Combine(1, 2, 3, 4));
}
[Fact]
public static void HashCode_Combine_Add_5()
{
var hc = new HashCode();
hc.Add(1);
hc.Add(2);
hc.Add(3);
hc.Add(4);
hc.Add(5);
Assert.Equal(hc.ToHashCode(), HashCode.Combine(1, 2, 3, 4, 5));
}
[Fact]
public static void HashCode_Combine_Add_6()
{
var hc = new HashCode();
hc.Add(1);
hc.Add(2);
hc.Add(3);
hc.Add(4);
hc.Add(5);
hc.Add(6);
Assert.Equal(hc.ToHashCode(), HashCode.Combine(1, 2, 3, 4, 5, 6));
}
[Fact]
public static void HashCode_Combine_Add_7()
{
var hc = new HashCode();
hc.Add(1);
hc.Add(2);
hc.Add(3);
hc.Add(4);
hc.Add(5);
hc.Add(6);
hc.Add(7);
Assert.Equal(hc.ToHashCode(), HashCode.Combine(1, 2, 3, 4, 5, 6, 7));
}
[Fact]
public static void HashCode_Combine_Add_8()
{
var hc = new HashCode();
hc.Add(1);
hc.Add(2);
hc.Add(3);
hc.Add(4);
hc.Add(5);
hc.Add(6);
hc.Add(7);
hc.Add(8);
Assert.Equal(hc.ToHashCode(), HashCode.Combine(1, 2, 3, 4, 5, 6, 7, 8));
}
[Fact]
public static void HashCode_GetHashCode()
{
var hc = new HashCode();
Assert.Throws<NotSupportedException>(() => hc.GetHashCode());
}
[Fact]
public static void HashCode_Equals()
{
var hc = new HashCode();
Assert.Throws<NotSupportedException>(() => hc.Equals(hc));
}
[Fact]
public static void HashCode_GetHashCode_Boxed()
{
var hc = new HashCode();
var obj = (object)hc;
Assert.Throws<NotSupportedException>(() => obj.GetHashCode());
}
[Fact]
public static void HashCode_Equals_Boxed()
{
var hc = new HashCode();
var obj = (object)hc;
Assert.Throws<NotSupportedException>(() => obj.Equals(obj));
}
public class ConstComparer : System.Collections.Generic.IEqualityComparer<string>
{
public const int ConstantValue = 1234;
public bool Equals(string x, string y) => false;
public int GetHashCode(string obj) => ConstantValue;
}
public class ConstHashCodeType
{
public override int GetHashCode() => ConstComparer.ConstantValue;
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.unity3d.scene
{
public class TooltipSaver : global::UnityEngine.MonoBehaviour, global::haxe.lang.IHxObject
{
public TooltipSaver(global::haxe.lang.EmptyObject empty) : base()
{
unchecked
{
}
#line default
}
public TooltipSaver() : base()
{
unchecked
{
}
#line default
}
public static object __hx_createEmpty()
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return new global::pony.unity3d.scene.TooltipSaver(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static object __hx_create(global::Array arr)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return new global::pony.unity3d.scene.TooltipSaver();
}
#line default
}
public global::Array<object> tooltips;
public virtual void Start()
{
unchecked
{
#line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
global::pony.unity3d.scene.Tooltip tooltip = default(global::pony.unity3d.scene.Tooltip);
if (( tooltip == default(global::pony.unity3d.scene.Tooltip) ))
{
#line 44 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
tooltip = ((global::pony.unity3d.scene.Tooltip) (global::hugs.GameObjectMethods.getTypedComponent<object>(this.gameObject, typeof(global::pony.unity3d.scene.Tooltip))) );
}
if (( tooltip == default(global::pony.unity3d.scene.Tooltip) ))
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
tooltip = ((global::pony.unity3d.scene.Tooltip) (global::hugs.GameObjectMethods.getParentTypedComponent<object>(this.gameObject, typeof(global::pony.unity3d.scene.Tooltip))) );
}
if (( tooltip == default(global::pony.unity3d.scene.Tooltip) ))
{
this.tooltips = global::hugs.GameObjectMethods.getComponentsInChildrenOfType<object>(this.gameObject, typeof(global::pony.unity3d.scene.Tooltip), default(global::haxe.lang.Null<bool>)).haxeArray();
}
else
{
#line 49 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
this.tooltips = new global::Array<object>(new object[]{tooltip});
}
}
#line default
}
public void saveColors()
{
unchecked
{
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
int _g = 0;
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
global::Array<object> _g1 = this.tooltips;
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
while (( _g < _g1.length ))
{
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
global::pony.unity3d.scene.Tooltip e = ((global::pony.unity3d.scene.Tooltip) (_g1[_g]) );
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
++ _g;
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
e.saveColors();
}
}
#line default
}
public virtual bool __hx_deleteField(string field, int hash)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return false;
}
#line default
}
public virtual object __hx_lookupField(string field, int hash, bool throwErrors, bool isCheck)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
if (isCheck)
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return global::haxe.lang.Runtime.undefined;
}
else
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
if (throwErrors)
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
throw global::haxe.lang.HaxeException.wrap("Field not found.");
}
else
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return default(object);
}
}
}
#line default
}
public virtual double __hx_lookupField_f(string field, int hash, bool throwErrors)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
if (throwErrors)
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
throw global::haxe.lang.HaxeException.wrap("Field not found or incompatible field type.");
}
else
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return default(double);
}
}
#line default
}
public virtual object __hx_lookupSetField(string field, int hash, object @value)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing.");
}
#line default
}
public virtual double __hx_lookupSetField_f(string field, int hash, double @value)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing or incompatible type.");
}
#line default
}
public virtual double __hx_setField_f(string field, int hash, double @value, bool handleProperties)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
switch (hash)
{
default:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.__hx_lookupSetField_f(field, hash, @value);
}
}
}
#line default
}
public virtual object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
switch (hash)
{
case 1575675685:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
this.hideFlags = ((global::UnityEngine.HideFlags) (@value) );
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return @value;
}
case 1224700491:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
this.name = global::haxe.lang.Runtime.toString(@value);
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return @value;
}
case 5790298:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
this.tag = global::haxe.lang.Runtime.toString(@value);
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return @value;
}
case 373703110:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
this.active = ((bool) (@value) );
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return @value;
}
case 2117141633:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
this.enabled = ((bool) (@value) );
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return @value;
}
case 896046654:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
this.useGUILayout = ((bool) (@value) );
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return @value;
}
case 1351267856:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
this.tooltips = ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (@value) ))) );
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return @value;
}
default:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.__hx_lookupSetField(field, hash, @value);
}
}
}
#line default
}
public virtual object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
switch (hash)
{
case 1826409040:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetType"), ((int) (1826409040) ))) );
}
case 304123084:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("ToString"), ((int) (304123084) ))) );
}
case 276486854:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetInstanceID"), ((int) (276486854) ))) );
}
case 295397041:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetHashCode"), ((int) (295397041) ))) );
}
case 1955029599:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Equals"), ((int) (1955029599) ))) );
}
case 1575675685:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.hideFlags;
}
case 1224700491:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.name;
}
case 294420221:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessageUpwards"), ((int) (294420221) ))) );
}
case 139469119:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessage"), ((int) (139469119) ))) );
}
case 967979664:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentsInChildren"), ((int) (967979664) ))) );
}
case 2122408236:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponents"), ((int) (2122408236) ))) );
}
case 1328964235:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentInChildren"), ((int) (1328964235) ))) );
}
case 1723652455:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponent"), ((int) (1723652455) ))) );
}
case 89600725:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CompareTag"), ((int) (89600725) ))) );
}
case 2134927590:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("BroadcastMessage"), ((int) (2134927590) ))) );
}
case 5790298:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.tag;
}
case 373703110:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.active;
}
case 1471506513:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.gameObject;
}
case 1751728597:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.particleSystem;
}
case 524620744:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.particleEmitter;
}
case 964013983:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.hingeJoint;
}
case 1238753076:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.collider;
}
case 674101152:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.guiTexture;
}
case 262266241:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.guiElement;
}
case 1515196979:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.networkView;
}
case 801759432:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.guiText;
}
case 662730966:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.audio;
}
case 853263683:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.renderer;
}
case 1431885287:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.constantForce;
}
case 1261760260:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.animation;
}
case 1962709206:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.light;
}
case 931940005:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.camera;
}
case 1895479501:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.rigidbody;
}
case 1167273324:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.transform;
}
case 2117141633:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.enabled;
}
case 2084823382:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopCoroutine"), ((int) (2084823382) ))) );
}
case 1856815770:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopAllCoroutines"), ((int) (1856815770) ))) );
}
case 832859768:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine_Auto"), ((int) (832859768) ))) );
}
case 987108662:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine"), ((int) (987108662) ))) );
}
case 602588383:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("IsInvoking"), ((int) (602588383) ))) );
}
case 1641152943:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("InvokeRepeating"), ((int) (1641152943) ))) );
}
case 1416948632:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Invoke"), ((int) (1416948632) ))) );
}
case 757431474:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CancelInvoke"), ((int) (757431474) ))) );
}
case 896046654:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.useGUILayout;
}
case 255873229:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("saveColors"), ((int) (255873229) ))) );
}
case 389604418:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Start"), ((int) (389604418) ))) );
}
case 1351267856:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.tooltips;
}
default:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.__hx_lookupField(field, hash, throwErrors, isCheck);
}
}
}
#line default
}
public virtual double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
switch (hash)
{
default:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return this.__hx_lookupField_f(field, hash, throwErrors);
}
}
}
#line default
}
public virtual object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
switch (hash)
{
case 757431474:case 1416948632:case 1641152943:case 602588383:case 987108662:case 832859768:case 1856815770:case 2084823382:case 2134927590:case 89600725:case 1723652455:case 1328964235:case 2122408236:case 967979664:case 139469119:case 294420221:case 1955029599:case 295397041:case 276486854:case 304123084:case 1826409040:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return global::haxe.lang.Runtime.slowCallField(this, field, dynargs);
}
case 255873229:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
this.saveColors();
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
break;
}
case 389604418:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
this.Start();
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
break;
}
default:
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return ((global::haxe.lang.Function) (this.__hx_getField(field, hash, true, false, false)) ).__hx_invokeDynamic(dynargs);
}
}
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
return default(object);
}
#line default
}
public virtual void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("hideFlags");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("name");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("tag");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("active");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("gameObject");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("particleSystem");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("particleEmitter");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("hingeJoint");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("collider");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("guiTexture");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("guiElement");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("networkView");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("guiText");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("audio");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("renderer");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("constantForce");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("animation");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("light");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("camera");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("rigidbody");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("transform");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("enabled");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("useGUILayout");
#line 38 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/scene/TooltipSaver.hx"
baseArr.push("tooltips");
}
#line default
}
}
}
| |
// 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.IO;
using System.Security.Cryptography.Apple;
using Internal.Cryptography;
namespace System.Security.Cryptography
{
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
public partial class RSA : AsymmetricAlgorithm
{
public static new RSA Create()
{
return new RSAImplementation.RSASecurityTransforms();
}
}
#endif
internal static partial class RSAImplementation
{
public sealed partial class RSASecurityTransforms : RSA
{
private SecKeyPair _keys;
public RSASecurityTransforms()
: this(2048)
{
}
public RSASecurityTransforms(int keySize)
{
KeySize = keySize;
}
internal RSASecurityTransforms(SafeSecKeyRefHandle publicKey)
{
SetKey(SecKeyPair.PublicOnly(publicKey));
}
internal RSASecurityTransforms(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle privateKey)
{
SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
public override KeySizes[] LegalKeySizes
{
get
{
return new KeySizes[]
{
// All values are in bits.
// 1024 was achieved via experimentation.
// 1024 and 1024+64 both generated successfully, 1024-64 produced errSecParam.
new KeySizes(minSize: 1024, maxSize: 16384, skipSize: 64),
};
}
}
public override int KeySize
{
get
{
return base.KeySize;
}
set
{
if (KeySize == value)
return;
// Set the KeySize before freeing the key so that an invalid value doesn't throw away the key
base.KeySize = value;
if (_keys != null)
{
_keys.Dispose();
_keys = null;
}
}
}
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
SecKeyPair keys = GetKeys();
SafeSecKeyRefHandle keyHandle = includePrivateParameters ? keys.PrivateKey : keys.PublicKey;
if (keyHandle == null)
{
throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
}
DerSequenceReader keyReader = Interop.AppleCrypto.SecKeyExport(keyHandle, includePrivateParameters);
RSAParameters parameters = new RSAParameters();
if (includePrivateParameters)
{
keyReader.ReadPkcs8Blob(ref parameters);
}
else
{
// When exporting a key handle opened from a certificate, it seems to
// export as a PKCS#1 blob instead of an X509 SubjectPublicKeyInfo blob.
// So, check for that.
if (keyReader.PeekTag() == (byte)DerSequenceReader.DerTag.Integer)
{
keyReader.ReadPkcs1PublicBlob(ref parameters);
}
else
{
keyReader.ReadSubjectPublicKeyInfo(ref parameters);
}
}
return parameters;
}
public override void ImportParameters(RSAParameters parameters)
{
bool isPrivateKey = parameters.D != null;
if (isPrivateKey)
{
// Start with the private key, in case some of the private key fields
// don't match the public key fields.
//
// Public import should go off without a hitch.
SafeSecKeyRefHandle privateKey = ImportKey(parameters);
RSAParameters publicOnly = new RSAParameters
{
Modulus = parameters.Modulus,
Exponent = parameters.Exponent,
};
SafeSecKeyRefHandle publicKey;
try
{
publicKey = ImportKey(publicOnly);
}
catch
{
privateKey.Dispose();
throw;
}
SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
else
{
SafeSecKeyRefHandle publicKey = ImportKey(parameters);
SetKey(SecKeyPair.PublicOnly(publicKey));
}
}
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
{
return Interop.AppleCrypto.RsaEncrypt(GetKeys().PublicKey, data, padding);
}
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
{
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
return Interop.AppleCrypto.RsaDecrypt(keys.PrivateKey, data, padding);
}
public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
if (padding != RSASignaturePadding.Pkcs1)
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
return Interop.AppleCrypto.GenerateSignature(
keys.PrivateKey,
hash,
PalAlgorithmFromAlgorithmName(hashAlgorithm));
}
public override bool VerifyHash(
byte[] hash,
byte[] signature,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
if (padding != RSASignaturePadding.Pkcs1)
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
return Interop.AppleCrypto.VerifySignature(
GetKeys().PublicKey,
hash,
signature,
PalAlgorithmFromAlgorithmName(hashAlgorithm));
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
return AsymmetricAlgorithmHelpers.HashData(data, offset, count, hashAlgorithm);
}
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
return AsymmetricAlgorithmHelpers.HashData(data, hashAlgorithm);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_keys != null)
{
_keys.Dispose();
_keys = null;
}
}
base.Dispose(disposing);
}
private static Interop.AppleCrypto.PAL_HashAlgorithm PalAlgorithmFromAlgorithmName(
HashAlgorithmName hashAlgorithmName)
{
if (hashAlgorithmName == HashAlgorithmName.MD5)
{
return Interop.AppleCrypto.PAL_HashAlgorithm.Md5;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA1)
{
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha1;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA256)
{
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha256;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA384)
{
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha384;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA512)
{
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha512;
}
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithmName.Name);
}
private SecKeyPair GetKeys()
{
SecKeyPair current = _keys;
if (current != null)
{
return current;
}
SafeSecKeyRefHandle publicKey;
SafeSecKeyRefHandle privateKey;
Interop.AppleCrypto.RsaGenerateKey(KeySizeValue, out publicKey, out privateKey);
current = SecKeyPair.PublicPrivatePair(publicKey, privateKey);
_keys = current;
return current;
}
private void SetKey(SecKeyPair newKeyPair)
{
SecKeyPair current = _keys;
_keys = newKeyPair;
current?.Dispose();
if (newKeyPair != null)
{
KeySizeValue = Interop.AppleCrypto.GetSimpleKeySizeInBits(newKeyPair.PublicKey);
}
}
private static SafeSecKeyRefHandle ImportKey(RSAParameters parameters)
{
bool isPrivateKey = parameters.D != null;
byte[] pkcs1Blob = isPrivateKey ? parameters.ToPkcs1Blob() : parameters.ToSubjectPublicKeyInfo();
return Interop.AppleCrypto.ImportEphemeralKey(pkcs1Blob, isPrivateKey);
}
}
}
internal static class RsaKeyBlobHelpers
{
private const string RsaOid = "1.2.840.113549.1.1.1";
// The PKCS#1 version blob for an RSA key based on 2 primes.
private static readonly byte[] s_versionNumberBytes = { 0 };
// The AlgorithmIdentifier structure for RSA contains an explicit NULL, for legacy/compat reasons.
private static readonly byte[][] s_encodedRsaAlgorithmIdentifier =
DerEncoder.ConstructSegmentedSequence(
DerEncoder.SegmentedEncodeOid(new Oid(RsaOid)),
// DER:NULL (0x05 0x00)
new byte[][]
{
new byte[] { (byte)DerSequenceReader.DerTag.Null },
new byte[] { 0 },
Array.Empty<byte>(),
});
internal static byte[] ToPkcs1Blob(this RSAParameters parameters)
{
if (parameters.Exponent == null || parameters.Modulus == null)
throw new CryptographicException(SR.Cryptography_InvalidRsaParameters);
if (parameters.D == null)
{
if (parameters.P != null ||
parameters.DP != null ||
parameters.Q != null ||
parameters.DQ != null ||
parameters.InverseQ != null)
{
throw new CryptographicException(SR.Cryptography_InvalidRsaParameters);
}
return DerEncoder.ConstructSequence(
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Modulus),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Exponent));
}
if (parameters.P == null ||
parameters.DP == null ||
parameters.Q == null ||
parameters.DQ == null ||
parameters.InverseQ == null)
{
throw new CryptographicException(SR.Cryptography_InvalidRsaParameters);
}
return DerEncoder.ConstructSequence(
DerEncoder.SegmentedEncodeUnsignedInteger(s_versionNumberBytes),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Modulus),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Exponent),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.D),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.P),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Q),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.DP),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.DQ),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.InverseQ));
}
internal static void ReadPkcs8Blob(this DerSequenceReader reader, ref RSAParameters parameters)
{
// OneAsymmetricKey ::= SEQUENCE {
// version Version,
// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
// privateKey PrivateKey,
// attributes [0] Attributes OPTIONAL,
// ...,
// [[2: publicKey [1] PublicKey OPTIONAL ]],
// ...
// }
//
// PrivateKeyInfo ::= OneAsymmetricKey
//
// PrivateKey ::= OCTET STRING
int version = reader.ReadInteger();
// We understand both version 0 and 1 formats,
// which are now known as v1 and v2, respectively.
if (version > 1)
{
throw new CryptographicException();
}
{
// Ensure we're reading RSA
DerSequenceReader algorithm = reader.ReadSequence();
string algorithmOid = algorithm.ReadOidAsString();
if (algorithmOid != RsaOid)
{
throw new CryptographicException();
}
}
byte[] privateKeyBytes = reader.ReadOctetString();
// Because this was an RSA private key, the key format is PKCS#1.
ReadPkcs1PrivateBlob(privateKeyBytes, ref parameters);
// We don't care about the rest of the blob here, but it's expected to not exist.
}
internal static byte[] ToSubjectPublicKeyInfo(this RSAParameters parameters)
{
Debug.Assert(parameters.D == null);
// SubjectPublicKeyInfo::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING }
return DerEncoder.ConstructSequence(
s_encodedRsaAlgorithmIdentifier,
DerEncoder.SegmentedEncodeBitString(
parameters.ToPkcs1Blob()));
}
internal static void ReadSubjectPublicKeyInfo(this DerSequenceReader keyInfo, ref RSAParameters parameters)
{
// SubjectPublicKeyInfo::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING }
DerSequenceReader algorithm = keyInfo.ReadSequence();
string algorithmOid = algorithm.ReadOidAsString();
if (algorithmOid != RsaOid)
{
throw new CryptographicException();
}
byte[] subjectPublicKeyBytes = keyInfo.ReadBitString();
DerSequenceReader subjectPublicKey = new DerSequenceReader(subjectPublicKeyBytes);
subjectPublicKey.ReadPkcs1PublicBlob(ref parameters);
}
internal static void ReadPkcs1PublicBlob(this DerSequenceReader subjectPublicKey, ref RSAParameters parameters)
{
parameters.Modulus = KeyBlobHelpers.TrimPaddingByte(subjectPublicKey.ReadIntegerBytes());
parameters.Exponent = KeyBlobHelpers.TrimPaddingByte(subjectPublicKey.ReadIntegerBytes());
if (subjectPublicKey.HasData)
throw new CryptographicException();
}
private static void ReadPkcs1PrivateBlob(byte[] privateKeyBytes, ref RSAParameters parameters)
{
// RSAPrivateKey::= SEQUENCE {
// version Version,
// modulus INTEGER, --n
// publicExponent INTEGER, --e
// privateExponent INTEGER, --d
// prime1 INTEGER, --p
// prime2 INTEGER, --q
// exponent1 INTEGER, --d mod(p - 1)
// exponent2 INTEGER, --d mod(q - 1)
// coefficient INTEGER, --(inverse of q) mod p
// otherPrimeInfos OtherPrimeInfos OPTIONAL
// }
DerSequenceReader privateKey = new DerSequenceReader(privateKeyBytes);
int version = privateKey.ReadInteger();
if (version != 0)
{
throw new CryptographicException();
}
parameters.Modulus = KeyBlobHelpers.TrimPaddingByte(privateKey.ReadIntegerBytes());
parameters.Exponent = KeyBlobHelpers.TrimPaddingByte(privateKey.ReadIntegerBytes());
int modulusLen = parameters.Modulus.Length;
int halfModulus = modulusLen / 2;
parameters.D = KeyBlobHelpers.PadOrTrim(privateKey.ReadIntegerBytes(), modulusLen);
parameters.P = KeyBlobHelpers.PadOrTrim(privateKey.ReadIntegerBytes(), halfModulus);
parameters.Q = KeyBlobHelpers.PadOrTrim(privateKey.ReadIntegerBytes(), halfModulus);
parameters.DP = KeyBlobHelpers.PadOrTrim(privateKey.ReadIntegerBytes(), halfModulus);
parameters.DQ = KeyBlobHelpers.PadOrTrim(privateKey.ReadIntegerBytes(), halfModulus);
parameters.InverseQ = KeyBlobHelpers.PadOrTrim(privateKey.ReadIntegerBytes(), halfModulus);
if (privateKey.HasData)
{
throw new CryptographicException();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SelectManyQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// SelectMany is effectively a nested loops join. It is given two data sources, an
/// outer and an inner -- actually, the inner is sometimes calculated by invoking a
/// function for each outer element -- and we walk the outer, walking the entire
/// inner enumerator for each outer element. There is an optional result selector
/// function which can transform the output before yielding it as a result element.
///
/// Notes:
/// Although select many takes two enumerable objects as input, it appears to the
/// query analysis infrastructure as a unary operator. That's because it works a
/// little differently than the other binary operators: it has to re-open the right
/// child every time an outer element is walked. The right child is NOT partitioned.
/// </summary>
/// <typeparam name="TLeftInput"></typeparam>
/// <typeparam name="TRightInput"></typeparam>
/// <typeparam name="TOutput"></typeparam>
internal sealed class SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> : UnaryQueryOperator<TLeftInput, TOutput>
{
private readonly Func<TLeftInput, IEnumerable<TRightInput>> _rightChildSelector; // To select a new child each iteration.
private readonly Func<TLeftInput, int, IEnumerable<TRightInput>> _indexedRightChildSelector; // To select a new child each iteration.
private readonly Func<TLeftInput, TRightInput, TOutput> _resultSelector; // An optional result selection function.
private bool _prematureMerge = false; // Whether to prematurely merge the input of this operator.
private bool _limitsParallelism = false; // Whether to prematurely merge the input of this operator.
//---------------------------------------------------------------------------------------
// Initializes a new select-many operator.
//
// Arguments:
// leftChild - the left data source from which to pull data.
// rightChild - the right data source from which to pull data.
// rightChildSelector - if no right data source was supplied, the selector function
// will generate a new right child for every unique left element.
// resultSelector - a selection function for creating output elements.
//
internal SelectManyQueryOperator(IEnumerable<TLeftInput> leftChild,
Func<TLeftInput, IEnumerable<TRightInput>> rightChildSelector,
Func<TLeftInput, int, IEnumerable<TRightInput>> indexedRightChildSelector,
Func<TLeftInput, TRightInput, TOutput> resultSelector)
: base(leftChild)
{
Debug.Assert(leftChild != null, "left child data source cannot be null");
Debug.Assert(rightChildSelector != null || indexedRightChildSelector != null,
"either right child data or selector must be supplied");
Debug.Assert(rightChildSelector == null || indexedRightChildSelector == null,
"either indexed- or non-indexed child selector must be supplied (not both)");
Debug.Assert(typeof(TRightInput) == typeof(TOutput) || resultSelector != null,
"right input and output must be the same types, otherwise the result selector may not be null");
_rightChildSelector = rightChildSelector;
_indexedRightChildSelector = indexedRightChildSelector;
_resultSelector = resultSelector;
// If the SelectMany is indexed, elements must be returned in the order in which
// indices were assigned.
_outputOrdered = Child.OutputOrdered || indexedRightChildSelector != null;
InitOrderIndex();
}
private void InitOrderIndex()
{
OrdinalIndexState childIndexState = Child.OrdinalIndexState;
if (_indexedRightChildSelector != null)
{
// If this is an indexed SelectMany, we need the order keys to be Correct, so that we can pass them
// into the user delegate.
_prematureMerge = ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct);
_limitsParallelism = _prematureMerge && childIndexState != OrdinalIndexState.Shuffled;
}
else
{
if (OutputOrdered)
{
// If the output of this SelectMany is ordered, the input keys must be at least increasing. The
// SelectMany algorithm assumes that there will be no duplicate order keys, so if the order keys
// are Shuffled, we need to merge prematurely.
_prematureMerge = ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Increasing);
}
}
SetOrdinalIndexState(OrdinalIndexState.Increasing);
}
internal override void WrapPartitionedStream<TLeftKey>(
PartitionedStream<TLeftInput, TLeftKey> inputStream, IPartitionedStreamRecipient<TOutput> recipient, bool preferStriping, QuerySettings settings)
{
int partitionCount = inputStream.PartitionCount;
if (_indexedRightChildSelector != null)
{
PartitionedStream<TLeftInput, int> inputStreamInt;
// If the index is not correct, we need to reindex.
if (_prematureMerge)
{
ListQueryResults<TLeftInput> listResults =
QueryOperator<TLeftInput>.ExecuteAndCollectResults(inputStream, partitionCount, OutputOrdered, preferStriping, settings);
inputStreamInt = listResults.GetPartitionedStream();
}
else
{
inputStreamInt = (PartitionedStream<TLeftInput, int>)(object)inputStream;
}
WrapPartitionedStreamIndexed(inputStreamInt, recipient, settings);
return;
}
//
//
if (_prematureMerge)
{
PartitionedStream<TLeftInput, int> inputStreamInt =
QueryOperator<TLeftInput>.ExecuteAndCollectResults(inputStream, partitionCount, OutputOrdered, preferStriping, settings)
.GetPartitionedStream();
WrapPartitionedStreamNotIndexed(inputStreamInt, recipient, settings);
}
else
{
WrapPartitionedStreamNotIndexed(inputStream, recipient, settings);
}
}
/// <summary>
/// A helper method for WrapPartitionedStream. We use the helper to reuse a block of code twice, but with
/// a different order key type. (If premature merge occurred, the order key type will be "int". Otherwise,
/// it will be the same type as "TLeftKey" in WrapPartitionedStream.)
/// </summary>
private void WrapPartitionedStreamNotIndexed<TLeftKey>(
PartitionedStream<TLeftInput, TLeftKey> inputStream, IPartitionedStreamRecipient<TOutput> recipient, QuerySettings settings)
{
int partitionCount = inputStream.PartitionCount;
var keyComparer = new PairComparer<TLeftKey, int>(inputStream.KeyComparer, Util.GetDefaultComparer<int>());
var outputStream = new PartitionedStream<TOutput, Pair>(partitionCount, keyComparer, OrdinalIndexState);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new SelectManyQueryOperatorEnumerator<TLeftKey>(inputStream[i], this, settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
/// <summary>
/// Similar helper method to WrapPartitionedStreamNotIndexed, except that this one is for the indexed variant
/// of SelectMany (i.e., the SelectMany that passes indices into the user sequence-generating delegate)
/// </summary>
private void WrapPartitionedStreamIndexed(
PartitionedStream<TLeftInput, int> inputStream, IPartitionedStreamRecipient<TOutput> recipient, QuerySettings settings)
{
var keyComparer = new PairComparer<int, int>(inputStream.KeyComparer, Util.GetDefaultComparer<int>());
var outputStream = new PartitionedStream<TOutput, Pair<int, int>>(inputStream.PartitionCount, keyComparer, OrdinalIndexState);
for (int i = 0; i < inputStream.PartitionCount; i++)
{
outputStream[i] = new IndexedSelectManyQueryOperatorEnumerator(inputStream[i], this, settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the left child and wrapping with a
// partition if needed. The right child is not opened yet -- this is always done on demand
// as the outer elements are enumerated.
//
internal override QueryResults<TOutput> Open(QuerySettings settings, bool preferStriping)
{
QueryResults<TLeftInput> childQueryResults = Child.Open(settings, preferStriping);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TOutput> AsSequentialQuery(CancellationToken token)
{
if (_rightChildSelector != null)
{
if (_resultSelector != null)
{
return CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_rightChildSelector, _resultSelector);
}
return (IEnumerable<TOutput>)(object)(CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_rightChildSelector));
}
else
{
Debug.Assert(_indexedRightChildSelector != null);
if (_resultSelector != null)
{
return CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_indexedRightChildSelector, _resultSelector);
}
return (IEnumerable<TOutput>)(object)(CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token).SelectMany(_indexedRightChildSelector));
}
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return _limitsParallelism; }
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for executing the SelectMany logic.
//
class IndexedSelectManyQueryOperatorEnumerator : QueryOperatorEnumerator<TOutput, Pair<int, int>>
{
private readonly QueryOperatorEnumerator<TLeftInput, int> _leftSource; // The left data source to enumerate.
private readonly SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> _selectManyOperator; // The select many operator to use.
private IEnumerator<TRightInput> _currentRightSource; // The current enumerator we're using.
private IEnumerator<TOutput> _currentRightSourceAsOutput; // If we need to access the enumerator for output directly (no result selector).
private Mutables _mutables; // bag of frequently mutated value types [allocate in moveNext to avoid false-sharing]
private readonly CancellationToken _cancellationToken;
private class Mutables
{
internal int _currentRightSourceIndex = -1; // The index for the right data source.
internal TLeftInput _currentLeftElement; // The current element in the left data source.
internal int _currentLeftSourceIndex; // The current key in the left data source.
internal int _lhsCount; //counts the number of lhs elements enumerated. used for cancellation testing.
}
//---------------------------------------------------------------------------------------
// Instantiates a new select-many enumerator. Notice that the right data source is an
// enumera*BLE* not an enumera*TOR*. It is re-opened for every single element in the left
// data source.
//
internal IndexedSelectManyQueryOperatorEnumerator(QueryOperatorEnumerator<TLeftInput, int> leftSource,
SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> selectManyOperator,
CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(selectManyOperator != null);
_leftSource = leftSource;
_selectManyOperator = selectManyOperator;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Straightforward IEnumerator<T> methods.
//
internal override bool MoveNext(ref TOutput currentElement, ref Pair<int, int> currentKey)
{
while (true)
{
if (_currentRightSource == null)
{
_mutables = new Mutables();
// Check cancellation every few lhs-enumerations in case none of them are producing
// any outputs. Otherwise, we rely on the consumer of this operator to be performing the checks.
if ((_mutables._lhsCount++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// We don't have a "current" right enumerator to use. We have to fetch the next
// one. If the left has run out of elements, however, we're done and just return
// false right away.
if (!_leftSource.MoveNext(ref _mutables._currentLeftElement, ref _mutables._currentLeftSourceIndex))
{
return false;
}
// Use the source selection routine to create a right child.
IEnumerable<TRightInput> rightChild =
_selectManyOperator._indexedRightChildSelector(_mutables._currentLeftElement, _mutables._currentLeftSourceIndex);
Debug.Assert(rightChild != null);
_currentRightSource = rightChild.GetEnumerator();
Debug.Assert(_currentRightSource != null);
// If we have no result selector, we will need to access the Current element of the right
// data source as though it is a TOutput. Unfortunately, we know that TRightInput must
// equal TOutput (we check it during operator construction), but the type system doesn't.
// Thus we would have to cast the result of invoking Current from type TRightInput to
// TOutput. This is no good, since the results could be value types. Instead, we save the
// enumerator object as an IEnumerator<TOutput> and access that later on.
if (_selectManyOperator._resultSelector == null)
{
_currentRightSourceAsOutput = (IEnumerator<TOutput>)(object)_currentRightSource;
Debug.Assert(_currentRightSourceAsOutput == _currentRightSource,
"these must be equal, otherwise the surrounding logic will be broken");
}
}
if (_currentRightSource.MoveNext())
{
_mutables._currentRightSourceIndex++;
// If the inner data source has an element, we can yield it.
if (_selectManyOperator._resultSelector != null)
{
// In the case of a selection function, use that to yield the next element.
currentElement = _selectManyOperator._resultSelector(_mutables._currentLeftElement, _currentRightSource.Current);
}
else
{
// Otherwise, the right input and output types must be the same. We use the
// casted copy of the current right source and just return its current element.
Debug.Assert(_currentRightSourceAsOutput != null);
currentElement = _currentRightSourceAsOutput.Current;
}
currentKey = new Pair<int, int>(_mutables._currentLeftSourceIndex, _mutables._currentRightSourceIndex);
return true;
}
else
{
// Otherwise, we have exhausted the right data source. Loop back around and try
// to get the next left element, then its right, and so on.
_currentRightSource.Dispose();
_currentRightSource = null;
_currentRightSourceAsOutput = null;
}
}
}
protected override void Dispose(bool disposing)
{
_leftSource.Dispose();
if (_currentRightSource != null)
{
_currentRightSource.Dispose();
}
}
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for executing the SelectMany logic.
//
class SelectManyQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TOutput, Pair>
{
private readonly QueryOperatorEnumerator<TLeftInput, TLeftKey> _leftSource; // The left data source to enumerate.
private readonly SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> _selectManyOperator; // The select many operator to use.
private IEnumerator<TRightInput> _currentRightSource; // The current enumerator we're using.
private IEnumerator<TOutput> _currentRightSourceAsOutput; // If we need to access the enumerator for output directly (no result selector).
private Mutables _mutables; // bag of frequently mutated value types [allocate in moveNext to avoid false-sharing]
private readonly CancellationToken _cancellationToken;
private class Mutables
{
internal int _currentRightSourceIndex = -1; // The index for the right data source.
internal TLeftInput _currentLeftElement; // The current element in the left data source.
internal TLeftKey _currentLeftKey; // The current key in the left data source.
internal int _lhsCount; // Counts the number of lhs elements enumerated. used for cancellation testing.
}
//---------------------------------------------------------------------------------------
// Instantiates a new select-many enumerator. Notice that the right data source is an
// enumera*BLE* not an enumera*TOR*. It is re-opened for every single element in the left
// data source.
//
internal SelectManyQueryOperatorEnumerator(QueryOperatorEnumerator<TLeftInput, TLeftKey> leftSource,
SelectManyQueryOperator<TLeftInput, TRightInput, TOutput> selectManyOperator,
CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(selectManyOperator != null);
_leftSource = leftSource;
_selectManyOperator = selectManyOperator;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Straightforward IEnumerator<T> methods.
//
internal override bool MoveNext(ref TOutput currentElement, ref Pair currentKey)
{
while (true)
{
if (_currentRightSource == null)
{
_mutables = new Mutables();
// Check cancellation every few lhs-enumerations in case none of them are producing
// any outputs. Otherwise, we rely on the consumer of this operator to be performing the checks.
if ((_mutables._lhsCount++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// We don't have a "current" right enumerator to use. We have to fetch the next
// one. If the left has run out of elements, however, we're done and just return
// false right away.
if (!_leftSource.MoveNext(ref _mutables._currentLeftElement, ref _mutables._currentLeftKey))
{
return false;
}
// Use the source selection routine to create a right child.
IEnumerable<TRightInput> rightChild = _selectManyOperator._rightChildSelector(_mutables._currentLeftElement);
Debug.Assert(rightChild != null);
_currentRightSource = rightChild.GetEnumerator();
Debug.Assert(_currentRightSource != null);
// If we have no result selector, we will need to access the Current element of the right
// data source as though it is a TOutput. Unfortunately, we know that TRightInput must
// equal TOutput (we check it during operator construction), but the type system doesn't.
// Thus we would have to cast the result of invoking Current from type TRightInput to
// TOutput. This is no good, since the results could be value types. Instead, we save the
// enumerator object as an IEnumerator<TOutput> and access that later on.
if (_selectManyOperator._resultSelector == null)
{
_currentRightSourceAsOutput = (IEnumerator<TOutput>)(object)_currentRightSource;
Debug.Assert(_currentRightSourceAsOutput == _currentRightSource,
"these must be equal, otherwise the surrounding logic will be broken");
}
}
if (_currentRightSource.MoveNext())
{
_mutables._currentRightSourceIndex++;
// If the inner data source has an element, we can yield it.
if (_selectManyOperator._resultSelector != null)
{
// In the case of a selection function, use that to yield the next element.
currentElement = _selectManyOperator._resultSelector(_mutables._currentLeftElement, _currentRightSource.Current);
}
else
{
// Otherwise, the right input and output types must be the same. We use the
// casted copy of the current right source and just return its current element.
Debug.Assert(_currentRightSourceAsOutput != null);
currentElement = _currentRightSourceAsOutput.Current;
}
currentKey = new Pair(_mutables._currentLeftKey, _mutables._currentRightSourceIndex);
return true;
}
else
{
// Otherwise, we have exhausted the right data source. Loop back around and try
// to get the next left element, then its right, and so on.
_currentRightSource.Dispose();
_currentRightSource = null;
_currentRightSourceAsOutput = null;
}
}
}
protected override void Dispose(bool disposing)
{
_leftSource.Dispose();
if (_currentRightSource != null)
{
_currentRightSource.Dispose();
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenMetaverse.StructuredData;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.CoreModules.World.Land;
using Caps=OpenSim.Framework.Capabilities.Caps;
using OSDArray=OpenMetaverse.StructuredData.OSDArray;
using OSDMap=OpenMetaverse.StructuredData.OSDMap;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WorldMapModule")]
public class WorldMapModule : INonSharedRegionModule, IWorldMapModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static string LogHeader = "[WORLD MAP]";
private static readonly string DEFAULT_WORLD_MAP_EXPORT_PATH = "exportmap.jpg";
private static readonly UUID STOP_UUID = UUID.Random();
private static readonly string m_mapLayerPath = "0001/";
private OpenSim.Framework.BlockingQueue<MapRequestState> requests = new OpenSim.Framework.BlockingQueue<MapRequestState>();
protected Scene m_scene;
private List<MapBlockData> cachedMapBlocks = new List<MapBlockData>();
private int cachedTime = 0;
private int blacklistTimeout = 10*60*1000; // 10 minutes
private byte[] myMapImageJPEG;
protected volatile bool m_Enabled = false;
private Dictionary<UUID, MapRequestState> m_openRequests = new Dictionary<UUID, MapRequestState>();
private Dictionary<string, int> m_blacklistedurls = new Dictionary<string, int>();
private Dictionary<ulong, int> m_blacklistedregions = new Dictionary<ulong, int>();
private Dictionary<ulong, string> m_cachedRegionMapItemsAddress = new Dictionary<ulong, string>();
private List<UUID> m_rootAgents = new List<UUID>();
private volatile bool threadrunning = false;
private IServiceThrottleModule m_ServiceThrottle;
//private int CacheRegionsDistance = 256;
#region INonSharedRegionModule Members
public virtual void Initialise (IConfigSource config)
{
string[] configSections = new string[] { "Map", "Startup" };
if (Util.GetConfigVarFromSections<string>(
config, "WorldMapModule", configSections, "WorldMap") == "WorldMap")
m_Enabled = true;
blacklistTimeout
= Util.GetConfigVarFromSections<int>(config, "BlacklistTimeout", configSections, 10 * 60) * 1000;
}
public virtual void AddRegion (Scene scene)
{
if (!m_Enabled)
return;
lock (scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IWorldMapModule>(this);
m_scene.AddCommand(
"Regions", this, "export-map",
"export-map [<path>]",
"Save an image of the world map", HandleExportWorldMapConsoleCommand);
m_scene.AddCommand(
"Regions", this, "generate map",
"generate map",
"Generates and stores a new maptile.", HandleGenerateMapConsoleCommand);
AddHandlers();
}
}
public virtual void RemoveRegion (Scene scene)
{
if (!m_Enabled)
return;
lock (m_scene)
{
m_Enabled = false;
RemoveHandlers();
m_scene = null;
}
}
public virtual void RegionLoaded (Scene scene)
{
if (!m_Enabled)
return;
m_ServiceThrottle = scene.RequestModuleInterface<IServiceThrottleModule>();
}
public virtual void Close()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public virtual string Name
{
get { return "WorldMapModule"; }
}
#endregion
// this has to be called with a lock on m_scene
protected virtual void AddHandlers()
{
myMapImageJPEG = new byte[0];
string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString();
regionimage = regionimage.Replace("-", "");
m_log.Info("[WORLD MAP]: JPEG Map location: " + m_scene.RegionInfo.ServerURI + "index.php?method=" + regionimage);
MainServer.Instance.AddHTTPHandler(regionimage,
new GenericHTTPDOSProtector(OnHTTPGetMapImage, OnHTTPThrottled, new BasicDosProtectorOptions()
{
AllowXForwardedFor = false,
ForgetTimeSpan = TimeSpan.FromMinutes(2),
MaxRequestsInTimeframe = 4,
ReportingName = "MAPDOSPROTECTOR",
RequestTimeSpan = TimeSpan.FromSeconds(10),
ThrottledAction = BasicDOSProtector.ThrottleAction.DoThrottledMethod
}).Process);
MainServer.Instance.AddLLSDHandler(
"/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(), HandleRemoteMapItemRequest);
m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
m_scene.EventManager.OnNewClient += OnNewClient;
m_scene.EventManager.OnClientClosed += ClientLoggedOut;
m_scene.EventManager.OnMakeChildAgent += MakeChildAgent;
m_scene.EventManager.OnMakeRootAgent += MakeRootAgent;
m_scene.EventManager.OnRegionUp += OnRegionUp;
// StartThread(new object());
}
// this has to be called with a lock on m_scene
protected virtual void RemoveHandlers()
{
// StopThread();
m_scene.EventManager.OnRegionUp -= OnRegionUp;
m_scene.EventManager.OnMakeRootAgent -= MakeRootAgent;
m_scene.EventManager.OnMakeChildAgent -= MakeChildAgent;
m_scene.EventManager.OnClientClosed -= ClientLoggedOut;
m_scene.EventManager.OnNewClient -= OnNewClient;
m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString();
regionimage = regionimage.Replace("-", "");
MainServer.Instance.RemoveLLSDHandler("/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(),
HandleRemoteMapItemRequest);
MainServer.Instance.RemoveHTTPHandler("", regionimage);
}
public void OnRegisterCaps(UUID agentID, Caps caps)
{
//m_log.DebugFormat("[WORLD MAP]: OnRegisterCaps: agentID {0} caps {1}", agentID, caps);
string capsBase = "/CAPS/" + caps.CapsObjectPath;
caps.RegisterHandler(
"MapLayer",
new RestStreamHandler(
"POST",
capsBase + m_mapLayerPath,
(request, path, param, httpRequest, httpResponse)
=> MapLayerRequest(request, path, param, agentID, caps),
"MapLayer",
agentID.ToString()));
}
/// <summary>
/// Callback for a map layer request
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string MapLayerRequest(string request, string path, string param,
UUID agentID, Caps caps)
{
//try
//
//m_log.DebugFormat("[MAPLAYER]: path: {0}, param: {1}, agent:{2}",
// path, param, agentID.ToString());
// There is a major hack going on in this method. The viewer doesn't request
// map blocks (RequestMapBlocks) above 2048. That means that if we don't hack,
// grids above that cell don't have a map at all. So, here's the hack: we wait
// for this CAP request to come, and we inject the map blocks at this point.
// In a normal scenario, this request simply sends back the MapLayer (the blue color).
// In the hacked scenario, it also sends the map blocks via UDP.
//
// 6/8/2011 -- I'm adding an explicit 2048 check, so that we never forget that there is
// a hack here, and so that regions below 4096 don't get spammed with unnecessary map blocks.
if (m_scene.RegionInfo.RegionLocX >= 2048 || m_scene.RegionInfo.RegionLocY >= 2048)
{
ScenePresence avatarPresence = null;
m_scene.TryGetScenePresence(agentID, out avatarPresence);
if (avatarPresence != null)
{
bool lookup = false;
lock (cachedMapBlocks)
{
if (cachedMapBlocks.Count > 0 && ((cachedTime + 1800) > Util.UnixTimeSinceEpoch()))
{
List<MapBlockData> mapBlocks;
mapBlocks = cachedMapBlocks;
avatarPresence.ControllingClient.SendMapBlock(mapBlocks, 0);
}
else
{
lookup = true;
}
}
if (lookup)
{
List<MapBlockData> mapBlocks = new List<MapBlockData>(); ;
// Get regions that are within 8 regions of here
List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID,
(int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocX - 8),
(int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocX + 8),
(int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocY - 8),
(int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocY + 8) );
foreach (GridRegion r in regions)
{
MapBlockData block = MapBlockFromGridRegion(r, 0);
mapBlocks.Add(block);
}
avatarPresence.ControllingClient.SendMapBlock(mapBlocks, 0);
lock (cachedMapBlocks)
cachedMapBlocks = mapBlocks;
cachedTime = Util.UnixTimeSinceEpoch();
}
}
}
LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
return mapResponse.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="mapReq"></param>
/// <returns></returns>
public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq)
{
// m_log.DebugFormat("[WORLD MAP]: MapLayer Request in region: {0}", m_scene.RegionInfo.RegionName);
LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
return mapResponse;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected static OSDMapLayer GetOSDMapLayerResponse()
{
OSDMapLayer mapLayer = new OSDMapLayer();
mapLayer.Right = 5000;
mapLayer.Top = 5000;
mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006");
return mapLayer;
}
#region EventHandlers
/// <summary>
/// Registered for event
/// </summary>
/// <param name="client"></param>
private void OnNewClient(IClientAPI client)
{
client.OnRequestMapBlocks += RequestMapBlocks;
client.OnMapItemRequest += HandleMapItemRequest;
}
/// <summary>
/// Client logged out, check to see if there are any more root agents in the simulator
/// If not, stop the mapItemRequest Thread
/// Event handler
/// </summary>
/// <param name="AgentId">AgentID that logged out</param>
private void ClientLoggedOut(UUID AgentId, Scene scene)
{
lock (m_rootAgents)
{
m_rootAgents.Remove(AgentId);
}
}
#endregion
/// <summary>
/// Starts the MapItemRequest Thread
/// Note that this only gets started when there are actually agents in the region
/// Additionally, it gets stopped when there are none.
/// </summary>
/// <param name="o"></param>
private void StartThread(object o)
{
if (threadrunning) return;
threadrunning = true;
// m_log.Debug("[WORLD MAP]: Starting remote MapItem request thread");
Watchdog.StartThread(
process,
string.Format("MapItemRequestThread ({0})", m_scene.RegionInfo.RegionName),
ThreadPriority.BelowNormal,
true,
true);
}
/// <summary>
/// Enqueues a 'stop thread' MapRequestState. Causes the MapItemRequest thread to end
/// </summary>
private void StopThread()
{
MapRequestState st = new MapRequestState();
st.agentID = STOP_UUID;
st.EstateID=0;
st.flags=0;
st.godlike=false;
st.itemtype=0;
st.regionhandle=0;
requests.Enqueue(st);
}
public virtual void HandleMapItemRequest(IClientAPI remoteClient, uint flags,
uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
{
// m_log.DebugFormat("[WORLD MAP]: Handle MapItem request {0} {1}", regionhandle, itemtype);
lock (m_rootAgents)
{
if (!m_rootAgents.Contains(remoteClient.AgentId))
return;
}
uint xstart = 0;
uint ystart = 0;
Util.RegionHandleToWorldLoc(m_scene.RegionInfo.RegionHandle, out xstart, out ystart);
if (itemtype == (int)GridItemType.AgentLocations)
{
if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle)
{
// Just requesting map info about the current, local region
int tc = Environment.TickCount;
List<mapItemReply> mapitems = new List<mapItemReply>();
mapItemReply mapitem = new mapItemReply();
if (m_scene.GetRootAgentCount() <= 1)
{
mapitem = new mapItemReply(
xstart + 1,
ystart + 1,
UUID.Zero,
Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()),
0, 0);
mapitems.Add(mapitem);
}
else
{
m_scene.ForEachRootScenePresence(delegate(ScenePresence sp)
{
// Don't send a green dot for yourself
if (sp.UUID != remoteClient.AgentId)
{
mapitem = new mapItemReply(
xstart + (uint)sp.AbsolutePosition.X,
ystart + (uint)sp.AbsolutePosition.Y,
UUID.Zero,
Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()),
1, 0);
mapitems.Add(mapitem);
}
});
}
remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags);
}
else
{
// Remote Map Item Request
// ensures that the blockingqueue doesn't get borked if the GetAgents() timing changes.
RequestMapItems("",remoteClient.AgentId,flags,EstateID,godlike,itemtype,regionhandle);
}
}
else if (itemtype == (int)GridItemType.LandForSale) // Service 7 (MAP_ITEM_LAND_FOR_SALE)
{
if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle)
{
// Parcels
ILandChannel landChannel = m_scene.LandChannel;
List<ILandObject> parcels = landChannel.AllParcels();
// Local Map Item Request
List<mapItemReply> mapitems = new List<mapItemReply>();
mapItemReply mapitem = new mapItemReply();
if ((parcels != null) && (parcels.Count >= 1))
{
foreach (ILandObject parcel_interface in parcels)
{
// Play it safe
if (!(parcel_interface is LandObject))
continue;
LandObject land = (LandObject)parcel_interface;
LandData parcel = land.LandData;
// Show land for sale
if ((parcel.Flags & (uint)ParcelFlags.ForSale) == (uint)ParcelFlags.ForSale)
{
Vector3 min = parcel.AABBMin;
Vector3 max = parcel.AABBMax;
float x = (min.X+max.X)/2;
float y = (min.Y+max.Y)/2;
mapitem = new mapItemReply(
xstart + (uint)x,
ystart + (uint)y,
parcel.GlobalID,
parcel.Name,
parcel.Area,
parcel.SalePrice
);
mapitems.Add(mapitem);
}
}
}
remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags);
}
else
{
// Remote Map Item Request
// ensures that the blockingqueue doesn't get borked if the GetAgents() timing changes.
RequestMapItems("",remoteClient.AgentId,flags,EstateID,godlike,itemtype,regionhandle);
}
}
else if (itemtype == (int)GridItemType.Telehub) // Service 1 (MAP_ITEM_TELEHUB)
{
if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle)
{
List<mapItemReply> mapitems = new List<mapItemReply>();
mapItemReply mapitem = new mapItemReply();
SceneObjectGroup sog = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject);
if (sog != null)
{
mapitem = new mapItemReply(
xstart + (uint)sog.AbsolutePosition.X,
ystart + (uint)sog.AbsolutePosition.Y,
UUID.Zero,
sog.Name,
0, // color (not used)
0 // 0 = telehub / 1 = infohub
);
mapitems.Add(mapitem);
remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags);
}
}
else
{
// Remote Map Item Request
RequestMapItems("",remoteClient.AgentId,flags,EstateID,godlike,itemtype,regionhandle);
}
}
}
private int nAsyncRequests = 0;
/// <summary>
/// Processing thread main() loop for doing remote mapitem requests
/// </summary>
public void process()
{
//const int MAX_ASYNC_REQUESTS = 20;
try
{
while (true)
{
MapRequestState st = requests.Dequeue(1000);
// end gracefully
if (st.agentID == STOP_UUID)
break;
if (st.agentID != UUID.Zero)
{
bool dorequest = true;
lock (m_rootAgents)
{
if (!m_rootAgents.Contains(st.agentID))
dorequest = false;
}
if (dorequest && !m_blacklistedregions.ContainsKey(st.regionhandle))
{
while (nAsyncRequests >= MAX_ASYNC_REQUESTS) // hit the break
Thread.Sleep(80);
RequestMapItemsDelegate d = RequestMapItemsAsync;
d.BeginInvoke(st.agentID, st.flags, st.EstateID, st.godlike, st.itemtype, st.regionhandle, RequestMapItemsCompleted, null);
//OSDMap response = RequestMapItemsAsync(st.agentID, st.flags, st.EstateID, st.godlike, st.itemtype, st.regionhandle);
//RequestMapItemsCompleted(response);
Interlocked.Increment(ref nAsyncRequests);
}
}
Watchdog.UpdateThread();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[WORLD MAP]: Map item request thread terminated abnormally with exception {0}", e);
}
threadrunning = false;
Watchdog.RemoveThread();
}
const int MAX_ASYNC_REQUESTS = 20;
/// <summary>
/// Enqueues the map item request into the services throttle processing thread
/// </summary>
/// <param name="state"></param>
public void EnqueueMapItemRequest(MapRequestState st)
{
m_ServiceThrottle.Enqueue("map-item", st.regionhandle.ToString() + st.agentID.ToString(), delegate
{
if (st.agentID != UUID.Zero)
{
bool dorequest = true;
lock (m_rootAgents)
{
if (!m_rootAgents.Contains(st.agentID))
dorequest = false;
}
if (dorequest && !m_blacklistedregions.ContainsKey(st.regionhandle))
{
if (nAsyncRequests >= MAX_ASYNC_REQUESTS) // hit the break
{
// AH!!! Recursive !
// Put this request back in the queue and return
EnqueueMapItemRequest(st);
return;
}
RequestMapItemsDelegate d = RequestMapItemsAsync;
d.BeginInvoke(st.agentID, st.flags, st.EstateID, st.godlike, st.itemtype, st.regionhandle, RequestMapItemsCompleted, null);
//OSDMap response = RequestMapItemsAsync(st.agentID, st.flags, st.EstateID, st.godlike, st.itemtype, st.regionhandle);
//RequestMapItemsCompleted(response);
Interlocked.Increment(ref nAsyncRequests);
}
}
});
}
/// <summary>
/// Sends the mapitem response to the IClientAPI
/// </summary>
/// <param name="response">The OSDMap Response for the mapitem</param>
private void RequestMapItemsCompleted(IAsyncResult iar)
{
AsyncResult result = (AsyncResult)iar;
RequestMapItemsDelegate icon = (RequestMapItemsDelegate)result.AsyncDelegate;
OSDMap response = (OSDMap)icon.EndInvoke(iar);
Interlocked.Decrement(ref nAsyncRequests);
if (!response.ContainsKey("requestID"))
return;
UUID requestID = response["requestID"].AsUUID();
if (requestID != UUID.Zero)
{
MapRequestState mrs = new MapRequestState();
mrs.agentID = UUID.Zero;
lock (m_openRequests)
{
if (m_openRequests.ContainsKey(requestID))
{
mrs = m_openRequests[requestID];
m_openRequests.Remove(requestID);
}
}
if (mrs.agentID != UUID.Zero)
{
ScenePresence av = null;
m_scene.TryGetScenePresence(mrs.agentID, out av);
if (av != null)
{
if (response.ContainsKey(mrs.itemtype.ToString()))
{
List<mapItemReply> returnitems = new List<mapItemReply>();
OSDArray itemarray = (OSDArray)response[mrs.itemtype.ToString()];
for (int i = 0; i < itemarray.Count; i++)
{
OSDMap mapitem = (OSDMap)itemarray[i];
mapItemReply mi = new mapItemReply();
mi.FromOSD(mapitem);
returnitems.Add(mi);
}
av.ControllingClient.SendMapItemReply(returnitems.ToArray(), mrs.itemtype, mrs.flags);
}
// Service 7 (MAP_ITEM_LAND_FOR_SALE)
uint itemtype = (uint)GridItemType.LandForSale;
if (response.ContainsKey(itemtype.ToString()))
{
List<mapItemReply> returnitems = new List<mapItemReply>();
OSDArray itemarray = (OSDArray)response[itemtype.ToString()];
for (int i = 0; i < itemarray.Count; i++)
{
OSDMap mapitem = (OSDMap)itemarray[i];
mapItemReply mi = new mapItemReply();
mi.FromOSD(mapitem);
returnitems.Add(mi);
}
av.ControllingClient.SendMapItemReply(returnitems.ToArray(), itemtype, mrs.flags);
}
// Service 1 (MAP_ITEM_TELEHUB)
itemtype = (uint)GridItemType.Telehub;
if (response.ContainsKey(itemtype.ToString()))
{
List<mapItemReply> returnitems = new List<mapItemReply>();
OSDArray itemarray = (OSDArray)response[itemtype.ToString()];
for (int i = 0; i < itemarray.Count; i++)
{
OSDMap mapitem = (OSDMap)itemarray[i];
mapItemReply mi = new mapItemReply();
mi.FromOSD(mapitem);
returnitems.Add(mi);
}
av.ControllingClient.SendMapItemReply(returnitems.ToArray(), itemtype, mrs.flags);
}
}
}
}
}
/// <summary>
/// Enqueue the MapItem request for remote processing
/// </summary>
/// <param name="httpserver">blank string, we discover this in the process</param>
/// <param name="id">Agent ID that we are making this request on behalf</param>
/// <param name="flags">passed in from packet</param>
/// <param name="EstateID">passed in from packet</param>
/// <param name="godlike">passed in from packet</param>
/// <param name="itemtype">passed in from packet</param>
/// <param name="regionhandle">Region we're looking up</param>
public void RequestMapItems(string httpserver, UUID id, uint flags,
uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
{
MapRequestState st = new MapRequestState();
st.agentID = id;
st.flags = flags;
st.EstateID = EstateID;
st.godlike = godlike;
st.itemtype = itemtype;
st.regionhandle = regionhandle;
EnqueueMapItemRequest(st);
}
private delegate OSDMap RequestMapItemsDelegate(UUID id, uint flags,
uint EstateID, bool godlike, uint itemtype, ulong regionhandle);
/// <summary>
/// Does the actual remote mapitem request
/// This should be called from an asynchronous thread
/// Request failures get blacklisted until region restart so we don't
/// continue to spend resources trying to contact regions that are down.
/// </summary>
/// <param name="httpserver">blank string, we discover this in the process</param>
/// <param name="id">Agent ID that we are making this request on behalf</param>
/// <param name="flags">passed in from packet</param>
/// <param name="EstateID">passed in from packet</param>
/// <param name="godlike">passed in from packet</param>
/// <param name="itemtype">passed in from packet</param>
/// <param name="regionhandle">Region we're looking up</param>
/// <returns></returns>
private OSDMap RequestMapItemsAsync(UUID id, uint flags,
uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
{
// m_log.DebugFormat("[WORLDMAP]: RequestMapItemsAsync; region handle: {0} {1}", regionhandle, itemtype);
string httpserver = "";
bool blacklisted = false;
lock (m_blacklistedregions)
{
if (m_blacklistedregions.ContainsKey(regionhandle))
{
if (Environment.TickCount > (m_blacklistedregions[regionhandle] + blacklistTimeout))
{
m_log.DebugFormat("[WORLD MAP]: Unblock blacklisted region {0}", regionhandle);
m_blacklistedregions.Remove(regionhandle);
}
else
blacklisted = true;
}
}
if (blacklisted)
return new OSDMap();
UUID requestID = UUID.Random();
lock (m_cachedRegionMapItemsAddress)
{
if (m_cachedRegionMapItemsAddress.ContainsKey(regionhandle))
httpserver = m_cachedRegionMapItemsAddress[regionhandle];
}
if (httpserver.Length == 0)
{
uint x = 0, y = 0;
Util.RegionHandleToWorldLoc(regionhandle, out x, out y);
GridRegion mreg = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)x, (int)y);
if (mreg != null)
{
httpserver = mreg.ServerURI + "MAP/MapItems/" + regionhandle.ToString();
lock (m_cachedRegionMapItemsAddress)
{
if (!m_cachedRegionMapItemsAddress.ContainsKey(regionhandle))
m_cachedRegionMapItemsAddress.Add(regionhandle, httpserver);
}
}
else
{
lock (m_blacklistedregions)
{
if (!m_blacklistedregions.ContainsKey(regionhandle))
m_blacklistedregions.Add(regionhandle, Environment.TickCount);
}
//m_log.InfoFormat("[WORLD MAP]: Blacklisted region {0}", regionhandle.ToString());
}
}
blacklisted = false;
lock (m_blacklistedurls)
{
if (m_blacklistedurls.ContainsKey(httpserver))
{
if (Environment.TickCount > (m_blacklistedurls[httpserver] + blacklistTimeout))
{
m_log.DebugFormat("[WORLD MAP]: Unblock blacklisted URL {0}", httpserver);
m_blacklistedurls.Remove(httpserver);
}
else
blacklisted = true;
}
}
// Can't find the http server
if (httpserver.Length == 0 || blacklisted)
return new OSDMap();
MapRequestState mrs = new MapRequestState();
mrs.agentID = id;
mrs.EstateID = EstateID;
mrs.flags = flags;
mrs.godlike = godlike;
mrs.itemtype=itemtype;
mrs.regionhandle = regionhandle;
lock (m_openRequests)
m_openRequests.Add(requestID, mrs);
WebRequest mapitemsrequest = null;
try
{
mapitemsrequest = WebRequest.Create(httpserver);
}
catch (Exception e)
{
m_log.DebugFormat("[WORLD MAP]: Access to {0} failed with {1}", httpserver, e);
return new OSDMap();
}
mapitemsrequest.Method = "POST";
mapitemsrequest.ContentType = "application/xml+llsd";
OSDMap RAMap = new OSDMap();
// string RAMapString = RAMap.ToString();
OSD LLSDofRAMap = RAMap; // RENAME if this works
byte[] buffer = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap);
OSDMap responseMap = new OSDMap();
responseMap["requestID"] = OSD.FromUUID(requestID);
Stream os = null;
try
{ // send the Post
mapitemsrequest.ContentLength = buffer.Length; //Count bytes to send
os = mapitemsrequest.GetRequestStream();
os.Write(buffer, 0, buffer.Length); //Send it
//m_log.DebugFormat("[WORLD MAP]: Getting MapItems from {0}", httpserver);
}
catch (WebException ex)
{
m_log.WarnFormat("[WORLD MAP]: Bad send on GetMapItems {0}", ex.Message);
responseMap["connect"] = OSD.FromBoolean(false);
lock (m_blacklistedurls)
{
if (!m_blacklistedurls.ContainsKey(httpserver))
m_blacklistedurls.Add(httpserver, Environment.TickCount);
}
m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver);
return responseMap;
}
catch
{
m_log.DebugFormat("[WORLD MAP]: RequestMapItems failed for {0}", httpserver);
responseMap["connect"] = OSD.FromBoolean(false);
return responseMap;
}
finally
{
if (os != null)
os.Dispose();
}
string response_mapItems_reply = null;
{
try
{
using (WebResponse webResponse = mapitemsrequest.GetResponse())
{
if (webResponse != null)
{
using (Stream s = webResponse.GetResponseStream())
using (StreamReader sr = new StreamReader(s))
response_mapItems_reply = sr.ReadToEnd().Trim();
}
else
{
return new OSDMap();
}
}
}
catch (WebException)
{
responseMap["connect"] = OSD.FromBoolean(false);
lock (m_blacklistedurls)
{
if (!m_blacklistedurls.ContainsKey(httpserver))
m_blacklistedurls.Add(httpserver, Environment.TickCount);
}
m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver);
return responseMap;
}
catch
{
m_log.DebugFormat("[WORLD MAP]: RequestMapItems failed for {0}", httpserver);
responseMap["connect"] = OSD.FromBoolean(false);
lock (m_blacklistedregions)
{
if (!m_blacklistedregions.ContainsKey(regionhandle))
m_blacklistedregions.Add(regionhandle, Environment.TickCount);
}
return responseMap;
}
OSD rezResponse = null;
try
{
rezResponse = OSDParser.DeserializeLLSDXml(response_mapItems_reply);
responseMap = (OSDMap)rezResponse;
responseMap["requestID"] = OSD.FromUUID(requestID);
}
catch (Exception ex)
{
m_log.InfoFormat("[WORLD MAP]: exception on parse of RequestMapItems reply from {0}: {1}", httpserver, ex.Message);
responseMap["connect"] = OSD.FromBoolean(false);
lock (m_blacklistedregions)
{
if (!m_blacklistedregions.ContainsKey(regionhandle))
m_blacklistedregions.Add(regionhandle, Environment.TickCount);
}
return responseMap;
}
}
if (!responseMap.ContainsKey(itemtype.ToString())) // remote sim doesnt have the stated region handle
{
m_log.DebugFormat("[WORLD MAP]: Remote sim does not have the stated region. Blacklisting.");
lock (m_blacklistedregions)
{
if (!m_blacklistedregions.ContainsKey(regionhandle))
m_blacklistedregions.Add(regionhandle, Environment.TickCount);
}
}
return responseMap;
}
/// <summary>
/// Requests map blocks in area of minX, maxX, minY, MaxY in world cordinates
/// </summary>
/// <param name="minX"></param>
/// <param name="minY"></param>
/// <param name="maxX"></param>
/// <param name="maxY"></param>
public virtual void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag)
{
if ((flag & 0x10000) != 0) // user clicked on qthe map a tile that isn't visible
{
List<MapBlockData> response = new List<MapBlockData>();
// this should return one mapblock at most. It is triggered by a click
// on an unloaded square.
// But make sure: Look whether the one we requested is in there
List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID,
(int)Util.RegionToWorldLoc((uint)minX), (int)Util.RegionToWorldLoc((uint)maxX),
(int)Util.RegionToWorldLoc((uint)minY), (int)Util.RegionToWorldLoc((uint)maxY) );
m_log.DebugFormat("[WORLD MAP MODULE] RequestMapBlocks min=<{0},{1}>, max=<{2},{3}>, flag={4}, cntFound={5}",
minX, minY, maxX, maxY, flag.ToString("X"), regions.Count);
if (regions != null)
{
foreach (GridRegion r in regions)
{
if (r.RegionLocX == Util.RegionToWorldLoc((uint)minX)
&& r.RegionLocY == Util.RegionToWorldLoc((uint)minY) )
{
// found it => add it to response
// Version 2 viewers can handle the larger regions
if ((flag & 2) == 2)
response.AddRange(Map2BlockFromGridRegion(r, flag));
else
response.Add(MapBlockFromGridRegion(r, flag));
break;
}
}
}
if (response.Count == 0)
{
// response still empty => couldn't find the map-tile the user clicked on => tell the client
MapBlockData block = new MapBlockData();
block.X = (ushort)minX;
block.Y = (ushort)minY;
block.Access = (byte)SimAccess.Down; // means 'simulator is offline'
// block.Access = (byte)SimAccess.NonExistent;
response.Add(block);
}
// The lower 16 bits are an unsigned int16
remoteClient.SendMapBlock(response, flag & 0xffff);
}
else
{
// normal mapblock request. Use the provided values
GetAndSendBlocks(remoteClient, minX, minY, maxX, maxY, flag);
}
}
protected virtual List<MapBlockData> GetAndSendBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag)
{
List<MapBlockData> mapBlocks = new List<MapBlockData>();
List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID,
(int)Util.RegionToWorldLoc((uint)(minX - 4)), (int)Util.RegionToWorldLoc((uint)(maxX + 4)),
(int)Util.RegionToWorldLoc((uint)(minY - 4)), (int)Util.RegionToWorldLoc((uint)(maxY + 4)) );
m_log.DebugFormat("{0} GetAndSendBlocks. min=<{1},{2}>, max=<{3},{4}>, cntFound={5}",
LogHeader, minX, minY, maxX, maxY, regions.Count);
foreach (GridRegion r in regions)
{
// Version 2 viewers can handle the larger regions
if ((flag & 2) == 2)
mapBlocks.AddRange(Map2BlockFromGridRegion(r, flag));
else
mapBlocks.Add(MapBlockFromGridRegion(r, flag));
}
remoteClient.SendMapBlock(mapBlocks, flag & 0xffff);
return mapBlocks;
}
// Fill a passed MapBlockData from a GridRegion
public MapBlockData MapBlockFromGridRegion(GridRegion r, uint flag)
{
MapBlockData block = new MapBlockData();
block.Access = r.Access;
switch (flag & 0xffff)
{
case 0:
block.MapImageId = r.TerrainImage;
break;
case 2:
block.MapImageId = r.ParcelImage;
break;
default:
block.MapImageId = UUID.Zero;
break;
}
block.Name = r.RegionName;
block.X = (ushort)Util.WorldToRegionLoc((uint)r.RegionLocX);
block.Y = (ushort)Util.WorldToRegionLoc((uint)r.RegionLocY);
block.SizeX = (ushort) r.RegionSizeX;
block.SizeY = (ushort) r.RegionSizeY;
return block;
}
public List<MapBlockData> Map2BlockFromGridRegion(GridRegion r, uint flag)
{
List<MapBlockData> blocks = new List<MapBlockData>();
MapBlockData block = new MapBlockData();
if (r == null)
{
block.Access = (byte)SimAccess.Down;
block.MapImageId = UUID.Zero;
blocks.Add(block);
}
else
{
block.Access = r.Access;
switch (flag & 0xffff)
{
case 0:
block.MapImageId = r.TerrainImage;
break;
case 2:
block.MapImageId = r.ParcelImage;
break;
default:
block.MapImageId = UUID.Zero;
break;
}
block.Name = r.RegionName;
block.X = (ushort)(r.RegionLocX / Constants.RegionSize);
block.Y = (ushort)(r.RegionLocY / Constants.RegionSize);
block.SizeX = (ushort)r.RegionSizeX;
block.SizeY = (ushort)r.RegionSizeY;
blocks.Add(block);
}
return blocks;
}
public Hashtable OnHTTPThrottled(Hashtable keysvals)
{
Hashtable reply = new Hashtable();
int statuscode = 500;
reply["str_response_string"] = "";
reply["int_response_code"] = statuscode;
reply["content_type"] = "text/plain";
return reply;
}
public Hashtable OnHTTPGetMapImage(Hashtable keysvals)
{
m_log.Debug("[WORLD MAP]: Sending map image jpeg");
Hashtable reply = new Hashtable();
int statuscode = 200;
byte[] jpeg = new byte[0];
if (myMapImageJPEG.Length == 0)
{
MemoryStream imgstream = null;
Bitmap mapTexture = new Bitmap(1,1);
ManagedImage managedImage;
Image image = (Image)mapTexture;
try
{
// Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data
imgstream = new MemoryStream();
// non-async because we know we have the asset immediately.
AssetBase mapasset = m_scene.AssetService.Get(m_scene.RegionInfo.RegionSettings.TerrainImageID.ToString());
// Decode image to System.Drawing.Image
if (OpenJPEG.DecodeToImage(mapasset.Data, out managedImage, out image))
{
// Save to bitmap
mapTexture = new Bitmap(image);
EncoderParameters myEncoderParameters = new EncoderParameters();
myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
// Save bitmap to stream
mapTexture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters);
// Write the stream to a byte array for output
jpeg = imgstream.ToArray();
myMapImageJPEG = jpeg;
}
}
catch (Exception)
{
// Dummy!
m_log.Warn("[WORLD MAP]: Unable to generate Map image");
}
finally
{
// Reclaim memory, these are unmanaged resources
// If we encountered an exception, one or more of these will be null
if (mapTexture != null)
mapTexture.Dispose();
if (image != null)
image.Dispose();
if (imgstream != null)
imgstream.Dispose();
}
}
else
{
// Use cached version so we don't have to loose our mind
jpeg = myMapImageJPEG;
}
reply["str_response_string"] = Convert.ToBase64String(jpeg);
reply["int_response_code"] = statuscode;
reply["content_type"] = "image/jpeg";
return reply;
}
// From msdn
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
/// <summary>
/// Export the world map
/// </summary>
/// <param name="fileName"></param>
public void HandleExportWorldMapConsoleCommand(string module, string[] cmdparams)
{
if (m_scene.ConsoleScene() == null)
{
// FIXME: If console region is root then this will be printed by every module. Currently, there is no
// way to prevent this, short of making the entire module shared (which is complete overkill).
// One possibility is to return a bool to signal whether the module has completely handled the command
m_log.InfoFormat("[WORLD MAP]: Please change to a specific region in order to export its world map");
return;
}
if (m_scene.ConsoleScene() != m_scene)
return;
string exportPath;
if (cmdparams.Length > 1)
exportPath = cmdparams[1];
else
exportPath = DEFAULT_WORLD_MAP_EXPORT_PATH;
m_log.InfoFormat(
"[WORLD MAP]: Exporting world map for {0} to {1}", m_scene.RegionInfo.RegionName, exportPath);
List<MapBlockData> mapBlocks = new List<MapBlockData>();
List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID,
(int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocX - 9),
(int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocX + 9),
(int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocY - 9),
(int)Util.RegionToWorldLoc(m_scene.RegionInfo.RegionLocY + 9));
List<AssetBase> textures = new List<AssetBase>();
List<Image> bitImages = new List<Image>();
foreach (GridRegion r in regions)
{
MapBlockData mapBlock = MapBlockFromGridRegion(r, 0);
AssetBase texAsset = m_scene.AssetService.Get(mapBlock.MapImageId.ToString());
if (texAsset != null)
{
textures.Add(texAsset);
}
//else
//{
// // WHAT?!? This doesn't seem right. Commenting (diva)
// texAsset = m_scene.AssetService.Get(mapBlock.MapImageId.ToString());
// if (texAsset != null)
// {
// textures.Add(texAsset);
// }
//}
}
foreach (AssetBase asset in textures)
{
ManagedImage managedImage;
Image image;
if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
bitImages.Add(image);
}
Bitmap mapTexture = new Bitmap(2560, 2560);
Graphics g = Graphics.FromImage(mapTexture);
SolidBrush sea = new SolidBrush(Color.DarkBlue);
g.FillRectangle(sea, 0, 0, 2560, 2560);
for (int i = 0; i < mapBlocks.Count; i++)
{
ushort x = (ushort)((mapBlocks[i].X - m_scene.RegionInfo.RegionLocX) + 10);
ushort y = (ushort)((mapBlocks[i].Y - m_scene.RegionInfo.RegionLocY) + 10);
g.DrawImage(bitImages[i], (x * 128), 2560 - (y * 128), 128, 128); // y origin is top
}
mapTexture.Save(exportPath, ImageFormat.Jpeg);
m_log.InfoFormat(
"[WORLD MAP]: Successfully exported world map for {0} to {1}",
m_scene.RegionInfo.RegionName, exportPath);
}
public void HandleGenerateMapConsoleCommand(string module, string[] cmdparams)
{
Scene consoleScene = m_scene.ConsoleScene();
if (consoleScene != null && consoleScene != m_scene)
return;
GenerateMaptile();
}
public OSD HandleRemoteMapItemRequest(string path, OSD request, string endpoint)
{
uint xstart = 0;
uint ystart = 0;
Util.RegionHandleToWorldLoc(m_scene.RegionInfo.RegionHandle,out xstart,out ystart);
// m_log.DebugFormat("{0} HandleRemoteMapItemRequest. loc=<{1},{2}>",
// LogHeader, Util.WorldToRegionLoc(xstart), Util.WorldToRegionLoc(ystart));
// Service 6 (MAP_ITEM_AGENTS_LOCATION; green dots)
OSDMap responsemap = new OSDMap();
int tc = Environment.TickCount;
if (m_scene.GetRootAgentCount() == 0)
{
OSDMap responsemapdata = new OSDMap();
responsemapdata["X"] = OSD.FromInteger((int)(xstart + 1));
responsemapdata["Y"] = OSD.FromInteger((int)(ystart + 1));
responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()));
responsemapdata["Extra"] = OSD.FromInteger(0);
responsemapdata["Extra2"] = OSD.FromInteger(0);
OSDArray responsearr = new OSDArray();
responsearr.Add(responsemapdata);
responsemap["6"] = responsearr;
}
else
{
OSDArray responsearr = new OSDArray(m_scene.GetRootAgentCount());
m_scene.ForEachRootScenePresence(delegate(ScenePresence sp)
{
OSDMap responsemapdata = new OSDMap();
responsemapdata["X"] = OSD.FromInteger((int)(xstart + sp.AbsolutePosition.X));
responsemapdata["Y"] = OSD.FromInteger((int)(ystart + sp.AbsolutePosition.Y));
responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()));
responsemapdata["Extra"] = OSD.FromInteger(1);
responsemapdata["Extra2"] = OSD.FromInteger(0);
responsearr.Add(responsemapdata);
});
responsemap["6"] = responsearr;
}
// Service 7 (MAP_ITEM_LAND_FOR_SALE)
ILandChannel landChannel = m_scene.LandChannel;
List<ILandObject> parcels = landChannel.AllParcels();
if ((parcels == null) || (parcels.Count == 0))
{
OSDMap responsemapdata = new OSDMap();
responsemapdata["X"] = OSD.FromInteger((int)(xstart + 1));
responsemapdata["Y"] = OSD.FromInteger((int)(ystart + 1));
responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
responsemapdata["Name"] = OSD.FromString("");
responsemapdata["Extra"] = OSD.FromInteger(0);
responsemapdata["Extra2"] = OSD.FromInteger(0);
OSDArray responsearr = new OSDArray();
responsearr.Add(responsemapdata);
responsemap["7"] = responsearr;
}
else
{
OSDArray responsearr = new OSDArray(m_scene.GetRootAgentCount());
foreach (ILandObject parcel_interface in parcels)
{
// Play it safe
if (!(parcel_interface is LandObject))
continue;
LandObject land = (LandObject)parcel_interface;
LandData parcel = land.LandData;
// Show land for sale
if ((parcel.Flags & (uint)ParcelFlags.ForSale) == (uint)ParcelFlags.ForSale)
{
Vector3 min = parcel.AABBMin;
Vector3 max = parcel.AABBMax;
float x = (min.X+max.X)/2;
float y = (min.Y+max.Y)/2;
OSDMap responsemapdata = new OSDMap();
responsemapdata["X"] = OSD.FromInteger((int)(xstart + x));
responsemapdata["Y"] = OSD.FromInteger((int)(ystart + y));
// responsemapdata["Z"] = OSD.FromInteger((int)m_scene.GetGroundHeight(x,y));
responsemapdata["ID"] = OSD.FromUUID(parcel.GlobalID);
responsemapdata["Name"] = OSD.FromString(parcel.Name);
responsemapdata["Extra"] = OSD.FromInteger(parcel.Area);
responsemapdata["Extra2"] = OSD.FromInteger(parcel.SalePrice);
responsearr.Add(responsemapdata);
}
}
responsemap["7"] = responsearr;
}
if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero)
{
SceneObjectGroup sog = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject);
if (sog != null)
{
OSDArray responsearr = new OSDArray();
OSDMap responsemapdata = new OSDMap();
responsemapdata["X"] = OSD.FromInteger((int)(xstart + sog.AbsolutePosition.X));
responsemapdata["Y"] = OSD.FromInteger((int)(ystart + sog.AbsolutePosition.Y));
// responsemapdata["Z"] = OSD.FromInteger((int)m_scene.GetGroundHeight(x,y));
responsemapdata["ID"] = OSD.FromUUID(sog.UUID);
responsemapdata["Name"] = OSD.FromString(sog.Name);
responsemapdata["Extra"] = OSD.FromInteger(0); // color (unused)
responsemapdata["Extra2"] = OSD.FromInteger(0); // 0 = telehub / 1 = infohub
responsearr.Add(responsemapdata);
responsemap["1"] = responsearr;
}
}
return responsemap;
}
public void GenerateMaptile()
{
// Cannot create a map for a nonexistent heightmap
if (m_scene.Heightmap == null)
return;
//create a texture asset of the terrain
IMapImageGenerator terrain = m_scene.RequestModuleInterface<IMapImageGenerator>();
if (terrain == null)
return;
m_log.DebugFormat("[WORLD MAP]: Generating map image for {0}", m_scene.RegionInfo.RegionName);
byte[] data = terrain.WriteJpeg2000Image();
if (data == null)
return;
byte[] overlay = GenerateOverlay();
UUID terrainImageID = UUID.Random();
UUID parcelImageID = UUID.Zero;
AssetBase asset = new AssetBase(
terrainImageID,
"terrainImage_" + m_scene.RegionInfo.RegionID.ToString(),
(sbyte)AssetType.Texture,
m_scene.RegionInfo.RegionID.ToString());
asset.Data = data;
asset.Description = m_scene.RegionInfo.RegionName;
asset.Temporary = false;
asset.Flags = AssetFlags.Maptile;
// Store the new one
m_log.DebugFormat("[WORLD MAP]: Storing map tile {0} for {1}", asset.ID, m_scene.RegionInfo.RegionName);
m_scene.AssetService.Store(asset);
if (overlay != null)
{
parcelImageID = UUID.Random();
AssetBase parcels = new AssetBase(
parcelImageID,
"parcelImage_" + m_scene.RegionInfo.RegionID.ToString(),
(sbyte)AssetType.Texture,
m_scene.RegionInfo.RegionID.ToString());
parcels.Data = overlay;
parcels.Description = m_scene.RegionInfo.RegionName;
parcels.Temporary = false;
parcels.Flags = AssetFlags.Maptile;
m_scene.AssetService.Store(parcels);
}
// Switch to the new one
UUID lastTerrainImageID = m_scene.RegionInfo.RegionSettings.TerrainImageID;
UUID lastParcelImageID = m_scene.RegionInfo.RegionSettings.ParcelImageID;
m_scene.RegionInfo.RegionSettings.TerrainImageID = terrainImageID;
m_scene.RegionInfo.RegionSettings.ParcelImageID = parcelImageID;
m_scene.RegionInfo.RegionSettings.Save();
// Delete the old one
// m_log.DebugFormat("[WORLDMAP]: Deleting old map tile {0}", lastTerrainImageID);
m_scene.AssetService.Delete(lastTerrainImageID.ToString());
if (lastParcelImageID != UUID.Zero)
m_scene.AssetService.Delete(lastParcelImageID.ToString());
}
private void MakeRootAgent(ScenePresence avatar)
{
lock (m_rootAgents)
{
if (!m_rootAgents.Contains(avatar.UUID))
{
m_rootAgents.Add(avatar.UUID);
}
}
}
private void MakeChildAgent(ScenePresence avatar)
{
lock (m_rootAgents)
{
m_rootAgents.Remove(avatar.UUID);
}
}
public void OnRegionUp(GridRegion otherRegion)
{
ulong regionhandle = otherRegion.RegionHandle;
string httpserver = otherRegion.ServerURI + "MAP/MapItems/" + regionhandle.ToString();
lock (m_blacklistedregions)
{
if (!m_blacklistedregions.ContainsKey(regionhandle))
m_blacklistedregions.Remove(regionhandle);
}
lock (m_blacklistedurls)
{
if (m_blacklistedurls.ContainsKey(httpserver))
m_blacklistedurls.Remove(httpserver);
}
lock (m_cachedRegionMapItemsAddress)
{
if (!m_cachedRegionMapItemsAddress.ContainsKey(regionhandle))
m_cachedRegionMapItemsAddress.Remove(regionhandle);
}
}
private Byte[] GenerateOverlay()
{
// These need to be ints for bitmap generation
int regionSizeX = (int)m_scene.RegionInfo.RegionSizeX;
int regionSizeY = (int)m_scene.RegionInfo.RegionSizeY;
int landTileSize = LandManagementModule.LandUnit;
int regionLandTilesX = regionSizeX / landTileSize;
int regionLandTilesY = regionSizeY / landTileSize;
using (Bitmap overlay = new Bitmap(regionSizeX, regionSizeY))
{
bool[,] saleBitmap = new bool[regionLandTilesX, regionLandTilesY];
for (int x = 0; x < regionLandTilesX; x++)
{
for (int y = 0; y < regionLandTilesY; y++)
saleBitmap[x, y] = false;
}
bool landForSale = false;
List<ILandObject> parcels = m_scene.LandChannel.AllParcels();
Color background = Color.FromArgb(0, 0, 0, 0);
using (Graphics g = Graphics.FromImage(overlay))
{
using (SolidBrush transparent = new SolidBrush(background))
g.FillRectangle(transparent, 0, 0, regionSizeX, regionSizeY);
foreach (ILandObject land in parcels)
{
// m_log.DebugFormat("[WORLD MAP]: Parcel {0} flags {1}", land.LandData.Name, land.LandData.Flags);
if ((land.LandData.Flags & (uint)ParcelFlags.ForSale) != 0)
{
landForSale = true;
saleBitmap = land.MergeLandBitmaps(saleBitmap, land.GetLandBitmap());
}
}
if (!landForSale)
{
m_log.DebugFormat("[WORLD MAP]: Region {0} has no parcels for sale, not generating overlay", m_scene.RegionInfo.RegionName);
return null;
}
m_log.DebugFormat("[WORLD MAP]: Region {0} has parcels for sale, generating overlay", m_scene.RegionInfo.RegionName);
using (SolidBrush yellow = new SolidBrush(Color.FromArgb(255, 249, 223, 9)))
{
for (int x = 0 ; x < regionLandTilesX ; x++)
{
for (int y = 0 ; y < regionLandTilesY ; y++)
{
if (saleBitmap[x, y])
g.FillRectangle(
yellow, x * landTileSize,
regionSizeX - landTileSize - (y * landTileSize),
landTileSize,
landTileSize);
}
}
}
}
try
{
return OpenJPEG.EncodeFromImage(overlay, true);
}
catch (Exception e)
{
m_log.DebugFormat("[WORLD MAP]: Error creating parcel overlay: " + e.ToString());
}
}
return null;
}
}
public struct MapRequestState
{
public UUID agentID;
public uint flags;
public uint EstateID;
public bool godlike;
public uint itemtype;
public ulong regionhandle;
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Settings/Master/Item/PokeballAttributes.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Settings.Master.Item {
/// <summary>Holder for reflection information generated from POGOProtos/Settings/Master/Item/PokeballAttributes.proto</summary>
public static partial class PokeballAttributesReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Settings/Master/Item/PokeballAttributes.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PokeballAttributesReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjhQT0dPUHJvdG9zL1NldHRpbmdzL01hc3Rlci9JdGVtL1Bva2ViYWxsQXR0",
"cmlidXRlcy5wcm90bxIfUE9HT1Byb3Rvcy5TZXR0aW5ncy5NYXN0ZXIuSXRl",
"bRohUE9HT1Byb3Rvcy9FbnVtcy9JdGVtRWZmZWN0LnByb3RvIpUBChJQb2tl",
"YmFsbEF0dHJpYnV0ZXMSMQoLaXRlbV9lZmZlY3QYASABKA4yHC5QT0dPUHJv",
"dG9zLkVudW1zLkl0ZW1FZmZlY3QSFQoNY2FwdHVyZV9tdWx0aRgCIAEoAhIc",
"ChRjYXB0dXJlX211bHRpX2VmZmVjdBgDIAEoAhIXCg9pdGVtX2VmZmVjdF9t",
"b2QYBCABKAJiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Enums.ItemEffectReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.Master.Item.PokeballAttributes), global::POGOProtos.Settings.Master.Item.PokeballAttributes.Parser, new[]{ "ItemEffect", "CaptureMulti", "CaptureMultiEffect", "ItemEffectMod" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class PokeballAttributes : pb::IMessage<PokeballAttributes> {
private static readonly pb::MessageParser<PokeballAttributes> _parser = new pb::MessageParser<PokeballAttributes>(() => new PokeballAttributes());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PokeballAttributes> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Settings.Master.Item.PokeballAttributesReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PokeballAttributes() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PokeballAttributes(PokeballAttributes other) : this() {
itemEffect_ = other.itemEffect_;
captureMulti_ = other.captureMulti_;
captureMultiEffect_ = other.captureMultiEffect_;
itemEffectMod_ = other.itemEffectMod_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PokeballAttributes Clone() {
return new PokeballAttributes(this);
}
/// <summary>Field number for the "item_effect" field.</summary>
public const int ItemEffectFieldNumber = 1;
private global::POGOProtos.Enums.ItemEffect itemEffect_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.ItemEffect ItemEffect {
get { return itemEffect_; }
set {
itemEffect_ = value;
}
}
/// <summary>Field number for the "capture_multi" field.</summary>
public const int CaptureMultiFieldNumber = 2;
private float captureMulti_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float CaptureMulti {
get { return captureMulti_; }
set {
captureMulti_ = value;
}
}
/// <summary>Field number for the "capture_multi_effect" field.</summary>
public const int CaptureMultiEffectFieldNumber = 3;
private float captureMultiEffect_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float CaptureMultiEffect {
get { return captureMultiEffect_; }
set {
captureMultiEffect_ = value;
}
}
/// <summary>Field number for the "item_effect_mod" field.</summary>
public const int ItemEffectModFieldNumber = 4;
private float itemEffectMod_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float ItemEffectMod {
get { return itemEffectMod_; }
set {
itemEffectMod_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PokeballAttributes);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PokeballAttributes other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ItemEffect != other.ItemEffect) return false;
if (CaptureMulti != other.CaptureMulti) return false;
if (CaptureMultiEffect != other.CaptureMultiEffect) return false;
if (ItemEffectMod != other.ItemEffectMod) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ItemEffect != 0) hash ^= ItemEffect.GetHashCode();
if (CaptureMulti != 0F) hash ^= CaptureMulti.GetHashCode();
if (CaptureMultiEffect != 0F) hash ^= CaptureMultiEffect.GetHashCode();
if (ItemEffectMod != 0F) hash ^= ItemEffectMod.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ItemEffect != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) ItemEffect);
}
if (CaptureMulti != 0F) {
output.WriteRawTag(21);
output.WriteFloat(CaptureMulti);
}
if (CaptureMultiEffect != 0F) {
output.WriteRawTag(29);
output.WriteFloat(CaptureMultiEffect);
}
if (ItemEffectMod != 0F) {
output.WriteRawTag(37);
output.WriteFloat(ItemEffectMod);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ItemEffect != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ItemEffect);
}
if (CaptureMulti != 0F) {
size += 1 + 4;
}
if (CaptureMultiEffect != 0F) {
size += 1 + 4;
}
if (ItemEffectMod != 0F) {
size += 1 + 4;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PokeballAttributes other) {
if (other == null) {
return;
}
if (other.ItemEffect != 0) {
ItemEffect = other.ItemEffect;
}
if (other.CaptureMulti != 0F) {
CaptureMulti = other.CaptureMulti;
}
if (other.CaptureMultiEffect != 0F) {
CaptureMultiEffect = other.CaptureMultiEffect;
}
if (other.ItemEffectMod != 0F) {
ItemEffectMod = other.ItemEffectMod;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
itemEffect_ = (global::POGOProtos.Enums.ItemEffect) input.ReadEnum();
break;
}
case 21: {
CaptureMulti = input.ReadFloat();
break;
}
case 29: {
CaptureMultiEffect = input.ReadFloat();
break;
}
case 37: {
ItemEffectMod = input.ReadFloat();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using UnityEngine;
using System.Collections.Generic;
using tk2dRuntime.TileMap;
[System.Flags]
public enum tk2dTileFlags {
None = 0x00000000,
FlipX = 0x01000000,
FlipY = 0x02000000,
Rot90 = 0x04000000,
}
[ExecuteInEditMode]
[AddComponentMenu("2D Toolkit/TileMap/TileMap")]
/// <summary>
/// Tile Map
/// </summary>
public class tk2dTileMap : MonoBehaviour, tk2dRuntime.ISpriteCollectionForceBuild
{
/// <summary>
/// This is a link to the editor data object (tk2dTileMapEditorData).
/// It contains presets, and other data which isn't really relevant in game.
/// </summary>
public string editorDataGUID = "";
/// <summary>
/// Tile map data, stores shared parameters for tilemaps
/// </summary>
public tk2dTileMapData data;
/// <summary>
/// Tile map render and collider object
/// </summary>
public GameObject renderData;
/// <summary>
/// The sprite collection used by the tilemap
/// </summary>
[SerializeField]
private tk2dSpriteCollectionData spriteCollection = null;
public tk2dSpriteCollectionData Editor__SpriteCollection
{
get
{
return spriteCollection;
}
set
{
spriteCollection = value;
}
}
public tk2dSpriteCollectionData SpriteCollectionInst
{
get
{
if (spriteCollection != null)
return spriteCollection.inst;
else
return null;
}
}
[SerializeField]
int spriteCollectionKey;
/// <summary>Width of the tilemap</summary>
public int width = 128;
/// <summary>Height of the tilemap</summary>
public int height = 128;
/// <summary>X axis partition size for this tilemap</summary>
public int partitionSizeX = 32;
/// <summary>Y axis partition size for this tilemap</summary>
public int partitionSizeY = 32;
[SerializeField]
Layer[] layers;
[SerializeField]
ColorChannel colorChannel;
[SerializeField]
GameObject prefabsRoot;
[System.Serializable]
public class TilemapPrefabInstance {
public int x, y, layer;
public GameObject instance;
}
[SerializeField]
List<TilemapPrefabInstance> tilePrefabsList = new List<TilemapPrefabInstance>();
[SerializeField]
bool _inEditMode = false;
public bool AllowEdit { get { return _inEditMode; } }
// holds a path to a serialized mesh, uses this to work out dump directory for meshes
public string serializedMeshPath;
void Awake()
{
bool spriteCollectionKeyMatch = true;
if (SpriteCollectionInst && (SpriteCollectionInst.buildKey != spriteCollectionKey || SpriteCollectionInst.needMaterialInstance)) {
spriteCollectionKeyMatch = false;
}
if (Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.OSXEditor)
{
if ((Application.isPlaying && _inEditMode == true) || !spriteCollectionKeyMatch)
{
// Switched to edit mode while still in edit mode, rebuild
EndEditMode();
}
else {
if (spriteCollection != null && data != null && renderData == null) {
Build(BuildFlags.ForceBuild);
}
}
}
else
{
if (_inEditMode == true)
{
Debug.LogError("Tilemap " + name + " is still in edit mode. Please fix." +
"Building overhead will be significant.");
EndEditMode();
}
else if (!spriteCollectionKeyMatch)
{
Build(BuildFlags.ForceBuild);
}
else if (spriteCollection != null && data != null && renderData == null) {
Build(BuildFlags.ForceBuild);
}
}
}
#if UNITY_EDITOR
void OnEnable() {
if (spriteCollection != null && data != null && renderData != null
&& SpriteCollectionInst != null && SpriteCollectionInst.needMaterialInstance) {
bool needBuild = false;
if (layers != null) {
foreach (tk2dRuntime.TileMap.Layer layer in layers) {
if (layer.spriteChannel != null && layer.spriteChannel.chunks != null) {
foreach (tk2dRuntime.TileMap.SpriteChunk chunk in layer.spriteChannel.chunks) {
if (chunk.gameObject != null && chunk.gameObject.renderer != null) {
if (chunk.gameObject.renderer.sharedMaterial == null) {
needBuild = true;
break;
}
}
}
}
}
}
if (needBuild) {
Build(BuildFlags.ForceBuild);
}
}
}
#endif
void OnDestroy() {
if (layers != null) {
foreach (tk2dRuntime.TileMap.Layer layer in layers) {
layer.DestroyGameData(this);
}
}
if (renderData != null) {
tk2dUtil.DestroyImmediate(renderData);
}
}
#if UNITY_EDITOR
void OnDrawGizmos() {
if (data != null) {
Vector3 p0 = data.tileOrigin;
Vector3 p1 = new Vector3(p0.x + data.tileSize.x * width, p0.y + data.tileSize.y * height, 0.0f);
Gizmos.color = Color.clear;
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawCube((p0 + p1) * 0.5f, (p1 - p0));
Gizmos.matrix = Matrix4x4.identity;
Gizmos.color = Color.white;
}
}
#endif
[System.Flags]
public enum BuildFlags {
Default = 0,
EditMode = 1,
ForceBuild = 2
};
/// <summary>
/// Builds the tilemap. Call this after using the SetTile functions to
/// rebuild the affected partitions. Build only rebuilds affected partitions
/// and is efficent enough to use at runtime if you don't use Unity colliders.
/// Avoid building tilemaps every frame if you use Unity colliders as it will
/// likely be too slow for runtime use.
/// </summary>
public void Build() { Build(BuildFlags.Default); }
/// <summary>
/// Like <see cref="T:Build"/> above, but forces a build of all partitions.
/// </summary>
public void ForceBuild() { Build(BuildFlags.ForceBuild); }
// Clears all spawned instances, but retains the renderData object
void ClearSpawnedInstances()
{
if (layers == null)
return;
BuilderUtil.HideTileMapPrefabs( this );
for (int layerIdx = 0; layerIdx < layers.Length; ++layerIdx)
{
Layer layer = layers[layerIdx];
for (int chunkIdx = 0; chunkIdx < layer.spriteChannel.chunks.Length; ++chunkIdx)
{
var chunk = layer.spriteChannel.chunks[chunkIdx];
if (chunk.gameObject == null)
continue;
var transform = chunk.gameObject.transform;
List<Transform> children = new List<Transform>();
for (int i = 0; i < transform.childCount; ++i)
children.Add(transform.GetChild(i));
for (int i = 0; i < children.Count; ++i)
tk2dUtil.DestroyImmediate(children[i].gameObject);
}
}
}
void SetPrefabsRootActive(bool active) {
if (prefabsRoot != null)
#if UNITY_3_5
prefabsRoot.SetActiveRecursively(active);
#else
tk2dUtil.SetActive(prefabsRoot, active);
#endif
}
public void Build(BuildFlags buildFlags)
{
#if UNITY_EDITOR || !UNITY_FLASH
// Sanitize tilePrefabs input, to avoid branches later
if (data != null && spriteCollection != null)
{
if (data.tilePrefabs == null)
data.tilePrefabs = new GameObject[SpriteCollectionInst.Count];
else if (data.tilePrefabs.Length != SpriteCollectionInst.Count)
System.Array.Resize(ref data.tilePrefabs, SpriteCollectionInst.Count);
// Fix up data if necessary
BuilderUtil.InitDataStore(this);
}
else
{
return;
}
// Sanitize sprite collection material ids
if (SpriteCollectionInst)
SpriteCollectionInst.InitMaterialIds();
bool forceBuild = (buildFlags & BuildFlags.ForceBuild) != 0;
// When invalid, everything needs to be rebuilt
if (SpriteCollectionInst && SpriteCollectionInst.buildKey != spriteCollectionKey)
forceBuild = true;
// Remember active layers
Dictionary<Layer, bool> layersActive = new Dictionary<Layer,bool>();
if (layers != null)
{
for (int layerIdx = 0; layerIdx < layers.Length; ++layerIdx)
{
Layer layer = layers[layerIdx];
if (layer != null && layer.gameObject != null)
{
#if UNITY_3_5
layersActive[layer] = layer.gameObject.active;
#else
layersActive[layer] = layer.gameObject.activeSelf;
#endif
}
}
}
if (forceBuild) {
ClearSpawnedInstances();
}
BuilderUtil.CreateRenderData(this, _inEditMode, layersActive);
RenderMeshBuilder.Build(this, _inEditMode, forceBuild);
if (!_inEditMode)
{
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
tk2dSpriteDefinition def = SpriteCollectionInst.FirstValidDefinition;
if (def != null && def.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D) {
ColliderBuilder2D.Build(this, forceBuild);
}
else
#endif
{
ColliderBuilder3D.Build(this, forceBuild);
}
BuilderUtil.SpawnPrefabs(this, forceBuild);
}
// Clear dirty flag on everything
foreach (var layer in layers)
layer.ClearDirtyFlag();
if (colorChannel != null)
colorChannel.ClearDirtyFlag();
// Update sprite collection key
if (SpriteCollectionInst)
spriteCollectionKey = SpriteCollectionInst.buildKey;
#endif
}
/// <summary>
/// Gets the tile coordinate at position. This can be used to obtain tile or color data explicitly from layers
/// Returns true if the position is within the tilemap bounds
/// </summary>
public bool GetTileAtPosition(Vector3 position, out int x, out int y)
{
float ox, oy;
bool b = GetTileFracAtPosition(position, out ox, out oy);
x = (int)ox;
y = (int)oy;
return b;
}
/// <summary>
/// Gets the tile coordinate at position. This can be used to obtain tile or color data explicitly from layers
/// The fractional value returned is the fraction into the current tile
/// Returns true if the position is within the tilemap bounds
/// </summary>
public bool GetTileFracAtPosition(Vector3 position, out float x, out float y)
{
switch (data.tileType)
{
case tk2dTileMapData.TileType.Rectangular:
{
Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position);
x = (localPosition.x - data.tileOrigin.x) / data.tileSize.x;
y = (localPosition.y - data.tileOrigin.y) / data.tileSize.y;
return (x >= 0 && x < width && y >= 0 && y < height);
}
case tk2dTileMapData.TileType.Isometric:
{
if (data.tileSize.x == 0.0f)
break;
float tileAngle = Mathf.Atan2(data.tileSize.y, data.tileSize.x / 2.0f);
Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position);
x = (localPosition.x - data.tileOrigin.x) / data.tileSize.x;
y = ((localPosition.y - data.tileOrigin.y) / (data.tileSize.y));
float fy = y * 0.5f;
int iy = (int)fy;
float fry = fy - iy;
float frx = x % 1.0f;
x = (int)x;
y = iy * 2;
if (frx > 0.5f)
{
if (fry > 0.5f && Mathf.Atan2(1.0f - fry, (frx - 0.5f) * 2) < tileAngle)
y += 1;
else if (fry < 0.5f && Mathf.Atan2(fry, (frx - 0.5f) * 2) < tileAngle)
y -= 1;
}
else if (frx < 0.5f)
{
if (fry > 0.5f && Mathf.Atan2(fry - 0.5f, frx * 2) > tileAngle)
{
y += 1;
x -= 1;
}
if (fry < 0.5f && Mathf.Atan2(fry, (0.5f - frx) * 2) < tileAngle)
{
y -= 1;
x -= 1;
}
}
return (x >= 0 && x < width && y >= 0 && y < height);
}
}
x = 0.0f;
y = 0.0f;
return false;
}
/// <summary>
/// Returns the tile position in world space
/// </summary>
public Vector3 GetTilePosition(int x, int y)
{
switch (data.tileType)
{
case tk2dTileMapData.TileType.Rectangular:
default:
{
Vector3 localPosition = new Vector3(
x * data.tileSize.x + data.tileOrigin.x,
y * data.tileSize.y + data.tileOrigin.y,
0);
return transform.localToWorldMatrix.MultiplyPoint(localPosition);
}
case tk2dTileMapData.TileType.Isometric:
{
Vector3 localPosition = new Vector3(
((float)x + (((y & 1) == 0) ? 0.0f : 0.5f)) * data.tileSize.x + data.tileOrigin.x,
y * data.tileSize.y + data.tileOrigin.y,
0);
return transform.localToWorldMatrix.MultiplyPoint(localPosition);
}
}
}
/// <summary>
/// Gets the tile at position. This can be used to obtain tile data, etc
/// -1 = no data or empty tile
/// </summary>
public int GetTileIdAtPosition(Vector3 position, int layer)
{
if (layer < 0 || layer >= layers.Length)
return -1;
int x, y;
if (!GetTileAtPosition(position, out x, out y))
return -1;
return layers[layer].GetTile(x, y);
}
/// <summary>
/// Returns the tile info chunk for the tile. Use this to store additional metadata
/// </summary>
public tk2dRuntime.TileMap.TileInfo GetTileInfoForTileId(int tileId)
{
return data.GetTileInfoForSprite(tileId);
}
/// <summary>
/// Gets the tile at position. This can be used to obtain tile data, etc
/// -1 = no data or empty tile
/// </summary>
public Color GetInterpolatedColorAtPosition(Vector3 position)
{
Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position);
int x = (int)((localPosition.x - data.tileOrigin.x) / data.tileSize.x);
int y = (int)((localPosition.y - data.tileOrigin.y) / data.tileSize.y);
if (colorChannel == null || colorChannel.IsEmpty)
return Color.white;
if (x < 0 || x >= width ||
y < 0 || y >= height)
{
return colorChannel.clearColor;
}
int offset;
ColorChunk colorChunk = colorChannel.FindChunkAndCoordinate(x, y, out offset);
if (colorChunk.Empty)
{
return colorChannel.clearColor;
}
else
{
int colorChunkRowOffset = partitionSizeX + 1;
Color tileColorx0y0 = colorChunk.colors[offset];
Color tileColorx1y0 = colorChunk.colors[offset + 1];
Color tileColorx0y1 = colorChunk.colors[offset + colorChunkRowOffset];
Color tileColorx1y1 = colorChunk.colors[offset + colorChunkRowOffset + 1];
float wx = x * data.tileSize.x + data.tileOrigin.x;
float wy = y * data.tileSize.y + data.tileOrigin.y;
float ix = (localPosition.x - wx) / data.tileSize.x;
float iy = (localPosition.y - wy) / data.tileSize.y;
Color cy0 = Color.Lerp(tileColorx0y0, tileColorx1y0, ix);
Color cy1 = Color.Lerp(tileColorx0y1, tileColorx1y1, ix);
return Color.Lerp(cy0, cy1, iy);
}
}
// ISpriteCollectionBuilder
public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection)
{
return (this.spriteCollection != null) && (spriteCollection == this.spriteCollection || spriteCollection == this.spriteCollection.inst);
}
// We might need to end edit mode when running in game
public void EndEditMode()
{
_inEditMode = false;
SetPrefabsRootActive(true);
Build(BuildFlags.ForceBuild);
if (prefabsRoot != null) {
tk2dUtil.DestroyImmediate(prefabsRoot);
prefabsRoot = null;
}
}
#if UNITY_EDITOR
public void BeginEditMode()
{
if (layers == null) {
_inEditMode = true;
return;
}
if (!_inEditMode) {
_inEditMode = true;
// Destroy all children
// Only necessary when switching INTO edit mode
BuilderUtil.HideTileMapPrefabs(this);
SetPrefabsRootActive(false);
}
Build(BuildFlags.ForceBuild);
}
public bool AreSpritesInitialized()
{
return layers != null;
}
public bool HasColorChannel()
{
return (colorChannel != null && !colorChannel.IsEmpty);
}
public void CreateColorChannel()
{
colorChannel = new ColorChannel(width, height, partitionSizeX, partitionSizeY);
colorChannel.Create();
}
public void DeleteColorChannel()
{
colorChannel.Delete();
}
public void DeleteSprites(int layerId, int x0, int y0, int x1, int y1)
{
x0 = Mathf.Clamp(x0, 0, width - 1);
y0 = Mathf.Clamp(y0, 0, height - 1);
x1 = Mathf.Clamp(x1, 0, width - 1);
y1 = Mathf.Clamp(y1, 0, height - 1);
int numTilesX = x1 - x0 + 1;
int numTilesY = y1 - y0 + 1;
var layer = layers[layerId];
for (int y = 0; y < numTilesY; ++y)
{
for (int x = 0; x < numTilesX; ++x)
{
layer.SetTile(x0 + x, y0 + y, -1);
}
}
layer.OptimizeIncremental();
}
#endif
public void TouchMesh(Mesh mesh)
{
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(mesh);
#endif
}
public void DestroyMesh(Mesh mesh)
{
#if UNITY_EDITOR
if (UnityEditor.AssetDatabase.GetAssetPath(mesh).Length != 0)
{
mesh.Clear();
UnityEditor.AssetDatabase.DeleteAsset(UnityEditor.AssetDatabase.GetAssetPath(mesh));
}
else
{
tk2dUtil.DestroyImmediate(mesh);
}
#else
tk2dUtil.DestroyImmediate(mesh);
#endif
}
public int GetTilePrefabsListCount() {
return tilePrefabsList.Count;
}
public List<TilemapPrefabInstance> TilePrefabsList {
get {
return tilePrefabsList;
}
}
public void GetTilePrefabsListItem(int index, out int x, out int y, out int layer, out GameObject instance) {
TilemapPrefabInstance item = tilePrefabsList[index];
x = item.x;
y = item.y;
layer = item.layer;
instance = item.instance;
}
public void SetTilePrefabsList(List<int> xs, List<int> ys, List<int> layers, List<GameObject> instances) {
int n = instances.Count;
tilePrefabsList = new List<TilemapPrefabInstance>(n);
for (int i = 0; i < n; ++i) {
TilemapPrefabInstance item = new TilemapPrefabInstance();
item.x = xs[i];
item.y = ys[i];
item.layer = layers[i];
item.instance = instances[i];
tilePrefabsList.Add(item);
}
}
/// <summary>
/// Gets or sets the layers.
/// </summary>
public Layer[] Layers
{
get { return layers; }
set { layers = value; }
}
/// <summary>
/// Gets or sets the color channel.
/// </summary>
public ColorChannel ColorChannel
{
get { return colorChannel; }
set { colorChannel = value; }
}
/// <summary>
/// Gets or sets the prefabs root.
/// </summary>
public GameObject PrefabsRoot
{
get { return prefabsRoot; }
set { prefabsRoot = value; }
}
/// <summary>Gets the tile on a layer at x, y</summary>
/// <returns>The tile - either a sprite Id or -1 if the tile is empty.</returns>
public int GetTile(int x, int y, int layer) {
if (layer < 0 || layer >= layers.Length)
return -1;
return layers[layer].GetTile(x, y);
}
/// <summary>Gets the tile flags on a layer at x, y</summary>
/// <returns>The tile flags - a combination of tk2dTileFlags</returns>
public tk2dTileFlags GetTileFlags(int x, int y, int layer) {
if (layer < 0 || layer >= layers.Length)
return tk2dTileFlags.None;
return layers[layer].GetTileFlags(x, y);
}
/// <summary>Sets the tile on a layer at x, y - either a sprite Id or -1 if the tile is empty.</summary>
public void SetTile(int x, int y, int layer, int tile) {
if (layer < 0 || layer >= layers.Length)
return;
layers[layer].SetTile(x, y, tile);
}
/// <summary>Sets the tile flags on a layer at x, y - a combination of tk2dTileFlags</summary>
public void SetTileFlags(int x, int y, int layer, tk2dTileFlags flags) {
if (layer < 0 || layer >= layers.Length)
return;
layers[layer].SetTileFlags(x, y, flags);
}
/// <summary>Clears the tile on a layer at x, y</summary>
public void ClearTile(int x, int y, int layer) {
if (layer < 0 || layer >= layers.Length)
return;
layers[layer].ClearTile(x, y);
}
}
| |
// 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.Windows.Media;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Language.Intellisense;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static class GlyphExtensions
{
public static StandardGlyphGroup GetStandardGlyphGroup(this Glyph glyph)
{
switch (glyph)
{
case Glyph.Assembly:
return StandardGlyphGroup.GlyphAssembly;
case Glyph.BasicFile:
case Glyph.BasicProject:
return StandardGlyphGroup.GlyphVBProject;
case Glyph.ClassPublic:
case Glyph.ClassProtected:
case Glyph.ClassPrivate:
case Glyph.ClassInternal:
return StandardGlyphGroup.GlyphGroupClass;
case Glyph.ConstantPublic:
case Glyph.ConstantProtected:
case Glyph.ConstantPrivate:
case Glyph.ConstantInternal:
return StandardGlyphGroup.GlyphGroupConstant;
case Glyph.CSharpFile:
return StandardGlyphGroup.GlyphCSharpFile;
case Glyph.CSharpProject:
return StandardGlyphGroup.GlyphCoolProject;
case Glyph.DelegatePublic:
case Glyph.DelegateProtected:
case Glyph.DelegatePrivate:
case Glyph.DelegateInternal:
return StandardGlyphGroup.GlyphGroupDelegate;
case Glyph.EnumPublic:
case Glyph.EnumProtected:
case Glyph.EnumPrivate:
case Glyph.EnumInternal:
return StandardGlyphGroup.GlyphGroupEnum;
case Glyph.EnumMember:
return StandardGlyphGroup.GlyphGroupEnumMember;
case Glyph.Error:
return StandardGlyphGroup.GlyphGroupError;
case Glyph.ExtensionMethodPublic:
return StandardGlyphGroup.GlyphExtensionMethod;
case Glyph.ExtensionMethodProtected:
return StandardGlyphGroup.GlyphExtensionMethodProtected;
case Glyph.ExtensionMethodPrivate:
return StandardGlyphGroup.GlyphExtensionMethodPrivate;
case Glyph.ExtensionMethodInternal:
return StandardGlyphGroup.GlyphExtensionMethodInternal;
case Glyph.EventPublic:
case Glyph.EventProtected:
case Glyph.EventPrivate:
case Glyph.EventInternal:
return StandardGlyphGroup.GlyphGroupEvent;
case Glyph.FieldPublic:
case Glyph.FieldProtected:
case Glyph.FieldPrivate:
case Glyph.FieldInternal:
return StandardGlyphGroup.GlyphGroupField;
case Glyph.InterfacePublic:
case Glyph.InterfaceProtected:
case Glyph.InterfacePrivate:
case Glyph.InterfaceInternal:
return StandardGlyphGroup.GlyphGroupInterface;
case Glyph.Intrinsic:
return StandardGlyphGroup.GlyphGroupIntrinsic;
case Glyph.Keyword:
return StandardGlyphGroup.GlyphKeyword;
case Glyph.Label:
return StandardGlyphGroup.GlyphGroupIntrinsic;
case Glyph.Local:
return StandardGlyphGroup.GlyphGroupVariable;
case Glyph.Namespace:
return StandardGlyphGroup.GlyphGroupNamespace;
case Glyph.MethodPublic:
case Glyph.MethodProtected:
case Glyph.MethodPrivate:
case Glyph.MethodInternal:
return StandardGlyphGroup.GlyphGroupMethod;
case Glyph.ModulePublic:
case Glyph.ModuleProtected:
case Glyph.ModulePrivate:
case Glyph.ModuleInternal:
return StandardGlyphGroup.GlyphGroupModule;
case Glyph.OpenFolder:
return StandardGlyphGroup.GlyphOpenFolder;
case Glyph.Operator:
return StandardGlyphGroup.GlyphGroupOperator;
case Glyph.Parameter:
return StandardGlyphGroup.GlyphGroupVariable;
case Glyph.PropertyPublic:
case Glyph.PropertyProtected:
case Glyph.PropertyPrivate:
case Glyph.PropertyInternal:
return StandardGlyphGroup.GlyphGroupProperty;
case Glyph.RangeVariable:
return StandardGlyphGroup.GlyphGroupVariable;
case Glyph.Reference:
return StandardGlyphGroup.GlyphReference;
case Glyph.StructurePublic:
case Glyph.StructureProtected:
case Glyph.StructurePrivate:
case Glyph.StructureInternal:
return StandardGlyphGroup.GlyphGroupStruct;
case Glyph.TypeParameter:
return StandardGlyphGroup.GlyphGroupType;
case Glyph.Snippet:
return StandardGlyphGroup.GlyphCSharpExpansion;
case Glyph.CompletionWarning:
return StandardGlyphGroup.GlyphCompletionWarning;
default:
throw new ArgumentException("glyph");
}
}
public static StandardGlyphItem GetStandardGlyphItem(this Glyph icon)
{
switch (icon)
{
case Glyph.ClassProtected:
case Glyph.ConstantProtected:
case Glyph.DelegateProtected:
case Glyph.EnumProtected:
case Glyph.EventProtected:
case Glyph.FieldProtected:
case Glyph.InterfaceProtected:
case Glyph.MethodProtected:
case Glyph.ModuleProtected:
case Glyph.PropertyProtected:
case Glyph.StructureProtected:
return StandardGlyphItem.GlyphItemProtected;
case Glyph.ClassPrivate:
case Glyph.ConstantPrivate:
case Glyph.DelegatePrivate:
case Glyph.EnumPrivate:
case Glyph.EventPrivate:
case Glyph.FieldPrivate:
case Glyph.InterfacePrivate:
case Glyph.MethodPrivate:
case Glyph.ModulePrivate:
case Glyph.PropertyPrivate:
case Glyph.StructurePrivate:
return StandardGlyphItem.GlyphItemPrivate;
case Glyph.ClassInternal:
case Glyph.ConstantInternal:
case Glyph.DelegateInternal:
case Glyph.EnumInternal:
case Glyph.EventInternal:
case Glyph.FieldInternal:
case Glyph.InterfaceInternal:
case Glyph.MethodInternal:
case Glyph.ModuleInternal:
case Glyph.PropertyInternal:
case Glyph.StructureInternal:
return StandardGlyphItem.GlyphItemFriend;
default:
// We don't want any overlays
return StandardGlyphItem.GlyphItemPublic;
}
}
public static ImageSource GetImageSource(this Glyph? glyph, IGlyphService glyphService)
{
return glyph.HasValue ? glyph.Value.GetImageSource(glyphService) : null;
}
public static ImageSource GetImageSource(this Glyph glyph, IGlyphService glyphService)
{
return glyphService.GetGlyph(glyph.GetStandardGlyphGroup(), glyph.GetStandardGlyphItem());
}
public static ImageMoniker GetImageMoniker(this Glyph glyph)
{
switch (glyph)
{
case Glyph.Assembly:
return KnownMonikers.Assembly;
case Glyph.BasicFile:
return KnownMonikers.VBFileNode;
case Glyph.BasicProject:
return KnownMonikers.VBProjectNode;
case Glyph.ClassPublic:
return KnownMonikers.ClassPublic;
case Glyph.ClassProtected:
return KnownMonikers.ClassProtected;
case Glyph.ClassPrivate:
return KnownMonikers.ClassPrivate;
case Glyph.ClassInternal:
return KnownMonikers.ClassInternal;
case Glyph.CSharpFile:
return KnownMonikers.CSFileNode;
case Glyph.CSharpProject:
return KnownMonikers.CSProjectNode;
case Glyph.ConstantPublic:
return KnownMonikers.ConstantPublic;
case Glyph.ConstantProtected:
return KnownMonikers.ConstantProtected;
case Glyph.ConstantPrivate:
return KnownMonikers.ConstantPrivate;
case Glyph.ConstantInternal:
return KnownMonikers.ConstantInternal;
case Glyph.DelegatePublic:
return KnownMonikers.DelegatePublic;
case Glyph.DelegateProtected:
return KnownMonikers.DelegateProtected;
case Glyph.DelegatePrivate:
return KnownMonikers.DelegatePrivate;
case Glyph.DelegateInternal:
return KnownMonikers.DelegateInternal;
case Glyph.EnumPublic:
return KnownMonikers.EnumerationPublic;
case Glyph.EnumProtected:
return KnownMonikers.EnumerationProtected;
case Glyph.EnumPrivate:
return KnownMonikers.EnumerationPrivate;
case Glyph.EnumInternal:
return KnownMonikers.EnumerationInternal;
case Glyph.EnumMember:
return KnownMonikers.EnumerationItemPublic;
case Glyph.Error:
return KnownMonikers.StatusError;
case Glyph.EventPublic:
return KnownMonikers.EventPublic;
case Glyph.EventProtected:
return KnownMonikers.EventProtected;
case Glyph.EventPrivate:
return KnownMonikers.EventPrivate;
case Glyph.EventInternal:
return KnownMonikers.EventInternal;
// Extension methods have the same glyph regardless of accessibility.
case Glyph.ExtensionMethodPublic:
case Glyph.ExtensionMethodProtected:
case Glyph.ExtensionMethodPrivate:
case Glyph.ExtensionMethodInternal:
return KnownMonikers.ExtensionMethod;
case Glyph.FieldPublic:
return KnownMonikers.FieldPublic;
case Glyph.FieldProtected:
return KnownMonikers.FieldProtected;
case Glyph.FieldPrivate:
return KnownMonikers.FieldPrivate;
case Glyph.FieldInternal:
return KnownMonikers.FieldInternal;
case Glyph.InterfacePublic:
return KnownMonikers.InterfacePublic;
case Glyph.InterfaceProtected:
return KnownMonikers.InterfaceProtected;
case Glyph.InterfacePrivate:
return KnownMonikers.InterfacePrivate;
case Glyph.InterfaceInternal:
return KnownMonikers.InterfaceInternal;
// TODO: Figure out the right thing to return here.
case Glyph.Intrinsic:
return KnownMonikers.Type;
case Glyph.Keyword:
return KnownMonikers.IntellisenseKeyword;
case Glyph.Label:
return KnownMonikers.Label;
case Glyph.Parameter:
case Glyph.Local:
return KnownMonikers.LocalVariable;
case Glyph.Namespace:
return KnownMonikers.Namespace;
case Glyph.MethodPublic:
return KnownMonikers.MethodPublic;
case Glyph.MethodProtected:
return KnownMonikers.MethodProtected;
case Glyph.MethodPrivate:
return KnownMonikers.MethodPrivate;
case Glyph.MethodInternal:
return KnownMonikers.MethodInternal;
case Glyph.ModulePublic:
return KnownMonikers.ModulePublic;
case Glyph.ModuleProtected:
return KnownMonikers.ModuleProtected;
case Glyph.ModulePrivate:
return KnownMonikers.ModulePrivate;
case Glyph.ModuleInternal:
return KnownMonikers.ModuleInternal;
case Glyph.OpenFolder:
return KnownMonikers.OpenFolder;
case Glyph.Operator:
return KnownMonikers.Operator;
case Glyph.PropertyPublic:
return KnownMonikers.PropertyPublic;
case Glyph.PropertyProtected:
return KnownMonikers.PropertyProtected;
case Glyph.PropertyPrivate:
return KnownMonikers.PropertyPrivate;
case Glyph.PropertyInternal:
return KnownMonikers.PropertyInternal;
case Glyph.RangeVariable:
return KnownMonikers.FieldPublic;
case Glyph.Reference:
return KnownMonikers.Reference;
case Glyph.StructurePublic:
return KnownMonikers.ValueTypePublic;
case Glyph.StructureProtected:
return KnownMonikers.ValueTypeProtected;
case Glyph.StructurePrivate:
return KnownMonikers.ValueTypePrivate;
case Glyph.StructureInternal:
return KnownMonikers.ValueTypeInternal;
case Glyph.TypeParameter:
return KnownMonikers.Type;
case Glyph.Snippet:
return KnownMonikers.Snippet;
case Glyph.CompletionWarning:
return KnownMonikers.IntellisenseWarning;
case Glyph.NuGet:
return KnownMonikers.NuGet;
default:
throw new ArgumentException("glyph");
}
}
public static Glyph GetGlyph(this ImmutableArray<string> tags)
{
foreach (var tag in tags)
{
switch (tag)
{
case CompletionTags.Assembly:
return Glyph.Assembly;
case CompletionTags.File:
return tags.Contains(LanguageNames.VisualBasic) ? Glyph.BasicFile : Glyph.CSharpFile;
case CompletionTags.Project:
return tags.Contains(LanguageNames.VisualBasic) ? Glyph.BasicProject : Glyph.CSharpProject;
case CompletionTags.Class:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.ClassProtected;
case Accessibility.Private:
return Glyph.ClassPrivate;
case Accessibility.Internal:
return Glyph.ClassInternal;
case Accessibility.Public:
default:
return Glyph.ClassPublic;
}
case CompletionTags.Constant:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.ConstantProtected;
case Accessibility.Private:
return Glyph.ConstantPrivate;
case Accessibility.Internal:
return Glyph.ConstantInternal;
case Accessibility.Public:
default:
return Glyph.ConstantPublic;
}
case CompletionTags.Delegate:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.DelegateProtected;
case Accessibility.Private:
return Glyph.DelegatePrivate;
case Accessibility.Internal:
return Glyph.DelegateInternal;
case Accessibility.Public:
default:
return Glyph.DelegatePublic;
}
case CompletionTags.Enum:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.EnumProtected;
case Accessibility.Private:
return Glyph.EnumPrivate;
case Accessibility.Internal:
return Glyph.EnumInternal;
case Accessibility.Public:
default:
return Glyph.EnumPublic;
}
case CompletionTags.EnumMember:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.EnumMember;
case Accessibility.Private:
return Glyph.EnumMember;
case Accessibility.Internal:
return Glyph.EnumMember;
case Accessibility.Public:
default:
return Glyph.EnumMember;
}
case CompletionTags.Error:
return Glyph.Error;
case CompletionTags.Event:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.EventProtected;
case Accessibility.Private:
return Glyph.EventPrivate;
case Accessibility.Internal:
return Glyph.EventInternal;
case Accessibility.Public:
default:
return Glyph.EventPublic;
}
case CompletionTags.ExtensionMethod:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.ExtensionMethodProtected;
case Accessibility.Private:
return Glyph.ExtensionMethodPrivate;
case Accessibility.Internal:
return Glyph.ExtensionMethodInternal;
case Accessibility.Public:
default:
return Glyph.ExtensionMethodPublic;
}
case CompletionTags.Field:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.FieldProtected;
case Accessibility.Private:
return Glyph.FieldPrivate;
case Accessibility.Internal:
return Glyph.FieldInternal;
case Accessibility.Public:
default:
return Glyph.FieldPublic;
}
case CompletionTags.Interface:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.InterfaceProtected;
case Accessibility.Private:
return Glyph.InterfacePrivate;
case Accessibility.Internal:
return Glyph.InterfaceInternal;
case Accessibility.Public:
default:
return Glyph.InterfacePublic;
}
case CompletionTags.Intrinsic:
return Glyph.Intrinsic;
case CompletionTags.Keyword:
return Glyph.Keyword;
case CompletionTags.Label:
return Glyph.Label;
case CompletionTags.Local:
return Glyph.Local;
case CompletionTags.Namespace:
return Glyph.Namespace;
case CompletionTags.Method:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.MethodProtected;
case Accessibility.Private:
return Glyph.MethodPrivate;
case Accessibility.Internal:
return Glyph.MethodInternal;
case Accessibility.Public:
default:
return Glyph.MethodPublic;
}
case CompletionTags.Module:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.ModulePublic;
case Accessibility.Private:
return Glyph.ModulePrivate;
case Accessibility.Internal:
return Glyph.ModuleInternal;
case Accessibility.Public:
default:
return Glyph.ModulePublic;
}
case CompletionTags.Folder:
return Glyph.OpenFolder;
case CompletionTags.Operator:
return Glyph.Operator;
case CompletionTags.Parameter:
return Glyph.Parameter;
case CompletionTags.Property:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.PropertyProtected;
case Accessibility.Private:
return Glyph.PropertyPrivate;
case Accessibility.Internal:
return Glyph.PropertyInternal;
case Accessibility.Public:
default:
return Glyph.PropertyPublic;
}
case CompletionTags.RangeVariable:
return Glyph.RangeVariable;
case CompletionTags.Reference:
return Glyph.Reference;
case CompletionTags.Structure:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.StructureProtected;
case Accessibility.Private:
return Glyph.StructurePrivate;
case Accessibility.Internal:
return Glyph.StructureInternal;
case Accessibility.Public:
default:
return Glyph.StructurePublic;
}
case CompletionTags.TypeParameter:
return Glyph.TypeParameter;
case CompletionTags.Snippet:
return Glyph.Snippet;
case CompletionTags.Warning:
return Glyph.CompletionWarning;
}
}
return default(Glyph);
}
private static Accessibility GetAccessibility(ImmutableArray<string> tags)
{
if (tags.Contains(CompletionTags.Public))
{
return Accessibility.Public;
}
else if (tags.Contains(CompletionTags.Protected))
{
return Accessibility.Protected;
}
else if (tags.Contains(CompletionTags.Internal))
{
return Accessibility.Internal;
}
else if (tags.Contains(CompletionTags.Private))
{
return Accessibility.Private;
}
else
{
return Accessibility.NotApplicable;
}
}
}
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
namespace Mono.Cecil.Cil {
public enum FlowControl {
Branch,
Break,
Call,
Cond_Branch,
Meta,
Next,
Phi,
Return,
Throw,
}
public enum OpCodeType {
Annotation,
Macro,
Nternal,
Objmodel,
Prefix,
Primitive,
}
public enum OperandType {
InlineBrTarget,
InlineField,
InlineI,
InlineI8,
InlineMethod,
InlineNone,
InlinePhi,
InlineR,
InlineSig,
InlineString,
InlineSwitch,
InlineTok,
InlineType,
InlineVar,
InlineArg,
ShortInlineBrTarget,
ShortInlineI,
ShortInlineR,
ShortInlineVar,
ShortInlineArg,
}
public enum StackBehaviour {
Pop0,
Pop1,
Pop1_pop1,
Popi,
Popi_pop1,
Popi_popi,
Popi_popi8,
Popi_popi_popi,
Popi_popr4,
Popi_popr8,
Popref,
Popref_pop1,
Popref_popi,
Popref_popi_popi,
Popref_popi_popi8,
Popref_popi_popr4,
Popref_popi_popr8,
Popref_popi_popref,
PopAll,
Push0,
Push1,
Push1_push1,
Pushi,
Pushi8,
Pushr4,
Pushr8,
Pushref,
Varpop,
Varpush,
}
public struct OpCode : IEquatable<OpCode> {
readonly byte op1;
readonly byte op2;
readonly byte code;
readonly byte flow_control;
readonly byte opcode_type;
readonly byte operand_type;
readonly byte stack_behavior_pop;
readonly byte stack_behavior_push;
public string Name {
get { return OpCodeNames.names [(int) Code]; }
}
public int Size {
get { return op1 == 0xff ? 1 : 2; }
}
public byte Op1 {
get { return op1; }
}
public byte Op2 {
get { return op2; }
}
public short Value {
get { return op1 == 0xff ? op2 : (short) ((op1 << 8) | op2); }
}
public Code Code {
get { return (Code) code; }
}
public FlowControl FlowControl {
get { return (FlowControl) flow_control; }
}
public OpCodeType OpCodeType {
get { return (OpCodeType) opcode_type; }
}
public OperandType OperandType {
get { return (OperandType) operand_type; }
}
public StackBehaviour StackBehaviourPop {
get { return (StackBehaviour) stack_behavior_pop; }
}
public StackBehaviour StackBehaviourPush {
get { return (StackBehaviour) stack_behavior_push; }
}
internal OpCode (int x, int y)
{
this.op1 = (byte) ((x >> 0) & 0xff);
this.op2 = (byte) ((x >> 8) & 0xff);
this.code = (byte) ((x >> 16) & 0xff);
this.flow_control = (byte) ((x >> 24) & 0xff);
this.opcode_type = (byte) ((y >> 0) & 0xff);
this.operand_type = (byte) ((y >> 8) & 0xff);
this.stack_behavior_pop = (byte) ((y >> 16) & 0xff);
this.stack_behavior_push = (byte) ((y >> 24) & 0xff);
if (op1 == 0xff)
OpCodes.OneByteOpCode [op2] = this;
else
OpCodes.TwoBytesOpCode [op2] = this;
}
public override int GetHashCode ()
{
return Value;
}
public override bool Equals (object obj)
{
if (!(obj is OpCode))
return false;
var opcode = (OpCode) obj;
return op1 == opcode.op1 && op2 == opcode.op2;
}
public bool Equals (OpCode opcode)
{
return op1 == opcode.op1 && op2 == opcode.op2;
}
public static bool operator == (OpCode one, OpCode other)
{
return one.op1 == other.op1 && one.op2 == other.op2;
}
public static bool operator != (OpCode one, OpCode other)
{
return one.op1 != other.op1 || one.op2 != other.op2;
}
public override string ToString ()
{
return Name;
}
}
static class OpCodeNames {
internal static readonly string [] names;
static OpCodeNames ()
{
var table = new byte [] {
3, 110, 111, 112,
5, 98, 114, 101, 97, 107,
7, 108, 100, 97, 114, 103, 46, 48,
7, 108, 100, 97, 114, 103, 46, 49,
7, 108, 100, 97, 114, 103, 46, 50,
7, 108, 100, 97, 114, 103, 46, 51,
7, 108, 100, 108, 111, 99, 46, 48,
7, 108, 100, 108, 111, 99, 46, 49,
7, 108, 100, 108, 111, 99, 46, 50,
7, 108, 100, 108, 111, 99, 46, 51,
7, 115, 116, 108, 111, 99, 46, 48,
7, 115, 116, 108, 111, 99, 46, 49,
7, 115, 116, 108, 111, 99, 46, 50,
7, 115, 116, 108, 111, 99, 46, 51,
7, 108, 100, 97, 114, 103, 46, 115,
8, 108, 100, 97, 114, 103, 97, 46, 115,
7, 115, 116, 97, 114, 103, 46, 115,
7, 108, 100, 108, 111, 99, 46, 115,
8, 108, 100, 108, 111, 99, 97, 46, 115,
7, 115, 116, 108, 111, 99, 46, 115,
6, 108, 100, 110, 117, 108, 108,
9, 108, 100, 99, 46, 105, 52, 46, 109, 49,
8, 108, 100, 99, 46, 105, 52, 46, 48,
8, 108, 100, 99, 46, 105, 52, 46, 49,
8, 108, 100, 99, 46, 105, 52, 46, 50,
8, 108, 100, 99, 46, 105, 52, 46, 51,
8, 108, 100, 99, 46, 105, 52, 46, 52,
8, 108, 100, 99, 46, 105, 52, 46, 53,
8, 108, 100, 99, 46, 105, 52, 46, 54,
8, 108, 100, 99, 46, 105, 52, 46, 55,
8, 108, 100, 99, 46, 105, 52, 46, 56,
8, 108, 100, 99, 46, 105, 52, 46, 115,
6, 108, 100, 99, 46, 105, 52,
6, 108, 100, 99, 46, 105, 56,
6, 108, 100, 99, 46, 114, 52,
6, 108, 100, 99, 46, 114, 56,
3, 100, 117, 112,
3, 112, 111, 112,
3, 106, 109, 112,
4, 99, 97, 108, 108,
5, 99, 97, 108, 108, 105,
3, 114, 101, 116,
4, 98, 114, 46, 115,
9, 98, 114, 102, 97, 108, 115, 101, 46, 115,
8, 98, 114, 116, 114, 117, 101, 46, 115,
5, 98, 101, 113, 46, 115,
5, 98, 103, 101, 46, 115,
5, 98, 103, 116, 46, 115,
5, 98, 108, 101, 46, 115,
5, 98, 108, 116, 46, 115,
8, 98, 110, 101, 46, 117, 110, 46, 115,
8, 98, 103, 101, 46, 117, 110, 46, 115,
8, 98, 103, 116, 46, 117, 110, 46, 115,
8, 98, 108, 101, 46, 117, 110, 46, 115,
8, 98, 108, 116, 46, 117, 110, 46, 115,
2, 98, 114,
7, 98, 114, 102, 97, 108, 115, 101,
6, 98, 114, 116, 114, 117, 101,
3, 98, 101, 113,
3, 98, 103, 101,
3, 98, 103, 116,
3, 98, 108, 101,
3, 98, 108, 116,
6, 98, 110, 101, 46, 117, 110,
6, 98, 103, 101, 46, 117, 110,
6, 98, 103, 116, 46, 117, 110,
6, 98, 108, 101, 46, 117, 110,
6, 98, 108, 116, 46, 117, 110,
6, 115, 119, 105, 116, 99, 104,
8, 108, 100, 105, 110, 100, 46, 105, 49,
8, 108, 100, 105, 110, 100, 46, 117, 49,
8, 108, 100, 105, 110, 100, 46, 105, 50,
8, 108, 100, 105, 110, 100, 46, 117, 50,
8, 108, 100, 105, 110, 100, 46, 105, 52,
8, 108, 100, 105, 110, 100, 46, 117, 52,
8, 108, 100, 105, 110, 100, 46, 105, 56,
7, 108, 100, 105, 110, 100, 46, 105,
8, 108, 100, 105, 110, 100, 46, 114, 52,
8, 108, 100, 105, 110, 100, 46, 114, 56,
9, 108, 100, 105, 110, 100, 46, 114, 101, 102,
9, 115, 116, 105, 110, 100, 46, 114, 101, 102,
8, 115, 116, 105, 110, 100, 46, 105, 49,
8, 115, 116, 105, 110, 100, 46, 105, 50,
8, 115, 116, 105, 110, 100, 46, 105, 52,
8, 115, 116, 105, 110, 100, 46, 105, 56,
8, 115, 116, 105, 110, 100, 46, 114, 52,
8, 115, 116, 105, 110, 100, 46, 114, 56,
3, 97, 100, 100,
3, 115, 117, 98,
3, 109, 117, 108,
3, 100, 105, 118,
6, 100, 105, 118, 46, 117, 110,
3, 114, 101, 109,
6, 114, 101, 109, 46, 117, 110,
3, 97, 110, 100,
2, 111, 114,
3, 120, 111, 114,
3, 115, 104, 108,
3, 115, 104, 114,
6, 115, 104, 114, 46, 117, 110,
3, 110, 101, 103,
3, 110, 111, 116,
7, 99, 111, 110, 118, 46, 105, 49,
7, 99, 111, 110, 118, 46, 105, 50,
7, 99, 111, 110, 118, 46, 105, 52,
7, 99, 111, 110, 118, 46, 105, 56,
7, 99, 111, 110, 118, 46, 114, 52,
7, 99, 111, 110, 118, 46, 114, 56,
7, 99, 111, 110, 118, 46, 117, 52,
7, 99, 111, 110, 118, 46, 117, 56,
8, 99, 97, 108, 108, 118, 105, 114, 116,
5, 99, 112, 111, 98, 106,
5, 108, 100, 111, 98, 106,
5, 108, 100, 115, 116, 114,
6, 110, 101, 119, 111, 98, 106,
9, 99, 97, 115, 116, 99, 108, 97, 115, 115,
6, 105, 115, 105, 110, 115, 116,
9, 99, 111, 110, 118, 46, 114, 46, 117, 110,
5, 117, 110, 98, 111, 120,
5, 116, 104, 114, 111, 119,
5, 108, 100, 102, 108, 100,
6, 108, 100, 102, 108, 100, 97,
5, 115, 116, 102, 108, 100,
6, 108, 100, 115, 102, 108, 100,
7, 108, 100, 115, 102, 108, 100, 97,
6, 115, 116, 115, 102, 108, 100,
5, 115, 116, 111, 98, 106,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 49, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 50, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 52, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 56, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 49, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 50, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 52, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 56, 46, 117, 110,
13, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 46, 117, 110,
13, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 46, 117, 110,
3, 98, 111, 120,
6, 110, 101, 119, 97, 114, 114,
5, 108, 100, 108, 101, 110,
7, 108, 100, 101, 108, 101, 109, 97,
9, 108, 100, 101, 108, 101, 109, 46, 105, 49,
9, 108, 100, 101, 108, 101, 109, 46, 117, 49,
9, 108, 100, 101, 108, 101, 109, 46, 105, 50,
9, 108, 100, 101, 108, 101, 109, 46, 117, 50,
9, 108, 100, 101, 108, 101, 109, 46, 105, 52,
9, 108, 100, 101, 108, 101, 109, 46, 117, 52,
9, 108, 100, 101, 108, 101, 109, 46, 105, 56,
8, 108, 100, 101, 108, 101, 109, 46, 105,
9, 108, 100, 101, 108, 101, 109, 46, 114, 52,
9, 108, 100, 101, 108, 101, 109, 46, 114, 56,
10, 108, 100, 101, 108, 101, 109, 46, 114, 101, 102,
8, 115, 116, 101, 108, 101, 109, 46, 105,
9, 115, 116, 101, 108, 101, 109, 46, 105, 49,
9, 115, 116, 101, 108, 101, 109, 46, 105, 50,
9, 115, 116, 101, 108, 101, 109, 46, 105, 52,
9, 115, 116, 101, 108, 101, 109, 46, 105, 56,
9, 115, 116, 101, 108, 101, 109, 46, 114, 52,
9, 115, 116, 101, 108, 101, 109, 46, 114, 56,
10, 115, 116, 101, 108, 101, 109, 46, 114, 101, 102,
10, 108, 100, 101, 108, 101, 109, 46, 97, 110, 121,
10, 115, 116, 101, 108, 101, 109, 46, 97, 110, 121,
9, 117, 110, 98, 111, 120, 46, 97, 110, 121,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 49,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 49,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 50,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 50,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 52,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 52,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 56,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 56,
9, 114, 101, 102, 97, 110, 121, 118, 97, 108,
8, 99, 107, 102, 105, 110, 105, 116, 101,
8, 109, 107, 114, 101, 102, 97, 110, 121,
7, 108, 100, 116, 111, 107, 101, 110,
7, 99, 111, 110, 118, 46, 117, 50,
7, 99, 111, 110, 118, 46, 117, 49,
6, 99, 111, 110, 118, 46, 105,
10, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105,
10, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117,
7, 97, 100, 100, 46, 111, 118, 102,
10, 97, 100, 100, 46, 111, 118, 102, 46, 117, 110,
7, 109, 117, 108, 46, 111, 118, 102,
10, 109, 117, 108, 46, 111, 118, 102, 46, 117, 110,
7, 115, 117, 98, 46, 111, 118, 102,
10, 115, 117, 98, 46, 111, 118, 102, 46, 117, 110,
10, 101, 110, 100, 102, 105, 110, 97, 108, 108, 121,
5, 108, 101, 97, 118, 101,
7, 108, 101, 97, 118, 101, 46, 115,
7, 115, 116, 105, 110, 100, 46, 105,
6, 99, 111, 110, 118, 46, 117,
7, 97, 114, 103, 108, 105, 115, 116,
3, 99, 101, 113,
3, 99, 103, 116,
6, 99, 103, 116, 46, 117, 110,
3, 99, 108, 116,
6, 99, 108, 116, 46, 117, 110,
5, 108, 100, 102, 116, 110,
9, 108, 100, 118, 105, 114, 116, 102, 116, 110,
5, 108, 100, 97, 114, 103,
6, 108, 100, 97, 114, 103, 97,
5, 115, 116, 97, 114, 103,
5, 108, 100, 108, 111, 99,
6, 108, 100, 108, 111, 99, 97,
5, 115, 116, 108, 111, 99,
8, 108, 111, 99, 97, 108, 108, 111, 99,
9, 101, 110, 100, 102, 105, 108, 116, 101, 114,
10, 117, 110, 97, 108, 105, 103, 110, 101, 100, 46,
9, 118, 111, 108, 97, 116, 105, 108, 101, 46,
5, 116, 97, 105, 108, 46,
7, 105, 110, 105, 116, 111, 98, 106,
12, 99, 111, 110, 115, 116, 114, 97, 105, 110, 101, 100, 46,
5, 99, 112, 98, 108, 107,
7, 105, 110, 105, 116, 98, 108, 107,
3, 110, 111, 46,
7, 114, 101, 116, 104, 114, 111, 119,
6, 115, 105, 122, 101, 111, 102,
10, 114, 101, 102, 97, 110, 121, 116, 121, 112, 101,
9, 114, 101, 97, 100, 111, 110, 108, 121, 46,
};
names = new string [219];
for (int i = 0, p = 0; i < names.Length; i++) {
var buffer = new char [table [p++]];
for (int j = 0; j < buffer.Length; j++)
buffer [j] = (char) table [p++];
names [i] = new string (buffer);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Timers;
using System.Threading;
namespace Alibaba.F2E.Tianma {
class Node : EventEmitter {
// Process status constants.
enum Status { Idle, Starting, Running, Stopping }
// Standard error buffer.
string error = "";
// Standard output buffer.
string output = "";
// Node process instance.
Process process = null;
// Node process start info.
ProcessStartInfo startInfo;
// Current process status.
Status status;
// Flush timer.
System.Timers.Timer timer;
// Singleton check.
public static bool IsRunning() {
bool result = false;
if (File.Exists(".pid")) {
try {
// Try to find running process by previous saved pid.
Process process = Process.GetProcessById(Convert.ToInt32(File.ReadAllText(".pid")));
if (process.MainModule.ModuleName == "node.exe") {
result = true;
}
} catch (Exception ex) {
// Depress compiling warning.
Exception dummy = ex;
}
}
return result;
}
// Constructor.
public Node(string config) {
timer = new System.Timers.Timer();
timer.Interval = 100;
timer.Elapsed += Flush;
startInfo = new ProcessStartInfo();
startInfo.FileName = FindExec("node.exe");
startInfo.Arguments = "\"" + config + "\"";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
SetEV();
AddHandler("start", Start);
AddHandler("stop", Stop);
}
// Restart process.
public void Restart(object sender, EventArgsEx args) {
if (args.Type == "switch") {
startInfo.Arguments = "\"" + args.Message + "\"";
}
if (status == Status.Running) {
// Stop current process and start a new process immediately.
status = Status.Stopping;
process.Exited += Start;
process.Kill();
} else if (status == Status.Idle) {
EmitEvent("start");
}
}
// Start process.
public void Start(object sender, EventArgs args) {
if (status == Status.Idle) {
status = Status.Starting;
process = new Process();
process.StartInfo = startInfo;
process.EnableRaisingEvents = true;
process.ErrorDataReceived += OnError;
process.OutputDataReceived += OnOutput;
process.Exited += OnExit;
process.Start();
process.PriorityClass = ProcessPriorityClass.High;
process.BeginErrorReadLine();
process.BeginOutputReadLine();
// Save current PID.
File.WriteAllText(".pid", String.Format("{0}", process.Id));
status = Status.Running;
}
if (status == Status.Running) {
EmitEvent("started");
}
}
// Stop process.
public void Stop(object sender, EventArgs args) {
if (status == Status.Running) {
status = Status.Stopping;
process.Kill();
} else if (status == Status.Idle) {
EmitEvent("stopped");
}
}
// Get command result synchronously.
string Command(string exec, string arguments) {
Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = FindExec(exec);
process.StartInfo.Arguments = arguments;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
string output = process.StandardOutput.ReadToEnd().Trim();
process.WaitForExit();
process.Close();
return output;
}
// Find pathname of executable file.
string FindExec(string name) {
string path = Environment.GetEnvironmentVariable("PATH");
foreach (string folder in path.Split(new char[] { ';' })) {
string exec = Path.Combine(folder.Trim(), name);
if (File.Exists(exec)) {
return exec;
}
}
return "";
}
// Flush buffer.
void Flush(object sender, ElapsedEventArgs args) {
if (!timer.Enabled) {
return;
} else if (output.Length > 0) {
EmitEvent("output", output);
output = "";
} else if (error.Length > 0) {
EmitEvent("error", error);
error = "";
}
}
// Setup enviroment variables.
void SetEV() {
Environment.SetEnvironmentVariable("NODE_PATH", Command("tianma.cmd", "libpath"));
}
// Standard error event handler.
void OnError(object sender, DataReceivedEventArgs args) {
if (!String.IsNullOrEmpty(args.Data)) {
timer.Stop();
error += args.Data + "\n";
timer.Start();
}
}
// Exit event handler.
void OnExit(object sender, EventArgs args) {
process.CancelErrorRead();
process.CancelOutputRead();
process.Close();
status = Status.Idle;
EmitEvent("stopped");
}
// Standard output event handler.
void OnOutput(object sender, DataReceivedEventArgs args) {
if (!String.IsNullOrEmpty(args.Data)) {
timer.Stop();
output += args.Data + "\n";
timer.Start();
}
}
}
}
| |
// Copyright (c) 2001-2022 Aspose Pty Ltd. All Rights Reserved.
//
// This file is part of Aspose.Words. The source code in this file
// is only intended as a supplement to the documentation, and is provided
// "as is", without warranty of any kind, either expressed or implied.
//////////////////////////////////////////////////////////////////////////
using System.IO;
using System.Linq;
using Aspose.Words;
using Aspose.Words.Saving;
using NUnit.Framework;
namespace ApiExamples
{
[TestFixture]
internal class ExSavingCallback : ApiExampleBase
{
[Test]
public void CheckThatAllMethodsArePresent()
{
HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions();
htmlFixedSaveOptions.PageSavingCallback = new CustomFileNamePageSavingCallback();
ImageSaveOptions imageSaveOptions = new ImageSaveOptions(SaveFormat.Png);
imageSaveOptions.PageSavingCallback = new CustomFileNamePageSavingCallback();
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.PageSavingCallback = new CustomFileNamePageSavingCallback();
PsSaveOptions psSaveOptions = new PsSaveOptions();
psSaveOptions.PageSavingCallback = new CustomFileNamePageSavingCallback();
SvgSaveOptions svgSaveOptions = new SvgSaveOptions();
svgSaveOptions.PageSavingCallback = new CustomFileNamePageSavingCallback();
XamlFixedSaveOptions xamlFixedSaveOptions = new XamlFixedSaveOptions();
xamlFixedSaveOptions.PageSavingCallback = new CustomFileNamePageSavingCallback();
XpsSaveOptions xpsSaveOptions = new XpsSaveOptions();
xpsSaveOptions.PageSavingCallback = new CustomFileNamePageSavingCallback();
}
//ExStart
//ExFor:IPageSavingCallback
//ExFor:IPageSavingCallback.PageSaving(PageSavingArgs)
//ExFor:PageSavingArgs
//ExFor:PageSavingArgs.PageFileName
//ExFor:PageSavingArgs.KeepPageStreamOpen
//ExFor:PageSavingArgs.PageIndex
//ExFor:PageSavingArgs.PageStream
//ExFor:FixedPageSaveOptions.PageSavingCallback
//ExSummary:Shows how to use a callback to save a document to HTML page by page.
[Test] //ExSkip
public void PageFileNames()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Page 1.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page 2.");
builder.InsertImage(ImageDir + "Logo.jpg");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page 3.");
// Create an "HtmlFixedSaveOptions" object, which we can pass to the document's "Save" method
// to modify how we convert the document to HTML.
HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions();
// We will save each page in this document to a separate HTML file in the local file system.
// Set a callback that allows us to name each output HTML document.
htmlFixedSaveOptions.PageSavingCallback = new CustomFileNamePageSavingCallback();
doc.Save(ArtifactsDir + "SavingCallback.PageFileNames.html", htmlFixedSaveOptions);
string[] filePaths = Directory.GetFiles(ArtifactsDir).Where(
s => s.StartsWith(ArtifactsDir + "SavingCallback.PageFileNames.Page_")).OrderBy(s => s).ToArray();
Assert.AreEqual(3, filePaths.Length);
}
/// <summary>
/// Saves all pages to a file and directory specified within.
/// </summary>
private class CustomFileNamePageSavingCallback : IPageSavingCallback
{
public void PageSaving(PageSavingArgs args)
{
string outFileName = $"{ArtifactsDir}SavingCallback.PageFileNames.Page_{args.PageIndex}.html";
// Below are two ways of specifying where Aspose.Words will save each page of the document.
// 1 - Set a filename for the output page file:
args.PageFileName = outFileName;
// 2 - Create a custom stream for the output page file:
args.PageStream = new FileStream(outFileName, FileMode.Create);
Assert.False(args.KeepPageStreamOpen);
}
}
//ExEnd
//ExStart
//ExFor:DocumentPartSavingArgs
//ExFor:DocumentPartSavingArgs.Document
//ExFor:DocumentPartSavingArgs.DocumentPartFileName
//ExFor:DocumentPartSavingArgs.DocumentPartStream
//ExFor:DocumentPartSavingArgs.KeepDocumentPartStreamOpen
//ExFor:IDocumentPartSavingCallback
//ExFor:IDocumentPartSavingCallback.DocumentPartSaving(DocumentPartSavingArgs)
//ExFor:IImageSavingCallback
//ExFor:IImageSavingCallback.ImageSaving
//ExFor:ImageSavingArgs
//ExFor:ImageSavingArgs.ImageFileName
//ExFor:HtmlSaveOptions
//ExFor:HtmlSaveOptions.DocumentPartSavingCallback
//ExFor:HtmlSaveOptions.ImageSavingCallback
//ExSummary:Shows how to split a document into parts and save them.
[Test] //ExSkip
public void DocumentPartsFileNames()
{
Document doc = new Document(MyDir + "Rendering.docx");
string outFileName = "SavingCallback.DocumentPartsFileNames.html";
// Create an "HtmlFixedSaveOptions" object, which we can pass to the document's "Save" method
// to modify how we convert the document to HTML.
HtmlSaveOptions options = new HtmlSaveOptions();
// If we save the document normally, there will be one output HTML
// document with all the source document's contents.
// Set the "DocumentSplitCriteria" property to "DocumentSplitCriteria.SectionBreak" to
// save our document to multiple HTML files: one for each section.
options.DocumentSplitCriteria = DocumentSplitCriteria.SectionBreak;
// Assign a custom callback to the "DocumentPartSavingCallback" property to alter the document part saving logic.
options.DocumentPartSavingCallback = new SavedDocumentPartRename(outFileName, options.DocumentSplitCriteria);
// If we convert a document that contains images into html, we will end up with one html file which links to several images.
// Each image will be in the form of a file in the local file system.
// There is also a callback that can customize the name and file system location of each image.
options.ImageSavingCallback = new SavedImageRename(outFileName);
doc.Save(ArtifactsDir + outFileName, options);
}
/// <summary>
/// Sets custom filenames for output documents that the saving operation splits a document into.
/// </summary>
private class SavedDocumentPartRename : IDocumentPartSavingCallback
{
public SavedDocumentPartRename(string outFileName, DocumentSplitCriteria documentSplitCriteria)
{
mOutFileName = outFileName;
mDocumentSplitCriteria = documentSplitCriteria;
}
void IDocumentPartSavingCallback.DocumentPartSaving(DocumentPartSavingArgs args)
{
// We can access the entire source document via the "Document" property.
Assert.True(args.Document.OriginalFileName.EndsWith("Rendering.docx"));
string partType = string.Empty;
switch (mDocumentSplitCriteria)
{
case DocumentSplitCriteria.PageBreak:
partType = "Page";
break;
case DocumentSplitCriteria.ColumnBreak:
partType = "Column";
break;
case DocumentSplitCriteria.SectionBreak:
partType = "Section";
break;
case DocumentSplitCriteria.HeadingParagraph:
partType = "Paragraph from heading";
break;
}
string partFileName = $"{mOutFileName} part {++mCount}, of type {partType}{Path.GetExtension(args.DocumentPartFileName)}";
// Below are two ways of specifying where Aspose.Words will save each part of the document.
// 1 - Set a filename for the output part file:
args.DocumentPartFileName = partFileName;
// 2 - Create a custom stream for the output part file:
args.DocumentPartStream = new FileStream(ArtifactsDir + partFileName, FileMode.Create);
Assert.True(args.DocumentPartStream.CanWrite);
Assert.False(args.KeepDocumentPartStreamOpen);
}
private int mCount;
private readonly string mOutFileName;
private readonly DocumentSplitCriteria mDocumentSplitCriteria;
}
/// <summary>
/// Sets custom filenames for image files that an HTML conversion creates.
/// </summary>
public class SavedImageRename : IImageSavingCallback
{
public SavedImageRename(string outFileName)
{
mOutFileName = outFileName;
}
void IImageSavingCallback.ImageSaving(ImageSavingArgs args)
{
string imageFileName = $"{mOutFileName} shape {++mCount}, of type {args.CurrentShape.ShapeType}{Path.GetExtension(args.ImageFileName)}";
// Below are two ways of specifying where Aspose.Words will save each part of the document.
// 1 - Set a filename for the output image file:
args.ImageFileName = imageFileName;
// 2 - Create a custom stream for the output image file:
args.ImageStream = new FileStream(ArtifactsDir + imageFileName, FileMode.Create);
Assert.True(args.ImageStream.CanWrite);
Assert.True(args.IsImageAvailable);
Assert.False(args.KeepImageStreamOpen);
}
private int mCount;
private readonly string mOutFileName;
}
//ExEnd
//ExStart
//ExFor:CssSavingArgs
//ExFor:CssSavingArgs.CssStream
//ExFor:CssSavingArgs.Document
//ExFor:CssSavingArgs.IsExportNeeded
//ExFor:CssSavingArgs.KeepCssStreamOpen
//ExFor:CssStyleSheetType
//ExFor:HtmlSaveOptions.CssSavingCallback
//ExFor:HtmlSaveOptions.CssStyleSheetFileName
//ExFor:HtmlSaveOptions.CssStyleSheetType
//ExFor:ICssSavingCallback
//ExFor:ICssSavingCallback.CssSaving(CssSavingArgs)
//ExSummary:Shows how to work with CSS stylesheets that an HTML conversion creates.
[Test] //ExSkip
public void ExternalCssFilenames()
{
Document doc = new Document(MyDir + "Rendering.docx");
// Create an "HtmlFixedSaveOptions" object, which we can pass to the document's "Save" method
// to modify how we convert the document to HTML.
HtmlSaveOptions options = new HtmlSaveOptions();
// Set the "CssStylesheetType" property to "CssStyleSheetType.External" to
// accompany a saved HTML document with an external CSS stylesheet file.
options.CssStyleSheetType = CssStyleSheetType.External;
// Below are two ways of specifying directories and filenames for output CSS stylesheets.
// 1 - Use the "CssStyleSheetFileName" property to assign a filename to our stylesheet:
options.CssStyleSheetFileName = ArtifactsDir + "SavingCallback.ExternalCssFilenames.css";
// 2 - Use a custom callback to name our stylesheet:
options.CssSavingCallback =
new CustomCssSavingCallback(ArtifactsDir + "SavingCallback.ExternalCssFilenames.css", true, false);
doc.Save(ArtifactsDir + "SavingCallback.ExternalCssFilenames.html", options);
}
/// <summary>
/// Sets a custom filename, along with other parameters for an external CSS stylesheet.
/// </summary>
private class CustomCssSavingCallback : ICssSavingCallback
{
public CustomCssSavingCallback(string cssDocFilename, bool isExportNeeded, bool keepCssStreamOpen)
{
mCssTextFileName = cssDocFilename;
mIsExportNeeded = isExportNeeded;
mKeepCssStreamOpen = keepCssStreamOpen;
}
public void CssSaving(CssSavingArgs args)
{
// We can access the entire source document via the "Document" property.
Assert.True(args.Document.OriginalFileName.EndsWith("Rendering.docx"));
args.CssStream = new FileStream(mCssTextFileName, FileMode.Create);
args.IsExportNeeded = mIsExportNeeded;
args.KeepCssStreamOpen = mKeepCssStreamOpen;
Assert.True(args.CssStream.CanWrite);
}
private readonly string mCssTextFileName;
private readonly bool mIsExportNeeded;
private readonly bool mKeepCssStreamOpen;
}
//ExEnd
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
namespace ILCompiler
{
//
// NameMangler is reponsible for giving extern C/C++ names to managed types, methods and fields
//
// The key invariant is that the mangled names are independent on the compilation order.
//
public class NameMangler
{
private readonly bool _mangleForCplusPlus;
public NameMangler(bool mangleForCplusPlus)
{
_mangleForCplusPlus = mangleForCplusPlus;
}
//
// Turn a name into a valid C/C++ identifier
//
internal string SanitizeName(string s, bool typeName = false)
{
StringBuilder sb = null;
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')))
{
if (sb != null)
sb.Append(c);
continue;
}
if ((c >= '0') && (c <= '9'))
{
// C identifiers cannot start with a digit. Prepend underscores.
if (i == 0)
{
if (sb == null)
sb = new StringBuilder(s.Length + 2);
sb.Append("_");
}
if (sb != null)
sb.Append(c);
continue;
}
if (sb == null)
sb = new StringBuilder(s, 0, i, s.Length);
// For CppCodeGen, replace "." (C# namespace separator) with "::" (C++ namespace separator)
if (typeName && c == '.' && _mangleForCplusPlus)
{
sb.Append("::");
continue;
}
// Everything else is replaced by underscore.
// TODO: We assume that there won't be collisions with our own or C++ built-in identifiers.
sb.Append("_");
}
return (sb != null) ? sb.ToString() : s;
}
/// <summary>
/// Dictionary given a mangled name for a given <see cref="TypeDesc"/>
/// </summary>
private ImmutableDictionary<TypeDesc, string> _mangledTypeNames = ImmutableDictionary<TypeDesc, string>.Empty;
/// <summary>
/// Given a set of names <param name="set"/> check if <param name="origName"/>
/// is unique, if not add a numbered suffix until it becomes unique.
/// </summary>
/// <param name="origName">Name to check for uniqueness.</param>
/// <param name="set">Set of names already used.</param>
/// <returns>A name based on <param name="origName"/> that is not part of <param name="set"/>.</returns>
private string DisambiguateName(string origName, ISet<string> set)
{
int iter = 0;
string result = origName;
while (set.Contains(result))
{
result = string.Concat(origName, "_", (iter++).ToStringInvariant());
}
return result;
}
public string GetMangledTypeName(TypeDesc type)
{
string mangledName;
if (_mangledTypeNames.TryGetValue(type, out mangledName))
return mangledName;
return ComputeMangledTypeName(type);
}
/// <summary>
/// If given <param name="type"/> is an <see cref="EcmaType"/> precompute its mangled type name
/// along with all the other types from the same module as <param name="type"/>.
/// Otherwise, it is a constructed type and to the EcmaType's mangled name we add a suffix to
/// show what kind of constructed type it is (e.g. appending __Array for an array type).
/// </summary>
/// <param name="type">Type to mangled</param>
/// <returns>Mangled name for <param name="type"/>.</returns>
private string ComputeMangledTypeName(TypeDesc type)
{
if (type is EcmaType)
{
EcmaType ecmaType = (EcmaType)type;
string prependAssemblyName = SanitizeName(((EcmaAssembly)ecmaType.EcmaModule).GetName().Name);
var deduplicator = new HashSet<string>();
// Add consistent names for all types in the module, independent on the order in which
// they are compiled
lock (this)
{
foreach (MetadataType t in ((EcmaType)type).EcmaModule.GetAllTypes())
{
string name = t.GetFullName();
// Include encapsulating type
DefType containingType = t.ContainingType;
while (containingType != null)
{
name = containingType.GetFullName() + "_" + name;
containingType = containingType.ContainingType;
}
name = SanitizeName(name, true);
if (_mangleForCplusPlus)
{
// Always generate a fully qualified name
name = "::" + prependAssemblyName + "::" + name;
}
else
{
name = prependAssemblyName + "_" + name;
}
// Ensure that name is unique and update our tables accordingly.
name = DisambiguateName(name, deduplicator);
deduplicator.Add(name);
_mangledTypeNames = _mangledTypeNames.Add(t, name);
}
}
return _mangledTypeNames[type];
}
string mangledName;
switch (type.Category)
{
case TypeFlags.Array:
case TypeFlags.SzArray:
// mangledName = "Array<" + GetSignatureCPPTypeName(((ArrayType)type).ElementType) + ">";
mangledName = GetMangledTypeName(((ArrayType)type).ElementType) + "__Array";
if (!type.IsSzArray)
mangledName += "Rank" + ((ArrayType)type).Rank.ToStringInvariant();
break;
case TypeFlags.ByRef:
mangledName = GetMangledTypeName(((ByRefType)type).ParameterType) + "__ByRef";
break;
case TypeFlags.Pointer:
mangledName = GetMangledTypeName(((PointerType)type).ParameterType) + "__Pointer";
break;
default:
// Case of a generic type. If `type' is a type definition we use the type name
// for mangling, otherwise we use the mangling of the type and its generic type
// parameters, e.g. A <B> becomes A__B.
var typeDefinition = type.GetTypeDefinition();
if (typeDefinition != type)
{
mangledName = GetMangledTypeName(typeDefinition);
var inst = type.Instantiation;
for (int i = 0; i < inst.Length; i++)
{
string instArgName = GetMangledTypeName(inst[i]);
if (_mangleForCplusPlus)
instArgName = instArgName.Replace("::", "_");
mangledName += "__" + instArgName;
}
}
else
{
mangledName = SanitizeName(((DefType)type).GetFullName(), true);
}
break;
}
lock (this)
{
// Ensure that name is unique and update our tables accordingly.
_mangledTypeNames = _mangledTypeNames.Add(type, mangledName);
}
return mangledName;
}
private ImmutableDictionary<MethodDesc, string> _mangledMethodNames = ImmutableDictionary<MethodDesc, string>.Empty;
public string GetMangledMethodName(MethodDesc method)
{
string mangledName;
if (_mangledMethodNames.TryGetValue(method, out mangledName))
return mangledName;
return ComputeMangledMethodName(method);
}
private string ComputeMangledMethodName(MethodDesc method)
{
string prependTypeName = null;
if (!_mangleForCplusPlus)
prependTypeName = GetMangledTypeName(method.OwningType);
if (method is EcmaMethod)
{
var deduplicator = new HashSet<string>();
// Add consistent names for all methods of the type, independent on the order in which
// they are compiled
lock (this)
{
foreach (var m in method.OwningType.GetMethods())
{
string name = SanitizeName(m.Name);
name = DisambiguateName(name, deduplicator);
deduplicator.Add(name);
if (prependTypeName != null)
name = prependTypeName + "__" + name;
_mangledMethodNames = _mangledMethodNames.Add(m, name);
}
}
return _mangledMethodNames[method];
}
string mangledName;
var methodDefinition = method.GetTypicalMethodDefinition();
if (methodDefinition != method)
{
mangledName = GetMangledMethodName(methodDefinition.GetMethodDefinition());
var inst = method.Instantiation;
for (int i = 0; i < inst.Length; i++)
{
string instArgName = GetMangledTypeName(inst[i]);
if (_mangleForCplusPlus)
instArgName = instArgName.Replace("::", "_");
mangledName += "__" + instArgName;
}
}
else
{
// Assume that Name is unique for all other methods
mangledName = SanitizeName(method.Name);
}
if (prependTypeName != null)
mangledName = prependTypeName + "__" + mangledName;
lock (this)
{
_mangledMethodNames = _mangledMethodNames.Add(method, mangledName);
}
return mangledName;
}
private ImmutableDictionary<FieldDesc, string> _mangledFieldNames = ImmutableDictionary<FieldDesc, string>.Empty;
public string GetMangledFieldName(FieldDesc field)
{
string mangledName;
if (_mangledFieldNames.TryGetValue(field, out mangledName))
return mangledName;
return ComputeMangledFieldName(field);
}
private string ComputeMangledFieldName(FieldDesc field)
{
string prependTypeName = null;
if (!_mangleForCplusPlus)
prependTypeName = GetMangledTypeName(field.OwningType);
if (field is EcmaField)
{
var deduplicator = new HashSet<string>();
// Add consistent names for all fields of the type, independent on the order in which
// they are compiled
lock (this)
{
foreach (var f in field.OwningType.GetFields())
{
string name = SanitizeName(f.Name);
name = DisambiguateName(name, deduplicator);
deduplicator.Add(name);
if (prependTypeName != null)
name = prependTypeName + "__" + name;
_mangledFieldNames = _mangledFieldNames.Add(f, name);
}
}
return _mangledFieldNames[field];
}
string mangledName = SanitizeName(field.Name);
if (prependTypeName != null)
mangledName = prependTypeName + "__" + mangledName;
lock (this)
{
_mangledFieldNames = _mangledFieldNames.Add(field, mangledName);
}
return mangledName;
}
}
}
| |
using UnityEngine;
using UnityEngine.PostProcessing;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace UnityEditor.PostProcessing
{
using Settings = ColorGradingModel.Settings;
using Tonemapper = ColorGradingModel.Tonemapper;
using ColorWheelMode = ColorGradingModel.ColorWheelMode;
[PostProcessingModelEditor(typeof(ColorGradingModel))]
public class ColorGradingModelEditor : PostProcessingModelEditor
{
static GUIContent[] s_Tonemappers =
{
new GUIContent("None"),
new GUIContent("Filmic (ACES)"),
new GUIContent("Neutral")
};
struct TonemappingSettings
{
public SerializedProperty tonemapper;
public SerializedProperty neutralBlackIn;
public SerializedProperty neutralWhiteIn;
public SerializedProperty neutralBlackOut;
public SerializedProperty neutralWhiteOut;
public SerializedProperty neutralWhiteLevel;
public SerializedProperty neutralWhiteClip;
}
struct BasicSettings
{
public SerializedProperty exposure;
public SerializedProperty temperature;
public SerializedProperty tint;
public SerializedProperty hueShift;
public SerializedProperty saturation;
public SerializedProperty contrast;
}
struct ChannelMixerSettings
{
public SerializedProperty[] channels;
public SerializedProperty currentEditingChannel;
}
struct ColorWheelsSettings
{
public SerializedProperty mode;
public SerializedProperty log;
public SerializedProperty linear;
}
static GUIContent[] s_Curves =
{
new GUIContent("YRGB"),
new GUIContent("Hue VS Hue"),
new GUIContent("Hue VS Sat"),
new GUIContent("Sat VS Sat"),
new GUIContent("Lum VS Sat")
};
struct CurvesSettings
{
public SerializedProperty master;
public SerializedProperty red;
public SerializedProperty green;
public SerializedProperty blue;
public SerializedProperty hueVShue;
public SerializedProperty hueVSsat;
public SerializedProperty satVSsat;
public SerializedProperty lumVSsat;
public SerializedProperty currentEditingCurve;
public SerializedProperty curveY;
public SerializedProperty curveR;
public SerializedProperty curveG;
public SerializedProperty curveB;
}
TonemappingSettings m_Tonemapping;
BasicSettings m_Basic;
ChannelMixerSettings m_ChannelMixer;
ColorWheelsSettings m_ColorWheels;
CurvesSettings m_Curves;
CurveEditor m_CurveEditor;
Dictionary<SerializedProperty, Color> m_CurveDict;
// Neutral tonemapping curve helper
const int k_CurveResolution = 24;
const float k_NeutralRangeX = 2f;
const float k_NeutralRangeY = 1f;
Vector3[] m_RectVertices = new Vector3[4];
Vector3[] m_LineVertices = new Vector3[2];
Vector3[] m_CurveVertices = new Vector3[k_CurveResolution];
Rect m_NeutralCurveRect;
public override void OnEnable()
{
// Tonemapping settings
m_Tonemapping = new TonemappingSettings
{
tonemapper = FindSetting((Settings x) => x.tonemapping.tonemapper),
neutralBlackIn = FindSetting((Settings x) => x.tonemapping.neutralBlackIn),
neutralWhiteIn = FindSetting((Settings x) => x.tonemapping.neutralWhiteIn),
neutralBlackOut = FindSetting((Settings x) => x.tonemapping.neutralBlackOut),
neutralWhiteOut = FindSetting((Settings x) => x.tonemapping.neutralWhiteOut),
neutralWhiteLevel = FindSetting((Settings x) => x.tonemapping.neutralWhiteLevel),
neutralWhiteClip = FindSetting((Settings x) => x.tonemapping.neutralWhiteClip)
};
// Basic settings
m_Basic = new BasicSettings
{
exposure = FindSetting((Settings x) => x.basic.postExposure),
temperature = FindSetting((Settings x) => x.basic.temperature),
tint = FindSetting((Settings x) => x.basic.tint),
hueShift = FindSetting((Settings x) => x.basic.hueShift),
saturation = FindSetting((Settings x) => x.basic.saturation),
contrast = FindSetting((Settings x) => x.basic.contrast)
};
// Channel mixer
m_ChannelMixer = new ChannelMixerSettings
{
channels = new[]
{
FindSetting((Settings x) => x.channelMixer.red),
FindSetting((Settings x) => x.channelMixer.green),
FindSetting((Settings x) => x.channelMixer.blue)
},
currentEditingChannel = FindSetting((Settings x) => x.channelMixer.currentEditingChannel)
};
// Color wheels
m_ColorWheels = new ColorWheelsSettings
{
mode = FindSetting((Settings x) => x.colorWheels.mode),
log = FindSetting((Settings x) => x.colorWheels.log),
linear = FindSetting((Settings x) => x.colorWheels.linear)
};
// Curves
m_Curves = new CurvesSettings
{
master = FindSetting((Settings x) => x.curves.master.curve),
red = FindSetting((Settings x) => x.curves.red.curve),
green = FindSetting((Settings x) => x.curves.green.curve),
blue = FindSetting((Settings x) => x.curves.blue.curve),
hueVShue = FindSetting((Settings x) => x.curves.hueVShue.curve),
hueVSsat = FindSetting((Settings x) => x.curves.hueVSsat.curve),
satVSsat = FindSetting((Settings x) => x.curves.satVSsat.curve),
lumVSsat = FindSetting((Settings x) => x.curves.lumVSsat.curve),
currentEditingCurve = FindSetting((Settings x) => x.curves.e_CurrentEditingCurve),
curveY = FindSetting((Settings x) => x.curves.e_CurveY),
curveR = FindSetting((Settings x) => x.curves.e_CurveR),
curveG = FindSetting((Settings x) => x.curves.e_CurveG),
curveB = FindSetting((Settings x) => x.curves.e_CurveB)
};
// Prepare the curve editor and extract curve display settings
m_CurveDict = new Dictionary<SerializedProperty, Color>();
var settings = CurveEditor.Settings.defaultSettings;
m_CurveEditor = new CurveEditor(settings);
AddCurve(m_Curves.master, new Color(1f, 1f, 1f), 2, false);
AddCurve(m_Curves.red, new Color(1f, 0f, 0f), 2, false);
AddCurve(m_Curves.green, new Color(0f, 1f, 0f), 2, false);
AddCurve(m_Curves.blue, new Color(0f, 0.5f, 1f), 2, false);
AddCurve(m_Curves.hueVShue, new Color(1f, 1f, 1f), 0, true);
AddCurve(m_Curves.hueVSsat, new Color(1f, 1f, 1f), 0, true);
AddCurve(m_Curves.satVSsat, new Color(1f, 1f, 1f), 0, false);
AddCurve(m_Curves.lumVSsat, new Color(1f, 1f, 1f), 0, false);
}
void AddCurve(SerializedProperty prop, Color color, uint minPointCount, bool loop)
{
var state = CurveEditor.CurveState.defaultState;
state.color = color;
state.visible = false;
state.minPointCount = minPointCount;
state.onlyShowHandlesOnSelection = true;
state.zeroKeyConstantValue = 0.5f;
state.loopInBounds = loop;
m_CurveEditor.Add(prop, state);
m_CurveDict.Add(prop, color);
}
public override void OnDisable()
{
m_CurveEditor.RemoveAll();
}
public override void OnInspectorGUI()
{
DoGUIFor("Tonemapping", DoTonemappingGUI);
EditorGUILayout.Space();
DoGUIFor("Basic", DoBasicGUI);
EditorGUILayout.Space();
DoGUIFor("Channel Mixer", DoChannelMixerGUI);
EditorGUILayout.Space();
DoGUIFor("Trackballs", DoColorWheelsGUI);
EditorGUILayout.Space();
DoGUIFor("Grading Curves", DoCurvesGUI);
}
void DoGUIFor(string title, Action func)
{
EditorGUILayout.LabelField(title, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
func();
EditorGUI.indentLevel--;
}
void DoTonemappingGUI()
{
int tid = EditorGUILayout.Popup(EditorGUIHelper.GetContent("Tonemapper"), m_Tonemapping.tonemapper.intValue, s_Tonemappers);
if (tid == (int)Tonemapper.Neutral)
{
DrawNeutralTonemappingCurve();
EditorGUILayout.PropertyField(m_Tonemapping.neutralBlackIn, EditorGUIHelper.GetContent("Black In"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteIn, EditorGUIHelper.GetContent("White In"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralBlackOut, EditorGUIHelper.GetContent("Black Out"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteOut, EditorGUIHelper.GetContent("White Out"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteLevel, EditorGUIHelper.GetContent("White Level"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteClip, EditorGUIHelper.GetContent("White Clip"));
}
m_Tonemapping.tonemapper.intValue = tid;
}
void DrawNeutralTonemappingCurve()
{
using (new GUILayout.HorizontalScope())
{
GUILayout.Space(EditorGUI.indentLevel * 15f);
m_NeutralCurveRect = GUILayoutUtility.GetRect(128, 80);
}
// Background
m_RectVertices[0] = PointInRect( 0f, 0f);
m_RectVertices[1] = PointInRect(k_NeutralRangeX, 0f);
m_RectVertices[2] = PointInRect(k_NeutralRangeX, k_NeutralRangeY);
m_RectVertices[3] = PointInRect( 0f, k_NeutralRangeY);
Handles.DrawSolidRectangleWithOutline(
m_RectVertices,
Color.white * 0.1f,
Color.white * 0.4f
);
// Horizontal lines
for (var i = 1; i < k_NeutralRangeY; i++)
DrawLine(0, i, k_NeutralRangeX, i, 0.4f);
// Vertical lines
for (var i = 1; i < k_NeutralRangeX; i++)
DrawLine(i, 0, i, k_NeutralRangeY, 0.4f);
// Label
Handles.Label(
PointInRect(0, k_NeutralRangeY) + Vector3.right,
"Neutral Tonemapper", EditorStyles.miniLabel
);
// Precompute some values
var tonemap = ((ColorGradingModel)target).settings.tonemapping;
const float scaleFactor = 20f;
const float scaleFactorHalf = scaleFactor * 0.5f;
float inBlack = tonemap.neutralBlackIn * scaleFactor + 1f;
float outBlack = tonemap.neutralBlackOut * scaleFactorHalf + 1f;
float inWhite = tonemap.neutralWhiteIn / scaleFactor;
float outWhite = 1f - tonemap.neutralWhiteOut / scaleFactor;
float blackRatio = inBlack / outBlack;
float whiteRatio = inWhite / outWhite;
const float a = 0.2f;
float b = Mathf.Max(0f, Mathf.LerpUnclamped(0.57f, 0.37f, blackRatio));
float c = Mathf.LerpUnclamped(0.01f, 0.24f, whiteRatio);
float d = Mathf.Max(0f, Mathf.LerpUnclamped(0.02f, 0.20f, blackRatio));
const float e = 0.02f;
const float f = 0.30f;
float whiteLevel = tonemap.neutralWhiteLevel;
float whiteClip = tonemap.neutralWhiteClip / scaleFactorHalf;
// Tonemapping curve
var vcount = 0;
while (vcount < k_CurveResolution)
{
float x = k_NeutralRangeX * vcount / (k_CurveResolution - 1);
float y = NeutralTonemap(x, a, b, c, d, e, f, whiteLevel, whiteClip);
if (y < k_NeutralRangeY)
{
m_CurveVertices[vcount++] = PointInRect(x, y);
}
else
{
if (vcount > 1)
{
// Extend the last segment to the top edge of the rect.
var v1 = m_CurveVertices[vcount - 2];
var v2 = m_CurveVertices[vcount - 1];
var clip = (m_NeutralCurveRect.y - v1.y) / (v2.y - v1.y);
m_CurveVertices[vcount - 1] = v1 + (v2 - v1) * clip;
}
break;
}
}
if (vcount > 1)
{
Handles.color = Color.white * 0.9f;
Handles.DrawAAPolyLine(2.0f, vcount, m_CurveVertices);
}
}
void DrawLine(float x1, float y1, float x2, float y2, float grayscale)
{
m_LineVertices[0] = PointInRect(x1, y1);
m_LineVertices[1] = PointInRect(x2, y2);
Handles.color = Color.white * grayscale;
Handles.DrawAAPolyLine(2f, m_LineVertices);
}
Vector3 PointInRect(float x, float y)
{
x = Mathf.Lerp(m_NeutralCurveRect.x, m_NeutralCurveRect.xMax, x / k_NeutralRangeX);
y = Mathf.Lerp(m_NeutralCurveRect.yMax, m_NeutralCurveRect.y, y / k_NeutralRangeY);
return new Vector3(x, y, 0);
}
float NeutralCurve(float x, float a, float b, float c, float d, float e, float f)
{
return ((x * (a * x + c * b) + d * e) / (x * (a * x + b) + d * f)) - e / f;
}
float NeutralTonemap(float x, float a, float b, float c, float d, float e, float f, float whiteLevel, float whiteClip)
{
x = Mathf.Max(0f, x);
// Tonemap
float whiteScale = 1f / NeutralCurve(whiteLevel, a, b, c, d, e, f);
x = NeutralCurve(x * whiteScale, a, b, c, d, e, f);
x *= whiteScale;
// Post-curve white point adjustment
x /= whiteClip;
return x;
}
void DoBasicGUI()
{
EditorGUILayout.PropertyField(m_Basic.exposure, EditorGUIHelper.GetContent("Post Exposure (EV)"));
EditorGUILayout.PropertyField(m_Basic.temperature);
EditorGUILayout.PropertyField(m_Basic.tint);
EditorGUILayout.PropertyField(m_Basic.hueShift);
EditorGUILayout.PropertyField(m_Basic.saturation);
EditorGUILayout.PropertyField(m_Basic.contrast);
}
void DoChannelMixerGUI()
{
int currentChannel = m_ChannelMixer.currentEditingChannel.intValue;
EditorGUI.BeginChangeCheck();
{
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel("Channel");
if (GUILayout.Toggle(currentChannel == 0, EditorGUIHelper.GetContent("Red|Red output channel."), EditorStyles.miniButtonLeft)) currentChannel = 0;
if (GUILayout.Toggle(currentChannel == 1, EditorGUIHelper.GetContent("Green|Green output channel."), EditorStyles.miniButtonMid)) currentChannel = 1;
if (GUILayout.Toggle(currentChannel == 2, EditorGUIHelper.GetContent("Blue|Blue output channel."), EditorStyles.miniButtonRight)) currentChannel = 2;
}
}
if (EditorGUI.EndChangeCheck())
{
GUI.FocusControl(null);
}
var serializedChannel = m_ChannelMixer.channels[currentChannel];
m_ChannelMixer.currentEditingChannel.intValue = currentChannel;
var v = serializedChannel.vector3Value;
v.x = EditorGUILayout.Slider(EditorGUIHelper.GetContent("Red|Modify influence of the red channel within the overall mix."), v.x, -2f, 2f);
v.y = EditorGUILayout.Slider(EditorGUIHelper.GetContent("Green|Modify influence of the green channel within the overall mix."), v.y, -2f, 2f);
v.z = EditorGUILayout.Slider(EditorGUIHelper.GetContent("Blue|Modify influence of the blue channel within the overall mix."), v.z, -2f, 2f);
serializedChannel.vector3Value = v;
}
void DoColorWheelsGUI()
{
int wheelMode = m_ColorWheels.mode.intValue;
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(15);
if (GUILayout.Toggle(wheelMode == (int)ColorWheelMode.Linear, "Linear", EditorStyles.miniButtonLeft)) wheelMode = (int)ColorWheelMode.Linear;
if (GUILayout.Toggle(wheelMode == (int)ColorWheelMode.Log, "Log", EditorStyles.miniButtonRight)) wheelMode = (int)ColorWheelMode.Log;
}
m_ColorWheels.mode.intValue = wheelMode;
EditorGUILayout.Space();
if (wheelMode == (int)ColorWheelMode.Linear)
{
EditorGUILayout.PropertyField(m_ColorWheels.linear);
WheelSetTitle(GUILayoutUtility.GetLastRect(), "Linear Controls");
}
else if (wheelMode == (int)ColorWheelMode.Log)
{
EditorGUILayout.PropertyField(m_ColorWheels.log);
WheelSetTitle(GUILayoutUtility.GetLastRect(), "Log Controls");
}
}
static void WheelSetTitle(Rect position, string label)
{
var matrix = GUI.matrix;
var rect = new Rect(position.x - 10f, position.y, TrackballGroupDrawer.m_Size, TrackballGroupDrawer.m_Size);
GUIUtility.RotateAroundPivot(-90f, rect.center);
GUI.Label(rect, label, FxStyles.centeredMiniLabel);
GUI.matrix = matrix;
}
void ResetVisibleCurves()
{
foreach (var curve in m_CurveDict)
{
var state = m_CurveEditor.GetCurveState(curve.Key);
state.visible = false;
m_CurveEditor.SetCurveState(curve.Key, state);
}
}
void SetCurveVisible(SerializedProperty prop)
{
var state = m_CurveEditor.GetCurveState(prop);
state.visible = true;
m_CurveEditor.SetCurveState(prop, state);
}
bool SpecialToggle(bool value, string name, out bool rightClicked)
{
var rect = GUILayoutUtility.GetRect(EditorGUIHelper.GetContent(name), EditorStyles.toolbarButton);
var e = Event.current;
rightClicked = (e.type == EventType.MouseUp && rect.Contains(e.mousePosition) && e.button == 1);
return GUI.Toggle(rect, value, name, EditorStyles.toolbarButton);
}
static Material s_MaterialSpline;
void DoCurvesGUI()
{
EditorGUILayout.Space();
EditorGUI.indentLevel -= 2;
ResetVisibleCurves();
using (new EditorGUI.DisabledGroupScope(serializedProperty.serializedObject.isEditingMultipleObjects))
{
int curveEditingId = 0;
// Top toolbar
using (new GUILayout.HorizontalScope(EditorStyles.toolbar))
{
curveEditingId = EditorGUILayout.Popup(m_Curves.currentEditingCurve.intValue, s_Curves, EditorStyles.toolbarPopup, GUILayout.MaxWidth(150f));
bool y = false, r = false, g = false, b = false;
if (curveEditingId == 0)
{
EditorGUILayout.Space();
bool rightClickedY, rightClickedR, rightClickedG, rightClickedB;
y = SpecialToggle(m_Curves.curveY.boolValue, "Y", out rightClickedY);
r = SpecialToggle(m_Curves.curveR.boolValue, "R", out rightClickedR);
g = SpecialToggle(m_Curves.curveG.boolValue, "G", out rightClickedG);
b = SpecialToggle(m_Curves.curveB.boolValue, "B", out rightClickedB);
if (!y && !r && !g && !b)
{
r = g = b = false;
y = true;
}
if (rightClickedY || rightClickedR || rightClickedG || rightClickedB)
{
y = rightClickedY;
r = rightClickedR;
g = rightClickedG;
b = rightClickedB;
}
if (y) SetCurveVisible(m_Curves.master);
if (r) SetCurveVisible(m_Curves.red);
if (g) SetCurveVisible(m_Curves.green);
if (b) SetCurveVisible(m_Curves.blue);
m_Curves.curveY.boolValue = y;
m_Curves.curveR.boolValue = r;
m_Curves.curveG.boolValue = g;
m_Curves.curveB.boolValue = b;
}
else
{
switch (curveEditingId)
{
case 1: SetCurveVisible(m_Curves.hueVShue);
break;
case 2: SetCurveVisible(m_Curves.hueVSsat);
break;
case 3: SetCurveVisible(m_Curves.satVSsat);
break;
case 4: SetCurveVisible(m_Curves.lumVSsat);
break;
}
}
GUILayout.FlexibleSpace();
if (GUILayout.Button("Reset", EditorStyles.toolbarButton))
{
switch (curveEditingId)
{
case 0:
if (y) m_Curves.master.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
if (r) m_Curves.red.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
if (g) m_Curves.green.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
if (b) m_Curves.blue.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
break;
case 1: m_Curves.hueVShue.animationCurveValue = new AnimationCurve();
break;
case 2: m_Curves.hueVSsat.animationCurveValue = new AnimationCurve();
break;
case 3: m_Curves.satVSsat.animationCurveValue = new AnimationCurve();
break;
case 4: m_Curves.lumVSsat.animationCurveValue = new AnimationCurve();
break;
}
}
m_Curves.currentEditingCurve.intValue = curveEditingId;
}
// Curve area
var settings = m_CurveEditor.settings;
var rect = GUILayoutUtility.GetAspectRect(2f);
var innerRect = settings.padding.Remove(rect);
if (Event.current.type == EventType.Repaint)
{
// Background
EditorGUI.DrawRect(rect, new Color(0.15f, 0.15f, 0.15f, 1f));
if (s_MaterialSpline == null)
s_MaterialSpline = new Material(Shader.Find("Hidden/Post FX/UI/Curve Background")) { hideFlags = HideFlags.HideAndDontSave };
if (curveEditingId == 1 || curveEditingId == 2)
DrawBackgroundTexture(innerRect, 0);
else if (curveEditingId == 3 || curveEditingId == 4)
DrawBackgroundTexture(innerRect, 1);
// Bounds
Handles.color = Color.white;
Handles.DrawSolidRectangleWithOutline(innerRect, Color.clear, new Color(0.8f, 0.8f, 0.8f, 0.5f));
// Grid setup
Handles.color = new Color(1f, 1f, 1f, 0.05f);
int hLines = (int)Mathf.Sqrt(innerRect.width);
int vLines = (int)(hLines / (innerRect.width / innerRect.height));
// Vertical grid
int gridOffset = Mathf.FloorToInt(innerRect.width / hLines);
int gridPadding = ((int)(innerRect.width) % hLines) / 2;
for (int i = 1; i < hLines; i++)
{
var offset = i * Vector2.right * gridOffset;
offset.x += gridPadding;
Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.x, innerRect.yMax - 1) + offset);
}
// Horizontal grid
gridOffset = Mathf.FloorToInt(innerRect.height / vLines);
gridPadding = ((int)(innerRect.height) % vLines) / 2;
for (int i = 1; i < vLines; i++)
{
var offset = i * Vector2.up * gridOffset;
offset.y += gridPadding;
Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.xMax - 1, innerRect.y) + offset);
}
}
// Curve editor
if (m_CurveEditor.OnGUI(rect))
{
Repaint();
GUI.changed = true;
}
if (Event.current.type == EventType.Repaint)
{
// Borders
Handles.color = Color.black;
Handles.DrawLine(new Vector2(rect.x, rect.y - 18f), new Vector2(rect.xMax, rect.y - 18f));
Handles.DrawLine(new Vector2(rect.x, rect.y - 19f), new Vector2(rect.x, rect.yMax));
Handles.DrawLine(new Vector2(rect.x, rect.yMax), new Vector2(rect.xMax, rect.yMax));
Handles.DrawLine(new Vector2(rect.xMax, rect.yMax), new Vector2(rect.xMax, rect.y - 18f));
// Selection info
var selection = m_CurveEditor.GetSelection();
if (selection.curve != null && selection.keyframeIndex > -1)
{
var key = selection.keyframe.Value;
var infoRect = innerRect;
infoRect.x += 5f;
infoRect.width = 100f;
infoRect.height = 30f;
GUI.Label(infoRect, string.Format("{0}\n{1}", key.time.ToString("F3"), key.value.ToString("F3")), FxStyles.preLabel);
}
}
}
/*
EditorGUILayout.HelpBox(
@"Curve editor cheat sheet:
- [Del] or [Backspace] to remove a key
- [Ctrl] to break a tangent handle
- [Shift] to align tangent handles
- [Double click] to create a key on the curve(s) at mouse position
- [Alt] + [Double click] to create a key on the curve(s) at a given time",
MessageType.Info);
*/
EditorGUILayout.Space();
EditorGUI.indentLevel += 2;
}
void DrawBackgroundTexture(Rect rect, int pass)
{
float scale = EditorGUIUtility.pixelsPerPoint;
var oldRt = RenderTexture.active;
var rt = RenderTexture.GetTemporary(Mathf.CeilToInt(rect.width * scale), Mathf.CeilToInt(rect.height * scale), 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
s_MaterialSpline.SetFloat("_DisabledState", GUI.enabled ? 1f : 0.5f);
s_MaterialSpline.SetFloat("_PixelScaling", EditorGUIUtility.pixelsPerPoint);
Graphics.Blit(null, rt, s_MaterialSpline, pass);
RenderTexture.active = oldRt;
GUI.DrawTexture(rect, rt);
RenderTexture.ReleaseTemporary(rt);
}
}
}
| |
// 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.Contracts;
namespace System.Globalization
{
public partial class CompareInfo
{
internal unsafe CompareInfo(CultureInfo culture)
{
const uint LCMAP_SORTHANDLE = 0x20000000;
_name = culture.m_name;
_sortName = culture.SortName;
IntPtr handle;
int ret = Interop.mincore.LCMapStringEx(_sortName, LCMAP_SORTHANDLE, null, 0, &handle, IntPtr.Size, null, null, IntPtr.Zero);
_sortHandle = ret > 0 ? handle : IntPtr.Zero;
}
private static unsafe int FindStringOrdinal(
uint dwFindStringOrdinalFlags,
string stringSource,
int offset,
int cchSource,
string value,
int cchValue,
bool bIgnoreCase)
{
fixed (char* pSource = stringSource)
fixed (char* pValue = value)
{
int ret = Interop.mincore.FindStringOrdinal(
dwFindStringOrdinalFlags,
pSource + offset,
cchSource,
pValue,
cchValue,
bIgnoreCase ? 1 : 0);
return ret < 0 ? ret : ret + offset;
}
}
internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Contract.Assert(source != null);
Contract.Assert(value != null);
return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase);
}
internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Contract.Assert(source != null);
Contract.Assert(value != null);
return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase);
}
private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options)
{
Contract.Assert(source != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
return 0;
}
int tmpHash = 0;
fixed (char* pSource = source)
{
if (Interop.mincore.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
LCMAP_HASH | (uint)GetNativeCompareFlags(options),
pSource, source.Length,
&tmpHash, sizeof(int),
null, null, _sortHandle) == 0)
{
Environment.FailFast("LCMapStringEx failed!");
}
}
return tmpHash;
}
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
// Use the OS to compare and then convert the result to expected value by subtracting 2
return Interop.mincore.CompareStringOrdinal(string1, count1, string2, count2, true) - 2;
}
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
Contract.Assert(string1 != null);
Contract.Assert(string2 != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pString1 = string1)
fixed (char* pString2 = string2)
{
int result = Interop.mincore.CompareStringEx(
pLocaleName,
(uint)GetNativeCompareFlags(options),
pString1 + offset1,
length1,
pString2 + offset2,
length2,
null,
null,
_sortHandle);
if (result == 0)
{
Environment.FailFast("CompareStringEx failed");
}
// Map CompareStringEx return value to -1, 0, 1.
return result - 2;
}
}
private unsafe int FindString(
uint dwFindNLSStringFlags,
string lpStringSource,
int startSource,
int cchSource,
string lpStringValue,
int startValue,
int cchValue)
{
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pSource = lpStringSource)
fixed (char* pValue = lpStringValue)
{
char* pS = pSource + startSource;
char* pV = pValue + startValue;
return Interop.mincore.FindNLSStringEx(
pLocaleName,
dwFindNLSStringFlags,
pS,
cchSource,
pV,
cchValue,
null,
null,
null,
_sortHandle);
}
}
private int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(target != null);
Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
// TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
// and add a precondition that target is not empty.
if (target.Length == 0)
return startIndex; // keep Whidbey compatibility
if ((options & CompareOptions.Ordinal) != 0)
{
return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false);
}
else
{
int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options),
source,
startIndex,
count,
target,
0,
target.Length);
if (retValue >= 0)
{
return retValue + startIndex;
}
}
return -1;
}
private int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(target != null);
Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
// TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
// and add a precondition that target is not empty.
if (target.Length == 0)
return startIndex; // keep Whidbey compatibility
if ((options & CompareOptions.Ordinal) != 0)
{
return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: true);
}
else
{
int retValue = FindString(FIND_FROMEND | (uint)GetNativeCompareFlags(options),
source,
startIndex - count + 1,
count,
target,
0,
target.Length);
if (retValue >= 0)
{
return retValue + startIndex - (count - 1);
}
}
return -1;
}
private bool StartsWith(string source, string prefix, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(!string.IsNullOrEmpty(prefix));
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options),
source,
0,
source.Length,
prefix,
0,
prefix.Length) >= 0;
}
private bool EndsWith(string source, string suffix, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(!string.IsNullOrEmpty(suffix));
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options),
source,
0,
source.Length,
suffix,
0,
suffix.Length) >= 0;
}
// PAL ends here
private readonly IntPtr _sortHandle;
private const uint LCMAP_HASH = 0x00040000;
private const int FIND_STARTSWITH = 0x00100000;
private const int FIND_ENDSWITH = 0x00200000;
private const int FIND_FROMSTART = 0x00400000;
private const int FIND_FROMEND = 0x00800000;
// TODO: Instead of this method could we just have upstack code call IndexOfOrdinal with ignoreCase = false?
private static unsafe int FastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount, bool findLastIndex)
{
int retValue = -1;
int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex;
#if !TEST_CODEGEN_OPTIMIZATION
fixed (char* pSource = source, spTarget = target)
{
char* spSubSource = pSource + sourceStartIndex;
#else
String.StringPointer spSubSource = source.GetStringPointer(sourceStartIndex);
String.StringPointer spTarget = target.GetStringPointer();
#endif
if (findLastIndex)
{
int startPattern = (sourceCount - 1) - targetCount + 1;
if (startPattern < 0)
return -1;
char patternChar0 = spTarget[0];
for (int ctrSrc = startPattern; ctrSrc >= 0; ctrSrc--)
{
if (spSubSource[ctrSrc] != patternChar0)
continue;
int ctrPat;
for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
{
if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
break;
}
if (ctrPat == targetCount)
{
retValue = ctrSrc;
break;
}
}
if (retValue >= 0)
{
retValue += startIndex - sourceCount + 1;
}
}
else
{
int endPattern = (sourceCount - 1) - targetCount + 1;
if (endPattern < 0)
return -1;
char patternChar0 = spTarget[0];
for (int ctrSrc = 0; ctrSrc <= endPattern; ctrSrc++)
{
if (spSubSource[ctrSrc] != patternChar0)
continue;
int ctrPat;
for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
{
if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
break;
}
if (ctrPat == targetCount)
{
retValue = ctrSrc;
break;
}
}
if (retValue >= 0)
{
retValue += startIndex;
}
}
#if !TEST_CODEGEN_OPTIMIZATION
}
return retValue;
#endif // TEST_CODEGEN_OPTIMIZATION
}
private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal
private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead)
private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal.
private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead)
private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols.
private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character.
private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing
private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols.
private static int GetNativeCompareFlags(CompareOptions options)
{
// Use "linguistic casing" by default (load the culture's casing exception tables)
int nativeCompareFlags = NORM_LINGUISTIC_CASING;
if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; }
if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; }
if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; }
if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; }
if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; }
if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; }
// TODO: Can we try for GetNativeCompareFlags to never
// take Ordinal or OridnalIgnoreCase. This value is not part of Win32, we just handle it special
// in some places.
// Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
Contract.Assert(((options & ~(CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreSymbols |
CompareOptions.IgnoreWidth |
CompareOptions.StringSort)) == 0) ||
(options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled");
return nativeCompareFlags;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.AddImport;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Packaging;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CSharp.CodeFixes.AddImport.AddImportDiagnosticIds;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.AddImport
{
internal static class AddImportDiagnosticIds
{
/// <summary>
/// name does not exist in context
/// </summary>
public const string CS0103 = nameof(CS0103);
/// <summary>
/// type or namespace could not be found
/// </summary>
public const string CS0246 = nameof(CS0246);
/// <summary>
/// wrong number of type args
/// </summary>
public const string CS0305 = nameof(CS0305);
/// <summary>
/// type does not contain a definition of method or extension method
/// </summary>
public const string CS1061 = nameof(CS1061);
/// <summary>
/// cannot find implementation of query pattern
/// </summary>
public const string CS1935 = nameof(CS1935);
/// <summary>
/// The non-generic type 'A' cannot be used with type arguments
/// </summary>
public const string CS0308 = nameof(CS0308);
/// <summary>
/// 'A' is inaccessible due to its protection level
/// </summary>
public const string CS0122 = nameof(CS0122);
/// <summary>
/// The using alias 'A' cannot be used with type arguments
/// </summary>
public const string CS0307 = nameof(CS0307);
/// <summary>
/// 'A' is not an attribute class
/// </summary>
public const string CS0616 = nameof(CS0616);
/// <summary>
/// No overload for method 'X' takes 'N' arguments
/// </summary>
public const string CS1501 = nameof(CS1501);
/// <summary>
/// cannot convert from 'int' to 'string'
/// </summary>
public const string CS1503 = nameof(CS1503);
/// <summary>
/// XML comment on 'construct' has syntactically incorrect cref attribute 'name'
/// </summary>
public const string CS1574 = nameof(CS1574);
/// <summary>
/// Invalid type for parameter 'parameter number' in XML comment cref attribute
/// </summary>
public const string CS1580 = nameof(CS1580);
/// <summary>
/// Invalid return type in XML comment cref attribute
/// </summary>
public const string CS1581 = nameof(CS1581);
/// <summary>
/// XML comment has syntactically incorrect cref attribute
/// </summary>
public const string CS1584 = nameof(CS1584);
/// <summary>
/// Type 'X' does not contain a valid extension method accepting 'Y'
/// </summary>
public const string CS1929 = nameof(CS1929);
/// <summary>
/// Cannot convert method group 'X' to non-delegate type 'Y'. Did you intend to invoke the method?
/// </summary>
public const string CS0428 = nameof(CS0428);
/// <summary>
/// There is no argument given that corresponds to the required formal parameter 'X' of 'Y'
/// </summary>
public const string CS7036 = nameof(CS7036);
public static ImmutableArray<string> FixableTypeIds =
ImmutableArray.Create(
CS0103,
CS0246,
CS0305,
CS0308,
CS0122,
CS0307,
CS0616,
CS1580,
CS1581);
public static ImmutableArray<string> FixableDiagnosticIds =
FixableTypeIds.Concat(ImmutableArray.Create(
CS1061,
CS1935,
CS1501,
CS1503,
CS1574,
CS1584,
CS1929,
CS0428,
CS7036));
}
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddUsingOrImport), Shared]
internal class CSharpAddImportCodeFixProvider : AbstractAddImportCodeFixProvider<SimpleNameSyntax>
{
public override ImmutableArray<string> FixableDiagnosticIds => AddImportDiagnosticIds.FixableDiagnosticIds;
public CSharpAddImportCodeFixProvider()
{
}
/// <summary>For testing purposes only (so that tests can pass in mock values)</summary>
internal CSharpAddImportCodeFixProvider(
IPackageInstallerService installerService,
IPackageSearchService packageSearchService)
: base(installerService, packageSearchService)
{
}
protected override bool CanAddImport(SyntaxNode node, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return false;
}
return node.CanAddUsingDirectives(cancellationToken);
}
protected override bool CanAddImportForMethod(
Diagnostic diagnostic, ISyntaxFactsService syntaxFacts, SyntaxNode node, out SimpleNameSyntax nameNode)
{
nameNode = null;
switch (diagnostic.Id)
{
case CS7036:
case CS0428:
case CS1061:
if (node.IsKind(SyntaxKind.ConditionalAccessExpression))
{
node = (node as ConditionalAccessExpressionSyntax).WhenNotNull;
}
else if (node.IsKind(SyntaxKind.MemberBindingExpression))
{
node = (node as MemberBindingExpressionSyntax).Name;
}
else if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression))
{
return true;
}
break;
case CS0122:
case CS1501:
if (node is SimpleNameSyntax)
{
break;
}
else if (node is MemberBindingExpressionSyntax)
{
node = (node as MemberBindingExpressionSyntax).Name;
}
break;
case CS1929:
var memberAccessName = (node.Parent as MemberAccessExpressionSyntax)?.Name;
var conditionalAccessName = (((node.Parent as ConditionalAccessExpressionSyntax)?.WhenNotNull as InvocationExpressionSyntax)?.Expression as MemberBindingExpressionSyntax)?.Name;
if (memberAccessName == null && conditionalAccessName == null)
{
return false;
}
node = memberAccessName ?? conditionalAccessName;
break;
case CS1503:
//// look up its corresponding method name
var parent = node.GetAncestor<InvocationExpressionSyntax>();
if (parent == null)
{
return false;
}
var method = parent.Expression as MemberAccessExpressionSyntax;
if (method != null)
{
node = method.Name;
}
break;
default:
return false;
}
nameNode = node as SimpleNameSyntax;
if (!nameNode.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) &&
!nameNode.IsParentKind(SyntaxKind.MemberBindingExpression))
{
return false;
}
var memberAccess = nameNode.Parent as MemberAccessExpressionSyntax;
var memberBinding = nameNode.Parent as MemberBindingExpressionSyntax;
if (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) ||
memberAccess.IsParentKind(SyntaxKind.ElementAccessExpression) ||
memberBinding.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) ||
memberBinding.IsParentKind(SyntaxKind.ElementAccessExpression))
{
return false;
}
if (!syntaxFacts.IsMemberAccessExpressionName(node))
{
return false;
}
return true;
}
protected override bool CanAddImportForNamespace(Diagnostic diagnostic, SyntaxNode node, out SimpleNameSyntax nameNode)
{
nameNode = null;
return false;
}
protected override bool CanAddImportForQuery(Diagnostic diagnostic, SyntaxNode node)
{
if (diagnostic.Id != CS1935)
{
return false;
}
return node.AncestorsAndSelf().Any(n => n is QueryExpressionSyntax && !(n.Parent is QueryContinuationSyntax));
}
protected override bool CanAddImportForType(Diagnostic diagnostic, SyntaxNode node, out SimpleNameSyntax nameNode)
{
nameNode = null;
switch (diagnostic.Id)
{
case CS0103:
case CS0246:
case CS0305:
case CS0308:
case CS0122:
case CS0307:
case CS0616:
case CS1580:
case CS1581:
break;
case CS1574:
case CS1584:
var cref = node as QualifiedCrefSyntax;
if (cref != null)
{
node = cref.Container;
}
break;
default:
return false;
}
return TryFindStandaloneType(node, out nameNode);
}
private static bool TryFindStandaloneType(SyntaxNode node, out SimpleNameSyntax nameNode)
{
var qn = node as QualifiedNameSyntax;
if (qn != null)
{
node = GetLeftMostSimpleName(qn);
}
nameNode = node as SimpleNameSyntax;
return nameNode.LooksLikeStandaloneTypeName();
}
private static SimpleNameSyntax GetLeftMostSimpleName(QualifiedNameSyntax qn)
{
while (qn != null)
{
var left = qn.Left;
var simpleName = left as SimpleNameSyntax;
if (simpleName != null)
{
return simpleName;
}
qn = left as QualifiedNameSyntax;
}
return null;
}
protected override ISet<INamespaceSymbol> GetNamespacesInScope(
SemanticModel semanticModel,
SyntaxNode node,
CancellationToken cancellationToken)
{
return semanticModel.GetUsingNamespacesInScope(node);
}
protected override ITypeSymbol GetQueryClauseInfo(
SemanticModel semanticModel,
SyntaxNode node,
CancellationToken cancellationToken)
{
var query = node.AncestorsAndSelf().OfType<QueryExpressionSyntax>().First();
if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(query.FromClause, cancellationToken)))
{
return null;
}
foreach (var clause in query.Body.Clauses)
{
if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(clause, cancellationToken)))
{
return null;
}
}
if (InfoBoundSuccessfully(semanticModel.GetSymbolInfo(query.Body.SelectOrGroup, cancellationToken)))
{
return null;
}
var fromClause = query.FromClause;
return semanticModel.GetTypeInfo(fromClause.Expression, cancellationToken).Type;
}
private bool InfoBoundSuccessfully(SymbolInfo symbolInfo)
{
return InfoBoundSuccessfully(symbolInfo.Symbol);
}
private bool InfoBoundSuccessfully(QueryClauseInfo semanticInfo)
{
return InfoBoundSuccessfully(semanticInfo.OperationInfo);
}
private static bool InfoBoundSuccessfully(ISymbol operation)
{
operation = operation.GetOriginalUnreducedDefinition();
return operation != null;
}
protected override string GetDescription(IReadOnlyList<string> nameParts)
{
return $"using { string.Join(".", nameParts) };";
}
protected override string GetDescription(
INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, SyntaxNode contextNode, bool checkForExistingUsing)
{
var root = GetCompilationUnitSyntaxNode(contextNode);
// No localization necessary
string externAliasString;
if (TryGetExternAliasString(namespaceSymbol, semanticModel, root, out externAliasString))
{
return $"extern alias {externAliasString};";
}
string namespaceString;
if (TryGetNamespaceString(namespaceSymbol, root, false, null, checkForExistingUsing, out namespaceString))
{
return $"using {namespaceString};";
}
string staticNamespaceString;
if (TryGetStaticNamespaceString(namespaceSymbol, root, false, null, out staticNamespaceString))
{
return $"using static {staticNamespaceString};";
}
// We can't find a string to show to the user, we should not show this codefix.
return null;
}
protected override async Task<Document> AddImportAsync(
SyntaxNode contextNode,
INamespaceOrTypeSymbol namespaceOrTypeSymbol,
Document document,
bool placeSystemNamespaceFirst,
CancellationToken cancellationToken)
{
var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken);
var newRoot = await AddImportWorkerAsync(document, root, contextNode, namespaceOrTypeSymbol, placeSystemNamespaceFirst, cancellationToken).ConfigureAwait(false);
return document.WithSyntaxRoot(newRoot);
}
private async Task<CompilationUnitSyntax> AddImportWorkerAsync(
Document document, CompilationUnitSyntax root, SyntaxNode contextNode,
INamespaceOrTypeSymbol namespaceOrTypeSymbol, bool placeSystemNamespaceFirst, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var simpleUsingDirective = GetUsingDirective(root, namespaceOrTypeSymbol, semanticModel, fullyQualify: false);
var externAliasUsingDirective = GetExternAliasUsingDirective(root, namespaceOrTypeSymbol, semanticModel);
if (externAliasUsingDirective != null)
{
root = root.AddExterns(
externAliasUsingDirective
.WithAdditionalAnnotations(Formatter.Annotation));
}
if (simpleUsingDirective == null)
{
return root;
}
// Because of the way usings can be nested inside of namespace declarations,
// we need to check if the usings must be fully qualified so as not to be
// ambiguous with the containing namespace.
if (UsingsAreContainedInNamespace(contextNode))
{
// When we add usings we try and place them, as best we can, where the user
// wants them according to their settings. This means we can't just add the fully-
// qualified usings and expect the simplifier to take care of it, the usings have to be
// simplified before we attempt to add them to the document.
// You might be tempted to think that we could call
// AddUsings -> Simplifier -> SortUsings
// But this will clobber the users using settings without asking. Instead we create a new
// Document and check if our using can be simplified. Worst case we need to back out the
// fully qualified change and reapply with the simple name.
var fullyQualifiedUsingDirective = GetUsingDirective(root, namespaceOrTypeSymbol, semanticModel, fullyQualify: true);
var newRoot = root.AddUsingDirective(
fullyQualifiedUsingDirective, contextNode, placeSystemNamespaceFirst,
Formatter.Annotation);
var newUsing = newRoot
.DescendantNodes().OfType<UsingDirectiveSyntax>()
.Where(uds => uds.IsEquivalentTo(fullyQualifiedUsingDirective, topLevel: true))
.Single();
newRoot = newRoot.TrackNodes(newUsing);
var documentWithSyntaxRoot = document.WithSyntaxRoot(newRoot);
var options = document.Project.Solution.Workspace.Options;
var simplifiedDocument = await Simplifier.ReduceAsync(documentWithSyntaxRoot, newUsing.Span, options, cancellationToken).ConfigureAwait(false);
newRoot = (CompilationUnitSyntax)await simplifiedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var simplifiedUsing = newRoot.GetCurrentNode(newUsing);
if (simplifiedUsing.Name.IsEquivalentTo(newUsing.Name, topLevel: true))
{
// Not fully qualifying the using causes to refer to a different namespace so we need to keep it as is.
return (CompilationUnitSyntax)await documentWithSyntaxRoot.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
}
else
{
// It does not matter if it is fully qualified or simple so lets return the simple name.
return root.AddUsingDirective(
simplifiedUsing.WithoutTrivia().WithoutAnnotations(), contextNode, placeSystemNamespaceFirst,
Formatter.Annotation);
}
}
else
{
// simple form
return root.AddUsingDirective(
simpleUsingDirective, contextNode, placeSystemNamespaceFirst,
Formatter.Annotation);
}
}
protected override Task<Document> AddImportAsync(
SyntaxNode contextNode, IReadOnlyList<string> namespaceParts, Document document, bool placeSystemNamespaceFirst, CancellationToken cancellationToken)
{
var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken);
// Suppress diagnostics on the import we create. Because we only get here when we are
// adding a nuget package, it is certainly the case that in the preview this will not
// bind properly. It will look silly to show such an error, so we just suppress things.
var simpleUsingDirective = SyntaxFactory.UsingDirective(
CreateNameSyntax(namespaceParts, namespaceParts.Count - 1)).WithAdditionalAnnotations(
SuppressDiagnosticsAnnotation.Create());
// If we have an existing using with this name then don't bother adding this new using.
if (root.Usings.Any(u => u.IsEquivalentTo(simpleUsingDirective, topLevel: false)))
{
return Task.FromResult(document);
}
var newRoot = root.AddUsingDirective(
simpleUsingDirective, contextNode, placeSystemNamespaceFirst,
Formatter.Annotation);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
private NameSyntax CreateNameSyntax(IReadOnlyList<string> namespaceParts, int index)
{
var part = namespaceParts[index];
if (SyntaxFacts.GetKeywordKind(part) != SyntaxKind.None)
{
part = "@" + part;
}
var namePiece = SyntaxFactory.IdentifierName(part);
return index == 0
? (NameSyntax)namePiece
: SyntaxFactory.QualifiedName(CreateNameSyntax(namespaceParts, index - 1), namePiece);
}
private static ExternAliasDirectiveSyntax GetExternAliasUsingDirective(CompilationUnitSyntax root, INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel)
{
string externAliasString;
if (TryGetExternAliasString(namespaceSymbol, semanticModel, root, out externAliasString))
{
return SyntaxFactory.ExternAliasDirective(SyntaxFactory.Identifier(externAliasString));
}
return null;
}
private UsingDirectiveSyntax GetUsingDirective(CompilationUnitSyntax root, INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, bool fullyQualify)
{
if (namespaceSymbol is INamespaceSymbol)
{
string namespaceString;
string externAliasString;
TryGetExternAliasString(namespaceSymbol, semanticModel, root, out externAliasString);
if (externAliasString != null)
{
if (TryGetNamespaceString(namespaceSymbol, root, false, externAliasString,
checkForExistingUsing: true, namespaceString: out namespaceString))
{
return SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(namespaceString).WithAdditionalAnnotations(Simplifier.Annotation));
}
return null;
}
if (TryGetNamespaceString(namespaceSymbol, root, fullyQualify, null,
checkForExistingUsing: true, namespaceString: out namespaceString))
{
return SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(namespaceString).WithAdditionalAnnotations(Simplifier.Annotation));
}
}
if (namespaceSymbol is ITypeSymbol)
{
string staticNamespaceString;
if (TryGetStaticNamespaceString(namespaceSymbol, root, fullyQualify, null, out staticNamespaceString))
{
return SyntaxFactory.UsingDirective(
SyntaxFactory.Token(SyntaxKind.UsingKeyword),
SyntaxFactory.Token(SyntaxKind.StaticKeyword),
null,
SyntaxFactory.ParseName(staticNamespaceString).WithAdditionalAnnotations(Simplifier.Annotation),
SyntaxFactory.Token(SyntaxKind.SemicolonToken));
}
}
return null;
}
private bool UsingsAreContainedInNamespace(SyntaxNode contextNode)
{
return contextNode.GetAncestor<NamespaceDeclarationSyntax>()?.DescendantNodes().OfType<UsingDirectiveSyntax>().FirstOrDefault() != null;
}
private static bool TryGetExternAliasString(INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, CompilationUnitSyntax root, out string externAliasString)
{
externAliasString = null;
var metadataReference = semanticModel.Compilation.GetMetadataReference(namespaceSymbol.ContainingAssembly);
if (metadataReference == null)
{
return false;
}
var aliases = metadataReference.Properties.Aliases;
if (aliases.IsEmpty)
{
return false;
}
aliases = metadataReference.Properties.Aliases.Where(a => a != MetadataReferenceProperties.GlobalAlias).ToImmutableArray();
if (!aliases.Any())
{
return false;
}
externAliasString = aliases.First();
return ShouldAddExternAlias(aliases, root);
}
private static bool TryGetNamespaceString(
INamespaceOrTypeSymbol namespaceSymbol, CompilationUnitSyntax root, bool fullyQualify, string alias,
bool checkForExistingUsing, out string namespaceString)
{
if (namespaceSymbol is ITypeSymbol)
{
namespaceString = null;
return false;
}
namespaceString = fullyQualify
? namespaceSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
: namespaceSymbol.ToDisplayString();
if (alias != null)
{
namespaceString = alias + "::" + namespaceString;
}
return checkForExistingUsing
? ShouldAddUsing(namespaceString, root)
: true;
}
private static bool TryGetStaticNamespaceString(INamespaceOrTypeSymbol namespaceSymbol, CompilationUnitSyntax root, bool fullyQualify, string alias, out string namespaceString)
{
if (namespaceSymbol is INamespaceSymbol)
{
namespaceString = null;
return false;
}
namespaceString = fullyQualify
? namespaceSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
: namespaceSymbol.ToDisplayString();
if (alias != null)
{
namespaceString = alias + "::" + namespaceString;
}
return ShouldAddStaticUsing(namespaceString, root);
}
private static bool ShouldAddExternAlias(ImmutableArray<string> aliases, CompilationUnitSyntax root)
{
var identifiers = root.DescendantNodes().OfType<ExternAliasDirectiveSyntax>().Select(e => e.Identifier.ToString());
var externAliases = aliases.Where(a => identifiers.Contains(a));
return !externAliases.Any();
}
private static bool ShouldAddUsing(string usingDirective, CompilationUnitSyntax root)
{
var simpleUsings = root.Usings.Where(u => u.StaticKeyword.IsKind(SyntaxKind.None));
return !simpleUsings.Any(u => u.Name.ToString() == usingDirective);
}
private static bool ShouldAddStaticUsing(string usingDirective, CompilationUnitSyntax root)
{
var staticUsings = root.Usings.Where(u => u.StaticKeyword.IsKind(SyntaxKind.StaticKeyword));
return !staticUsings.Any(u => u.Name.ToString() == usingDirective);
}
private static CompilationUnitSyntax GetCompilationUnitSyntaxNode(SyntaxNode contextNode, CancellationToken cancellationToken = default(CancellationToken))
{
return (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken);
}
protected override bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
var leftExpression = syntaxFacts.GetExpressionOfMemberAccessExpression(expression);
if (leftExpression == null)
{
if (expression.IsKind(SyntaxKind.CollectionInitializerExpression))
{
leftExpression = expression.GetAncestor<ObjectCreationExpressionSyntax>();
}
else
{
return false;
}
}
var semanticInfo = semanticModel.GetTypeInfo(leftExpression, cancellationToken);
var leftExpressionType = semanticInfo.Type;
return IsViableExtensionMethod(method, leftExpressionType);
}
internal override bool IsViableField(IFieldSymbol field, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
return IsViablePropertyOrField(field, expression, semanticModel, syntaxFacts, cancellationToken);
}
internal override bool IsViableProperty(IPropertySymbol property, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
return IsViablePropertyOrField(property, expression, semanticModel, syntaxFacts, cancellationToken);
}
private bool IsViablePropertyOrField(ISymbol propertyOrField, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
if (!propertyOrField.IsStatic)
{
return false;
}
var leftName = (expression as MemberAccessExpressionSyntax)?.Expression as SimpleNameSyntax;
if (leftName == null)
{
return false;
}
return StringComparer.Ordinal.Compare(propertyOrField.ContainingType.Name, leftName.Identifier.Text) == 0;
}
internal override bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel)
{
if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression))
{
var objectCreationExpressionSyntax = node.GetAncestor<ObjectCreationExpressionSyntax>();
if (objectCreationExpressionSyntax == null)
{
return false;
}
return true;
}
return false;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.