context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/*
* 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;
namespace OpenSim.Framework
{
public class PriorityQueue
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public delegate bool UpdatePriorityHandler(ref uint priority, ISceneEntity entity);
/// <summary>
/// Total number of queues (priorities) available
/// </summary>
public const uint NumberOfQueues = 12;
/// <summary>
/// Number of queuest (priorities) that are processed immediately
/// </summary.
public const uint NumberOfImmediateQueues = 2;
private MinHeap<MinHeapItem>[] m_heaps = new MinHeap<MinHeapItem>[NumberOfQueues];
private Dictionary<uint, LookupItem> m_lookupTable;
// internal state used to ensure the deqeues are spread across the priority
// queues "fairly". queuecounts is the amount to pull from each queue in
// each pass. weighted towards the higher priority queues
private uint m_nextQueue = 0;
private uint m_countFromQueue = 0;
private uint[] m_queueCounts = { 8, 4, 4, 2, 2, 2, 2, 1, 1, 1, 1, 1 };
// next request is a counter of the number of updates queued, it provides
// a total ordering on the updates coming through the queue and is more
// lightweight (and more discriminating) than tick count
private UInt64 m_nextRequest = 0;
/// <summary>
/// Lock for enqueue and dequeue operations on the priority queue
/// </summary>
private object m_syncRoot = new object();
public object SyncRoot {
get { return this.m_syncRoot; }
}
#region constructor
public PriorityQueue() : this(MinHeap<MinHeapItem>.DEFAULT_CAPACITY) { }
public PriorityQueue(int capacity)
{
m_lookupTable = new Dictionary<uint, LookupItem>(capacity);
for (int i = 0; i < m_heaps.Length; ++i)
m_heaps[i] = new MinHeap<MinHeapItem>(capacity);
m_nextQueue = NumberOfImmediateQueues;
m_countFromQueue = m_queueCounts[m_nextQueue];
}
#endregion Constructor
#region PublicMethods
/// <summary>
/// Return the number of items in the queues
/// </summary>
public int Count
{
get
{
int count = 0;
for (int i = 0; i < m_heaps.Length; ++i)
count += m_heaps[i].Count;
return count;
}
}
/// <summary>
/// Enqueue an item into the specified priority queue
/// </summary>
public bool Enqueue(uint pqueue, IEntityUpdate value)
{
LookupItem lookup;
uint localid = value.Entity.LocalId;
UInt64 entry = m_nextRequest++;
if (m_lookupTable.TryGetValue(localid, out lookup))
{
entry = lookup.Heap[lookup.Handle].EntryOrder;
value.Update(lookup.Heap[lookup.Handle].Value);
lookup.Heap.Remove(lookup.Handle);
}
pqueue = Util.Clamp<uint>(pqueue, 0, NumberOfQueues - 1);
lookup.Heap = m_heaps[pqueue];
lookup.Heap.Add(new MinHeapItem(pqueue, entry, value), ref lookup.Handle);
m_lookupTable[localid] = lookup;
return true;
}
/// <summary>
/// Remove an item from one of the queues. Specifically, it removes the
/// oldest item from the next queue in order to provide fair access to
/// all of the queues
/// </summary>
public bool TryDequeue(out IEntityUpdate value, out Int32 timeinqueue)
{
// If there is anything in priority queue 0, return it first no
// matter what else. Breaks fairness. But very useful.
for (int iq = 0; iq < NumberOfImmediateQueues; iq++)
{
if (m_heaps[iq].Count > 0)
{
MinHeapItem item = m_heaps[iq].RemoveMin();
m_lookupTable.Remove(item.Value.Entity.LocalId);
timeinqueue = Environment.TickCount - item.EntryTime;
value = item.Value;
return true;
}
}
// To get the fair queing, we cycle through each of the
// queues when finding an element to dequeue.
// We pull (NumberOfQueues - QueueIndex) items from each queue in order
// to give lower numbered queues a higher priority and higher percentage
// of the bandwidth.
// Check for more items to be pulled from the current queue
if (m_heaps[m_nextQueue].Count > 0 && m_countFromQueue > 0)
{
m_countFromQueue--;
MinHeapItem item = m_heaps[m_nextQueue].RemoveMin();
m_lookupTable.Remove(item.Value.Entity.LocalId);
timeinqueue = Environment.TickCount - item.EntryTime;
value = item.Value;
return true;
}
// Find the next non-immediate queue with updates in it
for (int i = 0; i < NumberOfQueues; ++i)
{
m_nextQueue = (uint)((m_nextQueue + 1) % NumberOfQueues);
m_countFromQueue = m_queueCounts[m_nextQueue];
// if this is one of the immediate queues, just skip it
if (m_nextQueue < NumberOfImmediateQueues)
continue;
if (m_heaps[m_nextQueue].Count > 0)
{
m_countFromQueue--;
MinHeapItem item = m_heaps[m_nextQueue].RemoveMin();
m_lookupTable.Remove(item.Value.Entity.LocalId);
timeinqueue = Environment.TickCount - item.EntryTime;
value = item.Value;
return true;
}
}
timeinqueue = 0;
value = default(IEntityUpdate);
return false;
}
/// <summary>
/// Reapply the prioritization function to each of the updates currently
/// stored in the priority queues.
/// </summary
public void Reprioritize(UpdatePriorityHandler handler)
{
MinHeapItem item;
foreach (LookupItem lookup in new List<LookupItem>(this.m_lookupTable.Values))
{
if (lookup.Heap.TryGetValue(lookup.Handle, out item))
{
uint pqueue = item.PriorityQueue;
uint localid = item.Value.Entity.LocalId;
if (handler(ref pqueue, item.Value.Entity))
{
// unless the priority queue has changed, there is no need to modify
// the entry
pqueue = Util.Clamp<uint>(pqueue, 0, NumberOfQueues - 1);
if (pqueue != item.PriorityQueue)
{
lookup.Heap.Remove(lookup.Handle);
LookupItem litem = lookup;
litem.Heap = m_heaps[pqueue];
litem.Heap.Add(new MinHeapItem(pqueue, item), ref litem.Handle);
m_lookupTable[localid] = litem;
}
}
else
{
// m_log.WarnFormat("[PQUEUE]: UpdatePriorityHandler returned false for {0}",item.Value.Entity.UUID);
lookup.Heap.Remove(lookup.Handle);
this.m_lookupTable.Remove(localid);
}
}
}
}
/// <summary>
/// </summary>
public override string ToString()
{
string s = "";
for (int i = 0; i < NumberOfQueues; i++)
s += String.Format("{0,7} ",m_heaps[i].Count);
return s;
}
#endregion PublicMethods
#region MinHeapItem
private struct MinHeapItem : IComparable<MinHeapItem>
{
private IEntityUpdate value;
internal IEntityUpdate Value {
get {
return this.value;
}
}
private uint pqueue;
internal uint PriorityQueue {
get {
return this.pqueue;
}
}
private Int32 entrytime;
internal Int32 EntryTime {
get {
return this.entrytime;
}
}
private UInt64 entryorder;
internal UInt64 EntryOrder
{
get {
return this.entryorder;
}
}
internal MinHeapItem(uint pqueue, MinHeapItem other)
{
this.entrytime = other.entrytime;
this.entryorder = other.entryorder;
this.value = other.value;
this.pqueue = pqueue;
}
internal MinHeapItem(uint pqueue, UInt64 entryorder, IEntityUpdate value)
{
this.entrytime = Environment.TickCount;
this.entryorder = entryorder;
this.value = value;
this.pqueue = pqueue;
}
public override string ToString()
{
return String.Format("[{0},{1},{2}]",pqueue,entryorder,value.Entity.LocalId);
}
public int CompareTo(MinHeapItem other)
{
// I'm assuming that the root part of an SOG is added to the update queue
// before the component parts
return Comparer<UInt64>.Default.Compare(this.EntryOrder, other.EntryOrder);
}
}
#endregion
#region LookupItem
private struct LookupItem
{
internal MinHeap<MinHeapItem> Heap;
internal IHandle Handle;
}
#endregion
}
}
| |
namespace XLabs.Platform.Services.Media
{
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Database;
using Android.OS;
using Android.Provider;
using Environment = Android.OS.Environment;
using Uri = Android.Net.Uri;
/// <summary>
/// Class MediaPickerActivity.
/// </summary>
[Activity]
internal class MediaPickerActivity
: Activity
{
#region Constants
/// <summary>
/// The extra path
/// </summary>
internal const string ExtraPath = "path";
/// <summary>
/// The extra location
/// </summary>
internal const string ExtraLocation = "location";
/// <summary>
/// The extra type
/// </summary>
internal const string ExtraType = "type";
/// <summary>
/// The extra identifier
/// </summary>
internal const string ExtraId = "id";
/// <summary>
/// The extra action
/// </summary>
internal const string ExtraAction = "action";
/// <summary>
/// The extra tasked
/// </summary>
internal const string ExtraTasked = "tasked";
/// <summary>
/// The medi a_ fil e_ extr a_ name
/// </summary>
internal const string MediaFileExtraName = "MediaFile";
#endregion Constants
#region Private Member Variables
/// <summary>
/// The action
/// </summary>
private string _action;
/// <summary>
/// The description
/// </summary>
private string _description;
/// <summary>
/// The identifier
/// </summary>
private int _id;
/// <summary>
/// The is photo
/// </summary>
private bool _isPhoto;
/// <summary>
/// The user's destination path.
/// </summary>
private Uri _path;
/// <summary>
/// The quality
/// </summary>
private VideoQuality _quality;
/// <summary>
/// The seconds
/// </summary>
private int _seconds;
/// <summary>
/// The tasked
/// </summary>
private bool _tasked;
/// <summary>
/// The title
/// </summary>
private string _title;
/// <summary>
/// The type
/// </summary>
private string _type;
#endregion Private Member Variables
#region Event Handlers
/// <summary>
/// Occurs when [media picked].
/// </summary>
internal static event EventHandler<MediaPickedEventArgs> MediaPicked;
#endregion Event Handlers
#region Methods
#region Overides
/// <summary>
/// Called to retrieve per-instance state from an activity before being killed
/// so that the state can be restored in <c><see cref="M:Android.App.Activity.OnCreate(Android.OS.Bundle)" /></c> or
/// <c><see cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" /></c> (the <c><see cref="T:Android.OS.Bundle" /></c> populated by this method
/// will be passed to both).
/// </summary>
/// <param name="outState">Bundle in which to place your saved state.</param>
/// <since version="Added in API level 1" />
/// <altmember cref="M:Android.App.Activity.OnCreate(Android.OS.Bundle)" />
/// <altmember cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" />
/// <altmember cref="M:Android.App.Activity.OnPause" />
/// <remarks><para tool="javadoc-to-mdoc">Called to retrieve per-instance state from an activity before being killed
/// so that the state can be restored in <c><see cref="M:Android.App.Activity.OnCreate(Android.OS.Bundle)" /></c> or
/// <c><see cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" /></c> (the <c><see cref="T:Android.OS.Bundle" /></c> populated by this method
/// will be passed to both).
/// </para>
/// <para tool="javadoc-to-mdoc">This method is called before an activity may be killed so that when it
/// comes back some time in the future it can restore its state. For example,
/// if activity B is launched in front of activity A, and at some point activity
/// A is killed to reclaim resources, activity A will have a chance to save the
/// current state of its user interface via this method so that when the user
/// returns to activity A, the state of the user interface can be restored
/// via <c><see cref="M:Android.App.Activity.OnCreate(Android.OS.Bundle)" /></c> or <c><see cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" /></c>.
/// </para>
/// <para tool="javadoc-to-mdoc">Do not confuse this method with activity lifecycle callbacks such as
/// <c><see cref="M:Android.App.Activity.OnPause" /></c>, which is always called when an activity is being placed
/// in the background or on its way to destruction, or <c><see cref="M:Android.App.Activity.OnStop" /></c> which
/// is called before destruction. One example of when <c><see cref="M:Android.App.Activity.OnPause" /></c> and
/// <c><see cref="M:Android.App.Activity.OnStop" /></c> is called and not this method is when a user navigates back
/// from activity B to activity A: there is no need to call <c><see cref="M:Android.App.Activity.OnSaveInstanceState(Android.OS.Bundle)" /></c>
/// on B because that particular instance will never be restored, so the
/// system avoids calling it. An example when <c><see cref="M:Android.App.Activity.OnPause" /></c> is called and
/// not <c><see cref="M:Android.App.Activity.OnSaveInstanceState(Android.OS.Bundle)" /></c> is when activity B is launched in front of activity A:
/// the system may avoid calling <c><see cref="M:Android.App.Activity.OnSaveInstanceState(Android.OS.Bundle)" /></c> on activity A if it isn't
/// killed during the lifetime of B since the state of the user interface of
/// A will stay intact.
/// </para>
/// <para tool="javadoc-to-mdoc">The default implementation takes care of most of the UI per-instance
/// state for you by calling <c><see cref="M:Android.Views.View.OnSaveInstanceState" /></c> on each
/// view in the hierarchy that has an id, and by saving the id of the currently
/// focused view (all of which is restored by the default implementation of
/// <c><see cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" /></c>). If you override this method to save additional
/// information not captured by each individual view, you will likely want to
/// call through to the default implementation, otherwise be prepared to save
/// all of the state of each view yourself.
/// </para>
/// <para tool="javadoc-to-mdoc">If called, this method will occur before <c><see cref="M:Android.App.Activity.OnStop" /></c>. There are
/// no guarantees about whether it will occur before or after <c><see cref="M:Android.App.Activity.OnPause" /></c>.</para>
/// <para tool="javadoc-to-mdoc">
/// <format type="text/html">
/// <a href="http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)" target="_blank">[Android Documentation]</a>
/// </format>
/// </para></remarks>
protected override void OnSaveInstanceState(Bundle outState)
{
outState.PutBoolean("ran", true);
outState.PutString(MediaStore.MediaColumns.Title, _title);
outState.PutString(MediaStore.Images.ImageColumns.Description, _description);
outState.PutInt(ExtraId, _id);
outState.PutString(ExtraType, _type);
outState.PutString(ExtraAction, _action);
outState.PutInt(MediaStore.ExtraDurationLimit, _seconds);
outState.PutInt(MediaStore.ExtraVideoQuality, (int) _quality);
outState.PutBoolean(ExtraTasked, _tasked);
if (_path != null)
outState.PutString(ExtraPath, _path.Path);
base.OnSaveInstanceState(outState);
}
/// <summary>
/// Called when the activity is starting.
/// </summary>
/// <param name="savedInstanceState">If the activity is being re-initialized after
/// previously being shut down then this Bundle contains the data it most
/// recently supplied in <c><see cref="M:Android.App.Activity.OnSaveInstanceState(Android.OS.Bundle)" /></c>. <format type="text/html"><b><i>Note: Otherwise it is null.</i></b></format></param>
/// <since version="Added in API level 1" />
/// <altmember cref="M:Android.App.Activity.OnStart" />
/// <altmember cref="M:Android.App.Activity.OnSaveInstanceState(Android.OS.Bundle)" />
/// <altmember cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" />
/// <altmember cref="M:Android.App.Activity.OnPostCreate(Android.OS.Bundle)" />
/// <remarks><para tool="javadoc-to-mdoc">Called when the activity is starting. This is where most initialization
/// should go: calling <c><see cref="M:Android.App.Activity.SetContentView(System.Int32)" /></c> to inflate the
/// activity's UI, using <c><see cref="M:Android.App.Activity.FindViewById(System.Int32)" /></c> to programmatically interact
/// with widgets in the UI, calling
/// <c><see cref="M:Android.App.Activity.ManagedQuery(Android.Net.Uri, System.String[], System.String[], System.String[], System.String[])" /></c> to retrieve
/// cursors for data being displayed, etc.
/// </para>
/// <para tool="javadoc-to-mdoc">You can call <c><see cref="M:Android.App.Activity.Finish" /></c> from within this function, in
/// which case onDestroy() will be immediately called without any of the rest
/// of the activity lifecycle (<c><see cref="M:Android.App.Activity.OnStart" /></c>, <c><see cref="M:Android.App.Activity.OnResume" /></c>,
/// <c><see cref="M:Android.App.Activity.OnPause" /></c>, etc) executing.
/// </para>
/// <para tool="javadoc-to-mdoc">
/// <i>Derived classes must call through to the super class's
/// implementation of this method. If they do not, an exception will be
/// thrown.</i>
/// </para>
/// <para tool="javadoc-to-mdoc">
/// <format type="text/html">
/// <a href="http://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle)" target="_blank">[Android Documentation]</a>
/// </format>
/// </para></remarks>
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
var b = (savedInstanceState ?? Intent.Extras);
var ran = b.GetBoolean("ran", false);
_title = b.GetString(MediaStore.MediaColumns.Title);
_description = b.GetString(MediaStore.Images.ImageColumns.Description);
_tasked = b.GetBoolean(ExtraTasked);
_id = b.GetInt(ExtraId, 0);
_type = b.GetString(ExtraType);
if (_type == "image/*")
{
_isPhoto = true;
}
_action = b.GetString(ExtraAction);
Intent pickIntent = null;
try
{
pickIntent = new Intent(_action);
if (_action == Intent.ActionPick)
pickIntent.SetType(_type);
else
{
if (!_isPhoto)
{
_seconds = b.GetInt(MediaStore.ExtraDurationLimit, 0);
if (_seconds != 0)
{
pickIntent.PutExtra(MediaStore.ExtraDurationLimit, _seconds);
}
}
_quality = (VideoQuality) b.GetInt(MediaStore.ExtraVideoQuality, (int) VideoQuality.High);
pickIntent.PutExtra(MediaStore.ExtraVideoQuality, GetVideoQuality(_quality));
if (!ran)
{
_path = GetOutputMediaFile(this, b.GetString(ExtraPath), _title, _isPhoto);
Touch();
pickIntent.PutExtra(MediaStore.ExtraOutput, _path);
}
else
_path = Uri.Parse(b.GetString(ExtraPath));
}
if (!ran)
{
StartActivityForResult(pickIntent, _id);
}
}
catch (Exception ex)
{
RaiseOnMediaPicked(new MediaPickedEventArgs(_id, ex));
}
finally
{
if (pickIntent != null)
pickIntent.Dispose();
}
}
/// <summary>
/// Called when an activity you launched exits, giving you the requestCode
/// you started it with, the resultCode it returned, and any additional
/// data from it.
/// </summary>
/// <param name="requestCode">The integer request code originally supplied to
/// startActivityForResult(), allowing you to identify who this
/// result came from.</param>
/// <param name="resultCode">The integer result code returned by the child activity
/// through its setResult().</param>
/// <param name="data">An Intent, which can return result data to the caller
/// (various data can be attached to Intent "extras").</param>
/// <since version="Added in API level 1" />
/// <altmember cref="M:Android.App.Activity.StartActivityForResult(Android.Content.Intent, System.Int32)" />
/// <altmember cref="M:Android.App.Activity.CreatePendingResult(System.Int32, Android.Content.Intent, Android.Content.Intent)" />
/// <altmember cref="M:Android.App.Activity.SetResult(Android.App.Result)" />
/// <remarks><para tool="javadoc-to-mdoc">Called when an activity you launched exits, giving you the requestCode
/// you started it with, the resultCode it returned, and any additional
/// data from it. The <format type="text/html"><var>resultCode</var></format> will be
/// <c><see cref="F:Android.App.Result.Canceled" /></c> if the activity explicitly returned that,
/// didn't return any result, or crashed during its operation.
/// </para>
/// <para tool="javadoc-to-mdoc">You will receive this call immediately before onResume() when your
/// activity is re-starting.</para>
/// <para tool="javadoc-to-mdoc">
/// <format type="text/html">
/// <a href="http://developer.android.com/reference/android/app/Activity.html#onActivityResult(int, int, android.content.Intent)" target="_blank">[Android Documentation]</a>
/// </format>
/// </para></remarks>
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (_tasked)
{
var future = resultCode == Result.Canceled
? TaskUtils.TaskFromResult(new MediaPickedEventArgs(requestCode, true))
: GetMediaFileAsync(this, requestCode, _action, _isPhoto, ref _path, (data != null) ? data.Data : null);
Finish();
future.ContinueWith(t => RaiseOnMediaPicked(t.Result));
}
else
{
if (resultCode == Result.Canceled)
{
SetResult(Result.Canceled);
}
else
{
var resultData = new Intent();
resultData.PutExtra(MediaFileExtraName, (data != null) ? data.Data : null);
resultData.PutExtra(ExtraPath, _path);
resultData.PutExtra("isPhoto", _isPhoto);
resultData.PutExtra(ExtraAction, _action);
SetResult(Result.Ok, resultData);
}
Finish();
}
}
#endregion Overides
#region Private Static Methods
/// <summary>
/// Gets the media file asynchronous.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="requestCode">The request code.</param>
/// <param name="action">The action.</param>
/// <param name="isPhoto">if set to <c>true</c> [is photo].</param>
/// <param name="path">The path.</param>
/// <param name="data">The data.</param>
/// <returns>Task<MediaPickedEventArgs>.</returns>
internal static Task<MediaPickedEventArgs> GetMediaFileAsync(Context context, int requestCode, string action,
bool isPhoto, ref Uri path, Uri data)
{
Task<Tuple<string, bool>> pathFuture;
Action<bool> dispose = null;
string originalPath = null;
if (action != Intent.ActionPick)
{
originalPath = path.Path;
// Not all camera apps respect EXTRA_OUTPUT, some will instead
// return a content or file uri from data.
if (data != null && data.Path != originalPath)
{
originalPath = data.ToString();
var currentPath = path.Path;
pathFuture = TryMoveFileAsync(context, data, path, isPhoto).ContinueWith(t =>
new Tuple<string, bool>(t.Result ? currentPath : null, false));
}
else
pathFuture = TaskUtils.TaskFromResult(new Tuple<string, bool>(path.Path, false));
}
else if (data != null)
{
originalPath = data.ToString();
path = data;
pathFuture = GetFileForUriAsync(context, path, isPhoto);
}
else
{
pathFuture = TaskUtils.TaskFromResult<Tuple<string, bool>>(null);
}
return pathFuture.ContinueWith(t =>
{
string resultPath = t.Result.Item1;
if (resultPath != null && File.Exists(t.Result.Item1))
{
if (t.Result.Item2)
{
dispose = d => File.Delete(resultPath);
}
var mf = new MediaFile(resultPath, () => File.OpenRead(t.Result.Item1) , dispose);
return new MediaPickedEventArgs(requestCode, false, mf);
}
return new MediaPickedEventArgs(requestCode, new MediaFileNotFoundException(originalPath));
});
}
/// <summary>
/// Tries the move file asynchronous.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="url">The URL.</param>
/// <param name="path">The path.</param>
/// <param name="isPhoto">if set to <c>true</c> [is photo].</param>
/// <returns>Task<System.Boolean>.</returns>
private static Task<bool> TryMoveFileAsync(Context context, Uri url, Uri path, bool isPhoto)
{
string moveTo = GetLocalPath(path);
return GetFileForUriAsync(context, url, isPhoto).ContinueWith(t =>
{
if (t.Result.Item1 == null)
return false;
File.Delete(moveTo);
File.Move(t.Result.Item1, moveTo);
if (url.Scheme == "content")
context.ContentResolver.Delete(url, null, null);
return true;
}, TaskScheduler.Default);
}
/// <summary>
/// Gets the video quality.
/// </summary>
/// <param name="videoQuality">The video quality.</param>
/// <returns>System.Int32.</returns>
private static int GetVideoQuality(VideoQuality videoQuality)
{
switch (videoQuality)
{
case VideoQuality.Medium:
case VideoQuality.High:
return 1;
default:
return 0;
}
}
/// <summary>
/// Gets the output media file.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="subdir">The subdir.</param>
/// <param name="name">The name.</param>
/// <param name="isPhoto">if set to <c>true</c> [is photo].</param>
/// <returns>Uri.</returns>
/// <exception cref="System.IO.IOException">Couldn't create directory, have you added the WRITE_EXTERNAL_STORAGE permission?</exception>
private static Uri GetOutputMediaFile(Context context, string subdir, string name, bool isPhoto)
{
subdir = subdir ?? String.Empty;
if (String.IsNullOrWhiteSpace(name))
{
name = MediaFileHelpers.GetMediaFileWithPath(isPhoto, subdir, string.Empty, name);
}
var mediaType = (isPhoto) ? Environment.DirectoryPictures : Environment.DirectoryMovies;
using (var mediaStorageDir = new Java.IO.File(context.GetExternalFilesDir(mediaType), subdir))
{
if (!mediaStorageDir.Exists())
{
if (!mediaStorageDir.Mkdirs())
throw new IOException("Couldn't create directory, have you added the WRITE_EXTERNAL_STORAGE permission?");
// Ensure this media doesn't show up in gallery apps
using (var nomedia = new Java.IO.File(mediaStorageDir, ".nomedia"))
nomedia.CreateNewFile();
}
return Uri.FromFile(new Java.IO.File(MediaFileHelpers.GetUniqueMediaFileWithPath(isPhoto, mediaStorageDir.Path, name, File.Exists)));
}
}
/// <summary>
/// Gets the file for URI asynchronous.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="uri">The URI.</param>
/// <param name="isPhoto">if set to <c>true</c> [is photo].</param>
/// <returns>Task<Tuple<System.String, System.Boolean>>.</returns>
internal static Task<Tuple<string, bool>> GetFileForUriAsync(Context context, Uri uri, bool isPhoto)
{
var tcs = new TaskCompletionSource<Tuple<string, bool>>();
if (uri.Scheme == "file")
tcs.SetResult(new Tuple<string, bool>(new System.Uri(uri.ToString()).LocalPath, false));
else if (uri.Scheme == "content")
{
Task.Factory.StartNew(() =>
{
ICursor cursor = null;
try
{
cursor = context.ContentResolver.Query(uri, null, null, null, null);
if (cursor == null || !cursor.MoveToNext())
tcs.SetResult(new Tuple<string, bool>(null, false));
else
{
int column = cursor.GetColumnIndex(MediaStore.MediaColumns.Data);
string contentPath = null;
if (column != -1)
contentPath = cursor.GetString(column);
bool copied = false;
// If they don't follow the "rules", try to copy the file locally
// if (contentPath == null || !contentPath.StartsWith("file"))
// {
// copied = true;
// Uri outputPath = GetOutputMediaFile(context, "temp", null, isPhoto);
//
// try
// {
// using (Stream input = context.ContentResolver.OpenInputStream(uri))
// using (Stream output = File.Create(outputPath.Path))
// input.CopyTo(output);
//
// contentPath = outputPath.Path;
// }
// catch (FileNotFoundException)
// {
// // If there's no data associated with the uri, we don't know
// // how to open this. contentPath will be null which will trigger
// // MediaFileNotFoundException.
// }
// }
tcs.SetResult(new Tuple<string, bool>(contentPath, copied));
}
}
finally
{
if (cursor != null)
{
cursor.Close();
cursor.Dispose();
}
}
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
else
tcs.SetResult(new Tuple<string, bool>(null, false));
return tcs.Task;
}
/// <summary>
/// Gets the local path.
/// </summary>
/// <param name="uri">The URI.</param>
/// <returns>System.String.</returns>
private static string GetLocalPath(Uri uri)
{
return new System.Uri(uri.ToString()).LocalPath;
}
#endregion Private Static Methods
#region Private Methods
/// <summary>
/// Touches this instance.
/// </summary>
private void Touch()
{
if (_path.Scheme != "file")
return;
File.Create(GetLocalPath(_path)).Close();
}
#endregion Private Methods
#region Raise Event Handlers
/// <summary>
/// Handles the <see cref="E:MediaPicked" /> event.
/// </summary>
/// <param name="e">The <see cref="MediaPickedEventArgs"/> instance containing the event data.</param>
private static void RaiseOnMediaPicked(MediaPickedEventArgs e)
{
var picked = MediaPicked;
if (picked != null)
{
picked(null, e);
}
}
#endregion Raise Event Handlers
#endregion Methods
}
/// <summary>
/// Class MediaPickedEventArgs.
/// </summary>
internal class MediaPickedEventArgs
: EventArgs
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MediaPickedEventArgs"/> class.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="error">The error.</param>
/// <exception cref="System.ArgumentNullException">error</exception>
public MediaPickedEventArgs(int id, Exception error)
{
if (error == null)
throw new ArgumentNullException("error");
RequestId = id;
Error = error;
}
/// <summary>
/// Initializes a new instance of the <see cref="MediaPickedEventArgs"/> class.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="isCanceled">if set to <c>true</c> [is canceled].</param>
/// <param name="media">The media.</param>
/// <exception cref="System.ArgumentNullException">media</exception>
public MediaPickedEventArgs(int id, bool isCanceled, MediaFile media = null)
{
RequestId = id;
IsCanceled = isCanceled;
if (!IsCanceled && media == null)
throw new ArgumentNullException("media");
Media = media;
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Gets the request identifier.
/// </summary>
/// <value>The request identifier.</value>
public int RequestId { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is canceled.
/// </summary>
/// <value><c>true</c> if this instance is canceled; otherwise, <c>false</c>.</value>
public bool IsCanceled { get; private set; }
/// <summary>
/// Gets the error.
/// </summary>
/// <value>The error.</value>
public Exception Error { get; private set; }
/// <summary>
/// Gets the media.
/// </summary>
/// <value>The media.</value>
public MediaFile Media { get; private set; }
#endregion Public Properties
#region Public Methods
/// <summary>
/// To the task.
/// </summary>
/// <returns>Task<MediaFile>.</returns>
public Task<MediaFile> ToTask()
{
var tcs = new TaskCompletionSource<MediaFile>();
if (IsCanceled)
tcs.SetCanceled();
else if (Error != null)
tcs.SetException(Error);
else
tcs.SetResult(Media);
return tcs.Task;
}
#endregion Public Methods
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace KERBALISM.Planner
{
///<summary> Planners simulator for all vessel aspects other than resource simulation </summary>
public sealed class VesselAnalyzer
{
public void Analyze(List<Part> parts, ResourceSimulator sim, EnvironmentAnalyzer env)
{
// note: vessel analysis require resource analysis, but at the same time resource analysis
// require vessel analysis, so we are using resource analysis from previous frame (that's okay)
// in the past, it was the other way around - however that triggered a corner case when va.comforts
// was null (because the vessel analysis was still never done) and some specific rule/process
// in resource analysis triggered an exception, leading to the vessel analysis never happening
// inverting their order avoided this corner-case
Analyze_crew(parts);
Analyze_habitat(parts, sim, env);
Analyze_radiation(parts, sim);
Analyze_reliability(parts);
Analyze_qol(parts, sim, env);
Analyze_comms(parts);
}
void Analyze_crew(List<Part> parts)
{
// get number of kerbals assigned to the vessel in the editor
// note: crew manifest is not reset after root part is deleted
VesselCrewManifest manifest = KSP.UI.CrewAssignmentDialog.Instance.GetManifest();
crew = manifest.GetAllCrew(false).FindAll(k => k != null);
crew_count = (uint)crew.Count;
crew_engineer = crew.Find(k => k.trait == "Engineer") != null;
crew_scientist = crew.Find(k => k.trait == "Scientist") != null;
crew_pilot = crew.Find(k => k.trait == "Pilot") != null;
crew_engineer_maxlevel = 0;
crew_scientist_maxlevel = 0;
crew_pilot_maxlevel = 0;
foreach (ProtoCrewMember c in crew)
{
switch (c.trait)
{
case "Engineer":
crew_engineer_maxlevel = Math.Max(crew_engineer_maxlevel, (uint)c.experienceLevel);
break;
case "Scientist":
crew_scientist_maxlevel = Math.Max(crew_scientist_maxlevel, (uint)c.experienceLevel);
break;
case "Pilot":
crew_pilot_maxlevel = Math.Max(crew_pilot_maxlevel, (uint)c.experienceLevel);
break;
}
}
// scan the parts
crew_capacity = 0;
foreach (Part p in parts)
{
// accumulate crew capacity
crew_capacity += (uint)p.CrewCapacity;
}
// if the user press ALT, the planner consider the vessel crewed at full capacity
if (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt))
crew_count = crew_capacity;
}
void Analyze_habitat(List<Part> parts, ResourceSimulator sim, EnvironmentAnalyzer env)
{
// calculate total volume
volume = sim.Resource("Atmosphere").capacity / 1e3;
// calculate total surface
surface = sim.Resource("Shielding").capacity;
// determine if the vessel has pressure control capabilities
pressurized = sim.Resource("Atmosphere").produced > 0.0 || env.breathable;
// determine if the vessel has scrubbing capabilities
scrubbed = sim.Resource("WasteAtmosphere").consumed > 0.0 || env.breathable;
// scan the parts
double max_pressure = 1.0;
foreach (Part p in parts)
{
// for each module
foreach (PartModule m in p.Modules)
{
// skip disabled modules
if (!m.isEnabled)
continue;
if (m.moduleName == "Habitat")
{
Habitat h = m as Habitat;
max_pressure = Math.Min(max_pressure, h.max_pressure);
}
}
}
pressurized &= max_pressure >= Settings.PressureThreshold;
}
void Analyze_comms(List<Part> parts)
{
has_comms = false;
foreach (Part p in parts)
{
foreach (PartModule m in p.Modules)
{
// skip disabled modules
if (!m.isEnabled)
continue;
// RemoteTech enabled, passive's don't count
if (m.moduleName == "ModuleRTAntenna")
has_comms = true;
else if (m is ModuleDataTransmitter mdt)
{
// CommNet enabled and external transmitter
if (HighLogic.fetch.currentGame.Parameters.Difficulty.EnableCommNet)
if (mdt.antennaType != AntennaType.INTERNAL)
has_comms = true;
// the simple stupid always connected signal system
else
has_comms = true;
}
}
}
}
void Analyze_radiation(List<Part> parts, ResourceSimulator sim)
{
// scan the parts
emitted = 0.0;
foreach (Part p in parts)
{
// for each module
foreach (PartModule m in p.Modules)
{
// skip disabled modules
if (!m.isEnabled)
continue;
// accumulate emitter radiation
if (m.moduleName == "Emitter")
{
Emitter emitter = m as Emitter;
emitter.Recalculate();
if (emitter.running)
{
if (emitter.radiation > 0) emitted += emitter.radiation * emitter.radiation_impact;
else emitted += emitter.radiation;
}
}
}
}
// calculate shielding factor
double amount = sim.Resource("Shielding").amount;
double capacity = sim.Resource("Shielding").capacity;
shielding = capacity > 0
? Radiation.ShieldingEfficiency(amount / capacity)
: 0;
}
void Analyze_reliability(List<Part> parts)
{
// reset data
high_quality = 0.0;
components = 0;
failure_year = 0.0;
redundancy = new Dictionary<string, int>();
// scan the parts
double year_time = 60.0 * 60.0 * Lib.HoursInDay * Lib.DaysInYear;
foreach (Part p in parts)
{
// for each module
foreach (PartModule m in p.Modules)
{
// skip disabled modules
if (!m.isEnabled)
continue;
// malfunctions
if (m.moduleName == "Reliability")
{
Reliability reliability = m as Reliability;
// calculate mtbf
double mtbf = reliability.mtbf * (reliability.quality ? Settings.QualityScale : 1.0);
if (mtbf <= 0) continue;
// accumulate failures/y
failure_year += year_time / mtbf;
// accumulate high quality percentage
high_quality += reliability.quality ? 1.0 : 0.0;
// accumulate number of components
++components;
// compile redundancy data
if (reliability.redundancy.Length > 0)
{
int count = 0;
if (redundancy.TryGetValue(reliability.redundancy, out count))
{
redundancy[reliability.redundancy] = count + 1;
}
else
{
redundancy.Add(reliability.redundancy, 1);
}
}
}
}
}
// calculate high quality percentage
high_quality /= Math.Max(components, 1u);
}
void Analyze_qol(List<Part> parts, ResourceSimulator sim, EnvironmentAnalyzer env)
{
// calculate living space factor
living_space = Lib.Clamp((volume / Math.Max(crew_count, 1u)) / PreferencesComfort.Instance.livingSpace, 0.1, 1.0);
// calculate comfort factor
comforts = new Comforts(parts, env.landed, crew_count > 1, has_comms);
}
// general
public List<ProtoCrewMember> crew; // full information on all crew
public uint crew_count; // crew member on board
public uint crew_capacity; // crew member capacity
public bool crew_engineer; // true if an engineer is among the crew
public bool crew_scientist; // true if a scientist is among the crew
public bool crew_pilot; // true if a pilot is among the crew
public uint crew_engineer_maxlevel; // experience level of top engineer on board
public uint crew_scientist_maxlevel; // experience level of top scientist on board
public uint crew_pilot_maxlevel; // experience level of top pilot on board
// habitat
public double volume; // total volume in m^3
public double surface; // total surface in m^2
public bool pressurized; // true if the vessel has pressure control capabilities
public bool scrubbed; // true if the vessel has co2 scrubbing capabilities
public bool humid; // true if the vessel has co2 scrubbing capabilities
// radiation related
public double emitted; // amount of radiation emitted by components
public double shielding; // shielding factor
// quality-of-life related
public double living_space; // living space factor
public Comforts comforts; // comfort info
// reliability-related
public uint components; // number of components that can fail
public double high_quality; // percentage of high quality components
public double failure_year; // estimated failures per-year, averaged per-component
public Dictionary<string, int> redundancy; // number of components per redundancy group
public bool has_comms;
}
} // KERBALISM
| |
using Saga.Enumarations;
using Saga.Map;
using Saga.Packets;
using Saga.Structures;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Sockets;
namespace Saga.PrimaryTypes
{
[System.Reflection.Obfuscation(Exclude = true, StripAfterObfuscation = true)]
[Serializable()]
public class Zone : ICloneable
{
#region Private Members
private byte map;
private ZoneType type;
private WorldCoordinate cathelaya_location;
private WorldCoordinate promise_location;
private uint regioncode;
private int weather;
[NonSerialized()]
private HeightMap heightmap;
[NonSerialized()]
private Regiontree regiontree;
#endregion Private Members
#region Public Members
public Regiontree Regiontree
{
get
{
return regiontree;
}
protected internal set
{
regiontree = value;
}
}
public ZoneType Type
{
get
{
return type;
}
protected internal set
{
type = value;
}
}
public byte Map
{
get
{
return map;
}
protected internal set
{
map = value;
}
}
public WorldCoordinate CathelayaLocation
{
get
{
return cathelaya_location;
}
protected internal set
{
cathelaya_location = value;
}
}
public WorldCoordinate ProsmiseLocation
{
get
{
return promise_location;
}
protected internal set
{
promise_location = value;
}
}
public HeightMap Heightmap
{
get
{
return heightmap;
}
protected internal set
{
heightmap = value;
}
}
/// <summary>
/// Returns the regioncode for the specified map.
/// </summary>
/// <remarks>
/// Each map is associated with his own unique region code or with a
/// shared regioncode. The region code is use by the internal quest
/// system to filter out official/personal quests.
///
/// When entering a new zone the personal quest list is filled by personal
/// quests that are available based upon the regioncode and matches the
/// criteria for beeing visible.
/// </remarks>
public uint RegionCode
{
get
{
return regioncode;
}
protected internal set
{
regioncode = value;
}
}
/// <summary>
/// Get's the current weather as a interger.
/// </summary>
public int Weather
{
get
{
return weather;
}
}
#endregion Public Members
#region Public methods
public void Clear()
{
lock (this.regiontree)
{
List<MapObject> list = new List<MapObject>();
list.AddRange(regiontree.Clear());
foreach (Character character in Regiontree.SearchActors(SearchFlags.Characters))
{
foreach (MapObject regionObject in list)
{
try
{
SMSG_ACTORDELETE spkt = new SMSG_ACTORDELETE();
spkt.ActorID = regionObject.id;
spkt.SessionId = character.id;
character.client.Send((byte[])spkt);
}
catch (SocketException)
{
break;
}
catch (Exception e)
{
Trace.TraceWarning(e.ToString());
}
}
}
foreach (MapObject regionObject in list)
{
try
{
regionObject.OnDeregister();
}
catch (Exception)
{
//Do nothing
}
}
}
}
/// <summary>
/// Occurs when entering a zone.
/// </summary>
/// <param name="character"></param>
public virtual void OnEnter(Character character)
{
}
/// <summary>
/// Occurs when leaving a zone
/// </summary>
/// <param name="character"></param>
public virtual void OnLeave(Character character)
{
if (character.currentzone == this)
{
if (!this.Regiontree.Unsubscribe(character))
{
Trace.TraceError("Unsubscribe failed");
}
Regiontree tree = character.currentzone.Regiontree;
foreach (MapObject target in tree.SearchActors(character, Saga.Enumarations.SearchFlags.DynamicObjects))
{
if (MapObject.IsPlayer(target))
{
Character cTarget = (Character)target;
if (cTarget != character && cTarget.client.isloaded == true)
character.HideObject(cTarget);
target.Disappear(character);
}
else
{
target.Disappear(character);
}
}
}
}
public IEnumerable<MapObject> GetObjectsInRegionalRange(MapObject a)
{
/*
* Returns all objects in the regional sightrange.
*
* Usefull for updates that should be spread about amongst
* multiple regions. For example update player information
*
*/
foreach (MapObject c in this.regiontree.SearchActors(a, SearchFlags.DynamicObjects))
{
yield return c;
}
}
/// <summary>
/// Returns all objects in the regional sightrange.
/// </summary>
/// <param name="a">Object which to check if he can see</param>
/// <returns>a list of objects which can be seen</returns>
/// <remarks>
/// Usefull for updates that should be spread about amongst
/// multiple regions. For example update player information
/// </remarks>
public IEnumerable<MapObject> GetObjectsInSightRange(MapObject a)
{
foreach (MapObject c in this.regiontree.SearchActors(a, SearchFlags.DynamicObjects))
{
if (IsInSightRangeByRadius(c.Position, a.Position))
yield return c;
}
}
/// <summary>
/// Returns all chacters in the regional sightrange.
/// </summary>
/// <param name="a">Object which to check if he can see</param>
/// <returns>a list of objects which can be seen</returns>
/// <remarks>
/// Usefull for updates that should be spread about amongst
/// multiple regions. For example update player information
/// </remarks>
public IEnumerable<Character> GetCharactersInSightRange(MapObject a)
{
foreach (MapObject c in this.regiontree.SearchActors(a, SearchFlags.Characters))
{
if (MapObject.IsPlayer(c))
if (IsInSightRangeByRadius(c.Position, a.Position))
yield return (Character)c;
}
}
/// <summary>
/// Check if a object is in sightrange of eachother
/// </summary>
/// <returns>
/// Checks if position a is in a range of position b.
/// This sub function is used to calculate objects we are allowed to
/// see. Applied for 3 axices: X, Y, Z.///
/// </returns>
public bool IsInSightRangeByRadius(Point A, Point B)
{
double dx = (double)(A.x - B.x);
double dy = (double)(A.y - B.y);
double dz = (double)(A.z - B.z);
double distance = Math.Sqrt(dx * dx + dy * dy + dz * dz);
return distance < 10000;
}
/// <summary>
/// </summary>
/// <returns>True if a object is visible by a square bounds</returns>
/// <remarks>
/// Checks if position a is in range of position b.
/// This sub function should be obfuscated, and could serve as a backup
/// for the Radius.
/// </remarks>
public bool IsInSightRangeBySquare(Point A, Point B)
{
if (Math.Abs(A.x - B.x) > 10000) return false;
if (Math.Abs(A.y - B.y) > 10000) return false;
return true;
}
public Point GetZ(Point postion)
{
//Correct z-heightmap with z-index
float z = 0;
if (this.Heightmap != null)
{
if (this.Heightmap.GetZ(postion.x, postion.y, out z))
{
return new Point(postion.x, postion.y, z + 30);
}
else
{
return postion;
}
}
else
{
return postion;
}
}
public bool SaveLocation(Character character)
{
if (character.currentzone.ProsmiseLocation.map > 0)
{
character.savelocation = character.currentzone.ProsmiseLocation;
SMSG_KAFTRAHOMEPOINT spkt = new SMSG_KAFTRAHOMEPOINT();
spkt.SessionId = character.id;
spkt.Result = 0;
spkt.Zone = character.savelocation.map;
character.client.Send((byte[])spkt);
WorldCoordinate lpos = character.lastlocation.map > 0 ? character.lastlocation : character.savelocation;
WorldCoordinate spos = character.savelocation;
if (spos.map == character.currentzone.Map)
{
SMSG_RETURNMAPLIST spkt2 = new SMSG_RETURNMAPLIST();
spkt2.ToMap = lpos.map;
spkt2.FromMap = character.currentzone.CathelayaLocation.map;
spkt2.IsSaveLocationSet = (lpos.map > 0) ? (byte)1 : (byte)0;
spkt2.SessionId = character.id;
character.client.Send((byte[])spkt2);
}
else
{
SMSG_RETURNMAPLIST spkt2 = new SMSG_RETURNMAPLIST();
spkt2.ToMap = spos.map;
spkt2.FromMap = character.currentzone.CathelayaLocation.map;
spkt2.IsSaveLocationSet = (spos.map > 0) ? (byte)1 : (byte)0;
spkt2.SessionId = character.id;
character.client.Send((byte[])spkt2);
}
return true;
}
else
{
SMSG_KAFTRAHOMEPOINT spkt = new SMSG_KAFTRAHOMEPOINT();
spkt.SessionId = character.id;
spkt.Result = 1;
character.client.Send((byte[])spkt);
return false;
}
}
public void UpdateWeather(int Weather)
{
this.weather = Weather;
foreach (Character c in this.regiontree.SearchActors(SearchFlags.Characters))
{
CommonFunctions.UpdateTimeWeather(c as Character);
}
}
/// <summary>
/// Is called when the weather changes
/// </summary>
/// <remarks>
/// This method is called when the weather of the zone is supposed to change.
/// Our parameter the int weather speciafies the new weather in which it's
/// supposed to change.
///
/// Override this method when you need to control which types of weathers
/// should be allowed for the current map.
/// </remarks>
/// <param name="Weather"></param>
public virtual void OnChangeWeather(int Weather)
{
UpdateWeather(Weather);
}
#endregion Public methods
#region ICloneable Members
/// <summary>
/// Clones the zone with a clean regiontree.
/// </summary>
/// <returns>Cloned zone instance</returns>
object ICloneable.Clone()
{
Zone b = new Zone();
b.ProsmiseLocation = this.ProsmiseLocation;
b.CathelayaLocation = this.CathelayaLocation;
b.RegionCode = this.RegionCode;
b.Regiontree = new Regiontree();
b.Type = this.Type;
b.weather = this.Weather;
b.map = this.map;
return b;
}
#endregion ICloneable Members
}
}
| |
/*******************************************************************************
* Copyright 2017 ROBOTIS CO., LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/* Author: Ryu Woon Jung (Leon) */
using System;
using System.Runtime.InteropServices;
namespace dynamixel_sdk
{
class dynamixel
{
const string dll_path = "../../../../../../../../c/build/win64/output/dxl_x64_c.dll";
#region PortHandler
[DllImport(dll_path)]
public static extern int portHandler (string port_name);
[DllImport(dll_path)]
public static extern bool openPort (int port_num);
[DllImport(dll_path)]
public static extern void closePort (int port_num);
[DllImport(dll_path)]
public static extern void clearPort (int port_num);
[DllImport(dll_path)]
public static extern void setPortName (int port_num, string port_name);
[DllImport(dll_path)]
public static extern string getPortName (int port_num);
[DllImport(dll_path)]
public static extern bool setBaudRate (int port_num, int baudrate);
[DllImport(dll_path)]
public static extern int getBaudRate (int port_num);
[DllImport(dll_path)]
public static extern int readPort (int port_num, byte[] packet, int length);
[DllImport(dll_path)]
public static extern int writePort (int port_num, byte[] packet, int length);
[DllImport(dll_path)]
public static extern void setPacketTimeout (int port_num, UInt16 packet_length);
[DllImport(dll_path)]
public static extern void setPacketTimeoutMSec(int port_num, double msec);
[DllImport(dll_path)]
public static extern bool isPacketTimeout (int port_num);
#endregion
#region PacketHandler
[DllImport(dll_path)]
public static extern void packetHandler ();
[DllImport(dll_path)]
public static extern IntPtr getTxRxResult (int protocol_version, int result);
[DllImport(dll_path)]
public static extern IntPtr getRxPacketError (int protocol_version, byte error);
[DllImport(dll_path)]
public static extern int getLastTxRxResult (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern byte getLastRxPacketError(int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern void setDataWrite (int port_num, int protocol_version, UInt16 data_length, UInt16 data_pos, UInt32 data);
[DllImport(dll_path)]
public static extern UInt32 getDataRead (int port_num, int protocol_version, UInt16 data_length, UInt16 data_pos);
[DllImport(dll_path)]
public static extern void txPacket (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern void rxPacket (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern void txRxPacket (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern void ping (int port_num, int protocol_version, byte id);
[DllImport(dll_path)]
public static extern UInt16 pingGetModelNum (int port_num, int protocol_version, byte id);
[DllImport(dll_path)]
public static extern void broadcastPing (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern bool getBroadcastPingResult(int port_num, int protocol_version, int id);
[DllImport(dll_path)]
public static extern void reboot (int port_num, int protocol_version, byte id);
[DllImport(dll_path)]
public static extern void factoryReset (int port_num, int protocol_version, byte id, byte option);
[DllImport(dll_path)]
public static extern void readTx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void readRx (int port_num, int protocol_version, UInt16 length);
[DllImport(dll_path)]
public static extern void readTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void read1ByteTx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern byte read1ByteRx (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern byte read1ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern void read2ByteTx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern UInt16 read2ByteRx (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern UInt16 read2ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern void read4ByteTx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern UInt32 read4ByteRx (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern UInt32 read4ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern void writeTxOnly (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void writeTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void write1ByteTxOnly (int port_num, int protocol_version, byte id, UInt16 address, byte data);
[DllImport(dll_path)]
public static extern void write1ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address, byte data);
[DllImport(dll_path)]
public static extern void write2ByteTxOnly (int port_num, int protocol_version, byte id, UInt16 address, UInt16 data);
[DllImport(dll_path)]
public static extern void write2ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 data);
[DllImport(dll_path)]
public static extern void write4ByteTxOnly (int port_num, int protocol_version, byte id, UInt16 address, UInt32 data);
[DllImport(dll_path)]
public static extern void write4ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt32 data);
[DllImport(dll_path)]
public static extern void regWriteTxOnly (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void regWriteTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void syncReadTx (int port_num, int protocol_version, UInt16 start_address, UInt16 data_length, UInt16 param_length);
// syncReadRx -> GroupSyncRead
// syncReadTxRx -> GroupSyncRead
[DllImport(dll_path)]
public static extern void syncWriteTxOnly (int port_num, int protocol_version, UInt16 start_address, UInt16 data_length, UInt16 param_length);
[DllImport(dll_path)]
public static extern void bulkReadTx (int port_num, int protocol_version, UInt16 param_length);
// bulkReadRx -> GroupBulkRead
// bulkReadTxRx -> GroupBulkRead
[DllImport(dll_path)]
public static extern void bulkWriteTxOnly (int port_num, int protocol_version, UInt16 param_length);
#endregion
#region GroupBulkRead
[DllImport(dll_path)]
public static extern int groupBulkRead (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern bool groupBulkReadAddParam (int group_num, byte id, UInt16 start_address, UInt16 data_length);
[DllImport(dll_path)]
public static extern void groupBulkReadRemoveParam(int group_num, byte id);
[DllImport(dll_path)]
public static extern void groupBulkReadClearParam (int group_num);
[DllImport(dll_path)]
public static extern void groupBulkReadTxPacket (int group_num);
[DllImport(dll_path)]
public static extern void groupBulkReadRxPacket (int group_num);
[DllImport(dll_path)]
public static extern void groupBulkReadTxRxPacket (int group_num);
[DllImport(dll_path)]
public static extern bool groupBulkReadIsAvailable(int group_num, byte id, UInt16 address, UInt16 data_length);
[DllImport(dll_path)]
public static extern UInt32 groupBulkReadGetData (int group_num, byte id, UInt16 address, UInt16 data_length);
#endregion
#region GroupBulkWrite
[DllImport(dll_path)]
public static extern int groupBulkWrite (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern bool groupBulkWriteAddParam (int group_num, byte id, UInt16 start_address, UInt16 data_length, UInt32 data, UInt16 input_length);
[DllImport(dll_path)]
public static extern void groupBulkWriteRemoveParam (int group_num, byte id);
[DllImport(dll_path)]
public static extern bool groupBulkWriteChangeParam (int group_num, byte id, UInt16 start_address, UInt16 data_length, UInt32 data, UInt16 input_length, UInt16 data_pos);
[DllImport(dll_path)]
public static extern void groupBulkWriteClearParam (int group_num);
[DllImport(dll_path)]
public static extern void groupBulkWriteTxPacket (int group_num);
#endregion
#region GroupSyncRead
[DllImport(dll_path)]
public static extern int groupSyncRead (int port_num, int protocol_version, UInt16 start_address, UInt16 data_length);
[DllImport(dll_path)]
public static extern bool groupSyncReadAddParam (int group_num, byte id);
[DllImport(dll_path)]
public static extern void groupSyncReadRemoveParam (int group_num, byte id);
[DllImport(dll_path)]
public static extern void groupSyncReadClearParam (int group_num);
[DllImport(dll_path)]
public static extern void groupSyncReadTxPacket (int group_num);
[DllImport(dll_path)]
public static extern void groupSyncReadRxPacket (int group_num);
[DllImport(dll_path)]
public static extern void groupSyncReadTxRxPacket (int group_num);
[DllImport(dll_path)]
public static extern bool groupSyncReadIsAvailable (int group_num, byte id, UInt16 address, UInt16 data_length);
[DllImport(dll_path)]
public static extern UInt32 groupSyncReadGetData (int group_num, byte id, UInt16 address, UInt16 data_length);
#endregion
#region GroupSyncWrite
[DllImport(dll_path)]
public static extern int groupSyncWrite (int port_num, int protocol_version, UInt16 start_address, UInt16 data_length);
[DllImport(dll_path)]
public static extern bool groupSyncWriteAddParam (int group_num, byte id, UInt32 data, UInt16 data_length);
[DllImport(dll_path)]
public static extern void groupSyncWriteRemoveParam (int group_num, byte id);
[DllImport(dll_path)]
public static extern bool groupSyncWriteChangeParam (int group_num, byte id, UInt32 data, UInt16 data_length, UInt16 data_pos);
[DllImport(dll_path)]
public static extern void groupSyncWriteClearParam (int group_num);
[DllImport(dll_path)]
public static extern void groupSyncWriteTxPacket (int group_num);
#endregion
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009, 2010 Oracle and/or its affiliates. All rights reserved.
*
*/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using BerkeleyDB.Internal;
namespace BerkeleyDB {
/// <summary>
/// A class representing a HashDatabase. The Hash format is an extensible,
/// dynamic hashing scheme.
/// </summary>
public class HashDatabase : Database {
private HashFunctionDelegate hashHandler;
private EntryComparisonDelegate compareHandler;
private EntryComparisonDelegate dupCompareHandler;
private BDB_CompareDelegate doCompareRef;
private BDB_HashDelegate doHashRef;
private BDB_CompareDelegate doDupCompareRef;
#region Constructors
private HashDatabase(DatabaseEnvironment env, uint flags)
: base(env, flags) { }
internal HashDatabase(BaseDatabase clone) : base(clone) { }
private void Config(HashDatabaseConfig cfg) {
base.Config(cfg);
/*
* Database.Config calls set_flags, but that doesn't get the Hash
* specific flags. No harm in calling it again.
*/
db.set_flags(cfg.flags);
if (cfg.HashFunction != null)
HashFunction = cfg.HashFunction;
// The duplicate comparison function cannot change.
if (cfg.DuplicateCompare != null)
DupCompare = cfg.DuplicateCompare;
if (cfg.fillFactorIsSet)
db.set_h_ffactor(cfg.FillFactor);
if (cfg.nelemIsSet)
db.set_h_nelem(cfg.TableSize);
if (cfg.HashComparison != null)
Compare = cfg.HashComparison;
}
/// <summary>
/// Instantiate a new HashDatabase object and open the database
/// represented by <paramref name="Filename"/>.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="Filename"/> is null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe.
/// </para>
/// <para>
/// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation
/// will be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <returns>A new, open database object</returns>
public static HashDatabase Open(
string Filename, HashDatabaseConfig cfg) {
return Open(Filename, null, cfg, null);
}
/// <summary>
/// Instantiate a new HashDatabase object and open the database
/// represented by <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/>.
/// </summary>
/// <remarks>
/// <para>
/// If both <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/> are null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe. If
/// <paramref name="Filename"/> is null and
/// <paramref name="DatabaseName"/> is non-null, the database can be
/// opened by other threads of control and will be replicated to client
/// sites in any replication group.
/// </para>
/// <para>
/// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation
/// will be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="DatabaseName">
/// This parameter allows applications to have multiple databases in a
/// single file. Although no DatabaseName needs to be specified, it is
/// an error to attempt to open a second database in a file that was not
/// initially created using a database name.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <returns>A new, open database object</returns>
public static HashDatabase Open(
string Filename, string DatabaseName, HashDatabaseConfig cfg) {
return Open(Filename, DatabaseName, cfg, null);
}
/// <summary>
/// Instantiate a new HashDatabase object and open the database
/// represented by <paramref name="Filename"/>.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="Filename"/> is null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe.
/// </para>
/// <para>
/// If <paramref name="txn"/> is null, but
/// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will
/// be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open. Also note that the
/// transaction must be committed before the object is closed.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>A new, open database object</returns>
public static HashDatabase Open(
string Filename, HashDatabaseConfig cfg, Transaction txn) {
return Open(Filename, null, cfg, txn);
}
/// <summary>
/// Instantiate a new HashDatabase object and open the database
/// represented by <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/>.
/// </summary>
/// <remarks>
/// <para>
/// If both <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/> are null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe. If
/// <paramref name="Filename"/> is null and
/// <paramref name="DatabaseName"/> is non-null, the database can be
/// opened by other threads of control and will be replicated to client
/// sites in any replication group.
/// </para>
/// <para>
/// If <paramref name="txn"/> is null, but
/// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will
/// be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open. Also note that the
/// transaction must be committed before the object is closed.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="DatabaseName">
/// This parameter allows applications to have multiple databases in a
/// single file. Although no DatabaseName needs to be specified, it is
/// an error to attempt to open a second database in a file that was not
/// initially created using a database name.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>A new, open database object</returns>
public static HashDatabase Open(string Filename,
string DatabaseName, HashDatabaseConfig cfg, Transaction txn) {
HashDatabase ret = new HashDatabase(cfg.Env, 0);
ret.Config(cfg);
ret.db.open(Transaction.getDB_TXN(txn),
Filename, DatabaseName, DBTYPE.DB_HASH, cfg.openFlags, 0);
ret.isOpen = true;
return ret;
}
#endregion Constructors
#region Callbacks
private static int doDupCompare(
IntPtr dbp, IntPtr dbt1p, IntPtr dbt2p) {
DB db = new DB(dbp, false);
DBT dbt1 = new DBT(dbt1p, false);
DBT dbt2 = new DBT(dbt2p, false);
return ((HashDatabase)(db.api_internal)).DupCompare(
DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2));
}
private static uint doHash(IntPtr dbp, IntPtr datap, uint len) {
DB db = new DB(dbp, false);
byte[] t_data = new byte[len];
Marshal.Copy(datap, t_data, 0, (int)len);
return ((HashDatabase)(db.api_internal)).hashHandler(t_data);
}
private static int doCompare(IntPtr dbp, IntPtr dbtp1, IntPtr dbtp2) {
DB db = new DB(dbp, false);
DBT dbt1 = new DBT(dbtp1, false);
DBT dbt2 = new DBT(dbtp2, false);
return ((HashDatabase)(db.api_internal)).compareHandler(
DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2));
}
#endregion Callbacks
#region Properties
/// <summary>
/// The Hash key comparison function. The comparison function is called
/// whenever it is necessary to compare a key specified by the
/// application with a key currently stored in the tree.
/// </summary>
public EntryComparisonDelegate Compare {
get { return compareHandler; }
private set {
if (value == null)
db.set_h_compare(null);
else if (compareHandler == null) {
if (doCompareRef == null)
doCompareRef = new BDB_CompareDelegate(doCompare);
db.set_h_compare(doCompareRef);
}
compareHandler = value;
}
}
/// <summary>
/// The duplicate data item comparison function.
/// </summary>
public EntryComparisonDelegate DupCompare {
get { return dupCompareHandler; }
private set {
/* Cannot be called after open. */
if (value == null)
db.set_dup_compare(null);
else if (dupCompareHandler == null) {
if (doDupCompareRef == null)
doDupCompareRef = new BDB_CompareDelegate(doDupCompare);
db.set_dup_compare(doDupCompareRef);
}
dupCompareHandler = value;
}
}
/// <summary>
/// Whether the insertion of duplicate data items in the database is
/// permitted, and whether duplicates items are sorted.
/// </summary>
public DuplicatesPolicy Duplicates {
get {
uint flags = 0;
db.get_flags(ref flags);
if ((flags & DbConstants.DB_DUPSORT) != 0)
return DuplicatesPolicy.SORTED;
else if ((flags & DbConstants.DB_DUP) != 0)
return DuplicatesPolicy.UNSORTED;
else
return DuplicatesPolicy.NONE;
}
}
/// <summary>
/// The desired density within the hash table.
/// </summary>
public uint FillFactor {
get {
uint ret = 0;
db.get_h_ffactor(ref ret);
return ret;
}
}
/// <summary>
/// A user-defined hash function; if no hash function is specified, a
/// default hash function is used.
/// </summary>
public HashFunctionDelegate HashFunction {
get { return hashHandler; }
private set {
if (value == null)
db.set_h_hash(null);
else if (hashHandler == null) {
if (doHashRef == null)
doHashRef = new BDB_HashDelegate(doHash);
db.set_h_hash(doHashRef);
}
hashHandler = value;
}
}
/// <summary>
/// An estimate of the final size of the hash table.
/// </summary>
public uint TableSize {
get {
uint ret = 0;
db.get_h_nelem(ref ret);
return ret;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Compact the database, and optionally return unused database pages to
/// the underlying filesystem.
/// </summary>
/// <remarks>
/// If the operation occurs in a transactional database, the operation
/// will be implicitly transaction protected using multiple
/// transactions. These transactions will be periodically committed to
/// avoid locking large sections of the tree. Any deadlocks encountered
/// cause the compaction operation to be retried from the point of the
/// last transaction commit.
/// </remarks>
/// <param name="cdata">Compact configuration parameters</param>
/// <returns>
/// Compact operation statistics, where <see cref="CompactData.End"/>
/// holds the integer value representing which bucket the compaction
/// stopped in.
/// </returns>
public CompactData Compact(CompactConfig cdata) {
return Compact(cdata, null);
}
/// <summary>
/// Compact the database, and optionally return unused database pages to
/// the underlying filesystem.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="txn"/> is non-null, then the operation is
/// performed using that transaction. In this event, large sections of
/// the tree may be locked during the course of the transaction.
/// </para>
/// <para>
/// If <paramref name="txn"/> is null, but the operation occurs in a
/// transactional database, the operation will be implicitly transaction
/// protected using multiple transactions. These transactions will be
/// periodically committed to avoid locking large sections of the tree.
/// Any deadlocks encountered cause the compaction operation to be
/// retried from the point of the last transaction commit.
/// </para>
/// </remarks>
/// <param name="cdata">Compact configuration parameters</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>
/// Compact operation statistics, where <see cref="CompactData.End"/>
/// holds the integer value representing which bucket the compaction
/// stopped in.
/// </returns>
public CompactData Compact(CompactConfig cdata, Transaction txn) {
DatabaseEntry end = null;
if (cdata.returnEnd)
end = new DatabaseEntry();
db.compact(Transaction.getDB_TXN(txn), cdata.start, cdata.stop,
CompactConfig.getDB_COMPACT(cdata), cdata.flags, end);
return new CompactData(CompactConfig.getDB_COMPACT(cdata), end);
}
/// <summary>
/// Create a database cursor.
/// </summary>
/// <returns>A newly created cursor</returns>
public new HashCursor Cursor() {
return Cursor(new CursorConfig(), null);
}
/// <summary>
/// Create a database cursor with the given configuration.
/// </summary>
/// <param name="cfg">
/// The configuration properties for the cursor.
/// </param>
/// <returns>A newly created cursor</returns>
public new HashCursor Cursor(CursorConfig cfg) {
return Cursor(cfg, null);
}
/// <summary>
/// Create a transactionally protected database cursor.
/// </summary>
/// <param name="txn">
/// The transaction context in which the cursor may be used.
/// </param>
/// <returns>A newly created cursor</returns>
public new HashCursor Cursor(Transaction txn) {
return Cursor(new CursorConfig(), txn);
}
/// <summary>
/// Create a transactionally protected database cursor with the given
/// configuration.
/// </summary>
/// <param name="cfg">
/// The configuration properties for the cursor.
/// </param>
/// <param name="txn">
/// The transaction context in which the cursor may be used.
/// </param>
/// <returns>A newly created cursor</returns>
public new HashCursor Cursor(CursorConfig cfg, Transaction txn) {
return new HashCursor(
db.cursor(Transaction.getDB_TXN(txn), cfg.flags), Pagesize);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public HashStats FastStats() {
return Stats(null, true, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public HashStats FastStats(Transaction txn) {
return Stats(txn, true, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <overloads>
/// <para>
/// Among other things, this method makes it possible for applications
/// to request key and record counts without incurring the performance
/// penalty of traversing the entire database.
/// </para>
/// <para>
/// The statistical information is described by the
/// <see cref="BTreeStats"/>, <see cref="HashStats"/>,
/// <see cref="QueueStats"/>, and <see cref="RecnoStats"/> classes.
/// </para>
/// </overloads>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="isoDegree">
/// The level of isolation for database reads.
/// <see cref="Isolation.DEGREE_ONE"/> will be silently ignored for
/// databases which did not specify
/// <see cref="DatabaseConfig.ReadUncommitted"/>.
/// </param>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public HashStats FastStats(Transaction txn, Isolation isoDegree) {
return Stats(txn, true, isoDegree);
}
/// <summary>
/// Return pages to the filesystem that are already free and at the end
/// of the file.
/// </summary>
/// <returns>
/// The number of database pages returned to the filesystem
/// </returns>
public uint TruncateUnusedPages() {
return TruncateUnusedPages(null);
}
/// <summary>
/// Return pages to the filesystem that are already free and at the end
/// of the file.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>
/// The number of database pages returned to the filesystem
/// </returns>
public uint TruncateUnusedPages(Transaction txn) {
DB_COMPACT cdata = new DB_COMPACT();
db.compact(Transaction.getDB_TXN(txn),
null, null, cdata, DbConstants.DB_FREELIST_ONLY, null);
return cdata.compact_pages_truncated;
}
/// <summary>
/// Store the key/data pair in the database only if it does not already
/// appear in the database.
/// </summary>
/// <param name="key">The key to store in the database</param>
/// <param name="data">The data item to store in the database</param>
public void PutNoDuplicate(DatabaseEntry key, DatabaseEntry data) {
PutNoDuplicate(key, data, null);
}
/// <summary>
/// Store the key/data pair in the database only if it does not already
/// appear in the database.
/// </summary>
/// <param name="key">The key to store in the database</param>
/// <param name="data">The data item to store in the database</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
public void PutNoDuplicate(
DatabaseEntry key, DatabaseEntry data, Transaction txn) {
Put(key, data, txn, DbConstants.DB_NODUPDATA);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <returns>Database statistical information.</returns>
public HashStats Stats() {
return Stats(null, false, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>Database statistical information.</returns>
public HashStats Stats(Transaction txn) {
return Stats(txn, false, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <overloads>
/// The statistical information is described by
/// <see cref="BTreeStats"/>.
/// </overloads>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="isoDegree">
/// The level of isolation for database reads.
/// <see cref="Isolation.DEGREE_ONE"/> will be silently ignored for
/// databases which did not specify
/// <see cref="DatabaseConfig.ReadUncommitted"/>.
/// </param>
/// <returns>Database statistical information.</returns>
public HashStats Stats(Transaction txn, Isolation isoDegree) {
return Stats(txn, false, isoDegree);
}
private HashStats Stats(
Transaction txn, bool fast, Isolation isoDegree) {
uint flags = 0;
flags |= fast ? DbConstants.DB_FAST_STAT : 0;
switch (isoDegree) {
case Isolation.DEGREE_ONE:
flags |= DbConstants.DB_READ_UNCOMMITTED;
break;
case Isolation.DEGREE_TWO:
flags |= DbConstants.DB_READ_COMMITTED;
break;
}
HashStatStruct st = db.stat_hash(Transaction.getDB_TXN(txn), flags);
return new HashStats(st);
}
#endregion Methods
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Specialized;
using System.Linq;
using Moq;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Layout;
using Avalonia.LogicalTree;
using Avalonia.Platform;
using Avalonia.Styling;
using Avalonia.UnitTests;
using Avalonia.VisualTree;
using Xunit;
using Avalonia.Input;
namespace Avalonia.Controls.UnitTests.Primitives
{
public class PopupTests
{
[Fact]
public void Setting_Child_Should_Set_Child_Controls_LogicalParent()
{
var target = new Popup();
var child = new Control();
target.Child = child;
Assert.Equal(child.Parent, target);
Assert.Equal(((ILogical)child).LogicalParent, target);
}
[Fact]
public void Clearing_Child_Should_Clear_Child_Controls_Parent()
{
var target = new Popup();
var child = new Control();
target.Child = child;
target.Child = null;
Assert.Null(child.Parent);
Assert.Null(((ILogical)child).LogicalParent);
}
[Fact]
public void Child_Control_Should_Appear_In_LogicalChildren()
{
var target = new Popup();
var child = new Control();
target.Child = child;
Assert.Equal(new[] { child }, target.GetLogicalChildren());
}
[Fact]
public void Clearing_Child_Should_Remove_From_LogicalChildren()
{
var target = new Popup();
var child = new Control();
target.Child = child;
target.Child = null;
Assert.Equal(new ILogical[0], ((ILogical)target).LogicalChildren.ToList());
}
[Fact]
public void Setting_Child_Should_Fire_LogicalChildren_CollectionChanged()
{
var target = new Popup();
var child = new Control();
var called = false;
((ILogical)target).LogicalChildren.CollectionChanged += (s, e) =>
called = e.Action == NotifyCollectionChangedAction.Add;
target.Child = child;
Assert.True(called);
}
[Fact]
public void Clearing_Child_Should_Fire_LogicalChildren_CollectionChanged()
{
var target = new Popup();
var child = new Control();
var called = false;
target.Child = child;
((ILogical)target).LogicalChildren.CollectionChanged += (s, e) =>
called = e.Action == NotifyCollectionChangedAction.Remove;
target.Child = null;
Assert.True(called);
}
[Fact]
public void Changing_Child_Should_Fire_LogicalChildren_CollectionChanged()
{
var target = new Popup();
var child1 = new Control();
var child2 = new Control();
var called = false;
target.Child = child1;
((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = true;
target.Child = child2;
Assert.True(called);
}
[Fact]
public void Setting_Child_Should_Not_Set_Childs_VisualParent()
{
var target = new Popup();
var child = new Control();
target.Child = child;
Assert.Null(((IVisual)child).VisualParent);
}
[Fact]
public void PopupRoot_Should_Initially_Be_Null()
{
using (CreateServices())
{
var target = new Popup();
Assert.Null(target.PopupRoot);
}
}
[Fact]
public void PopupRoot_Should_Have_Null_VisualParent()
{
using (CreateServices())
{
var target = new Popup();
target.Open();
Assert.Null(target.PopupRoot.GetVisualParent());
}
}
[Fact]
public void PopupRoot_Should_Have_Popup_As_LogicalParent()
{
using (CreateServices())
{
var target = new Popup();
target.Open();
Assert.Equal(target, target.PopupRoot.Parent);
Assert.Equal(target, target.PopupRoot.GetLogicalParent());
}
}
[Fact]
public void PopupRoot_Should_Be_Detached_From_Logical_Tree_When_Popup_Is_Detached()
{
using (CreateServices())
{
var target = new Popup();
var root = new TestRoot { Child = target };
target.Open();
var popupRoot = (ILogical)target.PopupRoot;
Assert.True(popupRoot.IsAttachedToLogicalTree);
root.Child = null;
Assert.False(((ILogical)target).IsAttachedToLogicalTree);
}
}
[Fact]
public void PopupRoot_Should_Have_Template_Applied()
{
using (CreateServices())
{
var window = new Window();
var target = new Popup();
var child = new Control();
window.Content = target;
target.Open();
Assert.Single(target.PopupRoot.GetVisualChildren());
var templatedChild = target.PopupRoot.GetVisualChildren().Single();
Assert.IsType<ContentPresenter>(templatedChild);
Assert.Equal(target.PopupRoot, ((IControl)templatedChild).TemplatedParent);
}
}
[Fact]
public void Templated_Control_With_Popup_In_Template_Should_Set_TemplatedParent()
{
using (CreateServices())
{
PopupContentControl target;
var root = new TestRoot
{
Child = target = new PopupContentControl
{
Content = new Border(),
Template = new FuncControlTemplate<PopupContentControl>(PopupContentControlTemplate),
},
StylingParent = AvaloniaLocator.Current.GetService<IGlobalStyles>()
};
target.ApplyTemplate();
var popup = (Popup)target.GetTemplateChildren().First(x => x.Name == "popup");
popup.Open();
var popupRoot = popup.PopupRoot;
var children = popupRoot.GetVisualDescendants().ToList();
var types = children.Select(x => x.GetType().Name).ToList();
Assert.Equal(
new[]
{
"ContentPresenter",
"ContentPresenter",
"Border",
},
types);
var templatedParents = children
.OfType<IControl>()
.Select(x => x.TemplatedParent).ToList();
Assert.Equal(
new object[]
{
popupRoot,
target,
null,
},
templatedParents);
}
}
[Fact]
public void DataContextBeginUpdate_Should_Not_Be_Called_For_Controls_That_Dont_Inherit()
{
using (CreateServices())
{
TestControl child;
var popup = new Popup
{
Child = child = new TestControl(),
DataContext = "foo",
};
var beginCalled = false;
child.DataContextBeginUpdate += (s, e) => beginCalled = true;
// Test for #1245. Here, the child's logical parent is the popup but it's not yet
// attached to a visual tree because the popup hasn't been opened.
Assert.Same(popup, ((ILogical)child).LogicalParent);
Assert.Same(popup, child.InheritanceParent);
Assert.Null(child.GetVisualRoot());
popup.Open();
// #1245 was caused by the fact that DataContextBeginUpdate was called on `target`
// when the PopupRoot was created, even though PopupRoot isn't the
// InheritanceParent of child.
Assert.False(beginCalled);
}
}
private static IDisposable CreateServices()
{
var result = AvaloniaLocator.EnterScope();
var styles = new Styles
{
new Style(x => x.OfType<PopupRoot>())
{
Setters = new[]
{
new Setter(TemplatedControl.TemplateProperty, new FuncControlTemplate<PopupRoot>(PopupRootTemplate)),
}
},
};
var globalStyles = new Mock<IGlobalStyles>();
globalStyles.Setup(x => x.IsStylesInitialized).Returns(true);
globalStyles.Setup(x => x.Styles).Returns(styles);
var renderInterface = new Mock<IPlatformRenderInterface>();
AvaloniaLocator.CurrentMutable
.Bind<IGlobalStyles>().ToFunc(() => globalStyles.Object)
.Bind<IWindowingPlatform>().ToConstant(new WindowingPlatformMock())
.Bind<IStyler>().ToTransient<Styler>()
.Bind<IPlatformRenderInterface>().ToFunc(() => renderInterface.Object)
.Bind<IInputManager>().ToConstant(new InputManager());
return result;
}
private static IControl PopupRootTemplate(PopupRoot control)
{
return new ContentPresenter
{
Name = "PART_ContentPresenter",
[~ContentPresenter.ContentProperty] = control[~ContentControl.ContentProperty],
};
}
private static IControl PopupContentControlTemplate(PopupContentControl control)
{
return new Popup
{
Name = "popup",
Child = new ContentPresenter
{
[~ContentPresenter.ContentProperty] = control[~ContentControl.ContentProperty],
}
};
}
private class PopupContentControl : ContentControl
{
}
private class TestControl : Decorator
{
public event EventHandler DataContextBeginUpdate;
public new IAvaloniaObject InheritanceParent => base.InheritanceParent;
protected override void OnDataContextBeginUpdate()
{
DataContextBeginUpdate?.Invoke(this, EventArgs.Empty);
base.OnDataContextBeginUpdate();
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Player.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Penumbra;
namespace Platformer2D
{
/// <summary>
/// Our fearless adventurer!
/// </summary>
class Player
{
// Animations
private Animation idleAnimation;
private Animation runAnimation;
private Animation jumpAnimation;
private Animation celebrateAnimation;
private Animation dieAnimation;
private SpriteEffects flip = SpriteEffects.None;
private AnimationPlayer sprite;
// Sounds
private SoundEffect killedSound;
private SoundEffect jumpSound;
private SoundEffect fallSound;
// Lighting
public Light Light { get; } = new PointLight
{
Scale = new Vector2(800),
Color = Color.White,
ShadowType = ShadowType.Occluded
};
public Level Level
{
get { return level; }
}
Level level;
public bool IsAlive
{
get { return isAlive; }
}
bool isAlive;
// Physics state
public Vector2 Position
{
get { return position; }
set
{
position = value;
Light.Position = new Vector2(value.X, value.Y - 30);
}
}
Vector2 position;
private float previousBottom;
public Vector2 Velocity
{
get { return velocity; }
set { velocity = value; }
}
Vector2 velocity;
// Constants for controling horizontal movement
private const float MoveAcceleration = 13000.0f;
private const float MaxMoveSpeed = 1750.0f;
private const float GroundDragFactor = 0.48f;
private const float AirDragFactor = 0.58f;
// Constants for controlling vertical movement
private const float MaxJumpTime = 0.35f;
private const float JumpLaunchVelocity = -3500.0f;
private const float GravityAcceleration = 3400.0f;
private const float MaxFallSpeed = 550.0f;
private const float JumpControlPower = 0.14f;
// Input configuration
private const float MoveStickScale = 1.0f;
private const float AccelerometerScale = 1.5f;
private const Buttons JumpButton = Buttons.A;
/// <summary>
/// Gets whether or not the player's feet are on the ground.
/// </summary>
public bool IsOnGround
{
get { return isOnGround; }
}
bool isOnGround;
/// <summary>
/// Current user movement input.
/// </summary>
private float movement;
// Jumping state
private bool isJumping;
private bool wasJumping;
private float jumpTime;
private Rectangle localBounds;
/// <summary>
/// Gets a rectangle which bounds this player in world space.
/// </summary>
public Rectangle BoundingRectangle
{
get
{
int left = (int)Math.Round(Position.X - sprite.Origin.X) + localBounds.X;
int top = (int)Math.Round(Position.Y - sprite.Origin.Y) + localBounds.Y;
return new Rectangle(left, top, localBounds.Width, localBounds.Height);
}
}
/// <summary>
/// Constructors a new player.
/// </summary>
public Player(Level level, Vector2 position)
{
this.level = level;
LoadContent();
Reset(position);
}
/// <summary>
/// Loads the player sprite sheet and sounds.
/// </summary>
public void LoadContent()
{
// Load animated textures.
idleAnimation = new Animation(Level.Content.Load<Texture2D>("Sprites/Player/Idle"), 0.1f, true);
runAnimation = new Animation(Level.Content.Load<Texture2D>("Sprites/Player/Run"), 0.1f, true);
jumpAnimation = new Animation(Level.Content.Load<Texture2D>("Sprites/Player/Jump"), 0.1f, false);
celebrateAnimation = new Animation(Level.Content.Load<Texture2D>("Sprites/Player/Celebrate"), 0.1f, false);
dieAnimation = new Animation(Level.Content.Load<Texture2D>("Sprites/Player/Die"), 0.1f, false);
// Calculate bounds within texture size.
int width = (int)(idleAnimation.FrameWidth * 0.4);
int left = (idleAnimation.FrameWidth - width) / 2;
int height = (int)(idleAnimation.FrameWidth * 0.8);
int top = idleAnimation.FrameHeight - height;
localBounds = new Rectangle(left, top, width, height);
// Load sounds.
killedSound = Level.Content.Load<SoundEffect>("Sounds/PlayerKilled");
jumpSound = Level.Content.Load<SoundEffect>("Sounds/PlayerJump");
fallSound = Level.Content.Load<SoundEffect>("Sounds/PlayerFall");
}
/// <summary>
/// Resets the player to life.
/// </summary>
/// <param name="position">The position to come to life at.</param>
public void Reset(Vector2 position)
{
Position = position;
Velocity = Vector2.Zero;
isAlive = true;
sprite.PlayAnimation(idleAnimation);
}
/// <summary>
/// Handles input, performs physics, and animates the player sprite.
/// </summary>
/// <remarks>
/// We pass in all of the input states so that our game is only polling the hardware
/// once per frame. We also pass the game's orientation because when using the accelerometer,
/// we need to reverse our motion when the orientation is in the LandscapeRight orientation.
/// </remarks>
public void Update(
GameTime gameTime,
KeyboardState keyboardState,
GamePadState gamePadState,
AccelerometerState accelState,
DisplayOrientation orientation)
{
GetInput(keyboardState, gamePadState, accelState, orientation);
ApplyPhysics(gameTime);
if (IsAlive && IsOnGround)
{
if (Math.Abs(Velocity.X) - 0.02f > 0)
{
sprite.PlayAnimation(runAnimation);
}
else
{
sprite.PlayAnimation(idleAnimation);
}
}
// Clear input.
movement = 0.0f;
isJumping = false;
}
/// <summary>
/// Gets player horizontal movement and jump commands from input.
/// </summary>
private void GetInput(
KeyboardState keyboardState,
GamePadState gamePadState,
AccelerometerState accelState,
DisplayOrientation orientation)
{
// Get analog horizontal movement.
movement = gamePadState.ThumbSticks.Left.X * MoveStickScale;
// Ignore small movements to prevent running in place.
if (Math.Abs(movement) < 0.5f)
movement = 0.0f;
// Move the player with accelerometer
if (Math.Abs(accelState.Acceleration.Y) > 0.10f)
{
// set our movement speed
movement = MathHelper.Clamp(-accelState.Acceleration.Y * AccelerometerScale, -1f, 1f);
// if we're in the LandscapeLeft orientation, we must reverse our movement
if (orientation == DisplayOrientation.LandscapeRight)
movement = -movement;
}
// If any digital horizontal movement input is found, override the analog movement.
if (gamePadState.IsButtonDown(Buttons.DPadLeft) ||
keyboardState.IsKeyDown(Keys.Left) ||
keyboardState.IsKeyDown(Keys.A))
{
movement = -1.0f;
}
else if (gamePadState.IsButtonDown(Buttons.DPadRight) ||
keyboardState.IsKeyDown(Keys.Right) ||
keyboardState.IsKeyDown(Keys.D))
{
movement = 1.0f;
}
// Check if the player wants to jump.
isJumping =
gamePadState.IsButtonDown(JumpButton) ||
keyboardState.IsKeyDown(Keys.Space) ||
keyboardState.IsKeyDown(Keys.Up) ||
keyboardState.IsKeyDown(Keys.W);
}
/// <summary>
/// Updates the player's velocity and position based on input, gravity, etc.
/// </summary>
public void ApplyPhysics(GameTime gameTime)
{
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
Vector2 previousPosition = Position;
// Base velocity is a combination of horizontal movement control and
// acceleration downward due to gravity.
velocity.X += movement * MoveAcceleration * elapsed;
velocity.Y = MathHelper.Clamp(velocity.Y + GravityAcceleration * elapsed, -MaxFallSpeed, MaxFallSpeed);
velocity.Y = DoJump(velocity.Y, gameTime);
// Apply pseudo-drag horizontally.
if (IsOnGround)
velocity.X *= GroundDragFactor;
else
velocity.X *= AirDragFactor;
// Prevent the player from running faster than his top speed.
velocity.X = MathHelper.Clamp(velocity.X, -MaxMoveSpeed, MaxMoveSpeed);
// Apply velocity.
Position += velocity * elapsed;
Position = new Vector2((float)Math.Round(Position.X), (float)Math.Round(Position.Y));
// If the player is now colliding with the level, separate them.
HandleCollisions();
// If the collision stopped us from moving, reset the velocity to zero.
if (Position.X == previousPosition.X)
velocity.X = 0;
if (Position.Y == previousPosition.Y)
velocity.Y = 0;
}
/// <summary>
/// Calculates the Y velocity accounting for jumping and
/// animates accordingly.
/// </summary>
/// <remarks>
/// During the accent of a jump, the Y velocity is completely
/// overridden by a power curve. During the decent, gravity takes
/// over. The jump velocity is controlled by the jumpTime field
/// which measures time into the accent of the current jump.
/// </remarks>
/// <param name="velocityY">
/// The player's current velocity along the Y axis.
/// </param>
/// <returns>
/// A new Y velocity if beginning or continuing a jump.
/// Otherwise, the existing Y velocity.
/// </returns>
private float DoJump(float velocityY, GameTime gameTime)
{
// If the player wants to jump
if (isJumping)
{
// Begin or continue a jump
if ((!wasJumping && IsOnGround) || jumpTime > 0.0f)
{
if (jumpTime == 0.0f)
jumpSound.Play();
jumpTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
sprite.PlayAnimation(jumpAnimation);
}
// If we are in the ascent of the jump
if (0.0f < jumpTime && jumpTime <= MaxJumpTime)
{
// Fully override the vertical velocity with a power curve that gives players more control over the top of the jump
velocityY = JumpLaunchVelocity * (1.0f - (float)Math.Pow(jumpTime / MaxJumpTime, JumpControlPower));
}
else
{
// Reached the apex of the jump
jumpTime = 0.0f;
}
}
else
{
// Continues not jumping or cancels a jump in progress
jumpTime = 0.0f;
}
wasJumping = isJumping;
return velocityY;
}
/// <summary>
/// Detects and resolves all collisions between the player and his neighboring
/// tiles. When a collision is detected, the player is pushed away along one
/// axis to prevent overlapping. There is some special logic for the Y axis to
/// handle platforms which behave differently depending on direction of movement.
/// </summary>
private void HandleCollisions()
{
// Get the player's bounding rectangle and find neighboring tiles.
Rectangle bounds = BoundingRectangle;
int leftTile = (int)Math.Floor((float)bounds.Left / Tile.Width);
int rightTile = (int)Math.Ceiling(((float)bounds.Right / Tile.Width)) - 1;
int topTile = (int)Math.Floor((float)bounds.Top / Tile.Height);
int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / Tile.Height)) - 1;
// Reset flag to search for ground collision.
isOnGround = false;
// For each potentially colliding tile,
for (int y = topTile; y <= bottomTile; ++y)
{
for (int x = leftTile; x <= rightTile; ++x)
{
// If this tile is collidable,
TileCollision collision = Level.GetCollision(x, y);
if (collision != TileCollision.Passable)
{
// Determine collision depth (with direction) and magnitude.
Rectangle tileBounds = Level.GetBounds(x, y);
Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);
if (depth != Vector2.Zero)
{
float absDepthX = Math.Abs(depth.X);
float absDepthY = Math.Abs(depth.Y);
// Resolve the collision along the shallow axis.
if (absDepthY < absDepthX || collision == TileCollision.Platform)
{
// If we crossed the top of a tile, we are on the ground.
if (previousBottom <= tileBounds.Top)
isOnGround = true;
// Ignore platforms, unless we are on the ground.
if (collision == TileCollision.Impassable || IsOnGround)
{
// Resolve the collision along the Y axis.
Position = new Vector2(Position.X, Position.Y + depth.Y);
// Perform further collisions with the new bounds.
bounds = BoundingRectangle;
}
}
else if (collision == TileCollision.Impassable) // Ignore platforms.
{
// Resolve the collision along the X axis.
Position = new Vector2(Position.X + depth.X, Position.Y);
// Perform further collisions with the new bounds.
bounds = BoundingRectangle;
}
}
}
}
}
// Save the new bounds bottom.
previousBottom = bounds.Bottom;
}
/// <summary>
/// Called when the player has been killed.
/// </summary>
/// <param name="killedBy">
/// The enemy who killed the player. This parameter is null if the player was
/// not killed by an enemy (fell into a hole).
/// </param>
public void OnKilled(Enemy killedBy)
{
isAlive = false;
if (killedBy != null)
killedSound.Play();
else
fallSound.Play();
sprite.PlayAnimation(dieAnimation);
}
/// <summary>
/// Called when this player reaches the level's exit.
/// </summary>
public void OnReachedExit()
{
sprite.PlayAnimation(celebrateAnimation);
}
/// <summary>
/// Draws the animated player.
/// </summary>
public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
// Flip the sprite to face the way we are moving.
if (Velocity.X > 0)
flip = SpriteEffects.FlipHorizontally;
else if (Velocity.X < 0)
flip = SpriteEffects.None;
// Draw that sprite.
sprite.Draw(gameTime, spriteBatch, Position, flip);
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfileDiameterSessionBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStringArray))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileULong))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileDiameterSessionDiameterSessionProfileStatistics))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileEnabledState))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileIPAddress))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileDiameterSessionProfilePersistType))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStatisticsByVirtual))]
public partial class LocalLBProfileDiameterSession : iControlInterface {
public LocalLBProfileDiameterSession() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_array_acct_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void add_array_acct_application_id(
string [] profile_names,
LocalLBProfileStringArray [] values
) {
this.Invoke("add_array_acct_application_id", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginadd_array_acct_application_id(string [] profile_names,LocalLBProfileStringArray [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_array_acct_application_id", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endadd_array_acct_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_array_auth_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void add_array_auth_application_id(
string [] profile_names,
LocalLBProfileStringArray [] values
) {
this.Invoke("add_array_auth_application_id", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginadd_array_auth_application_id(string [] profile_names,LocalLBProfileStringArray [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_array_auth_application_id", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endadd_array_auth_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void create(
string [] profile_names
) {
this.Invoke("create", new object [] {
profile_names});
}
public System.IAsyncResult Begincreate(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
profile_names}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_profiles
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void delete_all_profiles(
) {
this.Invoke("delete_all_profiles", new object [0]);
}
public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState);
}
public void Enddelete_all_profiles(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void delete_profile(
string [] profile_names
) {
this.Invoke("delete_profile", new object [] {
profile_names});
}
public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_profile", new object[] {
profile_names}, callback, asyncState);
}
public void Enddelete_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_acct_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_acct_application_id(
string [] profile_names
) {
object [] results = this.Invoke("get_acct_application_id", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_acct_application_id(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_acct_application_id", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_acct_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileDiameterSessionDiameterSessionProfileStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((LocalLBProfileDiameterSessionDiameterSessionProfileStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public LocalLBProfileDiameterSessionDiameterSessionProfileStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileDiameterSessionDiameterSessionProfileStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_array_acct_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileStringArray [] get_array_acct_application_id(
string [] profile_names
) {
object [] results = this.Invoke("get_array_acct_application_id", new object [] {
profile_names});
return ((LocalLBProfileStringArray [])(results[0]));
}
public System.IAsyncResult Beginget_array_acct_application_id(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_array_acct_application_id", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileStringArray [] Endget_array_acct_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileStringArray [])(results[0]));
}
//-----------------------------------------------------------------------
// get_array_auth_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileStringArray [] get_array_auth_application_id(
string [] profile_names
) {
object [] results = this.Invoke("get_array_auth_application_id", new object [] {
profile_names});
return ((LocalLBProfileStringArray [])(results[0]));
}
public System.IAsyncResult Beginget_array_auth_application_id(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_array_auth_application_id", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileStringArray [] Endget_array_auth_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileStringArray [])(results[0]));
}
//-----------------------------------------------------------------------
// get_auth_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_auth_application_id(
string [] profile_names
) {
object [] results = this.Invoke("get_auth_application_id", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_auth_application_id(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_auth_application_id", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_auth_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_default_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_default_profile(
string [] profile_names
) {
object [] results = this.Invoke("get_default_profile", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_default_profile", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_default_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] profile_names
) {
object [] results = this.Invoke("get_description", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_destination_host_rewrite
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_destination_host_rewrite(
string [] profile_names
) {
object [] results = this.Invoke("get_destination_host_rewrite", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_destination_host_rewrite(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_destination_host_rewrite", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_destination_host_rewrite(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_destination_realm_rewrite
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_destination_realm_rewrite(
string [] profile_names
) {
object [] results = this.Invoke("get_destination_realm_rewrite", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_destination_realm_rewrite(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_destination_realm_rewrite", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_destination_realm_rewrite(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_discard_unroutable_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_discard_unroutable_state(
string [] profile_names
) {
object [] results = this.Invoke("get_discard_unroutable_state", new object [] {
profile_names});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_discard_unroutable_state(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_discard_unroutable_state", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_discard_unroutable_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_handshake_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_handshake_timeout(
string [] profile_names
) {
object [] results = this.Invoke("get_handshake_timeout", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_handshake_timeout(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_handshake_timeout", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_handshake_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_host_ip_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileIPAddress [] get_host_ip_address(
string [] profile_names
) {
object [] results = this.Invoke("get_host_ip_address", new object [] {
profile_names});
return ((LocalLBProfileIPAddress [])(results[0]));
}
public System.IAsyncResult Beginget_host_ip_address(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_host_ip_address", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileIPAddress [] Endget_host_ip_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileIPAddress [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_maximum_message_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_maximum_message_size(
string [] profile_names
) {
object [] results = this.Invoke("get_maximum_message_size", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_maximum_message_size(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_maximum_message_size", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_maximum_message_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_maximum_watchdog_failures
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_maximum_watchdog_failures(
string [] profile_names
) {
object [] results = this.Invoke("get_maximum_watchdog_failures", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_maximum_watchdog_failures(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_maximum_watchdog_failures", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_maximum_watchdog_failures(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_origin_host
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_origin_host(
string [] profile_names
) {
object [] results = this.Invoke("get_origin_host", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_origin_host(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_origin_host", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_origin_host(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_origin_host_rewrite
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_origin_host_rewrite(
string [] profile_names
) {
object [] results = this.Invoke("get_origin_host_rewrite", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_origin_host_rewrite(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_origin_host_rewrite", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_origin_host_rewrite(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_origin_realm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_origin_realm(
string [] profile_names
) {
object [] results = this.Invoke("get_origin_realm", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_origin_realm(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_origin_realm", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_origin_realm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_origin_realm_rewrite
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_origin_realm_rewrite(
string [] profile_names
) {
object [] results = this.Invoke("get_origin_realm_rewrite", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_origin_realm_rewrite(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_origin_realm_rewrite", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_origin_realm_rewrite(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_persist_avp
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_persist_avp(
string [] profile_names
) {
object [] results = this.Invoke("get_persist_avp", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_persist_avp(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_persist_avp", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_persist_avp(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_persist_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_persist_timeout(
string [] profile_names
) {
object [] results = this.Invoke("get_persist_timeout", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_persist_timeout(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_persist_timeout", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_persist_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_persist_type
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileDiameterSessionProfilePersistType [] get_persist_type(
string [] profile_names
) {
object [] results = this.Invoke("get_persist_type", new object [] {
profile_names});
return ((LocalLBProfileDiameterSessionProfilePersistType [])(results[0]));
}
public System.IAsyncResult Beginget_persist_type(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_persist_type", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileDiameterSessionProfilePersistType [] Endget_persist_type(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileDiameterSessionProfilePersistType [])(results[0]));
}
//-----------------------------------------------------------------------
// get_product_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_product_name(
string [] profile_names
) {
object [] results = this.Invoke("get_product_name", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_product_name(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_product_name", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_product_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_reset_on_timeout_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_reset_on_timeout_state(
string [] profile_names
) {
object [] results = this.Invoke("get_reset_on_timeout_state", new object [] {
profile_names});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_reset_on_timeout_state(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_reset_on_timeout_state", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_reset_on_timeout_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_route_unconfigured_peers_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_route_unconfigured_peers_state(
string [] profile_names
) {
object [] results = this.Invoke("get_route_unconfigured_peers_state", new object [] {
profile_names});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_route_unconfigured_peers_state(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_route_unconfigured_peers_state", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_route_unconfigured_peers_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileDiameterSessionDiameterSessionProfileStatistics get_statistics(
string [] profile_names
) {
object [] results = this.Invoke("get_statistics", new object [] {
profile_names});
return ((LocalLBProfileDiameterSessionDiameterSessionProfileStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileDiameterSessionDiameterSessionProfileStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileDiameterSessionDiameterSessionProfileStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics_by_virtual
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileStatisticsByVirtual get_statistics_by_virtual(
string [] profile_names,
string [] [] virtual_names
) {
object [] results = this.Invoke("get_statistics_by_virtual", new object [] {
profile_names,
virtual_names});
return ((LocalLBProfileStatisticsByVirtual)(results[0]));
}
public System.IAsyncResult Beginget_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics_by_virtual", new object[] {
profile_names,
virtual_names}, callback, asyncState);
}
public LocalLBProfileStatisticsByVirtual Endget_statistics_by_virtual(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileStatisticsByVirtual)(results[0]));
}
//-----------------------------------------------------------------------
// get_vendor_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_vendor_id(
string [] profile_names
) {
object [] results = this.Invoke("get_vendor_id", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_vendor_id(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_vendor_id", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_vendor_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_vendor_specific_acct_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_vendor_specific_acct_application_id(
string [] profile_names
) {
object [] results = this.Invoke("get_vendor_specific_acct_application_id", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_vendor_specific_acct_application_id(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_vendor_specific_acct_application_id", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_vendor_specific_acct_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_vendor_specific_auth_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_vendor_specific_auth_application_id(
string [] profile_names
) {
object [] results = this.Invoke("get_vendor_specific_auth_application_id", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_vendor_specific_auth_application_id(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_vendor_specific_auth_application_id", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_vendor_specific_auth_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_vendor_specific_vendor_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_vendor_specific_vendor_id(
string [] profile_names
) {
object [] results = this.Invoke("get_vendor_specific_vendor_id", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_vendor_specific_vendor_id(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_vendor_specific_vendor_id", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_vendor_specific_vendor_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_watchdog_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_watchdog_timeout(
string [] profile_names
) {
object [] results = this.Invoke("get_watchdog_timeout", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_watchdog_timeout(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_watchdog_timeout", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_watchdog_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// is_base_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_base_profile(
string [] profile_names
) {
object [] results = this.Invoke("is_base_profile", new object [] {
profile_names});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_base_profile", new object[] {
profile_names}, callback, asyncState);
}
public bool [] Endis_base_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// is_system_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_system_profile(
string [] profile_names
) {
object [] results = this.Invoke("is_system_profile", new object [] {
profile_names});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_system_profile", new object[] {
profile_names}, callback, asyncState);
}
public bool [] Endis_system_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_array_acct_application_ids
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void remove_all_array_acct_application_ids(
string [] profile_names
) {
this.Invoke("remove_all_array_acct_application_ids", new object [] {
profile_names});
}
public System.IAsyncResult Beginremove_all_array_acct_application_ids(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_array_acct_application_ids", new object[] {
profile_names}, callback, asyncState);
}
public void Endremove_all_array_acct_application_ids(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_array_auth_application_ids
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void remove_all_array_auth_application_ids(
string [] profile_names
) {
this.Invoke("remove_all_array_auth_application_ids", new object [] {
profile_names});
}
public System.IAsyncResult Beginremove_all_array_auth_application_ids(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_array_auth_application_ids", new object[] {
profile_names}, callback, asyncState);
}
public void Endremove_all_array_auth_application_ids(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_array_acct_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void remove_array_acct_application_id(
string [] profile_names,
LocalLBProfileStringArray [] values
) {
this.Invoke("remove_array_acct_application_id", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginremove_array_acct_application_id(string [] profile_names,LocalLBProfileStringArray [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_array_acct_application_id", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endremove_array_acct_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_array_auth_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void remove_array_auth_application_id(
string [] profile_names,
LocalLBProfileStringArray [] values
) {
this.Invoke("remove_array_auth_application_id", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginremove_array_auth_application_id(string [] profile_names,LocalLBProfileStringArray [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_array_auth_application_id", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endremove_array_auth_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void reset_statistics(
string [] profile_names
) {
this.Invoke("reset_statistics", new object [] {
profile_names});
}
public System.IAsyncResult Beginreset_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
profile_names}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// reset_statistics_by_virtual
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void reset_statistics_by_virtual(
string [] profile_names,
string [] [] virtual_names
) {
this.Invoke("reset_statistics_by_virtual", new object [] {
profile_names,
virtual_names});
}
public System.IAsyncResult Beginreset_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics_by_virtual", new object[] {
profile_names,
virtual_names}, callback, asyncState);
}
public void Endreset_statistics_by_virtual(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_acct_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_acct_application_id(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_acct_application_id", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_acct_application_id(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_acct_application_id", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_acct_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_auth_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_auth_application_id(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_auth_application_id", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_auth_application_id(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_auth_application_id", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_auth_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_default_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_default_profile(
string [] profile_names,
string [] defaults
) {
this.Invoke("set_default_profile", new object [] {
profile_names,
defaults});
}
public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_default_profile", new object[] {
profile_names,
defaults}, callback, asyncState);
}
public void Endset_default_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_description(
string [] profile_names,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
profile_names,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
profile_names,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_destination_host_rewrite
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_destination_host_rewrite(
string [] profile_names,
LocalLBProfileString [] values
) {
this.Invoke("set_destination_host_rewrite", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_destination_host_rewrite(string [] profile_names,LocalLBProfileString [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_destination_host_rewrite", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_destination_host_rewrite(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_destination_realm_rewrite
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_destination_realm_rewrite(
string [] profile_names,
LocalLBProfileString [] values
) {
this.Invoke("set_destination_realm_rewrite", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_destination_realm_rewrite(string [] profile_names,LocalLBProfileString [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_destination_realm_rewrite", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_destination_realm_rewrite(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_discard_unroutable_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_discard_unroutable_state(
string [] profile_names,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_discard_unroutable_state", new object [] {
profile_names,
states});
}
public System.IAsyncResult Beginset_discard_unroutable_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_discard_unroutable_state", new object[] {
profile_names,
states}, callback, asyncState);
}
public void Endset_discard_unroutable_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_handshake_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_handshake_timeout(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_handshake_timeout", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_handshake_timeout(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_handshake_timeout", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_handshake_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_host_ip_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_host_ip_address(
string [] profile_names,
LocalLBProfileIPAddress [] values
) {
this.Invoke("set_host_ip_address", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_host_ip_address(string [] profile_names,LocalLBProfileIPAddress [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_host_ip_address", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_host_ip_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_maximum_message_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_maximum_message_size(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_maximum_message_size", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_maximum_message_size(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_maximum_message_size", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_maximum_message_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_maximum_watchdog_failures
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_maximum_watchdog_failures(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_maximum_watchdog_failures", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_maximum_watchdog_failures(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_maximum_watchdog_failures", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_maximum_watchdog_failures(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_origin_host
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_origin_host(
string [] profile_names,
LocalLBProfileString [] values
) {
this.Invoke("set_origin_host", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_origin_host(string [] profile_names,LocalLBProfileString [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_origin_host", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_origin_host(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_origin_host_rewrite
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_origin_host_rewrite(
string [] profile_names,
LocalLBProfileString [] values
) {
this.Invoke("set_origin_host_rewrite", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_origin_host_rewrite(string [] profile_names,LocalLBProfileString [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_origin_host_rewrite", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_origin_host_rewrite(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_origin_realm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_origin_realm(
string [] profile_names,
LocalLBProfileString [] values
) {
this.Invoke("set_origin_realm", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_origin_realm(string [] profile_names,LocalLBProfileString [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_origin_realm", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_origin_realm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_origin_realm_rewrite
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_origin_realm_rewrite(
string [] profile_names,
LocalLBProfileString [] values
) {
this.Invoke("set_origin_realm_rewrite", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_origin_realm_rewrite(string [] profile_names,LocalLBProfileString [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_origin_realm_rewrite", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_origin_realm_rewrite(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_persist_avp
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_persist_avp(
string [] profile_names,
LocalLBProfileString [] values
) {
this.Invoke("set_persist_avp", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_persist_avp(string [] profile_names,LocalLBProfileString [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_persist_avp", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_persist_avp(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_persist_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_persist_timeout(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_persist_timeout", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_persist_timeout(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_persist_timeout", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_persist_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_persist_type
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_persist_type(
string [] profile_names,
LocalLBProfileDiameterSessionProfilePersistType [] values
) {
this.Invoke("set_persist_type", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_persist_type(string [] profile_names,LocalLBProfileDiameterSessionProfilePersistType [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_persist_type", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_persist_type(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_product_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_product_name(
string [] profile_names,
LocalLBProfileString [] values
) {
this.Invoke("set_product_name", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_product_name(string [] profile_names,LocalLBProfileString [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_product_name", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_product_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_reset_on_timeout_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_reset_on_timeout_state(
string [] profile_names,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_reset_on_timeout_state", new object [] {
profile_names,
states});
}
public System.IAsyncResult Beginset_reset_on_timeout_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_reset_on_timeout_state", new object[] {
profile_names,
states}, callback, asyncState);
}
public void Endset_reset_on_timeout_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_route_unconfigured_peers_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_route_unconfigured_peers_state(
string [] profile_names,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_route_unconfigured_peers_state", new object [] {
profile_names,
states});
}
public System.IAsyncResult Beginset_route_unconfigured_peers_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_route_unconfigured_peers_state", new object[] {
profile_names,
states}, callback, asyncState);
}
public void Endset_route_unconfigured_peers_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_vendor_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_vendor_id(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_vendor_id", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_vendor_id(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_vendor_id", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_vendor_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_vendor_specific_acct_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_vendor_specific_acct_application_id(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_vendor_specific_acct_application_id", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_vendor_specific_acct_application_id(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_vendor_specific_acct_application_id", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_vendor_specific_acct_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_vendor_specific_auth_application_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_vendor_specific_auth_application_id(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_vendor_specific_auth_application_id", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_vendor_specific_auth_application_id(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_vendor_specific_auth_application_id", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_vendor_specific_auth_application_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_vendor_specific_vendor_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_vendor_specific_vendor_id(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_vendor_specific_vendor_id", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_vendor_specific_vendor_id(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_vendor_specific_vendor_id", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_vendor_specific_vendor_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_watchdog_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterSession",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterSession", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterSession")]
public void set_watchdog_timeout(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_watchdog_timeout", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_watchdog_timeout(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_watchdog_timeout", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_watchdog_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDiameterSession.PersistKey", Namespace = "urn:iControl")]
public enum LocalLBProfileDiameterSessionPersistKey
{
DIAMETERSESSION_PERSIST_KEY_UNKNOWN,
DIAMETERSESSION_PERSIST_KEY_CALL_ID,
DIAMETERSESSION_PERSIST_KEY_SOURCE_ADDRESS,
DIAMETERSESSION_PERSIST_KEY_CUSTOM,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDiameterSession.PersistType", Namespace = "urn:iControl")]
public enum LocalLBProfileDiameterSessionPersistType
{
DIAMETERSESSION_PERSIST_TYPE_UNKNOWN,
DIAMETERSESSION_PERSIST_TYPE_NONE,
DIAMETERSESSION_PERSIST_TYPE_SESSION,
}
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDiameterSession.DiameterSessionProfileStatisticEntry", Namespace = "urn:iControl")]
public partial class LocalLBProfileDiameterSessionDiameterSessionProfileStatisticEntry
{
private string profile_nameField;
public string profile_name
{
get { return this.profile_nameField; }
set { this.profile_nameField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDiameterSession.DiameterSessionProfileStatistics", Namespace = "urn:iControl")]
public partial class LocalLBProfileDiameterSessionDiameterSessionProfileStatistics
{
private LocalLBProfileDiameterSessionDiameterSessionProfileStatisticEntry [] statisticsField;
public LocalLBProfileDiameterSessionDiameterSessionProfileStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDiameterSession.ProfilePersistType", Namespace = "urn:iControl")]
public partial class LocalLBProfileDiameterSessionProfilePersistType
{
private LocalLBProfileDiameterSessionPersistType valueField;
public LocalLBProfileDiameterSessionPersistType value
{
get { return this.valueField; }
set { this.valueField = value; }
}
private bool default_flagField;
public bool default_flag
{
get { return this.default_flagField; }
set { this.default_flagField = value; }
}
};
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Security;
using System.Xml;
#if !MONO
namespace NLog.UnitTests.Config
{
using NLog.Config;
using System;
using System.IO;
using System.Threading;
using Xunit;
public class ReloadTests : NLogTestBase
{
[Fact]
public void TestNoAutoReload()
{
string config1 = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string config2 = @"<nlog>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string configFilePath = Path.Combine(tempPath, "noreload.nlog");
WriteConfigFile(configFilePath, config1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(configFilePath);
Assert.False(((XmlLoggingConfiguration)LogManager.Configuration).AutoReload);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(configFilePath, config2, assertDidReload: false);
logger.Debug("bbb");
// Assert that config1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestAutoReloadOnFileChange()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] ReloadTests.TestAutoReloadOnFileChange because we are running in Travis");
return;
}
#endif
string config1 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string config2 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string badConfig = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='(${message})' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string configFilePath = Path.Combine(tempPath, "reload.nlog");
WriteConfigFile(configFilePath, config1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(configFilePath);
Assert.True(((XmlLoggingConfiguration)LogManager.Configuration).AutoReload);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(configFilePath, badConfig, assertDidReload: false);
logger.Debug("bbb");
// Assert that config1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
ChangeAndReloadConfigFile(configFilePath, config2);
logger.Debug("ccc");
// Assert that config2 is loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestAutoReloadOnFileMove()
{
string config1 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string config2 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string configFilePath = Path.Combine(tempPath, "reload.nlog");
WriteConfigFile(configFilePath, config1);
string otherFilePath = Path.Combine(tempPath, "other.nlog");
try
{
LogManager.Configuration = new XmlLoggingConfiguration(configFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
File.Move(configFilePath, otherFilePath);
reloadWaiter.WaitForReload();
}
logger.Debug("bbb");
// Assert that config1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
WriteConfigFile(otherFilePath, config2);
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
File.Move(otherFilePath, configFilePath);
reloadWaiter.WaitForReload();
Assert.True(reloadWaiter.DidReload);
}
logger.Debug("ccc");
// Assert that config2 is loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestAutoReloadOnFileCopy()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] ReloadTests.TestAutoReloadOnFileCopy because we are running in Travis");
return;
}
#endif
string config1 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string config2 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string configFilePath = Path.Combine(tempPath, "reload.nlog");
WriteConfigFile(configFilePath, config1);
string otherFilePath = Path.Combine(tempPath, "other.nlog");
try
{
LogManager.Configuration = new XmlLoggingConfiguration(configFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
File.Delete(configFilePath);
reloadWaiter.WaitForReload();
}
logger.Debug("bbb");
// Assert that config1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
WriteConfigFile(otherFilePath, config2);
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
File.Copy(otherFilePath, configFilePath);
File.Delete(otherFilePath);
reloadWaiter.WaitForReload();
Assert.True(reloadWaiter.DidReload);
}
logger.Debug("ccc");
// Assert that config2 is loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestIncludedConfigNoReload()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] ReloadTests.TestIncludedConfigNoReload because we are running in Travis");
return;
}
#endif
string mainConfig1 = @"<nlog>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string mainConfig2 = @"<nlog>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Info' writeTo='debug' /></rules>
</nlog>";
string includedConfig1 = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>";
string includedConfig2 = @"<nlog>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string mainConfigFilePath = Path.Combine(tempPath, "main.nlog");
WriteConfigFile(mainConfigFilePath, mainConfig1);
string includedConfigFilePath = Path.Combine(tempPath, "included.nlog");
WriteConfigFile(includedConfigFilePath, includedConfig1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2, assertDidReload: false);
logger.Debug("bbb");
// Assert that mainConfig1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
WriteConfigFile(mainConfigFilePath, mainConfig1);
ChangeAndReloadConfigFile(includedConfigFilePath, includedConfig2, assertDidReload: false);
logger.Debug("ccc");
// Assert that includedConfig1 is still loaded.
AssertDebugLastMessage("debug", "ccc");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestIncludedConfigReload()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] ReloadTests.TestIncludedConfigNoReload because we are running in Travis");
return;
}
#endif
string mainConfig1 = @"<nlog>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string mainConfig2 = @"<nlog>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Info' writeTo='debug' /></rules>
</nlog>";
string includedConfig1 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>";
string includedConfig2 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string mainConfigFilePath = Path.Combine(tempPath, "main.nlog");
WriteConfigFile(mainConfigFilePath, mainConfig1);
string includedConfigFilePath = Path.Combine(tempPath, "included.nlog");
WriteConfigFile(includedConfigFilePath, includedConfig1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2, assertDidReload: false);
logger.Debug("bbb");
// Assert that mainConfig1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
WriteConfigFile(mainConfigFilePath, mainConfig1);
ChangeAndReloadConfigFile(includedConfigFilePath, includedConfig2);
logger.Debug("ccc");
// Assert that includedConfig2 is loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestMainConfigReload()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] ReloadTests.TestMainConfigReload because we are running in Travis");
return;
}
#endif
string mainConfig1 = @"<nlog autoReload='true'>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string mainConfig2 = @"<nlog autoReload='true'>
<include file='included2.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string included1Config = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>";
string included2Config1 = @"<nlog>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
</nlog>";
string included2Config2 = @"<nlog>
<targets><target name='debug' type='Debug' layout='(${message})' /></targets>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string mainConfigFilePath = Path.Combine(tempPath, "main.nlog");
WriteConfigFile(mainConfigFilePath, mainConfig1);
string included1ConfigFilePath = Path.Combine(tempPath, "included.nlog");
WriteConfigFile(included1ConfigFilePath, included1Config);
string included2ConfigFilePath = Path.Combine(tempPath, "included2.nlog");
WriteConfigFile(included2ConfigFilePath, included2Config1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2);
logger.Debug("bbb");
// Assert that mainConfig2 is loaded (which refers to included2.nlog).
AssertDebugLastMessage("debug", "[bbb]");
ChangeAndReloadConfigFile(included2ConfigFilePath, included2Config2);
logger.Debug("ccc");
// Assert that included2Config2 is loaded.
AssertDebugLastMessage("debug", "(ccc)");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestMainConfigReloadIncludedConfigNoReload()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] ReloadTests.TestMainConfigReload because we are running in Travis");
return;
}
#endif
string mainConfig1 = @"<nlog autoReload='true'>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string mainConfig2 = @"<nlog autoReload='true'>
<include file='included2.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string included1Config = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>";
string included2Config1 = @"<nlog autoReload='false'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
</nlog>";
string included2Config2 = @"<nlog autoReload='false'>
<targets><target name='debug' type='Debug' layout='(${message})' /></targets>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string mainConfigFilePath = Path.Combine(tempPath, "main.nlog");
WriteConfigFile(mainConfigFilePath, mainConfig1);
string included1ConfigFilePath = Path.Combine(tempPath, "included.nlog");
WriteConfigFile(included1ConfigFilePath, included1Config);
string included2ConfigFilePath = Path.Combine(tempPath, "included2.nlog");
WriteConfigFile(included2ConfigFilePath, included2Config1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2);
logger.Debug("bbb");
// Assert that mainConfig2 is loaded (which refers to included2.nlog).
AssertDebugLastMessage("debug", "[bbb]");
ChangeAndReloadConfigFile(included2ConfigFilePath, included2Config2, assertDidReload: false);
logger.Debug("ccc");
// Assert that included2Config1 is still loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestKeepVariablesOnReload()
{
string config = @"<nlog autoReload='true' keepVariablesOnReload='true'>
<variable name='var1' value='' />
<variable name='var2' value='keep_value' />
</nlog>";
LogManager.Configuration = XmlLoggingConfigurationMock.CreateFromXml(config);
LogManager.Configuration.Variables["var1"] = "new_value";
LogManager.Configuration.Variables["var3"] = "new_value3";
LogManager.Configuration = LogManager.Configuration.Reload();
Assert.Equal("new_value", LogManager.Configuration.Variables["var1"].OriginalText);
Assert.Equal("keep_value", LogManager.Configuration.Variables["var2"].OriginalText);
Assert.Equal("new_value3", LogManager.Configuration.Variables["var3"].OriginalText);
}
[Fact]
public void TestResetVariablesOnReload()
{
string config = @"<nlog autoReload='true' keepVariablesOnReload='false'>
<variable name='var1' value='' />
<variable name='var2' value='keep_value' />
</nlog>";
LogManager.Configuration = XmlLoggingConfigurationMock.CreateFromXml(config);
LogManager.Configuration.Variables["var1"] = "new_value";
LogManager.Configuration.Variables["var3"] = "new_value3";
LogManager.Configuration = LogManager.Configuration.Reload();
Assert.Equal("", LogManager.Configuration.Variables["var1"].OriginalText);
Assert.Equal("keep_value", LogManager.Configuration.Variables["var2"].OriginalText);
}
private static void WriteConfigFile(string configFilePath, string config)
{
using (StreamWriter writer = File.CreateText(configFilePath))
writer.Write(config);
}
private static void ChangeAndReloadConfigFile(string configFilePath, string config, bool assertDidReload = true)
{
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
WriteConfigFile(configFilePath, config);
reloadWaiter.WaitForReload();
if (assertDidReload)
Assert.True(reloadWaiter.DidReload, $"Config '{configFilePath}' did not reload.");
}
}
private class ConfigurationReloadWaiter : IDisposable
{
private ManualResetEvent counterEvent = new ManualResetEvent(false);
public ConfigurationReloadWaiter()
{
LogManager.ConfigurationReloaded += SignalCounterEvent(counterEvent);
}
public bool DidReload { get { return counterEvent.WaitOne(0); } }
public void Dispose()
{
LogManager.ConfigurationReloaded -= SignalCounterEvent(counterEvent);
}
public void WaitForReload()
{
counterEvent.WaitOne(3000);
}
private static EventHandler<LoggingConfigurationReloadedEventArgs> SignalCounterEvent(ManualResetEvent counterEvent)
{
return (sender, e) =>
{
counterEvent.Set();
};
}
}
}
/// <summary>
/// Xml config with reload without file-reads for performance
/// </summary>
public class XmlLoggingConfigurationMock : XmlLoggingConfiguration
{
private XmlElement _xmlElement;
private string _fileName;
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="element">The XML element.</param>
/// <param name="fileName">Name of the XML file.</param>
internal XmlLoggingConfigurationMock(XmlElement element, string fileName) : base(element, fileName)
{
_xmlElement = element;
_fileName = fileName;
}
private bool _reloading;
#region Overrides of XmlLoggingConfiguration
public override LoggingConfiguration Reload()
{
if (_reloading)
{
return new XmlLoggingConfigurationMock(_xmlElement, _fileName);
}
_reloading = true;
var factory = LogManager.LogFactory;
//reloadTimer should be set for ReloadConfigOnTimer
factory.reloadTimer = new Timer((a) => { });
factory.ReloadConfigOnTimer(this);
_reloading = false;
return factory.Configuration;
}
#endregion
public static XmlLoggingConfigurationMock CreateFromXml(string configXml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(configXml);
string currentDirectory = null;
try
{
currentDirectory = Environment.CurrentDirectory;
}
catch (SecurityException)
{
//ignore
}
return new XmlLoggingConfigurationMock(doc.DocumentElement, currentDirectory);
}
}
}
#endif
| |
// This file makes use of the LeMP 'unroll' macro to avoid copy-pasting code.
// See http://ecsharp.net/lemp/avoid-tedium-with-LeMP.html for an explanation.
#importMacros(LeMP);
namespace System
{
/// <summary>
/// Represents errors that occur during program execution.
/// </summary>
public class Exception : Object
{
/// <summary>
/// Creates an exception.
/// </summary>
public Exception()
: this("An exception occurred.")
{ }
/// <summary>
/// Creates an exception from an error message.
/// </summary>
/// <param name="message">An error message.</param>
public Exception(string message)
: this(message, null)
{ }
/// <summary>
/// Creates an exception from an error message and an inner
/// exception.
/// </summary>
/// <param name="message">An error message.</param>
/// <param name="innerException">An exception that gives rise to this exception.</param>
public Exception(string message, Exception innerException)
{
this.Message = message;
this.InnerException = innerException;
}
/// <summary>
/// Gets the inner exception that gave rise to this exception.
/// </summary>
/// <returns>The inner exception.</returns>
public Exception InnerException { get; private set; }
/// <summary>
/// Gets a message that describes the current exception.
/// </summary>
/// <returns>A message that describes why the exception occurred.</returns>
public virtual string Message { get; private set; }
}
unroll ((TYPE, BASE_TYPE, DEFAULT_MESSAGE) in (
(SystemException, Exception, "System error."),
(InvalidOperationException, SystemException, "Operation is not valid due to the current state of the object."),
(NotSupportedException, SystemException, "Specified method is not supported."),
(NotImplementedException, SystemException, "Specified functionality is not implemented."),
(UnauthorizedAccessException, SystemException, "Unauthorized access."),
(IndexOutOfRangeException, SystemException, "Index was outside the bounds of the array.")))
{
public class TYPE : BASE_TYPE
{
/// <summary>
/// Creates an exception.
/// </summary>
public TYPE()
: base(DEFAULT_MESSAGE)
{ }
/// <summary>
/// Creates an exception from an error message.
/// </summary>
/// <param name="message">An error message.</param>
public TYPE(string message)
: base(message)
{ }
/// <summary>
/// Creates an exception from an error message and an inner
/// exception.
/// </summary>
/// <param name="message">An error message.</param>
/// <param name="innerException">An exception that gives rise to this exception.</param>
public TYPE(string message, Exception innerException)
: base(message, innerException)
{ }
}
}
/// <summary>
/// A type of exception that is thrown when at least one argument does
/// not meet a method's contract.
/// </summary>
public class ArgumentException : SystemException
{
public ArgumentException()
: base("Value does not fall within the expected range.")
{ }
public ArgumentException(string message)
: base(message)
{ }
public ArgumentException(string message, Exception innerException)
: base(message, innerException)
{ }
public ArgumentException(string message, string paramName, Exception innerException)
: base(message, innerException)
{
this.paramName = paramName;
}
public ArgumentException(string message, string paramName)
: base(message)
{
this.paramName = paramName;
}
private string paramName;
/// <inheritdoc/>
public override string Message
{
get
{
if (string.IsNullOrEmpty(paramName))
{
return base.Message;
}
else
{
return base.Message + Environment.NewLine +
"Parameter name: " + paramName;
}
}
}
/// <summary>
/// Gets the name of the parameter that broke a method's contract.
/// </summary>
/// <returns>The name of a parameter.</returns>
public virtual string ParamName
{
get { return paramName; }
}
}
unroll ((TYPE, DEFAULT_MESSAGE) in (
(ArgumentNullException, "Value cannot be null."),))
{
public class TYPE : ArgumentException
{
public TYPE()
: base(DEFAULT_MESSAGE)
{ }
public TYPE(string paramName)
: base(DEFAULT_MESSAGE, paramName)
{ }
public TYPE(string message, Exception innerException)
: base(message, innerException)
{ }
public TYPE(string paramName, string message)
: base(message, paramName)
{ }
}
}
/// <summary>
/// A type of exception that is thrown when a value is outside of the
/// legal range for a parameter.
/// </summary>
public class ArgumentOutOfRangeException : ArgumentException
{
private const string DefaultMessage = "Specified argument was out of the range of valid values.";
public ArgumentOutOfRangeException()
: base(DefaultMessage)
{ }
public ArgumentOutOfRangeException(string paramName)
: base(DefaultMessage, paramName)
{ }
public ArgumentOutOfRangeException(string paramName, string message)
: base(message, paramName)
{ }
public ArgumentOutOfRangeException(string message, Exception innerException)
: base(message, innerException)
{ }
public ArgumentOutOfRangeException(string paramName, object actualValue, string message)
: base(message, paramName)
{
this.actualValue = actualValue;
}
/// <inheritdoc/>
public override string Message
{
get
{
string s = base.Message;
if (actualValue == null)
{
return s;
}
else
{
return s + Environment.NewLine + "Actual value was " + actualValue.ToString() + ".";
}
}
}
private object actualValue;
/// <summary>
/// Gets the value of the argument that broke a method's contract.
/// </summary>
/// <returns>The actual value of the argument.</returns>
public virtual object ActualValue
{
get { return actualValue; }
}
}
/// <summary>
/// A type of exception that is thrown when an already-exposed value is accessed.
/// </summary>
public class ObjectDisposedException : InvalidOperationException
{
public ObjectDisposedException(string objectName)
: this(objectName, "Cannot access a disposed object.")
{
}
public ObjectDisposedException(string objectName, string message)
: base(message)
{
this.objectName = objectName;
}
public ObjectDisposedException(string message, Exception innerException)
: base(message, innerException)
{ }
/// <inheritdoc/>
public override string Message
{
get
{
if (string.IsNullOrEmpty(ObjectName))
{
return base.Message;
}
else
{
return base.Message + Environment.NewLine + "Object name: " + ObjectName;
}
}
}
private string objectName;
/// <summary>
/// Gets the name of the object that was already disposed.
/// </summary>
/// <returns>The name of the object.</returns>
public string ObjectName
{
get
{
return objectName ?? "";
}
}
}
}
| |
// 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 AndByte()
{
var test = new SimpleBinaryOpTest__AndByte();
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();
if (Sse2.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 (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 class works
test.RunClassLclFldScenario();
if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AndByte testClass)
{
var result = Sse2.And(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndByte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.And(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AndByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleBinaryOpTest__AndByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.And(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.And(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.And(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.And(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = Sse2.And(
Sse2.LoadVector128((Byte*)(pClsVar1)),
Sse2.LoadVector128((Byte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.And(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.And(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.And(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AndByte();
var result = Sse2.And(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AndByte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = Sse2.And(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.And(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.And(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.And(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.And(
Sse2.LoadVector128((Byte*)(&test._fld1)),
Sse2.LoadVector128((Byte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((byte)(left[0] & right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((byte)(left[i] & right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.And)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using NUnit.Framework;
using System.Drawing;
using System.Text.RegularExpressions;
using OpenQA.Selenium.Environment;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Interactions
{
[TestFixture]
public class DragAndDropTest : DriverTestFixture
{
[SetUp]
public void SetupTest()
{
IActionExecutor actionExecutor = driver as IActionExecutor;
if (actionExecutor != null)
{
actionExecutor.ResetInputState();
}
}
[Test]
public void DragAndDropRelative()
{
driver.Url = dragAndDropPage;
IWebElement img = driver.FindElement(By.Id("test1"));
Point expectedLocation = drag(img, img.Location, 150, 200);
Assert.AreEqual(expectedLocation, img.Location);
expectedLocation = drag(img, img.Location, -50, -25);
Assert.AreEqual(expectedLocation, img.Location);
expectedLocation = drag(img, img.Location, 0, 0);
Assert.AreEqual(expectedLocation, img.Location);
expectedLocation = drag(img, img.Location, 1, -1);
Assert.AreEqual(expectedLocation, img.Location);
}
[Test]
public void DragAndDropToElement()
{
driver.Url = dragAndDropPage;
IWebElement img1 = driver.FindElement(By.Id("test1"));
IWebElement img2 = driver.FindElement(By.Id("test2"));
Actions actionProvider = new Actions(driver);
actionProvider.DragAndDrop(img2, img1).Perform();
Assert.AreEqual(img1.Location, img2.Location);
}
[Test]
public void DragAndDropToElementInIframe()
{
driver.Url = iframePage;
IWebElement iframe = driver.FindElement(By.TagName("iframe"));
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].src = arguments[1]", iframe,
dragAndDropPage);
driver.SwitchTo().Frame(0);
IWebElement img1 = WaitFor<IWebElement>(() =>
{
try
{
IWebElement element1 = driver.FindElement(By.Id("test1"));
return element1;
}
catch (NoSuchElementException)
{
return null;
}
}, "Element with ID 'test1' not found");
IWebElement img2 = driver.FindElement(By.Id("test2"));
new Actions(driver).DragAndDrop(img2, img1).Perform();
Assert.AreEqual(img1.Location, img2.Location);
}
[Test]
public void DragAndDropElementWithOffsetInIframeAtBottom()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("iframeAtBottom.html");
IWebElement iframe = driver.FindElement(By.TagName("iframe"));
driver.SwitchTo().Frame(iframe);
IWebElement img1 = driver.FindElement(By.Id("test1"));
Point initial = img1.Location;
new Actions(driver).DragAndDropToOffset(img1, 20, 20).Perform();
initial.Offset(20, 20);
Assert.AreEqual(initial, img1.Location);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.Edge, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.Firefox, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.IE, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.Safari, "Moving outside of view port throws exception in spec-compliant driver")]
public void DragAndDropElementWithOffsetInScrolledDiv()
{
if (TestUtilities.IsFirefox(driver) && TestUtilities.IsNativeEventsEnabled(driver))
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("dragAndDropInsideScrolledDiv.html");
IWebElement el = driver.FindElement(By.Id("test1"));
Point initial = el.Location;
new Actions(driver).DragAndDropToOffset(el, 3700, 3700).Perform();
initial.Offset(3700, 3700);
Assert.AreEqual(initial, el.Location);
}
[Test]
public void ElementInDiv()
{
driver.Url = dragAndDropPage;
IWebElement img = driver.FindElement(By.Id("test3"));
Point startLocation = img.Location;
Point expectedLocation = drag(img, startLocation, 100, 100);
Point endLocation = img.Location;
Assert.AreEqual(expectedLocation, endLocation);
}
[Test]
public void DragTooFar()
{
driver.Url = dragAndDropPage;
IWebElement img = driver.FindElement(By.Id("test1"));
// Dragging too far left and up does not move the element. It will be at
// its original location after the drag.
Point originalLocation = new Point(0, 0);
Actions actionProvider = new Actions(driver);
Assert.That(() => actionProvider.DragAndDropToOffset(img, 2147480000, 2147400000).Perform(), Throws.InstanceOf<WebDriverException>());
new Actions(driver).Release().Perform();
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.Edge, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.Firefox, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.IE, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.Safari, "Moving outside of view port throws exception in spec-compliant driver")]
public void ShouldAllowUsersToDragAndDropToElementsOffTheCurrentViewPort()
{
Size originalSize = driver.Manage().Window.Size;
Size testSize = new Size(300, 300);
driver.Url = dragAndDropPage;
driver.Manage().Window.Size = testSize;
try
{
driver.Url = dragAndDropPage;
IWebElement img = driver.FindElement(By.Id("test3"));
Point expectedLocation = drag(img, img.Location, 100, 100);
Assert.AreEqual(expectedLocation, img.Location);
}
finally
{
driver.Manage().Window.Size = originalSize;
}
}
[Test]
public void DragAndDropOnJQueryItems()
{
driver.Url = droppableItems;
IWebElement toDrag = driver.FindElement(By.Id("draggable"));
IWebElement dropInto = driver.FindElement(By.Id("droppable"));
// Wait until all event handlers are installed.
System.Threading.Thread.Sleep(500);
Actions actionProvider = new Actions(driver);
actionProvider.DragAndDrop(toDrag, dropInto).Perform();
string text = dropInto.FindElement(By.TagName("p")).Text;
DateTime endTime = DateTime.Now.Add(TimeSpan.FromSeconds(15));
while (text != "Dropped!" && (DateTime.Now < endTime))
{
System.Threading.Thread.Sleep(200);
text = dropInto.FindElement(By.TagName("p")).Text;
}
Assert.AreEqual("Dropped!", text);
IWebElement reporter = driver.FindElement(By.Id("drop_reports"));
// Assert that only one mouse click took place and the mouse was moved
// during it.
string reporterText = reporter.Text;
Assert.That(reporterText, Does.Match("start( move)* down( move)+ up"));
Assert.AreEqual(1, Regex.Matches(reporterText, "down").Count, "Reporter text:" + reporterText);
Assert.AreEqual(1, Regex.Matches(reporterText, "up").Count, "Reporter text:" + reporterText);
Assert.That(reporterText, Does.Contain("move"));
}
[Test]
[IgnoreBrowser(Browser.Opera, "Untested")]
[IgnoreBrowser(Browser.Firefox, "Moving outside of view port throws exception in spec-compliant driver")]
[IgnoreBrowser(Browser.IE, "Moving outside of view port throws exception in spec-compliant driver")]
public void CanDragAnElementNotVisibleInTheCurrentViewportDueToAParentOverflow()
{
driver.Url = dragDropOverflowPage;
IWebElement toDrag = driver.FindElement(By.Id("time-marker"));
IWebElement dragTo = driver.FindElement(By.Id("11am"));
Point srcLocation = toDrag.Location;
Point targetLocation = dragTo.Location;
int yOffset = targetLocation.Y - srcLocation.Y;
Assert.AreNotEqual(0, yOffset);
new Actions(driver).DragAndDropToOffset(toDrag, 0, yOffset).Perform();
Assert.AreEqual(dragTo.Location, toDrag.Location);
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
public void DragAndDropRelativeAndToElement()
{
driver.Url = dragAndDropPage;
IWebElement img1 = driver.FindElement(By.Id("test1"));
IWebElement img2 = driver.FindElement(By.Id("test2"));
Actions actionProvider = new Actions(driver);
actionProvider.DragAndDropToOffset(img1, 100, 100).DragAndDrop(img2, img1).Perform();
Assert.AreEqual(img1.Location, img2.Location);
}
private Point drag(IWebElement elem, Point initialLocation, int moveRightBy, int moveDownBy)
{
Point expectedLocation = new Point(initialLocation.X, initialLocation.Y);
expectedLocation.Offset(moveRightBy, moveDownBy);
Actions actionProvider = new Actions(driver);
actionProvider.DragAndDropToOffset(elem, moveRightBy, moveDownBy).Perform();
return expectedLocation;
}
}
}
| |
// 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.Diagnostics;
using System.Reflection;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Completion;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
[ExportLanguageSpecificOptionSerializer(
LanguageNames.CSharp,
OrganizerOptions.FeatureName,
SplitStringLiteralOptions.FeatureName,
AddImportOptions.FeatureName,
CompletionOptions.FeatureName,
CSharpCompletionOptions.FeatureName,
CSharpCodeStyleOptions.FeatureName,
CodeStyleOptions.PerLanguageCodeStyleOption,
SimplificationOptions.PerLanguageFeatureName,
ExtractMethodOptions.FeatureName,
CSharpFormattingOptions.IndentFeatureName,
CSharpFormattingOptions.NewLineFormattingFeatureName,
CSharpFormattingOptions.SpacingFeatureName,
CSharpFormattingOptions.WrappingFeatureName,
FormattingOptions.InternalTabFeatureName,
FeatureOnOffOptions.OptionName,
ServiceFeatureOnOffOptions.OptionName), Shared]
internal sealed class CSharpSettingsManagerOptionSerializer : AbstractSettingsManagerOptionSerializer
{
[ImportingConstructor]
public CSharpSettingsManagerOptionSerializer(SVsServiceProvider serviceProvider, IOptionService optionService)
: base(serviceProvider, optionService)
{
}
private const string WrappingIgnoreSpacesAroundBinaryOperator = nameof(AutomationObject.Wrapping_IgnoreSpacesAroundBinaryOperators);
private const string SpaceAroundBinaryOperator = nameof(AutomationObject.Space_AroundBinaryOperator);
private const string UnindentLabels = nameof(AutomationObject.Indent_UnindentLabels);
private const string FlushLabelsLeft = nameof(AutomationObject.Indent_FlushLabelsLeft);
private const string Style_QualifyFieldAccess = nameof(AutomationObject.Style_QualifyFieldAccess);
private const string Style_QualifyPropertyAccess = nameof(AutomationObject.Style_QualifyPropertyAccess);
private const string Style_QualifyMethodAccess = nameof(AutomationObject.Style_QualifyMethodAccess);
private const string Style_QualifyEventAccess = nameof(AutomationObject.Style_QualifyEventAccess);
private const string Style_UseImplicitTypeForIntrinsicTypes = nameof(AutomationObject.Style_UseImplicitTypeForIntrinsicTypes);
private const string Style_UseImplicitTypeWhereApparent = nameof(AutomationObject.Style_UseImplicitTypeWhereApparent);
private const string Style_UseImplicitTypeWherePossible = nameof(AutomationObject.Style_UseImplicitTypeWherePossible);
private KeyValuePair<string, IOption> GetOptionInfoForOnOffOptions(FieldInfo fieldInfo)
{
var value = (IOption)fieldInfo.GetValue(obj: null);
return new KeyValuePair<string, IOption>(GetStorageKeyForOption(value), value);
}
private bool ShouldIncludeOnOffOption(FieldInfo fieldInfo)
{
return SupportsOnOffOption((IOption)fieldInfo.GetValue(obj: null));
}
protected override ImmutableDictionary<string, IOption> CreateStorageKeyToOptionMap()
{
var result = ImmutableDictionary.Create<string, IOption>(StringComparer.OrdinalIgnoreCase).ToBuilder();
result.AddRange(new[]
{
new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.TriggerOnTypingLetters), CompletionOptions.TriggerOnTypingLetters),
new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.TriggerOnDeletion), CompletionOptions.TriggerOnDeletion),
new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.ShowCompletionItemFilters), CompletionOptions.ShowCompletionItemFilters),
new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems), CompletionOptions.HighlightMatchingPortionsOfCompletionListItems),
});
Type[] types = new[]
{
typeof(OrganizerOptions),
typeof(AddImportOptions),
typeof(SplitStringLiteralOptions),
typeof(CSharpCompletionOptions),
typeof(SimplificationOptions),
typeof(CSharpCodeStyleOptions),
typeof(ExtractMethodOptions),
typeof(ServiceFeatureOnOffOptions),
typeof(CSharpFormattingOptions),
typeof(CodeStyleOptions)
};
var bindingFlags = BindingFlags.Public | BindingFlags.Static;
result.AddRange(GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfo));
types = new[] { typeof(FeatureOnOffOptions) };
result.AddRange(GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfoForOnOffOptions, this.ShouldIncludeOnOffOption));
return result.ToImmutable();
}
protected override string LanguageName { get { return LanguageNames.CSharp; } }
protected override string SettingStorageRoot { get { return "TextEditor.CSharp.Specific."; } }
protected override string GetStorageKeyForOption(IOption option)
{
var name = option.Name;
if (option == ServiceFeatureOnOffOptions.ClosedFileDiagnostic)
{
// ClosedFileDiagnostics has been deprecated in favor of CSharpClosedFileDiagnostics.
// ClosedFileDiagnostics had a default value of 'true', while CSharpClosedFileDiagnostics has a default value of 'false'.
// We want to ensure that we don't fetch the setting store value for the old flag, as that can cause the default value for this option to change.
name = nameof(AutomationObject.CSharpClosedFileDiagnostics);
}
return SettingStorageRoot + name;
}
protected override bool SupportsOption(IOption option, string languageName)
{
if (option == OrganizerOptions.PlaceSystemNamespaceFirst ||
option == AddImportOptions.SuggestForTypesInReferenceAssemblies ||
option == AddImportOptions.SuggestForTypesInNuGetPackages ||
option.Feature == CodeStyleOptions.PerLanguageCodeStyleOption ||
option.Feature == CSharpCodeStyleOptions.FeatureName ||
option.Feature == CSharpFormattingOptions.WrappingFeatureName ||
option.Feature == CSharpFormattingOptions.IndentFeatureName ||
option.Feature == CSharpFormattingOptions.SpacingFeatureName ||
option.Feature == CSharpFormattingOptions.NewLineFormattingFeatureName)
{
return true;
}
else if (languageName == LanguageNames.CSharp)
{
if (option == CompletionOptions.TriggerOnTypingLetters ||
option == CompletionOptions.TriggerOnDeletion ||
option == CompletionOptions.ShowCompletionItemFilters ||
option == CompletionOptions.HighlightMatchingPortionsOfCompletionListItems ||
option == CompletionOptions.EnterKeyBehavior ||
option == CompletionOptions.SnippetsBehavior ||
option.Feature == SimplificationOptions.PerLanguageFeatureName ||
option.Feature == ExtractMethodOptions.FeatureName ||
option.Feature == ServiceFeatureOnOffOptions.OptionName ||
option.Feature == FormattingOptions.InternalTabFeatureName)
{
return true;
}
else if (option.Feature == FeatureOnOffOptions.OptionName)
{
return SupportsOnOffOption(option);
}
}
return false;
}
private bool SupportsOnOffOption(IOption option)
{
return option == FeatureOnOffOptions.AutoFormattingOnCloseBrace ||
option == FeatureOnOffOptions.AutoFormattingOnSemicolon ||
option == FeatureOnOffOptions.LineSeparator ||
option == FeatureOnOffOptions.Outlining ||
option == FeatureOnOffOptions.ReferenceHighlighting ||
option == FeatureOnOffOptions.KeywordHighlighting ||
option == FeatureOnOffOptions.FormatOnPaste ||
option == FeatureOnOffOptions.AutoXmlDocCommentGeneration ||
option == FeatureOnOffOptions.AutoInsertBlockCommentStartString ||
option == FeatureOnOffOptions.RefactoringVerification ||
option == FeatureOnOffOptions.RenameTracking ||
option == FeatureOnOffOptions.RenameTrackingPreview;
}
public override bool TryFetch(OptionKey optionKey, out object value)
{
value = null;
if (this.Manager == null)
{
Debug.Fail("Manager field is unexpectedly null.");
return false;
}
if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator)
{
// Remove space -> Space_AroundBinaryOperator = 0
// Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing
// Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1
object ignoreSpacesAroundBinaryObjectValue = this.Manager.GetValueOrDefault(WrappingIgnoreSpacesAroundBinaryOperator, defaultValue: 0);
if (ignoreSpacesAroundBinaryObjectValue.Equals(1))
{
value = BinaryOperatorSpacingOptions.Ignore;
return true;
}
object spaceAroundBinaryOperatorObjectValue = this.Manager.GetValueOrDefault(SpaceAroundBinaryOperator, defaultValue: 1);
if (spaceAroundBinaryOperatorObjectValue.Equals(0))
{
value = BinaryOperatorSpacingOptions.Remove;
return true;
}
value = BinaryOperatorSpacingOptions.Single;
return true;
}
if (optionKey.Option == CSharpFormattingOptions.LabelPositioning)
{
object flushLabelLeftObjectValue = this.Manager.GetValueOrDefault(FlushLabelsLeft, defaultValue: 0);
if (flushLabelLeftObjectValue.Equals(1))
{
value = LabelPositionOptions.LeftMost;
return true;
}
object unindentLabelsObjectValue = this.Manager.GetValueOrDefault(UnindentLabels, defaultValue: 1);
if (unindentLabelsObjectValue.Equals(0))
{
value = LabelPositionOptions.NoIndent;
return true;
}
value = LabelPositionOptions.OneLess;
return true;
}
// code style: use this.
if (optionKey.Option == CodeStyleOptions.QualifyFieldAccess)
{
return FetchStyleBool(Style_QualifyFieldAccess, out value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyPropertyAccess)
{
return FetchStyleBool(Style_QualifyPropertyAccess, out value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyMethodAccess)
{
return FetchStyleBool(Style_QualifyMethodAccess, out value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyEventAccess)
{
return FetchStyleBool(Style_QualifyEventAccess, out value);
}
// code style: use var options.
if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes)
{
return FetchStyleBool(Style_UseImplicitTypeForIntrinsicTypes, out value);
}
else if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeWhereApparent)
{
return FetchStyleBool(Style_UseImplicitTypeWhereApparent, out value);
}
else if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeWherePossible)
{
return FetchStyleBool(Style_UseImplicitTypeWherePossible, out value);
}
if (optionKey.Option == CompletionOptions.EnterKeyBehavior)
{
return FetchEnterKeyBehavior(optionKey, out value);
}
if (optionKey.Option == CompletionOptions.SnippetsBehavior)
{
return FetchSnippetsBehavior(optionKey, out value);
}
if (optionKey.Option == CompletionOptions.TriggerOnDeletion)
{
return FetchTriggerOnDeletion(optionKey, out value);
}
return base.TryFetch(optionKey, out value);
}
private bool FetchTriggerOnDeletion(OptionKey optionKey, out object value)
{
if (!base.TryFetch(optionKey, out value))
{
return false;
}
if (value == null)
{
// The default behavior for c# is to not trigger completion on deletion.
value = (bool?)false;
}
return true;
}
private bool FetchStyleBool(string settingName, out object value)
{
var typeStyleValue = Manager.GetValueOrDefault<string>(settingName);
return FetchStyleOption<bool>(typeStyleValue, out value);
}
/// <summary>
/// The EnterKeyBehavior option (formerly AddNewLineOnEnterAfterFullyTypedWord) used to only exist in C# and as a boolean.
/// We need to maintain the meaning of the serialized legacy setting.
/// </summary>
private bool FetchSnippetsBehavior(OptionKey optionKey, out object value)
{
if (!base.TryFetch(optionKey, out value))
{
return false;
}
if (!value.Equals(SnippetsRule.Default))
{
return true;
}
// if the SnippetsBehavior setting cannot be loaded, then attempt to load and upgrade the legacy setting
#pragma warning disable CS0618 // IncludeSnippets is obsolete
if (base.TryFetch(CSharpCompletionOptions.IncludeSnippets, out value))
#pragma warning restore CS0618
{
if ((bool)value)
{
value = SnippetsRule.AlwaysInclude;
}
else
{
value = SnippetsRule.NeverInclude;
}
return true;
}
value = SnippetsRule.AlwaysInclude;
return true;
}
/// <summary>
/// The EnterKeyBehavior option (formerly AddNewLineOnEnterAfterFullyTypedWord) used to only exist in C# and as a boolean.
/// We need to maintain the meaning of the serialized legacy setting.
/// </summary>
private bool FetchEnterKeyBehavior(OptionKey optionKey, out object value)
{
if (!base.TryFetch(optionKey, out value))
{
return false;
}
if (!value.Equals(EnterKeyRule.Default))
{
return true;
}
// if the EnterKeyBehavior setting cannot be loaded, then attempt to load and upgrade the legacy AddNewLineOnEnterAfterFullyTypedWord setting
#pragma warning disable CS0618 // AddNewLineOnEnterAfterFullyTypedWord is obsolete
if (base.TryFetch(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord, out value))
#pragma warning restore CS0618
{
int intValue = (int)value;
switch (intValue)
{
case 1:
value = EnterKeyRule.AfterFullyTypedWord;
break;
case 0:
default:
value = EnterKeyRule.Never;
break;
}
return true;
}
value = EnterKeyRule.Never;
return true;
}
public override bool TryPersist(OptionKey optionKey, object value)
{
if (this.Manager == null)
{
Debug.Fail("Manager field is unexpectedly null.");
return false;
}
if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator)
{
// Remove space -> Space_AroundBinaryOperator = 0
// Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing
// Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1
switch ((BinaryOperatorSpacingOptions)value)
{
case BinaryOperatorSpacingOptions.Remove:
{
this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false);
this.Manager.SetValueAsync(SpaceAroundBinaryOperator, 0, isMachineLocal: false);
return true;
}
case BinaryOperatorSpacingOptions.Ignore:
{
this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false);
this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, 1, isMachineLocal: false);
return true;
}
case BinaryOperatorSpacingOptions.Single:
{
this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false);
this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false);
return true;
}
}
}
else if (optionKey.Option == CSharpFormattingOptions.LabelPositioning)
{
switch ((LabelPositionOptions)value)
{
case LabelPositionOptions.LeftMost:
{
this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false);
this.Manager.SetValueAsync(FlushLabelsLeft, 1, isMachineLocal: false);
return true;
}
case LabelPositionOptions.NoIndent:
{
this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false);
this.Manager.SetValueAsync(UnindentLabels, 0, isMachineLocal: false);
return true;
}
case LabelPositionOptions.OneLess:
{
this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false);
this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false);
return true;
}
}
}
// code style: use this.
if (optionKey.Option == CodeStyleOptions.QualifyFieldAccess)
{
return PersistStyleOption<bool>(Style_QualifyFieldAccess, value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyPropertyAccess)
{
return PersistStyleOption<bool>(Style_QualifyPropertyAccess, value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyMethodAccess)
{
return PersistStyleOption<bool>(Style_QualifyMethodAccess, value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyEventAccess)
{
return PersistStyleOption<bool>(Style_QualifyEventAccess, value);
}
// code style: use var options.
if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes)
{
return PersistStyleOption<bool>(Style_UseImplicitTypeForIntrinsicTypes, value);
}
else if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeWhereApparent)
{
return PersistStyleOption<bool>(Style_UseImplicitTypeWhereApparent, value);
}
else if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeWherePossible)
{
return PersistStyleOption<bool>(Style_UseImplicitTypeWherePossible, value);
}
return base.TryPersist(optionKey, value);
}
private bool PersistStyleOption<T>(string option, object value)
{
var serializedValue = ((CodeStyleOption<T>)value).ToXElement().ToString();
this.Manager.SetValueAsync(option, value: serializedValue, isMachineLocal: false);
return true;
}
private static bool FetchStyleOption<T>(string typeStyleOptionValue, out object value)
{
if (string.IsNullOrEmpty(typeStyleOptionValue))
{
value = CodeStyleOption<T>.Default;
}
else
{
value = CodeStyleOption<T>.FromXElement(XElement.Parse(typeStyleOptionValue));
}
return true;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
namespace FastLogAsync
{
/// <summary>
/// Logging system initializes itself with static constructor.
/// Define FAST_LOG compilation symbol to allow using logging in assembly/file
/// Define FAST_TRACE to also allow tracing/verbose log
/// </summary>
public static class Log
{
public static string TimeStampFormat = "HH:mm:ss.fff";
private const string DateTimeStampFormat = "yyyy-MM-dd HH:mm:ss.fff";
// you can configure this properties at runtime
// and/or set AppSettings with the same names in configuration file
// echo everything to console
public static bool ConsoleOutputEnabled;
// save log lines to file
public static bool FileOutputEnabled = true;
public static bool InfoLogEnabled = true;
public static bool ErrorLogEnabled = true;
public static bool TraceLogEnabled = true;
// public static string LogFilePath;
/// <summary>
/// It's best to subscribe this method to 'exiting' events of your application.
/// It still tries to exit gracefully, but not all the cases is possible to cover
/// without application-specific exit events.
/// </summary>
public static void DoGracefullExit()
{
try
{
LogQueue.CompleteAdding();
_writingThread.Join();
}
catch
{
// we rally don't care about exceptions here
}
}
[Conditional("FAST_LOG")]
public static void Info(string msg, params object[] par)
{
if (!InfoLogEnabled) return;
LogQueue.Add(string.Format("{0} INF {1}\r\n", DateTime.UtcNow.ToString(TimeStampFormat),
// need to check because {} symbols might break Format call
(par == null || par.Length == 0) ? msg : string.Format(msg, par)));
}
[Conditional("FAST_LOG")]
public static void Error(string msg, params object[] par)
{
if (!ErrorLogEnabled) return;
LogQueue.Add(string.Format("{0} ERR {1}\r\n", DateTime.UtcNow.ToString(TimeStampFormat),
// need to check because {} symbols might break Format call
(par == null || par.Length == 0) ? msg : string.Format(msg, par)));
}
[Conditional("FAST_LOG")]
public static void Error(Exception ex)
{
Error(ex.ToString());
}
[Conditional("FAST_TRACE")]
public static void Trace(string msg,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
if (!TraceLogEnabled) return;
LogQueue.Add(string.Format("{0} TRC {1}:{2}[{3}] {4}\r\n", DateTime.UtcNow.ToString(TimeStampFormat),
Path.GetFileName(sourceFilePath), memberName,
sourceLineNumber, msg));
}
// INTERNALS ------------------------------------------------------------
private static readonly Thread _writingThread;
private static readonly BlockingCollection<string> LogQueue;
private static int _currentDay = -1;
private static StreamWriter _currentFileStream;
//static constructor
static Log()
{
TryLoadSetting("TimeStampFormat", ref TimeStampFormat);
TryLoadSetting("ConsoleOutputEnabled", ref ConsoleOutputEnabled);
TryLoadSetting("FileOutputEnabled", ref FileOutputEnabled);
TryLoadSetting("InfoLogEnabled", ref InfoLogEnabled);
TryLoadSetting("ErrorLogEnabled", ref ErrorLogEnabled);
TryLoadSetting("TraceLogEnabled", ref TraceLogEnabled);
LogQueue = new BlockingCollection<string>();
AppDomain.CurrentDomain.ProcessExit += (s, a) => DoGracefullExit();
_writingThread = new Thread(Write);
_writingThread.Name = "Log writer thread";
_writingThread.IsBackground = true;
_writingThread.Priority = ThreadPriority.BelowNormal;
_writingThread.Start();
LogQueue.Add(string.Format("-------------------------------------------------\r\n" +
"{0} Logging system is initialized\r\n" +
"-------------------------------------------------\r\n",
DateTime.UtcNow.ToString(DateTimeStampFormat)));
}
// returns appSetting value if available
private static void TryLoadSetting(string name, ref bool val)
{
bool test;
if (bool.TryParse(ConfigurationManager.AppSettings[name], out test))
val = test;
}
private static void TryLoadSetting(string name, ref string val)
{
if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings[name]))
val = ConfigurationManager.AppSettings[name];
}
// Property handles daily roll-over files
private static StreamWriter LogFile
{
get
{
if (DateTime.UtcNow.Day == _currentDay)
return _currentFileStream;
// changing file
_currentDay = DateTime.UtcNow.Day;
string dirName = Path.Combine(
Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory),
"logs");
if (!Directory.Exists(dirName))
Directory.CreateDirectory(dirName);
string logFile = Path.Combine(dirName, DateTime.UtcNow.ToString(@"yyMMdd.lo\g"));
if (_currentFileStream != null)
_currentFileStream.Dispose();
_currentFileStream = new StreamWriter(File.Open(logFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
_currentFileStream.AutoFlush = true;
return _currentFileStream;
}
}
// Infinite logging thread
private static void Write()
{
string msg;
try
{
while (true)
{
msg = LogQueue.Take();
if (FileOutputEnabled)
LogFile.Write(msg);
if (ConsoleOutputEnabled)
{
var oldColor = Console.ForegroundColor;
var type = msg.Substring(9, 3);
switch (type)
{
case "ERR":
Console.ForegroundColor = ConsoleColor.Red;
break;
case "INF":
Console.ForegroundColor = ConsoleColor.Cyan;
break;
}
Console.Write(msg);
Console.ForegroundColor = oldColor;
}
}
}
catch
{
msg = string.Format("---------------------------------------------------\r\n" +
"{0} Logging system is shutting down\r\n" +
"---------------------------------------------------\r\n",
DateTime.UtcNow.ToString(DateTimeStampFormat));
if (FileOutputEnabled)
LogFile.Write(msg);
if (ConsoleOutputEnabled)
Console.Write(msg);
}
}
//------------------------------------------------------------
}
}
| |
//
// System.Drawing.KnownColors
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Peter Dennis Bartok (pbartok@novell.com)
// Sebastien Pouliot <sebastien@ximian.com>
//
// 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.
//
namespace System.Drawing {
#if NET_2_0
internal static class KnownColors {
#else
internal class KnownColors {
private KnownColors ()
{
}
#endif
// FindColorMatch relies on the index + 1 == KnowColor match
static internal uint[] ArgbValues = new uint[] {
0x00000000, /* 000 - Empty */
0xFFD4D0C8, /* 001 - ActiveBorder */
0xFF0054E3, /* 002 - ActiveCaption */
0xFFFFFFFF, /* 003 - ActiveCaptionText */
0xFF808080, /* 004 - AppWorkspace */
0xFFECE9D8, /* 005 - Control */
0xFFACA899, /* 006 - ControlDark */
0xFF716F64, /* 007 - ControlDarkDark */
0xFFF1EFE2, /* 008 - ControlLight */
0xFFFFFFFF, /* 009 - ControlLightLight */
0xFF000000, /* 010 - ControlText */
0xFF004E98, /* 011 - Desktop */
0xFFACA899, /* 012 - GrayText */
0xFF316AC5, /* 013 - Highlight */
0xFFFFFFFF, /* 014 - HighlightText */
0xFF000080, /* 015 - HotTrack */
0xFFD4D0C8, /* 016 - InactiveBorder */
0xFF7A96DF, /* 017 - InactiveCaption */
0xFFD8E4F8, /* 018 - InactiveCaptionText */
0xFFFFFFE1, /* 019 - Info */
0xFF000000, /* 020 - InfoText */
0xFFFFFFFF, /* 021 - Menu */
0xFF000000, /* 022 - MenuText */
0xFFD4D0C8, /* 023 - ScrollBar */
0xFFFFFFFF, /* 024 - Window */
0xFF000000, /* 025 - WindowFrame */
0xFF000000, /* 026 - WindowText */
0x00FFFFFF, /* 027 - Transparent */
0xFFF0F8FF, /* 028 - AliceBlue */
0xFFFAEBD7, /* 029 - AntiqueWhite */
0xFF00FFFF, /* 030 - Aqua */
0xFF7FFFD4, /* 031 - Aquamarine */
0xFFF0FFFF, /* 032 - Azure */
0xFFF5F5DC, /* 033 - Beige */
0xFFFFE4C4, /* 034 - Bisque */
0xFF000000, /* 035 - Black */
0xFFFFEBCD, /* 036 - BlanchedAlmond */
0xFF0000FF, /* 037 - Blue */
0xFF8A2BE2, /* 038 - BlueViolet */
0xFFA52A2A, /* 039 - Brown */
0xFFDEB887, /* 040 - BurlyWood */
0xFF5F9EA0, /* 041 - CadetBlue */
0xFF7FFF00, /* 042 - Chartreuse */
0xFFD2691E, /* 043 - Chocolate */
0xFFFF7F50, /* 044 - Coral */
0xFF6495ED, /* 045 - CornflowerBlue */
0xFFFFF8DC, /* 046 - Cornsilk */
0xFFDC143C, /* 047 - Crimson */
0xFF00FFFF, /* 048 - Cyan */
0xFF00008B, /* 049 - DarkBlue */
0xFF008B8B, /* 050 - DarkCyan */
0xFFB8860B, /* 051 - DarkGoldenrod */
0xFFA9A9A9, /* 052 - DarkGray */
0xFF006400, /* 053 - DarkGreen */
0xFFBDB76B, /* 054 - DarkKhaki */
0xFF8B008B, /* 055 - DarkMagenta */
0xFF556B2F, /* 056 - DarkOliveGreen */
0xFFFF8C00, /* 057 - DarkOrange */
0xFF9932CC, /* 058 - DarkOrchid */
0xFF8B0000, /* 059 - DarkRed */
0xFFE9967A, /* 060 - DarkSalmon */
0xFF8FBC8B, /* 061 - DarkSeaGreen */
0xFF483D8B, /* 062 - DarkSlateBlue */
0xFF2F4F4F, /* 063 - DarkSlateGray */
0xFF00CED1, /* 064 - DarkTurquoise */
0xFF9400D3, /* 065 - DarkViolet */
0xFFFF1493, /* 066 - DeepPink */
0xFF00BFFF, /* 067 - DeepSkyBlue */
0xFF696969, /* 068 - DimGray */
0xFF1E90FF, /* 069 - DodgerBlue */
0xFFB22222, /* 070 - Firebrick */
0xFFFFFAF0, /* 071 - FloralWhite */
0xFF228B22, /* 072 - ForestGreen */
0xFFFF00FF, /* 073 - Fuchsia */
0xFFDCDCDC, /* 074 - Gainsboro */
0xFFF8F8FF, /* 075 - GhostWhite */
0xFFFFD700, /* 076 - Gold */
0xFFDAA520, /* 077 - Goldenrod */
0xFF808080, /* 078 - Gray */
0xFF008000, /* 079 - Green */
0xFFADFF2F, /* 080 - GreenYellow */
0xFFF0FFF0, /* 081 - Honeydew */
0xFFFF69B4, /* 082 - HotPink */
0xFFCD5C5C, /* 083 - IndianRed */
0xFF4B0082, /* 084 - Indigo */
0xFFFFFFF0, /* 085 - Ivory */
0xFFF0E68C, /* 086 - Khaki */
0xFFE6E6FA, /* 087 - Lavender */
0xFFFFF0F5, /* 088 - LavenderBlush */
0xFF7CFC00, /* 089 - LawnGreen */
0xFFFFFACD, /* 090 - LemonChiffon */
0xFFADD8E6, /* 091 - LightBlue */
0xFFF08080, /* 092 - LightCoral */
0xFFE0FFFF, /* 093 - LightCyan */
0xFFFAFAD2, /* 094 - LightGoldenrodYellow */
0xFFD3D3D3, /* 095 - LightGray */
0xFF90EE90, /* 096 - LightGreen */
0xFFFFB6C1, /* 097 - LightPink */
0xFFFFA07A, /* 098 - LightSalmon */
0xFF20B2AA, /* 099 - LightSeaGreen */
0xFF87CEFA, /* 100 - LightSkyBlue */
0xFF778899, /* 101 - LightSlateGray */
0xFFB0C4DE, /* 102 - LightSteelBlue */
0xFFFFFFE0, /* 103 - LightYellow */
0xFF00FF00, /* 104 - Lime */
0xFF32CD32, /* 105 - LimeGreen */
0xFFFAF0E6, /* 106 - Linen */
0xFFFF00FF, /* 107 - Magenta */
0xFF800000, /* 108 - Maroon */
0xFF66CDAA, /* 109 - MediumAquamarine */
0xFF0000CD, /* 110 - MediumBlue */
0xFFBA55D3, /* 111 - MediumOrchid */
0xFF9370DB, /* 112 - MediumPurple */
0xFF3CB371, /* 113 - MediumSeaGreen */
0xFF7B68EE, /* 114 - MediumSlateBlue */
0xFF00FA9A, /* 115 - MediumSpringGreen */
0xFF48D1CC, /* 116 - MediumTurquoise */
0xFFC71585, /* 117 - MediumVioletRed */
0xFF191970, /* 118 - MidnightBlue */
0xFFF5FFFA, /* 119 - MintCream */
0xFFFFE4E1, /* 120 - MistyRose */
0xFFFFE4B5, /* 121 - Moccasin */
0xFFFFDEAD, /* 122 - NavajoWhite */
0xFF000080, /* 123 - Navy */
0xFFFDF5E6, /* 124 - OldLace */
0xFF808000, /* 125 - Olive */
0xFF6B8E23, /* 126 - OliveDrab */
0xFFFFA500, /* 127 - Orange */
0xFFFF4500, /* 128 - OrangeRed */
0xFFDA70D6, /* 129 - Orchid */
0xFFEEE8AA, /* 130 - PaleGoldenrod */
0xFF98FB98, /* 131 - PaleGreen */
0xFFAFEEEE, /* 132 - PaleTurquoise */
0xFFDB7093, /* 133 - PaleVioletRed */
0xFFFFEFD5, /* 134 - PapayaWhip */
0xFFFFDAB9, /* 135 - PeachPuff */
0xFFCD853F, /* 136 - Peru */
0xFFFFC0CB, /* 137 - Pink */
0xFFDDA0DD, /* 138 - Plum */
0xFFB0E0E6, /* 139 - PowderBlue */
0xFF800080, /* 140 - Purple */
0xFFFF0000, /* 141 - Red */
0xFFBC8F8F, /* 142 - RosyBrown */
0xFF4169E1, /* 143 - RoyalBlue */
0xFF8B4513, /* 144 - SaddleBrown */
0xFFFA8072, /* 145 - Salmon */
0xFFF4A460, /* 146 - SandyBrown */
0xFF2E8B57, /* 147 - SeaGreen */
0xFFFFF5EE, /* 148 - SeaShell */
0xFFA0522D, /* 149 - Sienna */
0xFFC0C0C0, /* 150 - Silver */
0xFF87CEEB, /* 151 - SkyBlue */
0xFF6A5ACD, /* 152 - SlateBlue */
0xFF708090, /* 153 - SlateGray */
0xFFFFFAFA, /* 154 - Snow */
0xFF00FF7F, /* 155 - SpringGreen */
0xFF4682B4, /* 156 - SteelBlue */
0xFFD2B48C, /* 157 - Tan */
0xFF008080, /* 158 - Teal */
0xFFD8BFD8, /* 159 - Thistle */
0xFFFF6347, /* 160 - Tomato */
0xFF40E0D0, /* 161 - Turquoise */
0xFFEE82EE, /* 162 - Violet */
0xFFF5DEB3, /* 163 - Wheat */
0xFFFFFFFF, /* 164 - White */
0xFFF5F5F5, /* 165 - WhiteSmoke */
0xFFFFFF00, /* 166 - Yellow */
0xFF9ACD32, /* 167 - YellowGreen */
#if NET_2_0
0xFFECE9D8, /* 168 - ButtonFace */
0xFFFFFFFF, /* 169 - ButtonHighlight */
0xFFACA899, /* 170 - ButtonShadow */
0xFF3D95FF, /* 171 - GradientActiveCaption */
0xFF9DB9EB, /* 172 - GradientInactiveCaption */
0xFFECE9D8, /* 173 - MenuBar */
0xFF316AC5, /* 174 - MenuHighlight */
#endif
};
static KnownColors ()
{
/*if (GDIPlus.RunningOnWindows ()) {
// If we're on Windows we should behave like MS and pull the colors
RetrieveWindowsSystemColors ();
}*/
// note: Mono's SWF Theme class will call the static Update method to apply
// correct system colors outside Windows
}
// Windows values are in BGR format and without alpha
// so we force it to opaque (or everything will be transparent) and reverse B and R
/*static uint GetSysColor (GetSysColorIndex index)
{
uint bgr = GDIPlus.Win32GetSysColor (index);
return 0xFF000000 | (bgr & 0xFF) << 16 | (bgr & 0xFF00) | (bgr >> 16);
}*/
static void RetrieveWindowsSystemColors ()
{
/*
ArgbValues [(int)KnownColor.ActiveBorder] = GetSysColor (GetSysColorIndex.COLOR_ACTIVEBORDER);
ArgbValues [(int)KnownColor.ActiveCaption] = GetSysColor (GetSysColorIndex.COLOR_ACTIVECAPTION);
ArgbValues [(int)KnownColor.ActiveCaptionText] = GetSysColor (GetSysColorIndex.COLOR_CAPTIONTEXT);
ArgbValues [(int)KnownColor.AppWorkspace] = GetSysColor (GetSysColorIndex.COLOR_APPWORKSPACE);
ArgbValues [(int)KnownColor.Control] = GetSysColor (GetSysColorIndex.COLOR_BTNFACE);
ArgbValues [(int)KnownColor.ControlDark] = GetSysColor (GetSysColorIndex.COLOR_BTNSHADOW);
ArgbValues [(int)KnownColor.ControlDarkDark] = GetSysColor (GetSysColorIndex.COLOR_3DDKSHADOW);
ArgbValues [(int)KnownColor.ControlLight] = GetSysColor (GetSysColorIndex.COLOR_3DLIGHT);
ArgbValues [(int)KnownColor.ControlLightLight] = GetSysColor (GetSysColorIndex.COLOR_BTNHIGHLIGHT);
ArgbValues [(int)KnownColor.ControlText] = GetSysColor (GetSysColorIndex.COLOR_BTNTEXT);
ArgbValues [(int)KnownColor.Desktop] = GetSysColor (GetSysColorIndex.COLOR_DESKTOP);
ArgbValues [(int)KnownColor.GrayText] = GetSysColor (GetSysColorIndex.COLOR_GRAYTEXT);
ArgbValues [(int)KnownColor.Highlight] = GetSysColor (GetSysColorIndex.COLOR_HIGHLIGHT);
ArgbValues [(int)KnownColor.HighlightText] = GetSysColor (GetSysColorIndex.COLOR_HIGHLIGHTTEXT);
ArgbValues [(int)KnownColor.HotTrack] = GetSysColor (GetSysColorIndex.COLOR_HOTLIGHT);
ArgbValues [(int)KnownColor.InactiveBorder] = GetSysColor (GetSysColorIndex.COLOR_INACTIVEBORDER);
ArgbValues [(int)KnownColor.InactiveCaption] = GetSysColor (GetSysColorIndex.COLOR_INACTIVECAPTION);
ArgbValues [(int)KnownColor.InactiveCaptionText] = GetSysColor (GetSysColorIndex.COLOR_INACTIVECAPTIONTEXT);
ArgbValues [(int)KnownColor.Info] = GetSysColor (GetSysColorIndex.COLOR_INFOBK);
ArgbValues [(int)KnownColor.InfoText] = GetSysColor (GetSysColorIndex.COLOR_INFOTEXT);
ArgbValues [(int)KnownColor.Menu] = GetSysColor (GetSysColorIndex.COLOR_MENU);
ArgbValues [(int)KnownColor.MenuText] = GetSysColor (GetSysColorIndex.COLOR_MENUTEXT);
ArgbValues [(int)KnownColor.ScrollBar] = GetSysColor (GetSysColorIndex.COLOR_SCROLLBAR);
ArgbValues [(int)KnownColor.Window] = GetSysColor (GetSysColorIndex.COLOR_WINDOW);
ArgbValues [(int)KnownColor.WindowFrame] = GetSysColor (GetSysColorIndex.COLOR_WINDOWFRAME);
ArgbValues [(int)KnownColor.WindowText] = GetSysColor (GetSysColorIndex.COLOR_WINDOWTEXT);
*/
#if NET_2_0
ArgbValues [(int)KnownColor.ButtonFace] = GetSysColor (GetSysColorIndex.COLOR_BTNFACE);
ArgbValues [(int)KnownColor.ButtonHighlight] = GetSysColor (GetSysColorIndex.COLOR_BTNHIGHLIGHT);
ArgbValues [(int)KnownColor.ButtonShadow] = GetSysColor (GetSysColorIndex.COLOR_BTNSHADOW);
ArgbValues [(int)KnownColor.GradientActiveCaption] = GetSysColor (GetSysColorIndex.COLOR_GRADIENTACTIVECAPTION);
ArgbValues [(int)KnownColor.GradientInactiveCaption] = GetSysColor (GetSysColorIndex.COLOR_GRADIENTINACTIVECAPTION);
ArgbValues [(int)KnownColor.MenuBar] = GetSysColor (GetSysColorIndex.COLOR_MENUBAR);
ArgbValues [(int)KnownColor.MenuHighlight] = GetSysColor (GetSysColorIndex.COLOR_MENUHIGHLIGHT);
#endif
}
public static Color FromKnownColor (KnownColor kc)
{
Color c;
short n = (short)kc;
if ((n <= 0) || (n >= ArgbValues.Length)) {
// This is what it returns!
c = Color.FromArgb (0, 0, 0, 0);
#if ONLY_1_1
c.name = kc.ToString ();
#endif
c.state |= (short) Color.ColorType.Named;
} else {
c = new Color ();
c.state = (short) (Color.ColorType.ARGB | Color.ColorType.Known | Color.ColorType.Named);
if ((n < 27) || (n > 169))
c.state |= (short) Color.ColorType.System;
c.Value = ArgbValues [n];
#if ONLY_1_1
c.name = GetName (n);
#endif
}
c.knownColor = n;
return c;
}
public static string GetName (short kc)
{
switch (kc) {
case 1: return "ActiveBorder";
case 2: return "ActiveCaption";
case 3: return "ActiveCaptionText";
case 4: return "AppWorkspace";
case 5: return "Control";
case 6: return "ControlDark";
case 7: return "ControlDarkDark";
case 8: return "ControlLight";
case 9: return "ControlLightLight";
case 10: return "ControlText";
case 11: return "Desktop";
case 12: return "GrayText";
case 13: return "Highlight";
case 14: return "HighlightText";
case 15: return "HotTrack";
case 16: return "InactiveBorder";
case 17: return "InactiveCaption";
case 18: return "InactiveCaptionText";
case 19: return "Info";
case 20: return "InfoText";
case 21: return "Menu";
case 22: return "MenuText";
case 23: return "ScrollBar";
case 24: return "Window";
case 25: return "WindowFrame";
case 26: return "WindowText";
case 27: return "Transparent";
case 28: return "AliceBlue";
case 29: return "AntiqueWhite";
case 30: return "Aqua";
case 31: return "Aquamarine";
case 32: return "Azure";
case 33: return "Beige";
case 34: return "Bisque";
case 35: return "Black";
case 36: return "BlanchedAlmond";
case 37: return "Blue";
case 38: return "BlueViolet";
case 39: return "Brown";
case 40: return "BurlyWood";
case 41: return "CadetBlue";
case 42: return "Chartreuse";
case 43: return "Chocolate";
case 44: return "Coral";
case 45: return "CornflowerBlue";
case 46: return "Cornsilk";
case 47: return "Crimson";
case 48: return "Cyan";
case 49: return "DarkBlue";
case 50: return "DarkCyan";
case 51: return "DarkGoldenrod";
case 52: return "DarkGray";
case 53: return "DarkGreen";
case 54: return "DarkKhaki";
case 55: return "DarkMagenta";
case 56: return "DarkOliveGreen";
case 57: return "DarkOrange";
case 58: return "DarkOrchid";
case 59: return "DarkRed";
case 60: return "DarkSalmon";
case 61: return "DarkSeaGreen";
case 62: return "DarkSlateBlue";
case 63: return "DarkSlateGray";
case 64: return "DarkTurquoise";
case 65: return "DarkViolet";
case 66: return "DeepPink";
case 67: return "DeepSkyBlue";
case 68: return "DimGray";
case 69: return "DodgerBlue";
case 70: return "Firebrick";
case 71: return "FloralWhite";
case 72: return "ForestGreen";
case 73: return "Fuchsia";
case 74: return "Gainsboro";
case 75: return "GhostWhite";
case 76: return "Gold";
case 77: return "Goldenrod";
case 78: return "Gray";
case 79: return "Green";
case 80: return "GreenYellow";
case 81: return "Honeydew";
case 82: return "HotPink";
case 83: return "IndianRed";
case 84: return "Indigo";
case 85: return "Ivory";
case 86: return "Khaki";
case 87: return "Lavender";
case 88: return "LavenderBlush";
case 89: return "LawnGreen";
case 90: return "LemonChiffon";
case 91: return "LightBlue";
case 92: return "LightCoral";
case 93: return "LightCyan";
case 94: return "LightGoldenrodYellow";
case 95: return "LightGray";
case 96: return "LightGreen";
case 97: return "LightPink";
case 98: return "LightSalmon";
case 99: return "LightSeaGreen";
case 100: return "LightSkyBlue";
case 101: return "LightSlateGray";
case 102: return "LightSteelBlue";
case 103: return "LightYellow";
case 104: return "Lime";
case 105: return "LimeGreen";
case 106: return "Linen";
case 107: return "Magenta";
case 108: return "Maroon";
case 109: return "MediumAquamarine";
case 110: return "MediumBlue";
case 111: return "MediumOrchid";
case 112: return "MediumPurple";
case 113: return "MediumSeaGreen";
case 114: return "MediumSlateBlue";
case 115: return "MediumSpringGreen";
case 116: return "MediumTurquoise";
case 117: return "MediumVioletRed";
case 118: return "MidnightBlue";
case 119: return "MintCream";
case 120: return "MistyRose";
case 121: return "Moccasin";
case 122: return "NavajoWhite";
case 123: return "Navy";
case 124: return "OldLace";
case 125: return "Olive";
case 126: return "OliveDrab";
case 127: return "Orange";
case 128: return "OrangeRed";
case 129: return "Orchid";
case 130: return "PaleGoldenrod";
case 131: return "PaleGreen";
case 132: return "PaleTurquoise";
case 133: return "PaleVioletRed";
case 134: return "PapayaWhip";
case 135: return "PeachPuff";
case 136: return "Peru";
case 137: return "Pink";
case 138: return "Plum";
case 139: return "PowderBlue";
case 140: return "Purple";
case 141: return "Red";
case 142: return "RosyBrown";
case 143: return "RoyalBlue";
case 144: return "SaddleBrown";
case 145: return "Salmon";
case 146: return "SandyBrown";
case 147: return "SeaGreen";
case 148: return "SeaShell";
case 149: return "Sienna";
case 150: return "Silver";
case 151: return "SkyBlue";
case 152: return "SlateBlue";
case 153: return "SlateGray";
case 154: return "Snow";
case 155: return "SpringGreen";
case 156: return "SteelBlue";
case 157: return "Tan";
case 158: return "Teal";
case 159: return "Thistle";
case 160: return "Tomato";
case 161: return "Turquoise";
case 162: return "Violet";
case 163: return "Wheat";
case 164: return "White";
case 165: return "WhiteSmoke";
case 166: return "Yellow";
case 167: return "YellowGreen";
#if NET_2_0
case 168: return "ButtonFace";
case 169: return "ButtonHighlight";
case 170: return "ButtonShadow";
case 171: return "GradientActiveCaption";
case 172: return "GradientInactiveCaption";
case 173: return "MenuBar";
case 174: return "MenuHighlight";
#endif
default: return String.Empty;
}
}
public static string GetName (KnownColor kc)
{
return GetName ((short)kc);
}
// FIXME: Linear scan
public static Color FindColorMatch (Color c)
{
uint argb = (uint) c.ToArgb ();
// 1-based
const int first_real_color_index = (int) KnownColor.AliceBlue;
const int last_real_color_index = (int) KnownColor.YellowGreen;
for (int i = first_real_color_index - 1; i < last_real_color_index; i++) {
if (argb == KnownColors.ArgbValues [i])
return KnownColors.FromKnownColor ((KnownColor)i);
}
return Color.Empty;
}
// When this method is called, we teach any new color(s) to the Color class
// NOTE: This is called (reflection) by System.Windows.Forms.Theme (this isn't dead code)
public static void Update (int knownColor, int color)
{
ArgbValues[knownColor] = (uint)color;
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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 Aurora.Framework;
using System;
using System.Collections.Generic;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Services.Interfaces
{
public class CachedUserInfo : IDataTransferable
{
public IAgentInfo AgentInfo;
public UserAccount UserAccount;
public GroupMembershipData ActiveGroup;
public List<GroupMembershipData> GroupMemberships = new List<GroupMembershipData>();
public override void FromOSD(OSDMap map)
{
AgentInfo = new IAgentInfo();
AgentInfo.FromOSD((OSDMap)(map["AgentInfo"]));
UserAccount = new UserAccount();
UserAccount.FromOSD((OSDMap)(map["UserAccount"]));
if (!map.ContainsKey("ActiveGroup"))
ActiveGroup = null;
else
{
ActiveGroup = new GroupMembershipData();
ActiveGroup.FromOSD((OSDMap)(map["ActiveGroup"]));
}
GroupMemberships = ((OSDArray)map["GroupMemberships"]).ConvertAll<GroupMembershipData>((o) =>
{
GroupMembershipData group = new GroupMembershipData();
group.FromOSD((OSDMap)o);
return group;
});
}
public override OSDMap ToOSD()
{
OSDMap map = new OSDMap();
map["AgentInfo"] = AgentInfo.ToOSD();
map["UserAccount"] = UserAccount.ToOSD();
if(ActiveGroup != null)
map["ActiveGroup"] = ActiveGroup.ToOSD();
map["GroupMemberships"] = GroupMemberships.ToOSDArray();
return map;
}
}
public interface ISimulationService
{
#region Local Initalization
/// <summary>
/// Add and set up the scene for the simulation module
/// </summary>
/// <param name = "scene"></param>
void Init(IScene scene);
/// <summary>
/// Remove the scene from the list of known scenes
/// </summary>
/// <param name = "scene"></param>
void RemoveScene(IScene scene);
/// <summary>
/// Try to find a scene with the given region handle
/// </summary>
/// <param name = "regionHandle"></param>
/// <returns></returns>
IScene GetScene(ulong regionHandle);
/// <summary>
/// Get the 'inner' simulation service.
/// For the remote simulation service, this gives the local simulation service.
/// For the local simulation service. this gives the same service as it is already the local service.
/// </summary>
/// <returns></returns>
ISimulationService GetInnerService();
#endregion
#region Agents
/// <summary>
/// Create an agent at the given destination
/// Grid Server only.
/// </summary>
/// <param name = "destination"></param>
/// <param name = "aCircuit"></param>
/// <param name = "teleportFlags"></param>
/// <param name = "data"></param>
/// <param name = "reason"></param>
/// <returns></returns>
bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, AgentData data,
out int requestedUDPPort, out string reason);
/// <summary>
/// Full child agent update.
/// Grid Server only.
/// </summary>
/// <param name = "regionHandle"></param>
/// <param name = "data"></param>
/// <returns></returns>
bool UpdateAgent(GridRegion destination, AgentData data);
/// <summary>
/// Short child agent update, mostly for position.
/// Grid Server only.
/// </summary>
/// <param name = "regionHandle"></param>
/// <param name = "data"></param>
/// <returns></returns>
bool UpdateAgent(GridRegion destination, AgentPosition data);
/// <summary>
/// Pull the root agent info from the given destination
/// Grid Server only.
/// </summary>
/// <param name = "destination"></param>
/// <param name = "id"></param>
/// <param name = "agent"></param>
/// <param name = "circuitData"></param>
/// <returns></returns>
bool RetrieveAgent(GridRegion destination, UUID id, bool agentIsLeaving, out AgentData agent,
out AgentCircuitData circuitData);
/// <summary>
/// Close agent.
/// Grid Server only.
/// </summary>
/// <param name = "regionHandle"></param>
/// <param name = "id"></param>
/// <returns></returns>
bool CloseAgent(GridRegion destination, UUID id);
/// <summary>
/// Makes a root agent into a child agent in the given region
/// DOES mark the agent as leaving (removes attachments among other things)
/// </summary>
/// <param name = "AgentID"></param>
/// <param name = "Region"></param>
bool MakeChildAgent(UUID AgentID, UUID leavingRegion, GridRegion Region, bool markAgentAsLeaving);
/// <summary>
/// Tells the region that the agent was not able to leave the region and needs to be resumed
/// </summary>
/// <param name = "AgentID"></param>
/// <param name = "RegionID"></param>
bool FailedToMoveAgentIntoNewRegion(UUID AgentID, UUID RegionID);
#endregion Agents
#region Objects
/// <summary>
/// Create an object in the destination region. This message is used primarily for prim crossing.
/// </summary>
/// <param name = "regionHandle"></param>
/// <param name = "sog"></param>
/// <returns></returns>
bool CreateObject(GridRegion destination, ISceneObject sog);
/// <summary>
/// Create an object from the user's inventory in the destination region.
/// This message is used primarily by clients for attachments.
/// </summary>
/// <param name = "regionHandle"></param>
/// <param name = "userID"></param>
/// <param name = "itemID"></param>
/// <returns></returns>
bool CreateObject(GridRegion destination, UUID userID, UUID itemID);
#endregion Objects
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: __ComObject
**
**
** __ComObject is the root class for all COM wrappers. This class
** defines only the basics. This class is used for wrapping COM objects
** accessed from COM+
**
**
===========================================================*/
namespace System {
using System;
using System.Collections;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Security.Permissions;
internal class __ComObject : MarshalByRefObject
{
private Hashtable m_ObjectToDataMap;
/*============================================================
** default constructor
** can't instantiate this directly
=============================================================*/
protected __ComObject ()
{
}
//====================================================================
// Overrides ToString() to make sure we call to IStringable if the
// COM object implements it in the case of weakly typed RCWs
//====================================================================
public override string ToString()
{
//
// Only do the IStringable cast when running under AppX for better compat
// Otherwise we could do a IStringable cast in classic apps which could introduce
// a thread transition which would lead to deadlock
//
if (AppDomain.IsAppXModel())
{
// Check whether the type implements IStringable.
IStringable stringableType = this as IStringable;
if (stringableType != null)
{
return stringableType.ToString();
}
}
return base.ToString();
}
[System.Security.SecurityCritical] // auto-generated
internal IntPtr GetIUnknown(out bool fIsURTAggregated)
{
fIsURTAggregated = !GetType().IsDefined(typeof(ComImportAttribute), false);
return System.Runtime.InteropServices.Marshal.GetIUnknownForObject(this);
}
//====================================================================
// This method retrieves the data associated with the specified
// key if any such data exists for the current __ComObject.
//====================================================================
internal Object GetData(Object key)
{
Object data = null;
// Synchronize access to the map.
lock(this)
{
// If the map hasn't been allocated, then there can be no data for the specified key.
if (m_ObjectToDataMap != null)
{
// Look up the data in the map.
data = m_ObjectToDataMap[key];
}
}
return data;
}
//====================================================================
// This method sets the data for the specified key on the current
// __ComObject.
//====================================================================
internal bool SetData(Object key, Object data)
{
bool bAdded = false;
// Synchronize access to the map.
lock(this)
{
// If the map hasn't been allocated yet, allocate it.
if (m_ObjectToDataMap == null)
m_ObjectToDataMap = new Hashtable();
// If there isn't already data in the map then add it.
if (m_ObjectToDataMap[key] == null)
{
m_ObjectToDataMap[key] = data;
bAdded = true;
}
}
return bAdded;
}
//====================================================================
// This method is called from within the EE and releases all the
// cached data for the __ComObject.
//====================================================================
[System.Security.SecurityCritical] // auto-generated
internal void ReleaseAllData()
{
// Synchronize access to the map.
lock(this)
{
// If the map hasn't been allocated, then there is nothing to do.
if (m_ObjectToDataMap != null)
{
foreach (Object o in m_ObjectToDataMap.Values)
{
// Note: the value could be an object[]
// We are fine for now as object[] doesn't implement IDisposable nor derive from __ComObject
// If the object implements IDisposable, then call Dispose on it.
IDisposable DisposableObj = o as IDisposable;
if (DisposableObj != null)
DisposableObj.Dispose();
// If the object is a derived from __ComObject, then call Marshal.ReleaseComObject on it.
__ComObject ComObj = o as __ComObject;
if (ComObj != null)
Marshal.ReleaseComObject(ComObj);
}
// Set the map to null to indicate it has been cleaned up.
m_ObjectToDataMap = null;
}
}
}
//====================================================================
// This method is called from within the EE and is used to handle
// calls on methods of event interfaces.
//====================================================================
[System.Security.SecurityCritical] // auto-generated
internal Object GetEventProvider(RuntimeType t)
{
// Check to see if we already have a cached event provider for this type.
Object EvProvider = GetData(t);
// If we don't then we need to create one.
if (EvProvider == null)
EvProvider = CreateEventProvider(t);
return EvProvider;
}
[System.Security.SecurityCritical] // auto-generated
internal int ReleaseSelf()
{
return Marshal.InternalReleaseComObject(this);
}
[System.Security.SecurityCritical] // auto-generated
internal void FinalReleaseSelf()
{
Marshal.InternalFinalReleaseComObject(this);
}
[System.Security.SecurityCritical] // auto-generated
#if !FEATURE_CORECLR
[ReflectionPermissionAttribute(SecurityAction.Assert, MemberAccess=true)]
#endif
private Object CreateEventProvider(RuntimeType t)
{
// Create the event provider for the specified type.
Object EvProvider = Activator.CreateInstance(t, Activator.ConstructorDefault | BindingFlags.NonPublic, null, new Object[]{this}, null);
// Attempt to cache the wrapper on the object.
if (!SetData(t, EvProvider))
{
// Dispose the event provider if it implements IDisposable.
IDisposable DisposableEvProv = EvProvider as IDisposable;
if (DisposableEvProv != null)
DisposableEvProv.Dispose();
// Another thead already cached the wrapper so use that one instead.
EvProvider = GetData(t);
}
return EvProvider;
}
}
}
| |
using FILE = System.IO.TextWriter;
using System;
#region Limits
#if !MAX_VARIABLE_NUMBER
using ynVar = System.Int16;
#else
using ynVar = System.Int32;
#endif
#if MAX_ATTACHED
using yDbMask = System.Int64;
#else
using yDbMask = System.Int32;
#endif
#endregion
namespace Core
{
public class Blob { }
public partial class Vdbe
{
const int COLNAME_NAME = 0;
const int COLNAME_DECLTYPE = 1;
const int COLNAME_DATABASE = 2;
const int COLNAME_TABLE = 3;
const int COLNAME_COLUMN = 4;
#if ENABLE_COLUMN_METADATA
const int COLNAME_N = 5; // Number of COLNAME_xxx symbols
#else
#if OMIT_DECLTYPE
const int COLNAME_N = 1; // Number of COLNAME_xxx symbols
#else
const int COLNAME_N = 2;
#endif
#endif
static int ADDR(int x) { return -1 - x; }
public enum STMTSTATUS : byte
{
FULLSCAN_STEP = 1,
SORT = 2,
AUTOINDEX = 3,
}
public enum P4T : sbyte
{
NOTUSED = 0, // The P4 parameter is not used
DYNAMIC = -1, // Pointer to a string obtained from sqliteMalloc=();
STATIC = -2, // Pointer to a static string
COLLSEQ = -4, // P4 is a pointer to a CollSeq structure
FUNCDEF = -5, // P4 is a pointer to a FuncDef structure
KEYINFO = -6, // P4 is a pointer to a KeyInfo structure
VDBEFUNC = -7, // P4 is a pointer to a VdbeFunc structure
MEM = -8, // P4 is a pointer to a Mem* structure
TRANSIENT = 0, // P4 is a pointer to a transient string
VTAB = 10, // P4 is a pointer to an sqlite3_vtab structure
MPRINTF = -11, // P4 is a string obtained from sqlite3_mprintf=();
REAL = -12, // P4 is a 64-bit floating point value
INT64 = -13, // P4 is a 64-bit signed integer
INT32 = -14, // P4 is a 32-bit signed integer
INTARRAY = -15, // P4 is a vector of 32-bit integers
SUBPROGRAM = -18, // P4 is a pointer to a SubProgram structure
ADVANCE = -19, // P4 is a pointer to BtreeNext() or BtreePrev()
// When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure is made. That copy is freed when the Vdbe is finalized. But if the
// argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still gets freed when the Vdbe is finalized so it still should be obtained
// from a single sqliteMalloc(). But no copy is made and the calling function should *not* try to free the KeyInfo.
KEYINFO_HANDOFF = -16,
KEYINFO_STATIC = -17,
}
public enum OPFLAG : byte
{
NCHANGE = 0x01, // Set to update db->nChange
LASTROWID = 0x02, // Set to update db->lastRowid
ISUPDATE = 0x04, // This OP_Insert is an sql UPDATE
APPEND = 0x08, // This is likely to be an append
USESEEKRESULT = 0x10, // Try to avoid a seek in BtreeInsert()
CLEARCACHE = 0x20, // Clear pseudo-table cache in OP_Column
LENGTHARG = 0x40, // OP_Column only used for length()
TYPEOFARG = 0x80, // OP_Column only used for typeof()
BULKCSR = 0x01, // OP_Open** used to open bulk cursor
P2ISREG = 0x02, // P2 to OP_Open** is a register number
PERMUTE = 0x01, // OP_Compare: use the permutation
}
public class VdbeOp
{
public delegate RC AdvanceDelegate_t(Btree.BtCursor cur, ref int res);
public OP Opcode; // What operation to perform
public P4T P4Type; // One of the P4_xxx constants for p4
public OPFLG Opflags; // Mask of the OPFLG_* flags in opcodes.h
public byte P5; // Fifth parameter is an unsigned character
public int P1; // First operand
public int P2; // Second parameter (often the jump destination)
public int P3; // The third parameter
public class P4_t
{
public int I; // Integer value if p4type==P4_INT32
public object P; // Generic pointer
public string Z; // Pointer to data for string (char array) types
public long I64; // Used when p4type is P4T_INT64
public double Real; // Used when p4type is P4T_REAL
public FuncDef Func; // Used when p4type is P4T_FUNCDEF
public VdbeFunc VdbeFunc; // Used when p4type is P4T_VDBEFUNC
public CollSeq Coll; // Used when p4type is P4T_COLLSEQ
public Mem Mem; // Used when p4type is P4T_MEM
public VTable VTable; // Used when p4type is P4T_VTAB
public KeyInfo KeyInfo; // Used when p4type is P4T_KEYINFO
public int[] Is; // Used when p4type is P4T_INTARRAY
public SubProgram Program; // Used when p4type is P4T_SUBPROGRAM
public VdbeOp.AdvanceDelegate_t Advance; // Used when p4type is P4T_ADVANCE
}
public P4_t P4 = new P4_t(); // fourth parameter
#if DEBUG
public string Comment; // Comment to improve readability
#endif
#if VDBE_PROFILE
public int Cnt; // Number of times this instruction was executed
public ulong Cycles; // Total time spend executing this instruction
#endif
public void _memset()
{
Opcode = 0;
P4Type = 0;
P5 = 0;
P1 = 0;
P2 = 0;
P3 = 0;
P4 = new P4_t();
#if DEBUG
Comment = null;
#endif
#if VDBE_PROFILE
Cnt = 0;
Cycles = 0;
#endif
}
}
public class SubProgram
{
public array_t<VdbeOp> Ops; // Array of opcodes for sub-program
public int Mems; // Number of memory cells required
public int Csrs; // Number of cursors required
public int Onces; // Number of OP_Once instructions
public int Token; // id that may be used to recursive triggers
public SubProgram Next; // Next sub-program already visited
}
public struct VdbeOpList
{
public OP Opcode; // What operation to perform
public int P1; // First operand
public int P2; // Second parameter (often the jump destination)
public int P3; // Third parameter
public VdbeOpList(OP opcode, int p1, int p2, int p3)
{
Opcode = opcode;
P1 = p1;
P2 = p2;
P3 = p3;
}
}
//#if OMIT_FLOATING_POINT
////# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
//#else
// //void sqlite3VdbeMemSetDouble(Mem*, double);
//#endif
//#if !OMIT_SHARED_CACHE && THREADSAFE
// //void Enter(Vdbe);
// //void Leave(Vdbe);
//#else
// static void Enter( Vdbe p ) { }
// static void Leave( Vdbe p ) { }
//#endif
//#if !OMIT_FOREIGN_KEY
// //int sqlite3VdbeCheckFk(Vdbe *, int);
//#else
// static int sqlite3VdbeCheckFk(Vdbe p, int i) { return 0; }
//#endif
//#if !OMIT_INCRBLOB
// // int sqlite3VdbeMemExpandBlob(Mem);
//#else
// static RC sqlite3VdbeMemExpandBlob(Mem x) { return RC.OK; }
//#endif
public Context Ctx; // The database connection that owns this statement
public array_t<VdbeOp> Ops; // Space to hold the virtual machine's program
public array_t<Mem> Mems; // The memory locations
public Mem[] Args; // Arguments to currently executing user function
public Mem[] ColNames; // Column names to return
public Mem[] ResultSet; // Pointer to an array of results
public int OpsAlloc; // Number of slots allocated for aOp[]
public int LabelsAlloc; // Number of slots allocated in aLabel[]
public array_t<int> Labels; // Space to hold the labels
public ushort ResColumns; // Number of columns in one row of the result set
public uint Magic; // Magic number for sanity checking
public string ErrMsg; // Error message written here
public Vdbe Prev, Next; // Linked list of VDBEs with the same Vdbe.db
public array_t<VdbeCursor> Cursors; // One element of this array for each open cursor
public array_t2<ynVar, Mem> Vars; // Values for the OP_Variable opcode.
public array_t2<ynVar, string> VarNames; // Name of variables
public uint CacheCtr; // VdbeCursor row cache generation counter
public int PC; // The program counter
public RC RC_; // Value to return
public OE ErrorAction; // Recovery action to do in case of an error
public int MinWriteFileFormat; // Minimum file format for writable database files
public byte HasExplain; // True if EXPLAIN present on SQL command
public byte InVtabMethod; // See comments above
public bool ChangeCntOn; // True to update the change-counter
public bool Expired; // True if the VM needs to be recompiled
public bool RunOnlyOnce; // Automatically expire on reset
public bool UsesStmtJournal; // True if uses a statement journal
public bool ReadOnly; // True for read-only statements
public bool IsPrepareV2; // True if prepared with prepare_v2()
public bool DoingRerun; // True if rerunning after an auto-reprepare
public int Changes; // Number of db changes made since last reset
public yDbMask BtreeMask; // Bitmask of db.aDb[] entries referenced
public yDbMask LockMask; // Subset of btreeMask that requires a lock
public int StatementID; // Statement number (or 0 if has not opened stmt)
public int[] Counters = new int[3]; // Counters used by sqlite3_stmt_status()
#if !OMIT_TRACE
public long StartTime; // Time when query started - used for profiling
#endif
public long FkConstraints; // Number of imm. FK constraints this VM
public long StmtDefCons; // Number of def. constraints when stmt started
public string Sql_; // Text of the SQL statement that generated this
public object FreeThis; // Free this when deleting the vdbe
#if DEBUG
public FILE Trace; // Write an execution trace here, if not NULL
#endif
#if ENABLE_TREE_EXPLAIN
Explain _explain; // The explainer
string _explainString; // Explanation of data structures
#endif
public VdbeFrame Frames; // Parent frame
public int FramesLength; // Number of frames in Frames list
public VdbeFrame DelFrames; // List of frame objects to free on VM reset
public uint Expmask; // Binding to these vars invalidates VM
public SubProgram Programs; // Linked list of all sub-programs used by VM
public array_t<byte> OnceFlags; // Flags for OP_Once
public Vdbe _memcpy() { return (Vdbe)MemberwiseClone(); }
public void _memcpy(Vdbe ct)
{
ct.Ctx = Ctx;
ct.Ops = Ops; //ct.Ops.length = Ops.length;
ct.Mems = Mems; //ct.Mems.length = Mems.length;
ct.Args = Args; //ct.Args.length = Args.length;
ct.ColNames = ColNames;
ct.ResultSet = ResultSet;
ct.OpsAlloc = OpsAlloc;
ct.LabelsAlloc = LabelsAlloc;
ct.Labels = Labels; //ct.Labels.length = Labels.length;
ct.ResColumns = ResColumns;
ct.Magic = Magic;
ct.ErrMsg = ErrMsg;
ct.Prev = Prev; ct.Next = Next;
ct.Cursors = Cursors; //ct.Cursors.length = Cursors.length;
ct.Vars = Vars; ct.Vars.length = Vars.length;
ct.VarNames = VarNames; ct.VarNames.length = VarNames.length;
ct.CacheCtr = CacheCtr;
ct.PC = PC;
ct.RC_ = RC_;
ct.ErrorAction = ErrorAction;
ct.MinWriteFileFormat = MinWriteFileFormat;
ct.HasExplain = HasExplain;
ct.InVtabMethod = InVtabMethod;
ct.ChangeCntOn = ChangeCntOn;
ct.Expired = Expired;
ct.RunOnlyOnce = RunOnlyOnce;
ct.UsesStmtJournal = UsesStmtJournal;
ct.ReadOnly = ReadOnly;
ct.IsPrepareV2 = IsPrepareV2;
ct.DoingRerun = DoingRerun;
ct.Changes = Changes;
ct.BtreeMask = BtreeMask;
ct.LockMask = LockMask;
ct.StatementID = StatementID;
Counters.CopyTo(ct.Counters, 0);
#if !OMIT_TRACE
ct.StartTime = StartTime;
#endif
ct.FkConstraints = FkConstraints;
ct.StmtDefCons = StmtDefCons;
ct.Sql_ = Sql_;
ct.FreeThis = FreeThis;
#if DEBUG
ct.Trace = Trace;
#endif
#if ENABLE_TREE_EXPLAIN
ct._explain = _explain;
ct._explainString = _explainString;
#endif
ct.Frames = Frames;
ct.DelFrames = DelFrames;
ct.Expmask = Expmask;
ct.Programs = Programs;
ct.OnceFlags = OnceFlags;
}
const uint VDBE_MAGIC_INIT = 0x26bceaa5; // Building a VDBE program
const uint VDBE_MAGIC_RUN = 0xbdf20da3; // VDBE is ready to execute
const uint VDBE_MAGIC_HALT = 0x519c2973; // VDBE has completed execution
const uint VDBE_MAGIC_DEAD = 0xb606c3c8; // The VDBE has been deallocated
}
public partial class E
{
#if !OMIT_INCRBLOB
public static RC ExpandBlob(Mem P) { return ((P.Flags & MEM.Zero) != 0 ? Vdbe.MemExpandBlob(P) : 0); }
#else
public static RC ExpandBlob(Mem P) { return RC.OK; }
#endif
public static void VdbeMemRelease(Mem X) { if ((X.Flags & (MEM.Agg | MEM.Dyn | MEM.RowSet | MEM.Frame)) != 0) Vdbe.MemReleaseExternal(X); }
}
}
| |
/********************************************************
* ADO.NET 2.0 Data Provider for SQLite Version 3.X
* Written by Robert Simpson (robert@blackcastlesoft.com)
*
* Released to the public domain, use at your own risk!
********************************************************/
namespace Mono.Data.Sqlite
{
using System;
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using System.ComponentModel;
/// <summary>
/// SQLite implementation of DbCommand.
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[Designer("SQLite.Designer.SqliteCommandDesigner, SQLite.Designer, Version=1.0.36.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139"), ToolboxItem(true)]
#endif
public sealed class SqliteCommand : DbCommand, ICloneable
{
/// <summary>
/// The command text this command is based on
/// </summary>
private string _commandText;
/// <summary>
/// The connection the command is associated with
/// </summary>
private SqliteConnection _cnn;
/// <summary>
/// The version of the connection the command is associated with
/// </summary>
private long _version;
/// <summary>
/// Indicates whether or not a DataReader is active on the command.
/// </summary>
private WeakReference _activeReader;
/// <summary>
/// The timeout for the command, kludged because SQLite doesn't support per-command timeout values
/// </summary>
internal int _commandTimeout;
/// <summary>
/// Designer support
/// </summary>
private bool _designTimeVisible;
/// <summary>
/// Used by DbDataAdapter to determine updating behavior
/// </summary>
private UpdateRowSource _updateRowSource;
/// <summary>
/// The collection of parameters for the command
/// </summary>
private SqliteParameterCollection _parameterCollection;
/// <summary>
/// The SQL command text, broken into individual SQL statements as they are executed
/// </summary>
internal List<SqliteStatement> _statementList;
/// <summary>
/// Unprocessed SQL text that has not been executed
/// </summary>
internal string _remainingText;
/// <summary>
/// Transaction associated with this command
/// </summary>
private SqliteTransaction _transaction;
///<overloads>
/// Constructs a new SqliteCommand
/// </overloads>
/// <summary>
/// Default constructor
/// </summary>
public SqliteCommand() :this(null, null)
{
}
/// <summary>
/// Initializes the command with the given command text
/// </summary>
/// <param name="commandText">The SQL command text</param>
public SqliteCommand(string commandText)
: this(commandText, null, null)
{
}
/// <summary>
/// Initializes the command with the given SQL command text and attach the command to the specified
/// connection.
/// </summary>
/// <param name="commandText">The SQL command text</param>
/// <param name="connection">The connection to associate with the command</param>
public SqliteCommand(string commandText, SqliteConnection connection)
: this(commandText, connection, null)
{
}
/// <summary>
/// Initializes the command and associates it with the specified connection.
/// </summary>
/// <param name="connection">The connection to associate with the command</param>
public SqliteCommand(SqliteConnection connection)
: this(null, connection, null)
{
}
private SqliteCommand(SqliteCommand source) : this(source.CommandText, source.Connection, source.Transaction)
{
CommandTimeout = source.CommandTimeout;
DesignTimeVisible = source.DesignTimeVisible;
UpdatedRowSource = source.UpdatedRowSource;
foreach (SqliteParameter param in source._parameterCollection)
{
Parameters.Add(param.Clone());
}
}
/// <summary>
/// Initializes a command with the given SQL, connection and transaction
/// </summary>
/// <param name="commandText">The SQL command text</param>
/// <param name="connection">The connection to associate with the command</param>
/// <param name="transaction">The transaction the command should be associated with</param>
public SqliteCommand(string commandText, SqliteConnection connection, SqliteTransaction transaction)
{
_statementList = null;
_activeReader = null;
_commandTimeout = 30;
_parameterCollection = new SqliteParameterCollection(this);
_designTimeVisible = true;
_updateRowSource = UpdateRowSource.None;
_transaction = null;
if (commandText != null)
CommandText = commandText;
if (connection != null)
{
DbConnection = connection;
_commandTimeout = connection.DefaultTimeout;
}
if (transaction != null)
Transaction = transaction;
}
/// <summary>
/// Disposes of the command and clears all member variables
/// </summary>
/// <param name="disposing">Whether or not the class is being explicitly or implicitly disposed</param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
// If a reader is active on this command, don't destroy the command, instead let the reader do it
SqliteDataReader reader = null;
if (_activeReader != null)
{
try
{
reader = _activeReader.Target as SqliteDataReader;
}
catch
{
}
}
if (reader != null)
{
reader._disposeCommand = true;
_activeReader = null;
return;
}
Connection = null;
_parameterCollection.Clear();
_commandText = null;
}
}
/// <summary>
/// Clears and destroys all statements currently prepared
/// </summary>
internal void ClearCommands()
{
if (_activeReader != null)
{
SqliteDataReader reader = null;
try
{
reader = _activeReader.Target as SqliteDataReader;
}
catch
{
}
if (reader != null)
reader.Close();
_activeReader = null;
}
if (_statementList == null) return;
int x = _statementList.Count;
for (int n = 0; n < x; n++)
_statementList[n].Dispose();
_statementList = null;
_parameterCollection.Unbind();
}
/// <summary>
/// Builds an array of prepared statements for each complete SQL statement in the command text
/// </summary>
internal SqliteStatement BuildNextCommand()
{
SqliteStatement stmt = null;
try
{
if (_statementList == null)
_remainingText = _commandText;
stmt = _cnn._sql.Prepare(_cnn, _remainingText, (_statementList == null) ? null : _statementList[_statementList.Count - 1], (uint)(_commandTimeout * 1000), out _remainingText);
if (stmt != null)
{
stmt._command = this;
if (_statementList == null)
_statementList = new List<SqliteStatement>();
_statementList.Add(stmt);
_parameterCollection.MapParameters(stmt);
stmt.BindParameters();
}
return stmt;
}
catch (Exception)
{
if (stmt != null)
{
if (_statementList.Contains(stmt))
_statementList.Remove(stmt);
stmt.Dispose();
}
// If we threw an error compiling the statement, we cannot continue on so set the remaining text to null.
_remainingText = null;
throw;
}
}
internal SqliteStatement GetStatement(int index)
{
// Haven't built any statements yet
if (_statementList == null) return BuildNextCommand();
// If we're at the last built statement and want the next unbuilt statement, then build it
if (index == _statementList.Count)
{
if (String.IsNullOrEmpty(_remainingText) == false) return BuildNextCommand();
else return null; // No more commands
}
SqliteStatement stmt = _statementList[index];
stmt.BindParameters();
return stmt;
}
/// <summary>
/// Not implemented
/// </summary>
public override void Cancel()
{
if (_activeReader != null)
{
SqliteDataReader reader = _activeReader.Target as SqliteDataReader;
if (reader != null)
reader.Cancel();
}
}
/// <summary>
/// The SQL command text associated with the command
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[DefaultValue(""), RefreshProperties(RefreshProperties.All), Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, Microsoft.VSDesigner, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
#endif
public override string CommandText
{
get
{
return _commandText;
}
set
{
if (_commandText == value) return;
if (_activeReader != null && _activeReader.IsAlive)
{
throw new InvalidOperationException("Cannot set CommandText while a DataReader is active");
}
ClearCommands();
_commandText = value;
if (_cnn == null) return;
}
}
/// <summary>
/// The amount of time to wait for the connection to become available before erroring out
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[DefaultValue((int)30)]
#endif
public override int CommandTimeout
{
get
{
return _commandTimeout;
}
set
{
_commandTimeout = value;
}
}
/// <summary>
/// The type of the command. SQLite only supports CommandType.Text
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[RefreshProperties(RefreshProperties.All), DefaultValue(CommandType.Text)]
#endif
public override CommandType CommandType
{
get
{
return CommandType.Text;
}
set
{
if (value != CommandType.Text)
{
throw new NotSupportedException();
}
}
}
/// <summary>
/// Forwards to the local CreateParameter() function
/// </summary>
/// <returns></returns>
protected override DbParameter CreateDbParameter()
{
return CreateParameter();
}
/// <summary>
/// Create a new parameter
/// </summary>
/// <returns></returns>
public new SqliteParameter CreateParameter()
{
return new SqliteParameter();
}
/// <summary>
/// The connection associated with this command
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[DefaultValue((string)null), Editor("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, Microsoft.VSDesigner, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
#endif
public new SqliteConnection Connection
{
get { return _cnn; }
set
{
if (_activeReader != null && _activeReader.IsAlive)
throw new InvalidOperationException("Cannot set Connection while a DataReader is active");
if (_cnn != null)
{
ClearCommands();
//_cnn.RemoveCommand(this);
}
_cnn = value;
if (_cnn != null)
_version = _cnn._version;
//if (_cnn != null)
// _cnn.AddCommand(this);
}
}
/// <summary>
/// Forwards to the local Connection property
/// </summary>
protected override DbConnection DbConnection
{
get
{
return Connection;
}
set
{
Connection = (SqliteConnection)value;
}
}
/// <summary>
/// Returns the SqliteParameterCollection for the given command
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
#endif
public new SqliteParameterCollection Parameters
{
get { return _parameterCollection; }
}
/// <summary>
/// Forwards to the local Parameters property
/// </summary>
protected override DbParameterCollection DbParameterCollection
{
get
{
return Parameters;
}
}
/// <summary>
/// The transaction associated with this command. SQLite only supports one transaction per connection, so this property forwards to the
/// command's underlying connection.
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
#endif
public new SqliteTransaction Transaction
{
get { return _transaction; }
set
{
if (_cnn != null)
{
if (_activeReader != null && _activeReader.IsAlive)
throw new InvalidOperationException("Cannot set Transaction while a DataReader is active");
if (value != null)
{
if (value._cnn != _cnn)
throw new ArgumentException("Transaction is not associated with the command's connection");
}
_transaction = value;
}
else
{
Connection = value.Connection;
_transaction = value;
}
}
}
/// <summary>
/// Forwards to the local Transaction property
/// </summary>
protected override DbTransaction DbTransaction
{
get
{
return Transaction;
}
set
{
Transaction = (SqliteTransaction)value;
}
}
/// <summary>
/// This function ensures there are no active readers, that we have a valid connection,
/// that the connection is open, that all statements are prepared and all parameters are assigned
/// in preparation for allocating a data reader.
/// </summary>
private void InitializeForReader()
{
if (_activeReader != null && _activeReader.IsAlive)
throw new InvalidOperationException("DataReader already active on this command");
if (_cnn == null)
throw new InvalidOperationException("No connection associated with this command");
if (_cnn.State != ConnectionState.Open)
throw new InvalidOperationException("Database is not open");
// If the version of the connection has changed, clear out any previous commands before starting
if (_cnn._version != _version)
{
_version = _cnn._version;
ClearCommands();
}
// Map all parameters for statements already built
_parameterCollection.MapParameters(null);
//// Set the default command timeout
//_cnn._sql.SetTimeout(_commandTimeout * 1000);
}
/// <summary>
/// Creates a new SqliteDataReader to execute/iterate the array of SQLite prepared statements
/// </summary>
/// <param name="behavior">The behavior the data reader should adopt</param>
/// <returns>Returns a SqliteDataReader object</returns>
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
{
return ExecuteReader(behavior);
}
/// <summary>
/// Overrides the default behavior to return a SqliteDataReader specialization class
/// </summary>
/// <param name="behavior">The flags to be associated with the reader</param>
/// <returns>A SqliteDataReader</returns>
public new SqliteDataReader ExecuteReader(CommandBehavior behavior)
{
InitializeForReader();
SqliteDataReader rd = new SqliteDataReader(this, behavior);
_activeReader = new WeakReference(rd, false);
return rd;
}
/// <summary>
/// Overrides the default behavior of DbDataReader to return a specialized SqliteDataReader class
/// </summary>
/// <returns>A SqliteDataReader</returns>
public new SqliteDataReader ExecuteReader()
{
return ExecuteReader(CommandBehavior.Default);
}
/// <summary>
/// Called by the SqliteDataReader when the data reader is closed.
/// </summary>
internal void ClearDataReader()
{
_activeReader = null;
}
/// <summary>
/// Execute the command and return the number of rows inserted/updated affected by it.
/// </summary>
/// <returns></returns>
public override int ExecuteNonQuery()
{
using (SqliteDataReader reader = ExecuteReader(CommandBehavior.SingleRow | CommandBehavior.SingleResult))
{
while (reader.NextResult()) ;
return reader.RecordsAffected;
}
}
/// <summary>
/// Execute the command and return the first column of the first row of the resultset
/// (if present), or null if no resultset was returned.
/// </summary>
/// <returns>The first column of the first row of the first resultset from the query</returns>
public override object ExecuteScalar()
{
using (SqliteDataReader reader = ExecuteReader(CommandBehavior.SingleRow | CommandBehavior.SingleResult))
{
if (reader.Read())
return reader[0];
}
return null;
}
/// <summary>
/// Does nothing. Commands are prepared as they are executed the first time, and kept in prepared state afterwards.
/// </summary>
public override void Prepare()
{
}
/// <summary>
/// Sets the method the SqliteCommandBuilder uses to determine how to update inserted or updated rows in a DataTable.
/// </summary>
[DefaultValue(UpdateRowSource.None)]
public override UpdateRowSource UpdatedRowSource
{
get
{
return _updateRowSource;
}
set
{
_updateRowSource = value;
}
}
/// <summary>
/// Determines if the command is visible at design time. Defaults to True.
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[DesignOnly(true), Browsable(false), DefaultValue(true), EditorBrowsable(EditorBrowsableState.Never)]
#endif
public override bool DesignTimeVisible
{
get
{
return _designTimeVisible;
}
set
{
_designTimeVisible = value;
#if !PLATFORM_COMPACTFRAMEWORK
TypeDescriptor.Refresh(this);
#endif
}
}
/// <summary>
/// Clones a command, including all its parameters
/// </summary>
/// <returns>A new SqliteCommand with the same commandtext, connection and parameters</returns>
public object Clone()
{
return new SqliteCommand(this);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
public static partial class BitConverter
{
public static readonly bool IsLittleEndian;
public static long DoubleToInt64Bits(double value) { return default(long); }
public static byte[] GetBytes(bool value) { return default(byte[]); }
public static byte[] GetBytes(char value) { return default(byte[]); }
public static byte[] GetBytes(double value) { return default(byte[]); }
public static byte[] GetBytes(short value) { return default(byte[]); }
public static byte[] GetBytes(int value) { return default(byte[]); }
public static byte[] GetBytes(long value) { return default(byte[]); }
public static byte[] GetBytes(float value) { return default(byte[]); }
[System.CLSCompliantAttribute(false)]
public static byte[] GetBytes(ushort value) { return default(byte[]); }
[System.CLSCompliantAttribute(false)]
public static byte[] GetBytes(uint value) { return default(byte[]); }
[System.CLSCompliantAttribute(false)]
public static byte[] GetBytes(ulong value) { return default(byte[]); }
public static double Int64BitsToDouble(long value) { return default(double); }
public static bool ToBoolean(byte[] value, int startIndex) { return default(bool); }
public static char ToChar(byte[] value, int startIndex) { return default(char); }
public static double ToDouble(byte[] value, int startIndex) { return default(double); }
public static short ToInt16(byte[] value, int startIndex) { return default(short); }
public static int ToInt32(byte[] value, int startIndex) { return default(int); }
public static long ToInt64(byte[] value, int startIndex) { return default(long); }
public static float ToSingle(byte[] value, int startIndex) { return default(float); }
public static string ToString(byte[] value) { return default(string); }
public static string ToString(byte[] value, int startIndex) { return default(string); }
public static string ToString(byte[] value, int startIndex, int length) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(byte[] value, int startIndex) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(byte[] value, int startIndex) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(byte[] value, int startIndex) { return default(ulong); }
}
public static partial class Convert
{
public static object ChangeType(object value, System.Type conversionType) { return default(object); }
public static object ChangeType(object value, System.Type conversionType, System.IFormatProvider provider) { return default(object); }
public static object ChangeType(object value, System.TypeCode typeCode, System.IFormatProvider provider) { return default(object); }
public static byte[] FromBase64CharArray(char[] inArray, int offset, int length) { return default(byte[]); }
public static byte[] FromBase64String(string s) { return default(byte[]); }
public static System.TypeCode GetTypeCode(object value) { return default(System.TypeCode); }
public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut) { return default(int); }
public static string ToBase64String(byte[] inArray) { return default(string); }
public static string ToBase64String(byte[] inArray, int offset, int length) { return default(string); }
public static bool ToBoolean(bool value) { return default(bool); }
public static bool ToBoolean(byte value) { return default(bool); }
public static bool ToBoolean(decimal value) { return default(bool); }
public static bool ToBoolean(double value) { return default(bool); }
public static bool ToBoolean(short value) { return default(bool); }
public static bool ToBoolean(int value) { return default(bool); }
public static bool ToBoolean(long value) { return default(bool); }
public static bool ToBoolean(object value) { return default(bool); }
public static bool ToBoolean(object value, System.IFormatProvider provider) { return default(bool); }
[System.CLSCompliantAttribute(false)]
public static bool ToBoolean(sbyte value) { return default(bool); }
public static bool ToBoolean(float value) { return default(bool); }
public static bool ToBoolean(string value) { return default(bool); }
public static bool ToBoolean(string value, System.IFormatProvider provider) { return default(bool); }
[System.CLSCompliantAttribute(false)]
public static bool ToBoolean(ushort value) { return default(bool); }
[System.CLSCompliantAttribute(false)]
public static bool ToBoolean(uint value) { return default(bool); }
[System.CLSCompliantAttribute(false)]
public static bool ToBoolean(ulong value) { return default(bool); }
public static byte ToByte(bool value) { return default(byte); }
public static byte ToByte(byte value) { return default(byte); }
public static byte ToByte(char value) { return default(byte); }
public static byte ToByte(decimal value) { return default(byte); }
public static byte ToByte(double value) { return default(byte); }
public static byte ToByte(short value) { return default(byte); }
public static byte ToByte(int value) { return default(byte); }
public static byte ToByte(long value) { return default(byte); }
public static byte ToByte(object value) { return default(byte); }
public static byte ToByte(object value, System.IFormatProvider provider) { return default(byte); }
[System.CLSCompliantAttribute(false)]
public static byte ToByte(sbyte value) { return default(byte); }
public static byte ToByte(float value) { return default(byte); }
public static byte ToByte(string value) { return default(byte); }
public static byte ToByte(string value, System.IFormatProvider provider) { return default(byte); }
public static byte ToByte(string value, int fromBase) { return default(byte); }
[System.CLSCompliantAttribute(false)]
public static byte ToByte(ushort value) { return default(byte); }
[System.CLSCompliantAttribute(false)]
public static byte ToByte(uint value) { return default(byte); }
[System.CLSCompliantAttribute(false)]
public static byte ToByte(ulong value) { return default(byte); }
public static char ToChar(byte value) { return default(char); }
public static char ToChar(short value) { return default(char); }
public static char ToChar(int value) { return default(char); }
public static char ToChar(long value) { return default(char); }
public static char ToChar(object value) { return default(char); }
public static char ToChar(object value, System.IFormatProvider provider) { return default(char); }
[System.CLSCompliantAttribute(false)]
public static char ToChar(sbyte value) { return default(char); }
public static char ToChar(string value) { return default(char); }
public static char ToChar(string value, System.IFormatProvider provider) { return default(char); }
[System.CLSCompliantAttribute(false)]
public static char ToChar(ushort value) { return default(char); }
[System.CLSCompliantAttribute(false)]
public static char ToChar(uint value) { return default(char); }
[System.CLSCompliantAttribute(false)]
public static char ToChar(ulong value) { return default(char); }
public static System.DateTime ToDateTime(object value) { return default(System.DateTime); }
public static System.DateTime ToDateTime(object value, System.IFormatProvider provider) { return default(System.DateTime); }
public static System.DateTime ToDateTime(string value) { return default(System.DateTime); }
public static System.DateTime ToDateTime(string value, System.IFormatProvider provider) { return default(System.DateTime); }
public static decimal ToDecimal(bool value) { return default(decimal); }
public static decimal ToDecimal(byte value) { return default(decimal); }
public static decimal ToDecimal(decimal value) { return default(decimal); }
public static decimal ToDecimal(double value) { return default(decimal); }
public static decimal ToDecimal(short value) { return default(decimal); }
public static decimal ToDecimal(int value) { return default(decimal); }
public static decimal ToDecimal(long value) { return default(decimal); }
public static decimal ToDecimal(object value) { return default(decimal); }
public static decimal ToDecimal(object value, System.IFormatProvider provider) { return default(decimal); }
[System.CLSCompliantAttribute(false)]
public static decimal ToDecimal(sbyte value) { return default(decimal); }
public static decimal ToDecimal(float value) { return default(decimal); }
public static decimal ToDecimal(string value) { return default(decimal); }
public static decimal ToDecimal(string value, System.IFormatProvider provider) { return default(decimal); }
[System.CLSCompliantAttribute(false)]
public static decimal ToDecimal(ushort value) { return default(decimal); }
[System.CLSCompliantAttribute(false)]
public static decimal ToDecimal(uint value) { return default(decimal); }
[System.CLSCompliantAttribute(false)]
public static decimal ToDecimal(ulong value) { return default(decimal); }
public static double ToDouble(bool value) { return default(double); }
public static double ToDouble(byte value) { return default(double); }
public static double ToDouble(decimal value) { return default(double); }
public static double ToDouble(double value) { return default(double); }
public static double ToDouble(short value) { return default(double); }
public static double ToDouble(int value) { return default(double); }
public static double ToDouble(long value) { return default(double); }
public static double ToDouble(object value) { return default(double); }
public static double ToDouble(object value, System.IFormatProvider provider) { return default(double); }
[System.CLSCompliantAttribute(false)]
public static double ToDouble(sbyte value) { return default(double); }
public static double ToDouble(float value) { return default(double); }
public static double ToDouble(string value) { return default(double); }
public static double ToDouble(string value, System.IFormatProvider provider) { return default(double); }
[System.CLSCompliantAttribute(false)]
public static double ToDouble(ushort value) { return default(double); }
[System.CLSCompliantAttribute(false)]
public static double ToDouble(uint value) { return default(double); }
[System.CLSCompliantAttribute(false)]
public static double ToDouble(ulong value) { return default(double); }
public static short ToInt16(bool value) { return default(short); }
public static short ToInt16(byte value) { return default(short); }
public static short ToInt16(char value) { return default(short); }
public static short ToInt16(decimal value) { return default(short); }
public static short ToInt16(double value) { return default(short); }
public static short ToInt16(short value) { return default(short); }
public static short ToInt16(int value) { return default(short); }
public static short ToInt16(long value) { return default(short); }
public static short ToInt16(object value) { return default(short); }
public static short ToInt16(object value, System.IFormatProvider provider) { return default(short); }
[System.CLSCompliantAttribute(false)]
public static short ToInt16(sbyte value) { return default(short); }
public static short ToInt16(float value) { return default(short); }
public static short ToInt16(string value) { return default(short); }
public static short ToInt16(string value, System.IFormatProvider provider) { return default(short); }
public static short ToInt16(string value, int fromBase) { return default(short); }
[System.CLSCompliantAttribute(false)]
public static short ToInt16(ushort value) { return default(short); }
[System.CLSCompliantAttribute(false)]
public static short ToInt16(uint value) { return default(short); }
[System.CLSCompliantAttribute(false)]
public static short ToInt16(ulong value) { return default(short); }
public static int ToInt32(bool value) { return default(int); }
public static int ToInt32(byte value) { return default(int); }
public static int ToInt32(char value) { return default(int); }
public static int ToInt32(decimal value) { return default(int); }
public static int ToInt32(double value) { return default(int); }
public static int ToInt32(short value) { return default(int); }
public static int ToInt32(int value) { return default(int); }
public static int ToInt32(long value) { return default(int); }
public static int ToInt32(object value) { return default(int); }
public static int ToInt32(object value, System.IFormatProvider provider) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int ToInt32(sbyte value) { return default(int); }
public static int ToInt32(float value) { return default(int); }
public static int ToInt32(string value) { return default(int); }
public static int ToInt32(string value, System.IFormatProvider provider) { return default(int); }
public static int ToInt32(string value, int fromBase) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int ToInt32(ushort value) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int ToInt32(uint value) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int ToInt32(ulong value) { return default(int); }
public static long ToInt64(bool value) { return default(long); }
public static long ToInt64(byte value) { return default(long); }
public static long ToInt64(char value) { return default(long); }
public static long ToInt64(decimal value) { return default(long); }
public static long ToInt64(double value) { return default(long); }
public static long ToInt64(short value) { return default(long); }
public static long ToInt64(int value) { return default(long); }
public static long ToInt64(long value) { return default(long); }
public static long ToInt64(object value) { return default(long); }
public static long ToInt64(object value, System.IFormatProvider provider) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static long ToInt64(sbyte value) { return default(long); }
public static long ToInt64(float value) { return default(long); }
public static long ToInt64(string value) { return default(long); }
public static long ToInt64(string value, System.IFormatProvider provider) { return default(long); }
public static long ToInt64(string value, int fromBase) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static long ToInt64(ushort value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static long ToInt64(uint value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static long ToInt64(ulong value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(bool value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(byte value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(char value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(decimal value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(double value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(short value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(int value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(long value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(object value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(object value, System.IFormatProvider provider) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(sbyte value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(float value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string value, System.IFormatProvider provider) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string value, int fromBase) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(ushort value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(uint value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(ulong value) { return default(sbyte); }
public static float ToSingle(bool value) { return default(float); }
public static float ToSingle(byte value) { return default(float); }
public static float ToSingle(decimal value) { return default(float); }
public static float ToSingle(double value) { return default(float); }
public static float ToSingle(short value) { return default(float); }
public static float ToSingle(int value) { return default(float); }
public static float ToSingle(long value) { return default(float); }
public static float ToSingle(object value) { return default(float); }
public static float ToSingle(object value, System.IFormatProvider provider) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static float ToSingle(sbyte value) { return default(float); }
public static float ToSingle(float value) { return default(float); }
public static float ToSingle(string value) { return default(float); }
public static float ToSingle(string value, System.IFormatProvider provider) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static float ToSingle(ushort value) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static float ToSingle(uint value) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static float ToSingle(ulong value) { return default(float); }
public static string ToString(bool value) { return default(string); }
public static string ToString(bool value, System.IFormatProvider provider) { return default(string); }
public static string ToString(byte value) { return default(string); }
public static string ToString(byte value, System.IFormatProvider provider) { return default(string); }
public static string ToString(byte value, int toBase) { return default(string); }
public static string ToString(char value) { return default(string); }
public static string ToString(char value, System.IFormatProvider provider) { return default(string); }
public static string ToString(System.DateTime value) { return default(string); }
public static string ToString(System.DateTime value, System.IFormatProvider provider) { return default(string); }
public static string ToString(decimal value) { return default(string); }
public static string ToString(decimal value, System.IFormatProvider provider) { return default(string); }
public static string ToString(double value) { return default(string); }
public static string ToString(double value, System.IFormatProvider provider) { return default(string); }
public static string ToString(short value) { return default(string); }
public static string ToString(short value, System.IFormatProvider provider) { return default(string); }
public static string ToString(short value, int toBase) { return default(string); }
public static string ToString(int value) { return default(string); }
public static string ToString(int value, System.IFormatProvider provider) { return default(string); }
public static string ToString(int value, int toBase) { return default(string); }
public static string ToString(long value) { return default(string); }
public static string ToString(long value, System.IFormatProvider provider) { return default(string); }
public static string ToString(long value, int toBase) { return default(string); }
public static string ToString(object value) { return default(string); }
public static string ToString(object value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(sbyte value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(sbyte value, System.IFormatProvider provider) { return default(string); }
public static string ToString(float value) { return default(string); }
public static string ToString(float value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ushort value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ushort value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(uint value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(uint value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ulong value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ulong value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(bool value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(byte value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(char value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(decimal value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(double value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(short value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(int value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(long value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(object value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(object value, System.IFormatProvider provider) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(sbyte value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(float value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(string value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(string value, System.IFormatProvider provider) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(string value, int fromBase) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(ushort value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(uint value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(ulong value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(bool value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(byte value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(char value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(decimal value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(double value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(short value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(int value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(long value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(object value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(object value, System.IFormatProvider provider) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(sbyte value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(float value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(string value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(string value, System.IFormatProvider provider) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(string value, int fromBase) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(ushort value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(uint value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(ulong value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(bool value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(byte value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(char value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(decimal value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(double value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(short value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(int value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(long value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(object value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(object value, System.IFormatProvider provider) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(sbyte value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(float value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(string value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(string value, System.IFormatProvider provider) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(string value, int fromBase) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(ushort value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(uint value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(ulong value) { return default(ulong); }
}
public static partial class Environment
{
public static int CurrentManagedThreadId { get { return default(int); } }
public static bool HasShutdownStarted { get { return default(bool); } }
public static string NewLine { get { return default(string); } }
public static int ProcessorCount { get { return default(int); } }
public static string StackTrace { get { return default(string); } }
public static int TickCount { get { return default(int); } }
public static string ExpandEnvironmentVariables(string name) { return default(string); }
public static void Exit(int exitCode) {}
[System.Security.SecurityCriticalAttribute]
public static void FailFast(string message) { }
[System.Security.SecurityCriticalAttribute]
public static void FailFast(string message, System.Exception exception) { }
public static string GetEnvironmentVariable(string variable) { return default(string); }
public static System.Collections.IDictionary GetEnvironmentVariables() { return default(System.Collections.IDictionary); }
public static void SetEnvironmentVariable(string variable, string value) { }
public static string[] GetCommandLineArgs() { return default(string[]); }
}
public static partial class Math
{
public static decimal Abs(decimal value) { return default(decimal); }
public static double Abs(double value) { return default(double); }
public static short Abs(short value) { return default(short); }
public static int Abs(int value) { return default(int); }
public static long Abs(long value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte Abs(sbyte value) { return default(sbyte); }
public static float Abs(float value) { return default(float); }
public static double Acos(double d) { return default(double); }
public static double Asin(double d) { return default(double); }
public static double Atan(double d) { return default(double); }
public static double Atan2(double y, double x) { return default(double); }
public static decimal Ceiling(decimal d) { return default(decimal); }
public static double Ceiling(double a) { return default(double); }
public static double Cos(double d) { return default(double); }
public static double Cosh(double value) { return default(double); }
public static double Exp(double d) { return default(double); }
public static decimal Floor(decimal d) { return default(decimal); }
public static double Floor(double d) { return default(double); }
public static double IEEERemainder(double x, double y) { return default(double); }
public static double Log(double d) { return default(double); }
public static double Log(double a, double newBase) { return default(double); }
public static double Log10(double d) { return default(double); }
public static byte Max(byte val1, byte val2) { return default(byte); }
public static decimal Max(decimal val1, decimal val2) { return default(decimal); }
public static double Max(double val1, double val2) { return default(double); }
public static short Max(short val1, short val2) { return default(short); }
public static int Max(int val1, int val2) { return default(int); }
public static long Max(long val1, long val2) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte Max(sbyte val1, sbyte val2) { return default(sbyte); }
public static float Max(float val1, float val2) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static ushort Max(ushort val1, ushort val2) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint Max(uint val1, uint val2) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong Max(ulong val1, ulong val2) { return default(ulong); }
public static byte Min(byte val1, byte val2) { return default(byte); }
public static decimal Min(decimal val1, decimal val2) { return default(decimal); }
public static double Min(double val1, double val2) { return default(double); }
public static short Min(short val1, short val2) { return default(short); }
public static int Min(int val1, int val2) { return default(int); }
public static long Min(long val1, long val2) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte Min(sbyte val1, sbyte val2) { return default(sbyte); }
public static float Min(float val1, float val2) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static ushort Min(ushort val1, ushort val2) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint Min(uint val1, uint val2) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong Min(ulong val1, ulong val2) { return default(ulong); }
public static double Pow(double x, double y) { return default(double); }
public static decimal Round(decimal d) { return default(decimal); }
public static decimal Round(decimal d, int decimals) { return default(decimal); }
public static decimal Round(decimal d, int decimals, System.MidpointRounding mode) { return default(decimal); }
public static decimal Round(decimal d, System.MidpointRounding mode) { return default(decimal); }
public static double Round(double a) { return default(double); }
public static double Round(double value, int digits) { return default(double); }
public static double Round(double value, int digits, System.MidpointRounding mode) { return default(double); }
public static double Round(double value, System.MidpointRounding mode) { return default(double); }
public static int Sign(decimal value) { return default(int); }
public static int Sign(double value) { return default(int); }
public static int Sign(short value) { return default(int); }
public static int Sign(int value) { return default(int); }
public static int Sign(long value) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int Sign(sbyte value) { return default(int); }
public static int Sign(float value) { return default(int); }
public static double Sin(double a) { return default(double); }
public static double Sinh(double value) { return default(double); }
public static double Sqrt(double d) { return default(double); }
public static double Tan(double a) { return default(double); }
public static double Tanh(double value) { return default(double); }
public static decimal Truncate(decimal d) { return default(decimal); }
public static double Truncate(double d) { return default(double); }
}
public enum MidpointRounding
{
AwayFromZero = 1,
ToEven = 0,
}
public partial class Progress<T> : System.IProgress<T>
{
public Progress() { }
public Progress(System.Action<T> handler) { }
public event System.EventHandler<T> ProgressChanged { add { } remove { } }
protected virtual void OnReport(T value) { }
void System.IProgress<T>.Report(T value) { }
}
public partial class Random
{
public Random() { }
public Random(int Seed) { }
public virtual int Next() { return default(int); }
public virtual int Next(int maxValue) { return default(int); }
public virtual int Next(int minValue, int maxValue) { return default(int); }
public virtual void NextBytes(byte[] buffer) { }
public virtual double NextDouble() { return default(double); }
protected virtual double Sample() { return default(double); }
}
public abstract partial class StringComparer : System.Collections.Generic.IComparer<string>, System.Collections.Generic.IEqualityComparer<string>, System.Collections.IComparer, System.Collections.IEqualityComparer
{
protected StringComparer() { }
public static System.StringComparer CurrentCulture { get { return default(System.StringComparer); } }
public static System.StringComparer CurrentCultureIgnoreCase { get { return default(System.StringComparer); } }
public static System.StringComparer Ordinal { get { return default(System.StringComparer); } }
public static System.StringComparer OrdinalIgnoreCase { get { return default(System.StringComparer); } }
public abstract int Compare(string x, string y);
public abstract bool Equals(string x, string y);
public abstract int GetHashCode(string obj);
int System.Collections.IComparer.Compare(object x, object y) { return default(int); }
bool System.Collections.IEqualityComparer.Equals(object x, object y) { return default(bool); }
int System.Collections.IEqualityComparer.GetHashCode(object obj) { return default(int); }
}
public partial class UriBuilder
{
public UriBuilder() { }
public UriBuilder(string uri) { }
public UriBuilder(string schemeName, string hostName) { }
public UriBuilder(string scheme, string host, int portNumber) { }
public UriBuilder(string scheme, string host, int port, string pathValue) { }
public UriBuilder(string scheme, string host, int port, string path, string extraValue) { }
public UriBuilder(System.Uri uri) { }
public string Fragment { get { return default(string); } set { } }
public string Host { get { return default(string); } set { } }
public string Password { get { return default(string); } set { } }
public string Path { get { return default(string); } set { } }
public int Port { get { return default(int); } set { } }
public string Query { get { return default(string); } set { } }
public string Scheme { get { return default(string); } set { } }
public System.Uri Uri { get { return default(System.Uri); } }
public string UserName { get { return default(string); } set { } }
public override bool Equals(object rparam) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override string ToString() { return default(string); }
}
}
namespace System.Diagnostics
{
public partial class Stopwatch
{
public static readonly long Frequency;
public static readonly bool IsHighResolution;
public Stopwatch() { }
public System.TimeSpan Elapsed { get { return default(System.TimeSpan); } }
public long ElapsedMilliseconds { get { return default(long); } }
public long ElapsedTicks { get { return default(long); } }
public bool IsRunning { get { return default(bool); } }
public static long GetTimestamp() { return default(long); }
public void Reset() { }
public void Restart() { }
public void Start() { }
public static System.Diagnostics.Stopwatch StartNew() { return default(System.Diagnostics.Stopwatch); }
public void Stop() { }
}
}
namespace System.IO
{
public static partial class Path
{
public static readonly char AltDirectorySeparatorChar;
public static readonly char DirectorySeparatorChar;
public static readonly char PathSeparator;
public static readonly char VolumeSeparatorChar;
public static string ChangeExtension(string path, string extension) { return default(string); }
public static string Combine(string path1, string path2) { return default(string); }
public static string Combine(string path1, string path2, string path3) { return default(string); }
public static string Combine(params string[] paths) { return default(string); }
public static string GetDirectoryName(string path) { return default(string); }
public static string GetExtension(string path) { return default(string); }
public static string GetFileName(string path) { return default(string); }
public static string GetFileNameWithoutExtension(string path) { return default(string); }
public static string GetFullPath(string path) { return default(string); }
public static char[] GetInvalidFileNameChars() { return default(char[]); }
public static char[] GetInvalidPathChars() { return default(char[]); }
public static string GetPathRoot(string path) { return default(string); }
public static string GetRandomFileName() { return default(string); }
public static string GetTempFileName() { return default(string); }
public static string GetTempPath() { return default(string); }
public static bool HasExtension(string path) { return default(bool); }
public static bool IsPathRooted(string path) { return default(bool); }
}
}
namespace System.Net
{
public static partial class WebUtility
{
public static string HtmlDecode(string value) { return default(string); }
public static string HtmlEncode(string value) { return default(string); }
public static string UrlDecode(string encodedValue) { return default(string); }
public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count) { return default(byte[]); }
public static string UrlEncode(string value) { return default(string); }
public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count) { return default(byte[]); }
}
}
namespace System.Runtime.Versioning
{
public sealed partial class FrameworkName : System.IEquatable<System.Runtime.Versioning.FrameworkName>
{
public FrameworkName(string frameworkName) { }
public FrameworkName(string identifier, System.Version version) { }
public FrameworkName(string identifier, System.Version version, string profile) { }
public string FullName { get { return default(string); } }
public string Identifier { get { return default(string); } }
public string Profile { get { return default(string); } }
public System.Version Version { get { return default(System.Version); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Runtime.Versioning.FrameworkName other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Runtime.Versioning.FrameworkName left, System.Runtime.Versioning.FrameworkName right) { return default(bool); }
public static bool operator !=(System.Runtime.Versioning.FrameworkName left, System.Runtime.Versioning.FrameworkName right) { return default(bool); }
public override string ToString() { return default(string); }
}
}
| |
namespace RRLab.PhysiologyWorkbench.GUI
{
partial class HotkeyManagerDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param genotype="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this._SaveButton = new System.Windows.Forms.Button();
this._CancelButton = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.MappingsListBox = new System.Windows.Forms.ListBox();
this.flowLayoutPanel3 = new System.Windows.Forms.FlowLayoutPanel();
this.RemoveButton = new System.Windows.Forms.Button();
this.AddButton = new System.Windows.Forms.Button();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.label1 = new System.Windows.Forms.Label();
this.ActionsComboBox = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.HotkeyTextBox = new System.Windows.Forms.TextBox();
this.flowLayoutPanel1.SuspendLayout();
this.panel1.SuspendLayout();
this.flowLayoutPanel3.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.AutoSize = true;
this.flowLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.flowLayoutPanel1.Controls.Add(this._SaveButton);
this.flowLayoutPanel1.Controls.Add(this._CancelButton);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft;
this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 295);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(260, 29);
this.flowLayoutPanel1.TabIndex = 0;
//
// _SaveButton
//
this._SaveButton.AutoSize = true;
this._SaveButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._SaveButton.Location = new System.Drawing.Point(215, 3);
this._SaveButton.Name = "_SaveButton";
this._SaveButton.Size = new System.Drawing.Size(42, 23);
this._SaveButton.TabIndex = 0;
this._SaveButton.Text = "&Save";
this._SaveButton.UseVisualStyleBackColor = true;
this._SaveButton.Click += new System.EventHandler(this.OnSaveClicked);
//
// _CancelButton
//
this._CancelButton.AutoSize = true;
this._CancelButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._CancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this._CancelButton.Location = new System.Drawing.Point(159, 3);
this._CancelButton.Name = "_CancelButton";
this._CancelButton.Size = new System.Drawing.Size(50, 23);
this._CancelButton.TabIndex = 1;
this._CancelButton.Text = "&Cancel";
this._CancelButton.UseVisualStyleBackColor = true;
//
// panel1
//
this.panel1.Controls.Add(this.MappingsListBox);
this.panel1.Controls.Add(this.flowLayoutPanel3);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(260, 233);
this.panel1.TabIndex = 1;
//
// MappingsListBox
//
this.MappingsListBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.MappingsListBox.FormattingEnabled = true;
this.MappingsListBox.Location = new System.Drawing.Point(0, 0);
this.MappingsListBox.Name = "MappingsListBox";
this.MappingsListBox.Size = new System.Drawing.Size(260, 199);
this.MappingsListBox.TabIndex = 2;
this.MappingsListBox.SelectedIndexChanged += new System.EventHandler(this.OnSelectedHotkeyMappingChanged);
//
// flowLayoutPanel3
//
this.flowLayoutPanel3.AutoSize = true;
this.flowLayoutPanel3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.flowLayoutPanel3.Controls.Add(this.RemoveButton);
this.flowLayoutPanel3.Controls.Add(this.AddButton);
this.flowLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Bottom;
this.flowLayoutPanel3.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft;
this.flowLayoutPanel3.Location = new System.Drawing.Point(0, 204);
this.flowLayoutPanel3.Name = "flowLayoutPanel3";
this.flowLayoutPanel3.Size = new System.Drawing.Size(260, 29);
this.flowLayoutPanel3.TabIndex = 1;
//
// RemoveButton
//
this.RemoveButton.AutoSize = true;
this.RemoveButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.RemoveButton.Location = new System.Drawing.Point(200, 3);
this.RemoveButton.Name = "RemoveButton";
this.RemoveButton.Size = new System.Drawing.Size(57, 23);
this.RemoveButton.TabIndex = 0;
this.RemoveButton.Text = "&Remove";
this.RemoveButton.UseVisualStyleBackColor = true;
this.RemoveButton.Click += new System.EventHandler(this.OnRemoveClicked);
//
// AddButton
//
this.AddButton.AutoSize = true;
this.AddButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.AddButton.Location = new System.Drawing.Point(158, 3);
this.AddButton.Name = "AddButton";
this.AddButton.Size = new System.Drawing.Size(36, 23);
this.AddButton.TabIndex = 1;
this.AddButton.Text = "&Add";
this.AddButton.UseVisualStyleBackColor = true;
this.AddButton.Click += new System.EventHandler(this.OnAddClicked);
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 2;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.ActionsComboBox, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.label2, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.HotkeyTextBox, 1, 1);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 233);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.Size = new System.Drawing.Size(260, 62);
this.tableLayoutPanel1.TabIndex = 2;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
this.label1.Location = new System.Drawing.Point(3, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(44, 27);
this.label1.TabIndex = 2;
this.label1.Text = "Action:";
//
// ActionsComboBox
//
this.ActionsComboBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.ActionsComboBox.FormattingEnabled = true;
this.ActionsComboBox.Location = new System.Drawing.Point(53, 3);
this.ActionsComboBox.Name = "ActionsComboBox";
this.ActionsComboBox.Size = new System.Drawing.Size(204, 21);
this.ActionsComboBox.TabIndex = 3;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Dock = System.Windows.Forms.DockStyle.Fill;
this.label2.Location = new System.Drawing.Point(3, 27);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(44, 35);
this.label2.TabIndex = 4;
this.label2.Text = "Hotkey:";
//
// HotkeyTextBox
//
this.HotkeyTextBox.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.HotkeyTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.HotkeyTextBox.Location = new System.Drawing.Point(53, 30);
this.HotkeyTextBox.Name = "HotkeyTextBox";
this.HotkeyTextBox.ReadOnly = true;
this.HotkeyTextBox.Size = new System.Drawing.Size(204, 20);
this.HotkeyTextBox.TabIndex = 5;
this.HotkeyTextBox.Text = "Press the desired hotkey";
this.HotkeyTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnHotkeyEntered);
//
// HotkeyManagerDialog
//
this.AcceptButton = this._SaveButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this._CancelButton;
this.ClientSize = new System.Drawing.Size(260, 324);
this.Controls.Add(this.panel1);
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.flowLayoutPanel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "HotkeyManagerDialog";
this.Text = "Configure Hotkeys...";
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.flowLayoutPanel3.ResumeLayout(false);
this.flowLayoutPanel3.PerformLayout();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Button _SaveButton;
private System.Windows.Forms.Button _CancelButton;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.ListBox MappingsListBox;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel3;
private System.Windows.Forms.Button RemoveButton;
private System.Windows.Forms.Button AddButton;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ComboBox ActionsComboBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox HotkeyTextBox;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlatRedBall.Graphics;
using Microsoft.Xna.Framework.Graphics;
using FlatRedBall;
using Microsoft.Xna.Framework;
using FlatRedBall.Content;
using FlatRedBall.Content.Scene;
using FlatRedBall.IO;
using FlatRedBall.Input;
using FlatRedBall.Debugging;
using FlatRedBall.Math;
using TMXGlueLib.DataTypes;
namespace FlatRedBall.TileGraphics
{
public enum SortAxis
{
None,
X,
Y
}
public class MapDrawableBatch : PositionedObject, IVisible, IDrawableBatch
{
#region Fields
protected Tileset mTileset;
#region XML Docs
/// <summary>
/// The effect used to draw. Shared by all instances for performance reasons
/// </summary>
#endregion
private static BasicEffect mBasicEffect;
private static AlphaTestEffect mAlphaTestEffect;
/// <summary>
/// The vertices used to draw the map.
/// </summary>
/// <remarks>
/// Coordinate order is:
/// 3 2
///
/// 0 1
/// </remarks>
protected VertexPositionTexture[] mVertices;
protected Texture2D mTexture;
#region XML Docs
/// <summary>
/// The indices to draw the shape
/// </summary>
#endregion
protected int[] mIndices;
Dictionary<string, List<int>> mNamedTileOrderedIndexes = new Dictionary<string, List<int>>();
private int mCurrentNumberOfTiles = 0;
private SortAxis mSortAxis;
#endregion
#region Properties
public List<TMXGlueLib.DataTypes.NamedValue> Properties
{
get;
private set;
} = new List<TMXGlueLib.DataTypes.NamedValue>();
/// <summary>
/// The axis on which tiles are sorted. This is used to perform tile culling for performance.
/// Setting this to SortAxis.None will turn off culling.
/// </summary>
public SortAxis SortAxis
{
get
{
return mSortAxis;
}
set
{
mSortAxis = value;
}
}
#region XML Docs
/// <summary>
/// Here we tell the engine if we want this batch
/// updated every frame. Since we have no updating to
/// do though, we will set this to false
/// </summary>
#endregion
public bool UpdateEveryFrame
{
get { return true; }
}
public float RenderingScale
{
get;
set;
}
public Dictionary<string, List<int>> NamedTileOrderedIndexes
{
get
{
return mNamedTileOrderedIndexes;
}
}
public bool Visible
{
get;
set;
}
public bool ZBuffered
{
get;
set;
}
public int QuadCount
{
get
{
return mVertices.Length / 4;
}
}
public VertexPositionTexture[] Vertices
{
get
{
return mVertices;
}
}
public Texture2D Texture
{
get
{
return mTexture;
}
set
{
if (value == null)
{
throw new Exception("Texture can't be null.");
}
if (mTexture != null && (mTexture.Width != value.Width || mTexture.Height != value.Height))
{
throw new Exception("New texture must match previous texture dimensions.");
}
mTexture = value;
}
}
// Doing these properties this way lets me avoid a computational step of 1 - ParallaxMultiplier in the Update() function
// To explain the get & set values, algebra:
// if _parallaxMultiplier = 1 - value (set)
// then _parallaxMultiplier - 1 = -value
// so -(_parallaxMultiplier - 1) = value
// thus -_parallaxMultiplier + 1 = value (get)
private float _parallaxMultiplierX;
public float ParallaxMultiplierX
{
get { return -_parallaxMultiplierX + 1; }
set { _parallaxMultiplierX = 1 - value; }
}
private float _parallaxMultiplierY;
public float ParallaxMultiplierY
{
get { return -_parallaxMultiplierY + 1; }
set { _parallaxMultiplierY = 1 - value; }
}
public TextureFilter? TextureFilter { get; set; } = null;
#endregion
#region Constructor / Initialization
// this exists purely for Clone
public MapDrawableBatch()
{
}
public MapDrawableBatch(int numberOfTiles, Texture2D texture)
: base()
{
if (texture == null)
throw new ArgumentNullException("texture");
Visible = true;
InternalInitialize();
mTexture = texture;
mVertices = new VertexPositionTexture[4 * numberOfTiles];
mIndices = new int[6 * numberOfTiles];
}
#region XML Docs
/// <summary>
/// Create and initialize all assets
/// </summary>
#endregion
public MapDrawableBatch(int numberOfTiles, int textureTileDimensionWidth, int textureTileDimensionHeight, Texture2D texture)
: base()
{
if (texture == null)
throw new ArgumentNullException("texture");
Visible = true;
InternalInitialize();
mTexture = texture;
mVertices = new VertexPositionTexture[4 * numberOfTiles];
mIndices = new int[6 * numberOfTiles];
mTileset = new Tileset(texture, textureTileDimensionWidth, textureTileDimensionHeight);
}
//public MapDrawableBatch(int mapWidth, int mapHeight, float mapTileDimension, int textureTileDimension, string tileSetFilename)
// : base()
//{
// InternalInitialize();
// mTileset = new Tileset(tileSetFilename, textureTileDimension);
// mMapWidth = mapWidth;
// mMapHeight = mapHeight;
// int numberOfTiles = mapWidth * mapHeight;
// // the number of vertices is 4 times the number of tiles (each tile gets 4 vertices)
// mVertices = new VertexPositionTexture[4 * numberOfTiles];
// // the number of indices is 6 times the number of tiles
// mIndices = new short[6 * numberOfTiles];
// for(int i = 0; i < mapHeight; i++)
// {
// for (int j = 0; j < mapWidth; j++)
// {
// int currentTile = mapHeight * i + j;
// int currentVertex = currentTile * 4;
// float xOffset = j * mapTileDimension;
// float yOffset = i * mapTileDimension;
// int currentIndex = currentTile * 6; // 6 indices per tile
// // TEMP
// Vector2[] coords = mTileset.GetTextureCoordinateVectorsOfTextureIndex(new Random().Next()%4);
// // END TEMP
// // create vertices
// mVertices[currentVertex + 0] = new VertexPositionTexture(new Vector3(xOffset + 0f, yOffset + 0f, 0f), coords[0]);
// mVertices[currentVertex + 1] = new VertexPositionTexture(new Vector3(xOffset + mapTileDimension, yOffset + 0f, 0f), coords[1]);
// mVertices[currentVertex + 2] = new VertexPositionTexture(new Vector3(xOffset + mapTileDimension, yOffset + mapTileDimension, 0f), coords[2]);
// mVertices[currentVertex + 3] = new VertexPositionTexture(new Vector3(xOffset + 0f, yOffset + mapTileDimension, 0f), coords[3]);
// // create indices
// mIndices[currentIndex + 0] = (short)(currentVertex + 0);
// mIndices[currentIndex + 1] = (short)(currentVertex + 1);
// mIndices[currentIndex + 2] = (short)(currentVertex + 2);
// mIndices[currentIndex + 3] = (short)(currentVertex + 0);
// mIndices[currentIndex + 4] = (short)(currentVertex + 2);
// mIndices[currentIndex + 5] = (short)(currentVertex + 3);
// mCurrentNumberOfTiles++;
// }
// }
// mTexture = FlatRedBallServices.Load<Texture2D>(@"content/tiles");
//}
void InternalInitialize()
{
// We're going to share these because creating effects is slow...
// But is this okay if we tombstone?
if (mBasicEffect == null)
{
mBasicEffect = new BasicEffect(FlatRedBallServices.GraphicsDevice);
mBasicEffect.VertexColorEnabled = false;
mBasicEffect.TextureEnabled = true;
}
if (mAlphaTestEffect == null)
{
mAlphaTestEffect = new AlphaTestEffect(FlatRedBallServices.GraphicsDevice);
mAlphaTestEffect.Alpha = 1;
mAlphaTestEffect.VertexColorEnabled = false;
}
RenderingScale = 1;
}
#endregion
#region Methods
public void AddToManagers()
{
SpriteManager.AddDrawableBatch(this);
//SpriteManager.AddPositionedObject(mMapBatch);
}
public void AddToManagers(Layer layer)
{
SpriteManager.AddToLayer(this, layer);
}
public static MapDrawableBatch FromScnx(string sceneFileName, string contentManagerName, bool verifySameTexturePerLayer)
{
// TODO: This line crashes when the path is already absolute!
string absoluteFileName = FileManager.MakeAbsolute(sceneFileName);
// TODO: The exception doesn't make sense when the file type is wrong.
SceneSave saveInstance = SceneSave.FromFile(absoluteFileName);
int startingIndex = 0;
string oldRelativeDirectory = FileManager.RelativeDirectory;
FileManager.RelativeDirectory = FileManager.GetDirectory(absoluteFileName);
// get the list of sprites from our map file
List<SpriteSave> spriteSaveList = saveInstance.SpriteList;
// we use the sprites as defined in the scnx file to create and draw the map.
MapDrawableBatch mMapBatch = FromSpriteSaves(spriteSaveList, startingIndex, spriteSaveList.Count, contentManagerName, verifySameTexturePerLayer);
FileManager.RelativeDirectory = oldRelativeDirectory;
// temp
//mMapBatch = new MapDrawableBatch(32, 32, 32f, 64, @"content/tiles");
return mMapBatch;
}
/* This creates a MapDrawableBatch (MDB) from the list of sprites provided to us by the FlatRedBall (FRB) Scene XML (scnx) file. */
public static MapDrawableBatch FromSpriteSaves(List<SpriteSave> spriteSaveList, int startingIndex, int count, string contentManagerName, bool verifySameTexturesPerLayer)
{
#if DEBUG
if (verifySameTexturesPerLayer)
{
VerifySingleTexture(spriteSaveList, startingIndex, count);
}
#endif
// We got it! We are going to make some assumptions:
// First we need the texture. We'll assume all Sprites
// use the same texture:
// TODO: I (Bryan) really HATE this assumption. But it will work for now.
SpriteSave firstSprite = spriteSaveList[startingIndex];
// This is the file name of the texture, but the file name is relative to the .scnx location
string textureRelativeToScene = firstSprite.Texture;
// so we load the texture
Texture2D texture = FlatRedBallServices.Load<Texture2D>(textureRelativeToScene, contentManagerName);
if (!MathFunctions.IsPowerOfTwo(texture.Width) || !MathFunctions.IsPowerOfTwo(texture.Height))
{
throw new Exception("The dimensions of the texture file " + texture.Name + " are not power of 2!");
}
// Assume all the dimensions of the textures are the same. I.e. all tiles use the same texture width and height.
// This assumption is safe for Iso and Ortho tile maps.
int tileFileDimensionsWidth = 0;
int tileFileDimensionsHeight = 0;
if (spriteSaveList.Count > startingIndex)
{
SpriteSave s = spriteSaveList[startingIndex];
// deduce the dimensionality of the tile from the texture coordinates
tileFileDimensionsWidth = (int)System.Math.Round((double)((s.RightTextureCoordinate - s.LeftTextureCoordinate) * texture.Width));
tileFileDimensionsHeight = (int)System.Math.Round((double)((s.BottomTextureCoordinate - s.TopTextureCoordinate) * texture.Height));
}
// alas, we create the MDB
MapDrawableBatch mMapBatch = new MapDrawableBatch(count, tileFileDimensionsWidth, tileFileDimensionsHeight, texture);
int lastIndexExclusive = startingIndex + count;
for (int i = startingIndex; i < lastIndexExclusive; i++)
{
SpriteSave spriteSave = spriteSaveList[i];
// We don't want objects within the IDB to have a different Z than the IDB itself
// (if possible) because that makes the IDB behave differently when using sorting vs.
// the zbuffer.
const bool setZTo0 = true;
mMapBatch.Paste(spriteSave, setZTo0);
}
return mMapBatch;
}
public MapDrawableBatch Clone()
{
return base.Clone<MapDrawableBatch>();
}
// Bring the texture coordinates in to adjust for rendering issues on dx9/ogl
public const float CoordinateAdjustment = .00002f;
internal static MapDrawableBatch FromReducedLayer(TMXGlueLib.DataTypes.ReducedLayerInfo reducedLayerInfo, LayeredTileMap owner, TMXGlueLib.DataTypes.ReducedTileMapInfo rtmi, string contentManagerName)
{
int tileDimensionWidth = reducedLayerInfo.TileWidth;
int tileDimensionHeight = reducedLayerInfo.TileHeight;
float quadWidth = reducedLayerInfo.TileWidth;
float quadHeight = reducedLayerInfo.TileHeight;
string textureName = reducedLayerInfo.Texture;
#if IOS || ANDROID
textureName = textureName.ToLowerInvariant();
#endif
Texture2D texture = FlatRedBallServices.Load<Texture2D>(textureName, contentManagerName);
MapDrawableBatch toReturn = new MapDrawableBatch(reducedLayerInfo.Quads.Count, tileDimensionWidth, tileDimensionHeight, texture);
toReturn.Name = reducedLayerInfo.Name;
Vector3 position = new Vector3();
Vector2 tileDimensions = new Vector2(quadWidth, quadHeight);
IEnumerable<TMXGlueLib.DataTypes.ReducedQuadInfo> quads = null;
if (rtmi.NumberCellsWide > rtmi.NumberCellsTall)
{
quads = reducedLayerInfo.Quads.OrderBy(item => item.LeftQuadCoordinate).ToList();
toReturn.mSortAxis = SortAxis.X;
}
else
{
quads = reducedLayerInfo.Quads.OrderBy(item => item.BottomQuadCoordinate).ToList();
toReturn.mSortAxis = SortAxis.Y;
}
foreach (var quad in quads)
{
position.X = quad.LeftQuadCoordinate;
position.Y = quad.BottomQuadCoordinate;
// The Z of the quad should be relative to this layer, not absolute Z values.
// A multi-layer map will offset the individual layer Z values, the quads should have a Z of 0.
// position.Z = reducedLayerInfo.Z;
var textureValues = new Vector4();
// The purpose of CoordinateAdjustment is to bring the texture values "in", to reduce the chance of adjacent
// tiles drawing on a given tile quad. If we don't do this, we can get slivers of adjacent colors appearing, causing
// lines or grid patterns.
// To bring the values "in" we have to consider rotated quads.
textureValues.X = CoordinateAdjustment + (float)quad.LeftTexturePixel / (float)texture.Width; // Left
textureValues.Y = -CoordinateAdjustment + (float)(quad.LeftTexturePixel + tileDimensionWidth) / (float)texture.Width; // Right
textureValues.Z = CoordinateAdjustment + (float)quad.TopTexturePixel / (float)texture.Height; // Top
textureValues.W = -CoordinateAdjustment + (float)(quad.TopTexturePixel + tileDimensionHeight) / (float)texture.Height; // Bottom
// pad before doing any rotations/flipping
const bool pad = true;
if (pad)
{
const float amountToAdd = .0000001f;
textureValues.X += amountToAdd; // Left
textureValues.Y -= amountToAdd; // Right
textureValues.Z += amountToAdd; // Top
textureValues.W -= amountToAdd; // Bottom
}
if ((quad.FlipFlags & TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedHorizontallyFlag) == TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedHorizontallyFlag)
{
var temp = textureValues.Y;
textureValues.Y = textureValues.X;
textureValues.X = temp;
}
if ((quad.FlipFlags & TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedVerticallyFlag) == TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedVerticallyFlag)
{
var temp = textureValues.Z;
textureValues.Z = textureValues.W;
textureValues.W = temp;
}
int tileIndex = toReturn.AddTile(position, tileDimensions,
//quad.LeftTexturePixel, quad.TopTexturePixel, quad.LeftTexturePixel + tileDimensionWidth, quad.TopTexturePixel + tileDimensionHeight);
textureValues);
if ((quad.FlipFlags & TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedDiagonallyFlag) == TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedDiagonallyFlag)
{
toReturn.ApplyDiagonalFlip(tileIndex);
}
// This was moved to outside of this conversion, to support shaps
//if (quad.QuadSpecificProperties != null)
//{
// var listToAdd = quad.QuadSpecificProperties.ToList();
// listToAdd.Add(new NamedValue { Name = "Name", Value = quad.Name });
// owner.Properties.Add(quad.Name, listToAdd);
//}
if (quad.RotationDegrees != 0)
{
// Tiled rotates clockwise :(
var rotationRadians = -MathHelper.ToRadians(quad.RotationDegrees);
Vector3 bottomLeftPos = toReturn.Vertices[tileIndex * 4].Position;
Vector3 vertPos = toReturn.Vertices[tileIndex * 4 + 1].Position;
MathFunctions.RotatePointAroundPoint(bottomLeftPos, ref vertPos, rotationRadians);
toReturn.Vertices[tileIndex * 4 + 1].Position = vertPos;
vertPos = toReturn.Vertices[tileIndex * 4 + 2].Position;
MathFunctions.RotatePointAroundPoint(bottomLeftPos, ref vertPos, rotationRadians);
toReturn.Vertices[tileIndex * 4 + 2].Position = vertPos;
vertPos = toReturn.Vertices[tileIndex * 4 + 3].Position;
MathFunctions.RotatePointAroundPoint(bottomLeftPos, ref vertPos, rotationRadians);
toReturn.Vertices[tileIndex * 4 + 3].Position = vertPos;
}
toReturn.RegisterName(quad.Name, tileIndex);
}
return toReturn;
}
public void Paste(Sprite sprite)
{
Paste(sprite, false);
}
public int Paste(Sprite sprite, bool setZTo0)
{
// here we have the Sprite's X and Y in absolute coords as well as its texture coords
// NOTE: I appended the Z coordinate for the sake of iso maps. This SHOULDN'T have an effect on the ortho maps since I believe the
// TMX->SCNX tool sets all z to zero.
// The AddTile method expects the bottom-left corner
float x = sprite.X - sprite.ScaleX;
float y = sprite.Y - sprite.ScaleY;
float z = sprite.Z;
if (setZTo0)
{
z = 0;
}
float width = 2f * sprite.ScaleX; // w
float height = 2f * sprite.ScaleY; // z
float topTextureCoordinate = sprite.TopTextureCoordinate;
float bottomTextureCoordinate = sprite.BottomTextureCoordinate;
float leftTextureCoordinate = sprite.LeftTextureCoordinate;
float rightTextureCoordinate = sprite.RightTextureCoordinate;
int tileIndex = mCurrentNumberOfTiles;
RegisterName(sprite.Name, tileIndex);
// add the textured tile to our map so that we may draw it.
return AddTile(new Vector3(x, y, z),
new Vector2(width, height),
new Vector4(leftTextureCoordinate, rightTextureCoordinate, topTextureCoordinate, bottomTextureCoordinate));
}
public void Paste(SpriteSave spriteSave)
{
Paste(spriteSave, false);
}
public int Paste(SpriteSave spriteSave, bool setZTo0)
{
// here we have the Sprite's X and Y in absolute coords as well as its texture coords
// NOTE: I appended the Z coordinate for the sake of iso maps. This SHOULDN'T have an effect on the ortho maps since I believe the
// TMX->SCNX tool sets all z to zero.
// The AddTile method expects the bottom-left corner
float x = spriteSave.X - spriteSave.ScaleX;
float y = spriteSave.Y - spriteSave.ScaleY;
float z = spriteSave.Z;
if (setZTo0)
{
z = 0;
}
float width = 2f * spriteSave.ScaleX; // w
float height = 2f * spriteSave.ScaleY; // z
float topTextureCoordinate = spriteSave.TopTextureCoordinate;
float bottomTextureCoordinate = spriteSave.BottomTextureCoordinate;
float leftTextureCoordinate = spriteSave.LeftTextureCoordinate;
float rightTextureCoordinate = spriteSave.RightTextureCoordinate;
int tileIndex = mCurrentNumberOfTiles;
RegisterName(spriteSave.Name, tileIndex);
// add the textured tile to our map so that we may draw it.
return AddTile(new Vector3(x, y, z), new Vector2(width, height), new Vector4(leftTextureCoordinate, rightTextureCoordinate, topTextureCoordinate, bottomTextureCoordinate));
}
private static void VerifySingleTexture(List<SpriteSave> spriteSaveList, int startingIndex, int count)
{
// Every Sprite should either have the same texture
if (spriteSaveList.Count != 0)
{
string texture = spriteSaveList[startingIndex].Texture;
for (int i = startingIndex + 1; i < startingIndex + count; i++)
{
SpriteSave ss = spriteSaveList[i];
if (ss.Texture != texture)
{
float leftOfSprite = ss.X - ss.ScaleX;
float indexX = leftOfSprite / (ss.ScaleX * 2);
float topOfSprite = ss.Y + ss.ScaleY;
float indexY = (0 - topOfSprite) / (ss.ScaleY * 2);
throw new Exception("All Sprites do not have the same texture");
}
}
}
}
private void RegisterName(string name, int tileIndex)
{
int throwaway;
if (!string.IsNullOrEmpty(name) && !int.TryParse(name, out throwaway))
{
// TEMPORARY:
// The tmx converter
// names all Sprites with
// a number if their name is
// not explicitly set. Therefore
// we have to ignore those and look
// for explicit names (names not numbers).
// Will talk to Domenic about this to fix it.
if (!mNamedTileOrderedIndexes.ContainsKey(name))
{
mNamedTileOrderedIndexes.Add(name, new List<int>());
}
mNamedTileOrderedIndexes[name].Add(tileIndex);
}
}
Vector2[] coords = new Vector2[4];
/// <summary>
/// Paints a texture on a tile. This method takes the index of the Sprite in the order it was added
/// to the MapDrawableBatch, so it supports any configuration including non-rectangular maps and maps with
/// gaps.
/// </summary>
/// <param name="orderedTileIndex">The index of the tile to paint - this matches the index of the tile as it was added.</param>
/// <param name="newTextureId"></param>
public void PaintTile(int orderedTileIndex, int newTextureId)
{
int currentVertex = orderedTileIndex * 4; // 4 vertices per tile
// Reusing the coords array saves us on allocation
mTileset.GetTextureCoordinateVectorsOfTextureIndex(newTextureId, coords);
// Coords are
// 3 2
//
// 0 1
mVertices[currentVertex + 0].TextureCoordinate = coords[0];
mVertices[currentVertex + 1].TextureCoordinate = coords[1];
mVertices[currentVertex + 2].TextureCoordinate = coords[2];
mVertices[currentVertex + 3].TextureCoordinate = coords[3];
}
/// <summary>
/// Sets the left and top texture coordiantes of the tile represented by orderedTileIndex. The right and bottom texture coordaintes
/// are set automatically according to the tileset dimensions.
/// </summary>
/// <param name="orderedTileIndex">The ordered tile index.</param>
/// <param name="textureXCoordinate">The left texture coordiante (in UV coordinates)</param>
/// <param name="textureYCoordinate">The top texture coordainte (in UV coordinates)</param>
public void PaintTileTextureCoordinates(int orderedTileIndex, float textureXCoordinate, float textureYCoordinate)
{
int currentVertex = orderedTileIndex * 4; // 4 vertices per tile
mTileset.GetCoordinatesForTile(coords, textureXCoordinate, textureYCoordinate);
mVertices[currentVertex + 0].TextureCoordinate = coords[0];
mVertices[currentVertex + 1].TextureCoordinate = coords[1];
mVertices[currentVertex + 2].TextureCoordinate = coords[2];
mVertices[currentVertex + 3].TextureCoordinate = coords[3];
}
public void PaintTileTextureCoordinates(int orderedTileIndex, float leftCoordinate, float topCoordinate, float rightCoordinate, float bottomCoordinate)
{
int currentVertex = orderedTileIndex * 4; // 4 vertices per tile
// Coords are
// 3 2
//
// 0 1
mVertices[currentVertex + 0].TextureCoordinate.X = leftCoordinate;
mVertices[currentVertex + 0].TextureCoordinate.Y = bottomCoordinate;
mVertices[currentVertex + 1].TextureCoordinate.X = rightCoordinate;
mVertices[currentVertex + 1].TextureCoordinate.Y = bottomCoordinate;
mVertices[currentVertex + 2].TextureCoordinate.X = rightCoordinate;
mVertices[currentVertex + 2].TextureCoordinate.Y = topCoordinate;
mVertices[currentVertex + 3].TextureCoordinate.X = leftCoordinate;
mVertices[currentVertex + 3].TextureCoordinate.Y = topCoordinate;
}
// Swaps the top-right for the bottom-left verts
public void ApplyDiagonalFlip(int orderedTileIndex)
{
int currentVertex = orderedTileIndex * 4; // 4 vertices per tile
// Coords are
// 3 2
//
// 0 1
var old0 = mVertices[currentVertex + 0].TextureCoordinate;
mVertices[currentVertex + 0].TextureCoordinate = mVertices[currentVertex + 2].TextureCoordinate;
mVertices[currentVertex + 2].TextureCoordinate = old0;
}
public void RotateTextureCoordinatesCounterclockwise(int orderedTileIndex)
{
int currentVertex = orderedTileIndex * 4; // 4 vertices per tile
// Coords are
// 3 2
//
// 0 1
var old3 = mVertices[currentVertex + 3].TextureCoordinate;
mVertices[currentVertex + 3].TextureCoordinate = mVertices[currentVertex + 2].TextureCoordinate;
mVertices[currentVertex + 2].TextureCoordinate = mVertices[currentVertex + 1].TextureCoordinate;
mVertices[currentVertex + 1].TextureCoordinate = mVertices[currentVertex + 0].TextureCoordinate;
mVertices[currentVertex + 0].TextureCoordinate = old3;
}
public void GetTextureCoordiantesForOrderedTile(int orderedTileIndex, out float textureX, out float textureY)
{
// The order is:
// 3 2
//
// 0 1
// So we want to add 3 to the index to get the top-left vert, then use
// the texture coordinates there to get the
Vector2 vector = mVertices[(orderedTileIndex * 4) + 3].TextureCoordinate;
textureX = vector.X;
textureY = vector.Y;
}
public void GetBottomLeftWorldCoordinateForOrderedTile(int orderedTileIndex, out float x, out float y)
{
// The order is:
// 3 2
//
// 0 1
// So we just need to mutiply by 4 and not add anything
Vector3 vector = mVertices[(orderedTileIndex * 4)].Position;
x = vector.X;
y = vector.Y;
}
/// <summary>
/// Adds a tile to the tile map
/// </summary>
/// <param name="bottomLeftPosition"></param>
/// <param name="dimensions"></param>
/// <param name="texture">
/// 4 points defining the boundaries in the texture for the tile.
/// (X = left, Y = right, Z = top, W = bottom)
/// </param>
public int AddTile(Vector3 bottomLeftPosition, Vector2 dimensions, Vector4 texture)
{
int toReturn = mCurrentNumberOfTiles;
int currentVertex = mCurrentNumberOfTiles * 4;
int currentIndex = mCurrentNumberOfTiles * 6; // 6 indices per tile (there are mVertices.Length/4 tiles)
float xOffset = bottomLeftPosition.X;
float yOffset = bottomLeftPosition.Y;
float zOffset = bottomLeftPosition.Z;
float width = dimensions.X;
float height = dimensions.Y;
// create vertices
mVertices[currentVertex + 0] = new VertexPositionTexture(new Vector3(xOffset + 0f, yOffset + 0f, zOffset), new Vector2(texture.X, texture.W));
mVertices[currentVertex + 1] = new VertexPositionTexture(new Vector3(xOffset + width, yOffset + 0f, zOffset), new Vector2(texture.Y, texture.W));
mVertices[currentVertex + 2] = new VertexPositionTexture(new Vector3(xOffset + width, yOffset + height, zOffset), new Vector2(texture.Y, texture.Z));
mVertices[currentVertex + 3] = new VertexPositionTexture(new Vector3(xOffset + 0f, yOffset + height, zOffset), new Vector2(texture.X, texture.Z));
// create indices
mIndices[currentIndex + 0] = currentVertex + 0;
mIndices[currentIndex + 1] = currentVertex + 1;
mIndices[currentIndex + 2] = currentVertex + 2;
mIndices[currentIndex + 3] = currentVertex + 0;
mIndices[currentIndex + 4] = currentVertex + 2;
mIndices[currentIndex + 5] = currentVertex + 3;
mCurrentNumberOfTiles++;
return toReturn;
}
/// <summary>
/// Add a tile to the map
/// </summary>
/// <param name="bottomLeftPosition"></param>
/// <param name="tileDimensions"></param>
/// <param name="textureTopLeftX">Top left X coordinate in the core texture</param>
/// <param name="textureTopLeftY">Top left Y coordinate in the core texture</param>
/// <param name="textureBottomRightX">Bottom right X coordinate in the core texture</param>
/// <param name="textureBottomRightY">Bottom right Y coordinate in the core texture</param>
public int AddTile(Vector3 bottomLeftPosition, Vector2 tileDimensions, int textureTopLeftX, int textureTopLeftY, int textureBottomRightX, int textureBottomRightY)
{
// Form vector4 for AddTile overload
var textureValues = new Vector4();
textureValues.X = (float)textureTopLeftX / (float)mTexture.Width; // Left
textureValues.Y = (float)textureBottomRightX / (float)mTexture.Width; // Right
textureValues.Z = (float)textureTopLeftY / (float)mTexture.Height; // Top
textureValues.W = (float)textureBottomRightY / (float)mTexture.Height; // Bottom
return AddTile(bottomLeftPosition, tileDimensions, textureValues);
}
/// <summary>
/// Renders the MapDrawableBatch
/// </summary>
/// <param name="camera">The currently drawing camera</param>
public void Draw(Camera camera)
{
////////////////////Early Out///////////////////
if (!AbsoluteVisible)
{
return;
}
if (mVertices.Length == 0)
{
return;
}
//////////////////End Early Out/////////////////
int firstVertIndex;
int lastVertIndex;
int indexStart;
int numberOfTriangles;
GetRenderingIndexValues(camera, out firstVertIndex, out lastVertIndex, out indexStart, out numberOfTriangles);
if (numberOfTriangles != 0)
{
TextureFilter? oldTextureFilter = null;
if (this.TextureFilter != null && this.TextureFilter != FlatRedBallServices.GraphicsOptions.TextureFilter)
{
oldTextureFilter = FlatRedBallServices.GraphicsOptions.TextureFilter;
FlatRedBallServices.GraphicsOptions.TextureFilter = this.TextureFilter.Value;
}
TextureAddressMode oldTextureAddressMode;
Effect effectTouse = PrepareRenderingStates(camera, out oldTextureAddressMode);
foreach (EffectPass pass in effectTouse.CurrentTechnique.Passes)
{
// Start each pass
pass.Apply();
int numberVertsToDraw = lastVertIndex - firstVertIndex;
// Right now this uses the (slower) DrawUserIndexedPrimitives
// It could use DrawIndexedPrimitives instead for much faster performance,
// but to do that we'd have to keep VB's around and make sure to re-create them
// whenever the graphics device is lost.
FlatRedBallServices.GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionTexture>(
PrimitiveType.TriangleList,
mVertices,
firstVertIndex,
numberVertsToDraw,
mIndices,
indexStart, numberOfTriangles);
}
Renderer.TextureAddressMode = oldTextureAddressMode;
if (ZBuffered)
{
FlatRedBallServices.GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
}
if (oldTextureFilter != null)
{
FlatRedBallServices.GraphicsOptions.TextureFilter = oldTextureFilter.Value;
}
}
}
private Effect PrepareRenderingStates(Camera camera, out TextureAddressMode oldTextureAddressMode)
{
// Set graphics states
FlatRedBallServices.GraphicsDevice.RasterizerState = RasterizerState.CullNone;
FlatRedBall.Graphics.Renderer.BlendOperation = BlendOperation.Regular;
Effect effectTouse = null;
if (ZBuffered)
{
FlatRedBallServices.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
camera.SetDeviceViewAndProjection(mAlphaTestEffect, false);
mAlphaTestEffect.World = Matrix.CreateScale(RenderingScale) * base.TransformationMatrix;
mAlphaTestEffect.Texture = mTexture;
effectTouse = mAlphaTestEffect;
}
else
{
camera.SetDeviceViewAndProjection(mBasicEffect, false);
mBasicEffect.World = Matrix.CreateScale(RenderingScale) * base.TransformationMatrix;
mBasicEffect.Texture = mTexture;
effectTouse = mBasicEffect;
}
// We won't need to use any other kind of texture
// address mode besides clamp, and clamp is required
// on the "Reach" profile when the texture is not power
// of two. Let's set it to clamp here so that we don't crash
// on non-power-of-two textures.
oldTextureAddressMode = Renderer.TextureAddressMode;
Renderer.TextureAddressMode = TextureAddressMode.Clamp;
return effectTouse;
}
private void GetRenderingIndexValues(Camera camera, out int firstVertIndex, out int lastVertIndex, out int indexStart, out int numberOfTriangles)
{
firstVertIndex = 0;
lastVertIndex = mVertices.Length;
float tileWidth = mVertices[1].Position.X - mVertices[0].Position.X;
if (mSortAxis == SortAxis.X)
{
float minX = camera.AbsoluteLeftXEdgeAt(this.Z);
float maxX = camera.AbsoluteRightXEdgeAt(this.Z);
minX -= this.X;
maxX -= this.X;
firstVertIndex = GetFirstAfterX(mVertices, minX - tileWidth);
lastVertIndex = GetFirstAfterX(mVertices, maxX) + 4;
}
else if (mSortAxis == SortAxis.Y)
{
float minY = camera.AbsoluteBottomYEdgeAt(this.Z);
float maxY = camera.AbsoluteTopYEdgeAt(this.Z);
minY -= this.Y;
maxY -= this.Y;
firstVertIndex = GetFirstAfterY(mVertices, minY - tileWidth);
lastVertIndex = GetFirstAfterY(mVertices, maxY) + 4;
}
lastVertIndex = System.Math.Min(lastVertIndex, mVertices.Length);
indexStart = 0;// (firstVertIndex * 3) / 2;
int indexEndExclusive = ((lastVertIndex - firstVertIndex) * 3) / 2;
numberOfTriangles = (indexEndExclusive - indexStart) / 3;
}
public static int GetFirstAfterX(VertexPositionTexture[] list, float xGreaterThan)
{
int min = 0;
int originalMax = list.Length / 4;
int max = list.Length / 4;
int mid = (max + min) / 2;
while (min < max)
{
mid = (max + min) / 2;
float midItem = list[mid * 4].Position.X;
if (midItem > xGreaterThan)
{
// Is this the last one?
// Not sure why this is here, because if we have just 2 items,
// this will always return a value of 1 instead
//if (mid * 4 + 4 >= list.Length)
//{
// return mid * 4;
//}
// did we find it?
if (mid > 0 && list[(mid - 1) * 4].Position.X <= xGreaterThan)
{
return mid * 4;
}
else
{
max = mid - 1;
}
}
else if (midItem <= xGreaterThan)
{
if (mid == 0)
{
return mid * 4;
}
else if (mid < originalMax - 1 && list[(mid + 1) * 4].Position.X > xGreaterThan)
{
return (mid + 1) * 4;
}
else
{
min = mid + 1;
}
}
}
if (min == 0)
{
return 0;
}
else
{
return list.Length;
}
}
public static int GetFirstAfterY(VertexPositionTexture[] list, float yGreaterThan)
{
int min = 0;
int originalMax = list.Length / 4;
int max = list.Length / 4;
int mid = (max + min) / 2;
while (min < max)
{
mid = (max + min) / 2;
float midItem = list[mid * 4].Position.Y;
if (midItem > yGreaterThan)
{
// Is this the last one?
// See comment in GetFirstAfterX
//if (mid * 4 + 4 >= list.Length)
//{
// return mid * 4;
//}
// did we find it?
if (mid > 0 && list[(mid - 1) * 4].Position.Y <= yGreaterThan)
{
return mid * 4;
}
else
{
max = mid - 1;
}
}
else if (midItem <= yGreaterThan)
{
if (mid == 0)
{
return mid * 4;
}
else if (mid < originalMax - 1 && list[(mid + 1) * 4].Position.Y > yGreaterThan)
{
return (mid + 1) * 4;
}
else
{
min = mid + 1;
}
}
}
if (min == 0)
{
return 0;
}
else
{
return list.Length;
}
}
#region XML Docs
/// <summary>
/// Here we update our batch - but this batch doesn't
/// need to be updated
/// </summary>
#endregion
public void Update()
{
float leftView = Camera.Main.AbsoluteLeftXEdgeAt(0);
float topView = Camera.Main.AbsoluteTopYEdgeAt(0);
float cameraOffsetX = leftView - CameraOriginX;
float cameraOffsetY = topView - CameraOriginY;
this.RelativeX = cameraOffsetX * _parallaxMultiplierX;
this.RelativeY = cameraOffsetY * _parallaxMultiplierY;
this.TimedActivity(TimeManager.SecondDifference, TimeManager.SecondDifferenceSquaredDividedByTwo, TimeManager.LastSecondDifference);
// The MapDrawableBatch may be attached to a LayeredTileMap (the container of all layers)
// If so, the player may move the LayeredTileMap and expect all contained layers to move along
// with it. To allow this, we need to have dependencies updated. We'll do this by simply updating
// dependencies here, although I don't know at this point if there's a better way - like if we should
// be adding this to the SpriteManager's PositionedObjectList. This is an improvement so we'll do it for
// now and revisit this in case there's a problem in the future.
this.UpdateDependencies(TimeManager.CurrentTime);
}
// TODO: I would like to somehow make this a property on the LayeredTileMap, but right now it is easier to put them here
public float CameraOriginY { get; set; }
public float CameraOriginX { get; set; }
IVisible IVisible.Parent
{
get
{
return this.Parent as IVisible;
}
}
public bool AbsoluteVisible
{
get
{
if (this.Visible)
{
var parentAsIVisible = this.Parent as IVisible;
if (parentAsIVisible == null || IgnoresParentVisibility)
{
return true;
}
else
{
// this is true, so return if the parent is visible:
return parentAsIVisible.AbsoluteVisible;
}
}
else
{
return false;
}
}
}
public bool IgnoresParentVisibility
{
get;
set;
}
#region XML Docs
/// <summary>
/// Don't call this, instead call SpriteManager.RemoveDrawableBatch
/// </summary>
#endregion
public void Destroy()
{
this.RemoveSelfFromListsBelongingTo();
}
public void MergeOntoThis(IEnumerable<MapDrawableBatch> mapDrawableBatches)
{
int quadsToAdd = 0;
int quadsOnThis = QuadCount;
foreach (var mdb in mapDrawableBatches)
{
quadsToAdd += mdb.QuadCount;
}
int totalNumberOfVerts = 4 * (this.QuadCount + quadsToAdd);
int totalNumberOfIndexes = 6 * (this.QuadCount + quadsToAdd);
var oldVerts = mVertices;
var oldIndexes = mIndices;
mVertices = new VertexPositionTexture[totalNumberOfVerts];
mIndices = new int[totalNumberOfIndexes];
oldVerts.CopyTo(mVertices, 0);
oldIndexes.CopyTo(mIndices, 0);
int currentQuadIndex = quadsOnThis;
int index = 0;
foreach (var mdb in mapDrawableBatches)
{
int startVert = currentQuadIndex * 4;
int startIndex = currentQuadIndex * 6;
int numberOfIndices = mdb.mIndices.Length;
int numberOfNewVertices = mdb.mVertices.Length;
mdb.mVertices.CopyTo(mVertices, startVert);
mdb.mIndices.CopyTo(mIndices, startIndex);
for (int i = startIndex; i < startIndex + numberOfIndices; i++)
{
mIndices[i] += startVert;
}
for (int i = startVert; i < startVert + numberOfNewVertices; i++)
{
mVertices[i].Position.Z += index + 1;
}
foreach (var kvp in mdb.mNamedTileOrderedIndexes)
{
string key = kvp.Key;
List<int> toAddTo;
if (mNamedTileOrderedIndexes.ContainsKey(key))
{
toAddTo = mNamedTileOrderedIndexes[key];
}
else
{
toAddTo = new List<int>();
mNamedTileOrderedIndexes[key] = toAddTo;
}
foreach (var namedIndex in kvp.Value)
{
toAddTo.Add(namedIndex + currentQuadIndex);
}
}
currentQuadIndex += mdb.QuadCount;
index++;
}
}
public void RemoveQuads(IEnumerable<int> quadIndexes)
{
var vertList = mVertices.ToList();
// Reverse - go from biggest to smallest
foreach (var indexToRemove in quadIndexes.Distinct().OrderBy(item => -item))
{
// and go from biggest to smallest here too
vertList.RemoveAt(indexToRemove * 4 + 3);
vertList.RemoveAt(indexToRemove * 4 + 2);
vertList.RemoveAt(indexToRemove * 4 + 1);
vertList.RemoveAt(indexToRemove * 4 + 0);
}
mVertices = vertList.ToArray();
// The mNamedTileOrderedIndexes is a dictionary that stores which indexes are stored
// with which tiles. For example, the key in the dictionary may be "Lava", in which case
// the value is the indexes of the tiles that use the Lava tile.
// If we do end up removing any quads, then all following quads will shift, so we need to
// adjust the indexes so the naming works correctly
List<int> orderedInts = quadIndexes.OrderBy(item => item).Distinct().ToList();
int numberOfRemovals = 0;
foreach (var kvp in mNamedTileOrderedIndexes)
{
var ints = kvp.Value;
numberOfRemovals = 0;
for (int i = 0; i < ints.Count; i++)
{
// Nothing left to test, so subtract and move on....
if (numberOfRemovals == orderedInts.Count)
{
ints[i] -= numberOfRemovals;
}
else if (ints[i] == orderedInts[numberOfRemovals])
{
ints.Clear();
break;
}
else if (ints[i] < orderedInts[numberOfRemovals])
{
ints[i] -= numberOfRemovals;
}
else
{
while (numberOfRemovals < orderedInts.Count && ints[i] > orderedInts[numberOfRemovals])
{
numberOfRemovals++;
}
if (numberOfRemovals < orderedInts.Count && ints[i] == orderedInts[numberOfRemovals])
{
ints.Clear();
break;
}
ints[i] -= numberOfRemovals;
}
}
}
}
#endregion
}
public static class MapDrawableBatchExtensionMethods
{
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.Text
{
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// sequential blocks of bytes are converted into blocks of characters through
// calls to the GetChars method. The decoder maintains state between the
// conversions, allowing it to correctly decode byte sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Decoder abstract base
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
internal class DecoderNLS : Decoder
{
// Remember our encoding
private Encoding _encoding;
private bool _mustFlush;
internal bool _throwOnOverflow;
internal int _bytesUsed;
private int _leftoverBytes; // leftover data from a previous invocation of GetChars (up to 4 bytes)
private int _leftoverByteCount; // number of bytes of actual data in _leftoverBytes
internal DecoderNLS(Encoding encoding)
{
_encoding = encoding;
_fallback = this._encoding.DecoderFallback;
this.Reset();
}
// This is used by our child deserializers
internal DecoderNLS()
{
_encoding = null;
this.Reset();
}
public override void Reset()
{
ClearLeftoverData();
_fallbackBuffer?.Reset();
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return GetCharCount(bytes, index, count, false);
}
public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes),
SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(bytes),
SR.ArgumentOutOfRange_IndexCountBuffer);
// Just call pointer version
fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes))
return GetCharCount(pBytes + index, count, flush);
}
public unsafe override int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes),
SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_NeedNonNegNum);
// Remember the flush
_mustFlush = flush;
_throwOnOverflow = true;
// By default just call the encoding version, no flush by default
return _encoding.GetCharCount(bytes, count, this);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false);
}
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, bool flush)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
SR.ArgumentOutOfRange_IndexCountBuffer);
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException(nameof(charIndex),
SR.ArgumentOutOfRange_Index);
int charCount = chars.Length - charIndex;
// Just call pointer version
fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes))
fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars))
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount,
pChars + charIndex, charCount, flush);
}
public unsafe override int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
// Remember our flush
_mustFlush = flush;
_throwOnOverflow = true;
// By default just call the encodings version
return _encoding.GetChars(bytes, byteCount, chars, charCount, this);
}
// This method is used when the output buffer might not be big enough.
// Just call the pointer version. (This gets chars)
public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate parameters
if (bytes == null || chars == null)
throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)),
SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
SR.ArgumentOutOfRange_IndexCountBuffer);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
// Just call the pointer version (public overrides can't do this)
fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes))
{
fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars))
{
Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush,
out bytesUsed, out charsUsed, out completed);
}
}
}
// This is the version that used pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting chars
public unsafe override void Convert(byte* bytes, int byteCount,
char* chars, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
// We don't want to throw
_mustFlush = flush;
_throwOnOverflow = false;
_bytesUsed = 0;
// Do conversion
charsUsed = _encoding.GetChars(bytes, byteCount, chars, charCount, this);
bytesUsed = _bytesUsed;
// Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (bytesUsed == byteCount) && (!flush || !this.HasState) &&
(_fallbackBuffer == null || _fallbackBuffer.Remaining == 0);
// Our data thingy are now full, we can return
}
public bool MustFlush
{
get
{
return _mustFlush;
}
}
// Anything left in our decoder?
internal virtual bool HasState
{
get
{
return false;
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow)
internal void ClearMustFlush()
{
_mustFlush = false;
}
internal ReadOnlySpan<byte> GetLeftoverData()
{
return MemoryMarshal.AsBytes(new ReadOnlySpan<int>(ref _leftoverBytes, 1)).Slice(0, _leftoverByteCount);
}
internal void SetLeftoverData(ReadOnlySpan<byte> bytes)
{
bytes.CopyTo(MemoryMarshal.AsBytes(new Span<int>(ref _leftoverBytes, 1)));
_leftoverByteCount = bytes.Length;
}
internal bool HasLeftoverData => _leftoverByteCount != 0;
internal void ClearLeftoverData()
{
_leftoverByteCount = 0;
}
internal int DrainLeftoverDataForGetCharCount(ReadOnlySpan<byte> bytes, out int bytesConsumed)
{
// Quick check: we _should not_ have leftover fallback data from a previous invocation,
// as we'd end up consuming any such data and would corrupt whatever Convert call happens
// to be in progress. Unlike EncoderNLS, this is simply a Debug.Assert. No exception is thrown.
Debug.Assert(_fallbackBuffer is null || _fallbackBuffer.Remaining == 0, "Should have no data remaining in the fallback buffer.");
// Copy the existing leftover data plus as many bytes as possible of the new incoming data
// into a temporary concated buffer, then get its char count by decoding it.
Span<byte> combinedBuffer = stackalloc byte[4];
combinedBuffer = combinedBuffer.Slice(0, ConcatInto(GetLeftoverData(), bytes, combinedBuffer));
int charCount = 0;
switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed))
{
case OperationStatus.Done:
charCount = value.Utf16SequenceLength;
goto Finish; // successfully transcoded bytes -> chars
case OperationStatus.NeedMoreData:
if (MustFlush)
{
goto case OperationStatus.InvalidData; // treat as equivalent to bad data
}
else
{
goto Finish; // consumed some bytes, output 0 chars
}
case OperationStatus.InvalidData:
break;
default:
Debug.Fail("Unexpected OperationStatus return value.");
break;
}
// Couldn't decode the buffer. Fallback the buffer instead.
if (FallbackBuffer.Fallback(combinedBuffer.Slice(0, combinedBufferBytesConsumed).ToArray(), index: 0))
{
charCount = _fallbackBuffer.DrainRemainingDataForGetCharCount();
Debug.Assert(charCount >= 0, "Fallback buffer shouldn't have returned a negative char count.");
}
Finish:
bytesConsumed = combinedBufferBytesConsumed - _leftoverByteCount; // amount of 'bytes' buffer consumed just now
return charCount;
}
internal int DrainLeftoverDataForGetChars(ReadOnlySpan<byte> bytes, Span<char> chars, out int bytesConsumed)
{
// Quick check: we _should not_ have leftover fallback data from a previous invocation,
// as we'd end up consuming any such data and would corrupt whatever Convert call happens
// to be in progress. Unlike EncoderNLS, this is simply a Debug.Assert. No exception is thrown.
Debug.Assert(_fallbackBuffer is null || _fallbackBuffer.Remaining == 0, "Should have no data remaining in the fallback buffer.");
// Copy the existing leftover data plus as many bytes as possible of the new incoming data
// into a temporary concated buffer, then transcode it from bytes to chars.
Span<byte> combinedBuffer = stackalloc byte[4];
combinedBuffer = combinedBuffer.Slice(0, ConcatInto(GetLeftoverData(), bytes, combinedBuffer));
int charsWritten = 0;
bool persistNewCombinedBuffer = false;
switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed))
{
case OperationStatus.Done:
if (value.TryEncodeToUtf16(chars, out charsWritten))
{
goto Finish; // successfully transcoded bytes -> chars
}
else
{
goto DestinationTooSmall;
}
case OperationStatus.NeedMoreData:
if (MustFlush)
{
goto case OperationStatus.InvalidData; // treat as equivalent to bad data
}
else
{
persistNewCombinedBuffer = true;
goto Finish; // successfully consumed some bytes, output no chars
}
case OperationStatus.InvalidData:
break;
default:
Debug.Fail("Unexpected OperationStatus return value.");
break;
}
// Couldn't decode the buffer. Fallback the buffer instead.
if (FallbackBuffer.Fallback(combinedBuffer.Slice(0, combinedBufferBytesConsumed).ToArray(), index: 0)
&& !_fallbackBuffer.TryDrainRemainingDataForGetChars(chars, out charsWritten))
{
goto DestinationTooSmall;
}
Finish:
if (persistNewCombinedBuffer)
{
Debug.Assert(combinedBufferBytesConsumed == combinedBuffer.Length, "We should be asked to persist the entire combined buffer.");
SetLeftoverData(combinedBuffer); // the buffer still only contains partial data; a future call to Convert will need it
}
else
{
ClearLeftoverData(); // the buffer contains no partial data; we'll go down the normal paths
}
bytesConsumed = combinedBufferBytesConsumed - _leftoverByteCount; // amount of 'bytes' buffer consumed just now
return charsWritten;
DestinationTooSmall:
// If we got to this point, we're trying to write chars to the output buffer, but we're unable to do
// so. Unlike EncoderNLS, this type does not allow partial writes to the output buffer. Since we know
// draining leftover data is the first operation performed by any DecoderNLS API, there was no
// opportunity for any code before us to make forward progress, so we must fail immediately.
_encoding.ThrowCharsOverflow(this, nothingDecoded: true);
throw null; // will never reach this point
}
/// <summary>
/// Given a byte buffer <paramref name="dest"/>, concatenates as much of <paramref name="srcLeft"/> followed
/// by <paramref name="srcRight"/> into it as will fit, then returns the total number of bytes copied.
/// </summary>
private static int ConcatInto(ReadOnlySpan<byte> srcLeft, ReadOnlySpan<byte> srcRight, Span<byte> dest)
{
int total = 0;
for (int i = 0; i < srcLeft.Length; i++)
{
if ((uint)total >= (uint)dest.Length)
{
goto Finish;
}
else
{
dest[total++] = srcLeft[i];
}
}
for (int i = 0; i < srcRight.Length; i++)
{
if ((uint)total >= (uint)dest.Length)
{
goto Finish;
}
else
{
dest[total++] = srcRight[i];
}
}
Finish:
return total;
}
}
}
| |
/**
* @file
* This file defines a class for parsing and generating message bus messages
*/
/******************************************************************************
* Copyright (c) 2012-2013, AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace AllJoynUnity
{
public partial class AllJoyn
{
public const int ALLJOYN_MAX_NAME_LEN = 255; /*!< The maximum length of certain bus names */
public const int ALLJOYN_MAX_ARRAY_LEN = 131072; /*!< DBus limits array length to 2^26. AllJoyn limits it to 2^17 */
public const int ALLJOYN_MAX_PACKET_LEN = (ALLJOYN_MAX_ARRAY_LEN + 4096); /*!< DBus limits packet length to 2^27. AllJoyn limits it further to 2^17 + 4096 to allow for 2^17 payload */
/** @name Endianness indicators */
// @{
/** indicates the bus is little endian */
public const byte ALLJOYN_LITTLE_ENDIAN = 0x6c; // hex value for ascii letter 'l'
/** indicates the bus is big endian */
public const byte ALLJOYN_BIG_ENDIAN = 0x42; // hex value for ascii letter 'B'
// @}
/** @name Flag types */
// @{
/** No reply is expected*/
public const byte ALLJOYN_FLAG_NO_REPLY_EXPECTED = 0x01;
/** Auto start the service */
public const byte ALLJOYN_FLAG_AUTO_START = 0x02;
/** Allow messages from remote hosts (valid only in Hello message) */
public const byte ALLJOYN_FLAG_ALLOW_REMOTE_MSG = 0x04;
/** Sessionless message */
public const byte ALLJOYN_FLAG_SESSIONLESS = 0x10;
/** Global (bus-to-bus) broadcast */
public const byte ALLJOYN_FLAG_GLOBAL_BROADCAST = 0x20;
/** Header is compressed */
public const byte ALLJOYN_FLAG_COMPRESSED = 0x40;
/** Body is encrypted */
public const byte ALLJOYN_FLAG_ENCRYPTED = 0x80;
// @}
/** ALLJOYN protocol version */
public const byte ALLJOYN_MAJOR_PROTOCOL_VERSION = 1;
/**
* Message is a reference counted (managed) version of _Message
*/
public class Message : IDisposable
{
/** Message types */
public enum Type : int
{
Invalid = 0, ///< an invalid message type
MethodCall = 1, ///< a method call message type
MethodReturn = 2, ///< a method return message type
Error = 3, ///< an error message type
Signal = 4 ///< a signal message type
}
/**
* Constructor for a message
*
* @param bus The bus that this message is sent or received on.
*/
public Message(BusAttachment bus)
{
_message = alljoyn_message_create(bus.UnmanagedPtr);
}
/**
* Copy constructor for a message
*
* @param other Message to copy from.
*/
internal Message(IntPtr message)
{
_message = message;
_isDisposed = true;
}
/**
* Return a specific argument.
*
* @param index The index of the argument to get.
*
* @return
* - The argument
* - NULL if unmarshal failed or there is not such argument.
*/
public MsgArg GetArg(int index)
{
IntPtr msgArgs = alljoyn_message_getarg(_message, (UIntPtr)index);
return (msgArgs != IntPtr.Zero ? new MsgArg(msgArgs) : null);
}
/**
* Return the arguments for this Message.
*
* @return An AllJoyn.MsgArg containing all the arguments for this Message
*/
public MsgArg GetArgs()
{
IntPtr MsgArgPtr;
UIntPtr numArgs;
alljoyn_message_getargs(_message, out numArgs, out MsgArgPtr);
MsgArg args = new MsgArg(MsgArgPtr, (int)numArgs);
return args;
}
/**
* Unpack and return the arguments for this message. This method uses the
* functionality from AllJoyn.MsgArg.Get(string, out object) see MsgArg.cs
* for documentation.
*
* @param signature The signature to match against the message arguments.
* @param value object unpacked values the values into
* @return
* - QStatus.OK if the signature matched and MsgArg was successfully unpacked.
* - QStatus.BUS_SIGNATURE_MISMATCH if the signature did not match.
* - An error status otherwise
*/
public QStatus GetArgs(string signature, out object value)
{
return GetArgs().Get(signature, out value);
}
/**
* Accessor function to get the sender for this message.
*
* @return
* - The senders well-known name string stored in the AllJoyn header field.
* - An empty string if the message did not specify a sender.
*/
[Obsolete("Use the property Sender instead of the function GetSender")]
public string GetSender()
{
IntPtr sender = alljoyn_message_getsender(_message);
return (sender != IntPtr.Zero ? Marshal.PtrToStringAnsi(sender) : null);
}
/**
* Return a specific argument.
*
* @param index The index of the argument to get.
*
* @return
* - The argument
* - NULL if unmarshal failed or there is not such argument.
*/
public MsgArg this[int i]
{
get
{
return GetArg(i);
}
}
/**
* Return true if message's TTL header indicates that it is expired
*
* @return Returns true if the message's TTL header indicates that is has expired.
*/
public bool IsExpired()
{
uint throw_away_value;
return alljoyn_message_isexpired(_message, out throw_away_value);
}
/**
* Return true if message's TTL header indicates that it is expired
*
* @param[out] tillExpireMS Written with number of milliseconds before message expires
* If message never expires value is set to the uint.MaxValue.
*
* @return Returns true if the message's TTL header indicates that is has expired.
*/
public bool IsExpired(out uint tillExpireMS)
{
return alljoyn_message_isexpired(_message, out tillExpireMS);
}
/**
* If the message is an error message returns the error name and optionally the error message string
*
* @param[out] errorMessage Return the error message string stored
*
* @return
* - If error detected return error name stored in the AllJoyn header field
* - NULL if error not detected
*/
public string GetErrorName(out string errorMessage)
{
UIntPtr errorMessageSz;
alljoyn_message_geterrorname(_message, IntPtr.Zero, out errorMessageSz);
byte[] sink = new byte[(int)errorMessageSz];
GCHandle gch = GCHandle.Alloc(sink, GCHandleType.Pinned);
IntPtr errorName = alljoyn_message_geterrorname(_message, gch.AddrOfPinnedObject(), out errorMessageSz);
gch.Free();
// The returned buffer will contain a nul character an so we must remove the last character.
errorMessage = System.Text.ASCIIEncoding.ASCII.GetString(sink, 0, (int)errorMessageSz - 1);
return Marshal.PtrToStringAnsi(errorName);
}
/**
* Returns an XML string representation of the message
*
* @return an XML string representation of the message
*
*/
public override string ToString()
{
UIntPtr signatureSz = alljoyn_message_tostring(_message, IntPtr.Zero, (UIntPtr)0);
byte[] sink = new byte[(int)signatureSz];
GCHandle gch = GCHandle.Alloc(sink, GCHandleType.Pinned);
alljoyn_message_tostring(_message, gch.AddrOfPinnedObject(), signatureSz);
gch.Free();
// The returned buffer will contain a nul character an so we must remove the last character.
if ((int)signatureSz != 0)
{
return System.Text.ASCIIEncoding.ASCII.GetString(sink, 0, (int)signatureSz - 1);
}
else
{
return "";
}
}
#region Properties
/**
* Determine if message is a broadcast signal.
*
* @return Return true if this is a broadcast signal.
*/
public bool IsBroadcastSignal
{
get
{
return alljoyn_message_isbroadcastsignal(_message);
}
}
/**
* Messages broadcast to all devices are global broadcast messages.
*
* @return Return true if this is a global broadcast message.
*/
public bool IsGlobalBroadcast
{
get
{
return alljoyn_message_isglobalbroadcast(_message);
}
}
/**
* Messages sent without sessions are sessionless.
*
* @return Return true if this is a sessionless message.
*/
public bool IsSessionless
{
get
{
return alljoyn_message_issessionless(_message);
}
}
/**
* Returns the flags for the message.
* @return flags for the message
*
* @see Flag types
*/
public byte Flags
{
get
{
return alljoyn_message_getflags(_message);
}
}
/**
* Determine if the message is marked as unreliable. Unreliable messages have a
* non-zero time-to-live and may be silently discarded.
*
* @return Returns true if the message is unreliable, that is, has a
* non-zero time-to-live.
*/
public bool IsUnreliable
{
get
{
return alljoyn_message_isunreliable(_message);
}
}
/**
* Determine if the message was encrypted.
*
* @return Returns true if the message was encrypted.
*/
public bool IsEncrypted
{
get
{
return alljoyn_message_isencrypted(_message);
}
}
/**
* Get the name of the authentication mechanism that was used to generate
* the encryption key if the message is encrypted.
*
* @return the name of an authentication mechanism or an empty string.
*/
public string AuthMechanism
{
get
{
return Marshal.PtrToStringAnsi(alljoyn_message_getauthmechanism(_message));
}
}
/**
* Return the type of the message
*
* @return message type
*/
public Type MessageType
{
get
{
return (Type)alljoyn_message_gettype(_message);
}
}
/**
* Accessor function to get serial number for the message. Usually only
* important for AllJoyn.Message.MethodCall for matching up the reply to
* the call.
*
* @return the serial number of the Message
*/
public uint CallSerial
{
get
{
return alljoyn_message_getcallserial(_message);
}
}
/**
* Get the signature for this message
*
* @return
* - The AllJoyn SIGNATURE string stored in the AllJoyn header field
* - An empty string if unable to find the AllJoyn signature
*/
public string Signature
{
get
{
return Marshal.PtrToStringAnsi(alljoyn_message_getsignature(_message));
}
}
/**
* Accessor function to get the object path for this message
*
* @return
* - The AllJoyn object path string stored in the AllJoyn header field
* - An empty string if unable to find the AllJoyn object path
*/
public string ObjectPath
{
get
{
return Marshal.PtrToStringAnsi(alljoyn_message_getobjectpath(_message));
}
}
/**
* Accessor function to get the interface for this message
*
* @return
* - The AllJoyn interface string stored in the AllJoyn header field
* - An empty string if unable to find the interface
*/
public string Interface
{
get
{
return Marshal.PtrToStringAnsi(alljoyn_message_getinterface(_message));
}
}
/**
* Accessor function to get the member (method/signal) name for this message
*
* @return
* - The AllJoyn member (method/signal) name string stored in the AllJoyn header field
* - An empty string if unable to find the member name
*/
public string MemberName
{
get
{
return Marshal.PtrToStringAnsi(alljoyn_message_getmembername(_message));
}
}
/**
* Accessor function to get the reply serial number for the message. Only meaningful for
* AllJoyn.Message.Type.MethodReturn
*
* @return
* - The serial number for the message stored in the AllJoyn header field
* - Zero if unable to find the serial number. Note that 0 is an invalid serial number.
*/
public uint ReplySerial
{
get
{
return alljoyn_message_getreplyserial(_message);
}
}
/**
* Accessor function to get the sender for this message.
*
* @return
* - The senders well-known name string stored in the AllJoyn header field.
* - An empty string if the message did not specify a sender.
*/
public string Sender
{
get
{
return Marshal.PtrToStringAnsi(alljoyn_message_getsender(_message));
}
}
/**
* Get the unique name of the endpoint that the message was received on.
*
* @return
* - The unique name of the endpoint that the message was received on.
*/
public string ReceiveEndPointName
{
get
{
return Marshal.PtrToStringAnsi(alljoyn_message_getreceiveendpointname(_message));
}
}
/**
* Accessor function to get the destination for this message
*
* @return
* - The message destination string stored in the AllJoyn header field.
* - An empty string if unable to find the message destination.
*/
public string Destination
{
get
{
return Marshal.PtrToStringAnsi(alljoyn_message_getdestination(_message));
}
}
/**
* Accessor function to get the compression token for the message.
*
* @return
* - Compression token for the message stored in the AllJoyn header field
* - 0 'zero' if there is no compression token.
*/
public uint CompressionToken
{
get
{
return alljoyn_message_getcompressiontoken(_message);
}
}
/**
* Accessor function to get the session id for the message.
*
* @return
* - Session id for the message
* - 0 'zero' if sender did not specify a session
*/
public uint SessionId
{
get
{
return alljoyn_message_getsessionid(_message);
}
}
/**
* Returns a string that provides a brief description of the message
*
* @return A string that provides a brief description of the message
*/
public string Description
{
get
{
UIntPtr descriptionSz = alljoyn_message_description(_message, IntPtr.Zero, (UIntPtr)0);
byte[] sink = new byte[(int)descriptionSz];
GCHandle gch = GCHandle.Alloc(sink, GCHandleType.Pinned);
alljoyn_message_description(_message, gch.AddrOfPinnedObject(), descriptionSz);
gch.Free();
// The returned buffer will contain a nul character an so we must remove the last character.
if ((int)descriptionSz != 0)
{
return System.Text.ASCIIEncoding.ASCII.GetString(sink, 0, (int)descriptionSz - 1);
}
else
{
return "";
}
}
}
/**
* Returns the timestamp (in milliseconds) for this message. If the message header contained a
* timestamp this is the estimated timestamp for when the message was sent by the remote device,
* otherwise it is the timestamp for when the message was unmarshaled. Note that the timestamp
* is always relative to local time.
*
* @return The timestamp for this message.
*/
public uint TimeStamp
{
get
{
return alljoyn_message_gettimestamp(_message);
}
}
#endregion
#region IDisposable
~Message()
{
Dispose(false);
}
/**
* Dispose the Message
* @param disposing describes if its activly being disposed
*/
protected virtual void Dispose(bool disposing)
{
if(!_isDisposed)
{
alljoyn_message_destroy(_message);
_message = IntPtr.Zero;
}
_isDisposed = true;
}
/**
* Dispose the Message
*/
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region DLL Imports
[DllImport(DLL_IMPORT_TARGET)]
private static extern IntPtr alljoyn_message_create(IntPtr bus);
[DllImport(DLL_IMPORT_TARGET)]
private static extern void alljoyn_message_destroy(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private static extern IntPtr alljoyn_message_getarg(IntPtr msg, UIntPtr argN);
[DllImport(DLL_IMPORT_TARGET)]
private static extern void alljoyn_message_getargs(IntPtr msg, out UIntPtr numArgs, out IntPtr args);
[DllImport(DLL_IMPORT_TARGET)]
private static extern IntPtr alljoyn_message_getsender(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
[return: MarshalAs(UnmanagedType.U1)]
private extern static bool alljoyn_message_isbroadcastsignal(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
[return: MarshalAs(UnmanagedType.U1)]
private extern static bool alljoyn_message_isglobalbroadcast(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
[return: MarshalAs(UnmanagedType.U1)]
private extern static bool alljoyn_message_issessionless(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static byte alljoyn_message_getflags(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
[return: MarshalAs(UnmanagedType.U1)]
private extern static bool alljoyn_message_isexpired(IntPtr msg, out uint tillExpireMS);
[DllImport(DLL_IMPORT_TARGET)]
[return: MarshalAs(UnmanagedType.U1)]
private extern static bool alljoyn_message_isunreliable(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
[return: MarshalAs(UnmanagedType.U1)]
private extern static bool alljoyn_message_isencrypted(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static IntPtr alljoyn_message_getauthmechanism(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static int alljoyn_message_gettype(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static uint alljoyn_message_getcallserial(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static IntPtr alljoyn_message_getsignature(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static IntPtr alljoyn_message_getobjectpath(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static IntPtr alljoyn_message_getinterface(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static IntPtr alljoyn_message_getmembername(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static uint alljoyn_message_getreplyserial(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static IntPtr alljoyn_message_getreceiveendpointname(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static IntPtr alljoyn_message_getdestination(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static uint alljoyn_message_getcompressiontoken(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static uint alljoyn_message_getsessionid(IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static IntPtr alljoyn_message_geterrorname(IntPtr msg, IntPtr erroMessage, out UIntPtr errorMessage_size);
[DllImport(DLL_IMPORT_TARGET)]
private extern static UIntPtr alljoyn_message_tostring(IntPtr msg, IntPtr str, UIntPtr buf);
[DllImport(DLL_IMPORT_TARGET)]
private extern static UIntPtr alljoyn_message_description(IntPtr msg, IntPtr str, UIntPtr bug);
[DllImport(DLL_IMPORT_TARGET)]
private extern static uint alljoyn_message_gettimestamp(IntPtr msg);
#endregion
#region Internal Properties
internal IntPtr UnmanagedPtr
{
get
{
return _message;
}
}
#endregion
#region Data
IntPtr _message;
bool _isDisposed = false;
#endregion
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using EmsApi.Client.V2;
using EmsApi.Dto.V2;
using FluentAssertions;
using TechTalk.SpecFlow;
namespace EmsApi.Tests.SpecFlow
{
[Binding, Scope( Feature = "AnalyticSets" )]
public class AnalyticSetsSteps : FeatureTest
{
private NewAnalyticCollection m_newAnalyticCollection;
private UpdateAnalyticCollection m_updateAnalyticCollection;
private NewAnalyticSet m_newAnalyticSet;
private UpdateAnalyticSet m_updateAnalyticSet;
private NewAnalyticSetGroup m_newAnalyticSetGroup;
private UpdateAnalyticSetGroup m_updateAnalyticSetGroup;
[When( @"I run GetAnalyticSetGroups" )]
public void WhenIRunGetAnalyticSetGroups()
{
m_result.Object = m_api.AnalyticSets.GetAnalyticSetGroups();
}
[When( @"I run GetAnalyticSetGroup and enter an analytic group id of '(.*)'" )]
public void WhenIRunGetAnalyticSetGroupAndEnterAnAnalyticGroupIdOf( string p0 )
{
m_result.Object = m_api.AnalyticSets.GetAnalyticSetGroup( p0 );
}
[When( @"I run GetAnalyticSet and enter a group id of '(.*)' and a set name of '(.*)'" )]
public void WhenIRunGetAnalyticSetAndEnterAGroupIdOfAndASetNameOf( string p0, string p1 )
{
m_result.Object = m_api.AnalyticSets.GetAnalyticSet( p0, p1 );
}
[Then( @"An AnalyticSetGroup object is returned" )]
public void ThenAnAnalyticSetGroupObjectIsReturned()
{
m_result.Object.ShouldNotBeNullOfType<AnalyticSetGroup>();
}
[Then( @"An AnalyticSet object is returned" )]
public void ThenAnAnalyticSetObjectIsReturned()
{
m_result.Object.ShouldNotBeNullOfType<AnalyticSet>();
}
[Then( @"It has the name '(.*)'" )]
public void ThenItHasTheName( string p0 )
{
m_result.GetPropertyValue<string>( "Name" ).Should().Be( p0 );
}
[Given( @"I have a NewAnalyticSetGroup with name '(.*)'" )]
public void GivenIHaveANewAnalyticSetGroupWithName( string p0 )
{
m_newAnalyticSetGroup = new NewAnalyticSetGroup
{
Name = p0,
ParentGroupId = "Root"
};
}
[When( @"I run CreateAnalyticSetGroup with group id '(.*)'" )]
public void WhenIRunCreateAnalyticSetGroupWithGroupId( string p0 )
{
m_result.Object = m_api.AnalyticSets.CreateAnalyticSetGroup( m_newAnalyticSetGroup );
}
[Then( @"An AnalyticSetGroupCreated object is returned" )]
public void ThenAnAnalyticSetGroupCreatedObjectIsReturned()
{
m_result.Object.ShouldNotBeNullOfType<AnalyticSetGroupCreated>();
}
[Given( @"I have a UpdateAnalyticSetGroup" )]
public void GivenIHaveAUpdateAnalyticSetGroup()
{
m_updateAnalyticSetGroup = new UpdateAnalyticSetGroup
{
Name = "Updated Analytic Set Group",
ParentGroupId = "Root"
};
}
[When( @"I run UpdateAnalyticSetGroup with group id '(.*)'" )]
public void WhenIRunUpdateAnalyticSetGroupWithGroupId( string p0 )
{
m_result.Object = m_api.AnalyticSets.UpdateAnalyticSetGroup( p0, m_updateAnalyticSetGroup );
}
[Then( @"An AnalyticSetGroupUpdated object is returned" )]
public void ThenAnAnalyticSetGroupUpdatedObjectIsReturned()
{
m_result.Object.ShouldNotBeNullOfType<AnalyticSetGroupUpdated>();
}
[When( @"I run GetAnalyticSetGroup with group id '(.*)'" )]
public void WhenIRunGetAnalyticSetGroupWithGroupId( string p0 )
{
m_result.Object = m_api.AnalyticSets.GetAnalyticSetGroup( p0 );
}
[When( @"I run DeleteAnalyticSetGroup with group id '(.*)'" )]
public void WhenIRunDeleteAnalyticSetGroupWithGroupId( string p0 )
{
m_api.AnalyticSets.DeleteAnalyticSetGroup( p0 );
}
[Then( @"the analytic set group with id '(.*)' does not exist" )]
public void ThenTheAnalyticSetGroupWithIdDoesNotExist( string p0 )
{
Action getDeletedCollection = () =>
{
m_api.AnalyticSets.GetAnalyticSetGroup( p0 );
};
getDeletedCollection.Should().Throw<EmsApiException>()
.WithMessage( "One or more errors occurred. (Response status code does not indicate success: 404 (Not Found).)" );
}
[Given( @"I have a NewAnalyticSet with name '(.*)'" )]
public void GivenIHaveANewAnalyticSetWithName( string p0 )
{
m_newAnalyticSet = new NewAnalyticSet
{
Name = p0,
Description = "new analytic set",
Items = new Collection<NewAnalyticSetItem>
{
new NewAnalyticSetItem {
AnalyticId = "H4sIAAAAAAAEAJ2STW/CMAyGz0PiPyAO3NIkbekHsEqTuCDBBcS0qxunEKkkrA1jP39tUWDVtstuie3ntf0mi62sTfkBeSlXKLVVhZLV6PNU6nqmnsdHa88zSq/Xq3cNPFMdqM8Yp2+b9U4c5QmI0rUFLeT4xtyJukvXHoIFYbStQFjHh5TF9AWVt69gnA0Ho9HiNoWsVpgtoVyqk9S1MvoVyotc0G/ZXvXuLEUzsFg2TbJJaedbY+zkYOftuS/iEO+x73+2bMWHg6enXoM2CAgsRT8gPPKRhBEggTBICDCBIAvMgyJpIdqjnNTGoGzvayOgXGFX6GKuplujDfhJMY0lByLzKCehSHnTaiqIz30meYxpDqxTuBONRL/3X5Y476gz8uF9z+tfX2Gv1ful+UWZABA+a2zgQcRJEQRIRJGnJMUkSrFgYRjGP4Xv+HDgkv1fmX0BGyq1a6wCAAA="
}
}
};
}
[When( @"I run CreateAnalyticSet with group id '(.*)'" )]
public void WhenIRunCreateAnalyticSetWithGroupId( string p0 )
{
m_result.Object = m_api.AnalyticSets.CreateAnalyticSet( p0, m_newAnalyticSet );
}
[Then( @"An AnalyticSetCreated object is returned" )]
public void ThenAnAnalyticSetCreatedObjectIsReturned()
{
m_result.Object.ShouldNotBeNullOfType<AnalyticSetCreated>();
}
[When( @"I run GetAnalyticSet with group id '(.*)' and analytic name '(.*)'" )]
public void WhenIRunGetAnalyticSetWithGroupIdAndAnalyticName( string p0, string p1 )
{
m_result.Object = m_api.AnalyticSets.GetAnalyticSet( p0, p1 );
}
[Then( @"it has the description '(.*)'" )]
public void ThenItHasTheDescription( string p0 )
{
m_result.GetPropertyValue<string>( "Description" ).Should().Be( p0 );
}
[Given( @"I have a UpdateAnalyticSet" )]
public void GivenIHaveAUpdateAnalyticSet()
{
m_updateAnalyticSet = new UpdateAnalyticSet
{
Description = "updated analytic set",
Items = new Collection<NewAnalyticSetItem>
{
new NewAnalyticSetItem
{
AnalyticId = "H4sIAAAAAAAEAJ2STW/CMAyGz0PiPyAO3NIkbekHsEqTuCDBBcS0qxunEKkkrA1jP39tUWDVtstuie3ntf0mi62sTfkBeSlXKLVVhZLV6PNU6nqmnsdHa88zSq/Xq3cNPFMdqM8Yp2+b9U4c5QmI0rUFLeT4xtyJukvXHoIFYbStQFjHh5TF9AWVt69gnA0Ho9HiNoWsVpgtoVyqk9S1MvoVyotc0G/ZXvXuLEUzsFg2TbJJaedbY+zkYOftuS/iEO+x73+2bMWHg6enXoM2CAgsRT8gPPKRhBEggTBICDCBIAvMgyJpIdqjnNTGoGzvayOgXGFX6GKuplujDfhJMY0lByLzKCehSHnTaiqIz30meYxpDqxTuBONRL/3X5Y476gz8uF9z+tfX2Gv1ful+UWZABA+a2zgQcRJEQRIRJGnJMUkSrFgYRjGP4Xv+HDgkv1fmX0BGyq1a6wCAAA="
}
}
};
}
[When( @"I run UpdateAnalyticSet with group id '(.*)' and analytic set name '(.*)'" )]
public void WhenIRunUpdateAnalyticSetWithGroupId( string p0, string p1 )
{
m_api.AnalyticSets.UpdateAnalyticSet( p0, p1, m_updateAnalyticSet );
}
[When( @"I run DeleteAnalyticSet with group id '(.*)' and analytic set name '(.*)'" )]
public void WhenIRunDeleteAnalyticSetWithGroupIdAndAnalyticSetName( string p0, string p1 )
{
m_api.AnalyticSets.DeleteAnalyticSet( p0, p1 );
}
[Then( @"the analytic set in group id '(.*)' and name '(.*)' does not exist" )]
public void ThenTheAnalyticSetInGroupIdAndNameDoesNotExist( string p0, string p1 )
{
Action getDeletedSet = () =>
{
m_api.AnalyticSets.GetAnalyticSet( p0, p1 );
};
getDeletedSet.Should().Throw<EmsApiException>()
.WithMessage( $"Unable to find an analytic set with the name {p1} in group {p0}" );
}
[Given( @"I have a NewAnalyticCollection with name '(.*)'" )]
public void GivenIHaveANewAnalyticCollectionWithName( string p0 )
{
m_newAnalyticCollection = new NewAnalyticCollection
{
Name = p0,
Description = "new analytic collection",
Items = new Collection<NewAnalyticCollectionItem>
{
new NewAnalyticCollectionItem {
AnalyticId = "H4sIAAAAAAAEAJ2STW/CMAyGz0PiPyAO3NIkbekHsEqTuCDBBcS0qxunEKkkrA1jP39tUWDVtstuie3ntf0mi62sTfkBeSlXKLVVhZLV6PNU6nqmnsdHa88zSq/Xq3cNPFMdqM8Yp2+b9U4c5QmI0rUFLeT4xtyJukvXHoIFYbStQFjHh5TF9AWVt69gnA0Ho9HiNoWsVpgtoVyqk9S1MvoVyotc0G/ZXvXuLEUzsFg2TbJJaedbY+zkYOftuS/iEO+x73+2bMWHg6enXoM2CAgsRT8gPPKRhBEggTBICDCBIAvMgyJpIdqjnNTGoGzvayOgXGFX6GKuplujDfhJMY0lByLzKCehSHnTaiqIz30meYxpDqxTuBONRL/3X5Y476gz8uF9z+tfX2Gv1ful+UWZABA+a2zgQcRJEQRIRJGnJMUkSrFgYRjGP4Xv+HDgkv1fmX0BGyq1a6wCAAA="
}
}
};
}
[When( @"I run CreateAnalyticCollection with group id '(.*)'" )]
public void WhenIRunCreateAnalyticCollectionWithGroupId( string p0 )
{
m_result.Object = m_api.AnalyticSets.CreateAnalyticCollection( p0, m_newAnalyticCollection );
}
[Then( @"An AnalyticCollectionCreated object is returned" )]
public void ThenAnAnalyticCollectionCreatedObjectIsReturned()
{
m_result.Object.ShouldNotBeNullOfType<AnalyticCollectionCreated>();
}
[When( @"I run GetAnalyticCollection with group id '(.*)' and analytic name '(.*)'" )]
public void WhenIRunGetAnalyticCollectionWithGroupIdAndAnalyticName( string p0, string p1 )
{
m_result.Object = m_api.AnalyticSets.GetAnalyticCollection( p0, p1 );
}
[Then( @"An AnalyticCollection object is returned" )]
public void ThenAnAnalyticCollectionObjectIsReturned()
{
m_result.Object.ShouldNotBeNullOfType<AnalyticCollection>();
}
[Given( @"I have a UpdateAnalyticCollection" )]
public void GivenIHaveAUpdateAnalyticCollection()
{
m_updateAnalyticCollection = new UpdateAnalyticCollection
{
Description = "updated analytic collection",
Items = new Collection<NewAnalyticCollectionItem>
{
new NewAnalyticCollectionItem
{
AnalyticId = "H4sIAAAAAAAEAJ2STW/CMAyGz0PiPyAO3NIkbekHsEqTuCDBBcS0qxunEKkkrA1jP39tUWDVtstuie3ntf0mi62sTfkBeSlXKLVVhZLV6PNU6nqmnsdHa88zSq/Xq3cNPFMdqM8Yp2+b9U4c5QmI0rUFLeT4xtyJukvXHoIFYbStQFjHh5TF9AWVt69gnA0Ho9HiNoWsVpgtoVyqk9S1MvoVyotc0G/ZXvXuLEUzsFg2TbJJaedbY+zkYOftuS/iEO+x73+2bMWHg6enXoM2CAgsRT8gPPKRhBEggTBICDCBIAvMgyJpIdqjnNTGoGzvayOgXGFX6GKuplujDfhJMY0lByLzKCehSHnTaiqIz30meYxpDqxTuBONRL/3X5Y476gz8uF9z+tfX2Gv1ful+UWZABA+a2zgQcRJEQRIRJGnJMUkSrFgYRjGP4Xv+HDgkv1fmX0BGyq1a6wCAAA="
}
}
};
}
[When( @"I run UpdateAnalyticCollection with group id '(.*)' and analytic collection name '(.*)'" )]
public void WhenIRunUpdateAnalyticCollectionWithGroupId( string p0, string p1 )
{
m_api.AnalyticSets.UpdateAnalyticCollection( p0, p1, m_updateAnalyticCollection );
}
[When( @"I run DeleteAnalyticCollection with group id '(.*)' and analytic collection name '(.*)'" )]
public void WhenIRunDeleteAnalyticCollectionWithGroupIdAndAnalyticCollectionName( string p0, string p1 )
{
m_api.AnalyticSets.DeleteAnalyticCollection( p0, p1 );
}
[Then( @"the analytic collection in group id '(.*)' and name '(.*)' does not exist" )]
public void ThenTheAnalyticCollectionInGroupIdAndNameDoesNotExist( string p0, string p1 )
{
Action getDeletedCollection = () =>
{
m_api.AnalyticSets.GetAnalyticCollection( p0, p1 );
};
getDeletedCollection.Should().Throw<EmsApiException>()
.WithMessage( $"Unable to find an analytic collection with the name {p1} in group {p0}" );
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Xml;
using System.Diagnostics.Contracts;
namespace System.Xml.Linq
{
// Summary:
// Represents the abstract concept of a node (one of: element, comment, document
// type, processing instruction, or text node) in the XML tree.
public abstract class XNode : XObject
{
extern internal XNode();
// Summary:
// Gets a comparer that can compare the relative position of two nodes.
//
// Returns:
// A System.Xml.Linq.XNodeDocumentOrderComparer that can compare the relative
// position of two nodes.
public static XNodeDocumentOrderComparer DocumentOrderComparer
{
get
{
Contract.Ensures(Contract.Result<XNodeDocumentOrderComparer>() != null);
return default(XNodeDocumentOrderComparer);
}
}
//
// Summary:
// Gets a comparer that can compare two nodes for value equality.
//
// Returns:
// A System.Xml.Linq.XNodeEqualityComparer that can compare two nodes for value
// equality.
public static XNodeEqualityComparer EqualityComparer
{
get
{
Contract.Ensures(Contract.Result<XNodeEqualityComparer>() != null);
return default(XNodeEqualityComparer);
}
}
//
// Summary:
// Gets the next sibling node of this node.
//
// Returns:
// The System.Xml.Linq.XNode that contains the next sibling node.
extern public XNode NextNode { get; }
//
// Summary:
// Gets the previous sibling node of this node.
//
// Returns:
// The System.Xml.Linq.XNode that contains the previous sibling node.
extern public XNode PreviousNode { get; }
// Summary:
// Adds the specified content immediately after this node.
//
// Parameters:
// content:
// A content object that contains simple content or a collection of content
// objects to be added after this node.
//
// Exceptions:
// System.InvalidOperationException:
// The parent is null.
extern public void AddAfterSelf(object content);
//
// Summary:
// Adds the specified content immediately after this node.
//
// Parameters:
// content:
// A parameter list of content objects.
//
// Exceptions:
// System.InvalidOperationException:
// The parent is null.
extern public void AddAfterSelf(params object[] content);
//
// Summary:
// Adds the specified content immediately before this node.
//
// Parameters:
// content:
// A content object that contains simple content or a collection of content
// objects to be added before this node.
//
// Exceptions:
// System.InvalidOperationException:
// The parent is null.
extern public void AddBeforeSelf(object content);
//
// Summary:
// Adds the specified content immediately before this node.
//
// Parameters:
// content:
// A parameter list of content objects.
//
// Exceptions:
// System.InvalidOperationException:
// The parent is null.
extern public void AddBeforeSelf(params object[] content);
//
// Summary:
// Returns a collection of the ancestor elements of this node.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// of the ancestor elements of this node.
[Pure]
public IEnumerable<XElement> Ancestors()
{
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a filtered collection of the ancestor elements of this node. Only
// elements that have a matching System.Xml.Linq.XName are included in the collection.
//
// Parameters:
// name:
// The System.Xml.Linq.XName to match.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// of the ancestor elements of this node. Only elements that have a matching
// System.Xml.Linq.XName are included in the collection. The nodes in the returned
// collection are in reverse document order. This method uses deferred execution.
[Pure]
public IEnumerable<XElement> Ancestors(XName name)
{
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Compares two nodes to determine their relative XML document order.
//
// Parameters:
// n1:
// First System.Xml.Linq.XNode to compare.
//
// n2:
// Second System.Xml.Linq.XNode to compare.
//
// Returns:
// An int containing 0 if the nodes are equal; -1 if n1 is before n2; 1 if n1
// is after n2.
//
// Exceptions:
// System.InvalidOperationException:
// The two nodes do not share a common ancestor.
[Pure]
extern public static int CompareDocumentOrder(XNode n1, XNode n2);
//
// Summary:
// Creates an System.Xml.XmlReader for this node.
//
// Returns:
// An System.Xml.XmlReader that can be used to read this node and its descendants.
public XmlReader CreateReader()
{
Contract.Ensures(Contract.Result<XmlReader>() != null);
return default(XmlReader);
}
//
// Summary:
// Compares the values of two nodes, including the values of all descendant
// nodes.
//
// Parameters:
// n1:
// The first System.Xml.Linq.XNode to compare.
//
// n2:
// The second System.Xml.Linq.XNode to compare.
//
// Returns:
// true if the nodes are equal; otherwise false.
[Pure]
extern public static bool DeepEquals(XNode n1, XNode n2);
//
// Summary:
// Returns a collection of the sibling elements after this node, in document
// order.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// of the sibling elements after this node, in document order.
[Pure]
public IEnumerable<XElement> ElementsAfterSelf()
{
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a filtered collection of the sibling elements after this node, in
// document order. Only elements that have a matching System.Xml.Linq.XName
// are included in the collection.
//
// Parameters:
// name:
// The System.Xml.Linq.XName to match.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// of the sibling elements after this node, in document order. Only elements
// that have a matching System.Xml.Linq.XName are included in the collection.
[Pure]
public IEnumerable<XElement> ElementsAfterSelf(XName name)
{
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a collection of the sibling elements before this node, in document
// order.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// of the sibling elements before this node, in document order.
[Pure]
public IEnumerable<XElement> ElementsBeforeSelf()
{
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a filtered collection of the sibling elements before this node, in
// document order. Only elements that have a matching System.Xml.Linq.XName
// are included in the collection.
//
// Parameters:
// name:
// The System.Xml.Linq.XName to match.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// of the sibling elements before this node, in document order. Only elements
// that have a matching System.Xml.Linq.XName are included in the collection.
[Pure]
public IEnumerable<XElement> ElementsBeforeSelf(XName name)
{
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Determines if the current node appears after a specified node in terms of
// document order.
//
// Parameters:
// node:
// The System.Xml.Linq.XNode to compare for document order.
//
// Returns:
// true if this node appears after the specified node; otherwise false.
[Pure]
extern public bool IsAfter(XNode node);
//
// Summary:
// Determines if the current node appears before a specified node in terms of
// document order.
//
// Parameters:
// node:
// The System.Xml.Linq.XNode to compare for document order.
//
// Returns:
// true if this node appears before the specified node; otherwise false.
[Pure]
extern public bool IsBefore(XNode node);
//
// Summary:
// Returns a collection of the sibling nodes after this node, in document order.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XNode of
// the sibling nodes after this node, in document order.
[Pure]
public IEnumerable<XNode> NodesAfterSelf()
{
Contract.Ensures(Contract.Result<IEnumerable<XNode>>() != null);
return default(IEnumerable<XNode>);
}
//
// Summary:
// Returns a collection of the sibling nodes before this node, in document order.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XNode of
// the sibling nodes before this node, in document order.
[Pure]
public IEnumerable<XNode> NodesBeforeSelf()
{
Contract.Ensures(Contract.Result<IEnumerable<XNode>>() != null);
return default(IEnumerable<XNode>);
}
//
// Summary:
// Creates an System.Xml.Linq.XNode from an System.Xml.XmlReader.
//
// Parameters:
// reader:
// An System.Xml.XmlReader positioned at the node to read into this System.Xml.Linq.XNode.
//
// Returns:
// An System.Xml.Linq.XNode that contains the node and its descendant nodes
// that were read from the reader. The runtime type of the node is determined
// by the node type (System.Xml.Linq.XObject.NodeType) of the first node encountered
// in the reader.
//
// Exceptions:
// System.InvalidOperationException:
// The System.Xml.XmlReader is not positioned on a recognized node type.
//
// System.Xml.XmlException:
// The underlying System.Xml.XmlReader throws an exception.
public static XNode ReadFrom(XmlReader reader)
{
Contract.Requires(reader != null);
Contract.Ensures(Contract.Result<XNode>() != null);
return default(XNode);
}
//
// Summary:
// Removes this node from its parent.
//
// Exceptions:
// System.InvalidOperationException:
// The parent is null.
extern public void Remove();
//
// Summary:
// Replaces this node with the specified content.
//
// Parameters:
// content:
// Content that replaces this node.
extern public void ReplaceWith(object content);
//
// Summary:
// Replaces this node with the specified content.
//
// Parameters:
// content:
// A parameter list of the new content.
extern public void ReplaceWith(params object[] content);
//
// Summary:
// Returns the XML for this node, optionally disabling formatting.
//
// Parameters:
// options:
// A System.Xml.Linq.SaveOptions that specifies formatting behavior.
//
// Returns:
// A System.String containing the XML.
[Pure]
public string ToString(SaveOptions options)
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
//
// Summary:
// Writes this node to an System.Xml.XmlWriter.
//
// Parameters:
// writer:
// An System.Xml.XmlWriter into which this method will write.
public virtual void WriteTo(XmlWriter writer)
{
Contract.Requires(writer != null);
}
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
using GuruComponents.CodeEditor.Library.Drawing;
namespace GuruComponents.CodeEditor.Library.Drawing.Internal
{
using PVOID = IntPtr;
using FIBITMAP = Int32;
using FIMULTIBITMAP = Int32;
/* [StructLayout(LayoutKind.Sequential)]
public class FreeImageIO
{
public FI_ReadProc readProc;
public FI_WriteProc writeProc;
public FI_SeekProc seekProc;
public FI_TellProc tellProc;
}
[StructLayout(LayoutKind.Sequential)]
public class FI_Handle
{
public FileStream stream;
}
public delegate void FI_ReadProc(IntPtr buffer, uint size, uint count, IntPtr handle);
public delegate void FI_WriteProc(IntPtr buffer, uint size, uint count, IntPtr handle);
public delegate int FI_SeekProc(IntPtr handle, long offset, int origin);
public delegate int FI_TellProc(IntPtr handle);
*/
internal delegate void FreeImage_OutputMessageFunction(FreeImage.FreeImageFormat format, string msg);
internal class FreeImageApi
{
// Init/Error routines ----------------------------------------
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Initialise")]
public static extern void Initialise(bool loadLocalPluginsOnly);
// alias for Americans :)
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Initialise")]
public static extern void Initialize(bool loadLocalPluginsOnly);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_DeInitialise")]
public static extern void DeInitialise();
// alias for Americians :)
[DllImport("FreeImage.dll", EntryPoint="FreeImage_DeInitialise")]
public static extern void DeInitialize();
[DllImport("FreeImage.dll", EntryPoint = "FreeImage_CloseMemory")]
public static extern void CloseMemory(IntPtr stream);
// Version routines -------------------------------------------
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetVersion")]
public static extern string GetVersion();
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetCopyrightMessage")]
public static extern string GetCopyrightMessage();
// Message Output routines ------------------------------------
// missing void FreeImage_OutputMessageProc(int fif,
// const char *fmt, ...);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_SetOutputMessage")]
public static extern void SetOutputMessage(FreeImage_OutputMessageFunction omf);
// Allocate/Clone/Unload routines -----------------------------
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Allocate")]
public static extern FIBITMAP Allocate(int width, int height,
int bpp, uint red_mask, uint green_mask, uint blue_mask);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_AllocateT")]
public static extern FIBITMAP AllocateT(FreeImage.FreeImageType ftype, int width,
int height, int bpp, uint red_mask, uint green_mask,
uint blue_mask);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Clone")]
public static extern FIBITMAP Clone(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Unload")]
public static extern void Unload(FIBITMAP dib);
// Load/Save routines -----------------------------------------
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Load")]
public static extern FIBITMAP Load(FreeImage.FreeImageFormat format, string filename, int flags);
// missing FIBITMAP FreeImage_LoadFromHandle(FreeImage.FreeImageFormat fif,
// FreeImageIO *io, fi_handle handle, int flags);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Save")]
public static extern bool Save(FreeImage.FreeImageFormat format, FIBITMAP dib, string filename, int flags);
// missing BOOL FreeImage_SaveToHandle(FreeImage.FreeImageFormat fif, FIBITMAP *dib,
// FreeImageIO *io, fi_handle handle, int flags);
// Plugin interface -------------------------------------------
// missing FreeImage.FreeImageFormat FreeImage_RegisterLocalPlugin(FI_InitProc proc_address,
// const char *format, const char *description,
// const char *extension, const char *regexpr);
//
// missing FreeImage.FreeImageFormat FreeImage_RegisterExternalPlugin(const char *path,
// const char *format, const char *description,
// const char *extension, const char *regexpr);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFCount")]
public static extern int GetFIFCount();
[DllImport("FreeImage.dll", EntryPoint="FreeImage_SetPluginEnabled")]
public static extern int SetPluginEnabled(FreeImage.FreeImageFormat format, bool enabled);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_IsPluginEnabled")]
public static extern int IsPluginEnabled(FreeImage.FreeImageFormat format);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFFromFormat")]
public static extern FreeImage.FreeImageFormat GetFIFFromFormat(string format);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFFromMime")]
public static extern FreeImage.FreeImageFormat GetFIFFromMime(string mime);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFormatFromFIF")]
public static extern string GetFormatFromFIF(FreeImage.FreeImageFormat format);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFExtensionList")]
public static extern string GetFIFExtensionList(FreeImage.FreeImageFormat format);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFDescription")]
public static extern string GetFIFDescription(FreeImage.FreeImageFormat format);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFRegExpr")]
public static extern string GetFIFRegExpr(FreeImage.FreeImageFormat format);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFFromFilename")]
public static extern FreeImage.FreeImageFormat GetFIFFromFilename([MarshalAs( UnmanagedType.LPStr) ]string filename);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_FIFSupportsReading")]
public static extern bool FIFSupportsReading(FreeImage.FreeImageFormat format);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_FIFSupportsWriting")]
public static extern bool FIFSupportsWriting(FreeImage.FreeImageFormat format);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_FIFSupportsExportBPP")]
public static extern bool FIFSupportsExportBPP(FreeImage.FreeImageFormat format, int bpp);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_FIFSupportsExportType")]
public static extern bool FIFSupportsExportType(FreeImage.FreeImageFormat format, FreeImage.FreeImageType ftype);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_FIFSupportsICCProfiles")]
public static extern bool FIFSupportsICCProfiles(FreeImage.FreeImageFormat format, FreeImage.FreeImageType ftype);
// Multipage interface ----------------------------------------
[DllImport("FreeImage.dll", EntryPoint="FreeImage_OpenMultiBitmap")]
public static extern FIMULTIBITMAP OpenMultiBitmap(
FreeImage.FreeImageFormat format, string filename, bool createNew, bool readOnly, bool keepCacheInMemory);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_CloseMultiBitmap")]
public static extern long CloseMultiBitmap(FIMULTIBITMAP bitmap, int flags);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetPageCount")]
public static extern int GetPageCount(FIMULTIBITMAP bitmap);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_AppendPage")]
public static extern void AppendPage(FIMULTIBITMAP bitmap, FIBITMAP data);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_InsertPage")]
public static extern void InsertPage(FIMULTIBITMAP bitmap, int page, FIBITMAP data);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_DeletePage")]
public static extern void DeletePage(FIMULTIBITMAP bitmap, int page);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_LockPage")]
public static extern FIBITMAP LockPage(FIMULTIBITMAP bitmap, int page);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_UnlockPage")]
public static extern void UnlockPage(FIMULTIBITMAP bitmap, int page, bool changed);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_MovePage")]
public static extern bool MovePage(FIMULTIBITMAP bitmap, int target, int source);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetLockedPageNumbers")]
public static extern bool GetLockedPageNumbers(FIMULTIBITMAP bitmap, IntPtr pages, IntPtr count);
// File type request routines ---------------------------------
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFileType")]
public static extern FreeImage.FreeImageFormat GetFileType(string filename, int size);
// missing FreeImage.FreeImageFormat FreeImage_GetFileTypeFromHandle(FreeImageIO *io,
// fi_handle handle, int size);
// Image type request routines --------------------------------
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetImageType")]
public static extern FreeImage.FreeImageType GetImageType(FIBITMAP dib);
// Info functions ---------------------------------------------
[DllImport("FreeImage.dll", EntryPoint="FreeImage_IsLittleEndian")]
public static extern bool IsLittleEndian();
// Pixel access functions -------------------------------------
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetBits")]
public static extern IntPtr GetBits(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetScanLine")]
public static extern IntPtr GetScanLine(FIBITMAP dib, int scanline);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetPixelIndex")]
public static extern bool GetPixelIndex(FIBITMAP dib, uint x, uint y, byte value);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetColorsUsed")]
public static extern uint GetColorsUsed(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetBPP")]
public static extern uint GetBPP(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetWidth")]
public static extern uint GetWidth(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetHeight")]
public static extern uint GetHeight(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetLine")]
public static extern uint GetLine(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetPitch")]
public static extern uint GetPitch(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetDIBSize")]
public static extern uint GetDIBSize(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetPalette")]
[return: MarshalAs(UnmanagedType.LPStruct)]
public static extern RGBQUAD GetPalette(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetDotsPerMeterX")]
public static extern uint GetDotsPerMeterX(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetDotsPerMeterY")]
public static extern uint GetDotsPerMeterY(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetInfoHeader")]
[return: MarshalAs(UnmanagedType.LPStruct)]
public static extern BITMAPINFOHEADER GetInfoHeader(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetInfo")]
public static extern IntPtr GetInfo(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetColorType")]
public static extern int GetColorType(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetRedMask")]
public static extern uint GetRedMask(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetGreenMask")]
public static extern uint GetGreenMask(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetBlueMask")]
public static extern uint GetBlueMask(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetTransparencyCount")]
public static extern uint GetTransparencyCount(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetTransparencyTable")]
public static extern IntPtr GetTransparencyTable(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_SetTransparent")]
public static extern void SetTransparent(FIBITMAP dib, bool enabled);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_IsTransparent")]
public static extern bool IsTransparent(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertTo8Bits")]
public static extern FIBITMAP ConvertTo8Bits(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertTo16Bits555")]
public static extern FIBITMAP ConvertTo16Bits555(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertTo16Bits565")]
public static extern FIBITMAP ConvertTo16Bits565(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertTo24Bits")]
public static extern FIBITMAP ConvertTo24Bits(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertTo32Bits")]
public static extern FIBITMAP ConvertTo32Bits(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="ColorQuantize")]
public static extern FIBITMAP ColorQuantize(FIBITMAP dib, FreeImage.FreeImageQuantize quantize);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Threshold")]
public static extern FIBITMAP Threshold(FIBITMAP dib, byte t);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Dither")]
public static extern FIBITMAP Dither(FIBITMAP dib, FreeImage.FreeImageDither algorithm);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertFromRawBits")]
public static extern FIBITMAP ConvertFromRawBits(byte[] bits, int width, int height,
int pitch, uint bpp, uint redMask, uint greenMask, uint blueMask, bool topDown);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertToRawBits")]
public static extern void ConvertToRawBits(IntPtr bits, FIBITMAP dib, int pitch,
uint bpp, uint redMask, uint greenMask, uint blueMask, bool topDown);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_RotateClassic")]
public static extern FIBITMAP RotateClassic(FIBITMAP dib, Double angle);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_RotateEx")]
public static extern FIBITMAP RotateEx(
FIBITMAP dib, Double angle, Double xShift, Double yShift, Double xOrigin, Double yOrigin, bool useMask);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_FlipHorizontal")]
public static extern bool FlipHorizontal(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_FlipVertical")]
public static extern bool FlipVertical(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Rescale")]
public static extern FIBITMAP Rescale(FIBITMAP dib, int dst_width, int dst_height, FreeImage.FreeImageFilter filter);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_AdjustCurve")]
public static extern bool AdjustCurve(FIBITMAP dib, byte[] lut, FreeImage.FreeImageColorChannel channel);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_AdjustGamma")]
public static extern bool AdjustGamma(FIBITMAP dib, Double gamma);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_AdjustBrightness")]
public static extern bool AdjustBrightness(FIBITMAP dib, Double percentage);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_AdjustContrast")]
public static extern bool AdjustContrast(FIBITMAP dib, Double percentage);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Invert")]
public static extern bool Invert(FIBITMAP dib);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetHistogram")]
public static extern bool GetHistogram(FIBITMAP dib, int histo, FreeImage.FreeImageColorChannel channel);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_GetChannel")]
public static extern bool GetChannel(FIBITMAP dib, FreeImage.FreeImageColorChannel channel);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_SetChannel")]
public static extern bool SetChannel(FIBITMAP dib, FIBITMAP dib8, FreeImage.FreeImageColorChannel channel);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Copy")]
public static extern FIBITMAP Copy(FIBITMAP dib, int left, int top, int right, int bottom);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_Paste")]
public static extern bool Paste(FIBITMAP dst, FIBITMAP src, int left, int top, int alpha);
[DllImport("FreeImage.dll", EntryPoint="FreeImage_OpenMemory")]
public static extern IntPtr OpenMemory(IntPtr data, int size);
[DllImport("FreeImage.dll", EntryPoint = "FreeImage_LoadFromMemory")]
public static extern int LoadFromMemory(FreeImage.FreeImageFormat format, IntPtr stream, int flags);
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#region
using NLog.Config;
using NLog.Layouts;
using NLog.Targets;
using System.IO;
using Xunit;
#endregion
namespace NLog.UnitTests.LayoutRenderers
{
public class VariableLayoutRendererTests : NLogTestBase
{
[Fact]
public void Var_from_xml()
{
CreateConfigFromXml();
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=realgoodpassword", lastMessage);
}
[Fact]
public void Var_from_xml_and_edit()
{
CreateConfigFromXml();
LogManager.Configuration.Variables["password"] = "123";
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=123", lastMessage);
}
[Fact]
public void Var_with_layout_renderers()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name='user' value='logger=${logger}' />
<variable name='password' value='realgoodpassword' />
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.Configuration.Variables["password"] = "123";
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and logger=A=123", lastMessage);
}
[Fact]
public void Var_in_file_target()
{
string folderPath = Path.GetTempPath();
string logFilePath = Path.Combine(folderPath, "test.log");
LogManager.Configuration = CreateConfigurationFromString(string.Format(@"
<nlog>
<variable name='dir' value='{0}' />
<targets>
<target name='f' type='file' fileName='${{var:dir}}/test.log' layout='${{message}}' lineEnding='LF' />
</targets>
<rules>
<logger name='*' writeTo='f' />
</rules>
</nlog>", folderPath));
try
{
LogManager.GetLogger("A").Debug("msg");
Assert.True(File.Exists(logFilePath), "Log file was not created at expected file path.");
Assert.Equal("msg\n", File.ReadAllText(logFilePath));
}
finally
{
File.Delete(logFilePath);
}
}
[Fact]
public void Var_with_other_var()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name='user' value='${var:password}=' />
<variable name='password' value='realgoodpassword' />
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.Configuration.Variables["password"] = "123";
ILogger logger = LogManager.GetLogger("A");
// LogManager.ReconfigExistingLoggers();
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and 123==123", lastMessage);
}
[Fact]
public void Var_from_api()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.Configuration.Variables["user"] = "admin";
LogManager.Configuration.Variables["password"] = "123";
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=123", lastMessage);
}
[Fact]
public void Var_default()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name='user' value='admin' />
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password:default=unknown}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=unknown", lastMessage);
}
[Fact]
public void Var_default_after_clear()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name='user' value='admin' />
<variable name='password' value='realgoodpassword' />
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password:default=unknown}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
LogManager.Configuration.Variables.Remove("password");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=unknown", lastMessage);
}
[Fact]
public void Var_default_after_set_null()
{
CreateConfigFromXml();
ILogger logger = LogManager.GetLogger("A");
LogManager.Configuration.Variables["password"] = null;
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=", lastMessage);
}
[Fact]
public void Var_default_after_set_emptyString()
{
CreateConfigFromXml();
ILogger logger = LogManager.GetLogger("A");
LogManager.Configuration.Variables["password"] = "";
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=", lastMessage);
}
[Fact]
public void Var_default_after_xml_emptyString()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name='user' value='admin' />
<variable name='password' value='' />
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=", lastMessage);
}
[Fact]
public void null_should_be_ok()
{
Layout l = "${var:var1}";
var config = new NLog.Config.LoggingConfiguration();
config.Variables["var1"] = null;
l.Initialize(config);
var result = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal("", result);
}
[Fact]
public void null_should_not_use_default()
{
Layout l = "${var:var1:default=x}";
var config = new NLog.Config.LoggingConfiguration();
config.Variables["var1"] = null;
l.Initialize(config);
var result = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal("", result);
}
[Fact]
public void notset_should_use_default()
{
Layout l = "${var:var1:default=x}";
var config = new NLog.Config.LoggingConfiguration();
l.Initialize(config);
var result = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal("x", result);
}
[Fact]
public void test_with_mockLogManager()
{
ILogger logger = MyLogManager.Instance.GetLogger("A");
logger.Debug("msg");
var t1 = _mockConfig.FindTargetByName<DebugTarget>("t1");
Assert.NotNull(t1);
Assert.NotNull(t1.LastMessage);
Assert.Equal("msg|my-mocking-manager", t1.LastMessage);
}
private static readonly LoggingConfiguration _mockConfig = new LoggingConfiguration();
static VariableLayoutRendererTests()
{
var t1 = new DebugTarget
{
Name = "t1",
Layout = "${message}|${var:var1:default=x}"
};
_mockConfig.AddTarget(t1);
_mockConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, t1));
_mockConfig.Variables["var1"] = "my-mocking-manager";
}
class MyLogManager
{
private static readonly LogFactory _instance = new LogFactory(_mockConfig);
public static LogFactory Instance
{
get { return _instance; }
}
}
private void CreateConfigFromXml()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name='user' value='admin' />
<variable name='password' value='realgoodpassword' />
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
}
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using System.Security;
using System.Xml;
using System.Xml.Linq;
using Examine;
using Examine.LuceneEngine;
using Lucene.Net.Documents;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Services;
using Umbraco.Core.Sync;
using Umbraco.Web.Cache;
using UmbracoExamine;
using umbraco;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.member;
using umbraco.interfaces;
using Content = umbraco.cms.businesslogic.Content;
using Document = umbraco.cms.businesslogic.web.Document;
using Member = umbraco.cms.businesslogic.member.Member;
namespace Umbraco.Web.Search
{
/// <summary>
/// Used to wire up events for Examine
/// </summary>
public sealed class ExamineEvents : ApplicationEventHandler
{
/// <summary>
/// Once the application has started we should bind to all events and initialize the providers.
/// </summary>
/// <param name="httpApplication"></param>
/// <param name="applicationContext"></param>
/// <remarks>
/// We need to do this on the Started event as to guarantee that all resolvers are setup properly.
/// </remarks>
protected override void ApplicationStarted(UmbracoApplicationBase httpApplication, ApplicationContext applicationContext)
{
LogHelper.Info<ExamineEvents>("Initializing Examine and binding to business logic events");
var registeredProviders = ExamineManager.Instance.IndexProviderCollection
.OfType<BaseUmbracoIndexer>().Count(x => x.EnableDefaultEventHandler);
LogHelper.Info<ExamineEvents>("Adding examine event handlers for index providers: {0}", () => registeredProviders);
//don't bind event handlers if we're not suppose to listen
if (registeredProviders == 0)
return;
//Bind to distributed cache events - this ensures that this logic occurs on ALL servers that are taking part
// in a load balanced environment.
CacheRefresherBase<UnpublishedPageCacheRefresher>.CacheUpdated += UnpublishedPageCacheRefresherCacheUpdated;
CacheRefresherBase<PageCacheRefresher>.CacheUpdated += PublishedPageCacheRefresherCacheUpdated;
CacheRefresherBase<MediaCacheRefresher>.CacheUpdated += MediaCacheRefresherCacheUpdated;
CacheRefresherBase<MemberCacheRefresher>.CacheUpdated += MemberCacheRefresherCacheUpdated;
CacheRefresherBase<ContentTypeCacheRefresher>.CacheUpdated += ContentTypeCacheRefresherCacheUpdated;
var contentIndexer = ExamineManager.Instance.IndexProviderCollection["InternalIndexer"] as UmbracoContentIndexer;
if (contentIndexer != null)
{
contentIndexer.DocumentWriting += IndexerDocumentWriting;
}
var memberIndexer = ExamineManager.Instance.IndexProviderCollection["InternalMemberIndexer"] as UmbracoMemberIndexer;
if (memberIndexer != null)
{
memberIndexer.DocumentWriting += IndexerDocumentWriting;
}
}
/// <summary>
/// This is used to refresh content indexers IndexData based on the DataService whenever a content type is changed since
/// properties may have been added/removed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// See: http://issues.umbraco.org/issue/U4-4798
/// </remarks>
static void ContentTypeCacheRefresherCacheUpdated(ContentTypeCacheRefresher sender, CacheRefresherEventArgs e)
{
var indexersToUpdated = ExamineManager.Instance.IndexProviderCollection.OfType<UmbracoContentIndexer>();
foreach (var provider in indexersToUpdated)
{
provider.RefreshIndexerDataFromDataService();
}
}
static void MemberCacheRefresherCacheUpdated(MemberCacheRefresher sender, CacheRefresherEventArgs e)
{
switch (e.MessageType)
{
case MessageType.RefreshById:
var c1 = ApplicationContext.Current.Services.MemberService.GetById((int)e.MessageObject);
if (c1 != null)
{
ReIndexForMember(c1);
}
break;
case MessageType.RemoveById:
// This is triggered when the item is permanently deleted
DeleteIndexForEntity((int)e.MessageObject, false);
break;
case MessageType.RefreshByInstance:
var c3 = e.MessageObject as IMember;
if (c3 != null)
{
ReIndexForMember(c3);
}
break;
case MessageType.RemoveByInstance:
// This is triggered when the item is permanently deleted
var c4 = e.MessageObject as IMember;
if (c4 != null)
{
DeleteIndexForEntity(c4.Id, false);
}
break;
case MessageType.RefreshAll:
case MessageType.RefreshByJson:
default:
//We don't support these, these message types will not fire for unpublished content
break;
}
}
/// <summary>
/// Handles index management for all media events - basically handling saving/copying/trashing/deleting
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void MediaCacheRefresherCacheUpdated(MediaCacheRefresher sender, CacheRefresherEventArgs e)
{
switch (e.MessageType)
{
case MessageType.RefreshById:
var c1 = ApplicationContext.Current.Services.MediaService.GetById((int)e.MessageObject);
if (c1 != null)
{
ReIndexForMedia(c1, c1.Trashed == false);
}
break;
case MessageType.RemoveById:
var c2 = ApplicationContext.Current.Services.MediaService.GetById((int)e.MessageObject);
if (c2 != null)
{
//This is triggered when the item has trashed.
// So we need to delete the index from all indexes not supporting unpublished content.
DeleteIndexForEntity(c2.Id, true);
//We then need to re-index this item for all indexes supporting unpublished content
ReIndexForMedia(c2, false);
}
break;
case MessageType.RefreshByJson:
var jsonPayloads = MediaCacheRefresher.DeserializeFromJsonPayload((string)e.MessageObject);
if (jsonPayloads.Any())
{
foreach (var payload in jsonPayloads)
{
switch (payload.Operation)
{
case MediaCacheRefresher.OperationType.Saved:
var media1 = ApplicationContext.Current.Services.MediaService.GetById(payload.Id);
if (media1 != null)
{
ReIndexForMedia(media1, media1.Trashed == false);
}
break;
case MediaCacheRefresher.OperationType.Trashed:
//keep if trashed for indexes supporting unpublished
//(delete the index from all indexes not supporting unpublished content)
DeleteIndexForEntity(payload.Id, true);
//We then need to re-index this item for all indexes supporting unpublished content
var media2 = ApplicationContext.Current.Services.MediaService.GetById(payload.Id);
if (media2 != null)
{
ReIndexForMedia(media2, false);
}
break;
case MediaCacheRefresher.OperationType.Deleted:
//permanently remove from all indexes
DeleteIndexForEntity(payload.Id, false);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
break;
case MessageType.RefreshByInstance:
case MessageType.RemoveByInstance:
case MessageType.RefreshAll:
default:
//We don't support these, these message types will not fire for media
break;
}
}
/// <summary>
/// Handles index management for all published content events - basically handling published/unpublished
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// This will execute on all servers taking part in load balancing
/// </remarks>
static void PublishedPageCacheRefresherCacheUpdated(PageCacheRefresher sender, CacheRefresherEventArgs e)
{
switch (e.MessageType)
{
case MessageType.RefreshById:
var c1 = ApplicationContext.Current.Services.ContentService.GetById((int)e.MessageObject);
if (c1 != null)
{
ReIndexForContent(c1, true);
}
break;
case MessageType.RemoveById:
//This is triggered when the item has been unpublished or trashed (which also performs an unpublish).
var c2 = ApplicationContext.Current.Services.ContentService.GetById((int)e.MessageObject);
if (c2 != null)
{
// So we need to delete the index from all indexes not supporting unpublished content.
DeleteIndexForEntity(c2.Id, true);
// We then need to re-index this item for all indexes supporting unpublished content
ReIndexForContent(c2, false);
}
break;
case MessageType.RefreshByInstance:
var c3 = e.MessageObject as IContent;
if (c3 != null)
{
ReIndexForContent(c3, true);
}
break;
case MessageType.RemoveByInstance:
//This is triggered when the item has been unpublished or trashed (which also performs an unpublish).
var c4 = e.MessageObject as IContent;
if (c4 != null)
{
// So we need to delete the index from all indexes not supporting unpublished content.
DeleteIndexForEntity(c4.Id, true);
// We then need to re-index this item for all indexes supporting unpublished content
ReIndexForContent(c4, false);
}
break;
case MessageType.RefreshAll:
case MessageType.RefreshByJson:
default:
//We don't support these for examine indexing
break;
}
}
/// <summary>
/// Handles index management for all unpublished content events - basically handling saving/copying/deleting
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// This will execute on all servers taking part in load balancing
/// </remarks>
static void UnpublishedPageCacheRefresherCacheUpdated(UnpublishedPageCacheRefresher sender, CacheRefresherEventArgs e)
{
switch (e.MessageType)
{
case MessageType.RefreshById:
var c1 = ApplicationContext.Current.Services.ContentService.GetById((int) e.MessageObject);
if (c1 != null)
{
ReIndexForContent(c1, false);
}
break;
case MessageType.RemoveById:
// This is triggered when the item is permanently deleted
DeleteIndexForEntity((int)e.MessageObject, false);
break;
case MessageType.RefreshByInstance:
var c3 = e.MessageObject as IContent;
if (c3 != null)
{
ReIndexForContent(c3, false);
}
break;
case MessageType.RemoveByInstance:
// This is triggered when the item is permanently deleted
var c4 = e.MessageObject as IContent;
if (c4 != null)
{
DeleteIndexForEntity(c4.Id, false);
}
break;
case MessageType.RefreshByJson:
var jsonPayloads = UnpublishedPageCacheRefresher.DeserializeFromJsonPayload((string)e.MessageObject);
if (jsonPayloads.Any())
{
foreach (var payload in jsonPayloads)
{
switch (payload.Operation)
{
case UnpublishedPageCacheRefresher.OperationType.Deleted:
//permanently remove from all indexes
DeleteIndexForEntity(payload.Id, false);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
break;
case MessageType.RefreshAll:
default:
//We don't support these, these message types will not fire for unpublished content
break;
}
}
private static void ReIndexForMember(IMember member)
{
ExamineManager.Instance.ReIndexNode(
member.ToXml(), IndexTypes.Member,
ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>()
//ensure that only the providers are flagged to listen execute
.Where(x => x.EnableDefaultEventHandler));
}
/// <summary>
/// Event handler to create a lower cased version of the node name, this is so we can support case-insensitive searching and still
/// use the Whitespace Analyzer
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void IndexerDocumentWriting(object sender, DocumentWritingEventArgs e)
{
if (e.Fields.Keys.Contains("nodeName"))
{
//TODO: This logic should really be put into the content indexer instead of hidden here!!
//add the lower cased version
e.Document.Add(new Field("__nodeName",
e.Fields["nodeName"].ToLower(),
Field.Store.YES,
Field.Index.ANALYZED,
Field.TermVector.NO
));
}
}
private static void ReIndexForMedia(IMedia sender, bool isMediaPublished)
{
var xml = sender.ToXml();
//add an icon attribute to get indexed
xml.Add(new XAttribute("icon", sender.ContentType.Icon));
ExamineManager.Instance.ReIndexNode(
xml, IndexTypes.Media,
ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>()
//Index this item for all indexers if the media is not trashed, otherwise if the item is trashed
// then only index this for indexers supporting unpublished media
.Where(x => isMediaPublished || (x.SupportUnpublishedContent))
.Where(x => x.EnableDefaultEventHandler));
}
/// <summary>
/// Remove items from any index that doesn't support unpublished content
/// </summary>
/// <param name="entityId"></param>
/// <param name="keepIfUnpublished">
/// If true, indicates that we will only delete this item from indexes that don't support unpublished content.
/// If false it will delete this from all indexes regardless.
/// </param>
private static void DeleteIndexForEntity(int entityId, bool keepIfUnpublished)
{
ExamineManager.Instance.DeleteFromIndex(
entityId.ToString(CultureInfo.InvariantCulture),
ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>()
//if keepIfUnpublished == true then only delete this item from indexes not supporting unpublished content,
// otherwise if keepIfUnpublished == false then remove from all indexes
.Where(x => keepIfUnpublished == false || x.SupportUnpublishedContent == false)
.Where(x => x.EnableDefaultEventHandler));
}
/// <summary>
/// Re-indexes a content item whether published or not but only indexes them for indexes supporting unpublished content
/// </summary>
/// <param name="sender"></param>
/// <param name="isContentPublished">
/// Value indicating whether the item is published or not
/// </param>
private static void ReIndexForContent(IContent sender, bool isContentPublished)
{
var xml = sender.ToXml();
//add an icon attribute to get indexed
xml.Add(new XAttribute("icon", sender.ContentType.Icon));
ExamineManager.Instance.ReIndexNode(
xml, IndexTypes.Content,
ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>()
//Index this item for all indexers if the content is published, otherwise if the item is not published
// then only index this for indexers supporting unpublished content
.Where(x => isContentPublished || (x.SupportUnpublishedContent))
.Where(x => x.EnableDefaultEventHandler));
}
/// <summary>
/// Converts a content node to XDocument
/// </summary>
/// <param name="node"></param>
/// <param name="cacheOnly">true if data is going to be returned from cache</param>
/// <returns></returns>
[Obsolete("This method is no longer used and will be removed from the core in future versions, the cacheOnly parameter has no effect. Use the other ToXDocument overload instead")]
public static XDocument ToXDocument(Content node, bool cacheOnly)
{
return ToXDocument(node);
}
/// <summary>
/// Converts a content node to Xml
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private static XDocument ToXDocument(Content node)
{
if (TypeHelper.IsTypeAssignableFrom<Document>(node))
{
return new XDocument(((Document) node).Content.ToXml());
}
if (TypeHelper.IsTypeAssignableFrom<global::umbraco.cms.businesslogic.media.Media>(node))
{
return new XDocument(((global::umbraco.cms.businesslogic.media.Media) node).MediaItem.ToXml());
}
var xDoc = new XmlDocument();
var xNode = xDoc.CreateNode(XmlNodeType.Element, "node", "");
node.XmlPopulate(xDoc, ref xNode, false);
if (xNode.Attributes["nodeTypeAlias"] == null)
{
//we'll add the nodeTypeAlias ourselves
XmlAttribute d = xDoc.CreateAttribute("nodeTypeAlias");
d.Value = node.ContentType.Alias;
xNode.Attributes.Append(d);
}
return new XDocument(ExamineXmlExtensions.ToXElement(xNode));
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Drawing;
using System.Windows.Forms;
using DotSpatial.Controls.Header;
namespace DotSpatial.Controls
{
/// <summary>
/// A pre-configured status strip with a thread safe Progress function
/// </summary>
[ToolboxBitmap(typeof(SpatialStatusStrip), "SpatialStatusStrip.ico")]
[PartNotDiscoverable] // Do not allow discover this class by MEF
public partial class SpatialStatusStrip : StatusStrip, IStatusControl
{
#region Fields
private readonly Dictionary<StatusPanel, PanelGuiElements> _panels = new Dictionary<StatusPanel, PanelGuiElements>();
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SpatialStatusStrip"/> class which has a built in, thread safe Progress handler.
/// </summary>
public SpatialStatusStrip()
{
InitializeComponent();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the progress bar. By default, the first ToolStripProgressBar that is added to the tool strip.
/// </summary>
/// <value>
/// The progress bar.
/// </value>
[Description("Gets or sets the progress bar. By default, the first ToolStripProgressBar that is added to the tool strip.")]
public ToolStripProgressBar ProgressBar { get; set; }
/// <summary>
/// Gets or sets the progress label. By default, the first ToolStripStatusLabel that is added to the tool strip.
/// </summary>
/// <value>
/// The progress label.
/// </value>
[Description("Gets or sets the progress label. By default, the first ToolStripStatusLabel that is added to the tool strip.")]
public ToolStripStatusLabel ProgressLabel { get; set; }
#endregion
#region Methods
/// <inheritdoc />
public void Add(StatusPanel panel)
{
if (panel == null) throw new ArgumentNullException(nameof(panel));
ToolStripProgressBar pb = null;
var psp = panel as ProgressStatusPanel;
if (psp != null)
{
pb = new ToolStripProgressBar
{
Name = GetKeyName<ToolStripProgressBar>(panel.Key),
Width = 100,
Alignment = ToolStripItemAlignment.Left
};
Items.Add(pb);
}
var sl = new ToolStripStatusLabel
{
Name = GetKeyName<ToolStripStatusLabel>(panel.Key),
Text = panel.Caption,
Spring = panel.Width == 0,
TextAlign = ContentAlignment.MiddleLeft
};
Items.Add(sl);
_panels.Add(panel, new PanelGuiElements
{
Caption = sl,
Progress = pb
});
panel.PropertyChanged += PanelOnPropertyChanged;
}
/// <summary>
/// This method is thread safe so that people calling this method don't cause a cross-thread violation
/// by updating the progress indicator from a different thread
/// </summary>
/// <param name="key">A string message with just a description of what is happening, but no percent completion information</param>
/// <param name="percent">The integer percent from 0 to 100</param>
/// <param name="message">A message</param>
public void Progress(string key, int percent, string message)
{
if (InvokeRequired)
{
BeginInvoke((Action<int, string>)UpdateProgress, percent, message);
}
else
{
UpdateProgress(percent, message);
}
}
/// <inheritdoc />
public void Remove(StatusPanel panel)
{
if (panel == null) throw new ArgumentNullException(nameof(panel));
panel.PropertyChanged -= PanelOnPropertyChanged;
PanelGuiElements panelDesc;
if (!_panels.TryGetValue(panel, out panelDesc)) return;
if (panelDesc.Caption != null)
Items.Remove(panelDesc.Caption);
if (panelDesc.Progress != null)
Items.Remove(panelDesc.Progress);
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.ToolStrip.ItemAdded"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.ToolStripItemEventArgs"/> that contains the event data.</param>
protected override void OnItemAdded(ToolStripItemEventArgs e)
{
base.OnItemAdded(e);
if (ProgressBar == null)
{
var pb = e.Item as ToolStripProgressBar;
if (pb != null)
{
ProgressBar = pb;
}
}
if (ProgressLabel == null)
{
var sl = e.Item as ToolStripStatusLabel;
if (sl != null)
{
ProgressLabel = sl;
}
}
}
/// <inheritdoc />
protected override void OnItemRemoved(ToolStripItemEventArgs e)
{
base.OnItemRemoved(e);
if (ProgressBar == e.Item) ProgressBar = null;
if (ProgressLabel == e.Item) ProgressLabel = null;
}
private static string GetKeyName<T>(string key)
{
return typeof(T).Name + key;
}
private void PanelOnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var panel = (StatusPanel)sender;
if (InvokeRequired)
{
BeginInvoke((Action<StatusPanel, string>)UpdatePanelGuiProps, panel, e.PropertyName);
}
else
{
UpdatePanelGuiProps(panel, e.PropertyName);
}
}
private void UpdatePanelGuiProps(StatusPanel sender, string propertyName)
{
PanelGuiElements panelDesc;
if (!_panels.TryGetValue(sender, out panelDesc)) return;
switch (propertyName)
{
case "Caption":
if (panelDesc.Caption != null)
{
panelDesc.Caption.Text = sender.Caption;
}
break;
case "Percent":
if (panelDesc.Progress != null && sender is ProgressStatusPanel)
{
panelDesc.Progress.Value = ((ProgressStatusPanel)sender).Percent;
}
break;
}
Refresh();
}
private void UpdateProgress(int percent, string message)
{
if (ProgressBar != null)
ProgressBar.Value = percent;
if (ProgressLabel != null)
ProgressLabel.Text = message;
Refresh();
}
#endregion
#region Classes
/// <summary>
/// PanelGuiElements
/// </summary>
internal class PanelGuiElements
{
#region Properties
/// <summary>
/// Gets or sets the caption.
/// </summary>
public ToolStripStatusLabel Caption { get; set; }
/// <summary>
/// Gets or sets the progress bar.
/// </summary>
public ToolStripProgressBar Progress { get; set; }
#endregion
}
#endregion
}
}
| |
using System;
using Renci.SshNet.Security.Org.BouncyCastle.Math.EC.Endo;
using Renci.SshNet.Security.Org.BouncyCastle.Math.EC.Multiplier;
using Renci.SshNet.Security.Org.BouncyCastle.Math.Field;
namespace Renci.SshNet.Security.Org.BouncyCastle.Math.EC
{
internal class ECAlgorithms
{
public static bool IsF2mCurve(ECCurve c)
{
return IsF2mField(c.Field);
}
public static bool IsF2mField(IFiniteField field)
{
return field.Dimension > 1 && field.Characteristic.Equals(BigInteger.Two)
&& field is IPolynomialExtensionField;
}
public static bool IsFpCurve(ECCurve c)
{
return IsFpField(c.Field);
}
public static bool IsFpField(IFiniteField field)
{
return field.Dimension == 1;
}
public static ECPoint SumOfMultiplies(ECPoint[] ps, BigInteger[] ks)
{
if (ps == null || ks == null || ps.Length != ks.Length || ps.Length < 1)
throw new ArgumentException("point and scalar arrays should be non-null, and of equal, non-zero, length");
int count = ps.Length;
switch (count)
{
case 1:
return ps[0].Multiply(ks[0]);
case 2:
return SumOfTwoMultiplies(ps[0], ks[0], ps[1], ks[1]);
default:
break;
}
ECPoint p = ps[0];
ECCurve c = p.Curve;
ECPoint[] imported = new ECPoint[count];
imported[0] = p;
for (int i = 1; i < count; ++i)
{
imported[i] = ImportPoint(c, ps[i]);
}
GlvEndomorphism glvEndomorphism = c.GetEndomorphism() as GlvEndomorphism;
if (glvEndomorphism != null)
{
return ImplCheckResult(ImplSumOfMultipliesGlv(imported, ks, glvEndomorphism));
}
return ImplCheckResult(ImplSumOfMultiplies(imported, ks));
}
public static ECPoint SumOfTwoMultiplies(ECPoint P, BigInteger a, ECPoint Q, BigInteger b)
{
ECCurve cp = P.Curve;
Q = ImportPoint(cp, Q);
// Point multiplication for Koblitz curves (using WTNAF) beats Shamir's trick
{
AbstractF2mCurve f2mCurve = cp as AbstractF2mCurve;
if (f2mCurve != null && f2mCurve.IsKoblitz)
{
return ImplCheckResult(P.Multiply(a).Add(Q.Multiply(b)));
}
}
GlvEndomorphism glvEndomorphism = cp.GetEndomorphism() as GlvEndomorphism;
if (glvEndomorphism != null)
{
return ImplCheckResult(
ImplSumOfMultipliesGlv(new ECPoint[] { P, Q }, new BigInteger[] { a, b }, glvEndomorphism));
}
return ImplCheckResult(ImplShamirsTrickWNaf(P, a, Q, b));
}
/*
* "Shamir's Trick", originally due to E. G. Straus
* (Addition chains of vectors. American Mathematical Monthly,
* 71(7):806-808, Aug./Sept. 1964)
*
* Input: The points P, Q, scalar k = (km?, ... , k1, k0)
* and scalar l = (lm?, ... , l1, l0).
* Output: R = k * P + l * Q.
* 1: Z <- P + Q
* 2: R <- O
* 3: for i from m-1 down to 0 do
* 4: R <- R + R {point doubling}
* 5: if (ki = 1) and (li = 0) then R <- R + P end if
* 6: if (ki = 0) and (li = 1) then R <- R + Q end if
* 7: if (ki = 1) and (li = 1) then R <- R + Z end if
* 8: end for
* 9: return R
*/
public static ECPoint ShamirsTrick(ECPoint P, BigInteger k, ECPoint Q, BigInteger l)
{
ECCurve cp = P.Curve;
Q = ImportPoint(cp, Q);
return ImplCheckResult(ImplShamirsTrickJsf(P, k, Q, l));
}
public static ECPoint ImportPoint(ECCurve c, ECPoint p)
{
ECCurve cp = p.Curve;
if (!c.Equals(cp))
throw new ArgumentException("Point must be on the same curve");
return c.ImportPoint(p);
}
public static void MontgomeryTrick(ECFieldElement[] zs, int off, int len)
{
MontgomeryTrick(zs, off, len, null);
}
public static void MontgomeryTrick(ECFieldElement[] zs, int off, int len, ECFieldElement scale)
{
/*
* Uses the "Montgomery Trick" to invert many field elements, with only a single actual
* field inversion. See e.g. the paper:
* "Fast Multi-scalar Multiplication Methods on Elliptic Curves with Precomputation Strategy Using Montgomery Trick"
* by Katsuyuki Okeya, Kouichi Sakurai.
*/
ECFieldElement[] c = new ECFieldElement[len];
c[0] = zs[off];
int i = 0;
while (++i < len)
{
c[i] = c[i - 1].Multiply(zs[off + i]);
}
--i;
if (scale != null)
{
c[i] = c[i].Multiply(scale);
}
ECFieldElement u = c[i].Invert();
while (i > 0)
{
int j = off + i--;
ECFieldElement tmp = zs[j];
zs[j] = c[i].Multiply(u);
u = u.Multiply(tmp);
}
zs[off] = u;
}
/**
* Simple shift-and-add multiplication. Serves as reference implementation
* to verify (possibly faster) implementations, and for very small scalars.
*
* @param p
* The point to multiply.
* @param k
* The multiplier.
* @return The result of the point multiplication <code>kP</code>.
*/
public static ECPoint ReferenceMultiply(ECPoint p, BigInteger k)
{
BigInteger x = k.Abs();
ECPoint q = p.Curve.Infinity;
int t = x.BitLength;
if (t > 0)
{
if (x.TestBit(0))
{
q = p;
}
for (int i = 1; i < t; i++)
{
p = p.Twice();
if (x.TestBit(i))
{
q = q.Add(p);
}
}
}
return k.SignValue < 0 ? q.Negate() : q;
}
public static ECPoint ValidatePoint(ECPoint p)
{
if (!p.IsValid())
throw new InvalidOperationException("Invalid point");
return p;
}
public static ECPoint CleanPoint(ECCurve c, ECPoint p)
{
ECCurve cp = p.Curve;
if (!c.Equals(cp))
throw new ArgumentException("Point must be on the same curve", "p");
return c.DecodePoint(p.GetEncoded(false));
}
internal static ECPoint ImplCheckResult(ECPoint p)
{
if (!p.IsValidPartial())
throw new InvalidOperationException("Invalid result");
return p;
}
internal static ECPoint ImplShamirsTrickJsf(ECPoint P, BigInteger k, ECPoint Q, BigInteger l)
{
ECCurve curve = P.Curve;
ECPoint infinity = curve.Infinity;
// TODO conjugate co-Z addition (ZADDC) can return both of these
ECPoint PaddQ = P.Add(Q);
ECPoint PsubQ = P.Subtract(Q);
ECPoint[] points = new ECPoint[] { Q, PsubQ, P, PaddQ };
curve.NormalizeAll(points);
ECPoint[] table = new ECPoint[] {
points[3].Negate(), points[2].Negate(), points[1].Negate(),
points[0].Negate(), infinity, points[0],
points[1], points[2], points[3] };
byte[] jsf = WNafUtilities.GenerateJsf(k, l);
ECPoint R = infinity;
int i = jsf.Length;
while (--i >= 0)
{
int jsfi = jsf[i];
// NOTE: The shifting ensures the sign is extended correctly
int kDigit = ((jsfi << 24) >> 28), lDigit = ((jsfi << 28) >> 28);
int index = 4 + (kDigit * 3) + lDigit;
R = R.TwicePlus(table[index]);
}
return R;
}
internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k,
ECPoint Q, BigInteger l)
{
bool negK = k.SignValue < 0, negL = l.SignValue < 0;
k = k.Abs();
l = l.Abs();
int widthP = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(k.BitLength)));
int widthQ = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(l.BitLength)));
WNafPreCompInfo infoP = WNafUtilities.Precompute(P, widthP, true);
WNafPreCompInfo infoQ = WNafUtilities.Precompute(Q, widthQ, true);
ECPoint[] preCompP = negK ? infoP.PreCompNeg : infoP.PreComp;
ECPoint[] preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp;
ECPoint[] preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg;
ECPoint[] preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg;
byte[] wnafP = WNafUtilities.GenerateWindowNaf(widthP, k);
byte[] wnafQ = WNafUtilities.GenerateWindowNaf(widthQ, l);
return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ);
}
internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k, ECPointMap pointMapQ, BigInteger l)
{
bool negK = k.SignValue < 0, negL = l.SignValue < 0;
k = k.Abs();
l = l.Abs();
int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(System.Math.Max(k.BitLength, l.BitLength))));
ECPoint Q = WNafUtilities.MapPointWithPrecomp(P, width, true, pointMapQ);
WNafPreCompInfo infoP = WNafUtilities.GetWNafPreCompInfo(P);
WNafPreCompInfo infoQ = WNafUtilities.GetWNafPreCompInfo(Q);
ECPoint[] preCompP = negK ? infoP.PreCompNeg : infoP.PreComp;
ECPoint[] preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp;
ECPoint[] preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg;
ECPoint[] preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg;
byte[] wnafP = WNafUtilities.GenerateWindowNaf(width, k);
byte[] wnafQ = WNafUtilities.GenerateWindowNaf(width, l);
return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ);
}
private static ECPoint ImplShamirsTrickWNaf(ECPoint[] preCompP, ECPoint[] preCompNegP, byte[] wnafP,
ECPoint[] preCompQ, ECPoint[] preCompNegQ, byte[] wnafQ)
{
int len = System.Math.Max(wnafP.Length, wnafQ.Length);
ECCurve curve = preCompP[0].Curve;
ECPoint infinity = curve.Infinity;
ECPoint R = infinity;
int zeroes = 0;
for (int i = len - 1; i >= 0; --i)
{
int wiP = i < wnafP.Length ? (int)(sbyte)wnafP[i] : 0;
int wiQ = i < wnafQ.Length ? (int)(sbyte)wnafQ[i] : 0;
if ((wiP | wiQ) == 0)
{
++zeroes;
continue;
}
ECPoint r = infinity;
if (wiP != 0)
{
int nP = System.Math.Abs(wiP);
ECPoint[] tableP = wiP < 0 ? preCompNegP : preCompP;
r = r.Add(tableP[nP >> 1]);
}
if (wiQ != 0)
{
int nQ = System.Math.Abs(wiQ);
ECPoint[] tableQ = wiQ < 0 ? preCompNegQ : preCompQ;
r = r.Add(tableQ[nQ >> 1]);
}
if (zeroes > 0)
{
R = R.TimesPow2(zeroes);
zeroes = 0;
}
R = R.TwicePlus(r);
}
if (zeroes > 0)
{
R = R.TimesPow2(zeroes);
}
return R;
}
internal static ECPoint ImplSumOfMultiplies(ECPoint[] ps, BigInteger[] ks)
{
int count = ps.Length;
bool[] negs = new bool[count];
WNafPreCompInfo[] infos = new WNafPreCompInfo[count];
byte[][] wnafs = new byte[count][];
for (int i = 0; i < count; ++i)
{
BigInteger ki = ks[i]; negs[i] = ki.SignValue < 0; ki = ki.Abs();
int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(ki.BitLength)));
infos[i] = WNafUtilities.Precompute(ps[i], width, true);
wnafs[i] = WNafUtilities.GenerateWindowNaf(width, ki);
}
return ImplSumOfMultiplies(negs, infos, wnafs);
}
internal static ECPoint ImplSumOfMultipliesGlv(ECPoint[] ps, BigInteger[] ks, GlvEndomorphism glvEndomorphism)
{
BigInteger n = ps[0].Curve.Order;
int len = ps.Length;
BigInteger[] abs = new BigInteger[len << 1];
for (int i = 0, j = 0; i < len; ++i)
{
BigInteger[] ab = glvEndomorphism.DecomposeScalar(ks[i].Mod(n));
abs[j++] = ab[0];
abs[j++] = ab[1];
}
ECPointMap pointMap = glvEndomorphism.PointMap;
if (glvEndomorphism.HasEfficientPointMap)
{
return ECAlgorithms.ImplSumOfMultiplies(ps, pointMap, abs);
}
ECPoint[] pqs = new ECPoint[len << 1];
for (int i = 0, j = 0; i < len; ++i)
{
ECPoint p = ps[i], q = pointMap.Map(p);
pqs[j++] = p;
pqs[j++] = q;
}
return ECAlgorithms.ImplSumOfMultiplies(pqs, abs);
}
internal static ECPoint ImplSumOfMultiplies(ECPoint[] ps, ECPointMap pointMap, BigInteger[] ks)
{
int halfCount = ps.Length, fullCount = halfCount << 1;
bool[] negs = new bool[fullCount];
WNafPreCompInfo[] infos = new WNafPreCompInfo[fullCount];
byte[][] wnafs = new byte[fullCount][];
for (int i = 0; i < halfCount; ++i)
{
int j0 = i << 1, j1 = j0 + 1;
BigInteger kj0 = ks[j0]; negs[j0] = kj0.SignValue < 0; kj0 = kj0.Abs();
BigInteger kj1 = ks[j1]; negs[j1] = kj1.SignValue < 0; kj1 = kj1.Abs();
int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(System.Math.Max(kj0.BitLength, kj1.BitLength))));
ECPoint P = ps[i], Q = WNafUtilities.MapPointWithPrecomp(P, width, true, pointMap);
infos[j0] = WNafUtilities.GetWNafPreCompInfo(P);
infos[j1] = WNafUtilities.GetWNafPreCompInfo(Q);
wnafs[j0] = WNafUtilities.GenerateWindowNaf(width, kj0);
wnafs[j1] = WNafUtilities.GenerateWindowNaf(width, kj1);
}
return ImplSumOfMultiplies(negs, infos, wnafs);
}
private static ECPoint ImplSumOfMultiplies(bool[] negs, WNafPreCompInfo[] infos, byte[][] wnafs)
{
int len = 0, count = wnafs.Length;
for (int i = 0; i < count; ++i)
{
len = System.Math.Max(len, wnafs[i].Length);
}
ECCurve curve = infos[0].PreComp[0].Curve;
ECPoint infinity = curve.Infinity;
ECPoint R = infinity;
int zeroes = 0;
for (int i = len - 1; i >= 0; --i)
{
ECPoint r = infinity;
for (int j = 0; j < count; ++j)
{
byte[] wnaf = wnafs[j];
int wi = i < wnaf.Length ? (int)(sbyte)wnaf[i] : 0;
if (wi != 0)
{
int n = System.Math.Abs(wi);
WNafPreCompInfo info = infos[j];
ECPoint[] table = (wi < 0 == negs[j]) ? info.PreComp : info.PreCompNeg;
r = r.Add(table[n >> 1]);
}
}
if (r == infinity)
{
++zeroes;
continue;
}
if (zeroes > 0)
{
R = R.TimesPow2(zeroes);
zeroes = 0;
}
R = R.TwicePlus(r);
}
if (zeroes > 0)
{
R = R.TimesPow2(zeroes);
}
return R;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime
{
internal class Dispatcher
{
internal ISiloMessageCenter Transport { get; }
private readonly OrleansTaskScheduler scheduler;
private readonly Catalog catalog;
private readonly Logger logger;
private readonly ClusterConfiguration config;
private readonly PlacementDirectorsManager placementDirectorsManager;
private readonly ILocalGrainDirectory localGrainDirectory;
private readonly double rejectionInjectionRate;
private readonly bool errorInjection;
private readonly double errorInjectionRate;
private readonly SafeRandom random;
internal Dispatcher(
OrleansTaskScheduler scheduler,
ISiloMessageCenter transport,
Catalog catalog,
ClusterConfiguration config,
PlacementDirectorsManager placementDirectorsManager,
ILocalGrainDirectory localGrainDirectory)
{
this.scheduler = scheduler;
this.catalog = catalog;
Transport = transport;
this.config = config;
this.placementDirectorsManager = placementDirectorsManager;
this.localGrainDirectory = localGrainDirectory;
logger = LogManager.GetLogger("Dispatcher", LoggerType.Runtime);
rejectionInjectionRate = config.Globals.RejectionInjectionRate;
double messageLossInjectionRate = config.Globals.MessageLossInjectionRate;
errorInjection = rejectionInjectionRate > 0.0d || messageLossInjectionRate > 0.0d;
errorInjectionRate = rejectionInjectionRate + messageLossInjectionRate;
random = new SafeRandom();
}
#region Receive path
/// <summary>
/// Receive a new message:
/// - validate order constraints, queue (or possibly redirect) if out of order
/// - validate transactions constraints
/// - invoke handler if ready, otherwise enqueue for later invocation
/// </summary>
/// <param name="message"></param>
public void ReceiveMessage(Message message)
{
MessagingProcessingStatisticsGroup.OnDispatcherMessageReceive(message);
// Don't process messages that have already timed out
if (message.IsExpired)
{
logger.Warn(ErrorCode.Dispatcher_DroppingExpiredMessage, "Dropping an expired message: {0}", message);
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Expired");
message.DropExpiredMessage(MessagingStatisticsGroup.Phase.Dispatch);
return;
}
// check if its targeted at a new activation
if (message.TargetGrain.IsSystemTarget)
{
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "ReceiveMessage on system target.");
throw new InvalidOperationException("Dispatcher was called ReceiveMessage on system target for " + message);
}
if (errorInjection && ShouldInjectError(message))
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_InjectingRejection, "Injecting a rejection");
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "ErrorInjection");
RejectMessage(message, Message.RejectionTypes.Unrecoverable, null, "Injected rejection");
return;
}
try
{
Task ignore;
ActivationData target = catalog.GetOrCreateActivation(
message.TargetAddress,
message.IsNewPlacement,
message.NewGrainType,
String.IsNullOrEmpty(message.GenericGrainType) ? null : message.GenericGrainType,
message.RequestContextData,
out ignore);
if (ignore != null)
{
ignore.Ignore();
}
if (message.Direction == Message.Directions.Response)
{
ReceiveResponse(message, target);
}
else // Request or OneWay
{
if (target.State == ActivationState.Valid)
{
catalog.ActivationCollector.TryRescheduleCollection(target);
}
// Silo is always capable to accept a new request. It's up to the activation to handle its internal state.
// If activation is shutting down, it will queue and later forward this request.
ReceiveRequest(message, target);
}
}
catch (Exception ex)
{
try
{
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Non-existent activation");
var nea = ex as Catalog.NonExistentActivationException;
if (nea == null)
{
var str = String.Format("Error creating activation for {0}. Message {1}", message.NewGrainType, message);
logger.Error(ErrorCode.Dispatcher_ErrorCreatingActivation, str, ex);
throw new OrleansException(str, ex);
}
if (nea.IsStatelessWorker)
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation,
String.Format("Intermediate StatelessWorker NonExistentActivation for message {0}", message), ex);
}
else
{
logger.Info(ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation,
String.Format("Intermediate NonExistentActivation for message {0}", message), ex);
}
ActivationAddress nonExistentActivation = nea.NonExistentActivation;
if (message.Direction != Message.Directions.Response)
{
// Un-register the target activation so we don't keep getting spurious messages.
// The time delay (one minute, as of this writing) is to handle the unlikely but possible race where
// this request snuck ahead of another request, with new placement requested, for the same activation.
// If the activation registration request from the new placement somehow sneaks ahead of this un-registration,
// we want to make sure that we don't un-register the activation we just created.
// We would add a counter here, except that there's already a counter for this in the Catalog.
// Note that this has to run in a non-null scheduler context, so we always queue it to the catalog's context
var origin = message.SendingSilo;
scheduler.QueueWorkItem(new ClosureWorkItem(
// don't use message.TargetAddress, cause it may have been removed from the headers by this time!
async () =>
{
try
{
await this.localGrainDirectory.UnregisterAfterNonexistingActivation(
nonExistentActivation, origin);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Dispatcher_FailedToUnregisterNonExistingAct,
String.Format("Failed to un-register NonExistentActivation {0}",
nonExistentActivation), exc);
}
},
() => "LocalGrainDirectory.UnregisterAfterNonexistingActivation"),
catalog.SchedulingContext);
ProcessRequestToInvalidActivation(message, nonExistentActivation, null, "Non-existent activation");
}
else
{
logger.Warn(
ErrorCode.Dispatcher_NoTargetActivation,
nonExistentActivation.Silo.IsClient
? "No target client {0} for response message: {1}. It's likely that the client recently disconnected."
: "No target activation {0} for response message: {1}",
nonExistentActivation,
message);
this.localGrainDirectory.InvalidateCacheEntry(nonExistentActivation);
}
}
catch (Exception exc)
{
// Unable to create activation for this request - reject message
RejectMessage(message, Message.RejectionTypes.Transient, exc);
}
}
}
public void RejectMessage(
Message message,
Message.RejectionTypes rejectType,
Exception exc,
string rejectInfo = null)
{
if (message.Direction == Message.Directions.Request)
{
var str = String.Format("{0} {1}", rejectInfo ?? "", exc == null ? "" : exc.ToString());
MessagingStatisticsGroup.OnRejectedMessage(message);
Message rejection = message.CreateRejectionResponse(rejectType, str, exc as OrleansException);
SendRejectionMessage(rejection);
}
else
{
logger.Warn(ErrorCode.Messaging_Dispatcher_DiscardRejection,
"Discarding {0} rejection for message {1}. Exc = {2}",
Enum.GetName(typeof(Message.Directions), message.Direction), message, exc == null ? "" : exc.Message);
}
}
internal void SendRejectionMessage(Message rejection)
{
if (rejection.Result == Message.ResponseTypes.Rejection)
{
Transport.SendMessage(rejection);
rejection.ReleaseBodyAndHeaderBuffers();
}
else
{
throw new InvalidOperationException(
"Attempt to invoke Dispatcher.SendRejectionMessage() for a message that isn't a rejection.");
}
}
private void ReceiveResponse(Message message, ActivationData targetActivation)
{
lock (targetActivation)
{
if (targetActivation.State == ActivationState.Invalid)
{
logger.Warn(ErrorCode.Dispatcher_Receive_InvalidActivation,
"Response received for invalid activation {0}", message);
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Ivalid");
return;
}
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message);
if (Transport.TryDeliverToProxy(message)) return;
RuntimeClient.Current.ReceiveResponse(message);
}
}
/// <summary>
/// Check if we can locally accept this message.
/// Redirects if it can't be accepted.
/// </summary>
/// <param name="message"></param>
/// <param name="targetActivation"></param>
private void ReceiveRequest(Message message, ActivationData targetActivation)
{
lock (targetActivation)
{
if (targetActivation.State == ActivationState.Invalid)
{
ProcessRequestToInvalidActivation(
message,
targetActivation.Address,
targetActivation.ForwardingAddress,
"ReceiveRequest");
}
else if (!ActivationMayAcceptRequest(targetActivation, message))
{
// Check for deadlock before Enqueueing.
if (config.Globals.PerformDeadlockDetection && !message.TargetGrain.IsSystemTarget)
{
try
{
CheckDeadlock(message);
}
catch (DeadlockException exc)
{
// Record that this message is no longer flowing through the system
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Deadlock");
logger.Warn(ErrorCode.Dispatcher_DetectedDeadlock,
"Detected Application Deadlock: {0}", exc.Message);
// We want to send DeadlockException back as an application exception, rather than as a system rejection.
SendResponse(message, Response.ExceptionResponse(exc));
return;
}
}
EnqueueRequest(message, targetActivation);
}
else
{
HandleIncomingRequest(message, targetActivation);
}
}
}
/// <summary>
/// Determine if the activation is able to currently accept the given message
/// - always accept responses
/// For other messages, require that:
/// - activation is properly initialized
/// - the message would not cause a reentrancy conflict
/// </summary>
/// <param name="targetActivation"></param>
/// <param name="incoming"></param>
/// <returns></returns>
private bool ActivationMayAcceptRequest(ActivationData targetActivation, Message incoming)
{
if (targetActivation.State != ActivationState.Valid) return false;
if (!targetActivation.IsCurrentlyExecuting) return true;
return CanInterleave(targetActivation, incoming);
}
/// <summary>
/// Whether an incoming message can interleave
/// </summary>
/// <param name="targetActivation"></param>
/// <param name="incoming"></param>
/// <returns></returns>
public bool CanInterleave(ActivationData targetActivation, Message incoming)
{
bool canInterleave =
catalog.CanInterleave(targetActivation.ActivationId, incoming)
|| incoming.IsAlwaysInterleave
|| targetActivation.Running == null
|| (targetActivation.Running.IsReadOnly && incoming.IsReadOnly);
return canInterleave;
}
/// <summary>
/// Check if the current message will cause deadlock.
/// Throw DeadlockException if yes.
/// </summary>
/// <param name="message">Message to analyze</param>
private void CheckDeadlock(Message message)
{
var requestContext = message.RequestContextData;
object obj;
if (requestContext == null ||
!requestContext.TryGetValue(RequestContext.CALL_CHAIN_REQUEST_CONTEXT_HEADER, out obj) ||
obj == null) return; // first call in a chain
var prevChain = ((IList)obj);
ActivationId nextActivationId = message.TargetActivation;
// check if the target activation already appears in the call chain.
foreach (object invocationObj in prevChain)
{
var prevId = ((RequestInvocationHistory)invocationObj).ActivationId;
if (!prevId.Equals(nextActivationId) || catalog.CanInterleave(nextActivationId, message)) continue;
var newChain = new List<RequestInvocationHistory>();
newChain.AddRange(prevChain.Cast<RequestInvocationHistory>());
newChain.Add(new RequestInvocationHistory(message));
throw new DeadlockException(newChain);
}
}
/// <summary>
/// Handle an incoming message and queue/invoke appropriate handler
/// </summary>
/// <param name="message"></param>
/// <param name="targetActivation"></param>
public void HandleIncomingRequest(Message message, ActivationData targetActivation)
{
lock (targetActivation)
{
if (targetActivation.State == ActivationState.Invalid)
{
ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "HandleIncomingRequest");
return;
}
// Now we can actually scheduler processing of this request
targetActivation.RecordRunning(message);
var context = new SchedulingContext(targetActivation);
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message);
scheduler.QueueWorkItem(new InvokeWorkItem(targetActivation, message, context, this), context);
}
}
/// <summary>
/// Enqueue message for local handling after transaction completes
/// </summary>
/// <param name="message"></param>
/// <param name="targetActivation"></param>
private void EnqueueRequest(Message message, ActivationData targetActivation)
{
var overloadException = targetActivation.CheckOverloaded(logger);
if (overloadException != null)
{
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Overload2");
RejectMessage(message, Message.RejectionTypes.Overloaded, overloadException, "Target activation is overloaded " + targetActivation);
return;
}
switch (targetActivation.EnqueueMessage(message))
{
case ActivationData.EnqueueMessageResult.Success:
// Great, nothing to do
break;
case ActivationData.EnqueueMessageResult.ErrorInvalidActivation:
ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "EnqueueRequest");
break;
case ActivationData.EnqueueMessageResult.ErrorStuckActivation:
// Avoid any new call to this activation
catalog.DeactivateStuckActivation(targetActivation);
ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "EnqueueRequest - blocked grain");
break;
default:
throw new ArgumentOutOfRangeException();
}
// Dont count this as end of processing. The message will come back after queueing via HandleIncomingRequest.
#if DEBUG
// This is a hot code path, so using #if to remove diags from Release version
// Note: Caller already holds lock on activation
if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_EnqueueMessage,
"EnqueueMessage for {0}: targetActivation={1}", message.TargetActivation, targetActivation.DumpStatus());
#endif
}
internal void ProcessRequestToInvalidActivation(
Message message,
ActivationAddress oldAddress,
ActivationAddress forwardingAddress,
string failedOperation,
Exception exc = null)
{
// Just use this opportunity to invalidate local Cache Entry as well.
if (oldAddress != null)
{
this.localGrainDirectory.InvalidateCacheEntry(oldAddress);
}
// IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already.
scheduler.QueueWorkItem(new ClosureWorkItem(
() => TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc)),
catalog.SchedulingContext);
}
internal void ProcessRequestsToInvalidActivation(
List<Message> messages,
ActivationAddress oldAddress,
ActivationAddress forwardingAddress,
string failedOperation,
Exception exc = null)
{
// Just use this opportunity to invalidate local Cache Entry as well.
if (oldAddress != null)
{
this.localGrainDirectory.InvalidateCacheEntry(oldAddress);
}
logger.Info(ErrorCode.Messaging_Dispatcher_ForwardingRequests,
String.Format("Forwarding {0} requests to old address {1} after {2}.", messages.Count, oldAddress, failedOperation));
// IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already.
scheduler.QueueWorkItem(new ClosureWorkItem(
() =>
{
foreach (var message in messages)
{
TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc);
}
}
), catalog.SchedulingContext);
}
internal void TryForwardRequest(Message message, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null)
{
bool forwardingSucceded = true;
try
{
logger.Info(ErrorCode.Messaging_Dispatcher_TryForward,
String.Format("Trying to forward after {0}, ForwardCount = {1}. Message {2}.", failedOperation, message.ForwardCount, message));
// if this message is from a different cluster and hit a non-existing activation
// in this cluster (which can happen due to stale cache or directory states)
// we forward it back to the original silo it came from in the original cluster,
// and target it to a fictional activation that is guaranteed to not exist.
// This ensures that the GSI protocol creates a new instance there instead of here.
if (forwardingAddress == null
&& message.TargetSilo != message.SendingSilo
&& !this.localGrainDirectory.IsSiloInCluster(message.SendingSilo))
{
message.IsReturnedFromRemoteCluster = true; // marks message to force invalidation of stale directory entry
forwardingAddress = ActivationAddress.NewActivationAddress(message.SendingSilo, message.TargetGrain);
logger.Info(ErrorCode.Messaging_Dispatcher_ReturnToOriginCluster,
String.Format("Forwarding back to origin cluster, to fictional activation {0}", message));
}
MessagingProcessingStatisticsGroup.OnDispatcherMessageReRouted(message);
if (oldAddress != null)
{
message.AddToCacheInvalidationHeader(oldAddress);
}
forwardingSucceded = InsideRuntimeClient.Current.TryForwardMessage(message, forwardingAddress);
}
catch (Exception exc2)
{
forwardingSucceded = false;
exc = exc2;
}
finally
{
if (!forwardingSucceded)
{
var str = String.Format("Forwarding failed: tried to forward message {0} for {1} times after {2} to invalid activation. Rejecting now.",
message, message.ForwardCount, failedOperation);
logger.Warn(ErrorCode.Messaging_Dispatcher_TryForwardFailed, str, exc);
RejectMessage(message, Message.RejectionTypes.Transient, exc, str);
}
}
}
#endregion
#region Send path
/// <summary>
/// Send an outgoing message
/// - may buffer for transaction completion / commit if it ends a transaction
/// - choose target placement address, maintaining send order
/// - add ordering info and maintain send order
///
/// </summary>
/// <param name="message"></param>
/// <param name="sendingActivation"></param>
public async Task AsyncSendMessage(Message message, ActivationData sendingActivation = null)
{
try
{
await AddressMessage(message);
TransportMessage(message);
}
catch (Exception ex)
{
if (ShouldLogError(ex))
{
logger.Error(ErrorCode.Dispatcher_SelectTarget_Failed,
String.Format("SelectTarget failed with {0}", ex.Message),
ex);
}
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "SelectTarget failed");
RejectMessage(message, Message.RejectionTypes.Unrecoverable, ex);
}
}
private bool ShouldLogError(Exception ex)
{
return !(ex.GetBaseException() is KeyNotFoundException) &&
!(ex.GetBaseException() is ClientNotAvailableException);
}
// this is a compatibility method for portions of the code base that don't use
// async/await yet, which is almost everything. there's no liability to discarding the
// Task returned by AsyncSendMessage()
internal void SendMessage(Message message, ActivationData sendingActivation = null)
{
AsyncSendMessage(message, sendingActivation).Ignore();
}
/// <summary>
/// Resolve target address for a message
/// - use transaction info
/// - check ordering info in message and sending activation
/// - use sender's placement strategy
/// </summary>
/// <param name="message"></param>
/// <returns>Resolve when message is addressed (modifies message fields)</returns>
private async Task AddressMessage(Message message)
{
var targetAddress = message.TargetAddress;
if (targetAddress.IsComplete) return;
// placement strategy is determined by searching for a specification. first, we check for a strategy associated with the grain reference,
// second, we check for a strategy associated with the target's interface. third, we check for a strategy associated with the activation sending the
// message.
var strategy = targetAddress.Grain.IsGrain ? catalog.GetGrainPlacementStrategy(targetAddress.Grain) : null;
var placementResult = await this.placementDirectorsManager.SelectOrAddActivation(
message.SendingAddress, message.TargetGrain, this.catalog, strategy);
if (placementResult.IsNewPlacement && targetAddress.Grain.IsClient)
{
logger.Error(ErrorCode.Dispatcher_AddressMsg_UnregisteredClient, String.Format("AddressMessage could not find target for client pseudo-grain {0}", message));
throw new KeyNotFoundException(String.Format("Attempting to send a message {0} to an unregistered client pseudo-grain {1}", message, targetAddress.Grain));
}
message.SetTargetPlacement(placementResult);
if (placementResult.IsNewPlacement)
{
CounterStatistic.FindOrCreate(StatisticNames.DISPATCHER_NEW_PLACEMENT).Increment();
}
if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_AddressMsg_SelectTarget, "AddressMessage Placement SelectTarget {0}", message);
}
internal void SendResponse(Message request, Response response)
{
// create the response
var message = request.CreateResponseMessage();
message.BodyObject = response;
if (message.TargetGrain.IsSystemTarget)
{
SendSystemTargetMessage(message);
}
else
{
TransportMessage(message);
}
}
internal void SendSystemTargetMessage(Message message)
{
message.Category = message.TargetGrain.Equals(Constants.MembershipOracleId) ?
Message.Categories.Ping : Message.Categories.System;
if (message.TargetSilo == null)
{
message.TargetSilo = Transport.MyAddress;
}
if (message.TargetActivation == null)
{
message.TargetActivation = ActivationId.GetSystemActivation(message.TargetGrain, message.TargetSilo);
}
TransportMessage(message);
}
/// <summary>
/// Directly send a message to the transport without processing
/// </summary>
/// <param name="message"></param>
public void TransportMessage(Message message)
{
if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_Send_AddressedMessage, "Addressed message {0}", message);
Transport.SendMessage(message);
}
#endregion
#region Execution
/// <summary>
/// Invoked when an activation has finished a transaction and may be ready for additional transactions
/// </summary>
/// <param name="activation">The activation that has just completed processing this message</param>
/// <param name="message">The message that has just completed processing.
/// This will be <c>null</c> for the case of completion of Activate/Deactivate calls.</param>
internal void OnActivationCompletedRequest(ActivationData activation, Message message)
{
lock (activation)
{
#if DEBUG
// This is a hot code path, so using #if to remove diags from Release version
if (logger.IsVerbose2)
{
logger.Verbose2(ErrorCode.Dispatcher_OnActivationCompletedRequest_Waiting,
"OnActivationCompletedRequest {0}: Activation={1}", activation.ActivationId, activation.DumpStatus());
}
#endif
activation.ResetRunning(message);
// ensure inactive callbacks get run even with transactions disabled
if (!activation.IsCurrentlyExecuting)
activation.RunOnInactive();
// Run message pump to see if there is a new request arrived to be processed
RunMessagePump(activation);
}
}
internal void RunMessagePump(ActivationData activation)
{
// Note: this method must be called while holding lock (activation)
#if DEBUG
// This is a hot code path, so using #if to remove diags from Release version
// Note: Caller already holds lock on activation
if (logger.IsVerbose2)
{
logger.Verbose2(ErrorCode.Dispatcher_ActivationEndedTurn_Waiting,
"RunMessagePump {0}: Activation={1}", activation.ActivationId, activation.DumpStatus());
}
#endif
// don't run any messages if activation is not ready or deactivating
if (activation.State != ActivationState.Valid) return;
bool runLoop;
do
{
runLoop = false;
var nextMessage = activation.PeekNextWaitingMessage();
if (nextMessage == null) continue;
if (!ActivationMayAcceptRequest(activation, nextMessage)) continue;
activation.DequeueNextWaitingMessage();
// we might be over-writing an already running read only request.
HandleIncomingRequest(nextMessage, activation);
runLoop = true;
}
while (runLoop);
}
private bool ShouldInjectError(Message message)
{
if (!errorInjection || message.Direction != Message.Directions.Request) return false;
double r = random.NextDouble() * 100;
if (!(r < errorInjectionRate)) return false;
if (r < rejectionInjectionRate)
{
return true;
}
if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_InjectingMessageLoss, "Injecting a message loss");
// else do nothing and intentionally drop message on the floor to inject a message loss
return true;
}
#endregion
}
}
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
using qx.ui.core;
namespace qx.ui.form
{
/// <summary>
/// <para>Basic class for a selectbox like lists. Basically supports a popup
/// with a list and the whole children management.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.form.AbstractSelectBox", OmitOptionalParameters = true, Export = false)]
public abstract partial class AbstractSelectBox : qx.ui.core.Widget, qx.ui.form.IForm
{
#region Events
/// <summary>
/// <para>Fired when the invalidMessage was modified</para>
/// </summary>
public event Action<qx.eventx.type.Data> OnChangeInvalidMessage;
/// <summary>
/// <para>Fired when the required was modified</para>
/// </summary>
public event Action<qx.eventx.type.Data> OnChangeRequired;
/// <summary>
/// <para>Fired when the valid state was modified</para>
/// </summary>
public event Action<qx.eventx.type.Data> OnChangeValid;
#endregion Events
#region Properties
/// <summary>
/// <para>Whether the widget is focusable e.g. rendering a focus border and visualize
/// as active element.</para>
/// <para>See also <see cref="IsTabable"/> which allows runtime checks for
/// isChecked or other stuff to test whether the widget is
/// reachable via the TAB key.</para>
/// </summary>
[JsProperty(Name = "focusable", NativeField = true)]
public bool Focusable { get; set; }
/// <summary>
/// <para>Formatter which format the value from the selected ListItem.
/// Uses the default formatter <see cref="#_defaultFormat"/>.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "format", NativeField = true)]
public Action<object> Format { get; set; }
/// <summary>
/// <para>The maximum height of the list popup. Setting this value to
/// null will set cause the list to be auto-sized.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "maxListHeight", NativeField = true)]
public double MaxListHeight { get; set; }
/// <summary>
/// <para>The LayoutItem‘s preferred width.</para>
/// <para>The computed width may differ from the given width due to
/// stretching. Also take a look at the related properties
/// <see cref="MinWidth"/> and <see cref="MaxWidth"/>.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "width", NativeField = true)]
public double Width { get; set; }
/// <summary>
/// <para>Message which is shown in an invalid tooltip.</para>
/// </summary>
[JsProperty(Name = "invalidMessage", NativeField = true)]
public string InvalidMessage { get; set; }
/// <summary>
/// <para>Flag signaling if a widget is required.</para>
/// </summary>
[JsProperty(Name = "required", NativeField = true)]
public bool Required { get; set; }
/// <summary>
/// <para>Message which is shown in an invalid tooltip if the <see cref="Required"/> is
/// set to true.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "requiredInvalidMessage", NativeField = true)]
public string RequiredInvalidMessage { get; set; }
/// <summary>
/// <para>Flag signaling if a widget is valid. If a widget is invalid, an invalid
/// state will be set.</para>
/// </summary>
[JsProperty(Name = "valid", NativeField = true)]
public bool Valid { get; set; }
#endregion Properties
#region Methods
public AbstractSelectBox() { throw new NotImplementedException(); }
/// <summary>
/// <para>Hides the list popup.</para>
/// </summary>
[JsMethod(Name = "close")]
public void Close() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the list widget.</para>
/// </summary>
/// <returns>the list</returns>
[JsMethod(Name = "getChildrenContainer")]
public qx.ui.form.List GetChildrenContainer() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property format.</para>
/// </summary>
[JsMethod(Name = "getFormat")]
public Action<object> GetFormat() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property maxListHeight.</para>
/// </summary>
[JsMethod(Name = "getMaxListHeight")]
public double GetMaxListHeight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property format
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property format.</param>
[JsMethod(Name = "initFormat")]
public void InitFormat(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property maxListHeight
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property maxListHeight.</param>
[JsMethod(Name = "initMaxListHeight")]
public void InitMaxListHeight(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Shows the list popup.</para>
/// </summary>
[JsMethod(Name = "open")]
public void Open() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property format.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetFormat")]
public void ResetFormat() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property maxListHeight.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetMaxListHeight")]
public void ResetMaxListHeight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property format.</para>
/// </summary>
/// <param name="value">New value for property format.</param>
[JsMethod(Name = "setFormat")]
public void SetFormat(Action<object> value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property maxListHeight.</para>
/// </summary>
/// <param name="value">New value for property maxListHeight.</param>
[JsMethod(Name = "setMaxListHeight")]
public void SetMaxListHeight(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the popup’s visibility.</para>
/// </summary>
[JsMethod(Name = "toggle")]
public void Toggle() { throw new NotImplementedException(); }
/// <summary>
/// <para>Adds a new child widget.</para>
/// <para>The supported keys of the layout options map depend on the layout manager
/// used to position the widget. The options are documented in the class
/// documentation of each layout manager <see cref="qx.ui.layout"/>.</para>
/// </summary>
/// <param name="child">the item to add.</param>
/// <param name="options">Optional layout data for item.</param>
/// <returns>This object (for chaining support)</returns>
[JsMethod(Name = "add")]
public Widget Add(LayoutItem child, object options = null) { throw new NotImplementedException(); }
/// <summary>
/// <para>Add an item after another already inserted item</para>
/// <para>This method works on the widget’s children list. Some layout managers
/// (e.g. <see cref="qx.ui.layout.HBox"/>) use the children order as additional
/// layout information. Other layout manager (e.g. <see cref="qx.ui.layout.Grid"/>)
/// ignore the children order for the layout process.</para>
/// </summary>
/// <param name="child">item to add</param>
/// <param name="after">item, after which the new item will be inserted</param>
/// <param name="options">Optional layout data for item.</param>
[JsMethod(Name = "addAfter")]
public void AddAfter(LayoutItem child, LayoutItem after, object options = null) { throw new NotImplementedException(); }
/// <summary>
/// <para>Add a child at the specified index</para>
/// <para>This method works on the widget’s children list. Some layout managers
/// (e.g. <see cref="qx.ui.layout.HBox"/>) use the children order as additional
/// layout information. Other layout manager (e.g. <see cref="qx.ui.layout.Grid"/>)
/// ignore the children order for the layout process.</para>
/// </summary>
/// <param name="child">item to add</param>
/// <param name="index">Index, at which the item will be inserted</param>
/// <param name="options">Optional layout data for item.</param>
[JsMethod(Name = "addAt")]
public void AddAt(LayoutItem child, double index, object options = null) { throw new NotImplementedException(); }
/// <summary>
/// <para>Add an item before another already inserted item</para>
/// <para>This method works on the widget’s children list. Some layout managers
/// (e.g. <see cref="qx.ui.layout.HBox"/>) use the children order as additional
/// layout information. Other layout manager (e.g. <see cref="qx.ui.layout.Grid"/>)
/// ignore the children order for the layout process.</para>
/// </summary>
/// <param name="child">item to add</param>
/// <param name="before">item before the new item will be inserted.</param>
/// <param name="options">Optional layout data for item.</param>
[JsMethod(Name = "addBefore")]
public void AddBefore(LayoutItem child, LayoutItem before, object options = null) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the children list</para>
/// </summary>
/// <returns>The children array (Arrays are reference types, please to not modify them in-place)</returns>
[JsMethod(Name = "getChildren")]
public LayoutItem GetChildren() { throw new NotImplementedException(); }
/// <summary>
/// <para>Whether the widget contains children.</para>
/// </summary>
/// <returns>Returns true when the widget has children.</returns>
[JsMethod(Name = "hasChildren")]
public bool HasChildren() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the index position of the given item if it is
/// a child item. Otherwise it returns -1.</para>
/// <para>This method works on the widget’s children list. Some layout managers
/// (e.g. <see cref="qx.ui.layout.HBox"/>) use the children order as additional
/// layout information. Other layout manager (e.g. <see cref="qx.ui.layout.Grid"/>)
/// ignore the children order for the layout process.</para>
/// </summary>
/// <param name="child">the item to query for</param>
/// <returns>The index position or -1 when the given item is no child of this layout.</returns>
[JsMethod(Name = "indexOf")]
public double IndexOf(LayoutItem child) { throw new NotImplementedException(); }
/// <summary>
/// <para>Remove the given child item.</para>
/// </summary>
/// <param name="child">the item to remove</param>
/// <returns>This object (for chaining support)</returns>
[JsMethod(Name = "remove")]
public Widget Remove(LayoutItem child) { throw new NotImplementedException(); }
/// <summary>
/// <para>Remove all children.</para>
/// </summary>
/// <returns>An array containing the removed children.</returns>
[JsMethod(Name = "removeAll")]
public JsArray RemoveAll() { throw new NotImplementedException(); }
/// <summary>
/// <para>Remove the item at the specified index.</para>
/// <para>This method works on the widget’s children list. Some layout managers
/// (e.g. <see cref="qx.ui.layout.HBox"/>) use the children order as additional
/// layout information. Other layout manager (e.g. <see cref="qx.ui.layout.Grid"/>)
/// ignore the children order for the layout process.</para>
/// </summary>
/// <param name="index">Index of the item to remove.</param>
/// <returns>The removed item</returns>
[JsMethod(Name = "removeAt")]
public qx.ui.core.LayoutItem RemoveAt(double index) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the invalid message of the widget.</para>
/// </summary>
/// <returns>The current set message.</returns>
[JsMethod(Name = "getInvalidMessage")]
public string GetInvalidMessage() { throw new NotImplementedException(); }
/// <summary>
/// <para>Return the current required state of the widget.</para>
/// </summary>
/// <returns>True, if the widget is required.</returns>
[JsMethod(Name = "getRequired")]
public bool GetRequired() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the invalid message if required of the widget.</para>
/// </summary>
/// <returns>The current set message.</returns>
[JsMethod(Name = "getRequiredInvalidMessage")]
public string GetRequiredInvalidMessage() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the valid state of the widget.</para>
/// </summary>
/// <returns>If the state of the widget is valid.</returns>
[JsMethod(Name = "getValid")]
public bool GetValid() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property invalidMessage
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property invalidMessage.</param>
[JsMethod(Name = "initInvalidMessage")]
public void InitInvalidMessage(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property required
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property required.</param>
[JsMethod(Name = "initRequired")]
public void InitRequired(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property requiredInvalidMessage
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property requiredInvalidMessage.</param>
[JsMethod(Name = "initRequiredInvalidMessage")]
public void InitRequiredInvalidMessage(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property valid
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property valid.</param>
[JsMethod(Name = "initValid")]
public void InitValid(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property required equals true.</para>
/// </summary>
[JsMethod(Name = "isRequired")]
public void IsRequired() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property valid equals true.</para>
/// </summary>
[JsMethod(Name = "isValid")]
public void IsValid() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property invalidMessage.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetInvalidMessage")]
public void ResetInvalidMessage() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property required.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetRequired")]
public void ResetRequired() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property requiredInvalidMessage.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetRequiredInvalidMessage")]
public void ResetRequiredInvalidMessage() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property valid.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetValid")]
public void ResetValid() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the invalid message of the widget.</para>
/// </summary>
/// <param name="message">The invalid message.</param>
[JsMethod(Name = "setInvalidMessage")]
public void SetInvalidMessage(string message) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the required state of a widget.</para>
/// </summary>
/// <param name="required">A flag signaling if the widget is required.</param>
[JsMethod(Name = "setRequired")]
public void SetRequired(bool required) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the invalid message if required of the widget.</para>
/// </summary>
/// <param name="message">The invalid message.</param>
[JsMethod(Name = "setRequiredInvalidMessage")]
public void SetRequiredInvalidMessage(string message) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the valid state of the widget.</para>
/// </summary>
/// <param name="valid">The valid state of the widget.</param>
[JsMethod(Name = "setValid")]
public void SetValid(bool valid) { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property required.</para>
/// </summary>
[JsMethod(Name = "toggleRequired")]
public void ToggleRequired() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property valid.</para>
/// </summary>
[JsMethod(Name = "toggleValid")]
public void ToggleValid() { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
// --------------------------------
// GFM Pipe Tables
// --------------------------------
using System;
using NUnit.Framework;
namespace Markdig.Tests.Specs.GFMPipeTables
{
[TestFixture]
public class TestExtensionsGfmPipeTable
{
// # Extensions
//
// This section describes the different extensions supported:
//
// ## Gfm Pipe Table
//
// This groups a certain set of behaviors that makes pipe tables adhere more strictly to the GitHub-flavored Markdown specification.
//
// A pipe table is detected when:
//
// **Rule #1**
// - Each line of a paragraph block have to contain at least a **column delimiter** `|` that is not embedded by either a code inline (backtick \`) or a HTML inline.
// - The second row must separate the first header row from sub-sequent rows by containing a **header column separator** for each column separated by a column delimiter. A header column separator is:
// - starting by optional spaces
// - followed by an optional `:` to specify left align
// - followed by a sequence of at least one `-` character
// - followed by an optional `:` to specify right align (or center align if left align is also defined)
// - ending by optional spaces
//
// Because a list has a higher precedence than a pipe table, a table header row separator requires at least 2 dashes `--` to start a header row:
[Test]
public void ExtensionsGfmPipeTable_Example001()
{
// Example 1
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b
// -- | -
// 0 | 1
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>0</td>
// <td>1</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 1\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a | b\n-- | -\n0 | 1", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// The following is also considered as a table, even if the second line starts like a list:
[Test]
public void ExtensionsGfmPipeTable_Example002()
{
// Example 2
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b
// - | -
// 0 | 1
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>0</td>
// <td>1</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 2\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a | b\n- | -\n0 | 1", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// A pipe table with only one header row is allowed:
[Test]
public void ExtensionsGfmPipeTable_Example003()
{
// Example 3
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b
// -- | --
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// </table>
Console.WriteLine("Example 3\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a | b\n-- | --", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n</table>", "gfm-pipetables");
}
// After a row separator header, they will be interpreted as plain column:
[Test]
public void ExtensionsGfmPipeTable_Example004()
{
// Example 4
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b
// -- | --
// -- | --
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>--</td>
// <td>--</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 4\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a | b\n-- | --\n-- | --", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>--</td>\n<td>--</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// But if a table doesn't start with a column delimiter, it is not interpreted as a table, even if following lines have a column delimiter
[Test]
public void ExtensionsGfmPipeTable_Example005()
{
// Example 5
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a b
// c | d
// e | f
//
// Should be rendered as:
// <p>a b
// c | d
// e | f</p>
Console.WriteLine("Example 5\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a b\nc | d\ne | f", "<p>a b\nc | d\ne | f</p>", "gfm-pipetables");
}
// If a line doesn't have a column delimiter `|` the table is not detected
[Test]
public void ExtensionsGfmPipeTable_Example006()
{
// Example 6
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b
// c no d
//
// Should be rendered as:
// <p>a | b
// c no d</p>
Console.WriteLine("Example 6\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a | b\nc no d", "<p>a | b\nc no d</p>", "gfm-pipetables");
}
// If a row contains more columns than the header row, the extra columns will be ignored:
[Test]
public void ExtensionsGfmPipeTable_Example007()
{
// Example 7
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b
// -- | --
// 0 | 1 | 2
// 3 | 4
// 5 |
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>0</td>
// <td>1</td>
// </tr>
// <tr>
// <td>3</td>
// <td>4</td>
// </tr>
// <tr>
// <td>5</td>
// <td></td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 7\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a | b \n-- | --\n0 | 1 | 2\n3 | 4\n5 |", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n</tr>\n<tr>\n<td>3</td>\n<td>4</td>\n</tr>\n<tr>\n<td>5</td>\n<td></td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// **Rule #2**
// A pipe table ends after a blank line or the end of the file.
//
// **Rule #3**
// A cell content is trimmed (start and end) from white-spaces.
[Test]
public void ExtensionsGfmPipeTable_Example008()
{
// Example 8
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b |
// -- | --
// 0 | 1 |
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>0</td>
// <td>1</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 8\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a | b |\n-- | --\n0 | 1 |", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// **Rule #4**
// Column delimiters `|` at the very beginning of a line or just before a line ending with only spaces and/or terminated by a newline can be omitted
[Test]
public void ExtensionsGfmPipeTable_Example009()
{
// Example 9
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b |
// -- | --
// | 0 | 1
// | 2 | 3 |
// 4 | 5
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>0</td>
// <td>1</td>
// </tr>
// <tr>
// <td>2</td>
// <td>3</td>
// </tr>
// <tr>
// <td>4</td>
// <td>5</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 9\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec(" a | b |\n-- | --\n| 0 | 1\n| 2 | 3 |\n 4 | 5 ", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n</tr>\n<tr>\n<td>2</td>\n<td>3</td>\n</tr>\n<tr>\n<td>4</td>\n<td>5</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// A pipe may be present at both the beginning/ending of each line:
[Test]
public void ExtensionsGfmPipeTable_Example010()
{
// Example 10
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// |a|b|
// |-|-|
// |0|1|
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>0</td>
// <td>1</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 10\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("|a|b|\n|-|-|\n|0|1|", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// Or may be omitted on one side:
[Test]
public void ExtensionsGfmPipeTable_Example011()
{
// Example 11
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a|b|
// -|-|
// 0|1|
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>0</td>
// <td>1</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 11\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a|b|\n-|-|\n0|1|", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
[Test]
public void ExtensionsGfmPipeTable_Example012()
{
// Example 12
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// |a|b
// |-|-
// |0|1
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>0</td>
// <td>1</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 12\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("|a|b\n|-|-\n|0|1", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// Single column table can be declared with lines starting only by a column delimiter:
[Test]
public void ExtensionsGfmPipeTable_Example013()
{
// Example 13
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// | a
// | --
// | b
// | c
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>b</td>
// </tr>
// <tr>
// <td>c</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 13\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("| a\n| --\n| b\n| c ", "<table>\n<thead>\n<tr>\n<th>a</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>b</td>\n</tr>\n<tr>\n<td>c</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// **Rule #5**
//
// The first row is considered as a **header row** if it is separated from the regular rows by a row containing a **header column separator** for each column. A header column separator is:
//
// - starting by optional spaces
// - followed by an optional `:` to specify left align
// - followed by a sequence of at least one `-` character
// - followed by an optional `:` to specify right align (or center align if left align is also defined)
// - ending by optional spaces
[Test]
public void ExtensionsGfmPipeTable_Example014()
{
// Example 14
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b
// -------|-------
// 0 | 1
// 2 | 3
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>0</td>
// <td>1</td>
// </tr>
// <tr>
// <td>2</td>
// <td>3</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 14\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec(" a | b \n-------|-------\n 0 | 1 \n 2 | 3 ", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n</tr>\n<tr>\n<td>2</td>\n<td>3</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// The text alignment is defined by default to be center for header and left for cells. If the left alignment is applied, it will force the column heading to be left aligned.
// There is no way to define a different alignment for heading and cells (apart from the default).
// The text alignment can be changed by using the character `:` with the header column separator:
[Test]
public void ExtensionsGfmPipeTable_Example015()
{
// Example 15
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b | c
// :------|:-------:| ----:
// 0 | 1 | 2
// 3 | 4 | 5
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th style="text-align: left;">a</th>
// <th style="text-align: center;">b</th>
// <th style="text-align: right;">c</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td style="text-align: left;">0</td>
// <td style="text-align: center;">1</td>
// <td style="text-align: right;">2</td>
// </tr>
// <tr>
// <td style="text-align: left;">3</td>
// <td style="text-align: center;">4</td>
// <td style="text-align: right;">5</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 15\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec(" a | b | c \n:------|:-------:| ----:\n 0 | 1 | 2 \n 3 | 4 | 5 ", "<table>\n<thead>\n<tr>\n<th style=\"text-align: left;\">a</th>\n<th style=\"text-align: center;\">b</th>\n<th style=\"text-align: right;\">c</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: left;\">0</td>\n<td style=\"text-align: center;\">1</td>\n<td style=\"text-align: right;\">2</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">3</td>\n<td style=\"text-align: center;\">4</td>\n<td style=\"text-align: right;\">5</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// Test alignment with starting and ending pipes:
[Test]
public void ExtensionsGfmPipeTable_Example016()
{
// Example 16
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// | abc | def | ghi |
// |:---:|-----|----:|
// | 1 | 2 | 3 |
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th style="text-align: center;">abc</th>
// <th>def</th>
// <th style="text-align: right;">ghi</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td style="text-align: center;">1</td>
// <td>2</td>
// <td style="text-align: right;">3</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 16\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("| abc | def | ghi |\n|:---:|-----|----:|\n| 1 | 2 | 3 |", "<table>\n<thead>\n<tr>\n<th style=\"text-align: center;\">abc</th>\n<th>def</th>\n<th style=\"text-align: right;\">ghi</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">1</td>\n<td>2</td>\n<td style=\"text-align: right;\">3</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// The following example shows a non matching header column separator:
[Test]
public void ExtensionsGfmPipeTable_Example017()
{
// Example 17
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b
// -------|---x---
// 0 | 1
// 2 | 3
//
// Should be rendered as:
// <p>a | b
// -------|---x---
// 0 | 1
// 2 | 3</p>
Console.WriteLine("Example 17\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec(" a | b\n-------|---x---\n 0 | 1\n 2 | 3 ", "<p>a | b\n-------|---x---\n0 | 1\n2 | 3</p> ", "gfm-pipetables");
}
// **Rule #6**
//
// A column delimiter has a higher priority than emphasis delimiter
[Test]
public void ExtensionsGfmPipeTable_Example018()
{
// Example 18
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// *a* | b
// ----- |-----
// 0 | _1_
// _2 | 3*
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th><em>a</em></th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>0</td>
// <td><em>1</em></td>
// </tr>
// <tr>
// <td>_2</td>
// <td>3*</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 18\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec(" *a* | b\n----- |-----\n 0 | _1_\n _2 | 3* ", "<table>\n<thead>\n<tr>\n<th><em>a</em></th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td><em>1</em></td>\n</tr>\n<tr>\n<td>_2</td>\n<td>3*</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// **Rule #7**
//
// A backtick/code delimiter has a higher precedence than a column delimiter `|`:
[Test]
public void ExtensionsGfmPipeTable_Example019()
{
// Example 19
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b `
// 0 | `
//
// Should be rendered as:
// <p>a | b <code>0 |</code></p>
Console.WriteLine("Example 19\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a | b `\n0 | ` ", "<p>a | b <code>0 |</code></p> ", "gfm-pipetables");
}
// **Rule #8**
//
// A HTML inline has a higher precedence than a column delimiter `|`:
[Test]
public void ExtensionsGfmPipeTable_Example020()
{
// Example 20
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a <a href="" title="|"></a> | b
// -- | --
// 0 | 1
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a <a href="" title="|"></a></th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>0</td>
// <td>1</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 20\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a <a href=\"\" title=\"|\"></a> | b\n-- | --\n0 | 1", "<table>\n<thead>\n<tr>\n<th>a <a href=\"\" title=\"|\"></a></th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// **Rule #9**
//
// Links have a higher precedence than the column delimiter character `|`:
[Test]
public void ExtensionsGfmPipeTable_Example021()
{
// Example 21
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b
// -- | --
// [This is a link with a | inside the label](http://google.com) | 1
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td><a href="http://google.com">This is a link with a | inside the label</a></td>
// <td>1</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 21\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a | b\n-- | --\n[This is a link with a | inside the label](http://google.com) | 1", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><a href=\"http://google.com\">This is a link with a | inside the label</a></td>\n<td>1</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// **Rule #10**
//
// It is possible to have a single row header only:
[Test]
public void ExtensionsGfmPipeTable_Example022()
{
// Example 22
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b
// -- | --
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// </table>
Console.WriteLine("Example 22\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a | b\n-- | --", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n</table>", "gfm-pipetables");
}
[Test]
public void ExtensionsGfmPipeTable_Example023()
{
// Example 23
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// |a|b|c
// |---|---|---|
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// <th>c</th>
// </tr>
// </thead>
// </table>
Console.WriteLine("Example 23\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("|a|b|c\n|---|---|---|", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n<th>c</th>\n</tr>\n</thead>\n</table>", "gfm-pipetables");
}
// **Tests**
//
// Tests trailing spaces after pipes
[Test]
public void ExtensionsGfmPipeTable_Example024()
{
// Example 24
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// | abc | def |
// |---|---|
// | cde| ddd|
// | eee| fff|
// | fff | fffff |
// |gggg | ffff |
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>abc</th>
// <th>def</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>cde</td>
// <td>ddd</td>
// </tr>
// <tr>
// <td>eee</td>
// <td>fff</td>
// </tr>
// <tr>
// <td>fff</td>
// <td>fffff</td>
// </tr>
// <tr>
// <td>gggg</td>
// <td>ffff</td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 24\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("| abc | def | \n|---|---|\n| cde| ddd| \n| eee| fff|\n| fff | fffff | \n|gggg | ffff | ", "<table>\n<thead>\n<tr>\n<th>abc</th>\n<th>def</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>cde</td>\n<td>ddd</td>\n</tr>\n<tr>\n<td>eee</td>\n<td>fff</td>\n</tr>\n<tr>\n<td>fff</td>\n<td>fffff</td>\n</tr>\n<tr>\n<td>gggg</td>\n<td>ffff</td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
// **Normalized columns count**
//
// The tables are normalized to the number of columns found in the table header.
// Extra columns will be ignored, missing columns will be inserted.
[Test]
public void ExtensionsGfmPipeTable_Example025()
{
// Example 25
// Section: Extensions / Gfm Pipe Table
//
// The following Markdown:
// a | b
// -- | -
// 0 | 1 | 2
// 3 |
//
// Should be rendered as:
// <table>
// <thead>
// <tr>
// <th>a</th>
// <th>b</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>0</td>
// <td>1</td>
// </tr>
// <tr>
// <td>3</td>
// <td></td>
// </tr>
// </tbody>
// </table>
Console.WriteLine("Example 25\nSection Extensions / Gfm Pipe Table\n");
TestParser.TestSpec("a | b\n-- | - \n0 | 1 | 2\n3 |", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n</tr>\n<tr>\n<td>3</td>\n<td></td>\n</tr>\n</tbody>\n</table>", "gfm-pipetables");
}
}
}
| |
using UnityEngine;
using System.Collections;
public class EnemySight : MonoBehaviour
{
public float fieldOfViewAngle = 100f; // Number of degrees, centred on forward, for the enemy see.
public Vector3 personalLastSighting; // Last place this enemy spotted the player.
private NavMeshAgent nav; // Reference to the NavMeshAgent component.
private SphereCollider col; // Reference to the sphere collider trigger component.
private Animator anim; // Reference to the Animator.
private LastPlayerSighting lastPlayerSighting; // Reference to last global sighting of the player.
private GameObject player; // Reference to the player.
private Animator playerAnim; // Reference to the player's animator component.
private PlayerHealth playerHealth; // Reference to the player's health script.
private HashIDs hash; // Reference to the HashIDs.
private Vector3 previousSighting; // Where the player was sighted last frame.
public bool playerInSight; // Whether or not the player is currently sighted.
private EnemyAI ai;
private GameObject[] ammunitions;
public bool ammunitionInSight;
public GameObject currentAmmunition;
private GameObject[] laserSwitches;
public GameObject currentSwitch;
public bool switchInSight;
private GameObject[] healthPackages;
public bool healthInSight;
public GameObject currentHealthPackage;
private GameObject drone;
private bool droneInSight = false;
void Awake ()
{
// Setting up the references.
nav = GetComponent<NavMeshAgent>();
col = GetComponent<SphereCollider>();
anim = GetComponent<Animator>();
lastPlayerSighting = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent<LastPlayerSighting>();
player = GameObject.FindGameObjectWithTag(Tags.player);
ammunitions = GameObject.FindGameObjectsWithTag(Tags.ammunition);
healthPackages = GameObject.FindGameObjectsWithTag(Tags.health);
laserSwitches = GameObject.FindGameObjectsWithTag(Tags.laserSwitch);
playerAnim = player.GetComponent<Animator>();
playerHealth = player.GetComponent<PlayerHealth>();
hash = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent<HashIDs>();
ai = transform.GetComponent<EnemyAI>();
// Set the personal sighting and the previous sighting to the reset position.
personalLastSighting = lastPlayerSighting.resetPosition;
previousSighting = lastPlayerSighting.resetPosition;
}
void Update ()
{
// If the last global sighting of the player has changed...
if(lastPlayerSighting.position != previousSighting)
// ... then update the personal sighting to be the same as the global sighting.
personalLastSighting = lastPlayerSighting.position;
// Set the previous sighting to the be the sighting from this frame.
previousSighting = lastPlayerSighting.position;
// If the player is alive...
if(playerHealth.health > 0f && ai.ammunitionQt > 0)
// ... set the animator parameter to whether the player is in sight or not.
anim.SetBool(hash.playerInSightBool, playerInSight);
else
// ... set the animator parameter to false.
anim.SetBool(hash.playerInSightBool, false);
}
void OnTriggerStay (Collider other)
{
// If the player has entered the trigger sphere...
if(other.gameObject == player)
{
// By default the player is not in sight.
playerInSight = false;
// Create a vector from the enemy to the player and store the angle between it and forward.
Vector3 direction = other.transform.position - transform.position;
float angle = Vector3.Angle(direction, transform.forward);
// If the angle between forward and where the player is, is less than half the angle of view...
if(angle < fieldOfViewAngle * 0.5f)
{
RaycastHit hit;
// ... and if a raycast towards the player hits something...
if(Physics.Raycast(transform.position + transform.up, direction.normalized, out hit, col.radius))
{
// ... and if the raycast hits the player...
if(hit.collider.gameObject == player)
{
// ... the player is in sight.
playerInSight = true;
// Set the last global sighting is the players current position.
//lastPlayerSighting.position = player.transform.position;
}
}
}
// Store the name hashes of the current states.
int playerLayerZeroStateHash = playerAnim.GetCurrentAnimatorStateInfo(0).nameHash;
int playerLayerOneStateHash = playerAnim.GetCurrentAnimatorStateInfo(1).nameHash;
// If the player is running or is attracting attention...
if(playerLayerZeroStateHash == hash.locomotionState || playerLayerOneStateHash == hash.shoutState)
{
// ... and if the player is within hearing range...
if(CalculatePathLength(player.transform.position) <= col.radius)
// ... set the last personal sighting of the player to the player's current position.
personalLastSighting = player.transform.position;
}
}
if(drone != null && other.gameObject == drone){
droneInSight = false;
Vector3 direction = other.transform.position - transform.position;
float angle = Vector3.Angle(direction, transform.forward);
if(angle < fieldOfViewAngle * 0.5f){
RaycastHit hit;
if(Physics.Raycast(transform.position + transform.up, direction.normalized, out hit, col.radius)){
if(drone != null && hit.collider.gameObject == drone){
droneInSight = true;
}
}
}
}
foreach(GameObject ammo in ammunitions)
if(other.gameObject == ammo){
ammunitionInSight = false;
// Create a vector from the enemy to the player and store the angle between it and forward.
Vector3 direction = other.transform.position - transform.position;
float angle = Vector3.Angle(direction, transform.forward);
// If the angle between forward and where the player is, is less than half the angle of view...
if(angle < fieldOfViewAngle * 0.5f){
RaycastHit hit;
if(Physics.Raycast(transform.position + transform.up, direction.normalized, out hit, col.radius))
if(hit.collider.gameObject == ammo){
ammunitionInSight = true;
currentAmmunition = other.gameObject;
}
}
}
foreach(GameObject hp in healthPackages)
if(other.gameObject == hp){
healthInSight = false;
// Create a vector from the enemy to the player and store the angle between it and forward.
Vector3 direction = other.transform.position - transform.position;
float angle = Vector3.Angle(direction, transform.forward);
// If the angle between forward and where the player is, is less than half the angle of view...
if(angle < fieldOfViewAngle * 0.5f){
RaycastHit hit;
if(Physics.Raycast(transform.position + transform.up, direction.normalized, out hit, col.radius))
if(hit.collider.gameObject == hp){
healthInSight = true;
currentHealthPackage = other.gameObject;
}
}
}
foreach(GameObject laserSwitch in laserSwitches)
if(other.gameObject == laserSwitch){
switchInSight = false;
// Create a vector from the enemy to the player and store the angle between it and forward.
Vector3 direction = other.transform.position - transform.position;
float angle = Vector3.Angle(direction, transform.forward);
// If the angle between forward and where the player is, is less than half the angle of view...
if(angle < fieldOfViewAngle * 0.5f){
RaycastHit hit;
if(Physics.Raycast(transform.position + transform.up, direction.normalized, out hit, col.radius))
if(hit.collider.gameObject == laserSwitch){
switchInSight = true;
currentSwitch = other.gameObject;
}
}
}
}
void OnTriggerExit (Collider other)
{
// If the player leaves the trigger zone...
if(other.gameObject == player)
// ... the player is not in sight.
playerInSight = false;
}
float CalculatePathLength (Vector3 targetPosition)
{
// Create a path and set it based on a target position.
NavMeshPath path = new NavMeshPath();
if(nav.enabled)
nav.CalculatePath(targetPosition, path);
// Create an array of points which is the length of the number of corners in the path + 2.
Vector3 [] allWayPoints = new Vector3[path.corners.Length + 2];
// The first point is the enemy's position.
allWayPoints[0] = transform.position;
// The last point is the target position.
allWayPoints[allWayPoints.Length - 1] = targetPosition;
// The points inbetween are the corners of the path.
for(int i = 0; i < path.corners.Length; i++)
{
allWayPoints[i + 1] = path.corners[i];
}
// Create a float to store the path length that is by default 0.
float pathLength = 0;
// Increment the path length by an amount equal to the distance between each waypoint and the next.
for(int i = 0; i < allWayPoints.Length - 1; i++)
{
pathLength += Vector3.Distance(allWayPoints[i], allWayPoints[i + 1]);
}
return pathLength;
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// An amusement park.
/// </summary>
public class AmusementPark_Core : TypeCore, IEntertainmentBusiness
{
public AmusementPark_Core()
{
this._TypeId = 15;
this._Id = "AmusementPark";
this._Schema_Org_Url = "http://schema.org/AmusementPark";
string label = "";
GetLabel(out label, "AmusementPark", typeof(AmusementPark_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,96};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{96};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 408164 $
* $LastChangedDate: 2006-05-21 06:27:09 -0600 (Sun, 21 May 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* 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.
*
********************************************************************************/
#endregion
#region Imports
using System;
using System.Collections;
using System.Collections.Specialized;
#endregion
namespace IBatisNet.Common.Utilities.TypesResolver
{
/// <summary>
/// Provides access to a central registry of aliased <see cref="System.Type"/>s.
/// </summary>
/// <remarks>
/// <p>
/// Simplifies configuration by allowing aliases to be used instead of
/// fully qualified type names.
/// </p>
/// <p>
/// Comes 'pre-loaded' with a number of convenience alias' for the more
/// common types; an example would be the '<c>int</c>' (or '<c>Integer</c>'
/// for Visual Basic.NET developers) alias for the <see cref="System.Int32"/>
/// type.
/// </p>
/// </remarks>
public class TypeRegistry
{
#region Constants
/// <summary>
/// The alias around the 'list' type.
/// </summary>
public const string ArrayListAlias1 = "arraylist";
/// <summary>
/// Another alias around the 'list' type.
/// </summary>
public const string ArrayListAlias2 = "list";
/// <summary>
/// Another alias around the 'bool' type.
/// </summary>
public const string BoolAlias = "bool";
/// <summary>
/// The alias around the 'bool' type.
/// </summary>
public const string BooleanAlias = "boolean";
/// <summary>
/// The alias around the 'byte' type.
/// </summary>
public const string ByteAlias = "byte";
/// <summary>
/// The alias around the 'char' type.
/// </summary>
public const string CharAlias = "char";
/// <summary>
/// The alias around the 'DateTime' type.
/// </summary>
public const string DateAlias1 = "datetime";
/// <summary>
/// Another alias around the 'DateTime' type.
/// </summary>
public const string DateAlias2 = "date";
/// <summary>
/// The alias around the 'decimal' type.
/// </summary>
public const string DecimalAlias = "decimal";
/// <summary>
/// The alias around the 'double' type.
/// </summary>
public const string DoubleAlias = "double";
/// <summary>
/// The alias around the 'float' type.
/// </summary>
public const string FloatAlias = "float";
/// <summary>
/// Another alias around the 'float' type.
/// </summary>
public const string SingleAlias = "single";
/// <summary>
/// The alias around the 'guid' type.
/// </summary>
public const string GuidAlias = "guid";
/// <summary>
/// The alias around the 'Hashtable' type.
/// </summary>
public const string HashtableAlias1 = "hashtable";
/// <summary>
/// Another alias around the 'Hashtable' type.
/// </summary>
public const string HashtableAlias2 = "map";
/// <summary>
/// Another alias around the 'Hashtable' type.
/// </summary>
public const string HashtableAlias3 = "hashmap";
/// <summary>
/// The alias around the 'short' type.
/// </summary>
public const string Int16Alias1 = "int16";
/// <summary>
/// Another alias around the 'short' type.
/// </summary>
public const string Int16Alias2 = "short";
/// <summary>
/// The alias around the 'int' type.
/// </summary>
public const string Int32Alias1 = "int32";
/// <summary>
/// Another alias around the 'int' type.
/// </summary>
public const string Int32Alias2 = "int";
/// <summary>
/// Another alias around the 'int' type.
/// </summary>
public const string Int32Alias3 = "integer";
/// <summary>
/// The alias around the 'long' type.
/// </summary>
public const string Int64Alias1 = "int64";
/// <summary>
/// Another alias around the 'long' type.
/// </summary>
public const string Int64Alias2 = "long";
/// <summary>
/// The alias around the 'unsigned short' type.
/// </summary>
public const string UInt16Alias1 = "uint16";
/// <summary>
/// Another alias around the 'unsigned short' type.
/// </summary>
public const string UInt16Alias2 = "ushort";
/// <summary>
/// The alias around the 'unsigned int' type.
/// </summary>
public const string UInt32Alias1 = "uint32";
/// <summary>
/// Another alias around the 'unsigned int' type.
/// </summary>
public const string UInt32Alias2 = "uint";
/// <summary>
/// The alias around the 'unsigned long' type.
/// </summary>
public const string UInt64Alias1 = "uint64";
/// <summary>
/// Another alias around the 'unsigned long' type.
/// </summary>
public const string UInt64Alias2 = "ulong";
/// <summary>
/// The alias around the 'SByte' type.
/// </summary>
public const string SByteAlias = "sbyte";
/// <summary>
/// The alias around the 'string' type.
/// </summary>
public const string StringAlias = "string";
/// <summary>
/// The alias around the 'TimeSpan' type.
/// </summary>
public const string TimeSpanAlias = "timespan";
#if dotnet2
/// <summary>
/// The alias around the 'int?' type.
/// </summary>
public const string NullableInt32Alias = "int?";
/// <summary>
/// The alias around the 'int?[]' array type.
/// </summary>
public const string NullableInt32ArrayAlias = "int?[]";
/// <summary>
/// The alias around the 'decimal?' type.
/// </summary>
public const string NullableDecimalAlias = "decimal?";
/// <summary>
/// The alias around the 'decimal?[]' array type.
/// </summary>
public const string NullableDecimalArrayAlias = "decimal?[]";
/// <summary>
/// The alias around the 'char?' type.
/// </summary>
public const string NullableCharAlias = "char?";
/// <summary>
/// The alias around the 'char?[]' array type.
/// </summary>
public const string NullableCharArrayAlias = "char?[]";
/// <summary>
/// The alias around the 'long?' type.
/// </summary>
public const string NullableInt64Alias = "long?";
/// <summary>
/// The alias around the 'long?[]' array type.
/// </summary>
public const string NullableInt64ArrayAlias = "long?[]";
/// <summary>
/// The alias around the 'short?' type.
/// </summary>
public const string NullableInt16Alias = "short?";
/// <summary>
/// The alias around the 'short?[]' array type.
/// </summary>
public const string NullableInt16ArrayAlias = "short?[]";
/// <summary>
/// The alias around the 'unsigned int?' type.
/// </summary>
public const string NullableUInt32Alias = "uint?";
/// <summary>
/// The alias around the 'unsigned long?' type.
/// </summary>
public const string NullableUInt64Alias = "ulong?";
/// <summary>
/// The alias around the 'ulong?[]' array type.
/// </summary>
public const string NullableUInt64ArrayAlias = "ulong?[]";
/// <summary>
/// The alias around the 'uint?[]' array type.
/// </summary>
public const string NullableUInt32ArrayAlias = "uint?[]";
/// <summary>
/// The alias around the 'unsigned short?' type.
/// </summary>
public const string NullableUInt16Alias = "ushort?";
/// <summary>
/// The alias around the 'ushort?[]' array type.
/// </summary>
public const string NullableUInt16ArrayAlias = "ushort?[]";
/// <summary>
/// The alias around the 'double?' type.
/// </summary>
public const string NullableDoubleAlias = "double?";
/// <summary>
/// The alias around the 'double?[]' array type.
/// </summary>
public const string NullableDoubleArrayAlias = "double?[]";
/// <summary>
/// The alias around the 'float?' type.
/// </summary>
public const string NullableFloatAlias = "float?";
/// <summary>
/// The alias around the 'float?[]' array type.
/// </summary>
public const string NullableFloatArrayAlias = "float?[]";
/// <summary>
/// The alias around the 'bool?' type.
/// </summary>
public const string NullableBoolAlias = "bool?";
/// <summary>
/// The alias around the 'bool?[]' array type.
/// </summary>
public const string NullableBoolArrayAlias = "bool?[]";
#endif
#endregion
#region Fields
private static IDictionary _types = new Hashtable();
#endregion
#region Constructor (s) / Destructor
/// <summary>
/// Creates a new instance of the <see cref="TypeRegistry"/> class.
/// </summary>
/// <remarks>
/// <p>
/// This is a utility class, and as such has no publicly visible
/// constructors.
/// </p>
/// </remarks>
private TypeRegistry() {}
/// <summary>
/// Initialises the static properties of the TypeAliasResolver class.
/// </summary>
static TypeRegistry()
{
// Initialize a dictionary with some fully qualifiaed name
_types[ArrayListAlias1] = typeof (ArrayList);
_types[ArrayListAlias2] = typeof (ArrayList);
_types[BoolAlias] = typeof (bool);
_types[BooleanAlias] = typeof (bool);
_types[ByteAlias] = typeof (byte);
_types[CharAlias] = typeof (char);
_types[DateAlias1] = typeof (DateTime);
_types[DateAlias2] = typeof (DateTime);
_types[DecimalAlias] = typeof (decimal);
_types[DoubleAlias] = typeof (double);
_types[FloatAlias] = typeof (float);
_types[SingleAlias] = typeof (float);
_types[GuidAlias] = typeof (Guid);
_types[HashtableAlias1] = typeof (Hashtable);
_types[HashtableAlias2] = typeof (Hashtable);
_types[HashtableAlias3] = typeof (Hashtable);
_types[Int16Alias1] = typeof (short);
_types[Int16Alias2] = typeof (short);
_types[Int32Alias1] = typeof (int);
_types[Int32Alias2] = typeof (int);
_types[Int32Alias3] = typeof (int);
_types[Int64Alias1] = typeof (long);
_types[Int64Alias2] = typeof (long);
_types[UInt16Alias1] = typeof (ushort);
_types[UInt16Alias2] = typeof (ushort);
_types[UInt32Alias1] = typeof (uint);
_types[UInt32Alias2] = typeof (uint);
_types[UInt64Alias1] = typeof (ulong);
_types[UInt64Alias2] = typeof (ulong);
_types[SByteAlias] = typeof (sbyte);
_types[StringAlias] = typeof (string);
_types[TimeSpanAlias] = typeof (string);
#if dotnet2
_types[NullableInt32Alias] = typeof(int?);
_types[NullableInt32ArrayAlias] = typeof(int?[]);
_types[NullableDecimalAlias] = typeof(decimal?);
_types[NullableDecimalArrayAlias] = typeof(decimal?[]);
_types[NullableCharAlias] = typeof(char?);
_types[NullableCharArrayAlias] = typeof(char?[]);
_types[NullableInt64Alias] = typeof(long?);
_types[NullableInt64ArrayAlias] = typeof(long?[]);
_types[NullableInt16Alias] = typeof(short?);
_types[NullableInt16ArrayAlias] = typeof(short?[]);
_types[NullableUInt32Alias] = typeof(uint?);
_types[NullableUInt32ArrayAlias] = typeof(uint?[]);
_types[NullableUInt64Alias] = typeof(ulong?);
_types[NullableUInt64ArrayAlias] = typeof(ulong?[]);
_types[NullableUInt16Alias] = typeof(ushort?);
_types[NullableUInt16ArrayAlias] = typeof(ushort?[]);
_types[NullableDoubleAlias] = typeof(double?);
_types[NullableDoubleArrayAlias] = typeof(double?[]);
_types[NullableFloatAlias] = typeof(float?);
_types[NullableFloatArrayAlias] = typeof(float?[]);
_types[NullableBoolAlias] = typeof(bool?);
_types[NullableBoolArrayAlias] = typeof(bool?[]);
#endif
}
#endregion
#region Methods
/// <summary>
/// Resolves the supplied <paramref name="alias"/> to a <see cref="System.Type"/>.
/// </summary>
/// <param name="alias">
/// The alias to resolve.
/// </param>
/// <returns>
/// The <see cref="System.Type"/> the supplied <paramref name="alias"/> was
/// associated with, or <see lang="null"/> if no <see cref="System.Type"/>
/// was previously registered for the supplied <paramref name="alias"/>.
/// </returns>
/// <remarks>The alis name will be convert in lower character before the resolution.</remarks>
/// <exception cref="System.ArgumentNullException">
/// If the supplied <paramref name="alias"/> is <see langword="null"/> or
/// contains only whitespace character(s).
/// </exception>
public static Type ResolveType(string alias)
{
return (Type)_types[alias.ToLower()];
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Linq;
using GLTF.Extensions;
using GLTF.Math;
using Newtonsoft.Json;
namespace GLTF.Schema
{
/// <summary>
/// A node in the node hierarchy.
/// When the node contains `skin`, all `mesh.primitives` must contain `JOINT`
/// and `WEIGHT` attributes. A node can have either a `matrix` or any combination
/// of `translation`/`rotation`/`scale` (TRS) properties.
/// TRS properties are converted to matrices and postmultiplied in
/// the `T * R * S` order to compose the transformation matrix;
/// first the scale is applied to the vertices, then the rotation, and then
/// the translation. If none are provided, the transform is the Identity.
/// When a node is targeted for animation
/// (referenced by an animation.channel.target), only TRS properties may be present;
/// `matrix` will not be present.
/// </summary>
public class Node : GLTFChildOfRootProperty
{
/// <summary>
/// If true, extracts transform, rotation, scale values from the Matrix4x4. Otherwise uses the Transform, Rotate, Scale directly as specified by by the node.
/// </summary>
public bool UseTRS;
/// <summary>
/// The index of the camera referenced by this node.
/// </summary>
public CameraId Camera;
/// <summary>
/// The indices of this node's children.
/// </summary>
public List<NodeId> Children;
/// <summary>
/// The index of the skin referenced by this node.
/// </summary>
public SkinId Skin;
/// <summary>
/// A floating-point 4x4 transformation matrix stored in column-major order.
/// </summary>
public Matrix4x4 Matrix = Matrix4x4.Identity;
/// <summary>
/// The index of the mesh in this node.
/// </summary>
public MeshId Mesh;
/// <summary>
/// The node's unit quaternion rotation in the order (x, y, z, w),
/// where w is the scalar.
/// </summary>
public Quaternion Rotation = new Quaternion(0, 0, 0, 1);
/// <summary>
/// The node's non-uniform scale.
/// </summary>
public Vector3 Scale = Vector3.One;
/// <summary>
/// The node's translation.
/// </summary>
public Vector3 Translation = Vector3.Zero;
/// <summary>
/// The weights of the instantiated Morph Target.
/// Number of elements must match number of Morph Targets of used mesh.
/// </summary>
public List<double> Weights;
public Node()
{
}
public Node(Node node, GLTFRoot gltfRoot) : base(node, gltfRoot)
{
if (node == null) return;
UseTRS = node.UseTRS;
if (node.Camera != null)
{
Camera = new CameraId(node.Camera, gltfRoot);
}
if (node.Children != null)
{
Children = new List<NodeId>(node.Children.Count);
foreach (NodeId child in node.Children)
{
Children.Add(new NodeId(child, gltfRoot));
}
}
if (node.Skin != null)
{
Skin = new SkinId(node.Skin, gltfRoot);
}
if (node.Matrix != null)
{
Matrix = new Matrix4x4(node.Matrix);
}
if (node.Mesh != null)
{
Mesh = new MeshId(node.Mesh, gltfRoot);
}
Rotation = node.Rotation;
Scale = node.Scale;
Translation = node.Translation;
if (node.Weights != null)
{
Weights = node.Weights.ToList();
}
}
public static Node Deserialize(GLTFRoot root, JsonReader reader)
{
var node = new Node();
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case "camera":
node.Camera = CameraId.Deserialize(root, reader);
break;
case "children":
node.Children = NodeId.ReadList(root, reader);
break;
case "skin":
node.Skin = SkinId.Deserialize(root, reader);
break;
case "matrix":
var list = reader.ReadDoubleList();
// gltf has column ordered matricies
var mat = new Matrix4x4(
(float)list[0], (float)list[1], (float)list[2], (float)list[3], (float)list[4], (float)list[5], (float)list[6], (float)list[7],
(float)list[8], (float)list[9], (float)list[10], (float)list[11], (float)list[12], (float)list[13], (float)list[14], (float)list[15]
);
node.Matrix = mat;
break;
case "mesh":
node.Mesh = MeshId.Deserialize(root, reader);
break;
case "rotation":
node.UseTRS = true;
node.Rotation = reader.ReadAsQuaternion();
break;
case "scale":
node.UseTRS = true;
node.Scale = reader.ReadAsVector3();
break;
case "translation":
node.UseTRS = true;
node.Translation = reader.ReadAsVector3();
break;
case "weights":
node.Weights = reader.ReadDoubleList();
break;
default:
node.DefaultPropertyDeserializer(root, reader);
break;
}
}
return node;
}
public override void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
if (Camera != null)
{
writer.WritePropertyName("camera");
writer.WriteValue(Camera.Id);
}
if (Children != null && Children.Count > 0)
{
writer.WritePropertyName("children");
writer.WriteStartArray();
foreach (var child in Children)
{
writer.WriteValue(child.Id);
}
writer.WriteEndArray();
}
if (Skin != null)
{
writer.WritePropertyName("skin");
writer.WriteValue(Skin.Id);
}
if (!Matrix.Equals(Matrix4x4.Identity))
{
writer.WritePropertyName("matrix");
writer.WriteStartArray();
writer.WriteValue(Matrix.M11); writer.WriteValue(Matrix.M21); writer.WriteValue(Matrix.M31); writer.WriteValue(Matrix.M41);
writer.WriteValue(Matrix.M12); writer.WriteValue(Matrix.M22); writer.WriteValue(Matrix.M32); writer.WriteValue(Matrix.M42);
writer.WriteValue(Matrix.M13); writer.WriteValue(Matrix.M23); writer.WriteValue(Matrix.M33); writer.WriteValue(Matrix.M43);
writer.WriteValue(Matrix.M14); writer.WriteValue(Matrix.M24); writer.WriteValue(Matrix.M34); writer.WriteValue(Matrix.M44);
writer.WriteEndArray();
}
if (Mesh != null)
{
writer.WritePropertyName("mesh");
writer.WriteValue(Mesh.Id);
}
if (Rotation != Quaternion.Identity)
{
writer.WritePropertyName("rotation");
writer.WriteStartArray();
writer.WriteValue(Rotation.X);
writer.WriteValue(Rotation.Y);
writer.WriteValue(Rotation.Z);
writer.WriteValue(Rotation.W);
writer.WriteEndArray();
}
if (Scale != Vector3.One)
{
writer.WritePropertyName("scale");
writer.WriteStartArray();
writer.WriteValue(Scale.X);
writer.WriteValue(Scale.Y);
writer.WriteValue(Scale.Z);
writer.WriteEndArray();
}
if (Translation != Vector3.Zero)
{
writer.WritePropertyName("translation");
writer.WriteStartArray();
writer.WriteValue(Translation.X);
writer.WriteValue(Translation.Y);
writer.WriteValue(Translation.Z);
writer.WriteEndArray();
}
if (Weights != null && Weights.Count > 0)
{
writer.WritePropertyName("weights");
writer.WriteStartArray();
foreach (var weight in Weights)
{
writer.WriteValue(weight);
}
writer.WriteEndArray();
}
base.Serialize(writer);
writer.WriteEndObject();
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2013 FUJIWARA, Yusuke
//
// 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.
//
#endregion -- License Terms --
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Threading;
#if NETFX_CORE
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
#endif
namespace MsgPack.Serialization
{
/// <summary>
/// <strong>This is intened to MsgPack for CLI internal use. Do not use this type from application directly.</strong>
/// Represents serialization context information for internal serialization logic.
/// </summary>
public sealed class SerializationContext
{
private static SerializationContext _default = new SerializationContext();
/// <summary>
/// Gets or sets the default instance.
/// </summary>
/// <value>
/// The default <see cref="SerializationContext"/> instance.
/// </value>
/// <exception cref="ArgumentNullException">The setting value is <c>null</c>.</exception>
public static SerializationContext Default
{
get { return _default; }
set
{
if ( value == null )
{
throw new ArgumentNullException( "value" );
}
_default = value;
}
}
private readonly SerializerRepository _serializers;
private readonly HashSet<Type> _typeLock;
/// <summary>
/// Gets the current <see cref="SerializerRepository"/>.
/// </summary>
/// <value>
/// The current <see cref="SerializerRepository"/>.
/// </value>
public SerializerRepository Serializers
{
get
{
Contract.Ensures( Contract.Result<SerializerRepository>() != null );
return this._serializers;
}
}
private EmitterFlavor _emitterFlavor = EmitterFlavor.FieldBased;
/// <summary>
/// Gets or sets the <see cref="EmitterFlavor"/>.
/// </summary>
/// <value>
/// The <see cref="EmitterFlavor"/>
/// </value>
/// <remarks>
/// For testing purposes.
/// </remarks>
internal EmitterFlavor EmitterFlavor
{
get { return this._emitterFlavor; }
set { this._emitterFlavor = value; }
}
private readonly SerializationCompatibilityOptions _compatibilityOptions;
/// <summary>
/// Gets the compatibility options.
/// </summary>
/// <value>
/// The <see cref="SerializationCompatibilityOptions"/> which stores compatibility options. This value will not be <c>null</c>.
/// </value>
public SerializationCompatibilityOptions CompatibilityOptions
{
get
{
Contract.Ensures( Contract.Result<SerializationCompatibilityOptions>() != null );
return this._compatibilityOptions;
}
}
private SerializationMethod _serializationMethod;
/// <summary>
/// Gets or sets the <see cref="SerializationMethod"/> to determine serialization strategy.
/// </summary>
/// <value>
/// The <see cref="SerializationMethod"/> to determine serialization strategy.
/// </value>
public SerializationMethod SerializationMethod
{
get
{
Contract.Ensures( Enum.IsDefined( typeof( SerializationMethod ), Contract.Result<SerializationMethod>() ) );
return this._serializationMethod;
}
set
{
switch ( value )
{
case Serialization.SerializationMethod.Array:
case Serialization.SerializationMethod.Map:
{
break;
}
default:
{
throw new ArgumentOutOfRangeException( "value" );
}
}
Contract.EndContractBlock();
this._serializationMethod = value;
}
}
private SerializationMethodGeneratorOption _generatorOption;
/// <summary>
/// Gets or sets the <see cref="SerializationMethodGeneratorOption"/> to control code generation.
/// </summary>
/// <value>
/// The <see cref="SerializationMethodGeneratorOption"/>.
/// </value>
public SerializationMethodGeneratorOption GeneratorOption
{
get
{
//Contract.Ensures( Enum.IsDefined( typeof( SerializationMethod ), Contract.Result<SerializationMethodGeneratorOption>() ) );
return this._generatorOption;
}
set
{
switch ( value )
{
case SerializationMethodGeneratorOption.Fast:
#if !SILVERLIGHT
case SerializationMethodGeneratorOption.CanCollect:
case SerializationMethodGeneratorOption.CanDump:
#endif
{
break;
}
default:
{
throw new ArgumentOutOfRangeException( "value" );
}
}
Contract.EndContractBlock();
this._generatorOption = value;
}
}
private readonly DefaultConcreteTypeRepository _defaultCollectionTypes;
/// <summary>
/// Gets the default collection types.
/// </summary>
/// <value>
/// The default collection types. This value will not be <c>null</c>.
/// </value>
public DefaultConcreteTypeRepository DefaultCollectionTypes
{
get { return this._defaultCollectionTypes; }
}
/// <summary>
/// Initializes a new instance of the <see cref="SerializationContext"/> class with copy of <see cref="SerializerRepository.Default"/>.
/// </summary>
public SerializationContext()
: this( new SerializerRepository( SerializerRepository.Default ), PackerCompatibilityOptions.Classic ) { }
/// <summary>
/// Initializes a new instance of the <see cref="SerializationContext"/> class with copy of <see cref="SerializerRepository.GetDefault(PackerCompatibilityOptions)"/> for specified <see cref="PackerCompatibilityOptions"/>.
/// </summary>
/// <param name="packerCompatibilityOptions"><see cref="PackerCompatibilityOptions"/> which will be used on built-in serializers.</param>
public SerializationContext( PackerCompatibilityOptions packerCompatibilityOptions )
: this( new SerializerRepository( SerializerRepository.GetDefault( packerCompatibilityOptions ) ), packerCompatibilityOptions ) { }
internal SerializationContext(
SerializerRepository serializers, PackerCompatibilityOptions packerCompatibilityOptions )
{
Contract.Requires( serializers != null );
this._compatibilityOptions =
new SerializationCompatibilityOptions()
{
PackerCompatibilityOptions =
packerCompatibilityOptions
};
this._serializers = serializers;
this._typeLock = new HashSet<Type>();
this._defaultCollectionTypes = new DefaultConcreteTypeRepository();
}
internal bool ContainsSerializer( Type rootType )
{
return this._serializers.Contains( rootType );
}
/// <summary>
/// Gets the <see cref="MessagePackSerializer{T}"/> with this instance.
/// </summary>
/// <typeparam name="T">Type of serialization/deserialization target.</typeparam>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>.
/// If there is exiting one, returns it.
/// Else the new instance will be created.
/// </returns>
/// <remarks>
/// This method automatically register new instance via <see cref="M:SerializationRepository.Register{T}(MessagePackSerializer{T})"/>.
/// </remarks>
public MessagePackSerializer<T> GetSerializer<T>()
{
Contract.Ensures( Contract.Result<MessagePackSerializer<T>>() != null );
var serializer = this._serializers.Get<T>( this );
if ( serializer == null )
{
bool lockTaken = false;
try
{
try { }
finally
{
lock( this._typeLock )
{
lockTaken = this._typeLock.Add( typeof( T ) );
}
}
if ( !lockTaken )
{
return new LazyDelegatingMessagePackSerializer<T>( this );
}
serializer = MessagePackSerializer.Create<T>( this );
}
finally
{
if ( lockTaken )
{
lock( this._typeLock )
{
this._typeLock.Remove( typeof( T ) );
}
}
}
if ( !this._serializers.Register<T>( serializer ) )
{
serializer = this._serializers.Get<T>( this );
}
}
return serializer;
}
/// <summary>
/// Gets the serializer for the specified <see cref="Type"/>.
/// </summary>
/// <param name="targetType">Type of the serialization target.</param>
/// <returns>
/// <see cref="IMessagePackSingleObjectSerializer"/>.
/// If there is exiting one, returns it.
/// Else the new instance will be created.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="targetType"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// Although <see cref="GetSerializer{T}"/> is preferred,
/// this method can be used from non-generic type or methods.
/// </remarks>
public IMessagePackSingleObjectSerializer GetSerializer( Type targetType )
{
if ( targetType == null )
{
throw new ArgumentNullException( "targetType" );
}
Contract.Ensures( Contract.Result<IMessagePackSerializer>() != null );
return SerializerGetter.Instance.Get( this, targetType );
}
private sealed class SerializerGetter
{
public static readonly SerializerGetter Instance = new SerializerGetter();
private readonly Dictionary<RuntimeTypeHandle, Func<SerializationContext, IMessagePackSingleObjectSerializer>> _cache =
new Dictionary<RuntimeTypeHandle, Func<SerializationContext, IMessagePackSingleObjectSerializer>>();
private SerializerGetter() { }
public IMessagePackSingleObjectSerializer Get( SerializationContext context, Type targetType )
{
Func<SerializationContext, IMessagePackSingleObjectSerializer> func;
if ( !this._cache.TryGetValue( targetType.TypeHandle, out func ) || func == null )
{
#if !NETFX_CORE
func =
Delegate.CreateDelegate(
typeof( Func<SerializationContext, IMessagePackSingleObjectSerializer> ),
typeof( SerializerGetter<> ).MakeGenericType( targetType ).GetMethod( "Get" )
) as Func<SerializationContext, IMessagePackSingleObjectSerializer>;
#else
var contextParameter = Expression.Parameter( typeof( SerializationContext ), "context" );
func =
Expression.Lambda<Func<SerializationContext, IMessagePackSingleObjectSerializer>>(
Expression.Call(
null,
typeof( SerializerGetter<> ).MakeGenericType( targetType ).GetRuntimeMethods().Single( m => m.Name == "Get" ),
contextParameter
),
contextParameter
).Compile();
#endif
this._cache[ targetType.TypeHandle ] = func;
}
return func( context );
}
}
private static class SerializerGetter<T>
{
#if !NETFX_CORE
private static readonly Func<SerializationContext, MessagePackSerializer<T>> _func =
Delegate.CreateDelegate(
typeof( Func<SerializationContext, MessagePackSerializer<T>> ),
Metadata._SerializationContext.GetSerializer1_Method.MakeGenericMethod( typeof( T ) )
) as Func<SerializationContext, MessagePackSerializer<T>>;
#else
private static readonly Func<SerializationContext, MessagePackSerializer<T>> _func =
CreateFunc();
private static Func<SerializationContext, MessagePackSerializer<T>> CreateFunc()
{
var thisParameter = Expression.Parameter( typeof( SerializationContext ), "this" );
return
Expression.Lambda<Func<SerializationContext, MessagePackSerializer<T>>>(
Expression.Call(
thisParameter,
Metadata._SerializationContext.GetSerializer1_Method.MakeGenericMethod( typeof( T ) )
),
thisParameter
).Compile();
}
#endif
public static IMessagePackSingleObjectSerializer Get( SerializationContext context )
{
return _func( context );
}
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Parallel.Tests
{
public partial class ParallelQueryCombinationTests
{
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Aggregate(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize),
operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate((x, y) => x + y));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Aggregate_Seed(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize),
operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (x, y) => x + y));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Aggregate_Result(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize),
operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (x, y) => x + y, r => r));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Aggregate_Accumulator(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize),
operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (a, x) => a + x, (l, r) => l + r, r => r));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Aggregate_SeedFactory(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize),
operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(() => 0, (a, x) => a + x, (l, r) => l + r, r => r));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void All_False(LabeledOperation source, LabeledOperation operation)
{
Assert.False(operation.Item(DefaultStart, DefaultSize, source.Item).All(x => false));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void All_True(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).All(x => seen.Add(x)));
seen.AssertComplete();
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Any_False(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.False(operation.Item(DefaultStart, DefaultSize, source.Item).Any(x => !seen.Add(x)));
seen.AssertComplete();
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Any_True(LabeledOperation source, LabeledOperation operation)
{
Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).Any(x => true));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Average(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize) / (double)DefaultSize,
operation.Item(DefaultStart, DefaultSize, source.Item).Average());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Average_Nullable(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize) / (double?)DefaultSize,
operation.Item(DefaultStart, DefaultSize, source.Item).Average(x => (int?)x));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Cast(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int? i in operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>())
{
Assert.True(i.HasValue);
Assert.Equal(seen++, i.Value);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Cast_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Contains_True(LabeledOperation source, LabeledOperation operation)
{
Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).Contains(DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Contains_False(LabeledOperation source, LabeledOperation operation)
{
Assert.False(operation.Item(DefaultStart, DefaultSize, source.Item).Contains(DefaultStart + DefaultSize));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Count_Elements(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultSize, operation.Item(DefaultStart, DefaultSize, source.Item).Count());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Count_Predicate_Some(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).Count(x => x < DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Count_Predicate_None(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(0, operation.Item(DefaultStart, DefaultSize, source.Item).Count(x => x < DefaultStart));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void DefaultIfEmpty(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty())
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void DefaultIfEmpty_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Distinct(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct();
foreach (int i in query)
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Distinct_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct();
Assert.All(query.ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void ElementAt(LabeledOperation source, LabeledOperation operation)
{
ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, source.Item);
int seen = DefaultStart;
for (int i = 0; i < DefaultSize; i++)
{
Assert.Equal(seen++, query.ElementAt(i));
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void ElementAtOrDefault(LabeledOperation source, LabeledOperation operation)
{
ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, source.Item);
int seen = DefaultStart;
for (int i = 0; i < DefaultSize; i++)
{
Assert.Equal(seen++, query.ElementAtOrDefault(i));
}
Assert.Equal(DefaultStart + DefaultSize, seen);
Assert.Equal(default(int), query.ElementAtOrDefault(-1));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Except(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)
.Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, source.Item));
foreach (int i in query)
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Except_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)
.Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, source.Item));
Assert.All(query.ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void First(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).First());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void First_Predicate(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).First(x => x >= DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void FirstOrDefault(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void FirstOrDefault_Predicate(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(x => x >= DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void FirstOrDefault_Predicate_None(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(default(int), operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(x => false));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void ForAll(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
operation.Item(DefaultStart, DefaultSize, source.Item).ForAll(x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void GetEnumerator(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
IEnumerator<int> enumerator = operation.Item(DefaultStart, DefaultSize, source.Item).GetEnumerator();
while (enumerator.MoveNext())
{
int current = enumerator.Current;
Assert.Equal(seen++, current);
Assert.Equal(current, enumerator.Current);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
Assert.Throws<NotSupportedException>(() => enumerator.Reset());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void GroupBy(LabeledOperation source, LabeledOperation operation)
{
int seenKey = DefaultStart / GroupFactor;
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor))
{
Assert.Equal(seenKey++, group.Key);
int seenElement = group.Key * GroupFactor;
Assert.All(group, x => Assert.Equal(seenElement++, x));
Assert.Equal(Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement);
}
Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void GroupBy_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seenKey = DefaultStart / GroupFactor;
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor).ToList())
{
Assert.Equal(seenKey++, group.Key);
int seenElement = group.Key * GroupFactor;
Assert.All(group, x => Assert.Equal(seenElement++, x));
Assert.Equal(Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement);
}
Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void GroupBy_ElementSelector(LabeledOperation source, LabeledOperation operation)
{
int seenKey = DefaultStart / GroupFactor;
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y))
{
Assert.Equal(seenKey++, group.Key);
int seenElement = -group.Key * GroupFactor;
Assert.All(group, x => Assert.Equal(seenElement--, x));
Assert.Equal(-Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement);
}
Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void GroupBy_ElementSelector_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seenKey = DefaultStart / GroupFactor;
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y).ToList())
{
Assert.Equal(seenKey++, group.Key);
int seenElement = -group.Key * GroupFactor;
Assert.All(group, x => Assert.Equal(seenElement--, x));
Assert.Equal(-Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement);
}
Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Intersect(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item)
.Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item));
foreach (int i in query)
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Intersect_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item)
.Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item));
Assert.All(query.ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Last(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Last());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Last_Predicate(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize / 2 - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Last(x => x < DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void LastOrDefault(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void LastOrDefault_Predicate(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize / 2 - 1, operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault(x => x < DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void LastOrDefault_Predicate_None(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(default(int), operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault(x => false));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void LongCount_Elements(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultSize, operation.Item(DefaultStart, DefaultSize, source.Item).LongCount());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void LongCount_Predicate_Some(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).LongCount(x => x < DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void LongCount_Predicate_None(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(0, operation.Item(DefaultStart, DefaultSize, source.Item).LongCount(x => x < DefaultStart));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Max(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Max());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Max_Nullable(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Max(x => (int?)x));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Min(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).Min());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Min_Nullable(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).Min(x => (int?)x));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void OfType(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>())
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void OfType_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void OfType_Other(LabeledOperation source, LabeledOperation operation)
{
Assert.Empty(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<long>());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void OfType_Other_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
Assert.Empty(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<long>().ToList());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void OrderBy_Initial(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => x))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void OrderBy_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => x).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void OrderBy_OtherDirection(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => -x))
{
Assert.Equal(--seen, i);
}
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void OrderBy_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => -x).ToList(), x => Assert.Equal(--seen, x));
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void OrderByDescending_Initial(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => -x))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void OrderByDescending_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => -x).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void OrderByDescending_OtherDirection(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => x))
{
Assert.Equal(--seen, i);
}
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void OrderByDescending_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => x).ToList(), x => Assert.Equal(--seen, x));
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Reverse(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Reverse())
{
Assert.Equal(--seen, i);
}
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Reverse_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Reverse().ToList())
{
Assert.Equal(--seen, i);
}
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Select(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x))
{
Assert.Equal(seen--, i);
}
Assert.Equal(-DefaultStart - DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Select_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x).ToList(), x => Assert.Equal(seen--, x));
Assert.Equal(-DefaultStart - DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Select_Indexed(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { Assert.Equal(DefaultStart + index, x); return -x; }))
{
Assert.Equal(seen--, i);
}
Assert.Equal(-DefaultStart - DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Select_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { Assert.Equal(DefaultStart + index, x); return -x; }).ToList(), x => Assert.Equal(seen--, x));
Assert.Equal(-DefaultStart - DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SelectMany(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)))
{
Assert.Equal(seen--, i);
}
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SelectMany_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)).ToList(), x => Assert.Equal(seen--, x));
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SelectMany_Indexed(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }))
{
Assert.Equal(seen--, i);
}
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SelectMany_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }).ToList(), x => Assert.Equal(seen--, x));
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SelectMany_ResultSelector(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x))
{
Assert.Equal(seen--, i);
}
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SelectMany_ResultSelector_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => Assert.Equal(seen--, x));
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SelectMany_Indexed_ResultSelector(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x))
{
Assert.Equal(seen--, i);
}
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SelectMany_Indexed_ResultSelector_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => Assert.Equal(seen--, x));
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SequenceEqual(LabeledOperation source, LabeledOperation operation)
{
Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).SequenceEqual(ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered()));
Assert.True(ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered().SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Item)));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SequenceEqual_Self(LabeledOperation source, LabeledOperation operation)
{
Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Item)));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void Single(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart, operation.Item(DefaultStart, 1, source.Item).Single());
Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).Single(x => x == DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void SingleOrDefault(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart, operation.Item(DefaultStart, 1, source.Item).SingleOrDefault());
Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).SingleOrDefault(x => x == DefaultStart + DefaultSize / 2));
if (!operation.ToString().StartsWith("DefaultIfEmpty"))
{
Assert.Equal(default(int), operation.Item(DefaultStart, 0, source.Item).SingleOrDefault());
Assert.Equal(default(int), operation.Item(DefaultStart, 0, source.Item).SingleOrDefault(x => x == DefaultStart + DefaultSize / 2));
}
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Skip(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize / 2;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Skip_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize / 2;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SkipWhile(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize / 2;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile(x => x < DefaultStart + DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SkipWhile_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize / 2;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SkipWhile_Indexed(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize / 2;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile((x, index) => index < DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void SkipWhile_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize / 2;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void Sum(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Sum());
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void Sum_Nullable(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Sum(x => (int?)x));
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Take(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Take_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void TakeWhile(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile(x => x < DefaultStart + DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void TakeWhile_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void TakeWhile_Indexed(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile((x, index) => index < DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void TakeWhile_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void ThenBy_Initial(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => x))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void ThenBy_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => x).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void ThenBy_OtherDirection(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => -x))
{
Assert.Equal(--seen, i);
}
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void ThenBy_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => -x).ToList(), x => Assert.Equal(--seen, x));
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void ThenByDescending_Initial(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => -x))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void ThenByDescending_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => -x).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void ThenByDescending_OtherDirection(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => x))
{
Assert.Equal(--seen, i);
}
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void ThenByDescending_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => x).ToList(), x => Assert.Equal(--seen, x));
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void ToArray(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToArray(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void ToDictionary(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToDictionary(x => x * 2),
p =>
{
seen.Add(p.Key / 2);
Assert.Equal(p.Key, p.Value * 2);
});
seen.AssertComplete();
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void ToDictionary_ElementSelector(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToDictionary(x => x, y => y * 2),
p =>
{
seen.Add(p.Key);
Assert.Equal(p.Key * 2, p.Value);
});
seen.AssertComplete();
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void ToList(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void ToLookup(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seenOuter = new IntegerRangeSet(0, 2);
ILookup<int, int> lookup = operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x % 2);
Assert.All(lookup,
group =>
{
seenOuter.Add(group.Key);
IntegerRangeSet seenInner = new IntegerRangeSet(DefaultStart / 2, (DefaultSize + ((1 + group.Key) % 2)) / 2);
Assert.All(group, y => { Assert.Equal(group.Key, y % 2); seenInner.Add(y / 2); });
seenInner.AssertComplete();
});
seenOuter.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
[MemberData("UnaryUnorderedOperators")]
[MemberData("BinaryUnorderedOperators")]
public static void ToLookup_ElementSelector(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seenOuter = new IntegerRangeSet(0, 2);
ILookup<int, int> lookup = operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x % 2, y => -y);
Assert.All(lookup,
group =>
{
seenOuter.Add(group.Key);
IntegerRangeSet seenInner = new IntegerRangeSet(DefaultStart / 2, (DefaultSize + ((1 + group.Key) % 2)) / 2);
Assert.All(group, y => { Assert.Equal(group.Key, -y % 2); seenInner.Add(-y / 2); });
seenInner.AssertComplete();
});
seenOuter.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Where(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Where_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Where_Indexed(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => index < DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Where_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Zip(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize, source.Item)
.Zip(operation.Item(0, DefaultSize, source.Item), (x, y) => (x + y) / 2);
foreach (int i in query)
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData("UnaryOperators")]
[MemberData("BinaryOperators")]
public static void Zip_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(0, DefaultSize, source.Item)
.Zip(operation.Item(DefaultStart * 2, DefaultSize, source.Item), (x, y) => (x + y) / 2);
Assert.All(query.ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
}
}
| |
//
// Carbon.cs
//
// Author:
// Michael Hutchinson <mhutchinson@novell.com>
// Geoff Norton <gnorton@novell.com>
//
// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
#pragma warning disable 0169
namespace OsxIntegration.Framework
{
internal delegate CarbonEventHandlerStatus EventDelegate (IntPtr callRef, IntPtr eventRef, IntPtr userData);
internal delegate CarbonEventHandlerStatus AEHandlerDelegate (IntPtr inEvnt, IntPtr outEvt, uint refConst);
internal static class Carbon
{
public const string CarbonLib = "/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon";
[DllImport (CarbonLib)]
public static extern IntPtr GetApplicationEventTarget ();
[DllImport (CarbonLib)]
public static extern IntPtr GetControlEventTarget (IntPtr control);
[DllImport (CarbonLib)]
public static extern IntPtr GetWindowEventTarget (IntPtr window);
[DllImport (CarbonLib)]
public static extern IntPtr GetMenuEventTarget (IntPtr menu);
[DllImport (CarbonLib)]
public static extern CarbonEventClass GetEventClass (IntPtr eventref);
[DllImport (CarbonLib)]
public static extern uint GetEventKind (IntPtr eventref);
#region Event handler installation
[DllImport (CarbonLib)]
static extern EventStatus InstallEventHandler (IntPtr target, EventDelegate handler, uint count,
CarbonEventTypeSpec [] types, IntPtr user_data, out IntPtr handlerRef);
[DllImport (CarbonLib)]
public static extern EventStatus RemoveEventHandler (IntPtr handlerRef);
public static IntPtr InstallEventHandler (IntPtr target, EventDelegate handler, CarbonEventTypeSpec [] types)
{
IntPtr handlerRef;
CheckReturn (InstallEventHandler (target, handler, (uint)types.Length, types, IntPtr.Zero, out handlerRef));
return handlerRef;
}
public static IntPtr InstallEventHandler (IntPtr target, EventDelegate handler, CarbonEventTypeSpec type)
{
return InstallEventHandler (target, handler, new CarbonEventTypeSpec[] { type });
}
public static IntPtr InstallApplicationEventHandler (EventDelegate handler, CarbonEventTypeSpec [] types)
{
return InstallEventHandler (GetApplicationEventTarget (), handler, types);
}
public static IntPtr InstallApplicationEventHandler (EventDelegate handler, CarbonEventTypeSpec type)
{
return InstallEventHandler (GetApplicationEventTarget (), handler, new CarbonEventTypeSpec[] { type });
}
#endregion
#region Event parameter extraction
[DllImport (CarbonLib)]
public static extern EventStatus GetEventParameter (IntPtr eventRef, CarbonEventParameterName name, CarbonEventParameterType desiredType,
out CarbonEventParameterType actualType, uint size, ref uint outSize, ref IntPtr outPtr);
public static IntPtr GetEventParameter (IntPtr eventRef, CarbonEventParameterName name, CarbonEventParameterType desiredType)
{
CarbonEventParameterType actualType;
uint outSize = 0;
IntPtr val = IntPtr.Zero;
CheckReturn (GetEventParameter (eventRef, name, desiredType, out actualType, (uint)IntPtr.Size, ref outSize, ref val));
return val;
}
[DllImport (CarbonLib)]
static extern EventStatus GetEventParameter (IntPtr eventRef, CarbonEventParameterName name, CarbonEventParameterType desiredType,
out CarbonEventParameterType actualType, uint size, ref uint outSize, IntPtr dataBuffer);
[DllImport (CarbonLib)]
static extern EventStatus GetEventParameter (IntPtr eventRef, CarbonEventParameterName name, CarbonEventParameterType desiredType,
uint zero, uint size, uint zero2, IntPtr dataBuffer);
public static T GetEventParameter<T> (IntPtr eventRef, CarbonEventParameterName name, CarbonEventParameterType desiredType) where T : struct
{
int len = Marshal.SizeOf (typeof (T));
IntPtr bufferPtr = Marshal.AllocHGlobal (len);
CheckReturn (GetEventParameter (eventRef, name, desiredType, 0, (uint)len, 0, bufferPtr));
T val = (T)Marshal.PtrToStructure (bufferPtr, typeof (T));
Marshal.FreeHGlobal (bufferPtr);
return val;
}
#endregion
#region Sending events
[DllImport (CarbonLib)]
static extern EventStatus SendEventToEventTarget (IntPtr eventRef, IntPtr eventTarget);
[DllImport (CarbonLib)]
static extern EventStatus CreateEvent (IntPtr allocator, CarbonEventClass classID, uint kind, double eventTime,
CarbonEventAttributes flags, out IntPtr eventHandle);
[DllImport (CarbonLib)]
static extern void ReleaseEvent (IntPtr eventHandle);
static EventStatus SendApplicationEvent (CarbonEventClass classID, uint kind, CarbonEventAttributes flags)
{
IntPtr eventHandle;
EventStatus s = CreateEvent (IntPtr.Zero, classID, kind, 0, flags, out eventHandle);
if (s != EventStatus.Ok)
return s;
s = SendEventToEventTarget (eventHandle, GetApplicationEventTarget ());
ReleaseEvent (eventHandle);
return s;
}
[DllImport (CarbonLib)]
public static extern CarbonEventHandlerStatus ProcessHICommand (ref CarbonHICommand command);
#endregion
#region AEList manipulation
[DllImport (CarbonLib)]
static extern int AECountItems (ref AEDesc descList, out int count); //return an OSErr
public static int AECountItems (ref AEDesc descList)
{
int count;
CheckReturn (AECountItems (ref descList, out count));
return count;
}
[DllImport (CarbonLib)]
static extern AEDescStatus AEGetNthPtr (ref AEDesc descList, int index, CarbonEventParameterType desiredType, uint keyword,
out CarbonEventParameterType actualType, IntPtr buffer, int bufferSize, out int actualSize);
[DllImport (CarbonLib)]
static extern AEDescStatus AEGetNthPtr (ref AEDesc descList, int index, CarbonEventParameterType desiredType, uint keyword,
uint zero, IntPtr buffer, int bufferSize, int zero2);
public static T AEGetNthPtr<T> (ref AEDesc descList, int index, CarbonEventParameterType desiredType) where T : struct
{
int len = Marshal.SizeOf (typeof (T));
IntPtr bufferPtr = Marshal.AllocHGlobal (len);
try {
CheckReturn ((int)AEGetNthPtr (ref descList, index, desiredType, 0, 0, bufferPtr, len, 0));
T val = (T)Marshal.PtrToStructure (bufferPtr, typeof (T));
return val;
} finally{
Marshal.FreeHGlobal (bufferPtr);
}
}
[DllImport (CarbonLib)]
static extern AEDescStatus AEGetNthPtr (ref AEDesc descList, int index, CarbonEventParameterType desiredType, uint keyword,
uint zero, out IntPtr outPtr, int bufferSize, int zero2);
public static IntPtr AEGetNthPtr (ref AEDesc descList, int index, CarbonEventParameterType desiredType)
{
IntPtr ret;
CheckReturn ((int)AEGetNthPtr (ref descList, index, desiredType, 0, 0, out ret, 4, 0));
return ret;
}
[DllImport (CarbonLib)]
public static extern int AEDisposeDesc (ref AEDesc desc);
[DllImport (CarbonLib)]
public static extern AEDescStatus AESizeOfNthItem (ref AEDesc descList, int index, ref CarbonEventParameterType type, out int size);
//FIXME: this might not work in some encodings. need to test more.
static string GetStringFromAEPtr (ref AEDesc descList, int index)
{
int size;
CarbonEventParameterType type = CarbonEventParameterType.UnicodeText;
if (AESizeOfNthItem (ref descList, index, ref type, out size) == AEDescStatus.Ok) {
IntPtr buffer = Marshal.AllocHGlobal (size);
try {
if (AEGetNthPtr (ref descList, index, type, 0, 0, buffer, size, 0) == AEDescStatus.Ok)
return Marshal.PtrToStringAuto (buffer, size);
} finally {
Marshal.FreeHGlobal (buffer);
}
}
return null;
}
#endregion
[DllImport (CarbonLib)]
static extern int FSRefMakePath (ref FSRef fsRef, IntPtr buffer, uint bufferSize);
public static string FSRefToPath (ref FSRef fsRef)
{
//FIXME: is this big enough?
const int MAX_LENGTH = 4096;
IntPtr buf = IntPtr.Zero;
string ret;
try {
buf = Marshal.AllocHGlobal (MAX_LENGTH);
CheckReturn (FSRefMakePath (ref fsRef, buf, (uint)MAX_LENGTH));
//FIXME: on Mono, auto is UTF-8, which is correct but I'd prefer to be more explicit
ret = Marshal.PtrToStringAuto (buf, MAX_LENGTH);
} finally {
if (buf != IntPtr.Zero)
Marshal.FreeHGlobal (buf);
}
return ret;
}
#region Error checking
public static void CheckReturn (EventStatus status)
{
int intStatus = (int) status;
if (intStatus < 0)
throw new EventStatusException (status);
}
public static void CheckReturn (int osErr)
{
if (osErr != 0) {
string s = GetMacOSStatusCommentString (osErr);
throw new SystemException ("Unexpected OS error code " + osErr + ": " + s);
}
}
[DllImport (CarbonLib)]
static extern string GetMacOSStatusCommentString (int osErr);
#endregion
#region Char code conversion
internal static int ConvertCharCode (string code)
{
return (code[3]) | (code[2] << 8) | (code[1] << 16) | (code[0] << 24);
}
internal static string UnConvertCharCode (int i)
{
return new string (new char[] {
(char)(i >> 24),
(char)(0xFF & (i >> 16)),
(char)(0xFF & (i >> 8)),
(char)(0xFF & i),
});
}
#endregion
#region Navigation services
[DllImport (CarbonLib)]
static extern NavStatus NavDialogSetFilterTypeIdentifiers (IntPtr getFileDialogRef, IntPtr typeIdentifiersCFArray);
[DllImport (CarbonLib)]
static extern NavEventUPP NewNavEventUPP (NavEventProc userRoutine);
[DllImport (CarbonLib)]
static extern NavObjectFilterUPP NewNavObjectFilterUPP (NavObjectFilterProc userRoutine);
[DllImport (CarbonLib)]
static extern NavPreviewUPP NewNavPreviewUPP (NavPreviewProc userRoutine);
delegate void NavEventProc (NavEventCallbackMessage callBackSelector, ref NavCBRec callBackParms, IntPtr callBackUD);
delegate bool NavObjectFilterProc (ref AEDesc theItem, IntPtr info, IntPtr callBackUD, NavFilterModes filterMode);
delegate bool NavPreviewProc (ref NavCBRec callBackParms, IntPtr callBackUD);
[DllImport (CarbonLib)]
static extern void DisposeNavEventUPP (NavEventUPP userUPP);
[DllImport (CarbonLib)]
static extern void DisposeNavObjectFilterUPP (NavObjectFilterUPP userUPP);
[DllImport (CarbonLib)]
static extern void DisposeNavPreviewUPP (NavPreviewUPP userUPP);
#endregion
#region Internal Mac API for setting process name
[DllImport (CarbonLib)]
static extern int GetCurrentProcess (out ProcessSerialNumber psn);
[DllImport (CarbonLib)]
static extern int CPSSetProcessName (ref ProcessSerialNumber psn, string name);
public static void SetProcessName (string name)
{
try {
ProcessSerialNumber psn;
if (GetCurrentProcess (out psn) == 0)
CPSSetProcessName (ref psn, name);
} catch {} //EntryPointNotFoundException?
}
struct ProcessSerialNumber {
ulong highLongOfPSN;
ulong lowLongOfPSN;
}
#endregion
public static List<string> GetFileListFromEventRef (IntPtr eventRef)
{
AEDesc list = GetEventParameter<AEDesc> (eventRef, CarbonEventParameterName.DirectObject, CarbonEventParameterType.AEList);
long count = AECountItems (ref list);
var files = new List<string> ();
for (int i = 1; i <= count; i++) {
FSRef fsRef = AEGetNthPtr<FSRef> (ref list, i, CarbonEventParameterType.FSRef);
string file = FSRefToPath (ref fsRef);
if (!string.IsNullOrEmpty (file))
files.Add (file);
}
CheckReturn (AEDisposeDesc (ref list));
return files;
}
public static List<string> GetUrlListFromEventRef (IntPtr eventRef)
{
AEDesc list = GetEventParameter<AEDesc> (eventRef, CarbonEventParameterName.DirectObject, CarbonEventParameterType.AEList);
long count = AECountItems (ref list);
var files = new List<string> ();
for (int i = 1; i <= count; i++) {
string url = GetStringFromAEPtr (ref list, i);
if (!string.IsNullOrEmpty (url))
files.Add (url);
}
Carbon.CheckReturn (Carbon.AEDisposeDesc (ref list));
return files;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 2)]
struct AEDesc
{
uint descriptorType;
IntPtr dataHandle;
}
[StructLayout(LayoutKind.Sequential, Pack = 2, Size = 80)]
struct FSRef
{
//this is an 80-char opaque byte array
private byte hidden;
}
internal enum CarbonEventHandlerStatus //this is an OSStatus
{
Handled = 0,
NotHandled = -9874,
}
internal enum CarbonEventParameterName : uint
{
DirectObject = 757935405, // '----'
}
internal enum CarbonEventParameterType : uint
{
HICommand = 1751346532, // 'hcmd'
MenuRef = 1835363957, // 'menu'
WindowRef = 2003398244, // 'wind'
Char = 1413830740, // 'TEXT'
UInt32 = 1835100014, // 'magn'
UnicodeText = 1970567284, // 'utxt'
AEList = 1818850164, // 'list'
WildCard = 707406378, // '****'
FSRef = 1718841958, // 'fsrf'
}
internal enum CarbonEventClass : uint
{
Mouse = 1836021107, // 'mous'
Keyboard = 1801812322, // 'keyb'
TextInput = 1952807028, // 'text'
Application = 1634758764, // 'appl'
RemoteAppleEvent = 1701867619, //'eppc' //remote apple event?
Menu = 1835363957, // 'menu'
Window = 2003398244, // 'wind'
Control = 1668183148, // 'cntl'
Command = 1668113523, // 'cmds'
Tablet = 1952607348, // 'tblt'
Volume = 1987013664, // 'vol '
Appearance = 1634758765, // 'appm'
Service = 1936028278, // 'serv'
Toolbar = 1952604530, // 'tbar'
ToolbarItem = 1952606580, // 'tbit'
Accessibility = 1633903461, // 'acce'
HIObject = 1751740258, // 'hiob'
AppleEvent = 1634039412, // 'aevt'
Internet = 1196773964, // 'GURL'
}
public enum CarbonCommandID : uint
{
OK = 1869291552, // 'ok '
Cancel = 1852797985, // 'not!'
Quit = 1903520116, // 'quit'
Undo = 1970168943, // 'undo'
Redo = 1919247471, // 'redo'
Cut = 1668641824, // 'cut '
Copy = 1668247673, // 'copy'
Paste = 1885434740, // 'past'
Clear = 1668048225, // 'clea',
SelectAll = 1935764588, // 'sall',
Preferences = 1886545254, //'pref'
About = 1633841013, // 'abou'
New = 1852143392, // 'new ',
Open = 1869636974, // 'open'
Close = 1668050803, // 'clos'
Save = 1935767141, // 'save',
SaveAs = 1937138035, // 'svas'
Revert = 1920365172, // 'rvrt'
Print = 1886547572, // 'prnt'
PageSetup = 1885431653, // 'page',
AppHelp = 1634233456, //'ahlp'
//menu manager handles these automatically
Hide = 1751737445, // 'hide'
HideOthers = 1751737455, // 'hido'
ShowAll = 1936220524, // 'shal'
ZoomWindow = 2054123373, // 'zoom'
MinimizeWindow = 1835626089, // 'mini'
MinimizeAll = 1835626081, // 'mina'
MaximizeAll = 1835104353, // 'maxa'
ArrangeInFront = 1718775412, // 'frnt'
BringAllToFront = 1650881140, // 'bfrt'
SelectWindow = 1937205614, // 'swin'
RotateWindowsForward = 1919906935, // 'rotw'
RotateWindowsBackward = 1919906914, // 'rotb'
RotateFloatingWindowsForward = 1920231031, // 'rtfw'
RotateFloatingWindowsBackward = 1920231010, // 'rtfb'
//created automatically -- used for inserting before/after the default window list
WindowListSeparator = 2003592310, // 'wldv'
WindowListTerminator = 2003596148, // 'wlst'
}
internal enum CarbonEventCommand : uint
{
Process = 1,
UpdateStatus = 2,
}
internal enum CarbonEventMenu : uint
{
BeginTracking = 1,
EndTracking = 2,
ChangeTrackingMode = 3,
Opening = 4,
Closed = 5,
TargetItem = 6,
MatchKey = 7,
}
internal enum CarbonEventAttributes : uint
{
None = 0,
UserEvent = (1 << 0),
Monitored= 1 << 3,
}
internal enum CarbonEventApple
{
OpenApplication = 1868656752, // 'oapp'
ReopenApplication = 1918988400, //'rapp'
OpenDocuments = 1868853091, // 'odoc'
PrintDocuments = 188563030, // 'pdoc'
OpenContents = 1868787566, // 'ocon'
QuitApplication = 1903520116, // 'quit'
ShowPreferences = 1886545254, // 'pref'
ApplicationDied = 1868720500, // 'obit'
GetUrl = 1196773964, // 'GURL'
}
[StructLayout(LayoutKind.Sequential, Pack = 2)]
struct CarbonEventTypeSpec
{
public CarbonEventClass EventClass;
public uint EventKind;
public CarbonEventTypeSpec (CarbonEventClass eventClass, UInt32 eventKind)
{
this.EventClass = eventClass;
this.EventKind = eventKind;
}
public CarbonEventTypeSpec (CarbonEventMenu kind) : this (CarbonEventClass.Menu, (uint) kind)
{
}
public CarbonEventTypeSpec (CarbonEventCommand kind) : this (CarbonEventClass.Command, (uint) kind)
{
}
public CarbonEventTypeSpec (CarbonEventApple kind) : this (CarbonEventClass.AppleEvent, (uint) kind)
{
}
public static implicit operator CarbonEventTypeSpec (CarbonEventMenu kind)
{
return new CarbonEventTypeSpec (kind);
}
public static implicit operator CarbonEventTypeSpec (CarbonEventCommand kind)
{
return new CarbonEventTypeSpec (kind);
}
public static implicit operator CarbonEventTypeSpec (CarbonEventApple kind)
{
return new CarbonEventTypeSpec (kind);
}
}
class EventStatusException : SystemException
{
public EventStatusException (EventStatus status)
{
StatusCode = status;
}
public EventStatus StatusCode {
get; private set;
}
}
enum EventStatus // this is an OSStatus
{
Ok = 0,
//event manager
EventAlreadyPostedErr = -9860,
EventTargetBusyErr = -9861,
EventClassInvalidErr = -9862,
EventClassIncorrectErr = -9864,
EventHandlerAlreadyInstalledErr = -9866,
EventInternalErr = -9868,
EventKindIncorrectErr = -9869,
EventParameterNotFoundErr = -9870,
EventNotHandledErr = -9874,
EventLoopTimedOutErr = -9875,
EventLoopQuitErr = -9876,
EventNotInQueueErr = -9877,
EventHotKeyExistsErr = -9878,
EventHotKeyInvalidErr = -9879,
}
enum AEDescStatus
{
Ok = 0,
MemoryFull = -108,
CoercionFail = -1700,
DescRecordNotFound = -1701,
WrongDataType = -1703,
NotAEDesc = -1704,
ReplyNotArrived = -1718,
}
[StructLayout(LayoutKind.Explicit)]
struct CarbonHICommand //technically HICommandExtended, but they're compatible
{
[FieldOffset(0)]
CarbonHICommandAttributes attributes;
[FieldOffset(4)]
uint commandID;
[FieldOffset(8)]
IntPtr controlRef;
[FieldOffset(8)]
IntPtr windowRef;
[FieldOffset(8)]
HIMenuItem menuItem;
public CarbonHICommand (uint commandID, HIMenuItem item)
{
windowRef = controlRef = IntPtr.Zero;
this.commandID = commandID;
this.menuItem = item;
this.attributes = CarbonHICommandAttributes.FromMenu;
}
public CarbonHICommandAttributes Attributes { get { return attributes; } }
public uint CommandID { get { return commandID; } }
public IntPtr ControlRef { get { return controlRef; } }
public IntPtr WindowRef { get { return windowRef; } }
public HIMenuItem MenuItem { get { return menuItem; } }
public bool IsFromMenu {
get { return attributes == CarbonHICommandAttributes.FromMenu; }
}
public bool IsFromControl {
get { return attributes == CarbonHICommandAttributes.FromControl; }
}
public bool IsFromWindow {
get { return attributes == CarbonHICommandAttributes.FromWindow; }
}
}
[StructLayout(LayoutKind.Sequential, Pack = 2)]
struct HIMenuItem
{
IntPtr menuRef;
ushort index;
public HIMenuItem (IntPtr menuRef, ushort index)
{
this.index = index;
this.menuRef = menuRef;
}
public IntPtr MenuRef { get { return menuRef; } }
public ushort Index { get { return index; } }
}
//*NOT* flags
enum CarbonHICommandAttributes : uint
{
FromMenu = 1,
FromControl = 1 << 1,
FromWindow = 1 << 2,
}
[StructLayout(LayoutKind.Sequential, Pack = 2)]
struct FileTranslationSpec
{
uint componentSignature; // OSType
IntPtr translationSystemInfo; // void*
FileTypeSpec src;
FileTypeSpec dst;
}
[StructLayout(LayoutKind.Sequential, Pack = 2)]
struct FileTypeSpec
{/*
uint format; // FileType
long hint;
TranslationAttributes flags;
uint catInfoType; // OSType
uint catInfoCreator; // OSType
*/
}
}
| |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Teknik.Areas.Podcast.Models;
using Teknik.Areas.Podcast.ViewModels;
using Teknik.Areas.Users.Utility;
using Teknik.Attributes;
using Teknik.Configuration;
using Teknik.Controllers;
using Teknik.Data;
using Teknik.Filters;
using Teknik.Models;
using Teknik.Utilities;
using Teknik.Logging;
namespace Teknik.Areas.Podcast.Controllers
{
[Authorize]
[Area("Podcast")]
public class PodcastController : DefaultController
{
public PodcastController(ILogger<Logger> logger, Config config, TeknikEntities dbContext) : base(logger, config, dbContext) { }
[AllowAnonymous]
[TrackPageView]
public IActionResult Index()
{
MainViewModel model = new MainViewModel();
model.Title = _config.PodcastConfig.Title;
model.Description = _config.PodcastConfig.Description;
try
{
ViewBag.Title = _config.PodcastConfig.Title;
ViewBag.Description = _config.PodcastConfig.Description;
bool editor = User.IsInRole("Podcast");
var foundPodcasts = _dbContext.Podcasts.Where(p => (p.Published || editor)).FirstOrDefault();
if (foundPodcasts != null)
{
model.HasPodcasts = (foundPodcasts != null);
}
else
{
model.Error = true;
model.ErrorMessage = "No Podcasts Available";
}
return View("~/Areas/Podcast/Views/Podcast/Main.cshtml", model);
}
catch (Exception ex)
{
model.Error = true;
model.ErrorMessage = ex.Message;
return View("~/Areas/Podcast/Views/Podcast/Main.cshtml", model);
}
}
#region Podcasts
[AllowAnonymous]
[TrackPageView]
public IActionResult View(int episode)
{
PodcastViewModel model = new PodcastViewModel();
// find the podcast specified
bool editor = User.IsInRole("Podcast");
var foundPodcast = _dbContext.Podcasts.Where(p => ((p.Published || editor) && p.Episode == episode)).FirstOrDefault();
if (foundPodcast != null)
{
model = new PodcastViewModel(foundPodcast);
ViewBag.Title = model.Title + " | Teknikast";
return View("~/Areas/Podcast/Views/Podcast/ViewPodcast.cshtml", model);
}
model.Error = true;
model.ErrorMessage = "No Podcasts Available";
return View("~/Areas/Podcast/Views/Podcast/ViewPodcast.cshtml", model);
}
[HttpGet]
[AllowAnonymous]
[ResponseCache(Duration = 31536000, Location = ResponseCacheLocation.Any)]
[TrackDownload]
public IActionResult Download(int episode, string fileName)
{
string path = string.Empty;
string contentType = string.Empty;
long contentLength = 0;
DateTime dateUploaded = new DateTime(1900, 1, 1);
// find the podcast specified
var foundPodcast = _dbContext.Podcasts.Where(p => (p.Published && p.Episode == episode)).FirstOrDefault();
if (foundPodcast != null)
{
PodcastFile file = foundPodcast.Files.Where(f => f.FileName == fileName).FirstOrDefault();
if (file != null)
{
path = file.Path;
contentType = file.ContentType;
contentLength = file.ContentLength;
fileName = file.FileName;
dateUploaded = foundPodcast.DateEdited;
}
else
{
return new StatusCodeResult(StatusCodes.Status404NotFound);
}
}
else
{
return new StatusCodeResult(StatusCodes.Status404NotFound);
}
if (System.IO.File.Exists(path))
{
// Are they downloading it by range?
bool byRange = !string.IsNullOrEmpty(Request.Headers["Range"]); // We do not support ranges
bool isCached = !string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]); // Check to see if they have a cache
if (isCached)
{
// The file is cached, let's just 304 this
Response.StatusCode = 304;
Response.Headers.Add("Content-Length", "0");
return Content(string.Empty);
}
else
{
long startByte = 0;
long endByte = contentLength - 1;
long length = contentLength;
#region Range Calculation
// check to see if we need to pass a specified range
if (byRange)
{
long anotherStart = startByte;
long anotherEnd = endByte;
string[] arr_split = Request.Headers["Range"].ToString().Split(new char[] { '=' });
string range = arr_split[1];
// Make sure the client hasn't sent us a multibyte range
if (range.IndexOf(",") > -1)
{
// (?) Shoud this be issued here, or should the first
// range be used? Or should the header be ignored and
// we output the whole content?
Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
return new StatusCodeResult(StatusCodes.Status416RequestedRangeNotSatisfiable);
}
// If the range starts with an '-' we start from the beginning
// If not, we forward the file pointer
// And make sure to get the end byte if spesified
if (range.StartsWith("-"))
{
// The n-number of the last bytes is requested
anotherStart = startByte - Convert.ToInt64(range.Substring(1));
}
else
{
arr_split = range.Split(new char[] { '-' });
anotherStart = Convert.ToInt64(arr_split[0]);
long temp = 0;
anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : contentLength;
}
/* Check the range and make sure it's treated according to the specs.
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
*/
// End bytes can not be larger than $end.
anotherEnd = (anotherEnd > endByte) ? endByte : anotherEnd;
// Validate the requested range and return an error if it's not correct.
if (anotherStart > anotherEnd || anotherStart > contentLength - 1 || anotherEnd >= contentLength)
{
Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
return new StatusCodeResult(StatusCodes.Status416RequestedRangeNotSatisfiable);
}
startByte = anotherStart;
endByte = anotherEnd;
length = endByte - startByte + 1; // Calculate new content length
// Ranges are response of 206
Response.StatusCode = 206;
}
#endregion
// We accept ranges
Response.Headers.Add("Accept-Ranges", "0-" + contentLength);
// Notify the client the byte range we'll be outputting
Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
// Notify the client the content length we'll be outputting
Response.Headers.Add("Content-Length", length.ToString());
var cd = new System.Net.Mime.ContentDisposition
{
FileName = fileName,
Inline = true
};
Response.Headers.Add("Content-Disposition", cd.ToString());
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
// Reset file stream to starting position (or start of range)
fileStream.Seek(startByte, SeekOrigin.Begin);
return new BufferedFileStreamResult(contentType, (response) => ResponseHelper.StreamToOutput(response, true, fileStream, (int)length, 4 * 1024), false);
}
}
return new StatusCodeResult(StatusCodes.Status404NotFound);
}
[HttpPost]
[AllowAnonymous]
public IActionResult GetPodcasts(int startPodcastID, int count)
{
bool editor = User.IsInRole("Podcast");
var podcasts = _dbContext.Podcasts.Where(p => p.Published || editor).OrderByDescending(p => p.DatePosted).Skip(startPodcastID).Take(count).ToList();
List<PodcastViewModel> podcastViews = new List<PodcastViewModel>();
if (podcasts != null)
{
foreach (Models.Podcast podcast in podcasts)
{
podcastViews.Add(new PodcastViewModel(podcast));
}
}
return PartialView("~/Areas/Podcast/Views/Podcast/Podcasts.cshtml", podcastViews);
}
[HttpPost]
[AllowAnonymous]
public IActionResult GetPodcastEpisode(int podcastId)
{
bool editor = User.IsInRole("Podcast");
var foundPodcast = _dbContext.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
if (foundPodcast != null)
{
return Json(new { result = foundPodcast.Episode });
}
return Json(new { error = "No podcast found" });
}
[HttpPost]
[AllowAnonymous]
public IActionResult GetPodcastTitle(int podcastId)
{
bool editor = User.IsInRole("Podcast");
var foundPodcast = _dbContext.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
if (foundPodcast != null)
{
return Json(new { result = foundPodcast.Title });
}
return Json(new { error = "No podcast found" });
}
[HttpPost]
[AllowAnonymous]
public IActionResult GetPodcastDescription(int podcastId)
{
bool editor = User.IsInRole("Podcast");
var foundPodcast = _dbContext.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
if (foundPodcast != null)
{
return Json(new { result = foundPodcast.Description });
}
return Json(new { error = "No podcast found" });
}
[HttpPost]
[AllowAnonymous]
public IActionResult GetPodcastFiles(int podcastId)
{
bool editor = User.IsInRole("Podcast");
var foundPodcast = _dbContext.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
if (foundPodcast != null)
{
List<object> files = new List<object>();
foreach (PodcastFile file in foundPodcast.Files)
{
object fileObj = new
{
name = file.FileName,
id = file.PodcastFileId
};
files.Add(fileObj);
}
return Json(new { result = new { files = files } });
}
return Json(new { error = "No podcast found" });
}
[HttpPost]
public async Task<IActionResult> CreatePodcast(int episode, string title, string description)
{
if (ModelState.IsValid)
{
if (User.IsInRole("Podcast"))
{
// Grab the next episode number
Models.Podcast lastPod = _dbContext.Podcasts.Where(p => p.Episode == episode).FirstOrDefault();
if (lastPod == null)
{
// Create the podcast object
Models.Podcast podcast = new Models.Podcast();
podcast.Episode = episode;
podcast.Title = title;
podcast.Description = description;
podcast.DatePosted = DateTime.Now;
podcast.DatePublished = DateTime.Now;
podcast.DateEdited = DateTime.Now;
podcast.Files = await SaveFilesAsync(Request.Form.Files, episode);
_dbContext.Podcasts.Add(podcast);
_dbContext.SaveChanges();
return Json(new { result = true });
}
return Json(new { error = "That episode already exists" });
}
return Json(new { error = "You don't have permission to create a podcast" });
}
return Json(new { error = "No podcast created" });
}
[HttpPost]
public async Task<IActionResult> EditPodcast(int podcastId, int episode, string title, string description, string fileIds)
{
if (ModelState.IsValid)
{
if (User.IsInRole("Podcast"))
{
Models.Podcast podcast = _dbContext.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault();
if (podcast != null)
{
if (_dbContext.Podcasts.Where(p => p.Episode != episode).FirstOrDefault() == null || podcast.Episode == episode)
{
podcast.Episode = episode;
podcast.Title = title;
podcast.Description = description;
podcast.DateEdited = DateTime.Now;
// Remove any files not in fileIds
List<string> fileIdList = new List<string>();
if (!string.IsNullOrEmpty(fileIds))
{
fileIdList = fileIds.Split(',').ToList();
}
for (int i = 0; i < podcast.Files.Count; i++)
{
PodcastFile curFile = podcast.Files.ElementAt(i);
if (!fileIdList.Exists(id => id == curFile.PodcastFileId.ToString()))
{
if (System.IO.File.Exists(curFile.Path))
{
System.IO.File.Delete(curFile.Path);
}
_dbContext.PodcastFiles.Remove(curFile);
podcast.Files.Remove(curFile);
}
}
await SaveFilesAsync(Request.Form.Files, episode);
// Add any new files
List<PodcastFile> newFiles = await SaveFilesAsync(Request.Form.Files, episode);
foreach (PodcastFile file in newFiles)
{
podcast.Files.Add(file);
}
// Save podcast
_dbContext.Entry(podcast).State = EntityState.Modified;
_dbContext.SaveChanges();
return Json(new { result = true });
}
return Json(new { error = "That episode already exists" });
}
return Json(new { error = "No podcast found" });
}
return Json(new { error = "You don't have permission to edit this podcast" });
}
return Json(new { error = "Invalid Inputs" });
}
[HttpPost]
public IActionResult PublishPodcast(int podcastId, bool publish)
{
if (ModelState.IsValid)
{
if (User.IsInRole("Podcast"))
{
Models.Podcast podcast = _dbContext.Podcasts.Find(podcastId);
if (podcast != null)
{
podcast.Published = publish;
if (publish)
podcast.DatePublished = DateTime.Now;
_dbContext.Entry(podcast).State = EntityState.Modified;
_dbContext.SaveChanges();
return Json(new { result = true });
}
return Json(new { error = "No podcast found" });
}
return Json(new { error = "You don't have permission to publish this podcast" });
}
return Json(new { error = "Invalid Inputs" });
}
[HttpPost]
public IActionResult DeletePodcast(int podcastId)
{
if (ModelState.IsValid)
{
if (User.IsInRole("Podcast"))
{
Models.Podcast podcast = _dbContext.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault();
if (podcast != null)
{
foreach (PodcastFile file in podcast.Files)
{
System.IO.File.Delete(file.Path);
}
_dbContext.Podcasts.Remove(podcast);
_dbContext.SaveChanges();
return Json(new { result = true });
}
return Json(new { error = "No podcast found" });
}
return Json(new { error = "You don't have permission to delete this podcast" });
}
return Json(new { error = "Invalid Inputs" });
}
#endregion
#region Comments
[HttpPost]
[AllowAnonymous]
public IActionResult GetComments(int podcastId, int startCommentID, int count)
{
var comments = _dbContext.PodcastComments.Where(p => (p.PodcastId == podcastId)).OrderByDescending(p => p.DatePosted).Skip(startCommentID).Take(count).ToList();
List<CommentViewModel> commentViews = new List<CommentViewModel>();
if (comments != null)
{
foreach (PodcastComment comment in comments)
{
commentViews.Add(new CommentViewModel(comment));
}
}
return PartialView("~/Areas/Podcast/Views/Podcast/Comments.cshtml", commentViews);
}
[HttpPost]
[AllowAnonymous]
public IActionResult GetCommentArticle(int commentID)
{
PodcastComment comment = _dbContext.PodcastComments.Where(p => (p.PodcastCommentId == commentID)).FirstOrDefault();
if (comment != null)
{
return Json(new { result = comment.Article });
}
return Json(new { error = "No article found" });
}
[HttpPost]
public IActionResult CreateComment(int podcastId, string article)
{
if (ModelState.IsValid)
{
if (_dbContext.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault() != null)
{
PodcastComment comment = new PodcastComment();
comment.PodcastId = podcastId;
comment.UserId = UserHelper.GetUser(_dbContext, User.Identity.Name).UserId;
comment.Article = article;
comment.DatePosted = DateTime.Now;
comment.DateEdited = DateTime.Now;
_dbContext.PodcastComments.Add(comment);
_dbContext.SaveChanges();
return Json(new { result = true });
}
return Json(new { error = "That podcast does not exist" });
}
return Json(new { error = "Invalid Parameters" });
}
[HttpPost]
public IActionResult EditComment(int commentID, string article)
{
if (ModelState.IsValid)
{
PodcastComment comment = _dbContext.PodcastComments.Where(c => c.PodcastCommentId == commentID).FirstOrDefault();
if (comment != null)
{
if (comment.User.Username == User.Identity.Name || User.IsInRole("Admin"))
{
comment.Article = article;
comment.DateEdited = DateTime.Now;
_dbContext.Entry(comment).State = EntityState.Modified;
_dbContext.SaveChanges();
return Json(new { result = true });
}
return Json(new { error = "You don't have permission to edit this comment" });
}
return Json(new { error = "No comment found" });
}
return Json(new { error = "Invalid Parameters" });
}
[HttpPost]
public IActionResult DeleteComment(int commentID)
{
if (ModelState.IsValid)
{
PodcastComment comment = _dbContext.PodcastComments.Where(c => c.PodcastCommentId == commentID).FirstOrDefault();
if (comment != null)
{
if (comment.User.Username == User.Identity.Name || User.IsInRole("Admin"))
{
_dbContext.PodcastComments.Remove(comment);
_dbContext.SaveChanges();
return Json(new { result = true });
}
return Json(new { error = "You don't have permission to delete this comment" });
}
return Json(new { error = "No comment found" });
}
return Json(new { error = "Invalid Parameters" });
}
#endregion
[DisableRequestSizeLimit]
public async Task<List<PodcastFile>> SaveFilesAsync(IFormFileCollection files, int episode)
{
List<PodcastFile> podFiles = new List<PodcastFile>();
if (files.Count > 0)
{
for (int i = 0; i < files.Count; i++)
{
IFormFile file = files[i];
long fileSize = file.Length;
string fileName = file.FileName;
string fileExt = Path.GetExtension(fileName);
if (!Directory.Exists(_config.PodcastConfig.PodcastDirectory))
{
Directory.CreateDirectory(_config.PodcastConfig.PodcastDirectory);
}
string newName = string.Format("Teknikast_Episode_{0}{1}", episode, fileExt);
int index = 1;
while (System.IO.File.Exists(Path.Combine(_config.PodcastConfig.PodcastDirectory, newName)))
{
newName = string.Format("Teknikast_Episode_{0} ({1}){2}", episode, index, fileExt);
index++;
}
string fullPath = Path.Combine(_config.PodcastConfig.PodcastDirectory, newName);
PodcastFile podFile = new PodcastFile();
podFile.Path = fullPath;
podFile.FileName = newName;
podFile.ContentType = file.ContentType;
podFile.ContentLength = file.Length;
podFiles.Add(podFile);
using (FileStream fs = new FileStream(fullPath, FileMode.Create))
{
await file.CopyToAsync(fs);
}
}
}
return podFiles;
}
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
using System;
using System.Text;
using Generator.Documentation.Rust;
using Generator.IO;
namespace Generator.Encoder.Rust {
sealed class GenCreateNameArgs {
#pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
public string CreatePrefix;
public string Register;
public string Memory;
public string Int32;
public string UInt32;
public string Int64;
public string UInt64;
#pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
public static readonly GenCreateNameArgs RustNames = new GenCreateNameArgs {
CreatePrefix = "with",
Register = "_reg",
Memory = "_mem",
Int32 = "_i32",
UInt32 = "_u32",
Int64 = "_i64",
UInt64 = "_u64",
};
}
sealed class InstrCreateGenImpl {
readonly GenTypes genTypes;
readonly IdentifierConverter idConverter;
readonly RustDocCommentWriter docWriter;
readonly StringBuilder sb;
public InstrCreateGenImpl(GenTypes genTypes, IdentifierConverter idConverter, RustDocCommentWriter docWriter) {
this.genTypes = genTypes;
this.idConverter = idConverter;
this.docWriter = docWriter;
sb = new StringBuilder();
}
public void WriteDocs(FileWriter writer, CreateMethod method, string sectionTitle, Action? writeSection) {
const string typeName = "Instruction";
docWriter.BeginWrite(writer);
foreach (var doc in method.Docs)
docWriter.WriteDocLine(writer, doc, typeName);
docWriter.WriteLine(writer, string.Empty);
if (writeSection is not null) {
docWriter.WriteLine(writer, $"# {sectionTitle}");
docWriter.WriteLine(writer, string.Empty);
writeSection();
docWriter.WriteLine(writer, string.Empty);
}
docWriter.WriteLine(writer, "# Arguments");
docWriter.WriteLine(writer, string.Empty);
for (int i = 0; i < method.Args.Count; i++) {
var arg = method.Args[i];
docWriter.Write($"* `{idConverter.Argument(arg.Name)}`: ");
docWriter.WriteDocLine(writer, arg.Doc, typeName);
}
docWriter.EndWrite(writer);
}
static bool IsSnakeCase(string s) {
foreach (var c in s) {
if (!(char.IsLower(c) || char.IsDigit(c) || c == '_'))
return false;
}
return true;
}
public void WriteMethodDeclArgs(FileWriter writer, CreateMethod method) {
bool comma = false;
foreach (var arg in method.Args) {
if (comma)
writer.Write(", ");
comma = true;
var argName = idConverter.Argument(arg.Name);
if (!IsSnakeCase(argName)) {
writer.Write(RustConstants.AttributeAllowNonSnakeCase);
writer.Write(" ");
}
writer.Write(argName);
writer.Write(": ");
switch (arg.Type) {
case MethodArgType.Code:
writer.Write(genTypes[TypeIds.Code].Name(idConverter));
break;
case MethodArgType.Register:
writer.Write(genTypes[TypeIds.Register].Name(idConverter));
break;
case MethodArgType.RepPrefixKind:
writer.Write(genTypes[TypeIds.RepPrefixKind].Name(idConverter));
break;
case MethodArgType.Memory:
writer.Write("MemoryOperand");
break;
case MethodArgType.UInt8:
writer.Write("u8");
break;
case MethodArgType.UInt16:
writer.Write("u16");
break;
case MethodArgType.Int32:
writer.Write("i32");
break;
case MethodArgType.PreferedInt32:
case MethodArgType.UInt32:
writer.Write("u32");
break;
case MethodArgType.Int64:
writer.Write("i64");
break;
case MethodArgType.UInt64:
writer.Write("u64");
break;
case MethodArgType.ByteSlice:
writer.Write("&[u8]");
break;
case MethodArgType.WordSlice:
writer.Write("&[u16]");
break;
case MethodArgType.DwordSlice:
writer.Write("&[u32]");
break;
case MethodArgType.QwordSlice:
writer.Write("&[u64]");
break;
case MethodArgType.ByteArray:
case MethodArgType.WordArray:
case MethodArgType.DwordArray:
case MethodArgType.QwordArray:
case MethodArgType.BytePtr:
case MethodArgType.WordPtr:
case MethodArgType.DwordPtr:
case MethodArgType.QwordPtr:
case MethodArgType.ArrayIndex:
case MethodArgType.ArrayLength:
default:
throw new InvalidOperationException();
}
}
}
public static bool Is64BitArgument(MethodArgType type) {
switch (type) {
case MethodArgType.Code:
case MethodArgType.Register:
case MethodArgType.RepPrefixKind:
case MethodArgType.Memory:
case MethodArgType.UInt8:
case MethodArgType.UInt16:
case MethodArgType.Int32:
case MethodArgType.UInt32:
case MethodArgType.PreferedInt32:
case MethodArgType.ByteSlice:
case MethodArgType.WordSlice:
case MethodArgType.DwordSlice:
case MethodArgType.QwordSlice:
return false;
case MethodArgType.Int64:
case MethodArgType.UInt64:
return true;
case MethodArgType.ArrayIndex:
case MethodArgType.ArrayLength:
// Never used, but if they're used in the future, they should be converted to u32 types if RustJS
throw new InvalidOperationException();
case MethodArgType.ByteArray:
case MethodArgType.WordArray:
case MethodArgType.DwordArray:
case MethodArgType.QwordArray:
case MethodArgType.BytePtr:
case MethodArgType.WordPtr:
case MethodArgType.DwordPtr:
case MethodArgType.QwordPtr:
default:
throw new ArgumentOutOfRangeException(nameof(type));
}
}
public string GetCreateName(CreateMethod method, GenCreateNameArgs genNames) => GetCreateName(sb, method, genNames);
public static string GetCreateName(StringBuilder sb, CreateMethod method, GenCreateNameArgs genNames) {
if (method.Args.Count == 0 || method.Args[0].Type != MethodArgType.Code)
throw new InvalidOperationException();
sb.Clear();
sb.Append(genNames.CreatePrefix);
var args = method.Args;
for (int i = 1; i < args.Count; i++) {
var arg = args[i];
switch (arg.Type) {
case MethodArgType.Register:
sb.Append(genNames.Register);
break;
case MethodArgType.Memory:
sb.Append(genNames.Memory);
break;
case MethodArgType.Int32:
sb.Append(genNames.Int32);
break;
case MethodArgType.UInt32:
sb.Append(genNames.UInt32);
break;
case MethodArgType.Int64:
sb.Append(genNames.Int64);
break;
case MethodArgType.UInt64:
sb.Append(genNames.UInt64);
break;
case MethodArgType.Code:
case MethodArgType.RepPrefixKind:
case MethodArgType.UInt8:
case MethodArgType.UInt16:
case MethodArgType.PreferedInt32:
case MethodArgType.ArrayIndex:
case MethodArgType.ArrayLength:
case MethodArgType.ByteArray:
case MethodArgType.WordArray:
case MethodArgType.DwordArray:
case MethodArgType.QwordArray:
case MethodArgType.ByteSlice:
case MethodArgType.WordSlice:
case MethodArgType.DwordSlice:
case MethodArgType.QwordSlice:
case MethodArgType.BytePtr:
case MethodArgType.WordPtr:
case MethodArgType.DwordPtr:
case MethodArgType.QwordPtr:
default:
throw new InvalidOperationException();
}
}
return sb.ToString();
}
static bool HasImmediateArg_8_16_32_64(CreateMethod method) {
foreach (var arg in method.Args) {
switch (arg.Type) {
case MethodArgType.UInt8:
case MethodArgType.UInt16:
case MethodArgType.Int32:
case MethodArgType.UInt32:
case MethodArgType.Int64:
case MethodArgType.UInt64:
return true;
}
}
return false;
}
// Assumes it's a generic with_*() method (not a specialized method such as with_movsb() etc)
public static bool HasTryMethod(CreateMethod method) =>
HasImmediateArg_8_16_32_64(method);
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPoco;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Dtos;
using Umbraco.Core.Configuration;
using Umbraco.Core.Scoping;
namespace Umbraco.Core.Sync
{
/// <summary>
/// An <see cref="IServerMessenger"/> that works by storing messages in the database.
/// </summary>
//
// this messenger writes ALL instructions to the database,
// but only processes instructions coming from remote servers,
// thus ensuring that instructions run only once
//
public class DatabaseServerMessenger : ServerMessengerBase, ISyncBootStateAccessor
{
private readonly IRuntimeState _runtime;
private readonly ManualResetEvent _syncIdle;
private readonly object _locko = new object();
private readonly IProfilingLogger _profilingLogger;
private readonly ISqlContext _sqlContext;
private readonly Lazy<string> _distCacheFilePath;
private int _lastId = -1;
private DateTime _lastSync;
private DateTime _lastPruned;
private bool _syncing;
private bool _released;
private readonly Lazy<SyncBootState> _getSyncBootState;
public DatabaseServerMessengerOptions Options { get; }
public DatabaseServerMessenger(
IRuntimeState runtime, IScopeProvider scopeProvider, ISqlContext sqlContext, IProfilingLogger proflog, IGlobalSettings globalSettings,
bool distributedEnabled, DatabaseServerMessengerOptions options)
: base(distributedEnabled)
{
ScopeProvider = scopeProvider ?? throw new ArgumentNullException(nameof(scopeProvider));
_sqlContext = sqlContext;
_runtime = runtime;
_profilingLogger = proflog ?? throw new ArgumentNullException(nameof(proflog));
Logger = proflog;
Options = options ?? throw new ArgumentNullException(nameof(options));
_lastPruned = _lastSync = DateTime.UtcNow;
_syncIdle = new ManualResetEvent(true);
_distCacheFilePath = new Lazy<string>(() => GetDistCacheFilePath(globalSettings));
_getSyncBootState = new Lazy<SyncBootState>(BootInternal);
}
protected ILogger Logger { get; }
protected IScopeProvider ScopeProvider { get; }
protected Sql<ISqlContext> Sql() => _sqlContext.Sql();
private string DistCacheFilePath => _distCacheFilePath.Value;
#region Messenger
protected override bool RequiresDistributed(ICacheRefresher refresher, MessageType dispatchType)
{
// we don't care if there's servers listed or not,
// if distributed call is enabled we will make the call
return _getSyncBootState.IsValueCreated && DistributedEnabled;
}
protected override void DeliverRemote(
ICacheRefresher refresher,
MessageType messageType,
IEnumerable<object> ids = null,
string json = null)
{
var idsA = ids?.ToArray();
if (GetArrayType(idsA, out var idType) == false)
throw new ArgumentException("All items must be of the same type, either int or Guid.", nameof(ids));
var instructions = RefreshInstruction.GetInstructions(refresher, messageType, idsA, idType, json);
var dto = new CacheInstructionDto
{
UtcStamp = DateTime.UtcNow,
Instructions = JsonConvert.SerializeObject(instructions, Formatting.None),
OriginIdentity = LocalIdentity,
InstructionCount = instructions.Sum(x => x.JsonIdCount)
};
using (var scope = ScopeProvider.CreateScope())
{
scope.Database.Insert(dto);
scope.Complete();
}
}
#endregion
#region Sync
[Obsolete("This is no longer used and will be removed in future versions")]
protected void Boot()
{
// if called, just forces the boot logic
_ = GetSyncBootState();
}
private SyncBootState BootInternal()
{
// weight:10, must release *before* the published snapshot service, because once released
// the service will *not* be able to properly handle our notifications anymore
const int weight = 10;
if (!(_runtime is RuntimeState runtime))
throw new NotSupportedException($"Unsupported IRuntimeState implementation {_runtime.GetType().FullName}, expecting {typeof(RuntimeState).FullName}.");
var registered = runtime.MainDom.Register(
() =>
{
lock (_locko)
{
_released = true; // no more syncs
}
// wait a max of 5 seconds and then return, so that we don't block
// the entire MainDom callbacks chain and prevent the AppDomain from
// properly releasing MainDom - a timeout here means that one refresher
// is taking too much time processing, however when it's done we will
// not update lastId and stop everything
var idle = _syncIdle.WaitOne(5000);
if (idle == false)
{
Logger.Warn<DatabaseServerMessenger>("The wait lock timed out, application is shutting down. The current instruction batch will be re-processed.");
}
},
weight);
SyncBootState bootState = SyncBootState.Unknown;
if (registered == false)
{
return bootState;
}
ReadLastSynced(); // get _lastId
using (var scope = ScopeProvider.CreateScope())
{
EnsureInstructions(scope.Database); // reset _lastId if instructions are missing
bootState = Initialize(scope.Database); // boot
scope.Complete();
}
return bootState;
}
/// <summary>
/// Initializes a server that has never synchronized before.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// Callers MUST ensure thread-safety.
/// </remarks>
private SyncBootState Initialize(IUmbracoDatabase database)
{
// could occur if shutting down immediately once starting up and before we've initialized
if (_released) return SyncBootState.Unknown;
var coldboot = false;
if (_lastId < 0) // never synced before
{
// we haven't synced - in this case we aren't going to sync the whole thing, we will assume this is a new
// server and it will need to rebuild it's own caches, eg Lucene or the xml cache file.
Logger.Warn<DatabaseServerMessenger>("No last synced Id found, this generally means this is a new server/install."
+ " The server will build its caches and indexes, and then adjust its last synced Id to the latest found in"
+ " the database and maintain cache updates based on that Id.");
coldboot = true;
}
else
{
//check for how many instructions there are to process, each row contains a count of the number of instructions contained in each
//row so we will sum these numbers to get the actual count.
var count = database.ExecuteScalar<int>("SELECT SUM(instructionCount) FROM umbracoCacheInstruction WHERE id > @lastId", new { lastId = _lastId });
if (count > Options.MaxProcessingInstructionCount)
{
//too many instructions, proceed to cold boot
Logger.Warn<DatabaseServerMessenger, int, int>(
"The instruction count ({InstructionCount}) exceeds the specified MaxProcessingInstructionCount ({MaxProcessingInstructionCount})."
+ " The server will skip existing instructions, rebuild its caches and indexes entirely, adjust its last synced Id"
+ " to the latest found in the database and maintain cache updates based on that Id.",
count, Options.MaxProcessingInstructionCount);
coldboot = true;
}
}
if (coldboot)
{
// go get the last id in the db and store it
// note: do it BEFORE initializing otherwise some instructions might get lost
// when doing it before, some instructions might run twice - not an issue
var maxId = database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction");
//if there is a max currently, or if we've never synced
if (maxId > 0 || _lastId < 0)
SaveLastSynced(maxId);
// execute initializing callbacks
if (Options.InitializingCallbacks != null)
{
foreach (var callback in Options.InitializingCallbacks)
{
callback();
}
}
}
return coldboot ? SyncBootState.ColdBoot : SyncBootState.WarmBoot;
}
/// <summary>
/// Synchronize the server (throttled).
/// </summary>
protected internal void Sync()
{
lock (_locko)
{
if (_syncing)
return;
//Don't continue if we are released
if (_released)
return;
if ((DateTime.UtcNow - _lastSync).TotalSeconds <= Options.ThrottleSeconds)
return;
//Set our flag and the lock to be in it's original state (i.e. it can be awaited)
_syncing = true;
_syncIdle.Reset();
_lastSync = DateTime.UtcNow;
}
try
{
using (_profilingLogger.DebugDuration<DatabaseServerMessenger>("Syncing from database..."))
using (var scope = ScopeProvider.CreateScope())
{
ProcessDatabaseInstructions(scope.Database);
//Check for pruning throttling
if (_released || (DateTime.UtcNow - _lastPruned).TotalSeconds <= Options.PruneThrottleSeconds)
{
scope.Complete();
return;
}
_lastPruned = _lastSync;
switch (Current.RuntimeState.ServerRole)
{
case ServerRole.Single:
case ServerRole.Master:
PruneOldInstructions(scope.Database);
break;
}
scope.Complete();
}
}
finally
{
lock (_locko)
{
//We must reset our flag and signal any waiting locks
_syncing = false;
}
_syncIdle.Set();
}
}
/// <summary>
/// Process instructions from the database.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
/// <returns>
/// Returns the number of processed instructions
/// </returns>
private void ProcessDatabaseInstructions(IUmbracoDatabase database)
{
// NOTE
// we 'could' recurse to ensure that no remaining instructions are pending in the table before proceeding but I don't think that
// would be a good idea since instructions could keep getting added and then all other threads will probably get stuck from serving requests
// (depending on what the cache refreshers are doing). I think it's best we do the one time check, process them and continue, if there are
// pending requests after being processed, they'll just be processed on the next poll.
//
// TODO: not true if we're running on a background thread, assuming we can?
var sql = Sql().SelectAll()
.From<CacheInstructionDto>()
.Where<CacheInstructionDto>(dto => dto.Id > _lastId)
.OrderBy<CacheInstructionDto>(dto => dto.Id);
//only retrieve the top 100 (just in case there's tons)
// even though MaxProcessingInstructionCount is by default 1000 we still don't want to process that many
// rows in one request thread since each row can contain a ton of instructions (until 7.5.5 in which case
// a row can only contain MaxProcessingInstructionCount)
var topSql = sql.SelectTop(100);
// only process instructions coming from a remote server, and ignore instructions coming from
// the local server as they've already been processed. We should NOT assume that the sequence of
// instructions in the database makes any sense whatsoever, because it's all async.
var localIdentity = LocalIdentity;
var lastId = 0;
//tracks which ones have already been processed to avoid duplicates
var processed = new HashSet<RefreshInstruction>();
//It would have been nice to do this in a Query instead of Fetch using a data reader to save
// some memory however we cannot do that because inside of this loop the cache refreshers are also
// performing some lookups which cannot be done with an active reader open
foreach (var dto in database.Fetch<CacheInstructionDto>(topSql))
{
//If this flag gets set it means we're shutting down! In this case, we need to exit asap and cannot
// continue processing anything otherwise we'll hold up the app domain shutdown
if (_released)
{
break;
}
if (dto.OriginIdentity == localIdentity)
{
// just skip that local one but update lastId nevertheless
lastId = dto.Id;
continue;
}
// deserialize remote instructions & skip if it fails
JArray jsonA;
try
{
jsonA = JsonConvert.DeserializeObject<JArray>(dto.Instructions);
}
catch (JsonException ex)
{
Logger.Error<DatabaseServerMessenger, int, string>(ex, "Failed to deserialize instructions ({DtoId}: '{DtoInstructions}').",
dto.Id,
dto.Instructions);
lastId = dto.Id; // skip
continue;
}
var instructionBatch = GetAllInstructions(jsonA);
//process as per-normal
var success = ProcessDatabaseInstructions(instructionBatch, dto, processed, ref lastId);
//if they couldn't be all processed (i.e. we're shutting down) then exit
if (success == false)
{
Logger.Info<DatabaseServerMessenger>("The current batch of instructions was not processed, app is shutting down");
break;
}
}
if (lastId > 0)
SaveLastSynced(lastId);
}
/// <summary>
/// Processes the instruction batch and checks for errors
/// </summary>
/// <param name="instructionBatch"></param>
/// <param name="dto"></param>
/// <param name="processed">
/// Tracks which instructions have already been processed to avoid duplicates
/// </param>
/// <param name="lastId"></param>
/// <returns>
/// returns true if all instructions in the batch were processed, otherwise false if they could not be due to the app being shut down
/// </returns>
private bool ProcessDatabaseInstructions(IReadOnlyCollection<RefreshInstruction> instructionBatch, CacheInstructionDto dto, HashSet<RefreshInstruction> processed, ref int lastId)
{
// execute remote instructions & update lastId
try
{
var result = NotifyRefreshers(instructionBatch, processed);
if (result)
{
//if all instructions we're processed, set the last id
lastId = dto.Id;
}
return result;
}
//catch (ThreadAbortException ex)
//{
// //This will occur if the instructions processing is taking too long since this is occurring on a request thread.
// // Or possibly if IIS terminates the appdomain. In any case, we should deal with this differently perhaps...
//}
catch (Exception ex)
{
Logger.Error<DatabaseServerMessenger, int, string>(
ex,
"DISTRIBUTED CACHE IS NOT UPDATED. Failed to execute instructions ({DtoId}: '{DtoInstructions}'). Instruction is being skipped/ignored",
dto.Id,
dto.Instructions);
//we cannot throw here because this invalid instruction will just keep getting processed over and over and errors
// will be thrown over and over. The only thing we can do is ignore and move on.
lastId = dto.Id;
return false;
}
////if this is returned it will not be saved
//return -1;
}
/// <summary>
/// Remove old instructions from the database
/// </summary>
/// <remarks>
/// Always leave the last (most recent) record in the db table, this is so that not all instructions are removed which would cause
/// the site to cold boot if there's been no instruction activity for more than DaysToRetainInstructions.
/// See: http://issues.umbraco.org/issue/U4-7643#comment=67-25085
/// </remarks>
private void PruneOldInstructions(IUmbracoDatabase database)
{
var pruneDate = DateTime.UtcNow.AddDays(-Options.DaysToRetainInstructions);
// using 2 queries is faster than convoluted joins
var maxId = database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction;");
var delete = new Sql().Append(@"DELETE FROM umbracoCacheInstruction WHERE utcStamp < @pruneDate AND id < @maxId",
new { pruneDate, maxId });
database.Execute(delete);
}
/// <summary>
/// Ensure that the last instruction that was processed is still in the database.
/// </summary>
/// <remarks>
/// If the last instruction is not in the database anymore, then the messenger
/// should not try to process any instructions, because some instructions might be lost,
/// and it should instead cold-boot.
/// However, if the last synced instruction id is '0' and there are '0' records, then this indicates
/// that it's a fresh site and no user actions have taken place, in this circumstance we do not want to cold
/// boot. See: http://issues.umbraco.org/issue/U4-8627
/// </remarks>
private void EnsureInstructions(IUmbracoDatabase database)
{
if (_lastId == 0)
{
var sql = Sql().Select("COUNT(*)")
.From<CacheInstructionDto>();
var count = database.ExecuteScalar<int>(sql);
//if there are instructions but we haven't synced, then a cold boot is necessary
if (count > 0)
_lastId = -1;
}
else
{
var sql = Sql().SelectAll()
.From<CacheInstructionDto>()
.Where<CacheInstructionDto>(dto => dto.Id == _lastId);
var dtos = database.Fetch<CacheInstructionDto>(sql);
//if the last synced instruction is not found in the db, then a cold boot is necessary
if (dtos.Count == 0)
_lastId = -1;
}
}
/// <summary>
/// Reads the last-synced id from file into memory.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
private void ReadLastSynced()
{
if (File.Exists(DistCacheFilePath) == false) return;
var content = File.ReadAllText(DistCacheFilePath);
if (int.TryParse(content, out var last))
_lastId = last;
}
/// <summary>
/// Updates the in-memory last-synced id and persists it to file.
/// </summary>
/// <param name="id">The id.</param>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
private void SaveLastSynced(int id)
{
File.WriteAllText(DistCacheFilePath, id.ToString(CultureInfo.InvariantCulture));
_lastId = id;
}
/// <summary>
/// Gets the unique local identity of the executing AppDomain.
/// </summary>
/// <remarks>
/// <para>It is not only about the "server" (machine name and appDomainappId), but also about
/// an AppDomain, within a Process, on that server - because two AppDomains running at the same
/// time on the same server (eg during a restart) are, practically, a LB setup.</para>
/// <para>Practically, all we really need is the guid, the other infos are here for information
/// and debugging purposes.</para>
/// </remarks>
protected static readonly string LocalIdentity = NetworkHelper.MachineName // eg DOMAIN\SERVER
+ "/" + HttpRuntime.AppDomainAppId // eg /LM/S3SVC/11/ROOT
+ " [P" + Process.GetCurrentProcess().Id // eg 1234
+ "/D" + AppDomain.CurrentDomain.Id // eg 22
+ "] " + Guid.NewGuid().ToString("N").ToUpper(); // make it truly unique
private string GetDistCacheFilePath(IGlobalSettings globalSettings)
{
var fileName = HttpRuntime.AppDomainAppId.ReplaceNonAlphanumericChars(string.Empty) + "-lastsynced.txt";
var distCacheFilePath = Path.Combine(globalSettings.LocalTempPath, "DistCache", fileName);
//ensure the folder exists
var folder = Path.GetDirectoryName(distCacheFilePath);
if (folder == null)
throw new InvalidOperationException("The folder could not be determined for the file " + distCacheFilePath);
if (Directory.Exists(folder) == false)
Directory.CreateDirectory(folder);
return distCacheFilePath;
}
#endregion
public virtual SyncBootState GetSyncBootState() => _getSyncBootState.Value;
#region Notify refreshers
private static ICacheRefresher GetRefresher(Guid id)
{
var refresher = Current.CacheRefreshers[id];
if (refresher == null)
throw new InvalidOperationException("Cache refresher with ID \"" + id + "\" does not exist.");
return refresher;
}
private static IJsonCacheRefresher GetJsonRefresher(Guid id)
{
return GetJsonRefresher(GetRefresher(id));
}
private static IJsonCacheRefresher GetJsonRefresher(ICacheRefresher refresher)
{
var jsonRefresher = refresher as IJsonCacheRefresher;
if (jsonRefresher == null)
throw new InvalidOperationException("Cache refresher with ID \"" + refresher.RefresherUniqueId + "\" does not implement " + typeof(IJsonCacheRefresher) + ".");
return jsonRefresher;
}
/// <summary>
/// Parses out the individual instructions to be processed
/// </summary>
/// <param name="jsonArray"></param>
/// <returns></returns>
private static List<RefreshInstruction> GetAllInstructions(IEnumerable<JToken> jsonArray)
{
var result = new List<RefreshInstruction>();
foreach (var jsonItem in jsonArray)
{
// could be a JObject in which case we can convert to a RefreshInstruction,
// otherwise it could be another JArray - in which case we'll iterate that.
var jsonObj = jsonItem as JObject;
if (jsonObj != null)
{
var instruction = jsonObj.ToObject<RefreshInstruction>();
result.Add(instruction);
}
else
{
var jsonInnerArray = (JArray)jsonItem;
result.AddRange(GetAllInstructions(jsonInnerArray)); // recurse
}
}
return result;
}
/// <summary>
/// executes the instructions against the cache refresher instances
/// </summary>
/// <param name="instructions"></param>
/// <param name="processed"></param>
/// <returns>
/// Returns true if all instructions were processed, otherwise false if the processing was interrupted (i.e. app shutdown)
/// </returns>
private bool NotifyRefreshers(IEnumerable<RefreshInstruction> instructions, HashSet<RefreshInstruction> processed)
{
foreach (var instruction in instructions)
{
//Check if the app is shutting down, we need to exit if this happens.
if (_released)
{
return false;
}
//this has already been processed
if (processed.Contains(instruction))
continue;
switch (instruction.RefreshType)
{
case RefreshMethodType.RefreshAll:
RefreshAll(instruction.RefresherId);
break;
case RefreshMethodType.RefreshByGuid:
RefreshByGuid(instruction.RefresherId, instruction.GuidId);
break;
case RefreshMethodType.RefreshById:
RefreshById(instruction.RefresherId, instruction.IntId);
break;
case RefreshMethodType.RefreshByIds:
RefreshByIds(instruction.RefresherId, instruction.JsonIds);
break;
case RefreshMethodType.RefreshByJson:
RefreshByJson(instruction.RefresherId, instruction.JsonPayload);
break;
case RefreshMethodType.RemoveById:
RemoveById(instruction.RefresherId, instruction.IntId);
break;
}
processed.Add(instruction);
}
return true;
}
private static void RefreshAll(Guid uniqueIdentifier)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.RefreshAll();
}
private static void RefreshByGuid(Guid uniqueIdentifier, Guid id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Refresh(id);
}
private static void RefreshById(Guid uniqueIdentifier, int id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Refresh(id);
}
private static void RefreshByIds(Guid uniqueIdentifier, string jsonIds)
{
var refresher = GetRefresher(uniqueIdentifier);
foreach (var id in JsonConvert.DeserializeObject<int[]>(jsonIds))
refresher.Refresh(id);
}
private static void RefreshByJson(Guid uniqueIdentifier, string jsonPayload)
{
var refresher = GetJsonRefresher(uniqueIdentifier);
refresher.Refresh(jsonPayload);
}
private static void RemoveById(Guid uniqueIdentifier, int id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Remove(id);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using DotVVM.Framework.Compilation;
using DotVVM.Framework.Compilation.Binding;
using DotVVM.Framework.Compilation.ControlTree;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
using DotVVM.Framework.Compilation.Parser;
using DotVVM.Framework.Compilation.Styles;
using DotVVM.Framework.Compilation.Validation;
using Newtonsoft.Json;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.Routing;
using DotVVM.Framework.ResourceManagement;
using DotVVM.Framework.Runtime;
using DotVVM.Framework.Runtime.Filters;
using DotVVM.Framework.Security;
using DotVVM.Framework.ResourceManagement.ClientGlobalize;
using DotVVM.Framework.ViewModel;
using DotVVM.Framework.ViewModel.Serialization;
using DotVVM.Framework.ViewModel.Validation;
using System.Globalization;
using System.Reflection;
using DotVVM.Framework.Hosting.Middlewares;
using DotVVM.Framework.Utils;
using Microsoft.Extensions.DependencyInjection;
namespace DotVVM.Framework.Configuration
{
public class DotvvmConfiguration
{
public const string DotvvmControlTagPrefix = "dot";
/// <summary>
/// Gets or sets the application physical path.
/// </summary>
[JsonIgnore]
public string ApplicationPhysicalPath { get; set; }
/// <summary>
/// Gets the settings of the markup.
/// </summary>
[JsonProperty("markup", DefaultValueHandling = DefaultValueHandling.Ignore)]
public DotvvmMarkupConfiguration Markup { get; private set; }
/// <summary>
/// Gets the route table.
/// </summary>
[JsonProperty("routes")]
[JsonConverter(typeof(RouteTableJsonConverter))]
public DotvvmRouteTable RouteTable { get; private set; }
/// <summary>
/// Gets the configuration of resources.
/// </summary>
[JsonProperty("resources", DefaultValueHandling = DefaultValueHandling.Ignore)]
[JsonConverter(typeof(ResourceRepositoryJsonConverter))]
public DotvvmResourceRepository Resources { get; private set; }
/// <summary>
/// Gets the security configuration.
/// </summary>
[JsonProperty("security")]
public DotvvmSecurityConfiguration Security { get; private set; }
/// <summary>
/// Gets the runtime configuration.
/// </summary>
[JsonProperty("runtime", DefaultValueHandling = DefaultValueHandling.Ignore)]
public DotvvmRuntimeConfiguration Runtime { get; private set; }
/// <summary>
/// Gets or sets the default culture.
/// </summary>
[JsonProperty("defaultCulture", DefaultValueHandling = DefaultValueHandling.Ignore)]
public string DefaultCulture { get; set; }
/// <summary>
/// Gets or sets whether the client side validation rules should be enabled.
/// </summary>
[JsonProperty("clientSideValidation", DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool ClientSideValidation { get; set; } = true;
/// <summary>
/// Gets or sets whether the application should run in debug mode.
/// </summary>
[JsonProperty("debug", DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool Debug { get; set; }
[JsonIgnore]
public Dictionary<string, IRouteParameterConstraint> RouteConstraints { get; } = new Dictionary<string, IRouteParameterConstraint>();
/// <summary>
/// Whether DotVVM compiler should generate runtime debug info for bindings. It can be useful, but may also cause unexpected problems.
/// </summary>
public bool AllowBindingDebugging { get; set; }
/// <summary>
/// Gets an instance of the service locator component.
/// </summary>
[JsonIgnore]
public ServiceLocator ServiceLocator { get; private set; }
[JsonIgnore]
public StyleRepository Styles { get; set; }
[JsonProperty("compiledViewsAssemblies")]
public List<string> CompiledViewsAssemblies { get; set; } = new List<string>() { "CompiledViews.dll" };
/// <summary>
/// Initializes a new instance of the <see cref="DotvvmConfiguration"/> class.
/// </summary>
internal DotvvmConfiguration()
{
DefaultCulture = CultureInfo.CurrentCulture.Name;
Markup = new DotvvmMarkupConfiguration();
RouteTable = new DotvvmRouteTable(this);
Resources = new DotvvmResourceRepository();
Security = new DotvvmSecurityConfiguration();
Runtime = new DotvvmRuntimeConfiguration();
Styles = new StyleRepository();
}
/// <summary>
/// Creates the default configuration and optionally registers additional application services.
/// </summary>
/// <param name="registerServices">An action to register additional services.</param>
public static DotvvmConfiguration CreateDefault(Action<IServiceCollection> registerServices = null)
{
var services = new ServiceCollection();
var config = CreateDefault(new ServiceLocator(services));
DotvvmServiceCollectionExtensions.RegisterDotVVMServices(services, config);
registerServices?.Invoke(services);
return config;
}
/// <summary>
/// Creates the default configuration using the given service provider.
/// </summary>
/// <param name="serviceProvider">The service provider to resolve services from.</param>
public static DotvvmConfiguration CreateDefault(IServiceProvider serviceProvider)
=> CreateDefault(new ServiceLocator(serviceProvider));
private static DotvvmConfiguration CreateDefault(ServiceLocator serviceLocator)
{
var config = new DotvvmConfiguration {
ServiceLocator = serviceLocator
};
config.Runtime.GlobalFilters.Add(new ModelValidationFilterAttribute());
config.Markup.Controls.AddRange(new[]
{
new DotvvmControlConfiguration() { TagPrefix = "dot", Namespace = "DotVVM.Framework.Controls", Assembly = "DotVVM.Framework" }
});
RegisterConstraints(config);
RegisterResources(config);
return config;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
static void RegisterConstraints(DotvvmConfiguration configuration)
{
configuration.RouteConstraints.Add("alpha", GenericRouteParameterType.Create("[a-zA-Z]*?"));
configuration.RouteConstraints.Add("bool", GenericRouteParameterType.Create<bool>("true|false", bool.TryParse));
configuration.RouteConstraints.Add("decimal", GenericRouteParameterType.Create<decimal>("-?[0-9.e]*?", Invariant.TryParse));
configuration.RouteConstraints.Add("double", GenericRouteParameterType.Create<double>("-?[0-9.e]*?", Invariant.TryParse));
configuration.RouteConstraints.Add("float", GenericRouteParameterType.Create<float>("-?[0-9.e]*?", Invariant.TryParse));
configuration.RouteConstraints.Add("guid", GenericRouteParameterType.Create<Guid>("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", Guid.TryParse));
configuration.RouteConstraints.Add("int", GenericRouteParameterType.Create<int>("-?[0-9]*?", Invariant.TryParse));
configuration.RouteConstraints.Add("posint", GenericRouteParameterType.Create<int>("[0-9]*?", Invariant.TryParse));
configuration.RouteConstraints.Add("length", new GenericRouteParameterType(p => "[^/]{" + p + "}"));
configuration.RouteConstraints.Add("long", GenericRouteParameterType.Create<long>("-?[0-9]*?", Invariant.TryParse));
configuration.RouteConstraints.Add("max", new GenericRouteParameterType(p => "-?[0-9.e]*?", (valueString, parameter) =>
{
double value;
if (!Invariant.TryParse(valueString, out value)) return ParameterParseResult.Failed;
if (double.Parse(parameter, CultureInfo.InvariantCulture) < value) return ParameterParseResult.Failed;
return ParameterParseResult.Create(value);
}));
configuration.RouteConstraints.Add("min", new GenericRouteParameterType(p => "-?[0-9.e]*?", (valueString, parameter) =>
{
double value;
if (!Invariant.TryParse(valueString, out value)) return ParameterParseResult.Failed;
if (double.Parse(parameter, CultureInfo.InvariantCulture) > value) return ParameterParseResult.Failed;
return ParameterParseResult.Create(value);
}));
configuration.RouteConstraints.Add("range", new GenericRouteParameterType(p => "-?[0-9.e]*?", (valueString, parameter) =>
{
double value;
if (!Invariant.TryParse(valueString, out value)) return ParameterParseResult.Failed;
var split = parameter.Split(',');
if (double.Parse(split[0], CultureInfo.InvariantCulture) > value || double.Parse(split[1], CultureInfo.InvariantCulture) < value) return ParameterParseResult.Failed;
return ParameterParseResult.Create(value);
}));
configuration.RouteConstraints.Add("maxLength", new GenericRouteParameterType(p => "[^/]{0," + p + "}"));
configuration.RouteConstraints.Add("minLength", new GenericRouteParameterType(p => "[^/]{" + p + ",}"));
configuration.RouteConstraints.Add("regex", new GenericRouteParameterType(p => p));
}
private static void RegisterResources(DotvvmConfiguration configuration)
{
configuration.Resources.Register(ResourceConstants.JQueryResourceName,
new ScriptResource(new RemoteResourceLocation("https://code.jquery.com/jquery-2.1.1.min.js"))
{
LocationFallback = new ResourceLocationFallback(
"window.jQuery",
new EmbeddedResourceLocation(typeof(DotvvmConfiguration).GetTypeInfo().Assembly, "DotVVM.Framework.Resources.Scripts.jquery-2.1.1.min.js"))
});
configuration.Resources.Register(ResourceConstants.KnockoutJSResourceName,
new ScriptResource(new EmbeddedResourceLocation(
typeof(DotvvmConfiguration).GetTypeInfo().Assembly,
"DotVVM.Framework.Resources.Scripts.knockout-latest.js")));
configuration.Resources.Register(ResourceConstants.DotvvmResourceName + ".internal",
new ScriptResource(new EmbeddedResourceLocation(
typeof(DotvvmConfiguration).GetTypeInfo().Assembly,
"DotVVM.Framework.Resources.Scripts.DotVVM.js"))
{
Dependencies = new[] { ResourceConstants.KnockoutJSResourceName }
});
configuration.Resources.Register(ResourceConstants.DotvvmResourceName,
new InlineScriptResource()
{
Code = @"if (window.dotvvm) { throw 'DotVVM is already loaded!'; } window.dotvvm = new DotVVM();",
Dependencies = new[] { ResourceConstants.DotvvmResourceName + ".internal" }
});
configuration.Resources.Register(ResourceConstants.DotvvmDebugResourceName,
new ScriptResource(new EmbeddedResourceLocation(
typeof(DotvvmConfiguration).GetTypeInfo().Assembly,
"DotVVM.Framework.Resources.Scripts.DotVVM.Debug.js"))
{
Dependencies = new[] { ResourceConstants.DotvvmResourceName, ResourceConstants.JQueryResourceName }
});
configuration.Resources.Register(ResourceConstants.DotvvmFileUploadCssResourceName,
new StylesheetResource(new EmbeddedResourceLocation(
typeof (DotvvmConfiguration).GetTypeInfo().Assembly,
"DotVVM.Framework.Resources.Scripts.DotVVM.FileUpload.css")));
RegisterGlobalizeResources(configuration);
}
private static void RegisterGlobalizeResources(DotvvmConfiguration configuration)
{
configuration.Resources.Register(ResourceConstants.GlobalizeResourceName,
new ScriptResource(new EmbeddedResourceLocation(
typeof(DotvvmConfiguration).GetTypeInfo().Assembly,
"DotVVM.Framework.Resources.Scripts.Globalize.globalize.js")));
configuration.Resources.RegisterNamedParent("globalize", new JQueryGlobalizeResourceRepository());
}
}
}
| |
//
// JsonSerializer.cs
//
// Author:
// Marek Habersack <mhabersack@novell.com>
//
// (C) 2008 Novell, Inc. http://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.
//
namespace Nancy.Json
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
internal sealed class JsonSerializer
{
internal static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
static readonly DateTime MinimumJavaScriptDate = new DateTime (100, 1, 1, 0, 0, 0, DateTimeKind.Utc);
static readonly MethodInfo serializeGenericDictionary = typeof (JsonSerializer).GetMethod ("SerializeGenericDictionary", BindingFlags.NonPublic | BindingFlags.Instance);
Dictionary <object, bool> objectCache;
JavaScriptSerializer serializer;
JavaScriptTypeResolver typeResolver;
int recursionLimit;
int maxJsonLength;
int recursionDepth;
Dictionary <Type, MethodInfo> serializeGenericDictionaryMethods;
public JsonSerializer (JavaScriptSerializer serializer)
{
if (serializer == null)
throw new ArgumentNullException ("serializer");
this.serializer = serializer;
typeResolver = serializer.TypeResolver;
recursionLimit = serializer.RecursionLimit;
maxJsonLength = serializer.MaxJsonLength;
}
public void Serialize (object obj, StringBuilder output)
{
if (output == null)
throw new ArgumentNullException ("output");
DoSerialize (obj, output);
}
public void Serialize (object obj, TextWriter output)
{
if (output == null)
throw new ArgumentNullException ("output");
StringBuilder sb = new StringBuilder ();
DoSerialize (obj, sb);
output.Write (sb.ToString ());
}
void DoSerialize (object obj, StringBuilder output)
{
recursionDepth = 0;
objectCache = new Dictionary <object, bool> ();
SerializeValue (obj, output);
}
void SerializeValue (object obj, StringBuilder output)
{
recursionDepth++;
SerializeValueImpl (obj, output);
recursionDepth--;
}
void SerializeValueImpl (object obj, StringBuilder output)
{
if (recursionDepth > recursionLimit)
throw new ArgumentException ("Recursion limit has been exceeded while serializing object of type '{0}'", obj != null ? obj.GetType ().ToString () : "[null]");
if (obj == null || DBNull.Value.Equals (obj)) {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
return;
}
#if !__MonoCS__
if (obj.GetType().Name == "RuntimeType")
{
obj = obj.ToString();
}
#else
if (obj.GetType().Name == "MonoType")
{
obj = obj.ToString();
}
#endif
Type valueType = obj.GetType ();
JavaScriptConverter jsc = serializer.GetConverter (valueType);
if (jsc != null) {
IDictionary <string, object> result = jsc.Serialize (obj, serializer);
if (result == null) {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
return;
}
if (typeResolver != null) {
string typeId = typeResolver.ResolveTypeId (valueType);
if (!String.IsNullOrEmpty (typeId))
result [JavaScriptSerializer.SerializedTypeNameKey] = typeId;
}
SerializeValue (result, output);
return;
}
TypeCode typeCode = Type.GetTypeCode (valueType);
switch (typeCode) {
case TypeCode.String:
WriteValue (output, (string)obj);
return;
case TypeCode.Char:
WriteValue (output, (char)obj);
return;
case TypeCode.Boolean:
WriteValue (output, (bool)obj);
return;
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.Byte:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
if (valueType.IsEnum) {
WriteEnumValue (output, obj, typeCode);
return;
}
goto case TypeCode.Decimal;
case TypeCode.Single:
WriteValue (output, (float)obj);
return;
case TypeCode.Double:
WriteValue (output, (double)obj);
return;
case TypeCode.Decimal:
WriteValue (output, obj as IConvertible);
return;
case TypeCode.DateTime:
WriteValue (output, (DateTime)obj);
return;
}
if (typeof (Uri).IsAssignableFrom (valueType)) {
WriteValue (output, (Uri)obj);
return;
}
if (typeof (Guid).IsAssignableFrom (valueType)) {
WriteValue (output, (Guid)obj);
return;
}
IConvertible convertible = obj as IConvertible;
if (convertible != null) {
WriteValue (output, convertible);
return;
}
try {
if (objectCache.ContainsKey (obj))
throw new InvalidOperationException ("Circular reference detected.");
objectCache.Add (obj, true);
Type closedIDict = GetClosedIDictionaryBase(valueType);
if (closedIDict != null) {
if (serializeGenericDictionaryMethods == null)
serializeGenericDictionaryMethods = new Dictionary <Type, MethodInfo> ();
MethodInfo mi;
if (!serializeGenericDictionaryMethods.TryGetValue (closedIDict, out mi)) {
Type[] types = closedIDict.GetGenericArguments ();
mi = serializeGenericDictionary.MakeGenericMethod (types [0], types [1]);
serializeGenericDictionaryMethods.Add (closedIDict, mi);
}
mi.Invoke (this, new object[] {output, obj});
return;
}
IDictionary dict = obj as IDictionary;
if (dict != null) {
SerializeDictionary (output, dict);
return;
}
IEnumerable enumerable = obj as IEnumerable;
if (enumerable != null) {
SerializeEnumerable (output, enumerable);
return;
}
SerializeArbitraryObject (output, obj, valueType);
} finally {
objectCache.Remove (obj);
}
}
Type GetClosedIDictionaryBase(Type t) {
if(t.IsGenericType && typeof (IDictionary <,>).IsAssignableFrom (t.GetGenericTypeDefinition ()))
return t;
foreach(Type iface in t.GetInterfaces()) {
if(iface.IsGenericType && typeof (IDictionary <,>).IsAssignableFrom (iface.GetGenericTypeDefinition ()))
return iface;
}
return null;
}
bool ShouldIgnoreMember (MemberInfo mi, out MethodInfo getMethod)
{
getMethod = null;
if (mi == null)
return true;
if (mi.IsDefined (typeof (ScriptIgnoreAttribute), true))
return true;
FieldInfo fi = mi as FieldInfo;
if (fi != null)
return false;
PropertyInfo pi = mi as PropertyInfo;
if (pi == null)
return true;
getMethod = pi.GetGetMethod ();
if (getMethod == null || getMethod.GetParameters ().Length > 0) {
getMethod = null;
return true;
}
return false;
}
object GetMemberValue (object obj, MemberInfo mi)
{
FieldInfo fi = mi as FieldInfo;
if (fi != null)
return fi.GetValue (obj);
MethodInfo method = mi as MethodInfo;
if (method == null)
throw new InvalidOperationException ("Member is not a method (internal error).");
object ret;
try {
ret = method.Invoke (obj, null);
} catch (TargetInvocationException niex) {
if (niex.InnerException is NotImplementedException) {
Console.WriteLine ("!!! COMPATIBILITY WARNING. FEATURE NOT IMPLEMENTED. !!!");
Console.WriteLine (niex);
Console.WriteLine ("!!! RETURNING NULL. PLEASE LET MONO DEVELOPERS KNOW ABOUT THIS EXCEPTION. !!!");
return null;
}
throw;
}
return ret;
}
void SerializeArbitraryObject (StringBuilder output, object obj, Type type)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
bool first = true;
if (typeResolver != null) {
string typeId = typeResolver.ResolveTypeId (type);
if (!String.IsNullOrEmpty (typeId)) {
WriteDictionaryEntry (output, first, JavaScriptSerializer.SerializedTypeNameKey, typeId);
first = false;
}
}
SerializeMembers <FieldInfo> (type.GetFields (BindingFlags.Public | BindingFlags.Instance), obj, output, ref first);
SerializeMembers <PropertyInfo> (type.GetProperties (BindingFlags.Public | BindingFlags.Instance), obj, output, ref first);
StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
}
void SerializeMembers <T> (T[] members, object obj, StringBuilder output, ref bool first) where T: MemberInfo
{
MemberInfo member;
MethodInfo getMethod;
string name;
foreach (T mi in members) {
if (ShouldIgnoreMember (mi as MemberInfo, out getMethod))
continue;
name = mi.Name;
if (getMethod != null)
member = getMethod;
else
member = mi;
WriteDictionaryEntry (output, first, name, GetMemberValue (obj, member));
if (first)
first = false;
}
}
void SerializeEnumerable (StringBuilder output, IEnumerable enumerable)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "[");
bool first = true;
foreach (object value in enumerable) {
if (!first)
StringBuilderExtensions.AppendCount (output, maxJsonLength, ',');
SerializeValue (value, output);
if (first)
first = false;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "]");
}
void SerializeDictionary (StringBuilder output, IDictionary dict)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
bool first = true;
foreach (DictionaryEntry entry in dict) {
WriteDictionaryEntry (output, first, entry.Key as string, entry.Value);
if (first)
first = false;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
}
void SerializeGenericDictionary <TKey, TValue> (StringBuilder output, IDictionary <TKey, TValue> dict)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
bool first = true;
foreach (KeyValuePair <TKey, TValue> kvp in dict)
{
var key = typeof(TKey) == typeof(Guid) ? kvp.Key.ToString() : kvp.Key as string;
WriteDictionaryEntry (output, first, key, kvp.Value);
if (first)
first = false;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
}
void WriteDictionaryEntry (StringBuilder output, bool skipComma, string key, object value)
{
if (key == null)
throw new InvalidOperationException ("Only dictionaries with keys convertible to string, or guid keys are supported.");
if (!skipComma)
StringBuilderExtensions.AppendCount (output, maxJsonLength, ',');
WriteValue (output, key);
StringBuilderExtensions.AppendCount (output, maxJsonLength, ':');
SerializeValue (value, output);
}
void WriteEnumValue (StringBuilder output, object value, TypeCode typeCode)
{
switch (typeCode) {
case TypeCode.SByte:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (sbyte)value);
return;
case TypeCode.Int16:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (short)value);
return;
case TypeCode.UInt16:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (ushort)value);
return;
case TypeCode.Int32:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (int)value);
return;
case TypeCode.Byte:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (byte)value);
return;
case TypeCode.UInt32:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (uint)value);
return;
case TypeCode.Int64:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (long)value);
return;
case TypeCode.UInt64:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (ulong)value);
return;
default:
throw new InvalidOperationException (String.Format ("Invalid type code for enum: {0}", typeCode));
}
}
void WriteValue (StringBuilder output, float value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString ("r",Json.DefaultNumberFormatInfo));
}
void WriteValue (StringBuilder output, double value)
{
StringBuilderExtensions.AppendCount(output, maxJsonLength, value.ToString("r",Json.DefaultNumberFormatInfo));
}
void WriteValue (StringBuilder output, Guid value)
{
WriteValue (output, value.ToString ());
}
void WriteValue (StringBuilder output, Uri value)
{
WriteValue (output, value.GetComponents (UriComponents.AbsoluteUri, UriFormat.UriEscaped));
}
void WriteValue (StringBuilder output, DateTime value)
{
value = value.ToUniversalTime ();
if (value < MinimumJavaScriptDate)
value = MinimumJavaScriptDate;
long ticks = (value.Ticks - InitialJavaScriptDateTicks) / (long)10000;
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"\\/Date(" + ticks + ")\\/\"");
}
void WriteValue (StringBuilder output, IConvertible value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString (CultureInfo.InvariantCulture));
}
void WriteValue (StringBuilder output, bool value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value ? "true" : "false");
}
void WriteValue (StringBuilder output, char value)
{
if (value == '\0') {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
return;
}
WriteValue (output, value.ToString ());
}
void WriteValue (StringBuilder output, string value)
{
if (String.IsNullOrEmpty (value)) {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"\"");
return;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"");
char c;
for (int i = 0; i < value.Length; i++) {
c = value [i];
switch (c) {
case '\t':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\t");
break;
case '\n':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\n");
break;
case '\r':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\r");
break;
case '\f':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\f");
break;
case '\b':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\b");
break;
case '<':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u003c");
break;
case '>':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u003e");
break;
case '"':
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\\\"");
break;
case '\'':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u0027");
break;
case '\\':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\\");
break;
default:
if (c > '\u001f')
StringBuilderExtensions.AppendCount (output, maxJsonLength, c);
else {
output.Append("\\u00");
int intVal = (int) c;
StringBuilderExtensions.AppendCount (output, maxJsonLength, (char) ('0' + (intVal >> 4)));
intVal &= 0xf;
StringBuilderExtensions.AppendCount (output, maxJsonLength, (char) (intVal < 10 ? '0' + intVal : 'a' + (intVal - 10)));
}
break;
}
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"");
}
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion --- License ---
using System;
using System.Runtime.InteropServices;
namespace MatterHackers.VectorMath
{
/// <summary>
/// Represents a 3D vector using three float-precision floating-point numbers.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector3Float : IEquatable<Vector3Float>
{
#region Fields
/// <summary>
/// The X component of the Vector3Float.
/// </summary>
public float x;
/// <summary>
/// The Y component of the Vector3Float.
/// </summary>
public float y;
/// <summary>
/// The Z component of the Vector3Float.
/// </summary>
public float z;
#endregion Fields
#region Constructors
/// <summary>
/// Constructs a new Vector3Float.
/// </summary>
/// <param name="x">The x component of the Vector3Float.</param>
/// <param name="y">The y component of the Vector3Float.</param>
/// <param name="z">The z component of the Vector3Float.</param>
public Vector3Float(double x, double y, double z)
: this((float)x, (float)y, (float)z)
{
}
public Vector3Float(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
/// <summary>
/// Constructs a new instance from the given Vector2d.
/// </summary>
/// <param name="v">The Vector2d to copy components from.</param>
public Vector3Float(Vector2 v, float z = 0)
{
#if true
throw new NotImplementedException();
#else
x = v.x;
y = v.y;
this.z = z;
#endif
}
/// <summary>
/// Constructs a new instance from the given Vector3Floatd.
/// </summary>
/// <param name="v">The Vector3Floatd to copy components from.</param>
public Vector3Float(Vector3Float v)
{
x = v.x;
y = v.y;
z = v.z;
}
public Vector3Float(float[] floatArray)
{
x = floatArray[0];
y = floatArray[1];
z = floatArray[2];
}
/// <summary>
/// Constructs a new instance from the given Vector4d.
/// </summary>
/// <param name="v">The Vector4d to copy components from.</param>
public Vector3Float(Vector4 v)
{
#if true
throw new NotImplementedException();
#else
x = v.x;
y = v.y;
z = v.z;
#endif
}
public Vector3Float(Vector3 position)
{
this.x = (float)position.x;
this.y = (float)position.y;
this.z = (float)position.z;
}
#endregion Constructors
#region Properties
public float this[int index]
{
get
{
switch (index)
{
case 0:
return x;
case 1:
return y;
case 2:
return z;
default:
return 0;
}
}
set
{
switch (index)
{
case 0:
x = value;
break;
case 1:
y = value;
break;
case 2:
z = value;
break;
default:
throw new Exception();
}
}
}
#endregion Properties
#region Public Members
#region Instance
#region public float Length
/// <summary>
/// Gets the length (magnitude) of the vector.
/// </summary>
/// <see cref="LengthFast"/>
/// <seealso cref="LengthSquared"/>
public float Length
{
get
{
return (float)Math.Sqrt(x * x + y * y + z * z);
}
}
#endregion public float Length
#region public float LengthSquared
/// <summary>
/// Gets the square of the vector length (magnitude).
/// </summary>
/// <remarks>
/// This property avoids the costly square root operation required by the Length property. This makes it more suitable
/// for comparisons.
/// </remarks>
/// <see cref="Length"/>
/// <seealso cref="LengthFast"/>
public float LengthSquared
{
get
{
return x * x + y * y + z * z;
}
}
#endregion public float LengthSquared
#region public void Normalize()
/// <summary>
/// Returns a normalized Vector of this.
/// </summary>
/// <returns></returns>
public Vector3Float GetNormal()
{
Vector3Float temp = this;
temp.Normalize();
return temp;
}
/// <summary>
/// Scales the Vector3Floatd to unit length.
/// </summary>
public void Normalize()
{
float scale = 1.0f / this.Length;
x *= scale;
y *= scale;
z *= scale;
}
#endregion public void Normalize()
#region public float[] ToArray()
public float[] ToArray()
{
return new float[] { x, y, z };
}
#endregion public float[] ToArray()
#endregion Instance
#region Static
#region Fields
/// <summary>
/// Defines a unit-length Vector3Floatd that points towards the X-axis.
/// </summary>
public static readonly Vector3Float UnitX = new Vector3Float(1, 0, 0);
/// <summary>
/// Defines a unit-length Vector3Floatd that points towards the Y-axis.
/// </summary>
public static readonly Vector3Float UnitY = new Vector3Float(0, 1, 0);
/// <summary>
/// /// Defines a unit-length Vector3Floatd that points towards the Z-axis.
/// </summary>
public static readonly Vector3Float UnitZ = new Vector3Float(0, 0, 1);
/// <summary>
/// Defines a zero-length Vector3Float.
/// </summary>
public static readonly Vector3Float Zero = new Vector3Float(0, 0, 0);
/// <summary>
/// Defines an instance with all components set to 1.
/// </summary>
public static readonly Vector3Float One = new Vector3Float(1, 1, 1);
/// <summary>
/// Defines an instance with all components set to positive infinity.
/// </summary>
public static readonly Vector3Float PositiveInfinity = new Vector3Float(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
/// <summary>
/// Defines an instance with all components set to negative infinity.
/// </summary>
public static readonly Vector3Float NegativeInfinity = new Vector3Float(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity);
/// <summary>
/// Defines the size of the Vector3Floatd struct in bytes.
/// </summary>
public static readonly int SizeInBytes = Marshal.SizeOf(new Vector3Float());
#endregion Fields
#region Add
/// <summary>
/// Adds two vectors.
/// </summary>
/// <param name="a">Left operand.</param>
/// <param name="b">Right operand.</param>
/// <returns>Result of operation.</returns>
public static Vector3Float Add(Vector3Float a, Vector3Float b)
{
Add(ref a, ref b, out a);
return a;
}
/// <summary>
/// Adds two vectors.
/// </summary>
/// <param name="a">Left operand.</param>
/// <param name="b">Right operand.</param>
/// <param name="result">Result of operation.</param>
public static void Add(ref Vector3Float a, ref Vector3Float b, out Vector3Float result)
{
result = new Vector3Float(a.x + b.x, a.y + b.y, a.z + b.z);
}
#endregion Add
#region Subtract
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>Result of subtraction</returns>
public static Vector3Float Subtract(Vector3Float a, Vector3Float b)
{
Subtract(ref a, ref b, out a);
return a;
}
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">Result of subtraction</param>
public static void Subtract(ref Vector3Float a, ref Vector3Float b, out Vector3Float result)
{
result = new Vector3Float(a.x - b.x, a.y - b.y, a.z - b.z);
}
#endregion Subtract
#region Multiply
/// <summary>
/// Multiplies a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector3Float Multiply(Vector3Float vector, float scale)
{
Multiply(ref vector, scale, out vector);
return vector;
}
/// <summary>
/// Multiplies a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Multiply(ref Vector3Float vector, float scale, out Vector3Float result)
{
result = new Vector3Float(vector.x * scale, vector.y * scale, vector.z * scale);
}
/// <summary>
/// Multiplies a vector by the components a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector3Float Multiply(Vector3Float vector, Vector3Float scale)
{
Multiply(ref vector, ref scale, out vector);
return vector;
}
/// <summary>
/// Multiplies a vector by the components of a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Multiply(ref Vector3Float vector, ref Vector3Float scale, out Vector3Float result)
{
result = new Vector3Float(vector.x * scale.x, vector.y * scale.y, vector.z * scale.z);
}
#endregion Multiply
#region Divide
/// <summary>
/// Divides a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector3Float Divide(Vector3Float vector, float scale)
{
Divide(ref vector, scale, out vector);
return vector;
}
/// <summary>
/// Divides a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Divide(ref Vector3Float vector, float scale, out Vector3Float result)
{
Multiply(ref vector, 1 / scale, out result);
}
/// <summary>
/// Divides a vector by the components of a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector3Float Divide(Vector3Float vector, Vector3Float scale)
{
Divide(ref vector, ref scale, out vector);
return vector;
}
/// <summary>
/// Divide a vector by the components of a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Divide(ref Vector3Float vector, ref Vector3Float scale, out Vector3Float result)
{
result = new Vector3Float(vector.x / scale.x, vector.y / scale.y, vector.z / scale.z);
}
#endregion Divide
#region ComponentMin
/// <summary>
/// Calculate the component-wise minimum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>The component-wise minimum</returns>
public static Vector3Float ComponentMin(Vector3Float a, Vector3Float b)
{
a.x = a.x < b.x ? a.x : b.x;
a.y = a.y < b.y ? a.y : b.y;
a.z = a.z < b.z ? a.z : b.z;
return a;
}
/// <summary>
/// Calculate the component-wise minimum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">The component-wise minimum</param>
public static void ComponentMin(ref Vector3Float a, ref Vector3Float b, out Vector3Float result)
{
result.x = a.x < b.x ? a.x : b.x;
result.y = a.y < b.y ? a.y : b.y;
result.z = a.z < b.z ? a.z : b.z;
}
#endregion ComponentMin
#region ComponentMax
/// <summary>
/// Calculate the component-wise maximum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>The component-wise maximum</returns>
public static Vector3Float ComponentMax(Vector3Float a, Vector3Float b)
{
a.x = a.x > b.x ? a.x : b.x;
a.y = a.y > b.y ? a.y : b.y;
a.z = a.z > b.z ? a.z : b.z;
return a;
}
/// <summary>
/// Calculate the component-wise maximum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">The component-wise maximum</param>
public static void ComponentMax(ref Vector3Float a, ref Vector3Float b, out Vector3Float result)
{
result.x = a.x > b.x ? a.x : b.x;
result.y = a.y > b.y ? a.y : b.y;
result.z = a.z > b.z ? a.z : b.z;
}
#endregion ComponentMax
#region Min
/// <summary>
/// Returns the Vector3d with the minimum magnitude
/// </summary>
/// <param name="left">Left operand</param>
/// <param name="right">Right operand</param>
/// <returns>The minimum Vector3Float</returns>
public static Vector3Float Min(Vector3Float left, Vector3Float right)
{
return left.LengthSquared < right.LengthSquared ? left : right;
}
#endregion Min
#region Max
/// <summary>
/// Returns the Vector3d with the minimum magnitude
/// </summary>
/// <param name="left">Left operand</param>
/// <param name="right">Right operand</param>
/// <returns>The minimum Vector3Float</returns>
public static Vector3Float Max(Vector3Float left, Vector3Float right)
{
return left.LengthSquared >= right.LengthSquared ? left : right;
}
#endregion Max
#region Clamp
/// <summary>
/// Clamp a vector to the given minimum and maximum vectors
/// </summary>
/// <param name="vec">Input vector</param>
/// <param name="min">Minimum vector</param>
/// <param name="max">Maximum vector</param>
/// <returns>The clamped vector</returns>
public static Vector3Float Clamp(Vector3Float vec, Vector3Float min, Vector3Float max)
{
vec.x = vec.x < min.x ? min.x : vec.x > max.x ? max.x : vec.x;
vec.y = vec.y < min.y ? min.y : vec.y > max.y ? max.y : vec.y;
vec.z = vec.z < min.z ? min.z : vec.z > max.z ? max.z : vec.z;
return vec;
}
/// <summary>
/// Clamp a vector to the given minimum and maximum vectors
/// </summary>
/// <param name="vec">Input vector</param>
/// <param name="min">Minimum vector</param>
/// <param name="max">Maximum vector</param>
/// <param name="result">The clamped vector</param>
public static void Clamp(ref Vector3Float vec, ref Vector3Float min, ref Vector3Float max, out Vector3Float result)
{
result.x = vec.x < min.x ? min.x : vec.x > max.x ? max.x : vec.x;
result.y = vec.y < min.y ? min.y : vec.y > max.y ? max.y : vec.y;
result.z = vec.z < min.z ? min.z : vec.z > max.z ? max.z : vec.z;
}
#endregion Clamp
#region Normalize
/// <summary>
/// Scale a vector to unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <returns>The normalized vector</returns>
public static Vector3Float Normalize(Vector3Float vec)
{
float scale = 1.0f / vec.Length;
vec.x *= scale;
vec.y *= scale;
vec.z *= scale;
return vec;
}
/// <summary>
/// Scale a vector to unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <param name="result">The normalized vector</param>
public static void Normalize(ref Vector3Float vec, out Vector3Float result)
{
float scale = 1.0f / vec.Length;
result.x = vec.x * scale;
result.y = vec.y * scale;
result.z = vec.z * scale;
}
#endregion Normalize
#region Dot
/// <summary>
/// Calculate the dot (scalar) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <returns>The dot product of the two inputs</returns>
public static float Dot(Vector3Float left, Vector3Float right)
{
return left.x * right.x + left.y * right.y + left.z * right.z;
}
/// <summary>
/// Calculate the dot (scalar) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <param name="result">The dot product of the two inputs</param>
public static void Dot(ref Vector3Float left, ref Vector3Float right, out float result)
{
result = left.x * right.x + left.y * right.y + left.z * right.z;
}
#endregion Dot
#region Cross
/// <summary>
/// Caclulate the cross (vector) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <returns>The cross product of the two inputs</returns>
public static Vector3Float Cross(Vector3Float left, Vector3Float right)
{
Vector3Float result;
Cross(ref left, ref right, out result);
return result;
}
/// <summary>
/// Caclulate the cross (vector) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <returns>The cross product of the two inputs</returns>
/// <param name="result">The cross product of the two inputs</param>
public static void Cross(ref Vector3Float left, ref Vector3Float right, out Vector3Float result)
{
result = new Vector3Float(left.y * right.z - left.z * right.y,
left.z * right.x - left.x * right.z,
left.x * right.y - left.y * right.x);
}
#endregion Cross
#region Utility
/// <summary>
/// Checks if 3 points are collinear (all lie on the same line).
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <param name="epsilon"></param>
/// <returns></returns>
public static bool Collinear(Vector3Float a, Vector3Float b, Vector3Float c, float epsilon = .000001f)
{
// Return true if a, b, and c all lie on the same line.
return Math.Abs(Cross(b - a, c - a).Length) < epsilon;
}
#endregion Utility
#region Lerp
/// <summary>
/// Returns a new Vector that is the linear blend of the 2 given Vectors
/// </summary>
/// <param name="a">First input vector</param>
/// <param name="b">Second input vector</param>
/// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param>
/// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns>
public static Vector3Float Lerp(Vector3Float a, Vector3Float b, float blend)
{
a.x = blend * (b.x - a.x) + a.x;
a.y = blend * (b.y - a.y) + a.y;
a.z = blend * (b.z - a.z) + a.z;
return a;
}
/// <summary>
/// Returns a new Vector that is the linear blend of the 2 given Vectors
/// </summary>
/// <param name="a">First input vector</param>
/// <param name="b">Second input vector</param>
/// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param>
/// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param>
public static void Lerp(ref Vector3Float a, ref Vector3Float b, float blend, out Vector3Float result)
{
result.x = blend * (b.x - a.x) + a.x;
result.y = blend * (b.y - a.y) + a.y;
result.z = blend * (b.z - a.z) + a.z;
}
#endregion Lerp
#region Barycentric
/// <summary>
/// Interpolate 3 Vectors using Barycentric coordinates
/// </summary>
/// <param name="a">First input Vector</param>
/// <param name="b">Second input Vector</param>
/// <param name="c">Third input Vector</param>
/// <param name="u">First Barycentric Coordinate</param>
/// <param name="v">Second Barycentric Coordinate</param>
/// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns>
public static Vector3Float BaryCentric(Vector3Float a, Vector3Float b, Vector3Float c, float u, float v)
{
return a + u * (b - a) + v * (c - a);
}
/// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary>
/// <param name="a">First input Vector.</param>
/// <param name="b">Second input Vector.</param>
/// <param name="c">Third input Vector.</param>
/// <param name="u">First Barycentric Coordinate.</param>
/// <param name="v">Second Barycentric Coordinate.</param>
/// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param>
public static void BaryCentric(ref Vector3Float a, ref Vector3Float b, ref Vector3Float c, float u, float v, out Vector3Float result)
{
result = a; // copy
Vector3Float temp = b; // copy
Subtract(ref temp, ref a, out temp);
Multiply(ref temp, u, out temp);
Add(ref result, ref temp, out result);
temp = c; // copy
Subtract(ref temp, ref a, out temp);
Multiply(ref temp, v, out temp);
Add(ref result, ref temp, out result);
}
#endregion Barycentric
#region Transform
/// <summary>Transform a direction vector by the given Matrix
/// Assumes the matrix has a bottom row of (0,0,0,1), that is the translation part is ignored.
/// </summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed vector</returns>
public static Vector3Float TransformVector(Vector3Float vec, Matrix4X4 mat)
{
return new Vector3Float(
Vector3Float.Dot(vec, new Vector3Float(mat.Column0)),
Vector3Float.Dot(vec, new Vector3Float(mat.Column1)),
Vector3Float.Dot(vec, new Vector3Float(mat.Column2)));
}
/// <summary>Transform a direction vector by the given Matrix
/// Assumes the matrix has a bottom row of (0,0,0,1), that is the translation part is ignored.
/// </summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed vector</param>
public static void TransformVector(ref Vector3Float vec, ref Matrix4X4 mat, out Vector3Float result)
{
#if true
throw new NotImplementedException();
#else
result.x = vec.x * mat.Row0.x +
vec.y * mat.Row1.x +
vec.z * mat.Row2.x;
result.y = vec.x * mat.Row0.y +
vec.y * mat.Row1.y +
vec.z * mat.Row2.y;
result.z = vec.x * mat.Row0.z +
vec.y * mat.Row1.z +
vec.z * mat.Row2.z;
#endif
}
/// <summary>Transform a Normal by the given Matrix</summary>
/// <remarks>
/// This calculates the inverse of the given matrix, use TransformNormalInverse if you
/// already have the inverse to avoid this extra calculation
/// </remarks>
/// <param name="norm">The normal to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed normal</returns>
public static Vector3Float TransformNormal(Vector3Float norm, Matrix4X4 mat)
{
mat.Invert();
return TransformNormalInverse(norm, mat);
}
/// <summary>Transform a Normal by the given Matrix</summary>
/// <remarks>
/// This calculates the inverse of the given matrix, use TransformNormalInverse if you
/// already have the inverse to avoid this extra calculation
/// </remarks>
/// <param name="norm">The normal to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed normal</param>
public static void TransformNormal(ref Vector3Float norm, ref Matrix4X4 mat, out Vector3Float result)
{
Matrix4X4 Inverse = Matrix4X4.Invert(mat);
Vector3Float.TransformNormalInverse(ref norm, ref Inverse, out result);
}
/// <summary>Transform a Normal by the (transpose of the) given Matrix</summary>
/// <remarks>
/// This version doesn't calculate the inverse matrix.
/// Use this version if you already have the inverse of the desired transform to hand
/// </remarks>
/// <param name="norm">The normal to transform</param>
/// <param name="invMat">The inverse of the desired transformation</param>
/// <returns>The transformed normal</returns>
public static Vector3Float TransformNormalInverse(Vector3Float norm, Matrix4X4 invMat)
{
return new Vector3Float(
Vector3Float.Dot(norm, new Vector3Float(invMat.Row0)),
Vector3Float.Dot(norm, new Vector3Float(invMat.Row1)),
Vector3Float.Dot(norm, new Vector3Float(invMat.Row2)));
}
/// <summary>Transform a Normal by the (transpose of the) given Matrix</summary>
/// <remarks>
/// This version doesn't calculate the inverse matrix.
/// Use this version if you already have the inverse of the desired transform to hand
/// </remarks>
/// <param name="norm">The normal to transform</param>
/// <param name="invMat">The inverse of the desired transformation</param>
/// <param name="result">The transformed normal</param>
public static void TransformNormalInverse(ref Vector3Float norm, ref Matrix4X4 invMat, out Vector3Float result)
{
#if true
throw new NotImplementedException();
#else
result.x = norm.x * invMat.Row0.x +
norm.y * invMat.Row0.y +
norm.z * invMat.Row0.z;
result.y = norm.x * invMat.Row1.x +
norm.y * invMat.Row1.y +
norm.z * invMat.Row1.z;
result.z = norm.x * invMat.Row2.x +
norm.y * invMat.Row2.y +
norm.z * invMat.Row2.z;
#endif
}
/// <summary>Transform a Position by the given Matrix</summary>
/// <param name="pos">The position to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed position</returns>
public static Vector3Float TransformPosition(Vector3Float pos, Matrix4X4 mat)
{
#if true
throw new NotImplementedException();
#else
return new Vector3Float(
Vector3Float.Dot(pos, new Vector3Float((float)mat.Column0)) + mat.Row3.x,
Vector3Float.Dot(pos, new Vector3Float((float)mat.Column1)) + mat.Row3.y,
Vector3Float.Dot(pos, new Vector3Float((float)mat.Column2)) + mat.Row3.z);
#endif
}
/// <summary>Transform a Position by the given Matrix</summary>
/// <param name="pos">The position to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed position</param>
public static void TransformPosition(ref Vector3Float pos, ref Matrix4X4 mat, out Vector3Float result)
{
#if true
throw new NotImplementedException();
#else
result.x = pos.x * mat.Row0.x +
pos.y * mat.Row1.x +
pos.z * mat.Row2.x +
mat.Row3.x;
result.y = pos.x * mat.Row0.y +
pos.y * mat.Row1.y +
pos.z * mat.Row2.y +
mat.Row3.y;
result.z = pos.x * mat.Row0.z +
pos.y * mat.Row1.z +
pos.z * mat.Row2.z +
mat.Row3.z;
#endif
}
/// <summary>
/// Transform all the vectors in the array by the given Matrix.
/// </summary>
/// <param name="boundsVerts"></param>
/// <param name="rotationQuaternion"></param>
public static void Transform(Vector3Float[] vecArray, Matrix4X4 mat)
{
for (int i = 0; i < vecArray.Length; i++)
{
vecArray[i] = Transform(vecArray[i], mat);
}
}
/// <summary>Transform a Vector by the given Matrix</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed vector</returns>
public static Vector3Float Transform(Vector3Float vec, Matrix4X4 mat)
{
Vector3Float result;
Transform(ref vec, ref mat, out result);
return result;
}
/// <summary>Transform a Vector by the given Matrix</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed vector</param>
public static void Transform(ref Vector3Float vec, ref Matrix4X4 mat, out Vector3Float result)
{
#if true
throw new NotImplementedException();
#else
Vector4 v4 = new Vector4(vec.x, vec.y, vec.z, 1.0);
Vector4.Transform(ref v4, ref mat, out v4);
result = v4.Xyz;
#endif
}
/// <summary>
/// Transforms a vector by a quaternion rotation.
/// </summary>
/// <param name="vec">The vector to transform.</param>
/// <param name="quat">The quaternion to rotate the vector by.</param>
/// <returns>The result of the operation.</returns>
public static Vector3Float Transform(Vector3Float vec, Quaternion quat)
{
#if true
throw new NotImplementedException();
#else
Vector3Float result;
Transform(ref vec, ref quat, out result);
return result;
#endif
}
/// <summary>
/// Transforms a vector by a quaternion rotation.
/// </summary>
/// <param name="vec">The vector to transform.</param>
/// <param name="quat">The quaternion to rotate the vector by.</param>
/// <param name="result">The result of the operation.</param>
public static void Transform(ref Vector3Float vec, ref Quaternion quat, out Vector3Float result)
{
#if true
throw new NotImplementedException();
#else
// Since vec.W == 0, we can optimize quat * vec * quat^-1 as follows:
// vec + 2.0 * cross(quat.xyz, cross(quat.xyz, vec) + quat.w * vec)
Vector3Float xyz = quat.Xyz, temp, temp2;
Vector3Float.Cross(ref xyz, ref vec, out temp);
Vector3Float.Multiply(ref vec, quat.W, out temp2);
Vector3Float.Add(ref temp, ref temp2, out temp);
Vector3Float.Cross(ref xyz, ref temp, out temp);
Vector3Float.Multiply(ref temp, 2, out temp);
Vector3Float.Add(ref vec, ref temp, out result);
#endif
}
/// <summary>
/// Transform all the vectors in the array by the quaternion rotation.
/// </summary>
/// <param name="boundsVerts"></param>
/// <param name="rotationQuaternion"></param>
public static void Transform(Vector3Float[] vecArray, Quaternion rotationQuaternion)
{
for (int i = 0; i < vecArray.Length; i++)
{
vecArray[i] = Transform(vecArray[i], rotationQuaternion);
}
}
/// <summary>
/// Transform a Vector3d by the given Matrix, and project the resulting Vector4 back to a Vector3Float
/// </summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed vector</returns>
public static Vector3Float TransformPerspective(Vector3Float vec, Matrix4X4 mat)
{
#if true
throw new NotImplementedException();
#else
Vector3Float result;
TransformPerspective(ref vec, ref mat, out result);
return result;
#endif
}
/// <summary>Transform a Vector3d by the given Matrix, and project the resulting Vector4d back to a Vector3d</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed vector</param>
public static void TransformPerspective(ref Vector3Float vec, ref Matrix4X4 mat, out Vector3Float result)
{
#if true
throw new NotImplementedException();
#else
Vector4 v = new Vector4(vec);
Vector4.Transform(ref v, ref mat, out v);
result.x = v.x / v.w;
result.y = v.y / v.w;
result.z = v.z / v.w;
#endif
}
#endregion Transform
#region CalculateAngle
/// <summary>
/// Calculates the angle (in radians) between two vectors.
/// </summary>
/// <param name="first">The first vector.</param>
/// <param name="second">The second vector.</param>
/// <returns>Angle (in radians) between the vectors.</returns>
/// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks>
public static float CalculateAngle(Vector3Float first, Vector3Float second)
{
return (float)Math.Acos((Vector3Float.Dot(first, second)) / (first.Length * second.Length));
}
/// <summary>Calculates the angle (in radians) between two vectors.</summary>
/// <param name="first">The first vector.</param>
/// <param name="second">The second vector.</param>
/// <param name="result">Angle (in radians) between the vectors.</param>
/// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks>
public static void CalculateAngle(ref Vector3Float first, ref Vector3Float second, out float result)
{
float temp;
Vector3Float.Dot(ref first, ref second, out temp);
result = (float)Math.Acos(temp / (first.Length * second.Length));
}
#endregion CalculateAngle
#endregion Static
#region Swizzle
/// <summary>
/// Gets or sets an OpenTK.Vector2d with the X and Y components of this instance.
/// </summary>
public Vector2 Xy
{
get
{
return new Vector2(x, y);
}
set
{
#if true
throw new NotImplementedException();
#else
x = value.x; y = value.y;
#endif
}
}
#endregion Swizzle
#region Operators
/// <summary>
/// Adds two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>The result of the calculation.</returns>
public static Vector3Float operator +(Vector3Float left, Vector3Float right)
{
left.x += right.x;
left.y += right.y;
left.z += right.z;
return left;
}
/// <summary>
/// Subtracts two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>The result of the calculation.</returns>
public static Vector3Float operator -(Vector3Float left, Vector3Float right)
{
left.x -= right.x;
left.y -= right.y;
left.z -= right.z;
return left;
}
/// <summary>
/// Negates an instance.
/// </summary>
/// <param name="vec">The instance.</param>
/// <returns>The result of the calculation.</returns>
public static Vector3Float operator -(Vector3Float vec)
{
vec.x = -vec.x;
vec.y = -vec.y;
vec.z = -vec.z;
return vec;
}
/// <summary>
/// Component wise multiply two vectors together, x*x, y*y, z*z.
/// </summary>
/// <param name="vecA"></param>
/// <param name="vecB"></param>
/// <returns></returns>
public static Vector3Float operator *(Vector3Float vecA, Vector3Float vecB)
{
vecA.x *= vecB.x;
vecA.y *= vecB.y;
vecA.z *= vecB.z;
return vecA;
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="vec">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <returns>The result of the calculation.</returns>
public static Vector3Float operator *(Vector3Float vec, float scale)
{
vec.x *= scale;
vec.y *= scale;
vec.z *= scale;
return vec;
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="scale">The scalar.</param>
/// <param name="vec">The instance.</param>
/// <returns>The result of the calculation.</returns>
public static Vector3Float operator *(float scale, Vector3Float vec)
{
vec.x *= scale;
vec.y *= scale;
vec.z *= scale;
return vec;
}
/// <summary>
/// Creates a new vector which is the numerator devided by each component of the vector.
/// </summary>
/// <param name="numerator"></param>
/// <param name="vec"></param>
/// <returns>The result of the calculation.</returns>
public static Vector3Float operator /(float numerator, Vector3Float vec)
{
return new Vector3Float((numerator / vec.x), (numerator / vec.y), (numerator / vec.z));
}
/// <summary>
/// Divides an instance by a scalar.
/// </summary>
/// <param name="vec">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <returns>The result of the calculation.</returns>
public static Vector3Float operator /(Vector3Float vec, float scale)
{
float mult = 1 / scale;
vec.x *= mult;
vec.y *= mult;
vec.z *= mult;
return vec;
}
/// <summary>
/// Compares two instances for equality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left equals right; false otherwise.</returns>
public static bool operator ==(Vector3Float left, Vector3Float right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two instances for inequality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left does not equa lright; false otherwise.</returns>
public static bool operator !=(Vector3Float left, Vector3Float right)
{
return !left.Equals(right);
}
#endregion Operators
#region Overrides
#region public override string ToString()
/// <summary>
/// Returns a System.String that represents the current Vector3Float.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("[{0}, {1}, {2}]", x, y, z);
}
#endregion public override string ToString()
#region public override int GetHashCode()
/// <summary>
/// Returns the hashcode for this instance.
/// </summary>
/// <returns>A System.Int32 containing the unique hashcode for this instance.</returns>
public override int GetHashCode()
{
return new { x, y, z }.GetHashCode();
}
#endregion public override int GetHashCode()
#region public override bool Equals(object obj)
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">The object to compare to.</param>
/// <returns>True if the instances are equal; false otherwise.</returns>
public override bool Equals(object obj)
{
if (!(obj is Vector3Float))
return false;
return this.Equals((Vector3Float)obj);
}
/// <summary>
/// Indicates whether this instance and a specified object are equal within an error range.
/// </summary>
/// <param name="OtherVector"></param>
/// <param name="ErrorValue"></param>
/// <returns>True if the instances are equal; false otherwise.</returns>
public bool Equals(Vector3Float OtherVector, float ErrorValue)
{
if ((x < OtherVector.x + ErrorValue && x > OtherVector.x - ErrorValue) &&
(y < OtherVector.y + ErrorValue && y > OtherVector.y - ErrorValue) &&
(z < OtherVector.z + ErrorValue && z > OtherVector.z - ErrorValue))
{
return true;
}
return false;
}
#endregion public override bool Equals(object obj)
#endregion Overrides
#endregion Public Members
#region IEquatable<Vector3Float> Members
/// <summary>Indicates whether the current vector is equal to another vector.</summary>
/// <param name="other">A vector to compare with this vector.</param>
/// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns>
public bool Equals(Vector3Float other)
{
return
x == other.x &&
y == other.y &&
z == other.z;
}
#endregion IEquatable<Vector3Float> Members
public static float ComponentMax(Vector3Float vector3)
{
return Math.Max(vector3.x, Math.Max(vector3.y, vector3.z));
}
public static float ComponentMin(Vector3Float vector3)
{
return Math.Min(vector3.x, Math.Min(vector3.y, vector3.z));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition
{
using Microsoft.Azure.Management.ContainerRegistry.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
/// <summary>
/// The stage of the definition which contains all the minimum required inputs for the resource to be created,
/// but also allows for any other optional settings to be specified.
/// </summary>
public interface ITaskCreatable :
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.IAgentConfiguration,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITimeout,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ISourceTriggerDefinition,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITriggerTypes,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.ICreatable<Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistryTask>
{
}
/// <summary>
/// Container interface for all the definitions related to a registry task.
/// </summary>
public interface IDefinition :
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.IBlank,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ILocation,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.IPlatform,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskStepType,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ISourceTriggerDefinition,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITriggerTypes,
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskCreatable
{
}
/// <summary>
/// The stage of the container registry task definition that allows users to define either a source trigger and/or a base image trigger.
/// </summary>
public interface ITriggerTypes
{
/// <summary>
/// The function that begins the definition of a source trigger.
/// </summary>
/// <param name="sourceTriggerName">The name of the source trigger we are defining.</param>
/// <return>The first stage of the RegistrySourceTrigger definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistrySourceTrigger.Definition.IBlank DefineSourceTrigger(string sourceTriggerName);
/// <summary>
/// The function that defines a base image trigger with the two parameters required for base image trigger creation.
/// </summary>
/// <param name="baseImageTriggerName">The name of the base image trigger.</param>
/// <param name="baseImageTriggerType">The trigger type for the base image. Can be "All", "Runtime", or something else that the user inputs.</param>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskCreatable WithBaseImageTrigger(string baseImageTriggerName, BaseImageTriggerType baseImageTriggerType);
/// <summary>
/// The function that defines a base image trigger with all possible parameters for base image trigger creation.
/// </summary>
/// <param name="baseImageTriggerName">The name of the base image trigger.</param>
/// <param name="baseImageTriggerType">The trigger type for the base image. Can be "All", "Runtime", or something else that the user inputs.</param>
/// <param name="triggerStatus">The status for the trigger. Can be enabled, disabled, or something else that the user inputs.</param>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskCreatable WithBaseImageTrigger(string baseImageTriggerName, BaseImageTriggerType baseImageTriggerType, TriggerStatus triggerStatus);
}
/// <summary>
/// The stage of the container registry task definition that specifies the type of task step.
/// </summary>
public interface ITaskStepType
{
/// <summary>
/// Gets The function that specifies a task step of type DockerTaskStep.
/// </summary>
/// <summary>
/// Gets the first stage of the DockerTaskStep definition.
/// </summary>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryDockerTaskStep.Definition.IBlank DefineDockerTaskStep();
/// <summary>
/// Gets The function that specifies a task step of type EncodedTaskStep.
/// </summary>
/// <summary>
/// Gets the first stage of the EncodedTaskStep definition.
/// </summary>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryEncodedTaskStep.Definition.IBlank DefineEncodedTaskStep();
/// <summary>
/// Gets The function that specifies a task step of type FileTaskStep.
/// </summary>
/// <summary>
/// Gets the first stage of the FileTaskStep definition.
/// </summary>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryFileTaskStep.Definition.IBlank DefineFileTaskStep();
}
/// <summary>
/// The stage of the container registry task definition allowing to specify location.
/// </summary>
public interface ILocation
{
/// <summary>
/// The parameters specifying location of the container registry task.
/// </summary>
/// <param name="location">The location of the container registry task.</param>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.IPlatform WithLocation(string location);
/// <summary>
/// The parameters specifying location of the container registry task.
/// </summary>
/// <param name="location">The location of the container registry task.</param>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.IPlatform WithLocation(Region location);
}
/// <summary>
/// The stage of the container registry task definition allowing to specify the platform.
/// </summary>
public interface IPlatform
{
/// <summary>
/// The function that specifies a Linux OS system for the platform.
/// </summary>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskStepType WithLinux();
/// <summary>
/// The function that specifies a Linux OS system and architecture for the platform.
/// </summary>
/// <param name="architecture">The CPU architecture.</param>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskStepType WithLinux(Architecture architecture);
/// <summary>
/// The function that specifies a Linux OS system, architecture, and CPU variant.
/// </summary>
/// <param name="architecture">The CPU architecture.</param>
/// <param name="variant">The CPU variant.</param>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskStepType WithLinux(Architecture architecture, Variant variant);
/// <summary>
/// The function that specifies a platform.
/// </summary>
/// <param name="platformProperties">The properties of the platform.</param>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskStepType WithPlatform(PlatformProperties platformProperties);
/// <summary>
/// The function that specifies a Windows OS system for the platform.
/// </summary>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskStepType WithWindows();
/// <summary>
/// The function that specifies a Windows OS system and architecture for the platform.
/// </summary>
/// <param name="architecture">The CPU architecture.</param>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskStepType WithWindows(Architecture architecture);
/// <summary>
/// The function that specifies a Windows OS system, architecture, and CPU variant.
/// </summary>
/// <param name="architecture">The CPU architecture.</param>
/// <param name="variant">The CPU variant.</param>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskStepType WithWindows(Architecture architecture, Variant variant);
}
/// <summary>
/// The stage of the container registry task definition that allows users to define a source trigger.
/// </summary>
public interface ISourceTriggerDefinition
{
/// <summary>
/// The function that begins the definition of a source trigger.
/// </summary>
/// <param name="sourceTriggerName">The name of the source trigger we are defining.</param>
/// <return>The first stage of the RegistrySourceTrigger definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistrySourceTrigger.Definition.IBlank DefineSourceTrigger(string sourceTriggerName);
}
/// <summary>
/// The first stage of a container registry task definition.
/// </summary>
public interface IBlank
{
/// <summary>
/// The parameters referencing an existing container registry under which this task resides.
/// </summary>
/// <param name="resourceGroupName">The name of the parent container registry resource group.</param>
/// <param name="registryName">The name of the existing container registry.</param>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ILocation WithExistingRegistry(string resourceGroupName, string registryName);
}
/// <summary>
/// The stage of the container registry task definition that specifies the timeout for the container registry task.
/// </summary>
public interface ITimeout
{
/// <summary>
/// The function that sets the timeout time.
/// </summary>
/// <param name="timeout">The time for timeout.</param>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskCreatable WithTimeout(int timeout);
}
/// <summary>
/// The stage of the container registry task definition that specifies the AgentConfiguration for the container registry task.
/// </summary>
public interface IAgentConfiguration
{
/// <summary>
/// The function that specifies the count of the CPU.
/// </summary>
/// <param name="count">The CPU count.</param>
/// <return>The next stage of the container registry task definition.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.RegistryTask.Definition.ITaskCreatable WithCpuCount(int count);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using Jsonics.FromJson.PropertyHashing;
namespace Jsonics.FromJson
{
internal class StructFromJsonEmitter : FromJsonEmitter
{
LocalBuilder _propertyNameLocal;
LocalBuilder _jsonObjectLocal;
LocalBuilder _indexLocal;
LocalBuilder _propertyStartLocal;
LocalBuilder _propertyEndLocal;
Type _jsonObjectType;
bool _isNullable;
internal StructFromJsonEmitter(LocalBuilder lazyStringLocal, JsonILGenerator generator, FromJsonEmitters emitters)
: base(lazyStringLocal, generator, emitters)
{
_lazyStringLocal = lazyStringLocal;
_generator = generator;
}
Type _underlyingType;
internal override void Emit(LocalBuilder indexLocal, Type jsonObjectType)
{
_jsonObjectType = jsonObjectType;
_underlyingType = Nullable.GetUnderlyingType(_jsonObjectType);
_isNullable = _underlyingType != null;
if(!_isNullable)
{
_underlyingType = _jsonObjectType;
}
_indexLocal = indexLocal;
//construct object
_jsonObjectLocal = _generator.DeclareLocal(_underlyingType);
_generator.LoadLocalAddress(_jsonObjectLocal);
_generator.InitObject(_underlyingType);
//null check
Label loopCheck = _generator.DefineLabel();
var endLabel = _generator.DefineLabel();
if(_isNullable)
{
//(inputIndex, character) = json.ReadToAny(inputIndex, '{', 'n');
_generator.LoadLocalAddress(_lazyStringLocal);
_generator.LoadLocal(_indexLocal);
_generator.LoadConstantInt32('{');
_generator.LoadConstantInt32('n');
var readToAnyMethod = typeof(LazyString).GetRuntimeMethod("ReadToAny", new Type[]{typeof(int), typeof(char), typeof(char)});
_generator.Call(readToAnyMethod);
_generator.Duplicate();
Type tupleType = typeof(ValueTuple<int,char>);
_generator.LoadField(tupleType.GetRuntimeField("Item1"));
_generator.StoreLocal(_indexLocal);
//check for null
_generator.LoadField(tupleType.GetRuntimeField("Item2"));
_generator.LoadConstantInt32('n');
_generator.BranchIfNotEqualUnsigned(loopCheck);
//it's null
_generator.LoadLocal(_indexLocal);
_generator.LoadConstantInt32(4);
_generator.Add();
_generator.StoreLocal(_indexLocal);
var nullLocal = _generator.DeclareLocal(_jsonObjectType);
_generator.LoadLocalAddress(nullLocal);
_generator.InitObject(_jsonObjectType);
_generator.LoadLocal(nullLocal);
_generator.Branch(endLabel);
}
_generator.Branch(loopCheck);
//loop start
Label loopStart = _generator.DefineLabel();
_generator.Mark(loopStart);
//read to start of property
// int indexOfQuote = json.ReadTo(inputIndex, '\"');
_generator.LoadLocalAddress(_lazyStringLocal);
_generator.LoadLocal(_indexLocal);
_generator.LoadConstantInt32('\"');
var readToMethod = typeof(LazyString).GetRuntimeMethod("ReadTo", new Type[]{typeof(int), typeof(char)});
_generator.Call(readToMethod);
//int propertyStart = indexOfQuote + 1;
_generator.LoadConstantInt32(1);
_generator.Add();
//int propertyEnd = json.ReadTo(propertyStart, '\"');
_propertyStartLocal = _generator.DeclareLocal<int>();
_generator.StoreLocal(_propertyStartLocal);
_generator.LoadLocalAddress(_lazyStringLocal);
_generator.LoadLocal(_propertyStartLocal);
_generator.LoadConstantInt32('\"');
_generator.Call(readToMethod);
_propertyEndLocal = _generator.DeclareLocal<int>();
_generator.StoreLocal(_propertyEndLocal);
//var propertyName = json.SubString(propertyStart, propertyEnd - propertyStart);
_generator.LoadLocalAddress(_lazyStringLocal);
_generator.LoadLocal(_propertyStartLocal);
_generator.LoadLocal(_propertyEndLocal);
_generator.LoadLocal(_propertyStartLocal);
_generator.Subtract();
_generator.Call(typeof(LazyString).GetRuntimeMethod("SubString", new Type[]{typeof(int), typeof(int)}));
_propertyNameLocal = _generator.DeclareLocal<LazyString>();
_generator.StoreLocal(_propertyNameLocal);
//int intStart = json.ReadTo(propertyEnd + 1, ':') + 1;
_generator.LoadLocalAddress(_lazyStringLocal);
_generator.LoadLocal(_propertyEndLocal);
_generator.LoadConstantInt32(1);
_generator.Add();
_generator.LoadConstantInt32(':');
_generator.Call(readToMethod);
_generator.LoadConstantInt32(1);
_generator.Add();
_generator.StoreLocal(_indexLocal);
//properties
var unknownPropertyLabel = _generator.DefineLabel();
var propertiesQuery =
from property in _underlyingType.GetRuntimeProperties()
where property.CanWrite && property.GetCustomAttribute<IgnoreAttribute>(true) == null
select (IJsonPropertyInfo)new JsonPropertyInfo(property);
var fieldsQuery =
from field in _underlyingType.GetRuntimeFields()
where field.IsPublic && field.GetCustomAttribute<IgnoreAttribute>(true) == null
select (IJsonPropertyInfo)new JsonFieldInfo(field);
EmitProperties(propertiesQuery.Concat(fieldsQuery).ToArray(), loopCheck, unknownPropertyLabel);
//unknown property
_generator.Mark(unknownPropertyLabel);
_generator.LoadLocalAddress(_lazyStringLocal);
_generator.LoadLocal(_indexLocal);
_generator.Call(typeof(LazyString).GetRuntimeMethod("ReadToPropertyValueEnd", new Type[]{typeof(int)}));
_generator.StoreLocal(_indexLocal);
//loopCheck
_generator.Mark(loopCheck);
//skip whitespace
_generator.LoadLocalAddress(_lazyStringLocal);
_generator.LoadLocal(_indexLocal);
_generator.Call(typeof(LazyString).GetRuntimeMethod("SkipWhitespace", new Type[]{typeof(int)}));
_generator.StoreLocal(_indexLocal);
_generator.LoadArg(typeof(string), 1, false);
_generator.LoadLocal(_indexLocal);
_generator.CallVirtual(typeof(string).GetRuntimeMethod("get_Chars", new Type[]{typeof(int)}));
_generator.LoadConstantInt32('}');
_generator.BranchIfNotEqualUnsigned(loopStart);
//return
_generator.LoadLocal(_jsonObjectLocal);
if(_isNullable)
{
_generator.NewObject(_jsonObjectType.GetTypeInfo().GetConstructor(new []{_underlyingType}));
}
_generator.Mark(endLabel);
}
internal void EmitProperties(IJsonPropertyInfo[] properties, Label loopCheckLabel, Label unknownPropertyLabel)
{
var propertyHandlers = new List<Action>();
if(properties.Length == 0)
{
return;
}
EmitGroup(properties, propertyHandlers, loopCheckLabel, unknownPropertyLabel);
_generator.Branch(unknownPropertyLabel);
foreach(var propertyHandler in propertyHandlers)
{
propertyHandler();
}
}
void EmitGroup(IJsonPropertyInfo[] properties, List<Action> propertyHandlers, Label loopCheckLabel, Label unknownPropertyLabel)
{
var propertyHashFactory = new PropertyHashFactory();
var propertyNames = properties.Select(property => property.Name).ToArray();
var hashFunction = propertyHashFactory.FindBestHash(propertyNames);
var hashLocal = hashFunction.EmitHash(_generator, _propertyNameLocal);
var hashesQuery =
from property in properties
let hash = hashFunction.Hash(property.Name)
group property by hash into hashGroup
orderby hashGroup.Key
select hashGroup;
var hashes = hashesQuery.ToArray();
var switchGroups = FindSwitchGroups(hashes);
foreach(var switchGroup in switchGroups)
{
if(switchGroup.Count <= 2)
{
EmitIfGroup(switchGroup, propertyHandlers, unknownPropertyLabel, loopCheckLabel, hashLocal);
continue;
}
EmitSwitchGroup(switchGroup, propertyHandlers, unknownPropertyLabel, loopCheckLabel, hashLocal);
}
}
void EmitSwitchGroup(SwitchGroup switchGroup, List<Action> propertyHandlers, Label unknownPropertyLabel, Label loopCheckLabel, LocalBuilder hashLocal)
{
var jumpTable = new List<Label>();
int tableIndex = 0;
int offset = switchGroup[0].Key;
foreach(var hashGroup in switchGroup)
{
int hashValueIndex = hashGroup.Key - offset;
while(tableIndex != hashValueIndex)
{
//fill in gaps
tableIndex++;
jumpTable.Add(loopCheckLabel);
}
var propertyLabel = _generator.DefineLabel();
jumpTable.Add(propertyLabel);
propertyHandlers.Add(() =>
{
EmitPropertyHandler(propertyLabel, hashGroup, unknownPropertyLabel, loopCheckLabel);
});
tableIndex++;
}
//substract
_generator.LoadLocal(hashLocal);
if(offset != 0)
{
_generator.LoadConstantInt32(offset);
_generator.Subtract();
}
//switch
_generator.Switch(jumpTable.ToArray());
}
void EmitPropertyHandler(
Label propertyLabel, IGrouping<int, IJsonPropertyInfo> propertyHash,
Label unknownPropertyLabel, Label loopCheckLabel)
{
_generator.Mark(propertyLabel);
var subProperties = propertyHash.ToArray();
if(subProperties.Length != 1)
{
//there was a hash collision so need to nest
EmitProperties(subProperties, loopCheckLabel, unknownPropertyLabel);
return;
}
var property = subProperties[0];
_generator.LoadLocalAddress(_propertyNameLocal);
_generator.LoadString(property.Name);
_generator.Call(typeof(LazyString).GetRuntimeMethod("EqualsString", new Type[]{typeof(string)}));
_generator.BranchIfFalse(unknownPropertyLabel);
//Parse property value
_generator.LoadLocalAddress(_jsonObjectLocal);
_emitters.Emit(_indexLocal, property.Type);
property.EmitSetValue(_generator);
//_generator.Call(_underlyingType.GetRuntimeMethod($"set_{property.Name}", new Type[]{property.PropertyType}));
_generator.Branch(loopCheckLabel);
}
void EmitIfGroup(
SwitchGroup ifGroup, List<Action> propertyHandlers,
Label unknownPropertyLabel, Label loopCheckLabel, LocalBuilder hashLocal)
{
foreach(var hashGroup in ifGroup)
{
int hash = hashGroup.Key;
var propertyLabel = _generator.DefineLabel();
_generator.LoadLocal(hashLocal);
if(hash == 0)
{
_generator.BranchIfFalse(propertyLabel);
}
else
{
_generator.LoadConstantInt32(hash);
_generator.BranchIfEqual(propertyLabel);
}
propertyHandlers.Add(() =>
{
EmitPropertyHandler(propertyLabel, hashGroup, unknownPropertyLabel, loopCheckLabel);
});
}
}
IEnumerable<SwitchGroup> FindSwitchGroups(IGrouping<int, IJsonPropertyInfo>[] hashes)
{
int last = 0;
int gaps = 0;
var switchGroup = new SwitchGroup();
foreach(var grouping in hashes)
{
int hash = grouping.Key;
gaps += hash - last -1;
if(gaps > 8)
{
//to many gaps this switch group is finished
yield return switchGroup;
switchGroup = new SwitchGroup();
gaps = 0;
}
switchGroup.Add(grouping);
}
yield return switchGroup;
}
class SwitchGroup : List<IGrouping<int, IJsonPropertyInfo>>{}
internal override bool TypeSupported(Type type)
{
return type.GetTypeInfo().IsValueType && !type.GetTypeInfo().IsEnum;
}
internal override JsonPrimitive PrimitiveType => JsonPrimitive.Object;
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
namespace System.Security {
using System;
using System.Globalization;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
internal class SecurityRuntime
{
private SecurityRuntime(){}
// Returns the security object for the caller of the method containing
// 'stackMark' on its frame.
//
// THE RETURNED OBJECT IS THE LIVE RUNTIME OBJECT. BE CAREFUL WITH IT!
//
// Internal only, do not doc.
//
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern
FrameSecurityDescriptor GetSecurityObjectForFrame(ref StackCrawlMark stackMark,
bool create);
// Constants used to return status to native
internal const bool StackContinue = true;
internal const bool StackHalt = false;
// this method is a big perf hit, so don't call unnecessarily
[System.Security.SecurityCritical] // auto-generated
internal static MethodInfo GetMethodInfo(RuntimeMethodHandleInternal rmh)
{
if (rmh.IsNullHandle())
return null;
#if _DEBUG
try
{
#endif
// Assert here because reflection will check grants and if we fail the check,
// there will be an infinite recursion that overflows the stack.
PermissionSet.s_fullTrust.Assert();
return (System.RuntimeType.GetMethodBase(RuntimeMethodHandle.GetDeclaringType(rmh), rmh) as MethodInfo);
#if _DEBUG
}
catch(Exception)
{
return null;
}
#endif
}
[System.Security.SecurityCritical] // auto-generated
private static bool FrameDescSetHelper(FrameSecurityDescriptor secDesc,
PermissionSet demandSet,
out PermissionSet alteredDemandSet,
RuntimeMethodHandleInternal rmh)
{
return secDesc.CheckSetDemand(demandSet, out alteredDemandSet, rmh);
}
[System.Security.SecurityCritical] // auto-generated
private static bool FrameDescHelper(FrameSecurityDescriptor secDesc,
IPermission demandIn,
PermissionToken permToken,
RuntimeMethodHandleInternal rmh)
{
return secDesc.CheckDemand((CodeAccessPermission) demandIn, permToken, rmh);
}
#if FEATURE_COMPRESSEDSTACK
[System.Security.SecurityCritical]
private static bool CheckDynamicMethodSetHelper(System.Reflection.Emit.DynamicResolver dynamicResolver,
PermissionSet demandSet,
out PermissionSet alteredDemandSet,
RuntimeMethodHandleInternal rmh)
{
System.Threading.CompressedStack creationStack = dynamicResolver.GetSecurityContext();
bool result;
try
{
result = creationStack.CheckSetDemandWithModificationNoHalt(demandSet, out alteredDemandSet, rmh);
}
catch (SecurityException ex)
{
throw new SecurityException(Environment.GetResourceString("Security_AnonymouslyHostedDynamicMethodCheckFailed"), ex);
}
return result;
}
[System.Security.SecurityCritical]
private static bool CheckDynamicMethodHelper(System.Reflection.Emit.DynamicResolver dynamicResolver,
IPermission demandIn,
PermissionToken permToken,
RuntimeMethodHandleInternal rmh)
{
System.Threading.CompressedStack creationStack = dynamicResolver.GetSecurityContext();
bool result;
try
{
result = creationStack.CheckDemandNoHalt((CodeAccessPermission)demandIn, permToken, rmh);
}
catch (SecurityException ex)
{
throw new SecurityException(Environment.GetResourceString("Security_AnonymouslyHostedDynamicMethodCheckFailed"), ex);
}
return result;
}
#endif // FEATURE_COMPRESSEDSTACK
//
// API for PermissionSets
//
[System.Security.SecurityCritical] // auto-generated
internal static void Assert(PermissionSet permSet, ref StackCrawlMark stackMark)
{
// Note: if the "AssertPermission" is not a permission that implements IUnrestrictedPermission
// you need to change the fourth parameter to a zero.
FrameSecurityDescriptor secObj = CodeAccessSecurityEngine.CheckNReturnSO(
CodeAccessSecurityEngine.AssertPermissionToken,
CodeAccessSecurityEngine.AssertPermission,
ref stackMark,
1 );
Contract.Assert(secObj != null,"Failure in SecurityRuntime.Assert() - secObj != null");
if (secObj == null)
{
// Security: REQ_SQ flag is missing. Bad compiler ?
System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
}
else
{
if (secObj.HasImperativeAsserts())
throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
secObj.SetAssert(permSet);
}
}
[System.Security.SecurityCritical] // auto-generated
internal static void AssertAllPossible(ref StackCrawlMark stackMark)
{
FrameSecurityDescriptor secObj =
SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
Contract.Assert(secObj != null, "Failure in SecurityRuntime.AssertAllPossible() - secObj != null");
if (secObj == null)
{
// Security: REQ_SQ flag is missing. Bad compiler ?
System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
}
else
{
if (secObj.GetAssertAllPossible())
throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
secObj.SetAssertAllPossible();
}
}
[System.Security.SecurityCritical] // auto-generated
internal static void Deny(PermissionSet permSet, ref StackCrawlMark stackMark)
{
#if FEATURE_CAS_POLICY
// Deny is only valid in legacy mode
if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_CasDeny"));
}
#endif // FEATURE_CAS_POLICY
FrameSecurityDescriptor secObj =
SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
Contract.Assert(secObj != null, "Failure in SecurityRuntime.Deny() - secObj != null");
if (secObj == null)
{
// Security: REQ_SQ flag is missing. Bad compiler ?
System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
}
else
{
if (secObj.HasImperativeDenials())
throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
secObj.SetDeny(permSet);
}
}
[System.Security.SecurityCritical] // auto-generated
internal static void PermitOnly(PermissionSet permSet, ref StackCrawlMark stackMark)
{
FrameSecurityDescriptor secObj =
SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
Contract.Assert(secObj != null, "Failure in SecurityRuntime.PermitOnly() - secObj != null");
if (secObj == null)
{
// Security: REQ_SQ flag is missing. Bad compiler ?
System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
}
else
{
if (secObj.HasImperativeRestrictions())
throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
secObj.SetPermitOnly(permSet);
}
}
//
// Revert API
//
[System.Security.SecurityCritical] // auto-generated
internal static void RevertAssert(ref StackCrawlMark stackMark)
{
FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false);
if (secObj != null)
{
secObj.RevertAssert();
}
else
{
throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
}
}
[System.Security.SecurityCritical] // auto-generated
internal static void RevertDeny(ref StackCrawlMark stackMark)
{
FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false);
if (secObj != null)
{
secObj.RevertDeny();
}
else
{
throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
}
}
[System.Security.SecurityCritical] // auto-generated
internal static void RevertPermitOnly(ref StackCrawlMark stackMark)
{
FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false);
if (secObj != null)
{
secObj.RevertPermitOnly();
}
else
{
throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
}
}
[System.Security.SecurityCritical] // auto-generated
internal static void RevertAll(ref StackCrawlMark stackMark)
{
FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false);
if (secObj != null)
{
secObj.RevertAll();
}
else
{
throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Formatters.Xml;
using Microsoft.AspNetCore.Mvc.Testing;
using XmlFormattersWebSite;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.FunctionalTests
{
public class XmlSerializerFormattersWrappingTest : IClassFixture<MvcTestFixture<Startup>>
{
public XmlSerializerFormattersWrappingTest(MvcTestFixture<Startup> fixture)
{
Factory = fixture.Factories.FirstOrDefault() ?? fixture.WithWebHostBuilder(builder => builder.UseStartup<Startup>());
Client = Factory.CreateDefaultClient();
}
public WebApplicationFactory<Startup> Factory { get; }
public HttpClient Client { get; }
[Theory]
[InlineData("http://localhost/IEnumerable/ValueTypes")]
[InlineData("http://localhost/IQueryable/ValueTypes")]
public async Task CanWrite_ValueTypes(string url)
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfInt xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><int>10</int>" +
"<int>20</int></ArrayOfInt>",
result);
}
[Theory]
[InlineData("http://localhost/IEnumerable/NonWrappedTypes")]
[InlineData("http://localhost/IQueryable/NonWrappedTypes")]
public async Task CanWrite_NonWrappedTypes(string url)
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfString xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><string>value1</string>" +
"<string>value2</string></ArrayOfString>",
result);
}
[Theory]
[InlineData("http://localhost/IEnumerable/NonWrappedTypes_NullInstance")]
[InlineData("http://localhost/IQueryable/NonWrappedTypes_NullInstance")]
public async Task CanWrite_NonWrappedTypes_NullInstance(string url)
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfString xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xsi:nil=\"true\" />",
result);
}
[Theory]
[InlineData("http://localhost/IEnumerable/NonWrappedTypes_Empty")]
[InlineData("http://localhost/IQueryable/NonWrappedTypes_Empty")]
public async Task CanWrite_NonWrappedTypes_Empty(string url)
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfString xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" />",
result);
}
[Theory]
[InlineData("http://localhost/IEnumerable/WrappedTypes")]
[InlineData("http://localhost/IQueryable/WrappedTypes")]
public async Task CanWrite_WrappedTypes(string url)
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfPersonWrapper xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><PersonWrapper><Id>10</Id>" +
"<Name>Mike</Name><Age>35</Age></PersonWrapper><PersonWrapper><Id>11</Id>" +
"<Name>Jimmy</Name><Age>35</Age></PersonWrapper></ArrayOfPersonWrapper>",
result);
}
[Theory]
[InlineData("http://localhost/IEnumerable/WrappedTypes_Empty")]
[InlineData("http://localhost/IQueryable/WrappedTypes_Empty")]
public async Task CanWrite_WrappedTypes_Empty(string url)
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfPersonWrapper xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" />",
result);
}
[Theory]
[InlineData("http://localhost/IEnumerable/WrappedTypes_NullInstance")]
[InlineData("http://localhost/IQueryable/WrappedTypes_NullInstance")]
public async Task CanWrite_WrappedTypes_NullInstance(string url)
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfPersonWrapper xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xsi:nil=\"true\" />",
result);
}
[Fact]
public async Task CanWrite_IEnumerableOf_SerializableErrors()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/IEnumerable/SerializableErrors");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfSerializableErrorWrapper xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><SerializableErrorWrapper><key1>key1-error</key1>" +
"<key2>key2-error</key2></SerializableErrorWrapper><SerializableErrorWrapper><key3>key1-error</key3>" +
"<key4>key2-error</key4></SerializableErrorWrapper></ArrayOfSerializableErrorWrapper>",
result);
}
[Fact]
public async Task ProblemDetails_IsSerialized()
{
// Arrange
using (new ActivityReplacer())
{
var expected = "<problem xmlns=\"urn:ietf:rfc:7807\">" +
"<status>404</status>" +
"<title>Not Found</title>" +
"<type>https://tools.ietf.org/html/rfc7231#section-6.5.4</type>" +
$"<traceId>{Activity.Current.Id}</traceId>" +
"</problem>";
// Act
var response = await Client.GetAsync("/api/XmlSerializerApi/ActionReturningClientErrorStatusCodeResult");
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.NotFound);
var content = await response.Content.ReadAsStringAsync();
var root = XDocument.Parse(content).Root;
Assert.Equal("404", root.Element(root.Name.Namespace.GetName("status"))?.Value);
Assert.Equal("Not Found", root.Element(root.Name.Namespace.GetName("title"))?.Value);
Assert.Equal("https://tools.ietf.org/html/rfc7231#section-6.5.4", root.Element(root.Name.Namespace.GetName("type"))?.Value);
// Activity is not null
Assert.NotNull(root.Element(root.Name.Namespace.GetName("traceId"))?.Value);
}
}
[Fact]
public async Task ProblemDetails_WithExtensionMembers_IsSerialized()
{
// Arrange
var expected = "<problem xmlns=\"urn:ietf:rfc:7807\">" +
"<instance>instance</instance>" +
"<status>404</status>" +
"<title>title</title>" +
"<Correlation>correlation</Correlation>" +
"<Accounts>Account1 Account2</Accounts>" +
"</problem>";
// Act
var response = await Client.GetAsync("/api/XmlSerializerApi/ActionReturningProblemDetails");
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.NotFound);
var content = await response.Content.ReadAsStringAsync();
XmlAssert.Equal(expected, content);
}
[Fact]
public async Task ValidationProblemDetails_IsSerialized()
{
// Arrange
using (new ActivityReplacer())
{
// Act
var response = await Client.GetAsync("/api/XmlSerializerApi/ActionReturningValidationProblem");
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.BadRequest);
var content = await response.Content.ReadAsStringAsync();
var root = XDocument.Parse(content).Root;
Assert.Equal("400", root.Element(root.Name.Namespace.GetName("status"))?.Value);
Assert.Equal("One or more validation errors occurred.", root.Element(root.Name.Namespace.GetName("title"))?.Value);
var mvcErrors = root.Element(root.Name.Namespace.GetName("MVC-Errors"));
Assert.NotNull(mvcErrors);
Assert.Equal("The State field is required.", mvcErrors.Element(root.Name.Namespace.GetName("State"))?.Value);
// Activity is not null
Assert.NotNull(root.Element(root.Name.Namespace.GetName("traceId"))?.Value);
}
}
[Fact]
public async Task ValidationProblemDetails_WithExtensionMembers_IsSerialized()
{
// Arrange
var expected = "<problem xmlns=\"urn:ietf:rfc:7807\">" +
"<detail>some detail</detail>" +
"<status>400</status>" +
"<title>One or more validation errors occurred.</title>" +
"<type>some type</type>" +
"<CorrelationId>correlation</CorrelationId>" +
"<MVC-Errors>" +
"<Error1>ErrorValue</Error1>" +
"</MVC-Errors>" +
"</problem>";
// Act
var response = await Client.GetAsync("/api/XmlSerializerApi/ActionReturningValidationDetailsWithMetadata");
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.BadRequest);
var content = await response.Content.ReadAsStringAsync();
XmlAssert.Equal(expected, content);
}
}
}
| |
namespace java.nio.channels
{
[global::MonoJavaBridge.JavaClass(typeof(global::java.nio.channels.FileChannel_))]
public abstract partial class FileChannel : java.nio.channels.spi.AbstractInterruptibleChannel, ByteChannel, GatheringByteChannel, ScatteringByteChannel
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected FileChannel(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public partial class MapMode : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected MapMode(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override global::java.lang.String toString()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.nio.channels.FileChannel.MapMode.staticClass, "toString", "()Ljava/lang/String;", ref global::java.nio.channels.FileChannel.MapMode._m0) as java.lang.String;
}
internal static global::MonoJavaBridge.FieldId _READ_ONLY6509;
public static global::java.nio.channels.FileChannel.MapMode READ_ONLY
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.nio.channels.FileChannel.MapMode.staticClass, _READ_ONLY6509)) as java.nio.channels.FileChannel.MapMode;
}
}
internal static global::MonoJavaBridge.FieldId _READ_WRITE6510;
public static global::java.nio.channels.FileChannel.MapMode READ_WRITE
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.nio.channels.FileChannel.MapMode.staticClass, _READ_WRITE6510)) as java.nio.channels.FileChannel.MapMode;
}
}
internal static global::MonoJavaBridge.FieldId _PRIVATE6511;
public static global::java.nio.channels.FileChannel.MapMode PRIVATE
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.nio.channels.FileChannel.MapMode.staticClass, _PRIVATE6511)) as java.nio.channels.FileChannel.MapMode;
}
}
static MapMode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.FileChannel.MapMode.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/FileChannel$MapMode"));
global::java.nio.channels.FileChannel.MapMode._READ_ONLY6509 = @__env.GetStaticFieldIDNoThrow(global::java.nio.channels.FileChannel.MapMode.staticClass, "READ_ONLY", "Ljava/nio/channels/FileChannel$MapMode;");
global::java.nio.channels.FileChannel.MapMode._READ_WRITE6510 = @__env.GetStaticFieldIDNoThrow(global::java.nio.channels.FileChannel.MapMode.staticClass, "READ_WRITE", "Ljava/nio/channels/FileChannel$MapMode;");
global::java.nio.channels.FileChannel.MapMode._PRIVATE6511 = @__env.GetStaticFieldIDNoThrow(global::java.nio.channels.FileChannel.MapMode.staticClass, "PRIVATE", "Ljava/nio/channels/FileChannel$MapMode;");
}
}
private static global::MonoJavaBridge.MethodId _m0;
public abstract global::java.nio.channels.FileLock @lock(long arg0, long arg1, bool arg2);
private static global::MonoJavaBridge.MethodId _m1;
public virtual global::java.nio.channels.FileLock @lock()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.channels.FileChannel.staticClass, "@lock", "()Ljava/nio/channels/FileLock;", ref global::java.nio.channels.FileChannel._m1) as java.nio.channels.FileLock;
}
private static global::MonoJavaBridge.MethodId _m2;
public abstract long size();
private static global::MonoJavaBridge.MethodId _m3;
public abstract long position();
private static global::MonoJavaBridge.MethodId _m4;
public abstract global::java.nio.channels.FileChannel position(long arg0);
private static global::MonoJavaBridge.MethodId _m5;
public abstract int write(java.nio.ByteBuffer arg0, long arg1);
private static global::MonoJavaBridge.MethodId _m6;
public abstract int write(java.nio.ByteBuffer arg0);
private static global::MonoJavaBridge.MethodId _m7;
public abstract long write(java.nio.ByteBuffer[] arg0, int arg1, int arg2);
private static global::MonoJavaBridge.MethodId _m8;
public virtual long write(java.nio.ByteBuffer[] arg0)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.channels.FileChannel.staticClass, "write", "([Ljava/nio/ByteBuffer;)J", ref global::java.nio.channels.FileChannel._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m9;
public abstract global::java.nio.MappedByteBuffer map(java.nio.channels.FileChannel.MapMode arg0, long arg1, long arg2);
private static global::MonoJavaBridge.MethodId _m10;
public virtual long read(java.nio.ByteBuffer[] arg0)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.channels.FileChannel.staticClass, "read", "([Ljava/nio/ByteBuffer;)J", ref global::java.nio.channels.FileChannel._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m11;
public abstract long read(java.nio.ByteBuffer[] arg0, int arg1, int arg2);
private static global::MonoJavaBridge.MethodId _m12;
public abstract int read(java.nio.ByteBuffer arg0);
private static global::MonoJavaBridge.MethodId _m13;
public abstract int read(java.nio.ByteBuffer arg0, long arg1);
private static global::MonoJavaBridge.MethodId _m14;
public virtual global::java.nio.channels.FileLock tryLock()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.channels.FileChannel.staticClass, "tryLock", "()Ljava/nio/channels/FileLock;", ref global::java.nio.channels.FileChannel._m14) as java.nio.channels.FileLock;
}
private static global::MonoJavaBridge.MethodId _m15;
public abstract global::java.nio.channels.FileLock tryLock(long arg0, long arg1, bool arg2);
private static global::MonoJavaBridge.MethodId _m16;
public abstract global::java.nio.channels.FileChannel truncate(long arg0);
private static global::MonoJavaBridge.MethodId _m17;
public abstract void force(bool arg0);
private static global::MonoJavaBridge.MethodId _m18;
public abstract long transferTo(long arg0, long arg1, java.nio.channels.WritableByteChannel arg2);
private static global::MonoJavaBridge.MethodId _m19;
public abstract long transferFrom(java.nio.channels.ReadableByteChannel arg0, long arg1, long arg2);
private static global::MonoJavaBridge.MethodId _m20;
protected FileChannel() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.nio.channels.FileChannel._m20.native == global::System.IntPtr.Zero)
global::java.nio.channels.FileChannel._m20 = @__env.GetMethodIDNoThrow(global::java.nio.channels.FileChannel.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.nio.channels.FileChannel.staticClass, global::java.nio.channels.FileChannel._m20);
Init(@__env, handle);
}
static FileChannel()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.FileChannel.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/FileChannel"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.nio.channels.FileChannel))]
internal sealed partial class FileChannel_ : java.nio.channels.FileChannel
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal FileChannel_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override global::java.nio.channels.FileLock @lock(long arg0, long arg1, bool arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.channels.FileChannel_.staticClass, "@lock", "(JJZ)Ljava/nio/channels/FileLock;", ref global::java.nio.channels.FileChannel_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.nio.channels.FileLock;
}
private static global::MonoJavaBridge.MethodId _m1;
public override long size()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.channels.FileChannel_.staticClass, "size", "()J", ref global::java.nio.channels.FileChannel_._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
public override long position()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.channels.FileChannel_.staticClass, "position", "()J", ref global::java.nio.channels.FileChannel_._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public override global::java.nio.channels.FileChannel position(long arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.channels.FileChannel_.staticClass, "position", "(J)Ljava/nio/channels/FileChannel;", ref global::java.nio.channels.FileChannel_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.nio.channels.FileChannel;
}
private static global::MonoJavaBridge.MethodId _m4;
public override int write(java.nio.ByteBuffer arg0, long arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.nio.channels.FileChannel_.staticClass, "write", "(Ljava/nio/ByteBuffer;J)I", ref global::java.nio.channels.FileChannel_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m5;
public override int write(java.nio.ByteBuffer arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.nio.channels.FileChannel_.staticClass, "write", "(Ljava/nio/ByteBuffer;)I", ref global::java.nio.channels.FileChannel_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public override long write(java.nio.ByteBuffer[] arg0, int arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.channels.FileChannel_.staticClass, "write", "([Ljava/nio/ByteBuffer;II)J", ref global::java.nio.channels.FileChannel_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m7;
public override global::java.nio.MappedByteBuffer map(java.nio.channels.FileChannel.MapMode arg0, long arg1, long arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.channels.FileChannel_.staticClass, "map", "(Ljava/nio/channels/FileChannel$MapMode;JJ)Ljava/nio/MappedByteBuffer;", ref global::java.nio.channels.FileChannel_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.nio.MappedByteBuffer;
}
private static global::MonoJavaBridge.MethodId _m8;
public override long read(java.nio.ByteBuffer[] arg0, int arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.channels.FileChannel_.staticClass, "read", "([Ljava/nio/ByteBuffer;II)J", ref global::java.nio.channels.FileChannel_._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m9;
public override int read(java.nio.ByteBuffer arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.nio.channels.FileChannel_.staticClass, "read", "(Ljava/nio/ByteBuffer;)I", ref global::java.nio.channels.FileChannel_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public override int read(java.nio.ByteBuffer arg0, long arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.nio.channels.FileChannel_.staticClass, "read", "(Ljava/nio/ByteBuffer;J)I", ref global::java.nio.channels.FileChannel_._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m11;
public override global::java.nio.channels.FileLock tryLock(long arg0, long arg1, bool arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.channels.FileChannel_.staticClass, "tryLock", "(JJZ)Ljava/nio/channels/FileLock;", ref global::java.nio.channels.FileChannel_._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.nio.channels.FileLock;
}
private static global::MonoJavaBridge.MethodId _m12;
public override global::java.nio.channels.FileChannel truncate(long arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.channels.FileChannel_.staticClass, "truncate", "(J)Ljava/nio/channels/FileChannel;", ref global::java.nio.channels.FileChannel_._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.nio.channels.FileChannel;
}
private static global::MonoJavaBridge.MethodId _m13;
public override void force(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.nio.channels.FileChannel_.staticClass, "force", "(Z)V", ref global::java.nio.channels.FileChannel_._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m14;
public override long transferTo(long arg0, long arg1, java.nio.channels.WritableByteChannel arg2)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.channels.FileChannel_.staticClass, "transferTo", "(JJLjava/nio/channels/WritableByteChannel;)J", ref global::java.nio.channels.FileChannel_._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m15;
public override long transferFrom(java.nio.channels.ReadableByteChannel arg0, long arg1, long arg2)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.channels.FileChannel_.staticClass, "transferFrom", "(Ljava/nio/channels/ReadableByteChannel;JJ)J", ref global::java.nio.channels.FileChannel_._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m16;
protected override void implCloseChannel()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.nio.channels.FileChannel_.staticClass, "implCloseChannel", "()V", ref global::java.nio.channels.FileChannel_._m16);
}
static FileChannel_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.FileChannel_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/FileChannel"));
}
}
}
| |
//
// HttpHeaders.cs
//
// Authors:
// Marek Safar <marek.safar@gmail.com>
//
// Copyright (C) 2011 Xamarin Inc (http://www.xamarin.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.Collections;
using System.Collections.Generic;
using System.Text;
namespace System.Net.Http.Headers
{
public abstract class HttpHeaders : IEnumerable<KeyValuePair<string, IEnumerable<string>>>
{
class HeaderBucket
{
//
// headers can hold an object of 3 kinds
// - simple type for parsed single values (e.g. DateTime)
// - CollectionHeader for multi-value headers
// - List<string> for not checked single values
//
public object Parsed;
List<string> values;
public readonly Func<object, string> CustomToString;
public HeaderBucket (object parsed, Func<object, string> converter = null)
{
this.Parsed = parsed;
this.CustomToString = converter;
}
public bool HasStringValues {
get {
return values != null && values.Count > 0;
}
}
public List<string> Values {
get {
return values ?? (values = new List<string> ());
}
set {
values = value;
}
}
public string ParsedToString ()
{
if (Parsed == null)
return null;
if (CustomToString != null)
return CustomToString (Parsed);
return Parsed.ToString ();
}
}
static readonly Dictionary<string, HeaderInfo> known_headers;
static HttpHeaders ()
{
var headers = new[] {
HeaderInfo.CreateMulti<MediaTypeWithQualityHeaderValue> ("Accept", MediaTypeWithQualityHeaderValue.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateMulti<StringWithQualityHeaderValue> ("Accept-Charset", StringWithQualityHeaderValue.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateMulti<StringWithQualityHeaderValue> ("Accept-Encoding", StringWithQualityHeaderValue.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateMulti<StringWithQualityHeaderValue> ("Accept-Language", StringWithQualityHeaderValue.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateMulti<string> ("Accept-Ranges", CollectionParser.TryParse, HttpHeaderKind.Response),
HeaderInfo.CreateSingle<TimeSpan> ("Age", Parser.TimeSpanSeconds.TryParse, HttpHeaderKind.Response),
HeaderInfo.CreateMulti<string> ("Allow", CollectionParser.TryParse, HttpHeaderKind.Content, 0),
HeaderInfo.CreateSingle<AuthenticationHeaderValue> ("Authorization", AuthenticationHeaderValue.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateSingle<CacheControlHeaderValue> ("Cache-Control", CacheControlHeaderValue.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
HeaderInfo.CreateMulti<string> ("Connection", CollectionParser.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
HeaderInfo.CreateMulti<string> ("Content-Encoding", CollectionParser.TryParse, HttpHeaderKind.Content),
HeaderInfo.CreateMulti<string> ("Content-Language", CollectionParser.TryParse, HttpHeaderKind.Content),
HeaderInfo.CreateSingle<long> ("Content-Length", Parser.Long.TryParse, HttpHeaderKind.Content),
HeaderInfo.CreateSingle<Uri> ("Content-Location", Parser.Uri.TryParse, HttpHeaderKind.Content),
HeaderInfo.CreateSingle<byte[]> ("Content-MD5", Parser.MD5.TryParse, HttpHeaderKind.Content),
HeaderInfo.CreateSingle<ContentRangeHeaderValue> ("Content-Range", ContentRangeHeaderValue.TryParse, HttpHeaderKind.Content),
HeaderInfo.CreateSingle<MediaTypeHeaderValue> ("Content-Type", MediaTypeHeaderValue.TryParse, HttpHeaderKind.Content),
HeaderInfo.CreateSingle<DateTimeOffset> ("Date", Parser.DateTime.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
HeaderInfo.CreateSingle<EntityTagHeaderValue> ("ETag", EntityTagHeaderValue.TryParse, HttpHeaderKind.Response),
HeaderInfo.CreateMulti<NameValueWithParametersHeaderValue> ("Expect", NameValueWithParametersHeaderValue.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateSingle<DateTimeOffset> ("Expires", Parser.DateTime.TryParse, HttpHeaderKind.Content),
HeaderInfo.CreateSingle<string> ("From", Parser.EmailAddress.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateSingle<Uri> ("Host", Parser.Uri.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateMulti<EntityTagHeaderValue> ("If-Match", EntityTagHeaderValue.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateSingle<DateTimeOffset> ("If-Modified-Since", Parser.DateTime.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateMulti<EntityTagHeaderValue> ("If-None-Match", EntityTagHeaderValue.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateSingle<RangeConditionHeaderValue> ("If-Range", RangeConditionHeaderValue.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateSingle<DateTimeOffset> ("If-Unmodified-Since", Parser.DateTime.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateSingle<DateTimeOffset> ("Last-Modified", Parser.DateTime.TryParse, HttpHeaderKind.Content),
HeaderInfo.CreateSingle<Uri> ("Location", Parser.Uri.TryParse, HttpHeaderKind.Response),
HeaderInfo.CreateSingle<int> ("Max-Forwards", Parser.Int.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateMulti<NameValueHeaderValue> ("Pragma", NameValueHeaderValue.TryParsePragma, HttpHeaderKind.Request | HttpHeaderKind.Response),
HeaderInfo.CreateMulti<AuthenticationHeaderValue> ("Proxy-Authenticate", AuthenticationHeaderValue.TryParse, HttpHeaderKind.Response),
HeaderInfo.CreateSingle<AuthenticationHeaderValue> ("Proxy-Authorization", AuthenticationHeaderValue.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateSingle<RangeHeaderValue> ("Range", RangeHeaderValue.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateSingle<Uri> ("Referer", Parser.Uri.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateSingle<RetryConditionHeaderValue> ("Retry-After", RetryConditionHeaderValue.TryParse, HttpHeaderKind.Response),
HeaderInfo.CreateMulti<ProductInfoHeaderValue> ("Server", ProductInfoHeaderValue.TryParse, HttpHeaderKind.Response),
HeaderInfo.CreateMulti<TransferCodingWithQualityHeaderValue> ("TE", TransferCodingWithQualityHeaderValue.TryParse, HttpHeaderKind.Request, 0),
HeaderInfo.CreateMulti<string> ("Trailer", CollectionParser.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
HeaderInfo.CreateMulti<TransferCodingHeaderValue> ("Transfer-Encoding", TransferCodingHeaderValue.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
HeaderInfo.CreateMulti<ProductHeaderValue> ("Upgrade", ProductHeaderValue.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
HeaderInfo.CreateMulti<ProductInfoHeaderValue> ("User-Agent", ProductInfoHeaderValue.TryParse, HttpHeaderKind.Request),
HeaderInfo.CreateMulti<string> ("Vary", CollectionParser.TryParse, HttpHeaderKind.Response),
HeaderInfo.CreateMulti<ViaHeaderValue> ("Via", ViaHeaderValue.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
HeaderInfo.CreateMulti<WarningHeaderValue> ("Warning", WarningHeaderValue.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
HeaderInfo.CreateMulti<AuthenticationHeaderValue> ("WWW-Authenticate", AuthenticationHeaderValue.TryParse, HttpHeaderKind.Response)
};
known_headers = new Dictionary<string, HeaderInfo> (StringComparer.OrdinalIgnoreCase);
foreach (var header in headers) {
known_headers.Add (header.Name, header);
}
}
readonly Dictionary<string, HeaderBucket> headers;
readonly HttpHeaderKind HeaderKind;
internal bool? connectionclose, transferEncodingChunked;
protected HttpHeaders ()
{
headers = new Dictionary<string, HeaderBucket> (StringComparer.OrdinalIgnoreCase);
}
internal HttpHeaders (HttpHeaderKind headerKind)
: this ()
{
this.HeaderKind = headerKind;
}
public void Add (string name, string value)
{
Add (name, new[] { value });
}
public void Add (string name, IEnumerable<string> values)
{
if (values == null)
throw new ArgumentNullException ("values");
AddInternal (name, values, CheckName (name), false);
}
internal bool AddValue (string value, HeaderInfo headerInfo, bool ignoreInvalid)
{
return AddInternal (headerInfo.Name, new [] { value }, headerInfo, ignoreInvalid);
}
bool AddInternal (string name, IEnumerable<string> values, HeaderInfo headerInfo, bool ignoreInvalid)
{
HeaderBucket bucket;
headers.TryGetValue (name, out bucket);
bool ok = true;
foreach (var value in values) {
bool first_entry = bucket == null;
if (headerInfo != null) {
object parsed_value;
if (!headerInfo.TryParse (value, out parsed_value)) {
if (ignoreInvalid) {
ok = false;
continue;
}
throw new FormatException ();
}
if (headerInfo.AllowsMany) {
if (bucket == null)
bucket = new HeaderBucket (headerInfo.CreateCollection (this));
headerInfo.AddToCollection (bucket.Parsed, parsed_value);
} else {
if (bucket != null)
throw new FormatException ();
bucket = new HeaderBucket (parsed_value);
}
} else {
if (bucket == null)
bucket = new HeaderBucket (null);
bucket.Values.Add (value ?? string.Empty);
}
if (first_entry) {
headers.Add (name, bucket);
}
}
return ok;
}
public bool TryAddWithoutValidation (string name, string value)
{
return TryAddWithoutValidation (name, new[] { value });
}
public bool TryAddWithoutValidation (string name, IEnumerable<string> values)
{
if (values == null)
throw new ArgumentNullException ("values");
HeaderInfo headerInfo;
if (!TryCheckName (name, out headerInfo))
return false;
AddInternal (name, values, null, true);
return true;
}
HeaderInfo CheckName (string name)
{
if (string.IsNullOrEmpty (name))
throw new ArgumentException ("name");
Parser.Token.Check (name);
HeaderInfo headerInfo;
if (known_headers.TryGetValue (name, out headerInfo) && (headerInfo.HeaderKind & HeaderKind) == 0) {
if (HeaderKind != HttpHeaderKind.None && ((HeaderKind | headerInfo.HeaderKind) & HttpHeaderKind.Content) != 0)
throw new InvalidOperationException (name);
return null;
}
return headerInfo;
}
bool TryCheckName (string name, out HeaderInfo headerInfo)
{
if (!Parser.Token.TryCheck (name)) {
headerInfo = null;
return false;
}
if (known_headers.TryGetValue (name, out headerInfo) && (headerInfo.HeaderKind & HeaderKind) == 0) {
if (HeaderKind != HttpHeaderKind.None && ((HeaderKind | headerInfo.HeaderKind) & HttpHeaderKind.Content) != 0)
return false;
}
return true;
}
public void Clear ()
{
connectionclose = null;
transferEncodingChunked = null;
headers.Clear ();
}
public bool Contains (string name)
{
CheckName (name);
return headers.ContainsKey (name);
}
public IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator ()
{
foreach (var entry in headers) {
var bucket = headers[entry.Key];
HeaderInfo headerInfo;
known_headers.TryGetValue (entry.Key, out headerInfo);
var svalues = GetAllHeaderValues (bucket, headerInfo);
if (svalues == null)
continue;
yield return new KeyValuePair<string, IEnumerable<string>> (entry.Key, svalues);
}
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
public IEnumerable<string> GetValues (string name)
{
CheckName (name);
IEnumerable<string> values;
if (!TryGetValues (name, out values))
throw new InvalidOperationException ();
return values;
}
public bool Remove (string name)
{
CheckName (name);
return headers.Remove (name);
}
public bool TryGetValues (string name, out IEnumerable<string> values)
{
HeaderInfo headerInfo;
if (!TryCheckName (name, out headerInfo)) {
values = null;
return false;
}
HeaderBucket bucket;
if (!headers.TryGetValue (name, out bucket)) {
values = null;
return false;
}
values = GetAllHeaderValues (bucket, headerInfo);
return true;
}
public override string ToString ()
{
var sb = new StringBuilder ();
foreach (var entry in this) {
sb.Append (entry.Key);
sb.Append (": ");
bool first = true;
foreach (var v in entry.Value) {
if (!first)
sb.Append (", ");
sb.Append (v);
first = false;
}
sb.Append ("\r\n");
}
return sb.ToString ();
}
internal void AddOrRemove (string name, string value)
{
if (string.IsNullOrEmpty (value))
Remove (name);
else
SetValue (name, value);
}
internal void AddOrRemove<T> (string name, T value, Func<object, string> converter = null) where T : class
{
if (value == null)
Remove (name);
else
SetValue (name, value, converter);
}
internal void AddOrRemove<T> (string name, T? value) where T : struct
{
AddOrRemove<T> (name, value, null);
}
internal void AddOrRemove<T> (string name, T? value, Func<object, string> converter) where T : struct
{
if (!value.HasValue)
Remove (name);
else
SetValue (name, value, converter);
}
List<string> GetAllHeaderValues (HeaderBucket bucket, HeaderInfo headerInfo)
{
List<string> string_values = null;
if (headerInfo != null && headerInfo.AllowsMany) {
string_values = headerInfo.ToStringCollection (bucket.Parsed);
} else {
if (bucket.Parsed != null) {
string s = bucket.ParsedToString ();
if (!string.IsNullOrEmpty (s)) {
string_values = new List<string> ();
string_values.Add (s);
}
}
}
if (bucket.HasStringValues) {
if (string_values == null)
string_values = new List<string> ();
string_values.AddRange (bucket.Values);
}
return string_values;
}
internal static HttpHeaderKind GetKnownHeaderKind (string name)
{
if (string.IsNullOrEmpty (name))
throw new ArgumentException ("name");
HeaderInfo headerInfo;
if (known_headers.TryGetValue (name, out headerInfo))
return headerInfo.HeaderKind;
return HttpHeaderKind.None;
}
internal T GetValue<T> (string name)
{
HeaderBucket value;
if (!headers.TryGetValue (name, out value))
return default (T);
if (value.HasStringValues) {
var hinfo = known_headers[name];
object pvalue;
if (!hinfo.TryParse (value.Values [0], out pvalue)) {
return typeof (T) == typeof (string) ? (T) (object) value.Values[0] : default (T);
}
value.Parsed = pvalue;
value.Values = null;
}
return (T) value.Parsed;
}
internal HttpHeaderValueCollection<T> GetValues<T> (string name) where T : class
{
HeaderBucket value;
if (!headers.TryGetValue (name, out value)) {
value = new HeaderBucket (new HttpHeaderValueCollection<T> (this, known_headers [name]));
headers.Add (name, value);
}
if (value.HasStringValues) {
var hinfo = known_headers[name];
if (value.Parsed == null)
value.Parsed = hinfo.CreateCollection (this);
object pvalue;
for (int i = 0; i < value.Values.Count; ++i) {
if (!hinfo.TryParse (value.Values[i], out pvalue))
continue;
hinfo.AddToCollection (value.Parsed, pvalue);
value.Values.RemoveAt (i);
--i;
}
}
return (HttpHeaderValueCollection<T>) value.Parsed;
}
void SetValue<T> (string name, T value, Func<object, string> toStringConverter = null)
{
headers[name] = new HeaderBucket (value, toStringConverter);
}
}
}
| |
using System;
using StructureMap.Configuration.DSL;
using StructureMap.Interceptors;
namespace StructureMap.Pipeline
{
public partial class ConfiguredInstance
{
[Obsolete("Change to Named()")]
public ConfiguredInstance WithName(string instanceKey)
{
Name = instanceKey;
return this;
}
public ConfiguredInstance Named(string instanceKey)
{
Name = instanceKey;
return this;
}
/// <summary>
/// Register an Action to perform on the object created by this Instance
/// before it is returned to the caller
/// </summary>
/// <typeparam name="TYPE"></typeparam>
/// <param name="handler"></param>
/// <returns></returns>
public ConfiguredInstance OnCreation<TYPE>(Action<TYPE> handler)
{
var interceptor = new StartupInterceptor<TYPE>((c, o) => handler(o));
Interceptor = interceptor;
return this;
}
/// <summary>
/// Register an Action to perform on the object created by this Instance
/// before it is returned to the caller
/// </summary>
/// <typeparam name="TYPE"></typeparam>
/// <param name="handler"></param>
/// <returns></returns>
public ConfiguredInstance OnCreation<TYPE>(Action<IContext, TYPE> handler)
{
var interceptor = new StartupInterceptor<TYPE>(handler);
Interceptor = interceptor;
return this;
}
/// <summary>
/// Register a Func to potentially enrich or substitute for the object
/// created by this Instance before it is returned to the caller
/// </summary>
/// <param name="handler"></param>
/// <returns></returns>
public ConfiguredInstance EnrichWith<TYPE>(EnrichmentHandler<TYPE> handler)
{
var interceptor = new EnrichmentInterceptor<TYPE>((c, o) => handler(o));
Interceptor = interceptor;
return this;
}
/// <summary>
/// Register a Func to potentially enrich or substitute for the object
/// created by this Instance before it is returned to the caller
/// </summary>
/// <param name="handler"></param>
/// <returns></returns>
public ConfiguredInstance EnrichWith<TYPE>(ContextEnrichmentHandler<TYPE> handler)
{
var interceptor = new EnrichmentInterceptor<TYPE>(handler);
Interceptor = interceptor;
return this;
}
/// <summary>
/// Inline definition of a dependency array like IService[] or IHandler[]
/// </summary>
/// <typeparam name="PLUGINTYPE"></typeparam>
/// <param name="propertyName"></param>
/// <returns></returns>
public ChildArrayExpression ChildArray<PLUGINTYPE>(string propertyName)
{
var expression =
new ChildArrayExpression(this, propertyName);
return expression;
}
/// <summary>
/// Inline definition of a dependency array like IService[] or IHandler[]
/// </summary>
/// <param name="propertyName"></param>
/// <returns></returns>
public ChildArrayExpression ChildArray(string propertyName)
{
return new ChildArrayExpression(this, propertyName);
}
public ChildArrayExpression ChildArray(Type pluginType)
{
string propertyName = findPropertyName(pluginType);
return ChildArray(propertyName);
}
/// <summary>
/// Inline definition of a dependency array like IService[] or IHandler[]
/// </summary>
/// <typeparam name="PLUGINTYPE"></typeparam>
/// <returns></returns>
public ChildArrayExpression ChildArray<PLUGINTYPE>()
{
return ChildArray(typeof (PLUGINTYPE));
}
/// <summary>
/// Start the definition of a child instance for type CONSTRUCTORARGUMENTTYPE
/// </summary>
/// <typeparam name="CONSTRUCTORARGUMENTTYPE"></typeparam>
/// <returns></returns>
public ChildInstanceExpression Child<CONSTRUCTORARGUMENTTYPE>()
{
Type dependencyType = typeof (CONSTRUCTORARGUMENTTYPE);
return Child(dependencyType);
}
/// <summary>
/// Start the definition of a child instance for type CONSTRUCTORARGUMENTTYPE
/// </summary>
/// <typeparam name="CONSTRUCTORARGUMENTTYPE"></typeparam>
/// <returns></returns>
public ChildInstanceExpression Child(Type dependencyType)
{
string propertyName = findPropertyName(dependencyType);
ChildInstanceExpression child = Child(propertyName);
child.ChildType = dependencyType;
return child;
}
/// <summary>
/// Inline definition of a constructor or a setter property dependency
/// </summary>
/// <param name="propertyName"></param>
/// <returns></returns>
public ChildInstanceExpression Child(string propertyName)
{
return new ChildInstanceExpression(this, propertyName);
}
/// <summary>
/// Starts the definition of a child instance specifying the argument name
/// in the case of a constructor function that consumes more than one argument
/// of type T
/// </summary>
/// <typeparam name="CONSTRUCTORARGUMENTTYPE"></typeparam>
/// <param name="propertyName"></param>
/// <returns></returns>
public ChildInstanceExpression Child<CONSTRUCTORARGUMENTTYPE>(string propertyName)
{
var child = new ChildInstanceExpression(this, propertyName);
child.ChildType = typeof (CONSTRUCTORARGUMENTTYPE);
return child;
}
/// <summary>
/// Inline definition of a constructor dependency
/// </summary>
/// <typeparam name="CONSTRUCTORARGUMENTTYPE"></typeparam>
/// <param name="propertyName"></param>
/// <returns></returns>
public ChildInstanceExpression CtorDependency<CONSTRUCTORARGUMENTTYPE>(string propertyName)
{
return Child<CONSTRUCTORARGUMENTTYPE>(propertyName);
}
/// <summary>
/// Inline definition of a setter dependency
/// </summary>
/// <typeparam name="CONSTRUCTORARGUMENTTYPE"></typeparam>
/// <param name="propertyName"></param>
/// <returns></returns>
public ChildInstanceExpression SetterDependency<CONSTRUCTORARGUMENTTYPE>(string propertyName)
{
return Child<CONSTRUCTORARGUMENTTYPE>(propertyName);
}
/// <summary>
/// Start the definition of a primitive argument to a constructor argument
/// </summary>
/// <param name="propertyName"></param>
/// <returns></returns>
public PropertyExpression<ConfiguredInstance> WithProperty(string propertyName)
{
return new PropertyExpression<ConfiguredInstance>(this, propertyName);
}
/// <summary>
/// Configure a primitive constructor argument
/// </summary>
/// <param name="propertyName"></param>
/// <returns></returns>
[Obsolete("Change to DependencyExpression<CTORTYPE> instead")]
public PropertyExpression<ConfiguredInstance> WithCtorArg(string propertyName)
{
return new PropertyExpression<ConfiguredInstance>(this, propertyName);
}
#region Nested type: ChildArrayExpression
public class ChildArrayExpression
{
private readonly ConfiguredInstance _instance;
private readonly string _propertyName;
public ChildArrayExpression(ConfiguredInstance instance, string propertyName)
{
_instance = instance;
_propertyName = propertyName;
}
/// <summary>
/// Configures an array of Instance's for the array dependency
/// </summary>
/// <param name="instances"></param>
/// <returns></returns>
public ConfiguredInstance Contains(params Instance[] instances)
{
_instance.SetCollection(_propertyName, instances);
return _instance;
}
}
#endregion
#region Nested type: ChildInstanceExpression
/// <summary>
/// Part of the Fluent Interface, represents a nonprimitive argument to a
/// constructure function
/// </summary>
public class ChildInstanceExpression
{
private readonly ConfiguredInstance _instance;
private readonly string _propertyName;
private Type _childType;
public ChildInstanceExpression(ConfiguredInstance instance, string propertyName)
{
_instance = instance;
_propertyName = propertyName;
}
public ChildInstanceExpression(ConfiguredInstance instance, string propertyName,
Type childType)
: this(instance, propertyName)
{
_childType = childType;
}
internal Type ChildType { set { _childType = value; } }
/// <summary>
/// Use a previously configured and named instance for the child
/// </summary>
/// <param name="instanceKey"></param>
/// <returns></returns>
public ConfiguredInstance IsNamedInstance(string instanceKey)
{
var instance = new ReferencedInstance(instanceKey);
_instance.SetChild(_propertyName, instance);
return _instance;
}
/// <summary>
/// Start the definition of a child instance by defining the concrete type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public ConfiguredInstance IsConcreteType<T>()
{
return IsConcreteType(typeof (T));
}
/// <summary>
/// Start the definition of a child instance by defining the concrete type
/// </summary>
/// <param name="pluggedType"></param>
/// <returns></returns>
public ConfiguredInstance IsConcreteType(Type pluggedType)
{
ExpressionValidator.ValidatePluggabilityOf(pluggedType).IntoPluginType(_childType);
var childInstance = new ConfiguredInstance(pluggedType);
_instance.SetChild(_propertyName, childInstance);
return _instance;
}
/// <summary>
/// Registers a configured instance to use as the argument to the parent's
/// constructor
/// </summary>
/// <param name="child"></param>
/// <returns></returns>
public ConfiguredInstance Is(Instance child)
{
_instance.SetChild(_propertyName, child);
return _instance;
}
public ConfiguredInstance Is(object value)
{
var instance = new ObjectInstance(value);
return Is(instance);
}
/// <summary>
/// Directs StructureMap to fill this dependency with the Default Instance of the
/// constructor or property type
/// </summary>
/// <returns></returns>
public ConfiguredInstance IsAutoFilled()
{
var instance = new DefaultInstance();
return Is(instance);
}
}
#endregion
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2015 FUJIWARA, Yusuke
//
// 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.
//
#endregion -- License Terms --
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace MsgPack.Serialization.ExpressionSerializers
{
/// <summary>
/// Non generic part of <see cref="ExpressionTreeSerializerBuilder{TObject}"/>.
/// </summary>
internal static class ExpressionTreeSerializerBuilderHelpers
{
public static Type GetSerializerClass( Type targetType, CollectionTraits traits )
{
switch ( traits.DetailedCollectionType )
{
case CollectionDetailedKind.GenericEnumerable:
{
return typeof( ExpressionCallbackEnumerableMessagePackSerializer<,> ).MakeGenericType( targetType, traits.ElementType );
}
case CollectionDetailedKind.GenericCollection:
case CollectionDetailedKind.GenericSet:
case CollectionDetailedKind.GenericList:
{
return typeof( ExpressionCallbackCollectionMessagePackSerializer<,> ).MakeGenericType( targetType, traits.ElementType );
}
case CollectionDetailedKind.GenericDictionary:
{
var keyValuePairGenericArguments = traits.ElementType.GetGenericArguments();
return
typeof( ExpressionCallbackDictionaryMessagePackSerializer<,,> ).MakeGenericType(
targetType,
keyValuePairGenericArguments[ 0 ],
keyValuePairGenericArguments[ 1 ]
);
}
#if !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
case CollectionDetailedKind.GenericReadOnlyCollection:
case CollectionDetailedKind.GenericReadOnlyList:
{
return typeof( ExpressionCallbackReadOnlyCollectionMessagePackSerializer<,> ).MakeGenericType( targetType, traits.ElementType );
}
case CollectionDetailedKind.GenericReadOnlyDictionary:
{
var keyValuePairGenericArguments = traits.ElementType.GetGenericArguments();
return
typeof( ExpressionCallbackReadOnlyDictionaryMessagePackSerializer<,,> ).MakeGenericType(
targetType,
keyValuePairGenericArguments[ 0 ],
keyValuePairGenericArguments[ 1 ]
);
}
#endif // !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
case CollectionDetailedKind.NonGenericEnumerable:
{
return typeof( ExpressionCallbackNonGenericEnumerableMessagePackSerializer<> ).MakeGenericType( targetType );
}
case CollectionDetailedKind.NonGenericCollection:
{
return typeof( ExpressionCallbackNonGenericCollectionMessagePackSerializer<> ).MakeGenericType( targetType );
}
case CollectionDetailedKind.NonGenericList:
{
return typeof( ExpressionCallbackNonGenericListMessagePackSerializer<> ).MakeGenericType( targetType );
}
case CollectionDetailedKind.NonGenericDictionary:
{
return typeof( ExpressionCallbackNonGenericDictionaryMessagePackSerializer<> ).MakeGenericType( targetType );
}
default:
{
return
targetType.GetIsEnum()
? typeof( ExpressionCallbackEnumMessagePackSerializer<> ).MakeGenericType( targetType )
: typeof( ExpressionCallbackMessagePackSerializer<> ).MakeGenericType( targetType );
}
}
}
// Ok this is generic, but private dependencies are non-generic.
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Well patterned" )]
public static Func<SerializationContext, MessagePackSerializer<TObject>> CreateFactory<TObject>( ExpressionTreeContext codeGenerationContext, CollectionTraits traits, PolymorphismSchema schema )
{
// Get at this point to prevent unexpected context change.
var packToCore = codeGenerationContext.GetPackToCore();
var unpackFromCore = codeGenerationContext.GetUnpackFromCore();
var unpackToCore = codeGenerationContext.GetUnpackToCore();
var createInstance = codeGenerationContext.GetCreateInstance();
var addItem = codeGenerationContext.GetAddItem();
switch ( traits.DetailedCollectionType )
{
case CollectionDetailedKind.NonGenericEnumerable:
{
var factory =
ReflectionExtensions.CreateInstancePreservingExceptionType<IEnumerableCallbackSerializerFactory>(
typeof( NonGenericEnumerableCallbackSerializerFactory<> ).MakeGenericType( typeof( TObject ) )
);
#if DEBUG
Contract.Assert( factory != null );
#endif // DEBUG
return
context =>
factory.Create( context, schema, createInstance, unpackFromCore, addItem ) as MessagePackSerializer<TObject>;
}
case CollectionDetailedKind.NonGenericCollection:
{
var factory =
ReflectionExtensions.CreateInstancePreservingExceptionType<IEnumerableCallbackSerializerFactory>(
typeof( NonGenericCollectionCallbackSerializerFactory<> ).MakeGenericType( typeof( TObject ) )
);
#if DEBUG
Contract.Assert( factory != null );
#endif // DEBUG
return
context =>
factory.Create( context, schema, createInstance, unpackFromCore, addItem ) as MessagePackSerializer<TObject>;
}
case CollectionDetailedKind.NonGenericList:
{
var factory =
ReflectionExtensions.CreateInstancePreservingExceptionType<ICollectionCallbackSerializerFactory>(
typeof( NonGenericListCallbackSerializerFactory<> ).MakeGenericType( typeof( TObject ) )
);
#if DEBUG
Contract.Assert( factory != null );
#endif // DEBUG
return
context =>
factory.Create( context, schema, createInstance, addItem ) as MessagePackSerializer<TObject>;
}
case CollectionDetailedKind.NonGenericDictionary:
{
var factory =
ReflectionExtensions.CreateInstancePreservingExceptionType<ICollectionCallbackSerializerFactory>(
typeof( NonGenericDictionaryCallbackSerializerFactory<> ).MakeGenericType( typeof( TObject ) )
);
#if DEBUG
Contract.Assert( factory != null );
#endif // DEBUG
return
context =>
factory.Create( context, schema, createInstance, addItem ) as MessagePackSerializer<TObject>;
}
case CollectionDetailedKind.GenericEnumerable:
{
var factory =
ReflectionExtensions.CreateInstancePreservingExceptionType<IEnumerableCallbackSerializerFactory>(
typeof( EnumerableCallbackSerializerFactory<,> ).MakeGenericType( typeof( TObject ), traits.ElementType )
);
#if DEBUG
Contract.Assert( factory != null );
#endif // DEBUG
return
context =>
factory.Create( context, schema, createInstance, unpackFromCore, addItem ) as MessagePackSerializer<TObject>;
}
case CollectionDetailedKind.GenericCollection:
case CollectionDetailedKind.GenericSet:
case CollectionDetailedKind.GenericList:
{
var factory =
ReflectionExtensions.CreateInstancePreservingExceptionType<ICollectionCallbackSerializerFactory>(
typeof( CollectionCallbackSerializerFactory<,> ).MakeGenericType( typeof( TObject ), traits.ElementType )
);
#if DEBUG
Contract.Assert( factory != null );
#endif // DEBUG
return
context =>
factory.Create( context, schema, createInstance, addItem ) as MessagePackSerializer<TObject>;
}
#if !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
case CollectionDetailedKind.GenericReadOnlyCollection:
case CollectionDetailedKind.GenericReadOnlyList:
{
var factory =
ReflectionExtensions.CreateInstancePreservingExceptionType<ICollectionCallbackSerializerFactory>(
typeof( ReadOnlyCollectionCallbackSerializerFactory<,> ).MakeGenericType( typeof( TObject ), traits.ElementType )
);
#if DEBUG
Contract.Assert( factory != null );
#endif // DEBUG
return
context =>
factory.Create( context, schema, createInstance, addItem ) as MessagePackSerializer<TObject>;
}
#endif // !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
case CollectionDetailedKind.GenericDictionary:
{
var keyValuePairGenericArguments = traits.ElementType.GetGenericArguments();
var factory =
ReflectionExtensions.CreateInstancePreservingExceptionType<ICollectionCallbackSerializerFactory>(
typeof( DictionaryCallbackSerializerFactory<,,> ).MakeGenericType(
typeof( TObject ),
keyValuePairGenericArguments[ 0 ],
keyValuePairGenericArguments[ 1 ]
)
);
#if DEBUG
Contract.Assert( factory != null );
#endif // DEBUG
return
context =>
factory.Create( context, schema, createInstance, addItem ) as MessagePackSerializer<TObject>;
}
#if !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
case CollectionDetailedKind.GenericReadOnlyDictionary:
{
var keyValuePairGenericArguments = traits.ElementType.GetGenericArguments();
var factory =
ReflectionExtensions.CreateInstancePreservingExceptionType<ICollectionCallbackSerializerFactory>(
typeof( ReadOnlyDictionaryCallbackSerializerFactory<,,> ).MakeGenericType(
typeof( TObject ),
keyValuePairGenericArguments[ 0 ],
keyValuePairGenericArguments[ 1 ]
)
);
#if DEBUG
Contract.Assert( factory != null );
#endif // DEBUG
return
context =>
factory.Create( context, schema, createInstance, addItem ) as MessagePackSerializer<TObject>;
}
#endif // !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
default:
{
var factory =
ReflectionExtensions.CreateInstancePreservingExceptionType<ICallbackSerializerFactory>(
typeof( CallbackSerializerFactory<> ).MakeGenericType(
typeof( TObject )
)
);
#if DEBUG
Contract.Assert( factory != null );
#endif // DEBUG
return
context =>
factory.Create( context, packToCore, unpackFromCore, unpackToCore ) as MessagePackSerializer<TObject>;
}
}
}
private interface ICallbackSerializerFactory
{
object Create(
SerializationContext context,
Delegate packTo,
Delegate unpackFrom,
Delegate unpackTo
);
}
private sealed class CallbackSerializerFactory<T> : ICallbackSerializerFactory
{
public CallbackSerializerFactory() { }
private static object Create(
SerializationContext context,
Action<ExpressionCallbackMessagePackSerializer<T>, SerializationContext, Packer, T> packTo,
Func<ExpressionCallbackMessagePackSerializer<T>, SerializationContext, Unpacker, T> unpackFrom,
Action<ExpressionCallbackMessagePackSerializer<T>, SerializationContext, Unpacker, T> unpackTo
)
{
return
new ExpressionCallbackMessagePackSerializer<T>(
context,
packTo,
unpackFrom,
unpackTo
);
}
public object Create(
SerializationContext context,
Delegate packTo,
Delegate unpackFrom,
Delegate unpackTo
)
{
return
Create(
context,
( Action<ExpressionCallbackMessagePackSerializer<T>, SerializationContext, Packer, T> )packTo,
( Func<ExpressionCallbackMessagePackSerializer<T>, SerializationContext, Unpacker, T> )unpackFrom,
( Action<ExpressionCallbackMessagePackSerializer<T>, SerializationContext, Unpacker, T> )unpackTo
);
}
}
private interface IEnumerableCallbackSerializerFactory
{
object Create(
SerializationContext context,
PolymorphismSchema schema,
Delegate createInstance,
Delegate unpackFrom,
Delegate addItem
);
}
private abstract class EnumerableCallbackSerializerFactoryBase<TCollection, TItem, TSerializer> :
IEnumerableCallbackSerializerFactory
{
protected abstract object Create(
SerializationContext context,
PolymorphismSchema schema,
Func<TSerializer, SerializationContext, int, TCollection> createInstance,
Func<TSerializer, SerializationContext, Unpacker, TCollection> unpackFrom,
Action<TSerializer, SerializationContext, TCollection, TItem> addItem
);
public object Create(
SerializationContext context,
PolymorphismSchema schema,
Delegate createInstance,
Delegate unpackFrom,
Delegate addItem
)
{
return
this.Create(
context,
schema,
( Func<TSerializer, SerializationContext, int, TCollection> )createInstance,
( Func<TSerializer, SerializationContext, Unpacker, TCollection> )unpackFrom,
( Action<TSerializer, SerializationContext, TCollection, TItem> )addItem
);
}
}
private sealed class EnumerableCallbackSerializerFactory<TCollection, TItem> : EnumerableCallbackSerializerFactoryBase<TCollection, TItem, ExpressionCallbackEnumerableMessagePackSerializer<TCollection, TItem>>
where TCollection : IEnumerable<TItem>
{
public EnumerableCallbackSerializerFactory() { }
protected override object Create(
SerializationContext context,
PolymorphismSchema schema,
Func<ExpressionCallbackEnumerableMessagePackSerializer<TCollection, TItem>, SerializationContext, int, TCollection> createInstance,
Func<ExpressionCallbackEnumerableMessagePackSerializer<TCollection, TItem>, SerializationContext, Unpacker, TCollection> unpackFrom,
Action<ExpressionCallbackEnumerableMessagePackSerializer<TCollection, TItem>, SerializationContext, TCollection, TItem> addItem
)
{
return
new ExpressionCallbackEnumerableMessagePackSerializer<TCollection, TItem>(
context,
schema,
createInstance,
unpackFrom,
addItem
);
}
}
private sealed class NonGenericEnumerableCallbackSerializerFactory<TCollection> : EnumerableCallbackSerializerFactoryBase<TCollection, object, ExpressionCallbackNonGenericEnumerableMessagePackSerializer<TCollection>>
where TCollection : IEnumerable
{
public NonGenericEnumerableCallbackSerializerFactory() { }
protected override object Create(
SerializationContext context,
PolymorphismSchema schema,
Func<ExpressionCallbackNonGenericEnumerableMessagePackSerializer<TCollection>, SerializationContext, int, TCollection> createInstance,
Func<ExpressionCallbackNonGenericEnumerableMessagePackSerializer<TCollection>, SerializationContext, Unpacker, TCollection> unpackFrom,
Action<ExpressionCallbackNonGenericEnumerableMessagePackSerializer<TCollection>, SerializationContext, TCollection, object> addItem
)
{
return
new ExpressionCallbackNonGenericEnumerableMessagePackSerializer<TCollection>(
context,
schema,
createInstance,
unpackFrom,
addItem
);
}
}
private sealed class NonGenericCollectionCallbackSerializerFactory<TCollection> : EnumerableCallbackSerializerFactoryBase<TCollection, object, ExpressionCallbackNonGenericCollectionMessagePackSerializer<TCollection>>
where TCollection : ICollection
{
public NonGenericCollectionCallbackSerializerFactory() { }
protected override object Create(
SerializationContext context,
PolymorphismSchema schema,
Func<ExpressionCallbackNonGenericCollectionMessagePackSerializer<TCollection>, SerializationContext, int, TCollection> createInstance,
Func<ExpressionCallbackNonGenericCollectionMessagePackSerializer<TCollection>, SerializationContext, Unpacker, TCollection> unpackFrom,
Action<ExpressionCallbackNonGenericCollectionMessagePackSerializer<TCollection>, SerializationContext, TCollection, object> addItem
)
{
return
new ExpressionCallbackNonGenericCollectionMessagePackSerializer<TCollection>(
context,
schema,
createInstance,
unpackFrom,
addItem
);
}
}
private interface ICollectionCallbackSerializerFactory
{
object Create(
SerializationContext context,
PolymorphismSchema schema,
Delegate createInstance,
Delegate addItem
);
}
private abstract class CollectionCallbackSerializerFactoryBase<TCollection, TItem, TSerializer> : ICollectionCallbackSerializerFactory
{
protected abstract object Create(
SerializationContext context,
PolymorphismSchema schema,
Func<TSerializer, SerializationContext, int, TCollection> createInstance,
Action<TSerializer, SerializationContext, TCollection, TItem> addItem
);
public object Create(
SerializationContext context,
PolymorphismSchema schema,
Delegate createInstance,
Delegate addItem
)
{
return
this.Create(
context,
schema,
( Func<TSerializer, SerializationContext, int, TCollection> )createInstance,
( Action<TSerializer, SerializationContext, TCollection, TItem> )addItem
);
}
}
private sealed class CollectionCallbackSerializerFactory<TCollection, TItem>
: CollectionCallbackSerializerFactoryBase<TCollection, TItem, ExpressionCallbackCollectionMessagePackSerializer<TCollection, TItem>>
where TCollection : ICollection<TItem>
{
public CollectionCallbackSerializerFactory() { }
protected override object Create(
SerializationContext context,
PolymorphismSchema schema,
Func<ExpressionCallbackCollectionMessagePackSerializer<TCollection, TItem>, SerializationContext, int, TCollection> createInstance,
Action<ExpressionCallbackCollectionMessagePackSerializer<TCollection, TItem>, SerializationContext, TCollection, TItem> addItem
)
{
return
new ExpressionCallbackCollectionMessagePackSerializer<TCollection, TItem>(
context,
schema,
createInstance
);
}
}
#if !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
private sealed class ReadOnlyCollectionCallbackSerializerFactory<TCollection, TItem>
: CollectionCallbackSerializerFactoryBase<TCollection, TItem, ExpressionCallbackReadOnlyCollectionMessagePackSerializer<TCollection, TItem>>
where TCollection : IReadOnlyCollection<TItem>
{
public ReadOnlyCollectionCallbackSerializerFactory() { }
protected override object Create(
SerializationContext context,
PolymorphismSchema schema,
Func<ExpressionCallbackReadOnlyCollectionMessagePackSerializer<TCollection, TItem>, SerializationContext, int, TCollection> createInstance,
Action<ExpressionCallbackReadOnlyCollectionMessagePackSerializer<TCollection, TItem>, SerializationContext, TCollection, TItem> addItem
)
{
return
new ExpressionCallbackReadOnlyCollectionMessagePackSerializer<TCollection, TItem>(
context,
schema,
createInstance,
addItem
);
}
}
#endif // !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
private sealed class NonGenericListCallbackSerializerFactory<TCollection>
: CollectionCallbackSerializerFactoryBase<TCollection, object, ExpressionCallbackNonGenericListMessagePackSerializer<TCollection>>
where TCollection : IList
{
public NonGenericListCallbackSerializerFactory() { }
protected override object Create(
SerializationContext context,
PolymorphismSchema schema,
Func<ExpressionCallbackNonGenericListMessagePackSerializer<TCollection>, SerializationContext, int, TCollection> createInstance,
Action<ExpressionCallbackNonGenericListMessagePackSerializer<TCollection>, SerializationContext, TCollection, object> addItem
)
{
return
new ExpressionCallbackNonGenericListMessagePackSerializer<TCollection>(
context,
schema,
createInstance
);
}
}
private sealed class NonGenericDictionaryCallbackSerializerFactory<TDictionary>
: CollectionCallbackSerializerFactoryBase<TDictionary, DictionaryEntry, ExpressionCallbackNonGenericDictionaryMessagePackSerializer<TDictionary>>
where TDictionary : IDictionary
{
public NonGenericDictionaryCallbackSerializerFactory() { }
protected override object Create(
SerializationContext context,
PolymorphismSchema schema,
Func<ExpressionCallbackNonGenericDictionaryMessagePackSerializer<TDictionary>, SerializationContext, int, TDictionary> createInstance,
Action<ExpressionCallbackNonGenericDictionaryMessagePackSerializer<TDictionary>, SerializationContext, TDictionary, DictionaryEntry> addItem
)
{
return
new ExpressionCallbackNonGenericDictionaryMessagePackSerializer<TDictionary>(
context,
schema,
createInstance
);
}
}
private sealed class DictionaryCallbackSerializerFactory<TDictionary, TKey, TValue> : ICollectionCallbackSerializerFactory
where TDictionary : IDictionary<TKey, TValue>
{
public DictionaryCallbackSerializerFactory() { }
private static object Create(
SerializationContext context,
PolymorphismSchema schema,
Func<ExpressionCallbackDictionaryMessagePackSerializer<TDictionary, TKey, TValue>, SerializationContext, int, TDictionary> createInstance
)
{
return
new ExpressionCallbackDictionaryMessagePackSerializer<TDictionary, TKey, TValue>(
context,
schema,
createInstance
);
}
public object Create(
SerializationContext context,
PolymorphismSchema schema,
Delegate createInstance,
Delegate addItem
)
{
return
Create(
context,
schema,
( Func<ExpressionCallbackDictionaryMessagePackSerializer<TDictionary, TKey, TValue>, SerializationContext, int, TDictionary> )createInstance
);
}
}
#if !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
private sealed class ReadOnlyDictionaryCallbackSerializerFactory<TDictionary, TKey, TValue> : ICollectionCallbackSerializerFactory
where TDictionary : IReadOnlyDictionary<TKey, TValue>
{
public ReadOnlyDictionaryCallbackSerializerFactory() { }
private static object Create(
SerializationContext context,
PolymorphismSchema schema,
Func<ExpressionCallbackReadOnlyDictionaryMessagePackSerializer<TDictionary, TKey, TValue>, SerializationContext, int, TDictionary> createInstance,
Action<ExpressionCallbackReadOnlyDictionaryMessagePackSerializer<TDictionary, TKey, TValue>, SerializationContext, TDictionary, TKey, TValue> addItem
)
{
return
new ExpressionCallbackReadOnlyDictionaryMessagePackSerializer<TDictionary, TKey, TValue>(
context,
schema,
createInstance,
addItem
);
}
public object Create(
SerializationContext context,
PolymorphismSchema schema,
Delegate createInstance,
Delegate addItem
)
{
return
Create(
context,
schema,
( Func<ExpressionCallbackReadOnlyDictionaryMessagePackSerializer<TDictionary, TKey, TValue>, SerializationContext, int, TDictionary> )createInstance,
( Action<ExpressionCallbackReadOnlyDictionaryMessagePackSerializer<TDictionary, TKey, TValue>, SerializationContext, TDictionary, TKey, TValue> )addItem
);
}
}
#endif // !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
}
}
| |
// 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.Diagnostics.Contracts;
using System.Text;
namespace System.IO.Compression
{
//The disposable fields that this class owns get disposed when the ZipArchive it belongs to gets disposed
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
public partial class ZipArchiveEntry
{
#region Fields
private const UInt16 DefaultVersionToExtract = 10;
//The maximum index of our buffers, from the maximum index of a byte array
private const int MaxSingleBufferSize = 0x7FFFFFC7;
private ZipArchive _archive;
private readonly Boolean _originallyInArchive;
private readonly Int32 _diskNumberStart;
private readonly ZipVersionMadeByPlatform _versionMadeByPlatform;
private readonly byte _versionMadeBySpecification;
private ZipVersionNeededValues _versionToExtract;
private BitFlagValues _generalPurposeBitFlag;
private CompressionMethodValues _storedCompressionMethod;
private DateTimeOffset _lastModified;
private Int64 _compressedSize;
private Int64 _uncompressedSize;
private Int64 _offsetOfLocalHeader;
private Int64? _storedOffsetOfCompressedData;
private UInt32 _crc32;
//An array of buffers, each a maximum of MaxSingleBufferSize in size
private Byte[][] _compressedBytes;
private MemoryStream _storedUncompressedData;
private Boolean _currentlyOpenForWrite;
private Boolean _everOpenedForWrite;
private Stream _outstandingWriteStream;
private String _storedEntryName;
private Byte[] _storedEntryNameBytes;
//only apply to update mode
private List<ZipGenericExtraField> _cdUnknownExtraFields;
private List<ZipGenericExtraField> _lhUnknownExtraFields;
private Byte[] _fileComment;
private CompressionLevel? _compressionLevel;
#endregion Fields
//Initializes, attaches it to archive
internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd, CompressionLevel compressionLevel)
: this(archive, cd)
{
_compressionLevel = compressionLevel;
}
//Initializes, attaches it to archive
internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd)
{
_archive = archive;
_originallyInArchive = true;
_diskNumberStart = cd.DiskNumberStart;
_versionMadeByPlatform = (ZipVersionMadeByPlatform)cd.VersionMadeByCompatibility;
_versionMadeBySpecification = cd.VersionMadeBySpecification;
_versionToExtract = (ZipVersionNeededValues)cd.VersionNeededToExtract;
_generalPurposeBitFlag = (BitFlagValues)cd.GeneralPurposeBitFlag;
CompressionMethod = (CompressionMethodValues)cd.CompressionMethod;
_lastModified = new DateTimeOffset(ZipHelper.DosTimeToDateTime(cd.LastModified));
_compressedSize = cd.CompressedSize;
_uncompressedSize = cd.UncompressedSize;
_offsetOfLocalHeader = cd.RelativeOffsetOfLocalHeader;
/* we don't know this yet: should be _offsetOfLocalHeader + 30 + _storedEntryNameBytes.Length + extrafieldlength
* but entryname/extra length could be different in LH
*/
_storedOffsetOfCompressedData = null;
_crc32 = cd.Crc32;
_compressedBytes = null;
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
_outstandingWriteStream = null;
FullName = DecodeEntryName(cd.Filename);
_lhUnknownExtraFields = null;
//the cd should have these as null if we aren't in Update mode
_cdUnknownExtraFields = cd.ExtraFields;
_fileComment = cd.FileComment;
_compressionLevel = null;
}
//Initializes new entry
internal ZipArchiveEntry(ZipArchive archive, String entryName, CompressionLevel compressionLevel)
: this(archive, entryName)
{
_compressionLevel = compressionLevel;
}
//Initializes new entry
internal ZipArchiveEntry(ZipArchive archive, String entryName)
{
_archive = archive;
_originallyInArchive = false;
_diskNumberStart = 0;
_versionMadeByPlatform = CurrentZipPlatform;
_versionMadeBySpecification = 0;
_versionToExtract = ZipVersionNeededValues.Default; //this must happen before following two assignment
_generalPurposeBitFlag = 0;
CompressionMethod = CompressionMethodValues.Deflate;
_lastModified = DateTimeOffset.Now;
_compressedSize = 0; //we don't know these yet
_uncompressedSize = 0;
_offsetOfLocalHeader = 0;
_storedOffsetOfCompressedData = null;
_crc32 = 0;
_compressedBytes = null;
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
_outstandingWriteStream = null;
FullName = entryName;
_cdUnknownExtraFields = null;
_lhUnknownExtraFields = null;
_fileComment = null;
_compressionLevel = null;
if (_storedEntryNameBytes.Length > UInt16.MaxValue)
throw new ArgumentException(SR.EntryNamesTooLong);
//grab the stream if we're in create mode
if (_archive.Mode == ZipArchiveMode.Create)
{
_archive.AcquireArchiveStream(this);
}
}
/// <summary>
/// The ZipArchive that this entry belongs to. If this entry has been deleted, this will return null.
/// </summary>
public ZipArchive Archive { get { return _archive; } }
/// <summary>
/// The compressed size of the entry. If the archive that the entry belongs to is in Create mode, attempts to get this property will always throw an exception. If the archive that the entry belongs to is in update mode, this property will only be valid if the entry has not been opened.
/// </summary>
/// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception>
public Int64 CompressedLength
{
get
{
Contract.Ensures(Contract.Result<Int64>() >= 0);
if (_everOpenedForWrite)
throw new InvalidOperationException(SR.LengthAfterWrite);
return _compressedSize;
}
}
/// <summary>
/// The relative path of the entry as stored in the Zip archive. Note that Zip archives allow any string to be the path of the entry, including invalid and absolute paths.
/// </summary>
public String FullName
{
get
{
Contract.Ensures(Contract.Result<String>() != null);
return _storedEntryName;
}
private set
{
if (value == null)
throw new ArgumentNullException("FullName");
bool isUTF8;
_storedEntryNameBytes = EncodeEntryName(value, out isUTF8);
_storedEntryName = value;
if (isUTF8)
_generalPurposeBitFlag |= BitFlagValues.UnicodeFileName;
else
_generalPurposeBitFlag &= ~BitFlagValues.UnicodeFileName;
if (ParseFileName(value, _versionMadeByPlatform) == "")
VersionToExtractAtLeast(ZipVersionNeededValues.ExplicitDirectory);
}
}
/// <summary>
/// The last write time of the entry as stored in the Zip archive. When setting this property, the DateTime will be converted to the
/// Zip timestamp format, which supports a resolution of two seconds. If the data in the last write time field is not a valid Zip timestamp,
/// an indicator value of 1980 January 1 at midnight will be returned.
/// </summary>
/// <exception cref="NotSupportedException">An attempt to set this property was made, but the ZipArchive that this entry belongs to was
/// opened in read-only mode.</exception>
/// <exception cref="ArgumentOutOfRangeException">An attempt was made to set this property to a value that cannot be represented in the
/// Zip timestamp format. The earliest date/time that can be represented is 1980 January 1 0:00:00 (midnight), and the last date/time
/// that can be represented is 2107 December 31 23:59:58 (one second before midnight).</exception>
public DateTimeOffset LastWriteTime
{
get
{
return _lastModified;
}
set
{
ThrowIfInvalidArchive();
if (_archive.Mode == ZipArchiveMode.Read)
throw new NotSupportedException(SR.ReadOnlyArchive);
if (_archive.Mode == ZipArchiveMode.Create && _everOpenedForWrite)
throw new IOException(SR.FrozenAfterWrite);
if (value.DateTime.Year < ZipHelper.ValidZipDate_YearMin || value.DateTime.Year > ZipHelper.ValidZipDate_YearMax)
throw new ArgumentOutOfRangeException("value", SR.DateTimeOutOfRange);
_lastModified = value;
}
}
/// <summary>
/// The uncompressed size of the entry. This property is not valid in Create mode, and it is only valid in Update mode if the entry has not been opened.
/// </summary>
/// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception>
public Int64 Length
{
get
{
Contract.Ensures(Contract.Result<Int64>() >= 0);
if (_everOpenedForWrite)
throw new InvalidOperationException(SR.LengthAfterWrite);
return _uncompressedSize;
}
}
/// <summary>
/// The filename of the entry. This is equivalent to the substring of Fullname that follows the final directory separator character.
/// </summary>
public String Name
{
get
{
return ParseFileName(FullName, _versionMadeByPlatform);
}
}
/// <summary>
/// Deletes the entry from the archive.
/// </summary>
/// <exception cref="IOException">The entry is already open for reading or writing.</exception>
/// <exception cref="NotSupportedException">The ZipArchive that this entry belongs to was opened in a mode other than ZipArchiveMode.Update. </exception>
/// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception>
public void Delete()
{
if (_archive == null)
return;
if (_currentlyOpenForWrite)
throw new IOException(SR.DeleteOpenEntry);
if (_archive.Mode != ZipArchiveMode.Update)
throw new NotSupportedException(SR.DeleteOnlyInUpdate);
_archive.ThrowIfDisposed();
_archive.RemoveEntry(this);
_archive = null;
UnloadStreams();
}
/// <summary>
/// Opens the entry. If the archive that the entry belongs to was opened in Read mode, the returned stream will be readable, and it may or may not be seekable. If Create mode, the returned stream will be writeable and not seekable. If Update mode, the returned stream will be readable, writeable, seekable, and support SetLength.
/// </summary>
/// <returns>A Stream that represents the contents of the entry.</returns>
/// <exception cref="IOException">The entry is already currently open for writing. -or- The entry has been deleted from the archive. -or- The archive that this entry belongs to was opened in ZipArchiveMode.Create, and this entry has already been written to once.</exception>
/// <exception cref="InvalidDataException">The entry is missing from the archive or is corrupt and cannot be read. -or- The entry has been compressed using a compression method that is not supported.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception>
public Stream Open()
{
Contract.Ensures(Contract.Result<Stream>() != null);
ThrowIfInvalidArchive();
switch (_archive.Mode)
{
case ZipArchiveMode.Read:
return OpenInReadMode(true);
case ZipArchiveMode.Create:
return OpenInWriteMode();
case ZipArchiveMode.Update:
default:
Debug.Assert(_archive.Mode == ZipArchiveMode.Update);
return OpenInUpdateMode();
}
}
/// <summary>
/// Returns the FullName of the entry.
/// </summary>
/// <returns>FullName of the entry</returns>
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return FullName;
}
/*
public void MoveTo(String destinationEntryName)
{
if (destinationEntryName == null)
throw new ArgumentNullException("destinationEntryName");
if (String.IsNullOrEmpty(destinationEntryName))
throw new ArgumentException("destinationEntryName cannot be empty", "destinationEntryName");
if (_archive == null)
throw new InvalidOperationException("Attempt to move a deleted entry");
if (_archive._isDisposed)
throw new ObjectDisposedException(_archive.ToString());
if (_archive.Mode != ZipArchiveMode.Update)
throw new NotSupportedException("MoveTo can only be used when the archive is in Update mode");
String oldFilename = _filename;
_filename = destinationEntryName;
if (_filenameLength > UInt16.MaxValue)
{
_filename = oldFilename;
throw new ArgumentException("Archive entry names must be smaller than 2^16 bytes");
}
}
*/
#region Privates
// Only allow opening ZipArchives with large ZipArchiveEntries in update mode when running in a 64-bit process.
// This is for compatibility with old behavior that threw an exception for all process bitnesses, because this
// will not work in a 32-bit process.
private static readonly bool s_allowLargeZipArchiveEntriesInUpdateMode = IntPtr.Size > 4;
internal Boolean EverOpenedForWrite { get { return _everOpenedForWrite; } }
private Int64 OffsetOfCompressedData
{
get
{
if (_storedOffsetOfCompressedData == null)
{
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
//by calling this, we are using local header _storedEntryNameBytes.Length and extraFieldLength
//to find start of data, but still using central directory size information
if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader))
throw new InvalidDataException(SR.LocalFileHeaderCorrupt);
_storedOffsetOfCompressedData = _archive.ArchiveStream.Position;
}
return _storedOffsetOfCompressedData.Value;
}
}
private MemoryStream UncompressedData
{
get
{
if (_storedUncompressedData == null)
{
//this means we have never opened it before
//if _uncompressedSize > Int32.MaxValue, it's still okay, because MemoryStream will just
//grow as data is copied into it
_storedUncompressedData = new MemoryStream((Int32)_uncompressedSize);
if (_originallyInArchive)
{
using (Stream decompressor = OpenInReadMode(false))
{
try
{
decompressor.CopyTo(_storedUncompressedData);
}
catch (InvalidDataException)
{
/* this is the case where the archive say the entry is deflate, but deflateStream
* throws an InvalidDataException. This property should only be getting accessed in
* Update mode, so we want to make sure _storedUncompressedData stays null so
* that later when we dispose the archive, this entry loads the compressedBytes, and
* copies them straight over
*/
_storedUncompressedData.Dispose();
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
throw;
}
}
}
//if they start modifying it, we should make sure it will get deflated
CompressionMethod = CompressionMethodValues.Deflate;
}
return _storedUncompressedData;
}
}
private CompressionMethodValues CompressionMethod
{
get { return _storedCompressionMethod; }
set
{
if (value == CompressionMethodValues.Deflate)
VersionToExtractAtLeast(ZipVersionNeededValues.Deflate);
_storedCompressionMethod = value;
}
}
private Encoding DefaultSystemEncoding
{
// On the desktop, this was Encoding.GetEncoding(0), which gives you the encoding object
// that corresponds too the default system codepage.
// However, in ProjectN, not only Encoding.GetEncoding(Int32) is not exposed, but there is also
// no guarantee that a notion of a default system code page exists on the OS.
// In fact, we can really only rely on UTF8 and UTF16 being present on all platforms.
// We fall back to UTF8 as this is what is used by ZIP when as the "unicode encoding".
get
{
return Encoding.UTF8;
// return Encoding.GetEncoding(0);
}
}
private String DecodeEntryName(Byte[] entryNameBytes)
{
Debug.Assert(entryNameBytes != null);
Encoding readEntryNameEncoding;
if ((_generalPurposeBitFlag & BitFlagValues.UnicodeFileName) == 0)
{
readEntryNameEncoding = (_archive == null)
? DefaultSystemEncoding
: _archive.EntryNameEncoding ?? DefaultSystemEncoding;
}
else
{
readEntryNameEncoding = Encoding.UTF8;
}
return readEntryNameEncoding.GetString(entryNameBytes);
}
private Byte[] EncodeEntryName(String entryName, out bool isUTF8)
{
Debug.Assert(entryName != null);
Encoding writeEntryNameEncoding;
if (_archive != null && _archive.EntryNameEncoding != null)
writeEntryNameEncoding = _archive.EntryNameEncoding;
else
writeEntryNameEncoding = ZipHelper.RequiresUnicode(entryName)
? Encoding.UTF8
: DefaultSystemEncoding;
isUTF8 = writeEntryNameEncoding.Equals(Encoding.UTF8);
return writeEntryNameEncoding.GetBytes(entryName);
}
/* does almost everything you need to do to forget about this entry
* writes the local header/data, gets rid of all the data,
* closes all of the streams except for the very outermost one that
* the user holds on to and is responsible for closing
*
* after calling this, and only after calling this can we be guaranteed
* that we are reading to write the central directory
*
* should only throw an exception in extremely exceptional cases because it is called from dispose
*/
internal void WriteAndFinishLocalEntry()
{
CloseStreams();
WriteLocalFileHeaderAndDataIfNeeded();
UnloadStreams();
}
//should only throw an exception in extremely exceptional cases because it is called from dispose
internal void WriteCentralDirectoryFileHeader()
{
//This part is simple, because we should definitely know the sizes by this time
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
//_entryname only gets set when we read in or call moveTo. MoveTo does a check, and
//reading in should not be able to produce a entryname longer than UInt16.MaxValue
Debug.Assert(_storedEntryNameBytes.Length <= UInt16.MaxValue);
//decide if we need the Zip64 extra field:
Zip64ExtraField zip64ExtraField = new Zip64ExtraField();
UInt32 compressedSizeTruncated, uncompressedSizeTruncated, offsetOfLocalHeaderTruncated;
Boolean zip64Needed = false;
if (SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
)
{
zip64Needed = true;
compressedSizeTruncated = ZipHelper.Mask32Bit;
uncompressedSizeTruncated = ZipHelper.Mask32Bit;
//If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways
zip64ExtraField.CompressedSize = _compressedSize;
zip64ExtraField.UncompressedSize = _uncompressedSize;
}
else
{
compressedSizeTruncated = (UInt32)_compressedSize;
uncompressedSizeTruncated = (UInt32)_uncompressedSize;
}
if (_offsetOfLocalHeader > UInt32.MaxValue
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
)
{
zip64Needed = true;
offsetOfLocalHeaderTruncated = ZipHelper.Mask32Bit;
//If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways
zip64ExtraField.LocalHeaderOffset = _offsetOfLocalHeader;
}
else
{
offsetOfLocalHeaderTruncated = (UInt32)_offsetOfLocalHeader;
}
if (zip64Needed)
VersionToExtractAtLeast(ZipVersionNeededValues.Zip64);
//determine if we can fit zip64 extra field and original extra fields all in
Int32 bigExtraFieldLength = (zip64Needed ? zip64ExtraField.TotalSize : 0)
+ (_cdUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_cdUnknownExtraFields) : 0);
UInt16 extraFieldLength;
if (bigExtraFieldLength > UInt16.MaxValue)
{
extraFieldLength = (UInt16)(zip64Needed ? zip64ExtraField.TotalSize : 0);
_cdUnknownExtraFields = null;
}
else
{
extraFieldLength = (UInt16)bigExtraFieldLength;
}
writer.Write(ZipCentralDirectoryFileHeader.SignatureConstant); // Central directory file header signature (4 bytes)
writer.Write(_versionMadeBySpecification); // Version made by Specification (version) (1 byte)
writer.Write((byte)CurrentZipPlatform); // Version made by Compatibility (type) (1 byte)
writer.Write((UInt16)_versionToExtract); // Minimum version needed to extract (2 bytes)
writer.Write((UInt16)_generalPurposeBitFlag); // General Purpose bit flag (2 bytes)
writer.Write((UInt16)CompressionMethod); // The Compression method (2 bytes)
writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); // File last modification time and date (4 bytes)
writer.Write(_crc32); // CRC-32 (4 bytes)
writer.Write(compressedSizeTruncated); // Compressed Size (4 bytes)
writer.Write(uncompressedSizeTruncated); // Uncompressed Size (4 bytes)
writer.Write((UInt16)_storedEntryNameBytes.Length); // File Name Length (2 bytes)
writer.Write(extraFieldLength); // Extra Field Length (2 bytes)
// This should hold because of how we read it originally in ZipCentralDirectoryFileHeader:
Debug.Assert((_fileComment == null) || (_fileComment.Length <= UInt16.MaxValue));
writer.Write(_fileComment != null ? (UInt16)_fileComment.Length : (UInt16)0); //file comment length
writer.Write((UInt16)0); //disk number start
writer.Write((UInt16)0); //internal file attributes
writer.Write((UInt32)0); //external file attributes
writer.Write(offsetOfLocalHeaderTruncated); //offset of local header
writer.Write(_storedEntryNameBytes);
//write extra fields
if (zip64Needed)
zip64ExtraField.WriteBlock(_archive.ArchiveStream);
if (_cdUnknownExtraFields != null)
ZipGenericExtraField.WriteAllBlocks(_cdUnknownExtraFields, _archive.ArchiveStream);
if (_fileComment != null)
writer.Write(_fileComment);
}
//returns false if fails, will get called on every entry before closing in update mode
//can throw InvalidDataException
internal Boolean LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded()
{
String message;
//we should have made this exact call in _archive.Init through ThrowIfOpenable
Debug.Assert(IsOpenable(false, true, out message));
//load local header's extra fields. it will be null if we couldn't read for some reason
if (_originallyInArchive)
{
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
_lhUnknownExtraFields = ZipLocalFileHeader.GetExtraFields(_archive.ArchiveReader);
}
if (!_everOpenedForWrite && _originallyInArchive)
{
//we know that it is openable at this point
_compressedBytes = new Byte[(_compressedSize / MaxSingleBufferSize) + 1][];
for (int i = 0; i < _compressedBytes.Length - 1; i++)
{
_compressedBytes[i] = new Byte[MaxSingleBufferSize];
}
_compressedBytes[_compressedBytes.Length - 1] = new Byte[_compressedSize % MaxSingleBufferSize];
_archive.ArchiveStream.Seek(OffsetOfCompressedData, SeekOrigin.Begin);
for (int i = 0; i < _compressedBytes.Length - 1; i++)
{
ZipHelper.ReadBytes(_archive.ArchiveStream, _compressedBytes[i], MaxSingleBufferSize);
}
ZipHelper.ReadBytes(_archive.ArchiveStream, _compressedBytes[_compressedBytes.Length - 1], (Int32)(_compressedSize % MaxSingleBufferSize));
}
return true;
}
internal void ThrowIfNotOpenable(Boolean needToUncompress, Boolean needToLoadIntoMemory)
{
String message;
if (!IsOpenable(needToUncompress, needToLoadIntoMemory, out message))
throw new InvalidDataException(message);
}
private CheckSumAndSizeWriteStream GetDataCompressor(Stream backingStream, Boolean leaveBackingStreamOpen, EventHandler onClose)
{
//stream stack: backingStream -> DeflateStream -> CheckSumWriteStream
//we should always be compressing with deflate. Stored is used for empty files, but we don't actually
//call through this function for that - we just write the stored value in the header
Debug.Assert(CompressionMethod == CompressionMethodValues.Deflate);
Stream compressorStream = _compressionLevel.HasValue
? new DeflateStream(backingStream, _compressionLevel.Value, leaveBackingStreamOpen)
: new DeflateStream(backingStream, CompressionMode.Compress, leaveBackingStreamOpen);
Boolean isIntermediateStream = true;
Boolean leaveCompressorStreamOpenOnClose = leaveBackingStreamOpen && !isIntermediateStream;
var checkSumStream = new CheckSumAndSizeWriteStream(
compressorStream,
backingStream,
leaveCompressorStreamOpenOnClose,
this,
onClose,
(Int64 initialPosition, Int64 currentPosition, UInt32 checkSum, Stream backing, ZipArchiveEntry thisRef, EventHandler closeHandler) =>
{
thisRef._crc32 = checkSum;
thisRef._uncompressedSize = currentPosition;
thisRef._compressedSize = backing.Position - initialPosition;
if (closeHandler != null)
closeHandler(thisRef, EventArgs.Empty);
});
return checkSumStream;
}
private Stream GetDataDecompressor(Stream compressedStreamToRead)
{
Stream uncompressedStream = null;
switch (CompressionMethod)
{
case CompressionMethodValues.Deflate:
uncompressedStream = new DeflateStream(compressedStreamToRead, CompressionMode.Decompress);
break;
case CompressionMethodValues.Stored:
default:
//we can assume that only deflate/stored are allowed because we assume that
//IsOpenable is checked before this function is called
Debug.Assert(CompressionMethod == CompressionMethodValues.Stored);
uncompressedStream = compressedStreamToRead;
break;
}
return uncompressedStream;
}
private Stream OpenInReadMode(Boolean checkOpenable)
{
if (checkOpenable)
ThrowIfNotOpenable(true, false);
Stream compressedStream = new SubReadStream(_archive.ArchiveStream, OffsetOfCompressedData, _compressedSize);
return GetDataDecompressor(compressedStream);
}
private Stream OpenInWriteMode()
{
if (_everOpenedForWrite)
throw new IOException(SR.CreateModeWriteOnceAndOneEntryAtATime);
//we assume that if another entry grabbed the archive stream, that it set this entry's _everOpenedForWrite property to true by calling WriteLocalFileHeaderIfNeeed
Debug.Assert(_archive.IsStillArchiveStreamOwner(this));
_everOpenedForWrite = true;
CheckSumAndSizeWriteStream crcSizeStream = GetDataCompressor(_archive.ArchiveStream, true,
(object o, EventArgs e) =>
{
//release the archive stream
var entry = (ZipArchiveEntry)o;
entry._archive.ReleaseArchiveStream(entry);
entry._outstandingWriteStream = null;
});
_outstandingWriteStream = new DirectToArchiveWriterStream(crcSizeStream, this);
return new WrappedStream(baseStream: _outstandingWriteStream, closeBaseStream: true);
}
private Stream OpenInUpdateMode()
{
if (_currentlyOpenForWrite)
throw new IOException(SR.UpdateModeOneStream);
ThrowIfNotOpenable(true, true);
_everOpenedForWrite = true;
_currentlyOpenForWrite = true;
//always put it at the beginning for them
UncompressedData.Seek(0, SeekOrigin.Begin);
return new WrappedStream(UncompressedData, this, thisRef =>
{
//once they close, we know uncompressed length, but still not compressed length
//so we don't fill in any size information
//those fields get figured out when we call GetCompressor as we write it to
//the actual archive
thisRef._currentlyOpenForWrite = false;
});
}
private Boolean IsOpenable(Boolean needToUncompress, Boolean needToLoadIntoMemory, out String message)
{
message = null;
if (_originallyInArchive)
{
if (needToUncompress)
{
if (CompressionMethod != CompressionMethodValues.Stored &&
CompressionMethod != CompressionMethodValues.Deflate)
{
message = SR.UnsupportedCompression;
return false;
}
}
if (_diskNumberStart != _archive.NumberOfThisDisk)
{
message = SR.SplitSpanned;
return false;
}
if (_offsetOfLocalHeader > _archive.ArchiveStream.Length)
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader))
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
//when this property gets called, some duplicated work
if (OffsetOfCompressedData + _compressedSize > _archive.ArchiveStream.Length)
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
//This limitation originally existed because a) it is unreasonable to load > 4GB into memory
//but also because the stream reading functions make it hard. This has been updated to handle
//this scenario in a 64-bit process using multiple buffers, delivered first as an OOB for
//compatibility.
if (needToLoadIntoMemory)
{
if (_compressedSize > Int32.MaxValue)
{
if (!s_allowLargeZipArchiveEntriesInUpdateMode)
{
message = SR.EntryTooLarge;
return false;
}
}
}
}
return true;
}
private Boolean SizesTooLarge()
{
return _compressedSize > UInt32.MaxValue || _uncompressedSize > UInt32.MaxValue;
}
//return value is true if we allocated an extra field for 64 bit headers, un/compressed size
private Boolean WriteLocalFileHeader(Boolean isEmptyFile)
{
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
//_entryname only gets set when we read in or call moveTo. MoveTo does a check, and
//reading in should not be able to produce a entryname longer than UInt16.MaxValue
Debug.Assert(_storedEntryNameBytes.Length <= UInt16.MaxValue);
//decide if we need the Zip64 extra field:
Zip64ExtraField zip64ExtraField = new Zip64ExtraField();
Boolean zip64Used = false;
UInt32 compressedSizeTruncated, uncompressedSizeTruncated;
//if we already know that we have an empty file don't worry about anything, just do a straight shot of the header
if (isEmptyFile)
{
CompressionMethod = CompressionMethodValues.Stored;
compressedSizeTruncated = 0;
uncompressedSizeTruncated = 0;
Debug.Assert(_compressedSize == 0);
Debug.Assert(_uncompressedSize == 0);
Debug.Assert(_crc32 == 0);
}
else
{
//if we have a non-seekable stream, don't worry about sizes at all, and just set the right bit
//if we are using the data descriptor, then sizes and crc should be set to 0 in the header
if (_archive.Mode == ZipArchiveMode.Create && _archive.ArchiveStream.CanSeek == false && !isEmptyFile)
{
_generalPurposeBitFlag |= BitFlagValues.DataDescriptor;
zip64Used = false;
compressedSizeTruncated = 0;
uncompressedSizeTruncated = 0;
//the crc should not have been set if we are in create mode, but clear it just to be sure
Debug.Assert(_crc32 == 0);
}
else //if we are not in streaming mode, we have to decide if we want to write zip64 headers
{
if (SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| (_archive._forceZip64 && _archive.Mode == ZipArchiveMode.Update)
#endif
)
{
zip64Used = true;
compressedSizeTruncated = ZipHelper.Mask32Bit;
uncompressedSizeTruncated = ZipHelper.Mask32Bit;
//prepare Zip64 extra field object. If we have one of the sizes, the other must go in there
zip64ExtraField.CompressedSize = _compressedSize;
zip64ExtraField.UncompressedSize = _uncompressedSize;
VersionToExtractAtLeast(ZipVersionNeededValues.Zip64);
}
else
{
zip64Used = false;
compressedSizeTruncated = (UInt32)_compressedSize;
uncompressedSizeTruncated = (UInt32)_uncompressedSize;
}
}
}
//save offset
_offsetOfLocalHeader = writer.BaseStream.Position;
//calculate extra field. if zip64 stuff + original extraField aren't going to fit, dump the original extraField, because this is more important
Int32 bigExtraFieldLength = (zip64Used ? zip64ExtraField.TotalSize : 0)
+ (_lhUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_lhUnknownExtraFields) : 0);
UInt16 extraFieldLength;
if (bigExtraFieldLength > UInt16.MaxValue)
{
extraFieldLength = (UInt16)(zip64Used ? zip64ExtraField.TotalSize : 0);
_lhUnknownExtraFields = null;
}
else
{
extraFieldLength = (UInt16)bigExtraFieldLength;
}
//write header
writer.Write(ZipLocalFileHeader.SignatureConstant);
writer.Write((UInt16)_versionToExtract);
writer.Write((UInt16)_generalPurposeBitFlag);
writer.Write((UInt16)CompressionMethod);
writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); //UInt32
writer.Write(_crc32); //UInt32
writer.Write(compressedSizeTruncated); //UInt32
writer.Write(uncompressedSizeTruncated); //UInt32
writer.Write((UInt16)_storedEntryNameBytes.Length);
writer.Write(extraFieldLength); //UInt16
writer.Write(_storedEntryNameBytes);
if (zip64Used)
zip64ExtraField.WriteBlock(_archive.ArchiveStream);
if (_lhUnknownExtraFields != null)
ZipGenericExtraField.WriteAllBlocks(_lhUnknownExtraFields, _archive.ArchiveStream);
return zip64Used;
}
private void WriteLocalFileHeaderAndDataIfNeeded()
{
//_storedUncompressedData gets frozen here, and is what gets written to the file
if (_storedUncompressedData != null || _compressedBytes != null)
{
if (_storedUncompressedData != null)
{
_uncompressedSize = _storedUncompressedData.Length;
//The compressor fills in CRC and sizes
//The DirectToArchiveWriterStream writes headers and such
using (Stream entryWriter = new DirectToArchiveWriterStream(
GetDataCompressor(_archive.ArchiveStream, true, null),
this))
{
_storedUncompressedData.Seek(0, SeekOrigin.Begin);
_storedUncompressedData.CopyTo(entryWriter);
_storedUncompressedData.Dispose();
_storedUncompressedData = null;
}
}
else
{
// we know the sizes at this point, so just go ahead and write the headers
if (_uncompressedSize == 0)
CompressionMethod = CompressionMethodValues.Stored;
WriteLocalFileHeader(false);
foreach (Byte[] compressedBytes in _compressedBytes)
{
_archive.ArchiveStream.Write(compressedBytes, 0, compressedBytes.Length);
}
}
}
else //there is no data in the file, but if we are in update mode, we still need to write a header
{
if (_archive.Mode == ZipArchiveMode.Update || !_everOpenedForWrite)
{
_everOpenedForWrite = true;
WriteLocalFileHeader(true);
}
}
}
/* Using _offsetOfLocalHeader, seeks back to where CRC and sizes should be in the header,
* writes them, then seeks back to where you started
* Assumes that the stream is currently at the end of the data
*/
private void WriteCrcAndSizesInLocalHeader(Boolean zip64HeaderUsed)
{
Int64 finalPosition = _archive.ArchiveStream.Position;
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
Boolean zip64Needed = SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
;
Boolean pretendStreaming = zip64Needed && !zip64HeaderUsed;
UInt32 compressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (UInt32)_compressedSize;
UInt32 uncompressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (UInt32)_uncompressedSize;
/* first step is, if we need zip64, but didn't allocate it, pretend we did a stream write, because
* we can't go back and give ourselves the space that the extra field needs.
* we do this by setting the correct property in the bit flag */
if (pretendStreaming)
{
_generalPurposeBitFlag |= BitFlagValues.DataDescriptor;
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToBitFlagFromHeaderStart,
SeekOrigin.Begin);
writer.Write((UInt16)_generalPurposeBitFlag);
}
/* next step is fill out the 32-bit size values in the normal header. we can't assume that
* they are correct. we also write the CRC */
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToCrcFromHeaderStart,
SeekOrigin.Begin);
if (!pretendStreaming)
{
writer.Write(_crc32);
writer.Write(compressedSizeTruncated);
writer.Write(uncompressedSizeTruncated);
}
else //but if we are pretending to stream, we want to fill in with zeroes
{
writer.Write((UInt32)0);
writer.Write((UInt32)0);
writer.Write((UInt32)0);
}
/* next step: if we wrote the 64 bit header initially, a different implementation might
* try to read it, even if the 32-bit size values aren't masked. thus, we should always put the
* correct size information in there. note that order of uncomp/comp is switched, and these are
* 64-bit values
* also, note that in order for this to be correct, we have to insure that the zip64 extra field
* is alwasy the first extra field that is written */
if (zip64HeaderUsed)
{
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.SizeOfLocalHeader
+ _storedEntryNameBytes.Length + Zip64ExtraField.OffsetToFirstField,
SeekOrigin.Begin);
writer.Write(_uncompressedSize);
writer.Write(_compressedSize);
_archive.ArchiveStream.Seek(finalPosition, SeekOrigin.Begin);
}
// now go to the where we were. assume that this is the end of the data
_archive.ArchiveStream.Seek(finalPosition, SeekOrigin.Begin);
/* if we are pretending we did a stream write, we want to write the data descriptor out
* the data descriptor can have 32-bit sizes or 64-bit sizes. In this case, we always use
* 64-bit sizes */
if (pretendStreaming)
{
writer.Write(_crc32);
writer.Write(_compressedSize);
writer.Write(_uncompressedSize);
}
}
private void WriteDataDescriptor()
{
// data descriptor can be 32-bit or 64-bit sizes. 32-bit is more compatible, so use that if possible
// signature is optional but recommended by the spec
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
writer.Write(ZipLocalFileHeader.DataDescriptorSignature);
writer.Write(_crc32);
if (SizesTooLarge())
{
writer.Write(_compressedSize);
writer.Write(_uncompressedSize);
}
else
{
writer.Write((UInt32)_compressedSize);
writer.Write((UInt32)_uncompressedSize);
}
}
private void UnloadStreams()
{
if (_storedUncompressedData != null)
_storedUncompressedData.Dispose();
_compressedBytes = null;
_outstandingWriteStream = null;
}
private void CloseStreams()
{
//if the user left the stream open, close the underlying stream for them
if (_outstandingWriteStream != null)
{
_outstandingWriteStream.Dispose();
}
}
private void VersionToExtractAtLeast(ZipVersionNeededValues value)
{
if (_versionToExtract < value)
{
_versionToExtract = value;
}
}
private void ThrowIfInvalidArchive()
{
if (_archive == null)
throw new InvalidOperationException(SR.DeletedEntry);
_archive.ThrowIfDisposed();
}
/// <summary>
/// Gets the file name of the path based on Windows path separator characters
/// </summary>
private static string GetFileName_Windows(string path)
{
int length = path.Length;
for (int i = length; --i >= 0;)
{
char ch = path[i];
if (ch == '\\' || ch == '/' || ch == ':')
return path.Substring(i + 1);
}
return path;
}
/// <summary>
/// Gets the file name of the path based on Unix path separator characters
/// </summary>
private static string GetFileName_Unix(string path)
{
int length = path.Length;
for (int i = length; --i >= 0;)
if (path[i] == '/')
return path.Substring(i + 1);
return path;
}
#endregion Privates
#region Nested Types
private class DirectToArchiveWriterStream : Stream
{
#region fields
private Int64 _position;
private CheckSumAndSizeWriteStream _crcSizeStream;
private Boolean _everWritten;
private Boolean _isDisposed;
private ZipArchiveEntry _entry;
private Boolean _usedZip64inLH;
private Boolean _canWrite;
#endregion
#region constructors
//makes the assumption that somewhere down the line, crcSizeStream is eventually writing directly to the archive
//this class calls other functions on ZipArchiveEntry that write directly to the archive
public DirectToArchiveWriterStream(CheckSumAndSizeWriteStream crcSizeStream, ZipArchiveEntry entry)
{
_position = 0;
_crcSizeStream = crcSizeStream;
_everWritten = false;
_isDisposed = false;
_entry = entry;
_usedZip64inLH = false;
_canWrite = true;
}
#endregion
#region properties
public override Int64 Length
{
get
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override Int64 Position
{
get
{
Contract.Ensures(Contract.Result<Int64>() >= 0);
ThrowIfDisposed();
return _position;
}
set
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override Boolean CanRead { get { return false; } }
public override Boolean CanSeek { get { return false; } }
public override Boolean CanWrite { get { return _canWrite; } }
#endregion
#region methods
private void ThrowIfDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(this.GetType().ToString(), SR.HiddenStreamName);
}
public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.ReadingNotSupported);
}
public override Int64 Seek(Int64 offset, SeekOrigin origin)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
public override void SetLength(Int64 value)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SetLengthRequiresSeekingAndWriting);
}
//careful: assumes that write is the only way to write to the stream, if writebyte/beginwrite are implemented
//they must set _everWritten, etc.
public override void Write(Byte[] buffer, Int32 offset, Int32 count)
{
//we can't pass the argument checking down a level
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentNeedNonNegative);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentNeedNonNegative);
if ((buffer.Length - offset) < count)
throw new ArgumentException(SR.OffsetLengthInvalid);
Contract.EndContractBlock();
ThrowIfDisposed();
Debug.Assert(CanWrite);
//if we're not actually writing anything, we don't want to trigger the header
if (count == 0)
return;
if (!_everWritten)
{
_everWritten = true;
//write local header, we are good to go
_usedZip64inLH = _entry.WriteLocalFileHeader(false);
}
_crcSizeStream.Write(buffer, offset, count);
_position += count;
}
public override void Flush()
{
ThrowIfDisposed();
Debug.Assert(CanWrite);
_crcSizeStream.Flush();
}
protected override void Dispose(Boolean disposing)
{
if (disposing && !_isDisposed)
{
_crcSizeStream.Dispose(); //now we have size/crc info
if (!_everWritten)
{
//write local header, no data, so we use stored
_entry.WriteLocalFileHeader(true);
}
else
{
//go back and finish writing
if (_entry._archive.ArchiveStream.CanSeek)
//finish writing local header if we have seek capabilities
_entry.WriteCrcAndSizesInLocalHeader(_usedZip64inLH);
else
//write out data descriptor if we don't have seek capabilities
_entry.WriteDataDescriptor();
}
_canWrite = false;
_isDisposed = true;
}
base.Dispose(disposing);
}
#endregion
} // DirectToArchiveWriterStream
[Flags]
private enum BitFlagValues : ushort { DataDescriptor = 0x8, UnicodeFileName = 0x800 }
private enum CompressionMethodValues : ushort { Stored = 0x0, Deflate = 0x8 }
private enum OpenableValues { Openable, FileNonExistent, FileTooLarge }
#endregion Nested Types
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !NETSTANDARD1_3 && !NETSTANDARD1_5
namespace NLog.Internal.NetworkSenders
{
using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
internal sealed class SslSocketProxy : ISocket, IDisposable
{
readonly AsyncCallback _sendCompleted;
readonly SocketProxy _socketProxy;
readonly string _host;
readonly SslProtocols _sslProtocol;
SslStream _sslStream;
public SslSocketProxy(string host, SslProtocols sslProtocol, SocketProxy socketProxy)
{
_socketProxy = socketProxy;
_host = host;
_sslProtocol = sslProtocol;
_sendCompleted = (ar) => SocketProxySendCompleted(ar);
}
public void Close()
{
if (_sslStream != null)
_sslStream.Close();
else
_socketProxy.Close();
}
public bool ConnectAsync(SocketAsyncEventArgs args)
{
var proxyArgs = new TcpNetworkSender.MySocketAsyncEventArgs();
proxyArgs.RemoteEndPoint = args.RemoteEndPoint;
proxyArgs.Completed += SocketProxyConnectCompleted;
proxyArgs.UserToken = args;
if (!_socketProxy.ConnectAsync(proxyArgs))
{
SocketProxyConnectCompleted(this, proxyArgs);
return false;
}
return true;
}
private void SocketProxySendCompleted(IAsyncResult asyncResult)
{
var proxyArgs = asyncResult.AsyncState as TcpNetworkSender.MySocketAsyncEventArgs;
try
{
_sslStream.EndWrite(asyncResult);
}
catch (SocketException ex)
{
if (proxyArgs != null)
proxyArgs.SocketError = ex.SocketErrorCode;
}
catch (Exception ex)
{
if (proxyArgs != null)
{
if (ex.InnerException is SocketException socketException)
proxyArgs.SocketError = socketException.SocketErrorCode;
else
proxyArgs.SocketError = SocketError.OperationAborted;
}
}
finally
{
proxyArgs?.RaiseCompleted();
}
}
private void SocketProxyConnectCompleted(object sender, SocketAsyncEventArgs e)
{
var proxyArgs = e.UserToken as TcpNetworkSender.MySocketAsyncEventArgs;
if (e.SocketError != SocketError.Success)
{
if (proxyArgs != null)
{
proxyArgs.SocketError = e.SocketError;
proxyArgs.RaiseCompleted();
}
}
else
{
try
{
_sslStream = new SslStream(new NetworkStream(_socketProxy.UnderlyingSocket), false, UserCertificateValidationCallback)
{
// Wait 20 secs before giving up on SSL-handshake
ReadTimeout = 20000
};
AuthenticateAsClient(_sslStream, _host, _sslProtocol);
}
catch (SocketException ex)
{
if (proxyArgs != null)
proxyArgs.SocketError = ex.SocketErrorCode;
}
catch (Exception ex)
{
if (proxyArgs != null)
{
proxyArgs.SocketError = GetSocketError(ex);
}
}
finally
{
proxyArgs?.RaiseCompleted();
}
}
}
private static SocketError GetSocketError(Exception ex)
{
SocketError socketError;
if (ex.InnerException is SocketException socketException)
{
socketError = socketException.SocketErrorCode;
}
else
{
socketError = SocketError.ConnectionRefused;
}
return socketError;
}
private static void AuthenticateAsClient(SslStream sslStream, string targetHost, SslProtocols enabledSslProtocols)
{
if (enabledSslProtocols != SslProtocols.Default)
sslStream.AuthenticateAsClient(targetHost, null, enabledSslProtocols, false);
else
sslStream.AuthenticateAsClient(targetHost);
}
private static bool UserCertificateValidationCallback(object sender, object certificate, object chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Common.InternalLogger.Debug("SSL certificate errors were encountered when establishing connection to the server: {0}, Certificate: {1}", sslPolicyErrors, certificate);
return false;
}
public bool SendAsync(SocketAsyncEventArgs args)
{
_sslStream.BeginWrite(args.Buffer, args.Offset, args.Count, _sendCompleted, args);
return true;
}
public bool SendToAsync(SocketAsyncEventArgs args)
{
return SendAsync(args);
}
public void Dispose()
{
if (_sslStream != null)
_sslStream.Dispose();
else
_socketProxy.Dispose();
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using ProtoCore.DSASM.Mirror;
using ProtoTestFx.TD;
namespace ProtoTest.TD.Associative
{
class InlineCondition
{
public TestFrameWork thisTest = new TestFrameWork();
string testPath = "..\\..\\..\\Scripts\\TD\\Associative\\InlineCondition\\";
[SetUp]
public void Setup()
{
}
[Test]
[Category("SmokeTest")]
public void T001_Inline_Using_Function_Call()
{
string src = @"
def fo1 : int(a1 : int)
{
return = a1 * a1;
}
a = 10;
b = 20;
smallest1 = a < b ? a : b;
largest1 = a > b ? a : b;
d = fo1(a);
smallest2 = (fo1(a)) < (fo1(b)) ? (fo1(a)) : (fo1(a)); //100
largest2 = (fo1(a)) > (fo1(b)) ? (fo1(a)) : (fo1(b)); //400
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
Assert.IsTrue((Int64)mirror.GetValue("smallest2").Payload == 100);
Assert.IsTrue((Int64)mirror.GetValue("largest2").Payload == 400);
}
[Test]
[Category("SmokeTest")]
public void T002_Inline_Using_Math_Lib_Functions()
{
string src = @" class Math
{
static def Sqrt ( a : var )
{
return = a/2.0;
}
}
def fo1 :int(a1 : int)
{
return = a1 * a1;
}
a = 10;
b = 20;
smallest1 = a < b ? a : b; //10
largest1 = a > b ? a : b; //20
smallest2 = Math.Sqrt(fo1(a)) < Math.Sqrt(fo1(b)) ? Math.Sqrt(fo1(a)) : Math.Sqrt(fo1(a)); //50.0
largest2 = Math.Sqrt(fo1(a)) > Math.Sqrt(fo1(b)) ? Math.Sqrt(fo1(a)) : Math.Sqrt(fo1(b)); //200.0
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
Assert.IsTrue((Double)mirror.GetValue("smallest2").Payload == 50.0);
Assert.IsTrue((Double)mirror.GetValue("largest2").Payload == 200.0);
}
[Test]
[Category("Replication")]
public void T003_Inline_Using_Collection()
{
//Assert.Fail("1456751 - Sprint16 : Rev 990 : Inline conditions not working with replication over collections");
string src = @"
Passed = 1;
Failed = 0;
Einstein = 56;
BenBarnes = 90;
BenGoh = 5;
Rameshwar = 80;
Jun = 68;
Roham = 50;
Smartness = { BenBarnes, BenGoh, Jun, Rameshwar, Roham }; // { 1, 0, 1, 1, 0 }
Results = Smartness > Einstein ? Passed : Failed;
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
List<Object> result = new List<object>() { 1, 0, 1, 1, 0, };
Assert.IsTrue(mirror.CompareArrays("Results", result, typeof(System.Int64)));
}
[Test]
[Category("Replication")]
public void T005_Inline_Using_2_Collections_In_Condition()
{
//Assert.Fail("1456751 - Sprint16 : Rev 990 : Inline conditions not working with replication over collections");
string src = @"
a1 = 1..3..1;
b1 = 4..6..1;
a2 = 1..3..1;
b2 = 4..7..1;
a3 = 1..4..1;
b3 = 4..6..1;
c1 = a1 > b1 ? true : false; // { false, false, false }
c2 = a2 > b2 ? true : false; // { false, false, false }
c3 = a3 > b3 ? true : false; // { false, false, false, null }
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
List<Object> c1 = new List<object>() { false, false, false };
List<Object> c2 = new List<object>() { false, false, false };
List<Object> c3 = new List<object>() { false, false, false };
Assert.IsTrue(mirror.CompareArrays("c1", c1, typeof(System.Boolean)));
Assert.IsTrue(mirror.CompareArrays("c2", c2, typeof(System.Boolean)));
Assert.IsTrue(mirror.CompareArrays("c3", c3, typeof(System.Boolean)));
}
[Test]
[Category("Replication")]
public void T006_Inline_Using_Different_Sized_1_Dim_Collections()
{
//Assert.Fail("1456751 - Sprint16 : Rev 990 : Inline conditions not working with replication over collections");
string src = @"
a = 10 ;
b = ((a - a / 2 * 2) > 0)? a : a+1 ; //11
c = 5;
d = ((c - c / 2 * 2) > 0)? c : c+1 ; //5
e1 = ((b>(d-b+d))) ? d : (d+1); //5
//inline conditional, returning different sized collections
c1 = {1,2,3};
c2 = {1,2};
a1 = {1, 2, 3, 4};
b1 = a1>3?true:a1; // expected : {1, 2, 3, true}
b2 = a1>3?true:c1; // expected : {1, 2, 3}
b3 = a1>3?c1:c2; // expected : {1, 2}
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Object[] b = new Object[] { 1, 2, 3, 4 };
Object[] c = new Object[] { 1, 2, 3 };
Object[] d = new Object[] { 1, 2 };
Object[] b1 = new Object[] { b, b, b, true };
Object[] b2 = new Object[] { c, c, c, true };
Object[] b3 = new Object[] { d, d, d, c };
thisTest.Verify("b1", b1);
thisTest.Verify("b2", b2);
thisTest.Verify("b3", b3);
}
[Test]
[Category("Replication")]
public void T007_Inline_Using_Collections_And_Replication()
{
string src = @"
def even : int(a : int)
{
return = a * 2;
}
a =1..10..1 ; //{1,2,3,4,5,6,7,8,9,10}
i = 1..5;
b = ((a[i] % 2) > 0)? even(a[i]) : a ; // { 1, 6, 3, 10, 5 }
c = ((a[0] % 2) > 0)? even(a[i]) : a ; // { 4, 6, 8, 10, 12 }
d = ((a[-2] % 2) == 0)? even(a[i]) : a ; // { 1, 2,..10}
e1 = (a[-2] == d[9])? 9 : a[1..2]; // { 2, 3 }
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// following verification might need to be updated for current implementation, once the defect above is fixed
// b = ((a[i] % 2) > 0)? even(a[i]) : a;
// replication only is supported on condition, not the overall expression.
// List<Object> b = new List<object>() { 1, 6, 3, 10, 5 };
// Assert.IsTrue(mirror.CompareArrays("b", b, typeof(System.Int64)));
List<Object> c = new List<object>() { 4, 6, 8, 10, 12 };
List<Object> d = new List<object>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<Object> e1 = new List<object>() { 2, 3 };
Assert.IsTrue(mirror.CompareArrays("c", c, typeof(System.Int64)));
Assert.IsTrue(mirror.CompareArrays("d", d, typeof(System.Int64)));
Assert.IsTrue(mirror.CompareArrays("e1", e1, typeof(System.Int64)));
}
[Test]
[Category("Replication")]
public void T008_Inline_Returing_Different_Ranks()
{
//Assert.Fail("1456751 - Sprint16 : Rev 990 : Inline conditions not working with replication over collections");
string src = @"
a = { 0, 1, 2, 4};
x = a > 1 ? 0 : {1,1}; // { 1, 1} ?
x_0 = x[0];
x_1 = x[1];
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Object[] b1 = new Object[] { new Object[] { 1, 1 }, new Object[] { 1, 1 }, 0, 0 };
thisTest.Verify("x", b1);
}
[Test]
[Category("Replication")]
public void T004_Inline_Inside_Class_Constructor_and_replication()
{
//Assert.Fail("1456751 - Sprint16 : Rev 990 : Inline conditions not working with replication over collections");
string src = @"class MyClass
{
positive : var;
constructor ByValue(value : int)
{
positive = value >= 0 ? true : false;
}
}
number = 2;
sample = MyClass.ByValue(number);
values = sample.positive; // { true, false }
number = { 3, -3 };
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
// expected "StatementUsedInAssignment" warning
List<Object> values = new List<object>() { true, false };
Assert.IsTrue(mirror.CompareArrays("values", values, typeof(System.Boolean)));
}
[Test]
[Category("Replication")]
public void T009_Inline_Using_Function_Call_And_Collection_And_Replication()
{
String errmsg = "1467166 - Sprint24 : rev 3133 : Regression : comparison of collection with singleton should yield null in imperative scope";
string src = @"
def even(a : int)
{
return = a * 2;
}
def odd(a : int )
{
return = a* 2 + 1;
}
x = 1..3;
a = ((even(5) > odd(3)))? even(5) : even(3); //10
b = ((even(x) > odd(x+1)))?odd(x+1):even(x) ; // {2,4,6}
c = odd(even(3)); // 13
d = ((a > c))?even(odd(c)) : odd(even(c)); //53
";
thisTest.VerifyRunScriptSource(src, errmsg);
Object n1 = null;
thisTest.Verify("b", new object[] { new object[] { 2, 4, 6 }, new object[] { 2, 4, 6 }, new object[] { 2, 4, 6 } });
thisTest.Verify("a", 10);
thisTest.Verify("c", 13);
thisTest.Verify("d", 53);
}
[Test]
[Category("Imperative")]
public void T010_Defect_1456751_replication_issue()
{
String errmsg = "1467166 - VALIDATION NEEDED - Sprint24 : rev 3133 : Regression : comparison of collection with singleton should yield null in imperative scope";
string src = @"xx;
x1;
x2;
x3;
x4;
[Imperative]
{
a = { 0, 1, 2};
b = { 3, 11 };
c = 5;
d = { 6, 7, 8, 9};
e = { 10 };
xx = 1 < a ? a : 5; // expected:5
yy = 0;
if( 1 < a )
yy = a;
else
yy = 5;
x1 = a < 5 ? b : 5; // expected:5
t1 = x1[0];
t2 = x1[1];
c1 = 0;
for (i in x1)
{
c1 = c1 + 1;
}
x2 = 5 > b ? b : 5; // expected:f
t3 = x2[0];
t4 = x2[1];
c2 = 0;
for (i in x2)
{
c2 = c2 + 1;
}
x3 = b < d ? b : e; // expected: {10}
t5 = x3[0];
c3 = 0;
for (i in x3)
{
c3 = c3 + 1;
}
x4 = b > e ? d : { 0, 1}; // expected {0,1}
t7 = x4[0];
c4 = 0;
for (i in x4)
{
c4 = c4 + 1;
}
}
/*
Expected :
result1 = { 5, 5, 2 };
thisTest.Verification(mirror, ""xx"", result1, 1);
thisTest.Verification(mirror, ""t1"", 3, 1);
thisTest.Verification(mirror, ""t2"", 11, 1);
thisTest.Verification(mirror, ""c1"", 2, 1);
thisTest.Verification(mirror, ""t3"", 3, 1);
thisTest.Verification(mirror, ""t4"", 5, 1);
thisTest.Verification(mirror, ""c2"", 2, 1);
thisTest.Verification(mirror, ""t5"", 3, 1);
thisTest.Verification(mirror, ""c3"", 1, 1);
thisTest.Verification(mirror, ""t7"", 0, 1);
thisTest.Verification(mirror, ""c4"", 1, 1);*/
";
thisTest.VerifyRunScriptSource(src, errmsg);
thisTest.Verify("xx", 5);
thisTest.Verify("x1", 5);
thisTest.Verify("x2", 5);
thisTest.Verify("x3", new object[] { 10 });
thisTest.Verify("x4", new object[] { 0, 1 });
}
[Test]
[Category("SmokeTest")]
public void T010_Defect_1456751_execution_on_both_true_and_false_path_issue()
{
string src = @"
a = 0;
def foo ( )
{
a = a + 1;
return = a;
}
x = 1 > 2 ? foo() + 1 : foo() + 2;
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
thisTest.Verify("x", 3);
thisTest.Verify("a", 1);
}
[Test]
[Category("SmokeTest")]
public void T011_Defect_1467281_conditionals()
{
string code =
@"x = 2 == { };
y = {}==null;
z = {{1}}=={1};
z2 = { { 1 } } == 1;
z3=1=={{1}};
z4={1}=={{1}};";
thisTest.RunScriptSource(code);
thisTest.SetErrorMessage("1467281 Sprint 26 - Rev 3695 [Design Decision] incorrect conditional tests on empty arrays ");
thisTest.Verify("x", false); //WAITING FOR DESIGN DECISION
thisTest.Verify("y", false);//WAITING FOR DESIGN DECISION
thisTest.Verify("z", null);
thisTest.Verify("z2", new object[] { new object[] { true } });
thisTest.Verify("z3", new object[] { new object[] { true } });
thisTest.Verify("z4", null);
}
[Test]
public void T012_Defect_1467288()
{
string code =
@"c = 0;
a = { 0, 1, 2 };
a = c > 1 ? a : a + 1;
//expected : { 1, 2, 3 }";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("a", new Object[] { 1, 2, 3 });
}
[Test]
public void T012_Defect_1467288_2()
{
string code =
@"
class A
{
a:var[]..[];
constructor A( c )
{
a = { 0, 1, 2 };
a = c > 1 ? a : a + 1;
}
}
x = { A.A(0), A.A(2)};
a1 = x.a;
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("a1", new Object[] { new Object[] { 1, 2, 3 }, new Object[] { 0, 1, 2 } });
}
[Test]
public void T012_Defect_1467288_3()
{
string code =
@"
class A
{
a:var[]..[];
constructor A( c )
{
a = { 0, 1, 2 };
a = c > 1 ? a : a + 1;
}
def foo (c)
{
a = c == 4 ? a : a + 1;
return = a;
}
}
x = { A.A(0), A.A(2)};
a1 = x.a;
test = a1.foo(5);
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("a1", new Object[] { new Object[] { 1, 2, 3 }, new Object[] { 0, 1, 2 } });
}
[Test]
public void T012_Defect_1467288_4()
{
string code =
@"
class A
{
a;
constructor A( c )
{
a = { 0, 1, 2 };
a = c > 1 ? a : a + 1;
}
}
x = { A.A(0), A.A(2)};
a = x.a;
//expected : { { 1,2,3}, {0,1,2} }
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("a", new Object[] { new Object[] { 1, 2, 3 }, new Object[] { 0, 1, 2 } });
}
[Test]
public void T012_Defect_1467288_5()
{
string code =
@"
class A
{
a : var[]..[];
constructor A( c )
{
a = { 0, 1, 2 };
a = c > 1 ? a : a + 1;
}
}
x = { A.A(0), A.A(2)};
a = x.a;
";
string errmsg = "1467288 - sprint25: rev 3731 : REGRESSION : NullReferenceException when using the same collection in both paths of a inline condition";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("a", new Object[] { new Object[] { 1, 2, 3 }, new Object[] { 0, 1, 2 } });
}
[Test]
public void T012_Defect_1467288_6()
{
string code =
@"
class A
{
a:var[]..[];
constructor A( c )
{
a = { 0, 1, 2 };
a = c > 1 ? a : a + 1;
}
def foo (c)
{
a = c == 4 ? a : a + 1;
return = a;
}
}
x = { A.A(0), A.A(2)};
a1 = x.a;
test = x.foo(5);
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("a1", new Object[] { new Object[] { 2, 3, 4 }, new Object[] { 1, 2, 3 } });
}
[Test]
public void T013_Defect_1467290()
{
string code =
@"c = 0;
x = 10;
x = c > 1 ? 3 : 4;
[Imperative]
{
c = 3;
}
test = x;";
string errmsg = "";//1467290 sprint25: rev 3731 : REGRESSION : Update with inline condition across multiple language blocks is not working as expected";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("x", 3);
}
[Test]
public void T013_Defect_1467290_2()
{
string code =
@"c = 0;
x = 10;
a = 1;
b = {1,2};
x = c > 1 ? a : b;
[Imperative]
{
c = 3;
a = 2;
}
test = x;";
string errmsg = "";//1467290 sprint25: rev 3731 : REGRESSION : Update with inline condition across multiple language blocks is not working as expected";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("x", 2);
}
[Test]
public void T013_Defect_1467290_3()
{
string code =
@"c = 0;
x = 10;
a = 1;
b = {1,2};
x = c > 1 ? a : b;
[Imperative]
{
c = 3;
a = 2;
[Associative]
{
c = -1;
b = { 2,3};
}
}
test = x;";
string errmsg = "";//1467290 sprint25: rev 3731 : REGRESSION : Update with inline condition across multiple language blocks is not working as expected";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("x", new Object[] { 2, 3 });
}
[Test]
public void T013_Defect_1467290_4()
{
string code =
@"c = 0;
x = 10;
a = {1,2};
x = c > 1 ? a : a +1;
[Imperative]
{
c = 3;
a = {2,3};
[Associative]
{
c = -1;
a = { 0,1};
}
}
test = x;";
string errmsg = "";//1467290 sprint25: rev 3731 : REGRESSION : Update with inline condition across multiple language blocks is not working as expected";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("x", new Object[] { 1, 2 });
}
[Test]
public void T014_InlineConditionContainUndefinedType()
{
string code = @"
x = C ? 1 : 0;
";
string errmsg = "";//DNL-1467449 Rev 4596 : REGRESSION : Undefined variables in inline condition causes Compiler Error";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("x", 0);
}
[Test]
public void T014_InlineConditionContainUndefinedType_2()
{
string code = @"
def foo ()
{
x = C ? 1 : 0;
return = x;
}
test = foo();
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("test", 0);
}
[Test]
public void T014_InlineConditionContainUndefinedType_3()
{
string code = @"
class A
{
static def foo ()
{
x = C==1 ? 1 : 0;
C = 1;
return = x;
}
}
test = A.foo();
";
string errmsg = "1467449 - Rev 4596 : REGRESSION : Undefined variables in inline condition causes Compiler Error";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("test", 1);
}
[Test]
public void T014_InlineConditionContainUndefinedType_4()
{
string code = @"
def foo ()
{
x = C == 1? 1 : 0;
C = 1;
return = x;
}
test = foo();
";
string errmsg = "1467449 - Rev 4596 : REGRESSION : Undefined variables in inline condition causes Compiler Error";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("test", 1);
}
[Test]
public void T014_InlineConditionContainUndefinedType_5()
{
string code = @"
x = C==1 ? 1 : 0;
C = 1;
";
string errmsg = "1467449 - Rev 4596 : REGRESSION : Undefined variables in inline condition causes Compiler Error";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("x", 1);
}
[Test]
public void T015_conditionequalto_1467482()
{
string code = @"
c = true;
d = c== true;
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", true);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T016_conditionnotequalto_1467482_2()
{
string code = @"
c = false;
d = c!= true;
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", true);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T017_conditionequalto_1467482_3()
{
string code = @"
d;
[Imperative]
{
c = true;
d = c== true;
}
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", true);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T018_conditionequalto_1467482_4()
{
string code = @"
d;
[Imperative]
{
c = false;
d = c!= true;
}
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", true);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T018_conditionequalto_1467503_5()
{
string code = @"
d;
c = false;
d = c!= null;
";
string errmsg = "1467503- null comparison returns null, it should return true or false";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", true);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T018_conditionequalto_1467503_6()
{
string code = @"
d;
c = false;
d = c== null;
";
string errmsg = "1467503- null comparison returns null, it should return true or false";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", false);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T018_conditionequalto_1467503_7()
{
string code = @"
d;
[Imperative]
{
c = false;
d = c== null;
}
";
string errmsg = "1465048- null comparison returns null, it should return true or false";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", false);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T018_conditionequalto_1467503_8()
{
string code = @"
d;
[Imperative]
{
c = false;
d = c!= null;
}
";
string errmsg = "1467503-null comparison returns null, it should return true or false";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", true);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T018_conditionequalto_1467403_9()
{
string code = @"
d;
c = null;
d = c== null;
";
string errmsg = "1467403 -in conditional it throws error could not decide which function to execute , for valid code a,d gives the correct result as well ";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", true);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T018_conditionequalto_1467403_10()
{
string code = @"
d;
c = null;
d = c!= null;
";
string errmsg = "1467403- in conditional it throws error could not decide which function to execute , for valid code a,d gives the correct result as well ";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", false);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T018_conditionequalto_1467403_11()
{
string code = @"
d;
[Imperative]
{
c = null;
d = c== null;
}
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", true);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T018_conditionequalto_1467403_12()
{
string code = @"
d;
[Imperative]
{
c = null;
d = c!= null;
}
";
string errmsg = "1467403 -in conditional it throws error could not decide which function to execute , for valid code a,d gives the correct result as well ";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", false);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T018_conditionequalto_1467403_13()
{
string code = @"
e;
c : int = 1;
d : int[] = { 1, 0 };
e = c == d;
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("e", new object[] { true, false });
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T018_conditionequalto_1467504_14()
{
string code = @"
e;
[Imperative]
{
c : int = 1;
d : int[] = { 1, 0 };
e = c == d;
}
";
string errmsg = "1467504-conditonal - comparison with an single vs array returns null in imperative block ";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("e", false);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T019_conditionequalto_1467469()
{
string code = @"
e;
class A{ a1 = 1; }
class B{ b2 = 2; }
a = A.A();
b = B.B();
c = 1 == 2;
d = a == b;
";
string errmsg = "1467469 equal to with user defined always returns true ";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("d", false);
thisTest.VerifyRuntimeWarningCount(0);
}
[Test]
public void T020_1467442()
{
string code = @"
z = 1;
z = (z > 0) ? 1 : 2;
z = 3;
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("z", 3);
}
[Test]
public void T021_1467442()
{
string code = @"
b = 0;
a = b;
z = 0;
z = z + ((a > 0) ? a : 0);
b = 5;
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("z", 5);
}
[Test]
public void T021_1467442_2()
{
string code = @"
z = 0;
z = z + ((a > 0) ? a : 0);
a = 1;
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("z", 1);
}
[Test]
public void T021_1467442_3()
{
string code = @"
def foo ()
{
z = z + ((a > 0) ? a : 0);
a = 1;
}
z = 0;
test = foo();
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("z", 1);
}
[Test]
public void T021_1467442_4()
{
string code = @"
class A
{
constructor A ()
{
z = z + ((a > 0) ? a : 0);
a = 1;
}
}
z = 0;
t1 = A.A();
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("z", 1);
}
[Test]
public void T021_1467442_5()
{
string code = @"
a = 1;
b = 1;
c = 1;
z = a > 0 ? (b > 1 ? 0 : 1 ) : ( c > 1 ? 2 : 3);
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("z", 1);
}
[Test]
public void T021_1467442_6()
{
string code = @"
def foo ( x : double)
{
return = 0;
}
def foo ( x : bool)
{
return = 1;
}
a = 1;
z = foo ( a > 0 ? 1.4 : false );
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("z", 0);
}
[Test]
public void T021_1467442_7()
{
string code = @"
def foo ( x : double)
{
return = 0;
}
def foo ( x : bool)
{
return = 1;
}
a = {-1, 1};
z = foo ( a > 0 ? 1.4 : false );
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("z", new Object[] { 1, 0 });
}
[Test]
public void T021_1467442_8()
{
string code = @"
class A
{
static def foo ( x : double)
{
return = 0;
}
static def foo ( x : bool)
{
return = 1;
}
}
a = {-1, 1};
z = A.foo ( a > 0 ? 1.4 : false );
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("z", new Object[] { 1, 0 });
}
[Test]
public void T021_1467442_9()
{
string code = @"
def foo ( x )
{
return = x;
}
def foo2 ( x )
{
return = x;
}
a = {-1, 1};
z = foo2 ( a > 0 ? foo(1) : foo(2) );
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("z", new Object[] { 2, 1 });
}
[Test]
public void T021_1467442_10()
{
string code = @"
def foo ( x )
{
return = x;
}
def foo2 ( x )
{
return = x;
}
a = {-1, 1};
z;
[Imperative]
{
for ( i in 0..1 )
{
z[i] = foo2 ( a[i] > 0 ? foo(1) : foo(2) );
}
}
";
string errmsg = "";
thisTest.VerifyRunScriptSource(code, errmsg);
thisTest.Verify("z", new Object[] { 2, 1 });
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: DocumentGridContextMenu.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Context menu for DocumentGrid
//
//---------------------------------------------------------------------------
namespace MS.Internal.Documents
{
using MS.Internal;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using System.Runtime.InteropServices;
using System.Security;
using MS.Internal.Documents;
using System.Security.Permissions;
using MS.Win32;
using System.Windows.Interop;
// A Component of DocumentViewer supporting the default ContextMenu.
internal static class DocumentGridContextMenu
{
//------------------------------------------------------
//
// Class Internal Methods
//
//------------------------------------------------------
#region Class Internal Methods
// Registers the event handler for DocumentGrid.
/// <SecurityNote>
/// Critical: This code hooks up a call back to context menu opening event which has the ability to spoof copy
/// TreatAsSafe: This code does not expose the callback and does not drive any input into it
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
internal static void RegisterClassHandler()
{
EventManager.RegisterClassHandler(typeof(DocumentGrid), FrameworkElement.ContextMenuOpeningEvent, new ContextMenuEventHandler(OnContextMenuOpening));
EventManager.RegisterClassHandler(typeof(DocumentApplicationDocumentViewer), FrameworkElement.ContextMenuOpeningEvent, new ContextMenuEventHandler(OnDocumentViewerContextMenuOpening));
}
#endregion Class Internal Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Callback for FrameworkElement.ContextMenuOpeningEvent, when fired from DocumentViewer. This is
/// here to catch the event when it is fired by the keyboard rather than the mouse.
/// </summary>
/// <SecurityNote>
/// Critical - forwards user-initiated information to OnContextMenuOpening, which is also SecurityCritical
/// </SecurityNote>
[SecurityCritical]
private static void OnDocumentViewerContextMenuOpening(object sender, ContextMenuEventArgs e)
{
if (e.CursorLeft == KeyboardInvokedSentinel)
{
DocumentViewer dv = sender as DocumentViewer;
if (dv != null && dv.ScrollViewer != null)
{
OnContextMenuOpening(dv.ScrollViewer.Content, e);
}
}
}
// Callback for FrameworkElement.ContextMenuOpeningEvent.
// If the control is using the default ContextMenu, we initialize it
// here.
/// <SecurityNote>
/// Critical - accepts a parameter which may be used to set the userInitiated
/// bit on a command, which is used for security purposes later.
/// </SecurityNote>
[SecurityCritical]
private static void OnContextMenuOpening(object sender, ContextMenuEventArgs e)
{
DocumentGrid documentGrid = sender as DocumentGrid;
ContextMenu contextMenu;
if (documentGrid == null)
{
return;
}
// We only want to programmatically generate the menu for Mongoose
if (!(documentGrid.DocumentViewerOwner is DocumentApplicationDocumentViewer))
return;
// If the DocumentViewer or ScrollViewer has a ContextMenu set, the DocumentGrid menu should be ignored
if (documentGrid.DocumentViewerOwner.ContextMenu != null || documentGrid.DocumentViewerOwner.ScrollViewer.ContextMenu != null)
return;
// Start by grabbing whatever's set to the UiScope's ContextMenu property.
contextMenu = documentGrid.ContextMenu;
// If someone explicitly set it null -- don't mess with it.
if (documentGrid.ReadLocalValue(FrameworkElement.ContextMenuProperty) == null)
return;
// If it's not null, someone's overriding our default -- don't mess with it.
if (contextMenu != null)
return;
// It's a default null, so spin up a temporary ContextMenu now.
contextMenu = new ViewerContextMenu();
contextMenu.Placement = PlacementMode.RelativePoint;
contextMenu.PlacementTarget = documentGrid;
((ViewerContextMenu)contextMenu).AddMenuItems(documentGrid, e.UserInitiated);
Point uiScopeMouseDownPoint;
if (e.CursorLeft == KeyboardInvokedSentinel)
{
uiScopeMouseDownPoint = new Point(.5 * documentGrid.ViewportWidth, .5 * documentGrid.ViewportHeight);
}
else
{
uiScopeMouseDownPoint = Mouse.GetPosition(documentGrid);
}
contextMenu.HorizontalOffset = uiScopeMouseDownPoint.X;
contextMenu.VerticalOffset = uiScopeMouseDownPoint.Y;
// This line raises a public event.
contextMenu.IsOpen = true;
e.Handled = true;
}
#endregion Private methods
//------------------------------------------------------
//
// Private Constants
//
//------------------------------------------------------
#region Private Constants
private const double KeyboardInvokedSentinel = -1.0; // e.CursorLeft has this value when the menu is invoked with the keyboard.
#endregion
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Types
// Default ContextMenu for TextBox and RichTextBox.
private class ViewerContextMenu : ContextMenu
{
// Initialize the context menu.
// Creates a new instance.
/// <SecurityNote>
/// Critical - accepts a parameter which may be used to set the userInitiated
/// bit on a command, which is used for security purposes later.
/// Although there is a demand here to prevent non userinitiated
/// code paths to be blocked this function is not TreatAsSafe because
/// we want to track any new callers to this call
/// </SecurityNote>
[SecurityCritical]
internal void AddMenuItems(DocumentGrid dg, bool userInitiated)
{
// create a special menu item for paste which only works for user initiated copy
// within the confines of partial trust this cannot be done programmatically
if (userInitiated == false)
{
SecurityHelper.DemandAllClipboardPermission();
}
this.Name = "ViewerContextMenu";
SetMenuProperties(new EditorMenuItem(), dg, ApplicationCommands.Copy); // Copy will be marked as user initiated
// build menu for XPSViewer
SetMenuProperties(new MenuItem(), dg, ApplicationCommands.SelectAll);
AddSeparator();
SetMenuProperties(
new MenuItem(),
dg,
NavigationCommands.PreviousPage,
SR.Get(SRID.DocumentApplicationContextMenuPreviousPageHeader),
SR.Get(SRID.DocumentApplicationContextMenuPreviousPageInputGesture));
SetMenuProperties(
new MenuItem(),
dg,
NavigationCommands.NextPage,
SR.Get(SRID.DocumentApplicationContextMenuNextPageHeader),
SR.Get(SRID.DocumentApplicationContextMenuNextPageInputGesture));
SetMenuProperties(
new MenuItem(),
dg,
NavigationCommands.FirstPage,
null, //menu header
SR.Get(SRID.DocumentApplicationContextMenuFirstPageInputGesture));
SetMenuProperties(
new MenuItem(),
dg,
NavigationCommands.LastPage,
null, //menu header
SR.Get(SRID.DocumentApplicationContextMenuLastPageInputGesture));
AddSeparator();
SetMenuProperties(new MenuItem(), dg, ApplicationCommands.Print);
}
private void AddSeparator()
{
this.Items.Add(new Separator());
}
//Helper to set properties on the menu items based on the command
private void SetMenuProperties(MenuItem menuItem, DocumentGrid dg, RoutedUICommand command)
{
SetMenuProperties(menuItem, dg, command, null, null);
}
private void SetMenuProperties(MenuItem menuItem, DocumentGrid dg, RoutedUICommand command, string header, string inputGestureText)
{
menuItem.Command = command;
menuItem.CommandTarget = dg.DocumentViewerOwner; // the text editor expects the commands to come from the DocumentViewer
if (header == null)
{
menuItem.Header = command.Text; // use default menu text for this command
}
else
{
menuItem.Header = header;
}
if (inputGestureText != null)
{
menuItem.InputGestureText = inputGestureText;
}
menuItem.Name = "ViewerContextMenu_" + command.Name; // does not require localization
this.Items.Add(menuItem);
}
}
// Default EditorContextMenu item base class.
// Used to distinguish our items from anything an application
// may have added.
private class EditorMenuItem : MenuItem
{
internal EditorMenuItem() : base() {}
/// <SecurityNote>
/// Critical - accepts a parameter which may be used to set the userInitiated
/// bit on a command, which is used for security purposes later.
/// </SecurityNote>
[SecurityCritical]
internal override void OnClickCore(bool userInitiated)
{
OnClickImpl(userInitiated);
}
}
#endregion Private Types
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct01.strct01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct01.strct01;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
public int Foo(dynamic x = null, dynamic y = default(dynamic))
{
if (x == null && y == null)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct01a.strct01a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct01a.strct01a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
public int Foo(int? x = 2, int? y = 1)
{
if (x == 2 && y == 1)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
dynamic d = 1;
return p.Foo(y: d);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct03.strct03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct03.strct03;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
public int Foo(dynamic x, dynamic y = null)
{
if (x == 2 && y == null)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(2);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct03a.strct03a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct03a.strct03a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
public int Foo(int? x, int? y = 1)
{
if (x == 2 && y == 1)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
dynamic d = 2;
return p.Foo(d);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct05.strct05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct05.strct05;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters. multiple optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
public int Foo(dynamic z, dynamic x = null, dynamic y = null)
{
if (z == 1 && x == null && y == null)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(1);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct05a.strct05a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct05a.strct05a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters. multiple optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
public int Foo(int? z, int? x = 2, int? y = 1)
{
if (z == 1 && x == 2 && y == 1)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
dynamic d = 1;
return p.Foo(d);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct06a.strct06a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct06a.strct06a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters. Expressions used</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
public int Foo(int? z = 1 + 1)
{
if (z == 2)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct07a.strct07a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct07a.strct07a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters. Max int</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
public int Foo(int? z = 2147483647)
{
if (z == 2147483647)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct09a.strct09a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct09a.strct09a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
public int Foo(long? z = (long)1)
{
if (z == 1)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct12.strct12
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct12.strct12;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public struct Parent
{
public int Foo(
[Optional]
dynamic i)
{
if (i == System.Type.Missing)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct12a.strct12a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct12a.strct12a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public struct Parent
{
public int Foo(
[Optional]
int ? i)
{
if (i == null)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct13.strct13
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct13.strct13;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public struct Parent
{
public int Foo(
[Optional]
dynamic i, [Optional]
long j, [Optional]
float f, [Optional]
dynamic d)
{
if (d == System.Type.Missing)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct13a.strct13a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct13a.strct13a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public struct Parent
{
public int Foo(
[Optional]
int ? i, [Optional]
long ? j, [Optional]
float ? f, [Optional]
decimal ? d)
{
if (d == null)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct14a.strct14a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct14a.strct14a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description> Declaration of OPs with constant values</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
private const int x = 1;
public int Foo(long? z = x)
{
if (z == 1)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct18a.strct18a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct18a.strct18a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description> Declaration of OPs with constant values</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
private const string x = "test";
public int Foo(string z = x)
{
if (z == "test")
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct19a.strct19a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct19a.strct19a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description> Declaration of OPs with constant values</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
private const bool x = true;
public int Foo(bool? z = x)
{
if ((bool)z)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct20a.strct20a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.strct.strct20a.strct20a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description> Declaration of OPs with constant values</Description>
// <Expects status=success></Expects>
// <Code>
public struct Parent
{
public int Foo(string z = "test", int? y = 3)
{
if (z == "test" && y == 3)
return 1;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
try
{
p.Foo(3, "test");
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Parent.Foo(string, int?)");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using System.Linq;
using System.Runtime.CompilerServices;
using Scriban.Helpers;
using Scriban.Runtime;
using Scriban.Syntax;
namespace Scriban.Parsing
{
public partial class Parser
{
private ScriptBlockStatement ParseBlockStatement(ScriptStatement parentStatement, bool parseEndOfStatementAfterEnd = true)
{
Debug.Assert(!(parentStatement is ScriptBlockStatement));
Blocks.Push(parentStatement);
_blockLevel++;
EnterExpression();
var blockStatement = Open<ScriptBlockStatement>();
ScriptStatement statement;
bool hasEnd;
while (TryParseStatement(parentStatement, parseEndOfStatementAfterEnd, out statement, out hasEnd))
{
// statement may be null if we have parsed an else continuation of a previous block
if (statement != null)
{
blockStatement.Statements.Add(statement);
}
if (hasEnd)
{
break;
}
}
if (!hasEnd)
{
// If there are any end block not matching, we have an error
if (_blockLevel > 1)
{
if (_isLiquid)
{
var syntax = ScriptSyntaxAttribute.Get(parentStatement);
LogError(parentStatement, parentStatement?.Span ?? CurrentSpan, $"The `end{syntax.TypeName}` was not found");
}
else
{
// unit test: 201-if-else-error2.txt
LogError(parentStatement, GetSpanForToken(Previous), $"The <end> statement was not found");
}
}
}
LeaveExpression();
_blockLevel--;
Blocks.Pop();
return Close(blockStatement);
}
private bool TryParseStatement(ScriptStatement parent, bool parseEndOfStatementAfterEnd, out ScriptStatement statement, out bool hasEnd)
{
hasEnd = false;
bool nextStatement = true;
statement = null;
continueParsing:
if (_hasFatalError)
{
return false;
}
if (_pendingStatements.Count > 0)
{
statement = _pendingStatements.Dequeue();
return true;
}
switch (Current.Type)
{
case TokenType.Eof:
// Early exit
nextStatement = false;
break;
case TokenType.Raw:
case TokenType.Escape:
statement = ParseRawStatement();
if (parent is ScriptCaseStatement)
{
// In case we have a raw statement within directly a case
// we don't keep it
statement = null;
goto continueParsing;
}
break;
case TokenType.CodeEnter:
case TokenType.LiquidTagEnter:
case TokenType.CodeExit:
case TokenType.LiquidTagExit:
case TokenType.EscapeEnter:
case TokenType.EscapeExit:
statement = ParseEscapeStatement();
break;
case TokenType.FrontMatterMarker:
if (_inFrontMatter)
{
_inFrontMatter = false;
_inCodeSection = false;
// Parse the frontmatter end-marker
ExpectAndParseTokenTo(_frontmatter.EndMarker, TokenType.FrontMatterMarker);
Close(_frontmatter);
_frontmatter.TextPositionAfterEndMarker = Current.Start;
if (CurrentParsingMode == ScriptMode.FrontMatterAndContent || CurrentParsingMode == ScriptMode.FrontMatterOnly)
{
// Once the FrontMatter has been parsed, we can switch to default parsing mode.
CurrentParsingMode = ScriptMode.Default;
nextStatement = false;
}
}
else
{
LogError($"Unexpected frontmatter marker `{_lexer.Options.FrontMatterMarker}` while not inside a frontmatter");
NextToken();
}
break;
default:
if (_inCodeSection)
{
switch (Current.Type)
{
case TokenType.NewLine:
case TokenType.SemiColon:
PushTokenToTrivia();
NextToken();
goto continueParsing;
case TokenType.Identifier:
case TokenType.IdentifierSpecial:
var identifier = GetAsText(Current);
if (_isLiquid)
{
ParseLiquidStatement(identifier, parent, ref statement, ref hasEnd, ref nextStatement);
}
else
{
ParseScribanStatement(identifier, parent, parseEndOfStatementAfterEnd, ref statement, ref hasEnd, ref nextStatement);
}
break;
default:
if (IsStartOfExpression())
{
statement = ParseExpressionStatement();
}
else
{
nextStatement = false;
LogError($"Unexpected token {GetAsText(Current)}");
}
break;
}
}
else
{
nextStatement = false;
LogError($"Unexpected token {GetAsText(Current)} while not in a code block {{ ... }}");
// LOG an ERROR. Don't expect any other tokens outside a code section
}
break;
}
return nextStatement;
}
private ScriptCaptureStatement ParseCaptureStatement()
{
var captureStatement = Open<ScriptCaptureStatement>();
ExpectAndParseKeywordTo(captureStatement.CaptureKeyword); // Parse capture keyword
// unit test: 231-capture-error1.txt
captureStatement.Target = ExpectAndParseExpression(captureStatement);
ExpectEndOfStatement();
captureStatement.Body = ParseBlockStatement(captureStatement);
return Close(captureStatement);
}
private ScriptEscapeStatement ParseEscapeStatement()
{
bool isCodeEnter = Current.Type == TokenType.CodeEnter || Current.Type == TokenType.LiquidTagEnter;
bool isEscape = Current.Type == TokenType.EscapeEnter || Current.Type == TokenType.EscapeExit;
bool isEnter = isCodeEnter || Current.Type == TokenType.EscapeEnter;
bool isLiquid = Current.Type == TokenType.LiquidTagEnter || Current.Type == TokenType.LiquidTagExit;
Debug.Assert(isEnter || Current.Type == TokenType.CodeExit || Current.Type == TokenType.LiquidTagExit || isEscape);
// Log errors depending on if we are already in a code section or not
if (isCodeEnter)
{
if (_inCodeSection)
{
LogError("Unexpected token while already in a code block");
}
}
else if (!isEscape)
{
if (!_inCodeSection)
{
LogError("Unexpected code block exit '}}' while no code block enter '{{' has been found");
}
else if (CurrentParsingMode == ScriptMode.ScriptOnly)
{
LogError("Unexpected code clock exit '}}' while parsing in script only mode. '}}' is not allowed.");
}
}
_isLiquidTagSection = isCodeEnter && isLiquid;
_inCodeSection = isCodeEnter;
var scriptEscapeStatement = Open<ScriptEscapeStatement>();
scriptEscapeStatement.IsEntering = isEnter;
var tokenText = GetAsText(Current);
var whitespaceChar = tokenText[isEnter ? tokenText.Length - 1 : 0];
scriptEscapeStatement.WhitespaceMode = whitespaceChar switch
{
'-' => ScriptWhitespaceMode.Greedy,
'~' => ScriptWhitespaceMode.NonGreedy,
_ => ScriptWhitespaceMode.None,
};
if (isEscape)
{
if (_isLiquid)
{
scriptEscapeStatement.EscapeCount = 6;
}
else
{
int escapeCount = tokenText.Length - 2; // minus opening and closing {%{
if (whitespaceChar != (isEnter ? '{' : '}')) escapeCount--;
scriptEscapeStatement.EscapeCount = escapeCount;
}
}
NextToken(); // Skip enter/exit token
return Close(scriptEscapeStatement);
}
private ScriptCaseStatement ParseCaseStatement()
{
var caseStatement = Open<ScriptCaseStatement>();
ExpectAndParseKeywordTo(caseStatement.CaseKeyword); // Parse case keyword
caseStatement.Value = ExpectAndParseExpression(caseStatement, allowAssignment: false);
if (ExpectEndOfStatement())
{
caseStatement.Body = ParseBlockStatement(caseStatement);
}
return Close(caseStatement);
}
private ScriptConditionStatement ParseElseStatement(bool isElseIf)
{
// Case of elsif
if (_isLiquid && isElseIf)
{
return ParseIfStatement(false, ScriptKeyword.Else());
}
// unit test: 200-if-else-statement.txt
var nextToken = PeekToken();
if (!_isLiquid && nextToken.Type == TokenType.Identifier && GetAsText(nextToken) == "if")
{
var elseKeyword = ScriptKeyword.Else();
ExpectAndParseKeywordTo(elseKeyword);
return ParseIfStatement(false, elseKeyword);
}
var elseStatement = Open<ScriptElseStatement>();
ExpectAndParseKeywordTo(elseStatement.ElseKeyword); // Parse else statement
// unit test: 201-if-else-error4.txt
if (ExpectEndOfStatement())
{
elseStatement.Body = ParseBlockStatement(elseStatement);
}
return Close(elseStatement);
}
private ScriptStatement ParseExpressionStatement()
{
var expressionStatement = Open<ScriptExpressionStatement>();
var expression = TransformKeyword(ExpectAndParseExpressionAndAnonymous(expressionStatement));
// Special case, if the expression return should be converted back to a statement
if (expression is ScriptExpressionAsStatement expressionAsStatement)
{
return expressionAsStatement.Statement;
}
expressionStatement.Expression = expression;
ExpectEndOfStatement();
return Close(expressionStatement);
}
private T ParseForStatement<T>() where T : ScriptForStatement, new()
{
var forStatement = Open<T>();
ExpectAndParseKeywordTo(forStatement.ForOrTableRowKeyword); // Parse for or tablerow keyword
// unit test: 211-for-error1.txt
forStatement.Variable = ExpectAndParseExpression(forStatement, mode: ParseExpressionMode.BasicExpression);
if (forStatement.Variable != null)
{
if (!(forStatement.Variable is IScriptVariablePath))
{
LogError(forStatement, $"Expecting a variable instead of `{forStatement.Variable}`");
}
// A global variable used in a for should always be a loop only variable
if (forStatement.Variable is ScriptVariableGlobal previousVar)
{
var loopVar = ScriptVariable.Create(previousVar.BaseName, ScriptVariableScope.Loop);
loopVar.Span = previousVar.Span;
loopVar.Trivias = previousVar.Trivias;
forStatement.Variable = loopVar;
}
// in
if (Current.Type != TokenType.Identifier || GetAsText(Current) != "in")
{
// unit test: 211-for-error2.txt
LogError(forStatement, $"Expecting 'in' word instead of `{GetAsText(Current)}`");
}
else
{
ExpectAndParseKeywordTo(forStatement.InKeyword); // Parse in keyword
}
// unit test: 211-for-error3.txt
forStatement.Iterator = ExpectAndParseExpression(forStatement);
if (ExpectEndOfStatement())
{
forStatement.Body = ParseBlockStatement(forStatement);
}
}
return Close(forStatement);
}
private ScriptIfStatement ParseIfStatement(bool invert, ScriptKeyword elseKeyword = null)
{
// unit test: 200-if-else-statement.txt
var ifStatement = Open<ScriptIfStatement>();
ifStatement.ElseKeyword = elseKeyword;
if (_isLiquid && elseKeyword != null)
{
// Parse elseif
Open(ifStatement.IfKeyword);
NextToken();
Close(ifStatement.IfKeyword);
}
else
{
if (_isLiquid && invert) // we have an unless
{
Open(ifStatement.IfKeyword); // still transfer trivias to IfKeyword
NextToken();
Close(ifStatement.IfKeyword);
}
else
{
ExpectAndParseKeywordTo(ifStatement.IfKeyword); // Parse if keyword
}
}
var condition = ExpectAndParseExpression(ifStatement, allowAssignment: false);
// Transform a `if condition` to `if !(condition)`
if (invert)
{
var invertCondition = ScriptUnaryExpression.Wrap(ScriptUnaryOperator.Not, ScriptToken.Exclamation(), ScriptNestedExpression.Wrap(condition, _isKeepTrivia), _isKeepTrivia);
condition = invertCondition;
}
ifStatement.Condition = condition;
if (ExpectEndOfStatement())
{
ifStatement.Then = ParseBlockStatement(ifStatement);
}
return Close(ifStatement);
}
private ScriptRawStatement ParseRawStatement()
{
bool isEscape = Current.Type == TokenType.Escape;
var scriptStatement = Open<ScriptRawStatement>();
scriptStatement.IsEscape = isEscape;
// We keep span End here to update it with the raw span
var spanStart = Current.Start;
var spanEnd = Current.End;
NextToken(); // Skip raw or escape count
Close(scriptStatement);
// Because the previous will update the ScriptStatement with the wrong Span End for escape (escapecount1+)
// We make sure that we use the span end of the Raw token
scriptStatement.Span.End = spanEnd;
// Update the index of the slice/length
scriptStatement.Text = new ScriptStringSlice(_lexer.Text, spanStart.Offset, spanEnd.Offset - spanStart.Offset + 1);
return scriptStatement;
}
private ScriptWhenStatement ParseWhenStatement()
{
var whenStatement = Open<ScriptWhenStatement>();
ExpectAndParseKeywordTo(whenStatement.WhenKeyword); // Parse when keyword
// Parse the when values
// - a, b, c
// - a || b || c (scriban)
// - a or b or c (liquid)
while (true)
{
if (!IsVariableOrLiteral(Current))
{
break;
}
var variableOrLiteral = ParseVariableOrLiteral();
whenStatement.Values.Add(variableOrLiteral);
if (Current.Type == TokenType.Comma || (!_isLiquid && Current.Type == TokenType.DoubleVerticalBar) || (_isLiquid && GetAsText(Current) == "or"))
{
NextToken();
}
}
if (whenStatement.Values.Count == 0)
{
LogError(Current, "When is expecting at least one value.");
}
if (ExpectEndOfStatement())
{
whenStatement.Body = ParseBlockStatement(whenStatement);
}
return Close(whenStatement);
}
private void CheckNotInCase(ScriptStatement parent, Token token)
{
if (parent is ScriptCaseStatement)
{
// 205-case-when-statement-error1.txt
LogError(token, $"Unexpected statement/expression `{GetAsText(token)}` in the body of a `case` statement. Only `when`/`else` are expected.");
}
}
private ScriptVariable ExpectAndParseVariable(ScriptNode parentNode)
{
if (parentNode == null) throw new ArgumentNullException(nameof(parentNode));
if (Current.Type == TokenType.Identifier || Current.Type == TokenType.IdentifierSpecial)
{
var variableOrLiteral = ParseVariable();
var variable = variableOrLiteral as ScriptVariable;
if (variable != null && variable.Scope != ScriptVariableScope.Loop)
{
return (ScriptVariable)variableOrLiteral;
}
LogError(parentNode, $"Unexpected variable `{variableOrLiteral}`");
}
else
{
LogError(parentNode, $"Expecting a variable instead of `{GetAsText(Current)}`");
}
return null;
}
private bool ExpectEndOfStatement()
{
if (_isLiquid)
{
if (Current.Type == TokenType.CodeExit || (_isLiquidTagSection && Current.Type == TokenType.LiquidTagExit))
{
return true;
}
}
else if (Current.Type == TokenType.NewLine || Current.Type == TokenType.CodeExit || Current.Type == TokenType.SemiColon || Current.Type == TokenType.Eof)
{
if (Current.Type == TokenType.NewLine || Current.Type == TokenType.SemiColon)
{
PushTokenToTrivia();
FlushTriviasToLastTerminal();
NextToken();
}
return true;
}
// If we are not finding an end of statement, log a fatal error
LogError(CurrentSpan, $"Invalid token found `{GetAsText(Current)}`. Expecting <EOL>/end of line.", true);
return false;
}
private ScriptStatement FindFirstStatementExpectingEnd()
{
foreach (var scriptNode in Blocks)
{
if (ExpectStatementEnd(scriptNode))
{
return (ScriptStatement)scriptNode;
}
}
return null;
}
private static bool ExpectStatementEnd(ScriptNode scriptNode)
{
return (scriptNode is ScriptIfStatement && !((ScriptIfStatement)scriptNode).IsElseIf)
|| scriptNode is ScriptForStatement
|| scriptNode is ScriptCaptureStatement
|| scriptNode is ScriptWithStatement
|| scriptNode is ScriptWhileStatement
|| scriptNode is ScriptWrapStatement
|| scriptNode is ScriptCaseStatement
|| scriptNode is ScriptFunction
|| scriptNode is ScriptAnonymousFunction;
}
/// <summary>
/// Used internally to transform an expression into a statement
/// </summary>
private partial class ScriptExpressionAsStatement : ScriptExpression
{
public ScriptExpressionAsStatement(ScriptStatement statement)
{
Statement = statement;
}
public ScriptStatement Statement { get; }
public override object Evaluate(TemplateContext context)
{
throw new NotSupportedException();
}
public override void PrintTo(ScriptPrinter printer)
{
throw new NotSupportedException();
}
public override void Accept(ScriptVisitor visitor)
{
throw new NotSupportedException();
}
public override TResult Accept<TResult>(ScriptVisitor<TResult> visitor)
{
throw new NotSupportedException();
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace SysInternalsUpdater
{
[DebuggerDisplay("{FileName} ({FileSize}kb) - {LastChangedOn}")]
internal class SysInternalFile : ViewModelBase
{
private LiveSysInternals sysInternals;
public string SaveToDirectory { get; set; }
public SysInternalFile(LiveSysInternals liveSysInternals, Match match, string line)
{
this.sysInternals = liveSysInternals;
this.match = match;
this.SaveToDirectory = liveSysInternals.SaveFilesTo;
RelativePath = match.Groups[1].Value;
FileName = match.Groups[2].Value;
if (FileName.ToLower().EndsWith(".exe") || FileName.ToLower().EndsWith(".chm") || FileName.ToLower().EndsWith(".hlp"))
{
line = line.Remove(match.Index).Trim();
FileSize = Convert.ToInt32(line.Remove(0, line.LastIndexOf(" ")).Trim());
line = line.Remove(line.LastIndexOf(" "));
LastChangedOn = Convert.ToDateTime(line.Trim());
IsNew = DateTime.UtcNow.Subtract(LastChangedOn).TotalDays < 7;
UpdateCommandBools();
this.sysInternals.SaveFilesToChanged += LiveSysInternals_SaveFilesToChanged;
}
}
public async Task DownloadFile()
{
if (!IsDownloading && (ShowDownloadNow || ShowUpdateNow))
{
IsDownloading = true;
try
{
WebClient client = new WebClient();
await client.DownloadFileTaskAsync(DownloadFrom, SaveFileTo + ".tmp");
File.Delete(SaveFileTo);
File.Move(SaveFileTo + ".tmp", SaveFileTo);
File.SetCreationTime(SaveFileTo, LastChangedOn);
IsDownloading = false;
UpdateCommandBools();
}
catch (Exception ex)
{
IsDownloading = false;
MessageBox.Show(ex.ToString(), "error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
if (File.Exists(SaveFileTo + ".tmp"))
{
try
{
File.Delete(SaveFileTo + ".tmp");
}
catch
{ }
}
}
}
}
private string fileName = string.Empty;
public string FileName
{
get
{
return fileName;
}
set
{
base.UpdateProperty(ref fileName, value);
}
}
private string downloadFrom = string.Empty;
public string DownloadFrom
{
get
{
return downloadFrom;
}
set
{
base.UpdateProperty(ref downloadFrom, value);
}
}
private bool isDownloading = false;
public bool IsDownloading
{
get
{
return isDownloading;
}
set
{
base.UpdateProperty(ref isDownloading, value);
UpdateCommandBools();
}
}
private int fileSize = 0;
public int FileSize
{
get
{
return fileSize;
}
set
{
base.UpdateProperty(ref fileSize, value);
base.RaisePropertyChanged("FileSizeString");
}
}
public string FileSizeString
{
get
{
return (fileSize / 1000D).ToString("F2") + "kb";
}
}
private bool isNew = false;
public bool IsNew
{
get
{
return isNew;
}
set
{
base.UpdateProperty(ref isNew, value);
base.RaisePropertyChanged("IsNewVisibility");
}
}
public Visibility IsNewVisibility
{
get
{
return isNew ? Visibility.Visible : Visibility.Hidden;
}
}
private bool showDownloadNow = false;
public bool ShowDownloadNow
{
get
{
return showDownloadNow;
}
set
{
base.UpdateProperty(ref showDownloadNow, value);
}
}
private bool showUpdateNow = false;
public bool ShowUpdateNow
{
get
{
return showUpdateNow;
}
set
{
base.UpdateProperty(ref showUpdateNow, value);
base.RaisePropertyChanged("LastChangedOn");
base.RaisePropertyChanged("LastChangedOnDisplay");
base.RaisePropertyChanged("CurrentFileDate");
base.RaisePropertyChanged("CurrentFileDateDisplay");
base.RaisePropertyChanged("ShowUpdateVisibility");
}
}
private bool showOpen = false;
public bool ShowOpen
{
get
{
return showOpen;
}
set
{
base.UpdateProperty(ref showOpen, value);
}
}
public Visibility ShowUpdateVisibility
{
get
{
return ShowUpdateNow ? Visibility.Visible : Visibility.Collapsed;
}
}
private string saveFileTo = string.Empty;
private Match match;
public string SaveFileTo
{
get
{
return saveFileTo;
}
set
{
base.UpdateProperty(ref saveFileTo, value);
}
}
private void LiveSysInternals_SaveFilesToChanged(string location)
{
this.SaveToDirectory = location;
UpdateCommandBools();
}
public void UpdateCommandBools()
{
SaveFileTo = Path.Combine(SaveToDirectory, RelativePath.TrimStart('/'));
DownloadFrom = Path.Combine(LiveSysInternals.LiveSysInternalsUrl, RelativePath.TrimStart('/'));
ShowDownloadNow = !File.Exists(SaveFileTo) && !IsDownloading;
ShowUpdateNow = File.Exists(SaveFileTo) && !IsDownloading && LastChangedOn != File.GetCreationTime(SaveFileTo);
ShowOpen = File.Exists(SaveFileTo) && !IsDownloading;
}
private string relativePath = string.Empty;
public string RelativePath
{
get
{
return relativePath;
}
set
{
base.UpdateProperty(ref relativePath, value);
}
}
private DateTime lastChangedOn = DateTime.MinValue;
public DateTime LastChangedOn
{
get
{
return lastChangedOn;
}
set
{
base.UpdateProperty(ref lastChangedOn, value);
}
}
public DateTime? CurrentFileDate
{
get
{
if (File.Exists(SaveFileTo))
{
return File.GetCreationTime(SaveFileTo);
}
return null;
}
}
public string LastChangedOnDisplay
{
get
{
return LastChangedOn.ToString("dd MMM yyyy");
}
}
public string CurrentFileDateDisplay
{
get
{
return CurrentFileDate.HasValue ? CurrentFileDate.Value.ToString("dd MMM yyyy") : string.Empty;
}
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using Rc.Models;
namespace Rc.Migrations
{
[DbContext(typeof(RcContext))]
[Migration("20151208023803_ArticleAddDraft")]
partial class ArticleAddDraft
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348");
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("Rc.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("Rc.Models.Article", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CategoryId");
b.Property<string>("Content");
b.Property<DateTime>("CreatedDate");
b.Property<string>("CreatedUserId");
b.Property<DateTime?>("DeletedDate");
b.Property<string>("DeletedUserId");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsDraft");
b.Property<string>("Markdown");
b.Property<string>("PicUrl");
b.Property<string>("Summary");
b.Property<string>("Title")
.IsRequired();
b.Property<DateTime?>("UpdatedDate");
b.Property<string>("UpdatedUserId");
b.HasKey("Id");
});
modelBuilder.Entity("Rc.Models.ArticleTag", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("ArticleId");
b.Property<int>("TagId");
b.HasKey("Id");
});
modelBuilder.Entity("Rc.Models.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired();
b.Property<int>("Sort");
b.HasKey("Id");
});
modelBuilder.Entity("Rc.Models.Tag", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired();
b.HasKey("Id");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("Rc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("Rc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("Rc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Rc.Models.Article", b =>
{
b.HasOne("Rc.Models.Category")
.WithMany()
.HasForeignKey("CategoryId");
b.HasOne("Rc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("CreatedUserId");
b.HasOne("Rc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("DeletedUserId");
b.HasOne("Rc.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UpdatedUserId");
});
modelBuilder.Entity("Rc.Models.ArticleTag", b =>
{
b.HasOne("Rc.Models.Article")
.WithMany()
.HasForeignKey("ArticleId");
b.HasOne("Rc.Models.Tag")
.WithMany()
.HasForeignKey("TagId");
});
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
namespace _4PosBackOffice.NET
{
internal partial class frmWHlist : System.Windows.Forms.Form
{
string gFilter;
ADODB.Recordset gRS;
string gFilterSQL;
int gID;
short gSection;
private void loadLanguage()
{
//frmWHlist = No Code [Select a Warehouse]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmWHlist.Caption = rsLang("LanguageLayoutLnk_Description"): frmWHlist.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1080;
//Search|Checked
if (modRecordSet.rsLang.RecordCount){lbl.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;lbl.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1065;
//New|Checked
if (modRecordSet.rsLang.RecordCount){cmdNew.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdNew.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmWHlist.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
public int getItem()
{
cmdNew.Visible = false;
loadLanguage();
this.ShowDialog();
return gID;
}
public int doAction(ref short lSection)
{
gSection = lSection;
loadLanguage();
this.ShowDialog();
}
private void getNamespace()
{
}
private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.Close();
}
private void cmdNamespace_Click()
{
My.MyProject.Forms.frmFilter.loadFilter(ref gFilter);
getNamespace();
}
private void cmdNew_Click(System.Object eventSender, System.EventArgs eventArgs)
{
bool nwWH = false;
nwWH = true;
My.MyProject.Forms.frmWH.loadItem(ref 0);
doSearch();
}
private void DataList1_DblClick(System.Object eventSender, System.EventArgs eventArgs)
{
if (!string.IsNullOrEmpty(DataList1.BoundText)) {
//If gSection Then
// Select Case gSection
// Case 1
// report_POS DataList1.BoundText
// End Select
// Exit Sub
//Else
My.MyProject.Forms.frmWH.loadItem(ref Convert.ToInt32(DataList1.BoundText));
//End If
}
doSearch();
}
private void DataList1_KeyPress(System.Object eventSender, KeyPressEventArgs eventArgs)
{
switch (eventArgs.KeyChar) {
case Strings.ChrW(13):
DataList1_DblClick(DataList1, new System.EventArgs());
eventArgs.KeyChar = Strings.ChrW(0);
break;
case Strings.ChrW(27):
this.Close();
eventArgs.KeyChar = Strings.ChrW(0);
break;
}
}
private void frmWHlist_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
KeyAscii = 0;
cmdExit_Click(cmdExit, new System.EventArgs());
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmWHlist_Load(System.Object eventSender, System.EventArgs eventArgs)
{
object nwWH = null;
//UPGRADE_WARNING: Couldn't resolve default property of object nwWH. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
nwWH = false;
doSearch();
}
private void frmWHlist_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
gRS.Close();
}
private void txtSearch_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
txtSearch.SelectionStart = 0;
txtSearch.SelectionLength = 999;
}
private void txtSearch_KeyDown(System.Object eventSender, System.Windows.Forms.KeyEventArgs eventArgs)
{
short KeyCode = eventArgs.KeyCode;
short Shift = eventArgs.KeyData / 0x10000;
switch (KeyCode) {
case 40:
this.DataList1.Focus();
break;
}
}
private void txtSearch_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case 13:
doSearch();
KeyAscii = 0;
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void doSearch()
{
string sql = null;
string lString = null;
lString = Strings.Trim(txtSearch.Text);
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
lString = Strings.Replace(lString, " ", " ");
if (string.IsNullOrEmpty(lString)) {
} else {
lString = "WHERE (Warehouse_Name LIKE '%" + Strings.Replace(lString, " ", "%' AND Warehouse_Name LIKE '%") + "%')";
}
gRS = modRecordSet.getRS(ref "SELECT DISTINCT WarehouseID, Warehouse_Name FROM Warehouse " + lString + " ORDER BY WarehouseID");
//Display the list of Titles in the DataCombo
DataList1.DataSource = gRS;
DataList1.listField = "Warehouse_Name";
//Bind the DataCombo to the ADO Recordset
//UPGRADE_ISSUE: VBControlExtender property DataList1.DataSource is not supported at runtime. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="74E732F3-CAD8-417B-8BC9-C205714BB4A7"'
DataList1.DataSource = gRS;
DataList1.boundColumn = "WarehouseID";
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// ScreenManager.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace Minjie
{
/// <summary>
/// The screen manager is a component which manages one or more GameScreen
/// instances. It maintains a stack of screens, calls their Update and Draw
/// methods at the appropriate times, and automatically routes input to the
/// topmost active screen.
/// </summary>
/// <remarks>Based on a similar class in the Game State Management sample.</remarks>
public class ScreenManager : DrawableGameComponent
{
#region Fields
List<GameScreen> screens = new List<GameScreen>();
List<GameScreen> screensToUpdate = new List<GameScreen>();
InputState input = new InputState();
SpriteBatch spriteBatch;
bool isInitialized;
bool traceEnabled;
#endregion
#region Properties
/// <summary>
/// A default SpriteBatch shared by all the screens. This saves
/// each screen having to bother creating their own local instance.
/// </summary>
public SpriteBatch SpriteBatch
{
get { return spriteBatch; }
}
/// <summary>
/// If true, the manager prints out a list of all the screens
/// each time it is updated. This can be useful for making sure
/// everything is being added and removed at the right times.
/// </summary>
public bool TraceEnabled
{
get { return traceEnabled; }
set { traceEnabled = value; }
}
#endregion
#region Initialization
/// <summary>
/// Constructs a new screen manager component.
/// </summary>
public ScreenManager(Game game)
: base(game)
{
}
/// <summary>
/// Initializes the screen manager component.
/// </summary>
public override void Initialize()
{
base.Initialize();
isInitialized = true;
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
// Load content belonging to the screen manager.
ContentManager content = Game.Content;
spriteBatch = new SpriteBatch(GraphicsDevice);
// Tell each of the screens to load their content.
foreach (GameScreen screen in screens)
{
screen.LoadContent();
}
}
/// <summary>
/// Unload your graphics content.
/// </summary>
protected override void UnloadContent()
{
// Tell each of the screens to unload their content.
foreach (GameScreen screen in screens)
{
screen.UnloadContent();
}
}
#endregion
#region Update and Draw
/// <summary>
/// Allows each screen to run logic.
/// </summary>
public override void Update(GameTime gameTime)
{
// Read the keyboard and gamepad.
input.Update();
// Make a copy of the master screen list, to avoid confusion if
// the process of updating one screen adds or removes others.
screensToUpdate.Clear();
foreach (GameScreen screen in screens)
screensToUpdate.Add(screen);
bool otherScreenHasFocus = !Game.IsActive;
bool coveredByOtherScreen = false;
// Loop as long as there are screens waiting to be updated.
while (screensToUpdate.Count > 0)
{
// Pop the topmost screen off the waiting list.
GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
// Update the screen.
screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
if (screen.ScreenState == ScreenState.Active)
{
// If this is the first active screen we came across,
// give it a chance to handle input.
if (!otherScreenHasFocus)
{
screen.HandleInput(input);
otherScreenHasFocus = true;
}
// inform any subsequent screens that they are covered by this one.
coveredByOtherScreen = true;
}
}
// Print debug trace?
if (traceEnabled)
TraceScreens();
}
/// <summary>
/// Prints a list of all the screens, for debugging.
/// </summary>
void TraceScreens()
{
List<string> screenNames = new List<string>();
foreach (GameScreen screen in screens)
screenNames.Add(screen.GetType().Name);
Trace.WriteLine(string.Join(", ", screenNames.ToArray()));
}
/// <summary>
/// Tells each screen to draw itself.
/// </summary>
public override void Draw(GameTime gameTime)
{
foreach (GameScreen screen in screens)
{
if (screen.ScreenState == ScreenState.Hidden)
continue;
screen.Draw(gameTime);
}
}
#endregion
#region Public Methods
/// <summary>
/// Adds a new screen to the screen manager.
/// </summary>
public void AddScreen(GameScreen screen)
{
screen.ScreenManager = this;
// If we have a graphics device, tell the screen to load content.
if (isInitialized)
{
screen.LoadContent();
}
screens.Add(screen);
}
/// <summary>
/// Removes a screen from the screen manager. You should normally
/// use GameScreen.ExitScreen instead of calling this directly, so
/// the screen can gradually transition off rather than just being
/// instantly removed.
/// </summary>
public void RemoveScreen(GameScreen screen)
{
// If we have a graphics device, tell the screen to unload content.
if (isInitialized)
{
screen.UnloadContent();
}
screens.Remove(screen);
screensToUpdate.Remove(screen);
}
/// <summary>
/// Expose an array holding all the screens. We return a copy rather
/// than the real master list, because screens should only ever be added
/// or removed using the AddScreen and RemoveScreen methods.
/// </summary>
public GameScreen[] GetScreens()
{
return screens.ToArray();
}
#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.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class ReadExisting : PortsTest
{
//The number of random bytes to receive for read method testing
private const int numRndBytesToRead = 8;
//The number of random bytes to receive for large input buffer testing
private const int largeNumRndBytesToRead = 2048;
private enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered };
#region Test Cases
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
private void ASCIIEncoding()
{
VerifyRead(new ASCIIEncoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
private void UTF8Encoding()
{
VerifyRead(new UTF8Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
private void UTF32Encoding()
{
VerifyRead(new UTF32Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
private void SerialPort_ReadBufferedData()
{
int numberOfBytesToRead = 32;
VerifyRead(Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
private void SerialPort_IterativeReadBufferedData()
{
int numberOfBytesToRead = 32;
VerifyRead(Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
private void SerialPort_ReadBufferedAndNonBufferedData()
{
int numberOfBytesToRead = 64;
VerifyRead(Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
private void SerialPort_IterativeReadBufferedAndNonBufferedData()
{
int numberOfBytesToRead = 3;
VerifyRead(Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
private void GreedyRead()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(128, true);
byte[] byteXmitBuffer = new byte[1024];
char utf32Char = TCSupport.GenerateRandomCharNonSurrogate();
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
int numBytes;
Debug.WriteLine("Verifying that ReadExisting() will read everything from internal buffer and drivers buffer");
//Put the first byte of the utf32 encoder char in the last byte of this buffer
//when we read this later the buffer will have to be resized
byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0];
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length);
//Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's
//internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so
//the other 3 bytes of the ut32 encoded char can be in the buffer
com1.Read(new char[1023], 0, 1023);
Assert.Equal(1, com1.BytesToRead);
com1.Encoding = Encoding.UTF32;
com2.Encoding = Encoding.UTF32;
com2.Write(utf32CharBytes, 1, 3);
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
numBytes = Encoding.UTF32.GetByteCount(charXmitBuffer);
byte[] byteBuffer = Encoding.UTF32.GetBytes(charXmitBuffer);
var expectedChars = new char[1 + Encoding.UTF32.GetCharCount(byteBuffer)];
expectedChars[0] = utf32Char;
Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1);
TCSupport.WaitForReadBufferToLoad(com1, 4 + numBytes);
string rcvString = com1.ReadExisting();
Assert.NotNull(rcvString);
char[] actualChars = rcvString.ToCharArray();
Assert.Equal(expectedChars, actualChars);
Assert.Equal(0, com1.BytesToRead);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
private void LargeInputBuffer()
{
VerifyRead(largeNumRndBytesToRead);
}
#endregion
#region Verification for Test Cases
private void VerifyRead()
{
VerifyRead(new ASCIIEncoding(), numRndBytesToRead);
}
private void VerifyRead(int numberOfBytesToRead)
{
VerifyRead(new ASCIIEncoding(), numberOfBytesToRead);
}
private void VerifyRead(Encoding encoding)
{
VerifyRead(encoding, numRndBytesToRead);
}
private void VerifyRead(Encoding encoding, int numberOfBytesToRead)
{
VerifyRead(encoding, numberOfBytesToRead, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(Encoding encoding, int numberOfBytesToRead, ReadDataFromEnum readDataFrom)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
char[] charsToWrite = new char[numberOfBytesToRead];
byte[] bytesToWrite = new byte[numberOfBytesToRead];
//Genrate random chars to send
for (int i = 0; i < bytesToWrite.Length; i++)
{
char randChar = (char)rndGen.Next(0, ushort.MaxValue);
charsToWrite[i] = randChar;
}
Debug.WriteLine("Verifying read method endocing={0} with {1} random chars", encoding.EncodingName,
bytesToWrite.Length);
com1.ReadTimeout = 500;
com1.Encoding = encoding;
TCSupport.SetHighSpeed(com1, com2);
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
bytesToWrite = com1.Encoding.GetBytes(charsToWrite, 0, charsToWrite.Length);
switch (readDataFrom)
{
case ReadDataFromEnum.NonBuffered:
VerifyReadNonBuffered(com1, com2, bytesToWrite);
break;
case ReadDataFromEnum.Buffered:
VerifyReadBuffered(com1, com2, bytesToWrite);
break;
case ReadDataFromEnum.BufferedAndNonBuffered:
VerifyReadBufferedAndNonBuffered(com1, com2, bytesToWrite);
break;
default:
throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null);
}
}
}
private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars);
}
private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
BufferData(com1, com2, bytesToWrite);
PerformReadOnCom1FromCom2(com1, com2, expectedChars);
}
private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
char[] expectedChars = new char[com1.Encoding.GetCharCount(bytesToWrite, 0, bytesToWrite.Length) * 2];
char[] encodedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
Array.Copy(encodedChars, 0, expectedChars, 0, bytesToWrite.Length);
Array.Copy(encodedChars, 0, expectedChars, encodedChars.Length, encodedChars.Length);
BufferData(com1, com2, bytesToWrite);
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars);
}
private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer
Assert.Equal(bytesToWrite.Length, com1.BytesToRead);
}
private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars)
{
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 500;
Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250);
PerformReadOnCom1FromCom2(com1, com2, expectedChars);
}
private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars)
{
string rcvString = com1.ReadExisting();
char[] rcvBuffer = rcvString.ToCharArray();
//Compare the chars that were written with the ones we expected to read
Assert.Equal(expectedChars, rcvBuffer);
Assert.Equal(0, com1.BytesToRead);
}
#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.Threading;
/// <summary>
/// WaitOne
/// </summary>
// Verifies that WaitOne can acquire a
// mutex, that calling it while the mutex is held will
// cause a thread to block, that if the mutex is
// never released then WaitOne throws an
// AbandonedMutexException, and that calling it on a
// disposed-of mutex throws ObjectDisposedException
// this test works for Orcas and Client, but Mutex
// is not supported for Silverlight.
public class WaitHandleWaitOne1
{
#region Private Fields
private const int c_DEFAULT_SLEEP_TIME = 5000; // 1 second
private WaitHandle m_Handle = null;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
// this one tests that a WaitOne will wait on a Mutex
// and then grab it when it is free
public bool PosTest1()
{
bool retVal = false;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("PosTest1: WaitOne returns true when current instance receives a signal");
// m_Handle is of type WaitHandle
// Mutex is a subclass of WaitHandle
using(m_Handle = new Mutex())
{
try
{
// Spin up a thread. SignalMutex grabs
// the Mutex, then goes to sleep for 5 seconds. It
// only releases the mutex after sleeping for those
// 5 seconds
thread = new Thread(new ThreadStart(SignalMutex));
// Start it
thread.Start();
// Then put this calling thread to sleep
// for one second so that it doesn't beat the spawned
// thread to the mutex
Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race
// Now, the spawned thread should already
// have the mutex and be sleeping on it for several
// seconds. try to grab the mutex now. We should
// simply block until the other thread releases it,
// then we should get it.
// Net result, we should get true back from WaitOne
if (m_Handle.WaitOne() != true)
{
TestLibrary.TestFramework.LogError("001", "WaitOne returns false when current instance receives a signal.");
retVal = false;
}
else
{
// got the mutex ok
retVal = true;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
// Wait for the thread to terminate
if (null != thread)
{
// Wait on that thread
thread.Join();
}
}
}
return retVal;
}
#endregion
#region Negative Test Cases
// this one just tests that a WaitOne will receive
// a AbandonedMutexException
public bool NegTest1()
{
bool retVal = false;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("NegTest1: AbandonedMutexException should be thrown if a thread exited without releasing a mutex");
// m_Handle is of type WaitHandle
// Mutex is a subclass of WaitHandle
using(m_Handle = new Mutex())
{
try
{
// Spin up a thread. SignalMutex grabs
// the Mutex, then goes to sleep for 5 seconds.
thread = new Thread(new ThreadStart(NeverReleaseMutex));
// Start it
thread.Start();
// Then put this calling thread to sleep
// for just over one second so that it doesn't beat
// the spawned thread to the mutex
Thread.Sleep(c_DEFAULT_SLEEP_TIME / 3); // To avoid race
// Now, the spawned thread should already
// have the mutex and be sleeping on it forever.
// try to grab the mutex now. We should simply block until
// the other thread releases it, which is never. When that
// thread returns from its method, an AbandonedMutexException
// should be thrown instead
m_Handle.WaitOne();
// We should not get here
TestLibrary.TestFramework.LogError("101", "AbandonedMutexException is not thrown if a thread exited without releasing a mutex");
retVal = false;
}
catch (AbandonedMutexException)
{
// Swallow it, this is where we want
// the test to go
retVal = true;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
if (null != thread)
{
// The spawned thread is still running.
// Join on it until it is done
thread.Join();
}
}
}
return retVal;
}
// this one just tests that WaitOne will receive an
// ObjectDisposedException if the Mutex is disposed of
// by the spawned thread while WaitOne is waiting on it
public bool NegTest2()
{
bool retVal = false;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("NegTest2: ObjectDisposedException should be thrown if current instance has already been disposed");
try
{
// m_Handle is of type WaitHandle
// Mutex is a subclass of WaitHandle
m_Handle = new Mutex();
// Spin up a thread. DisposeMutex
// simply tries to dispose of the mutex.
thread = new Thread(new ThreadStart(DisposeMutex));
// Start it
thread.Start();
Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race
Thread.Sleep(c_DEFAULT_SLEEP_TIME);
// Now, the spawned thread should have
// had plenty of time to dispose of the mutex
// Calling WaitOne at this point should result
// in an ObjectDisposedException being thrown
m_Handle.WaitOne();
// We should not get here
TestLibrary.TestFramework.LogError("103", "ObjectDisposedException is not thrown if current instance has already been disposed");
retVal = false;
}
catch (ObjectDisposedException)
{
// Swallow it, this is where we want
// the test to go
retVal = true;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
if (null != thread)
{
// Wait for the spawned thread to finish
// cleaning up
thread.Join();
}
if (null != m_Handle)
{
// spawned thread was unable to dispose of it
((IDisposable)m_Handle).Dispose();
}
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
WaitHandleWaitOne1 test = new WaitHandleWaitOne1();
TestLibrary.TestFramework.BeginTestCase("WaitHandleWaitOne1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private void SignalMutex()
{
// Request ownership of the mutex.
// You can use the WaitHandle.WaitOne
// method to request ownership of a mutex. Block
// until m_Handle receives a signal
m_Handle.WaitOne();
// Put this thread to sleep
// for 5 seconds
Thread.Sleep(c_DEFAULT_SLEEP_TIME);
// Then release the mutex
(m_Handle as Mutex).ReleaseMutex();
}
private void NeverReleaseMutex()
{
// Request ownership of the mutex.
// You can use the WaitHandle.WaitOne
// method to request ownership of a mutex. Block
// until m_Handle receives a signal
m_Handle.WaitOne();
// Put this thread to sleep
// for 5 seconds
Thread.Sleep(c_DEFAULT_SLEEP_TIME);
// And we never release
// the mutex
}
private void DisposeMutex()
{
((IDisposable)m_Handle).Dispose();
}
#endregion
}
| |
//! \file ImageISG.cs
//! \date Tue Mar 17 10:01:44 2015
//! \brief ISM engine image format.
//
// Copyright (C) 2015 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Utility;
namespace GameRes.Formats.ISM
{
internal class IsgMetaData : ImageMetaData
{
public byte Type;
public int Colors;
public uint Packed;
public uint Unpacked;
}
[Export(typeof(ImageFormat))]
public class IsgFormat : ImageFormat
{
public override string Tag { get { return "ISG"; } }
public override string Description { get { return "ISM engine image format"; } }
public override uint Signature { get { return 0x204d5349u; } } // 'ISM '
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("IsgFormat.Write not implemented");
}
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = stream.ReadHeader (0x24);
if (!header.AsciiEqual ("ISM IMAGEFILE\x00"))
return null;
int colors = header[0x23];
if (0 == colors)
colors = 256;
return new IsgMetaData
{
Width = header.ToUInt16 (0x1d),
Height = header.ToUInt16 (0x1f),
BPP = 8,
Type = header[0x10],
Colors = colors,
Packed = header.ToUInt32 (0x11),
Unpacked = header.ToUInt32 (0x15),
};
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
var meta = (IsgMetaData)info;
if (0x21 != meta.Type && 0x10 != meta.Type)
throw new InvalidFormatException ("Unsupported ISM image type");
stream.Position = 0x30;
using (var input = new Reader (stream, meta))
{
if (0x21 == meta.Type)
input.Unpack21();
else
input.Unpack10();
var palette = new BitmapPalette (input.Palette);
return ImageData.CreateFlipped (info, PixelFormats.Indexed8, palette, input.Data, (int)info.Width);
}
}
internal class Reader : IDisposable
{
IBinaryStream m_input;
byte[] m_data;
Color[] m_palette;
int m_input_size;
public Color[] Palette { get { return m_palette; } }
public byte[] Data { get { return m_data; } }
public Reader (IBinaryStream file, IsgMetaData info)
{
int palette_size = (int)info.Colors*4;
var palette_data = new byte[Math.Max (0x400, palette_size)];
if (palette_size != file.Read (palette_data, 0, palette_size))
throw new InvalidFormatException();
m_palette = new Color[0x100];
for (int i = 0; i < m_palette.Length; ++i)
{
m_palette[i] = Color.FromRgb (palette_data[i*4+2], palette_data[i*4+1], palette_data[i*4]);
}
m_input = file;
m_input_size = (int)info.Packed;
m_data = new byte[info.Width * info.Height];
}
public void Unpack21 ()
{
int dst = 0;
var frame = new byte[2048];
int frame_pos = 2039;
int remaining = m_input_size;
byte ctl = m_input.ReadUInt8();
--remaining;
int bit = 0x80;
while (remaining > 0)
{
if (0 != (ctl & bit))
{
byte hi = m_input.ReadUInt8();
byte lo = m_input.ReadUInt8();
remaining -= 2;
int offset = (hi & 7) << 8 | lo;
for (int count = (hi >> 3) + 3; count > 0; --count)
{
byte p = frame[offset];
frame[frame_pos] = p;
m_data[dst++] = p;
offset = (offset + 1) & 0x7ff;
frame_pos = (frame_pos + 1) & 0x7ff;
}
}
else
{
byte p = m_input.ReadUInt8();
--remaining;
m_data[dst++] = p;
frame[frame_pos] = p;
frame_pos = (frame_pos + 1) & 0x7ff;
}
if (0 == (bit >>= 1))
{
ctl = m_input.ReadUInt8();
--remaining;
bit = 0x80;
}
}
}
public void Unpack10 ()
{
int dst = 0;
int remaining = m_input_size;
byte ctl = m_input.ReadUInt8();
--remaining;
int bit = 1;
while (remaining > 0)
{
byte p = m_input.ReadUInt8();
--remaining;
if (0 != (ctl & bit))
{
for (int count = 2 + m_input.ReadUInt8(); count > 0; --count)
m_data[dst++] = p;
--remaining;
}
else
{
m_data[dst++] = p;
}
if (0x100 == (bit <<= 1))
{
ctl = m_input.ReadUInt8();
--remaining;
bit = 1;
}
}
}
#region IDisposable Members
public void Dispose ()
{
GC.SuppressFinalize (this);
}
#endregion
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MessageHub.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* Copyright (c) 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.Net;
using System.Net.Sockets;
using System.Reflection;
using OpenSim.Framework;
using OpenMetaverse;
using log4net;
namespace OpenSim.Services.Interfaces
{
public interface IGridService
{
/// <summary>
/// Register a region with the grid service.
/// </summary>
/// <param name="regionInfos"> </param>
/// <returns></returns>
/// <exception cref="System.Exception">Thrown if region registration failed</exception>
string RegisterRegion(UUID scopeID, GridRegion regionInfos);
/// <summary>
/// Deregister a region with the grid service.
/// </summary>
/// <param name="regionID"></param>
/// <returns></returns>
/// <exception cref="System.Exception">Thrown if region deregistration failed</exception>
bool DeregisterRegion(UUID regionID);
/// <summary>
/// Get information about the regions neighbouring the given co-ordinates (in meters).
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID);
GridRegion GetRegionByUUID(UUID scopeID, UUID regionID);
/// <summary>
/// Get the region at the given position (in meters)
/// </summary>
/// <param name="scopeID"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
GridRegion GetRegionByPosition(UUID scopeID, int x, int y);
/// <summary>
/// Get information about a region which exactly matches the name given.
/// </summary>
/// <param name="scopeID"></param>
/// <param name="regionName"></param>
/// <returns>Returns the region information if the name matched. Null otherwise.</returns>
GridRegion GetRegionByName(UUID scopeID, string regionName);
/// <summary>
/// Get information about regions starting with the provided name.
/// </summary>
/// <param name="name">
/// The name to match against.
/// </param>
/// <param name="maxNumber">
/// The maximum number of results to return.
/// </param>
/// <returns>
/// A list of <see cref="RegionInfo"/>s of regions with matching name. If the
/// grid-server couldn't be contacted or returned an error, return null.
/// </returns>
List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber);
List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax);
List<GridRegion> GetDefaultRegions(UUID scopeID);
List<GridRegion> GetDefaultHypergridRegions(UUID scopeID);
List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y);
List<GridRegion> GetHyperlinks(UUID scopeID);
/// <summary>
/// Get internal OpenSimulator region flags.
/// </summary>
/// <remarks>
/// See OpenSimulator.Framework.RegionFlags. These are not returned in the GridRegion structure -
/// they currently need to be requested separately. Possibly this should change to avoid multiple service calls
/// in some situations.
/// </remarks>
/// <returns>
/// The region flags.
/// </returns>
/// <param name='scopeID'></param>
/// <param name='regionID'></param>
int GetRegionFlags(UUID scopeID, UUID regionID);
Dictionary<string,object> GetExtraFeatures();
}
public interface IHypergridLinker
{
GridRegion TryLinkRegionToCoords(UUID scopeID, string mapName, int xloc, int yloc, UUID ownerID, out string reason);
bool TryUnlinkRegion(string mapName);
}
public class GridRegion
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#pragma warning disable 414
private static readonly string LogHeader = "[GRID REGION]";
#pragma warning restore 414
/// <summary>
/// The port by which http communication occurs with the region
/// </summary>
public uint HttpPort { get; set; }
/// <summary>
/// A well-formed URI for the host region server (namely "http://" + ExternalHostName)
/// </summary>
public string ServerURI
{
get {
if (!String.IsNullOrEmpty(m_serverURI)) {
return m_serverURI;
} else {
if (HttpPort == 0)
return "http://" + m_externalHostName + "/";
else
return "http://" + m_externalHostName + ":" + HttpPort + "/";
}
}
set {
if ( value == null)
{
m_serverURI = String.Empty;
return;
}
if ( value.EndsWith("/") )
{
m_serverURI = value;
}
else
{
m_serverURI = value + '/';
}
}
}
protected string m_serverURI;
/// <summary>
/// Provides direct access to the 'm_serverURI' field, without returning a generated URL if m_serverURI is missing.
/// </summary>
public string RawServerURI
{
get { return m_serverURI; }
set { m_serverURI = value; }
}
public string RegionName
{
get { return m_regionName; }
set { m_regionName = value; }
}
protected string m_regionName = String.Empty;
/// <summary>
/// Region flags.
/// </summary>
/// <remarks>
/// If not set (chiefly if a robust service is running code pre OpenSim 0.8.1) then this will be null and
/// should be ignored. If you require flags information please use the separate IGridService.GetRegionFlags() call
/// XXX: This field is currently ignored when used in RegisterRegion, but could potentially be
/// used to set flags at this point.
/// </remarks>
public OpenSim.Framework.RegionFlags? RegionFlags { get; set; }
protected string m_externalHostName;
protected IPEndPoint m_internalEndPoint;
/// <summary>
/// The co-ordinate of this region in region units.
/// </summary>
public int RegionCoordX { get { return (int)Util.WorldToRegionLoc((uint)RegionLocX); } }
/// <summary>
/// The co-ordinate of this region in region units
/// </summary>
public int RegionCoordY { get { return (int)Util.WorldToRegionLoc((uint)RegionLocY); } }
/// <summary>
/// The location of this region in meters.
/// DANGER DANGER! Note that this name means something different in RegionInfo.
/// </summary>
public int RegionLocX
{
get { return m_regionLocX; }
set { m_regionLocX = value; }
}
protected int m_regionLocX;
public int RegionSizeX { get; set; }
public int RegionSizeY { get; set; }
/// <summary>
/// The location of this region in meters.
/// DANGER DANGER! Note that this name means something different in RegionInfo.
/// </summary>
public int RegionLocY
{
get { return m_regionLocY; }
set { m_regionLocY = value; }
}
protected int m_regionLocY;
protected UUID m_estateOwner;
public UUID EstateOwner
{
get { return m_estateOwner; }
set { m_estateOwner = value; }
}
public UUID RegionID = UUID.Zero;
public UUID ScopeID = UUID.Zero;
public UUID TerrainImage = UUID.Zero;
public UUID ParcelImage = UUID.Zero;
public byte Access;
public int Maturity;
public string RegionSecret = string.Empty;
public string Token = string.Empty;
public GridRegion()
{
RegionSizeX = (int)Constants.RegionSize;
RegionSizeY = (int)Constants.RegionSize;
m_serverURI = string.Empty;
}
public GridRegion(uint xcell, uint ycell)
{
m_regionLocX = (int)Util.RegionToWorldLoc(xcell);
m_regionLocY = (int)Util.RegionToWorldLoc(ycell);
RegionSizeX = (int)Constants.RegionSize;
RegionSizeY = (int)Constants.RegionSize;
}
public GridRegion(RegionInfo ConvertFrom)
{
m_regionName = ConvertFrom.RegionName;
m_regionLocX = (int)(ConvertFrom.WorldLocX);
m_regionLocY = (int)(ConvertFrom.WorldLocY);
RegionSizeX = (int)ConvertFrom.RegionSizeX;
RegionSizeY = (int)ConvertFrom.RegionSizeY;
m_internalEndPoint = ConvertFrom.InternalEndPoint;
m_externalHostName = ConvertFrom.ExternalHostName;
HttpPort = ConvertFrom.HttpPort;
RegionID = ConvertFrom.RegionID;
ServerURI = ConvertFrom.ServerURI;
TerrainImage = ConvertFrom.RegionSettings.TerrainImageID;
ParcelImage = ConvertFrom.RegionSettings.ParcelImageID;
Access = ConvertFrom.AccessLevel;
Maturity = ConvertFrom.RegionSettings.Maturity;
RegionSecret = ConvertFrom.regionSecret;
EstateOwner = ConvertFrom.EstateSettings.EstateOwner;
}
public GridRegion(GridRegion ConvertFrom)
{
m_regionName = ConvertFrom.RegionName;
RegionFlags = ConvertFrom.RegionFlags;
m_regionLocX = ConvertFrom.RegionLocX;
m_regionLocY = ConvertFrom.RegionLocY;
RegionSizeX = ConvertFrom.RegionSizeX;
RegionSizeY = ConvertFrom.RegionSizeY;
m_internalEndPoint = ConvertFrom.InternalEndPoint;
m_externalHostName = ConvertFrom.ExternalHostName;
HttpPort = ConvertFrom.HttpPort;
RegionID = ConvertFrom.RegionID;
ServerURI = ConvertFrom.ServerURI;
TerrainImage = ConvertFrom.TerrainImage;
ParcelImage = ConvertFrom.ParcelImage;
Access = ConvertFrom.Access;
Maturity = ConvertFrom.Maturity;
RegionSecret = ConvertFrom.RegionSecret;
EstateOwner = ConvertFrom.EstateOwner;
}
public GridRegion(Dictionary<string, object> kvp)
{
if (kvp.ContainsKey("uuid"))
RegionID = new UUID((string)kvp["uuid"]);
if (kvp.ContainsKey("locX"))
RegionLocX = Convert.ToInt32((string)kvp["locX"]);
if (kvp.ContainsKey("locY"))
RegionLocY = Convert.ToInt32((string)kvp["locY"]);
if (kvp.ContainsKey("sizeX"))
RegionSizeX = Convert.ToInt32((string)kvp["sizeX"]);
else
RegionSizeX = (int)Constants.RegionSize;
if (kvp.ContainsKey("sizeY"))
RegionSizeY = Convert.ToInt32((string)kvp["sizeY"]);
else
RegionSizeX = (int)Constants.RegionSize;
if (kvp.ContainsKey("regionName"))
RegionName = (string)kvp["regionName"];
if (kvp.ContainsKey("access"))
{
byte access = Convert.ToByte((string)kvp["access"]);
Access = access;
Maturity = (int)Util.ConvertAccessLevelToMaturity(access);
}
if (kvp.ContainsKey("flags") && kvp["flags"] != null)
RegionFlags = (OpenSim.Framework.RegionFlags?)Convert.ToInt32((string)kvp["flags"]);
if (kvp.ContainsKey("serverIP"))
{
//int port = 0;
//Int32.TryParse((string)kvp["serverPort"], out port);
//IPEndPoint ep = new IPEndPoint(IPAddress.Parse((string)kvp["serverIP"]), port);
ExternalHostName = (string)kvp["serverIP"];
}
else
ExternalHostName = "127.0.0.1";
if (kvp.ContainsKey("serverPort"))
{
Int32 port = 0;
Int32.TryParse((string)kvp["serverPort"], out port);
InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), port);
}
if (kvp.ContainsKey("serverHttpPort"))
{
UInt32 port = 0;
UInt32.TryParse((string)kvp["serverHttpPort"], out port);
HttpPort = port;
}
if (kvp.ContainsKey("serverURI"))
ServerURI = (string)kvp["serverURI"];
if (kvp.ContainsKey("regionMapTexture"))
UUID.TryParse((string)kvp["regionMapTexture"], out TerrainImage);
if (kvp.ContainsKey("parcelMapTexture"))
UUID.TryParse((string)kvp["parcelMapTexture"], out ParcelImage);
if (kvp.ContainsKey("regionSecret"))
RegionSecret =(string)kvp["regionSecret"];
if (kvp.ContainsKey("owner_uuid"))
EstateOwner = new UUID(kvp["owner_uuid"].ToString());
if (kvp.ContainsKey("Token"))
Token = kvp["Token"].ToString();
// m_log.DebugFormat("{0} New GridRegion. id={1}, loc=<{2},{3}>, size=<{4},{5}>",
// LogHeader, RegionID, RegionLocX, RegionLocY, RegionSizeX, RegionSizeY);
}
public Dictionary<string, object> ToKeyValuePairs()
{
Dictionary<string, object> kvp = new Dictionary<string, object>();
kvp["uuid"] = RegionID.ToString();
kvp["locX"] = RegionLocX.ToString();
kvp["locY"] = RegionLocY.ToString();
kvp["sizeX"] = RegionSizeX.ToString();
kvp["sizeY"] = RegionSizeY.ToString();
kvp["regionName"] = RegionName;
if (RegionFlags != null)
kvp["flags"] = ((int)RegionFlags).ToString();
kvp["serverIP"] = ExternalHostName; //ExternalEndPoint.Address.ToString();
kvp["serverHttpPort"] = HttpPort.ToString();
kvp["serverURI"] = ServerURI;
kvp["serverPort"] = InternalEndPoint.Port.ToString();
kvp["regionMapTexture"] = TerrainImage.ToString();
kvp["parcelMapTexture"] = ParcelImage.ToString();
kvp["access"] = Access.ToString();
kvp["regionSecret"] = RegionSecret;
kvp["owner_uuid"] = EstateOwner.ToString();
kvp["Token"] = Token.ToString();
// Maturity doesn't seem to exist in the DB
return kvp;
}
#region Definition of equality
/// <summary>
/// Define equality as two regions having the same, non-zero UUID.
/// </summary>
public bool Equals(GridRegion region)
{
if ((object)region == null)
return false;
// Return true if the non-zero UUIDs are equal:
return (RegionID != UUID.Zero) && RegionID.Equals(region.RegionID);
}
public override bool Equals(Object obj)
{
if (obj == null)
return false;
return Equals(obj as GridRegion);
}
public override int GetHashCode()
{
return RegionID.GetHashCode() ^ TerrainImage.GetHashCode() ^ ParcelImage.GetHashCode();
}
#endregion
/// <value>
/// This accessor can throw all the exceptions that Dns.GetHostAddresses can throw.
///
/// XXX Isn't this really doing too much to be a simple getter, rather than an explict method?
/// </value>
public IPEndPoint ExternalEndPoint
{
get { return Util.getEndPoint(m_externalHostName, m_internalEndPoint.Port); }
}
public string ExternalHostName
{
get { return m_externalHostName; }
set { m_externalHostName = value; }
}
public IPEndPoint InternalEndPoint
{
get { return m_internalEndPoint; }
set { m_internalEndPoint = value; }
}
public ulong RegionHandle
{
get { return Util.UIntsToLong((uint)RegionLocX, (uint)RegionLocY); }
}
}
}
| |
//=================================================================================================
// Copyright 2017 Dirk Lemstra <https://graphicsmagick.codeplex.com/>
//
// Licensed under the ImageMagick License (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.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.
//=================================================================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Media.Imaging;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Fasterflect;
namespace GraphicsMagick
{
public sealed class MagickReadSettings
{
internal object _Instance;
internal MagickReadSettings(object instance)
{
_Instance = instance;
}
public static object GetInstance(MagickReadSettings obj)
{
if (ReferenceEquals(obj, null))
return null;
return obj._Instance;
}
public static object GetInstance(object obj)
{
if (ReferenceEquals(obj, null))
return null;
MagickReadSettings casted = obj as MagickReadSettings;
if (ReferenceEquals(casted, null))
return obj;
return casted._Instance;
}
public MagickReadSettings()
: this(AssemblyHelper.CreateInstance(Types.MagickReadSettings))
{
}
public Nullable<ColorSpace> ColorSpace
{
get
{
object result;
try
{
result = _Instance.GetPropertyValue("ColorSpace");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
if (result == null)
return new Nullable<ColorSpace>();
else
return new Nullable<ColorSpace>((ColorSpace)result);
}
set
{
try
{
_Instance.SetPropertyValue("ColorSpace", value == null ? Types.NullableColorSpace.CreateInstance() : Types.NullableColorSpace.CreateInstance(new Type[] { Types.ColorSpace }, value.Value));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
}
public MagickGeometry Density
{
get
{
object result;
try
{
result = _Instance.GetPropertyValue("Density");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (result == null ? null : new MagickGeometry(result));
}
set
{
try
{
_Instance.SetPropertyValue("Density", MagickGeometry.GetInstance(value));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
}
public Nullable<MagickFormat> Format
{
get
{
object result;
try
{
result = _Instance.GetPropertyValue("Format");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
if (result == null)
return new Nullable<MagickFormat>();
else
return new Nullable<MagickFormat>((MagickFormat)result);
}
set
{
try
{
_Instance.SetPropertyValue("Format", value == null ? Types.NullableMagickFormat.CreateInstance() : Types.NullableMagickFormat.CreateInstance(new Type[] { Types.MagickFormat }, value.Value));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
}
public Nullable<Int32> Height
{
get
{
object result;
try
{
result = _Instance.GetPropertyValue("Height");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
if (result == null)
return new Nullable<Int32>();
else
return new Nullable<Int32>((Int32)result);
}
set
{
try
{
_Instance.SetPropertyValue("Height", value == null ? Types.NullableInt32.CreateInstance() : Types.NullableInt32.CreateInstance(new Type[] { typeof(Int32) }, value.Value));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
}
public PixelStorageSettings PixelStorage
{
get
{
object result;
try
{
result = _Instance.GetPropertyValue("PixelStorage");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
return (result == null ? null : new PixelStorageSettings(result));
}
set
{
try
{
_Instance.SetPropertyValue("PixelStorage", PixelStorageSettings.GetInstance(value));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
}
public Nullable<Boolean> UseMonochrome
{
get
{
object result;
try
{
result = _Instance.GetPropertyValue("UseMonochrome");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
if (result == null)
return new Nullable<Boolean>();
else
return new Nullable<Boolean>((Boolean)result);
}
set
{
try
{
_Instance.SetPropertyValue("UseMonochrome", value == null ? Types.NullableBoolean.CreateInstance() : Types.NullableBoolean.CreateInstance(new Type[] { typeof(Boolean) }, value.Value));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
}
public Nullable<Int32> Width
{
get
{
object result;
try
{
result = _Instance.GetPropertyValue("Width");
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
if (result == null)
return new Nullable<Int32>();
else
return new Nullable<Int32>((Int32)result);
}
set
{
try
{
_Instance.SetPropertyValue("Width", value == null ? Types.NullableInt32.CreateInstance() : Types.NullableInt32.CreateInstance(new Type[] { typeof(Int32) }, value.Value));
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
}
public void SetDefine(MagickFormat format, String name, String value)
{
try
{
_Instance.CallMethod("SetDefine", new Type[] {Types.MagickFormat, typeof(String), typeof(String)}, format, name, value);
}
catch (Exception ex)
{
throw ExceptionHelper.Create(ex);
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Android.Sax.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Android.Sax
{
/// <summary>
/// <para>Listens for the beginning and ending of text elements. </para>
/// </summary>
/// <java-name>
/// android/sax/TextElementListener
/// </java-name>
[Dot42.DexImport("android/sax/TextElementListener", AccessFlags = 1537)]
public partial interface ITextElementListener : global::Android.Sax.IStartElementListener, global::Android.Sax.IEndTextElementListener
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>The root XML element. The entry point for this API. Not safe for concurrent use.</para><para>For example, passing this XML:</para><para><pre>
/// <feed xmlns='>
/// <entry>
/// <id>bob</id>
/// </entry>
/// </feed>
/// </pre></para><para>to this code:</para><para><pre>
/// static final String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom";
///
/// ...
///
/// RootElement root = new RootElement(ATOM_NAMESPACE, "feed");
/// Element entry = root.getChild(ATOM_NAMESPACE, "entry");
/// entry.getChild(ATOM_NAMESPACE, "id").setEndTextElementListener(
/// new EndTextElementListener() {
/// public void end(String body) {
/// System.out.println("Entry ID: " + body);
/// }
/// });
///
/// XMLReader reader = ...;
/// reader.setContentHandler(root.getContentHandler());
/// reader.parse(...);
/// </pre></para><para>would output:</para><para><pre>
/// Entry ID: bob
/// </pre> </para>
/// </summary>
/// <java-name>
/// android/sax/RootElement
/// </java-name>
[Dot42.DexImport("android/sax/RootElement", AccessFlags = 33)]
public partial class RootElement : global::Android.Sax.Element
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a new root element with the given name.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public RootElement(string uri, string localName) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a new root element with the given name. Uses an empty string as the namespace.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public RootElement(string localName) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the SAX <c> ContentHandler </c> . Pass this to your SAX parser. </para>
/// </summary>
/// <java-name>
/// getContentHandler
/// </java-name>
[Dot42.DexImport("getContentHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)]
public virtual global::Org.Xml.Sax.IContentHandler GetContentHandler() /* MethodBuilder.Create */
{
return default(global::Org.Xml.Sax.IContentHandler);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal RootElement() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Gets the SAX <c> ContentHandler </c> . Pass this to your SAX parser. </para>
/// </summary>
/// <java-name>
/// getContentHandler
/// </java-name>
public global::Org.Xml.Sax.IContentHandler ContentHandler
{
[Dot42.DexImport("getContentHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)]
get{ return GetContentHandler(); }
}
}
/// <summary>
/// <para>Listens for the end of text elements. </para>
/// </summary>
/// <java-name>
/// android/sax/EndTextElementListener
/// </java-name>
[Dot42.DexImport("android/sax/EndTextElementListener", AccessFlags = 1537)]
public partial interface IEndTextElementListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>Invoked at the end of a text element with the body of the element.</para><para></para>
/// </summary>
/// <java-name>
/// end
/// </java-name>
[Dot42.DexImport("end", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void End(string body) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Listens for the end of elements. </para>
/// </summary>
/// <java-name>
/// android/sax/EndElementListener
/// </java-name>
[Dot42.DexImport("android/sax/EndElementListener", AccessFlags = 1537)]
public partial interface IEndElementListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>Invoked at the end of an element. </para>
/// </summary>
/// <java-name>
/// end
/// </java-name>
[Dot42.DexImport("end", "()V", AccessFlags = 1025)]
void End() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Listens for the beginning of elements. </para>
/// </summary>
/// <java-name>
/// android/sax/StartElementListener
/// </java-name>
[Dot42.DexImport("android/sax/StartElementListener", AccessFlags = 1537)]
public partial interface IStartElementListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>Invoked at the beginning of an element.</para><para></para>
/// </summary>
/// <java-name>
/// start
/// </java-name>
[Dot42.DexImport("start", "(Lorg/xml/sax/Attributes;)V", AccessFlags = 1025)]
void Start(global::Org.Xml.Sax.IAttributes attributes) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>An XML element. Provides access to child elements and hooks to listen for events related to this element.</para><para><para>RootElement </para></para>
/// </summary>
/// <java-name>
/// android/sax/Element
/// </java-name>
[Dot42.DexImport("android/sax/Element", AccessFlags = 33)]
public partial class Element
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal Element() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the child element with the given name. Uses an empty string as the namespace. </para>
/// </summary>
/// <java-name>
/// getChild
/// </java-name>
[Dot42.DexImport("getChild", "(Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)]
public virtual global::Android.Sax.Element GetChild(string localName) /* MethodBuilder.Create */
{
return default(global::Android.Sax.Element);
}
/// <summary>
/// <para>Gets the child element with the given name. </para>
/// </summary>
/// <java-name>
/// getChild
/// </java-name>
[Dot42.DexImport("getChild", "(Ljava/lang/String;Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)]
public virtual global::Android.Sax.Element GetChild(string uri, string localName) /* MethodBuilder.Create */
{
return default(global::Android.Sax.Element);
}
/// <summary>
/// <para>Gets the child element with the given name. Uses an empty string as the namespace. We will throw a org.xml.sax.SAXException at parsing time if the specified child is missing. This helps you ensure that your listeners are called. </para>
/// </summary>
/// <java-name>
/// requireChild
/// </java-name>
[Dot42.DexImport("requireChild", "(Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)]
public virtual global::Android.Sax.Element RequireChild(string localName) /* MethodBuilder.Create */
{
return default(global::Android.Sax.Element);
}
/// <summary>
/// <para>Gets the child element with the given name. We will throw a org.xml.sax.SAXException at parsing time if the specified child is missing. This helps you ensure that your listeners are called. </para>
/// </summary>
/// <java-name>
/// requireChild
/// </java-name>
[Dot42.DexImport("requireChild", "(Ljava/lang/String;Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)]
public virtual global::Android.Sax.Element RequireChild(string uri, string localName) /* MethodBuilder.Create */
{
return default(global::Android.Sax.Element);
}
/// <summary>
/// <para>Sets start and end element listeners at the same time. </para>
/// </summary>
/// <java-name>
/// setElementListener
/// </java-name>
[Dot42.DexImport("setElementListener", "(Landroid/sax/ElementListener;)V", AccessFlags = 1)]
public virtual void SetElementListener(global::Android.Sax.IElementListener elementListener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets start and end text element listeners at the same time. </para>
/// </summary>
/// <java-name>
/// setTextElementListener
/// </java-name>
[Dot42.DexImport("setTextElementListener", "(Landroid/sax/TextElementListener;)V", AccessFlags = 1)]
public virtual void SetTextElementListener(global::Android.Sax.ITextElementListener elementListener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets a listener for the start of this element. </para>
/// </summary>
/// <java-name>
/// setStartElementListener
/// </java-name>
[Dot42.DexImport("setStartElementListener", "(Landroid/sax/StartElementListener;)V", AccessFlags = 1)]
public virtual void SetStartElementListener(global::Android.Sax.IStartElementListener startElementListener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets a listener for the end of this element. </para>
/// </summary>
/// <java-name>
/// setEndElementListener
/// </java-name>
[Dot42.DexImport("setEndElementListener", "(Landroid/sax/EndElementListener;)V", AccessFlags = 1)]
public virtual void SetEndElementListener(global::Android.Sax.IEndElementListener endElementListener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets a listener for the end of this text element. </para>
/// </summary>
/// <java-name>
/// setEndTextElementListener
/// </java-name>
[Dot42.DexImport("setEndTextElementListener", "(Landroid/sax/EndTextElementListener;)V", AccessFlags = 1)]
public virtual void SetEndTextElementListener(global::Android.Sax.IEndTextElementListener endTextElementListener) /* MethodBuilder.Create */
{
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
}
/// <summary>
/// <para>Listens for the beginning and ending of elements. </para>
/// </summary>
/// <java-name>
/// android/sax/ElementListener
/// </java-name>
[Dot42.DexImport("android/sax/ElementListener", AccessFlags = 1537)]
public partial interface IElementListener : global::Android.Sax.IStartElementListener, global::Android.Sax.IEndElementListener
/* scope: __dot42__ */
{
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Marten.Events;
using Marten.Events.Projections;
using Marten.Testing.Harness;
using Shouldly;
using Weasel.Postgresql;
using Xunit;
namespace Marten.Testing.Events.Projections
{
public class project_events_from_multiple_streams_into_view: IntegrationContext
{
private static readonly Guid streamId = Guid.NewGuid();
private static readonly Guid streamId2 = Guid.NewGuid();
private QuestStarted started = new QuestStarted { Id = streamId, Name = "Find the Orb" };
private QuestStarted started2 = new QuestStarted { Id = streamId2, Name = "Find the Orb 2.0" };
private MonsterQuestsAdded monsterQuestsAdded = new MonsterQuestsAdded { QuestIds = new List<Guid> { streamId, streamId2 }, Name = "Dragon" };
private MonsterQuestsRemoved monsterQuestsRemoved = new MonsterQuestsRemoved { QuestIds = new List<Guid> { streamId, streamId2 }, Name = "Dragon" };
private QuestEnded ended = new QuestEnded { Id = streamId, Name = "Find the Orb" };
private MembersJoined joined = new MembersJoined { QuestId = streamId, Day = 2, Location = "Faldor's Farm", Members = new[] { "Garion", "Polgara", "Belgarath" } };
private MonsterSlayed slayed1 = new MonsterSlayed { QuestId = streamId, Name = "Troll" };
private MonsterSlayed slayed2 = new MonsterSlayed { QuestId = streamId, Name = "Dragon" };
private MonsterDestroyed destroyed = new MonsterDestroyed { QuestId = streamId, Name = "Troll" };
private MembersDeparted departed = new MembersDeparted { QuestId = streamId, Day = 5, Location = "Sendaria", Members = new[] { "Silk", "Barak" } };
private MembersJoined joined2 = new MembersJoined { QuestId = streamId, Day = 5, Location = "Sendaria", Members = new[] { "Silk", "Barak" } };
[Fact]
public async Task updateonly_event_for_custom_view_projection_should_not_create_new_document()
{
StoreOptions(_ =>
{
_.AutoCreateSchemaObjects = AutoCreate.All;
_.Events.TenancyStyle = Marten.Storage.TenancyStyle.Conjoined;
_.Schema.For<NewsletterSubscription>().MultiTenanted();
_.Projections.Add(new NewsletterSubscriptionProjection(), ProjectionLifecycle.Inline);
});
var subscriptionId = Guid.NewGuid();
var newsletterId = Guid.NewGuid();
var readerId = Guid.NewGuid();
var readerSubscribed = new ReaderSubscribed(subscriptionId, newsletterId, readerId, "John Doe");
theSession.Events.StartStream<NewsletterSubscription>(streamId, readerSubscribed);
await theSession.SaveChangesAsync();
var subscription = await theSession.LoadAsync<NewsletterSubscription>(subscriptionId);
subscription.ShouldNotBeNull();
var newsletterOpened = new NewsletterOpened(subscriptionId, DateTime.Now);
theSession.Events.Append(subscriptionId, newsletterOpened);
await theSession.SaveChangesAsync();
subscription = await theSession.LoadAsync<NewsletterSubscription>(subscriptionId);
subscription.ShouldNotBeNull();
var readerUnsubscribed = new ReaderUnsubscribed(subscriptionId);
theSession.Events.Append(subscriptionId, readerUnsubscribed);
await theSession.SaveChangesAsync();
subscription = await theSession.LoadAsync<NewsletterSubscription>(subscriptionId);
subscription.ShouldBeNull();
}
public project_events_from_multiple_streams_into_view(DefaultStoreFixture fixture) : base(fixture)
{
}
}
public class QuestView
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class PersistedView
{
public Guid Id { get; set; }
public List<object> Events { get; } = new List<object>();
public List<Guid> StreamIdsForEvents { get; set; } = new List<Guid>();
}
#region sample_viewprojection-from-class-with-eventdata
public class Lap
{
public Guid Id { get; set; }
public DateTimeOffset? Start { get; set; }
public DateTimeOffset? End { get; set; }
}
public abstract class LapEvent
{
public Guid LapId { get; set; }
}
public class LapStarted : LapEvent
{
}
public class LapFinished : LapEvent
{
}
public class LapViewProjection: ViewProjection<Lap, Guid>
{
public LapViewProjection()
{
// This tells the projection how to "split" the events
// and identify the document. It should be able to use
// a base class or interface. Can have multiple Identity()
// calls for different events.
Identity<LapEvent>(x => x.LapId);
}
public void Apply(Lap view, IEvent<LapStarted> eventData) =>
view.Start = eventData.Timestamp;
public void Apply(Lap view, IEvent<LapFinished> eventData) =>
view.End = eventData.Timestamp;
}
#endregion
#region sample_viewprojection-with-update-only
public abstract class SubscriptionEvent
{
public Guid SubscriptionId { get; set; }
}
public class NewsletterSubscription
{
public Guid Id { get; set; }
public Guid NewsletterId { get; set; }
public Guid ReaderId { get; set; }
public string FirstName { get; set; }
public int OpensCount { get; set; }
}
public class ReaderSubscribed : SubscriptionEvent
{
public Guid NewsletterId { get; }
public Guid ReaderId { get; }
public string FirstName { get; }
public ReaderSubscribed(Guid subscriptionId, Guid newsletterId, Guid readerId, string firstName)
{
SubscriptionId = subscriptionId;
NewsletterId = newsletterId;
ReaderId = readerId;
FirstName = firstName;
}
}
public class NewsletterOpened : SubscriptionEvent
{
public DateTime OpenedAt { get; }
public NewsletterOpened(Guid subscriptionId, DateTime openedAt)
{
SubscriptionId = subscriptionId;
OpenedAt = openedAt;
}
}
public class ReaderUnsubscribed : SubscriptionEvent
{
public ReaderUnsubscribed(Guid subscriptionId)
{
SubscriptionId = subscriptionId;
}
}
public class NewsletterSubscriptionProjection : ViewProjection<NewsletterSubscription, Guid>
{
public NewsletterSubscriptionProjection()
{
Identity<SubscriptionEvent>(x => x.SubscriptionId);
DeleteEvent<ReaderUnsubscribed>();
}
public void Apply(NewsletterSubscription view, ReaderSubscribed @event)
{
view.Id = @event.SubscriptionId;
view.NewsletterId = @event.NewsletterId;
view.ReaderId = @event.ReaderId;
view.FirstName = @event.FirstName;
view.OpensCount = 0;
}
public void Apply(NewsletterSubscription view, NewsletterOpened @event)
{
view.OpensCount++;
}
}
#endregion
public class Project
{
public Guid Id { get; set; }
public string Name { get; set; }
public void Apply(ProjectStarted e)
{
Id = e.Id;
Name = e.Name;
}
public void Apply(ProjectClosed e)
{
}
}
public class ProjectStarted
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class ProjectClosed
{
public Guid Id { get; set; }
}
}
| |
namespace SIM.Pipelines
{
#region Usings
using System;
using System.Data.SqlClient;
using System.IO;
using System.IO.Compression;
using System.Linq;
using SIM.Adapters.SqlServer;
using SIM.Adapters.WebServer;
using SIM.Pipelines.Install;
using Sitecore.Diagnostics.Base;
using Sitecore.Diagnostics.Base.Annotations;
using Sitecore.Diagnostics.Logging;
using SIM.Extensions;
using SIM.FileSystem;
using SIM.Instances;
#endregion
public static class AttachDatabasesHelper
{
// total number of steps in entire install/reinstall wizard without this one is around 5000, so we can assume attaching databases takes 5% so 250
public const int StepsCount = 250;
#region Public methods
public static void AttachDatabase(string name, string sqlPrefix, bool attachSql, string databasesFolderPath, ConnectionString connectionString, SqlConnectionStringBuilder defaultConnectionString, IPipelineController controller)
{
SetConnectionStringNode(name, sqlPrefix, defaultConnectionString, connectionString);
if (!attachSql)
{
return;
}
var databaseName = connectionString.GenerateDatabaseName(name, sqlPrefix);
var databasePath =
DatabaseFilenameHook(Path.Combine(databasesFolderPath, connectionString.DefaultFileName),
connectionString.Name.Replace("yafnet", "forum"), databasesFolderPath);
if (!FileSystem.Local.File.Exists(databasePath))
{
var file = Path.GetFileName(databasePath);
if (connectionString.Name.EqualsIgnoreCase("reporting"))
{
databasePath = Path.Combine(Path.GetDirectoryName(databasePath), "Sitecore.Analytics.mdf");
} else if (connectionString.Name.EqualsIgnoreCase("exm.dispatch"))
{
databasePath = Path.Combine(Path.GetDirectoryName(databasePath), "Sitecore.Exm.mdf");
}
else if (connectionString.Name.EqualsIgnoreCase("session"))
{
databasePath = Path.Combine(Path.GetDirectoryName(databasePath), "Sitecore.Sessions.mdf");
}
}
FileSystem.Local.File.AssertExists(databasePath, databasePath + " file doesn't exist");
// Make the database data file also matching databaseName
var newPath = databasePath.Replace(connectionString.DefaultFileName, string.Concat(databaseName, ".mdf"));
try
{
File.Move(databasePath, newPath);
}
catch { }
// Assert again
databasePath = newPath;
FileSystem.Local.File.AssertExists(databasePath, databasePath + " file doesn't exist");
if (SqlServerManager.Instance.DatabaseExists(databaseName, defaultConnectionString))
{
databaseName = ResolveConflict(defaultConnectionString, connectionString, databasePath, databaseName, controller);
}
if (databaseName != null)
{
SqlServerManager.Instance.AttachDatabase(databaseName, databasePath, defaultConnectionString);
}
}
public static void AttachDatabase(ConnectionString connectionString, SqlConnectionStringBuilder defaultConnectionString, string name, string sqlPrefix, bool attachSql, string databasesFolderPath, string instanceName, IPipelineController controller)
{
if (connectionString.IsMongoConnectionString)
{
connectionString.Value = AttachDatabasesHelper.GetMongoConnectionString(connectionString.Name, sqlPrefix);
connectionString.SaveChanges();
return;
}
if (connectionString.IsSqlConnectionString)
{
try
{
AttachDatabasesHelper.AttachDatabase(name, sqlPrefix, attachSql, databasesFolderPath, connectionString, defaultConnectionString, controller);
}
catch (Exception ex)
{
if (connectionString.Name == "reporting.secondary")
{
throw;
}
Log.Warn(ex, "Attaching reporting.secondary database failed. Skipping...");
}
}
}
public static string GetSqlPrefix(string cstr1, string cstr2)
{
var one = new SqlConnectionStringBuilder(cstr1).InitialCatalog;
var two = new SqlConnectionStringBuilder(cstr2).InitialCatalog;
var min = Math.Min(one.Length, two.Length);
var sqlPrefix = string.Empty;
for (var i = 0; i < min; ++i)
{
if (one[i] == two[i])
{
sqlPrefix = one.Substring(0, i + 1);
}
}
Assert.IsNotNull(sqlPrefix.EmptyToNull(), "two first database names have different prefixes when they must be similar");
return sqlPrefix.Replace(".", "_").TrimEnd('_');
}
[NotNull]
public static string DatabaseFilenameHook([NotNull] string databasePath, [NotNull] string databaseName, [NotNull] string databasesFolderPath)
{
Assert.ArgumentNotNull(databasePath, nameof(databasePath));
Assert.ArgumentNotNull(databaseName, nameof(databaseName));
if (!FileSystem.Local.File.Exists(databasePath))
{
string[] files = FileSystem.Local.Directory.GetFiles(databasesFolderPath, "*" + databaseName + ".mdf");
var file = files.SingleOrDefault();
if (!String.IsNullOrEmpty(file) && FileSystem.Local.File.Exists(file))
{
return file;
}
}
return databasePath;
}
public static string ResolveConflict(SqlConnectionStringBuilder defaultConnectionString, ConnectionString connectionString, string databasePath, string databaseName, IPipelineController controller)
{
var existingDatabasePath = SqlServerManager.Instance.GetDatabaseFileName(databaseName, defaultConnectionString);
if (String.IsNullOrEmpty(existingDatabasePath))
{
var m = "The database with the same '{0}' name is already exists in the SQL Server metabase but points to non-existing file. ".FormatWith(databaseName);
if (controller.Confirm(m + "Would you like to delete it?"))
{
SqlServerManager.Instance.DeleteDatabase(databaseName, defaultConnectionString);
return databaseName;
}
throw new Exception(m);
}
if (existingDatabasePath.EqualsIgnoreCase(databasePath))
{
return null;
}
// todo: replce this with shiny message box
var delete = "Delete the '{0}' database".FormatWith(databaseName);
const string AnotherName = "Use another database name";
const string Cancel = "Terminate current action";
string[] options = new[]
{
delete, AnotherName, Cancel
};
var m2 = "The database with '{0}' name already exists".FormatWith(databaseName);
var result = controller.Select(m2, options);
switch (result)
{
case Cancel:
throw new Exception(m2);
case AnotherName:
databaseName = ResolveConflictByUnsedName(defaultConnectionString, connectionString, databaseName);
break;
default:
SqlServerManager.Instance.DeleteDatabase(databaseName, defaultConnectionString);
break;
}
return databaseName;
}
#endregion
#region Private methods
[NotNull]
private static string GetMongoConnectionString([NotNull] string connectionStringName, [NotNull] string instanceName)
{
Assert.ArgumentNotNull(connectionStringName, nameof(connectionStringName));
Assert.ArgumentNotNull(instanceName, nameof(instanceName));
var mongoDbName = instanceName + "_" + connectionStringName;
var invalidChars = new[]
{
'\0', ' ', '.', '$', '/', '\\'
};
foreach (var @char in invalidChars)
{
mongoDbName = mongoDbName.Replace(@char, "_"); // #SIM-128 Fixed
}
var value = Settings.AppMongoConnectionString.Value.TrimEnd('/') + @"/" + mongoDbName;
return value;
}
[NotNull]
private static string GetUnusedDatabaseName([NotNull] SqlConnectionStringBuilder defaultConnectionString, [NotNull] string databaseName)
{
Assert.ArgumentNotNull(defaultConnectionString, nameof(defaultConnectionString));
Assert.ArgumentNotNull(databaseName, nameof(databaseName));
const int K = 100;
for (int i = 1; i <= K; i++)
{
if (!SqlServerManager.Instance.DatabaseExists(databaseName + '_' + i, defaultConnectionString))
{
return databaseName + "_" + i;
}
}
throw new InvalidOperationException("Something weird happen... Do you really have '{0}' file?".FormatWith(databaseName + "_" + K));
}
[NotNull]
private static string ResolveConflictByUnsedName([NotNull] SqlConnectionStringBuilder defaultConnectionString, [NotNull] ConnectionString connectionString, [NotNull] string databaseName)
{
Assert.ArgumentNotNull(defaultConnectionString, nameof(defaultConnectionString));
Assert.ArgumentNotNull(connectionString, nameof(connectionString));
Assert.ArgumentNotNull(databaseName, nameof(databaseName));
databaseName = GetUnusedDatabaseName(defaultConnectionString, databaseName);
connectionString.RealName = databaseName;
connectionString.SaveChanges();
return databaseName;
}
private static void SetConnectionStringNode([NotNull] string name, [NotNull] string sqlPrefix, [NotNull] SqlConnectionStringBuilder defaultConnectionString, [NotNull] ConnectionString connectionString)
{
Assert.ArgumentNotNull(name, nameof(name));
Assert.ArgumentNotNull(sqlPrefix, nameof(sqlPrefix));
Assert.ArgumentNotNull(defaultConnectionString, nameof(defaultConnectionString));
Assert.ArgumentNotNull(connectionString, nameof(connectionString));
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(defaultConnectionString.ConnectionString)
{
InitialCatalog = connectionString.GenerateDatabaseName(name, sqlPrefix),
IntegratedSecurity = false
};
connectionString.Value = builder.ToString();
connectionString.SaveChanges();
}
#endregion
public static string GetSqlPrefix(Instance instance)
{
var connectionStrings = instance.Configuration.ConnectionStrings.Where(x => x.IsSqlConnectionString).ToArray();
Assert.IsTrue(connectionStrings.Length >= 2, "2 or more sql connection strings are required");
return AttachDatabasesHelper.GetSqlPrefix(connectionStrings[0].Value, connectionStrings[1].Value);
}
public static void ExtractReportingDatabase(Instance instance, FileInfo destination)
{
Assert.ArgumentNotNull(instance, nameof(instance));
Assert.ArgumentNotNull(destination, nameof(destination));
var product = instance.Product;
Assert.IsNotNull(product.PackagePath.EmptyToNull(), "The {0} product distributive is not available in local repository", instance.ProductFullName);
var package = new FileInfo(product.PackagePath);
Assert.IsTrue(package.Exists, $"The {package.FullName} file does not exist");
using (var zip = ZipFile.OpenRead(package.FullName))
{
var entry = zip.Entries.FirstOrDefault(x => x.FullName.EndsWith("Sitecore.Analytics.mdf"));
Assert.IsNotNull(entry, "Cannot find Sitecore.Analytics.mdf in the {0} file", package.FullName);
entry.ExtractToFile(destination.FullName);
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class CommonEvents : GenericEvents
{
#region Functions
public override string GetEventType() { return GenericEventNames.Common; }
#endregion
#region Events
public class CommonEvent_Base : ICutsceneEventInterface { }
public class CommonEvent_ActivateGameObject : CommonEvent_Base
{
#region Functions
public void ActivateGameObject(GameObject go, bool active)
{
#if UNITY_3_5 || UNITY_3_4
go.active = active;
#else
go.SetActive(active);
#endif
}
public void ActivateGameObject(string go, bool active, string goParent)
{
GameObject parentGameObject = GameObject.Find(goParent);
if (parentGameObject != null)
{
GameObject child = VHUtils.FindChildRecursive(parentGameObject, go);
if (child != null)
{
child.SetActive(active);
}
else
{
Debug.LogError("Can't find gameobject with name:" + go);
}
}
else
{
Debug.LogError("Can't find gameobject with name:" + goParent);
}
}
public override object SaveRewindData(CutsceneEvent ce)
{
bool isActive = true;
if (!IsParamNull(ce, 0))
{
#if UNITY_3_5 || UNITY_3_4
isActive = Cast<GameObject>(ce, 0).active;
#else
isActive = Cast<GameObject>(ce, 0).activeSelf;
#endif
}
else
{
GameObject parentGameObject = GameObject.Find(Param(ce, 2).stringData);
if (parentGameObject != null)
{
GameObject child = VHUtils.FindChildRecursive(parentGameObject, Param(ce, 0).stringData);
if (child != null)
{
isActive = child.activeSelf;
}
}
}
return isActive;
}
public override void LoadRewindData(CutsceneEvent ce, object rData)
{
if (ce.FunctionOverloadIndex == 0)
{
ActivateGameObject(Cast<GameObject>(ce, 0), (bool)rData);
}
else
{
ActivateGameObject(Param(ce, 0).stringData, (bool)rData, Param(ce, 2).stringData);
}
}
#endregion
}
#if UNITY_3_5 || UNITY_3_4
public class CommonEvent_ActivateGameObjectRecursive : CommonEvent_Base
{
#region Functions
public void ActivateGameObjectRecursive(GameObject go, bool active)
{
go.SetActiveRecursively(active);
}
public override object SaveRewindData(CutsceneEvent ce)
{
return Cast<GameObject>(ce, 0).active;
}
public override void LoadRewindData(CutsceneEvent ce, object rData)
{
ActivateGameObjectRecursive(Cast<GameObject>(ce, 0), (bool)rData);
}
#endregion
}
#endif
public class CommonEvent_CreateGameObject : CommonEvent_Base
{
#region Variables
List<GameObject> m_CreatedObjects = new List<GameObject>();
#endregion
#region Functions
public void CreateGameObject(GameObject go)
{
m_CreatedObjects.Add((GameObject)GameObject.Instantiate(go));
}
public void CreateGameObject(GameObject go, Vector3 position, Vector3 rotation)
{
m_CreatedObjects.Add((GameObject)GameObject.Instantiate(go, position, Quaternion.Euler(rotation)));
}
public override object SaveRewindData(CutsceneEvent ce)
{
return m_CreatedObjects;
}
public override void LoadRewindData(CutsceneEvent ce, object rData)
{
List<GameObject> result = m_CreatedObjects.Except((List<GameObject>)rData).ToList();
for (int i = 0; i < result.Count; i++)
{
GameObject.Destroy(result[i]);
}
}
#endregion
}
public class CommonEvent_DestroyGameObject : CommonEvent_Base
{
#region Functions
public void DestroyGameObject(GameObject go)
{
Destroy(go);
}
#endregion
}
public class CommonEvent_TranslateGameObject : CommonEvent_Base
{
#region Functions
public void TranslateGameObject(GameObject go, Vector3 position)
{
go.transform.Translate(position);
}
public override object SaveRewindData(CutsceneEvent ce)
{
return Cast<GameObject>(ce, 0).transform.position;
}
public override void LoadRewindData(CutsceneEvent ce, object rData)
{
Cast<GameObject>(ce, 0).transform.position = (Vector3)rData;
}
#endregion
}
public class CommonEvent_RotateGameObject : CommonEvent_Base
{
#region Functions
public void RotateGameObject(GameObject go, Vector3 rotation)
{
go.transform.Rotate(rotation);
}
public override object SaveRewindData(CutsceneEvent ce)
{
return Cast<GameObject>(ce, 0).transform.rotation;
}
public override void LoadRewindData(CutsceneEvent ce, object rData)
{
Cast<GameObject>(ce, 0).transform.rotation = (Quaternion)rData;
}
#endregion
}
public class CommonEvent_TransformGameObject : CommonEvent_Base
{
#region Functions
public void TransformGameObject(GameObject go, Vector3 position)
{
go.transform.position = position;
}
public void TransformGameObject(GameObject go, Vector3 position, Vector3 rotation)
{
go.transform.position = position;
go.transform.rotation = Quaternion.Euler(rotation);
}
public void TransformGameObject(GameObject go, Vector3 position, Vector3 rotation, Vector3 scale)
{
go.transform.position = position;
go.transform.rotation = Quaternion.Euler(rotation);
go.transform.localScale = scale;
}
public void TransformGameObject(GameObject go, Transform transform)
{
go.transform.position = transform.position;
go.transform.rotation = transform.rotation;
go.transform.localScale = transform.localScale;
}
public void TransformGameObject(string go, Transform transform)
{
GameObject gameObj = GameObject.Find(go);
if (gameObj!= null)
{
gameObj.transform.position = transform.position;
gameObj.transform.rotation = transform.rotation;
gameObj.transform.localScale = transform.localScale;
}
}
public void TransformGameObject(string go, string transform)
{
GameObject gameObj = GameObject.Find(go);
GameObject transObject = GameObject.Find(transform);
if (gameObj != null && transObject != null)
{
gameObj.transform.position = transObject.transform.position;
gameObj.transform.rotation = transObject.transform.rotation;
gameObj.transform.localScale = transObject.transform.localScale;
}
}
public override object SaveRewindData(CutsceneEvent ce)
{
Transform transform = null;//
if (!IsParamNull(ce, 0))
{
transform = Cast<GameObject>(ce, 0).transform;
}
if (transform == null)
{
transform = GameObject.Find(Param(ce, 0).stringData).transform;
}
return transform != null ? new TransformData(transform.position, transform.rotation.eulerAngles, transform.localScale) : new TransformData();
}
public override void LoadRewindData(CutsceneEvent ce, object rData)
{
if (rData != null)
{
TransformData transformData = (TransformData)rData;
if (!string.IsNullOrEmpty(Param(ce, 0).stringData))
{
GameObject gameObj = GameObject.Find(Param(ce, 0).stringData);
TransformGameObject(gameObj, transformData.Position, transformData.Rotation, transformData.Scale);
}
else
{
TransformGameObject(Cast<GameObject>(ce, 0), transformData.Position, transformData.Rotation, transformData.Scale);
}
}
}
#endregion
}
public class CommonEvent_ApplyForce : CommonEvent_Base
{
#region Function
public void ApplyForce(Rigidbody rb, Vector3 force)
{
rb.AddForce(force);
}
public override object SaveRewindData(CutsceneEvent ce)
{
return SaveTransformHierarchy(Cast<Rigidbody>(ce, 0).transform);
}
public override void LoadRewindData(CutsceneEvent ce, object rData)
{
LoadTransformHierarchy((List<TransformData>)rData, Cast<Rigidbody>(ce, 0).transform);
}
#endregion
}
public class CommonEvent_SetTimeScale : CommonEvent_Base
{
#region Function
public void SetTimeScale(float timeScale)
{
Time.timeScale = timeScale;
}
public override object SaveRewindData(CutsceneEvent ce)
{
return Time.timeScale;
}
public override void LoadRewindData(CutsceneEvent ce, object rData)
{
SetTimeScale((float)rData);
}
#endregion
}
public class CommonEvent_Pause : CommonEvent_Base
{
#region Function
public void Pause(bool pause)
{
Time.timeScale = pause ? 0 : 1;
}
public override object SaveRewindData(CutsceneEvent ce)
{
return Time.timeScale == 0;
}
public override void LoadRewindData(CutsceneEvent ce, object rData)
{
Pause((bool)rData);
}
#endregion
}
public class CommonEvent_LookAt : CommonEvent_Base
{
#region Function
public void LookAt(GameObject looker, GameObject target)
{
looker.transform.LookAt(target.transform);
}
public void LookAt(GameObject looker, Vector3 target)
{
looker.transform.LookAt(target);
}
public override object SaveRewindData(CutsceneEvent ce)
{
return Cast<GameObject>(ce, 0).transform.rotation;
}
public override void LoadRewindData(CutsceneEvent ce, object rData)
{
Cast<GameObject>(ce, 0).transform.rotation = (Quaternion)rData;
}
#endregion
}
public class CommonEvent_SendVHMsg : CommonEvent_Base
{
#region Function
public void SendVHMsg(string message)
{
if (VHMsgBase.Get() != null)
{
VHMsgBase.Get().SendVHMsg(message);
}
}
public override string GetXMLString(CutsceneEvent ce)
{
return string.Format(@"<event message=""{0}"" stroke=""{1}"" ypos=""{2}"" id=""{3}""/>", ce.FindParameter("message").stringData, ce.StartTime, ce.GuiPosition.y, ce.Name);
}
public override void SetParameters(CutsceneEvent ce, System.Xml.XmlReader reader)
{
float startTime;
if (!string.IsNullOrEmpty(reader["start"]))
{
if (float.TryParse(reader["start"], out startTime))
{
ce.StartTime = startTime;
}
}
else if (!string.IsNullOrEmpty(reader["stroke"]))
{
if (float.TryParse(reader["stroke"], out startTime))
{
ce.StartTime = startTime;
}
}
ce.Name = !string.IsNullOrEmpty(reader["id"]) ? reader["id"] : "Event";
ce.FindParameter("message").stringData = reader["message"];
}
#endregion
}
public class CommonEvent_PlayCutscene : CommonEvent_Base
{
#region Function
public void PlayCutscene(Cutscene cutscene)
{
cutscene.Play();
}
public void PlayCutscene(string cutscene)
{
GameObject cutsceneGO = GameObject.Find(cutscene);
if (cutsceneGO != null)
{
Cutscene cs = cutsceneGO.GetComponent<Cutscene>();
if (cs != null)
{
cs.Play();
}
else
{
Debug.LogError("Gameobject " + cutscene + " doesn't have a Cutscene component");
}
}
else
{
Debug.LogError("No gameobject found with name " + cutscene);
}
}
public override string GetLengthParameterName() { return "cutscene"; }
#endregion
}
public class CommonEvent_PauseCutscene : CommonEvent_Base
{
#region Function
public void PauseCutscene(Cutscene cutscene)
{
cutscene.Pause();
}
#endregion
}
public class CommonEvent_LoadLevel : CommonEvent_Base
{
#region Function
public void LoadLevel(string levelName)
{
VHUtils.SceneManagerLoadScene(levelName);
}
public void LoadLevel(int level)
{
VHUtils.SceneManagerLoadScene(level);
}
#endregion
}
public class CommonEvent_SetParent : CommonEvent_Base
{
#region Function
public void SetParent(Transform parent, Transform child)
{
child.parent = parent;
}
public override object SaveRewindData(CutsceneEvent ce)
{
return Cast<GameObject>(ce, 0).transform.parent;
}
public override void LoadRewindData(CutsceneEvent ce, object rData)
{
SetParent(Cast<GameObject>(ce, 0).transform, (Transform)rData);
}
#endregion
}
public class CommonEvent_SendUnityMessage : CommonEvent_Base
{
#region Function
public void SendUnityMessage(GameObject messenger, string methodName)
{
messenger.SendMessage(methodName);
}
public void SendUnityMessage(GameObject messenger, string methodName, object value)
{
messenger.SendMessage(methodName, value);
}
#endregion
}
public class CommonEvent_BroadcastUnityMessage : CommonEvent_Base
{
#region Function
public void BroadcastUnityMessage(GameObject messenger, string methodName)
{
messenger.BroadcastMessage(methodName);
}
public void BroadcastUnityMessage(GameObject messenger, string methodName, object value)
{
messenger.SendMessage(methodName, value);
}
#endregion
}
public class CommonEvent_Marker : CommonEvent_Base
{
#region Function
// Note - this event intentionally does nothing
public void Marker() { }
public void Marker(float length) { }
public override string GetLengthParameterName() { return "length"; }
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "length")
{
param.floatData = 1;
}
}
#endregion
}
public class CommonEvent_DisplayObject : CommonEvent_Base
{
#region Function
public void DisplayObject(GameObject obj, float displayTime)
{
VHUtils.DisplayObject(obj, m_Behaviour, displayTime, true);
}
public void DisplayObject(GameObject obj, float displayTime, bool startsOn)
{
VHUtils.DisplayObject(obj, m_Behaviour, displayTime, startsOn);
}
public override string GetLengthParameterName() { return "displayTime"; }
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "displayTime")
{
param.floatData = 1;
}
}
#endregion
}
public class CommonEvent_DisplayText : CommonEvent_Base
{
#region Function
public void DisplayText(GUIText textObj, string text, float displayTime)
{
textObj.text = text;
VHUtils.DisplayObject(textObj.gameObject, m_Behaviour, displayTime, true);
}
public void DisplayText(GUIText textObj, string text, float displayTime, bool startsOn)
{
textObj.text = text;
VHUtils.DisplayObject(textObj.gameObject, m_Behaviour, displayTime, startsOn);
}
public override string GetLengthParameterName() { return "displayTime"; }
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "displayTime")
{
param.floatData = 1;
}
}
#endregion
}
public class CommonEvent_RecordPerformance_Start : CommonEvent_Base
{
#region Function
public void RecordPerformance_Start(VHTimeDemo recorder, string projectName, string timeDemoName)
{
recorder.StartTimeDemo(false, projectName, timeDemoName);
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "timeDemoName")
{
param.stringData = VHUtils.SceneManagerActiveSceneName();
}
}
#endregion
}
public class CommonEvent_RecordPerformance_Stop : CommonEvent_Base
{
#region Function
public void RecordPerformance_Stop(VHTimeDemo recorder)
{
//recorder.StopTimeDemo();
}
#endregion
}
public class CommonEvent_PlayMovieTexture : CommonEvent_Base
{
#region Function
#if !UNITY_IPHONE && !UNITY_ANDROID && !UNITY_WEBGL
public void PlayMovieTexture(MovieTexture movie)
{
movie.Play();
}
public void PlayMovieTexture(Material mat, MovieTexture movie)
{
mat.mainTexture = movie;
movie.Play();
}
#else
public void PlayMovieTexture(Texture movie) {}
public void PlayMovieTexture(Material mat, Texture movie) {}
#endif
#endregion
}
#endregion
}
| |
// Zlib.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009-2011 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// Last Saved: <2011-August-03 19:52:28>
//
// ------------------------------------------------------------------
//
// This module defines classes for ZLIB compression and
// decompression. This code is derived from the jzlib implementation of
// zlib, but significantly modified. The object model is not the same,
// and many of the behaviors are new or different. Nonetheless, in
// keeping with the license for jzlib, the copyright to that code is
// included below.
//
// ------------------------------------------------------------------
//
// The following notice applies to jzlib:
//
// Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the distribution.
//
// 3. The names of the authors may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
// INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
//
// -----------------------------------------------------------------------
//
// jzlib is based on zlib-1.1.3.
//
// The following notice applies to zlib:
//
// -----------------------------------------------------------------------
//
// Copyright (C) 1995-2004 Jean-loup Gailly and Mark Adler
//
// The ZLIB software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Jean-loup Gailly jloup@gzip.org
// Mark Adler madler@alumni.caltech.edu
//
// -----------------------------------------------------------------------
using System;
using Interop=System.Runtime.InteropServices;
namespace Cimbalino.Phone.Toolkit.Compression
{
/// <summary>
/// Describes how to flush the current deflate operation.
/// </summary>
/// <remarks>
/// The different FlushType values are useful when using a Deflate in a streaming application.
/// </remarks>
public enum FlushType
{
/// <summary>No flush at all.</summary>
None = 0,
/// <summary>Closes the current block, but doesn't flush it to
/// the output. Used internally only in hypothetical
/// scenarios. This was supposed to be removed by Zlib, but it is
/// still in use in some edge cases.
/// </summary>
Partial,
/// <summary>
/// Use this during compression to specify that all pending output should be
/// flushed to the output buffer and the output should be aligned on a byte
/// boundary. You might use this in a streaming communication scenario, so that
/// the decompressor can get all input data available so far. When using this
/// with a ZlibCodec, <c>AvailableBytesIn</c> will be zero after the call if
/// enough output space has been provided before the call. Flushing will
/// degrade compression and so it should be used only when necessary.
/// </summary>
Sync,
/// <summary>
/// Use this during compression to specify that all output should be flushed, as
/// with <c>FlushType.Sync</c>, but also, the compression state should be reset
/// so that decompression can restart from this point if previous compressed
/// data has been damaged or if random access is desired. Using
/// <c>FlushType.Full</c> too often can significantly degrade the compression.
/// </summary>
Full,
/// <summary>Signals the end of the compression/decompression stream.</summary>
Finish,
}
/// <summary>
/// The compression level to be used when using a DeflateStream or ZlibStream with CompressionMode.Compress.
/// </summary>
public enum CompressionLevel
{
/// <summary>
/// None means that the data will be simply stored, with no change at all.
/// If you are producing ZIPs for use on Mac OSX, be aware that archives produced with CompressionLevel.None
/// cannot be opened with the default zip reader. Use a different CompressionLevel.
/// </summary>
None= 0,
/// <summary>
/// Same as None.
/// </summary>
Level0 = 0,
/// <summary>
/// The fastest but least effective compression.
/// </summary>
BestSpeed = 1,
/// <summary>
/// A synonym for BestSpeed.
/// </summary>
Level1 = 1,
/// <summary>
/// A little slower, but better, than level 1.
/// </summary>
Level2 = 2,
/// <summary>
/// A little slower, but better, than level 2.
/// </summary>
Level3 = 3,
/// <summary>
/// A little slower, but better, than level 3.
/// </summary>
Level4 = 4,
/// <summary>
/// A little slower than level 4, but with better compression.
/// </summary>
Level5 = 5,
/// <summary>
/// The default compression level, with a good balance of speed and compression efficiency.
/// </summary>
Default = 6,
/// <summary>
/// A synonym for Default.
/// </summary>
Level6 = 6,
/// <summary>
/// Pretty good compression!
/// </summary>
Level7 = 7,
/// <summary>
/// Better compression than Level7!
/// </summary>
Level8 = 8,
/// <summary>
/// The "best" compression, where best means greatest reduction in size of the input data stream.
/// This is also the slowest compression.
/// </summary>
BestCompression = 9,
/// <summary>
/// A synonym for BestCompression.
/// </summary>
Level9 = 9,
}
/// <summary>
/// Describes options for how the compression algorithm is executed. Different strategies
/// work better on different sorts of data. The strategy parameter can affect the compression
/// ratio and the speed of compression but not the correctness of the compresssion.
/// </summary>
public enum CompressionStrategy
{
/// <summary>
/// The default strategy is probably the best for normal data.
/// </summary>
Default = 0,
/// <summary>
/// The <c>Filtered</c> strategy is intended to be used most effectively with data produced by a
/// filter or predictor. By this definition, filtered data consists mostly of small
/// values with a somewhat random distribution. In this case, the compression algorithm
/// is tuned to compress them better. The effect of <c>Filtered</c> is to force more Huffman
/// coding and less string matching; it is a half-step between <c>Default</c> and <c>HuffmanOnly</c>.
/// </summary>
Filtered = 1,
/// <summary>
/// Using <c>HuffmanOnly</c> will force the compressor to do Huffman encoding only, with no
/// string matching.
/// </summary>
HuffmanOnly = 2,
}
/// <summary>
/// An enum to specify the direction of transcoding - whether to compress or decompress.
/// </summary>
public enum CompressionMode
{
/// <summary>
/// Used to specify that the stream should compress the data.
/// </summary>
Compress= 0,
/// <summary>
/// Used to specify that the stream should decompress the data.
/// </summary>
Decompress = 1,
}
/// <summary>
/// A general purpose exception class for exceptions in the Zlib library.
/// </summary>
[Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000E")]
public class ZlibException : System.Exception
{
/// <summary>
/// The ZlibException class captures exception information generated
/// by the Zlib library.
/// </summary>
public ZlibException()
: base()
{
}
/// <summary>
/// This ctor collects a message attached to the exception.
/// </summary>
/// <param name="s">the message for the exception.</param>
public ZlibException(System.String s)
: base(s)
{
}
}
internal class SharedUtils
{
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static int URShift(int number, int bits)
{
return (int)((uint)number >> bits);
}
#if NOT
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static long URShift(long number, int bits)
{
return (long) ((UInt64)number >> bits);
}
#endif
/// <summary>
/// Reads a number of characters from the current source TextReader and writes
/// the data to the target array at the specified index.
/// </summary>
///
/// <param name="sourceTextReader">The source TextReader to read from</param>
/// <param name="target">Contains the array of characteres read from the source TextReader.</param>
/// <param name="start">The starting index of the target array.</param>
/// <param name="count">The maximum number of characters to read from the source TextReader.</param>
///
/// <returns>
/// The number of characters read. The number will be less than or equal to
/// count depending on the data available in the source TextReader. Returns -1
/// if the end of the stream is reached.
/// </returns>
public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count)
{
// Returns 0 bytes if not enough space in target
if (target.Length == 0) return 0;
char[] charArray = new char[target.Length];
int bytesRead = sourceTextReader.Read(charArray, start, count);
// Returns -1 if EOF
if (bytesRead == 0) return -1;
for (int index = start; index < start + bytesRead; index++)
target[index] = (byte)charArray[index];
return bytesRead;
}
internal static byte[] ToByteArray(System.String sourceString)
{
return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString);
}
internal static char[] ToCharArray(byte[] byteArray)
{
return System.Text.UTF8Encoding.UTF8.GetChars(byteArray);
}
}
internal static class InternalConstants
{
internal static readonly int MAX_BITS = 15;
internal static readonly int BL_CODES = 19;
internal static readonly int D_CODES = 30;
internal static readonly int LITERALS = 256;
internal static readonly int LENGTH_CODES = 29;
internal static readonly int L_CODES = (LITERALS + 1 + LENGTH_CODES);
// Bit length codes must not exceed MAX_BL_BITS bits
internal static readonly int MAX_BL_BITS = 7;
// repeat previous bit length 3-6 times (2 bits of repeat count)
internal static readonly int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
internal static readonly int REPZ_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
internal static readonly int REPZ_11_138 = 18;
}
internal sealed class StaticTree
{
internal static readonly short[] lengthAndLiteralsTreeCodes = new short[] {
12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8,
28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8,
2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8,
18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8,
10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8,
26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8,
6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8,
22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8,
14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8,
30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8,
1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8,
17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8,
9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8,
25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8,
5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8,
21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8,
13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8,
29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8,
19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9,
51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9,
11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9,
43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9,
27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9,
59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9,
7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9,
39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9,
23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9,
55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9,
15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9,
47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9,
31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9,
63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9,
0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7,
8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7,
4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7,
3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8
};
internal static readonly short[] distTreeCodes = new short[] {
0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5,
2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5,
1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5,
3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 };
internal static readonly StaticTree Literals;
internal static readonly StaticTree Distances;
internal static readonly StaticTree BitLengths;
internal short[] treeCodes; // static tree or null
internal int[] extraBits; // extra bits for each code or null
internal int extraBase; // base index for extra_bits
internal int elems; // max number of elements in the tree
internal int maxLength; // max bit length for the codes
private StaticTree(short[] treeCodes, int[] extraBits, int extraBase, int elems, int maxLength)
{
this.treeCodes = treeCodes;
this.extraBits = extraBits;
this.extraBase = extraBase;
this.elems = elems;
this.maxLength = maxLength;
}
static StaticTree()
{
Literals = new StaticTree(lengthAndLiteralsTreeCodes, Tree.ExtraLengthBits, InternalConstants.LITERALS + 1, InternalConstants.L_CODES, InternalConstants.MAX_BITS);
Distances = new StaticTree(distTreeCodes, Tree.ExtraDistanceBits, 0, InternalConstants.D_CODES, InternalConstants.MAX_BITS);
BitLengths = new StaticTree(null, Tree.extra_blbits, 0, InternalConstants.BL_CODES, InternalConstants.MAX_BL_BITS);
}
}
/// <summary>
/// Computes an Adler-32 checksum.
/// </summary>
/// <remarks>
/// The Adler checksum is similar to a CRC checksum, but faster to compute, though less
/// reliable. It is used in producing RFC1950 compressed streams. The Adler checksum
/// is a required part of the "ZLIB" standard. Applications will almost never need to
/// use this class directly.
/// </remarks>
///
/// <exclude/>
public sealed class Adler
{
// largest prime smaller than 65536
private static readonly uint BASE = 65521;
// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
private static readonly int NMAX = 5552;
#pragma warning disable 3001
#pragma warning disable 3002
/// <summary>
/// Calculates the Adler32 checksum.
/// </summary>
/// <remarks>
/// <para>
/// This is used within ZLIB. You probably don't need to use this directly.
/// </para>
/// </remarks>
/// <example>
/// To compute an Adler32 checksum on a byte array:
/// <code>
/// var adler = Adler.Adler32(0, null, 0, 0);
/// adler = Adler.Adler32(adler, buffer, index, length);
/// </code>
/// </example>
public static uint Adler32(uint adler, byte[] buf, int index, int len)
{
if (buf == null)
return 1;
uint s1 = (uint) (adler & 0xffff);
uint s2 = (uint) ((adler >> 16) & 0xffff);
while (len > 0)
{
int k = len < NMAX ? len : NMAX;
len -= k;
while (k >= 16)
{
//s1 += (buf[index++] & 0xff); s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
k -= 16;
}
if (k != 0)
{
do
{
s1 += buf[index++];
s2 += s1;
}
while (--k != 0);
}
s1 %= BASE;
s2 %= BASE;
}
return (uint)((s2 << 16) | s1);
}
#pragma warning restore 3001
#pragma warning restore 3002
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalGridServicesConnector")]
public class LocalGridServicesConnector : ISharedRegionModule, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private static string LogHeader = "[LOCAL GRID SERVICE CONNECTOR]";
private IGridService m_GridService;
private Dictionary<UUID, RegionCache> m_LocalCache = new Dictionary<UUID, RegionCache>();
private bool m_Enabled;
public LocalGridServicesConnector()
{
m_log.DebugFormat("{0} LocalGridServicesConnector no parms.", LogHeader);
}
public LocalGridServicesConnector(IConfigSource source)
{
m_log.DebugFormat("{0} LocalGridServicesConnector instantiated directly.", LogHeader);
InitialiseService(source);
}
#region ISharedRegionModule
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalGridServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("GridServices", "");
if (name == Name)
{
InitialiseService(source);
m_log.Info("[LOCAL GRID SERVICE CONNECTOR]: Local grid connector enabled");
}
}
}
private void InitialiseService(IConfigSource source)
{
IConfig config = source.Configs["GridService"];
if (config == null)
{
m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: GridService missing from OpenSim.ini");
return;
}
string serviceDll = config.GetString("LocalServiceModule", String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: No LocalServiceModule named in section GridService");
return;
}
Object[] args = new Object[] { source };
m_GridService =
ServerUtils.LoadPlugin<IGridService>(serviceDll,
args);
if (m_GridService == null)
{
m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: Can't load grid service");
return;
}
m_Enabled = true;
}
public void PostInitialise()
{
// FIXME: We will still add this command even if we aren't enabled since RemoteGridServiceConnector
// will have instantiated us directly.
MainConsole.Instance.Commands.AddCommand("Regions", false, "show neighbours",
"show neighbours",
"Shows the local regions' neighbours", HandleShowNeighboursCommand);
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IGridService>(this);
lock (m_LocalCache)
{
if (m_LocalCache.ContainsKey(scene.RegionInfo.RegionID))
m_log.ErrorFormat("[LOCAL GRID SERVICE CONNECTOR]: simulator seems to have more than one region with the same UUID. Please correct this!");
else
m_LocalCache.Add(scene.RegionInfo.RegionID, new RegionCache(scene));
}
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_LocalCache)
{
m_LocalCache[scene.RegionInfo.RegionID].Clear();
m_LocalCache.Remove(scene.RegionInfo.RegionID);
}
}
public void RegionLoaded(Scene scene)
{
}
#endregion
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
return m_GridService.RegisterRegion(scopeID, regionInfo);
}
public bool DeregisterRegion(UUID regionID)
{
return m_GridService.DeregisterRegion(regionID);
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
return m_GridService.GetNeighbours(scopeID, regionID);
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
return m_GridService.GetRegionByUUID(scopeID, regionID);
}
// Get a region given its base coordinates.
// NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST
// be the base coordinate of the region.
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
GridRegion region = null;
// uint regionX = Util.WorldToRegionLoc((uint)x);
// uint regionY = Util.WorldToRegionLoc((uint)y);
// First see if it's a neighbour, even if it isn't on this sim.
// Neighbour data is cached in memory, so this is fast
lock (m_LocalCache)
{
foreach (RegionCache rcache in m_LocalCache.Values)
{
region = rcache.GetRegionByPosition(x, y);
if (region != null)
{
// m_log.DebugFormat("{0} GetRegionByPosition. Found region {1} in cache. Pos=<{2},{3}>",
// LogHeader, region.RegionName, x, y);
break;
}
}
}
// Then try on this sim (may be a lookup in DB if this is using MySql).
if (region == null)
{
region = m_GridService.GetRegionByPosition(scopeID, x, y);
/*
if (region == null)
{
m_log.DebugFormat("{0} GetRegionByPosition. Region not found by grid service. Pos=<{1},{2}>",
LogHeader, regionX, regionY);
}
else
{
m_log.DebugFormat("{0} GetRegionByPosition. Requested region {1} from grid service. Pos=<{2},{3}>",
LogHeader, region.RegionName, regionX, regionY);
}
*/
}
return region;
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
return m_GridService.GetRegionByName(scopeID, regionName);
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
return m_GridService.GetRegionsByName(scopeID, name, maxNumber);
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
return m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
return m_GridService.GetDefaultRegions(scopeID);
}
public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
{
return m_GridService.GetDefaultHypergridRegions(scopeID);
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
return m_GridService.GetFallbackRegions(scopeID, x, y);
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
return m_GridService.GetHyperlinks(scopeID);
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
return m_GridService.GetRegionFlags(scopeID, regionID);
}
public Dictionary<string, object> GetExtraFeatures()
{
return m_GridService.GetExtraFeatures();
}
#endregion
public void HandleShowNeighboursCommand(string module, string[] cmdparams)
{
System.Text.StringBuilder caps = new System.Text.StringBuilder();
lock (m_LocalCache)
{
foreach (KeyValuePair<UUID, RegionCache> kvp in m_LocalCache)
{
caps.AppendFormat("*** Neighbours of {0} ({1}) ***\n", kvp.Value.RegionName, kvp.Key);
List<GridRegion> regions = kvp.Value.GetNeighbours();
foreach (GridRegion r in regions)
caps.AppendFormat(" {0} @ {1}-{2}\n", r.RegionName, Util.WorldToRegionLoc((uint)r.RegionLocX), Util.WorldToRegionLoc((uint)r.RegionLocY));
}
}
MainConsole.Instance.Output(caps.ToString());
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Tls
{
public class TlsClientProtocol
: TlsProtocol
{
protected TlsClient mTlsClient = null;
internal TlsClientContextImpl mTlsClientContext = null;
protected byte[] mSelectedSessionID = null;
protected TlsKeyExchange mKeyExchange = null;
protected TlsAuthentication mAuthentication = null;
protected CertificateStatus mCertificateStatus = null;
protected CertificateRequest mCertificateRequest = null;
public TlsClientProtocol(Stream stream, SecureRandom secureRandom)
: base(stream, secureRandom)
{
}
public TlsClientProtocol(Stream input, Stream output, SecureRandom secureRandom)
: base(input, output, secureRandom)
{
}
/**
* Initiates a TLS handshake in the role of client
*
* @param tlsClient The {@link TlsClient} to use for the handshake.
* @throws IOException If handshake was not successful.
*/
public virtual void Connect(TlsClient tlsClient)
{
if (tlsClient == null)
throw new ArgumentNullException("tlsClient");
if (this.mTlsClient != null)
throw new InvalidOperationException("'Connect' can only be called once");
this.mTlsClient = tlsClient;
this.mSecurityParameters = new SecurityParameters();
this.mSecurityParameters.entity = ConnectionEnd.client;
this.mTlsClientContext = new TlsClientContextImpl(mSecureRandom, mSecurityParameters);
this.mSecurityParameters.clientRandom = CreateRandomBlock(tlsClient.ShouldUseGmtUnixTime(),
mTlsClientContext.NonceRandomGenerator);
this.mTlsClient.Init(mTlsClientContext);
this.mRecordStream.Init(mTlsClientContext);
TlsSession sessionToResume = tlsClient.GetSessionToResume();
if (sessionToResume != null && sessionToResume.IsResumable)
{
SessionParameters sessionParameters = sessionToResume.ExportSessionParameters();
if (sessionParameters != null)
{
this.mTlsSession = sessionToResume;
this.mSessionParameters = sessionParameters;
}
}
SendClientHelloMessage();
this.mConnectionState = CS_CLIENT_HELLO;
CompleteHandshake();
}
protected override void CleanupHandshake()
{
base.CleanupHandshake();
this.mSelectedSessionID = null;
this.mKeyExchange = null;
this.mAuthentication = null;
this.mCertificateStatus = null;
this.mCertificateRequest = null;
}
protected override TlsContext Context
{
get { return mTlsClientContext; }
}
internal override AbstractTlsContext ContextAdmin
{
get { return mTlsClientContext; }
}
protected override TlsPeer Peer
{
get { return mTlsClient; }
}
protected override void HandleHandshakeMessage(byte type, byte[] data)
{
MemoryStream buf = new MemoryStream(data, false);
if (this.mResumedSession)
{
if (type != HandshakeType.finished || this.mConnectionState != CS_SERVER_HELLO)
throw new TlsFatalAlert(AlertDescription.unexpected_message);
ProcessFinishedMessage(buf);
this.mConnectionState = CS_SERVER_FINISHED;
SendFinishedMessage();
this.mConnectionState = CS_CLIENT_FINISHED;
this.mConnectionState = CS_END;
return;
}
switch (type)
{
case HandshakeType.certificate:
{
switch (this.mConnectionState)
{
case CS_SERVER_HELLO:
case CS_SERVER_SUPPLEMENTAL_DATA:
{
if (this.mConnectionState == CS_SERVER_HELLO)
{
HandleSupplementalData(null);
}
// Parse the Certificate message and Send to cipher suite
this.mPeerCertificate = Certificate.Parse(buf);
AssertEmpty(buf);
// TODO[RFC 3546] Check whether empty certificates is possible, allowed, or excludes CertificateStatus
if (this.mPeerCertificate == null || this.mPeerCertificate.IsEmpty)
{
this.mAllowCertificateStatus = false;
}
this.mKeyExchange.ProcessServerCertificate(this.mPeerCertificate);
this.mAuthentication = mTlsClient.GetAuthentication();
this.mAuthentication.NotifyServerCertificate(this.mPeerCertificate);
break;
}
default:
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
this.mConnectionState = CS_SERVER_CERTIFICATE;
break;
}
case HandshakeType.certificate_status:
{
switch (this.mConnectionState)
{
case CS_SERVER_CERTIFICATE:
{
if (!this.mAllowCertificateStatus)
{
/*
* RFC 3546 3.6. If a server returns a "CertificateStatus" message, then the
* server MUST have included an extension of type "status_request" with empty
* "extension_data" in the extended server hello..
*/
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
this.mCertificateStatus = CertificateStatus.Parse(buf);
AssertEmpty(buf);
// TODO[RFC 3546] Figure out how to provide this to the client/authentication.
this.mConnectionState = CS_CERTIFICATE_STATUS;
break;
}
default:
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
break;
}
case HandshakeType.finished:
{
switch (this.mConnectionState)
{
case CS_CLIENT_FINISHED:
case CS_SERVER_SESSION_TICKET:
{
if (this.mConnectionState == CS_CLIENT_FINISHED && this.mExpectSessionTicket)
{
/*
* RFC 5077 3.3. This message MUST be sent if the server included a
* SessionTicket extension in the ServerHello.
*/
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
ProcessFinishedMessage(buf);
this.mConnectionState = CS_SERVER_FINISHED;
this.mConnectionState = CS_END;
break;
}
default:
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
break;
}
case HandshakeType.server_hello:
{
switch (this.mConnectionState)
{
case CS_CLIENT_HELLO:
{
ReceiveServerHelloMessage(buf);
this.mConnectionState = CS_SERVER_HELLO;
this.mRecordStream.NotifyHelloComplete();
ApplyMaxFragmentLengthExtension();
if (this.mResumedSession)
{
this.mSecurityParameters.masterSecret = Arrays.Clone(this.mSessionParameters.MasterSecret);
this.mRecordStream.SetPendingConnectionState(Peer.GetCompression(), Peer.GetCipher());
SendChangeCipherSpecMessage();
}
else
{
InvalidateSession();
if (this.mSelectedSessionID.Length > 0)
{
this.mTlsSession = new TlsSessionImpl(this.mSelectedSessionID, null);
}
}
break;
}
default:
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
break;
}
case HandshakeType.supplemental_data:
{
switch (this.mConnectionState)
{
case CS_SERVER_HELLO:
{
HandleSupplementalData(ReadSupplementalDataMessage(buf));
break;
}
default:
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
break;
}
case HandshakeType.server_hello_done:
{
switch (this.mConnectionState)
{
case CS_SERVER_HELLO:
case CS_SERVER_SUPPLEMENTAL_DATA:
case CS_SERVER_CERTIFICATE:
case CS_CERTIFICATE_STATUS:
case CS_SERVER_KEY_EXCHANGE:
case CS_CERTIFICATE_REQUEST:
{
if (mConnectionState < CS_SERVER_SUPPLEMENTAL_DATA)
{
HandleSupplementalData(null);
}
if (mConnectionState < CS_SERVER_CERTIFICATE)
{
// There was no server certificate message; check it's OK
this.mKeyExchange.SkipServerCredentials();
this.mAuthentication = null;
}
if (mConnectionState < CS_SERVER_KEY_EXCHANGE)
{
// There was no server key exchange message; check it's OK
this.mKeyExchange.SkipServerKeyExchange();
}
AssertEmpty(buf);
this.mConnectionState = CS_SERVER_HELLO_DONE;
this.mRecordStream.HandshakeHash.SealHashAlgorithms();
IList clientSupplementalData = mTlsClient.GetClientSupplementalData();
if (clientSupplementalData != null)
{
SendSupplementalDataMessage(clientSupplementalData);
}
this.mConnectionState = CS_CLIENT_SUPPLEMENTAL_DATA;
TlsCredentials clientCreds = null;
if (mCertificateRequest == null)
{
this.mKeyExchange.SkipClientCredentials();
}
else
{
clientCreds = this.mAuthentication.GetClientCredentials(mCertificateRequest);
if (clientCreds == null)
{
this.mKeyExchange.SkipClientCredentials();
/*
* RFC 5246 If no suitable certificate is available, the client MUST Send a
* certificate message containing no certificates.
*
* NOTE: In previous RFCs, this was SHOULD instead of MUST.
*/
SendCertificateMessage(Certificate.EmptyChain);
}
else
{
this.mKeyExchange.ProcessClientCredentials(clientCreds);
SendCertificateMessage(clientCreds.Certificate);
}
}
this.mConnectionState = CS_CLIENT_CERTIFICATE;
/*
* Send the client key exchange message, depending on the key exchange we are using
* in our CipherSuite.
*/
SendClientKeyExchangeMessage();
this.mConnectionState = CS_CLIENT_KEY_EXCHANGE;
TlsHandshakeHash prepareFinishHash = mRecordStream.PrepareToFinish();
this.mSecurityParameters.sessionHash = GetCurrentPrfHash(Context, prepareFinishHash, null);
EstablishMasterSecret(Context, mKeyExchange);
mRecordStream.SetPendingConnectionState(Peer.GetCompression(), Peer.GetCipher());
if (clientCreds != null && clientCreds is TlsSignerCredentials)
{
TlsSignerCredentials signerCredentials = (TlsSignerCredentials)clientCreds;
/*
* RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
*/
SignatureAndHashAlgorithm signatureAndHashAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm(
Context, signerCredentials);
byte[] hash;
if (signatureAndHashAlgorithm == null)
{
hash = mSecurityParameters.SessionHash;
}
else
{
hash = prepareFinishHash.GetFinalHash(signatureAndHashAlgorithm.Hash);
}
byte[] signature = signerCredentials.GenerateCertificateSignature(hash);
DigitallySigned certificateVerify = new DigitallySigned(signatureAndHashAlgorithm, signature);
SendCertificateVerifyMessage(certificateVerify);
this.mConnectionState = CS_CERTIFICATE_VERIFY;
}
SendChangeCipherSpecMessage();
SendFinishedMessage();
break;
}
default:
throw new TlsFatalAlert(AlertDescription.handshake_failure);
}
this.mConnectionState = CS_CLIENT_FINISHED;
break;
}
case HandshakeType.server_key_exchange:
{
switch (this.mConnectionState)
{
case CS_SERVER_HELLO:
case CS_SERVER_SUPPLEMENTAL_DATA:
case CS_SERVER_CERTIFICATE:
case CS_CERTIFICATE_STATUS:
{
if (mConnectionState < CS_SERVER_SUPPLEMENTAL_DATA)
{
HandleSupplementalData(null);
}
if (mConnectionState < CS_SERVER_CERTIFICATE)
{
// There was no server certificate message; check it's OK
this.mKeyExchange.SkipServerCredentials();
this.mAuthentication = null;
}
this.mKeyExchange.ProcessServerKeyExchange(buf);
AssertEmpty(buf);
break;
}
default:
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
this.mConnectionState = CS_SERVER_KEY_EXCHANGE;
break;
}
case HandshakeType.certificate_request:
{
switch (this.mConnectionState)
{
case CS_SERVER_CERTIFICATE:
case CS_CERTIFICATE_STATUS:
case CS_SERVER_KEY_EXCHANGE:
{
if (this.mConnectionState != CS_SERVER_KEY_EXCHANGE)
{
// There was no server key exchange message; check it's OK
this.mKeyExchange.SkipServerKeyExchange();
}
if (this.mAuthentication == null)
{
/*
* RFC 2246 7.4.4. It is a fatal handshake_failure alert for an anonymous server
* to request client identification.
*/
throw new TlsFatalAlert(AlertDescription.handshake_failure);
}
this.mCertificateRequest = CertificateRequest.Parse(Context, buf);
AssertEmpty(buf);
this.mKeyExchange.ValidateCertificateRequest(this.mCertificateRequest);
/*
* TODO Give the client a chance to immediately select the CertificateVerify hash
* algorithm here to avoid tracking the other hash algorithms unnecessarily?
*/
TlsUtilities.TrackHashAlgorithms(this.mRecordStream.HandshakeHash,
this.mCertificateRequest.SupportedSignatureAlgorithms);
break;
}
default:
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
this.mConnectionState = CS_CERTIFICATE_REQUEST;
break;
}
case HandshakeType.session_ticket:
{
switch (this.mConnectionState)
{
case CS_CLIENT_FINISHED:
{
if (!this.mExpectSessionTicket)
{
/*
* RFC 5077 3.3. This message MUST NOT be sent if the server did not include a
* SessionTicket extension in the ServerHello.
*/
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
/*
* RFC 5077 3.4. If the client receives a session ticket from the server, then it
* discards any Session ID that was sent in the ServerHello.
*/
InvalidateSession();
ReceiveNewSessionTicketMessage(buf);
break;
}
default:
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
this.mConnectionState = CS_SERVER_SESSION_TICKET;
break;
}
case HandshakeType.hello_request:
{
AssertEmpty(buf);
/*
* RFC 2246 7.4.1.1 Hello request This message will be ignored by the client if the
* client is currently negotiating a session. This message may be ignored by the client
* if it does not wish to renegotiate a session, or the client may, if it wishes,
* respond with a no_renegotiation alert.
*/
if (this.mConnectionState == CS_END)
{
RefuseRenegotiation();
}
break;
}
case HandshakeType.client_hello:
case HandshakeType.client_key_exchange:
case HandshakeType.certificate_verify:
case HandshakeType.hello_verify_request:
default:
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
}
protected virtual void HandleSupplementalData(IList serverSupplementalData)
{
this.mTlsClient.ProcessServerSupplementalData(serverSupplementalData);
this.mConnectionState = CS_SERVER_SUPPLEMENTAL_DATA;
this.mKeyExchange = mTlsClient.GetKeyExchange();
this.mKeyExchange.Init(Context);
}
protected virtual void ReceiveNewSessionTicketMessage(MemoryStream buf)
{
NewSessionTicket newSessionTicket = NewSessionTicket.Parse(buf);
AssertEmpty(buf);
mTlsClient.NotifyNewSessionTicket(newSessionTicket);
}
protected virtual void ReceiveServerHelloMessage(MemoryStream buf)
{
{
ProtocolVersion server_version = TlsUtilities.ReadVersion(buf);
if (server_version.IsDtls)
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
// Check that this matches what the server is Sending in the record layer
if (!server_version.Equals(this.mRecordStream.ReadVersion))
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
ProtocolVersion client_version = Context.ClientVersion;
if (!server_version.IsEqualOrEarlierVersionOf(client_version))
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
this.mRecordStream.SetWriteVersion(server_version);
ContextAdmin.SetServerVersion(server_version);
this.mTlsClient.NotifyServerVersion(server_version);
}
/*
* Read the server random
*/
this.mSecurityParameters.serverRandom = TlsUtilities.ReadFully(32, buf);
this.mSelectedSessionID = TlsUtilities.ReadOpaque8(buf);
if (this.mSelectedSessionID.Length > 32)
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
this.mTlsClient.NotifySessionID(this.mSelectedSessionID);
this.mResumedSession = this.mSelectedSessionID.Length > 0 && this.mTlsSession != null
&& Arrays.AreEqual(this.mSelectedSessionID, this.mTlsSession.SessionID);
/*
* Find out which CipherSuite the server has chosen and check that it was one of the offered
* ones, and is a valid selection for the negotiated version.
*/
int selectedCipherSuite = TlsUtilities.ReadUint16(buf);
if (!Arrays.Contains(this.mOfferedCipherSuites, selectedCipherSuite)
|| selectedCipherSuite == CipherSuite.TLS_NULL_WITH_NULL_NULL
|| CipherSuite.IsScsv(selectedCipherSuite)
|| !TlsUtilities.IsValidCipherSuiteForVersion(selectedCipherSuite, Context.ServerVersion))
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
this.mTlsClient.NotifySelectedCipherSuite(selectedCipherSuite);
/*
* Find out which CompressionMethod the server has chosen and check that it was one of the
* offered ones.
*/
byte selectedCompressionMethod = TlsUtilities.ReadUint8(buf);
if (!Arrays.Contains(this.mOfferedCompressionMethods, selectedCompressionMethod))
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
this.mTlsClient.NotifySelectedCompressionMethod(selectedCompressionMethod);
/*
* RFC3546 2.2 The extended server hello message format MAY be sent in place of the server
* hello message when the client has requested extended functionality via the extended
* client hello message specified in Section 2.1. ... Note that the extended server hello
* message is only sent in response to an extended client hello message. This prevents the
* possibility that the extended server hello message could "break" existing TLS 1.0
* clients.
*/
this.mServerExtensions = ReadExtensions(buf);
/*
* RFC 3546 2.2 Note that the extended server hello message is only sent in response to an
* extended client hello message.
*
* However, see RFC 5746 exception below. We always include the SCSV, so an Extended Server
* Hello is always allowed.
*/
if (this.mServerExtensions != null)
{
foreach (int extType in this.mServerExtensions.Keys)
{
/*
* RFC 5746 3.6. Note that Sending a "renegotiation_info" extension in response to a
* ClientHello containing only the SCSV is an explicit exception to the prohibition
* in RFC 5246, Section 7.4.1.4, on the server Sending unsolicited extensions and is
* only allowed because the client is signaling its willingness to receive the
* extension via the TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV.
*/
if (extType == ExtensionType.renegotiation_info)
continue;
/*
* RFC 5246 7.4.1.4 An extension type MUST NOT appear in the ServerHello unless the
* same extension type appeared in the corresponding ClientHello. If a client
* receives an extension type in ServerHello that it did not request in the
* associated ClientHello, it MUST abort the handshake with an unsupported_extension
* fatal alert.
*/
if (null == TlsUtilities.GetExtensionData(this.mClientExtensions, extType))
throw new TlsFatalAlert(AlertDescription.unsupported_extension);
/*
* RFC 3546 2.3. If [...] the older session is resumed, then the server MUST ignore
* extensions appearing in the client hello, and Send a server hello containing no
* extensions[.]
*/
if (this.mResumedSession)
{
// TODO[compat-gnutls] GnuTLS test server Sends server extensions e.g. ec_point_formats
// TODO[compat-openssl] OpenSSL test server Sends server extensions e.g. ec_point_formats
// TODO[compat-polarssl] PolarSSL test server Sends server extensions e.g. ec_point_formats
// throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
}
}
/*
* RFC 5746 3.4. Client Behavior: Initial Handshake
*/
{
/*
* When a ServerHello is received, the client MUST check if it includes the
* "renegotiation_info" extension:
*/
byte[] renegExtData = TlsUtilities.GetExtensionData(this.mServerExtensions, ExtensionType.renegotiation_info);
if (renegExtData != null)
{
/*
* If the extension is present, set the secure_renegotiation flag to TRUE. The
* client MUST then verify that the length of the "renegotiated_connection"
* field is zero, and if it is not, MUST abort the handshake (by Sending a fatal
* handshake_failure alert).
*/
this.mSecureRenegotiation = true;
if (!Arrays.ConstantTimeAreEqual(renegExtData, CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
throw new TlsFatalAlert(AlertDescription.handshake_failure);
}
}
// TODO[compat-gnutls] GnuTLS test server fails to Send renegotiation_info extension when resuming
this.mTlsClient.NotifySecureRenegotiation(this.mSecureRenegotiation);
IDictionary sessionClientExtensions = mClientExtensions, sessionServerExtensions = mServerExtensions;
if (this.mResumedSession)
{
if (selectedCipherSuite != this.mSessionParameters.CipherSuite
|| selectedCompressionMethod != this.mSessionParameters.CompressionAlgorithm)
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
sessionClientExtensions = null;
sessionServerExtensions = this.mSessionParameters.ReadServerExtensions();
}
this.mSecurityParameters.cipherSuite = selectedCipherSuite;
this.mSecurityParameters.compressionAlgorithm = selectedCompressionMethod;
if (sessionServerExtensions != null)
{
{
/*
* RFC 7366 3. If a server receives an encrypt-then-MAC request extension from a client
* and then selects a stream or Authenticated Encryption with Associated Data (AEAD)
* ciphersuite, it MUST NOT send an encrypt-then-MAC response extension back to the
* client.
*/
bool serverSentEncryptThenMAC = TlsExtensionsUtilities.HasEncryptThenMacExtension(sessionServerExtensions);
if (serverSentEncryptThenMAC && !TlsUtilities.IsBlockCipherSuite(selectedCipherSuite))
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
this.mSecurityParameters.encryptThenMac = serverSentEncryptThenMAC;
}
this.mSecurityParameters.extendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(sessionServerExtensions);
this.mSecurityParameters.maxFragmentLength = ProcessMaxFragmentLengthExtension(sessionClientExtensions,
sessionServerExtensions, AlertDescription.illegal_parameter);
this.mSecurityParameters.truncatedHMac = TlsExtensionsUtilities.HasTruncatedHMacExtension(sessionServerExtensions);
/*
* TODO It's surprising that there's no provision to allow a 'fresh' CertificateStatus to be sent in
* a session resumption handshake.
*/
this.mAllowCertificateStatus = !this.mResumedSession
&& TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions, ExtensionType.status_request,
AlertDescription.illegal_parameter);
this.mExpectSessionTicket = !this.mResumedSession
&& TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions, ExtensionType.session_ticket,
AlertDescription.illegal_parameter);
}
/*
* TODO[session-hash]
*
* draft-ietf-tls-session-hash-04 4. Clients and servers SHOULD NOT accept handshakes
* that do not use the extended master secret [..]. (and see 5.2, 5.3)
*/
if (sessionClientExtensions != null)
{
this.mTlsClient.ProcessServerExtensions(sessionServerExtensions);
}
this.mSecurityParameters.prfAlgorithm = GetPrfAlgorithm(Context, this.mSecurityParameters.CipherSuite);
/*
* RFC 5264 7.4.9. Any cipher suite which does not explicitly specify
* verify_data_length has a verify_data_length equal to 12. This includes all
* existing cipher suites.
*/
this.mSecurityParameters.verifyDataLength = 12;
}
protected virtual void SendCertificateVerifyMessage(DigitallySigned certificateVerify)
{
HandshakeMessage message = new HandshakeMessage(HandshakeType.certificate_verify);
certificateVerify.Encode(message);
message.WriteToRecordStream(this);
}
protected virtual void SendClientHelloMessage()
{
this.mRecordStream.SetWriteVersion(this.mTlsClient.ClientHelloRecordLayerVersion);
ProtocolVersion client_version = this.mTlsClient.ClientVersion;
if (client_version.IsDtls)
throw new TlsFatalAlert(AlertDescription.internal_error);
ContextAdmin.SetClientVersion(client_version);
/*
* TODO RFC 5077 3.4. When presenting a ticket, the client MAY generate and include a
* Session ID in the TLS ClientHello.
*/
byte[] session_id = TlsUtilities.EmptyBytes;
if (this.mTlsSession != null)
{
session_id = this.mTlsSession.SessionID;
if (session_id == null || session_id.Length > 32)
{
session_id = TlsUtilities.EmptyBytes;
}
}
bool fallback = this.mTlsClient.IsFallback;
this.mOfferedCipherSuites = this.mTlsClient.GetCipherSuites();
this.mOfferedCompressionMethods = this.mTlsClient.GetCompressionMethods();
if (session_id.Length > 0 && this.mSessionParameters != null)
{
if (!Arrays.Contains(this.mOfferedCipherSuites, mSessionParameters.CipherSuite)
|| !Arrays.Contains(this.mOfferedCompressionMethods, mSessionParameters.CompressionAlgorithm))
{
session_id = TlsUtilities.EmptyBytes;
}
}
this.mClientExtensions = this.mTlsClient.GetClientExtensions();
HandshakeMessage message = new HandshakeMessage(HandshakeType.client_hello);
TlsUtilities.WriteVersion(client_version, message);
message.Write(this.mSecurityParameters.ClientRandom);
TlsUtilities.WriteOpaque8(session_id, message);
// Cipher Suites (and SCSV)
{
/*
* RFC 5746 3.4. The client MUST include either an empty "renegotiation_info" extension,
* or the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite value in the
* ClientHello. Including both is NOT RECOMMENDED.
*/
byte[] renegExtData = TlsUtilities.GetExtensionData(mClientExtensions, ExtensionType.renegotiation_info);
bool noRenegExt = (null == renegExtData);
bool noRenegScsv = !Arrays.Contains(mOfferedCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
if (noRenegExt && noRenegScsv)
{
// TODO Consider whether to default to a client extension instead
// this.mClientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(this.mClientExtensions);
// this.mClientExtensions[ExtensionType.renegotiation_info] = CreateRenegotiationInfo(TlsUtilities.EmptyBytes);
this.mOfferedCipherSuites = Arrays.Append(mOfferedCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
}
/*
* draft-ietf-tls-downgrade-scsv-00 4. If a client sends a ClientHello.client_version
* containing a lower value than the latest (highest-valued) version supported by the
* client, it SHOULD include the TLS_FALLBACK_SCSV cipher suite value in
* ClientHello.cipher_suites.
*/
if (fallback && !Arrays.Contains(mOfferedCipherSuites, CipherSuite.TLS_FALLBACK_SCSV))
{
this.mOfferedCipherSuites = Arrays.Append(mOfferedCipherSuites, CipherSuite.TLS_FALLBACK_SCSV);
}
TlsUtilities.WriteUint16ArrayWithUint16Length(mOfferedCipherSuites, message);
}
TlsUtilities.WriteUint8ArrayWithUint8Length(mOfferedCompressionMethods, message);
if (mClientExtensions != null)
{
WriteExtensions(message, mClientExtensions);
}
message.WriteToRecordStream(this);
}
protected virtual void SendClientKeyExchangeMessage()
{
HandshakeMessage message = new HandshakeMessage(HandshakeType.client_key_exchange);
this.mKeyExchange.GenerateClientKeyExchange(message);
message.WriteToRecordStream(this);
}
}
}
#endif
| |
//=============================================================================
// System : Sandcastle Help File Builder Components
// File : PostTransformComponent.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 06/28/2010
// Note : Copyright 2006-2010, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a build component that is a companion to the
// CodeBlockComponent. It is used to add the stylesheet and JavaScript
// links to the rendered HTML if the topic contains colorized code. In
// addition, it can insert a logo image at the top of each help topic and,
// for the Prototype presentation style, hide the language combo box if only
// one language appears in the Syntax section. With a modification to the
// Sandcastle reference content files, it will also add version information
// to each topic.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.3.3.0 11/23/2006 EFW Created the code
// 1.4.0.0 01/31/2007 EFW Added placement options for logo. Made changes
// to support custom presentation styles. Reworked
// version info code to improve performance when used
// with very large documentation builds.
// 1.5.0.0 06/19/2007 EFW Various additions and updates for the June CTP
// 1.6.0.1 10/30/2007 EFW Fixed the logo placement for the VS2005 style
// 1.6.0.3 06/20/2007 EFW Fixed bug that caused code blocks with an unknown
// or unspecified language to always be hidden.
// 1.6.0.7 03/24/2008 EFW Updated to handle multiple assembly versions.
// Updated to support use in conceptual builds.
// 1.7.0.0 06/01/2008 EFW Removed language filter support for Hana and
// Prototype due to changes in the way the
// transformations implement it.
// 1.9.0.0 06/06/2010 EFW Replaced outputPath element with an outputPaths
// element that supports multiple help file format
// output locations.
//=============================================================================
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using Microsoft.Ddue.Tools;
namespace SandcastleBuilder.Components
{
/// <summary>
/// This build component is a companion to the
/// <see cref="CodeBlockComponent"/>. It is used to add the
/// stylesheet and JavaScript links to the rendered HTML if the topic
/// contains colorized code. In addition, it can insert a logo image at
/// the top of each help topic and, for the Prototype presentation style,
/// hide the language combo box if only one language appears in the Syntax
/// section. With a modification to the Sandcastle reference content
/// files, it will also add version information to each topic.
/// </summary>
/// <remarks>The colorizer files are only copied once and only if code is
/// actually colorized. If the files already exist (i.e. additional
/// content has replaced them), they are not copied either. That way, you
/// can customize the color stylesheet as you see fit without modifying the
/// default stylesheet.
///
/// <p/>By adding "Version: {2}" to the <b>locationInformation</b> entry
/// and the <b>assemblyNameAndModule</b> entry in the
/// <b>reference_content.xml</b> file in the Prototype, VS2005, and Hana
/// style content files, you can add version information to each topic.
/// The help file builder uses a composite file with this fix already in
/// place.</remarks>
/// <example>
/// <code lang="xml" title="Example configuration">
/// <!-- Post-transform component configuration. This must
/// appear after the TransformComponent. See also:
/// CodeBlockComponent. -->
/// <component type="SandcastleBuilder.Components.PostTransformComponent"
/// assembly="C:\SandcastleComponents\SandcastleBuilder.Components.dll" >
/// <!-- Code colorizer files (required).
/// Attributes:
/// Stylesheet file (required)
/// Script file (required)
/// "Copy" image file (required) -->
/// <colorizer stylesheet="highlight.css" scriptFile="highlight.js"
/// copyImage="CopyCode.gif" />
///
/// <!-- Base output paths for the files (required). These should
/// match the parent folder of the output path of the HTML files
/// (see each of the SaveComponent instances below). -->
/// <outputPaths>
/// <path value="Output\HtmlHelp1\" />
/// <path value="Output\MSHelp2\" />
/// <path value="Output\MSHelpViewer\" />
/// <path value="Output\Website\" />
/// </outputPaths>
///
/// <!-- Logo image file (optional). Filename is required. The
/// height, width, altText, placement, and alignment attributes
/// are optional. -->
/// <logoFile filename="Logo.jpg" height="64" width="64"
/// altText="Test Logo" placement="left" alignment="left" />
/// </component>
/// </code>
/// </example>
public class PostTransformComponent : BuildComponent
{
#region Logo placement enumerations
//=====================================================================
/// <summary>
/// This enumeration defines the logo placement options
/// </summary>
public enum LogoPlacement
{
/// <summary>Place the logo to the left of the header text
/// (the default).</summary>
Left,
/// <summary>Place the logo to the right of the header text.</summary>
Right,
/// <summary>Place the logo above the header text.</summary>
Above
}
/// <summary>
/// This enumeration defines the logo alignment options when placement
/// is set to <b>Above</b>.
/// </summary>
public enum LogoAlignment
{
/// <summary>Left-align the logo (the default).</summary>
Left,
/// <summary>Right-align the logo.</summary>
Right,
/// <summary>Center the logo.</summary>
Center
}
#endregion
#region Private data members
//=====================================================================
// Script modification flag
// private static bool scriptsModified;
// Output folder paths
private List<string> outputPaths;
// The stylesheet, script, and image files to include and the output path
private string stylesheet, scriptFile, copyImage, copyImage_h;
private bool colorizerFilesCopied, logoFileCopied;
// Logo properties
private string logoFilename, logoAltText, alignment;
private int logoHeight, logoWidth;
private LogoPlacement placement;
#endregion
#region Constructor
//=====================================================================
/// <summary>
/// Constructor
/// </summary>
/// <param name="assembler">A reference to the build assembler.</param>
/// <param name="configuration">The configuration information</param>
/// <exception cref="ConfigurationErrorsException">This is thrown if
/// an error is detected in the configuration.</exception>
public PostTransformComponent(BuildAssembler assembler,
XPathNavigator configuration) : base(assembler, configuration)
{
XPathNavigator nav;
string attr;
int pos;
Assembly asm = Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);
base.WriteMessage(MessageLevel.Info, String.Format(CultureInfo.InvariantCulture,
"\r\n [{0}, version {1}]\r\n Post-Transform Component. " +
"{2}\r\n http://SHFB.CodePlex.com", fvi.ProductName,
fvi.ProductVersion, fvi.LegalCopyright));
outputPaths = new List<string>();
// The <colorizer> element is required and defines the colorizer
// file locations.
nav = configuration.SelectSingleNode("colorizer");
if(nav == null)
throw new ConfigurationErrorsException("You must specify " +
"a <colorizer> element to define the code colorizer " +
"files.");
// All of the attributes are required
stylesheet = nav.GetAttribute("stylesheet", String.Empty);
scriptFile = nav.GetAttribute("scriptFile", String.Empty);
copyImage = nav.GetAttribute("copyImage", String.Empty);
if(String.IsNullOrEmpty(stylesheet))
throw new ConfigurationErrorsException("You must specify a " +
"'stylesheet' attribute on the <colorizer> element");
if(String.IsNullOrEmpty(scriptFile))
throw new ConfigurationErrorsException("You must specify a " +
"'scriptFile' attribute on the <colorizer> element");
if(String.IsNullOrEmpty(copyImage))
throw new ConfigurationErrorsException("You must specify a " +
"'copyImage' attribute on the <colorizer> element");
// This element is obsolete, if found, tell the user to edit and save the configuration
nav = configuration.SelectSingleNode("outputPath");
if(nav != null)
throw new ConfigurationErrorsException("The PostTransformComponent configuration contains an " +
"obsolete <outputPath> element. Please edit the configuration to update it with the new " +
"<outputPaths> element.");
// Get the output paths
foreach(XPathNavigator path in configuration.Select("outputPaths/path"))
{
attr = path.GetAttribute("value", String.Empty);
if(attr[attr.Length - 1] != '\\')
attr += @"\";
if(!Directory.Exists(attr))
throw new ConfigurationErrorsException("The output path '" + attr + "' must exist");
outputPaths.Add(attr);
}
if(outputPaths.Count == 0)
throw new ConfigurationErrorsException("You must specify at least one <path> element in the " +
"<outputPaths> element");
// All present. Make sure they exist.
stylesheet = Path.GetFullPath(stylesheet);
scriptFile = Path.GetFullPath(scriptFile);
copyImage = Path.GetFullPath(copyImage);
// The highlight image will have the same name but with an "_h"
// suffix. If it doesn't exist, the copy image will be used.
pos = copyImage.LastIndexOf('.');
if(pos == -1)
copyImage_h = copyImage + "_h";
else
copyImage_h = copyImage.Substring(0, pos) + "_h" +
copyImage.Substring(pos);
if(!File.Exists(stylesheet))
throw new ConfigurationErrorsException("Could not find stylesheet file: " + stylesheet);
if(!File.Exists(stylesheet))
throw new ConfigurationErrorsException("Could not find script file: " + scriptFile);
if(!File.Exists(copyImage))
throw new ConfigurationErrorsException("Could not find image file: " + copyImage);
// The logo element is optional. The file must exist if specified.
nav = configuration.SelectSingleNode("logoFile");
if(nav != null)
{
logoFilename = nav.GetAttribute("filename", String.Empty);
if(!String.IsNullOrEmpty(logoFilename))
{
if(!File.Exists(logoFilename))
throw new ConfigurationErrorsException("The logo file '" + logoFilename + "' must exist");
logoAltText = nav.GetAttribute("altText", String.Empty);
attr = nav.GetAttribute("height", String.Empty);
if(!String.IsNullOrEmpty(attr))
if(!Int32.TryParse(attr, out logoHeight))
throw new ConfigurationErrorsException("The logo height must be an integer value");
attr = nav.GetAttribute("width", String.Empty);
if(!String.IsNullOrEmpty(attr))
if(!Int32.TryParse(attr, out logoWidth))
throw new ConfigurationErrorsException("The logo width must be an integer value");
// Ignore them if negative
if(logoHeight < 0)
logoHeight = 0;
if(logoWidth < 0)
logoWidth = 0;
// Placement and alignment are optional
attr = nav.GetAttribute("placement", String.Empty);
if(!String.IsNullOrEmpty(attr))
placement = (LogoPlacement)Enum.Parse(typeof(LogoPlacement), attr, true);
else
placement = LogoPlacement.Left;
attr = nav.GetAttribute("alignment", String.Empty);
if(!String.IsNullOrEmpty(attr))
alignment = attr;
else
alignment = "left";
}
}
}
#endregion
#region Apply the component
//=====================================================================
/// <summary>
/// This is implemented to perform the post-transformation tasks.
/// </summary>
/// <param name="document">The XML document with which to work.</param>
/// <param name="key">The key (member name) of the item being
/// documented.</param>
public override void Apply(XmlDocument document, string key)
{
XmlNode head, node, codePreTag, parent, codeBlock;
XmlAttribute attr;
string destStylesheet, destScriptFile, destImageFile;
int pos;
// Add the version information if possible
if(VersionInfoComponent.ItemVersions.Count != 0)
PostTransformComponent.AddVersionInfo(document);
// For the Prototype style, hide the dropdown if there's only
// one language. VS2005 and Hana ignore the language settings
// and show everything in the dropdown. We could fix that to but
// it will require a bit more work. Maybe later...
node = document.SelectSingleNode("//select[@id='languageSelector']");
if(node != null && node.SelectNodes("option").Count == 1)
{
attr = document.CreateAttribute("style");
attr.Value = "visibility: hidden;";
node.Attributes.Append(attr);
}
// Add the logo?
if(!String.IsNullOrEmpty(logoFilename))
this.AddLogo(document);
// Don't bother with the rest if the topic contains no code that
// needs the files.
if(CodeBlockComponent.ColorizedCodeBlocks.Count == 0)
return;
// Only copy the files if needed
if(!colorizerFilesCopied)
{
foreach(string outputPath in outputPaths)
{
destStylesheet = outputPath + @"styles\" + Path.GetFileName(stylesheet);
destScriptFile = outputPath + @"scripts\" + Path.GetFileName(scriptFile);
destImageFile = outputPath + @"icons\" + Path.GetFileName(CodeBlockComponent.CopyImageLocation);
if(!Directory.Exists(outputPath + @"styles"))
Directory.CreateDirectory(outputPath + @"styles");
if(!Directory.Exists(outputPath + @"scripts"))
Directory.CreateDirectory(outputPath + @"scripts");
if(!Directory.Exists(outputPath + @"icons"))
Directory.CreateDirectory(outputPath + @"icons");
// All attributes are turned off so that we can delete it later
if(!File.Exists(destStylesheet))
{
File.Copy(stylesheet, destStylesheet);
File.SetAttributes(destStylesheet, FileAttributes.Normal);
}
if(!File.Exists(destScriptFile))
{
File.Copy(scriptFile, destScriptFile);
File.SetAttributes(destScriptFile, FileAttributes.Normal);
}
// Always copy the image files, they may be different. Also, delete the
// destination file first if it exists as the filename casing may be different.
if(File.Exists(destImageFile))
{
File.SetAttributes(destImageFile, FileAttributes.Normal);
File.Delete(destImageFile);
}
File.Copy(copyImage, destImageFile);
File.SetAttributes(destImageFile, FileAttributes.Normal);
if(!File.Exists(copyImage_h))
copyImage_h = copyImage;
pos = destImageFile.LastIndexOf('.');
if(pos == -1)
destImageFile += "_h";
else
destImageFile = destImageFile.Substring(0, pos) + "_h" + destImageFile.Substring(pos);
if(File.Exists(destImageFile))
{
File.SetAttributes(destImageFile, FileAttributes.Normal);
File.Delete(destImageFile);
}
File.Copy(copyImage_h, destImageFile);
File.SetAttributes(destImageFile, FileAttributes.Normal);
}
colorizerFilesCopied = true;
}
// Find the <head> section
head = document.SelectSingleNode("html/head");
if(head == null)
{
base.WriteMessage(MessageLevel.Error,
"<head> section not found! Could not insert links.");
return;
}
// Add the link to the stylesheet
node = document.CreateNode(XmlNodeType.Element, "link", null);
attr = document.CreateAttribute("type");
attr.Value = "text/css";
node.Attributes.Append(attr);
attr = document.CreateAttribute("rel");
attr.Value = "stylesheet";
node.Attributes.Append(attr);
node.InnerXml = String.Format(CultureInfo.InvariantCulture,
"<includeAttribute name='href' item='stylePath'><parameter>{0}</parameter></includeAttribute>",
Path.GetFileName(stylesheet));
head.AppendChild(node);
// Add the link to the script
node = document.CreateNode(XmlNodeType.Element, "script", null);
attr = document.CreateAttribute("type");
attr.Value = "text/javascript";
node.Attributes.Append(attr);
// Script tags cannot be self-closing so set their inner text
// to a space so that they render as an opening and a closing tag.
node.InnerXml = String.Format(CultureInfo.InvariantCulture,
" <includeAttribute name='src' item='scriptPath'><parameter>{0}</parameter></includeAttribute>",
Path.GetFileName(scriptFile));
head.AppendChild(node);
// Strip out the Copy Code header and its related table used in the
// VS2005 and Hana styles. It doesn't work with the
// CodeBlockComponent code blocks.
XmlNodeList codeSpans = document.SelectNodes("//span[@class='copyCode']");
// Handle the Prototype style
if(codeSpans.Count == 0)
codeSpans = document.SelectNodes("//div[@class='code']");
foreach(XmlNode copyCode in codeSpans)
{
// Hana/VS2005
if(copyCode.Name == "span")
{
node = copyCode.ParentNode.ParentNode;
codePreTag = node.SelectSingleNode("following-sibling::*//pre");
//codePreTag = node.NextSibling.ChildNodes[0].ChildNodes[0];
// If it doesn't contain a marker, ignore it
if(codePreTag == null
|| !codePreTag.InnerXml.StartsWith("@@_SHFB_", StringComparison.Ordinal))
continue;
parent = node.ParentNode.ParentNode;
parent.RemoveChild(node.ParentNode);
parent.AppendChild(codePreTag);
}
else
{
// Sometimes we get an empty code div in the VS2005 style and it ends up here.
// If that happens, ignore it.
if(copyCode.ChildNodes.Count == 0)
continue;
// Prototype
parent = copyCode;
codePreTag = copyCode.ChildNodes[0];
// If it doesn't contain a marker, ignore it
if(!codePreTag.InnerXml.StartsWith("@@_SHFB_", StringComparison.Ordinal))
continue;
}
if(CodeBlockComponent.ColorizedCodeBlocks.TryGetValue(codePreTag.InnerXml, out codeBlock))
{
// VS2005 adds an extra span we can get rid of
if(parent.Name == "span")
{
parent.ParentNode.AppendChild(parent.ChildNodes[0]);
parent = parent.ParentNode;
parent.RemoveChild(parent.ChildNodes[0]);
}
// Replace the placeholder with the colorized code
codePreTag.ParentNode.ReplaceChild(codeBlock.ChildNodes[1], codePreTag);
// Replace the code div with the colorized code container
parent.ParentNode.ReplaceChild(codeBlock, parent);
// Add the code back to it
codeBlock.AppendChild(parent);
}
else
base.WriteMessage(MessageLevel.Warn, "Unable to locate colorized code for place holder: " +
codePreTag.InnerXml);
}
// Swap the literal "Copy" text with an include item so that it gets localized
codeSpans = document.SelectNodes("//span[@class='highlight-copycode']");
foreach(XmlNode span in codeSpans)
{
// Find the "Copy" image element and replace its "src" attribute with an include
// item that picks up the correct path. It is different for MS Help Viewer.
var copyImage = span.SelectSingleNode("img");
if(copyImage != null)
{
copyImage.Attributes.Remove(copyImage.Attributes["src"]);
copyImage.InnerXml = String.Format(CultureInfo.InvariantCulture,
"<includeAttribute name='src' item='iconPath'><parameter>{0}</parameter>" +
"</includeAttribute>", Path.GetFileName(CodeBlockComponent.CopyImageLocation));
}
span.InnerXml = span.InnerXml.Replace(" " + CodeBlockComponent.CopyText,
" <include item=\"copyCode\"/>");
}
/* 1.7.0.0 - Removed - See below.
// If there are code blocks associated with the Prototype or
// Hana style, connect them to the language filter.
codeSpans = document.SelectNodes("//span[starts-with(@id, 'cbc_')]");
if(codeSpans.Count != 0)
if(!PostTransformComponent.ConnectLanguageFilter(document,
codeSpans, outputPath))
base.WriteMessage(MessageLevel.Warn, "A required section " +
"was not found and language filtering will not work.");
*/
}
#endregion
#region Helper methods
//=====================================================================
/// <summary>
/// This is used to add version information to the topic
/// </summary>
/// <param name="document">The document to modify</param>
/// <remarks>This requires a modification to the Sandcastle
/// presentation style file reference_content.xml (all styles).
/// The help file builder uses a composite file for them and it
/// includes the fix. This can go away once version information
/// is supported by Sandcastle itself. The request has been
/// made.</remarks>
private static void AddVersionInfo(XmlDocument document)
{
XmlNodeList locationInfo;
XmlNode parameter, footer;
int idx = 0;
// Prototype style...
locationInfo = document.SelectNodes("//include[@item='locationInformation']");
// ... or VS2005/Hana style?
if(locationInfo.Count == 0)
locationInfo = document.SelectNodes("//include[@item='assemblyNameAndModule']");
else
{
// For prototype, move the version information below
// the footer.
footer = document.SelectSingleNode("//include[@item='footer']");
if(footer != null)
{
footer.ParentNode.RemoveChild(footer);
locationInfo[0].ParentNode.InsertBefore(footer, locationInfo[0]);
}
}
foreach(XmlNode location in locationInfo)
{
parameter = document.CreateNode(XmlNodeType.Element, "parameter", null);
if(idx < VersionInfoComponent.ItemVersions.Count)
parameter.InnerXml = VersionInfoComponent.ItemVersions[idx];
else
parameter.InnerXml = "?.?.?.?";
location.AppendChild(parameter);
idx++;
}
}
/// <summary>
/// This is called to add the logo to the page header area
/// </summary>
/// <param name="document">The document to which the logo is added.</param>
private void AddLogo(XmlDocument document)
{
XmlAttribute attr;
XmlNode div, divHeader, devLangsMenu, bottomTable,
memberOptionsMenu, memberFrameworksMenu, gradientTable;
string imgWidth, imgHeight, imgAltText, filename, destFile;
filename = Path.GetFileName(logoFilename);
if(!logoFileCopied)
{
foreach(string outputPath in outputPaths)
{
destFile = outputPath + @"icons\" + filename;
// Copy the logo to the icons folder if not there already.
// All attributes are turned off so that we can delete it later.
if(!File.Exists(destFile))
{
if(!Directory.Exists(outputPath + @"icons"))
Directory.CreateDirectory(outputPath + @"icons");
File.Copy(logoFilename, destFile);
File.SetAttributes(destFile, FileAttributes.Normal);
}
}
logoFileCopied = true;
}
imgAltText = (String.IsNullOrEmpty(logoAltText)) ? String.Empty : " alt='" + logoAltText + "'";
imgWidth = (logoWidth == 0) ? String.Empty : " width='" +
logoWidth.ToString(CultureInfo.InvariantCulture) + "'";
imgHeight = (logoHeight == 0) ? String.Empty : " height='" +
logoHeight.ToString(CultureInfo.InvariantCulture) + "'";
div = document.SelectSingleNode("//div[@id='control']");
// Prototype style?
if(div != null)
{
// Wrap the header <div> in a table with the image based on
// the placement option.
switch(placement)
{
case LogoPlacement.Left:
div.InnerXml = String.Format(CultureInfo.InvariantCulture,
"<table border='0' width='100%' cellpadding='0' " +
"cellspacing='0'><tr><td align='center' " +
"style='padding-right: 10px'><img {0}{1}{2}><includeAttribute name='src' " +
"item='iconPath'><parameter>{3}</parameter></includeAttribute></img></td>" +
"<td valign='top' width='100%'>{4}</td></tr></table>", imgAltText, imgWidth,
imgHeight, filename, div.InnerXml);
break;
case LogoPlacement.Right:
div.InnerXml = String.Format(CultureInfo.InvariantCulture,
"<table border='0' width='100%' cellpadding='0' " +
"cellspacing='0'><tr><td valign='top' " +
"width='100%'>{0}</td><td align='center' " +
"style='padding-left: 10px'><img {1}{2}{3}><includeAttribute name='src' " +
"item='iconPath'><parameter>{4}</parameter></includeAttribute></img>" +
"</td></tr></table>", div.InnerXml, imgAltText, imgWidth, imgHeight, filename);
break;
case LogoPlacement.Above:
div.InnerXml = String.Format(CultureInfo.InvariantCulture,
"<table border='0' width='100%' cellpadding='0' " +
"cellspacing='0'><tr><td align='{0}' " +
"style='padding-bottom: 5px'><img {1}{2}{3}><includeAttribute name='src' " +
"item='iconPath'><parameter>{4}</parameter></includeAttribute></img></td></tr>" +
"<tr><td valign='top' width='100%'>{5}</td></tr>" +
"</table>", alignment, imgAltText, imgWidth, imgHeight, filename, div.InnerXml);
break;
}
}
else
{
// VS2005/Hana style
div = document.SelectSingleNode("//table[@id='topTable']");
if(div == null)
{
base.WriteMessage(MessageLevel.Error, "Unable to locate " +
"'control' <div> or 'topTable' <table> to insert logo.");
return;
}
switch(placement)
{
case LogoPlacement.Left:
// Hana style?
if(div.ChildNodes.Count != 1)
{
// Insert a new row with a cell spanning all rows
div.InnerXml = String.Format(CultureInfo.InvariantCulture,
"<tr><td rowspan='4' align='center' style='width: 1px; padding: 0px'>" +
"<img {0}{1}{2}><includeAttribute name='src' item='iconPath'>" +
"<parameter>{3}</parameter></includeAttribute></img></td></tr>{4}",
imgAltText, imgWidth, imgHeight, filename, div.InnerXml);
attr = document.CreateAttribute("colspan");
attr.Value = "2";
div.ChildNodes[4].ChildNodes[0].Attributes.Append(attr);
}
else
{
// VS2005 style. Wrap the top table, dev lang
// menu and bottom table in a new table with a
// new cell on the left containing the logo.
divHeader = div.ParentNode;
devLangsMenu = div.NextSibling;
bottomTable = devLangsMenu.NextSibling;
memberOptionsMenu = memberFrameworksMenu = null;
if(bottomTable.Attributes["id"].Value == "memberOptionsMenu")
{
memberOptionsMenu = bottomTable;
bottomTable = bottomTable.NextSibling;
if(bottomTable.Attributes["id"].Value == "memberFrameworksMenu")
{
memberFrameworksMenu = bottomTable;
bottomTable = bottomTable.NextSibling;
}
}
gradientTable = bottomTable.NextSibling;
divHeader.InnerXml = String.Format(CultureInfo.InvariantCulture,
"<table cellspacing='0' cellpadding='0'><tr>" +
"<td align='center' style='width: 1px; padding: 0px'>" +
"<img {0}{1}{2}><includeAttribute name='src' item='iconPath'>" +
"<parameter>{3}</parameter></includeAttribute></img></td>" +
"<td>{4}{5}{6}{7}{8}</td></tr></table>{9}", imgAltText, imgWidth, imgHeight,
filename, div.OuterXml, devLangsMenu.OuterXml,
(memberOptionsMenu == null) ? String.Empty : memberOptionsMenu.OuterXml,
(memberFrameworksMenu == null) ? String.Empty : memberFrameworksMenu.OuterXml,
bottomTable.OuterXml, gradientTable.OuterXml);
}
break;
case LogoPlacement.Right:
// Hana style?
if(div.ChildNodes.Count != 1)
{
// For this, we add a second cell to the first row that spans three rows
div = div.ChildNodes[0];
div.InnerXml += String.Format(CultureInfo.InvariantCulture,
"<td rowspan='3' align='center' style='width: 1px; padding: 0px'>" +
"<img {0}{1}{2}><includeAttribute name='src' item='iconPath'>" +
"<parameter>{3}</parameter></includeAttribute></img></td>",
imgAltText, imgWidth, imgHeight, filename);
// For Hana, we need to add a colspan attribute to the last row
div = div.ParentNode;
attr = document.CreateAttribute("colspan");
attr.Value = "2";
div.ChildNodes[3].ChildNodes[0].Attributes.Append(attr);
}
else
{
// VS2005 style. Wrap the top table, dev lang
// menu and bottom table in a new table with a
// new cell on the right containing the logo.
divHeader = div.ParentNode;
devLangsMenu = div.NextSibling;
bottomTable = devLangsMenu.NextSibling;
memberOptionsMenu = memberFrameworksMenu = null;
if(bottomTable.Attributes["id"].Value == "memberOptionsMenu")
{
memberOptionsMenu = bottomTable;
bottomTable = bottomTable.NextSibling;
if(bottomTable.Attributes["id"].Value == "memberFrameworksMenu")
{
memberFrameworksMenu = bottomTable;
bottomTable = bottomTable.NextSibling;
}
}
gradientTable = bottomTable.NextSibling;
divHeader.InnerXml = String.Format(CultureInfo.InvariantCulture,
"<table cellspacing='0' cellpadding='0'><tr><td>{4}{5}{6}{7}{8}</td>" +
"<td align='center' style='width: 1px; padding: 0px'>" +
"<img {0}{1}{2}><includeAttribute name='src' item='iconPath'>" +
"<parameter>{3}</parameter></includeAttribute></img></td></tr></table>{9}",
imgAltText, imgWidth, imgHeight, filename, div.OuterXml, devLangsMenu.OuterXml,
(memberOptionsMenu == null) ? String.Empty : memberOptionsMenu.OuterXml,
(memberFrameworksMenu == null) ? String.Empty : memberFrameworksMenu.OuterXml,
bottomTable.OuterXml, gradientTable.OuterXml);
}
break;
case LogoPlacement.Above:
// Add a new first row
div.InnerXml = String.Format(CultureInfo.InvariantCulture,
"<tr><td align='{0}'><img {1}{2}{3}><includeAttribute name='src' " +
"item='iconPath'><parameter>{4}</parameter></includeAttribute></img></td></tr>{5}",
alignment, imgAltText, imgWidth, imgHeight, filename, div.InnerXml);
break;
}
}
}
/* 1.7.0.0 - Removed due to changes in the way the Hana and Prototype
* transformations implement the language filter. Unfortunately, it is no
* longer a simple matter of registering IDs and hacking a script. As such,
* support has been removed and a work item opened in the Sandcastle Styles
* project to see about adding support for it at a later date.
*
* http://www.codeplex.com/SandcastleStyles/WorkItem/View.aspx?WorkItemId=5091
*
/// <summary>
/// This is used to connect the code blocks in the Prototype and Hana
/// style to the language filter.
/// </summary>
/// <param name="document">The document</param>
/// <param name="codeSpans">The list of spans associated with code
/// blocks that need hooking up to the language filter</param>
/// <param name="outputPath">The output path where the scripts can
/// be found. The Hana style requires a couple of modifications.</param>
/// <returns>Returns true if successful or false on failure</returns>
private static bool ConnectLanguageFilter(XmlDocument document,
XmlNodeList codeSpans, string outputPath)
{
StringBuilder sb;
List<string> idList;
XmlAttribute lang;
XmlNode script, body;
string setState;
// Track the IDs. The Prototype style needs to register them.
idList = new List<string>();
foreach(XmlNode span in codeSpans)
idList.Add(span.Attributes["id"].Value);
script = document.SelectSingleNode("//script[contains(text(), " +
"'var sb = ')]");
// Prototype style?
if(script != null)
{
// Add the JavaScript to register the IDs and refresh the
// currently displayed elements.
sb = new StringBuilder(1024);
foreach(string idTitle in idList)
sb.AppendFormat("sb.elements.push(document.getElementById(" +
"'{0}'));\r\n", idTitle);
// Add the code to update the current filter after adding
// all of our elements.
string[] lines = script.InnerText.Split('\n');
for(int idx = lines.Length - 1; idx > 0; idx--)
if(lines[idx].IndexOf("sb.toggleStyle") != -1)
{
sb.Append(lines[idx]);
sb.Append('\n');
break;
}
script = document.CreateNode(XmlNodeType.Element, "script", null);
lang = document.CreateAttribute("type");
lang.Value = "text/javascript";
script.Attributes.Append(lang);
script.InnerText = sb.ToString();
body = document.SelectSingleNode("html/body");
if(body == null)
return false;
body.AppendChild(script);
}
else
{
script = document.SelectSingleNode("//script[contains(" +
"text(), 'curvedToggleClass')]");
// Hana style? If not, we're done as the VS2005 style takes
// care of everything automatically.
if(script != null)
{
// The script block contains another call to this method
// with the same two first parameters. We'll borrow them
// to also hook up the example section DIV.
script.InnerText += "languageFilter.registerTabbedArea(" +
"'curvedSyntaxTabs', 'syntaxTabs', " +
"'exampleSection');\r\n";
// We need to modify a couple of scripts for this style
if(!scriptsModified &&
!ModifyHanaScripts(outputPath + "scripts\\"))
return false;
// Find the default language filter. We'll use the first
// one in the language filter code. This may not be C#
// if the user has disabled it.
script = document.SelectSingleNode("//div[contains(" +
"@onclick, 'changeLanguage(')]/@onclick");
if(script == null)
return false;
setState = script.Value.Replace("changeLanguage",
"selectAndSetLanguage");
script = document.SelectSingleNode("//script[contains(" +
"text(), 'languageFilter.select')]");
if(script == null)
return false;
script.InnerText = script.InnerText.Replace(
"languageFilter.select(data)", setState);
}
}
return true;
}
/// <summary>
/// This will modify a couple of the Hana style's scripts and add the
/// necessary script to the end of the page to set the initial code
/// block state.
/// </summary>
/// <param name="outputPath">The output path where the scripts can
/// be found.</param>
/// <returns></returns>
private static bool ModifyHanaScripts(string outputPath)
{
string content, commonUtils = outputPath + "CommonUtilities.js",
langFilter = outputPath + "LanguageFilter.js";
int pos;
scriptsModified = true;
if(!File.Exists(commonUtils) || !File.Exists(langFilter))
return false;
using(StreamReader sr = new StreamReader(commonUtils))
{
content = sr.ReadToEnd();
}
pos = content.IndexOf("var blockElement");
if(pos == -1)
return false;
// Insert an if() statement to ignore any text elements
// within an example block that appear before a code block.
if(content.IndexOf("// SHFB -") == -1)
{
content = content.Insert(pos, "// SHFB - Code Block " +
"Component adjustment\r\nif(typeof(blockNodes[blockCount]." +
"getAttribute) == \"undefined\") continue;\r\n\r\n");
// We also need an if() statement to ignore code blocks
// not connected to any language filter.
pos = content.IndexOf(';', content.IndexOf("var blockElement"));
if(pos == -1)
return false;
content = content.Insert(pos + 1, "\r\nif(blockElement == " +
"null) continue;\r\n");
using(StreamWriter sw = new StreamWriter(commonUtils))
{
sw.Write(content);
}
}
using(StreamReader sr = new StreamReader(langFilter))
{
content = sr.ReadToEnd();
}
// Add a new method to select the elements and set the
// initial state of the language filter.
if(content.IndexOf("// SHFB -") == -1)
{
content += @"
// SHFB - Code Block Component fix
Selector.prototype.selectAndSetLanguage = function(data, name, style)
{
var value = data.get('lang');
if(value == null)
{
this.changeLanguage(data, name, style);
return;
}
var names = value.split(' ');
var nodes = getChildNodes(this.id);
for( var i=0; i<nodes.length; i++)
{
if(nodes[i].getAttribute('id') == names[0])
{
styleSheetHandler(this.id, data, value, this.curvedTabCollections,
this.tabCollections, this.blockCollections);
codeBlockHandler(this.id, data, value, this.curvedTabCollections,
this.tabCollections, this.blockCollections);
languageHandler(this.id, data, value, this.curvedTabCollections,
this.tabCollections, this.blockCollections);
}
}
this.changeLanguage(data, names[0], names[1]);
}";
using(StreamWriter sw = new StreamWriter(langFilter))
{
sw.Write(content);
}
}
return true;
}
*/
#endregion
#region Static configuration method for use with SHFB
//=====================================================================
/// <summary>
/// This static method is used by the Sandcastle Help File Builder to
/// let the component perform its own configuration.
/// </summary>
/// <param name="currentConfig">The current configuration XML fragment</param>
/// <returns>A string containing the new configuration XML fragment</returns>
public static string ConfigureComponent(string currentConfig)
{
using(PostTransformConfigDlg dlg = new PostTransformConfigDlg(currentConfig))
{
if(dlg.ShowDialog() == DialogResult.OK)
currentConfig = dlg.Configuration;
}
return currentConfig;
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Globalization;
using NUnit.Framework.Constraints;
namespace NUnit.Framework.Internal
{
/// <summary>
/// TextMessageWriter writes constraint descriptions and messages
/// in displayable form as a text stream. It tailors the display
/// of individual message components to form the standard message
/// format of NUnit assertion failure messages.
/// </summary>
public class TextMessageWriter : MessageWriter
{
#region Message Formats and Constants
private static readonly int DEFAULT_LINE_LENGTH = 78;
// Prefixes used in all failure messages. All must be the same
// length, which is held in the PrefixLength field. Should not
// contain any tabs or newline characters.
/// <summary>
/// Prefix used for the expected value line of a message
/// </summary>
public static readonly string Pfx_Expected = " Expected: ";
/// <summary>
/// Prefix used for the actual value line of a message
/// </summary>
public static readonly string Pfx_Actual = " But was: ";
/// <summary>
/// Length of a message prefix
/// </summary>
public static readonly int PrefixLength = Pfx_Expected.Length;
#endregion
#region Instance Fields
private int maxLineLength = DEFAULT_LINE_LENGTH;
private bool _sameValDiffTypes = false;
private string _expectedType, _actualType;
#endregion
#region Constructors
/// <summary>
/// Construct a TextMessageWriter
/// </summary>
public TextMessageWriter() { }
/// <summary>
/// Construct a TextMessageWriter, specifying a user message
/// and optional formatting arguments.
/// </summary>
/// <param name="userMessage"></param>
/// <param name="args"></param>
public TextMessageWriter(string userMessage, params object[] args)
{
if ( userMessage != null && userMessage != string.Empty)
this.WriteMessageLine(userMessage, args);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the maximum line length for this writer
/// </summary>
public override int MaxLineLength
{
get { return maxLineLength; }
set { maxLineLength = value; }
}
#endregion
#region Public Methods - High Level
/// <summary>
/// Method to write single line message with optional args, usually
/// written to precede the general failure message, at a given
/// indentation level.
/// </summary>
/// <param name="level">The indentation level of the message</param>
/// <param name="message">The message to be written</param>
/// <param name="args">Any arguments used in formatting the message</param>
public override void WriteMessageLine(int level, string message, params object[] args)
{
if (message != null)
{
while (level-- >= 0) Write(" ");
if (args != null && args.Length > 0)
message = string.Format(message, args);
WriteLine(MsgUtils.EscapeNullCharacters(message));
}
}
/// <summary>
/// Display Expected and Actual lines for a constraint. This
/// is called by MessageWriter's default implementation of
/// WriteMessageTo and provides the generic two-line display.
/// </summary>
/// <param name="result">The result of the constraint that failed</param>
public override void DisplayDifferences(ConstraintResult result)
{
WriteExpectedLine(result);
WriteActualLine(result);
WriteAdditionalLine(result);
}
/// <summary>
/// Gets the unique type name between expected and actual.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value causing the failure</param>
/// <param name="expectedType">Output of the unique type name for expected</param>
/// <param name="actualType">Output of the unique type name for actual</param>
private void ResolveTypeNameDifference(object expected, object actual, out string expectedType, out string actualType) {
TypeNameDifferenceResolver resolver = new TypeNameDifferenceResolver();
resolver.ResolveTypeNameDifference(expected, actual, out expectedType, out actualType);
expectedType = $" ({expectedType})";
actualType = $" ({actualType})";
}
/// <summary>
/// Display Expected and Actual lines for given values. This
/// method may be called by constraints that need more control over
/// the display of actual and expected values than is provided
/// by the default implementation.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value causing the failure</param>
public override void DisplayDifferences(object expected, object actual)
{
DisplayDifferences(expected, actual,null);
}
/// <summary>
/// Display Expected and Actual lines for given values, including
/// a tolerance value on the expected line.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value causing the failure</param>
/// <param name="tolerance">The tolerance within which the test was made</param>
public override void DisplayDifferences(object expected, object actual, Tolerance tolerance)
{
if (expected != null && actual != null && expected.GetType() != actual.GetType() && MsgUtils.FormatValue(expected) == MsgUtils.FormatValue(actual))
{
_sameValDiffTypes = true;
ResolveTypeNameDifference(expected, actual, out _expectedType, out _actualType);
}
WriteExpectedLine(expected, tolerance);
WriteActualLine(actual);
}
/// <summary>
/// Display the expected and actual string values on separate lines.
/// If the mismatch parameter is >=0, an additional line is displayed
/// line containing a caret that points to the mismatch point.
/// </summary>
/// <param name="expected">The expected string value</param>
/// <param name="actual">The actual string value</param>
/// <param name="mismatch">The point at which the strings don't match or -1</param>
/// <param name="ignoreCase">If true, case is ignored in string comparisons</param>
/// <param name="clipping">If true, clip the strings to fit the max line length</param>
public override void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping)
{
// Maximum string we can display without truncating
int maxDisplayLength = MaxLineLength
- PrefixLength // Allow for prefix
- 2; // 2 quotation marks
if ( clipping )
MsgUtils.ClipExpectedAndActual(ref expected, ref actual, maxDisplayLength, mismatch);
expected = MsgUtils.EscapeControlChars(expected);
actual = MsgUtils.EscapeControlChars(actual);
// The mismatch position may have changed due to clipping or white space conversion
mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, ignoreCase);
Write( Pfx_Expected );
Write( MsgUtils.FormatValue(expected) );
if ( ignoreCase )
Write( ", ignoring case" );
WriteLine();
WriteActualLine( actual );
//DisplayDifferences(expected, actual);
if (mismatch >= 0)
WriteCaretLine(mismatch);
}
#endregion
#region Public Methods - Low Level
/// <summary>
/// Writes the text for an actual value.
/// </summary>
/// <param name="actual">The actual value.</param>
public override void WriteActualValue(object actual)
{
WriteValue(actual);
}
/// <summary>
/// Writes the text for a generalized value.
/// </summary>
/// <param name="val">The value.</param>
public override void WriteValue(object val)
{
Write(MsgUtils.FormatValue(val));
}
/// <summary>
/// Writes the text for a collection value,
/// starting at a particular point, to a max length
/// </summary>
/// <param name="collection">The collection containing elements to write.</param>
/// <param name="start">The starting point of the elements to write</param>
/// <param name="max">The maximum number of elements to write</param>
public override void WriteCollectionElements(IEnumerable collection, long start, int max)
{
Write(MsgUtils.FormatCollection(collection, start, max));
}
#endregion
#region Helper Methods
/// <summary>
/// Write the generic 'Expected' line for a constraint
/// </summary>
/// <param name="result">The constraint that failed</param>
private void WriteExpectedLine(ConstraintResult result)
{
Write(Pfx_Expected);
WriteLine(result.Description);
}
/// <summary>
/// Write the generic 'Expected' line for a given value
/// </summary>
/// <param name="expected">The expected value</param>
private void WriteExpectedLine(object expected)
{
WriteExpectedLine(expected, null);
}
/// <summary>
/// Write the generic 'Expected' line for a given value
/// and tolerance.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="tolerance">The tolerance within which the test was made</param>
private void WriteExpectedLine(object expected, Tolerance tolerance)
{
Write(Pfx_Expected);
Write(MsgUtils.FormatValue(expected));
if (_sameValDiffTypes) {
Write(_expectedType);
}
if (tolerance != null && !tolerance.IsUnsetOrDefault)
{
Write(" +/- ");
Write(MsgUtils.FormatValue(tolerance.Amount));
if (tolerance.Mode != ToleranceMode.Linear)
Write(" {0}", tolerance.Mode);
}
WriteLine();
}
/// <summary>
/// Write the generic 'Actual' line for a constraint
/// </summary>
/// <param name="result">The ConstraintResult for which the actual value is to be written</param>
private void WriteActualLine(ConstraintResult result)
{
Write(Pfx_Actual);
result.WriteActualValueTo(this);
WriteLine();
//WriteLine(MsgUtils.FormatValue(result.ActualValue));
}
private void WriteAdditionalLine(ConstraintResult result)
{
result.WriteAdditionalLinesTo(this);
}
/// <summary>
/// Write the generic 'Actual' line for a given value
/// </summary>
/// <param name="actual">The actual value causing a failure</param>
private void WriteActualLine(object actual)
{
Write(Pfx_Actual);
WriteActualValue(actual);
if (_sameValDiffTypes)
{
Write(_actualType);
}
WriteLine();
}
private void WriteCaretLine(int mismatch)
{
// We subtract 2 for the initial 2 blanks and add back 1 for the initial quote
WriteLine(" {0}^", new string('-', PrefixLength + mismatch - 2 + 1));
}
#endregion
}
}
| |
/*
* Magix - A Web Application Framework for Humans
* Copyright 2010 - 2014 - thomas@magixilluminate.com
* Magix is licensed as MITx11, see enclosed License.txt File for Details.
*/
using System;
using System.Web.UI;
using Magix.UX;
using Magix.UX.Widgets;
using Magix.UX.Effects;
using Magix.Core;
using System.Web;
using System.Configuration;
using System.Collections.Generic;
using System.Diagnostics;
using Magix.UX.Widgets.Core;
namespace Magix.Core
{
/*
* base class for viewports
*/
public abstract class Viewport : ActiveModule
{
/*
* override to return default container
*/
protected abstract string GetDefaultContainer();
/*
* override to return all containers, except the system containers
*/
protected abstract string[] GetAllDefaultContainers();
/*
* contains all css files
*/
private List<string> CssFiles
{
get
{
if (ViewState["CssFiles"] == null)
ViewState["CssFiles"] = new List<string>();
return ViewState["CssFiles"] as List<string>;
}
}
/*
* contains all javascript files
*/
private List<string> JavaScriptFiles
{
get
{
if (ViewState["JavaScriptFiles"] == null)
ViewState["JavaScriptFiles"] = new List<string>();
return ViewState["JavaScriptFiles"] as List<string>;
}
}
protected override void OnInit(EventArgs e)
{
Load +=
delegate
{
Page_Load_Initializing();
if (!Manager.Instance.IsAjaxCallback && IsPostBack)
{
IncludeAllCssFiles();
IncludeAllJsFiles();
}
};
base.OnInit(e);
Page_Init_Initializing();
}
private void Page_Init_Initializing()
{
Node node = new Node();
node["is-postback"].Value = IsPostBack;
ActiveEvents.Instance.RaiseActiveEvent(
this,
"magix.viewport.page-init",
node);
}
private void Page_Load_Initializing()
{
if (!IsPostBack)
{
// Checking to see if this is a remotely activated Active Event
// And if so, raising the "magix.viewport.remote-event" active event
if (!Manager.Instance.IsAjaxCallback &&
Request.HttpMethod == "POST" &&
!string.IsNullOrEmpty(Page.Request["event"]))
{
// We only raise events which are allowed to be remotely invoked
if (ActiveEvents.Instance.IsAllowedRemotely(Page.Request["event"]))
{
Node node = new Node();
if (!string.IsNullOrEmpty(Page.Request["params"]))
node[Page.Request["event"]].AddRange(Node.FromJSONString(Page.Request["params"]));
else
node[Page.Request["event"]].Value = null;
bool inspect = node[Page.Request["event"]].Contains("inspect");
Node exe = new Node();
exe["_ip"].Value = node;
exe["_dp"].Value = node;
RaiseActiveEvent(
"magix.execute",
exe);
if (inspect)
{
// removing all nodes from result, except inspect
Node inspectNode = node[Page.Request["event"]]["inspect"];
node[Page.Request["event"]].Clear();
node[Page.Request["event"]].Add(inspectNode);
}
Page.Response.Clear();
Page.Response.Write("return:" + node[Page.Request["event"]].ToJSONString());
try
{
Page.Response.End();
}
catch
{
; // Intentionally do nothing ...
}
}
}
else
{
RaiseActiveEvent("magix.viewport.page-load");
}
}
}
/*
* helper, re-includes all css files
*/
private void IncludeAllCssFiles()
{
foreach (string idx in CssFiles)
{
IncludeCssFile(idx);
}
}
/*
* helper, re-includes all javascript files
*/
private void IncludeAllJsFiles()
{
foreach (string idx in JavaScriptFiles)
{
IncludeJavaScriptFile(idx);
}
}
/*
* helper for clearing controls from container, such that it gets un-registered
*/
private void ClearControls(DynamicPanel dynamic)
{
foreach (Control idx in dynamic.Controls)
{
ActiveEvents.Instance.RemoveListener(idx);
}
dynamic.ClearControls();
}
/*
* changes the title of the web page
*/
[ActiveEvent(Name = "magix.viewport.lock-to-device-width")]
protected void magix_viewport_lock_to_device_width(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewport.lock-to-device-width-dox].value");
AppendCodeFromResource(
ip,
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewport.lock-to-device-width-sample]");
return;
}
LiteralControl lit = new LiteralControl();
lit.Text = @"
<meta name=""viewport"" content=""width=device-width, initial-scale=1.0"" />
";
Page.Header.Controls.Add(lit);
}
/*
* changes the title of the web page
*/
[ActiveEvent(Name = "magix.viewport.set-title")]
protected void magix_viewport_set_title(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewport.set-title-dox].value");
AppendCodeFromResource(
ip,
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewport.set-title-sample]");
return;
}
Node dp = Dp(e.Params);
if (!ip.ContainsValue("title"))
throw new ArgumentException("no [title] given to [magix.viewport.set-title]");
string title = Expressions.GetExpressionValue<string>(ip["title"].Get<string>(), dp, ip, false);
Page.Title = title;
}
/*
* clears the given container
*/
[ActiveEvent(Name = "magix.viewport.clear-controls")]
protected virtual void magix_viewport_clear_controls(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewport.clear-controls-dox].value");
AppendCodeFromResource(
ip,
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewport.clear-controls-sample]");
return;
}
Node dp = Dp(e.Params);
string container = Expressions.GetExpressionValue<string>(ip.GetValue("container", ""), dp, ip, false);
bool resetClass = ip.ContainsValue("reset-class") ?
Expressions.GetExpressionValue<bool>(ip["reset-class"].Get<string>(), dp, ip, false) :
false;
string resetClassNewClass = null;
if (ip.Contains("reset-class") && ip["reset-class"].Contains("new-class"))
resetClassNewClass = ip["reset-class"]["new-class"].Get<string>("");
if (ip.ContainsValue("all") && ip["all"].Get<bool>())
{
foreach (string idx in GetAllDefaultContainers())
{
DynamicPanel dyn = Selector.FindControl<DynamicPanel>(
this,
idx);
ClearControls(dyn);
if (resetClass || !string.IsNullOrEmpty(resetClassNewClass))
{
if (!string.IsNullOrEmpty(resetClassNewClass))
dyn.Class = resetClassNewClass;
else
dyn.Class = "";
}
}
}
else
{
DynamicPanel dyn = Selector.FindControl<DynamicPanel>(
this,
container);
if (dyn == null)
return;
ClearControls(dyn);
if (resetClass || !string.IsNullOrEmpty(resetClassNewClass))
{
if (!string.IsNullOrEmpty(resetClassNewClass))
dyn.Class = resetClassNewClass;
else
dyn.Class = "";
}
}
}
/*
* executes the given javascript
*/
[ActiveEvent(Name = "magix.viewport.execute-javascript")]
protected void magix_viewport_execute_javascript(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewport.execute-javascript-dox].value");
AppendCodeFromResource(
ip,
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewport.execute-javascript-sample]");
return;
}
if (!ip.ContainsValue("script"))
throw new ArgumentException("no [script] given to [magix.viewport.execute-script]");
Node dp = Dp(e.Params);
string script = Expressions.GetFormattedExpression("script", e.Params, "");
Manager.Instance.JavaScriptWriter.Write(script);
}
/*
* helper for re-including css files
*/
private void IncludeCssFile (string cssFile)
{
if (!string.IsNullOrEmpty (cssFile))
{
if (cssFile.Contains("~"))
{
string appPath = HttpContext.Current.Request.Url.ToString ();
appPath = appPath.Substring (0, appPath.LastIndexOf ('/'));
cssFile = cssFile.Replace ("~", appPath);
}
if (Manager.Instance.IsAjaxCallback)
{
Manager.Instance.JavaScriptWriter.Write (
@"MUX.Element.prototype.includeCSS('<link href=""{0}"" rel=""stylesheet"" type=""text/css"" />');", cssFile);
}
else
{
LiteralControl lit = new LiteralControl ();
lit.Text = string.Format (@"
<link href=""{0}"" rel=""stylesheet"" type=""text/css"" />
",
cssFile);
Page.Header.Controls.Add (lit);
}
}
}
/*
* helper for including javascript file
*/
private void IncludeJavaScriptFile(string javaScriptFile)
{
javaScriptFile = javaScriptFile.Replace("~/", GetApplicationBaseUrl());
Manager.Instance.IncludeFileScript(javaScriptFile);
}
/*
* includes a file on the client
*/
[ActiveEvent(Name = "magix.viewport.include-client-file")]
protected void magix_viewport_include_client_file(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewport.include-client-file-dox].value");
AppendCodeFromResource(
ip,
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewport.include-client-file-sample]");
return;
}
Node dp = Dp(e.Params);
if (!ip.ContainsValue("type"))
throw new ArgumentException("no [type] given to [magix.viewport.include-client-file]");
string type = Expressions.GetExpressionValue<string>(ip["type"].Get<string>(), dp, ip, false);
if (!ip.ContainsValue("file"))
throw new ArgumentException("no [file] given to [magix.viewport.include-client-file]");
string file = Expressions.GetExpressionValue<string>(ip["file"].Get<string>(), dp, ip, false);
if (type == "css")
{
if (!CssFiles.Contains(file))
{
CssFiles.Add(file);
IncludeCssFile(file);
}
}
else if (type == "javascript")
{
if (!JavaScriptFiles.Contains(file))
{
JavaScriptFiles.Add(file);
IncludeJavaScriptFile(file);
}
}
else
throw new ArgumentException("only 'css' and 'javascript' are legal types in [magix.viewport.include-client-file]");
}
/*
* sets a viewstate object
*/
[ActiveEvent(Name = "magix.viewstate.set")]
protected virtual void magix_viewstate_set(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewstate.set-dox].value");
AppendCodeFromResource(
ip,
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewstate.set-sample]");
return;
}
Node dp = Dp(e.Params);
if (!ip.ContainsValue("id"))
throw new ArgumentException("no [id] given to [magix.viewstate.set]");
string id = Expressions.GetFormattedExpression("id", e.Params, "");
if (!ip.Contains("value"))
{
if (ViewState[id] != null)
ViewState.Remove(id);
}
else
{
Node value = null;
if (ip.ContainsValue("value") && ip["value"].Get<string>().StartsWith("["))
value = Expressions.GetExpressionValue<Node>(ip["value"].Get<string>(), dp, ip, false).Clone();
else
value = ip["value"].Clone();
ViewState[id] = value;
}
}
/*
* retrieves a viewstate object
*/
[ActiveEvent(Name = "magix.viewstate.get")]
protected virtual void magix_viewstate_get(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewstate.get-dox].value");
AppendCodeFromResource(
ip,
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewstate.get-sample]");
return;
}
Node dp = Dp(e.Params);
if (!ip.ContainsValue("id"))
throw new ArgumentException("no [id] given to [magix.viewstate.get]");
string id = Expressions.GetFormattedExpression("id", e.Params, "");
if (ViewState[id] != null && ViewState[id] is Node)
{
ip["value"].UnTie();
ip.Add((ViewState[id] as Node).Clone());
}
}
/*
* loads an active module
*/
[ActiveEvent(Name = "magix.viewport.load-module")]
protected virtual void magix_viewport_load_module(object sender, ActiveEventArgs e)
{
Node ip = Ip(e.Params);
if (ShouldInspect(ip))
{
AppendInspectFromResource(
ip["inspect"],
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewport.load-module-dox].value");
AppendCodeFromResource(
ip,
"Magix.Core",
"Magix.Core.hyperlisp.inspect.hl",
"[magix.viewport.load-module-sample]");
return;
}
Node dp = Dp(e.Params);
string container = GetDefaultContainer();
if (ip.ContainsValue("container"))
container = Expressions.GetExpressionValue<string>(ip["container"].Get<string>(), dp, ip, false);
DynamicPanel dyn = Selector.FindControl<DynamicPanel>(
this,
container);
if (dyn == null && ip.ContainsValue("container"))
return;
string moduleName = Expressions.GetExpressionValue<string>(ip["name"].Get<string>(), dp, ip, false);
ClearControls(dyn);
if (ip.ContainsValue("class"))
dyn.Class = Expressions.GetExpressionValue<string>(ip["class"].Get<string>(), dp, ip, false);
if (ip.ContainsValue("style"))
{
// clearing old styles
foreach (string idx in dyn.Style.Keys)
{
dyn.Style[idx] = "";
}
// setting new styles
string[] styles =
ip["style"].Get<string>().Replace("\n", "").Replace("\r", "").Split(
new char[] { ';' },
StringSplitOptions.RemoveEmptyEntries);
foreach (string idxStyle in styles)
{
dyn.Style[idxStyle.Split(':')[0]] = idxStyle.Split(':')[1];
}
}
dyn.LoadControl(moduleName, e.Params);
}
/*
* reloading controls upon postbacks
*/
protected void dynamic_LoadControls(object sender, DynamicPanel.ReloadEventArgs e)
{
DynamicPanel dynamic = sender as DynamicPanel;
Control ctrl = ModuleControllerLoader.Instance.LoadActiveModule(e.Key);
if (e.FirstReload)
{
ActiveModule module = ctrl as ActiveModule;
if (module != null)
{
Node nn = e.Extra as Node;
ctrl.Init +=
delegate
{
module.InitialLoading(nn);
};
}
}
dynamic.Controls.Add(ctrl);
}
}
}
| |
// 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.Globalization;
using Xunit;
namespace System.Globalization.CalendarsTests
{
// GregorianCalendar.AddMonths(DateTime, int)
public class GregorianCalendarAddMonths
{
private const int c_MIN_MONTHS_NUMBER = -120000;
private const int c_MAX_MONTHS_NUMBER = 120000;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
#region Positive tests
// PosTest1: Add zero month to the specified date time
[Fact]
public void PosTest1()
{
DateTime initialTime;
int months;
DateTime resultingTime;
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
months = 0;
initialTime = DateTime.Now;
resultingTime = myCalendar.AddMonths(initialTime, months);
Assert.Equal(initialTime, resultingTime);
}
// PosTest2: the specified time is MinSupportedDateTime and the number of months added is a random value between 1 and 120000
[Fact]
public void PosTest2()
{
DateTime initialTime;
int months;
DateTime resultingTime;
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
months = _generator.GetInt32(-55) % c_MAX_MONTHS_NUMBER + 1;
initialTime = myCalendar.MinSupportedDateTime;
resultingTime = myCalendar.AddMonths(initialTime, months);
VerifyAddMonthsResult(myCalendar, initialTime, resultingTime, months);
}
// PosTest3: the specified time is MaxSupportedDateTime and the number of months added is a random value between -120000 and -1
[Fact]
public void PosTest3()
{
DateTime initialTime;
int months;
DateTime resultingTime;
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
months = -1 * _generator.GetInt32(-55) % c_MAX_MONTHS_NUMBER - 1;
initialTime = myCalendar.MaxSupportedDateTime;
resultingTime = myCalendar.AddMonths(initialTime, months);
VerifyAddMonthsResult(myCalendar, initialTime, resultingTime, months);
}
// PosTest4: the specified time is random value between 0 and MaxSupportedDateTime, months added is a normal value
[Fact]
public void PosTest4()
{
DateTime initialTime;
int months;
DateTime resultingTime;
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
months = -1;
long maxTimeInTicks = myCalendar.MaxSupportedDateTime.Ticks;
long minTimeInTikcs = myCalendar.MinSupportedDateTime.Ticks;
initialTime = new DateTime(_generator.GetInt64(-55) % (maxTimeInTicks + 1));
resultingTime = myCalendar.AddMonths(initialTime, months);
VerifyAddMonthsResult(myCalendar, initialTime, resultingTime, months);
}
// PosTest5: the specified time is February in leap year, months added is a normal value
[Fact]
public void PosTest5()
{
DateTime initialTime;
int months;
DateTime resultingTime;
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
months = 13;
initialTime = myCalendar.ToDateTime(2000, 2, 29, 10, 30, 24, 0);
resultingTime = myCalendar.AddMonths(initialTime, months);
VerifyAddMonthsResult(myCalendar, initialTime, resultingTime, months);
}
// PosTest6: the specified time is February in leap year, months added is a normal value
[Fact]
public void PosTest6()
{
DateTime initialTime;
int months;
DateTime resultingTime;
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
months = 48;
initialTime = myCalendar.ToDateTime(1996, 2, 29, 10, 30, 24, 0);
resultingTime = myCalendar.AddMonths(initialTime, months);
VerifyAddMonthsResult(myCalendar, initialTime, resultingTime, months);
}
// PosTest7: the specified time is any month other than February in leap year, months added is a normal value
[Fact]
public void PosTest7()
{
DateTime initialTime;
int months;
DateTime resultingTime;
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
months = 48;
initialTime = myCalendar.ToDateTime(1996, 3, 29, 10, 30, 24, 0);
resultingTime = myCalendar.AddMonths(initialTime, months);
VerifyAddMonthsResult(myCalendar, initialTime, resultingTime, months);
}
// PosTest8: the specified time is February in common year, months added is a normal value
[Fact]
public void PosTest8()
{
DateTime initialTime;
int months;
DateTime resultingTime;
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
months = 48;
initialTime = myCalendar.ToDateTime(1999, 2, 28, 10, 30, 24, 0);
resultingTime = myCalendar.AddMonths(initialTime, months);
VerifyAddMonthsResult(myCalendar, initialTime, resultingTime, months);
}
#endregion
#region Helper methods for positive tests
private void VerifyAddMonthsResult(Calendar calendar, DateTime oldTime, DateTime newTime, int months)
{
int oldYear = calendar.GetYear(oldTime);
int oldMonth = calendar.GetMonth(oldTime);
int oldDay = calendar.GetDayOfMonth(oldTime);
long oldTicksOfDay = oldTime.Ticks % TimeSpan.TicksPerDay;
int newYear = calendar.GetYear(newTime);
int newMonth = calendar.GetMonth(newTime);
int newDay = calendar.GetDayOfMonth(newTime);
long newTicksOfDay = newTime.Ticks % TimeSpan.TicksPerDay;
Assert.Equal(oldTicksOfDay, newTicksOfDay);
Assert.False(newDay > oldDay);
Assert.False(newYear * 12 + newMonth != oldYear * 12 + oldMonth + months);
}
#endregion
#region Negative Tests
// NegTest1: months is less than -120000
[Fact]
public void NegTest1()
{
DateTime time;
int months;
System.Globalization.Calendar myCalendar;
time = DateTime.Now;
months = -1 * (c_MAX_MONTHS_NUMBER + 1 + _generator.GetInt32(-55) % (int.MaxValue - c_MAX_MONTHS_NUMBER));
myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.AddMonths(time, months);
});
}
// NegTest2: months is greater than 120000
[Fact]
public void NegTest2()
{
DateTime time;
int months;
System.Globalization.Calendar myCalendar;
time = DateTime.Now;
months = c_MAX_MONTHS_NUMBER + 1 + _generator.GetInt32(-55) % (int.MaxValue - c_MAX_MONTHS_NUMBER);
myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.AddMonths(time, months);
});
}
// NegTest3: The resulting DateTime is outside the supported range
[Fact]
public void NegTest3()
{
DateTime time;
int months;
System.Globalization.Calendar myCalendar;
myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
time = myCalendar.MaxSupportedDateTime;
months = 1;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.AddMonths(time, months);
});
}
#endregion
#region Helper method for all the tests
private string GetParamesInfo(DateTime time, int months)
{
string str = string.Empty;
str += string.Format("\nThe initial time is {0}, number of months added is {1}.", time, months);
return str;
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation. 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.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR.Infrastructure;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.SignalR.Transports
{
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Disposable fields are disposed from a different method")]
public abstract class TransportDisconnectBase : ITrackingConnection
{
private readonly HttpContext _context;
private readonly ITransportHeartbeat _heartbeat;
private TextWriter _outputWriter;
private ILogger _logger;
private int _timedOut;
private readonly IPerformanceCounterManager _counters;
private int _ended;
private TransportConnectionStates _state;
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "It can be set in any derived class.")]
protected string _lastMessageId;
internal static readonly Func<Task> _emptyTaskFunc = () => TaskAsyncHelper.Empty;
// The TCS that completes when the task returned by PersistentConnection.OnConnected does.
internal TaskCompletionSource<object> _connectTcs;
// Token that represents the end of the connection based on a combination of
// conditions (timeout, disconnect, connection forcibly ended, host shutdown)
private CancellationToken _connectionEndToken;
private SafeCancellationTokenSource _connectionEndTokenSource;
private Task _lastWriteTask = TaskAsyncHelper.Empty;
// Token that represents the host shutting down
private readonly CancellationToken _hostShutdownToken;
private IDisposable _hostRegistration;
private IDisposable _connectionEndRegistration;
// Token that represents the client disconnecting
private readonly CancellationToken _requestAborted;
internal HttpRequestLifeTime _requestLifeTime;
protected TransportDisconnectBase(HttpContext context, ITransportHeartbeat heartbeat, IPerformanceCounterManager performanceCounterManager, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory, IMemoryPool pool)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (heartbeat == null)
{
throw new ArgumentNullException("heartbeat");
}
if (performanceCounterManager == null)
{
throw new ArgumentNullException("performanceCounterManager");
}
if (applicationLifetime == null)
{
throw new ArgumentNullException("applicationLifetime");
}
if (loggerFactory == null)
{
throw new ArgumentNullException("loggerFactory");
}
Pool = pool;
_context = context;
_heartbeat = heartbeat;
_counters = performanceCounterManager;
_hostShutdownToken = applicationLifetime.ApplicationStopping;
_requestAborted = context.RequestAborted;
// Queue to protect against overlapping writes to the underlying response stream
WriteQueue = new TaskQueue();
_logger = loggerFactory.CreateLogger(GetType().FullName);
}
protected IMemoryPool Pool { get; private set; }
protected ILogger Logger
{
get
{
return _logger;
}
}
public string ConnectionId
{
get;
set;
}
protected string LastMessageId
{
get
{
return _lastMessageId;
}
}
protected virtual Task InitializeMessageId()
{
_lastMessageId = Context.Request.Query["messageId"];
return TaskAsyncHelper.Empty;
}
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This is for async.")]
public virtual Task<string> GetGroupsToken()
{
return TaskAsyncHelper.FromResult(Context.Request.Query["groupsToken"].ToString());
}
internal TaskQueue WriteQueue
{
get;
set;
}
public Func<bool, Task> Disconnected { get; set; }
// Token that represents the client disconnecting
public virtual CancellationToken CancellationToken
{
get
{
return _requestAborted;
}
}
public virtual bool IsAlive
{
get
{
// If the CTS is tripped or the request has ended then the connection isn't alive
return !(
CancellationToken.IsCancellationRequested ||
(_requestLifeTime != null && _requestLifeTime.Task.IsCompleted) ||
_lastWriteTask.IsCanceled ||
_lastWriteTask.IsFaulted
);
}
}
public Task ConnectTask
{
get
{
return _connectTcs.Task;
}
}
protected CancellationToken ConnectionEndToken
{
get
{
return _connectionEndToken;
}
}
protected CancellationToken HostShutdownToken
{
get
{
return _hostShutdownToken;
}
}
public bool IsTimedOut
{
get
{
return _timedOut == 1;
}
}
public virtual bool SupportsKeepAlive
{
get
{
return true;
}
}
public virtual bool RequiresTimeout
{
get
{
return false;
}
}
public virtual TimeSpan DisconnectThreshold
{
get { return TimeSpan.FromSeconds(5); }
}
protected bool IsConnectRequest
{
get
{
return Context.Request.LocalPath().EndsWith("/connect", StringComparison.OrdinalIgnoreCase);
}
}
protected bool IsSendRequest
{
get
{
return Context.Request.LocalPath().EndsWith("/send", StringComparison.OrdinalIgnoreCase);
}
}
protected bool IsAbortRequest
{
get
{
return Context.Request.LocalPath().EndsWith("/abort", StringComparison.OrdinalIgnoreCase);
}
}
protected virtual bool SuppressReconnect
{
get
{
return false;
}
}
protected ITransportConnection Connection { get; set; }
protected HttpContext Context
{
get { return _context; }
}
protected ITransportHeartbeat Heartbeat
{
get { return _heartbeat; }
}
protected void IncrementErrors()
{
_counters.ErrorsTransportTotal.Increment();
_counters.ErrorsTransportPerSec.Increment();
_counters.ErrorsAllTotal.Increment();
_counters.ErrorsAllPerSec.Increment();
}
public abstract void IncrementConnectionsCount();
public abstract void DecrementConnectionsCount();
public Task Disconnect()
{
return Abort(clean: false);
}
protected Task Abort()
{
return Abort(clean: true);
}
private Task Abort(bool clean)
{
if (clean)
{
ApplyState(TransportConnectionStates.Aborted);
}
else
{
ApplyState(TransportConnectionStates.Disconnected);
}
Logger.LogInformation("Abort(" + ConnectionId + ")");
// When a connection is aborted (graceful disconnect) we send a command to it
// telling to to disconnect. At that moment, we raise the disconnect event and
// remove this connection from the heartbeat so we don't end up raising it for the same connection.
Heartbeat.RemoveConnection(this);
// End the connection
End();
var disconnectTask = Disconnected != null ? Disconnected(clean) : TaskAsyncHelper.Empty;
// Ensure delegate continues to use the C# Compiler static delegate caching optimization.
return disconnectTask
.Catch((ex, state) => OnDisconnectError(ex, state), state: Logger, logger: Logger)
.Finally(state =>
{
var counters = (IPerformanceCounterManager)state;
counters.ConnectionsDisconnected.Increment();
}, _counters);
}
public void ApplyState(TransportConnectionStates states)
{
_state |= states;
}
public void Timeout()
{
if (Interlocked.Exchange(ref _timedOut, 1) == 0)
{
Logger.LogInformation("Timeout(" + ConnectionId + ")");
End();
}
}
public virtual Task KeepAlive()
{
return TaskAsyncHelper.Empty;
}
public void End()
{
if (Interlocked.Exchange(ref _ended, 1) == 0)
{
Logger.LogInformation("End(" + ConnectionId + ")");
if (_connectionEndTokenSource != null)
{
_connectionEndTokenSource.Cancel();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_connectionEndTokenSource.Dispose();
_connectionEndRegistration.Dispose();
_hostRegistration.Dispose();
ApplyState(TransportConnectionStates.Disposed);
}
}
protected internal Task EnqueueOperation(Func<Task> writeAsync)
{
return EnqueueOperation(state => ((Func<Task>)state).Invoke(), writeAsync);
}
protected virtual internal Task EnqueueOperation(Func<object, Task> writeAsync, object state)
{
if (!IsAlive)
{
return TaskAsyncHelper.Empty;
}
// Only enqueue new writes if the connection is alive
Task writeTask = WriteQueue.Enqueue(writeAsync, state);
_lastWriteTask = writeTask;
return writeTask;
}
protected virtual Task InitializePersistentState()
{
_requestLifeTime = new HttpRequestLifeTime(this, WriteQueue, Logger, ConnectionId);
// Create the TCS that completes when the task returned by PersistentConnection.OnConnected does.
_connectTcs = new TaskCompletionSource<object>();
// Create a token that represents the end of this connection's life
_connectionEndTokenSource = new SafeCancellationTokenSource();
_connectionEndToken = _connectionEndTokenSource.Token;
// Handle the shutdown token's callback so we can end our token if it trips
_hostRegistration = _hostShutdownToken.SafeRegister(state =>
{
((SafeCancellationTokenSource)state).Cancel();
},
_connectionEndTokenSource);
// When the connection ends release the request
_connectionEndRegistration = CancellationToken.SafeRegister(state =>
{
((HttpRequestLifeTime)state).Complete();
},
_requestLifeTime);
return InitializeMessageId();
}
private static void OnDisconnectError(AggregateException ex, object state)
{
((ILogger)state).LogError("Failed to raise disconnect: " + ex.GetBaseException());
}
}
}
| |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
namespace UnitTests
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.VCProjectEngine;
using NativeClientVSAddIn;
/// <summary>
/// This class contains utilities for running tests.
/// </summary>
public static class TestUtilities
{
/// <summary>
/// Name of the NaCl project in BlankValidSolution.
/// </summary>
public const string BlankNaClProjectName = @"NaClProject";
/// <summary>
/// Uniquename of the NaCl project in BlankValidSolution.
/// </summary>
public const string NaClProjectUniqueName = @"NaClProject\NaClProject.vcxproj";
/// <summary>
/// Uniquename of the non-NaCl project in BlankValidSolution.
/// </summary>
public const string NotNaClProjectUniqueName = @"NotNaCl\NotNaCl.csproj";
/// <summary>
/// A generic boolean statement to be used with RetryWithTimeout.
/// </summary>
/// <returns>True if the statement is true, false if false.</returns>
public delegate bool RetryStatement();
/// <summary>
/// This starts an instance of Visual Studio and get its DTE object.
/// </summary>
/// <returns>DTE of the started instance.</returns>
public static DTE2 StartVisualStudioInstance()
{
// Set up filter to handle threading events and automatically retry calls
// to dte which fail because dte is busy.
ComMessageFilter.Register();
Type visualStudioType;
if (IsVS2012())
visualStudioType = Type.GetTypeFromProgID("VisualStudio.DTE.11.0");
else
visualStudioType = Type.GetTypeFromProgID("VisualStudio.DTE.10.0");
DTE2 visualStudio = Activator.CreateInstance(visualStudioType) as DTE2;
if (visualStudio == null)
{
throw new Exception("Visual Studio failed to start");
}
visualStudio.MainWindow.Visible = true;
return visualStudio;
}
/// <summary>
/// This properly cleans up after StartVisualStudioInstance().
/// </summary>
/// <param name="dte">Dte instance returned by StartVisualStudioInstance().</param>
public static void CleanUpVisualStudioInstance(DTE2 dte)
{
if (dte != null)
{
if (dte.Solution != null)
{
dte.Solution.Close();
}
dte.Quit();
}
// Stop the message filter.
ComMessageFilter.Revoke();
}
public static void SetProjectType(Project project, string projectType, string platformName)
{
VCConfiguration config;
IVCRulePropertyStorage rule;
config = TestUtilities.GetVCConfiguration(project, "Debug", platformName);
rule = config.Rules.Item("ConfigurationGeneral");
rule.SetPropertyValue("ConfigurationType", projectType);
config = TestUtilities.GetVCConfiguration(project, "Release", platformName);
rule = config.Rules.Item("ConfigurationGeneral");
rule.SetPropertyValue("ConfigurationType", projectType);
}
public static bool IsVS2012()
{
#if VS2012
return true;
#else
return false;
#endif
}
static void AddPlatform(Project project, String platform, String copyFrom)
{
project.ConfigurationManager.AddPlatform(platform, copyFrom, true);
}
/// <summary>
/// Creates a blank valid NaCl project with up-to-date settings. The path to the new solution
/// is returned.
/// </summary>
/// <param name="dte">Interface to an open Visual Studio instance to use.</param>
/// <param name="name">Name to give newly created solution.</param>
/// <param name="pepperCopyFrom">Platform name to copy existing settings from to pepper.</param>
/// <param name="naclCopyFrom">Platform name to copy existing settings from to NaCl.</param>
/// <param name="testContext">Test context used for finding deployment directory.</param>
/// <returns>Path to the newly created solution.</returns>
public static string CreateBlankValidNaClSolution(
DTE2 dte, string name, string pepperCopyFrom, string naclCopyFrom, TestContext testContext)
{
string blankSolution = "BlankValidSolution";
string srcSolution = blankSolution;
if (IsVS2012())
srcSolution += "2012";
string newSolutionDir = Path.Combine(testContext.DeploymentDirectory, name);
string newSolution = Path.Combine(newSolutionDir, blankSolution + ".sln");
CopyDirectory(Path.Combine(testContext.DeploymentDirectory, srcSolution), newSolutionDir);
try
{
dte.Solution.Open(newSolution);
Project proj = dte.Solution.Projects.Item(NaClProjectUniqueName);
// Order matters if copying from the other Native Client type.
if (PropertyManager.IsNaClPlatform(pepperCopyFrom))
{
// create nacl platforms first
AddPlatform(proj, Strings.NaCl64PlatformName, naclCopyFrom);
AddPlatform(proj, Strings.NaCl32PlatformName, naclCopyFrom);
AddPlatform(proj, Strings.NaClARMPlatformName, naclCopyFrom);
AddPlatform(proj, Strings.PNaClPlatformName, naclCopyFrom);
AddPlatform(proj, Strings.PepperPlatformName, pepperCopyFrom);
}
else
{
// create pepper platform first
AddPlatform(proj, Strings.PepperPlatformName, pepperCopyFrom);
AddPlatform(proj, Strings.NaCl64PlatformName, naclCopyFrom);
AddPlatform(proj, Strings.NaCl32PlatformName, naclCopyFrom);
AddPlatform(proj, Strings.NaClARMPlatformName, naclCopyFrom);
AddPlatform(proj, Strings.PNaClPlatformName, naclCopyFrom);
}
proj.Save();
// Set the active solution configuration to Debug|NaCl64.
SetSolutionConfiguration(dte, NaClProjectUniqueName, "Debug", Strings.NaCl64PlatformName);
dte.Solution.SaveAs(newSolution);
SetSolutionConfiguration(dte, NaClProjectUniqueName, "Release", Strings.NaCl64PlatformName);
dte.Solution.SaveAs(newSolution);
}
finally
{
if (dte.Solution != null)
{
dte.Solution.Close();
}
}
return newSolution;
}
/// <summary>
/// This returns the text contained in the given output window pane.
/// </summary>
/// <param name="pane">Pane to get text from.</param>
/// <returns>Text in the window.</returns>
public static string GetPaneText(OutputWindowPane pane)
{
TextSelection selection = pane.TextDocument.Selection;
selection.StartOfDocument(false);
selection.EndOfDocument(true);
return selection.Text;
}
/// <summary>
/// This starts a python process that just sleeps waiting to be killed.
/// It can be used with DoesProcessExist() to verify that a process started/exited.
/// </summary>
/// <param name="identifierString">
/// A unique string to identify the process via its command line arguments.
/// </param>
/// <param name="timeout">Time in seconds to wait before process exits on its own.</param>
/// <returns>The process object that was started.</returns>
public static System.Diagnostics.Process StartProcessForKilling(
string identifierString, int timeout)
{
string args = string.Format(
"-c \"import time; time.sleep({0}); print '{1}'\"",
timeout,
identifierString);
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "python.exe";
proc.StartInfo.Arguments = args;
proc.Start();
return proc;
}
/// <summary>
/// This returns true if there is a running process that has command line arguments
/// containing the given Strings. The search is case-insensitive.
/// </summary>
/// <param name="processName">Name of the process executable.</param>
/// <param name="commandLineIdentifiers">Strings to check for.</param>
/// <returns>True if some process has the Strings in its command line arguments.</returns>
public static bool DoesProcessExist(string processName, params string[] commandLineIdentifiers)
{
List<string> results = new List<string>();
string query =
string.Format("select CommandLine from Win32_Process where Name='{0}'", processName);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
using (ManagementObjectCollection result = searcher.Get())
{
foreach (ManagementObject process in result)
{
string commandLine = process["CommandLine"] as string;
if (string.IsNullOrEmpty(commandLine))
{
break;
}
// Check if the command line contains each of the required identifiers.
if (commandLineIdentifiers.All(i => commandLine.Contains(i)))
{
return true;
}
}
}
}
return false;
}
/// <summary>
/// Sets the active configuration for the solution by specifying the configuration name
/// and platform name. A solution configuration containing a project configuration that has
/// the config and platform names specified for the specified project is selected.
/// </summary>
/// <param name="dte">The main visual studio object.</param>
/// <param name="projectUniqueName">UniqueName of the project to match.</param>
/// <param name="configurationName">Ex: "Debug" or "Release".</param>
/// <param name="platformName">Ex: "Win32" or "NaCl" or "PPAPI".</param>
public static void SetSolutionConfiguration(
DTE2 dte,
string projectUniqueName,
string configurationName,
string platformName)
{
foreach (EnvDTE.SolutionConfiguration config in
dte.Solution.SolutionBuild.SolutionConfigurations)
{
EnvDTE.SolutionContext context = null;
try
{
context = config.SolutionContexts.Item(projectUniqueName);
}
catch (ArgumentException)
{
throw new Exception(
string.Format("Project unique name not found in solution: {0}", projectUniqueName));
}
if (context == null)
{
throw new Exception("Failed to get solution context");
}
if (context.PlatformName == platformName && context.ConfigurationName == configurationName)
{
config.Activate();
return;
}
}
throw new Exception(string.Format(
"Matching configuration not found for {0}: {1}|{2}",
projectUniqueName,
platformName,
configurationName));
}
/// <summary>
/// Returns a VCConfiguration object with a matching configuration name and platform type.
/// </summary>
/// <param name="project">Project to get the configuration from.</param>
/// <param name="name">Name of configuration (e.g. 'Debug').</param>
/// <param name="platform">Name of the platform (e.g. 'NaCl').</param>
/// <returns>A matching VCConfiguration object.</returns>
public static VCConfiguration GetVCConfiguration(Project project, string name, string platform)
{
VCProject vcproj = (VCProject)project.Object;
IVCCollection configs = vcproj.Configurations;
foreach (VCConfiguration config in configs)
{
if (config.ConfigurationName == name && config.Platform.Name == platform)
{
return config;
}
}
throw new Exception(
string.Format("Project does not have configuration: {0}|{1}", platform, name));
}
/// <summary>
/// Tests that a given property has a specific value in a certain VCConfiguration
/// </summary>
/// <param name="configuration">Gives the platform and configuration type</param>
/// <param name="pageName">Property page name where property resides.</param>
/// <param name="propertyName">Name of the property to check.</param>
/// <param name="expectedValue">Expected value of the property.</param>
/// <param name="ignoreCase">Ignore case when comparing the expected and actual values.</param>
public static void AssertPropertyEquals(
VCConfiguration configuration,
string pageName,
string propertyName,
string expectedValue,
bool ignoreCase)
{
IVCRulePropertyStorage rule = configuration.Rules.Item(pageName);
string callInfo = string.Format(
"Page: {0}, Property: {1}, Configuration: {2}",
pageName,
propertyName,
configuration.ConfigurationName);
Assert.AreEqual(
expectedValue,
rule.GetUnevaluatedPropertyValue(propertyName),
ignoreCase,
callInfo);
}
/// <summary>
/// Tests that a given property contains a specific string in a certain VCConfiguration
/// </summary>
/// <param name="configuration">Gives the platform and configuration type</param>
/// <param name="pageName">Property page name where property resides.</param>
/// <param name="propertyName">Name of the property to check.</param>
/// <param name="expectedValue">Expected string to contain.</param>
/// <param name="ignoreCase">Ignore case when comparing the expected and actual values.</param>
public static void AssertPropertyContains(
VCConfiguration configuration,
string pageName,
string propertyName,
string expectedValue,
bool ignoreCase,
bool expand=false)
{
StringComparison caseSensitive = ignoreCase ?
StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
IVCRulePropertyStorage rule = configuration.Rules.Item(pageName);
string propertyValue;
if (expand)
propertyValue = rule.GetEvaluatedPropertyValue(propertyName);
else
propertyValue = rule.GetUnevaluatedPropertyValue(propertyName);
string message = string.Format(
"{0} should be contained in {1}. Page: {2}, Property: {3}, Configuration: {4}",
expectedValue,
propertyValue,
pageName,
propertyName,
configuration.ConfigurationName);
Assert.IsTrue(propertyValue.Contains(expectedValue, caseSensitive), message);
}
/// <summary>
/// Tests that a given property is not null or empty.
/// </summary>
/// <param name="configuration">Gives the platform and configuration type</param>
/// <param name="pageName">Property page name where property resides.</param>
/// <param name="propertyName">Name of the property to check.</param>
public static void AssertPropertyIsNotNullOrEmpty(
VCConfiguration configuration,
string pageName,
string propertyName)
{
IVCRulePropertyStorage rule = configuration.Rules.Item(pageName);
string propertyValue = rule.GetUnevaluatedPropertyValue(propertyName);
string message = string.Format(
"{0} was null or empty. Page: {1}, Configuration: {2}",
propertyName,
pageName,
configuration.ConfigurationName);
Assert.IsFalse(string.IsNullOrEmpty(propertyValue), message);
}
/// <summary>
/// Ensures that the add-in is configured to load on start. If it isn't then some tests may
/// unexpectedly fail, this check helps catch that problem early.
/// </summary>
/// <param name="dte">The main Visual Studio interface.</param>
/// <param name="addInName">The name of the add-in to check if loaded.</param>
public static void AssertAddinLoaded(DTE2 dte, string addInName)
{
bool found = false;
foreach (AddIn addin in dte.AddIns)
{
if (addin.Connected && addInName.Equals(addin.Name))
{
found = true;
break;
}
}
Assert.IsTrue(found, "Add-in is not configured to load on start.");
}
/// <summary>
/// Will retry the given statement up to maxRetry times while pausing between each try for
/// the given interval.
/// </summary>
/// <param name="test">Generic boolean statement.</param>
/// <param name="interval">Amount of time to wait between each retry.</param>
/// <param name="maxRetry">Maximum number of retries.</param>
/// <param name="message">Message to print on failure.</param>
public static void AssertTrueWithTimeout(
RetryStatement test, TimeSpan interval, int maxRetry, string message)
{
for (int tryCount = 0; tryCount <= maxRetry; tryCount++)
{
if (test.Invoke())
{
return;
}
System.Threading.Thread.Sleep(interval);
}
throw new Exception(string.Format("Statement timed out. {0}", message));
}
/// <summary>
/// Extends the string class to allow checking if a string contains another string
/// allowing a comparison type (such as case-insensitivity).
/// </summary>
/// <param name="source">Base string to search.</param>
/// <param name="toCheck">String to check if contained within base string.</param>
/// <param name="comparison">Comparison type.</param>
/// <returns>True if toCheck is contained in source.</returns>
public static bool Contains(this string source, string toCheck, StringComparison comparison)
{
return source.IndexOf(toCheck, comparison) != -1;
}
/// <summary>
/// Copies the entire contents of a directory and sub directories.
/// </summary>
/// <param name="source">Directory to copy from.</param>
/// <param name="dest">Directory to copy to.</param>
public static void CopyDirectory(string source, string dest)
{
DirectoryInfo dir = new DirectoryInfo(source);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(source);
}
if (!Directory.Exists(dest))
{
Directory.CreateDirectory(dest);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string path = Path.Combine(dest, file.Name);
file.CopyTo(path, false);
}
foreach (DirectoryInfo subdir in dir.GetDirectories())
{
string path = Path.Combine(dest, subdir.Name);
CopyDirectory(subdir.FullName, path);
}
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules
{
public class SunModule : ISunModule
{
/// <summary>
/// Note: Sun Hour can be a little deceaving. Although it's based on a 24 hour clock
/// it is not based on ~06:00 == Sun Rise. Rather it is based on 00:00 being sun-rise.
/// </summary>
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//
// Global Constants used to determine where in the sky the sun is
//
private const double m_SeasonalTilt = 0.03 * Math.PI; // A daily shift of approximately 1.7188 degrees
private const double m_AverageTilt = -0.25 * Math.PI; // A 45 degree tilt
private const double m_SunCycle = 2.0D * Math.PI; // A perfect circle measured in radians
private const double m_SeasonalCycle = 2.0D * Math.PI; // Ditto
//
// Per Region Values
//
private bool ready = false;
// This solves a chick before the egg problem
// the local SunFixedHour and SunFixed variables MUST be updated
// at least once with the proper Region Settings before we start
// updating those region settings in GenSunPos()
private bool receivedEstateToolsSunUpdate = false;
// Configurable values
private string m_RegionMode = "SL";
// Sun's position information is updated and sent to clients every m_UpdateInterval frames
private int m_UpdateInterval = 0;
// Number of real time hours per virtual day
private double m_DayLengthHours = 0;
// Number of virtual days to a virtual year
private int m_YearLengthDays = 0;
// Ratio of Daylight hours to Night time hours. This is accomplished by shifting the
// sun's orbit above the horizon
private double m_HorizonShift = 0;
// Used to scale current and positional time to adjust length of an hour during day vs night.
private double m_DayTimeSunHourScale;
// private double m_longitude = 0;
// private double m_latitude = 0;
// Configurable defaults Defaults close to SL
private string d_mode = "SL";
private int d_frame_mod = 100; // Every 10 seconds (actually less)
private double d_day_length = 4; // A VW day is 4 RW hours long
private int d_year_length = 60; // There are 60 VW days in a VW year
private double d_day_night = 0.5; // axis offset: Default Hoizon shift to try and closely match the sun model in LL Viewer
private double d_DayTimeSunHourScale = 0.5; // Day/Night hours are equal
// private double d_longitude = -73.53;
// private double d_latitude = 41.29;
// Frame counter
private uint m_frame = 0;
// Cached Scene reference
private Scene m_scene = null;
// Calculated Once in the lifetime of a region
private long TicksToEpoch; // Elapsed time for 1/1/1970
private uint SecondsPerSunCycle; // Length of a virtual day in RW seconds
private uint SecondsPerYear; // Length of a virtual year in RW seconds
private double SunSpeed; // Rate of passage in radians/second
private double SeasonSpeed; // Rate of change for seasonal effects
// private double HoursToRadians; // Rate of change for seasonal effects
private long TicksUTCOffset = 0; // seconds offset from UTC
// Calculated every update
private float OrbitalPosition; // Orbital placement at a point in time
private double HorizonShift; // Axis offset to skew day and night
private double TotalDistanceTravelled; // Distance since beginning of time (in radians)
private double SeasonalOffset; // Seaonal variation of tilt
private float Magnitude; // Normal tilt
// private double VWTimeRatio; // VW time as a ratio of real time
// Working values
private Vector3 Position = Vector3.Zero;
private Vector3 Velocity = Vector3.Zero;
private Quaternion Tilt = new Quaternion(1.0f, 0.0f, 0.0f, 0.0f);
// Used to fix the sun in the sky so it doesn't move based on current time
private bool m_SunFixed = false;
private float m_SunFixedHour = 0f;
private const int TICKS_PER_SECOND = 10000000;
// Current time in elapsed seconds since Jan 1st 1970
private ulong CurrentTime
{
get
{
return (ulong)(((DateTime.Now.Ticks) - TicksToEpoch + TicksUTCOffset) / TICKS_PER_SECOND);
}
}
// Time in seconds since UTC to use to calculate sun position.
ulong PosTime = 0;
/// <summary>
/// Calculate the sun's orbital position and its velocity.
/// </summary>
private void GenSunPos()
{
// Time in seconds since UTC to use to calculate sun position.
PosTime = CurrentTime;
if (m_SunFixed)
{
// SunFixedHour represents the "hour of day" we would like
// It's represented in 24hr time, with 0 hour being sun-rise
// Because our day length is probably not 24hrs {LL is 6} we need to do a bit of math
// Determine the current "day" from current time, so we can use "today"
// to determine Seasonal Tilt and what'not
// Integer math rounded is on purpose to drop fractional day, determines number
// of virtual days since Epoch
PosTime = CurrentTime / SecondsPerSunCycle;
// Since we want number of seconds since Epoch, multiply back up
PosTime *= SecondsPerSunCycle;
// Then offset by the current Fixed Sun Hour
// Fixed Sun Hour needs to be scaled to reflect the user configured Seconds Per Sun Cycle
PosTime += (ulong)((m_SunFixedHour / 24.0) * (ulong)SecondsPerSunCycle);
}
else
{
if (m_DayTimeSunHourScale != 0.5f)
{
ulong CurDaySeconds = CurrentTime % SecondsPerSunCycle;
double CurDayPercentage = (double)CurDaySeconds / SecondsPerSunCycle;
ulong DayLightSeconds = (ulong)(m_DayTimeSunHourScale * SecondsPerSunCycle);
ulong NightSeconds = SecondsPerSunCycle - DayLightSeconds;
PosTime = CurrentTime / SecondsPerSunCycle;
PosTime *= SecondsPerSunCycle;
if (CurDayPercentage < 0.5)
{
PosTime += (ulong)((CurDayPercentage / .5) * DayLightSeconds);
}
else
{
PosTime += DayLightSeconds;
PosTime += (ulong)(((CurDayPercentage - 0.5) / .5) * NightSeconds);
}
}
}
TotalDistanceTravelled = SunSpeed * PosTime; // distance measured in radians
OrbitalPosition = (float)(TotalDistanceTravelled % m_SunCycle); // position measured in radians
// TotalDistanceTravelled += HoursToRadians-(0.25*Math.PI)*Math.Cos(HoursToRadians)-OrbitalPosition;
// OrbitalPosition = (float) (TotalDistanceTravelled%SunCycle);
SeasonalOffset = SeasonSpeed * PosTime; // Present season determined as total radians travelled around season cycle
Tilt.W = (float)(m_AverageTilt + (m_SeasonalTilt * Math.Sin(SeasonalOffset))); // Calculate seasonal orbital N/S tilt
// m_log.Debug("[SUN] Total distance travelled = "+TotalDistanceTravelled+", present position = "+OrbitalPosition+".");
// m_log.Debug("[SUN] Total seasonal progress = "+SeasonalOffset+", present tilt = "+Tilt.W+".");
// The sun rotates about the Z axis
Position.X = (float)Math.Cos(-TotalDistanceTravelled);
Position.Y = (float)Math.Sin(-TotalDistanceTravelled);
Position.Z = 0;
// For interest we rotate it slightly about the X access.
// Celestial tilt is a value that ranges .025
Position *= Tilt;
// Finally we shift the axis so that more of the
// circle is above the horizon than below. This
// makes the nights shorter than the days.
Position = Vector3.Normalize(Position);
Position.Z = Position.Z + (float)HorizonShift;
Position = Vector3.Normalize(Position);
// m_log.Debug("[SUN] Position("+Position.X+","+Position.Y+","+Position.Z+")");
Velocity.X = 0;
Velocity.Y = 0;
Velocity.Z = (float)SunSpeed;
// Correct angular velocity to reflect the seasonal rotation
Magnitude = Position.Length();
if (m_SunFixed)
{
Velocity.X = 0;
Velocity.Y = 0;
Velocity.Z = 0;
}
else
{
Velocity = (Velocity * Tilt) * (1.0f / Magnitude);
}
// TODO: Decouple this, so we can get rid of Linden Hour info
// Update Region infor with new Sun Position and Hour
// set estate settings for region access to sun position
if (receivedEstateToolsSunUpdate)
{
m_scene.RegionInfo.RegionSettings.SunVector = Position;
m_scene.RegionInfo.RegionSettings.SunPosition = GetCurrentTimeAsLindenSunHour();
}
}
private float GetCurrentTimeAsLindenSunHour()
{
if (m_SunFixed)
{
return m_SunFixedHour + 6;
}
return GetCurrentSunHour() + 6.0f;
}
#region IRegion Methods
// Called immediately after the module is loaded for a given region
// i.e. Immediately after instance creation.
public void Initialize(Scene scene, IConfigSource config)
{
m_scene = scene;
m_frame = 0;
// This one puts an entry in the main help screen
m_scene.AddCommand(this, String.Empty, "sun", "Usage: sun [param] [value] - Get or Update Sun module paramater", null);
// This one enables the ability to type just "sun" without any parameters
m_scene.AddCommand(this, "sun", String.Empty, String.Empty, HandleSunConsoleCommand);
foreach (KeyValuePair<string, string> kvp in GetParamList())
{
m_scene.AddCommand(this, String.Format("sun {0}", kvp.Key), String.Format("{0} - {1}", kvp.Key, kvp.Value), String.Empty, HandleSunConsoleCommand);
}
TimeZone local = TimeZone.CurrentTimeZone;
TicksUTCOffset = local.GetUtcOffset(local.ToLocalTime(DateTime.Now)).Ticks;
m_log.Debug("[SUN]: localtime offset is " + TicksUTCOffset);
// Align ticks with Second Life
TicksToEpoch = new DateTime(1970, 1, 1).Ticks;
// Just in case they don't have the stanzas
try
{
IConfig sunConfig = config.Configs["Sun"];
if (sunConfig == null) {
m_log.Debug("[SUN]: Configuration access missing, using defaults.");
m_RegionMode = d_mode;
m_YearLengthDays = d_year_length;
m_DayLengthHours = d_day_length;
m_HorizonShift = d_day_night;
m_UpdateInterval = d_frame_mod;
m_DayTimeSunHourScale = d_DayTimeSunHourScale;
// m_latitude = d_latitude;
// m_longitude = d_longitude;
} else {
// Mode: determines how the sun is handled
m_RegionMode = config.Configs["Sun"].GetString("mode", d_mode);
// Mode: determines how the sun is handled
// m_latitude = config.Configs["Sun"].GetDouble("latitude", d_latitude);
// Mode: determines how the sun is handled
// m_longitude = config.Configs["Sun"].GetDouble("longitude", d_longitude);
// Year length in days
m_YearLengthDays = config.Configs["Sun"].GetInt("year_length", d_year_length);
// Day length in decimal hours
m_DayLengthHours = config.Configs["Sun"].GetDouble("day_length", d_day_length);
// Horizon shift, this is used to shift the sun's orbit, this affects the day / night ratio
// must hard code to ~.5 to match sun position in LL based viewers
m_HorizonShift = config.Configs["Sun"].GetDouble("day_night_offset", d_day_night);
// Scales the sun hours 0...12 vs 12...24, essentially makes daylight hours longer/shorter vs nighttime hours
m_DayTimeSunHourScale = config.Configs["Sun"].GetDouble("day_time_sun_hour_scale", d_DayTimeSunHourScale);
// Update frequency in frames
m_UpdateInterval = config.Configs["Sun"].GetInt("update_interval", d_frame_mod);
}
}
catch (Exception e)
{
m_log.Debug("[SUN]: Configuration access failed, using defaults. Reason: " + e.Message);
m_RegionMode = d_mode;
m_YearLengthDays = d_year_length;
m_DayLengthHours = d_day_length;
m_HorizonShift = d_day_night;
m_UpdateInterval = d_frame_mod;
m_DayTimeSunHourScale = d_DayTimeSunHourScale;
// m_latitude = d_latitude;
// m_longitude = d_longitude;
}
switch (m_RegionMode)
{
case "T1":
default:
case "SL":
// Time taken to complete a cycle (day and season)
SecondsPerSunCycle = (uint) (m_DayLengthHours * 60 * 60);
SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays);
// Ration of real-to-virtual time
// VWTimeRatio = 24/m_day_length;
// Speed of rotation needed to complete a cycle in the
// designated period (day and season)
SunSpeed = m_SunCycle/SecondsPerSunCycle;
SeasonSpeed = m_SeasonalCycle/SecondsPerYear;
// Horizon translation
HorizonShift = m_HorizonShift; // Z axis translation
// HoursToRadians = (SunCycle/24)*VWTimeRatio;
// Insert our event handling hooks
scene.EventManager.OnFrame += SunUpdate;
scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
scene.EventManager.OnEstateToolsSunUpdate += EstateToolsSunUpdate;
scene.EventManager.OnGetCurrentTimeAsLindenSunHour += GetCurrentTimeAsLindenSunHour;
ready = true;
m_log.Debug("[SUN]: Mode is " + m_RegionMode);
m_log.Debug("[SUN]: Initialization completed. Day is " + SecondsPerSunCycle + " seconds, and year is " + m_YearLengthDays + " days");
m_log.Debug("[SUN]: Axis offset is " + m_HorizonShift);
m_log.Debug("[SUN]: Percentage of time for daylight " + m_DayTimeSunHourScale);
m_log.Debug("[SUN]: Positional data updated every " + m_UpdateInterval + " frames");
break;
}
scene.RegisterModuleInterface<ISunModule>(this);
}
public void PostInitialize()
{
}
public void Close()
{
ready = false;
// Remove our hooks
m_scene.EventManager.OnFrame -= SunUpdate;
m_scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel;
m_scene.EventManager.OnEstateToolsSunUpdate -= EstateToolsSunUpdate;
m_scene.EventManager.OnGetCurrentTimeAsLindenSunHour -= GetCurrentTimeAsLindenSunHour;
}
public string Name
{
get { return "SunModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
#region EventManager Events
public void SunToClient(IClientAPI client)
{
if (m_RegionMode != "T1")
{
if (ready)
{
if (m_SunFixed)
{
// m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString());
client.SendSunPos(Position, Velocity, PosTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
}
else
{
// m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString());
client.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
}
}
}
}
public void SunUpdate()
{
if (((m_frame++ % m_UpdateInterval) != 0) || !ready || m_SunFixed || !receivedEstateToolsSunUpdate)
{
return;
}
GenSunPos(); // Generate shared values once
SunUpdateToAllClients();
}
/// <summary>
/// When an avatar enters the region, it's probably a good idea to send them the current sun info
/// </summary>
/// <param name="avatar"></param>
/// <param name="localLandID"></param>
/// <param name="regionID"></param>
private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
{
SunToClient(avatar.ControllingClient);
}
/// <summary>
///
/// </summary>
/// <param name="regionHandle"></param>
/// <param name="FixedTime">Is the sun's position fixed?</param>
/// <param name="useEstateTime">Use the Region or Estate Sun hour?</param>
/// <param name="FixedSunHour">What hour of the day is the Sun Fixed at?</param>
public void EstateToolsSunUpdate(ulong regionHandle, bool FixedSun, bool useEstateTime, float FixedSunHour)
{
if (m_scene.RegionInfo.RegionHandle == regionHandle)
{
// Must limit the Sun Hour to 0 ... 24
while (FixedSunHour > 24.0f)
FixedSunHour -= 24;
while (FixedSunHour < 0)
FixedSunHour += 24;
m_SunFixedHour = FixedSunHour;
m_SunFixed = FixedSun;
m_log.DebugFormat("[SUN]: Sun Settings Update: Fixed Sun? : {0}", m_SunFixed.ToString());
m_log.DebugFormat("[SUN]: Sun Settings Update: Sun Hour : {0}", m_SunFixedHour.ToString());
receivedEstateToolsSunUpdate = true;
// Generate shared values
GenSunPos();
// When sun settings are updated, we should update all clients with new settings.
SunUpdateToAllClients();
m_log.DebugFormat("[SUN]: PosTime : {0}", PosTime.ToString());
}
}
#endregion
private void SunUpdateToAllClients()
{
List<ScenePresence> avatars = m_scene.GetAvatars();
foreach (ScenePresence avatar in avatars)
{
if (!(avatar.IsChildAgent || avatar.IsDeleted || avatar.IsInTransit))
{
SunToClient(avatar.ControllingClient);
}
}
}
#region ISunModule Members
public double GetSunParameter(string param)
{
switch (param.ToLower())
{
case "year_length":
return m_YearLengthDays;
case "day_length":
return m_DayLengthHours;
case "day_night_offset":
return m_HorizonShift;
case "day_time_sun_hour_scale":
return m_DayTimeSunHourScale;
case "update_interval":
return m_UpdateInterval;
default:
throw new Exception("Unknown sun parameter.");
}
}
public void SetSunParameter(string param, double value)
{
HandleSunConsoleCommand("sun", new string[] {param, value.ToString() });
}
public float GetCurrentSunHour()
{
float ticksleftover = CurrentTime % SecondsPerSunCycle;
return (24.0f * (ticksleftover / SecondsPerSunCycle));
}
#endregion
public void HandleSunConsoleCommand(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("[Sun]: Please change to a specific region in order to set Sun parameters.");
return;
}
if (m_scene.ConsoleScene() != m_scene)
{
m_log.InfoFormat("[Sun]: Console Scene is not my scene.");
return;
}
m_log.InfoFormat("[Sun]: Processing command.");
foreach (string output in ParseCmdParams(cmdparams))
{
m_log.Info("[SUN] " + output);
}
}
private Dictionary<string, string> GetParamList()
{
Dictionary<string, string> Params = new Dictionary<string, string>();
Params.Add("year_length", "number of days to a year");
Params.Add("day_length", "number of seconds to a day");
Params.Add("day_night_offset", "induces a horizon shift");
Params.Add("update_interval", "how often to update the sun's position in frames");
Params.Add("day_time_sun_hour_scale", "scales day light vs nite hours to change day/night ratio");
return Params;
}
private List<string> ParseCmdParams(string[] args)
{
List<string> Output = new List<string>();
if ((args.Length == 1) || (args[1].ToLower() == "help") || (args[1].ToLower() == "list"))
{
Output.Add("The following parameters can be changed or viewed:");
foreach (KeyValuePair<string, string> kvp in GetParamList())
{
Output.Add(String.Format("{0} - {1}",kvp.Key, kvp.Value));
}
return Output;
}
if (args.Length == 2)
{
try
{
double value = GetSunParameter(args[1]);
Output.Add(String.Format("Parameter {0} is {1}.", args[1], value.ToString()));
}
catch (Exception)
{
Output.Add(String.Format("Unknown parameter {0}.", args[1]));
}
}
else if (args.Length == 3)
{
float value = 0.0f;
if (!float.TryParse(args[2], out value))
{
Output.Add(String.Format("The parameter value {0} is not a valid number.", args[2]));
}
switch (args[1].ToLower())
{
case "year_length":
m_YearLengthDays = (int)value;
break;
case "day_length":
m_DayLengthHours = value;
break;
case "day_night_offset":
m_HorizonShift = value;
break;
case "day_time_sun_hour_scale":
m_DayTimeSunHourScale = value;
break;
case "update_interval":
m_UpdateInterval = (int)value;
break;
default:
Output.Add(String.Format("Unknown parameter {0}.", args[1]));
return Output;
}
Output.Add(String.Format("Parameter {0} set to {1}.", args[1], value.ToString()));
// Generate shared values
GenSunPos();
// When sun settings are updated, we should update all clients with new settings.
SunUpdateToAllClients();
}
return Output;
}
}
}
| |
using System.Diagnostics;
using System;
using System.Management;
using System.Collections;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Web.UI.Design;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace ACSGhana.Web.Framework
{
namespace UI
{
namespace Controls
{
/// <summary>
/// A simple control that shows page numbers
/// </summary>
/// <remarks>You feed it the number of pages, how many pages to show and it will show links for that many pages along with
/// next and previous buttons as applicable. For example with a high count and current page being 5 and 5 displayed pages, it will show
/// first prev 3, 4, 5, 6, 7 next last </remarks>
public class PageNumberer : WebControl, IPostBackEventHandler
{
private int m_SelectedPage;
private int m_Count;
private int m_displayedPages;
/// <summary>
/// The currently selected page
/// </summary>
/// <value>The page number, with 1 being the first page</value>
/// <remarks></remarks>
public int SelectedPage
{
get
{
if (m_SelectedPage == 0)
{
object o = ViewState["SelectedPage"];
if (o == null)
{
m_SelectedPage = 1;
}
else
{
m_SelectedPage = System.Convert.ToInt32(o);
}
}
return m_SelectedPage;
}
set
{
ViewState["SelectedPage"] = value;
m_SelectedPage = value;
}
}
/// <summary>
/// The total number of pages
/// </summary>
public int Count
{
get
{
if (m_Count == 0)
{
object o = ViewState["Count"];
if (o == null)
{
m_Count = 1;
}
else
{
m_Count = System.Convert.ToInt32(o);
}
}
return m_Count;
}
set
{
ViewState["Count"] = value;
m_Count = value;
}
}
/// <summary>
/// How many pages to show in the display
/// </summary>
/// <value></value>
/// <remarks></remarks>
public int DisplayedPages
{
get
{
if (m_displayedPages == 0)
{
object o = ViewState["DisplayedPages"];
if (o == null)
{
m_displayedPages = 1;
}
else
{
m_displayedPages = System.Convert.ToInt32(o);
}
}
return m_displayedPages;
}
set
{
ViewState["DisplayedPages"] = value;
m_displayedPages = value;
}
}
protected override System.Web.UI.HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Div;
}
}
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
int prevListCount;
int nextListCount;
int startPage;
int endPage;
prevListCount = Math.Abs((m_displayedPages - 1) / 2);
if (m_SelectedPage <= prevListCount)
{
prevListCount = m_SelectedPage - 1;
}
nextListCount = m_displayedPages - prevListCount - 1;
if (m_SelectedPage + nextListCount > m_Count)
{
nextListCount = m_Count - m_SelectedPage;
}
startPage = m_SelectedPage - prevListCount;
endPage = m_SelectedPage + nextListCount;
if (startPage > 1)
{
renderItem(writer, "« First", 1);
}
if (SelectedPage > 1)
{
renderItem(writer, "< Prev", SelectedPage - 1);
}
for (int count = startPage; count <= endPage; count++)
{
string label;
if (count != endPage)
{
label = count.ToString() + ",";
}
else
{
label = count.ToString();
}
if (count == m_SelectedPage)
{
renderItem(writer, label, 0);
}
else
{
renderItem(writer, label, count);
}
}
if (SelectedPage < m_Count)
{
renderItem(writer, "Next >", SelectedPage + 1);
}
if (endPage < m_Count)
{
renderItem(writer, "Last »", m_Count);
}
}
public void renderItem(HtmlTextWriter writer, string text, int pageNum)
{
writer.RenderBeginTag(HtmlTextWriterTag.Span);
if (pageNum != 0)
{
writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ClientScript.GetPostBackClientHyperlink(this, pageNum.ToString()));
writer.RenderBeginTag(HtmlTextWriterTag.A);
}
writer.Write(text);
if (pageNum != 0)
{
writer.RenderEndTag();
}
writer.RenderEndTag();
}
/// <summary>
/// Event is fired when user clicks on a different page number.
/// </summary>
/// <remarks></remarks>
private EventHandler SelectedPageChangedEvent;
public event EventHandler SelectedPageChanged
{
add
{
SelectedPageChangedEvent = (EventHandler) System.Delegate.Combine(SelectedPageChangedEvent, value);
}
remove
{
SelectedPageChangedEvent = (EventHandler) System.Delegate.Remove(SelectedPageChangedEvent, value);
}
}
public void RaisePostBackEvent(string eventArgument)
{
int newPage;
if (int.TryParse(eventArgument, ref newPage))
{
this.SelectedPage = newPage;
OnSelectedPageChanged(EventArgs.Empty);
}
}
protected virtual void OnSelectedPageChanged(EventArgs e)
{
if (SelectedPageChangedEvent != null)
SelectedPageChangedEvent(this, e);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 XorInt32()
{
var test = new SimpleBinaryOpTest__XorInt32();
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__XorInt32
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int32);
private const int Op2ElementCount = VectorSize / sizeof(Int32);
private const int RetElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable;
static SimpleBinaryOpTest__XorInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__XorInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Xor(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Xor(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Xor(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_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.Xor), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorInt32();
var result = Sse2.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Xor(_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<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, 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 = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
if ((int)(left[0] ^ right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(left[i] ^ right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Xor)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using NUnit.Framework;
using strange.framework.api;
using strange.framework.impl;
namespace strange.unittests
{
[TestFixture()]
public class TestBinder
{
IBinder binder;
[SetUp]
public void SetUp()
{
binder = new Binder ();
}
[Test]
public void TestBindType ()
{
binder.Bind<InjectableSuperClass> ().To<InjectableDerivedClass> ();
IBinding binding = binder.GetBinding<InjectableSuperClass> ();
Assert.IsNotNull (binding);
Assert.That (binding.key == typeof(InjectableSuperClass));
Assert.That (binding.key != typeof(InjectableDerivedClass));
Assert.That (binding.value != typeof(InjectableSuperClass));
Assert.That ((binding.value as object[])[0] == typeof(InjectableDerivedClass));
}
[Test]
public void TestBindValue ()
{
object testKeyValue = new MarkerClass ();
binder.Bind(testKeyValue).To<InjectableDerivedClass> ();
IBinding binding = binder.GetBinding (testKeyValue);
Assert.IsNotNull (binding);
Assert.That (binding.key == testKeyValue);
Assert.That ((binding.value as object[])[0] == typeof(InjectableDerivedClass));
}
[Test]
public void TestNamedBinding ()
{
binder.Bind<InjectableSuperClass>().To<InjectableDerivedClass> ();
binder.Bind<InjectableSuperClass>().To<InjectableDerivedClass> ().ToName<MarkerClass>();
binder.Bind<InjectableSuperClass>().To<InjectableDerivedClass> ().ToName("strange");
//Test the unnamed binding
IBinding unnamedBinding = binder.GetBinding<InjectableSuperClass> ();
Assert.IsNotNull (unnamedBinding);
Assert.That (unnamedBinding.key == typeof(InjectableSuperClass));
Type unnamedBindingValue = (unnamedBinding.value as object[]) [0] as Type;
Assert.That (unnamedBindingValue == typeof(InjectableDerivedClass));
Assert.That (unnamedBinding.name != typeof(MarkerClass));
//Test the binding named by type
IBinding namedBinding = binder.GetBinding<InjectableSuperClass> (typeof(MarkerClass));
Assert.IsNotNull (namedBinding);
Assert.That (namedBinding.key == typeof(InjectableSuperClass));
Type namedBindingValue = (namedBinding.value as object[]) [0] as Type;
Assert.That (namedBindingValue == typeof(InjectableDerivedClass));
Assert.That (namedBinding.name == typeof(MarkerClass));
//Test the binding named by string
IBinding namedBinding2 = binder.GetBinding<InjectableSuperClass> ("strange");
Assert.IsNotNull (namedBinding2);
Assert.That (namedBinding2.key == typeof(InjectableSuperClass));
Type namedBinding2Value = (namedBinding2.value as object[]) [0] as Type;
Assert.That (namedBinding2Value == typeof(InjectableDerivedClass));
Assert.That ((string)namedBinding2.name == "strange");
}
[Test]
public void TestRemoveBindingByKey ()
{
binder.Bind<InjectableSuperClass>().To<InjectableDerivedClass> ();
binder.Bind<InjectableSuperClass>().To<InjectableDerivedClass> ().ToName<MarkerClass>();
//Test the unnamed binding
IBinding unnamedBinding = binder.GetBinding<InjectableSuperClass> ();
Assert.IsNotNull (unnamedBinding);
Assert.That (unnamedBinding.key == typeof(InjectableSuperClass));
Type unnamedBindingValue = (unnamedBinding.value as object[]) [0] as Type;
Assert.That (unnamedBindingValue == typeof(InjectableDerivedClass));
Assert.That (unnamedBinding.name != typeof(MarkerClass));
//Test the binding named by type
IBinding namedBinding = binder.GetBinding<InjectableSuperClass> (typeof(MarkerClass));
Assert.IsNotNull (namedBinding);
Assert.That (namedBinding.key == typeof(InjectableSuperClass));
Type namedBindingValue = (namedBinding.value as object[]) [0] as Type;
Assert.That (namedBindingValue == typeof(InjectableDerivedClass));
Assert.That (namedBinding.name == typeof(MarkerClass));
//Remove the first binding
binder.Unbind<InjectableSuperClass> ();
IBinding removedUnnamedBinding = binder.GetBinding<InjectableSuperClass> ();
Assert.IsNull (removedUnnamedBinding);
//Ensure the named binding still exists
IBinding unremovedNamedBinding = binder.GetBinding<InjectableSuperClass> (typeof(MarkerClass));
Assert.IsNotNull (unremovedNamedBinding);
}
[Test]
public void TestRemoveBindingByKeyAndName ()
{
binder.Bind<InjectableSuperClass>().To<InjectableDerivedClass> ();
IBinding namedBinding = binder.Bind<InjectableSuperClass>().To<InjectableDerivedClass> ().ToName<MarkerClass>();
//Remove the first binding
binder.Unbind (namedBinding.key, namedBinding.name);
IBinding removedNamedBinding = binder.GetBinding<InjectableSuperClass> (typeof(MarkerClass));
Assert.IsNull (removedNamedBinding);
//Ensure the unnamed binding still exists
IBinding unremovedUnnamedBinding = binder.GetBinding<InjectableSuperClass> ();
Assert.IsNotNull (unremovedUnnamedBinding);
}
[Test]
public void TestRemoveBindingByBinding ()
{
IBinding unnamedBinding = binder.Bind<InjectableSuperClass>().To<InjectableDerivedClass> ();
binder.Bind<InjectableSuperClass>().To<InjectableDerivedClass> ().ToName<MarkerClass>();
//Remove the first binding
binder.Unbind (unnamedBinding);
IBinding removedUnnamedBinding = binder.GetBinding<InjectableSuperClass> ();
Assert.IsNull (removedUnnamedBinding);
//Ensure the named binding still exists
IBinding unremovedNamedBinding = binder.GetBinding<InjectableSuperClass> (typeof(MarkerClass));
Assert.IsNotNull (unremovedNamedBinding);
}
[Test]
public void TestRemoveValueFromBinding()
{
IBinding binding = binder.Bind<float> ().To (1).To (2).To (3);
object[] before = binding.value as object[];
Assert.AreEqual (3, before.Length);
binder.RemoveValue (binding, 2);
object[] after = binding.value as object[];
Assert.AreEqual (2, after.Length);
Assert.AreEqual (1, after[0]);
Assert.AreEqual (3, after[1]);
}
[Test]
public void TestNullValueInBinding()
{
IBinding binding = binder.Bind<float> ().To (1).To (2).To (3);
object[] before = binding.value as object[];
Assert.AreEqual (3, before.Length);
binder.RemoveValue (binding, before);
object[] after = binding.value as object[];
Assert.IsNull (after);
}
[Test]
public void TestConflictWithoutWeak()
{
binder.Bind<ISimpleInterface>().To<SimpleInterfaceImplementer>();
TestDelegate testDelegate = delegate
{
binder.Bind<ISimpleInterface>().To<SimpleInterfaceImplementerTwo>();
object instance = binder.GetBinding<ISimpleInterface>().value;
Assert.IsNotNull(instance);
};
BinderException ex = Assert.Throws<BinderException>(testDelegate); //Because we have a conflict between the two above bindings
Assert.AreEqual (BinderExceptionType.CONFLICT_IN_BINDER, ex.type);
}
[Test]
public void TestWeakBindings()
{
SimpleInterfaceImplementer one = new SimpleInterfaceImplementer();
SimpleInterfaceImplementerTwo two = new SimpleInterfaceImplementerTwo();
IBinding binding = binder.Bind<ISimpleInterface>().To(one).Weak();
binding.valueConstraint = BindingConstraintType.ONE;
TestDelegate testDelegate = delegate
{
binder.Bind<ISimpleInterface>().To(two).valueConstraint = BindingConstraintType.ONE;
IBinding retrievedBinding = binder.GetBinding<ISimpleInterface>();
Assert.NotNull(retrievedBinding);
Assert.NotNull(retrievedBinding.value);
Console.WriteLine(retrievedBinding.value);
Assert.AreEqual(retrievedBinding.value, two);
};
Assert.DoesNotThrow(testDelegate); //Second binding "two" overrides weak binding "one"
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
namespace Northwind.CSLA.Library
{
/// <summary>
/// OrderDetailInfoList Generated by MyGeneration using the CSLA Object Mapping template
/// </summary>
[Serializable()]
[TypeConverter(typeof(OrderDetailInfoListConverter))]
public partial class OrderDetailInfoList : ReadOnlyListBase<OrderDetailInfoList, OrderDetailInfo>, ICustomTypeDescriptor, IDisposable
{
#region Business Methods
internal new IList<OrderDetailInfo> Items
{ get { return base.Items; } }
public void AddEvents()
{
foreach (OrderDetailInfo tmp in this)
{
tmp.Changed += new OrderDetailInfoEvent(tmp_Changed);
}
}
void tmp_Changed(object sender)
{
for (int i = 0; i < Count; i++)
{
if (base[i] == sender)
this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i));
}
}
public void Dispose()
{
foreach (OrderDetailInfo tmp in this)
{
tmp.Changed -= new OrderDetailInfoEvent(tmp_Changed);
}
}
#endregion
#region Factory Methods
/// <summary>
/// Return a list of all projects.
/// </summary>
public static OrderDetailInfoList Get()
{
try
{
OrderDetailInfoList tmp = DataPortal.Fetch<OrderDetailInfoList>();
OrderDetailInfo.AddList(tmp);
tmp.AddEvents();
return tmp;
}
catch (Exception ex)
{
throw new DbCslaException("Error on OrderDetailInfoList.Get", ex);
}
}
// TODO: Add alternative gets -
//public static OrderDetailInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<OrderDetailInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on OrderDetailInfoList.Get", ex);
// }
//}
public static OrderDetailInfoList GetByOrderID(int orderID)
{
try
{
OrderDetailInfoList tmp = DataPortal.Fetch<OrderDetailInfoList>(new OrderIDCriteria(orderID));
OrderDetailInfo.AddList(tmp);
tmp.AddEvents();
return tmp;
}
catch (Exception ex)
{
throw new DbCslaException("Error on OrderDetailInfoList.GetByOrderID", ex);
}
}
public static OrderDetailInfoList GetByProductID(int productID)
{
try
{
OrderDetailInfoList tmp = DataPortal.Fetch<OrderDetailInfoList>(new ProductIDCriteria(productID));
OrderDetailInfo.AddList(tmp);
tmp.AddEvents();
return tmp;
}
catch (Exception ex)
{
throw new DbCslaException("Error on OrderDetailInfoList.GetByProductID", ex);
}
}
private OrderDetailInfoList()
{ /* require use of factory methods */ }
#endregion
#region Data Access Portal
private void DataPortal_Fetch()
{
this.RaiseListChangedEvents = false;
Database.LogInfo("OrderDetailInfoList.DataPortal_Fetch", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "getOrderDetails";
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
IsReadOnly = false;
while (dr.Read()) this.Add(new OrderDetailInfo(dr));
IsReadOnly = true;
}
}
}
}
catch (Exception ex)
{
Database.LogException("OrderDetailInfoList.DataPortal_Fetch", ex);
throw new DbCslaException("OrderDetailInfoList.DataPortal_Fetch", ex);
}
this.RaiseListChangedEvents = true;
}
[Serializable()]
private class OrderIDCriteria
{
public OrderIDCriteria(int orderID)
{
_OrderID = orderID;
}
private int _OrderID;
public int OrderID
{
get { return _OrderID; }
set { _OrderID = value; }
}
}
private void DataPortal_Fetch(OrderIDCriteria criteria)
{
this.RaiseListChangedEvents = false;
Database.LogInfo("OrderDetailInfoList.DataPortal_FetchOrderID", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "getOrderDetailsByOrderID";
cm.Parameters.AddWithValue("@OrderID", criteria.OrderID);
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
IsReadOnly = false;
while (dr.Read()) this.Add(new OrderDetailInfo(dr));
IsReadOnly = true;
}
}
}
}
catch (Exception ex)
{
Database.LogException("OrderDetailInfoList.DataPortal_FetchOrderID", ex);
throw new DbCslaException("OrderDetailInfoList.DataPortal_Fetch", ex);
}
this.RaiseListChangedEvents = true;
}
[Serializable()]
private class ProductIDCriteria
{
public ProductIDCriteria(int productID)
{
_ProductID = productID;
}
private int _ProductID;
public int ProductID
{
get { return _ProductID; }
set { _ProductID = value; }
}
}
private void DataPortal_Fetch(ProductIDCriteria criteria)
{
this.RaiseListChangedEvents = false;
Database.LogInfo("OrderDetailInfoList.DataPortal_FetchProductID", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "getOrderDetailsByProductID";
cm.Parameters.AddWithValue("@ProductID", criteria.ProductID);
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
IsReadOnly = false;
while (dr.Read()) this.Add(new OrderDetailInfo(dr));
IsReadOnly = true;
}
}
}
}
catch (Exception ex)
{
Database.LogException("OrderDetailInfoList.DataPortal_FetchProductID", ex);
throw new DbCslaException("OrderDetailInfoList.DataPortal_Fetch", ex);
}
this.RaiseListChangedEvents = true;
}
#endregion
#region ICustomTypeDescriptor impl
public String GetClassName()
{ return TypeDescriptor.GetClassName(this, true); }
public AttributeCollection GetAttributes()
{ return TypeDescriptor.GetAttributes(this, true); }
public String GetComponentName()
{ return TypeDescriptor.GetComponentName(this, true); }
public TypeConverter GetConverter()
{ return TypeDescriptor.GetConverter(this, true); }
public EventDescriptor GetDefaultEvent()
{ return TypeDescriptor.GetDefaultEvent(this, true); }
public PropertyDescriptor GetDefaultProperty()
{ return TypeDescriptor.GetDefaultProperty(this, true); }
public object GetEditor(Type editorBaseType)
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); }
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{ return TypeDescriptor.GetEvents(this, attributes, true); }
public EventDescriptorCollection GetEvents()
{ return TypeDescriptor.GetEvents(this, true); }
public object GetPropertyOwner(PropertyDescriptor pd)
{ return this; }
/// <summary>
/// Called to get the properties of this type. Returns properties with certain
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{
// Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list
for (int i = 0; i < this.Items.Count; i++)
{
// Create a property descriptor for the item and add to the property descriptor collection
OrderDetailInfoListPropertyDescriptor pd = new OrderDetailInfoListPropertyDescriptor(this, i);
pds.Add(pd);
}
// return the property descriptor collection
return pds;
}
#endregion
} // Class
#region Property Descriptor
/// <summary>
/// Summary description for CollectionPropertyDescriptor.
/// </summary>
public partial class OrderDetailInfoListPropertyDescriptor : vlnListPropertyDescriptor
{
private OrderDetailInfo Item { get { return (OrderDetailInfo) _Item;} }
public OrderDetailInfoListPropertyDescriptor(OrderDetailInfoList collection, int index):base(collection, index){;}
}
#endregion
#region Converter
internal class OrderDetailInfoListConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is OrderDetailInfoList)
{
// Return department and department role separated by comma.
return ((OrderDetailInfoList) value).Items.Count.ToString() + " OrderDetails";
}
return base.ConvertTo(context, culture, value, destType);
}
}
#endregion
} // Namespace
| |
//! \file ImageSPD.cs
//! \date Thu Oct 08 16:25:55 2015
//! \brief TopCat compressed image.
//
// Copyright (C) 2015-2018 by morkt
//
// 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 GameRes.Utility;
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace GameRes.Formats.TopCat
{
internal class SpdMetaData : ImageMetaData
{
public Compression Method;
public uint UnpackedSize;
public byte SpdType;
}
internal enum Compression
{
LzRle = 0,
Lz = 1,
LzRleAlpha = 2,
LzRle2 = 0x100,
Spdc = 0x101,
LzRleAlpha2 = 0x102,
Jpeg = 0x103,
}
[Export(typeof(ImageFormat))]
public class SpdFormat : ImageFormat
{
public override string Tag { get { return "SPD"; } }
public override string Description { get { return "TopCat compressed image format"; } }
public override uint Signature { get { return 0x43445053; } } // 'SPDC'
public SpdFormat ()
{
Signatures = new uint[] { 0x43445053, 0x38445053, 0x37445053 }; // 'SPD8', 'SPD7'
}
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = stream.ReadHeader (0x14).ToArray();
unsafe
{
fixed (byte* raw = header)
{
uint* dw = (uint*)raw;
dw[3] -= (dw[4] >> 2) & 0xF731;
dw[2] -= (dw[4] << 2) & 0x137F;
dw[1] -= (dw[4] << 4) & 0xFFFF;
return new SpdMetaData
{
Width = dw[2],
Height = dw[3],
BPP = (int)(dw[1] >> 16),
Method = (Compression)(dw[1] & 0xFFFF),
UnpackedSize = dw[4],
SpdType = header[3],
};
}
}
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
var meta = (SpdMetaData)info;
if (Compression.Jpeg == meta.Method)
return ReadJpeg (stream.AsStream, meta);
using (var reader = new SpdReader (stream.AsStream, meta))
{
reader.Unpack();
return ImageData.Create (info, reader.Format, null, reader.Data);
}
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("SpdFormat.Write not implemented");
}
private ImageData ReadJpeg (Stream file, SpdMetaData info)
{
file.Position = 0x18;
var header = new byte[0x3C];
if (header.Length != file.Read (header, 0, header.Length))
throw new EndOfStreamException();
unsafe
{
fixed (byte* raw = header)
{
uint* dw = (uint*)raw;
for (int i = 0; i < 0xF; ++i)
dw[i] += 0xA8961EF1;
}
}
using (var rest = new StreamRegion (file, file.Position, true))
using (var jpeg = new PrefixStream (header, rest))
{
var decoder = new JpegBitmapDecoder (jpeg,
BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
var frame = decoder.Frames[0];
frame.Freeze();
return new ImageData (frame, info);
}
}
}
internal sealed class SpdReader : IDisposable
{
Stream m_input;
byte[] m_output;
SpdMetaData m_info;
public PixelFormat Format { get; private set; }
public byte[] Data { get { return m_output; } }
public SpdReader (Stream input, SpdMetaData info)
{
m_input = input;
m_output = new byte[info.UnpackedSize];
m_info = info;
if (24 == info.BPP)
Format = PixelFormats.Bgr24;
else if (32 == info.BPP)
Format = PixelFormats.Bgra32;
else
throw new NotSupportedException ("Not supported SPD image bitdepth");
}
public void Unpack ()
{
m_input.Position = 0x14;
switch (m_info.Method)
{
case Compression.Spdc:
UnpackSpdc();
break;
case Compression.Lz:
UnpackLz();
break;
case Compression.LzRle:
case Compression.LzRle2:
case Compression.LzRleAlpha:
case Compression.LzRleAlpha2:
{
UnpackLz();
var rgb = new byte[m_info.Height * m_info.Width * 4];
if (Compression.LzRle == m_info.Method || Compression.LzRle2 == m_info.Method)
{
if ('7' == m_info.SpdType)
UnpackRle (rgb, 4, 0, 8);
else
UnpackRle (rgb, 0, 8, 12);
}
else if ('8' == m_info.SpdType)
UnpackSpdAlpha (rgb, 8);
else if ('7' == m_info.SpdType)
UnpackSpdAlpha (rgb, 4);
else
UnpackRleAlpha (rgb);
m_output = rgb;
Format = PixelFormats.Bgra32;
break;
}
default:
throw new NotImplementedException ("SPD compression method not implemented");
}
}
void UnpackLz ()
{
int dst = 0;
while (dst < m_output.Length)
{
int ctl = m_input.ReadByte();
if (-1 == ctl)
break;
for (int bit = 1; bit != 0x100 && dst < m_output.Length; bit <<= 1)
{
if (0 != (ctl & bit))
{
int b = m_input.ReadByte();
if (-1 == b)
return;
m_output[dst++] = (byte)b;
}
else
{
int lo = m_input.ReadByte();
if (-1 == lo)
return;
int hi = m_input.ReadByte();
if (-1 == hi)
return;
int src = lo >> 4 | hi << 4;
int count = Math.Min (3 + (lo & 0xF), m_output.Length - dst);
Binary.CopyOverlapped (m_output, dst-src, dst, count);
dst += count;
}
}
}
}
void UnpackRle (byte[] rgb, int rgb_pos, int skip_pos, int ctl_src)
{
int rgb_src = LittleEndian.ToInt32 (m_output, rgb_pos);
bool skip = 0 == LittleEndian.ToInt32 (m_output, skip_pos);
int dst = 0;
while (dst < rgb.Length)
{
int n = LittleEndian.ToInt32 (m_output, ctl_src);
ctl_src += 4;
if (skip)
{
dst += n * 4;
}
else
{
for (; n != 0; --n)
{
rgb[dst++] = m_output[rgb_src++];
rgb[dst++] = m_output[rgb_src++];
rgb[dst++] = m_output[rgb_src++];
rgb[dst++] = 0xFF;
}
}
skip = !skip;
}
}
void UnpackRleAlpha (byte[] rgb)
{
int rgb_src = LittleEndian.ToInt32 (m_output, 0);
int ctl_src = 8;
int dst = 0;
while (dst < rgb.Length)
{
int count = LittleEndian.ToUInt16 (m_output, ctl_src);
ctl_src += 2;
int control = count >> 14;
count &= 0x3FFF;
if (0 == control)
{
dst += 4 * count;
}
else
{
for (; count != 0; --count)
{
rgb[dst++] = m_output[rgb_src++];
rgb[dst++] = m_output[rgb_src++];
rgb[dst++] = m_output[rgb_src++];
if (1 == control)
rgb[dst++] = 0xFF;
else
rgb[dst++] = m_output[ctl_src++];
}
}
}
}
void UnpackSpdAlpha (byte[] rgb, int ctl_src)
{
int rgb_src = LittleEndian.ToInt32 (m_output, 0);
int dst = 0;
while (dst < rgb.Length)
{
int control = m_output[ctl_src++];
if (0 == control)
{
int count = m_output[ctl_src++] + 1;
dst += 4 * count;
}
else if (1 == control)
{
int count = m_output[ctl_src++] + 1;
for (int i = 0; i < count; ++i)
{
rgb[dst++] = m_output[rgb_src++];
rgb[dst++] = m_output[rgb_src++];
rgb[dst++] = m_output[rgb_src++];
rgb[dst++] = 0xFF;
}
}
else
{
rgb[dst++] = m_output[rgb_src++];
rgb[dst++] = m_output[rgb_src++];
rgb[dst++] = m_output[rgb_src++];
rgb[dst++] = (byte)-control;
}
}
}
void UnpackSpdc ()
{
int pixel_size = m_info.BPP / 8;
int stride = pixel_size * (int)m_info.Width;
int[] offset_table = new int[28];
int i = 0;
while (i < 16)
offset_table[i++] = -pixel_size;
while (i < 24)
offset_table[i++] = -stride;
while (i < 26)
offset_table[i++] = -stride - pixel_size;
while (i < 28)
offset_table[i++] = -stride + pixel_size;
int dst = 0;
for (i = 0; i < pixel_size; ++i)
m_output[dst++] = (byte)GetBits (8);
while (dst < m_output.Length)
{
int x = GetBits (5, true);
if (x > 0x1B)
{
GetBits (3);
m_output[dst+2] = (byte)GetBits (8);
m_output[dst+1] = (byte)GetBits (8);
m_output[dst] = (byte)GetBits (8);
}
else
{
int src = dst + offset_table[x];
m_output[dst] = m_output[src];
m_output[dst+1] = m_output[src+1];
m_output[dst+2] = m_output[src+2];
GetBits (DiffPrefixTable[x] >> 1);
if (0 != (DiffPrefixTable[x] & 1))
{
int i1 = GetBits (8, true);
int i2 = GetBits (8 + DiffLengthsTable[i1], true) & 0xFF;
int i3 = GetBits (8 + DiffLengthsTable[i1] + DiffLengthsTable[i2], true) & 0xFF;
m_output[dst] += DiffTable[i1];
m_output[dst+1] += (byte)(DiffTable[i1] + DiffTable[i2]);
m_output[dst+2] += (byte)(DiffTable[i1] + DiffTable[i3]);
GetBits (DiffLengthsTable[i1] + DiffLengthsTable[i2] + DiffLengthsTable[i3]);
}
}
dst += pixel_size;
}
}
int m_bits = 0;
int m_cached_bits = 0;
// FIXME: add 'peek' feature to MsbBitStream class
int GetBits (int count, bool peek = false)
{
while (m_cached_bits < count)
{
int b = m_input.ReadByte();
if (-1 == b)
return 0;
m_bits = (m_bits << 8) | b;
m_cached_bits += 8;
}
int mask = (1 << count) - 1;
int left_bits = m_cached_bits - count;
if (!peek)
m_cached_bits = left_bits;
return (m_bits >> left_bits) & mask;
}
static readonly byte[] DiffPrefixTable = {
0x4, 0x4, 0x4, 0x4, 0x4, 0x4, 0x4, 0x4,
0x5, 0x5, 0x5, 0x5, 0x5, 0x5, 0x5, 0x5,
0x6, 0x6, 0x6, 0x6, 0x7, 0x7, 0x7, 0x7,
0xA, 0xB, 0xA, 0xB,
};
static readonly byte[] DiffLengthsTable = {
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
};
static readonly byte[] DiffTable = {
0x10, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0xF1, 0xF0,
0x08, 0x08, 0x07, 0x07, 0x06, 0x06, 0x05, 0x05, 0xFB, 0xFB, 0xFA, 0xFA, 0xF9, 0xF9, 0xF8, 0xF8,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE,
0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE,
};
#region IDisposable Members
bool _disposed = false;
public void Dispose ()
{
if (!_disposed)
{
_disposed = true;
}
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests
{
using System;
using System.Collections.Generic;
using Xunit;
public class LogLevelTests : NLogTestBase
{
[Fact]
[Trait("Component", "Core")]
public void OrdinalTest()
{
Assert.True(LogLevel.Trace < LogLevel.Debug);
Assert.True(LogLevel.Debug < LogLevel.Info);
Assert.True(LogLevel.Info < LogLevel.Warn);
Assert.True(LogLevel.Warn < LogLevel.Error);
Assert.True(LogLevel.Error < LogLevel.Fatal);
Assert.True(LogLevel.Fatal < LogLevel.Off);
Assert.False(LogLevel.Trace > LogLevel.Debug);
Assert.False(LogLevel.Debug > LogLevel.Info);
Assert.False(LogLevel.Info > LogLevel.Warn);
Assert.False(LogLevel.Warn > LogLevel.Error);
Assert.False(LogLevel.Error > LogLevel.Fatal);
Assert.False(LogLevel.Fatal > LogLevel.Off);
Assert.True(LogLevel.Trace <= LogLevel.Debug);
Assert.True(LogLevel.Debug <= LogLevel.Info);
Assert.True(LogLevel.Info <= LogLevel.Warn);
Assert.True(LogLevel.Warn <= LogLevel.Error);
Assert.True(LogLevel.Error <= LogLevel.Fatal);
Assert.True(LogLevel.Fatal <= LogLevel.Off);
Assert.False(LogLevel.Trace >= LogLevel.Debug);
Assert.False(LogLevel.Debug >= LogLevel.Info);
Assert.False(LogLevel.Info >= LogLevel.Warn);
Assert.False(LogLevel.Warn >= LogLevel.Error);
Assert.False(LogLevel.Error >= LogLevel.Fatal);
Assert.False(LogLevel.Fatal >= LogLevel.Off);
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelEqualityTest()
{
LogLevel levelTrace = LogLevel.Trace;
LogLevel levelInfo = LogLevel.Info;
Assert.True(LogLevel.Trace == levelTrace);
Assert.True(LogLevel.Info == levelInfo);
Assert.False(LogLevel.Trace == levelInfo);
Assert.False(LogLevel.Trace != levelTrace);
Assert.False(LogLevel.Info != levelInfo);
Assert.True(LogLevel.Trace != levelInfo);
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelFromOrdinal_InputInRange_ExpectValidLevel()
{
Assert.Same(LogLevel.FromOrdinal(0), LogLevel.Trace);
Assert.Same(LogLevel.FromOrdinal(1), LogLevel.Debug);
Assert.Same(LogLevel.FromOrdinal(2), LogLevel.Info);
Assert.Same(LogLevel.FromOrdinal(3), LogLevel.Warn);
Assert.Same(LogLevel.FromOrdinal(4), LogLevel.Error);
Assert.Same(LogLevel.FromOrdinal(5), LogLevel.Fatal);
Assert.Same(LogLevel.FromOrdinal(6), LogLevel.Off);
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelFromOrdinal_InputOutOfRange_ExpectException()
{
Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(100));
// Boundary conditions.
Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(-1));
Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(7));
}
[Fact]
[Trait("Component", "Core")]
public void FromStringTest()
{
Assert.Same(LogLevel.FromString("trace"), LogLevel.Trace);
Assert.Same(LogLevel.FromString("debug"), LogLevel.Debug);
Assert.Same(LogLevel.FromString("info"), LogLevel.Info);
Assert.Same(LogLevel.FromString("warn"), LogLevel.Warn);
Assert.Same(LogLevel.FromString("error"), LogLevel.Error);
Assert.Same(LogLevel.FromString("fatal"), LogLevel.Fatal);
Assert.Same(LogLevel.FromString("off"), LogLevel.Off);
Assert.Same(LogLevel.FromString("Trace"), LogLevel.Trace);
Assert.Same(LogLevel.FromString("Debug"), LogLevel.Debug);
Assert.Same(LogLevel.FromString("Info"), LogLevel.Info);
Assert.Same(LogLevel.FromString("Warn"), LogLevel.Warn);
Assert.Same(LogLevel.FromString("Error"), LogLevel.Error);
Assert.Same(LogLevel.FromString("Fatal"), LogLevel.Fatal);
Assert.Same(LogLevel.FromString("Off"), LogLevel.Off);
Assert.Same(LogLevel.FromString("TracE"), LogLevel.Trace);
Assert.Same(LogLevel.FromString("DebuG"), LogLevel.Debug);
Assert.Same(LogLevel.FromString("InfO"), LogLevel.Info);
Assert.Same(LogLevel.FromString("WarN"), LogLevel.Warn);
Assert.Same(LogLevel.FromString("ErroR"), LogLevel.Error);
Assert.Same(LogLevel.FromString("FataL"), LogLevel.Fatal);
Assert.Same(LogLevel.FromString("TRACE"), LogLevel.Trace);
Assert.Same(LogLevel.FromString("DEBUG"), LogLevel.Debug);
Assert.Same(LogLevel.FromString("INFO"), LogLevel.Info);
Assert.Same(LogLevel.FromString("WARN"), LogLevel.Warn);
Assert.Same(LogLevel.FromString("ERROR"), LogLevel.Error);
Assert.Same(LogLevel.FromString("FATAL"), LogLevel.Fatal);
}
[Fact]
[Trait("Component", "Core")]
public void FromStringFailingTest()
{
Assert.Throws<ArgumentException>(() => LogLevel.FromString("zzz"));
Assert.Throws<ArgumentNullException>(() => LogLevel.FromString(null));
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelNullComparison()
{
LogLevel level = LogLevel.Info;
Assert.False(level == null);
Assert.True(level != null);
Assert.False(null == level);
Assert.True(null != level);
level = null;
Assert.True(level == null);
Assert.False(level != null);
Assert.True(null == level);
Assert.False(null != level);
}
[Fact]
[Trait("Component", "Core")]
public void ToStringTest()
{
Assert.Equal("Trace", LogLevel.Trace.ToString());
Assert.Equal("Debug", LogLevel.Debug.ToString());
Assert.Equal("Info", LogLevel.Info.ToString());
Assert.Equal("Warn", LogLevel.Warn.ToString());
Assert.Equal("Error", LogLevel.Error.ToString());
Assert.Equal("Fatal", LogLevel.Fatal.ToString());
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelCompareTo_ValidLevels_ExpectIntValues()
{
LogLevel levelTrace = LogLevel.Trace;
LogLevel levelDebug = LogLevel.Debug;
LogLevel levelInfo = LogLevel.Info;
LogLevel levelWarn = LogLevel.Warn;
LogLevel levelError = LogLevel.Error;
LogLevel levelFatal = LogLevel.Fatal;
LogLevel levelOff = LogLevel.Off;
LogLevel levelMin = LogLevel.MinLevel;
LogLevel levelMax = LogLevel.MaxLevel;
Assert.Equal(LogLevel.Trace.CompareTo(levelDebug), -1);
Assert.Equal(LogLevel.Debug.CompareTo(levelInfo), -1);
Assert.Equal(LogLevel.Info.CompareTo(levelWarn), -1);
Assert.Equal(LogLevel.Warn.CompareTo(levelError), -1);
Assert.Equal(LogLevel.Error.CompareTo(levelFatal), -1);
Assert.Equal(LogLevel.Fatal.CompareTo(levelOff), -1);
Assert.Equal(1, LogLevel.Debug.CompareTo(levelTrace));
Assert.Equal(1, LogLevel.Info.CompareTo(levelDebug));
Assert.Equal(1, LogLevel.Warn.CompareTo(levelInfo));
Assert.Equal(1, LogLevel.Error.CompareTo(levelWarn));
Assert.Equal(1, LogLevel.Fatal.CompareTo(levelError));
Assert.Equal(1, LogLevel.Off.CompareTo(levelFatal));
Assert.Equal(0, LogLevel.Debug.CompareTo(levelDebug));
Assert.Equal(0, LogLevel.Info.CompareTo(levelInfo));
Assert.Equal(0, LogLevel.Warn.CompareTo(levelWarn));
Assert.Equal(0, LogLevel.Error.CompareTo(levelError));
Assert.Equal(0, LogLevel.Fatal.CompareTo(levelFatal));
Assert.Equal(0, LogLevel.Off.CompareTo(levelOff));
Assert.Equal(0, LogLevel.Trace.CompareTo(levelMin));
Assert.Equal(1, LogLevel.Debug.CompareTo(levelMin));
Assert.Equal(2, LogLevel.Info.CompareTo(levelMin));
Assert.Equal(3, LogLevel.Warn.CompareTo(levelMin));
Assert.Equal(4, LogLevel.Error.CompareTo(levelMin));
Assert.Equal(5, LogLevel.Fatal.CompareTo(levelMin));
Assert.Equal(6, LogLevel.Off.CompareTo(levelMin));
Assert.Equal(LogLevel.Trace.CompareTo(levelMax), -5);
Assert.Equal(LogLevel.Debug.CompareTo(levelMax), -4);
Assert.Equal(LogLevel.Info.CompareTo(levelMax), -3);
Assert.Equal(LogLevel.Warn.CompareTo(levelMax), -2);
Assert.Equal(LogLevel.Error.CompareTo(levelMax), -1);
Assert.Equal(0, LogLevel.Fatal.CompareTo(levelMax));
Assert.Equal(1, LogLevel.Off.CompareTo(levelMax));
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelCompareTo_Null_ExpectException()
{
Assert.Throws<ArgumentNullException>(() => LogLevel.MinLevel.CompareTo(null));
Assert.Throws<ArgumentNullException>(() => LogLevel.MaxLevel.CompareTo(null));
Assert.Throws<ArgumentNullException>(() => LogLevel.Debug.CompareTo(null));
}
[Fact]
[Trait("Component", "Core")]
public void LogLevel_MinMaxLevels_ExpectConstantValues()
{
Assert.Same(LogLevel.Trace, LogLevel.MinLevel);
Assert.Same(LogLevel.Fatal, LogLevel.MaxLevel);
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelGetHashCode()
{
Assert.Equal(0, LogLevel.Trace.GetHashCode());
Assert.Equal(1, LogLevel.Debug.GetHashCode());
Assert.Equal(2, LogLevel.Info.GetHashCode());
Assert.Equal(3, LogLevel.Warn.GetHashCode());
Assert.Equal(4, LogLevel.Error.GetHashCode());
Assert.Equal(5, LogLevel.Fatal.GetHashCode());
Assert.Equal(6, LogLevel.Off.GetHashCode());
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelEquals_Null_ExpectFalse()
{
Assert.False(LogLevel.Debug.Equals(null));
LogLevel logLevel = null;
Assert.False(LogLevel.Debug.Equals(logLevel));
Object obj = logLevel;
Assert.False(LogLevel.Debug.Equals(obj));
}
[Fact]
public void LogLevelEqual_TypeOfObject()
{
// Objects of any other type should always return false.
Assert.False(LogLevel.Debug.Equals((int) 1));
Assert.False(LogLevel.Debug.Equals((string)"Debug"));
// Valid LogLevel objects boxed as Object type.
Object levelTrace = LogLevel.Trace;
Object levelDebug = LogLevel.Debug;
Object levelInfo = LogLevel.Info;
Object levelWarn = LogLevel.Warn;
Object levelError = LogLevel.Error;
Object levelFatal = LogLevel.Fatal;
Object levelOff = LogLevel.Off;
Assert.False(LogLevel.Warn.Equals(levelTrace));
Assert.False(LogLevel.Warn.Equals(levelDebug));
Assert.False(LogLevel.Warn.Equals(levelInfo));
Assert.True(LogLevel.Warn.Equals(levelWarn));
Assert.False(LogLevel.Warn.Equals(levelError));
Assert.False(LogLevel.Warn.Equals(levelFatal));
Assert.False(LogLevel.Warn.Equals(levelOff));
}
[Fact]
public void LogLevelEqual_TypeOfLogLevel()
{
Assert.False(LogLevel.Warn.Equals(LogLevel.Trace));
Assert.False(LogLevel.Warn.Equals(LogLevel.Debug));
Assert.False(LogLevel.Warn.Equals(LogLevel.Info));
Assert.True(LogLevel.Warn.Equals(LogLevel.Warn));
Assert.False(LogLevel.Warn.Equals(LogLevel.Error));
Assert.False(LogLevel.Warn.Equals(LogLevel.Fatal));
Assert.False(LogLevel.Warn.Equals(LogLevel.Off));
}
[Fact]
public void LogLevel_GetAllLevels()
{
Assert.Equal(
new List<LogLevel>() { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal, LogLevel.Off },
LogLevel.AllLevels);
}
[Fact]
public void LogLevel_SetAllLevels()
{
Assert.Throws<NotSupportedException>(() => ((ICollection<LogLevel>) LogLevel.AllLevels).Add(LogLevel.Fatal));
}
[Fact]
public void LogLevel_GetAllLoggingLevels()
{
Assert.Equal(
new List<LogLevel>() { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal },
LogLevel.AllLoggingLevels);
}
[Fact]
public void LogLevel_SetAllLoggingLevels()
{
Assert.Throws<NotSupportedException>(() => ((ICollection<LogLevel>)LogLevel.AllLoggingLevels).Add(LogLevel.Fatal));
}
}
}
| |
//
// Node.cs
//
// This file was generated by XMLSPY 2004 Enterprise Edition.
//
// YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE
// OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION.
//
// Refer to the XMLSPY Documentation for further details.
// http://www.altova.com/xmlspy
//
using System;
using System.Xml;
namespace Altova
{
/// <summary>
/// class Node
/// </summary>
public abstract class Node
{
public enum NodeType { Attribute, Element };
protected internal XmlNode domNode;
#region Constructors
public Node()
{
domNode = Document.CreateTemporaryDomNode();
}
public Node(XmlDocument doc)
{
domNode = doc.DocumentElement;
}
public Node(XmlNode node)
{
domNode = node;
}
public Node(Node node)
{
domNode = node.domNode;
}
#endregion
#region Utility methods
public void MapPrefix(string prefix, string URI)
{
XmlElement element = (XmlElement)domNode;
if (prefix == null || prefix == "")
element.SetAttribute("xmlns", URI);
else
element.SetAttribute("xmlns:" + prefix, URI);
}
protected internal void DeclareNamespace(string prefix, string URI)
{
XmlElement root = domNode.OwnerDocument.DocumentElement;
XmlAttributeCollection attrs = root.Attributes;
if (attrs != null)
{
for (int i = 0; i < attrs.Count; i++)
{
XmlAttribute attr = attrs[i];
if (attr.Value == URI) // namespace URI already mapped?
return; // do not overwrite
}
}
if (prefix == null || prefix == "")
root.SetAttribute("xmlns", URI);
else
root.SetAttribute("xmlns:" + prefix, URI);
}
protected static string GetDomNodeValue(XmlNode node)
{
return node.InnerText;
}
protected static void SetDomNodeValue(XmlNode node, string Value)
{
node.InnerText = Value;
}
protected XmlElement CloneDomElementAs(string URI, string name, Node node)
{
XmlElement srcElement = (XmlElement)node.domNode;
XmlElement dstElement = domNode.OwnerDocument.CreateElement(name, URI);
XmlDocument doc = domNode.OwnerDocument;
foreach (XmlAttribute attribute in srcElement.Attributes)
dstElement.Attributes.Append((XmlAttribute)doc.ImportNode(attribute, false));
foreach (XmlNode childNode in srcElement.ChildNodes)
dstElement.AppendChild(doc.ImportNode(childNode, true));
return dstElement;
}
protected internal void MakeRoot(string namespaceURI, string rootElementName, string schemaLocation)
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement(rootElementName, namespaceURI);
doc.AppendChild(doc.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""));
doc.AppendChild(root);
root.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
if (namespaceURI == null || namespaceURI == "")
{
if (schemaLocation != null && schemaLocation != "")
{
XmlAttribute a = doc.CreateAttribute("xsi:noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
a.Value = schemaLocation;
root.SetAttributeNode(a);
}
}
else
{
if (schemaLocation != null && schemaLocation != "")
{
XmlAttribute a = doc.CreateAttribute("xsi:schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
a.Value = namespaceURI + " " + schemaLocation;
root.SetAttributeNode(a);
}
}
foreach (XmlAttribute attribute in domNode.Attributes)
root.Attributes.Append((XmlAttribute)doc.ImportNode(attribute, true));
foreach (XmlNode childNode in domNode.ChildNodes)
root.AppendChild(doc.ImportNode(childNode, true));
domNode = root;
}
#endregion
#region Child node manipulation methods
public XmlNode getDOMNode()
{
return domNode;
}
protected bool HasDomChild(NodeType type, string URI, string name)
{
if (type == NodeType.Attribute)
{
foreach (XmlAttribute attribute in domNode.Attributes)
if (attribute.NamespaceURI == URI && attribute.LocalName == name)
return true;
return false;
}
else
{
foreach (XmlNode node in domNode.ChildNodes)
if (node.NamespaceURI == URI && node.LocalName == name)
return true;
return false;
}
}
protected int DomChildCount(NodeType type, string URI, string name)
{
if (type == NodeType.Attribute)
{
foreach (XmlAttribute attribute in domNode.Attributes)
if (attribute.NamespaceURI == URI && attribute.LocalName == name)
return 1;
return 0;
}
else
{
int count = 0;
foreach (XmlNode node in domNode.ChildNodes)
if (node.NamespaceURI == URI && node.LocalName == name)
count++;
return count;
}
}
protected XmlNode AppendDomChild(NodeType type, string URI, string name, string Value)
{
if (type == NodeType.Attribute)
{
XmlAttribute attribute = domNode.OwnerDocument.CreateAttribute(name, URI);
attribute.Value = Value;
domNode.Attributes.Append(attribute);
return attribute;
}
else
{
XmlElement element = domNode.OwnerDocument.CreateElement(name, URI);
element.InnerText = Value;
domNode.AppendChild(element);
return element;
}
}
protected XmlNode AppendDomElement(string URI, string name, Node node)
{
node.domNode = CloneDomElementAs(URI, name, node);
return domNode.AppendChild(node.domNode);
}
protected XmlNode InsertDomChildAt(NodeType type, string URI, string name, int index, string Value)
{
if (type == NodeType.Attribute)
{
return AppendDomChild(type, URI, name, Value);
}
else
{
XmlElement element = domNode.OwnerDocument.CreateElement(name, URI);
element.InnerText = Value;
domNode.InsertBefore(element, GetDomChildAt(type, URI, name, index));
return element;
}
}
protected XmlNode InsertDomElementAt(string URI, string name, int index, Node node)
{
node.domNode = CloneDomElementAs(URI, name, node);
return domNode.InsertBefore(node.domNode, GetDomChildAt(NodeType.Element, URI, name, index));
}
protected XmlNode GetDomChildAt(NodeType type, string URI, string name, int index)
{
if (type == NodeType.Attribute)
{
if (index > 0)
throw new Exception("Index out of range");
foreach (XmlAttribute a in domNode.Attributes)
if (a.NamespaceURI == URI && a.LocalName == name)
return a;
throw new Exception("Not found");
}
else
{
int count = 0;
foreach (XmlNode n in domNode.ChildNodes)
if (n.NamespaceURI == URI && n.LocalName == name)
if (count++ == index)
return n;
if (count > 0)
throw new Exception("Index out of range");
else
throw new Exception("Not found");
}
}
protected XmlNode ReplaceDomChildAt(NodeType type, string URI, string name, int index, string Value)
{
if (type == NodeType.Attribute)
{
XmlAttribute attr = domNode.OwnerDocument.CreateAttribute(name, URI);
attr.Value = Value;
return domNode.Attributes.Append(attr);
}
else
{
XmlElement elem = domNode.OwnerDocument.CreateElement(name, URI);
elem.InnerText = Value;
return domNode.ReplaceChild(elem, GetDomChildAt(type, URI, name, index));
}
}
protected XmlNode ReplaceDomElementAt(string URI, string name, int index, Node node)
{
node.domNode = CloneDomElementAs(URI, name, node);
return domNode.ReplaceChild(node.domNode, GetDomChildAt(NodeType.Element, URI, name, index));
}
protected XmlNode RemoveDomChildAt(NodeType type, string URI, string name, int index)
{
if (type == NodeType.Attribute)
{
return domNode.Attributes.RemoveNamedItem(name, URI);
}
else
{
return domNode.RemoveChild(GetDomChildAt(type, URI, name, index));
}
}
protected static string LookupPrefix(XmlNode node, string URI)
{
if (node == null || URI == null || URI == "")
return null;
if (node.NodeType == XmlNodeType.Element)
{
XmlAttributeCollection attrs = node.Attributes;
if (attrs != null)
{
int len = attrs.Count;
for (int i = 0; i < len; i++)
{
XmlAttribute attr = attrs[i];
String name = attr.Name;
String value = attr.Value;
if (value != null && value == URI)
{
if (name.StartsWith("xmlns:"))
return name.Substring(6);
else
return null;
}
}
}
return LookupPrefix(node.ParentNode, URI);
}
else if (node.NodeType == XmlNodeType.Attribute)
{
return LookupPrefix(node.ParentNode, URI);
}
else
{
return null;
}
}
protected internal static void InternalAdjustPrefix(XmlNode node, bool qualified)
{
if (node != null && qualified)
{
string prefix = LookupPrefix(node, node.NamespaceURI);
if (prefix != null)
node.Prefix = prefix;
}
}
public abstract void AdjustPrefix();
#endregion
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.DNSServerBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBDNSServerDNSServerStatistics))]
public partial class LocalLBDNSServer : iControlInterface {
public LocalLBDNSServer() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
public void create(
string [] servers,
string [] addresses
) {
this.Invoke("create", new object [] {
servers,
addresses});
}
public System.IAsyncResult Begincreate(string [] servers,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
servers,
addresses}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_servers
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
public void delete_all_servers(
) {
this.Invoke("delete_all_servers", new object [0]);
}
public System.IAsyncResult Begindelete_all_servers(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_servers", new object[0], callback, asyncState);
}
public void Enddelete_all_servers(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
public void delete_server(
string [] servers
) {
this.Invoke("delete_server", new object [] {
servers});
}
public System.IAsyncResult Begindelete_server(string [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_server", new object[] {
servers}, callback, asyncState);
}
public void Enddelete_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_address(
string [] servers
) {
object [] results = this.Invoke("get_address", new object [] {
servers});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_address(string [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_address", new object[] {
servers}, callback, asyncState);
}
public string [] Endget_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBDNSServerDNSServerStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((LocalLBDNSServerDNSServerStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public LocalLBDNSServerDNSServerStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBDNSServerDNSServerStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_port(
string [] servers
) {
object [] results = this.Invoke("get_port", new object [] {
servers});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_port(string [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_port", new object[] {
servers}, callback, asyncState);
}
public long [] Endget_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_route_domain
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_route_domain(
string [] servers
) {
object [] results = this.Invoke("get_route_domain", new object [] {
servers});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_route_domain(string [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_route_domain", new object[] {
servers}, callback, asyncState);
}
public string [] Endget_route_domain(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBDNSServerDNSServerStatistics get_statistics(
string [] servers
) {
object [] results = this.Invoke("get_statistics", new object [] {
servers});
return ((LocalLBDNSServerDNSServerStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
servers}, callback, asyncState);
}
public LocalLBDNSServerDNSServerStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBDNSServerDNSServerStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_tsig_key
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_tsig_key(
string [] servers
) {
object [] results = this.Invoke("get_tsig_key", new object [] {
servers});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_tsig_key(string [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_tsig_key", new object[] {
servers}, callback, asyncState);
}
public string [] Endget_tsig_key(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
public void reset_statistics(
string [] servers
) {
this.Invoke("reset_statistics", new object [] {
servers});
}
public System.IAsyncResult Beginreset_statistics(string [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
servers}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
public void set_address(
string [] servers,
string [] addresses
) {
this.Invoke("set_address", new object [] {
servers,
addresses});
}
public System.IAsyncResult Beginset_address(string [] servers,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_address", new object[] {
servers,
addresses}, callback, asyncState);
}
public void Endset_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
public void set_port(
string [] servers,
long [] ports
) {
this.Invoke("set_port", new object [] {
servers,
ports});
}
public System.IAsyncResult Beginset_port(string [] servers,long [] ports, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_port", new object[] {
servers,
ports}, callback, asyncState);
}
public void Endset_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_route_domain
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
public void set_route_domain(
string [] servers,
string [] domains
) {
this.Invoke("set_route_domain", new object [] {
servers,
domains});
}
public System.IAsyncResult Beginset_route_domain(string [] servers,string [] domains, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_route_domain", new object[] {
servers,
domains}, callback, asyncState);
}
public void Endset_route_domain(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_tsig_key
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSServer",
RequestNamespace="urn:iControl:LocalLB/DNSServer", ResponseNamespace="urn:iControl:LocalLB/DNSServer")]
public void set_tsig_key(
string [] servers,
string [] keys
) {
this.Invoke("set_tsig_key", new object [] {
servers,
keys});
}
public System.IAsyncResult Beginset_tsig_key(string [] servers,string [] keys, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_tsig_key", new object[] {
servers,
keys}, callback, asyncState);
}
public void Endset_tsig_key(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.DNSServer.DNSServerStatisticEntry", Namespace = "urn:iControl")]
public partial class LocalLBDNSServerDNSServerStatisticEntry
{
private string serverField;
public string server
{
get { return this.serverField; }
set { this.serverField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.DNSServer.DNSServerStatistics", Namespace = "urn:iControl")]
public partial class LocalLBDNSServerDNSServerStatistics
{
private LocalLBDNSServerDNSServerStatisticEntry [] statisticsField;
public LocalLBDNSServerDNSServerStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
}
| |
//---------------------------------------------------------------------------
//
// File: ParserContext.cs
//
// Description:
// class for the main TypeConverterContext object passed to type converters
//
//
// History:
// 8/02/01: rogerg Created
// 05/23/03: peterost Ported to wcp
// 03/16/05: chandras Changed the XmlnsDictionary usage
//
// Copyright (C) 2001 by Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml;
using MS.Utility;
using System.Diagnostics;
#if PBTCOMPILER
namespace MS.Internal.Markup
#else
using System.Windows;
using System.Security;
using MS.Internal;
namespace System.Windows.Markup
#endif
{
#if PBTCOMPILER
///<summary>
/// The IUriContext interface allows elements (like Frame, PageViewer) and type converters
/// (like BitmapImage TypeConverters) a way to ensure that base uri is set on them by the
/// parser, codegen for xaml, baml and caml cases. The elements can then use this base uri
/// to navigate.
///</summary>
internal interface IUriContext
{
/// <summary>
/// Provides the base uri of the current context.
/// </summary>
Uri BaseUri
{
get;
set;
}
}
#endif
/// <summary>
/// Provides all the context information required by Parser
/// </summary>
#if PBTCOMPILER
internal class ParserContext : IUriContext
#else
public class ParserContext : IUriContext
#endif
{
#region Public Methods
/// <summary>
/// Constructor
/// </summary>
public ParserContext()
{
Initialize();
}
// Initialize the ParserContext to a known, default state. DO NOT wipe out
// data that may be able to be shared between seperate parses, such as the
// xamlTypeMapper and the map table.
internal void Initialize()
{
_xmlnsDictionary = null; // created on its first use
#if !PBTCOMPILER
_nameScopeStack = null;
#endif
_xmlLang = String.Empty;
_xmlSpace = String.Empty;
}
#if !PBTCOMPILER
/// <summary>
/// Constructor that takes the XmlParserContext.
/// A parserContext object will be built based on this.
/// </summary>
/// <param name="xmlParserContext">xmlParserContext to use</param>
public ParserContext(XmlParserContext xmlParserContext)
{
if (xmlParserContext == null)
{
throw new ArgumentNullException( "xmlParserContext" );
}
_xmlLang = xmlParserContext.XmlLang;
TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(XmlSpace));
if (typeConverter != null)
_xmlSpace = (string) typeConverter.ConvertToString(null, TypeConverterHelper.InvariantEnglishUS, xmlParserContext.XmlSpace);
else
_xmlSpace = String.Empty;
_xmlnsDictionary = new XmlnsDictionary() ;
if (xmlParserContext.BaseURI != null && xmlParserContext.BaseURI.Length > 0)
{
_baseUri = new Uri(xmlParserContext.BaseURI, UriKind.RelativeOrAbsolute);
}
XmlNamespaceManager xmlnsManager = xmlParserContext.NamespaceManager;
if (null != xmlnsManager)
{
foreach (string key in xmlnsManager)
{
_xmlnsDictionary.Add(key, xmlnsManager.LookupNamespace(key));
}
}
}
#endif
#if !PBTCOMPILER
/// <summary>
/// Constructor overload that takes an XmlReader, in order to
/// pull the BaseURI, Lang, and Space from it.
/// </summary>
internal ParserContext( XmlReader xmlReader )
{
if( xmlReader.BaseURI != null && xmlReader.BaseURI.Length != 0 )
{
BaseUri = new Uri( xmlReader.BaseURI );
}
XmlLang = xmlReader.XmlLang;
if( xmlReader.XmlSpace != System.Xml.XmlSpace.None )
{
XmlSpace = xmlReader.XmlSpace.ToString();
}
}
#endif
#if !PBTCOMPILER
/// <summary>
/// Constructor that takes the ParserContext.
/// A parserContext object will be built based on this.
/// </summary>
/// <param name="parserContext">xmlParserContext to use</param>
internal ParserContext(ParserContext parserContext)
{
_xmlLang = parserContext.XmlLang;
_xmlSpace = parserContext.XmlSpace;
_xamlTypeMapper = parserContext.XamlTypeMapper;
_mapTable = parserContext.MapTable;
_baseUri = parserContext.BaseUri;
_rootElement = parserContext._rootElement;
if (parserContext._nameScopeStack != null)
_nameScopeStack = (Stack)parserContext._nameScopeStack.Clone();
else
_nameScopeStack = null;
// Don't want to force the lazy init so we just set privates
_skipJournaledProperties = parserContext._skipJournaledProperties;
_xmlnsDictionary = null;
// when there are no namespace prefix mappings in incoming ParserContext,
// we are not going to create an empty XmlnsDictionary.
if (parserContext._xmlnsDictionary != null &&
parserContext._xmlnsDictionary.Count > 0)
{
_xmlnsDictionary = new XmlnsDictionary();
XmlnsDictionary xmlDictionaryFrom = parserContext.XmlnsDictionary;
if (null != xmlDictionaryFrom)
{
foreach (string key in xmlDictionaryFrom.Keys)
{
_xmlnsDictionary[key] = xmlDictionaryFrom[key];
}
}
}
}
#endif
/// <summary>
/// Pushes the context scope stack (modifications to the ParserContext only apply to levels below
/// the modification in the stack, except for the XamlTypeMapper property)
/// </summary>
internal void PushScope()
{
_repeat++;
_currentFreezeStackFrame.IncrementRepeatCount();
// Wait till the context needs XmlnsDictionary, create on first use.
if (_xmlnsDictionary != null)
_xmlnsDictionary.PushScope();
}
/// <summary>
/// Pops the context scope stack
/// </summary>
internal void PopScope()
{
// Pop state off of the _langSpaceStack
if (_repeat > 0)
{
_repeat--;
}
else
{
if (null != _langSpaceStack && _langSpaceStack.Count > 0)
{
_repeat = (int) _langSpaceStack.Pop();
_targetType = (Type) _langSpaceStack.Pop();
_xmlSpace = (string) _langSpaceStack.Pop();
_xmlLang = (string) _langSpaceStack.Pop();
}
}
// Pop state off of _currentFreezeStackFrame
if (!_currentFreezeStackFrame.DecrementRepeatCount())
{
// If the end of the current frame has been reached, pop
// the next frame off the freeze stack
_currentFreezeStackFrame = (FreezeStackFrame) _freezeStack.Pop();
}
// Wait till the context needs XmlnsDictionary, create on first use.
if (_xmlnsDictionary != null)
_xmlnsDictionary.PopScope();
}
/// <summary>
/// XmlNamespaceDictionary
/// </summary>
public XmlnsDictionary XmlnsDictionary
{
get
{
// Entry Point to others, initialize if null.
if (_xmlnsDictionary == null)
_xmlnsDictionary = new XmlnsDictionary();
return _xmlnsDictionary;
}
}
/// <summary>
/// XmlLang property
/// </summary>
public string XmlLang
{
get
{
return _xmlLang;
}
set
{
EndRepeat();
_xmlLang = (null == value ? String.Empty : value);
}
}
/// <summary>
/// XmlSpace property
/// </summary>
// (Why isn't this of type XmlSpace?)
public string XmlSpace
{
get
{
return _xmlSpace;
}
set
{
EndRepeat();
_xmlSpace = value;
}
}
//
// TargetType
//
// Keep track of the Style/Template TargetType's in the current context. This allows Setters etc
// to interpret properties without walking up the reader stack to see it. This is internal and
// hard-coded to target type, but the intent in the future is to generalize this so that we don't
// have to have the custom parser, and so that the designer can provide the same contextual information.
//
internal Type TargetType
{
get
{
return _targetType;
}
#if !PBTCOMPILER
set
{
EndRepeat();
_targetType = value;
}
#endif
}
// Items specific to XAML
/// <summary>
/// XamlTypeMapper that should be used when resolving XML
/// </summary>
public XamlTypeMapper XamlTypeMapper
{
get
{
return _xamlTypeMapper ;
}
set
{
// The BamlMapTable must always be kept in [....] with the XamlTypeMapper. If
// the XamlTypeMapper changes, then the map table must also be reset.
if (_xamlTypeMapper != value)
{
_xamlTypeMapper = value;
_mapTable = new BamlMapTable(value);
_xamlTypeMapper.MapTable = _mapTable;
}
}
}
#if !PBTCOMPILER
/// <summary>
/// Gets or sets the list of INameScopes in parent chain
/// </summary>
internal Stack NameScopeStack
{
get
{
if (_nameScopeStack == null)
_nameScopeStack = new Stack(2);
return _nameScopeStack;
}
}
#endif
/// <summary>
/// Gets or sets the base Uri
/// </summary>
public Uri BaseUri
{
get
{
return _baseUri ;
}
set
{
_baseUri = value;
}
}
#if !PBTCOMPILER
/// <summary>
/// Should DependencyProperties marked with the Journal metadata flag be set or skipped?
/// </summary>
/// <value></value>
internal bool SkipJournaledProperties
{
get { return _skipJournaledProperties; }
set { _skipJournaledProperties = value; }
}
//
// The Assembly which hosts the Baml stream.
//
/// <SecurityNote>
/// Critical - because it sets the value of the _streamCreatedAssembly field, and that is
/// SecurityCritical Data as this field is used by the BamlRecordReader to
/// allow legitimate internal types in Partial Trust.
/// </SecurityNote>
internal Assembly StreamCreatedAssembly
{
get { return _streamCreatedAssembly.Value; }
[SecurityCritical]
set { _streamCreatedAssembly.Value = value; }
}
#endif
/// <summary>
/// Operator for Converting a ParserContext to an XmlParserContext
/// </summary>
/// <param name="parserContext">ParserContext to Convert</param>
/// <returns>XmlParserContext</returns>
public static implicit operator XmlParserContext(ParserContext parserContext)
{
return ParserContext.ToXmlParserContext(parserContext);
}
/// <summary>
/// Operator for Converting a ParserContext to an XmlParserContext
/// </summary>
/// <param name="parserContext">ParserContext to Convert</param>
/// <returns>XmlParserContext</returns>
public static XmlParserContext ToXmlParserContext(ParserContext parserContext)
{
if (parserContext == null)
{
throw new ArgumentNullException( "parserContext" );
}
XmlNamespaceManager xmlnsMgr = new XmlNamespaceManager(new NameTable());
XmlSpace xmlSpace = System.Xml.XmlSpace.None;
if (parserContext.XmlSpace != null && parserContext.XmlSpace.Length != 0)
{
TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(System.Xml.XmlSpace));
if (null != typeConverter)
{
try
{
xmlSpace = (System.Xml.XmlSpace)typeConverter.ConvertFromString(null, TypeConverterHelper.InvariantEnglishUS, parserContext.XmlSpace);
}
catch (System.FormatException) // If it's not a valid space value, ignore it
{
xmlSpace = System.Xml.XmlSpace.None;
}
}
}
// We start getting Keys list only if we have non-empty dictionary
if (parserContext._xmlnsDictionary != null)
{
foreach (string key in parserContext._xmlnsDictionary.Keys)
{
xmlnsMgr.AddNamespace(key, parserContext._xmlnsDictionary[key]);
}
}
XmlParserContext xmlParserContext = new XmlParserContext(null, xmlnsMgr, parserContext.XmlLang, xmlSpace);
if( parserContext.BaseUri == null)
{
xmlParserContext.BaseURI = null;
}
else
{
string serializedSafe = parserContext.BaseUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.SafeUnescaped);
Uri sameUri = new Uri(serializedSafe);
string cannonicalString = sameUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped);
xmlParserContext.BaseURI = cannonicalString;
}
return xmlParserContext;
}
#endregion Public Methods
#region Internal
// Reset stack to default state
private void EndRepeat()
{
if (_repeat > 0)
{
if (null == _langSpaceStack)
{
_langSpaceStack = new Stack(1);
}
_langSpaceStack.Push(XmlLang);
_langSpaceStack.Push(XmlSpace);
_langSpaceStack.Push(TargetType);
_langSpaceStack.Push(_repeat);
_repeat = 0;
}
}
/// <summary>
/// LineNumber for the first character in the given
/// stream. This is used when parsing a section of a larger file so
/// that proper line number in the overall file can be calculated.
/// </summary>
internal int LineNumber
{
get { return _lineNumber; }
#if !PBTCOMPILER
set { _lineNumber = value; }
#endif
}
/// <summary>
/// LinePosition for the first character in the given
/// stream. This is used when parsing a section of a larger file so
/// that proper line positions in the overall file can be calculated.
/// </summary>
internal int LinePosition
{
get { return _linePosition; }
#if !PBTCOMPILER
set { _linePosition = value; }
#endif
}
#if !PBTCOMPILER
internal bool IsDebugBamlStream
{
get { return _isDebugBamlStream; }
set { _isDebugBamlStream = value; }
}
/// <summary>
/// Gets or sets the object at the root of the portion of the tree
/// currently being parsed. Note that this may not be the very top of the tree
/// if the parsing operation is scoped to a specific subtree, such as in Style
/// parsing.
/// </summary>
internal object RootElement
{
get { return _rootElement; }
set { _rootElement = value; }
}
// If this is false (default), then the parser does not own the stream and so if
// it has any defer loaded content, it needs to copy it into a byte array since
// the owner\caller will close the stream when parsing is complete. Currently, this
// is set to true only by the theme engine since the stream is a system-wide resource
// an dso will always be open for teh lifetime of the process laoding the theme and so
// it can be re-used for perf reasons.
internal bool OwnsBamlStream
{
get { return _ownsBamlStream; }
set { _ownsBamlStream = value; }
}
#endif
/// <summary>
/// Allows sharing a map table between instances of BamlReaders and Writers.
/// </summary>
internal BamlMapTable MapTable
{
get { return _mapTable; }
#if !PBTCOMPILER
set
{
// The XamlTypeMapper and the map table must always be kept in [....]. If the
// map table changes, update the XamlTypeMapper also
if (_mapTable != value)
{
_mapTable = value;
_xamlTypeMapper = _mapTable.XamlTypeMapper;
_xamlTypeMapper.MapTable = _mapTable;
}
}
#endif
}
#if !PBTCOMPILER
internal IStyleConnector StyleConnector
{
get { return _styleConnector; }
set { _styleConnector = value; }
}
// Keep a cached ProvideValueProvider so that we don't have to keep re-creating one.
internal ProvideValueServiceProvider ProvideValueProvider
{
get
{
if (_provideValueServiceProvider == null)
{
_provideValueServiceProvider = new ProvideValueServiceProvider(this);
}
return _provideValueServiceProvider;
}
}
/// <summary>
/// This is used to resolve a StaticResourceId record within a deferred content
/// section against a StaticResourceExtension on the parent dictionary.
/// </summary>
internal List<object[]> StaticResourcesStack
{
get
{
if (_staticResourcesStack == null)
{
_staticResourcesStack = new List<object[]>();
}
return _staticResourcesStack;
}
}
/// <summary>
/// Says if we are we currently loading deferred content
/// </summary>
internal bool InDeferredSection
{
get { return (_staticResourcesStack != null && _staticResourcesStack.Count > 0); }
}
#endif
// Return a new Parser context that has the same instance variables as this instance, with
// only scope dependent variables deep copied. Variables that are not dependent on scope
// (such as the baml map table) are not deep copied.
#if !PBTCOMPILER
internal ParserContext ScopedCopy()
{
return ScopedCopy( true /* copyNameScopeStack */ );
}
#endif
#if !PBTCOMPILER
/// <SecurityNote>
/// Critical - because it sets _streamCreatedAssembly on the ParserContext, and that is
/// SecurityCritical Data as this field is used by the BamlRecordReader to
/// allow legitimate internal types in Partial Trust.
/// Safe - because it gets this value from a copy of itself that gets it from a stream that
/// implements an internal IStreamInfo interface and IStreamInfo.Assembly is set\
/// by the ResourceContainer code that is SecurityCritical, but treated as safe.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal ParserContext ScopedCopy(bool copyNameScopeStack)
{
ParserContext context = new ParserContext();
context._baseUri = _baseUri;
context._skipJournaledProperties = _skipJournaledProperties;
context._xmlLang = _xmlLang;
context._xmlSpace = _xmlSpace;
context._repeat = _repeat;
context._lineNumber = _lineNumber;
context._linePosition = _linePosition;
context._isDebugBamlStream = _isDebugBamlStream;
context._mapTable = _mapTable;
context._xamlTypeMapper = _xamlTypeMapper;
context._targetType = _targetType;
context._streamCreatedAssembly.Value = _streamCreatedAssembly.Value;
context._rootElement = _rootElement;
context._styleConnector = _styleConnector;
// Copy the name scope stack, if necessary.
if (_nameScopeStack != null && copyNameScopeStack)
context._nameScopeStack = (_nameScopeStack != null) ? (Stack)_nameScopeStack.Clone() : null;
else
context._nameScopeStack = null;
// Deep copy only selected scope dependent instance variables
context._langSpaceStack = (_langSpaceStack != null) ? (Stack)_langSpaceStack.Clone() : null;
if (_xmlnsDictionary != null)
context._xmlnsDictionary = new XmlnsDictionary(_xmlnsDictionary);
else
context._xmlnsDictionary = null;
context._currentFreezeStackFrame = _currentFreezeStackFrame;
context._freezeStack = (_freezeStack != null) ? (Stack) _freezeStack.Clone() : null;
return context;
}
#endif
//
// This is called by a user of a parser context when it is a good time to drop unnecessary
// references (today, just an empty stack).
//
#if !PBTCOMPILER
internal void TrimState()
{
if( _nameScopeStack != null && _nameScopeStack.Count == 0 )
{
_nameScopeStack = null;
}
}
#endif
// Return a new Parser context that has the same instance variables as this instance,
// will all scoped and non-scoped complex properties deep copied.
#if !PBTCOMPILER
internal ParserContext Clone()
{
ParserContext context = ScopedCopy();
// Deep copy only selected instance variables
context._mapTable = (_mapTable != null) ? _mapTable.Clone() : null;
context._xamlTypeMapper = (_xamlTypeMapper != null) ? _xamlTypeMapper.Clone() : null;
// Connect the XamlTypeMapper and bamlmaptable
context._xamlTypeMapper.MapTable = context._mapTable;
context._mapTable.XamlTypeMapper = context._xamlTypeMapper;
return context;
}
#endif
#if !PBTCOMPILER
// Set/Get whether or not Freezables within the current scope
// should be Frozen.
internal bool FreezeFreezables
{
get
{
return _currentFreezeStackFrame.FreezeFreezables;
}
set
{
// If the freeze flag isn't actually changing, we don't need to
// register a change
if (value != _currentFreezeStackFrame.FreezeFreezables)
{
// When this scope was entered the repeat count was initially incremented,
// indicating no _freezeFreezables state changes within this scope.
//
// Now that a state change has been found, we need to replace that no-op with
// a directive to restore the old state by un-doing the increment
// and pushing the stack frame
#if DEBUG
bool canDecrement =
#endif
_currentFreezeStackFrame.DecrementRepeatCount();
#if DEBUG
// We're replacing a no-op with a state change. Detect if we accidently
// start replacing actual state changes. This might happen if we allowed
// FreezeFreezable to be set twice within the same scope, for
// example.
Debug.Assert(canDecrement);
#endif
if (_freezeStack == null)
{
// Lazily allocate a _freezeStack if this is the first
// state change.
_freezeStack = new Stack();
}
// Save the old frame
_freezeStack.Push(_currentFreezeStackFrame);
// Set the new frame
_currentFreezeStackFrame.Reset(value);
}
}
}
internal bool TryCacheFreezable(string value, Freezable freezable)
{
if (FreezeFreezables)
{
if (freezable.CanFreeze)
{
if (!freezable.IsFrozen)
{
freezable.Freeze();
}
if (_freezeCache == null)
{
_freezeCache = new Dictionary<string, Freezable>();
}
_freezeCache.Add(value, freezable);
return true;
}
}
return false;
}
internal Freezable TryGetFreezable(string value)
{
Freezable freezable = null;
if (_freezeCache != null)
{
_freezeCache.TryGetValue(value, out freezable);
}
return freezable;
}
#endif
#endregion Internal
#region Date
private XamlTypeMapper _xamlTypeMapper;
private Uri _baseUri;
private XmlnsDictionary _xmlnsDictionary;
private String _xmlLang = String.Empty;
private String _xmlSpace = String.Empty;
private Stack _langSpaceStack;
private int _repeat;
private Type _targetType;
#if !PBTCOMPILER
private bool _skipJournaledProperties;
private SecurityCriticalDataForSet<Assembly> _streamCreatedAssembly;
private bool _ownsBamlStream;
private ProvideValueServiceProvider _provideValueServiceProvider;
private IStyleConnector _styleConnector;
private Stack _nameScopeStack;
private List<object[]> _staticResourcesStack;
object _rootElement; // RootElement for the Page scoping [temporary, should be
// something like page name or baseUri]
#endif
// Struct that maintains both the freezeFreezable state & stack depth
// between freezeFreezable state changes
private struct FreezeStackFrame
{
internal void IncrementRepeatCount() { _repeatCount++; }
// Returns false when the count reaches 0 such that the decrement can not occur
internal bool DecrementRepeatCount()
{
if (_repeatCount > 0)
{
_repeatCount--;
return true;
}
else
{
return false;
}
}
#if !PBTCOMPILER
// Accessors for private state
internal bool FreezeFreezables
{
get { return _freezeFreezables; }
}
// Reset's this frame to a new scope. Only used with _currentFreezeStackFrame.
internal void Reset(bool freezeFreezables)
{
_freezeFreezables = freezeFreezables;
_repeatCount = 0;
}
// Whether or not Freezeables with the current scope should be Frozen
private bool _freezeFreezables;
#endif
// The number of frames until the next state change.
// We need to know how many times PopScope() is called until the
// state changes. That information is tracked by _repeatCount.
private int _repeatCount;
}
// First frame is maintained off of the _freezeStack to avoid allocating
// a Stack<FreezeStackFlag> for the common case where Freeze isn't specified.
FreezeStackFrame _currentFreezeStackFrame;
#if !PBTCOMPILER
// When cloning, it isn't necessary to copy this cache of freezables.
// This cache allows frozen freezables to use a shared instance and save on memory.
private Dictionary<string, Freezable> _freezeCache;
#endif
private Stack _freezeStack = null;
private int _lineNumber = 0; // number of lines between the start of the file and
// our starting point (the starting point of this context)
private int _linePosition=0; // default start ot left of first character which is a zero
private BamlMapTable _mapTable;
#if !PBTCOMPILER
private bool _isDebugBamlStream = false;
#endif
#endregion Data
}
}
| |
//
// WindowFrameBa.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
// Konrad M. Kruczynski <kkruczynski@antmicro.com>
//
// Copyright (c) 2011 Xamarin Inc
// Copyright (c) 2016 Antmicro Ltd
//
// 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 Xwt.Backends;
using System.Runtime.InteropServices;
using Xwt.Drawing;
using System.Linq;
namespace Xwt.GtkBackend
{
public class WindowFrameBackend: IWindowFrameBackend
{
Gtk.Window window;
IWindowFrameEventSink eventSink;
WindowFrame frontend;
Size requestedSize;
public WindowFrameBackend ()
{
}
// INTRODUCED BY ANTMICRO
public int Id
{
get { return gdk_x11_drawable_get_xid(window.GdkWindow.Handle); }
}
// ---
public Gtk.Window Window {
get { return window; }
set {
if (window != null)
window.Realized -= HandleRealized;
window = value;
window.Realized += HandleRealized;
}
}
void HandleRealized (object sender, EventArgs e)
{
if (opacity != 1d)
window.GdkWindow.Opacity = opacity;
}
protected WindowFrame Frontend {
get { return frontend; }
}
public ApplicationContext ApplicationContext {
get;
private set;
}
void IBackend.InitializeBackend (object frontend, ApplicationContext context)
{
this.frontend = (WindowFrame) frontend;
ApplicationContext = context;
}
public virtual void ReplaceChild (Gtk.Widget oldWidget, Gtk.Widget newWidget)
{
throw new NotSupportedException ();
}
#region IWindowFrameBackend implementation
void IWindowFrameBackend.Initialize (IWindowFrameEventSink eventSink)
{
this.eventSink = eventSink;
Initialize ();
#if !XWT_GTK3
Window.SizeRequested += delegate(object o, Gtk.SizeRequestedArgs args) {
if (!Window.Resizable) {
int w = args.Requisition.Width, h = args.Requisition.Height;
if (w < (int) requestedSize.Width)
w = (int) requestedSize.Width;
if (h < (int) requestedSize.Height)
h = (int) requestedSize.Height;
args.Requisition = new Gtk.Requisition () { Width = w, Height = h };
}
};
#endif
}
public virtual void Initialize ()
{
}
public virtual void Dispose ()
{
Window.Destroy ();
}
public IWindowFrameEventSink EventSink {
get { return eventSink; }
}
public void Move (double x, double y)
{
Window.Move ((int)x, (int)y);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnBoundsChanged (Bounds);
});
}
public virtual void SetSize (double width, double height)
{
Window.SetDefaultSize ((int)width, (int)height);
if (width == -1)
width = Bounds.Width;
if (height == -1)
height = Bounds.Height;
requestedSize = new Size (width, height);
Window.Resize ((int)width, (int)height);
}
public Rectangle Bounds {
get {
int w, h, x, y;
if (Window.GdkWindow != null) {
Window.GdkWindow.GetOrigin (out x, out y);
Window.GdkWindow.GetSize (out w, out h);
} else {
Window.GetPosition (out x, out y);
Window.GetSize (out w, out h);
}
return new Rectangle (x, y, w, h);
}
set {
requestedSize = value.Size;
Window.Move ((int)value.X, (int)value.Y);
Window.Resize ((int)value.Width, (int)value.Height);
Window.SetDefaultSize ((int)value.Width, (int)value.Height);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnBoundsChanged (Bounds);
});
}
}
public Size RequestedSize {
get { return requestedSize; }
}
bool IWindowFrameBackend.Visible {
get {
return window.Visible;
}
set {
window.Visible = value;
}
}
bool IWindowFrameBackend.Sensitive {
get {
return window.Sensitive;
}
set {
window.Sensitive = value;
}
}
double opacity = 1d;
double IWindowFrameBackend.Opacity {
get {
return opacity;
}
set {
opacity = value;
if (Window.GdkWindow != null)
Window.GdkWindow.Opacity = value;
}
}
bool IWindowFrameBackend.HasFocus {
get {
return Window.HasToplevelFocus;
}
}
string IWindowFrameBackend.Title {
get { return Window.Title; }
set { Window.Title = value; }
}
bool IWindowFrameBackend.Decorated {
get {
return Window.Decorated;
}
set {
Window.Decorated = value;
}
}
bool IWindowFrameBackend.ShowInTaskbar {
get {
return !Window.SkipTaskbarHint;
}
set {
Window.SkipTaskbarHint = !value;
}
}
void IWindowFrameBackend.SetTransientFor (IWindowFrameBackend window)
{
Window.TransientFor = ((WindowFrameBackend)window).Window;
}
public bool Resizable {
get {
return Window.Resizable;
}
set {
Window.Resizable = value;
}
}
bool fullScreen;
bool IWindowFrameBackend.FullScreen {
get {
return fullScreen;
}
set {
if (value != fullScreen) {
fullScreen = value;
if (fullScreen)
Window.Fullscreen ();
else
Window.Unfullscreen ();
}
}
}
object IWindowFrameBackend.Screen {
get {
return Window.Screen.GetMonitorAtWindow (Window.GdkWindow);
}
}
public void SetIcon(ImageDescription icon)
{
Window.IconList = ((GtkImage)icon.Backend).Frames.Select (f => f.Pixbuf).ToArray ();
}
#endregion
public virtual void EnableEvent (object ev)
{
if (ev is WindowFrameEvent) {
switch ((WindowFrameEvent)ev) {
case WindowFrameEvent.BoundsChanged:
Window.AddEvents ((int)Gdk.EventMask.StructureMask);
Window.ConfigureEvent += HandleConfigureEvent; break;
case WindowFrameEvent.Closed:
case WindowFrameEvent.CloseRequested:
Window.DeleteEvent += HandleCloseRequested; break;
case WindowFrameEvent.Shown:
Window.Shown += HandleShown; break;
case WindowFrameEvent.Hidden:
Window.Hidden += HandleHidden; break;
}
}
}
public virtual void DisableEvent (object ev)
{
if (ev is WindowFrameEvent) {
switch ((WindowFrameEvent)ev) {
case WindowFrameEvent.BoundsChanged:
Window.ConfigureEvent -= HandleConfigureEvent; break;
case WindowFrameEvent.Shown:
Window.Shown -= HandleShown; break;
case WindowFrameEvent.Hidden:
Window.Hidden -= HandleHidden; break;
}
}
}
void HandleHidden (object sender, EventArgs e)
{
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnHidden ();
});
}
void HandleShown (object sender, EventArgs e)
{
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnShown ();
});
}
[GLib.ConnectBefore]
void HandleConfigureEvent (object o, Gtk.ConfigureEventArgs args)
{
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnBoundsChanged (Bounds);
});
}
void HandleCloseRequested (object o, Gtk.DeleteEventArgs args)
{
args.RetVal = !PerformClose (true);
}
internal bool PerformClose (bool userClose)
{
bool close = false;
ApplicationContext.InvokeUserCode(delegate {
close = EventSink.OnCloseRequested ();
});
if (close) {
if (!userClose)
Window.Hide ();
ApplicationContext.InvokeUserCode(EventSink.OnClosed);
}
return close;
}
public void Present ()
{
if (Platform.IsMac)
GtkWorkarounds.GrabDesktopFocus ();
Window.Present ();
}
public virtual bool Close ()
{
return PerformClose (false);
}
public virtual void GetMetrics (out Size minSize, out Size decorationSize)
{
minSize = decorationSize = Size.Zero;
}
[DllImport("gdk-x11-2.0")]
static extern int gdk_x11_drawable_get_xid(IntPtr drawable);
}
}
| |
// 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 gcrv = Google.Cloud.Retail.V2;
using sys = System;
namespace Google.Cloud.Retail.V2
{
/// <summary>Resource name for the <c>Product</c> resource.</summary>
public sealed partial class ProductName : gax::IResourceName, sys::IEquatable<ProductName>
{
/// <summary>The possible contents of <see cref="ProductName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>.
/// </summary>
ProjectLocationCatalogBranchProduct = 1,
}
private static gax::PathTemplate s_projectLocationCatalogBranchProduct = new gax::PathTemplate("projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}");
/// <summary>Creates a <see cref="ProductName"/> 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="ProductName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static ProductName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ProductName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ProductName"/> with the pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</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="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ProductName"/> constructed from the provided ids.</returns>
public static ProductName FromProjectLocationCatalogBranchProduct(string projectId, string locationId, string catalogId, string branchId, string productId) =>
new ProductName(ResourceNameType.ProjectLocationCatalogBranchProduct, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), catalogId: gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId)), branchId: gax::GaxPreconditions.CheckNotNullOrEmpty(branchId, nameof(branchId)), productId: gax::GaxPreconditions.CheckNotNullOrEmpty(productId, nameof(productId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ProductName"/> with pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</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="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ProductName"/> with pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string catalogId, string branchId, string productId) =>
FormatProjectLocationCatalogBranchProduct(projectId, locationId, catalogId, branchId, productId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ProductName"/> with pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</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="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ProductName"/> with pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>.
/// </returns>
public static string FormatProjectLocationCatalogBranchProduct(string projectId, string locationId, string catalogId, string branchId, string productId) =>
s_projectLocationCatalogBranchProduct.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId)), gax::GaxPreconditions.CheckNotNullOrEmpty(branchId, nameof(branchId)), gax::GaxPreconditions.CheckNotNullOrEmpty(productId, nameof(productId)));
/// <summary>Parses the given resource name string into a new <see cref="ProductName"/> 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}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="productName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ProductName"/> if successful.</returns>
public static ProductName Parse(string productName) => Parse(productName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ProductName"/> 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}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="productName">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="ProductName"/> if successful.</returns>
public static ProductName Parse(string productName, bool allowUnparsed) =>
TryParse(productName, allowUnparsed, out ProductName 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="ProductName"/> 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}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="productName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ProductName"/>, 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 productName, out ProductName result) => TryParse(productName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ProductName"/> 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}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="productName">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="ProductName"/>, 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 productName, bool allowUnparsed, out ProductName result)
{
gax::GaxPreconditions.CheckNotNull(productName, nameof(productName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationCatalogBranchProduct.TryParseName(productName, out resourceName))
{
result = FromProjectLocationCatalogBranchProduct(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(productName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ProductName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string branchId = null, string catalogId = null, string locationId = null, string productId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
BranchId = branchId;
CatalogId = catalogId;
LocationId = locationId;
ProductId = productId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ProductName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</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="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param>
public ProductName(string projectId, string locationId, string catalogId, string branchId, string productId) : this(ResourceNameType.ProjectLocationCatalogBranchProduct, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), catalogId: gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId)), branchId: gax::GaxPreconditions.CheckNotNullOrEmpty(branchId, nameof(branchId)), productId: gax::GaxPreconditions.CheckNotNullOrEmpty(productId, nameof(productId)))
{
}
/// <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>Branch</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string BranchId { get; }
/// <summary>
/// The <c>Catalog</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CatalogId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Product</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProductId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { 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.ProjectLocationCatalogBranchProduct: return s_projectLocationCatalogBranchProduct.Expand(ProjectId, LocationId, CatalogId, BranchId, ProductId);
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 ProductName);
/// <inheritdoc/>
public bool Equals(ProductName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ProductName a, ProductName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ProductName a, ProductName b) => !(a == b);
}
/// <summary>Resource name for the <c>Branch</c> resource.</summary>
public sealed partial class BranchName : gax::IResourceName, sys::IEquatable<BranchName>
{
/// <summary>The possible contents of <see cref="BranchName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>.
/// </summary>
ProjectLocationCatalogBranch = 1,
}
private static gax::PathTemplate s_projectLocationCatalogBranch = new gax::PathTemplate("projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}");
/// <summary>Creates a <see cref="BranchName"/> 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="BranchName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static BranchName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new BranchName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="BranchName"/> with the pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</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="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="BranchName"/> constructed from the provided ids.</returns>
public static BranchName FromProjectLocationCatalogBranch(string projectId, string locationId, string catalogId, string branchId) =>
new BranchName(ResourceNameType.ProjectLocationCatalogBranch, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), catalogId: gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId)), branchId: gax::GaxPreconditions.CheckNotNullOrEmpty(branchId, nameof(branchId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BranchName"/> with pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</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="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BranchName"/> with pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string catalogId, string branchId) =>
FormatProjectLocationCatalogBranch(projectId, locationId, catalogId, branchId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BranchName"/> with pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</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="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BranchName"/> with pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>.
/// </returns>
public static string FormatProjectLocationCatalogBranch(string projectId, string locationId, string catalogId, string branchId) =>
s_projectLocationCatalogBranch.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId)), gax::GaxPreconditions.CheckNotNullOrEmpty(branchId, nameof(branchId)));
/// <summary>Parses the given resource name string into a new <see cref="BranchName"/> 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}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="branchName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="BranchName"/> if successful.</returns>
public static BranchName Parse(string branchName) => Parse(branchName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="BranchName"/> 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}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="branchName">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="BranchName"/> if successful.</returns>
public static BranchName Parse(string branchName, bool allowUnparsed) =>
TryParse(branchName, allowUnparsed, out BranchName 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="BranchName"/> 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}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="branchName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BranchName"/>, 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 branchName, out BranchName result) => TryParse(branchName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BranchName"/> 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}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="branchName">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="BranchName"/>, 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 branchName, bool allowUnparsed, out BranchName result)
{
gax::GaxPreconditions.CheckNotNull(branchName, nameof(branchName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationCatalogBranch.TryParseName(branchName, out resourceName))
{
result = FromProjectLocationCatalogBranch(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(branchName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private BranchName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string branchId = null, string catalogId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
BranchId = branchId;
CatalogId = catalogId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="BranchName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</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="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param>
public BranchName(string projectId, string locationId, string catalogId, string branchId) : this(ResourceNameType.ProjectLocationCatalogBranch, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), catalogId: gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId)), branchId: gax::GaxPreconditions.CheckNotNullOrEmpty(branchId, nameof(branchId)))
{
}
/// <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>Branch</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string BranchId { get; }
/// <summary>
/// The <c>Catalog</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CatalogId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { 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.ProjectLocationCatalogBranch: return s_projectLocationCatalogBranch.Expand(ProjectId, LocationId, CatalogId, BranchId);
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 BranchName);
/// <inheritdoc/>
public bool Equals(BranchName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(BranchName a, BranchName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(BranchName a, BranchName b) => !(a == b);
}
public partial class Product
{
/// <summary>
/// <see cref="gcrv::ProductName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcrv::ProductName ProductName
{
get => string.IsNullOrEmpty(Name) ? null : gcrv::ProductName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
namespace Bell.PPS.Database.Shared
{
/// <summary>
/// Options for modifying how DbConnectionScope.Current is affected while constructing a new scope.
/// </summary>
public enum DbConnectionScopeOption
{
Required, // Set self as currentScope if there isn't one already on the thread, otherwise don't do anything.
RequiresNew // Push self as currentScope (track prior scope and restore it on dispose).
}
// Allows almost-automated re-use of connections across multiple call levels
// while still controlling connection lifetimes. Multiple connections are supported within a single scope.
/// <summary>
/// Class to assist in managing connection lifetimes inside scopes.
/// </summary>
public sealed class DbConnectionScope : IDisposable
{
private static readonly AsyncLocal<DbConnectionScope> _asyncLocal = new AsyncLocal<DbConnectionScope>();
private static DbConnectionScope _currentScope
{
get
{
return _asyncLocal.Value;
}
set
{
_asyncLocal.Value = value;
}
}
private static ConditionalWeakTable<DbConnection, Task<DbConnection>> __openAsyncTasks = new ConditionalWeakTable<DbConnection, Task<DbConnection>>();
private readonly object SyncRoot = new object();
private DbConnectionScope _outerScope;
private string _transId;
private DbConnectionScopeOption _option;
private Lazy<ConcurrentDictionary<string, DbConnection>> _connections;
private bool _isDisposed;
public static DbConnectionScope Current
{
get
{
return _currentScope;
}
}
public static TConnection GetOpenConnection<TConnection>(IDbConnectionFactory factory, string connectionName)
where TConnection: DbConnection
{
return (TConnection)DbConnectionScope.Current.GetOpenConnection(factory, connectionName);
}
public static async Task<TConnection> GetOpenConnectionAsync<TConnection>(IDbConnectionFactory factory, string connectionName)
where TConnection : DbConnection
{
return (TConnection) await DbConnectionScope.Current.GetOpenConnectionAsync(factory, connectionName);
}
private static string CurrentTransactionId
{
get
{
string currTransId = string.Empty;
var currTran = Transaction.Current;
if (currTran != null)
{
currTransId = currTran.TransactionInformation.LocalIdentifier;
}
return currTransId;
}
}
public DbConnectionScope()
: this(DbConnectionScopeOption.Required)
{
}
public DbConnectionScope(DbConnectionScopeOption option)
{
_isDisposed = true; // short circuit Dispose until we're properly set up
this._transId = CurrentTransactionId;
this._option = option;
this._outerScope = null;
DbConnectionScope outerScope = _currentScope;
bool isAllocateOk = (outerScope == null || outerScope._transId != this._transId);
if (option == DbConnectionScopeOption.RequiresNew ||
(option == DbConnectionScopeOption.Required && isAllocateOk))
{
// only bother allocating dictionary if we're going to push
_connections = new Lazy<ConcurrentDictionary<string,DbConnection>>(()=> new ConcurrentDictionary<string,DbConnection>(), true);
// Devnote: Order of initial assignment is important in cases of failure!
_outerScope = outerScope;
_isDisposed = false;
_currentScope = this;
}
}
~DbConnectionScope()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public bool TryGetConnection(string connectionName, out DbConnection connection)
{
this.CheckTransaction();
lock (this.SyncRoot)
{
return TryGetConnectionByName(connectionName, out connection);
}
}
public DbConnection GetConnection(IDbConnectionFactory factory, string connectionName)
{
this.CheckTransaction();
DbConnection result = null;
lock (this.SyncRoot)
{
if (!this.TryGetConnectionByName(this, connectionName, out result))
{
result = factory.CreateConnection(connectionName);
_connections.Value.TryAdd(connectionName, result);
}
}
return result;
}
public DbConnection GetOpenConnection(IDbConnectionFactory factory, string connectionName)
{
return this.GetOpenConnectionInternal(factory, connectionName, 0);
}
public Task<DbConnection> GetOpenConnectionAsync(IDbConnectionFactory factory, string connectionName)
{
return this.GetOpenConnectionAsyncInternal(factory, connectionName, 0);
}
public DbConnectionScopeOption Option
{
get { return _option; }
}
private DbConnection GetOpenConnectionInternal(IDbConnectionFactory factory, string connectionName, int level)
{
if (level > 1)
throw new OverflowException(string.Format("Exceeded maximum times to get open connection: {0}", connectionName));
DbConnection result = this.GetConnection(factory, connectionName);
try
{
lock (result)
{
Task<DbConnection> openAsyncTask;
if (__openAsyncTasks.TryGetValue(result, out openAsyncTask))
{
openAsyncTask.Wait();
}
else
{
if (result.State == ConnectionState.Closed)
result.Open();
else if (result.State == ConnectionState.Broken && TryRemoveConnection(result))
{
return GetOpenConnectionInternal(factory, connectionName, level+1);
}
}
}
return result;
}
catch
{
TryRemoveConnection(result);
throw;
}
}
private Task<DbConnection> GetOpenConnectionAsyncInternal(IDbConnectionFactory factory, string connectionName, int level)
{
if (level > 1)
{
var error = new OverflowException(string.Format("Exceeded maximum times to get open connection: {0}", connectionName));
TaskCompletionSource<DbConnection> tcs = new TaskCompletionSource<DbConnection>();
tcs.SetException(error);
return tcs.Task;
}
DbConnection result = this.GetConnection(factory, connectionName);
lock (result)
{
Task<DbConnection> openAsyncTask;
if (__openAsyncTasks.TryGetValue(result, out openAsyncTask))
{
return openAsyncTask;
}
if (result.State == ConnectionState.Closed)
{
TaskCompletionSource<DbConnection> tcs = new TaskCompletionSource<DbConnection>();
var task = result.OpenAsync();
task.ContinueWith((antecedent) =>
{
if (_isDisposed)
{
tcs.SetCanceled();
return;
}
try
{
if (antecedent.IsFaulted)
{
TryRemoveConnection(result);
tcs.SetException(antecedent.Exception);
}
else if (antecedent.IsCanceled)
{
tcs.SetCanceled();
}
else
{
tcs.SetResult(result);
}
}
finally
{
__openAsyncTasks.Remove(result);
}
});
openAsyncTask = tcs.Task;
__openAsyncTasks.Add(result, openAsyncTask);
return openAsyncTask;
}
else if (result.State == ConnectionState.Broken && TryRemoveConnection(result))
{
return GetOpenConnectionAsyncInternal(factory, connectionName, level+1);
}
else
{
return Task.FromResult(result);
}
}
}
/// <summary>
/// In case of DbConnectionScopeOption equals Required
/// it returns outer scope with the same transaction id on the scope
/// typically it will be when TransactionScopeOption is Suppress on this scope and the outer scope
/// </summary>
/// <param name="resultScope"></param>
/// <returns></returns>
private bool TryGetCompatableScope(out DbConnectionScope resultScope)
{
resultScope = null;
if (this._option == DbConnectionScopeOption.RequiresNew)
return false;
resultScope = this._outerScope;
while (resultScope != null)
{
//find the outer scope with the same transaction id
if (!resultScope._isDisposed && resultScope._transId == this._transId)
break;
else
resultScope = resultScope._outerScope;
}
return resultScope != null;
}
private bool TryGetConnectionByName(DbConnectionScope scope, string connectionName, out DbConnection connection)
{
connection = null;
if (scope.TryGetConnectionByName(connectionName, out connection))
{
return true;
}
else if (scope.TryGetCompatableScope(out scope))
{
if (this.TryGetConnectionByName(scope, connectionName, out connection))
return true;
else
return false;
}
return false;
}
private bool TryGetConnectionByName(string connectionName, out DbConnection connection)
{
connection = null;
lock (this.SyncRoot)
{
CheckDisposed();
if (!_connections.IsValueCreated)
return false;
return _connections.Value.TryGetValue(connectionName, out connection);
}
}
/// <summary>
/// Removes the connection from current scope
/// and if not removed it tries to remove it from outer scopes
/// </summary>
/// <param name="connection"></param>
/// <returns></returns>
private bool TryRemoveConnection(DbConnection connection)
{
var scope = this;
while (scope != null)
{
if (!scope._isDisposed && scope.TryRemoveConnectionInternal(connection))
return true;
else
scope = scope._outerScope;
}
return false;
}
/// <summary>
/// Removes the connection from current scope
/// </summary>
/// <param name="connection"></param>
/// <returns></returns>
private bool TryRemoveConnectionInternal(DbConnection connection)
{
lock (this.SyncRoot)
{
if (this._isDisposed)
return false;
if (!_connections.IsValueCreated)
return false;
string key = string.Empty;
var connections = _connections.Value;
foreach (var kvp in connections)
{
if (Object.ReferenceEquals(kvp.Value, connection))
{
key = kvp.Key;
break;
}
}
if (!string.IsNullOrEmpty(key))
{
DbConnection tmp;
if (connections.TryRemove(key, out tmp))
{
tmp.Dispose();
return true;
}
}
return false;
}
}
/// <summary>
/// Handle calling API function after instance has been disposed
/// </summary>
private void CheckDisposed()
{
if (_isDisposed)
{
throw new ObjectDisposedException("DbConnectionScope");
}
}
private void CheckTransaction()
{
string id = CurrentTransactionId;
if (id != this._transId)
{
throw new InvalidOperationException("Transaction is not the same when DbConnectionScope was created");
}
}
private void Dispose(bool disposing)
{
if (_isDisposed)
return;
if (disposing)
{
lock (this.SyncRoot)
{
if (_isDisposed)
return;
DbConnectionScope outerScope = _outerScope;
while (outerScope != null && outerScope._isDisposed)
{
outerScope = outerScope._outerScope;
}
try
{
_currentScope = outerScope;
}
finally
{
_isDisposed = true;
if (_connections.IsValueCreated)
{
var connections = _connections.Value.Values.ToArray();
_connections.Value.Clear();
foreach (DbConnection connection in connections)
{
if (connection.State != ConnectionState.Closed)
{
connection.Dispose();
}
}
}
}
}
}
else
{
_isDisposed = true;
}
}
}
}
| |
// 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!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedGlobalPublicDelegatedPrefixesClientSnippets
{
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteGlobalPublicDelegatedPrefixeRequest, CallSettings)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = GlobalPublicDelegatedPrefixesClient.Create();
// Initialize request argument(s)
DeleteGlobalPublicDelegatedPrefixeRequest request = new DeleteGlobalPublicDelegatedPrefixeRequest
{
RequestId = "",
PublicDelegatedPrefix = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = globalPublicDelegatedPrefixesClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = globalPublicDelegatedPrefixesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteGlobalPublicDelegatedPrefixeRequest, CallSettings)
// Additional: DeleteAsync(DeleteGlobalPublicDelegatedPrefixeRequest, CancellationToken)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = await GlobalPublicDelegatedPrefixesClient.CreateAsync();
// Initialize request argument(s)
DeleteGlobalPublicDelegatedPrefixeRequest request = new DeleteGlobalPublicDelegatedPrefixeRequest
{
RequestId = "",
PublicDelegatedPrefix = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await globalPublicDelegatedPrefixesClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await globalPublicDelegatedPrefixesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, CallSettings)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = GlobalPublicDelegatedPrefixesClient.Create();
// Initialize request argument(s)
string project = "";
string publicDelegatedPrefix = "";
// Make the request
lro::Operation<Operation, Operation> response = globalPublicDelegatedPrefixesClient.Delete(project, publicDelegatedPrefix);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = globalPublicDelegatedPrefixesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, CallSettings)
// Additional: DeleteAsync(string, string, CancellationToken)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = await GlobalPublicDelegatedPrefixesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string publicDelegatedPrefix = "";
// Make the request
lro::Operation<Operation, Operation> response = await globalPublicDelegatedPrefixesClient.DeleteAsync(project, publicDelegatedPrefix);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await globalPublicDelegatedPrefixesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetGlobalPublicDelegatedPrefixeRequest, CallSettings)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = GlobalPublicDelegatedPrefixesClient.Create();
// Initialize request argument(s)
GetGlobalPublicDelegatedPrefixeRequest request = new GetGlobalPublicDelegatedPrefixeRequest
{
PublicDelegatedPrefix = "",
Project = "",
};
// Make the request
PublicDelegatedPrefix response = globalPublicDelegatedPrefixesClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetGlobalPublicDelegatedPrefixeRequest, CallSettings)
// Additional: GetAsync(GetGlobalPublicDelegatedPrefixeRequest, CancellationToken)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = await GlobalPublicDelegatedPrefixesClient.CreateAsync();
// Initialize request argument(s)
GetGlobalPublicDelegatedPrefixeRequest request = new GetGlobalPublicDelegatedPrefixeRequest
{
PublicDelegatedPrefix = "",
Project = "",
};
// Make the request
PublicDelegatedPrefix response = await globalPublicDelegatedPrefixesClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, CallSettings)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = GlobalPublicDelegatedPrefixesClient.Create();
// Initialize request argument(s)
string project = "";
string publicDelegatedPrefix = "";
// Make the request
PublicDelegatedPrefix response = globalPublicDelegatedPrefixesClient.Get(project, publicDelegatedPrefix);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, CallSettings)
// Additional: GetAsync(string, string, CancellationToken)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = await GlobalPublicDelegatedPrefixesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string publicDelegatedPrefix = "";
// Make the request
PublicDelegatedPrefix response = await globalPublicDelegatedPrefixesClient.GetAsync(project, publicDelegatedPrefix);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertGlobalPublicDelegatedPrefixeRequest, CallSettings)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = GlobalPublicDelegatedPrefixesClient.Create();
// Initialize request argument(s)
InsertGlobalPublicDelegatedPrefixeRequest request = new InsertGlobalPublicDelegatedPrefixeRequest
{
RequestId = "",
PublicDelegatedPrefixResource = new PublicDelegatedPrefix(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = globalPublicDelegatedPrefixesClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = globalPublicDelegatedPrefixesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertGlobalPublicDelegatedPrefixeRequest, CallSettings)
// Additional: InsertAsync(InsertGlobalPublicDelegatedPrefixeRequest, CancellationToken)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = await GlobalPublicDelegatedPrefixesClient.CreateAsync();
// Initialize request argument(s)
InsertGlobalPublicDelegatedPrefixeRequest request = new InsertGlobalPublicDelegatedPrefixeRequest
{
RequestId = "",
PublicDelegatedPrefixResource = new PublicDelegatedPrefix(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await globalPublicDelegatedPrefixesClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await globalPublicDelegatedPrefixesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, PublicDelegatedPrefix, CallSettings)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = GlobalPublicDelegatedPrefixesClient.Create();
// Initialize request argument(s)
string project = "";
PublicDelegatedPrefix publicDelegatedPrefixResource = new PublicDelegatedPrefix();
// Make the request
lro::Operation<Operation, Operation> response = globalPublicDelegatedPrefixesClient.Insert(project, publicDelegatedPrefixResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = globalPublicDelegatedPrefixesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, PublicDelegatedPrefix, CallSettings)
// Additional: InsertAsync(string, PublicDelegatedPrefix, CancellationToken)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = await GlobalPublicDelegatedPrefixesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
PublicDelegatedPrefix publicDelegatedPrefixResource = new PublicDelegatedPrefix();
// Make the request
lro::Operation<Operation, Operation> response = await globalPublicDelegatedPrefixesClient.InsertAsync(project, publicDelegatedPrefixResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await globalPublicDelegatedPrefixesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListGlobalPublicDelegatedPrefixesRequest, CallSettings)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = GlobalPublicDelegatedPrefixesClient.Create();
// Initialize request argument(s)
ListGlobalPublicDelegatedPrefixesRequest request = new ListGlobalPublicDelegatedPrefixesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<PublicDelegatedPrefixList, PublicDelegatedPrefix> response = globalPublicDelegatedPrefixesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (PublicDelegatedPrefix item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (PublicDelegatedPrefixList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PublicDelegatedPrefix item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PublicDelegatedPrefix> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PublicDelegatedPrefix item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListGlobalPublicDelegatedPrefixesRequest, CallSettings)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = await GlobalPublicDelegatedPrefixesClient.CreateAsync();
// Initialize request argument(s)
ListGlobalPublicDelegatedPrefixesRequest request = new ListGlobalPublicDelegatedPrefixesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<PublicDelegatedPrefixList, PublicDelegatedPrefix> response = globalPublicDelegatedPrefixesClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PublicDelegatedPrefix item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((PublicDelegatedPrefixList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PublicDelegatedPrefix item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PublicDelegatedPrefix> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PublicDelegatedPrefix item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, int?, CallSettings)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = GlobalPublicDelegatedPrefixesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<PublicDelegatedPrefixList, PublicDelegatedPrefix> response = globalPublicDelegatedPrefixesClient.List(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (PublicDelegatedPrefix item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (PublicDelegatedPrefixList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PublicDelegatedPrefix item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PublicDelegatedPrefix> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PublicDelegatedPrefix item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, int?, CallSettings)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = await GlobalPublicDelegatedPrefixesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<PublicDelegatedPrefixList, PublicDelegatedPrefix> response = globalPublicDelegatedPrefixesClient.ListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PublicDelegatedPrefix item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((PublicDelegatedPrefixList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PublicDelegatedPrefix item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PublicDelegatedPrefix> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PublicDelegatedPrefix item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void PatchRequestObject()
{
// Snippet: Patch(PatchGlobalPublicDelegatedPrefixeRequest, CallSettings)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = GlobalPublicDelegatedPrefixesClient.Create();
// Initialize request argument(s)
PatchGlobalPublicDelegatedPrefixeRequest request = new PatchGlobalPublicDelegatedPrefixeRequest
{
RequestId = "",
PublicDelegatedPrefixResource = new PublicDelegatedPrefix(),
PublicDelegatedPrefix = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = globalPublicDelegatedPrefixesClient.Patch(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = globalPublicDelegatedPrefixesClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchRequestObjectAsync()
{
// Snippet: PatchAsync(PatchGlobalPublicDelegatedPrefixeRequest, CallSettings)
// Additional: PatchAsync(PatchGlobalPublicDelegatedPrefixeRequest, CancellationToken)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = await GlobalPublicDelegatedPrefixesClient.CreateAsync();
// Initialize request argument(s)
PatchGlobalPublicDelegatedPrefixeRequest request = new PatchGlobalPublicDelegatedPrefixeRequest
{
RequestId = "",
PublicDelegatedPrefixResource = new PublicDelegatedPrefix(),
PublicDelegatedPrefix = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await globalPublicDelegatedPrefixesClient.PatchAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await globalPublicDelegatedPrefixesClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void Patch()
{
// Snippet: Patch(string, string, PublicDelegatedPrefix, CallSettings)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = GlobalPublicDelegatedPrefixesClient.Create();
// Initialize request argument(s)
string project = "";
string publicDelegatedPrefix = "";
PublicDelegatedPrefix publicDelegatedPrefixResource = new PublicDelegatedPrefix();
// Make the request
lro::Operation<Operation, Operation> response = globalPublicDelegatedPrefixesClient.Patch(project, publicDelegatedPrefix, publicDelegatedPrefixResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = globalPublicDelegatedPrefixesClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchAsync()
{
// Snippet: PatchAsync(string, string, PublicDelegatedPrefix, CallSettings)
// Additional: PatchAsync(string, string, PublicDelegatedPrefix, CancellationToken)
// Create client
GlobalPublicDelegatedPrefixesClient globalPublicDelegatedPrefixesClient = await GlobalPublicDelegatedPrefixesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string publicDelegatedPrefix = "";
PublicDelegatedPrefix publicDelegatedPrefixResource = new PublicDelegatedPrefix();
// Make the request
lro::Operation<Operation, Operation> response = await globalPublicDelegatedPrefixesClient.PatchAsync(project, publicDelegatedPrefix, publicDelegatedPrefixResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await globalPublicDelegatedPrefixesClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information
//
// XmlDsigC14NWithCommentsTransformTest.cs
// - Test Cases for XmlDsigC14NWithCommentsTransform
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Resolvers;
using Xunit;
namespace System.Security.Cryptography.Xml.Tests
{
// Note: GetInnerXml is protected in XmlDsigC14NWithCommentsTransform
// making it difficult to test properly. This class "open it up" :-)
public class UnprotectedXmlDsigC14NWithCommentsTransform : XmlDsigC14NWithCommentsTransform
{
public XmlNodeList UnprotectedGetInnerXml()
{
return base.GetInnerXml();
}
}
public class XmlDsigC14NWithCommentsTransformTest
{
[Fact]
public void Constructor()
{
XmlDsigC14NWithCommentsTransform xmlDsigC14NWithCommentsTransform = new XmlDsigC14NWithCommentsTransform();
Assert.Null(xmlDsigC14NWithCommentsTransform.Context);
Assert.Equal("http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments", xmlDsigC14NWithCommentsTransform.Algorithm);
Assert.Equal(new[] { typeof(Stream), typeof(XmlDocument), typeof(XmlNodeList) }, xmlDsigC14NWithCommentsTransform.InputTypes);
Assert.Equal(new[] { typeof(Stream) }, xmlDsigC14NWithCommentsTransform.OutputTypes);
}
[Fact]
public void GetInnerXml()
{
UnprotectedXmlDsigC14NWithCommentsTransform transform = new UnprotectedXmlDsigC14NWithCommentsTransform();
XmlNodeList xnl = transform.UnprotectedGetInnerXml();
Assert.Null(xnl);
}
[Theory]
[InlineData("")]
[InlineData(new byte[] { 0xBA, 0xD })]
public void LoadInput_UnsupportedType(object input)
{
XmlDsigC14NWithCommentsTransform xmlDsigC14NWithCommentsTransform = new XmlDsigC14NWithCommentsTransform();
AssertExtensions.Throws<ArgumentException>("obj", () => xmlDsigC14NWithCommentsTransform.LoadInput(input));
}
[Theory]
[InlineData(typeof(XmlDocument))]
[InlineData(typeof(XmlNodeList))]
public void GetOutput_UnsupportedType(Type type)
{
XmlDsigC14NWithCommentsTransform xmlDsigC14NWithCommentsTransform = new XmlDsigC14NWithCommentsTransform();
AssertExtensions.Throws<ArgumentException>("type", () => xmlDsigC14NWithCommentsTransform.GetOutput(type));
}
[Fact]
public void C14NSpecExample1()
{
XmlPreloadedResolver resolver = new XmlPreloadedResolver();
resolver.Add(TestHelpers.ToUri("world.dtd"), "");
string res = TestHelpers.ExecuteTransform(C14NSpecExample1Input, new XmlDsigC14NWithCommentsTransform(), Encoding.UTF8, resolver);
Assert.Equal(C14NSpecExample1Output, res);
}
[Theory]
[InlineData(C14NSpecExample2Input, C14NSpecExample2Output)]
[InlineData(C14NSpecExample3Input, C14NSpecExample3Output)]
[InlineData(C14NSpecExample4Input, C14NSpecExample4Output)]
public void C14NSpecExample(string input, string expectedOutput)
{
Assert.Equal(expectedOutput, ExecuteXmlDSigC14NTransform(input));
}
[Fact]
public void C14NSpecExample5()
{
XmlPreloadedResolver resolver = new XmlPreloadedResolver();
resolver.Add(TestHelpers.ToUri("doc.txt"), "world");
string input = C14NSpecExample5Input;
string result = ExecuteXmlDSigC14NTransform(input, Encoding.UTF8, resolver);
string expectedResult = C14NSpecExample5Output;
Assert.Equal(expectedResult, result);
}
[Fact]
public void C14NSpecExample6()
{
string res = ExecuteXmlDSigC14NTransform(C14NSpecExample6Input, Encoding.GetEncoding("ISO-8859-1"));
Assert.Equal(C14NSpecExample6Output, res);
}
private string ExecuteXmlDSigC14NTransform(string inputXml, Encoding encoding = null, XmlResolver resolver = null)
{
XmlDocument doc = new XmlDocument();
doc.XmlResolver = resolver;
doc.PreserveWhitespace = true;
doc.LoadXml(inputXml);
Encoding actualEncoding = encoding ?? Encoding.UTF8;
byte[] data = actualEncoding.GetBytes(inputXml);
using (Stream stream = new MemoryStream(data))
using (XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings { ValidationType = ValidationType.None, DtdProcessing = DtdProcessing.Parse, XmlResolver = resolver }))
{
doc.Load(reader);
XmlDsigC14NWithCommentsTransform transform = new XmlDsigC14NWithCommentsTransform();
transform.LoadInput(doc);
return TestHelpers.StreamToString((Stream) transform.GetOutput(), actualEncoding);
}
}
//
// Example 1 from C14N spec - PIs, Comments, and Outside of Document Element:
// http://www.w3.org/TR/xml-c14n#Example-OutsideDoc
//
static string C14NSpecExample1Input =>
"<?xml version=\"1.0\"?>\n" +
"\n" +
"<?xml-stylesheet href=\"doc.xsl\"\n" +
" type=\"text/xsl\" ?>\n" +
"\n" +
"<!DOCTYPE doc SYSTEM \"world.dtd\">\n" +
"\n" +
"<doc>Hello, world!<!-- Comment 1 --></doc>\n" +
"\n" +
"<?pi-without-data ?>\n\n" +
"<!-- Comment 2 -->\n\n" +
"<!-- Comment 3 -->\n";
static string C14NSpecExample1Output =>
"<?xml-stylesheet href=\"doc.xsl\"\n" +
" type=\"text/xsl\" ?>\n" +
"<doc>Hello, world!<!-- Comment 1 --></doc>\n" +
"<?pi-without-data?>\n" +
"<!-- Comment 2 -->\n" +
"<!-- Comment 3 -->";
//
// Example 2 from C14N spec - Whitespace in Document Content:
// http://www.w3.org/TR/xml-c14n#Example-WhitespaceInContent
//
const string C14NSpecExample2Input =
"<doc>\n" +
" <clean> </clean>\n" +
" <dirty> A B </dirty>\n" +
" <mixed>\n" +
" A\n" +
" <clean> </clean>\n" +
" B\n" +
" <dirty> A B </dirty>\n" +
" C\n" +
" </mixed>\n" +
"</doc>\n";
const string C14NSpecExample2Output =
"<doc>\n" +
" <clean> </clean>\n" +
" <dirty> A B </dirty>\n" +
" <mixed>\n" +
" A\n" +
" <clean> </clean>\n" +
" B\n" +
" <dirty> A B </dirty>\n" +
" C\n" +
" </mixed>\n" +
"</doc>";
//
// Example 3 from C14N spec - Start and End Tags:
// http://www.w3.org/TR/xml-c14n#Example-SETags
//
const string C14NSpecExample3Input =
"<!DOCTYPE doc [<!ATTLIST e9 attr CDATA \"default\">]>\n" +
"<doc>\n" +
" <e1 />\n" +
" <e2 ></e2>\n" +
" <e3 name = \"elem3\" id=\"elem3\" />\n" +
" <e4 name=\"elem4\" id=\"elem4\" ></e4>\n" +
" <e5 a:attr=\"out\" b:attr=\"sorted\" attr2=\"all\" attr=\"I\'m\"\n" +
" xmlns:b=\"http://www.ietf.org\" \n" +
" xmlns:a=\"http://www.w3.org\"\n" +
" xmlns=\"http://www.uvic.ca\"/>\n" +
" <e6 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" +
" <e7 xmlns=\"http://www.ietf.org\">\n" +
" <e8 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" +
" <e9 xmlns=\"\" xmlns:a=\"http://www.ietf.org\"/>\n" +
" </e8>\n" +
" </e7>\n" +
" </e6>\n" +
"</doc>\n";
const string C14NSpecExample3Output =
"<doc>\n" +
" <e1></e1>\n" +
" <e2></e2>\n" +
" <e3 id=\"elem3\" name=\"elem3\"></e3>\n" +
" <e4 id=\"elem4\" name=\"elem4\"></e4>\n" +
" <e5 xmlns=\"http://www.uvic.ca\" xmlns:a=\"http://www.w3.org\" xmlns:b=\"http://www.ietf.org\" attr=\"I\'m\" attr2=\"all\" b:attr=\"sorted\" a:attr=\"out\"></e5>\n" +
" <e6 xmlns:a=\"http://www.w3.org\">\n" +
" <e7 xmlns=\"http://www.ietf.org\">\n" +
" <e8 xmlns=\"\">\n" +
" <e9 xmlns:a=\"http://www.ietf.org\" attr=\"default\"></e9>\n" +
// " <e9 xmlns:a=\"http://www.ietf.org\"></e9>\n" +
" </e8>\n" +
" </e7>\n" +
" </e6>\n" +
"</doc>";
//
// Example 4 from C14N spec - Character Modifications and Character References:
// http://www.w3.org/TR/xml-c14n#Example-Chars
//
// Aleksey:
// This test does not include "normId" element
// because it has an invalid ID attribute "id" which
// should be normalized by XML parser. Currently Mono
// does not support this (see comment after this example
// in the spec).
const string C14NSpecExample4Input =
"<!DOCTYPE doc [<!ATTLIST normId id ID #IMPLIED>]>\n" +
"<doc>\n" +
" <text>First line
 Second line</text>\n" +
" <value>2</value>\n" +
" <compute><![CDATA[value>\"0\" && value<\"10\" ?\"valid\":\"error\"]]></compute>\n" +
" <compute expr=\'value>\"0\" && value<\"10\" ?\"valid\":\"error\"\'>valid</compute>\n" +
" <norm attr=\' '   
	 ' \'/>\n" +
// " <normId id=\' '   
	 ' \'/>\n" +
"</doc>\n";
const string C14NSpecExample4Output =
"<doc>\n" +
" <text>First line
\n" +
"Second line</text>\n" +
" <value>2</value>\n" +
" <compute>value>\"0\" && value<\"10\" ?\"valid\":\"error\"</compute>\n" +
" <compute expr=\"value>"0" && value<"10" ?"valid":"error"\">valid</compute>\n" +
" <norm attr=\" \' 
	 \' \"></norm>\n" +
// " <normId id=\"\' 
	 \'\"></normId>\n" +
"</doc>";
//
// Example 5 from C14N spec - Entity References:
// http://www.w3.org/TR/xml-c14n#Example-Entities
//
static string C14NSpecExample5Input =>
"<!DOCTYPE doc [\n" +
"<!ATTLIST doc attrExtEnt ENTITY #IMPLIED>\n" +
"<!ENTITY ent1 \"Hello\">\n" +
$"<!ENTITY ent2 SYSTEM \"doc.txt\">\n" +
"<!ENTITY entExt SYSTEM \"earth.gif\" NDATA gif>\n" +
"<!NOTATION gif SYSTEM \"viewgif.exe\">\n" +
"]>\n" +
"<doc attrExtEnt=\"entExt\">\n" +
" &ent1;, &ent2;!\n" +
"</doc>\n" +
"\n" +
$"<!-- Let doc.txt contain \"world\" (excluding the quotes) -->\n";
static string C14NSpecExample5Output =>
"<doc attrExtEnt=\"entExt\">\n" +
" Hello, world!\n" +
"</doc>\n" +
$"<!-- Let doc.txt contain \"world\" (excluding the quotes) -->";
//
// Example 6 from C14N spec - UTF-8 Encoding:
// http://www.w3.org/TR/xml-c14n#Example-UTF8
//
static string C14NSpecExample6Input =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" +
"<doc>©</doc>\n";
static string C14NSpecExample6Output =
"<doc>\xC2\xA9</doc>";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.