context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Microsoft.Win32;
namespace System.Globalization
{
public partial class JapaneseCalendar : Calendar
{
private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras";
private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive;
// We know about 4 built-in eras, however users may add additional era(s) from the
// registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
private static EraInfo[] GetJapaneseEras()
{
// Look in the registry key and see if we can find any ranges
int iFoundEras = 0;
EraInfo[] registryEraRanges = null;
try
{
// Need to access registry
RegistryKey key = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE).OpenSubKey(c_japaneseErasHive, false);
// Abort if we didn't find anything
if (key == null) return null;
// Look up the values in our reg key
String[] valueNames = key.GetValueNames();
if (valueNames != null && valueNames.Length > 0)
{
registryEraRanges = new EraInfo[valueNames.Length];
// Loop through the registry and read in all the values
for (int i = 0; i < valueNames.Length; i++)
{
// See if the era is a valid date
EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString());
// continue if not valid
if (era == null) continue;
// Remember we found one.
registryEraRanges[iFoundEras] = era;
iFoundEras++;
}
}
}
catch (System.Security.SecurityException)
{
// If we weren't allowed to read, then just ignore the error
return null;
}
catch (System.IO.IOException)
{
// If key is being deleted just ignore the error
return null;
}
catch (System.UnauthorizedAccessException)
{
// Registry access rights permissions, just ignore the error
return null;
}
//
// If we didn't have valid eras, then fail
// should have at least 4 eras
//
if (iFoundEras < 4) return null;
//
// Now we have eras, clean them up.
//
// Clean up array length
Array.Resize(ref registryEraRanges, iFoundEras);
// Sort them
Array.Sort(registryEraRanges, CompareEraRanges);
// Clean up era information
for (int i = 0; i < registryEraRanges.Length; i++)
{
// eras count backwards from length to 1 (and are 1 based indexes into string arrays)
registryEraRanges[i].era = registryEraRanges.Length - i;
// update max era year
if (i == 0)
{
// First range is 'til the end of the calendar
registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset;
}
else
{
// Rest are until the next era (remember most recent era is first in array)
registryEraRanges[i].maxEraYear = registryEraRanges[i - 1].yearOffset + 1 - registryEraRanges[i].yearOffset;
}
}
// Return our ranges
return registryEraRanges;
}
//
// Compare two era ranges, eg just the ticks
// Remember the era array is supposed to be in reverse chronological order
//
private static int CompareEraRanges(EraInfo a, EraInfo b)
{
return b.ticks.CompareTo(a.ticks);
}
//
// GetEraFromValue
//
// Parse the registry value name/data pair into an era
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
private static EraInfo GetEraFromValue(String value, String data)
{
// Need inputs
if (value == null || data == null) return null;
//
// Get Date
//
// Need exactly 10 characters in name for date
// yyyy.mm.dd although the . can be any character
if (value.Length != 10) return null;
int year;
int month;
int day;
ReadOnlySpan<char> valueSpan = value.AsReadOnlySpan();
if (!Int32.TryParse(valueSpan.Slice(0, 4), out year, style:NumberStyles.None, provider: NumberFormatInfo.InvariantInfo) ||
!Int32.TryParse(valueSpan.Slice(5, 2), out month, style:NumberStyles.None, provider: NumberFormatInfo.InvariantInfo) ||
!Int32.TryParse(valueSpan.Slice(8, 2), out day, style:NumberStyles.None, provider: NumberFormatInfo.InvariantInfo))
{
// Couldn't convert integer, fail
return null;
}
//
// Get Strings
//
// Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups)
String[] names = data.Split('_');
// Should have exactly 4 parts
// 0 - Era Name
// 1 - Abbreviated Era Name
// 2 - English Era Name
// 3 - Abbreviated English Era Name
if (names.Length != 4) return null;
// Each part should have data in it
if (names[0].Length == 0 ||
names[1].Length == 0 ||
names[2].Length == 0 ||
names[3].Length == 0)
return null;
//
// Now we have an era we can build
// Note that the era # and max era year need cleaned up after sorting
// Don't use the full English Era Name (names[2])
//
return new EraInfo(0, year, month, day, year - 1, 1, 0,
names[0], names[1], names[3]);
}
// PAL Layer ends here
private static string[] s_japaneseErasEnglishNames = new String[] { "M", "T", "S", "H" };
private static string GetJapaneseEnglishEraName(int era)
{
Debug.Assert(era > 0);
return era <= s_japaneseErasEnglishNames.Length ? s_japaneseErasEnglishNames[era - 1] : " ";
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime
{
using System.Threading;
using System.Security;
// IOThreadScheduler takes no locks due to contention problems on multiproc.
[Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.NonBlocking)]
class IOThreadScheduler
{
// Do not increase the maximum capacity above 32k! It must be a power of two, 0x8000 or less, in order to
// work with the strategy for 'headTail'.
const int MaximumCapacity = 0x8000;
[Fx.Tag.SecurityNote(Miscellaneous = "can be called outside user context")]
static class Bits
{
public const int HiShift = 32 / 2;
public const int HiOne = 1 << HiShift;
public const int LoHiBit = HiOne >> 1;
public const int HiHiBit = LoHiBit << HiShift;
public const int LoCountMask = LoHiBit - 1;
public const int HiCountMask = LoCountMask << HiShift;
public const int LoMask = LoCountMask | LoHiBit;
public const int HiMask = HiCountMask | HiHiBit;
public const int HiBits = LoHiBit | HiHiBit;
public static int Count(int slot)
{
return ((slot >> HiShift) - slot + 2 & LoMask) - 1;
}
public static int CountNoIdle(int slot)
{
return (slot >> HiShift) - slot + 1 & LoMask;
}
public static int IncrementLo(int slot)
{
return slot + 1 & LoMask | slot & HiMask;
}
// This method is only valid if you already know that (gate & HiBits) != 0.
public static bool IsComplete(int gate)
{
return (gate & HiMask) == gate << HiShift;
}
}
static IOThreadScheduler current = new IOThreadScheduler(32, 32);
readonly ScheduledOverlapped overlapped;
[Fx.Tag.Queue(typeof(Slot), Scope = Fx.Tag.Strings.AppDomain)]
[Fx.Tag.SecurityNote(Critical = "holds callbacks which get called outside of the app security context")]
[SecurityCritical]
readonly Slot[] slots;
[Fx.Tag.Queue(typeof(Slot), Scope = Fx.Tag.Strings.AppDomain)]
[Fx.Tag.SecurityNote(Critical = "holds callbacks which get called outside of the app security context")]
[SecurityCritical]
readonly Slot[] slotsLowPri;
// This field holds both the head (HiWord) and tail (LoWord) indicies into the slot array. This limits each
// value to 64k. In order to be able to distinguish wrapping the slot array (allowed) from wrapping the
// indicies relative to each other (not allowed), the size of the slot array is limited by an additional bit
// to 32k.
//
// The HiWord (head) holds the index of the last slot to have been scheduled into. The LoWord (tail) holds
// the index of the next slot to be dispatched from. When the queue is empty, the LoWord will be exactly
// one slot ahead of the HiWord. When the two are equal, the queue holds one item.
//
// When the tail is *two* slots ahead of the head (equivalent to a count of -1), that means the IOTS is
// idle. Hence, we start out headTail with a -2 (equivalent) in the head and zero in the tail.
[Fx.Tag.SynchronizationObject(Blocking = false, Kind = Fx.Tag.SynchronizationKind.InterlockedNoSpin)]
int headTail = -2 << Bits.HiShift;
// This field is the same except that it governs the low-priority work items. It doesn't have a concept
// of idle (-2) so starts empty (-1).
[Fx.Tag.SynchronizationObject(Blocking = false, Kind = Fx.Tag.SynchronizationKind.InterlockedNoSpin)]
int headTailLowPri = -1 << Bits.HiShift;
[Fx.Tag.SecurityNote(Critical = "creates a ScheduledOverlapped, touches slots, can be called outside of user context",
Safe = "The scheduled overlapped is only used internally, and flows security.")]
[SecuritySafeCritical]
IOThreadScheduler(int capacity, int capacityLowPri)
{
Fx.Assert(capacity > 0, "Capacity must be positive.");
Fx.Assert(capacity <= 0x8000, "Capacity cannot exceed 32k.");
Fx.Assert(capacityLowPri > 0, "Low-priority capacity must be positive.");
Fx.Assert(capacityLowPri <= 0x8000, "Low-priority capacity cannot exceed 32k.");
this.slots = new Slot[capacity];
Fx.Assert((this.slots.Length & SlotMask) == 0, "Capacity must be a power of two.");
this.slotsLowPri = new Slot[capacityLowPri];
Fx.Assert((this.slotsLowPri.Length & SlotMaskLowPri) == 0, "Low-priority capacity must be a power of two.");
this.overlapped = new ScheduledOverlapped();
}
[Fx.Tag.SecurityNote(Critical = "Calls into critical class CriticalHelper, doesn't flow context")]
[SecurityCritical]
public static void ScheduleCallbackNoFlow(Action<object> callback, object state)
{
if (callback == null)
{
throw Fx.Exception.ArgumentNull("callback");
}
bool queued = false;
while (!queued)
{
try { } finally
{
// Called in a finally because it needs to run uninterrupted in order to maintain consistency.
queued = IOThreadScheduler.current.ScheduleCallbackHelper(callback, state);
}
}
}
[Fx.Tag.SecurityNote(Critical = "Calls into critical class CriticalHelper, doesn't flow context")]
[SecurityCritical]
public static void ScheduleCallbackLowPriNoFlow(Action<object> callback, object state)
{
if (callback == null)
{
throw Fx.Exception.ArgumentNull("callback");
}
bool queued = false;
while (!queued)
{
try { } finally
{
// Called in a finally because it needs to run uninterrupted in order to maintain consistency.
queued = IOThreadScheduler.current.ScheduleCallbackLowPriHelper(callback, state);
}
}
}
// Returns true if successfully scheduled, false otherwise.
[Fx.Tag.SecurityNote(Critical = "calls into ScheduledOverlapped to post it, touches slots, can be called outside user context.")]
[SecurityCritical]
bool ScheduleCallbackHelper(Action<object> callback, object state)
{
// See if there's a free slot. Fortunately the overflow bit is simply lost.
int slot = Interlocked.Add(ref this.headTail, Bits.HiOne);
// If this brings us to 'empty', then the IOTS used to be 'idle'. Remember that, and increment
// again. This doesn't need to be in a loop, because until we call Post(), we can't go back to idle.
bool wasIdle = Bits.Count(slot) == 0;
if (wasIdle)
{
slot = Interlocked.Add(ref this.headTail, Bits.HiOne);
Fx.Assert(Bits.Count(slot) != 0, "IOTS went idle when it shouldn't have.");
}
// Check if we wrapped *around* to idle.
if (Bits.Count(slot) == -1)
{
// Since the capacity is limited to 32k, this means we wrapped the array at least twice. That's bad
// because headTail no longer knows how many work items we have - it looks like zero. This can
// only happen if 32k threads come through here while one is swapped out.
throw Fx.AssertAndThrowFatal("Head/Tail overflow!");
}
bool wrapped;
bool queued = this.slots[slot >> Bits.HiShift & SlotMask].TryEnqueueWorkItem(callback, state, out wrapped);
if (wrapped)
{
// Wrapped around the circular buffer. Create a new, bigger IOThreadScheduler.
IOThreadScheduler next =
new IOThreadScheduler(Math.Min(this.slots.Length * 2, MaximumCapacity), this.slotsLowPri.Length);
Interlocked.CompareExchange<IOThreadScheduler>(ref IOThreadScheduler.current, next, this);
}
if (wasIdle)
{
// It's our responsibility to kick off the overlapped.
this.overlapped.Post(this);
}
return queued;
}
// Returns true if successfully scheduled, false otherwise.
[Fx.Tag.SecurityNote(Critical = "calls into ScheduledOverlapped to post it, touches slots, can be called outside user context.")]
[SecurityCritical]
bool ScheduleCallbackLowPriHelper(Action<object> callback, object state)
{
// See if there's a free slot. Fortunately the overflow bit is simply lost.
int slot = Interlocked.Add(ref this.headTailLowPri, Bits.HiOne);
// If this is the first low-priority work item, make sure we're not idle.
bool wasIdle = false;
if (Bits.CountNoIdle(slot) == 1)
{
// Since Interlocked calls create a full thread barrier, this will read the value of headTail
// at the time of the Interlocked.Add or later. The invariant is that the IOTS is unidle at some
// point after the Add.
int ht = this.headTail;
if (Bits.Count(ht) == -1)
{
// Use a temporary local here to store the result of the Interlocked.CompareExchange. This
// works around a codegen bug in the 32-bit JIT (TFS 749182).
int interlockedResult = Interlocked.CompareExchange(ref this.headTail, ht + Bits.HiOne, ht);
if (ht == interlockedResult)
{
wasIdle = true;
}
}
}
// Check if we wrapped *around* to empty.
if (Bits.CountNoIdle(slot) == 0)
{
// Since the capacity is limited to 32k, this means we wrapped the array at least twice. That's bad
// because headTail no longer knows how many work items we have - it looks like zero. This can
// only happen if 32k threads come through here while one is swapped out.
throw Fx.AssertAndThrowFatal("Low-priority Head/Tail overflow!");
}
bool wrapped;
bool queued = this.slotsLowPri[slot >> Bits.HiShift & SlotMaskLowPri].TryEnqueueWorkItem(
callback, state, out wrapped);
if (wrapped)
{
IOThreadScheduler next =
new IOThreadScheduler(this.slots.Length, Math.Min(this.slotsLowPri.Length * 2, MaximumCapacity));
Interlocked.CompareExchange<IOThreadScheduler>(ref IOThreadScheduler.current, next, this);
}
if (wasIdle)
{
// It's our responsibility to kick off the overlapped.
this.overlapped.Post(this);
}
return queued;
}
[Fx.Tag.SecurityNote(Critical = "calls into ScheduledOverlapped to post it, touches slots, may be called outside of user context")]
[SecurityCritical]
void CompletionCallback(out Action<object> callback, out object state)
{
int slot = this.headTail;
int slotLowPri;
while (true)
{
Fx.Assert(Bits.Count(slot) != -1, "CompletionCallback called on idle IOTS!");
bool wasEmpty = Bits.Count(slot) == 0;
if (wasEmpty)
{
// We're about to set this to idle. First check the low-priority queue. This alone doesn't
// guarantee we service all the low-pri items - there hasn't even been an Interlocked yet. But
// we take care of that later.
slotLowPri = this.headTailLowPri;
while (Bits.CountNoIdle(slotLowPri) != 0)
{
if (slotLowPri == (slotLowPri = Interlocked.CompareExchange(ref this.headTailLowPri,
Bits.IncrementLo(slotLowPri), slotLowPri)))
{
this.overlapped.Post(this);
this.slotsLowPri[slotLowPri & SlotMaskLowPri].DequeueWorkItem(out callback, out state);
return;
}
}
}
if (slot == (slot = Interlocked.CompareExchange(ref this.headTail, Bits.IncrementLo(slot), slot)))
{
if (!wasEmpty)
{
this.overlapped.Post(this);
this.slots[slot & SlotMask].DequeueWorkItem(out callback, out state);
return;
}
// We just set the IOThreadScheduler to idle. Check if a low-priority item got added in the
// interim.
// Interlocked calls create a thread barrier, so this read will give us the value of
// headTailLowPri at the time of the interlocked that set us to idle, or later. The invariant
// here is that either the low-priority queue was empty at some point after we set the IOTS to
// idle (so that the next enqueue will notice, and issue a Post), or that the IOTS was unidle at
// some point after we set it to idle (so that the next attempt to go idle will verify that the
// low-priority queue is empty).
slotLowPri = this.headTailLowPri;
if (Bits.CountNoIdle(slotLowPri) != 0)
{
// Whoops, go back from being idle (unless someone else already did). If we go back, start
// over. (We still owe a Post.)
slot = Bits.IncrementLo(slot);
if (slot == Interlocked.CompareExchange(ref this.headTail, slot + Bits.HiOne, slot))
{
slot += Bits.HiOne;
continue;
}
// We know that there's a low-priority work item. But we also know that the IOThreadScheduler
// wasn't idle. It's best to let it take care of itself, since according to this method, we
// just set the IOThreadScheduler to idle so shouldn't take on any tasks.
}
break;
}
}
callback = null;
state = null;
return;
}
[Fx.Tag.SecurityNote(Critical = "touches slots, may be called outside of user context")]
[SecurityCritical]
bool TryCoalesce(out Action<object> callback, out object state)
{
int slot = this.headTail;
int slotLowPri;
while (true)
{
if (Bits.Count(slot) > 0)
{
if (slot == (slot = Interlocked.CompareExchange(ref this.headTail, Bits.IncrementLo(slot), slot)))
{
this.slots[slot & SlotMask].DequeueWorkItem(out callback, out state);
return true;
}
continue;
}
slotLowPri = this.headTailLowPri;
if (Bits.CountNoIdle(slotLowPri) > 0)
{
if (slotLowPri == (slotLowPri = Interlocked.CompareExchange(ref this.headTailLowPri,
Bits.IncrementLo(slotLowPri), slotLowPri)))
{
this.slotsLowPri[slotLowPri & SlotMaskLowPri].DequeueWorkItem(out callback, out state);
return true;
}
slot = this.headTail;
continue;
}
break;
}
callback = null;
state = null;
return false;
}
int SlotMask
{
[Fx.Tag.SecurityNote(Critical = "touches slots, may be called outside of user context")]
[SecurityCritical]
get
{
return this.slots.Length - 1;
}
}
int SlotMaskLowPri
{
[Fx.Tag.SecurityNote(Critical = "touches slots, may be called outside of user context")]
[SecurityCritical]
get
{
return this.slotsLowPri.Length - 1;
}
}
//
~IOThreadScheduler()
{
// If the AppDomain is shutting down, we may still have pending ops. The AppDomain shutdown will clean
// everything up.
if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload())
{
#if DEBUG
DebugVerifyHeadTail();
#endif
Cleanup();
}
}
[SecuritySafeCritical]
void Cleanup()
{
if (this.overlapped != null)
{
this.overlapped.Cleanup();
}
}
#if DEBUG
[SecuritySafeCritical]
private void DebugVerifyHeadTail()
{
if (this.slots != null)
{
// The headTail value could technically be zero if the constructor was aborted early. The
// constructor wasn't aborted early if the slot array got created.
Fx.Assert(Bits.Count(this.headTail) == -1, "IOTS finalized while not idle.");
for (int i = 0; i < this.slots.Length; i++)
{
this.slots[i].DebugVerifyEmpty();
}
}
if (this.slotsLowPri != null)
{
Fx.Assert(Bits.CountNoIdle(this.headTailLowPri) == 0, "IOTS finalized with low-priority items queued.");
for (int i = 0; i < this.slotsLowPri.Length; i++)
{
this.slotsLowPri[i].DebugVerifyEmpty();
}
}
}
#endif
// TryEnqueueWorkItem and DequeueWorkItem use the slot's 'gate' field for synchronization. Because the
// slot array is circular and there are no locks, we must assume that multiple threads can be entering each
// method simultaneously. If the first DequeueWorkItem occurs before the first TryEnqueueWorkItem, the
// sequencing (and the enqueue) fails.
//
// The gate is a 32-bit int divided into four fields. The bottom 15 bits (0x00007fff) are the count of
// threads that have entered TryEnqueueWorkItem. The first thread to enter is the one responsible for
// filling the slot with work. The 16th bit (0x00008000) is a flag indicating that the slot has been
// successfully filled. Only the first thread to enter TryEnqueueWorkItem can set this flag. The
// high-word (0x7fff0000) is the count of threads entering DequeueWorkItem. The first thread to enter
// is the one responsible for accepting (and eventually dispatching) the work in the slot. The
// high-bit (0x80000000) is a flag indicating that the slot has been successfully emptied.
//
// When the low-word and high-work counters are equal, and both bit flags have been set, the gate is considered
// 'complete' and can be reset back to zero. Any operation on the gate might bring it to this state.
// It's the responsibility of the thread that brings the gate to a completed state to reset it to zero.
// (It's possible that the gate will fall out of the completed state before it can be reset - that's ok,
// the next time it becomes completed it can be reset.)
//
// It's unlikely either count will ever go higher than 2 or 3.
//
// The value of 'callback' has these properties:
// - When the gate is zero, callback is null.
// - When the low-word count is non-zero, but the 0x8000 bit is unset, callback is writable by the thread
// that incremented the low word to 1. Its value is undefined for other threads. The thread that
// sets callback is responsible for setting the 0x8000 bit when it's done.
// - When the 0x8000 bit is set and the high-word count is zero, callback is valid. (It may be null.)
// - When the 0x8000 bit is set, the high-word count is non-zero, and the high bit is unset, callback is
// writable by the thread that incremented the high word to 1 *or* the thread that set the 0x8000 bit,
// whichever happened last. That thread can read the value and set callback to null. Its value is
// undefined for other threads. The thread that clears the callback is responsible for setting the
// high bit.
// - When the high bit is set, callback is null.
// - It's illegal for the gate to be in a state that would satisfy more than one of these conditions.
// - The state field follows the same rules as callback.
struct Slot
{
int gate;
Action<object> callback;
object state;
[Fx.Tag.SecurityNote(Miscellaneous = "called by critical code, can be called outside user context")]
public bool TryEnqueueWorkItem(Action<object> callback, object state, out bool wrapped)
{
// Register our arrival and check the state of this slot. If the slot was already full, we wrapped.
int gateSnapshot = Interlocked.Increment(ref this.gate);
wrapped = (gateSnapshot & Bits.LoCountMask) != 1;
if (wrapped)
{
if ((gateSnapshot & Bits.LoHiBit) != 0 && Bits.IsComplete(gateSnapshot))
{
Interlocked.CompareExchange(ref this.gate, 0, gateSnapshot);
}
return false;
}
Fx.Assert(this.callback == null, "Slot already has a work item.");
Fx.Assert((gateSnapshot & Bits.HiBits) == 0, "Slot already marked.");
this.state = state;
this.callback = callback;
// Set the special bit to show that the slot is filled.
gateSnapshot = Interlocked.Add(ref this.gate, Bits.LoHiBit);
Fx.Assert((gateSnapshot & Bits.HiBits) == Bits.LoHiBit, "Slot already empty.");
if ((gateSnapshot & Bits.HiCountMask) == 0)
{
// Good - no one has shown up looking for this work yet.
return true;
}
// Oops - someone already came looking for this work. We have to abort and reschedule.
this.state = null;
this.callback = null;
// Indicate that the slot is clear. We might be able to bypass setting the high bit.
if (gateSnapshot >> Bits.HiShift != (gateSnapshot & Bits.LoCountMask) ||
Interlocked.CompareExchange(ref this.gate, 0, gateSnapshot) != gateSnapshot)
{
gateSnapshot = Interlocked.Add(ref this.gate, Bits.HiHiBit);
if (Bits.IsComplete(gateSnapshot))
{
Interlocked.CompareExchange(ref this.gate, 0, gateSnapshot);
}
}
return false;
}
[Fx.Tag.SecurityNote(Miscellaneous = "called by critical code, can be called outside user context")]
public void DequeueWorkItem(out Action<object> callback, out object state)
{
// Stake our claim on the item.
int gateSnapshot = Interlocked.Add(ref this.gate, Bits.HiOne);
if ((gateSnapshot & Bits.LoHiBit) == 0)
{
// Whoops, a ----. The work item hasn't made it in yet. In this context, returning a null callback
// is treated like a degenrate work item (rather than an empty queue). The enqueuing thread will
// notice this ---- and reschedule the real work in a new slot. Do not reset the slot to zero,
// since it's still going to get enqueued into. (The enqueueing thread will reset it.)
callback = null;
state = null;
return;
}
// If we're the first, we get to do the work.
if ((gateSnapshot & Bits.HiCountMask) == Bits.HiOne)
{
callback = this.callback;
state = this.state;
this.state = null;
this.callback = null;
// Indicate that the slot is clear.
// We should be able to bypass setting the high-bit in the common case.
if ((gateSnapshot & Bits.LoCountMask) != 1 ||
Interlocked.CompareExchange(ref this.gate, 0, gateSnapshot) != gateSnapshot)
{
gateSnapshot = Interlocked.Add(ref this.gate, Bits.HiHiBit);
if (Bits.IsComplete(gateSnapshot))
{
Interlocked.CompareExchange(ref this.gate, 0, gateSnapshot);
}
}
}
else
{
callback = null;
state = null;
// If we're the last, we get to reset the slot.
if (Bits.IsComplete(gateSnapshot))
{
Interlocked.CompareExchange(ref this.gate, 0, gateSnapshot);
}
}
}
#if DEBUG
public void DebugVerifyEmpty()
{
Fx.Assert(this.gate == 0, "Finalized with unfinished slot.");
Fx.Assert(this.callback == null, "Finalized with leaked callback.");
Fx.Assert(this.state == null, "Finalized with leaked state.");
}
#endif
}
// A note about the IOThreadScheduler and the ScheduledOverlapped references:
// Although for each scheduler we have a single instance of overlapped, we cannot point to the scheduler from the
// overlapped, through the entire lifetime of the overlapped. This is because the ScheduledOverlapped is pinned
// and if it has a reference to the IOTS, it would be rooted and the finalizer will never get called.
// Therefore, we are passing the reference, when we post a pending callback and reset it, once the callback was
// invoked; during that time the scheduler is rooted but in that time we don't want that it would be collected
// by the GC anyway.
[Fx.Tag.SecurityNote(Critical = "manages NativeOverlapped instance, can be called outside user context")]
[SecurityCritical]
unsafe class ScheduledOverlapped
{
readonly NativeOverlapped* nativeOverlapped;
IOThreadScheduler scheduler;
public ScheduledOverlapped()
{
this.nativeOverlapped = (new Overlapped()).UnsafePack(
Fx.ThunkCallback(new IOCompletionCallback(IOCallback)), null);
}
[Fx.Tag.SecurityNote(Miscellaneous = "note that in some hosts this runs without any user context on the stack")]
void IOCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
// Unhook the IOThreadScheduler ASAP to prevent it from leaking.
IOThreadScheduler iots = this.scheduler;
this.scheduler = null;
Fx.Assert(iots != null, "Overlapped completed without a scheduler.");
Action<object> callback;
object state;
try { } finally
{
// Called in a finally because it needs to run uninterrupted in order to maintain consistency.
iots.CompletionCallback(out callback, out state);
}
bool found = true;
while (found)
{
// The callback can be null if synchronization misses result in unsuable slots. Keep going onto
// the next slot in such cases until there are no more slots.
if (callback != null)
{
callback(state);
}
try { } finally
{
// Called in a finally because it needs to run uninterrupted in order to maintain consistency.
found = iots.TryCoalesce(out callback, out state);
}
}
}
public void Post(IOThreadScheduler iots)
{
Fx.Assert(this.scheduler == null, "Post called on an overlapped that is already posted.");
Fx.Assert(iots != null, "Post called with a null scheduler.");
this.scheduler = iots;
ThreadPool.UnsafeQueueNativeOverlapped(this.nativeOverlapped);
}
[Fx.Tag.SecurityNote(Miscellaneous = "note that this runs on the finalizer thread")]
public void Cleanup()
{
if (this.scheduler != null)
{
throw Fx.AssertAndThrowFatal("Cleanup called on an overlapped that is in-flight.");
}
Overlapped.Free(this.nativeOverlapped);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
public class HttpWebRequest : WebRequest
{
private const int DefaultContinueTimeout = 350; // Current default value from .NET Desktop.
private WebHeaderCollection _webHeaderCollection = new WebHeaderCollection();
private Uri _requestUri;
private string _originVerb = HttpMethod.Get.Method;
// We allow getting and setting this (to preserve app-compat). But we don't do anything with it
// as the underlying System.Net.Http API doesn't support it.
private int _continueTimeout = DefaultContinueTimeout;
private bool _allowReadStreamBuffering = false;
private CookieContainer _cookieContainer = null;
private ICredentials _credentials = null;
private IWebProxy _proxy = WebRequest.DefaultWebProxy;
private Task<HttpResponseMessage> _sendRequestTask;
private int _beginGetRequestStreamCalled = 0;
private int _beginGetResponseCalled = 0;
private int _endGetRequestStreamCalled = 0;
private int _endGetResponseCalled = 0;
private RequestStream _requestStream;
private TaskCompletionSource<Stream> _requestStreamOperation = null;
private TaskCompletionSource<WebResponse> _responseOperation = null;
private AsyncCallback _requestStreamCallback = null;
private AsyncCallback _responseCallback = null;
private int _abortCalled = 0;
private CancellationTokenSource _sendRequestCts;
internal HttpWebRequest(Uri uri)
{
_requestUri = uri;
}
private void SetSpecialHeaders(string HeaderName, string value)
{
_webHeaderCollection.Remove(HeaderName);
if (!string.IsNullOrEmpty(value))
{
_webHeaderCollection[HeaderName] = value;
}
}
public string Accept
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Accept];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.Accept, value);
}
}
public virtual bool AllowReadStreamBuffering
{
get
{
return _allowReadStreamBuffering;
}
set
{
_allowReadStreamBuffering = value;
}
}
public override String ContentType
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.ContentType];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.ContentType, value);
}
}
public int ContinueTimeout
{
get
{
return _continueTimeout;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if ((value < 0) && (value != System.Threading.Timeout.Infinite))
{
throw new ArgumentOutOfRangeException("value", SR.net_io_timeout_use_ge_zero);
}
_continueTimeout = value;
}
}
public virtual CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
_cookieContainer = value;
}
}
public override ICredentials Credentials
{
get
{
return _credentials;
}
set
{
_credentials = value;
}
}
public virtual bool HaveResponse
{
get
{
return (_sendRequestTask != null) && (_sendRequestTask.Status == TaskStatus.RanToCompletion);
}
}
public override WebHeaderCollection Headers
{
get
{
return _webHeaderCollection;
}
set
{
// We can't change headers after they've already been sent.
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
WebHeaderCollection webHeaders = value;
WebHeaderCollection newWebHeaders = new WebHeaderCollection();
// Copy And Validate -
// Handle the case where their object tries to change
// name, value pairs after they call set, so therefore,
// we need to clone their headers.
foreach (String headerName in webHeaders.AllKeys)
{
newWebHeaders[headerName] = webHeaders[headerName];
}
_webHeaderCollection = newWebHeaders;
}
}
public override string Method
{
get
{
return _originVerb;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_badmethod, "value");
}
if (HttpValidationHelpers.IsInvalidMethodOrHeaderString(value))
{
throw new ArgumentException(SR.net_badmethod, "value");
}
_originVerb = value;
}
}
public override Uri RequestUri
{
get
{
return _requestUri;
}
}
public virtual bool SupportsCookieContainer
{
get
{
return true;
}
}
public override bool UseDefaultCredentials
{
get
{
return (_credentials == CredentialCache.DefaultCredentials);
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
// Match Desktop behavior. Changing this property will also
// change the .Credentials property as well.
_credentials = value ? CredentialCache.DefaultCredentials : null;
}
}
public override IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
// We can't change the proxy while the request is already fired.
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_proxy = value;
}
}
public override void Abort()
{
if (Interlocked.Exchange(ref _abortCalled, 1) != 0)
{
return;
}
// .NET Desktop behavior requires us to invoke outstanding callbacks
// before returning if used in either the BeginGetRequestStream or
// BeginGetResponse methods.
//
// If we can transition the task to the canceled state, then we invoke
// the callback. If we can't transition the task, it is because it is
// already in the terminal state and the callback has already been invoked
// via the async task continuation.
if (_responseOperation != null)
{
if (_responseOperation.TrySetCanceled() && _responseCallback != null)
{
_responseCallback(_responseOperation.Task);
}
// Cancel the underlying send operation.
Debug.Assert(_sendRequestCts != null);
_sendRequestCts.Cancel();
}
else if (_requestStreamOperation != null)
{
if (_requestStreamOperation.TrySetCanceled() && _requestStreamCallback != null)
{
_requestStreamCallback(_requestStreamOperation.Task);
}
}
}
private Task<Stream> GetRequestStream()
{
CheckAbort();
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
// Match Desktop behavior: prevent someone from getting a request stream
// if the protocol verb/method doesn't support it. Note that this is not
// entirely compliant RFC2616 for the aforementioned compatbility reasons.
if (string.Equals(HttpMethod.Get.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals(HttpMethod.Head.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals("CONNECT", _originVerb, StringComparison.OrdinalIgnoreCase))
{
throw new ProtocolViolationException(SR.net_nouploadonget);
}
_requestStream = new RequestStream();
return Task.FromResult((Stream)_requestStream);
}
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, Object state)
{
CheckAbort();
if (Interlocked.Exchange(ref _beginGetRequestStreamCalled, 1) != 0)
{
throw new InvalidOperationException(SR.net_repcall);
}
_requestStreamCallback = callback;
_requestStreamOperation = GetRequestStream().ToApm(callback, state);
return _requestStreamOperation.Task;
}
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
CheckAbort();
if (asyncResult == null || !(asyncResult is Task<Stream>))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, "asyncResult");
}
if (Interlocked.Exchange(ref _endGetRequestStreamCalled, 1) != 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetRequestStream"));
}
Stream stream;
try
{
stream = ((Task<Stream>)asyncResult).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
return stream;
}
private async Task<WebResponse> SendRequest()
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
var handler = new HttpClientHandler();
var client = new HttpClient(handler);
var request = new HttpRequestMessage(new HttpMethod(_originVerb), _requestUri);
if (_requestStream != null)
{
ArraySegment<byte> bytes = _requestStream.GetBuffer();
request.Content = new ByteArrayContent(bytes.Array, bytes.Offset, bytes.Count);
}
// Set to match original defaults of HttpWebRequest.
// HttpClientHandler.AutomaticDecompression defaults to true; set it to false to match the desktop behavior
handler.AutomaticDecompression = DecompressionMethods.None;
handler.Credentials = _credentials;
if (_cookieContainer != null)
{
handler.CookieContainer = _cookieContainer;
Debug.Assert(handler.UseCookies); // Default of handler.UseCookies is true.
}
else
{
handler.UseCookies = false;
}
Debug.Assert(handler.UseProxy); // Default of handler.UseProxy is true.
Debug.Assert(handler.Proxy == null); // Default of handler.Proxy is null.
if (_proxy == null)
{
handler.UseProxy = false;
}
else
{
handler.Proxy = _proxy;
}
// Copy the HttpWebRequest request headers from the WebHeaderCollection into HttpRequestMessage.Headers and
// HttpRequestMessage.Content.Headers.
foreach (string headerName in _webHeaderCollection)
{
// The System.Net.Http APIs require HttpRequestMessage headers to be properly divided between the request headers
// collection and the request content headers colllection for all well-known header names. And custom headers
// are only allowed in the request headers collection and not in the request content headers collection. If a well-known
// content related (entity-body) header is found and there is no actual content being sent (i.e. it's a GET verb),
// then we'll need to drop the header on the floor.
if (IsWellKnownContentHeader(headerName))
{
if (request.Content != null)
{
request.Content.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
}
else
{
request.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
}
_sendRequestTask = client.SendAsync(
request,
_allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
_sendRequestCts.Token);
HttpResponseMessage responseMessage = await _sendRequestTask.ConfigureAwait(false);
HttpWebResponse response = new HttpWebResponse(responseMessage, _requestUri, _cookieContainer);
if (!responseMessage.IsSuccessStatusCode)
{
throw new WebException(
SR.Format(SR.net_servererror, (int)response.StatusCode, response.StatusDescription),
null,
WebExceptionStatus.ProtocolError,
response);
}
return response;
}
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
CheckAbort();
if (Interlocked.Exchange(ref _beginGetResponseCalled, 1) != 0)
{
throw new InvalidOperationException(SR.net_repcall);
}
_sendRequestCts = new CancellationTokenSource();
_responseCallback = callback;
_responseOperation = SendRequest().ToApm(callback, state);
return _responseOperation.Task;
}
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
CheckAbort();
if (asyncResult == null || !(asyncResult is Task<WebResponse>))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, "asyncResult");
}
if (Interlocked.Exchange(ref _endGetResponseCalled, 1) != 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse"));
}
WebResponse response;
try
{
response = ((Task<WebResponse>)asyncResult).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
return response;
}
private bool RequestSubmitted
{
get
{
return _sendRequestTask != null;
}
}
private void CheckAbort()
{
if (Volatile.Read(ref _abortCalled) == 1)
{
throw new WebException(SR.net_reqaborted, WebExceptionStatus.RequestCanceled);
}
}
private readonly static string[] s_wellKnownContentHeaders = {
HttpKnownHeaderNames.ContentDisposition,
HttpKnownHeaderNames.ContentEncoding,
HttpKnownHeaderNames.ContentLanguage,
HttpKnownHeaderNames.ContentLength,
HttpKnownHeaderNames.ContentLocation,
HttpKnownHeaderNames.ContentMD5,
HttpKnownHeaderNames.ContentRange,
HttpKnownHeaderNames.ContentType,
HttpKnownHeaderNames.Expires,
HttpKnownHeaderNames.LastModified
};
private bool IsWellKnownContentHeader(string header)
{
foreach (string contentHeaderName in s_wellKnownContentHeaders)
{
if (string.Equals(header, contentHeaderName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
}
| |
/*
* 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 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.Collections.Generic;
using System.IO;
using System.Xml;
using log4net.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Tests.Common;
using OpenMetaverse.StructuredData;
namespace OpenSim.Region.CoreModules.World.Serialiser.Tests
{
[TestFixture]
public class SerialiserTests : OpenSimTestCase
{
private string xml = @"
<SceneObjectGroup>
<RootPart>
<SceneObjectPart xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<AllowedDrop>false</AllowedDrop>
<CreatorID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></CreatorID>
<FolderID><Guid>e6a5a05e-e8cc-4816-8701-04165e335790</Guid></FolderID>
<InventorySerial>1</InventorySerial>
<TaskInventory />
<ObjectFlags>0</ObjectFlags>
<UUID><Guid>e6a5a05e-e8cc-4816-8701-04165e335790</Guid></UUID>
<LocalId>2698615125</LocalId>
<Name>PrimMyRide</Name>
<Material>0</Material>
<PassTouches>false</PassTouches>
<RegionHandle>1099511628032000</RegionHandle>
<ScriptAccessPin>0</ScriptAccessPin>
<GroupPosition><X>147.23</X><Y>92.698</Y><Z>22.78084</Z></GroupPosition>
<OffsetPosition><X>0</X><Y>0</Y><Z>0</Z></OffsetPosition>
<RotationOffset><X>-4.371139E-08</X><Y>-1</Y><Z>-4.371139E-08</Z><W>0</W></RotationOffset>
<Velocity><X>0</X><Y>0</Y><Z>0</Z></Velocity>
<RotationalVelocity><X>0</X><Y>0</Y><Z>0</Z></RotationalVelocity>
<AngularVelocity><X>0</X><Y>0</Y><Z>0</Z></AngularVelocity>
<Acceleration><X>0</X><Y>0</Y><Z>0</Z></Acceleration>
<Description />
<Color />
<Text />
<SitName />
<TouchName />
<LinkNum>0</LinkNum>
<ClickAction>0</ClickAction>
<Shape>
<ProfileCurve>1</ProfileCurve>
<TextureEntry>AAAAAAAAERGZmQAAAAAABQCVlZUAAAAAQEAAAABAQAAAAAAAAAAAAAAAAAAAAA==</TextureEntry>
<ExtraParams>AA==</ExtraParams>
<PathBegin>0</PathBegin>
<PathCurve>16</PathCurve>
<PathEnd>0</PathEnd>
<PathRadiusOffset>0</PathRadiusOffset>
<PathRevolutions>0</PathRevolutions>
<PathScaleX>100</PathScaleX>
<PathScaleY>100</PathScaleY>
<PathShearX>0</PathShearX>
<PathShearY>0</PathShearY>
<PathSkew>0</PathSkew>
<PathTaperX>0</PathTaperX>
<PathTaperY>0</PathTaperY>
<PathTwist>0</PathTwist>
<PathTwistBegin>0</PathTwistBegin>
<PCode>9</PCode>
<ProfileBegin>0</ProfileBegin>
<ProfileEnd>0</ProfileEnd>
<ProfileHollow>0</ProfileHollow>
<Scale><X>10</X><Y>10</Y><Z>0.5</Z></Scale>
<State>0</State>
<ProfileShape>Square</ProfileShape>
<HollowShape>Same</HollowShape>
<SculptTexture><Guid>00000000-0000-0000-0000-000000000000</Guid></SculptTexture>
<SculptType>0</SculptType><SculptData />
<FlexiSoftness>0</FlexiSoftness>
<FlexiTension>0</FlexiTension>
<FlexiDrag>0</FlexiDrag>
<FlexiGravity>0</FlexiGravity>
<FlexiWind>0</FlexiWind>
<FlexiForceX>0</FlexiForceX>
<FlexiForceY>0</FlexiForceY>
<FlexiForceZ>0</FlexiForceZ>
<LightColorR>0</LightColorR>
<LightColorG>0</LightColorG>
<LightColorB>0</LightColorB>
<LightColorA>1</LightColorA>
<LightRadius>0</LightRadius>
<LightCutoff>0</LightCutoff>
<LightFalloff>0</LightFalloff>
<LightIntensity>1</LightIntensity>
<FlexiEntry>false</FlexiEntry>
<LightEntry>false</LightEntry>
<SculptEntry>false</SculptEntry>
</Shape>
<Scale><X>10</X><Y>10</Y><Z>0.5</Z></Scale>
<UpdateFlag>0</UpdateFlag>
<SitTargetOrientation><X>0</X><Y>0</Y><Z>0</Z><W>1</W></SitTargetOrientation>
<SitTargetPosition><X>0</X><Y>0</Y><Z>0</Z></SitTargetPosition>
<SitTargetPositionLL><X>0</X><Y>0</Y><Z>0</Z></SitTargetPositionLL>
<SitTargetOrientationLL><X>0</X><Y>0</Y><Z>0</Z><W>1</W></SitTargetOrientationLL>
<ParentID>0</ParentID>
<CreationDate>1211330445</CreationDate>
<Category>0</Category>
<SalePrice>0</SalePrice>
<ObjectSaleType>0</ObjectSaleType>
<OwnershipCost>0</OwnershipCost>
<GroupID><Guid>00000000-0000-0000-0000-000000000000</Guid></GroupID>
<OwnerID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></OwnerID>
<LastOwnerID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></LastOwnerID>
<BaseMask>2147483647</BaseMask>
<OwnerMask>2147483647</OwnerMask>
<GroupMask>0</GroupMask>
<EveryoneMask>0</EveryoneMask>
<NextOwnerMask>2147483647</NextOwnerMask>
<Flags>None</Flags>
<CollisionSound><Guid>00000000-0000-0000-0000-000000000000</Guid></CollisionSound>
<CollisionSoundVolume>0</CollisionSoundVolume>
<DynAttrs>
<llsd>
<map>
<key>MyNamespace</key>
<map>
<key>MyStore</key>
<map>
<key>the answer</key>
<integer>42</integer>
</map>
</map>
</map>
</llsd>
</DynAttrs>
</SceneObjectPart>
</RootPart>
<OtherParts />
</SceneObjectGroup>";
private string badFloatsXml = @"
<SceneObjectGroup>
<RootPart>
<SceneObjectPart xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<AllowedDrop>false</AllowedDrop>
<CreatorID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></CreatorID>
<FolderID><Guid>e6a5a05e-e8cc-4816-8701-04165e335790</Guid></FolderID>
<InventorySerial>1</InventorySerial>
<TaskInventory />
<ObjectFlags>0</ObjectFlags>
<UUID><Guid>e6a5a05e-e8cc-4816-8701-04165e335790</Guid></UUID>
<LocalId>2698615125</LocalId>
<Name>NaughtyPrim</Name>
<Material>0</Material>
<PassTouches>false</PassTouches>
<RegionHandle>1099511628032000</RegionHandle>
<ScriptAccessPin>0</ScriptAccessPin>
<GroupPosition><X>147.23</X><Y>92.698</Y><Z>22.78084</Z></GroupPosition>
<OffsetPosition><X>0</X><Y>0</Y><Z>0</Z></OffsetPosition>
<RotationOffset><X>-4.371139E-08</X><Y>-1</Y><Z>-4.371139E-08</Z><W>0</W></RotationOffset>
<Velocity><X>0</X><Y>0</Y><Z>0</Z></Velocity>
<RotationalVelocity><X>0</X><Y>0</Y><Z>0</Z></RotationalVelocity>
<AngularVelocity><X>0</X><Y>0</Y><Z>0</Z></AngularVelocity>
<Acceleration><X>0</X><Y>0</Y><Z>0</Z></Acceleration>
<Description />
<Color />
<Text />
<SitName />
<TouchName />
<LinkNum>0</LinkNum>
<ClickAction>0</ClickAction>
<Shape>
<ProfileCurve>1</ProfileCurve>
<TextureEntry>AAAAAAAAERGZmQAAAAAABQCVlZUAAAAAQEAAAABAQAAAAAAAAAAAAAAAAAAAAA==</TextureEntry>
<ExtraParams>AA==</ExtraParams>
<PathBegin>0</PathBegin>
<PathCurve>16</PathCurve>
<PathEnd>0</PathEnd>
<PathRadiusOffset>0</PathRadiusOffset>
<PathRevolutions>0</PathRevolutions>
<PathScaleX>100</PathScaleX>
<PathScaleY>100</PathScaleY>
<PathShearX>0</PathShearX>
<PathShearY>0</PathShearY>
<PathSkew>0</PathSkew>
<PathTaperX>0</PathTaperX>
<PathTaperY>0</PathTaperY>
<PathTwist>0</PathTwist>
<PathTwistBegin>0</PathTwistBegin>
<PCode>9</PCode>
<ProfileBegin>0</ProfileBegin>
<ProfileEnd>0</ProfileEnd>
<ProfileHollow>0</ProfileHollow>
<Scale><X>10</X><Y>10</Y><Z>0.5</Z></Scale>
<State>0</State>
<ProfileShape>Square</ProfileShape>
<HollowShape>Same</HollowShape>
<SculptTexture><Guid>00000000-0000-0000-0000-000000000000</Guid></SculptTexture>
<SculptType>0</SculptType><SculptData />
<FlexiSoftness>0</FlexiSoftness>
<FlexiTension>0,5</FlexiTension>
<FlexiDrag>yo mamma</FlexiDrag>
<FlexiGravity>0</FlexiGravity>
<FlexiWind>0</FlexiWind>
<FlexiForceX>0</FlexiForceX>
<FlexiForceY>0</FlexiForceY>
<FlexiForceZ>0</FlexiForceZ>
<LightColorR>0</LightColorR>
<LightColorG>0</LightColorG>
<LightColorB>0</LightColorB>
<LightColorA>1</LightColorA>
<LightRadius>0</LightRadius>
<LightCutoff>0</LightCutoff>
<LightFalloff>0</LightFalloff>
<LightIntensity>1</LightIntensity>
<FlexiEntry>false</FlexiEntry>
<LightEntry>false</LightEntry>
<SculptEntry>false</SculptEntry>
</Shape>
<Scale><X>10</X><Y>10</Y><Z>0.5</Z></Scale>
<UpdateFlag>0</UpdateFlag>
<SitTargetOrientation><X>0</X><Y>0</Y><Z>0</Z><W>1</W></SitTargetOrientation>
<SitTargetPosition><X>0</X><Y>0</Y><Z>0</Z></SitTargetPosition>
<SitTargetPositionLL><X>0</X><Y>0</Y><Z>0</Z></SitTargetPositionLL>
<SitTargetOrientationLL><X>0</X><Y>0</Y><Z>0</Z><W>1</W></SitTargetOrientationLL>
<ParentID>0</ParentID>
<CreationDate>1211330445</CreationDate>
<Category>0</Category>
<SalePrice>0</SalePrice>
<ObjectSaleType>0</ObjectSaleType>
<OwnershipCost>0</OwnershipCost>
<GroupID><Guid>00000000-0000-0000-0000-000000000000</Guid></GroupID>
<OwnerID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></OwnerID>
<LastOwnerID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></LastOwnerID>
<BaseMask>2147483647</BaseMask>
<OwnerMask>2147483647</OwnerMask>
<GroupMask>0</GroupMask>
<EveryoneMask>0</EveryoneMask>
<NextOwnerMask>2147483647</NextOwnerMask>
<Flags>None</Flags>
<CollisionSound><Guid>00000000-0000-0000-0000-000000000000</Guid></CollisionSound>
<CollisionSoundVolume>0</CollisionSoundVolume>
</SceneObjectPart>
</RootPart>
<OtherParts />
</SceneObjectGroup>";
private string xml2 = @"
<SceneObjectGroup>
<SceneObjectPart xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<CreatorID><UUID>b46ef588-411e-4a8b-a284-d7dcfe8e74ef</UUID></CreatorID>
<FolderID><UUID>9be68fdd-f740-4a0f-9675-dfbbb536b946</UUID></FolderID>
<InventorySerial>0</InventorySerial>
<TaskInventory />
<ObjectFlags>0</ObjectFlags>
<UUID><UUID>9be68fdd-f740-4a0f-9675-dfbbb536b946</UUID></UUID>
<LocalId>720005</LocalId>
<Name>PrimFun</Name>
<Material>0</Material>
<RegionHandle>1099511628032000</RegionHandle>
<ScriptAccessPin>0</ScriptAccessPin>
<GroupPosition><X>153.9854</X><Y>121.4908</Y><Z>62.21781</Z></GroupPosition>
<OffsetPosition><X>0</X><Y>0</Y><Z>0</Z></OffsetPosition>
<RotationOffset><X>0</X><Y>0</Y><Z>0</Z><W>1</W></RotationOffset>
<Velocity><X>0</X><Y>0</Y><Z>0</Z></Velocity>
<RotationalVelocity><X>0</X><Y>0</Y><Z>0</Z></RotationalVelocity>
<AngularVelocity><X>0</X><Y>0</Y><Z>0</Z></AngularVelocity>
<Acceleration><X>0</X><Y>0</Y><Z>0</Z></Acceleration>
<Description />
<Color />
<Text />
<SitName />
<TouchName />
<LinkNum>0</LinkNum>
<ClickAction>0</ClickAction>
<Shape>
<PathBegin>0</PathBegin>
<PathCurve>16</PathCurve>
<PathEnd>0</PathEnd>
<PathRadiusOffset>0</PathRadiusOffset>
<PathRevolutions>0</PathRevolutions>
<PathScaleX>200</PathScaleX>
<PathScaleY>200</PathScaleY>
<PathShearX>0</PathShearX>
<PathShearY>0</PathShearY>
<PathSkew>0</PathSkew>
<PathTaperX>0</PathTaperX>
<PathTaperY>0</PathTaperY>
<PathTwist>0</PathTwist>
<PathTwistBegin>0</PathTwistBegin>
<PCode>9</PCode>
<ProfileBegin>0</ProfileBegin>
<ProfileEnd>0</ProfileEnd>
<ProfileHollow>0</ProfileHollow>
<Scale><X>1.283131</X><Y>5.903858</Y><Z>4.266288</Z></Scale>
<State>0</State>
<ProfileShape>Circle</ProfileShape>
<HollowShape>Same</HollowShape>
<ProfileCurve>0</ProfileCurve>
<TextureEntry>iVVnRyTLQ+2SC0fK7RVGXwJ6yc/SU4RDA5nhJbLUw3R1AAAAAAAAaOw8QQOhPSRAAKE9JEAAAAAAAAAAAAAAAAAAAAA=</TextureEntry>
<ExtraParams>AA==</ExtraParams>
</Shape>
<Scale><X>1.283131</X><Y>5.903858</Y><Z>4.266288</Z></Scale>
<UpdateFlag>0</UpdateFlag>
<SitTargetOrientation><w>0</w><x>0</x><y>0</y><z>1</z></SitTargetOrientation>
<SitTargetPosition><x>0</x><y>0</y><z>0</z></SitTargetPosition>
<SitTargetPositionLL><X>0</X><Y>0</Y><Z>0</Z></SitTargetPositionLL>
<SitTargetOrientationLL><X>0</X><Y>0</Y><Z>1</Z><W>0</W></SitTargetOrientationLL>
<ParentID>0</ParentID>
<CreationDate>1216066902</CreationDate>
<Category>0</Category>
<SalePrice>0</SalePrice>
<ObjectSaleType>0</ObjectSaleType>
<OwnershipCost>0</OwnershipCost>
<GroupID><UUID>00000000-0000-0000-0000-000000000000</UUID></GroupID>
<OwnerID><UUID>b46ef588-411e-4a8b-a284-d7dcfe8e74ef</UUID></OwnerID>
<LastOwnerID><UUID>b46ef588-411e-4a8b-a284-d7dcfe8e74ef</UUID></LastOwnerID>
<BaseMask>2147483647</BaseMask>
<OwnerMask>2147483647</OwnerMask>
<GroupMask>0</GroupMask>
<EveryoneMask>0</EveryoneMask>
<NextOwnerMask>2147483647</NextOwnerMask>
<Flags>None</Flags>
<DynAttrs>
<llsd>
<map>
<key>MyNamespace</key>
<map>
<key>MyStore</key>
<map>
<key>last words</key>
<string>Rosebud</string>
</map>
</map>
</map>
</llsd>
</DynAttrs>
<SitTargetAvatar><UUID>00000000-0000-0000-0000-000000000000</UUID></SitTargetAvatar>
</SceneObjectPart>
<OtherParts />
</SceneObjectGroup>";
protected Scene m_scene;
protected SerialiserModule m_serialiserModule;
[TestFixtureSetUp]
public void Init()
{
m_serialiserModule = new SerialiserModule();
m_scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(m_scene, m_serialiserModule);
}
[Test]
public void TestDeserializeXml()
{
TestHelpers.InMethod();
//log4net.Config.XmlConfigurator.Configure();
SceneObjectGroup so = SceneObjectSerializer.FromOriginalXmlFormat(xml);
SceneObjectPart rootPart = so.RootPart;
Assert.That(rootPart.UUID, Is.EqualTo(new UUID("e6a5a05e-e8cc-4816-8701-04165e335790")));
Assert.That(rootPart.CreatorID, Is.EqualTo(new UUID("a6dacf01-4636-4bb9-8a97-30609438af9d")));
Assert.That(rootPart.Name, Is.EqualTo("PrimMyRide"));
OSDMap store = rootPart.DynAttrs.GetStore("MyNamespace", "MyStore");
Assert.AreEqual(42, store["the answer"].AsInteger());
// TODO: Check other properties
}
[Test]
public void TestDeserializeBadFloatsXml()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
SceneObjectGroup so = SceneObjectSerializer.FromOriginalXmlFormat(badFloatsXml);
SceneObjectPart rootPart = so.RootPart;
Assert.That(rootPart.UUID, Is.EqualTo(new UUID("e6a5a05e-e8cc-4816-8701-04165e335790")));
Assert.That(rootPart.CreatorID, Is.EqualTo(new UUID("a6dacf01-4636-4bb9-8a97-30609438af9d")));
Assert.That(rootPart.Name, Is.EqualTo("NaughtyPrim"));
// This terminates the deserialization earlier if couldn't be parsed.
// TODO: Need to address this
Assert.That(rootPart.GroupPosition.X, Is.EqualTo(147.23f));
Assert.That(rootPart.Shape.PathCurve, Is.EqualTo(16));
// Defaults for bad parses
Assert.That(rootPart.Shape.FlexiTension, Is.EqualTo(0));
Assert.That(rootPart.Shape.FlexiDrag, Is.EqualTo(0));
// TODO: Check other properties
}
[Test]
public void TestSerializeXml()
{
TestHelpers.InMethod();
//log4net.Config.XmlConfigurator.Configure();
string rpName = "My Little Donkey";
UUID rpUuid = UUID.Parse("00000000-0000-0000-0000-000000000964");
UUID rpCreatorId = UUID.Parse("00000000-0000-0000-0000-000000000915");
PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
// Vector3 groupPosition = new Vector3(10, 20, 30);
// Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
// Vector3 offsetPosition = new Vector3(5, 10, 15);
SceneObjectPart rp = new SceneObjectPart();
rp.UUID = rpUuid;
rp.Name = rpName;
rp.CreatorID = rpCreatorId;
rp.Shape = shape;
string daNamespace = "MyNamespace";
string daStoreName = "MyStore";
string daKey = "foo";
string daValue = "bar";
OSDMap myStore = new OSDMap();
myStore.Add(daKey, daValue);
rp.DynAttrs = new DAMap();
rp.DynAttrs.SetStore(daNamespace, daStoreName, myStore);
SceneObjectGroup so = new SceneObjectGroup(rp);
// Need to add the object to the scene so that the request to get script state succeeds
m_scene.AddSceneObject(so);
string xml = SceneObjectSerializer.ToOriginalXmlFormat(so);
XmlTextReader xtr = new XmlTextReader(new StringReader(xml));
xtr.ReadStartElement("SceneObjectGroup");
xtr.ReadStartElement("RootPart");
xtr.ReadStartElement("SceneObjectPart");
UUID uuid = UUID.Zero;
string name = null;
UUID creatorId = UUID.Zero;
DAMap daMap = null;
while (xtr.Read() && xtr.Name != "SceneObjectPart")
{
if (xtr.NodeType != XmlNodeType.Element)
continue;
switch (xtr.Name)
{
case "UUID":
xtr.ReadStartElement("UUID");
try
{
uuid = UUID.Parse(xtr.ReadElementString("UUID"));
xtr.ReadEndElement();
}
catch { } // ignore everything but <UUID><UUID>...</UUID></UUID>
break;
case "Name":
name = xtr.ReadElementContentAsString();
break;
case "CreatorID":
xtr.ReadStartElement("CreatorID");
creatorId = UUID.Parse(xtr.ReadElementString("UUID"));
xtr.ReadEndElement();
break;
case "DynAttrs":
daMap = new DAMap();
daMap.ReadXml(xtr);
break;
}
}
xtr.ReadEndElement();
xtr.ReadEndElement();
xtr.ReadStartElement("OtherParts");
xtr.ReadEndElement();
xtr.Close();
// TODO: More checks
Assert.That(uuid, Is.EqualTo(rpUuid));
Assert.That(name, Is.EqualTo(rpName));
Assert.That(creatorId, Is.EqualTo(rpCreatorId));
Assert.NotNull(daMap);
Assert.AreEqual(daValue, daMap.GetStore(daNamespace, daStoreName)[daKey].AsString());
}
[Test]
public void TestDeserializeXml2()
{
TestHelpers.InMethod();
//log4net.Config.XmlConfigurator.Configure();
SceneObjectGroup so = m_serialiserModule.DeserializeGroupFromXml2(xml2);
SceneObjectPart rootPart = so.RootPart;
Assert.That(rootPart.UUID, Is.EqualTo(new UUID("9be68fdd-f740-4a0f-9675-dfbbb536b946")));
Assert.That(rootPart.CreatorID, Is.EqualTo(new UUID("b46ef588-411e-4a8b-a284-d7dcfe8e74ef")));
Assert.That(rootPart.Name, Is.EqualTo("PrimFun"));
OSDMap store = rootPart.DynAttrs.GetStore("MyNamespace", "MyStore");
Assert.AreEqual("Rosebud", store["last words"].AsString());
// TODO: Check other properties
}
[Test]
public void TestSerializeXml2()
{
TestHelpers.InMethod();
//log4net.Config.XmlConfigurator.Configure();
string rpName = "My Little Pony";
UUID rpUuid = UUID.Parse("00000000-0000-0000-0000-000000000064");
UUID rpCreatorId = UUID.Parse("00000000-0000-0000-0000-000000000015");
PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
// Vector3 groupPosition = new Vector3(10, 20, 30);
// Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
// Vector3 offsetPosition = new Vector3(5, 10, 15);
SceneObjectPart rp = new SceneObjectPart();
rp.UUID = rpUuid;
rp.Name = rpName;
rp.CreatorID = rpCreatorId;
rp.Shape = shape;
string daNamespace = "MyNamespace";
string daStoreName = "MyStore";
string daKey = "foo";
string daValue = "bar";
OSDMap myStore = new OSDMap();
myStore.Add(daKey, daValue);
rp.DynAttrs = new DAMap();
rp.DynAttrs.SetStore(daNamespace, daStoreName, myStore);
SceneObjectGroup so = new SceneObjectGroup(rp);
// Need to add the object to the scene so that the request to get script state succeeds
m_scene.AddSceneObject(so);
Dictionary<string, object> options = new Dictionary<string, object>();
options["old-guids"] = true;
string xml2 = m_serialiserModule.SerializeGroupToXml2(so, options);
XmlTextReader xtr = new XmlTextReader(new StringReader(xml2));
xtr.ReadStartElement("SceneObjectGroup");
xtr.ReadStartElement("SceneObjectPart");
UUID uuid = UUID.Zero;
string name = null;
UUID creatorId = UUID.Zero;
DAMap daMap = null;
while (xtr.Read() && xtr.Name != "SceneObjectPart")
{
if (xtr.NodeType != XmlNodeType.Element)
continue;
switch (xtr.Name)
{
case "UUID":
xtr.ReadStartElement("UUID");
uuid = UUID.Parse(xtr.ReadElementString("Guid"));
xtr.ReadEndElement();
break;
case "Name":
name = xtr.ReadElementContentAsString();
break;
case "CreatorID":
xtr.ReadStartElement("CreatorID");
creatorId = UUID.Parse(xtr.ReadElementString("Guid"));
xtr.ReadEndElement();
break;
case "DynAttrs":
daMap = new DAMap();
daMap.ReadXml(xtr);
break;
}
}
xtr.ReadEndElement();
xtr.ReadStartElement("OtherParts");
xtr.ReadEndElement();
xtr.Close();
// TODO: More checks
Assert.That(uuid, Is.EqualTo(rpUuid));
Assert.That(name, Is.EqualTo(rpName));
Assert.That(creatorId, Is.EqualTo(rpCreatorId));
Assert.NotNull(daMap);
Assert.AreEqual(daValue, daMap.GetStore(daNamespace, daStoreName)[daKey].AsString());
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing Loggers.
/// </summary>
internal partial class LoggerOperations : IServiceOperations<ApiManagementClient>, ILoggerOperations
{
/// <summary>
/// Initializes a new instance of the LoggerOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal LoggerOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates new logger.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='loggerid'>
/// Required. Identifier of the logger.
/// </param>
/// <param name='parameters'>
/// Required. Create parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateAsync(string resourceGroupName, string serviceName, string loggerid, LoggerCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (loggerid == null)
{
throw new ArgumentNullException("loggerid");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Credentials == null)
{
throw new ArgumentNullException("parameters.Credentials");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("loggerid", loggerid);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/loggers/";
url = url + Uri.EscapeDataString(loggerid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject loggerCreateParametersValue = new JObject();
requestDoc = loggerCreateParametersValue;
loggerCreateParametersValue["type"] = parameters.Type.ToString();
if (parameters.Description != null)
{
loggerCreateParametersValue["description"] = parameters.Description;
}
if (parameters.Credentials != null)
{
if (parameters.Credentials is ILazyCollection == false || ((ILazyCollection)parameters.Credentials).IsInitialized)
{
JObject credentialsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Credentials)
{
string credentialsKey = pair.Key;
string credentialsValue = pair.Value;
credentialsDictionary[credentialsKey] = credentialsValue;
}
loggerCreateParametersValue["credentials"] = credentialsDictionary;
}
}
if (parameters.IsBuffered != null)
{
loggerCreateParametersValue["isBuffered"] = parameters.IsBuffered.Value;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes specific logger of the Api Management service instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='loggerid'>
/// Required. Identifier of the logger.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string loggerid, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (loggerid == null)
{
throw new ArgumentNullException("loggerid");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("loggerid", loggerid);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/loggers/";
url = url + Uri.EscapeDataString(loggerid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets specific logger.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='loggerid'>
/// Required. Identifier of the logger.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Get Logger operation response details.
/// </returns>
public async Task<LoggerGetResponse> GetAsync(string resourceGroupName, string serviceName, string loggerid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (loggerid == null)
{
throw new ArgumentNullException("loggerid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("loggerid", loggerid);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/loggers/";
url = url + Uri.EscapeDataString(loggerid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LoggerGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LoggerGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
LoggerGetContract valueInstance = new LoggerGetContract();
result.Value = valueInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
valueInstance.IdPath = idInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
LoggerTypeContract typeInstance = ((LoggerTypeContract)Enum.Parse(typeof(LoggerTypeContract), ((string)typeValue), true));
valueInstance.Type = typeInstance;
}
JToken descriptionValue = responseDoc["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
valueInstance.Description = descriptionInstance;
}
JToken isBufferedValue = responseDoc["isBuffered"];
if (isBufferedValue != null && isBufferedValue.Type != JTokenType.Null)
{
bool isBufferedInstance = ((bool)isBufferedValue);
valueInstance.IsBuffered = isBufferedInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all loggers.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Logger operation response details.
/// </returns>
public async Task<LoggerListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("query", query);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/loggers";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
List<string> odataFilter = new List<string>();
if (query != null && query.Filter != null)
{
odataFilter.Add(Uri.EscapeDataString(query.Filter));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (query != null && query.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
}
if (query != null && query.Skip != null)
{
queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LoggerListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LoggerListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
LoggerPaged resultInstance = new LoggerPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
LoggerGetContract loggerGetContractInstance = new LoggerGetContract();
resultInstance.Values.Add(loggerGetContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
loggerGetContractInstance.IdPath = idInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
LoggerTypeContract typeInstance = ((LoggerTypeContract)Enum.Parse(typeof(LoggerTypeContract), ((string)typeValue), true));
loggerGetContractInstance.Type = typeInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
loggerGetContractInstance.Description = descriptionInstance;
}
JToken isBufferedValue = valueValue["isBuffered"];
if (isBufferedValue != null && isBufferedValue.Type != JTokenType.Null)
{
bool isBufferedInstance = ((bool)isBufferedValue);
loggerGetContractInstance.IsBuffered = isBufferedInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List next logger page.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Logger operation response details.
/// </returns>
public async Task<LoggerListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LoggerListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LoggerListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
LoggerPaged resultInstance = new LoggerPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
LoggerGetContract loggerGetContractInstance = new LoggerGetContract();
resultInstance.Values.Add(loggerGetContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
loggerGetContractInstance.IdPath = idInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
LoggerTypeContract typeInstance = ((LoggerTypeContract)Enum.Parse(typeof(LoggerTypeContract), ((string)typeValue), true));
loggerGetContractInstance.Type = typeInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
loggerGetContractInstance.Description = descriptionInstance;
}
JToken isBufferedValue = valueValue["isBuffered"];
if (isBufferedValue != null && isBufferedValue.Type != JTokenType.Null)
{
bool isBufferedInstance = ((bool)isBufferedValue);
loggerGetContractInstance.IsBuffered = isBufferedInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Patches specific logger.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='loggerid'>
/// Required. Identifier of the logger.
/// </param>
/// <param name='parameters'>
/// Required. Update parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> UpdateAsync(string resourceGroupName, string serviceName, string loggerid, LoggerUpdateParameters parameters, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (loggerid == null)
{
throw new ArgumentNullException("loggerid");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("loggerid", loggerid);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/loggers/";
url = url + Uri.EscapeDataString(loggerid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject loggerUpdateParametersValue = new JObject();
requestDoc = loggerUpdateParametersValue;
loggerUpdateParametersValue["type"] = parameters.Type.ToString();
if (parameters.Description != null)
{
loggerUpdateParametersValue["description"] = parameters.Description;
}
if (parameters.Credentials != null)
{
if (parameters.Credentials is ILazyCollection == false || ((ILazyCollection)parameters.Credentials).IsInitialized)
{
JObject credentialsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Credentials)
{
string credentialsKey = pair.Key;
string credentialsValue = pair.Value;
credentialsDictionary[credentialsKey] = credentialsValue;
}
loggerUpdateParametersValue["credentials"] = credentialsDictionary;
}
}
if (parameters.IsBuffered != null)
{
loggerUpdateParametersValue["isBuffered"] = parameters.IsBuffered.Value;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DiagnosticAdapter;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.TestHost
{
public class TestServerTests
{
[Fact]
public async Task GenericRawCreateAndStartHost_GetTestServer()
{
using var host = new HostBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder
.ConfigureServices(services =>
{
services.AddSingleton<IServer>(serviceProvider => new TestServer(serviceProvider));
})
.Configure(app => { });
})
.Build();
await host.StartAsync();
var response = await host.GetTestServer().CreateClient().GetAsync("/");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task GenericCreateAndStartHost_GetTestServer()
{
using var host = await new HostBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder
.UseTestServer()
.Configure(app => { });
})
.StartAsync();
var response = await host.GetTestServer().CreateClient().GetAsync("/");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task GenericCreateAndStartHost_GetTestClient()
{
using var host = await new HostBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder
.UseTestServer()
.Configure(app => { });
})
.StartAsync();
var response = await host.GetTestClient().GetAsync("/");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task UseTestServerRegistersNoopHostLifetime()
{
using var host = await new HostBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder
.UseTestServer()
.Configure(app => { });
})
.StartAsync();
Assert.IsType<NoopHostLifetime>(host.Services.GetService<IHostLifetime>());
}
[Fact]
public void CreateWithDelegate()
{
// Arrange
// Act & Assert (Does not throw)
new TestServer(new WebHostBuilder().Configure(app => { }));
}
[Fact]
public void CreateWithDelegate_DI()
{
var builder = new WebHostBuilder()
.Configure(app => { })
.UseTestServer();
using var host = builder.Build();
host.Start();
}
[Fact]
public void DoesNotCaptureStartupErrorsByDefault()
{
var builder = new WebHostBuilder()
.Configure(app =>
{
throw new InvalidOperationException();
});
Assert.Throws<InvalidOperationException>(() => new TestServer(builder));
}
[Fact]
public async Task ServicesCanBeOverridenForTestingAsync()
{
var builder = new WebHostBuilder()
.ConfigureServices(s => s.AddSingleton<IServiceProviderFactory<ThirdPartyContainer>, ThirdPartyContainerServiceProviderFactory>())
.UseStartup<ThirdPartyContainerStartup>()
.ConfigureTestServices(services => services.AddSingleton(new SimpleService { Message = "OverridesConfigureServices" }))
.ConfigureTestContainer<ThirdPartyContainer>(container => container.Services.AddSingleton(new TestService { Message = "OverridesConfigureContainer" }));
var host = new TestServer(builder);
var response = await host.CreateClient().GetStringAsync("/");
Assert.Equal("OverridesConfigureServices, OverridesConfigureContainer", response);
}
public class ThirdPartyContainerStartup
{
public void ConfigureServices(IServiceCollection services) =>
services.AddSingleton(new SimpleService { Message = "ConfigureServices" });
public void ConfigureContainer(ThirdPartyContainer container) =>
container.Services.AddSingleton(new TestService { Message = "ConfigureContainer" });
public void Configure(IApplicationBuilder app) =>
app.Run(ctx => ctx.Response.WriteAsync(
$"{ctx.RequestServices.GetRequiredService<SimpleService>().Message}, {ctx.RequestServices.GetRequiredService<TestService>().Message}"));
}
public class ThirdPartyContainer
{
public IServiceCollection Services { get; set; }
}
public class ThirdPartyContainerServiceProviderFactory : IServiceProviderFactory<ThirdPartyContainer>
{
public ThirdPartyContainer CreateBuilder(IServiceCollection services) => new ThirdPartyContainer { Services = services };
public IServiceProvider CreateServiceProvider(ThirdPartyContainer containerBuilder) => containerBuilder.Services.BuildServiceProvider();
}
[Fact]
public void CaptureStartupErrorsSettingPreserved()
{
var builder = new WebHostBuilder()
.CaptureStartupErrors(true)
.Configure(app =>
{
throw new InvalidOperationException();
});
// Does not throw
new TestServer(builder);
}
[Fact]
public void ApplicationServicesAvailableFromTestServer()
{
var testService = new TestService();
var builder = new WebHostBuilder()
.Configure(app => { })
.ConfigureServices(services =>
{
services.AddSingleton(testService);
});
var server = new TestServer(builder);
Assert.Equal(testService, server.Host.Services.GetRequiredService<TestService>());
}
[Fact]
public async Task RequestServicesAutoCreated()
{
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(context =>
{
return context.Response.WriteAsync("RequestServices:" + (context.RequestServices != null));
});
});
var server = new TestServer(builder);
string result = await server.CreateClient().GetStringAsync("/path");
Assert.Equal("RequestServices:True", result);
}
[Fact]
public async Task DispoingTheRequestBodyDoesNotDisposeClientStreams()
{
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(async context =>
{
using (var sr = new StreamReader(context.Request.Body))
{
await context.Response.WriteAsync(await sr.ReadToEndAsync());
}
});
});
var server = new TestServer(builder);
var stream = new ThrowOnDisposeStream();
stream.Write(Encoding.ASCII.GetBytes("Hello World"));
stream.Seek(0, SeekOrigin.Begin);
var response = await server.CreateClient().PostAsync("/", new StreamContent(stream));
Assert.True(response.IsSuccessStatusCode);
Assert.Equal("Hello World", await response.Content.ReadAsStringAsync());
}
public class CustomContainerStartup
{
public IServiceProvider Services;
public IServiceProvider ConfigureServices(IServiceCollection services)
{
Services = services.BuildServiceProvider();
return Services;
}
public void Configure(IApplicationBuilder app)
{
var applicationServices = app.ApplicationServices;
app.Run(async context =>
{
await context.Response.WriteAsync("ApplicationServicesEqual:" + (applicationServices == Services));
});
}
}
[Fact]
public async Task CustomServiceProviderSetsApplicationServices()
{
var builder = new WebHostBuilder().UseStartup<CustomContainerStartup>();
var server = new TestServer(builder);
string result = await server.CreateClient().GetStringAsync("/path");
Assert.Equal("ApplicationServicesEqual:True", result);
}
[Fact]
public void TestServerConstructorWithFeatureCollectionAllowsInitializingServerFeatures()
{
// Arrange
var url = "http://localhost:8000/appName/serviceName";
var builder = new WebHostBuilder()
.UseUrls(url)
.Configure(applicationBuilder =>
{
var serverAddressesFeature = applicationBuilder.ServerFeatures.Get<IServerAddressesFeature>();
Assert.Contains(serverAddressesFeature.Addresses, s => string.Equals(s, url, StringComparison.Ordinal));
});
var featureCollection = new FeatureCollection();
featureCollection.Set<IServerAddressesFeature>(new ServerAddressesFeature());
// Act
new TestServer(builder, featureCollection);
// Assert
// Is inside configure callback
}
[Fact]
public void TestServerConstructorWithNullFeatureCollectionThrows()
{
var builder = new WebHostBuilder()
.Configure(b => { });
Assert.Throws<ArgumentNullException>(() => new TestServer(builder, null));
}
[Fact]
public void TestServerConstructorShouldProvideServicesFromPassedServiceProvider()
{
// Arrange
var serviceProvider = new ServiceCollection().BuildServiceProvider();
// Act
var testServer = new TestServer(serviceProvider);
// Assert
Assert.Equal(serviceProvider, testServer.Services);
}
[Fact]
public void TestServerConstructorShouldProvideServicesFromWebHost()
{
// Arrange
var testService = new TestService();
var builder = new WebHostBuilder()
.ConfigureServices(services => services.AddSingleton(testService))
.Configure(_ => { });
// Act
var testServer = new TestServer(builder);
// Assert
Assert.Equal(testService, testServer.Services.GetService<TestService>());
}
[Fact]
public async Task TestServerConstructorShouldProvideServicesFromHostBuilder()
{
// Arrange
var testService = new TestService();
using var host = await new HostBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder
.UseTestServer()
.ConfigureServices(services => services.AddSingleton(testService))
.Configure(_ => { });
})
.StartAsync();
// Act
// By calling GetTestServer(), a new TestServer instance will be instantiated
var testServer = host.GetTestServer();
// Assert
Assert.Equal(testService, testServer.Services.GetService<TestService>());
}
[Fact]
public async Task TestServerConstructorSetOptions()
{
// Arrange
var baseAddress = new Uri("http://localhost/test");
using var host = await new HostBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder
.UseTestServer(options =>
{
options.AllowSynchronousIO = true;
options.PreserveExecutionContext = true;
options.BaseAddress = baseAddress;
})
.Configure(_ => { });
})
.StartAsync();
// Act
// By calling GetTestServer(), a new TestServer instance will be instantiated
var testServer = host.GetTestServer();
// Assert
Assert.True(testServer.AllowSynchronousIO);
Assert.True(testServer.PreserveExecutionContext);
Assert.Equal(baseAddress, testServer.BaseAddress);
}
public class TestService { public string Message { get; set; } }
public class TestRequestServiceMiddleware
{
private RequestDelegate _next;
public TestRequestServiceMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext httpContext)
{
var services = new ServiceCollection();
services.AddTransient<TestService>();
httpContext.RequestServices = services.BuildServiceProvider();
return _next.Invoke(httpContext);
}
}
public class RequestServicesFilter : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return builder =>
{
builder.UseMiddleware<TestRequestServiceMiddleware>();
next(builder);
};
}
}
[Fact]
public async Task ExistingRequestServicesWillNotBeReplaced()
{
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(context =>
{
var service = context.RequestServices.GetService<TestService>();
return context.Response.WriteAsync("Found:" + (service != null));
});
})
.ConfigureServices(services =>
{
services.AddTransient<IStartupFilter, RequestServicesFilter>();
});
var server = new TestServer(builder);
string result = await server.CreateClient().GetStringAsync("/path");
Assert.Equal("Found:True", result);
}
[Fact]
public async Task CanSetCustomServiceProvider()
{
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(context =>
{
context.RequestServices = new ServiceCollection()
.AddTransient<TestService>()
.BuildServiceProvider();
var s = context.RequestServices.GetRequiredService<TestService>();
return context.Response.WriteAsync("Success");
});
});
var server = new TestServer(builder);
string result = await server.CreateClient().GetStringAsync("/path");
Assert.Equal("Success", result);
}
public class ReplaceServiceProvidersFeatureFilter : IStartupFilter, IServiceProvidersFeature
{
public ReplaceServiceProvidersFeatureFilter(IServiceProvider appServices, IServiceProvider requestServices)
{
ApplicationServices = appServices;
RequestServices = requestServices;
}
public IServiceProvider ApplicationServices { get; set; }
public IServiceProvider RequestServices { get; set; }
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return app =>
{
app.Use(async (context, nxt) =>
{
context.Features.Set<IServiceProvidersFeature>(this);
await nxt(context);
});
next(app);
};
}
}
[Fact]
public async Task ExistingServiceProviderFeatureWillNotBeReplaced()
{
var appServices = new ServiceCollection().BuildServiceProvider();
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(context =>
{
Assert.Equal(appServices, context.RequestServices);
return context.Response.WriteAsync("Success");
});
})
.ConfigureServices(services =>
{
services.AddSingleton<IStartupFilter>(new ReplaceServiceProvidersFeatureFilter(appServices, appServices));
});
var server = new TestServer(builder);
var result = await server.CreateClient().GetStringAsync("/path");
Assert.Equal("Success", result);
}
public class NullServiceProvidersFeatureFilter : IStartupFilter, IServiceProvidersFeature
{
public IServiceProvider ApplicationServices { get; set; }
public IServiceProvider RequestServices { get; set; }
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return app =>
{
app.Use(async (context, nxt) =>
{
context.Features.Set<IServiceProvidersFeature>(this);
await nxt(context);
});
next(app);
};
}
}
[Fact]
public async Task WillReplaceServiceProviderFeatureWithNullRequestServices()
{
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(context =>
{
Assert.Null(context.RequestServices);
return context.Response.WriteAsync("Success");
});
})
.ConfigureServices(services =>
{
services.AddTransient<IStartupFilter, NullServiceProvidersFeatureFilter>();
});
var server = new TestServer(builder);
var result = await server.CreateClient().GetStringAsync("/path");
Assert.Equal("Success", result);
}
[Fact]
public async Task CanAccessLogger()
{
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(context =>
{
var logger = app.ApplicationServices.GetRequiredService<ILogger<HttpContext>>();
return context.Response.WriteAsync("FoundLogger:" + (logger != null));
});
});
var server = new TestServer(builder);
string result = await server.CreateClient().GetStringAsync("/path");
Assert.Equal("FoundLogger:True", result);
}
[Fact]
public async Task CanAccessHttpContext()
{
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(context =>
{
var accessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
return context.Response.WriteAsync("HasContext:" + (accessor.HttpContext != null));
});
})
.ConfigureServices(services =>
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
});
var server = new TestServer(builder);
string result = await server.CreateClient().GetStringAsync("/path");
Assert.Equal("HasContext:True", result);
}
public class ContextHolder
{
public ContextHolder(IHttpContextAccessor accessor)
{
Accessor = accessor;
}
public IHttpContextAccessor Accessor { get; set; }
}
[Fact]
public async Task CanAddNewHostServices()
{
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(context =>
{
var accessor = app.ApplicationServices.GetRequiredService<ContextHolder>();
return context.Response.WriteAsync("HasContext:" + (accessor.Accessor.HttpContext != null));
});
})
.ConfigureServices(services =>
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<ContextHolder>();
});
var server = new TestServer(builder);
string result = await server.CreateClient().GetStringAsync("/path");
Assert.Equal("HasContext:True", result);
}
[Fact]
public async Task CreateInvokesApp()
{
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(context =>
{
return context.Response.WriteAsync("CreateInvokesApp");
});
});
var server = new TestServer(builder);
string result = await server.CreateClient().GetStringAsync("/path");
Assert.Equal("CreateInvokesApp", result);
}
[Fact]
public async Task DisposeStreamIgnored()
{
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(async context =>
{
await context.Response.WriteAsync("Response");
context.Response.Body.Dispose();
});
});
var server = new TestServer(builder);
HttpResponseMessage result = await server.CreateClient().GetAsync("/");
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.Equal("Response", await result.Content.ReadAsStringAsync());
}
[Fact]
public async Task DisposedServerThrows()
{
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(async context =>
{
await context.Response.WriteAsync("Response");
context.Response.Body.Dispose();
});
});
var server = new TestServer(builder);
HttpResponseMessage result = await server.CreateClient().GetAsync("/");
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
server.Dispose();
await Assert.ThrowsAsync<ObjectDisposedException>(() => server.CreateClient().GetAsync("/"));
}
[Fact]
public async Task CancelAborts()
{
var builder = new WebHostBuilder()
.Configure(app =>
{
app.Run(context =>
{
TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
tcs.SetCanceled();
return tcs.Task;
});
});
var server = new TestServer(builder);
await Assert.ThrowsAsync<TaskCanceledException>(async () => { string result = await server.CreateClient().GetStringAsync("/path"); });
}
[Fact]
public async Task CanCreateViaStartupType()
{
var builder = new WebHostBuilder()
.UseStartup<TestStartup>();
var server = new TestServer(builder);
HttpResponseMessage result = await server.CreateClient().GetAsync("/");
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.Equal("FoundService:True", await result.Content.ReadAsStringAsync());
}
[Fact]
public async Task CanCreateViaStartupTypeAndSpecifyEnv()
{
var builder = new WebHostBuilder()
.UseStartup<TestStartup>()
.UseEnvironment("Foo");
var server = new TestServer(builder);
HttpResponseMessage result = await server.CreateClient().GetAsync("/");
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.Equal("FoundFoo:False", await result.Content.ReadAsStringAsync());
}
[Fact]
public async Task BeginEndDiagnosticAvailable()
{
DiagnosticListener diagnosticListener = null;
var builder = new WebHostBuilder()
.Configure(app =>
{
diagnosticListener = app.ApplicationServices.GetRequiredService<DiagnosticListener>();
app.Run(context =>
{
return context.Response.WriteAsync("Hello World");
});
});
var server = new TestServer(builder);
var listener = new TestDiagnosticListener();
diagnosticListener.SubscribeWithAdapter(listener);
var result = await server.CreateClient().GetStringAsync("/path");
// This ensures that all diagnostics are completely written to the diagnostic listener
Thread.Sleep(1000);
Assert.Equal("Hello World", result);
Assert.NotNull(listener.BeginRequest?.HttpContext);
Assert.NotNull(listener.EndRequest?.HttpContext);
Assert.Null(listener.UnhandledException);
}
[Fact]
public async Task ExceptionDiagnosticAvailable()
{
DiagnosticListener diagnosticListener = null;
var builder = new WebHostBuilder().Configure(app =>
{
diagnosticListener = app.ApplicationServices.GetRequiredService<DiagnosticListener>();
app.Run(context =>
{
throw new Exception("Test exception");
});
});
var server = new TestServer(builder);
var listener = new TestDiagnosticListener();
diagnosticListener.SubscribeWithAdapter(listener);
await Assert.ThrowsAsync<Exception>(() => server.CreateClient().GetAsync("/path"));
// This ensures that all diagnostics are completely written to the diagnostic listener
Thread.Sleep(1000);
Assert.NotNull(listener.BeginRequest?.HttpContext);
Assert.Null(listener.EndRequest?.HttpContext);
Assert.NotNull(listener.UnhandledException?.HttpContext);
Assert.NotNull(listener.UnhandledException?.Exception);
}
[Theory]
[InlineData("http://localhost:12345")]
[InlineData("http://localhost:12345/")]
[InlineData("http://localhost:12345/hellohellohello")]
[InlineData("/isthereanybodyinthere?")]
public async Task ManuallySetHostWinsOverInferredHostFromRequestUri(string uri)
{
RequestDelegate appDelegate = ctx =>
ctx.Response.WriteAsync(ctx.Request.Headers.Host);
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, uri);
request.Headers.Host = "otherhost:5678";
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal("otherhost:5678", responseBody);
}
private class ThrowOnDisposeStream : MemoryStream
{
protected override void Dispose(bool disposing)
{
throw new InvalidOperationException("Dispose should not happen!");
}
public override ValueTask DisposeAsync()
{
throw new InvalidOperationException("DisposeAsync should not happen!");
}
}
public class TestDiagnosticListener
{
public class OnBeginRequestEventData
{
public IProxyHttpContext HttpContext { get; set; }
}
public OnBeginRequestEventData BeginRequest { get; set; }
[DiagnosticName("Microsoft.AspNetCore.Hosting.BeginRequest")]
public virtual void OnBeginRequest(IProxyHttpContext httpContext)
{
BeginRequest = new OnBeginRequestEventData()
{
HttpContext = httpContext,
};
}
public class OnEndRequestEventData
{
public IProxyHttpContext HttpContext { get; set; }
}
public OnEndRequestEventData EndRequest { get; set; }
[DiagnosticName("Microsoft.AspNetCore.Hosting.EndRequest")]
public virtual void OnEndRequest(IProxyHttpContext httpContext)
{
EndRequest = new OnEndRequestEventData()
{
HttpContext = httpContext,
};
}
public class OnUnhandledExceptionEventData
{
public IProxyHttpContext HttpContext { get; set; }
public IProxyException Exception { get; set; }
}
public OnUnhandledExceptionEventData UnhandledException { get; set; }
[DiagnosticName("Microsoft.AspNetCore.Hosting.UnhandledException")]
public virtual void OnUnhandledException(IProxyHttpContext httpContext, IProxyException exception)
{
UnhandledException = new OnUnhandledExceptionEventData()
{
HttpContext = httpContext,
Exception = exception,
};
}
}
public interface IProxyHttpContext
{
}
public interface IProxyException
{
}
public class Startup
{
public void Configure(IApplicationBuilder builder)
{
builder.Run(ctx => ctx.Response.WriteAsync("Startup"));
}
}
public class SimpleService
{
public SimpleService()
{
}
public string Message { get; set; }
}
public class TestStartup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<SimpleService>();
}
public void ConfigureFooServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app)
{
app.Run(context =>
{
var service = app.ApplicationServices.GetRequiredService<SimpleService>();
return context.Response.WriteAsync("FoundService:" + (service != null));
});
}
public void ConfigureFoo(IApplicationBuilder app)
{
app.Run(context =>
{
var service = app.ApplicationServices.GetService<SimpleService>();
return context.Response.WriteAsync("FoundFoo:" + (service != null));
});
}
}
}
}
| |
// Colorful FX - Unity Asset
// Copyright (c) 2015 - Thomas Hourdel
// http://www.thomashourdel.com
namespace Colorful.Editors
{
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System;
using ColorMode = Levels.ColorMode;
using Channel = Levels.Channel;
[CustomEditor(typeof(Levels))]
public class LevelsEditor : BaseEffectEditor
{
SerializedProperty p_Mode;
SerializedProperty p_InputL;
SerializedProperty p_InputR;
SerializedProperty p_InputG;
SerializedProperty p_InputB;
SerializedProperty p_OutputL;
SerializedProperty p_OutputR;
SerializedProperty p_OutputG;
SerializedProperty p_OutputB;
SerializedProperty p_CurrentChannel;
SerializedProperty p_Logarithmic;
SerializedProperty p_AutoRefresh;
Levels m_Target;
Texture2D m_TempTexture;
int[] m_Histogram = new int[256];
Rect m_HistogramRect = new Rect(0f, 0f, 1f, 1f);
Color MasterColor = EditorGUIUtility.isProSkin ? new Color(1f, 1f, 1f, 2f) : new Color(0.1f, 0.1f, 0.1f, 2f);
Color RedColor = new Color(1f, 0f, 0f, 2f);
Color GreenColor = EditorGUIUtility.isProSkin ? new Color(0f, 1f, 0f, 2f) : new Color(0.2f, 0.8f, 0.2f, 2f);
Color BlueColor = EditorGUIUtility.isProSkin ? new Color(0f, 1f, 1f, 2f) : new Color(0f, 0f, 1f, 2f);
Texture2D RampTexture;
static GUIContent[] presets = {
new GUIContent("Choose a preset..."),
new GUIContent("Default"),
new GUIContent("Darker"),
new GUIContent("Increase Contrast 1"),
new GUIContent("Increase Contrast 2"),
new GUIContent("Increase Contrast 3"),
new GUIContent("Lighten Shadows"),
new GUIContent("Lighter"),
new GUIContent("Midtones Brighter"),
new GUIContent("Midtones Darker")
};
static float[,] presetsData = { { 0, 1, 255, 0, 255 }, { 15, 1, 255, 0, 255 }, { 10, 1, 245, 0, 255 },
{ 20, 1, 235, 0, 255 }, { 30, 1, 225, 0, 255 }, { 0, 1.6f, 255, 0, 255 },
{ 0, 1, 230, 0, 255 }, { 0, 1.25f, 255, 0, 255 }, { 0, 0.75f, 255, 0, 255 } };
void OnEnable()
{
p_Mode = serializedObject.FindProperty("Mode");
p_InputL = serializedObject.FindProperty("InputL");
p_InputR = serializedObject.FindProperty("InputR");
p_InputG = serializedObject.FindProperty("InputG");
p_InputB = serializedObject.FindProperty("InputB");
p_OutputL = serializedObject.FindProperty("OutputL");
p_OutputR = serializedObject.FindProperty("OutputR");
p_OutputG = serializedObject.FindProperty("OutputG");
p_OutputB = serializedObject.FindProperty("OutputB");
p_CurrentChannel = serializedObject.FindProperty("e_CurrentChannel");
p_Logarithmic = serializedObject.FindProperty("e_Logarithmic");
p_AutoRefresh = serializedObject.FindProperty("e_AutoRefresh");
RampTexture = Resources.Load<Texture2D>(CLib.IsLinearColorSpace() ? "UI/GrayscaleRampLinear" : "UI/GrayscaleRamp");
m_Target = target as Levels;
m_Target.e_OnFrameEnd = UpdateHistogram;
m_Target.InternalForceRefresh();
InternalEditorUtility.RepaintAllViews();
}
void OnDisable()
{
m_Target.e_OnFrameEnd = null;
if (m_TempTexture != null)
DestroyImmediate(m_TempTexture);
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
{
bool isRGB = p_Mode.intValue == (int)ColorMode.RGB;
Channel currentChannel = (Channel)p_CurrentChannel.intValue;
if (isRGB) currentChannel = (Channel)EditorGUILayout.EnumPopup(currentChannel);
isRGB = GUILayout.Toggle(isRGB, GetContent("Multi-channel Mode"), EditorStyles.miniButton);
p_Mode.intValue = isRGB ? (int)ColorMode.RGB : (int)ColorMode.Monochrome;
p_CurrentChannel.intValue = (int)currentChannel;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
{
if (GUILayout.Button(GetContent("Auto B&W"), EditorStyles.miniButton))
{
int min = 0, max = 255;
for (int i = 0; i < 256; i++)
{
if (m_Histogram[255 - i] > 0)
min = 255 - i;
if (m_Histogram[i] > 0)
max = i;
}
if (p_Mode.intValue == (int)ColorMode.RGB)
{
if (p_CurrentChannel.intValue == (int)Channel.Red)
{
Vector3 input = p_InputR.vector3Value;
input.x = min;
input.y = max;
p_InputR.vector3Value = input;
}
else if (p_CurrentChannel.intValue == (int)Channel.Green)
{
Vector3 input = p_InputG.vector3Value;
input.x = min;
input.y = max;
p_InputG.vector3Value = input;
}
else if (p_CurrentChannel.intValue == (int)Channel.Blue)
{
Vector3 input = p_InputB.vector3Value;
input.x = min;
input.y = max;
p_InputB.vector3Value = input;
}
}
else
{
Vector3 input = p_InputL.vector3Value;
input.x = min;
input.y = max;
p_InputL.vector3Value = input;
}
}
GUILayout.FlexibleSpace();
p_Logarithmic.boolValue = GUILayout.Toggle(p_Logarithmic.boolValue, GetContent("Log"), EditorStyles.miniButtonLeft);
p_AutoRefresh.boolValue = GUILayout.Toggle(p_AutoRefresh.boolValue, GetContent("Auto Refresh"), EditorStyles.miniButtonMid);
EditorGUI.BeginDisabledGroup(p_AutoRefresh.boolValue);
if (GUILayout.Button(GetContent("Refresh"), EditorStyles.miniButtonRight))
Refresh();
EditorGUI.EndDisabledGroup();
}
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
Refresh();
EditorGUILayout.Space();
// Sizing
EditorGUILayout.BeginHorizontal();
{
Rect rect = GUILayoutUtility.GetRect(256f, 128f);
float width = Mathf.Min(512f, rect.width);
float height = Mathf.Min(128f, rect.height);
if (Event.current.type == EventType.Repaint)
{
m_HistogramRect = new Rect(
Mathf.Floor(rect.x + rect.width / 2f - width / 2f),
Mathf.Floor(rect.y + rect.height / 2f - height / 2f),
width, height
);
}
}
EditorGUILayout.EndHorizontal();
// Histogram
DrawHistogram(m_HistogramRect);
// Selected Channel UI
if (p_Mode.intValue == (int)ColorMode.RGB)
{
if (p_CurrentChannel.intValue == (int)Channel.Red) ChannelUI(m_HistogramRect.width, p_InputR, p_OutputR);
else if (p_CurrentChannel.intValue == (int)Channel.Green) ChannelUI(m_HistogramRect.width, p_InputG, p_OutputG);
else if (p_CurrentChannel.intValue == (int)Channel.Blue) ChannelUI(m_HistogramRect.width, p_InputB, p_OutputB);
}
else
{
ChannelUI(m_HistogramRect.width, p_InputL, p_OutputL);
}
// Presets
EditorGUI.BeginChangeCheck();
int selectedPreset = EditorGUILayout.Popup(GetContent("Preset"), 0, presets);
if (EditorGUI.EndChangeCheck() && selectedPreset > 0)
{
selectedPreset--;
p_Mode.intValue = (int)ColorMode.Monochrome;
p_InputL.vector3Value = new Vector3(
presetsData[selectedPreset, 0],
presetsData[selectedPreset, 2],
presetsData[selectedPreset, 1]
);
p_OutputL.vector2Value = new Vector2(
presetsData[selectedPreset, 3],
presetsData[selectedPreset, 4]
);
}
serializedObject.ApplyModifiedProperties();
}
void Refresh()
{
m_Target.InternalForceRefresh();
InternalEditorUtility.RepaintAllViews();
}
void ChannelUI(float width, SerializedProperty input, SerializedProperty output)
{
float inputMin = input.vector3Value.x;
float inputGamma = input.vector3Value.z;
float inputMax = input.vector3Value.y;
float outputMin = output.vector2Value.x;
float outputMax = output.vector2Value.y;
// Input
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
EditorGUILayout.MinMaxSlider(ref inputMin, ref inputMax, 0f, 255f, GUILayout.Width(width));
GUILayout.FlexibleSpace();
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal(GUILayout.Width(width));
{
inputMin = EditorGUILayout.FloatField((int)inputMin, GUILayout.Width(50));
GUILayout.FlexibleSpace();
inputGamma = EditorGUILayout.FloatField(inputGamma, GUILayout.Width(50));
GUILayout.FlexibleSpace();
inputMax = EditorGUILayout.FloatField((int)inputMax, GUILayout.Width(50));
}
GUILayout.EndHorizontal();
GUILayout.FlexibleSpace();
}
GUILayout.EndHorizontal();
EditorGUILayout.Space();
// Ramp
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
GUI.DrawTexture(GUILayoutUtility.GetRect(width, 20f), RampTexture, ScaleMode.StretchToFill);
GUILayout.FlexibleSpace();
}
GUILayout.EndHorizontal();
// Output
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
EditorGUILayout.MinMaxSlider(ref outputMin, ref outputMax, 0f, 255f, GUILayout.Width(width));
GUILayout.FlexibleSpace();
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal(GUILayout.Width(width));
{
outputMin = EditorGUILayout.FloatField((int)outputMin, GUILayout.Width(50));
GUILayout.FlexibleSpace();
outputMax = EditorGUILayout.FloatField((int)outputMax, GUILayout.Width(50));
}
GUILayout.EndHorizontal();
GUILayout.FlexibleSpace();
}
GUILayout.EndHorizontal();
input.vector3Value = new Vector3(inputMin, inputMax, Mathf.Clamp(inputGamma, 0.1f, 9.99f));
output.vector2Value = new Vector2(outputMin, outputMax);
EditorGUILayout.Separator();
}
void DrawHistogram(Rect rect)
{
// Scale histogram values
int[] scaledHistogram = new int[256];
int max = 0;
for (int i = 0; i < 256; i++)
max = (max < m_Histogram[i]) ? m_Histogram[i] : max;
scaledHistogram = new int[256];
if (p_Logarithmic.boolValue)
{
float factor = rect.height / Mathf.Log10(max);
for (int i = 0; i < 256; i++)
scaledHistogram[i] = (m_Histogram[i] == 0) ? 0 : Mathf.Max(Mathf.RoundToInt(Mathf.Log10(m_Histogram[i]) * factor), 1);
}
else
{
float factor = rect.height / max;
for (int i = 0; i < 256; i++)
scaledHistogram[i] = Mathf.Max(Mathf.RoundToInt(m_Histogram[i] * factor), 1);
}
// Color
if (p_Mode.intValue == (int)ColorMode.RGB)
{
if (p_CurrentChannel.intValue == (int)Channel.Red)
Handles.color = RedColor;
else if (p_CurrentChannel.intValue == (int)Channel.Green)
Handles.color = GreenColor;
else if (p_CurrentChannel.intValue == (int)Channel.Blue)
Handles.color = BlueColor;
}
else
{
Handles.color = MasterColor;
}
// Base line
Vector2 p1 = new Vector2(rect.x - 1, rect.yMax);
Vector2 p2 = new Vector2(rect.xMax - 1, rect.yMax);
Handles.DrawLine(p1, p2);
// Histogram
for (int i = 0; i < (int)rect.width; i++)
{
float remapI = (float)i / rect.width * 255f;
int index = Mathf.FloorToInt(remapI);
float fract = remapI - (float)index;
float v1 = scaledHistogram[index];
float v2 = scaledHistogram[Mathf.Min(index + 1, 255)];
float h = v1 * (1.0f - fract) + v2 * fract;
Handles.DrawLine(
new Vector2(rect.x + i, rect.yMax),
new Vector2(rect.x + i, rect.yMin + (rect.height - h))
);
}
}
void UpdateHistogram(RenderTexture source)
{
if (m_TempTexture == null || m_TempTexture.width != source.width || m_TempTexture.height != source.height)
{
if (m_TempTexture != null)
DestroyImmediate(m_TempTexture);
m_TempTexture = new Texture2D(source.width, source.height, TextureFormat.RGB24, false);
m_TempTexture.anisoLevel = 0;
m_TempTexture.wrapMode = TextureWrapMode.Clamp;
m_TempTexture.filterMode = FilterMode.Bilinear;
m_TempTexture.hideFlags = HideFlags.HideAndDontSave;
}
// Grab the screen content for the camera
RenderTexture.active = source;
m_TempTexture.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0, false);
m_TempTexture.Apply();
RenderTexture.active = null;
// Raw histogram data
Color[] pixels = m_TempTexture.GetPixels();
if (m_Target.Mode == ColorMode.Monochrome)
{
Array.Clear(m_Histogram, 0, 256);
for (int i = 0; i < pixels.Length; i++)
{
Color c = pixels[i];
m_Histogram[(int)((c.r * 0.2125f + c.g * 0.7154f + c.b * 0.0721f) * 255)]++;
}
}
else
{
switch (m_Target.e_CurrentChannel)
{
case Channel.Red:
Array.Clear(m_Histogram, 0, 256);
for (int i = 0; i < pixels.Length; i++)
m_Histogram[(int)(pixels[i].r * 255)]++;
break;
case Channel.Green:
Array.Clear(m_Histogram, 0, 256);
for (int i = 0; i < pixels.Length; i++)
m_Histogram[(int)(pixels[i].g * 255)]++;
break;
case Channel.Blue:
Array.Clear(m_Histogram, 0, 256);
for (int i = 0; i < pixels.Length; i++)
m_Histogram[(int)(pixels[i].b * 255)]++;
break;
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type T with 2 columns and 2 rows.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct gmat2<T> : IEnumerable<T>, IEquatable<gmat2<T>>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
public T m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
public T m01;
/// <summary>
/// Column 1, Rows 0
/// </summary>
public T m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
public T m11;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public gmat2(T m00, T m01, T m10, T m11)
{
this.m00 = m00;
this.m01 = m01;
this.m10 = m10;
this.m11 = m11;
}
/// <summary>
/// Constructs this matrix from a gmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat2<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat3x2<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat4x2<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat2x3<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat3<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat4x3<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat2x4<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat3x4<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat4<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gvec2<T> c0, gvec2<T> c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public T[,] Values => new[,] { { m00, m01 }, { m10, m11 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public T[] Values1D => new[] { m00, m01, m10, m11 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public gvec2<T> Column0
{
get
{
return new gvec2<T>(m00, m01);
}
set
{
m00 = value.x;
m01 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public gvec2<T> Column1
{
get
{
return new gvec2<T>(m10, m11);
}
set
{
m10 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public gvec2<T> Row0
{
get
{
return new gvec2<T>(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public gvec2<T> Row1
{
get
{
return new gvec2<T>(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static gmat2<T> Zero { get; } = new gmat2<T>(default(T), default(T), default(T), default(T));
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<T> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m10;
yield return m11;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 2 = 4).
/// </summary>
public int Count => 4;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public T this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m10;
case 3: return m11;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m10 = value; break;
case 3: this.m11 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public T this[int col, int row]
{
get
{
return this[col * 2 + row];
}
set
{
this[col * 2 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(gmat2<T> rhs) => ((EqualityComparer<T>.Default.Equals(m00, rhs.m00) && EqualityComparer<T>.Default.Equals(m01, rhs.m01)) && (EqualityComparer<T>.Default.Equals(m10, rhs.m10) && EqualityComparer<T>.Default.Equals(m11, rhs.m11)));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is gmat2<T> && Equals((gmat2<T>) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(gmat2<T> lhs, gmat2<T> rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(gmat2<T> lhs, gmat2<T> rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((EqualityComparer<T>.Default.GetHashCode(m00)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m01)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m10)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m11);
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public gmat2<T> Transposed => new gmat2<T>(m00, m10, m01, m11);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Numerics;
using Internal.Runtime.CompilerServices;
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif // BIT64
namespace System
{
internal static partial class SpanHelpers // .Byte
{
public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
byte valueHead = value;
ref byte valueTail = ref Unsafe.Add(ref value, 1);
int valueTailLength = valueLength - 1;
int index = 0;
for (; ; )
{
Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength".
int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Do a quick search for the first element of "value".
int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, index), valueHead, remainingSearchSpaceLength);
if (relativeIndex == -1)
break;
index += relativeIndex;
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(ref Unsafe.Add(ref searchSpace, index + 1), ref valueTail, valueTailLength))
return index; // The tail matched. Return a successful find.
index++;
}
return -1;
}
public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
int index = -1;
for (int i = 0; i < valueLength; i++)
{
var tempIndex = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
if ((uint)tempIndex < (uint)index)
{
index = tempIndex;
// Reduce space for search, cause we don't care if we find the search value after the index of a previously found value
searchSpaceLength = tempIndex;
if (index == 0)
break;
}
}
return index;
}
public static int LastIndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
int index = -1;
for (int i = 0; i < valueLength; i++)
{
var tempIndex = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
if (tempIndex > index)
index = tempIndex;
}
return index;
}
// Adapted from IndexOf(...)
public static unsafe bool Contains(ref byte searchSpace, byte value, int length)
{
Debug.Assert(length >= 0);
uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)length;
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
SequentialScan:
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 0) ||
uValue == Unsafe.AddByteOffset(ref searchSpace, index + 1) ||
uValue == Unsafe.AddByteOffset(ref searchSpace, index + 2) ||
uValue == Unsafe.AddByteOffset(ref searchSpace, index + 3) ||
uValue == Unsafe.AddByteOffset(ref searchSpace, index + 4) ||
uValue == Unsafe.AddByteOffset(ref searchSpace, index + 5) ||
uValue == Unsafe.AddByteOffset(ref searchSpace, index + 6) ||
uValue == Unsafe.AddByteOffset(ref searchSpace, index + 7))
{
goto Found;
}
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 0) ||
uValue == Unsafe.AddByteOffset(ref searchSpace, index + 1) ||
uValue == Unsafe.AddByteOffset(ref searchSpace, index + 2) ||
uValue == Unsafe.AddByteOffset(ref searchSpace, index + 3))
{
goto Found;
}
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index))
goto Found;
index += 1;
}
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)((length - (int)(byte*)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> vComparison = new Vector<byte>(value);
while ((byte*)nLength > (byte*)index)
{
var vMatches = Vector.Equals(vComparison, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index)));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
goto Found;
}
if ((int)(byte*)index < length)
{
nLength = (IntPtr)(length - (int)(byte*)index);
goto SequentialScan;
}
}
return false;
Found:
return true;
}
public static unsafe int IndexOf(ref byte searchSpace, byte value, int length)
{
Debug.Assert(length >= 0);
uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)length;
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
SequentialScan:
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index))
goto Found;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 1))
goto Found1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 2))
goto Found2;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 3))
goto Found3;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 4))
goto Found4;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 5))
goto Found5;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 6))
goto Found6;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 7))
goto Found7;
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index))
goto Found;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 1))
goto Found1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 2))
goto Found2;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 3))
goto Found3;
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index))
goto Found;
index += 1;
}
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)((length - (int)(byte*)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> vComparison = new Vector<byte>(value);
while ((byte*)nLength > (byte*)index)
{
var vMatches = Vector.Equals(vComparison, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index)));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)index + LocateFirstFoundByte(vMatches);
}
if ((int)(byte*)index < length)
{
nLength = (IntPtr)(length - (int)(byte*)index);
goto SequentialScan;
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
byte valueHead = value;
ref byte valueTail = ref Unsafe.Add(ref value, 1);
int valueTailLength = valueLength - 1;
int index = 0;
for (; ; )
{
Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength".
int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Do a quick search for the first element of "value".
int relativeIndex = LastIndexOf(ref searchSpace, valueHead, remainingSearchSpaceLength);
if (relativeIndex == -1)
break;
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(ref Unsafe.Add(ref searchSpace, relativeIndex + 1), ref valueTail, valueTailLength))
return relativeIndex; // The tail matched. Return a successful find.
index += remainingSearchSpaceLength - relativeIndex;
}
return -1;
}
public static unsafe int LastIndexOf(ref byte searchSpace, byte value, int length)
{
Debug.Assert(length >= 0);
uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)length; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)length;
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(((length & (Vector<byte>.Count - 1)) + unaligned) & (Vector<byte>.Count - 1));
}
SequentialScan:
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
index -= 8;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 7))
goto Found7;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 6))
goto Found6;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 5))
goto Found5;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 4))
goto Found4;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 3))
goto Found3;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 2))
goto Found2;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 1))
goto Found1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index))
goto Found;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
index -= 4;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 3))
goto Found3;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 2))
goto Found2;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index + 1))
goto Found1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index))
goto Found;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
index -= 1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, index))
goto Found;
}
if (Vector.IsHardwareAccelerated && ((byte*)index > (byte*)0))
{
nLength = (IntPtr)((int)(byte*)index & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> vComparison = new Vector<byte>(value);
while ((byte*)nLength > (byte*)(Vector<byte>.Count - 1))
{
var vMatches = Vector.Equals(vComparison, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index - Vector<byte>.Count)));
if (Vector<byte>.Zero.Equals(vMatches))
{
index -= Vector<byte>.Count;
nLength -= Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(index) - Vector<byte>.Count + LocateLastFoundByte(vMatches);
}
if ((byte*)index > (byte*)0)
{
nLength = index;
goto SequentialScan;
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe int IndexOfAny(ref byte searchSpace, byte value0, byte value1, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)length;
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
SequentialScan:
uint lookUp;
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 4);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found4;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 5);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found5;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 6);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found6;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 7);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found7;
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
index += 1;
}
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)((length - (int)(byte*)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> values0 = new Vector<byte>(value0);
Vector<byte> values1 = new Vector<byte>(value1);
while ((byte*)nLength > (byte*)index)
{
Vector<byte> vData = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index));
var vMatches = Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)index + LocateFirstFoundByte(vMatches);
}
if ((int)(byte*)index < length)
{
nLength = (IntPtr)(length - (int)(byte*)index);
goto SequentialScan;
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe int IndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue2 = value2; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)length;
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
SequentialScan:
uint lookUp;
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found2;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found3;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 4);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found4;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 5);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found5;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 6);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found6;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 7);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found7;
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found2;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found3;
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
index += 1;
}
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)((length - (int)(byte*)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> values0 = new Vector<byte>(value0);
Vector<byte> values1 = new Vector<byte>(value1);
Vector<byte> values2 = new Vector<byte>(value2);
while ((byte*)nLength > (byte*)index)
{
Vector<byte> vData = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index));
var vMatches = Vector.BitwiseOr(
Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1)),
Vector.Equals(vData, values2));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)index + LocateFirstFoundByte(vMatches);
}
if ((int)(byte*)index < length)
{
nLength = (IntPtr)(length - (int)(byte*)index);
goto SequentialScan;
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe int LastIndexOfAny(ref byte searchSpace, byte value0, byte value1, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)length; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)length;
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(((length & (Vector<byte>.Count - 1)) + unaligned) & (Vector<byte>.Count - 1));
}
SequentialScan:
uint lookUp;
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
index -= 8;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 7);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found7;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 6);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found6;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 5);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found5;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 4);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found4;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
index -= 4;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
index -= 1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
}
if (Vector.IsHardwareAccelerated && ((byte*)index > (byte*)0))
{
nLength = (IntPtr)((int)(byte*)index & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> values0 = new Vector<byte>(value0);
Vector<byte> values1 = new Vector<byte>(value1);
while ((byte*)nLength > (byte*)(Vector<byte>.Count - 1))
{
Vector<byte> vData = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index - Vector<byte>.Count));
var vMatches = Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1));
if (Vector<byte>.Zero.Equals(vMatches))
{
index -= Vector<byte>.Count;
nLength -= Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(index) - Vector<byte>.Count + LocateLastFoundByte(vMatches);
}
if ((byte*)index > (byte*)0)
{
nLength = index;
goto SequentialScan;
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe int LastIndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue2 = value2; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)length; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)length;
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
int unaligned = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(((length & (Vector<byte>.Count - 1)) + unaligned) & (Vector<byte>.Count - 1));
}
SequentialScan:
uint lookUp;
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
index -= 8;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 7);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found7;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 6);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found6;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 5);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found5;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 4);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found4;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found3;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found2;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
index -= 4;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found3;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found2;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
index -= 1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
}
if (Vector.IsHardwareAccelerated && ((byte*)index > (byte*)0))
{
nLength = (IntPtr)((int)(byte*)index & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> values0 = new Vector<byte>(value0);
Vector<byte> values1 = new Vector<byte>(value1);
Vector<byte> values2 = new Vector<byte>(value2);
while ((byte*)nLength > (byte*)(Vector<byte>.Count - 1))
{
Vector<byte> vData = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index - Vector<byte>.Count));
var vMatches = Vector.BitwiseOr(
Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1)),
Vector.Equals(vData, values2));
if (Vector<byte>.Zero.Equals(vMatches))
{
index -= Vector<byte>.Count;
nLength -= Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(index) - Vector<byte>.Count + LocateLastFoundByte(vMatches);
}
if ((byte*)index > (byte*)0)
{
nLength = index;
goto SequentialScan;
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
// Optimized byte-based SequenceEquals. The "length" parameter for this one is declared a nuint rather than int as we also use it for types other than byte
// where the length can exceed 2Gb once scaled by sizeof(T).
public static unsafe bool SequenceEqual(ref byte first, ref byte second, nuint length)
{
if (Unsafe.AreSame(ref first, ref second))
goto Equal;
IntPtr i = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr n = (IntPtr)(void*)length;
if (Vector.IsHardwareAccelerated && (byte*)n >= (byte*)Vector<byte>.Count)
{
n -= Vector<byte>.Count;
while ((byte*)n > (byte*)i)
{
if (Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref first, i)) !=
Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref second, i)))
{
goto NotEqual;
}
i += Vector<byte>.Count;
}
return Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref first, n)) ==
Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref second, n));
}
if ((byte*)n >= (byte*)sizeof(UIntPtr))
{
n -= sizeof(UIntPtr);
while ((byte*)n > (byte*)i)
{
if (Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref first, i)) !=
Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref second, i)))
{
goto NotEqual;
}
i += sizeof(UIntPtr);
}
return Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref first, n)) ==
Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref second, n));
}
while ((byte*)n > (byte*)i)
{
if (Unsafe.AddByteOffset(ref first, i) != Unsafe.AddByteOffset(ref second, i))
goto NotEqual;
i += 1;
}
Equal:
return true;
NotEqual: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return false;
}
// Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundByte(Vector<byte> match)
{
var vector64 = Vector.AsVectorUInt64(match);
ulong candidate = 0;
int i = 0;
// Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001
for (; i < Vector<ulong>.Count; i++)
{
candidate = vector64[i];
if (candidate != 0)
{
break;
}
}
// Single LEA instruction with jitted const (using function result)
return i * 8 + LocateFirstFoundByte(candidate);
}
public static unsafe int SequenceCompareTo(ref byte first, int firstLength, ref byte second, int secondLength)
{
Debug.Assert(firstLength >= 0);
Debug.Assert(secondLength >= 0);
if (Unsafe.AreSame(ref first, ref second))
goto Equal;
IntPtr minLength = (IntPtr)((firstLength < secondLength) ? firstLength : secondLength);
IntPtr i = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr n = (IntPtr)(void*)minLength;
if (Vector.IsHardwareAccelerated && (byte*)n > (byte*)Vector<byte>.Count)
{
n -= Vector<byte>.Count;
while ((byte*)n > (byte*)i)
{
if (Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref first, i)) !=
Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref second, i)))
{
goto NotEqual;
}
i += Vector<byte>.Count;
}
goto NotEqual;
}
if ((byte*)n > (byte*)sizeof(UIntPtr))
{
n -= sizeof(UIntPtr);
while ((byte*)n > (byte*)i)
{
if (Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref first, i)) !=
Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref second, i)))
{
goto NotEqual;
}
i += sizeof(UIntPtr);
}
}
NotEqual: // Workaround for https://github.com/dotnet/coreclr/issues/13549
while ((byte*)minLength > (byte*)i)
{
int result = Unsafe.AddByteOffset(ref first, i).CompareTo(Unsafe.AddByteOffset(ref second, i));
if (result != 0)
return result;
i += 1;
}
Equal:
return firstLength - secondLength;
}
// Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateLastFoundByte(Vector<byte> match)
{
var vector64 = Vector.AsVectorUInt64(match);
ulong candidate = 0;
int i = Vector<ulong>.Count - 1;
// Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001
for (; i >= 0; i--)
{
candidate = vector64[i];
if (candidate != 0)
{
break;
}
}
// Single LEA instruction with jitted const (using function result)
return i * 8 + LocateLastFoundByte(candidate);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundByte(ulong match)
{
// Flag least significant power of two bit
var powerOfTwoFlag = match ^ (match - 1);
// Shift all powers of two into the high byte and extract
return (int)((powerOfTwoFlag * XorPowerOfTwoToHighByte) >> 57);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateLastFoundByte(ulong match)
{
// Find the most significant byte that has its highest bit set
int index = 7;
while ((long)match > 0)
{
match = match << 8;
index--;
}
return index;
}
private const ulong XorPowerOfTwoToHighByte = (0x07ul |
0x06ul << 8 |
0x05ul << 16 |
0x04ul << 24 |
0x03ul << 32 |
0x02ul << 40 |
0x01ul << 48) + 1;
}
}
| |
namespace Fonet.Layout
{
using System.Collections;
using Fonet.DataTypes;
using Fonet.Fo.Flow;
using Fonet.Fo.Pagination;
using Fonet.Render.Pdf;
internal class Page
{
private int height;
private int width;
private BodyAreaContainer body;
private AreaContainer before;
private AreaContainer after;
private AreaContainer start;
private AreaContainer end;
private AreaTree areaTree;
private PageSequence pageSequence;
protected int pageNumber = 0;
protected string formattedPageNumber;
protected ArrayList linkSets = new ArrayList();
private ArrayList idList = new ArrayList();
private ArrayList footnotes = null;
private ArrayList markers = null;
internal Page(AreaTree areaTree, int height, int width)
{
this.areaTree = areaTree;
this.height = height;
this.width = width;
markers = new ArrayList();
}
public IDReferences getIDReferences()
{
return areaTree.getIDReferences();
}
public void setPageSequence(PageSequence pageSequence)
{
this.pageSequence = pageSequence;
}
public PageSequence getPageSequence()
{
return pageSequence;
}
public AreaTree getAreaTree()
{
return areaTree;
}
public void setNumber(int number)
{
pageNumber = number;
}
public int getNumber()
{
return pageNumber;
}
public void setFormattedNumber(string number)
{
formattedPageNumber = number;
}
public string getFormattedNumber()
{
return formattedPageNumber;
}
internal void addAfter(AreaContainer area)
{
after = area;
area.setPage(this);
}
internal void addBefore(AreaContainer area)
{
before = area;
area.setPage(this);
}
public void addBody(BodyAreaContainer area)
{
body = area;
area.setPage(this);
((BodyAreaContainer)area).getMainReferenceArea().setPage(this);
((BodyAreaContainer)area).getBeforeFloatReferenceArea().setPage(this);
((BodyAreaContainer)area).getFootnoteReferenceArea().setPage(this);
}
internal void addEnd(AreaContainer area)
{
end = area;
area.setPage(this);
}
internal void addStart(AreaContainer area)
{
start = area;
area.setPage(this);
}
public void render(PdfRenderer renderer)
{
renderer.RenderPage(this);
}
public AreaContainer getAfter()
{
return after;
}
public AreaContainer getBefore()
{
return before;
}
public AreaContainer getStart()
{
return start;
}
public AreaContainer getEnd()
{
return end;
}
public BodyAreaContainer getBody()
{
return body;
}
public int GetHeight()
{
return height;
}
public int getWidth()
{
return width;
}
public FontInfo getFontInfo()
{
return areaTree.getFontInfo();
}
public void addLinkSet(LinkSet linkSet)
{
linkSets.Add(linkSet);
}
public ArrayList getLinkSets()
{
return linkSets;
}
public bool hasLinks()
{
return linkSets.Count != 0;
}
public void addToIDList(string id)
{
idList.Add(id);
}
public ArrayList getIDList()
{
return idList;
}
public ArrayList getPendingFootnotes()
{
return footnotes;
}
public void setPendingFootnotes(ArrayList v)
{
footnotes = v;
if (footnotes != null)
{
foreach (FootnoteBody fb in footnotes)
{
if (!Footnote.LayoutFootnote(this, fb, null))
{
// footnotes are too large to fit on empty page.
}
}
footnotes = null;
}
}
public void addPendingFootnote(FootnoteBody fb)
{
if (footnotes == null)
{
footnotes = new ArrayList();
}
footnotes.Add(fb);
}
public void unregisterMarker(Marker marker)
{
markers.Remove(marker);
}
public void registerMarker(Marker marker)
{
markers.Add(marker);
}
public ArrayList getMarkers()
{
return this.markers;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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 !SILVERLIGHT
namespace NLog.UnitTests.Targets
{
using System;
using System.IO;
using System.Text;
using NUnit.Framework;
#if !NUNIT
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using NLog.Config;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Threading;
using System.Collections.Generic;
[TestFixture]
public class FileTargetTests : NLogTestBase
{
private readonly Logger logger = LogManager.GetLogger("NLog.UnitTests.Targets.FileTargetTests");
[Test]
public void SimpleFileTest1()
{
string tempFile = Path.GetTempFileName();
try
{
FileTarget ft = new FileTarget
{
FileName = SimpleLayout.Escape(tempFile),
LineEnding = LineEndingMode.LF,
Layout = "${level} ${message}",
OpenFileCacheTimeout = 0
};
SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
logger.Debug("aaa");
logger.Info("bbb");
logger.Warn("ccc");
LogManager.Configuration = null;
AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8);
}
finally
{
if (File.Exists(tempFile))
File.Delete(tempFile);
}
}
[Test]
public void CsvHeaderTest()
{
// test for the following changes
// https://github.com/NLog/NLog/commit/e1ed0d4857dddc95d5db09ee95e9a0c85afc7810
// codeplex ticket 6370
string tempFile = Path.GetTempFileName();
try
{
for (int i = 0; i < 2; i++)
{
var layout = new CsvLayout
{
Delimiter = CsvColumnDelimiterMode.Semicolon,
WithHeader = true,
Columns =
{
new CsvColumn("name", "${logger}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message", "${message}"),
}
};
FileTarget ft = new FileTarget
{
FileName = SimpleLayout.Escape(tempFile),
LineEnding = LineEndingMode.LF,
Layout = layout,
OpenFileCacheTimeout = 0,
ReplaceFileContentsOnEachWrite = false
};
SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
logger.Debug("aaa");
LogManager.Configuration = null;
}
AssertFileContents(tempFile, "name;level;message\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\n", Encoding.UTF8);
}
finally
{
if (File.Exists(tempFile))
File.Delete(tempFile);
}
}
[Test]
public void DeleteFileOnStartTest()
{
string tempFile = Path.GetTempFileName();
try
{
FileTarget ft = new FileTarget
{
FileName = SimpleLayout.Escape(tempFile),
LineEnding = LineEndingMode.LF,
Layout = "${level} ${message}"
};
SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
logger.Debug("aaa");
logger.Info("bbb");
logger.Warn("ccc");
LogManager.Configuration = null;
AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8);
// configure again, without
// DeleteOldFileOnStartup
ft = new FileTarget
{
FileName = SimpleLayout.Escape(tempFile),
LineEnding = LineEndingMode.LF,
Layout = "${level} ${message}"
};
SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
logger.Debug("aaa");
logger.Info("bbb");
logger.Warn("ccc");
LogManager.Configuration = null;
AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8);
// configure again, this time with
// DeleteOldFileOnStartup
ft = new FileTarget
{
FileName = SimpleLayout.Escape(tempFile),
LineEnding = LineEndingMode.LF,
Layout = "${level} ${message}",
DeleteOldFileOnStartup = true
};
SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
logger.Debug("aaa");
logger.Info("bbb");
logger.Warn("ccc");
LogManager.Configuration = null;
AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8);
}
finally
{
LogManager.Configuration = null;
if (File.Exists(tempFile))
File.Delete(tempFile);
}
}
[Test]
public void CreateDirsTest()
{
// create the file in a not-existent
// directory which forces creation
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
string tempFile = Path.Combine(tempPath, "file.txt");
try
{
FileTarget ft = new FileTarget
{
FileName = tempFile,
LineEnding = LineEndingMode.LF,
Layout = "${level} ${message}"
};
SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
logger.Debug("aaa");
logger.Info("bbb");
logger.Warn("ccc");
LogManager.Configuration = null;
AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8);
}
finally
{
LogManager.Configuration = null;
if (File.Exists(tempFile))
File.Delete(tempFile);
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Test]
public void SequentialArchiveTest1()
{
// create the file in a not-existent
// directory which forces creation
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
string tempFile = Path.Combine(tempPath, "file.txt");
try
{
FileTarget ft = new FileTarget
{
FileName = tempFile,
ArchiveFileName = Path.Combine(tempPath, "archive/{####}.txt"),
ArchiveAboveSize = 1000,
LineEnding = LineEndingMode.LF,
Layout = "${message}",
MaxArchiveFiles = 3,
ArchiveNumbering = ArchiveNumberingMode.Sequence
};
SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
// we emit 5 * 250 *(3 x aaa + \n) bytes
// so that we should get a full file + 3 archives
for (int i = 0; i < 250; ++i)
{
logger.Debug("aaa");
}
for (int i = 0; i < 250; ++i)
{
logger.Debug("bbb");
}
for (int i = 0; i < 250; ++i)
{
logger.Debug("ccc");
}
for (int i = 0; i < 250; ++i)
{
logger.Debug("ddd");
}
for (int i = 0; i < 250; ++i)
{
logger.Debug("eee");
}
LogManager.Configuration = null;
AssertFileContents(tempFile,
StringRepeat(250, "eee\n"),
Encoding.UTF8);
AssertFileContents(
Path.Combine(tempPath, "archive/0001.txt"),
StringRepeat(250, "bbb\n"),
Encoding.UTF8);
AssertFileContents(
Path.Combine(tempPath, "archive/0002.txt"),
StringRepeat(250, "ccc\n"),
Encoding.UTF8);
AssertFileContents(
Path.Combine(tempPath, "archive/0003.txt"),
StringRepeat(250, "ddd\n"),
Encoding.UTF8);
Assert.IsTrue(!File.Exists(Path.Combine(tempPath, "archive/0000.txt")));
Assert.IsTrue(!File.Exists(Path.Combine(tempPath, "archive/0004.txt")));
}
finally
{
LogManager.Configuration = null;
if (File.Exists(tempFile))
File.Delete(tempFile);
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Test]
public void RollingArchiveTest1()
{
// create the file in a not-existent
// directory which forces creation
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
string tempFile = Path.Combine(tempPath, "file.txt");
try
{
FileTarget ft = new FileTarget
{
FileName = tempFile,
ArchiveFileName = Path.Combine(tempPath, "archive/{####}.txt"),
ArchiveAboveSize = 1000,
LineEnding = LineEndingMode.LF,
ArchiveNumbering = ArchiveNumberingMode.Rolling,
Layout = "${message}",
MaxArchiveFiles = 3
};
SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
// we emit 5 * 250 * (3 x aaa + \n) bytes
// so that we should get a full file + 3 archives
for (int i = 0; i < 250; ++i)
{
logger.Debug("aaa");
}
for (int i = 0; i < 250; ++i)
{
logger.Debug("bbb");
}
for (int i = 0; i < 250; ++i)
{
logger.Debug("ccc");
}
for (int i = 0; i < 250; ++i)
{
logger.Debug("ddd");
}
for (int i = 0; i < 250; ++i)
{
logger.Debug("eee");
}
LogManager.Configuration = null;
AssertFileContents(tempFile,
StringRepeat(250, "eee\n"),
Encoding.UTF8);
AssertFileContents(
Path.Combine(tempPath, "archive/0000.txt"),
StringRepeat(250, "ddd\n"),
Encoding.UTF8);
AssertFileContents(
Path.Combine(tempPath, "archive/0001.txt"),
StringRepeat(250, "ccc\n"),
Encoding.UTF8);
AssertFileContents(
Path.Combine(tempPath, "archive/0002.txt"),
StringRepeat(250, "bbb\n"),
Encoding.UTF8);
Assert.IsTrue(!File.Exists(Path.Combine(tempPath, "archive/0003.txt")));
}
finally
{
LogManager.Configuration = null;
if (File.Exists(tempFile))
File.Delete(tempFile);
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Test]
public void MultiFileWrite()
{
// create the file in a not-existent
// directory which forces creation
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
try
{
FileTarget ft = new FileTarget
{
FileName = Path.Combine(tempPath, "${level}.txt"),
LineEnding = LineEndingMode.LF,
Layout = "${message}"
};
SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
for (int i = 0; i < 250; ++i)
{
logger.Trace("@@@");
logger.Debug("aaa");
logger.Info("bbb");
logger.Warn("ccc");
logger.Error("ddd");
logger.Fatal("eee");
}
LogManager.Configuration = null;
Assert.IsFalse(File.Exists(Path.Combine(tempPath, "Trace.txt")));
AssertFileContents(Path.Combine(tempPath, "Debug.txt"),
StringRepeat(250, "aaa\n"), Encoding.UTF8);
AssertFileContents(Path.Combine(tempPath, "Info.txt"),
StringRepeat(250, "bbb\n"), Encoding.UTF8);
AssertFileContents(Path.Combine(tempPath, "Warn.txt"),
StringRepeat(250, "ccc\n"), Encoding.UTF8);
AssertFileContents(Path.Combine(tempPath, "Error.txt"),
StringRepeat(250, "ddd\n"), Encoding.UTF8);
AssertFileContents(Path.Combine(tempPath, "Fatal.txt"),
StringRepeat(250, "eee\n"), Encoding.UTF8);
}
finally
{
//if (File.Exists(tempFile))
// File.Delete(tempFile);
LogManager.Configuration = null;
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Test]
public void BufferedMultiFileWrite()
{
// create the file in a not-existent
// directory which forces creation
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
try
{
FileTarget ft = new FileTarget
{
FileName = Path.Combine(tempPath, "${level}.txt"),
LineEnding = LineEndingMode.LF,
Layout = "${message}"
};
SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 10), LogLevel.Debug);
for (int i = 0; i < 250; ++i)
{
logger.Trace("@@@");
logger.Debug("aaa");
logger.Info("bbb");
logger.Warn("ccc");
logger.Error("ddd");
logger.Fatal("eee");
}
LogManager.Configuration = null;
Assert.IsFalse(File.Exists(Path.Combine(tempPath, "Trace.txt")));
AssertFileContents(Path.Combine(tempPath, "Debug.txt"),
StringRepeat(250, "aaa\n"), Encoding.UTF8);
AssertFileContents(Path.Combine(tempPath, "Info.txt"),
StringRepeat(250, "bbb\n"), Encoding.UTF8);
AssertFileContents(Path.Combine(tempPath, "Warn.txt"),
StringRepeat(250, "ccc\n"), Encoding.UTF8);
AssertFileContents(Path.Combine(tempPath, "Error.txt"),
StringRepeat(250, "ddd\n"), Encoding.UTF8);
AssertFileContents(Path.Combine(tempPath, "Fatal.txt"),
StringRepeat(250, "eee\n"), Encoding.UTF8);
}
finally
{
//if (File.Exists(tempFile))
// File.Delete(tempFile);
LogManager.Configuration = null;
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Test]
public void AsyncMultiFileWrite()
{
//InternalLogger.LogToConsole = true;
//InternalLogger.LogLevel = LogLevel.Trace;
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
try
{
FileTarget ft = new FileTarget
{
FileName = Path.Combine(tempPath, "${level}.txt"),
LineEnding = LineEndingMode.LF,
Layout = "${message} ${threadid}"
};
// this also checks that thread-volatile layouts
// such as ${threadid} are properly cached and not recalculated
// in logging threads.
string threadID = Thread.CurrentThread.ManagedThreadId.ToString();
//InternalLogger.LogToConsole = true;
//InternalLogger.LogLevel = LogLevel.Trace;
SimpleConfigurator.ConfigureForTargetLogging(new AsyncTargetWrapper(ft, 1000, AsyncTargetWrapperOverflowAction.Grow), LogLevel.Debug);
LogManager.ThrowExceptions = true;
for (int i = 0; i < 250; ++i)
{
logger.Trace("@@@");
logger.Debug("aaa");
logger.Info("bbb");
logger.Warn("ccc");
logger.Error("ddd");
logger.Fatal("eee");
}
LogManager.Flush();
LogManager.Configuration = null;
Assert.IsFalse(File.Exists(Path.Combine(tempPath, "Trace.txt")));
AssertFileContents(Path.Combine(tempPath, "Debug.txt"),
StringRepeat(250, "aaa " + threadID + "\n"), Encoding.UTF8);
AssertFileContents(Path.Combine(tempPath, "Info.txt"),
StringRepeat(250, "bbb " + threadID + "\n"), Encoding.UTF8);
AssertFileContents(Path.Combine(tempPath, "Warn.txt"),
StringRepeat(250, "ccc " + threadID + "\n"), Encoding.UTF8);
AssertFileContents(Path.Combine(tempPath, "Error.txt"),
StringRepeat(250, "ddd " + threadID + "\n"), Encoding.UTF8);
AssertFileContents(Path.Combine(tempPath, "Fatal.txt"),
StringRepeat(250, "eee " + threadID + "\n"), Encoding.UTF8);
}
finally
{
//if (File.Exists(tempFile))
// File.Delete(tempFile);
LogManager.Configuration = null;
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Test]
public void BatchErrorHandlingTest()
{
var fileTarget = new FileTarget {FileName = "${logger}", Layout = "${message}"};
fileTarget.Initialize(null);
// make sure that when file names get sorted, the asynchronous continuations are sorted with them as well
var exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Info, "file99.txt", "msg1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "a/", "msg1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "a/", "msg2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "a/", "msg3").WithContinuation(exceptions.Add)
};
fileTarget.WriteAsyncLogEvents(events);
Assert.AreEqual(4, exceptions.Count);
Assert.IsNull(exceptions[0]);
Assert.IsNotNull(exceptions[1]);
Assert.IsNotNull(exceptions[2]);
Assert.IsNotNull(exceptions[3]);
}
[Test]
public void DisposingFileTarget_WhenNotIntialized_ShouldNotThrow()
{
bool exceptionThrown = false;
var fileTarget = new FileTarget();
try
{
fileTarget.Dispose();
}
catch
{
exceptionThrown = true;
}
Assert.IsFalse(exceptionThrown);
}
[Test]
public void FileTarget_WithArchiveFileNameEndingInNumberPlaceholder_ShouldArchiveFile()
{
// create the file in a not-existent
// directory which forces creation
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
string tempFile = Path.Combine(tempPath, "file.txt");
try
{
FileTarget ft = new FileTarget
{
FileName = tempFile,
ArchiveFileName = Path.Combine(tempPath, "archive/test.log.{####}"),
ArchiveAboveSize = 1000
};
SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
for (int i = 0; i < 100; ++i)
{
logger.Debug("a");
}
LogManager.Configuration = null;
Assert.IsTrue(File.Exists(tempFile));
Assert.IsTrue(File.Exists(Path.Combine(tempPath, "archive/test.log.0000")));
}
finally
{
LogManager.Configuration = null;
if (File.Exists(tempFile))
File.Delete(tempFile);
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
}
}
#endif
| |
// This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEditor;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Fungus.EditorUtils
{
[CustomEditor (typeof(Variable), true)]
public class VariableEditor : CommandEditor
{
public override void OnEnable()
{
base.OnEnable();
Variable t = target as Variable;
t.hideFlags = HideFlags.HideInInspector;
}
public static VariableInfoAttribute GetVariableInfo(System.Type variableType)
{
object[] attributes = variableType.GetCustomAttributes(typeof(VariableInfoAttribute), false);
foreach (object obj in attributes)
{
VariableInfoAttribute variableInfoAttr = obj as VariableInfoAttribute;
if (variableInfoAttr != null)
{
return variableInfoAttr;
}
}
return null;
}
public static void VariableField(SerializedProperty property,
GUIContent label,
Flowchart flowchart,
string defaultText,
Func<Variable, bool> filter,
Func<string, int, string[], int> drawer = null)
{
List<string> variableKeys = new List<string>();
List<Variable> variableObjects = new List<Variable>();
variableKeys.Add(defaultText);
variableObjects.Add(null);
List<Variable> variables = flowchart.Variables;
int index = 0;
int selectedIndex = 0;
Variable selectedVariable = property.objectReferenceValue as Variable;
// When there are multiple Flowcharts in a scene with variables, switching
// between the Flowcharts can cause the wrong variable property
// to be inspected for a single frame. This has the effect of causing private
// variable references to be set to null when inspected. When this condition
// occurs we just skip displaying the property for this frame.
if (selectedVariable != null &&
selectedVariable.gameObject != flowchart.gameObject &&
selectedVariable.Scope == VariableScope.Private)
{
property.objectReferenceValue = null;
return;
}
foreach (Variable v in variables)
{
if (filter != null)
{
if (!filter(v))
{
continue;
}
}
variableKeys.Add(v.Key);
variableObjects.Add(v);
index++;
if (v == selectedVariable)
{
selectedIndex = index;
}
}
List<Flowchart> fsList = Flowchart.CachedFlowcharts;
foreach (Flowchart fs in fsList)
{
if (fs == flowchart)
{
continue;
}
List<Variable> publicVars = fs.GetPublicVariables();
foreach (Variable v in publicVars)
{
if (filter != null)
{
if (!filter(v))
{
continue;
}
}
variableKeys.Add(fs.name + "/" + v.Key);
variableObjects.Add(v);
index++;
if (v == selectedVariable)
{
selectedIndex = index;
}
}
}
if (drawer == null)
{
selectedIndex = EditorGUILayout.Popup(label.text, selectedIndex, variableKeys.ToArray());
}
else
{
selectedIndex = drawer(label.text, selectedIndex, variableKeys.ToArray());
}
property.objectReferenceValue = variableObjects[selectedIndex];
}
}
[CustomPropertyDrawer(typeof(VariablePropertyAttribute))]
public class VariableDrawer : PropertyDrawer
{
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
{
VariablePropertyAttribute variableProperty = attribute as VariablePropertyAttribute;
if (variableProperty == null)
{
return;
}
EditorGUI.BeginProperty(position, label, property);
// Filter the variables by the types listed in the VariableProperty attribute
Func<Variable, bool> compare = v =>
{
if (v == null)
{
return false;
}
if (variableProperty.VariableTypes.Length == 0)
{
var compatChecker = property.serializedObject.targetObject as ICollectionCompatible;
if (compatChecker != null)
{
return compatChecker.IsVarCompatibleWithCollection(v, variableProperty.compatibleVariableName);
}
else
{
return true;
}
}
return variableProperty.VariableTypes.Contains<System.Type>(v.GetType());
};
VariableEditor.VariableField(property,
label,
FlowchartWindow.GetFlowchart(),
variableProperty.defaultText,
compare,
(s,t,u) => (EditorGUI.Popup(position, s, t, u)));
EditorGUI.EndProperty();
}
}
public class VariableDataDrawer<T> : PropertyDrawer where T : Variable
{
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
// The variable reference and data properties must follow the naming convention 'typeRef', 'typeVal'
VariableInfoAttribute typeInfo = VariableEditor.GetVariableInfo(typeof(T));
if (typeInfo == null)
{
return;
}
string propNameBase = typeInfo.VariableType;
propNameBase = Char.ToLowerInvariant(propNameBase[0]) + propNameBase.Substring(1);
SerializedProperty referenceProp = property.FindPropertyRelative(propNameBase + "Ref");
SerializedProperty valueProp = property.FindPropertyRelative(propNameBase + "Val");
if (referenceProp == null || valueProp == null)
{
return;
}
Command command = property.serializedObject.targetObject as Command;
if (command == null)
{
return;
}
var flowchart = command.GetFlowchart() as Flowchart;
if (flowchart == null)
{
return;
}
var origLabel = new GUIContent(label);
var itemH = EditorGUI.GetPropertyHeight(valueProp, label);
if (itemH <= EditorGUIUtility.singleLineHeight*2)
{
DrawSingleLineProperty(position, origLabel, referenceProp, valueProp, flowchart, typeInfo);
}
else
{
DrawMultiLineProperty(position, origLabel, referenceProp, valueProp, flowchart, typeInfo);
}
EditorGUI.EndProperty();
}
protected virtual void DrawSingleLineProperty(Rect rect, GUIContent label, SerializedProperty referenceProp, SerializedProperty valueProp, Flowchart flowchart,
VariableInfoAttribute typeInfo)
{
int popupWidth = Mathf.RoundToInt(EditorGUIUtility.singleLineHeight);
const int popupGap = 5;
//get out starting rect with intent honoured
Rect controlRect = EditorGUI.PrefixLabel(rect, label);
Rect valueRect = controlRect;
valueRect.width = controlRect.width - popupWidth - popupGap;
Rect popupRect = controlRect;
//we are overriding much of the auto layout to cram this all on 1 line so zero the intend and restore it later
var prevIndent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
if (referenceProp.objectReferenceValue == null)
{
CustomVariableDrawerLookup.DrawCustomOrPropertyField(typeof(T), valueRect, valueProp, GUIContent.none);
popupRect.x += valueRect.width + popupGap;
popupRect.width = popupWidth;
}
EditorGUI.PropertyField(popupRect, referenceProp, GUIContent.none);
EditorGUI.indentLevel = prevIndent;
}
protected virtual void DrawMultiLineProperty(Rect rect, GUIContent label, SerializedProperty referenceProp, SerializedProperty valueProp, Flowchart flowchart,
VariableInfoAttribute typeInfo)
{
const int popupWidth = 100;
Rect controlRect = rect;
Rect valueRect = controlRect;
//valueRect.width = controlRect.width - 5;
Rect popupRect = controlRect;
popupRect.height = EditorGUIUtility.singleLineHeight;
if (referenceProp.objectReferenceValue == null)
{
//EditorGUI.PropertyField(valueRect, valueProp, label);
CustomVariableDrawerLookup.DrawCustomOrPropertyField(typeof(T), valueRect, valueProp, label);
popupRect.x = rect.width - popupWidth + 5;
popupRect.width = popupWidth;
}
else
{
popupRect = EditorGUI.PrefixLabel(rect, label);
}
EditorGUI.PropertyField(popupRect, referenceProp, GUIContent.none);
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
VariableInfoAttribute typeInfo = VariableEditor.GetVariableInfo(typeof(T));
if (typeInfo == null)
{
return EditorGUIUtility.singleLineHeight;
}
string propNameBase = typeInfo.VariableType;
propNameBase = Char.ToLowerInvariant(propNameBase[0]) + propNameBase.Substring(1);
SerializedProperty referenceProp = property.FindPropertyRelative(propNameBase + "Ref");
if (referenceProp.objectReferenceValue != null)
{
return EditorGUIUtility.singleLineHeight;
}
SerializedProperty valueProp = property.FindPropertyRelative(propNameBase + "Val");
return EditorGUI.GetPropertyHeight(valueProp, label);
}
}
[CustomPropertyDrawer (typeof(BooleanData))]
public class BooleanDataDrawer : VariableDataDrawer<BooleanVariable>
{}
[CustomPropertyDrawer (typeof(IntegerData))]
public class IntegerDataDrawer : VariableDataDrawer<IntegerVariable>
{}
[CustomPropertyDrawer (typeof(FloatData))]
public class FloatDataDrawer : VariableDataDrawer<FloatVariable>
{}
[CustomPropertyDrawer (typeof(StringData))]
public class StringDataDrawer : VariableDataDrawer<StringVariable>
{}
[CustomPropertyDrawer (typeof(StringDataMulti))]
public class StringDataMultiDrawer : VariableDataDrawer<StringVariable>
{}
}
| |
#region Copyright notice
/**
* Copyright (c) 2018 Samsung Electronics, Inc.,
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using DexterCS.Client;
using DexterCS.Client;
using DexterCS.Job;
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace DexterCS
{
public class CLIAnalysisResultHandler : IAnalysisResultHandler
{
private ILog cliLog;
private IDexterCLIOption cliOption;
private string dexterWebUrl;
private ICLIResultFile cliResultFile = new CLIResultFile();
private int totalCnt = 0;
private int totalOccurenceCnt = 0;
private int criticalCnt = 0;
private int majorCnt = 0;
private int minorCnt = 0;
private int etcCnt = 0;
private int crcCnt = 0;
public CLIAnalysisResultHandler(string dexterWebUrl, IDexterCLIOption cliOption, ILog cliLog)
{
this.dexterWebUrl = dexterWebUrl;
this.cliOption = cliOption;
this.cliLog = cliLog;
}
public void HandleBeginningOfResultFile()
{
try
{
if (cliOption.IsJsonResultFile)
{
cliResultFile.WriteJsonResultFilePrefix(cliOption.JsonResultFile);
}
if (cliOption.IsXmlResultFile)
{
cliResultFile.WriteXmlResultFilePrefix(cliOption.XmlResultFile);
}
if (cliOption.IsXml2ResultFile)
{
cliResultFile.WriteXml2ResultFilePrefix(cliOption.Xml2ResultFile);
}
}
catch (IOException e)
{
cliLog.Error(e.Message, e);
}
}
public void HandleEndOfResultFile()
{
try
{
if (cliOption.IsXmlResultFile)
{
cliResultFile.WriteXmlResultFilePostfix(cliOption.XmlResultFile);
}
else if (cliOption.IsJsonResultFile)
{
cliResultFile.WriteJsonResultFilePostfix(cliOption.JsonResultFile);
}
}
catch (Exception e)
{
cliLog.Error(e.StackTrace);
}
}
public void PrintLogAfterAnalyze()
{
cliLog.Info("");
cliLog.Info("====================================================");
cliLog.Info("- Total Defects: " + totalCnt);
cliLog.Info("- Critical Defects: " + criticalCnt);
cliLog.Info("- Major Defects: " + majorCnt);
cliLog.Info("- Minor Defects: " + minorCnt);
cliLog.Info("- CRC Defects: " + crcCnt);
cliLog.Info("- Etc. Defects: " + etcCnt);
cliLog.Info("- Total Occurences: " + totalOccurenceCnt);
cliLog.Info("====================================================");
cliLog.Info("");
}
public void HandleAnalysisResult(List<AnalysisResult> resultList, IDexterClient client)
{
if (resultList.Count == 0)
{
cliLog.Warn("No defect result");
return;
}
List<Defect> allDefectList = DexterAnalyzer.AllDefectList(resultList);
AnalysisResult firstAnalysisResult = resultList[0];
string sourceFileFullPath = firstAnalysisResult.SourceFileFullPath;
try
{
WriteResultFile(allDefectList, sourceFileFullPath);
string resultFilePrefixName = AnalysisResultFileManager.Instance.
GetResultFilePrefixName(firstAnalysisResult.ModulePath, firstAnalysisResult.FileName);
SendResultJob.SendResultFileThenDelete(client, resultFilePrefixName);
}
catch (IOException e)
{
cliLog.Error(e.StackTrace);
}
cliLog.Info(" - " + sourceFileFullPath);
if (allDefectList.Count == 0)
{
cliLog.Info(" > No Defect");
return;
}
else
{
cliLog.Info(" > Total Defects: " + allDefectList.Count);
}
PrintDefect(allDefectList);
}
private void PrintDefect(List<Defect> allDefectList)
{
foreach (var defect in allDefectList)
{
switch (defect.SeverityCode)
{
case "CRI":
criticalCnt++;
break;
case "MAJ":
majorCnt++;
break;
case "MIN":
minorCnt++;
break;
case "CRC":
crcCnt++;
break;
case "ETC":
etcCnt++;
break;
default:
defect.SeverityCode = "ETC";
etcCnt++;
break;
}
totalCnt++;
totalOccurenceCnt += defect.Occurences.Count;
cliLog.Info(" > " + defect.CheckerCode + " / " + defect.SeverityCode + " / "
+ defect.Occurences.Count + " / " + defect.MethodName + " / " + defect.ClassName);
PrintOccurences(defect.Occurences.ToArray());
}
}
private void PrintOccurences(Occurence[] occurence)
{
int i = 0;
foreach (var occ in occurence)
{
i += 1;
if (i == occurence.Count())
{
cliLog.Info(" + " + occ.StartLine + " " + occ.Message + " / " +
occ.VariableName + " / " + occ.StringValue);
}
else
{
cliLog.Info(" + " + occ.StartLine + " " + occ.Message + " / " +
occ.VariableName + " / " + occ.StringValue);
}
}
}
private void WriteResultFile(List<Defect> allDefectList, string sourceFileFullPath)
{
if (cliOption.IsJsonResultFile)
{
cliResultFile.WriteJsonResultFileBody(cliOption.JsonResultFile, allDefectList);
}
if (cliOption.IsXmlResultFile)
{
cliResultFile.WriteXmlResultFileBody(cliOption.XmlResultFile, allDefectList, sourceFileFullPath);
}
if (cliOption.IsXml2ResultFile)
{
cliResultFile.WriteXml2ResultFileBody(cliOption.Xml2ResultFile, allDefectList, sourceFileFullPath);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Streams;
namespace Orleans
{
/// <summary>
/// Client runtime for connecting to Orleans system
/// </summary>
/// TODO: Make this class non-static and inject it where it is needed.
public static class GrainClient
{
/// <summary>
/// Whether the client runtime has already been initialized
/// </summary>
/// <returns><c>true</c> if client runtime is already initialized</returns>
public static bool IsInitialized { get { return isFullyInitialized && RuntimeClient.Current != null; } }
internal static ClientConfiguration CurrentConfig { get; private set; }
internal static bool TestOnlyNoConnect { get; set; }
private static bool isFullyInitialized = false;
private static OutsideRuntimeClient outsideRuntimeClient;
private static readonly object initLock = new Object();
private static GrainFactory grainFactory;
// RuntimeClient.Current is set to something different than OutsideRuntimeClient - it can only be set to InsideRuntimeClient, since we only have 2.
// That means we are running in side a silo.
private static bool IsRunningInsideSilo { get { return RuntimeClient.Current != null && !(RuntimeClient.Current is OutsideRuntimeClient); } }
//TODO: prevent client code from using this from inside a Grain or provider
public static IGrainFactory GrainFactory
{
get
{
if (IsRunningInsideSilo)
{
// just in case, make sure we don't get NullRefExc when checking RuntimeContext.
bool runningInsideGrain = RuntimeContext.Current != null && RuntimeContext.CurrentActivationContext != null
&& RuntimeContext.CurrentActivationContext.ContextType == SchedulingContextType.Activation;
if (runningInsideGrain)
{
throw new OrleansException("You are running inside a grain. GrainClient.GrainFactory should only be used on the client side. " +
"Inside a grain use GrainFactory property of the Grain base class (use this.GrainFactory).");
}
else // running inside provider or else where
{
throw new OrleansException("You are running inside the provider code, on the silo. GrainClient.GrainFactory should only be used on the client side. " +
"Inside the provider code use GrainFactory that is passed via IProviderRuntime (use providerRuntime.GrainFactory).");
}
}
if (!IsInitialized)
{
throw new OrleansException("You must initialize the Grain Client before accessing the GrainFactory");
}
return grainFactory;
}
}
internal static GrainFactory InternalGrainFactory
{
get
{
if (!IsInitialized)
{
throw new OrleansException("You must initialize the Grain Client before accessing the InternalGrainFactory");
}
return grainFactory;
}
}
/// <summary>
/// Initializes the client runtime from the standard client configuration file.
/// </summary>
public static void Initialize()
{
ClientConfiguration config = ClientConfiguration.StandardLoad();
if (config == null)
{
Console.WriteLine("Error loading standard client configuration file.");
throw new ArgumentException("Error loading standard client configuration file");
}
InternalInitialize(config);
}
/// <summary>
/// Initializes the client runtime from the provided client configuration file.
/// If an error occurs reading the specified configuration file, the initialization fails.
/// </summary>
/// <param name="configFilePath">A relative or absolute pathname for the client configuration file.</param>
public static void Initialize(string configFilePath)
{
Initialize(new FileInfo(configFilePath));
}
/// <summary>
/// Initializes the client runtime from the provided client configuration file.
/// If an error occurs reading the specified configuration file, the initialization fails.
/// </summary>
/// <param name="configFile">The client configuration file.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static void Initialize(FileInfo configFile)
{
ClientConfiguration config;
try
{
config = ClientConfiguration.LoadFromFile(configFile.FullName);
}
catch (Exception ex)
{
Console.WriteLine("Error loading client configuration file {0}: {1}", configFile.FullName, ex);
throw;
}
if (config == null)
{
Console.WriteLine("Error loading client configuration file {0}:", configFile.FullName);
throw new ArgumentException(String.Format("Error loading client configuration file {0}:", configFile.FullName), "configFile");
}
InternalInitialize(config);
}
/// <summary>
/// Initializes the client runtime from the provided client configuration object.
/// If the configuration object is null, the initialization fails.
/// </summary>
/// <param name="config">A ClientConfiguration object.</param>
public static void Initialize(ClientConfiguration config)
{
if (config == null)
{
Console.WriteLine("Initialize was called with null ClientConfiguration object.");
throw new ArgumentException("Initialize was called with null ClientConfiguration object.", "config");
}
InternalInitialize(config);
}
/// <summary>
/// Initializes the client runtime from the standard client configuration file using the provided gateway address.
/// Any gateway addresses specified in the config file will be ignored and the provided gateway address wil be used instead.
/// </summary>
/// <param name="gatewayAddress">IP address and port of the gateway silo</param>
/// <param name="overrideConfig">Whether the specified gateway endpoint should override / replace the values from config file, or be additive</param>
public static void Initialize(IPEndPoint gatewayAddress, bool overrideConfig = true)
{
var config = ClientConfiguration.StandardLoad();
if (config == null)
{
Console.WriteLine("Error loading standard client configuration file.");
throw new ArgumentException("Error loading standard client configuration file");
}
if (overrideConfig)
{
config.Gateways = new List<IPEndPoint>(new[] { gatewayAddress });
}
else if (!config.Gateways.Contains(gatewayAddress))
{
config.Gateways.Add(gatewayAddress);
}
config.PreferedGatewayIndex = config.Gateways.IndexOf(gatewayAddress);
InternalInitialize(config);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void InternalInitialize(ClientConfiguration config, OutsideRuntimeClient runtimeClient = null)
{
// We deliberately want to run this initialization code on .NET thread pool thread to escape any
// TPL execution environment and avoid any conflicts with client's synchronization context
var tcs = new TaskCompletionSource<ClientConfiguration>();
WaitCallback doInit = state =>
{
try
{
if (TestOnlyNoConnect)
{
Trace.TraceInformation("TestOnlyNoConnect - Returning before connecting to cluster.");
}
else
{
// Finish initializing this client connection to the Orleans cluster
DoInternalInitialize(config, runtimeClient);
}
tcs.SetResult(config); // Resolve promise
}
catch (Exception exc)
{
tcs.SetException(exc); // Break promise
}
};
// Queue Init call to thread pool thread
ThreadPool.QueueUserWorkItem(doInit, null);
try
{
CurrentConfig = tcs.Task.Result; // Wait for Init to finish
}
catch (AggregateException ae)
{
// Flatten the aggregate exception, which can be deeply nested.
ae = ae.Flatten();
// If there is just one exception in the aggregate exception, throw that, otherwise throw the entire
// flattened aggregate exception.
var innerExceptions = ae.InnerExceptions;
var exceptionToThrow = innerExceptions.Count == 1 ? innerExceptions[0] : ae;
ExceptionDispatchInfo.Capture(exceptionToThrow).Throw();
}
}
/// <summary>
/// Initializes client runtime from client configuration object.
/// </summary>
private static void DoInternalInitialize(ClientConfiguration config, OutsideRuntimeClient runtimeClient = null)
{
if (IsInitialized)
return;
lock (initLock)
{
if (!IsInitialized)
{
try
{
// this is probably overkill, but this ensures isFullyInitialized false
// before we make a call that makes RuntimeClient.Current not null
isFullyInitialized = false;
grainFactory = new GrainFactory();
if (runtimeClient == null)
{
runtimeClient = new OutsideRuntimeClient(config, grainFactory);
}
outsideRuntimeClient = runtimeClient; // Keep reference, to avoid GC problems
outsideRuntimeClient.Start();
// this needs to be the last successful step inside the lock so
// IsInitialized doesn't return true until we're fully initialized
isFullyInitialized = true;
}
catch (Exception exc)
{
// just make sure to fully Uninitialize what we managed to partially initialize, so we don't end up in inconsistent state and can later on re-initialize.
Console.WriteLine("Initialization failed. {0}", exc);
InternalUninitialize();
throw;
}
}
}
}
/// <summary>
/// Uninitializes client runtime.
/// </summary>
public static void Uninitialize()
{
lock (initLock)
{
InternalUninitialize();
}
}
/// <summary>
/// Test hook to uninitialize client without cleanup
/// </summary>
public static void HardKill()
{
lock (initLock)
{
InternalUninitialize(false);
}
}
/// <summary>
/// This is the lock free version of uninitilize so we can share
/// it between the public method and error paths inside initialize.
/// This should only be called inside a lock(initLock) block.
/// </summary>
private static void InternalUninitialize(bool cleanup = true)
{
// Update this first so IsInitialized immediately begins returning
// false. Since this method should be protected externally by
// a lock(initLock) we should be able to reset everything else
// before the next init attempt.
isFullyInitialized = false;
if (RuntimeClient.Current != null)
{
try
{
RuntimeClient.Current.Reset(cleanup);
}
catch (Exception) { }
RuntimeClient.Current = null;
}
outsideRuntimeClient = null;
grainFactory = null;
}
/// <summary>
/// Check that the runtime is intialized correctly, and throw InvalidOperationException if not
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
private static void CheckInitialized()
{
if (!IsInitialized)
throw new InvalidOperationException("Runtime is not initialized. Call Client.Initialize method to initialize the runtime.");
}
/// <summary>
/// Provides logging facility for applications.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
public static Logger Logger
{
get
{
CheckInitialized();
return RuntimeClient.Current.AppLogger;
}
}
/// <summary>
/// Set a timeout for responses on this Orleans client.
/// </summary>
/// <param name="timeout"></param>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
public static void SetResponseTimeout(TimeSpan timeout)
{
CheckInitialized();
RuntimeClient.Current.SetResponseTimeout(timeout);
}
/// <summary>
/// Get a timeout of responses on this Orleans client.
/// </summary>
/// <returns>The response timeout.</returns>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
public static TimeSpan GetResponseTimeout()
{
CheckInitialized();
return RuntimeClient.Current.GetResponseTimeout();
}
/// <summary>
/// Global pre-call interceptor function
/// Synchronous callback made just before a message is about to be constructed and sent by a client to a grain.
/// This call will be made from the same thread that constructs the message to be sent, so any thread-local settings
/// such as <c>Orleans.RequestContext</c> will be picked up.
/// </summary>
/// <remarks>This callback method should return promptly and do a minimum of work, to avoid blocking calling thread or impacting throughput.</remarks>
/// <param name="request">Details of the method to be invoked, including InterfaceId and MethodId</param>
/// <param name="grain">The GrainReference this request is being sent through.</param>
public static Action<InvokeMethodRequest, IGrain> ClientInvokeCallback { get; set; }
public static IEnumerable<Streams.IStreamProvider> GetStreamProviders()
{
return RuntimeClient.Current.CurrentStreamProviderManager.GetStreamProviders();
}
internal static IStreamProviderRuntime CurrentStreamProviderRuntime
{
get { return RuntimeClient.Current.CurrentStreamProviderRuntime; }
}
public static Streams.IStreamProvider GetStreamProvider(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException("name");
return RuntimeClient.Current.CurrentStreamProviderManager.GetProvider(name) as Streams.IStreamProvider;
}
internal static IList<Uri> Gateways
{
get
{
CheckInitialized();
return outsideRuntimeClient.Gateways;
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Net;
using System.Runtime;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Security;
class HttpsChannelListener<TChannel> : HttpChannelListener<TChannel>
where TChannel : class, IChannel
{
readonly bool useCustomClientCertificateVerification;
bool shouldValidateClientCertificate;
bool useHostedClientCertificateMapping;
bool requireClientCertificate;
SecurityTokenAuthenticator certificateAuthenticator;
const HttpStatusCode CertificateErrorStatusCode = HttpStatusCode.Forbidden;
IChannelBindingProvider channelBindingProvider;
public HttpsChannelListener(HttpsTransportBindingElement httpsBindingElement, BindingContext context)
: base(httpsBindingElement, context)
{
this.requireClientCertificate = httpsBindingElement.RequireClientCertificate;
this.shouldValidateClientCertificate = ShouldValidateClientCertificate(this.requireClientCertificate, context);
// Pick up the MapCertificateToWindowsAccount setting from the configured token authenticator.
SecurityCredentialsManager credentialProvider =
context.BindingParameters.Find<SecurityCredentialsManager>();
if (credentialProvider == null)
{
credentialProvider = ServiceCredentials.CreateDefaultCredentials();
}
SecurityTokenManager tokenManager = credentialProvider.CreateSecurityTokenManager();
this.certificateAuthenticator =
TransportSecurityHelpers.GetCertificateTokenAuthenticator(tokenManager, context.Binding.Scheme,
TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress));
ServiceCredentials serviceCredentials = credentialProvider as ServiceCredentials;
if (serviceCredentials != null &&
serviceCredentials.ClientCertificate.Authentication.CertificateValidationMode == X509CertificateValidationMode.Custom)
{
useCustomClientCertificateVerification = true;
}
else
{
useCustomClientCertificateVerification = false;
X509SecurityTokenAuthenticator authenticator = this.certificateAuthenticator as X509SecurityTokenAuthenticator;
if (authenticator != null)
{
this.certificateAuthenticator = new X509SecurityTokenAuthenticator(X509CertificateValidator.None,
authenticator.MapCertificateToWindowsAccount, this.ExtractGroupsForWindowsAccounts, false);
}
}
if (this.RequireClientCertificate &&
this.AuthenticationScheme.IsNotSet(AuthenticationSchemes.Anonymous))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new InvalidOperationException(SR.GetString(
SR.HttpAuthSchemeAndClientCert, this.AuthenticationScheme)), TraceEventType.Error);
}
this.channelBindingProvider = new ChannelBindingProviderHelper();
}
public bool RequireClientCertificate
{
get
{
return this.requireClientCertificate;
}
}
public override string Scheme
{
get
{
return Uri.UriSchemeHttps;
}
}
public override bool IsChannelBindingSupportEnabled
{
get
{
return this.channelBindingProvider.IsChannelBindingSupportEnabled;
}
}
internal override UriPrefixTable<ITransportManagerRegistration> TransportManagerTable
{
get
{
return SharedHttpsTransportManager.StaticTransportManagerTable;
}
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(IChannelBindingProvider))
{
return (T)(object)this.channelBindingProvider;
}
return base.GetProperty<T>();
}
internal override void ApplyHostedContext(string virtualPath, bool isMetadataListener)
{
base.ApplyHostedContext(virtualPath, isMetadataListener);
useHostedClientCertificateMapping = AspNetEnvironment.Current.ValidateHttpsSettings(virtualPath, ref this.requireClientCertificate);
// We want to validate the certificate if IIS is set to require a client certificate
if (this.requireClientCertificate)
{
this.shouldValidateClientCertificate = true;
}
}
internal override ITransportManagerRegistration CreateTransportManagerRegistration(Uri listenUri)
{
return new SharedHttpsTransportManager(listenUri, this);
}
// Note: the returned SecurityMessageProperty has ownership of certificate and identity.
SecurityMessageProperty CreateSecurityProperty(X509Certificate2 certificate, WindowsIdentity identity, string authType)
{
SecurityToken token;
if (identity != null)
{
token = new X509WindowsSecurityToken(certificate, identity, authType, false);
}
else
{
token = new X509SecurityToken(certificate, false);
}
ReadOnlyCollection<IAuthorizationPolicy> policies = this.certificateAuthenticator.ValidateToken(token);
SecurityMessageProperty result = new SecurityMessageProperty();
result.TransportToken = new SecurityTokenSpecification(token, policies);
result.ServiceSecurityContext = new ServiceSecurityContext(policies);
return result;
}
public override SecurityMessageProperty ProcessAuthentication(IHttpAuthenticationContext authenticationContext)
{
if (this.shouldValidateClientCertificate)
{
SecurityMessageProperty retValue;
X509Certificate2 certificate = null;
try
{
bool isCertificateValid;
certificate = authenticationContext.GetClientCertificate(out isCertificateValid);
Fx.Assert(!this.requireClientCertificate || certificate != null, "ClientCertificate must be present");
if (certificate != null)
{
if (!this.useCustomClientCertificateVerification)
{
Fx.Assert(isCertificateValid, "ClientCertificate must be valid");
}
WindowsIdentity identity = null;
string authType = base.GetAuthType(authenticationContext);
if (this.useHostedClientCertificateMapping)
{
identity = authenticationContext.LogonUserIdentity;
if (identity == null || !identity.IsAuthenticated)
{
identity = WindowsIdentity.GetAnonymous();
}
else
{
// it is not recommended to call identity.AuthenticationType as this is a privileged instruction.
// when the identity is cloned, it will be created with an authtype indicating WindowsIdentity from a cert.
identity = SecurityUtils.CloneWindowsIdentityIfNecessary(identity, SecurityUtils.AuthTypeCertMap);
authType = SecurityUtils.AuthTypeCertMap;
}
}
retValue = CreateSecurityProperty(certificate, identity, authType);
}
else if (this.AuthenticationScheme == AuthenticationSchemes.Anonymous)
{
return new SecurityMessageProperty();
}
else
{
return base.ProcessAuthentication(authenticationContext);
}
}
#pragma warning suppress 56500 // covered by FXCop
catch (Exception exception)
{
if (Fx.IsFatal(exception))
throw;
// Audit Authentication failure
if (AuditLevel.Failure == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure))
WriteAuditEvent(AuditLevel.Failure, (certificate != null) ? SecurityUtils.GetCertificateId(certificate) : String.Empty, exception);
throw;
}
// Audit Authentication success
if (AuditLevel.Success == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Success))
WriteAuditEvent(AuditLevel.Success, (certificate != null) ? SecurityUtils.GetCertificateId(certificate) : String.Empty, null);
return retValue;
}
else if (this.AuthenticationScheme == AuthenticationSchemes.Anonymous)
{
return new SecurityMessageProperty();
}
else
{
return base.ProcessAuthentication(authenticationContext);
}
}
public override SecurityMessageProperty ProcessAuthentication(HttpListenerContext listenerContext)
{
if (this.shouldValidateClientCertificate)
{
SecurityMessageProperty retValue;
X509Certificate2 certificateEx = null;
try
{
X509Certificate certificate = listenerContext.Request.GetClientCertificate();
Fx.Assert(!this.requireClientCertificate || certificate != null,
"HttpListenerRequest.ClientCertificate is not present");
if (certificate != null)
{
if (!useCustomClientCertificateVerification)
{
Fx.Assert(listenerContext.Request.ClientCertificateError == 0,
"HttpListenerRequest.ClientCertificate is not valid");
}
certificateEx = new X509Certificate2(certificate);
retValue = CreateSecurityProperty(certificateEx, null, string.Empty);
}
else if (this.AuthenticationScheme == AuthenticationSchemes.Anonymous)
{
return new SecurityMessageProperty();
}
else
{
return base.ProcessAuthentication(listenerContext);
}
}
#pragma warning suppress 56500 // covered by FXCop
catch (Exception exception)
{
if (Fx.IsFatal(exception))
throw;
// Audit Authentication failure
if (AuditLevel.Failure == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure))
WriteAuditEvent(AuditLevel.Failure, (certificateEx != null) ? SecurityUtils.GetCertificateId(certificateEx) : String.Empty, exception);
throw;
}
// Audit Authentication success
if (AuditLevel.Success == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Success))
WriteAuditEvent(AuditLevel.Success, (certificateEx != null) ? SecurityUtils.GetCertificateId(certificateEx) : String.Empty, null);
return retValue;
}
else if (this.AuthenticationScheme == AuthenticationSchemes.Anonymous)
{
return new SecurityMessageProperty();
}
else
{
return base.ProcessAuthentication(listenerContext);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability103",
Justification = "The exceptions are wrapped already.")]
public override HttpStatusCode ValidateAuthentication(IHttpAuthenticationContext authenticationContext)
{
HttpStatusCode result = base.ValidateAuthentication(authenticationContext);
if (result == HttpStatusCode.OK)
{
if (this.shouldValidateClientCertificate)
{
bool isValidCertificate;
X509Certificate2 clientCertificate = authenticationContext.GetClientCertificate(out isValidCertificate);
if (clientCertificate == null)
{
if (this.RequireClientCertificate)
{
if (DiagnosticUtility.ShouldTraceError)
{
TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.HttpsClientCertificateNotPresent, SR.GetString(SR.TraceCodeHttpsClientCertificateNotPresent),
authenticationContext.CreateTraceRecord(), this, null);
}
result = CertificateErrorStatusCode;
}
}
else if (!isValidCertificate && !this.useCustomClientCertificateVerification)
{
if (DiagnosticUtility.ShouldTraceError)
{
TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.HttpsClientCertificateInvalid, SR.GetString(SR.TraceCodeHttpsClientCertificateInvalid),
authenticationContext.CreateTraceRecord(), this, null);
}
result = CertificateErrorStatusCode;
}
// Audit Authentication failure
if (result != HttpStatusCode.OK && (AuditLevel.Failure == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure)))
{
string message = SR.GetString(SR.HttpAuthenticationFailed, this.AuthenticationScheme, result);
Exception exception = DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(message));
WriteAuditEvent(AuditLevel.Failure, (clientCertificate != null) ? SecurityUtils.GetCertificateId(clientCertificate) : String.Empty, exception);
}
}
}
return result;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability103",
Justification = "The exceptions are wrapped already.")]
public override HttpStatusCode ValidateAuthentication(HttpListenerContext listenerContext)
{
HttpStatusCode result = base.ValidateAuthentication(listenerContext);
if (result == HttpStatusCode.OK)
{
if (this.shouldValidateClientCertificate)
{
HttpListenerRequest request = listenerContext.Request;
X509Certificate2 certificateEx = request.GetClientCertificate();
if (certificateEx == null)
{
if (this.RequireClientCertificate)
{
if (DiagnosticUtility.ShouldTraceWarning)
{
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.HttpsClientCertificateNotPresent,
SR.GetString(SR.TraceCodeHttpsClientCertificateNotPresent),
new HttpListenerRequestTraceRecord(listenerContext.Request), this, null);
}
result = CertificateErrorStatusCode;
}
}
else if (request.ClientCertificateError != 0 && !useCustomClientCertificateVerification)
{
if (DiagnosticUtility.ShouldTraceWarning)
{
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.HttpsClientCertificateInvalid,
SR.GetString(SR.TraceCodeHttpsClientCertificateInvalid1, "0x" + (request.ClientCertificateError & 65535).ToString("X", CultureInfo.InvariantCulture)),
new HttpListenerRequestTraceRecord(listenerContext.Request), this, null);
}
result = CertificateErrorStatusCode;
}
// Audit Authentication failure
if (result != HttpStatusCode.OK && (AuditLevel.Failure == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure)))
{
string message = SR.GetString(SR.HttpAuthenticationFailed, this.AuthenticationScheme, result);
Exception exception = DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(message));
WriteAuditEvent(AuditLevel.Failure, (certificateEx != null) ? SecurityUtils.GetCertificateId(certificateEx) : String.Empty, exception);
}
}
}
return result;
}
private static bool ShouldValidateClientCertificate(bool requireClientCertificateValidation, BindingContext context)
{
if (requireClientCertificateValidation)
{
return true;
}
return EndpointSettings.GetValue<bool>(context, EndpointSettings.ValidateOptionalClientCertificates, false);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using TestLibrary;
using System.Globalization;
class StringBuilderCapacity
{
static int Main()
{
StringBuilderCapacity test = new StringBuilderCapacity();
TestFramework.BeginTestCase("StringBuilder.Capacity");
if (test.RunTests())
{
TestFramework.EndTestCase();
TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestFramework.EndTestCase();
TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool ret = true;
// Positive Tests
ret &= Test2();
ret &= Test3();
ret &= Test4();
ret &= Test5();
// Negative Tests
ret &= Test1();
ret &= Test6();
ret &= Test7();
return ret;
}
public bool Test1()
{
string id = "Scenario1";
bool result = true;
TestFramework.BeginScenario("Scenario 1: Setting Capacity to 0");
try
{
StringBuilder sb = new StringBuilder("Test");
sb.Capacity = 0;
string output = sb.ToString();
int cap = sb.Capacity;
result = false;
TestFramework.LogError("001", "Error in " + id + ", expected exception not thrown. Capacity: " + cap + ", string: " + output);
}
catch (Exception exc)
{
if (exc.GetType() != typeof(ArgumentOutOfRangeException))
{
result = false;
TestFramework.LogError("003", "Unexpected exception in " + id + ", expected type: " + typeof(ArgumentOutOfRangeException).ToString() + ", Actual exception: " + exc.ToString());
}
}
return result;
}
public bool Test2()
{
string id = "Scenario2";
bool result = true;
TestFramework.BeginScenario("Scenario 2: Setting capacity to current capacity");
try
{
StringBuilder sb = new StringBuilder("Test", 4);
sb.Capacity = 4;
string output = sb.ToString();
int cap = sb.Capacity;
if (output != "Test")
{
result = false;
TestFramework.LogError("004", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: Test");
}
if (cap != 4)
{
result = false;
TestFramework.LogError("005", "Error in " + id + ", unexpected capacity. Actual capacity " + cap + ", Expected: 4");
}
}
catch (Exception exc)
{
result = false;
TestFramework.LogError("006", "Unexpected exception in " + id + ", exception: " + exc.ToString());
}
return result;
}
public bool Test3()
{
string id = "Scenario3";
bool result = true;
TestFramework.BeginScenario("Scenario 3: Setting capacity to > length < capacity");
try
{
StringBuilder sb = new StringBuilder("Test", 10);
sb.Capacity = 8;
string output = sb.ToString();
int capacity = sb.Capacity;
if (output != "Test")
{
result = false;
TestFramework.LogError("007", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: Test");
}
if (capacity != 8)
{
result = false;
TestFramework.LogError("008", "Error in " + id + ", unexpected legnth. Actual capacity" + capacity + ", Expected: 8");
}
}
catch (Exception exc)
{
result = false;
TestFramework.LogError("009", "Unexpected exception in " + id + ", exception: " + exc.ToString());
}
return result;
}
public bool Test4()
{
string id = "Scenario4";
bool result = true;
TestFramework.BeginScenario("Scenario 4: Setting capacity to > capacity");
try
{
StringBuilder sb = new StringBuilder("Test", 10);
sb.Capacity = 12;
string output = sb.ToString();
int cap = sb.Capacity;
if (output != "Test")
{
result = false;
TestFramework.LogError("010", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: Test");
}
if (cap != 12)
{
result = false;
TestFramework.LogError("011", "Error in " + id + ", unexpected legnth. Actual capacity " + cap + ", Expected: 12");
}
}
catch (Exception exc)
{
result = false;
TestFramework.LogError("012", "Unexpected exception in " + id + ", exception: " + exc.ToString());
}
return result;
}
public bool Test5()
{
string id = "Scenario5";
bool result = true;
TestFramework.BeginScenario("Scenario 5: Setting capacity to something very large");
try
{
StringBuilder sb = new StringBuilder("Test");
sb.Capacity = 10004;
string output = sb.ToString();
int capacity = sb.Capacity;
if (output != "Test")
{
result = false;
TestFramework.LogError("013", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: Test");
}
if (capacity != 10004)
{
result = false;
TestFramework.LogError("014", "Error in " + id + ", unexpected legnth. Actual capacity " + capacity + ", Expected: 10004");
}
}
catch (Exception exc)
{
result = false;
TestFramework.LogError("015", "Unexpected exception in " + id + ", exception: " + exc.ToString());
}
return result;
}
public bool Test6()
{
string id = "Scenario6";
bool result = true;
TestFramework.BeginScenario("Scenario 6: Setting Capacity to > max capacity");
try
{
StringBuilder sb = new StringBuilder(4, 10);
sb.Append("Test");
sb.Capacity = 12;
string output = sb.ToString();
result = false;
TestFramework.LogError("016", "Error in " + id + ", Expected exception not thrown. No exception. Actual string " + output + ", Expected: " + typeof(ArgumentOutOfRangeException).ToString());
}
catch (Exception exc)
{
if (exc.GetType() != typeof(ArgumentOutOfRangeException))
{
result = false;
TestFramework.LogError("017", "Unexpected exception in " + id + ", expected type: " + typeof(ArgumentOutOfRangeException).ToString() + ", Actual exception: " + exc.ToString());
}
}
return result;
}
public bool Test7()
{
string id = "Scenario7";
bool result = true;
TestFramework.BeginScenario("Scenario 7: Setting capacity to < 0");
try
{
StringBuilder sb = new StringBuilder(4, 10);
sb.Append("Test");
sb.Capacity = -1;
string output = sb.ToString();
result = false;
TestFramework.LogError("018", "Error in " + id + ", Expected exception not thrown. No exception. Actual string " + output + ", Expected: " + typeof(ArgumentOutOfRangeException).ToString());
}
catch (Exception exc)
{
if (exc.GetType() != typeof(ArgumentOutOfRangeException))
{
result = false;
TestFramework.LogError("018", "Unexpected exception in " + id + ", expected type: " + typeof(ArgumentOutOfRangeException).ToString() + ", Actual exception: " + exc.ToString());
}
}
return result;
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetActiveJobsSpectraS3Request : Ds3Request
{
private bool? _aggregating;
public bool? Aggregating
{
get { return _aggregating; }
set { WithAggregating(value); }
}
private string _bucketId;
public string BucketId
{
get { return _bucketId; }
set { WithBucketId(value); }
}
private JobChunkClientProcessingOrderGuarantee? _chunkClientProcessingOrderGuarantee;
public JobChunkClientProcessingOrderGuarantee? ChunkClientProcessingOrderGuarantee
{
get { return _chunkClientProcessingOrderGuarantee; }
set { WithChunkClientProcessingOrderGuarantee(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private string _name;
public string Name
{
get { return _name; }
set { WithName(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private Priority? _priority;
public Priority? Priority
{
get { return _priority; }
set { WithPriority(value); }
}
private DateTime? _rechunked;
public DateTime? Rechunked
{
get { return _rechunked; }
set { WithRechunked(value); }
}
private JobRequestType? _requestType;
public JobRequestType? RequestType
{
get { return _requestType; }
set { WithRequestType(value); }
}
private bool? _truncated;
public bool? Truncated
{
get { return _truncated; }
set { WithTruncated(value); }
}
private string _userId;
public string UserId
{
get { return _userId; }
set { WithUserId(value); }
}
public GetActiveJobsSpectraS3Request WithAggregating(bool? aggregating)
{
this._aggregating = aggregating;
if (aggregating != null)
{
this.QueryParams.Add("aggregating", aggregating.ToString());
}
else
{
this.QueryParams.Remove("aggregating");
}
return this;
}
public GetActiveJobsSpectraS3Request WithBucketId(Guid? bucketId)
{
this._bucketId = bucketId.ToString();
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId.ToString());
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetActiveJobsSpectraS3Request WithBucketId(string bucketId)
{
this._bucketId = bucketId;
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId);
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetActiveJobsSpectraS3Request WithChunkClientProcessingOrderGuarantee(JobChunkClientProcessingOrderGuarantee? chunkClientProcessingOrderGuarantee)
{
this._chunkClientProcessingOrderGuarantee = chunkClientProcessingOrderGuarantee;
if (chunkClientProcessingOrderGuarantee != null)
{
this.QueryParams.Add("chunk_client_processing_order_guarantee", chunkClientProcessingOrderGuarantee.ToString());
}
else
{
this.QueryParams.Remove("chunk_client_processing_order_guarantee");
}
return this;
}
public GetActiveJobsSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetActiveJobsSpectraS3Request WithName(string name)
{
this._name = name;
if (name != null)
{
this.QueryParams.Add("name", name);
}
else
{
this.QueryParams.Remove("name");
}
return this;
}
public GetActiveJobsSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetActiveJobsSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetActiveJobsSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetActiveJobsSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetActiveJobsSpectraS3Request WithPriority(Priority? priority)
{
this._priority = priority;
if (priority != null)
{
this.QueryParams.Add("priority", priority.ToString());
}
else
{
this.QueryParams.Remove("priority");
}
return this;
}
public GetActiveJobsSpectraS3Request WithRechunked(DateTime? rechunked)
{
this._rechunked = rechunked;
if (rechunked != null)
{
this.QueryParams.Add("rechunked", rechunked.ToString());
}
else
{
this.QueryParams.Remove("rechunked");
}
return this;
}
public GetActiveJobsSpectraS3Request WithRequestType(JobRequestType? requestType)
{
this._requestType = requestType;
if (requestType != null)
{
this.QueryParams.Add("request_type", requestType.ToString());
}
else
{
this.QueryParams.Remove("request_type");
}
return this;
}
public GetActiveJobsSpectraS3Request WithTruncated(bool? truncated)
{
this._truncated = truncated;
if (truncated != null)
{
this.QueryParams.Add("truncated", truncated.ToString());
}
else
{
this.QueryParams.Remove("truncated");
}
return this;
}
public GetActiveJobsSpectraS3Request WithUserId(Guid? userId)
{
this._userId = userId.ToString();
if (userId != null)
{
this.QueryParams.Add("user_id", userId.ToString());
}
else
{
this.QueryParams.Remove("user_id");
}
return this;
}
public GetActiveJobsSpectraS3Request WithUserId(string userId)
{
this._userId = userId;
if (userId != null)
{
this.QueryParams.Add("user_id", userId);
}
else
{
this.QueryParams.Remove("user_id");
}
return this;
}
public GetActiveJobsSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/active_job";
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace yycms.admin.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Types;
#if FEATURE_NUMERICS
using System.Numerics;
#else
using Microsoft.Scripting.Math;
using Complex = Microsoft.Scripting.Math.Complex64;
#endif
namespace IronPython.Runtime.Operations {
/// <summary>
/// Contains Python extension methods that are added to object
/// </summary>
public static class ObjectOps {
/// <summary> Types for which the pickle module has built-in support (from PEP 307 case 2) </summary>
[MultiRuntimeAware]
private static Dictionary<PythonType, object> _nativelyPickleableTypes;
/// <summary>
/// __class__, a custom slot so that it works for both objects and types.
/// </summary>
[SlotField]
public static PythonTypeSlot __class__ = new PythonTypeTypeSlot();
/// <summary>
/// Removes an attribute from the provided member
/// </summary>
public static void __delattr__(CodeContext/*!*/ context, object self, string name) {
if (self is PythonType) {
throw PythonOps.TypeError("can't apply this __delattr__ to type object");
}
PythonOps.ObjectDeleteAttribute(context, self, name);
}
/// <summary>
/// Returns the hash code of the given object
/// </summary>
public static int __hash__(object self) {
if (self == null) return NoneTypeOps.NoneHashCode;
return self.GetHashCode();
}
/// <summary>
/// Gets the specified attribute from the object without running any custom lookup behavior
/// (__getattr__ and __getattribute__)
/// </summary>
public static object __getattribute__(CodeContext/*!*/ context, object self, string name) {
return PythonOps.ObjectGetAttribute(context, self, name);
}
/// <summary>
/// Initializes the object. The base class does nothing.
/// </summary>
public static void __init__(CodeContext/*!*/ context, object self) {
}
/// <summary>
/// Initializes the object. The base class does nothing.
/// </summary>
public static void __init__(CodeContext/*!*/ context, object self, [NotNull]params object[] args\u00F8) {
InstanceOps.CheckInitArgs(context, null, args\u00F8, self);
}
/// <summary>
/// Initializes the object. The base class does nothing.
/// </summary>
public static void __init__(CodeContext/*!*/ context, object self, [ParamDictionary]IDictionary<object, object> kwargs, params object[] args\u00F8) {
InstanceOps.CheckInitArgs(context, kwargs, args\u00F8, self);
}
/// <summary>
/// Creates a new instance of the type
/// </summary>
[StaticExtensionMethod]
public static object __new__(CodeContext/*!*/ context, PythonType cls) {
if (cls == null) {
throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(cls)));
}
return cls.CreateInstance(context);
}
/// <summary>
/// Creates a new instance of the type
/// </summary>
[StaticExtensionMethod]
public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNull]params object[] args\u00F8) {
if (cls == null) {
throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(cls)));
}
InstanceOps.CheckNewArgs(context, null, args\u00F8, cls);
return cls.CreateInstance(context);
}
/// <summary>
/// Creates a new instance of the type
/// </summary>
[StaticExtensionMethod]
public static object __new__(CodeContext/*!*/ context, PythonType cls, [ParamDictionary]IDictionary<object, object> kwargs\u00F8, [NotNull]params object[] args\u00F8) {
if (cls == null) {
throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(cls)));
}
InstanceOps.CheckNewArgs(context, kwargs\u00F8, args\u00F8, cls);
return cls.CreateInstance(context);
}
/// <summary>
/// Runs the pickle protocol
/// </summary>
public static object __reduce__(CodeContext/*!*/ context, object self) {
return __reduce_ex__(context, self, 0);
}
/// <summary>
/// Runs the pickle protocol
/// </summary>
public static object __reduce_ex__(CodeContext/*!*/ context, object self) {
return __reduce_ex__(context, self, 0);
}
/// <summary>
/// Runs the pickle protocol
/// </summary>
public static object __reduce_ex__(CodeContext/*!*/ context, object self, object protocol) {
object objectReduce = PythonOps.GetBoundAttr(context, DynamicHelpers.GetPythonTypeFromType(typeof(object)), "__reduce__");
object myReduce;
if (PythonOps.TryGetBoundAttr(context, DynamicHelpers.GetPythonType(self), "__reduce__", out myReduce)) {
if (!PythonOps.IsRetBool(myReduce, objectReduce)) {
// A derived class overrode __reduce__ but not __reduce_ex__, so call
// specialized __reduce__ instead of generic __reduce_ex__.
// (see the "The __reduce_ex__ API" section of PEP 307)
return PythonOps.CallWithContext(context, myReduce, self);
}
}
if (PythonContext.GetContext(context).ConvertToInt32(protocol) < 2) {
return ReduceProtocol0(context, self);
} else {
return ReduceProtocol2(context, self);
}
}
/// <summary>
/// Returns the code representation of the object. The default implementation returns
/// a string which consists of the type and a unique numerical identifier.
/// </summary>
public static string __repr__(object self) {
return String.Format("<{0} object at {1}>",
DynamicHelpers.GetPythonType(self).Name,
PythonOps.HexId(self));
}
/// <summary>
/// Sets an attribute on the object without running any custom object defined behavior.
/// </summary>
public static void __setattr__(CodeContext/*!*/ context, object self, string name, object value) {
if (self is PythonType) {
throw PythonOps.TypeError("can't apply this __setattr__ to type object");
}
PythonOps.ObjectSetAttribute(context, self, name, value);
}
private static int AdjustPointerSize(int size) {
if (IntPtr.Size == 4) {
return size;
}
return size * 2;
}
/// <summary>
/// Returns the number of bytes of memory required to allocate the object.
/// </summary>
public static int __sizeof__(object self) {
IPythonObject ipo = self as IPythonObject;
int res = AdjustPointerSize(8); // vtable, sync blk
if (ipo != null) {
res += AdjustPointerSize(12); // class, dict, slots
}
Type t = DynamicHelpers.GetPythonType(self).FinalSystemType;
res += GetTypeSize(t);
return res;
}
private static int GetTypeSize(Type t) {
FieldInfo[] fields = t.GetFields(System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);
int res = 0;
foreach (FieldInfo fi in fields) {
if (fi.FieldType.IsClass() || fi.FieldType.IsInterface()) {
res += AdjustPointerSize(4);
} else if (fi.FieldType.IsPrimitive()) {
return System.Runtime.InteropServices.Marshal.SizeOf(fi.FieldType);
} else {
res += GetTypeSize(fi.FieldType);
}
}
return res;
}
/// <summary>
/// Returns a friendly string representation of the object.
/// </summary>
public static string __str__(CodeContext/*!*/ context, object o) {
return PythonOps.Repr(context, o);
}
public static NotImplementedType __subclasshook__(params object[] args) {
return NotImplementedType.Value;
}
public static string __format__(CodeContext/*!*/ context, object self, [NotNull]string/*!*/ formatSpec) {
string text = PythonOps.ToString(context, self);
StringFormatSpec spec = StringFormatSpec.FromString(formatSpec);
if (spec.Type != null && spec.Type != 's') {
throw PythonOps.ValueError("Unknown format code '{0}' for object of type 'str'", spec.Type.Value.ToString());
} else if (spec.Sign != null) {
throw PythonOps.ValueError("Sign not allowed in string format specifier");
} else if (spec.Alignment == '=') {
throw PythonOps.ValueError("'=' alignment not allowed in string format specifier");
} else if (spec.ThousandsComma) {
throw PythonOps.ValueError("Cannot specify ',' with 's'.");
}
// apply precision to shorten the string first
if (spec.Precision != null) {
int precision = spec.Precision.Value;
if (text.Length > precision) {
text = text.Substring(0, precision);
}
}
// then apply the minimum width & padding
text = spec.AlignText(text);
// finally return the text
return text;
}
#region Pickle helpers
// This is a dynamically-initialized property rather than a statically-initialized field
// to avoid a bootstrapping dependency loop
private static Dictionary<PythonType, object> NativelyPickleableTypes {
get {
if (_nativelyPickleableTypes == null) {
Dictionary<PythonType, object> typeDict = new Dictionary<PythonType, object>();
typeDict.Add(TypeCache.Null, null);
typeDict.Add(DynamicHelpers.GetPythonTypeFromType(typeof(bool)), null);
typeDict.Add(DynamicHelpers.GetPythonTypeFromType(typeof(int)), null);
typeDict.Add(DynamicHelpers.GetPythonTypeFromType(typeof(double)), null);
typeDict.Add(DynamicHelpers.GetPythonTypeFromType(typeof(Complex)), null);
typeDict.Add(DynamicHelpers.GetPythonTypeFromType(typeof(string)), null);
typeDict.Add(DynamicHelpers.GetPythonTypeFromType(typeof(PythonTuple)), null);
typeDict.Add(DynamicHelpers.GetPythonTypeFromType(typeof(List)), null);
typeDict.Add(DynamicHelpers.GetPythonTypeFromType(typeof(PythonDictionary)), null);
typeDict.Add(DynamicHelpers.GetPythonTypeFromType(typeof(PythonFunction)), null);
typeDict.Add(DynamicHelpers.GetPythonTypeFromType(typeof(BuiltinFunction)), null);
// type dict needs to be ensured to be fully initialized before assigning back
Thread.MemoryBarrier();
_nativelyPickleableTypes = typeDict;
}
return _nativelyPickleableTypes;
}
}
/// <summary>
/// Return a dict that maps slot names to slot values, but only include slots that have been assigned to.
/// Looks up slots in base types as well as the current type.
///
/// Sort-of Python equivalent (doesn't look up base slots, while the real code does):
/// return dict([(slot, getattr(self, slot)) for slot in type(self).__slots__ if hasattr(self, slot)])
///
/// Return null if the object has no __slots__, or empty dict if it has __slots__ but none are initialized.
/// </summary>
private static PythonDictionary GetInitializedSlotValues(object obj) {
PythonDictionary initializedSlotValues = new PythonDictionary();
IList<PythonType> mro = DynamicHelpers.GetPythonType(obj).ResolutionOrder;
object slots;
object slotValue;
foreach (object type in mro) {
if (PythonOps.TryGetBoundAttr(type, "__slots__", out slots)) {
List<string> slotNames = PythonType.SlotsToList(slots);
foreach (string slotName in slotNames) {
if (slotName == "__dict__") continue;
// don't reassign same-named slots from types earlier in the MRO
if (initializedSlotValues.__contains__(slotName)) continue;
if (PythonOps.TryGetBoundAttr(obj, slotName, out slotValue)) {
initializedSlotValues[slotName] = slotValue;
}
}
}
}
if (initializedSlotValues.Count == 0) return null;
return initializedSlotValues;
}
/// <summary>
/// Implements the default __reduce_ex__ method as specified by PEP 307 case 2 (new-style instance, protocol 0 or 1)
/// </summary>
internal static PythonTuple ReduceProtocol0(CodeContext/*!*/ context, object self) {
// CPython implements this in copyreg._reduce_ex
PythonType myType = DynamicHelpers.GetPythonType(self); // PEP 307 calls this "D"
ThrowIfNativelyPickable(myType);
object getState;
bool hasGetState = PythonOps.TryGetBoundAttr(context, self, "__getstate__", out getState);
object slots;
if (PythonOps.TryGetBoundAttr(context, myType, "__slots__", out slots) && PythonOps.Length(slots) > 0 && !hasGetState) {
// ??? does this work with superclass slots?
throw PythonOps.TypeError("a class that defines __slots__ without defining __getstate__ cannot be pickled with protocols 0 or 1");
}
PythonType closestNonPythonBase = FindClosestNonPythonBase(myType); // PEP 307 calls this "B"
object func = PythonContext.GetContext(context).PythonReconstructor;
object funcArgs = PythonTuple.MakeTuple(
myType,
closestNonPythonBase,
TypeCache.Object == closestNonPythonBase ? null : PythonCalls.Call(context, closestNonPythonBase, self)
);
object state;
if (hasGetState) {
state = PythonOps.CallWithContext(context, getState);
} else {
IPythonObject ipo = self as IPythonObject;
if (ipo != null) {
state = ipo.Dict;
} else if (!PythonOps.TryGetBoundAttr(context, self, "__dict__", out state)) {
state = null;
}
}
if (!PythonOps.IsTrue(state)) state = null;
return PythonTuple.MakeTuple(func, funcArgs, state);
}
private static void ThrowIfNativelyPickable(PythonType type) {
if (NativelyPickleableTypes.ContainsKey(type)) {
throw PythonOps.TypeError("can't pickle {0} objects", type.Name);
}
}
/// <summary>
/// Returns the closest base class (in terms of MRO) that isn't defined in Python code
/// </summary>
private static PythonType FindClosestNonPythonBase(PythonType type) {
foreach (PythonType pythonBase in type.ResolutionOrder) {
if (pythonBase.IsSystemType) {
return pythonBase;
}
}
throw PythonOps.TypeError("can't pickle {0} instance: no non-Python bases found", type.Name);
}
/// <summary>
/// Implements the default __reduce_ex__ method as specified by PEP 307 case 3 (new-style instance, protocol 2)
/// </summary>
private static PythonTuple ReduceProtocol2(CodeContext/*!*/ context, object self) {
PythonType myType = DynamicHelpers.GetPythonType(self);
object func, state, listIterator, dictIterator;
object[] funcArgs;
func = PythonContext.GetContext(context).NewObject;
object getNewArgsCallable;
if (PythonOps.TryGetBoundAttr(context, myType, "__getnewargs__", out getNewArgsCallable)) {
// TypeError will bubble up if __getnewargs__ isn't callable
PythonTuple newArgs = PythonOps.CallWithContext(context, getNewArgsCallable, self) as PythonTuple;
if (newArgs == null) {
throw PythonOps.TypeError("__getnewargs__ should return a tuple");
}
funcArgs = new object[1 + newArgs.Count];
funcArgs[0] = myType;
for (int i = 0; i < newArgs.Count; i++) funcArgs[i + 1] = newArgs[i];
} else {
funcArgs = new object[] { myType };
}
if (!PythonTypeOps.TryInvokeUnaryOperator(context,
self,
"__getstate__",
out state)) {
object dict;
IPythonObject ipo = self as IPythonObject;
if (ipo != null) {
dict = ipo.Dict;
} else if (!PythonOps.TryGetBoundAttr(context, self, "__dict__", out dict)) {
dict = null;
}
PythonDictionary initializedSlotValues = GetInitializedSlotValues(self);
if (initializedSlotValues != null && initializedSlotValues.Count == 0) {
initializedSlotValues = null;
}
if (dict == null && initializedSlotValues == null) state = null;
else if (dict != null && initializedSlotValues == null) state = dict;
else if (dict != null && initializedSlotValues != null) state = PythonTuple.MakeTuple(dict, initializedSlotValues);
else /*dict == null && initializedSlotValues != null*/ state = PythonTuple.MakeTuple(null, initializedSlotValues);
}
listIterator = null;
if (self is List) {
listIterator = PythonOps.GetEnumerator(self);
}
dictIterator = null;
if (self is PythonDictionary || self is PythonDictionary) {
dictIterator = PythonOps.Invoke(context, self, "iteritems", ArrayUtils.EmptyObjects);
}
return PythonTuple.MakeTuple(func, PythonTuple.MakeTuple(funcArgs), state, listIterator, dictIterator);
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Game.Scoring;
using osuTK;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Framework.Allocation;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
#nullable enable
namespace osu.Game.Online.Leaderboards
{
public class LeaderboardScoreTooltip : VisibilityContainer, ITooltip<ScoreInfo>
{
private OsuSpriteText timestampLabel = null!;
private FillFlowContainer<HitResultCell> topScoreStatistics = null!;
private FillFlowContainer<HitResultCell> bottomScoreStatistics = null!;
private FillFlowContainer<ModCell> modStatistics = null!;
public LeaderboardScoreTooltip()
{
AutoSizeAxes = Axes.Both;
AutoSizeDuration = 200;
AutoSizeEasing = Easing.OutQuint;
Masking = true;
CornerRadius = 5;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0.9f,
Colour = colours.Gray3,
},
new FillFlowContainer
{
Margin = new MarginPadding(5),
Spacing = new Vector2(10),
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
// Info row
timestampLabel = new OsuSpriteText
{
Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold),
},
// Mods row
modStatistics = new FillFlowContainer<ModCell>
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Spacing = new Vector2(5, 0),
},
new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
// Actual stats rows
topScoreStatistics = new FillFlowContainer<HitResultCell>
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(10, 0),
},
bottomScoreStatistics = new FillFlowContainer<HitResultCell>
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(10, 0),
},
}
},
}
}
};
}
private ScoreInfo? displayedScore;
public void SetContent(ScoreInfo score)
{
if (displayedScore?.Equals(score) == true)
return;
displayedScore = score;
timestampLabel.Text = $"Played on {score.Date.ToLocalTime():d MMMM yyyy HH:mm}";
modStatistics.Clear();
topScoreStatistics.Clear();
bottomScoreStatistics.Clear();
foreach (var mod in score.Mods)
{
modStatistics.Add(new ModCell(mod));
}
foreach (var result in score.GetStatisticsForDisplay())
{
if (result.Result > HitResult.Perfect)
bottomScoreStatistics.Add(new HitResultCell(result));
else
topScoreStatistics.Add(new HitResultCell(result));
}
}
protected override void PopIn() => this.FadeIn(20, Easing.OutQuint);
protected override void PopOut() => this.FadeOut(80, Easing.OutQuint);
public void Move(Vector2 pos) => Position = pos;
private class HitResultCell : CompositeDrawable
{
private readonly string displayName;
private readonly HitResult result;
private readonly int count;
public HitResultCell(HitResultDisplayStatistic stat)
{
AutoSizeAxes = Axes.Both;
displayName = stat.DisplayName;
result = stat.Result;
count = stat.Count;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
InternalChild = new FillFlowContainer
{
Height = 12,
AutoSizeAxes = Axes.X,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(5f, 0f),
Children = new Drawable[]
{
new OsuSpriteText
{
Font = OsuFont.Torus.With(size: 12, weight: FontWeight.SemiBold),
Text = displayName.ToUpperInvariant(),
Colour = colours.ForHitResult(result),
},
new OsuSpriteText
{
Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold),
Text = count.ToString(),
},
}
};
}
}
private class ModCell : CompositeDrawable
{
private readonly Mod mod;
public ModCell(Mod mod)
{
AutoSizeAxes = Axes.Both;
this.mod = mod;
}
[BackgroundDependencyLoader]
private void load()
{
FillFlowContainer container;
InternalChild = container = new FillFlowContainer
{
Height = 15,
AutoSizeAxes = Axes.X,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(2f, 0f),
Children = new Drawable[]
{
new ModIcon(mod, showTooltip: false).With(icon =>
{
icon.Origin = Anchor.CentreLeft;
icon.Anchor = Anchor.CentreLeft;
icon.Scale = new Vector2(15f / icon.Height);
}),
}
};
string description = mod.SettingDescription;
if (!string.IsNullOrEmpty(description))
{
container.Add(new OsuSpriteText
{
RelativeSizeAxes = Axes.Y,
Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold),
Text = mod.SettingDescription,
Origin = Anchor.CentreLeft,
Anchor = Anchor.CentreLeft,
Margin = new MarginPadding { Top = 1 },
});
}
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Monitoring.Autoscale;
using Microsoft.WindowsAzure.Management.Monitoring.Autoscale.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.WindowsAzure.Management.Monitoring.Autoscale
{
/// <summary>
/// Operations for managing the autoscale settings.
/// </summary>
internal partial class SettingOperations : IServiceOperations<AutoscaleClient>, Microsoft.WindowsAzure.Management.Monitoring.Autoscale.ISettingOperations
{
/// <summary>
/// Initializes a new instance of the SettingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SettingOperations(AutoscaleClient client)
{
this._client = client;
}
private AutoscaleClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Monitoring.Autoscale.AutoscaleClient.
/// </summary>
public AutoscaleClient Client
{
get { return this._client; }
}
/// <param name='resourceId'>
/// Required. The resource ID.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> CreateOrUpdateAsync(string resourceId, AutoscaleSettingCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceId == null)
{
throw new ArgumentNullException("resourceId");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceId", resourceId);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/autoscalesettings?";
url = url + "resourceId=" + Uri.EscapeDataString(resourceId.Trim());
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2013-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject autoscaleSettingCreateOrUpdateParametersValue = new JObject();
requestDoc = autoscaleSettingCreateOrUpdateParametersValue;
if (parameters.Setting != null)
{
if (parameters.Setting.Profiles != null)
{
if (parameters.Setting.Profiles is ILazyCollection == false || ((ILazyCollection)parameters.Setting.Profiles).IsInitialized)
{
JArray profilesArray = new JArray();
foreach (AutoscaleProfile profilesItem in parameters.Setting.Profiles)
{
JObject autoscaleProfileValue = new JObject();
profilesArray.Add(autoscaleProfileValue);
if (profilesItem.Name != null)
{
autoscaleProfileValue["Name"] = profilesItem.Name;
}
if (profilesItem.Capacity != null)
{
JObject capacityValue = new JObject();
autoscaleProfileValue["Capacity"] = capacityValue;
if (profilesItem.Capacity.Minimum != null)
{
capacityValue["Minimum"] = profilesItem.Capacity.Minimum;
}
if (profilesItem.Capacity.Maximum != null)
{
capacityValue["Maximum"] = profilesItem.Capacity.Maximum;
}
if (profilesItem.Capacity.Default != null)
{
capacityValue["Default"] = profilesItem.Capacity.Default;
}
}
if (profilesItem.Rules != null)
{
if (profilesItem.Rules is ILazyCollection == false || ((ILazyCollection)profilesItem.Rules).IsInitialized)
{
JArray rulesArray = new JArray();
foreach (ScaleRule rulesItem in profilesItem.Rules)
{
JObject scaleRuleValue = new JObject();
rulesArray.Add(scaleRuleValue);
if (rulesItem.MetricTrigger != null)
{
JObject metricTriggerValue = new JObject();
scaleRuleValue["MetricTrigger"] = metricTriggerValue;
if (rulesItem.MetricTrigger.MetricName != null)
{
metricTriggerValue["MetricName"] = rulesItem.MetricTrigger.MetricName;
}
if (rulesItem.MetricTrigger.MetricNamespace != null)
{
metricTriggerValue["MetricNamespace"] = rulesItem.MetricTrigger.MetricNamespace;
}
if (rulesItem.MetricTrigger.MetricSource != null)
{
metricTriggerValue["MetricSource"] = rulesItem.MetricTrigger.MetricSource;
}
metricTriggerValue["TimeGrain"] = TypeConversion.To8601String(rulesItem.MetricTrigger.TimeGrain);
metricTriggerValue["Statistic"] = rulesItem.MetricTrigger.Statistic.ToString();
metricTriggerValue["TimeWindow"] = TypeConversion.To8601String(rulesItem.MetricTrigger.TimeWindow);
metricTriggerValue["TimeAggregation"] = rulesItem.MetricTrigger.TimeAggregation.ToString();
metricTriggerValue["Operator"] = rulesItem.MetricTrigger.Operator.ToString();
metricTriggerValue["Threshold"] = rulesItem.MetricTrigger.Threshold;
}
if (rulesItem.ScaleAction != null)
{
JObject scaleActionValue = new JObject();
scaleRuleValue["ScaleAction"] = scaleActionValue;
scaleActionValue["Direction"] = rulesItem.ScaleAction.Direction.ToString();
scaleActionValue["Type"] = rulesItem.ScaleAction.Type.ToString();
if (rulesItem.ScaleAction.Value != null)
{
scaleActionValue["Value"] = rulesItem.ScaleAction.Value;
}
scaleActionValue["Cooldown"] = TypeConversion.To8601String(rulesItem.ScaleAction.Cooldown);
}
}
autoscaleProfileValue["Rules"] = rulesArray;
}
}
if (profilesItem.FixedDate != null)
{
JObject fixedDateValue = new JObject();
autoscaleProfileValue["FixedDate"] = fixedDateValue;
if (profilesItem.FixedDate.TimeZone != null)
{
fixedDateValue["TimeZone"] = profilesItem.FixedDate.TimeZone;
}
fixedDateValue["Start"] = profilesItem.FixedDate.Start;
fixedDateValue["End"] = profilesItem.FixedDate.End;
}
if (profilesItem.Recurrence != null)
{
JObject recurrenceValue = new JObject();
autoscaleProfileValue["Recurrence"] = recurrenceValue;
recurrenceValue["Frequency"] = profilesItem.Recurrence.Frequency.ToString();
if (profilesItem.Recurrence.Schedule != null)
{
JObject scheduleValue = new JObject();
recurrenceValue["Schedule"] = scheduleValue;
if (profilesItem.Recurrence.Schedule.TimeZone != null)
{
scheduleValue["TimeZone"] = profilesItem.Recurrence.Schedule.TimeZone;
}
if (profilesItem.Recurrence.Schedule.Days != null)
{
if (profilesItem.Recurrence.Schedule.Days is ILazyCollection == false || ((ILazyCollection)profilesItem.Recurrence.Schedule.Days).IsInitialized)
{
JArray daysArray = new JArray();
foreach (string daysItem in profilesItem.Recurrence.Schedule.Days)
{
daysArray.Add(daysItem);
}
scheduleValue["Days"] = daysArray;
}
}
if (profilesItem.Recurrence.Schedule.Hours != null)
{
if (profilesItem.Recurrence.Schedule.Hours is ILazyCollection == false || ((ILazyCollection)profilesItem.Recurrence.Schedule.Hours).IsInitialized)
{
JArray hoursArray = new JArray();
foreach (int hoursItem in profilesItem.Recurrence.Schedule.Hours)
{
hoursArray.Add(hoursItem);
}
scheduleValue["Hours"] = hoursArray;
}
}
if (profilesItem.Recurrence.Schedule.Minutes != null)
{
if (profilesItem.Recurrence.Schedule.Minutes is ILazyCollection == false || ((ILazyCollection)profilesItem.Recurrence.Schedule.Minutes).IsInitialized)
{
JArray minutesArray = new JArray();
foreach (int minutesItem in profilesItem.Recurrence.Schedule.Minutes)
{
minutesArray.Add(minutesItem);
}
scheduleValue["Minutes"] = minutesArray;
}
}
}
}
}
autoscaleSettingCreateOrUpdateParametersValue["Profiles"] = profilesArray;
}
}
autoscaleSettingCreateOrUpdateParametersValue["Enabled"] = parameters.Setting.Enabled;
}
requestContent = requestDoc.ToString(Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <param name='resourceId'>
/// Required. The resource ID.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> DeleteAsync(string resourceId, CancellationToken cancellationToken)
{
// Validate
if (resourceId == null)
{
throw new ArgumentNullException("resourceId");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceId", resourceId);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/autoscalesettings?";
url = url + "resourceId=" + Uri.EscapeDataString(resourceId.Trim());
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2013-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <param name='resourceId'>
/// Required. The resource ID.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Monitoring.Autoscale.Models.AutoscaleSettingGetResponse> GetAsync(string resourceId, CancellationToken cancellationToken)
{
// Validate
if (resourceId == null)
{
throw new ArgumentNullException("resourceId");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceId", resourceId);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/autoscalesettings?";
url = url + "resourceId=" + Uri.EscapeDataString(resourceId.Trim());
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2013-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AutoscaleSettingGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AutoscaleSettingGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
AutoscaleSetting settingInstance = new AutoscaleSetting();
result.Setting = settingInstance;
JToken profilesArray = responseDoc["Profiles"];
if (profilesArray != null && profilesArray.Type != JTokenType.Null)
{
foreach (JToken profilesValue in ((JArray)profilesArray))
{
AutoscaleProfile autoscaleProfileInstance = new AutoscaleProfile();
settingInstance.Profiles.Add(autoscaleProfileInstance);
JToken nameValue = profilesValue["Name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
autoscaleProfileInstance.Name = nameInstance;
}
JToken capacityValue = profilesValue["Capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
ScaleCapacity capacityInstance = new ScaleCapacity();
autoscaleProfileInstance.Capacity = capacityInstance;
JToken minimumValue = capacityValue["Minimum"];
if (minimumValue != null && minimumValue.Type != JTokenType.Null)
{
string minimumInstance = ((string)minimumValue);
capacityInstance.Minimum = minimumInstance;
}
JToken maximumValue = capacityValue["Maximum"];
if (maximumValue != null && maximumValue.Type != JTokenType.Null)
{
string maximumInstance = ((string)maximumValue);
capacityInstance.Maximum = maximumInstance;
}
JToken defaultValue = capacityValue["Default"];
if (defaultValue != null && defaultValue.Type != JTokenType.Null)
{
string defaultInstance = ((string)defaultValue);
capacityInstance.Default = defaultInstance;
}
}
JToken rulesArray = profilesValue["Rules"];
if (rulesArray != null && rulesArray.Type != JTokenType.Null)
{
foreach (JToken rulesValue in ((JArray)rulesArray))
{
ScaleRule scaleRuleInstance = new ScaleRule();
autoscaleProfileInstance.Rules.Add(scaleRuleInstance);
JToken metricTriggerValue = rulesValue["MetricTrigger"];
if (metricTriggerValue != null && metricTriggerValue.Type != JTokenType.Null)
{
MetricTrigger metricTriggerInstance = new MetricTrigger();
scaleRuleInstance.MetricTrigger = metricTriggerInstance;
JToken metricNameValue = metricTriggerValue["MetricName"];
if (metricNameValue != null && metricNameValue.Type != JTokenType.Null)
{
string metricNameInstance = ((string)metricNameValue);
metricTriggerInstance.MetricName = metricNameInstance;
}
JToken metricNamespaceValue = metricTriggerValue["MetricNamespace"];
if (metricNamespaceValue != null && metricNamespaceValue.Type != JTokenType.Null)
{
string metricNamespaceInstance = ((string)metricNamespaceValue);
metricTriggerInstance.MetricNamespace = metricNamespaceInstance;
}
JToken metricSourceValue = metricTriggerValue["MetricSource"];
if (metricSourceValue != null && metricSourceValue.Type != JTokenType.Null)
{
string metricSourceInstance = ((string)metricSourceValue);
metricTriggerInstance.MetricSource = metricSourceInstance;
}
JToken timeGrainValue = metricTriggerValue["TimeGrain"];
if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
{
TimeSpan timeGrainInstance = TypeConversion.From8601TimeSpan(((string)timeGrainValue));
metricTriggerInstance.TimeGrain = timeGrainInstance;
}
JToken statisticValue = metricTriggerValue["Statistic"];
if (statisticValue != null && statisticValue.Type != JTokenType.Null)
{
MetricStatisticType statisticInstance = ((MetricStatisticType)Enum.Parse(typeof(MetricStatisticType), ((string)statisticValue), true));
metricTriggerInstance.Statistic = statisticInstance;
}
JToken timeWindowValue = metricTriggerValue["TimeWindow"];
if (timeWindowValue != null && timeWindowValue.Type != JTokenType.Null)
{
TimeSpan timeWindowInstance = TypeConversion.From8601TimeSpan(((string)timeWindowValue));
metricTriggerInstance.TimeWindow = timeWindowInstance;
}
JToken timeAggregationValue = metricTriggerValue["TimeAggregation"];
if (timeAggregationValue != null && timeAggregationValue.Type != JTokenType.Null)
{
TimeAggregationType timeAggregationInstance = ((TimeAggregationType)Enum.Parse(typeof(TimeAggregationType), ((string)timeAggregationValue), true));
metricTriggerInstance.TimeAggregation = timeAggregationInstance;
}
JToken operatorValue = metricTriggerValue["Operator"];
if (operatorValue != null && operatorValue.Type != JTokenType.Null)
{
ComparisonOperationType operatorInstance = ((ComparisonOperationType)Enum.Parse(typeof(ComparisonOperationType), ((string)operatorValue), true));
metricTriggerInstance.Operator = operatorInstance;
}
JToken thresholdValue = metricTriggerValue["Threshold"];
if (thresholdValue != null && thresholdValue.Type != JTokenType.Null)
{
double thresholdInstance = ((double)thresholdValue);
metricTriggerInstance.Threshold = thresholdInstance;
}
}
JToken scaleActionValue = rulesValue["ScaleAction"];
if (scaleActionValue != null && scaleActionValue.Type != JTokenType.Null)
{
ScaleAction scaleActionInstance = new ScaleAction();
scaleRuleInstance.ScaleAction = scaleActionInstance;
JToken directionValue = scaleActionValue["Direction"];
if (directionValue != null && directionValue.Type != JTokenType.Null)
{
ScaleDirection directionInstance = ((ScaleDirection)Enum.Parse(typeof(ScaleDirection), ((string)directionValue), true));
scaleActionInstance.Direction = directionInstance;
}
JToken typeValue = scaleActionValue["Type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
ScaleType typeInstance = ((ScaleType)Enum.Parse(typeof(ScaleType), ((string)typeValue), true));
scaleActionInstance.Type = typeInstance;
}
JToken valueValue = scaleActionValue["Value"];
if (valueValue != null && valueValue.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue);
scaleActionInstance.Value = valueInstance;
}
JToken cooldownValue = scaleActionValue["Cooldown"];
if (cooldownValue != null && cooldownValue.Type != JTokenType.Null)
{
TimeSpan cooldownInstance = TypeConversion.From8601TimeSpan(((string)cooldownValue));
scaleActionInstance.Cooldown = cooldownInstance;
}
}
}
}
JToken fixedDateValue = profilesValue["FixedDate"];
if (fixedDateValue != null && fixedDateValue.Type != JTokenType.Null)
{
TimeWindow fixedDateInstance = new TimeWindow();
autoscaleProfileInstance.FixedDate = fixedDateInstance;
JToken timeZoneValue = fixedDateValue["TimeZone"];
if (timeZoneValue != null && timeZoneValue.Type != JTokenType.Null)
{
string timeZoneInstance = ((string)timeZoneValue);
fixedDateInstance.TimeZone = timeZoneInstance;
}
JToken startValue = fixedDateValue["Start"];
if (startValue != null && startValue.Type != JTokenType.Null)
{
DateTime startInstance = ((DateTime)startValue);
fixedDateInstance.Start = startInstance;
}
JToken endValue = fixedDateValue["End"];
if (endValue != null && endValue.Type != JTokenType.Null)
{
DateTime endInstance = ((DateTime)endValue);
fixedDateInstance.End = endInstance;
}
}
JToken recurrenceValue = profilesValue["Recurrence"];
if (recurrenceValue != null && recurrenceValue.Type != JTokenType.Null)
{
Recurrence recurrenceInstance = new Recurrence();
autoscaleProfileInstance.Recurrence = recurrenceInstance;
JToken frequencyValue = recurrenceValue["Frequency"];
if (frequencyValue != null && frequencyValue.Type != JTokenType.Null)
{
RecurrenceFrequency frequencyInstance = ((RecurrenceFrequency)Enum.Parse(typeof(RecurrenceFrequency), ((string)frequencyValue), true));
recurrenceInstance.Frequency = frequencyInstance;
}
JToken scheduleValue = recurrenceValue["Schedule"];
if (scheduleValue != null && scheduleValue.Type != JTokenType.Null)
{
RecurrentSchedule scheduleInstance = new RecurrentSchedule();
recurrenceInstance.Schedule = scheduleInstance;
JToken timeZoneValue2 = scheduleValue["TimeZone"];
if (timeZoneValue2 != null && timeZoneValue2.Type != JTokenType.Null)
{
string timeZoneInstance2 = ((string)timeZoneValue2);
scheduleInstance.TimeZone = timeZoneInstance2;
}
JToken daysArray = scheduleValue["Days"];
if (daysArray != null && daysArray.Type != JTokenType.Null)
{
foreach (JToken daysValue in ((JArray)daysArray))
{
scheduleInstance.Days.Add(((string)daysValue));
}
}
JToken hoursArray = scheduleValue["Hours"];
if (hoursArray != null && hoursArray.Type != JTokenType.Null)
{
foreach (JToken hoursValue in ((JArray)hoursArray))
{
scheduleInstance.Hours.Add(((int)hoursValue));
}
}
JToken minutesArray = scheduleValue["Minutes"];
if (minutesArray != null && minutesArray.Type != JTokenType.Null)
{
foreach (JToken minutesValue in ((JArray)minutesArray))
{
scheduleInstance.Minutes.Add(((int)minutesValue));
}
}
}
}
}
}
JToken enabledValue = responseDoc["Enabled"];
if (enabledValue != null && enabledValue.Type != JTokenType.Null)
{
bool enabledInstance = ((bool)enabledValue);
settingInstance.Enabled = enabledInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Linq;
using System.Reflection;
using System.Timers;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Collections.Generic;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Timer=System.Timers.Timer;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.World.Region
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RestartModule")]
public class RestartModule : INonSharedRegionModule, IRestartModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Scene m_Scene;
protected Timer m_CountdownTimer = null;
protected DateTime m_RestartBegin;
protected List<int> m_Alerts;
protected string m_Message;
protected UUID m_Initiator;
protected bool m_Notice = false;
protected IDialogModule m_DialogModule = null;
protected string m_MarkerPath = String.Empty;
private int[] m_CurrentAlerts = null;
public void Initialise(IConfigSource config)
{
IConfig restartConfig = config.Configs["RestartModule"];
if (restartConfig != null)
{
m_MarkerPath = restartConfig.GetString("MarkerPath", String.Empty);
}
}
public void AddRegion(Scene scene)
{
if (m_MarkerPath != String.Empty)
File.Delete(Path.Combine(m_MarkerPath,
scene.RegionInfo.RegionID.ToString()));
m_Scene = scene;
scene.RegisterModuleInterface<IRestartModule>(this);
MainConsole.Instance.Commands.AddCommand("Regions",
false, "region restart bluebox",
"region restart bluebox <message> <delta seconds>+",
"Schedule a region restart",
"Schedule a region restart after a given number of seconds. If one delta is given then the region is restarted in delta seconds time. A time to restart is sent to users in the region as a dismissable bluebox notice. If multiple deltas are given then a notice is sent when we reach each delta.",
HandleRegionRestart);
MainConsole.Instance.Commands.AddCommand("Regions",
false, "region restart notice",
"region restart notice <message> <delta seconds>+",
"Schedule a region restart",
"Schedule a region restart after a given number of seconds. If one delta is given then the region is restarted in delta seconds time. A time to restart is sent to users in the region as a transient notice. If multiple deltas are given then a notice is sent when we reach each delta.",
HandleRegionRestart);
MainConsole.Instance.Commands.AddCommand("Regions",
false, "region restart abort",
"region restart abort [<message>]",
"Abort a region restart", HandleRegionRestart);
}
public void RegionLoaded(Scene scene)
{
m_DialogModule = m_Scene.RequestModuleInterface<IDialogModule>();
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
public string Name
{
get { return "RestartModule"; }
}
public Type ReplaceableInterface
{
get { return typeof(IRestartModule); }
}
public TimeSpan TimeUntilRestart
{
get { return DateTime.Now - m_RestartBegin; }
}
public void ScheduleRestart(UUID initiator, string message, int[] alerts, bool notice)
{
if (m_CountdownTimer != null)
{
m_CountdownTimer.Stop();
m_CountdownTimer = null;
}
if (alerts == null)
{
CreateMarkerFile();
m_Scene.RestartNow();
return;
}
m_Message = message;
m_Initiator = initiator;
m_Notice = notice;
m_CurrentAlerts = alerts;
m_Alerts = new List<int>(alerts);
m_Alerts.Sort();
m_Alerts.Reverse();
if (m_Alerts[0] == 0)
{
CreateMarkerFile();
m_Scene.RestartNow();
return;
}
int nextInterval = DoOneNotice(true);
SetTimer(nextInterval);
}
public int DoOneNotice(bool sendOut)
{
if (m_Alerts.Count == 0 || m_Alerts[0] == 0)
{
CreateMarkerFile();
m_Scene.RestartNow();
return 0;
}
int nextAlert = 0;
while (m_Alerts.Count > 1)
{
if (m_Alerts[1] == m_Alerts[0])
{
m_Alerts.RemoveAt(0);
continue;
}
nextAlert = m_Alerts[1];
break;
}
int currentAlert = m_Alerts[0];
m_Alerts.RemoveAt(0);
if (sendOut)
{
int minutes = currentAlert / 60;
string currentAlertString = String.Empty;
if (minutes > 0)
{
if (minutes == 1)
currentAlertString += "1 minute";
else
currentAlertString += String.Format("{0} minutes", minutes);
if ((currentAlert % 60) != 0)
currentAlertString += " and ";
}
if ((currentAlert % 60) != 0)
{
int seconds = currentAlert % 60;
if (seconds == 1)
currentAlertString += "1 second";
else
currentAlertString += String.Format("{0} seconds", seconds);
}
string msg = String.Format(m_Message, currentAlertString);
if (m_DialogModule != null && msg != String.Empty)
{
if (m_Notice)
m_DialogModule.SendGeneralAlert(msg);
else
m_DialogModule.SendNotificationToUsersInRegion(m_Initiator, "System", msg);
}
}
return currentAlert - nextAlert;
}
public void SetTimer(int intervalSeconds)
{
if (intervalSeconds > 0)
{
m_CountdownTimer = new Timer();
m_CountdownTimer.AutoReset = false;
m_CountdownTimer.Interval = intervalSeconds * 1000;
m_CountdownTimer.Elapsed += OnTimer;
m_CountdownTimer.Start();
}
else if (m_CountdownTimer != null)
{
m_CountdownTimer.Stop();
m_CountdownTimer = null;
}
else
{
m_log.WarnFormat(
"[RESTART MODULE]: Tried to set restart timer to {0} in {1}, which is not a valid interval",
intervalSeconds, m_Scene.Name);
}
}
private void OnTimer(object source, ElapsedEventArgs e)
{
int nextInterval = DoOneNotice(true);
SetTimer(nextInterval);
}
public void DelayRestart(int seconds, string message)
{
if (m_CountdownTimer == null)
return;
m_CountdownTimer.Stop();
m_CountdownTimer = null;
m_Alerts = new List<int>(m_CurrentAlerts);
m_Alerts.Add(seconds);
m_Alerts.Sort();
m_Alerts.Reverse();
int nextInterval = DoOneNotice(false);
SetTimer(nextInterval);
}
public void AbortRestart(string message)
{
if (m_CountdownTimer != null)
{
m_CountdownTimer.Stop();
m_CountdownTimer = null;
if (m_DialogModule != null && message != String.Empty)
m_DialogModule.SendNotificationToUsersInRegion(UUID.Zero, "System", message);
//m_DialogModule.SendGeneralAlert(message);
}
if (m_MarkerPath != String.Empty)
File.Delete(Path.Combine(m_MarkerPath,
m_Scene.RegionInfo.RegionID.ToString()));
}
private void HandleRegionRestart(string module, string[] args)
{
if (!(MainConsole.Instance.ConsoleScene is Scene))
return;
if (MainConsole.Instance.ConsoleScene != m_Scene)
return;
if (args.Length < 5)
{
if (args.Length > 2)
{
if (args[2] == "abort")
{
string msg = String.Empty;
if (args.Length > 3)
msg = args[3];
AbortRestart(msg);
MainConsole.Instance.Output("Region restart aborted");
return;
}
}
MainConsole.Instance.Output("Error: restart region <mode> <name> <delta seconds>+");
return;
}
bool notice = false;
if (args[2] == "notice")
notice = true;
List<int> times = new List<int>();
for (int i = 4 ; i < args.Length ; i++)
times.Add(Convert.ToInt32(args[i]));
MainConsole.Instance.OutputFormat(
"Region {0} scheduled for restart in {1} seconds", m_Scene.Name, times.Sum());
ScheduleRestart(UUID.Zero, args[3], times.ToArray(), notice);
}
protected void CreateMarkerFile()
{
if (m_MarkerPath == String.Empty)
return;
string path = Path.Combine(m_MarkerPath, m_Scene.RegionInfo.RegionID.ToString());
try
{
string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
FileStream fs = File.Create(path);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
Byte[] buf = enc.GetBytes(pidstring);
fs.Write(buf, 0, buf.Length);
fs.Close();
}
catch (Exception)
{
}
}
}
}
| |
/*
* 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 OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Reflection;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalAssetServicesConnector")]
public class LocalAssetServicesConnector : ISharedRegionModule, IAssetService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IAssetService m_AssetService;
private IImprovedAssetCache m_Cache = null;
private bool m_Enabled = false;
public string Name
{
get { return "LocalAssetServicesConnector"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IAssetService>(this);
}
public bool[] AssetsExist(string[] ids)
{
return m_AssetService.AssetsExist(ids);
}
public void Close()
{
}
public bool Delete(string id)
{
if (m_Cache != null)
m_Cache.Expire(id);
return m_AssetService.Delete(id);
}
public AssetBase Get(string id)
{
// m_log.DebugFormat("[LOCAL ASSET SERVICES CONNECTOR]: Synchronously requesting asset {0}", id);
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset == null)
{
asset = m_AssetService.Get(id);
if ((m_Cache != null) && (asset != null))
m_Cache.Cache(asset);
// if (null == asset)
// m_log.WarnFormat("[LOCAL ASSET SERVICES CONNECTOR]: Could not synchronously find asset with id {0}", id);
}
return asset;
}
public bool Get(string id, Object sender, AssetRetrieved handler)
{
// m_log.DebugFormat("[LOCAL ASSET SERVICES CONNECTOR]: Asynchronously requesting asset {0}", id);
if (m_Cache != null)
{
AssetBase asset = m_Cache.Get(id);
if (asset != null)
{
Util.FireAndForget(delegate { handler(id, sender, asset); });
return true;
}
}
return m_AssetService.Get(id, sender, delegate(string assetID, Object s, AssetBase a)
{
if ((a != null) && (m_Cache != null))
m_Cache.Cache(a);
// if (null == a)
// m_log.WarnFormat("[LOCAL ASSET SERVICES CONNECTOR]: Could not asynchronously find asset with id {0}", id);
Util.FireAndForget(delegate { handler(assetID, s, a); });
});
}
public AssetBase GetCached(string id)
{
// m_log.DebugFormat("[LOCAL ASSET SERVICES CONNECTOR]: Cache request for {0}", id);
if (m_Cache != null)
return m_Cache.Get(id);
return null;
}
public byte[] GetData(string id)
{
// m_log.DebugFormat("[LOCAL ASSET SERVICES CONNECTOR]: Requesting data for asset {0}", id);
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset != null)
return asset.Data;
asset = m_AssetService.Get(id);
if (asset != null)
{
if (m_Cache != null)
m_Cache.Cache(asset);
return asset.Data;
}
return null;
}
public AssetMetadata GetMetadata(string id)
{
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset != null)
return asset.Metadata;
asset = m_AssetService.Get(id);
if (asset != null)
{
if (m_Cache != null)
m_Cache.Cache(asset);
return asset.Metadata;
}
return null;
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("AssetServices", "");
if (name == Name)
{
IConfig assetConfig = source.Configs["AssetService"];
if (assetConfig == null)
{
m_log.Error("[LOCAL ASSET SERVICES CONNECTOR]: AssetService missing from OpenSim.ini");
return;
}
string serviceDll = assetConfig.GetString("LocalServiceModule", String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL ASSET SERVICES CONNECTOR]: No LocalServiceModule named in section AssetService");
return;
}
else
{
m_log.DebugFormat("[LOCAL ASSET SERVICES CONNECTOR]: Loading asset service at {0}", serviceDll);
}
Object[] args = new Object[] { source };
m_AssetService = ServerUtils.LoadPlugin<IAssetService>(serviceDll, args);
if (m_AssetService == null)
{
m_log.Error("[LOCAL ASSET SERVICES CONNECTOR]: Can't load asset service");
return;
}
m_Enabled = true;
m_log.Info("[LOCAL ASSET SERVICES CONNECTOR]: Local asset connector enabled");
}
}
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
if (m_Cache == null)
{
m_Cache = scene.RequestModuleInterface<IImprovedAssetCache>();
if (!(m_Cache is ISharedRegionModule))
m_Cache = null;
}
m_log.DebugFormat(
"[LOCAL ASSET SERVICES CONNECTOR]: Enabled connector for region {0}", scene.RegionInfo.RegionName);
if (m_Cache != null)
{
m_log.DebugFormat(
"[LOCAL ASSET SERVICES CONNECTOR]: Enabled asset caching for region {0}",
scene.RegionInfo.RegionName);
}
else
{
// Short-circuit directly to storage layer. This ends up storing temporary and local assets.
//
scene.UnregisterModuleInterface<IAssetService>(this);
scene.RegisterModuleInterface<IAssetService>(m_AssetService);
}
}
public void RemoveRegion(Scene scene)
{
}
public string Store(AssetBase asset)
{
if (m_Cache != null)
m_Cache.Cache(asset);
if (asset.Local)
{
// m_log.DebugFormat(
// "[LOCAL ASSET SERVICE CONNECTOR]: Returning asset {0} {1} without querying database since status Temporary = {2}, Local = {3}",
// asset.Name, asset.ID, asset.Temporary, asset.Local);
return asset.ID;
}
else
{
// m_log.DebugFormat(
// "[LOCAL ASSET SERVICE CONNECTOR]: Passing {0} {1} on to asset service for storage, status Temporary = {2}, Local = {3}",
// asset.Name, asset.ID, asset.Temporary, asset.Local);
return m_AssetService.Store(asset);
}
}
public bool UpdateContent(string id, byte[] data)
{
AssetBase asset = null;
if (m_Cache != null)
m_Cache.Get(id);
if (asset != null)
{
asset.Data = data;
if (m_Cache != null)
m_Cache.Cache(asset);
}
return m_AssetService.UpdateContent(id, data);
}
}
}
| |
//! \file ImageIAF.cs
//! \date Sun May 31 21:17:54 2015
//! \brief IAF 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.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using GameRes.Compression;
using GameRes.Utility;
namespace GameRes.Formats.Triangle
{
internal class IafMetaData : ImageMetaData
{
public int DataOffset;
public int PackedSize;
public int UnpackedSize;
public int PackType;
}
[Export(typeof(ImageFormat))]
public class IafFormat : BmpFormat
{
public override string Tag { get { return "IAF"; } }
public override string Description { get { return "Triangle compressed bitmap format"; } }
public override uint Signature { get { return 0; } }
public override ImageMetaData ReadMetaData (Stream stream)
{
var header = new byte[0x14];
if (12 != stream.Read (header, 0, 12))
return null;
int data_offset;
int packed_size = LittleEndian.ToInt32 (header, 1);
int x, y, unpacked_size;
if (5+packed_size+0x14 == stream.Length)
{
data_offset = 5;
stream.Seek (-0x14, SeekOrigin.End);
if (0x14 != stream.Read (header, 0, 0x14))
return null;
x = LittleEndian.ToInt32 (header, 0);
y = LittleEndian.ToInt32 (header, 4);
unpacked_size = LittleEndian.ToInt32 (header, 0x10);
}
else
{
data_offset = 12;
x = LittleEndian.ToInt32 (header, 0);
y = LittleEndian.ToInt32 (header, 4);
unpacked_size = LittleEndian.ToInt32 (header, 8);
packed_size = (int)stream.Length-12;
}
if (Math.Abs (x) > 4096 || Math.Abs (y) > 4096)
return null;
int pack_type = (unpacked_size >> 30) & 3;
unpacked_size &= (int)~0xC0000000;
stream.Position = data_offset;
byte[] bmp;
if (0 == pack_type)
{
using (var reader = new LzssReader (stream, (int)stream.Length-12, 0x26))
{
reader.Unpack();
bmp = reader.Data;
}
}
else if (2 == pack_type)
{
using (var reader = new RleReader (stream, (int)stream.Length-12, 0x26))
{
reader.Unpack();
bmp = reader.Data;
}
}
else if (1 == pack_type)
{
bmp = new byte[0x26];
stream.Read (bmp, 0, bmp.Length);
}
else
{
return null;
}
if (bmp[0] != 'B' && bmp[0] != 'C' || bmp[1] != 'M')
return null;
int width = LittleEndian.ToInt32 (bmp, 0x12);
int height = LittleEndian.ToInt32 (bmp, 0x16);
int bpp = LittleEndian.ToInt16 (bmp, 0x1c);
return new IafMetaData
{
Width = (uint)width,
Height = (uint)height,
OffsetX = x,
OffsetY = y,
BPP = bpp,
DataOffset = data_offset,
PackedSize = packed_size,
UnpackedSize = unpacked_size,
PackType = pack_type,
};
}
public override ImageData Read (Stream stream, ImageMetaData info)
{
var meta = info as IafMetaData;
if (null == meta)
throw new ArgumentException ("IafFormat.Read should be supplied with IafMetaData", "info");
stream.Position = meta.DataOffset;
byte[] bitmap;
if (2 == meta.PackType)
{
using (var reader = new RleReader (stream, meta.PackedSize, meta.UnpackedSize))
{
reader.Unpack();
bitmap = reader.Data;
}
}
else if (0 == meta.PackType)
{
using (var reader = new LzssReader (stream, meta.PackedSize, meta.UnpackedSize))
{
reader.Unpack();
bitmap = reader.Data;
}
}
else
{
bitmap = new byte[meta.UnpackedSize];
if (bitmap.Length != stream.Read (bitmap, 0, bitmap.Length))
throw new InvalidFormatException ("Unexpected end of file");
}
if ('C' == bitmap[0])
{
bitmap[0] = (byte)'B';
if (info.BPP > 8)
bitmap = ConvertCM (bitmap, (int)info.Width, (int)info.Height, info.BPP);
}
if (meta.BPP >= 24) // currently alpha channel could be applied to 24+bpp bitmaps only
{
try
{
int bmp_size = LittleEndian.ToInt32 (bitmap, 2);
if (bitmap.Length - bmp_size > 0x36) // size of bmp header
{
if ('B' == bitmap[bmp_size] && 'M' == bitmap[bmp_size+1] &&
8 == bitmap[bmp_size+0x1c]) // 8bpp
{
uint alpha_width = LittleEndian.ToUInt32 (bitmap, bmp_size+0x12);
uint alpha_height = LittleEndian.ToUInt32 (bitmap, bmp_size+0x16);
if (info.Width == alpha_width && info.Height == alpha_height)
return BitmapWithAlphaChannel (meta, bitmap, bmp_size);
}
}
}
catch
{
// ignore any errors occured during alpha-channel read attempt,
// fallback to a plain bitmap
}
}
using (var bmp = new MemoryStream (bitmap))
return base.Read (bmp, info);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("IafFormat.Write not implemented");
}
static ImageData BitmapWithAlphaChannel (ImageMetaData info, byte[] bitmap, int alpha_offset)
{
int src_pixel_size = info.BPP/8;
int src_stride = (int)info.Width*src_pixel_size;
int src_pixels = LittleEndian.ToInt32 (bitmap, 0x0A);
int src_alpha = alpha_offset + LittleEndian.ToInt32 (bitmap, alpha_offset+0x0A);
var pixels = new byte[info.Width * info.Height * 4];
int dst = 0;
for (int y = (int)info.Height-1; y >= 0; --y)
{
int src = src_pixels + y*src_stride;
int alpha = src_alpha + y*(int)info.Width;
for (uint x = 0; x < info.Width; ++x)
{
pixels[dst++] = bitmap[src];
pixels[dst++] = bitmap[src+1];
pixels[dst++] = bitmap[src+2];
pixels[dst++] = (byte)~bitmap[alpha++];
src += src_pixel_size;
}
}
return ImageData.Create (info, PixelFormats.Bgra32, null, pixels);
}
static byte[] ConvertCM (byte[] input, int width, int height, int bpp)
{
int src = LittleEndian.ToInt32 (input, 0x0a);
int pixel_size = bpp / 8;
var bitmap = new byte[input.Length];
Buffer.BlockCopy (input, 0, bitmap, 0, src);
int stride = width * pixel_size;
int i = src;
for (int p = 0; p < pixel_size; ++p)
{
for (int y = 0; y < height; ++y)
{
int pixel = y * stride + p;
for (int x = 0; x < width; ++x)
{
bitmap[src+pixel] = input[i++];
pixel += pixel_size;
}
}
}
return bitmap;
}
}
internal class RleReader : IDataUnpacker, IDisposable
{
BinaryReader m_input;
byte[] m_output;
int m_size;
public byte[] Data { get { return m_output; } }
public RleReader (Stream input, int input_length, int output_length)
{
m_input = new ArcView.Reader (input);
m_output = new byte[output_length];
m_size = input_length;
}
public void Unpack ()
{
int src = 0;
int dst = 0;
while (dst < m_output.Length && src < m_size)
{
byte ctl = m_input.ReadByte();
++src;
if (0 == ctl)
{
int count = m_input.ReadByte();
++src;
count = Math.Min (count, m_output.Length - dst);
int read = m_input.Read (m_output, dst, count);
dst += count;
src += count;
}
else
{
int count = ctl;
byte b = m_input.ReadByte();
++src;
count = Math.Min (count, m_output.Length - dst);
for (int i = 0; i < count; i++)
m_output[dst++] = b;
}
}
}
#region IDisposable Members
bool disposed = false;
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!disposed)
{
if (disposing)
{
m_input.Dispose();
}
disposed = true;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using BudgetAnalyser.Engine.BankAccount;
using JetBrains.Annotations;
namespace BudgetAnalyser.Engine.Statement
{
/// <summary>
/// An Importer for ANZ Cheque and Savings Accounts bank statement exports.
/// </summary>
[AutoRegisterWithIoC(SingleInstance = true)]
internal class AnzAccountStatementImporterV1 : IBankStatementImporter
{
private const int TransactionTypeIndex = 0;
private const int DescriptionIndex = 1;
private const int Reference1Index = 2;
private const int Reference2Index = 3;
private const int Reference3Index = 4;
private const int AmountIndex = 5;
private const int DateIndex = 6;
private static readonly Dictionary<string, TransactionType> TransactionTypes = new Dictionary<string, TransactionType>();
private readonly BankImportUtilities importUtilities;
private readonly ILogger logger;
private readonly IReaderWriterSelector readerWriterSelector;
/// <summary>
/// Initializes a new instance of the <see cref="AnzAccountStatementImporterV1" /> class.
/// </summary>
/// <exception cref="System.ArgumentNullException">
/// </exception>
public AnzAccountStatementImporterV1([NotNull] BankImportUtilities importUtilities, [NotNull] ILogger logger, [NotNull] IReaderWriterSelector readerWriterSelector)
{
if (importUtilities == null)
{
throw new ArgumentNullException(nameof(importUtilities));
}
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
if (readerWriterSelector == null) throw new ArgumentNullException(nameof(readerWriterSelector));
this.importUtilities = importUtilities;
this.logger = logger;
this.readerWriterSelector = readerWriterSelector;
this.importUtilities.ConfigureLocale(new CultureInfo("en-NZ"));
// ANZ importers are NZ specific at this stage.
}
/// <summary>
/// Load the given file into a <see cref="StatementModel" />.
/// </summary>
/// <param name="fileName">The file to load.</param>
/// <param name="account">
/// The account to classify these transactions. This is useful when merging one statement to another. For example,
/// merging a cheque account export with visa account export, each can be classified using an account.
/// </param>
public async Task<StatementModel> LoadAsync(string fileName, Account account)
{
try
{
this.importUtilities.AbortIfFileDoesntExist(fileName);
}
catch (FileNotFoundException ex)
{
throw new KeyNotFoundException(ex.Message, ex);
}
var transactions = new List<Transaction>();
var firstTime = true;
foreach (var line in await ReadLinesAsync(fileName))
{
if (firstTime)
{
// File contains column headers
firstTime = false;
continue;
}
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
string[] split = line.Split(',');
var transaction = new Transaction
{
Account = account,
Description = this.importUtilities.FetchString(split, DescriptionIndex),
Reference1 = this.importUtilities.FetchString(split, Reference1Index),
Reference2 = this.importUtilities.FetchString(split, Reference2Index),
Reference3 = this.importUtilities.FetchString(split, Reference3Index),
Amount = this.importUtilities.FetchDecimal(split, AmountIndex),
Date = this.importUtilities.FetchDate(split, DateIndex)
};
transaction.TransactionType = FetchTransactionType(split, transaction.Amount);
transactions.Add(transaction);
}
var statement = new StatementModel(this.logger)
{
StorageKey = fileName,
LastImport = DateTime.Now
}.LoadTransactions(transactions);
return statement;
}
/// <summary>
/// Test the given file to see if this importer implementation can read and import it.
/// This will open and read some of the contents of the file.
/// </summary>
public async Task<bool> TasteTestAsync(string fileName)
{
this.importUtilities.AbortIfFileDoesntExist(fileName);
string[] lines = await ReadFirstTwoLinesAsync(fileName);
if (lines == null || lines.Length != 2 || lines[0].IsNothing() || lines[1].IsNothing())
{
return false;
}
try
{
if (!VerifyColumnHeaderLine(lines[0])) return false;
if (!VerifyFirstDataLine(lines[1])) return false;
}
catch (Exception)
{
return false;
}
return true;
}
/// <summary>
/// Reads the lines from the file asynchronously.
/// </summary>
protected virtual async Task<IEnumerable<string>> ReadLinesAsync(string fileName)
{
var reader = this.readerWriterSelector.SelectReaderWriter(false);
var allText = await reader.LoadFromDiskAsync(fileName);
return allText.SplitLines();
}
/// <summary>
/// Reads a chunk of text asynchronously.
/// </summary>
protected virtual async Task<string> ReadTextChunkAsync(string filePath)
{
var reader = this.readerWriterSelector.SelectReaderWriter(false);
return await reader.LoadFirstLinesFromDiskAsync(filePath, 2);
}
private TransactionType FetchTransactionType(string[] array, decimal amount)
{
var stringType = this.importUtilities.FetchString(array, TransactionTypeIndex);
if (stringType.IsNothing())
{
return null;
}
if (TransactionTypes.ContainsKey(stringType))
{
return TransactionTypes[stringType];
}
var transactionType = new NamedTransaction(stringType, amount < 0);
TransactionTypes.Add(stringType, transactionType);
return transactionType;
}
private async Task<string[]> ReadFirstTwoLinesAsync(string fileName)
{
var chunk = await ReadTextChunkAsync(fileName);
if (chunk.IsNothing())
{
return null;
}
return chunk.SplitLines(2);
}
private static bool VerifyColumnHeaderLine(string line)
{
var compareTo = line.EndsWith("\r", StringComparison.OrdinalIgnoreCase) ? line.Remove(line.Length - 1, 1) : line;
return string.CompareOrdinal(compareTo, "Type,Details,Particulars,Code,Reference,Amount,Date,ForeignCurrencyAmount,ConversionCharge") == 0;
}
private bool VerifyFirstDataLine(string line)
{
string[] split = line.Split(',');
var type = this.importUtilities.FetchString(split, 0);
if (string.IsNullOrWhiteSpace(type))
{
return false;
}
if (char.IsDigit(type.ToCharArray()[0]))
{
return false;
}
var amount = this.importUtilities.FetchDecimal(split, AmountIndex);
if (amount == 0)
{
return false;
}
var date = this.importUtilities.FetchDate(split, DateIndex);
if (date == DateTime.MinValue)
{
return false;
}
if (split.Length != 9)
{
return false;
}
return true;
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.PythonTools.Debugger.DebugEngine;
using Microsoft.PythonTools.Editor.Core;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.InterpreterList;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
using Microsoft.PythonTools.Project;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
namespace Microsoft.PythonTools {
public static class Extensions {
internal static bool IsAppxPackageableProject(this ProjectNode projectNode) {
var appxProp = projectNode.BuildProject.GetPropertyValue(ProjectFileConstants.AppxPackage);
var containerProp = projectNode.BuildProject.GetPropertyValue(ProjectFileConstants.WindowsAppContainer);
var appxFlag = false;
var containerFlag = false;
if (bool.TryParse(appxProp, out appxFlag) && bool.TryParse(containerProp, out containerFlag)) {
return appxFlag && containerFlag;
} else {
return false;
}
}
public static StandardGlyphGroup ToGlyphGroup(this PythonMemberType objectType) {
StandardGlyphGroup group;
switch (objectType) {
case PythonMemberType.Class: group = StandardGlyphGroup.GlyphGroupClass; break;
case PythonMemberType.DelegateInstance:
case PythonMemberType.Delegate: group = StandardGlyphGroup.GlyphGroupDelegate; break;
case PythonMemberType.Enum: group = StandardGlyphGroup.GlyphGroupEnum; break;
case PythonMemberType.Namespace: group = StandardGlyphGroup.GlyphGroupNamespace; break;
case PythonMemberType.Multiple: group = StandardGlyphGroup.GlyphGroupOverload; break;
case PythonMemberType.Field: group = StandardGlyphGroup.GlyphGroupField; break;
case PythonMemberType.Module: group = StandardGlyphGroup.GlyphGroupModule; break;
case PythonMemberType.Property: group = StandardGlyphGroup.GlyphGroupProperty; break;
case PythonMemberType.Instance: group = StandardGlyphGroup.GlyphGroupVariable; break;
case PythonMemberType.Constant: group = StandardGlyphGroup.GlyphGroupVariable; break;
case PythonMemberType.EnumInstance: group = StandardGlyphGroup.GlyphGroupEnumMember; break;
case PythonMemberType.Event: group = StandardGlyphGroup.GlyphGroupEvent; break;
case PythonMemberType.Keyword: group = StandardGlyphGroup.GlyphKeyword; break;
case PythonMemberType.Function:
case PythonMemberType.Method:
default:
group = StandardGlyphGroup.GlyphGroupMethod;
break;
}
return group;
}
internal static bool CanComplete(this ClassificationSpan token) {
return token.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Keyword) |
token.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Identifier);
}
/// <summary>
/// Returns the span to use for the provided intellisense session.
/// </summary>
/// <returns>A tracking span. The span may be of length zero if there
/// is no suitable token at the trigger point.</returns>
internal static ITrackingSpan GetApplicableSpan(this IIntellisenseSession session, ITextBuffer buffer) {
var snapshot = buffer.CurrentSnapshot;
var triggerPoint = session.GetTriggerPoint(buffer);
var span = snapshot.GetApplicableSpan(triggerPoint);
if (span != null) {
return span;
}
return snapshot.CreateTrackingSpan(triggerPoint.GetPosition(snapshot), 0, SpanTrackingMode.EdgeInclusive);
}
/// <summary>
/// Returns the applicable span at the provided position.
/// </summary>
/// <returns>A tracking span, or null if there is no token at the
/// provided position.</returns>
internal static ITrackingSpan GetApplicableSpan(this ITextSnapshot snapshot, ITrackingPoint point) {
return snapshot.GetApplicableSpan(point.GetPosition(snapshot));
}
/// <summary>
/// Returns the applicable span at the provided position.
/// </summary>
/// <returns>A tracking span, or null if there is no token at the
/// provided position.</returns>
internal static ITrackingSpan GetApplicableSpan(this ITextSnapshot snapshot, int position) {
var classifier = snapshot.TextBuffer.GetPythonClassifier();
var line = snapshot.GetLineFromPosition(position);
if (classifier == null || line == null) {
return null;
}
var spanLength = position - line.Start.Position;
// Increase position by one to include 'fob' in: "abc.|fob"
if (spanLength < line.Length) {
spanLength += 1;
}
var classifications = classifier.GetClassificationSpans(new SnapshotSpan(line.Start, spanLength));
// Handle "|"
if (classifications == null || classifications.Count == 0) {
return null;
}
var lastToken = classifications[classifications.Count - 1];
// Handle "fob |"
if (lastToken == null || position > lastToken.Span.End) {
return null;
}
if (position > lastToken.Span.Start) {
if (lastToken.CanComplete()) {
// Handle "fo|o"
return snapshot.CreateTrackingSpan(lastToken.Span, SpanTrackingMode.EdgeInclusive);
} else {
// Handle "<|="
return null;
}
}
var secondLastToken = classifications.Count >= 2 ? classifications[classifications.Count - 2] : null;
if (lastToken.Span.Start == position && lastToken.CanComplete() &&
(secondLastToken == null || // Handle "|fob"
position > secondLastToken.Span.End || // Handle "if |fob"
!secondLastToken.CanComplete())) { // Handle "abc.|fob"
return snapshot.CreateTrackingSpan(lastToken.Span, SpanTrackingMode.EdgeInclusive);
}
// Handle "abc|."
// ("ab|c." would have been treated as "ab|c")
if (secondLastToken != null && secondLastToken.Span.End == position && secondLastToken.CanComplete()) {
return snapshot.CreateTrackingSpan(secondLastToken.Span, SpanTrackingMode.EdgeInclusive);
}
return null;
}
internal static ITrackingSpan CreateTrackingSpan(this IQuickInfoSession session, ITextBuffer buffer) {
var triggerPoint = session.GetTriggerPoint(buffer);
var position = triggerPoint.GetPosition(buffer.CurrentSnapshot);
if (position == buffer.CurrentSnapshot.Length) {
return ((IIntellisenseSession)session).GetApplicableSpan(buffer);
}
return buffer.CurrentSnapshot.CreateTrackingSpan(position, 1, SpanTrackingMode.EdgeInclusive);
}
#pragma warning disable 0618
// TODO: Switch from smart tags to Light Bulb: http://go.microsoft.com/fwlink/?LinkId=394601
internal static ITrackingSpan CreateTrackingSpan(this ISmartTagSession session, ITextBuffer buffer) {
var triggerPoint = session.GetTriggerPoint(buffer);
var position = triggerPoint.GetPosition(buffer.CurrentSnapshot);
if (position == buffer.CurrentSnapshot.Length) {
return ((IIntellisenseSession)session).GetApplicableSpan(buffer);
}
var triggerChar = triggerPoint.GetCharacter(buffer.CurrentSnapshot);
if (position != 0 && !char.IsLetterOrDigit(triggerChar)) {
// end of line, back up one char as we may have an identifier
return buffer.CurrentSnapshot.CreateTrackingSpan(position - 1, 1, SpanTrackingMode.EdgeInclusive);
}
return buffer.CurrentSnapshot.CreateTrackingSpan(position, 1, SpanTrackingMode.EdgeInclusive);
}
#pragma warning restore 0618
public static IPythonInterpreterFactory GetPythonInterpreterFactory(this IVsHierarchy self) {
var node = (self.GetProject().GetCommonProject() as PythonProjectNode);
if (node != null) {
return node.GetInterpreterFactory();
}
return null;
}
public static IEnumerable<IVsProject> EnumerateLoadedProjects(this IVsSolution solution) {
var guid = new Guid(PythonConstants.ProjectFactoryGuid);
IEnumHierarchies hierarchies;
ErrorHandler.ThrowOnFailure((solution.GetProjectEnum(
(uint)(__VSENUMPROJFLAGS.EPF_MATCHTYPE | __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION),
ref guid,
out hierarchies)));
IVsHierarchy[] hierarchy = new IVsHierarchy[1];
uint fetched;
while (ErrorHandler.Succeeded(hierarchies.Next(1, hierarchy, out fetched)) && fetched == 1) {
var project = hierarchy[0] as IVsProject;
if (project != null) {
yield return project;
}
}
}
internal static IEnumerable<PythonProjectNode> EnumerateLoadedPythonProjects(this IVsSolution solution) {
return EnumerateLoadedProjects(solution)
.Select(p => p.GetPythonProject())
.Where(p => p != null);
}
public static IPythonProject AsPythonProject(this IVsProject project) {
return ((IVsHierarchy)project).GetProject().GetCommonProject() as PythonProjectNode;
}
public static IPythonProject AsPythonProject(this EnvDTE.Project project) {
return project.GetCommonProject() as PythonProjectNode;
}
internal static PythonProjectNode GetPythonProject(this IVsProject project) {
return ((IVsHierarchy)project).GetProject().GetCommonProject() as PythonProjectNode;
}
internal static PythonProjectNode GetPythonProject(this EnvDTE.Project project) {
return project.GetCommonProject() as PythonProjectNode;
}
/// <summary>
/// Gets the analysis entry for the given view and buffer.
///
/// For files on disk this is pretty easy - we analyze each file on it's own in a buffer parser.
/// Therefore we map filename -> analyzer and then get the analysis from teh analyzer. If we
/// determine an analyzer but the file isn't loaded into it for some reason this would return null.
/// We can also apply some policy to buffers depending upon the view that they're hosted in. For
/// example if a buffer is outside of any projects, but hosted in a difference view with a buffer
/// that is in a project, then we'll look in the view that has the project.
///
/// For interactive windows we will use the analyzer that's configured for the window.
/// </summary>
/// <param name="view"></param>
/// <param name="buffer"></param>
/// <param name="provider"></param>
/// <param name="entry"></param>
/// <returns></returns>
internal static bool TryGetAnalysisEntry(this ITextView view, ITextBuffer buffer, IServiceProvider provider, out AnalysisEntry entry) {
IPythonInteractiveIntellisense evaluator;
if ((evaluator = buffer.GetInteractiveWindow()?.Evaluator as IPythonInteractiveIntellisense) != null) {
var analyzer = evaluator.Analyzer;
if (analyzer != null && !string.IsNullOrEmpty(evaluator.AnalysisFilename)) {
entry = analyzer.GetAnalysisEntryFromPath(evaluator.AnalysisFilename);
} else {
entry = null;
}
return entry != null;
}
string path = buffer.GetFilePath();
if (path != null) {
var docTable = (IVsRunningDocumentTable4)provider.GetService(typeof(SVsRunningDocumentTable));
var cookie = VSConstants.VSCOOKIE_NIL;
try {
cookie = docTable.GetDocumentCookie(path);
} catch (ArgumentException) {
// Exception may be raised while VS is shutting down
entry = null;
return false;
}
VsProjectAnalyzer analyzer = null;
if (cookie != VSConstants.VSCOOKIE_NIL) {
IVsHierarchy hierarchy;
uint itemid;
docTable.GetDocumentHierarchyItem(cookie, out hierarchy, out itemid);
if (hierarchy != null) {
var pyProject = hierarchy.GetProject()?.GetPythonProject();
if (pyProject != null) {
analyzer = pyProject.GetAnalyzer();
}
}
}
if (analyzer == null && view != null) {
// We could spin up a new analyzer for non Python projects...
analyzer = view.GetBestAnalyzer(provider);
}
entry = analyzer?.GetAnalysisEntryFromPath(path);
return entry != null;
}
entry = null;
return false;
}
internal static AnalysisEntry GetAnalysisEntry(this FileNode node) {
return ((PythonProjectNode)node.ProjectMgr).GetAnalyzer().GetAnalysisEntryFromPath(node.Url);
}
/// <summary>
/// Gets the best analyzer for this text view, accounting for things like REPL windows and
/// difference windows.
/// </summary>
internal static VsProjectAnalyzer GetBestAnalyzer(this ITextView textView, IServiceProvider serviceProvider) {
// If we have a REPL evaluator we'll use it's analyzer
var evaluator = textView.TextBuffer.GetInteractiveWindow()?.Evaluator as IPythonInteractiveIntellisense;
if (evaluator != null) {
return evaluator.Analyzer;
}
// If we have a difference viewer we'll match the LHS w/ the RHS
var diffService = serviceProvider.GetComponentModel().GetService<IWpfDifferenceViewerFactoryService>();
if (diffService != null) {
var viewer = diffService.TryGetViewerForTextView(textView);
if (viewer != null) {
var entry = GetAnalysisEntry(null, viewer.DifferenceBuffer.LeftBuffer, serviceProvider) ??
GetAnalysisEntry(null, viewer.DifferenceBuffer.RightBuffer, serviceProvider);
if (entry != null) {
return entry.Analyzer;
}
}
}
return serviceProvider.GetPythonToolsService().DefaultAnalyzer;
}
internal static AnalysisEntry GetAnalysisEntry(this ITextView view, ITextBuffer buffer, IServiceProvider provider) {
AnalysisEntry res;
view.TryGetAnalysisEntry(buffer, provider, out res);
return res;
}
/// <summary>
/// Gets an analysis entry for this buffer. This will only succeed if the buffer is a file
/// on disk. It is not able to support things like difference views because we don't know
/// what view this buffer is hosted in. This method should only be used when we don't know
/// the current view for the buffer. Instead calling view.GetAnalysisEntry or view.TryGetAnalysisEntry
/// should be used.
/// </summary>
internal static AnalysisEntry GetAnalysisEntry(this ITextBuffer buffer, IServiceProvider serviceProvider) {
AnalysisEntry res;
TryGetAnalysisEntry(null, buffer, serviceProvider, out res);
return res;
}
internal static PythonProjectNode GetProject(this ITextBuffer buffer, IServiceProvider serviceProvider) {
var path = buffer.GetFilePath();
if (path != null) {
var sln = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
if (sln != null) {
foreach (var proj in sln.EnumerateLoadedPythonProjects()) {
int found;
var priority = new VSDOCUMENTPRIORITY[1];
uint itemId;
ErrorHandler.ThrowOnFailure(proj.IsDocumentInProject(path, out found, priority, out itemId));
if (found != 0) {
return proj;
}
}
}
}
return null;
}
internal static PythonLanguageVersion GetLanguageVersion(this ITextView textView, IServiceProvider serviceProvider) {
var evaluator = textView.TextBuffer.GetInteractiveWindow().GetPythonEvaluator();
if (evaluator != null) {
return evaluator.LanguageVersion;
}
return textView.GetBestAnalyzer(serviceProvider).LanguageVersion;
}
/// <summary>
/// Returns the active VsProjectAnalyzer being used for where the caret is currently located in this view.
/// </summary>
internal static VsProjectAnalyzer GetAnalyzerAtCaret(this ITextView textView, IServiceProvider serviceProvider) {
var buffer = textView.GetPythonBufferAtCaret();
if (buffer != null) {
return textView.GetAnalysisEntry(buffer, serviceProvider)?.Analyzer;
}
return null;
}
/// <summary>
/// Returns the AnalysisEntry being used for where the caret is currently located in this view.
///
/// Returns null if the caret isn't in Python code or an analysis doesn't exist for some reason.
/// </summary>
internal static AnalysisEntry GetAnalysisAtCaret(this ITextView textView, IServiceProvider serviceProvider) {
var buffer = textView.GetPythonBufferAtCaret();
if (buffer != null) {
return textView.GetAnalysisEntry(buffer, serviceProvider);
}
return null;
}
/// <summary>
/// Returns the ITextBuffer whose content type is Python for the current caret position in the text view.
///
/// Returns null if the caret isn't in a Python buffer.
/// </summary>
internal static ITextBuffer GetPythonBufferAtCaret(this ITextView textView) {
return GetPythonCaret(textView)?.Snapshot.TextBuffer;
}
/// <summary>
/// Gets the point where the caret is currently located in a Python buffer, or null if the caret
/// isn't currently positioned in a Python buffer.
/// </summary>
internal static SnapshotPoint? GetPythonCaret(this ITextView textView) {
return textView.BufferGraph.MapDownToFirstMatch(
textView.Caret.Position.BufferPosition,
PointTrackingMode.Positive,
EditorExtensions.IsPythonContent,
PositionAffinity.Successor
);
}
/// <summary>
/// Gets the current selection in a text view mapped down to the Python buffer(s).
/// </summary>
internal static NormalizedSnapshotSpanCollection GetPythonSelection(this ITextView textView) {
return textView.BufferGraph.MapDownToFirstMatch(
textView.Selection.StreamSelectionSpan.SnapshotSpan,
SpanTrackingMode.EdgeInclusive,
EditorExtensions.IsPythonContent
);
}
/// <summary>
/// Gets the Python project node associatd with the buffer where the caret is located.
///
/// This maps down to the current Python buffer, determines its filename, and then resolves
/// that filename back to the project.
/// </summary>
internal static PythonProjectNode GetProjectAtCaret(this ITextView textView, IServiceProvider serviceProvider) {
var point = textView.BufferGraph.MapDownToFirstMatch(
textView.Caret.Position.BufferPosition,
PointTrackingMode.Positive,
EditorExtensions.IsPythonContent,
PositionAffinity.Successor
);
if (point != null) {
var filename = point.Value.Snapshot.TextBuffer.GetFilePath();
return GetProjectFromFile(serviceProvider, filename);
}
return null;
}
internal static PythonProjectNode GetProjectFromFile(this IServiceProvider serviceProvider, string filename) {
var docTable = serviceProvider.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable4;
var cookie = docTable.GetDocumentCookie(filename);
if (cookie != VSConstants.VSCOOKIE_NIL) {
IVsHierarchy hierarchy;
uint itemid;
docTable.GetDocumentHierarchyItem(cookie, out hierarchy, out itemid);
var project = hierarchy.GetProject();
if (project != null) {
return project.GetPythonProject();
}
object projectObj;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_ExtObject, out projectObj));
return (projectObj as EnvDTE.Project)?.GetPythonProject();
}
return null;
}
internal static ITrackingSpan GetCaretSpan(this ITextView view) {
var caretPoint = view.GetPythonCaret();
Debug.Assert(caretPoint != null);
var snapshot = caretPoint.Value.Snapshot;
var caretPos = caretPoint.Value.Position;
// fob(
// ^
// +--- Caret here
//
// We want to lookup fob, not fob(
//
ITrackingSpan span;
if (caretPos != snapshot.Length) {
string curChar = snapshot.GetText(caretPos, 1);
if (!IsIdentifierChar(curChar[0]) && caretPos > 0) {
string prevChar = snapshot.GetText(caretPos - 1, 1);
if (IsIdentifierChar(prevChar[0])) {
caretPos--;
}
}
span = snapshot.CreateTrackingSpan(
caretPos,
1,
SpanTrackingMode.EdgeInclusive
);
} else {
span = snapshot.CreateTrackingSpan(
caretPos,
0,
SpanTrackingMode.EdgeInclusive
);
}
return span;
}
private static bool IsIdentifierChar(char curChar) {
return Char.IsLetterOrDigit(curChar) || curChar == '_';
}
/// <summary>
/// Reads a string from the socket which is encoded as:
/// U, byte count, bytes
/// A, byte count, ASCII
///
/// Which supports either UTF-8 or ASCII strings.
/// </summary>
internal static string ReadString(this Socket socket) {
byte[] cmd_buffer = new byte[4];
if (socket.Receive(cmd_buffer, 1, SocketFlags.None) == 1) {
bool isUnicode = cmd_buffer[0] == 'U';
if (socket.Receive(cmd_buffer) == 4) {
int filenameLen = BitConverter.ToInt32(cmd_buffer, 0);
byte[] buffer = new byte[filenameLen];
if (filenameLen != 0) {
int bytesRead = 0;
do {
bytesRead += socket.Receive(buffer, bytesRead, filenameLen - bytesRead, SocketFlags.None);
} while (bytesRead != filenameLen);
}
if (isUnicode) {
return Encoding.UTF8.GetString(buffer);
} else {
char[] chars = new char[buffer.Length];
for (int i = 0; i < buffer.Length; i++) {
chars[i] = (char)buffer[i];
}
return new string(chars);
}
} else {
Debug.Assert(false, "Failed to read length");
}
} else {
Debug.Assert(false, "Failed to read unicode/ascii byte");
}
return null;
}
internal static int ReadInt(this Socket socket) {
byte[] cmd_buffer = new byte[4];
if (socket.Receive(cmd_buffer) == 4) {
return BitConverter.ToInt32(cmd_buffer, 0);
}
throw new InvalidOperationException();
}
internal static VsProjectAnalyzer GetAnalyzer(this ITextBuffer buffer, IServiceProvider serviceProvider) {
var analysisEntry = GetAnalysisEntry(null, buffer, serviceProvider);
if (analysisEntry != null) {
return analysisEntry.Analyzer;
}
VsProjectAnalyzer analyzer;
// exists for tests where we don't run in VS and for the existing changes preview
if (buffer.Properties.TryGetProperty(typeof(VsProjectAnalyzer), out analyzer)) {
return analyzer;
}
return serviceProvider.GetPythonToolsService().DefaultAnalyzer;
}
internal static PythonToolsService GetPythonToolsService(this IServiceProvider serviceProvider) {
if (serviceProvider == null) {
return null;
}
var pyService = (PythonToolsService)serviceProvider.GetService(typeof(PythonToolsService));
if (pyService == null) {
var shell = (IVsShell)serviceProvider.GetService(typeof(SVsShell));
var pkgGuid = GuidList.guidPythonToolsPackage;
IVsPackage pkg;
if (!ErrorHandler.Succeeded(shell.IsPackageLoaded(ref pkgGuid, out pkg)) && pkg != null) {
Debug.Fail("Python Tools Package was loaded but could not get service");
return null;
}
var hr = shell.LoadPackage(ref pkgGuid, out pkg);
if (!ErrorHandler.Succeeded(hr)) {
Debug.Fail("Failed to load Python Tools Package: 0x{0:X08}".FormatUI(hr));
ErrorHandler.ThrowOnFailure(hr);
}
pyService = (PythonToolsService)serviceProvider.GetService(typeof(PythonToolsService));
}
return pyService;
}
internal static IComponentModel GetComponentModel(this IServiceProvider serviceProvider) {
if (serviceProvider == null) {
return null;
}
return (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
}
public static string BrowseForFileSave(this IServiceProvider provider, IntPtr owner, string filter, string initialPath = null) {
if (string.IsNullOrEmpty(initialPath)) {
initialPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar;
}
IVsUIShell uiShell = provider.GetService(typeof(SVsUIShell)) as IVsUIShell;
if (null == uiShell) {
using (var sfd = new System.Windows.Forms.SaveFileDialog()) {
sfd.AutoUpgradeEnabled = true;
sfd.Filter = filter;
sfd.FileName = Path.GetFileName(initialPath);
sfd.InitialDirectory = Path.GetDirectoryName(initialPath);
DialogResult result;
if (owner == IntPtr.Zero) {
result = sfd.ShowDialog();
} else {
result = sfd.ShowDialog(NativeWindow.FromHandle(owner));
}
if (result == DialogResult.OK) {
return sfd.FileName;
} else {
return null;
}
}
}
if (owner == IntPtr.Zero) {
ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner));
}
VSSAVEFILENAMEW[] saveInfo = new VSSAVEFILENAMEW[1];
saveInfo[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSSAVEFILENAMEW));
saveInfo[0].pwzFilter = filter.Replace('|', '\0') + "\0";
saveInfo[0].hwndOwner = owner;
saveInfo[0].nMaxFileName = 260;
var pFileName = Marshal.AllocCoTaskMem(520);
saveInfo[0].pwzFileName = pFileName;
saveInfo[0].pwzInitialDir = Path.GetDirectoryName(initialPath);
var nameArray = (Path.GetFileName(initialPath) + "\0").ToCharArray();
Marshal.Copy(nameArray, 0, pFileName, nameArray.Length);
try {
int hr = uiShell.GetSaveFileNameViaDlg(saveInfo);
if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED) {
return null;
}
ErrorHandler.ThrowOnFailure(hr);
return Marshal.PtrToStringAuto(saveInfo[0].pwzFileName);
} finally {
if (pFileName != IntPtr.Zero) {
Marshal.FreeCoTaskMem(pFileName);
}
}
}
public static string BrowseForFileOpen(this IServiceProvider serviceProvider, IntPtr owner, string filter, string initialPath = null) {
if (string.IsNullOrEmpty(initialPath)) {
initialPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar;
}
IVsUIShell uiShell = serviceProvider.GetService(typeof(SVsUIShell)) as IVsUIShell;
if (null == uiShell) {
using (var sfd = new System.Windows.Forms.OpenFileDialog()) {
sfd.AutoUpgradeEnabled = true;
sfd.Filter = filter;
sfd.FileName = Path.GetFileName(initialPath);
sfd.InitialDirectory = Path.GetDirectoryName(initialPath);
DialogResult result;
if (owner == IntPtr.Zero) {
result = sfd.ShowDialog();
} else {
result = sfd.ShowDialog(NativeWindow.FromHandle(owner));
}
if (result == DialogResult.OK) {
return sfd.FileName;
} else {
return null;
}
}
}
if (owner == IntPtr.Zero) {
ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner));
}
VSOPENFILENAMEW[] openInfo = new VSOPENFILENAMEW[1];
openInfo[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW));
openInfo[0].pwzFilter = filter.Replace('|', '\0') + "\0";
openInfo[0].hwndOwner = owner;
openInfo[0].nMaxFileName = 260;
var pFileName = Marshal.AllocCoTaskMem(520);
openInfo[0].pwzFileName = pFileName;
openInfo[0].pwzInitialDir = Path.GetDirectoryName(initialPath);
var nameArray = (Path.GetFileName(initialPath) + "\0").ToCharArray();
Marshal.Copy(nameArray, 0, pFileName, nameArray.Length);
try {
int hr = uiShell.GetOpenFileNameViaDlg(openInfo);
if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED) {
return null;
}
ErrorHandler.ThrowOnFailure(hr);
return Marshal.PtrToStringAuto(openInfo[0].pwzFileName);
} finally {
if (pFileName != IntPtr.Zero) {
Marshal.FreeCoTaskMem(pFileName);
}
}
}
internal static IContentType GetPythonContentType(this IServiceProvider provider) {
return provider.GetComponentModel().GetService<IContentTypeRegistryService>().GetContentType(PythonCoreConstants.ContentType);
}
internal static EnvDTE.DTE GetDTE(this IServiceProvider provider) {
return (EnvDTE.DTE)provider.GetService(typeof(EnvDTE.DTE));
}
internal static SVsShellDebugger GetShellDebugger(this IServiceProvider provider) {
return (SVsShellDebugger)provider.GetService(typeof(SVsShellDebugger));
}
internal static async System.Threading.Tasks.Task RefreshVariableViews(this IServiceProvider serviceProvider) {
EnvDTE.Debugger debugger = serviceProvider.GetDTE().Debugger;
AD7Engine engine = AD7Engine.GetEngineForProcess(debugger.CurrentProcess);
if (engine != null) {
await engine.RefreshThreadFrames(debugger.CurrentThread.ID);
var vsDebugger = (IDebugRefreshNotification140)serviceProvider.GetShellDebugger();
if (vsDebugger != null) {
// Passing fCallstackFormattingAffected = TRUE to OnExpressionEvaluationRefreshRequested to force refresh
vsDebugger.OnExpressionEvaluationRefreshRequested(1);
}
}
}
internal static SolutionEventsListener GetSolutionEvents(this IServiceProvider serviceProvider) {
return (SolutionEventsListener)serviceProvider.GetService(typeof(SolutionEventsListener));
}
internal static void GlobalInvoke(this IServiceProvider serviceProvider, CommandID cmdID) {
OleMenuCommandService mcs = serviceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
mcs.GlobalInvoke(cmdID);
}
internal static void GlobalInvoke(this IServiceProvider serviceProvider, CommandID cmdID, object arg) {
OleMenuCommandService mcs = serviceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
mcs.GlobalInvoke(cmdID, arg);
}
internal static void ShowOptionsPage(this IServiceProvider serviceProvider, Type optionsPageType) {
CommandID cmd = new CommandID(VSConstants.GUID_VSStandardCommandSet97, VSConstants.cmdidToolsOptions);
serviceProvider.GlobalInvoke(
cmd,
optionsPageType.GUID.ToString()
);
}
internal static void ShowInterpreterList(this IServiceProvider serviceProvider) {
serviceProvider.ShowWindowPane(typeof(InterpreterListToolWindow), true);
}
internal static void ShowWindowPane(this IServiceProvider serviceProvider, Type windowPane, bool focus) {
var toolWindowService = (IPythonToolsToolWindowService)serviceProvider.GetService(typeof(IPythonToolsToolWindowService));
toolWindowService.ShowWindowPane(windowPane, focus);
}
public static string BrowseForDirectory(this IServiceProvider provider, IntPtr owner, string initialDirectory = null) {
IVsUIShell uiShell = provider.GetService(typeof(SVsUIShell)) as IVsUIShell;
if (null == uiShell) {
using (var ofd = new FolderBrowserDialog()) {
ofd.RootFolder = Environment.SpecialFolder.Desktop;
ofd.ShowNewFolderButton = false;
DialogResult result;
if (owner == IntPtr.Zero) {
result = ofd.ShowDialog();
} else {
result = ofd.ShowDialog(NativeWindow.FromHandle(owner));
}
if (result == DialogResult.OK) {
return ofd.SelectedPath;
} else {
return null;
}
}
}
if (owner == IntPtr.Zero) {
ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner));
}
VSBROWSEINFOW[] browseInfo = new VSBROWSEINFOW[1];
browseInfo[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSBROWSEINFOW));
browseInfo[0].pwzInitialDir = initialDirectory;
browseInfo[0].hwndOwner = owner;
browseInfo[0].nMaxDirName = 260;
IntPtr pDirName = Marshal.AllocCoTaskMem(520);
browseInfo[0].pwzDirName = pDirName;
try {
int hr = uiShell.GetDirectoryViaBrowseDlg(browseInfo);
if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED) {
return null;
}
ErrorHandler.ThrowOnFailure(hr);
return Marshal.PtrToStringAuto(browseInfo[0].pwzDirName);
} finally {
if (pDirName != IntPtr.Zero) {
Marshal.FreeCoTaskMem(pDirName);
}
}
}
/// <summary>
/// Checks to see if this is a REPL buffer starting with a extensible command such as %cls, %load, etc...
/// </summary>
internal static bool IsReplBufferWithCommand(this ITextSnapshot snapshot) {
return snapshot.TextBuffer.Properties.ContainsProperty(typeof(IInteractiveEvaluator)) &&
snapshot.Length != 0 &&
(snapshot[0] == '%' || snapshot[0] == '$'); // IPython and normal repl commands
}
internal static bool IsAnalysisCurrent(this IPythonInterpreterFactory factory) {
var interpFact = factory as IPythonInterpreterFactoryWithDatabase;
if (interpFact != null) {
return interpFact.IsCurrent;
}
return true;
}
internal static bool IsOpenGrouping(this ClassificationSpan span) {
return span.ClassificationType.IsOfType(PythonPredefinedClassificationTypeNames.Grouping) &&
span.Span.Length == 1 &&
(span.Span.GetText() == "{" || span.Span.GetText() == "[" || span.Span.GetText() == "(");
}
internal static bool IsCloseGrouping(this ClassificationSpan span) {
return span.ClassificationType.IsOfType(PythonPredefinedClassificationTypeNames.Grouping) &&
span.Span.Length == 1 &&
(span.Span.GetText() == "}" || span.Span.GetText() == "]" || span.Span.GetText() == ")");
}
internal static T Pop<T>(this List<T> list) {
if (list.Count == 0) {
throw new InvalidOperationException();
}
var res = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
return res;
}
internal static T Peek<T>(this List<T> list) {
if (list.Count == 0) {
throw new InvalidOperationException();
}
return list[list.Count - 1];
}
internal static System.Threading.Tasks.Task StartNew(this TaskScheduler scheduler, Action func) {
return System.Threading.Tasks.Task.Factory.StartNew(func, default(CancellationToken), TaskCreationOptions.None, scheduler);
}
internal static int GetStartIncludingIndentation(this Node self, PythonAst ast) {
return self.StartIndex - (self.GetIndentationLevel(ast) ?? "").Length;
}
internal static string LimitLines(
this string str,
int maxLines = 30,
int charsPerLine = 200,
bool ellipsisAtEnd = true,
bool stopAtFirstBlankLine = false
) {
if (string.IsNullOrEmpty(str)) {
return str;
}
int lineCount = 0;
var prettyPrinted = new StringBuilder();
bool wasEmpty = true;
using (var reader = new StringReader(str)) {
for (var line = reader.ReadLine(); line != null && lineCount < maxLines; line = reader.ReadLine()) {
if (string.IsNullOrWhiteSpace(line)) {
if (wasEmpty) {
continue;
}
wasEmpty = true;
if (stopAtFirstBlankLine) {
lineCount = maxLines;
break;
}
lineCount += 1;
prettyPrinted.AppendLine();
} else {
wasEmpty = false;
lineCount += (line.Length / charsPerLine) + 1;
prettyPrinted.AppendLine(line);
}
}
}
if (ellipsisAtEnd && lineCount >= maxLines) {
prettyPrinted.AppendLine("...");
}
return prettyPrinted.ToString().Trim();
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.Collections.Generic;
using System.Runtime;
using System.Runtime.Serialization;
using System.Security;
using System.Reflection;
using System.ServiceModel;
using System.Xml;
#if USE_REFEMIT
public class JsonDataContract
#else
class JsonDataContract
#endif
{
[Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization."
+ "Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
JsonDataContractCriticalHelper helper;
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
protected JsonDataContract(DataContract traditionalDataContract)
{
this.helper = new JsonDataContractCriticalHelper(traditionalDataContract);
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
protected JsonDataContract(JsonDataContractCriticalHelper helper)
{
this.helper = helper;
}
internal virtual string TypeName
{
get { return null; }
}
protected JsonDataContractCriticalHelper Helper
{
[Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization."
+ "Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
get { return helper; }
}
protected DataContract TraditionalDataContract
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical TraditionalDataContract from the helper.",
Safe = "TraditionalDataContract only needs to be protected for write.")]
[SecuritySafeCritical]
get { return this.helper.TraditionalDataContract; }
}
Dictionary<XmlQualifiedName, DataContract> KnownDataContracts
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical KnownDataContracts from the helper.",
Safe = "KnownDataContracts only needs to be protected for write.")]
[SecuritySafeCritical]
get { return this.helper.KnownDataContracts; }
}
[Fx.Tag.SecurityNote(Critical = "Fetches the critical JsonDataContract from the helper.",
Safe = "JsonDataContract only needs to be protected for write.")]
[SecuritySafeCritical]
public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract)
{
return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract);
}
public object ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
PushKnownDataContracts(context);
object deserializedObject = ReadJsonValueCore(jsonReader, context);
PopKnownDataContracts(context);
return deserializedObject;
}
public virtual object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
return TraditionalDataContract.ReadXmlValue(jsonReader, context);
}
public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
{
PushKnownDataContracts(context);
WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle);
PopKnownDataContracts(context);
}
public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
{
TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context);
}
protected static object HandleReadValue(object obj, XmlObjectSerializerReadContext context)
{
context.AddNewObject(obj);
return obj;
}
protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader)
{
while (reader.MoveToAttribute(JsonGlobals.typeString) && (reader.Value == JsonGlobals.nullString))
{
reader.Skip();
reader.MoveToElement();
return true;
}
reader.MoveToElement();
return false;
}
protected void PopKnownDataContracts(XmlObjectSerializerContext context)
{
if (KnownDataContracts != null)
{
context.scopedKnownTypes.Pop();
}
}
protected void PushKnownDataContracts(XmlObjectSerializerContext context)
{
if (KnownDataContracts != null)
{
context.scopedKnownTypes.Push(KnownDataContracts);
}
}
[Fx.Tag.SecurityNote(Critical = "Holds all state used for (de)serializing types."
+ "Since the data is cached statically, we lock down access to it.")]
#pragma warning disable 618 // have not moved to the v4 security model yet
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
#if USE_REFEMIT
public class JsonDataContractCriticalHelper
#else
internal class JsonDataContractCriticalHelper
#endif
{
static object cacheLock = new object();
static object createDataContractLock = new object();
static JsonDataContract[] dataContractCache = new JsonDataContract[32];
static int dataContractID = 0;
static TypeHandleRef typeHandleRef = new TypeHandleRef();
static Dictionary<TypeHandleRef, IntRef> typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer());
Dictionary<XmlQualifiedName, DataContract> knownDataContracts;
DataContract traditionalDataContract;
string typeName;
internal JsonDataContractCriticalHelper(DataContract traditionalDataContract)
{
this.traditionalDataContract = traditionalDataContract;
AddCollectionItemContractsToKnownDataContracts();
this.typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value));
}
internal Dictionary<XmlQualifiedName, DataContract> KnownDataContracts
{
get { return this.knownDataContracts; }
}
internal DataContract TraditionalDataContract
{
get { return this.traditionalDataContract; }
}
internal virtual string TypeName
{
get { return this.typeName; }
}
public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract)
{
int id = JsonDataContractCriticalHelper.GetId(traditionalDataContract.UnderlyingType.TypeHandle);
JsonDataContract dataContract = dataContractCache[id];
if (dataContract == null)
{
dataContract = CreateJsonDataContract(id, traditionalDataContract);
dataContractCache[id] = dataContract;
}
return dataContract;
}
internal static int GetId(RuntimeTypeHandle typeHandle)
{
lock (cacheLock)
{
IntRef id;
typeHandleRef.Value = typeHandle;
if (!typeToIDCache.TryGetValue(typeHandleRef, out id))
{
int value = dataContractID++;
if (value >= dataContractCache.Length)
{
int newSize = (value < Int32.MaxValue / 2) ? value * 2 : Int32.MaxValue;
if (newSize <= value)
{
Fx.Assert("DataContract cache overflow");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(System.Runtime.Serialization.SR.GetString(System.Runtime.Serialization.SR.DataContractCacheOverflow)));
}
Array.Resize<JsonDataContract>(ref dataContractCache, newSize);
}
id = new IntRef(value);
try
{
typeToIDCache.Add(new TypeHandleRef(typeHandle), id);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
}
}
return id.Value;
}
}
static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract)
{
lock (createDataContractLock)
{
JsonDataContract dataContract = dataContractCache[id];
if (dataContract == null)
{
Type traditionalDataContractType = traditionalDataContract.GetType();
if (traditionalDataContractType == typeof(ObjectDataContract))
{
dataContract = new JsonObjectDataContract(traditionalDataContract);
}
else if (traditionalDataContractType == typeof(StringDataContract))
{
dataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(UriDataContract))
{
dataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(QNameDataContract))
{
dataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(ByteArrayDataContract))
{
dataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract);
}
else if (traditionalDataContract.IsPrimitive ||
traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName)
{
dataContract = new JsonDataContract(traditionalDataContract);
}
else if (traditionalDataContractType == typeof(ClassDataContract))
{
dataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(EnumDataContract))
{
dataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract);
}
else if ((traditionalDataContractType == typeof(GenericParameterDataContract)) ||
(traditionalDataContractType == typeof(SpecialTypeDataContract)))
{
dataContract = new JsonDataContract(traditionalDataContract);
}
else if (traditionalDataContractType == typeof(CollectionDataContract))
{
dataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(XmlDataContract))
{
dataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("traditionalDataContract",
SR.GetString(SR.JsonTypeNotSupportedByDataContractJsonSerializer, traditionalDataContract.UnderlyingType));
}
}
return dataContract;
}
}
void AddCollectionItemContractsToKnownDataContracts()
{
if (traditionalDataContract.KnownDataContracts != null)
{
foreach (KeyValuePair<XmlQualifiedName, DataContract> knownDataContract in traditionalDataContract.KnownDataContracts)
{
if (!object.ReferenceEquals(knownDataContract, null))
{
CollectionDataContract collectionDataContract = knownDataContract.Value as CollectionDataContract;
while (collectionDataContract != null)
{
DataContract itemContract = collectionDataContract.ItemContract;
if (knownDataContracts == null)
{
knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>();
}
if (!knownDataContracts.ContainsKey(itemContract.StableName))
{
knownDataContracts.Add(itemContract.StableName, itemContract);
}
if (collectionDataContract.ItemType.IsGenericType
&& collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>))
{
DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetGenericArguments()));
if (!knownDataContracts.ContainsKey(itemDataContract.StableName))
{
knownDataContracts.Add(itemDataContract.StableName, itemDataContract);
}
}
if (!(itemContract is CollectionDataContract))
{
break;
}
collectionDataContract = itemContract as CollectionDataContract;
}
}
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Prism.Regions;
using Prism.Regions.Behaviors;
using Prism.Wpf.Tests.Mocks;
namespace Prism.Wpf.Tests.Regions.Behaviors
{
[TestClass]
public class SelectorItemsSourceSyncRegionBehaviorFixture
{
[TestMethod]
public void CanAttachToSelector()
{
SelectorItemsSourceSyncBehavior behavior = CreateBehavior();
behavior.Attach();
Assert.IsTrue(behavior.IsAttached);
}
[TestMethod]
public void AttachSetsItemsSourceOfSelector()
{
SelectorItemsSourceSyncBehavior behavior = CreateBehavior();
var v1 = new Button();
var v2 = new Button();
behavior.Region.Add(v1);
behavior.Region.Add(v2);
behavior.Attach();
Assert.AreEqual(2, (behavior.HostControl as Selector).Items.Count);
}
[TestMethod]
public void IfViewsHaveSortHintThenViewsAreProperlySorted()
{
SelectorItemsSourceSyncBehavior behavior = CreateBehavior();
var v1 = new MockSortableView1();
var v2 = new MockSortableView2();
var v3 = new MockSortableView3();
behavior.Attach();
behavior.Region.Add(v3);
behavior.Region.Add(v2);
behavior.Region.Add(v1);
Assert.AreEqual(3, (behavior.HostControl as Selector).Items.Count);
Assert.AreSame(v1, (behavior.HostControl as Selector).Items[0]);
Assert.AreSame(v2, (behavior.HostControl as Selector).Items[1]);
Assert.AreSame(v3, (behavior.HostControl as Selector).Items[2]);
}
[TestMethod]
public void SelectionChangedShouldChangeActiveViews()
{
SelectorItemsSourceSyncBehavior behavior = CreateBehavior();
var v1 = new Button();
var v2 = new Button();
behavior.Region.Add(v1);
behavior.Region.Add(v2);
behavior.Attach();
(behavior.HostControl as Selector).SelectedItem = v1;
var activeViews = behavior.Region.ActiveViews;
Assert.AreEqual(1, activeViews.Count());
Assert.AreEqual(v1, activeViews.First());
(behavior.HostControl as Selector).SelectedItem = v2;
Assert.AreEqual(1, activeViews.Count());
Assert.AreEqual(v2, activeViews.First());
}
[TestMethod]
public void ActiveViewChangedShouldChangeSelectedItem()
{
SelectorItemsSourceSyncBehavior behavior = CreateBehavior();
var v1 = new Button();
var v2 = new Button();
behavior.Region.Add(v1);
behavior.Region.Add(v2);
behavior.Attach();
behavior.Region.Activate(v1);
Assert.AreEqual(v1, (behavior.HostControl as Selector).SelectedItem);
behavior.Region.Activate(v2);
Assert.AreEqual(v2, (behavior.HostControl as Selector).SelectedItem);
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void ItemsSourceSetThrows()
{
SelectorItemsSourceSyncBehavior behavior = CreateBehavior();
(behavior.HostControl as Selector).ItemsSource = new[] {new Button()};
behavior.Attach();
}
[TestMethod]
public void ControlWithExistingBindingOnItemsSourceWithNullValueThrows()
{
var behavor = CreateBehavior();
Binding binding = new Binding("Enumerable");
binding.Source = new SimpleModel() { Enumerable = null };
(behavor.HostControl as Selector).SetBinding(ItemsControl.ItemsSourceProperty, binding);
try
{
behavor.Attach();
}
catch (Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(InvalidOperationException));
StringAssert.Contains(ex.Message, "ItemsControl's ItemsSource property is not empty.");
}
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void AddingViewToTwoRegionsThrows()
{
var behavior1 = CreateBehavior();
var behavior2 = CreateBehavior();
behavior1.Attach();
behavior2.Attach();
var v1 = new Button();
behavior1.Region.Add(v1);
behavior2.Region.Add(v1);
}
[TestMethod]
public void ReactivatingViewAddsViewToTab()
{
var behavior1 = CreateBehavior();
behavior1.Attach();
var v1 = new Button();
var v2 = new Button();
behavior1.Region.Add(v1);
behavior1.Region.Add(v2);
behavior1.Region.Activate(v1);
Assert.IsTrue(behavior1.Region.ActiveViews.First() == v1);
behavior1.Region.Activate(v2);
Assert.IsTrue(behavior1.Region.ActiveViews.First() == v2);
behavior1.Region.Activate(v1);
Assert.IsTrue(behavior1.Region.ActiveViews.First() == v1);
}
[TestMethod]
public void ShouldAllowMultipleSelectedItemsForListBox()
{
var behavior1 = CreateBehavior();
ListBox listBox = new ListBox();
listBox.SelectionMode = SelectionMode.Multiple;
behavior1.HostControl = listBox;
behavior1.Attach();
var v1 = new Button();
var v2 = new Button();
behavior1.Region.Add(v1);
behavior1.Region.Add(v2);
listBox.SelectedItems.Add(v1);
listBox.SelectedItems.Add(v2);
Assert.IsTrue(behavior1.Region.ActiveViews.Contains(v1));
Assert.IsTrue(behavior1.Region.ActiveViews.Contains(v2));
}
private SelectorItemsSourceSyncBehavior CreateBehavior()
{
Region region = new Region();
Selector selector = new TabControl();
var behavior = new SelectorItemsSourceSyncBehavior();
behavior.HostControl = selector;
behavior.Region = region;
return behavior;
}
private class SimpleModel
{
public IEnumerable Enumerable { get; set; }
}
}
}
| |
using System;
namespace UnityEngine.PostProcessing
{
[Serializable]
public class AntialiasingModel : PostProcessingModel
{
public enum Method
{
Fxaa,
Taa
}
// Most settings aren't exposed to the user anymore, presets are enough. Still, I'm leaving
// the tooltip attributes in case an user wants to customize each preset.
#region FXAA Settings
public enum FxaaPreset
{
ExtremePerformance,
Performance,
Default,
Quality,
ExtremeQuality
}
[Serializable]
public struct FxaaQualitySettings
{
[Tooltip("The amount of desired sub-pixel aliasing removal. Effects the sharpeness of the output.")]
[Range(0f, 1f)]
public float subpixelAliasingRemovalAmount;
[Tooltip("The minimum amount of local contrast required to qualify a region as containing an edge.")]
[Range(0.063f, 0.333f)]
public float edgeDetectionThreshold;
[Tooltip("Local contrast adaptation value to disallow the algorithm from executing on the darker regions.")]
[Range(0f, 0.0833f)]
public float minimumRequiredLuminance;
public static FxaaQualitySettings[] presets =
{
// ExtremePerformance
new FxaaQualitySettings
{
subpixelAliasingRemovalAmount = 0f,
edgeDetectionThreshold = 0.333f,
minimumRequiredLuminance = 0.0833f
},
// Performance
new FxaaQualitySettings
{
subpixelAliasingRemovalAmount = 0.25f,
edgeDetectionThreshold = 0.25f,
minimumRequiredLuminance = 0.0833f
},
// Default
new FxaaQualitySettings
{
subpixelAliasingRemovalAmount = 0.75f,
edgeDetectionThreshold = 0.166f,
minimumRequiredLuminance = 0.0833f
},
// Quality
new FxaaQualitySettings
{
subpixelAliasingRemovalAmount = 1f,
edgeDetectionThreshold = 0.125f,
minimumRequiredLuminance = 0.0625f
},
// ExtremeQuality
new FxaaQualitySettings
{
subpixelAliasingRemovalAmount = 1f,
edgeDetectionThreshold = 0.063f,
minimumRequiredLuminance = 0.0312f
}
};
}
[Serializable]
public struct FxaaConsoleSettings
{
[Tooltip("The amount of spread applied to the sampling coordinates while sampling for subpixel information.")]
[Range(0.33f, 0.5f)]
public float subpixelSpreadAmount;
[Tooltip("This value dictates how sharp the edges in the image are kept; a higher value implies sharper edges.")]
[Range(2f, 8f)]
public float edgeSharpnessAmount;
[Tooltip("The minimum amount of local contrast required to qualify a region as containing an edge.")]
[Range(0.125f, 0.25f)]
public float edgeDetectionThreshold;
[Tooltip("Local contrast adaptation value to disallow the algorithm from executing on the darker regions.")]
[Range(0.04f, 0.06f)]
public float minimumRequiredLuminance;
public static FxaaConsoleSettings[] presets =
{
// ExtremePerformance
new FxaaConsoleSettings
{
subpixelSpreadAmount = 0.33f,
edgeSharpnessAmount = 8f,
edgeDetectionThreshold = 0.25f,
minimumRequiredLuminance = 0.06f
},
// Performance
new FxaaConsoleSettings
{
subpixelSpreadAmount = 0.33f,
edgeSharpnessAmount = 8f,
edgeDetectionThreshold = 0.125f,
minimumRequiredLuminance = 0.06f
},
// Default
new FxaaConsoleSettings
{
subpixelSpreadAmount = 0.5f,
edgeSharpnessAmount = 8f,
edgeDetectionThreshold = 0.125f,
minimumRequiredLuminance = 0.05f
},
// Quality
new FxaaConsoleSettings
{
subpixelSpreadAmount = 0.5f,
edgeSharpnessAmount = 4f,
edgeDetectionThreshold = 0.125f,
minimumRequiredLuminance = 0.04f
},
// ExtremeQuality
new FxaaConsoleSettings
{
subpixelSpreadAmount = 0.5f,
edgeSharpnessAmount = 2f,
edgeDetectionThreshold = 0.125f,
minimumRequiredLuminance = 0.04f
}
};
}
[Serializable]
public struct FxaaSettings
{
public FxaaPreset preset;
public static FxaaSettings defaultSettings
{
get
{
return new FxaaSettings
{
preset = FxaaPreset.Default
};
}
}
}
#endregion
#region TAA Settings
[Serializable]
public struct TaaSettings
{
[Tooltip("The diameter (in texels) inside which jitter samples are spread. Smaller values result in crisper but more aliased output, while larger values result in more stable but blurrier output.")]
[Range(0.1f, 1f)]
public float jitterSpread;
[Tooltip("Controls the amount of sharpening applied to the color buffer.")]
[Range(0f, 3f)]
public float sharpen;
[Tooltip("The blend coefficient for a stationary fragment. Controls the percentage of history sample blended into the final color.")]
[Range(0f, 1f)]
public float stationaryBlending;
[Tooltip("The blend coefficient for a fragment with significant motion. Controls the percentage of history sample blended into the final color.")]
[Range(0f, 1f)]
public float motionBlending;
public static TaaSettings defaultSettings
{
get
{
return new TaaSettings
{
jitterSpread = 0.75f,
sharpen = 0.3f,
stationaryBlending = 0.95f,
motionBlending = 0.85f
};
}
}
}
#endregion
[Serializable]
public struct Settings
{
public Method method;
public FxaaSettings fxaaSettings;
public TaaSettings taaSettings;
public static Settings defaultSettings
{
get
{
return new Settings
{
method = Method.Fxaa,
fxaaSettings = FxaaSettings.defaultSettings,
taaSettings = TaaSettings.defaultSettings
};
}
}
}
[SerializeField]
Settings m_Settings = Settings.defaultSettings;
public Settings settings
{
get { return m_Settings; }
set { m_Settings = value; }
}
public override void Reset()
{
m_Settings = Settings.defaultSettings;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using AutoRest.Core.Logging;
using AutoRest.Core.Properties;
using AutoRest.Core.Utilities;
using Newtonsoft.Json;
namespace AutoRest.Core.Extensibility
{
public static class ExtensionsLoader
{
/// <summary>
/// The name of the AutoRest configuration file.
/// </summary>
internal const string ConfigurationFileName = "AutoRest.json";
/// <summary>
/// Gets the code generator specified in the provided Settings.
/// </summary>
/// <param name="settings">The code generation settings</param>
/// <returns>Code generator specified in Settings.CodeGenerator</returns>
public static CodeGenerator GetCodeGenerator(Settings settings)
{
Logger.LogInfo(Resources.InitializingCodeGenerator);
if (settings == null)
{
throw new ArgumentNullException("settings");
}
if (string.IsNullOrEmpty(settings.CodeGenerator))
{
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture,
Resources.ParameterValueIsMissing, "CodeGenerator"));
}
CodeGenerator codeGenerator = null;
string configurationFile = GetConfigurationFileContent(settings);
if (configurationFile != null)
{
try
{
var config = JsonConvert.DeserializeObject<AutoRestConfiguration>(configurationFile);
codeGenerator = LoadTypeFromAssembly<CodeGenerator>(config.CodeGenerators, settings.CodeGenerator,
settings);
codeGenerator.PopulateSettings(settings.CustomSettings);
}
catch (Exception ex)
{
throw ErrorManager.CreateError(ex, Resources.ErrorParsingConfig);
}
}
else
{
throw ErrorManager.CreateError(Resources.ConfigurationFileNotFound);
}
Logger.LogInfo(Resources.GeneratorInitialized,
settings.CodeGenerator,
codeGenerator.GetType().Assembly.GetName().Version);
return codeGenerator;
}
/// <summary>
/// Gets the modeler specified in the provided Settings.
/// </summary>
/// <param name="settings">The code generation settings</param>
/// <returns>Modeler specified in Settings.Modeler</returns>
public static Modeler GetModeler(Settings settings)
{
Logger.LogInfo(Resources.InitializingModeler);
if (settings == null)
{
throw new ArgumentNullException("settings", "settings or settings.Modeler cannot be null.");
}
if (string.IsNullOrEmpty(settings.Modeler))
{
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture,
Resources.ParameterValueIsMissing, "Modeler"));
}
Modeler modeler = null;
string configurationFile = GetConfigurationFileContent(settings);
if (configurationFile != null)
{
try
{
var config = JsonConvert.DeserializeObject<AutoRestConfiguration>(configurationFile);
modeler = LoadTypeFromAssembly<Modeler>(config.Modelers, settings.Modeler, settings);
Settings.PopulateSettings(modeler, settings.CustomSettings);
}
catch (Exception ex)
{
throw ErrorManager.CreateError(ex, Resources.ErrorParsingConfig);
}
}
else
{
throw ErrorManager.CreateError(Resources.ConfigurationFileNotFound);
}
Logger.LogInfo(Resources.ModelerInitialized,
settings.Modeler,
modeler.GetType().Assembly.GetName().Version);
return modeler;
}
public static string GetConfigurationFileContent(Settings settings)
{
if (settings == null)
{
throw new ArgumentNullException("settings");
}
if (settings.FileSystem == null)
{
throw new InvalidOperationException("FileSystem is null in settings.");
}
string path = ConfigurationFileName;
if (!settings.FileSystem.FileExists(path))
{
path = Path.Combine(Directory.GetCurrentDirectory(), ConfigurationFileName);
}
if (!settings.FileSystem.FileExists(path))
{
path = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof (Settings)).Location),
ConfigurationFileName);
}
if (!settings.FileSystem.FileExists(path))
{
return null;
}
return settings.FileSystem.ReadFileAsText(path);
}
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")]
public static T LoadTypeFromAssembly<T>(IDictionary<string, AutoRestProviderConfiguration> section,
string key, Settings settings)
{
T instance = default(T);
if (settings != null && section != null && !section.IsNullOrEmpty() && section.ContainsKey(key))
{
string fullTypeName = section[key].TypeName;
if (string.IsNullOrEmpty(fullTypeName))
{
throw ErrorManager.CreateError(Resources.ExtensionNotFound, key);
}
int indexOfComma = fullTypeName.IndexOf(',');
if (indexOfComma < 0)
{
throw ErrorManager.CreateError(Resources.TypeShouldBeAssemblyQualified, fullTypeName);
}
string typeName = fullTypeName.Substring(0, indexOfComma).Trim();
string assemblyName = fullTypeName.Substring(indexOfComma + 1).Trim();
try
{
Assembly loadedAssembly;
try
{
loadedAssembly = Assembly.Load(assemblyName);
}
catch(FileNotFoundException)
{
loadedAssembly = Assembly.LoadFrom(assemblyName + ".dll");
if(loadedAssembly == null)
{
throw;
}
}
Type loadedType = loadedAssembly.GetTypes()
.Single(t => string.IsNullOrEmpty(typeName) ||
t.Name == typeName ||
t.FullName == typeName);
instance = (T) loadedType.GetConstructor(
new[] {typeof (Settings)}).Invoke(new object[] {settings});
if (!section[key].Settings.IsNullOrEmpty())
{
foreach (var settingFromFile in section[key].Settings)
{
settings.CustomSettings[settingFromFile.Key] = settingFromFile.Value;
}
}
}
catch (Exception ex)
{
throw ErrorManager.CreateError(ex, Resources.ErrorLoadingAssembly, key, ex.Message);
}
return instance;
}
throw ErrorManager.CreateError(Resources.ExtensionNotFound, key);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LoadBalancersOperations operations.
/// </summary>
public partial interface ILoadBalancersOperations
{
/// <summary>
/// Deletes the specified load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<LoadBalancer>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update load balancer
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<LoadBalancer>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the load balancers in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the load balancers in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<LoadBalancer>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update load balancer
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<LoadBalancer>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the load balancers in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the load balancers in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<LoadBalancer>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Security.Permissions;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design.WebControls;
using System.Web.UI.WebControls;
using SmallSharpTools.Logging;
using SmallSharpTools.YahooPack.Providers;
using SmallSharpTools.YahooPack.Web.Security;
namespace SmallSharpTools.YahooPack.Web.UI.Controls
{
/// <summary>
/// SmallSharpTools.YahooPack: Login Button
/// </summary>
[
AspNetHostingPermission(SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal),
ToolboxData("<{0}:YahooLoginButton runat=server></{0}:YahooLoginButton>"),
Designer(typeof(YahooLoginButtonDesigner))
]
public class YahooLoginButton : CompositeControl
{
#region " Events "
public event CancelEventHandler LoggingIn;
#endregion
#region " Variables "
private LinkButton loginButton;
#endregion
#region " Control Events "
protected void loginButton_Click(object sender, EventArgs e)
{
CancelEventArgs args = new CancelEventArgs(false);
OnLoggingIn(args);
if (!args.Cancel)
{
YahooSession yahooSession = YahooAuthenticationProvider.Instance.LoadSession();
StringBuilder appData = new StringBuilder();
if (ApplicationData.Count > 0)
{
foreach (string key in ApplicationData.Keys)
{
if (key.Contains("_") || key.Contains("."))
{
throw new InvalidDataException(
"Application Data Key cannot contain periods or underscores: " +
key);
}
if (ApplicationData[key].Contains("_") ||
ApplicationData[key].Contains("."))
{
throw new InvalidDataException(
"Application Data Value cannot contain periods or underscores: " +
ApplicationData[key]);
}
appData.Append(key);
appData.Append("_");
appData.Append(ApplicationData[key]);
appData.Append(".");
}
Logger.Debug("appData: " + appData.ToString());
}
string loginUrl = yahooSession.GetLoginUrl(appData.ToString());
HttpContext.Current.Response.Redirect(loginUrl);
}
}
#endregion
#region " Control Methods "
/// <summary>
/// Created child controls
/// </summary>
protected override void CreateChildControls()
{
// Clear child controls
Controls.Clear();
// Build the control tree
CreateControlHierarchy();
// Clear the viewstate of child controls
ClearChildViewState();
}
/// <summary>
/// Creates control hierarchy
/// </summary>
protected void CreateControlHierarchy()
{
if (loginButton == null)
{
loginButton = new LinkButton();
loginButton.Text = "Yahoo Login";
loginButton.Click += new EventHandler(loginButton_Click);
}
Controls.Add(loginButton);
}
#endregion
#region " Control Properties "
/// <summary>
/// Property
/// </summary>
[Browsable(true), Category("Display"), Description("Link Text"), DefaultValue("Yahoo Login")]
public string Text
{
get
{
EnsureChildControls();
return loginButton.Text;
}
set
{
EnsureChildControls();
loginButton.Text = value;
}
}
/// <summary>
/// Property
/// </summary>
[Browsable(true), Category("Display"), Description("CSS Class"), DefaultValue("")]
public new string CssClass
{
get
{
EnsureChildControls();
return loginButton.CssClass;
}
set
{
EnsureChildControls();
loginButton.CssClass = value;
}
}
private Dictionary<String, String> _applicationData = new Dictionary<String, String>();
[Browsable(true), Category("Behavior"), Description("Application Data"), DefaultValue("")]
public Dictionary<String, String> ApplicationData
{
get
{
EnsureChildControls();
return _applicationData;
}
}
#endregion
/// <summary>
/// Raise the LoggingIn event
/// </summary>
/// <param name="e"></param>
protected virtual void OnLoggingIn(CancelEventArgs e)
{
if (LoggingIn != null)
{
LoggingIn(this, e);
}
}
private ILogger Logger
{
get
{
return LoggingProvider.Instance.GetLogger(GetType());
}
}
}
#region " Helper Classes "
internal class YahooLoginButtonDesigner : CompositeControlDesigner
{
#region " Designer Methods "
/// <summary>
/// Override method
/// </summary>
public override void Initialize(IComponent component)
{
base.Initialize(component);
}
/// <summary>
/// Override method
/// </summary>
public override string GetDesignTimeHtml()
{
string markup;
try
{
markup = base.GetDesignTimeHtml();
}
catch (Exception ex)
{
markup = "<p style='background: #ccc; color: #900; font-weight: bold;'>Error: " +
ex.Message + "</p>\n<div>" +
ex.StackTrace + "</div>";
}
return markup;
}
#endregion
}
#endregion
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class ConsoleBase : MonoBehaviour
{
protected string status = "Ready";
protected string lastResponse = "";
public GUIStyle textStyle = new GUIStyle();
protected Texture2D lastResponseTexture;
protected Vector2 scrollPosition = Vector2.zero;
#if UNITY_IOS || UNITY_ANDROID || UNITY_WP8
protected int buttonHeight = 60;
protected int mainWindowWidth = Screen.width - 30;
protected int mainWindowFullWidth = Screen.width;
#else
protected int buttonHeight = 24;
protected int mainWindowWidth = 500;
protected int mainWindowFullWidth = 530;
#endif
virtual protected void Awake()
{
textStyle.alignment = TextAnchor.UpperLeft;
textStyle.wordWrap = true;
textStyle.padding = new RectOffset(10, 10, 10, 10);
textStyle.stretchHeight = true;
textStyle.stretchWidth = false;
}
protected bool Button(string label)
{
return GUILayout.Button(
label,
GUILayout.MinHeight(buttonHeight),
GUILayout.MaxWidth(mainWindowWidth)
);
}
protected void LabelAndTextField(string label, ref string text)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label, GUILayout.MaxWidth(150));
text = GUILayout.TextField(text);
GUILayout.EndHorizontal();
}
protected bool IsHorizontalLayout()
{
#if UNITY_IOS || UNITY_ANDROID || UNITY_WP8
return Screen.orientation == ScreenOrientation.Landscape;
#else
return true;
#endif
}
protected int TextWindowHeight
{
get
{
#if UNITY_IOS || UNITY_ANDROID || UNITY_WP8
return IsHorizontalLayout() ? Screen.height : 85;
#else
return Screen.height;
#endif
}
}
protected void Callback(FBResult result)
{
lastResponseTexture = null;
// Some platforms return the empty string instead of null.
if (!String.IsNullOrEmpty (result.Error))
{
lastResponse = "Error Response:\n" + result.Error;
}
else if (!String.IsNullOrEmpty (result.Text))
{
lastResponse = "Success Response:\n" + result.Text;
}
else if (result.Texture != null)
{
lastResponseTexture = result.Texture;
lastResponse = "Success Response: texture\n";
}
else
{
lastResponse = "Empty Response\n";
}
}
protected void AddCommonFooter()
{
var textAreaSize = GUILayoutUtility.GetRect(640, TextWindowHeight);
#if UNITY_IOS || UNITY_ANDROID || UNITY_WP8
GUI.TextArea(
textAreaSize,
string.Format(
" AppId: {0} \n UserId: {1}\n IsLoggedIn: {2}\n {3}",
FB.AppId,
FB.UserId,
FB.IsLoggedIn,
lastResponse
), textStyle);
#else
GUI.TextArea(
textAreaSize,
string.Format(
" AppId: {0} \n Facebook Dll: {1} \n UserId: {2}\n IsLoggedIn: {3}\n AccessToken: {4}\n AccessTokenExpiresAt: {5}\n {6}",
FB.AppId,
"Loaded Successfully",
FB.UserId,
FB.IsLoggedIn,
FB.AccessToken,
FB.AccessTokenExpiresAt,
lastResponse
), textStyle);
#endif
if (lastResponseTexture != null)
{
var texHeight = textAreaSize.y + 200;
if (Screen.height - lastResponseTexture.height < texHeight)
{
texHeight = Screen.height - lastResponseTexture.height;
}
GUI.Label(new Rect(textAreaSize.x + 5, texHeight, lastResponseTexture.width, lastResponseTexture.height), lastResponseTexture);
}
}
protected void AddCommonHeader()
{
if (IsHorizontalLayout())
{
GUILayout.BeginHorizontal();
GUILayout.BeginVertical();
}
GUILayout.Space(5);
GUILayout.Box("Status: " + status, GUILayout.MinWidth(mainWindowWidth));
#if UNITY_IOS || UNITY_ANDROID || UNITY_WP8
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
scrollPosition.y += Input.GetTouch(0).deltaPosition.y;
}
#endif
scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.MinWidth(mainWindowFullWidth));
GUILayout.BeginVertical();
GUI.enabled = !FB.IsInitialized;
if (Button("FB.Init"))
{
CallFBInit();
status = "FB.Init() called with " + FB.AppId;
}
GUILayout.BeginHorizontal();
GUI.enabled = FB.IsInitialized;
if (Button("Login"))
{
CallFBLogin();
status = "Login called";
}
GUI.enabled = FB.IsLoggedIn;
if (Button("Get publish_actions"))
{
CallFBLoginForPublish();
status = "Login (for publish_actions) called";
}
#if UNITY_IOS || UNITY_ANDROID || UNITY_WP8
if (Button("Logout"))
{
CallFBLogout();
status = "Logout called";
}
#endif
GUI.enabled = FB.IsInitialized;
GUILayout.EndHorizontal();
}
#region FB.Init() example
private void CallFBInit()
{
FB.Init(OnInitComplete, OnHideUnity);
}
private void OnInitComplete()
{
Debug.Log("FB.Init completed: Is user logged in? " + FB.IsLoggedIn);
}
private void OnHideUnity(bool isGameShown)
{
Debug.Log("Is game showing? " + isGameShown);
}
#endregion
#region FB.Login() example
private void CallFBLogin()
{
FB.Login("public_profile,email,user_friends", LoginCallback);
}
private void CallFBLoginForPublish()
{
// It is generally good behavior to split asking for read and publish
// permissions rather than ask for them all at once.
//
// In your own game, consider postponing this call until the moment
// you actually need it.
FB.Login("publish_actions", LoginCallback);
}
void LoginCallback(FBResult result)
{
if (result.Error != null)
lastResponse = "Error Response:\n" + result.Error;
else if (!FB.IsLoggedIn)
{
lastResponse = "Login cancelled by Player";
}
else
{
lastResponse = "Login was successful!";
}
}
private void CallFBLogout()
{
FB.Logout();
}
#endregion
}
| |
using UnityEngine;
using UnityEditor;
public class MegaFFDEditor : MegaModifierEditor
{
Vector3 pm = new Vector3();
public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers\\ffd_help.png"); }
bool showpoints = false;
public override bool Inspector()
{
MegaFFD mod = (MegaFFD)target;
#if !UNITY_5
EditorGUIUtility.LookLikeControls();
#endif
mod.KnotSize = EditorGUILayout.FloatField("Knot Size", mod.KnotSize);
mod.inVol = EditorGUILayout.Toggle("In Vol", mod.inVol);
handles = EditorGUILayout.Toggle("Handles", handles);
handleSize = EditorGUILayout.Slider("Size", handleSize, 0.0f, 1.0f);
mirrorX = EditorGUILayout.Toggle("Mirror X", mirrorX);
mirrorY = EditorGUILayout.Toggle("Mirror Y", mirrorY);
mirrorZ = EditorGUILayout.Toggle("Mirror Z", mirrorZ);
showpoints = EditorGUILayout.Foldout(showpoints, "Points");
if ( showpoints )
{
int gs = mod.GridSize();
//int num = gs * gs * gs;
for ( int x = 0; x < gs; x++ )
{
for ( int y = 0; y < gs; y++ )
{
for ( int z = 0; z < gs; z++ )
{
int i = (x * gs * gs) + (y * gs) + z;
mod.pt[i] = EditorGUILayout.Vector3Field("p[" + x + "," + y + "," + z + "]", mod.pt[i]);
}
}
}
}
return false;
}
static public float handleSize = 0.5f;
static public bool handles = true;
static public bool mirrorX = false;
static public bool mirrorY = false;
static public bool mirrorZ = false;
public override void DrawSceneGUI()
{
MegaFFD ffd = (MegaFFD)target;
bool snapshot = false;
if ( ffd.DisplayGizmo )
{
MegaModifiers context = ffd.GetComponent<MegaModifiers>();
if ( context && context.DrawGizmos )
{
Vector3 size = ffd.lsize;
Vector3 osize = ffd.lsize;
osize.x = 1.0f / size.x;
osize.y = 1.0f / size.y;
osize.z = 1.0f / size.z;
Matrix4x4 tm1 = Matrix4x4.identity;
Quaternion rot = Quaternion.Euler(ffd.gizmoRot);
tm1.SetTRS(-(ffd.gizmoPos + ffd.Offset), rot, ffd.gizmoScale); //Vector3.one);
Matrix4x4 tm = Matrix4x4.identity;
Handles.matrix = Matrix4x4.identity;
if ( context != null && context.sourceObj != null )
tm = context.sourceObj.transform.localToWorldMatrix * tm1;
else
tm = ffd.transform.localToWorldMatrix * tm1;
DrawGizmos(ffd, tm); //Handles.matrix);
Handles.color = Color.yellow;
#if false
int pc = ffd.GridSize();
pc = pc * pc * pc;
for ( int i = 0; i < pc; i++ )
{
Vector3 p = ffd.GetPoint(i); // + ffd.bcenter;
//pm = Handles.PositionHandle(p, Quaternion.identity);
pm = Handles.FreeMoveHandle(p, Quaternion.identity, ffd.KnotSize * 0.1f, Vector3.zero, Handles.CircleCap);
pm -= ffd.bcenter;
p = Vector3.Scale(pm, osize);
p.x += 0.5f;
p.y += 0.5f;
p.z += 0.5f;
ffd.pt[i] = p;
}
#endif
int gs = ffd.GridSize();
//int i = 0;
Vector3 ttp = Vector3.zero;
for ( int z = 0; z < gs; z++ )
{
for ( int y = 0; y < gs; y++ )
{
for ( int x = 0; x < gs; x++ )
{
int index = ffd.GridIndex(x, y, z);
//Vector3 p = ffd.GetPoint(i); // + ffd.bcenter;
Vector3 lp = ffd.GetPoint(index);
Vector3 p = lp; //tm.MultiplyPoint(lp); //ffdi); // + ffd.bcenter;
Vector3 tp = tm.MultiplyPoint(p);
if ( handles )
{
ttp = Handles.PositionHandle(tp, Quaternion.identity);
//pm = tm.inverse.MultiplyPoint(Handles.PositionHandle(tm.MultiplyPoint(p), Quaternion.identity));
//pm = PositionHandle(p, Quaternion.identity, handleSize, ffd.gizCol1.a);
}
else
ttp = Handles.FreeMoveHandle(tp, Quaternion.identity, ffd.KnotSize * 0.1f, Vector3.zero, Handles.CircleCap);
if ( ttp != tp )
{
if ( !snapshot )
{
MegaUndo.SetSnapshotTarget(ffd, "FFD Lattice Move");
snapshot = true;
}
}
pm = tm.inverse.MultiplyPoint(ttp);
Vector3 delta = pm - p;
//pm = lp + delta;
//ffd.SetPoint(x, y, z, pm);
pm -= ffd.bcenter;
p = Vector3.Scale(pm, osize);
p.x += 0.5f;
p.y += 0.5f;
p.z += 0.5f;
ffd.pt[index] = p;
if ( mirrorX )
{
int y1 = y - (gs - 1);
if ( y1 < 0 )
y1 = -y1;
if ( y != y1 )
{
Vector3 p1 = ffd.GetPoint(ffd.GridIndex(x, y1, z)); // + ffd.bcenter;
delta.y = -delta.y;
p1 += delta;
p1 -= ffd.bcenter;
p = Vector3.Scale(p1, osize);
p.x += 0.5f;
p.y += 0.5f;
p.z += 0.5f;
ffd.pt[ffd.GridIndex(x, y1, z)] = p;
}
}
if ( mirrorY )
{
int z1 = z - (gs - 1);
if ( z1 < 0 )
z1 = -z1;
if ( z != z1 )
{
Vector3 p1 = ffd.GetPoint(ffd.GridIndex(x, y, z1)); // + ffd.bcenter;
delta.z = -delta.z;
p1 += delta;
p1 -= ffd.bcenter;
p = Vector3.Scale(p1, osize);
p.x += 0.5f;
p.y += 0.5f;
p.z += 0.5f;
ffd.pt[ffd.GridIndex(x, y, z1)] = p;
}
}
if ( mirrorZ )
{
int x1 = x - (gs - 1);
if ( x1 < 0 )
x1 = -x1;
if ( x != x1 )
{
Vector3 p1 = ffd.GetPoint(ffd.GridIndex(x1, y, z)); // + ffd.bcenter;
delta.x = -delta.x;
p1 += delta;
p1 -= ffd.bcenter;
p = Vector3.Scale(p1, osize);
p.x += 0.5f;
p.y += 0.5f;
p.z += 0.5f;
ffd.pt[ffd.GridIndex(x1, y, z)] = p;
}
}
}
}
}
Handles.matrix = Matrix4x4.identity;
if ( GUI.changed && snapshot )
{
MegaUndo.CreateSnapshot();
MegaUndo.RegisterSnapshot();
}
MegaUndo.ClearSnapshotTarget();
}
}
}
public static Vector3 PositionHandle(Vector3 position, Quaternion rotation, float size, float alpha)
{
float handlesize = handleSize; //HandleUtility.GetHandleSize(position) * size;
Color color = Handles.color;
Color col = Color.red;
col.a = alpha;
Handles.color = col; //Color.red; //Handles..xAxisColor;
position = Handles.Slider(position, rotation * Vector3.right, handlesize, new Handles.DrawCapFunction(Handles.ArrowCap), 0.0f); //SnapSettings.move.x);
col = Color.green;
col.a = alpha;
Handles.color = col; //Color.green; //Handles.yAxisColor;
position = Handles.Slider(position, rotation * Vector3.up, handlesize, new Handles.DrawCapFunction(Handles.ArrowCap), 0.0f); //SnapSettings.move.y);
col = Color.blue;
col.a = alpha;
Handles.color = col; //Color.blue; //Handles.zAxisColor;
position = Handles.Slider(position, rotation * Vector3.forward, handlesize, new Handles.DrawCapFunction(Handles.ArrowCap), 0.0f); //SnapSettings.move.z);
col = Color.yellow;
col.a = alpha;
Handles.color = col; //Color.yellow; //Handles.centerColor;
position = Handles.FreeMoveHandle(position, rotation, handlesize * 0.15f, Vector3.zero, new Handles.DrawCapFunction(Handles.RectangleCap));
Handles.color = color;
return position;
}
Vector3[] pp3 = new Vector3[3];
#if false
public void DrawGizmos(MegaFFD ffd, Matrix4x4 tm)
{
Handles.color = ffd.gizCol1; //Color.red;
int pc = ffd.GridSize();
for ( int i = 0; i < pc; i++ )
{
for ( int j = 0; j < pc; j++ )
{
for ( int k = 0; k < pc; k++ )
{
//pp3[0] = tm.MultiplyPoint(ffd.GetPoint(i, j, k)); // + ffd.bcenter);
pp3[0] = ffd.GetPoint(i, j, k); // + ffd.bcenter);
if ( i < pc - 1 )
{
//pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i + 1, j, k)); // + ffd.bcenter);
pp3[1] = ffd.GetPoint(i + 1, j, k); // + ffd.bcenter);
Handles.DrawLine(pp3[0], pp3[1]);
}
if ( j < pc - 1 )
{
//pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j + 1, k)); // + ffd.bcenter);
pp3[1] = ffd.GetPoint(i, j + 1, k); // + ffd.bcenter);
Handles.DrawLine(pp3[0], pp3[1]);
}
if ( k < pc - 1 )
{
//pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j, k + 1)); // + ffd.bcenter);
pp3[1] = ffd.GetPoint(i, j, k + 1); // + ffd.bcenter);
Handles.DrawLine(pp3[0], pp3[1]);
}
}
}
}
}
#else
public void DrawGizmos(MegaFFD ffd, Matrix4x4 tm)
{
Handles.color = ffd.gizCol1; //Color.red;
int pc = ffd.GridSize();
for ( int i = 0; i < pc; i++ )
{
for ( int j = 0; j < pc; j++ )
{
for ( int k = 0; k < pc; k++ )
{
pp3[0] = tm.MultiplyPoint(ffd.GetPoint(i, j, k)); // + ffd.bcenter);
//pp3[0] = ffd.GetPoint(i, j, k); // + ffd.bcenter);
if ( i < pc - 1 )
{
pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i + 1, j, k)); // + ffd.bcenter);
//pp3[1] = ffd.GetPoint(i + 1, j, k); // + ffd.bcenter);
Handles.DrawLine(pp3[0], pp3[1]);
}
if ( j < pc - 1 )
{
pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j + 1, k)); // + ffd.bcenter);
//pp3[1] = ffd.GetPoint(i, j + 1, k); // + ffd.bcenter);
Handles.DrawLine(pp3[0], pp3[1]);
}
if ( k < pc - 1 )
{
pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j, k + 1)); // + ffd.bcenter);
//pp3[1] = ffd.GetPoint(i, j, k + 1); // + ffd.bcenter);
Handles.DrawLine(pp3[0], pp3[1]);
}
}
}
}
}
#endif
}
| |
/*
* Copyright (c) 2016 Tenebrous
*
* 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.
*
* Latest version: https://bitbucket.org/Tenebrous/unityeditorenhancements/wiki/Home
*/
using System;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Tenebrous.EditorEnhancements
{
internal static class AssetInfo
{
public static string GetPreviewInfo(this object pObject)
{
string info = "";
string typename = pObject.GetType().ToString().Replace("UnityEngine.", "");
if (pObject is AudioClip)
info = ((AudioClip) pObject).GetPreviewInfo();
else if (pObject is Texture2D)
info = ((Texture2D) pObject).GetPreviewInfo();
else if (pObject is Material)
info = ((Material) pObject).GetPreviewInfo();
else if (pObject is Mesh)
info = ((Mesh) pObject).GetPreviewInfo();
else if (pObject is MeshFilter)
info = ((MeshFilter) pObject).GetPreviewInfo();
else if (pObject is MeshRenderer)
info = ((MeshRenderer) pObject).GetPreviewInfo();
else if (pObject is GameObject)
info = ((GameObject) pObject).GetPreviewInfo();
else if (pObject is MonoScript)
{
typename = "";
info = ((MonoScript) pObject).GetPreviewInfo();
}
else if (pObject is Shader)
info = ((Shader) pObject).GetPreviewInfo();
else if (pObject is MonoBehaviour)
{
typename = pObject.GetType().BaseType.ToString().Replace("UnityEngine.", "");
info = ((MonoBehaviour) pObject).GetPreviewInfo();
}
else if (pObject is Behaviour)
info = ((Behaviour) pObject).GetPreviewInfo();
if (typename != "")
if (info == "")
info += typename;
else
info += " (" + typename + ")";
return (info);
}
public static string GetPreviewInfo(this AudioClip pObject)
{
string info = "";
TimeSpan clipTimespan = TimeSpan.FromSeconds(pObject.length);
if (clipTimespan.Hours > 0)
info += clipTimespan.Hours + ":";
info += clipTimespan.Minutes.ToString("00") + ":" + clipTimespan.Seconds.ToString("00") + "." +
clipTimespan.Milliseconds.ToString("000") + " ";
if (pObject.channels == 1)
info += "Mono\n";
else if (pObject.channels == 2)
info += "Stereo\n";
else
info += pObject.channels + " channels\n";
return (info);
}
public static string GetPreviewInfo(this Texture2D pObject)
{
if( pObject != null )
return pObject.format.ToString() + "\n"
+ pObject.width + "x" + pObject.height;
return "";
}
public static string GetPreviewInfo(this Material pObject)
{
string info = "";
info = pObject.shader.name;
foreach (Object obj in EditorUtility.CollectDependencies(new Object[] {pObject}))
if (obj is Texture)
info += "\n - " + obj.name;
return (info);
}
public static string GetPreviewInfo(this MeshFilter pObject)
{
if( pObject != null && pObject.sharedMesh != null )
return pObject.sharedMesh.GetPreviewInfo();
return "";
}
public static string GetPreviewInfo(this Mesh pObject)
{
if( pObject != null )
return pObject.vertexCount + " verts " + pObject.triangles.Length + " tris"
+ "\n" + pObject.name;
return "";
}
public static string GetPreviewInfo(this MeshRenderer pObject)
{
return "";
}
public static string GetPreviewInfo(this MonoScript pObject)
{
if( pObject != null )
{
Type assetclass = pObject.GetClass();
if( assetclass != null )
return assetclass.ToString() + "\n(" + assetclass.BaseType.ToString().Replace( "UnityEngine.", "" ) + ")";
else
return "(multiple classes)";
}
return "";
}
public static string GetPreviewInfo(this Shader pObject)
{
if( pObject != null )
return pObject.renderQueue.ToString();
return "";
}
public static string GetPreviewInfo(this MonoBehaviour pObject)
{
if( pObject != null )
{
MonoScript ms = MonoScript.FromMonoBehaviour( pObject );
if( ms != null )
return ms.name;
}
return "";
}
public static string GetPreviewInfo(this GameObject pObject)
{
if( pObject != null )
{
GameObject parent = PrefabUtility.GetCorrespondingObjectFromSource( pObject ) as GameObject;
if( parent != null )
return AssetDatabase.GetAssetPath( parent );
}
return "";
}
// components
public static string GetPreviewInfo(this Behaviour pObject)
{
if( pObject == null )
return "";
else if (pObject is Light)
return (pObject as Light).GetPreviewInfo();
else if (pObject is Camera)
return (pObject as Camera).GetPreviewInfo();
else if (pObject is AudioSource)
return (pObject as AudioSource).GetPreviewInfo();
else if (pObject is AudioReverbFilter)
return (pObject as AudioReverbFilter).GetPreviewInfo();
return "";
}
public static string GetPreviewInfo(this Light pObject)
{
if( pObject != null )
return pObject.type.ToString();
return "";
}
public static string GetPreviewInfo(this Camera pObject)
{
if( pObject != null )
{
if( pObject.orthographic )
return "Orthographic";
else
return "Perspective";
}
return "";
}
public static string GetPreviewInfo(this AudioSource pObject)
{
if( pObject != null && pObject.clip != null )
return pObject.clip.name;
return "";
}
public static string GetPreviewInfo(this AudioReverbFilter pObject)
{
if( pObject != null )
return pObject.reverbPreset.ToString();
return "";
}
// other extensions
public static bool HasAnyRenderers(this GameObject pObject)
{
if( pObject == null )
return false;
if (pObject.GetComponent<Renderer>() != null)
return (true);
foreach (Transform child in pObject.transform)
if (child.gameObject.HasAnyRenderers())
return (true);
return false;
}
}
}
| |
// (c) Copyright Esri, 2010 - 2016
// This source is subject to the Apache 2.0 License.
// Please see http://www.apache.org/licenses/LICENSE-2.0.html for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Resources;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Carto;
using System.IO;
using ESRI.ArcGIS.Display;
namespace ESRI.ArcGIS.OSM.GeoProcessing
{
// this function takes any combination of layers and create a group layer as the final output
[Guid("63eee1b1-15c5-49d7-a926-5eb0575000a0")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("OSMEditor.GPCombineLayers")]
public class GPCombineLayers : ESRI.ArcGIS.Geoprocessing.IGPFunction2
{
string m_DisplayName = "Combine Layers";
int in_LayersNumber, out_groupLayerNumber;
ResourceManager resourceManager = null;
IGPFunctionFactory osmGPFactory = null;
public GPCombineLayers()
{
try
{
resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);
m_DisplayName = string.Empty;
osmGPFactory = new OSMGPFactory();
}
catch { }
}
#region "IGPFunction2 Implementations"
public ESRI.ArcGIS.esriSystem.UID DialogCLSID
{
get
{
return null;
}
}
public string DisplayName
{
get
{
if (String.IsNullOrEmpty(m_DisplayName))
{
m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_CombineLayersName).DisplayName;
}
return m_DisplayName;
}
}
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
{
try
{
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
if (TrackCancel == null)
{
TrackCancel = new CancelTrackerClass();
}
IGPValue inputLayersGPValue = gpUtilities3.UnpackGPValue(paramvalues.get_Element(in_LayersNumber));
IGPMultiValue inputLayersMultiValue = gpUtilities3.UnpackGPValue(inputLayersGPValue) as IGPMultiValue;
IGPParameter outputGroupLayerParameter = paramvalues.get_Element(out_groupLayerNumber) as IGPParameter;
IGPValue outputGPGroupLayer = gpUtilities3.UnpackGPValue(outputGroupLayerParameter);
IGPCompositeLayer outputCompositeLayer = outputGPGroupLayer as IGPCompositeLayer;
if (outputCompositeLayer == null)
{
message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), outputGroupLayerParameter.Name));
return;
}
IGroupLayer groupLayer = null;
// find the last position of the "\" string
// in case we find such a thing, i.e. position is >= -1 then let's assume that we are dealing with a layer file on disk
// otherwise let's create a new group layer instance
string outputGPLayerNameAsString = outputGPGroupLayer.GetAsText();
int separatorPosition = outputGPLayerNameAsString.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
string layerName = String.Empty;
if (separatorPosition > -1)
{
layerName = outputGPGroupLayer.GetAsText().Substring(separatorPosition + 1);
}
else
{
layerName = outputGPGroupLayer.GetAsText();
}
ILayer foundLayer = null;
IGPLayer existingGPLayer = gpUtilities3.FindMapLayer2(layerName, out foundLayer);
if (foundLayer != null)
{
gpUtilities3.RemoveFromMapEx((IGPValue)existingGPLayer);
gpUtilities3.RemoveInternalLayerEx(foundLayer);
}
groupLayer = new GroupLayer();
((ILayer)groupLayer).Name = layerName;
for (int layerIndex = 0; layerIndex < inputLayersMultiValue.Count; layerIndex++)
{
IGPValue gpLayerToAdd = inputLayersMultiValue.get_Value(layerIndex) as IGPValue;
ILayer sourceLayer = gpUtilities3.DecodeLayer(gpLayerToAdd);
groupLayer.Add(sourceLayer);
}
outputGPGroupLayer = gpUtilities3.MakeGPValueFromObject(groupLayer);
if (separatorPosition > -1)
{
try
{
// in the case that we are dealing with a layer file on disk
// let's persist the group layer information into the file
ILayerFile pointLayerFile = new LayerFileClass();
if (System.IO.Path.GetExtension(outputGPLayerNameAsString).ToUpper().Equals(".LYR"))
{
if (pointLayerFile.get_IsPresent(outputGPLayerNameAsString))
{
try
{
gpUtilities3.Delete(outputGPGroupLayer);
}
catch (Exception ex)
{
message.AddError(120001, ex.Message);
return;
}
}
pointLayerFile.New(outputGPLayerNameAsString);
pointLayerFile.ReplaceContents(groupLayer);
pointLayerFile.Save();
}
outputGPGroupLayer = gpUtilities3.MakeGPValueFromObject(pointLayerFile.Layer);
}
catch (Exception ex)
{
message.AddError(120002, ex.Message);
return;
}
}
gpUtilities3.PackGPValue(outputGPGroupLayer, outputGroupLayerParameter);
}
catch (Exception ex)
{
message.AddError(120049, ex.Message);
}
}
public ESRI.ArcGIS.esriSystem.IName FullName
{
get
{
IName fullName = null;
if (osmGPFactory != null)
{
fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_CombineLayersName) as IName;
}
return fullName;
}
}
public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam)
{
return null;
}
public int HelpContext
{
get
{
return 0;
}
}
public string HelpFile
{
get
{
return default(string);
}
}
public bool IsLicensed()
{
return true;
}
public string MetadataFile
{
get
{
string metadafile = "gpcombinelayers.xml";
try
{
string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray());
string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation();
string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "gpcombinelayers_" + languageid[0] + ".xml";
string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "gpcombinelayers_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml";
if (System.IO.File.Exists(localizedMetaDataFileShort))
{
metadafile = localizedMetaDataFileShort;
}
else if (System.IO.File.Exists(localizedMetaDataFileLong))
{
metadafile = localizedMetaDataFileLong;
}
}
catch { }
return metadafile;
}
}
public string Name
{
get
{
return OSMGPFactory.m_CombineLayersName;
}
}
public ESRI.ArcGIS.esriSystem.IArray ParameterInfo
{
get
{
//
IArray parameterArray = new ArrayClass();
// input layers
IGPParameterEdit3 inputLayerFiles = new GPParameterClass() as IGPParameterEdit3;
IGPDataType inputType = new GPLayerTypeClass();
IGPMultiValueType multiValueType = new GPMultiValueTypeClass();
multiValueType.MemberDataType = inputType;
IGPMultiValue multiValueValue = new GPMultiValueClass();
multiValueValue.MemberDataType = inputType;
inputLayerFiles.DataType = (IGPDataType)multiValueType;
inputLayerFiles.Value = (IGPValue)multiValueValue;
inputLayerFiles.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
inputLayerFiles.DisplayName = resourceManager.GetString("GPTools_GPCombineLayers_inputlayers_desc");
inputLayerFiles.Name = "in_LayerFiles";
inputLayerFiles.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
in_LayersNumber = 0;
parameterArray.Add(inputLayerFiles);
// output group layer
IGPParameterEdit3 outputGroupLayer = new GPParameterClass() as IGPParameterEdit3;
outputGroupLayer.DataType = new GPGroupLayerTypeClass();
outputGroupLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
outputGroupLayer.DisplayName = resourceManager.GetString("GPTools_GPCombineLayers_outputgrouplayer_desc");
outputGroupLayer.Name = "out_grouplayer";
out_groupLayerNumber = 1;
parameterArray.Add(outputGroupLayer);
return parameterArray;
}
}
public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
{
// no special code required - let the framework handle it
}
public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
{
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
IGPParameter3 inputLayersParameter = paramvalues.get_Element(in_LayersNumber) as IGPParameter3;
IGPMultiValue inputLayersGPValue = gpUtilities3.UnpackGPValue(inputLayersParameter) as IGPMultiValue;
if (inputLayersGPValue == null)
{
return;
}
// check if there are input layer provided
if (inputLayersGPValue.Count == 0)
{
return;
}
IGPParameter3 outputLayerParameter = paramvalues.get_Element(out_groupLayerNumber) as IGPParameter3;
IGPValue outputLayerGPValue = gpUtilities3.UnpackGPValue(outputLayerParameter);
// if the output layer value is still empty and build a proposal for a name
if (outputLayerGPValue.IsEmpty())
{
// read the proposed name from the resources
string proposedOutputLayerName = resourceManager.GetString("GPTools_GPCombineLayers_outputgrouplayer_proposedname");
string proposedOutputLayerNameTest = proposedOutputLayerName;
int layerIndex = 2;
// check if a layer with the same name already exists
// if it does then attempt to append some index numbers to build a unique, new name
ILayer foundLayer = gpUtilities3.FindMapLayer(proposedOutputLayerNameTest);
while (foundLayer != null)
{
proposedOutputLayerNameTest = proposedOutputLayerName + " (" + layerIndex + ")";
foundLayer = gpUtilities3.FindMapLayer(proposedOutputLayerNameTest);
layerIndex = layerIndex + 1;
if (layerIndex > 10000)
{
break;
}
}
outputLayerGPValue.SetAsText(proposedOutputLayerNameTest);
gpUtilities3.PackGPValue(outputLayerGPValue, outputLayerParameter);
}
}
public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr)
{
return default(ESRI.ArcGIS.Geodatabase.IGPMessages);
}
#endregion
}
}
| |
/*
* Copyright (c) 2014 All Rights Reserved by the SDL Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Trisoft.ISHRemote.Objects;
using Trisoft.ISHRemote.Objects.Public;
using Trisoft.ISHRemote.Exceptions;
using System.Threading;
using System.Xml;
using Trisoft.ISHRemote.Interfaces;
using Trisoft.ISHRemote.Folder25ServiceReference;
using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
namespace Trisoft.ISHRemote.Cmdlets
{
/// <summary>
/// Which verb to use: check http://msdn.microsoft.com/en-us/library/ms714428(v=vs.85).aspx
/// How to trace the pipelin: http://www.eggheadcafe.com/software/aspnet/31521302/valuefrompipelinebypropertyname.aspx
/// External MAML help: http://cmille19.wordpress.com/2009/09/24/external-maml-help-files/
/// and: http://technet.microsoft.com/en-us/library/dd819489.aspx
/// Progress Record: http://community.bartdesmet.net/blogs/bart/archive/2006/11/26/PowerShell-_2D00_-A-cmdlet-that-reports-progress-_2D00_-A-simple-file-downloader-cmdlet.aspx
/// </summary>
public abstract class TrisoftCmdlet : PSCmdlet
{
/// <summary>
/// Sleep constant used to slow down the progress bars to check the messages.
/// </summary>
protected const int SleepTime = 0;
public readonly ILogger Logger;
private int _tickCountStart;
private readonly ProgressRecord _parentProgressRecord;
protected int _parentCurrent;
protected int _parentTotal;
private readonly ProgressRecord _childProgressRecord;
/// <summary>
/// Name of the PSVariable so you don't have to specify '-IshSession $ishSession' anymore, should be set by New-IshSession
/// </summary>
internal const string ISHRemoteSessionStateIshSession = "ISHRemoteSessionStateIshSession";
/// <summary>
/// Error message you get when you didn't pass an explicit -IshSession on the cmdlet, or New-IshSession didn't set the SessionState variable
/// </summary>
internal const string ISHRemoteSessionStateIshSessionException = "IshSession is null. Please create a session first using New-IshSession. Or explicitly pass parameter -IshSession to your cmdlet.";
protected TrisoftCmdlet()
{
Logger = TrisoftCmdletLogger.Instance();
TrisoftCmdletLogger.Initialize(this);
const int parentActivityId = 1111; //whatever number
const int childActivityId = 2222;
_parentProgressRecord = new ProgressRecord(parentActivityId, base.GetType().Name, "Processing...");
_parentProgressRecord.SecondsRemaining = -1;
_childProgressRecord = new ProgressRecord(childActivityId, base.GetType().Name + " subtask ", "Subprocessing...");
_childProgressRecord.ParentActivityId = parentActivityId;
_childProgressRecord.SecondsRemaining = -1;
}
protected override void BeginProcessing()
{
WriteDebug("BeginProcessing");
_tickCountStart = Environment.TickCount;
base.BeginProcessing();
}
protected override void EndProcessing()
{
base.EndProcessing();
WriteDebug($"EndProcessing elapsed:{(Environment.TickCount - _tickCountStart)}ms");
}
protected void WriteObject(IshSession ishSession, Enumerations.ISHType[] ishType, List<IshBaseObject> ishBaseObjects, bool enumerateCollection)
{
switch (ishSession.PipelineObjectPreference)
{
case Enumerations.PipelineObjectPreference.PSObjectNoteProperty:
List<PSObject> psObjects = new List<PSObject>();
foreach (var IshBaseObject in ishBaseObjects)
{
PSObject psObject = PSObject.AsPSObject(IshBaseObject); // returning a PSObject object that inherits from ishObject
foreach (IshField ishField in IshBaseObject.IshFields.Fields())
{
psObject.Properties.Add(ishSession.NameHelper.GetPSNoteProperty(ishType, (IshMetadataField)ishField));
}
psObjects.Add(psObject);
}
WriteObject(psObjects, enumerateCollection);
break;
case Enumerations.PipelineObjectPreference.Off:
WriteObject(ishBaseObjects, true);
break;
}
}
protected void WriteObject(IshSession ishSession, Enumerations.ISHType[] ishType, IshBaseObject ishBaseObject, bool enumerateCollection)
{
List<IshBaseObject> ishBaseObjectList = new List<IshBaseObject>();
ishBaseObjectList.Add(ishBaseObject);
WriteObject(ishSession, ishType, ishBaseObjectList, enumerateCollection);
}
/// <summary>
/// Write progress over the complete cmdlet, so over updates and retrieves
/// </summary>
/// <param name="message">What are you processing</param>
/// <param name="current">Current step number</param>
/// <param name="total">Total number of steps</param>
public void WriteParentProgress(string message, int current, int total)
{
try
{
_parentTotal = total;
if (current <= total)
{
_parentCurrent = current;
}
else
{
WriteDebug($"WriteParentProgress Corrected to 100% progress for incoming message[{message}] current[{current}] total[{total}]");
_parentCurrent = total;
}
_parentProgressRecord.PercentComplete = _parentCurrent * 100 / _parentTotal;
_parentProgressRecord.StatusDescription = $"{message} ({_parentCurrent}/{_parentTotal})";
base.WriteProgress(_parentProgressRecord);
#if DEBUG
Thread.Sleep(SleepTime);
#endif
}
catch (Exception exception)
{
WriteWarning(exception.Message);
}
}
/// <summary>
/// Write progress over the specific (webservice) calls required to process a list of ids/ishobjects
/// </summary>
/// <param name="message">What are you processing</param>
/// <param name="current">Current step number</param>
/// <param name="total">Total number of steps</param>
public void WriteChildProgress(string message, int current, int total)
{
try
{
// Updating progress bar of the child
_childProgressRecord.PercentComplete = current * 100 / total;
_childProgressRecord.StatusDescription = message;
WriteVerbose(message);
// Skipping child write progress when current is '1', so only a progress when there is more to do
// Alternative could be if current==total to avoid a lot progress records to scroll by
if (current > 1)
{
base.WriteProgress(_childProgressRecord);
}
// Updating progress bar of the parent
_parentProgressRecord.PercentComplete = (int)((_parentCurrent * 100 / _parentTotal) + ((current * 100 / total) * (1.0 / _parentTotal)));
base.WriteProgress(_parentProgressRecord);
#if DEBUG
Thread.Sleep(SleepTime);
#endif
}
catch (Exception exception)
{
WriteWarning(exception.Message);
}
}
/// <summary>
/// Intentional override to include cmdlet origin
/// </summary>
public new void WriteVerbose(string message)
{
base.WriteVerbose(base.GetType().Name + " " + message);
WriteDebug(message);
}
/// <summary>
/// Intentional override to include cmdlet origin and timestamp
/// </summary>
public new void WriteDebug(string message)
{
base.WriteDebug($"{base.GetType().Name} {DateTime.Now.ToString("yyyyMMdd.HHmmss.fff")} {message}");
}
/// <summary>
/// Intentional override to include cmdlet origin
/// </summary>
public new void WriteWarning(string message)
{
base.WriteWarning(base.GetType().Name + " " + message);
}
/// <summary>
/// Convert base folder label into a BaseFolder enumeration value
/// </summary>
/// <param name="ishSession">The <see cref="IshSession"/>.</param>
/// <param name="baseFolderLabel">Label of the base folder</param>
/// <returns>The BaseFolder enumeration value</returns>
internal virtual Folder25ServiceReference.BaseFolder BaseFolderLabelToEnum(IshSession ishSession, string baseFolderLabel)
{
foreach (Folder25ServiceReference.BaseFolder baseFolder in System.Enum.GetValues(typeof(Folder25ServiceReference.BaseFolder)))
{
var folderLabel = BaseFolderEnumToLabel(ishSession, baseFolder);
if (String.CompareOrdinal(folderLabel, baseFolderLabel) == 0)
{
return baseFolder;
}
}
// The baseFolder is wrong
// EL: DIRTY WORKAROUND BELOW TO THROW AN EXCEPTION WITH ERROR CODE 102001
string xmlIshFolder = ishSession.Folder25.GetMetadata(
BaseFolder.System,
new string[] { "'" + baseFolderLabel + "'" }, // Use faulty folder path with quotes added, so we can throw the expected exception with errorcode=102001
"");
return BaseFolder.Data;
}
/// <summary>
/// Convert a BaseFolder enumeration value into a base folder label
/// </summary>
/// <param name="ishSession">Client session object to the InfoShare server instance. Keeps track of your security tokens and provide you clients to the various API end points. Holds matching contract parameters like separators, batch and chunk sizes.</param>
/// <param name="baseFolder">BaseFolder enumeration value</param>
/// <returns>base folder label</returns>
internal virtual string BaseFolderEnumToLabel(IshSession ishSession, Folder25ServiceReference.BaseFolder baseFolder)
{
IshFields requestedMetadata = new IshFields();
requestedMetadata.AddField(new IshRequestedMetadataField("FNAME", Enumerations.Level.None, Enumerations.ValueType.All));
string xmlIshFolder = ishSession.Folder25.GetMetadata(
baseFolder,
new string[] { }, // Use empty folder path so we can just get the basefolder name
requestedMetadata.ToXml());
XmlDocument result = new XmlDocument();
result.LoadXml(xmlIshFolder);
XmlElement xmlIshFolderElement = (XmlElement)result.SelectSingleNode("ishfolder");
IshFolder ishFolder = new IshFolder(xmlIshFolderElement);
return ((IshMetadataField)ishFolder.IshFields.RetrieveFirst("FNAME", Enumerations.Level.None, Enumerations.ValueType.Value)).Value;
}
/// <summary>
/// Devides one list to multiple lists by batchsize
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="list">List to devide</param>
/// <param name="batchSize"></param>
/// <returns>Multiple lists, all having maximally batchsize elements</returns>
internal List<List<T>> DevideListInBatches<T>(List<T> list, int batchSize)
{
var outList = new List<List<T>>();
if (list != null)
{
for (int i = 0; i < list.Count; i += batchSize)
{
outList.Add(list.Skip(i).Take(batchSize).ToList<T>());
}
}
return outList;
}
/// <summary>
/// Groups IshObjects list by LogicalIds and divides into multiple lists by batchsize so that objects with the same LogicalIds are never split between batches.
/// </summary>
/// <param name="list">List to devide</param>
/// <param name="batchSize"></param>
/// <returns>Multiple lists grouped by LogicalIds and having maximally batchsize elements, but the same LogicalId is never split between batches</returns>
internal List<List<IshObject>>DevideListInBatchesByLogicalId(List<IshObject> list, int batchSize)
{
var outList = new List<List<IshObject>>();
if (list != null)
{
var ishObjectsGroupedByIshRef = list.GroupBy(ishObject => ishObject.IshRef);
var tempList = new List<IshObject>(ishObjectsGroupedByIshRef.First().ToList());
foreach (var ishObjectsIshRefGroup in ishObjectsGroupedByIshRef.Skip(1))
{
if (tempList.Count + ishObjectsIshRefGroup.Count() <= batchSize)
{
tempList.AddRange(ishObjectsIshRefGroup.ToList());
}
else
{
outList.Add(tempList);
tempList = ishObjectsIshRefGroup.ToList();
}
}
outList.Add(tempList);
}
return outList;
}
}
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
using Trinity.Network.Messaging;
using Trinity.Utilities;
using Trinity;
using Trinity.Network.Sockets;
using Trinity.Diagnostics;
using System.Diagnostics;
using Trinity.Core.Lib;
using System.Runtime.CompilerServices;
namespace Trinity.Network.Sockets
{
internal struct TypeSyncRequestResponseHandlerTuple
{
public ushort Id;
public SynReqRspHandler Handler;
}
internal struct TypeSyncRequestHandlerTuple
{
public ushort Id;
public SynReqHandler Handler;
}
internal struct TypeAsyncRequestHandlerTuple
{
public ushort Id;
public AsyncReqHandler Handler;
}
unsafe class MessageHandlers
{
/// <summary>
/// We need to guarantee that all handlers are registered before accepting requests
/// </summary>
static MessageHandlers()
{
_message_parser = new MessageHandlers();
}
/// <summary>
/// Used to trigger static constructor.
/// </summary>
internal static void Initialize()
{
}
private static MessageHandlers _message_parser;
public static MessageHandlers DefaultParser
{
get
{
return _message_parser;
}
}
/// <summary>
/// Handler table for synchronous messages with responseBuff
/// </summary>
internal SynReqRspHandler[] sync_rsp_handlers = new SynReqRspHandler[ushort.MaxValue + 1];
internal SynReqRspHandler[] preserved_sync_rsp_handlers = new SynReqRspHandler[ushort.MaxValue + 1];
/// <summary>
/// Handler table for synchronous messages without responseBuff
/// </summary>
internal SynReqHandler[] sync_handlers = new SynReqHandler[ushort.MaxValue + 1];
internal SynReqHandler[] preserved_sync_handlers = new SynReqHandler[ushort.MaxValue + 1];
/// <summary>
/// Handler table for asynchronous message without responseBuff
/// </summary>
internal AsyncReqHandler[] async_handlers = new AsyncReqHandler[ushort.MaxValue + 1];
internal AsyncReqHandler[] preserved_async_handlers = new AsyncReqHandler[ushort.MaxValue + 1];
/// <summary>
/// Handler table for asynchronous message with responseBuff
/// </summary>
internal AsyncReqRspHandler[] async_rsp_handlers = new AsyncReqRspHandler[ushort.MaxValue + 1];
public MessageHandlers()
{
for (int i = 0; i <= ushort.MaxValue; ++i)
{
sync_rsp_handlers[i] = null;
sync_handlers[i] = null;
async_handlers[i] = null;
async_rsp_handlers[i] = null;
preserved_sync_rsp_handlers[i] = null;
preserved_sync_handlers[i] = null;
preserved_async_handlers[i] = null;
}
//install default synchronous message without response handlers
for (int i = 0; i < DefaultSyncReqHandlerSet.MessageHandlerList.Count; ++i)
{
preserved_sync_handlers[DefaultSyncReqHandlerSet.MessageHandlerList[i].Id] = DefaultSyncReqHandlerSet.MessageHandlerList[i].Handler;
Log.WriteLine(LogLevel.Debug, "Preserved sync message " + (RequestType)DefaultSyncReqHandlerSet.MessageHandlerList[i].Id + " is registered.");
}
//install the default synchronous request with response handlers
for (int i = 0; i < DefaultSyncReqRspHandlerSet.MessageHandlerList.Count; ++i)
{
preserved_sync_rsp_handlers[DefaultSyncReqRspHandlerSet.MessageHandlerList[i].Id] = DefaultSyncReqRspHandlerSet.MessageHandlerList[i].Handler;
Log.WriteLine(LogLevel.Debug, "Preserved sync (rsp) message " + (RequestType)DefaultSyncReqRspHandlerSet.MessageHandlerList[i].Id + " is registered.");
}
//install default asynchronous request handlers
for (int i = 0; i < DefaultAsynReqHandlerSet.MessageHandlerList.Count; ++i)
{
preserved_async_handlers[DefaultAsynReqHandlerSet.MessageHandlerList[i].Id] = DefaultAsynReqHandlerSet.MessageHandlerList[i].Handler;
Log.WriteLine(LogLevel.Debug, "Preserved async message " + (RequestType)DefaultAsynReqHandlerSet.MessageHandlerList[i].Id + " is registered.");
}
}
public bool RegisterMessageHandler(ushort msgId, SynReqRspHandler message_handler)
{
try
{
sync_rsp_handlers[msgId] = message_handler;
Log.WriteLine(LogLevel.Debug, "Sync (rsp) message " + msgId + " is registered.");
return true;
}
catch (Exception ex)
{
Trinity.Diagnostics.Log.WriteLine(ex.Message);
Trinity.Diagnostics.Log.WriteLine(ex.StackTrace);
return false;
}
}
public bool RegisterPreservedMessageHandler(ushort msgId, SynReqRspHandler message_handler)
{
try
{
preserved_sync_rsp_handlers[msgId] = message_handler;
Log.WriteLine(LogLevel.Debug, "Preserved sync (rsp) message " + msgId + " is registered.");
return true;
}
catch (Exception ex)
{
Trinity.Diagnostics.Log.WriteLine(ex.Message);
Trinity.Diagnostics.Log.WriteLine(ex.StackTrace);
return false;
}
}
public bool RegisterMessageHandler(ushort msgId, SynReqHandler message_handler)
{
try
{
sync_handlers[msgId] = message_handler;
Log.WriteLine(LogLevel.Debug, "Sync message " + msgId + " is registered.");
return true;
}
catch (Exception ex)
{
Trinity.Diagnostics.Log.WriteLine(ex.Message);
Trinity.Diagnostics.Log.WriteLine(ex.StackTrace);
return false;
}
}
public bool RegisterPreservedMessageHandler(ushort msgId, SynReqHandler message_handler)
{
try
{
preserved_sync_handlers[msgId] = message_handler;
Log.WriteLine(LogLevel.Debug, "Preserved sync message " + msgId + " is registered.");
return true;
}
catch (Exception ex)
{
Trinity.Diagnostics.Log.WriteLine(ex.Message);
Trinity.Diagnostics.Log.WriteLine(ex.StackTrace);
return false;
}
}
public bool RegisterMessageHandler(ushort msgId, AsyncReqHandler request_handler)
{
try
{
async_handlers[msgId] = request_handler;
Log.WriteLine(LogLevel.Debug, "Async message " + msgId + " is registered.");
return true;
}
catch (Exception ex)
{
Trinity.Diagnostics.Log.WriteLine(ex.Message);
Trinity.Diagnostics.Log.WriteLine(ex.StackTrace);
return false;
}
}
public bool RegisterPreservedMessageHandler(ushort msgId, AsyncReqHandler request_handler)
{
try
{
preserved_async_handlers[msgId] = request_handler;
Log.WriteLine(LogLevel.Debug, "Preserved async message " + msgId + " is registered.");
return true;
}
catch (Exception ex)
{
Trinity.Diagnostics.Log.WriteLine(ex.Message);
Trinity.Diagnostics.Log.WriteLine(ex.StackTrace);
return false;
}
}
public bool RegisterMessageHandler(ushort msgId, AsyncReqRspHandler request_handler)
{
try
{
async_rsp_handlers[msgId] = request_handler;
Log.WriteLine(LogLevel.Debug, "Async with response message " + msgId + " is registered.");
return true;
}
catch (Exception ex)
{
Trinity.Diagnostics.Log.WriteLine(ex.Message);
Trinity.Diagnostics.Log.WriteLine(ex.StackTrace);
return false;
}
}
#region _SetSendRecvBuff helpers
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe void _SetSendRecvBuff(TrinityErrorCode msgProcessResult, MessageBuff* sendRecvBuff, TrinityMessage response)
{
if (TrinityErrorCode.E_SUCCESS == msgProcessResult)
{
// Response buffer will be freed in Trinity.C after it is sent
sendRecvBuff->Buffer = response.Buffer;
sendRecvBuff->BytesToSend = (uint)response.Size;
}
else// TrinityErrorCode.E_RPC_EXCEPTION == msgProcessResult
{
// The client is expecting a reply payload, it will be notified because
// the payload length is E_RPC_EXCEPTION;
sendRecvBuff->Buffer = (byte*)Memory.malloc(sizeof(TrinityErrorCode));
sendRecvBuff->BytesToSend = sizeof(TrinityErrorCode);
*(TrinityErrorCode*)sendRecvBuff->Buffer = TrinityErrorCode.E_RPC_EXCEPTION;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe void _SetSendRecvBuff(TrinityErrorCode msgProcessResult, MessageBuff* sendRecvBuff)
{
if (TrinityErrorCode.E_SUCCESS == msgProcessResult)
{
// Response buffer will be freed in Trinity.C after it is sent
sendRecvBuff->Buffer = (byte*)Memory.malloc(sizeof(TrinityErrorCode));
sendRecvBuff->BytesToSend = sizeof(TrinityErrorCode);
*(TrinityErrorCode*)sendRecvBuff->Buffer = TrinityErrorCode.E_SUCCESS;
}
else// TrinityErrorCode.E_RPC_EXCEPTION == msgProcessResult
{
// The client is expecting an ACK package, it will be notified because
// the status code would be E_RPC_EXCEPTION;
sendRecvBuff->Buffer = (byte*)Memory.malloc(sizeof(TrinityErrorCode));
sendRecvBuff->BytesToSend = sizeof(TrinityErrorCode);
*(TrinityErrorCode*)sendRecvBuff->Buffer = TrinityErrorCode.E_RPC_EXCEPTION;
}
}
#endregion
internal void DispatchMessage(MessageBuff* sendRecvBuff)
{
byte* ByteArray = sendRecvBuff->Buffer;
int Length = (int)sendRecvBuff->BytesReceived;
TrinityMessageType msgType = (TrinityMessageType)sendRecvBuff->Buffer[TrinityProtocol.TrinityMsgTypeOffset];
ushort msgId = *(ushort*)(ByteArray + TrinityProtocol.TrinityMsgIdOffset);
TrinityErrorCode msgProcessResult;
try
{
switch (msgType)
{
case TrinityMessageType.SYNC_WITH_RSP:
SynReqRspArgs sync_rsp_args = new SynReqRspArgs(ByteArray,
TrinityProtocol.TrinityMsgHeader,
Length - TrinityProtocol.TrinityMsgHeader,
sync_rsp_handlers[msgId]);
msgProcessResult = sync_rsp_args.MessageProcess();
_SetSendRecvBuff(msgProcessResult, sendRecvBuff, sync_rsp_args.Response);
return;
case TrinityMessageType.PRESERVED_SYNC_WITH_RSP:
SynReqRspArgs preserved_sync_rsp_args = new SynReqRspArgs(ByteArray,
TrinityProtocol.TrinityMsgHeader,
Length - TrinityProtocol.TrinityMsgHeader,
preserved_sync_rsp_handlers[msgId]);
msgProcessResult = preserved_sync_rsp_args.MessageProcess();
_SetSendRecvBuff(msgProcessResult, sendRecvBuff, preserved_sync_rsp_args.Response);
return;
case TrinityMessageType.SYNC:
SynReqArgs sync_args = new SynReqArgs(ByteArray,
TrinityProtocol.TrinityMsgHeader,
Length - TrinityProtocol.TrinityMsgHeader,
sync_handlers[msgId]);
msgProcessResult = sync_args.MessageProcess();
_SetSendRecvBuff(msgProcessResult, sendRecvBuff);
return;
case TrinityMessageType.PRESERVED_SYNC:
SynReqArgs preserved_sync_args = new SynReqArgs(ByteArray,
TrinityProtocol.TrinityMsgHeader,
Length - TrinityProtocol.TrinityMsgHeader,
preserved_sync_handlers[msgId]);
msgProcessResult = preserved_sync_args.MessageProcess();
_SetSendRecvBuff(msgProcessResult, sendRecvBuff);
return;
case TrinityMessageType.ASYNC:
AsynReqArgs async_args = new AsynReqArgs(ByteArray,
TrinityProtocol.TrinityMsgHeader,
Length - TrinityProtocol.TrinityMsgHeader,
async_handlers[msgId]);
msgProcessResult = async_args.AsyncProcessMessage();
_SetSendRecvBuff(msgProcessResult, sendRecvBuff);
return;
case TrinityMessageType.PRESERVED_ASYNC:
AsynReqArgs preserved_async_args = new AsynReqArgs(ByteArray,
TrinityProtocol.TrinityMsgHeader,
Length - TrinityProtocol.TrinityMsgHeader,
preserved_async_handlers[msgId]);
msgProcessResult = preserved_async_args.AsyncProcessMessage();
_SetSendRecvBuff(msgProcessResult, sendRecvBuff);
return;
case TrinityMessageType.ASYNC_WITH_RSP:
AsynReqRspArgs async_rsp_args = new AsynReqRspArgs(ByteArray,
TrinityProtocol.TrinityMsgHeader,
Length - TrinityProtocol.TrinityMsgHeader,
async_rsp_handlers[msgId]);
msgProcessResult = async_rsp_args.AsyncProcessMessage();
_SetSendRecvBuff(msgProcessResult, sendRecvBuff);
return;
default:
throw new Exception("Not recognized message type.");
}
}
catch (Exception ex)
{
Log.WriteLine("Message Type: " + msgType);
Log.WriteLine("Message SN: " + msgId);
Log.WriteLine(ex.Message);
Log.WriteLine(ex.StackTrace);
_SetSendRecvBuff(TrinityErrorCode.E_RPC_EXCEPTION, sendRecvBuff);
return;
}
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents a meeting request that an attendee can accept or decline. Properties available on meeting requests are defined in the MeetingRequestSchema class.
/// </summary>
[ServiceObjectDefinition(XmlElementNames.MeetingRequest)]
public class MeetingRequest : MeetingMessage, ICalendarActionProvider
{
/// <summary>
/// Initializes a new instance of the <see cref="MeetingRequest"/> class.
/// </summary>
/// <param name="parentAttachment">The parent attachment.</param>
internal MeetingRequest(ItemAttachment parentAttachment)
: base(parentAttachment)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MeetingRequest"/> class.
/// </summary>
/// <param name="service">EWS service to which this object belongs.</param>
internal MeetingRequest(ExchangeService service)
: base(service)
{
}
/// <summary>
/// Binds to an existing meeting request and loads the specified set of properties.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="service">The service to use to bind to the meeting request.</param>
/// <param name="id">The Id of the meeting request to bind to.</param>
/// <param name="propertySet">The set of properties to load.</param>
/// <returns>A MeetingRequest instance representing the meeting request corresponding to the specified Id.</returns>
public static new MeetingRequest Bind(
ExchangeService service,
ItemId id,
PropertySet propertySet)
{
return service.BindToItem<MeetingRequest>(id, propertySet);
}
/// <summary>
/// Binds to an existing meeting request and loads its first class properties.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="service">The service to use to bind to the meeting request.</param>
/// <param name="id">The Id of the meeting request to bind to.</param>
/// <returns>A MeetingRequest instance representing the meeting request corresponding to the specified Id.</returns>
public static new MeetingRequest Bind(ExchangeService service, ItemId id)
{
return MeetingRequest.Bind(
service,
id,
PropertySet.FirstClassProperties);
}
/// <summary>
/// Internal method to return the schema associated with this type of object.
/// </summary>
/// <returns>The schema associated with this type of object.</returns>
internal override ServiceObjectSchema GetSchema()
{
return MeetingRequestSchema.Instance;
}
/// <summary>
/// Gets the minimum required server version.
/// </summary>
/// <returns>Earliest Exchange version in which this service object type is supported.</returns>
internal override ExchangeVersion GetMinimumRequiredServerVersion()
{
return ExchangeVersion.Exchange2007_SP1;
}
/// <summary>
/// Creates a local meeting acceptance message that can be customized and sent.
/// </summary>
/// <param name="tentative">Specifies whether the meeting will be tentatively accepted.</param>
/// <returns>An AcceptMeetingInvitationMessage representing the meeting acceptance message. </returns>
public AcceptMeetingInvitationMessage CreateAcceptMessage(bool tentative)
{
return new AcceptMeetingInvitationMessage(this, tentative);
}
/// <summary>
/// Creates a local meeting declination message that can be customized and sent.
/// </summary>
/// <returns>A DeclineMeetingInvitation representing the meeting declination message. </returns>
public DeclineMeetingInvitationMessage CreateDeclineMessage()
{
return new DeclineMeetingInvitationMessage(this);
}
/// <summary>
/// Accepts the meeting. Calling this method results in a call to EWS.
/// </summary>
/// <param name="sendResponse">Indicates whether to send a response to the organizer.</param>
/// <returns>
/// A CalendarActionResults object containing the various items that were created or modified as a
/// results of this operation.
/// </returns>
public CalendarActionResults Accept(bool sendResponse)
{
return this.InternalAccept(false, sendResponse);
}
/// <summary>
/// Tentatively accepts the meeting. Calling this method results in a call to EWS.
/// </summary>
/// <param name="sendResponse">Indicates whether to send a response to the organizer.</param>
/// <returns>
/// A CalendarActionResults object containing the various items that were created or modified as a
/// results of this operation.
/// </returns>
public CalendarActionResults AcceptTentatively(bool sendResponse)
{
return this.InternalAccept(true, sendResponse);
}
/// <summary>
/// Accepts the meeting.
/// </summary>
/// <param name="tentative">True if tentative accept.</param>
/// <param name="sendResponse">Indicates whether to send a response to the organizer.</param>
/// <returns>
/// A CalendarActionResults object containing the various items that were created or modified as a
/// results of this operation.
/// </returns>
internal CalendarActionResults InternalAccept(bool tentative, bool sendResponse)
{
AcceptMeetingInvitationMessage accept = this.CreateAcceptMessage(tentative);
if (sendResponse)
{
return accept.SendAndSaveCopy();
}
else
{
return accept.Save();
}
}
/// <summary>
/// Declines the meeting invitation. Calling this method results in a call to EWS.
/// </summary>
/// <param name="sendResponse">Indicates whether to send a response to the organizer.</param>
/// <returns>
/// A CalendarActionResults object containing the various items that were created or modified as a
/// results of this operation.
/// </returns>
public CalendarActionResults Decline(bool sendResponse)
{
DeclineMeetingInvitationMessage decline = this.CreateDeclineMessage();
if (sendResponse)
{
return decline.SendAndSaveCopy();
}
else
{
return decline.Save();
}
}
#region Properties
/// <summary>
/// Gets the type of this meeting request.
/// </summary>
public MeetingRequestType MeetingRequestType
{
get { return (MeetingRequestType)this.PropertyBag[MeetingRequestSchema.MeetingRequestType]; }
}
/// <summary>
/// Gets the a value representing the intended free/busy status of the meeting.
/// </summary>
public LegacyFreeBusyStatus IntendedFreeBusyStatus
{
get { return (LegacyFreeBusyStatus)this.PropertyBag[MeetingRequestSchema.IntendedFreeBusyStatus]; }
}
/// <summary>
/// Gets the change highlights of the meeting request.
/// </summary>
public ChangeHighlights ChangeHighlights
{
get { return (ChangeHighlights)this.PropertyBag[MeetingRequestSchema.ChangeHighlights]; }
}
/// <summary>
/// Gets the Enhanced location object.
/// </summary>
public EnhancedLocation EnhancedLocation
{
get { return (EnhancedLocation)this.PropertyBag[MeetingRequestSchema.EnhancedLocation]; }
}
/// <summary>
/// Gets the start time of the appointment.
/// </summary>
public DateTime Start
{
get { return (DateTime)this.PropertyBag[AppointmentSchema.Start]; }
}
/// <summary>
/// Gets the end time of the appointment.
/// </summary>
public DateTime End
{
get { return (DateTime)this.PropertyBag[AppointmentSchema.End]; }
}
/// <summary>
/// Gets the original start time of this appointment.
/// </summary>
public DateTime OriginalStart
{
get { return (DateTime)this.PropertyBag[AppointmentSchema.OriginalStart]; }
}
/// <summary>
/// Gets a value indicating whether this appointment is an all day event.
/// </summary>
public bool IsAllDayEvent
{
get { return (bool)this.PropertyBag[AppointmentSchema.IsAllDayEvent]; }
}
/// <summary>
/// Gets a value indicating the free/busy status of the owner of this appointment.
/// </summary>
public LegacyFreeBusyStatus LegacyFreeBusyStatus
{
get { return (LegacyFreeBusyStatus)this.PropertyBag[AppointmentSchema.LegacyFreeBusyStatus]; }
}
/// <summary>
/// Gets the location of this appointment.
/// </summary>
public string Location
{
get { return (string)this.PropertyBag[AppointmentSchema.Location]; }
}
/// <summary>
/// Gets a text indicating when this appointment occurs. The text returned by When is localized using the Exchange Server culture or using the culture specified in the PreferredCulture property of the ExchangeService object this appointment is bound to.
/// </summary>
public string When
{
get { return (string)this.PropertyBag[AppointmentSchema.When]; }
}
/// <summary>
/// Gets a value indicating whether the appointment is a meeting.
/// </summary>
public bool IsMeeting
{
get { return (bool)this.PropertyBag[AppointmentSchema.IsMeeting]; }
}
/// <summary>
/// Gets a value indicating whether the appointment has been cancelled.
/// </summary>
public bool IsCancelled
{
get { return (bool)this.PropertyBag[AppointmentSchema.IsCancelled]; }
}
/// <summary>
/// Gets a value indicating whether the appointment is recurring.
/// </summary>
public bool IsRecurring
{
get { return (bool)this.PropertyBag[AppointmentSchema.IsRecurring]; }
}
/// <summary>
/// Gets a value indicating whether the meeting request has already been sent.
/// </summary>
public bool MeetingRequestWasSent
{
get { return (bool)this.PropertyBag[AppointmentSchema.MeetingRequestWasSent]; }
}
/// <summary>
/// Gets a value indicating the type of this appointment.
/// </summary>
public AppointmentType AppointmentType
{
get { return (AppointmentType)this.PropertyBag[AppointmentSchema.AppointmentType]; }
}
/// <summary>
/// Gets a value indicating what was the last response of the user that loaded this meeting.
/// </summary>
public MeetingResponseType MyResponseType
{
get { return (MeetingResponseType)this.PropertyBag[AppointmentSchema.MyResponseType]; }
}
/// <summary>
/// Gets the organizer of this meeting.
/// </summary>
public EmailAddress Organizer
{
get { return (EmailAddress)this.PropertyBag[AppointmentSchema.Organizer]; }
}
/// <summary>
/// Gets a list of required attendees for this meeting.
/// </summary>
public AttendeeCollection RequiredAttendees
{
get { return (AttendeeCollection)this.PropertyBag[AppointmentSchema.RequiredAttendees]; }
}
/// <summary>
/// Gets a list of optional attendeed for this meeting.
/// </summary>
public AttendeeCollection OptionalAttendees
{
get { return (AttendeeCollection)this.PropertyBag[AppointmentSchema.OptionalAttendees]; }
}
/// <summary>
/// Gets a list of resources for this meeting.
/// </summary>
public AttendeeCollection Resources
{
get { return (AttendeeCollection)this.PropertyBag[AppointmentSchema.Resources]; }
}
/// <summary>
/// Gets the number of calendar entries that conflict with this appointment in the authenticated user's calendar.
/// </summary>
public int ConflictingMeetingCount
{
get { return (int)this.PropertyBag[AppointmentSchema.ConflictingMeetingCount]; }
}
/// <summary>
/// Gets the number of calendar entries that are adjacent to this appointment in the authenticated user's calendar.
/// </summary>
public int AdjacentMeetingCount
{
get { return (int)this.PropertyBag[AppointmentSchema.AdjacentMeetingCount]; }
}
/// <summary>
/// Gets a list of meetings that conflict with this appointment in the authenticated user's calendar.
/// </summary>
public ItemCollection<Appointment> ConflictingMeetings
{
get { return (ItemCollection<Appointment>)this.PropertyBag[AppointmentSchema.ConflictingMeetings]; }
}
/// <summary>
/// Gets a list of meetings that conflict with this appointment in the authenticated user's calendar.
/// </summary>
public ItemCollection<Appointment> AdjacentMeetings
{
get { return (ItemCollection<Appointment>)this.PropertyBag[AppointmentSchema.AdjacentMeetings]; }
}
/// <summary>
/// Gets the duration of this appointment.
/// </summary>
public TimeSpan Duration
{
get { return (TimeSpan)this.PropertyBag[AppointmentSchema.Duration]; }
}
/// <summary>
/// Gets the name of the time zone this appointment is defined in.
/// </summary>
public string TimeZone
{
get { return (string)this.PropertyBag[AppointmentSchema.TimeZone]; }
}
/// <summary>
/// Gets the time when the attendee replied to the meeting request.
/// </summary>
public DateTime AppointmentReplyTime
{
get { return (DateTime)this.PropertyBag[AppointmentSchema.AppointmentReplyTime]; }
}
/// <summary>
/// Gets the sequence number of this appointment.
/// </summary>
public int AppointmentSequenceNumber
{
get { return (int)this.PropertyBag[AppointmentSchema.AppointmentSequenceNumber]; }
}
/// <summary>
/// Gets the state of this appointment.
/// </summary>
public int AppointmentState
{
get { return (int)this.PropertyBag[AppointmentSchema.AppointmentState]; }
}
/// <summary>
/// Gets the recurrence pattern for this meeting request.
/// </summary>
public Recurrence Recurrence
{
get { return (Recurrence)this.PropertyBag[AppointmentSchema.Recurrence]; }
}
/// <summary>
/// Gets an OccurrenceInfo identifying the first occurrence of this meeting.
/// </summary>
public OccurrenceInfo FirstOccurrence
{
get { return (OccurrenceInfo)this.PropertyBag[AppointmentSchema.FirstOccurrence]; }
}
/// <summary>
/// Gets an OccurrenceInfo identifying the last occurrence of this meeting.
/// </summary>
public OccurrenceInfo LastOccurrence
{
get { return (OccurrenceInfo)this.PropertyBag[AppointmentSchema.LastOccurrence]; }
}
/// <summary>
/// Gets a list of modified occurrences for this meeting.
/// </summary>
public OccurrenceInfoCollection ModifiedOccurrences
{
get { return (OccurrenceInfoCollection)this.PropertyBag[AppointmentSchema.ModifiedOccurrences]; }
}
/// <summary>
/// Gets a list of deleted occurrences for this meeting.
/// </summary>
public DeletedOccurrenceInfoCollection DeletedOccurrences
{
get { return (DeletedOccurrenceInfoCollection)this.PropertyBag[AppointmentSchema.DeletedOccurrences]; }
}
/// <summary>
/// Gets time zone of the start property of this meeting request.
/// </summary>
public TimeZoneInfo StartTimeZone
{
get { return (TimeZoneInfo)this.PropertyBag[AppointmentSchema.StartTimeZone]; }
}
/// <summary>
/// Gets time zone of the end property of this meeting request.
/// </summary>
public TimeZoneInfo EndTimeZone
{
get { return (TimeZoneInfo)this.PropertyBag[AppointmentSchema.EndTimeZone]; }
}
/// <summary>
/// Gets the type of conferencing that will be used during the meeting.
/// </summary>
public int ConferenceType
{
get { return (int)this.PropertyBag[AppointmentSchema.ConferenceType]; }
}
/// <summary>
/// Gets a value indicating whether new time proposals are allowed for attendees of this meeting.
/// </summary>
public bool AllowNewTimeProposal
{
get { return (bool)this.PropertyBag[AppointmentSchema.AllowNewTimeProposal]; }
}
/// <summary>
/// Gets a value indicating whether this is an online meeting.
/// </summary>
public bool IsOnlineMeeting
{
get { return (bool)this.PropertyBag[AppointmentSchema.IsOnlineMeeting]; }
}
/// <summary>
/// Gets the URL of the meeting workspace. A meeting workspace is a shared Web site for planning meetings and tracking results.
/// </summary>
public string MeetingWorkspaceUrl
{
get { return (string)this.PropertyBag[AppointmentSchema.MeetingWorkspaceUrl]; }
}
/// <summary>
/// Gets the URL of the Microsoft NetShow online meeting.
/// </summary>
public string NetShowUrl
{
get { return (string)this.PropertyBag[AppointmentSchema.NetShowUrl]; }
}
#endregion
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
namespace Boo.Lang.Compiler.Steps
{
using System.Text;
using Boo.Lang.Compiler;
using Boo.Lang.Compiler.Ast;
public class PreErrorChecking : AbstractVisitorCompilerStep
{
static string[] InvalidMemberPrefixes = new string[] {
"___",
"get_",
"set_",
"add_",
"remove_",
"raise_" };
override public void Run()
{
Visit(CompileUnit);
}
override public void LeaveField(Field node)
{
MakeStaticIfNeeded(node);
CheckMemberName(node);
CantBeMarkedAbstract(node);
CantBeMarkedPartial(node);
}
override public void LeaveProperty(Property node)
{
MakeStaticIfNeeded(node);
CheckMemberName(node);
CantBeMarkedTransient(node);
CantBeMarkedPartial(node);
CheckExplicitImpl(node);
CheckModifierCombination(node);
}
override public void LeaveConstructor(Constructor node)
{
MakeStaticIfNeeded(node);
CantBeMarkedTransient(node);
CantBeMarkedPartial(node);
CantBeMarkedFinal(node);
CannotReturnValue(node);
ConstructorCannotBePolymorphic(node);
}
override public void LeaveMethod(Method node)
{
MakeStaticIfNeeded(node);
CheckMemberName(node);
CantBeMarkedTransient(node);
CantBeMarkedPartial(node);
CheckExplicitImpl(node);
CheckModifierCombination(node);
}
override public void LeaveEvent(Event node)
{
MakeStaticIfNeeded(node);
CheckMemberName(node);
CantBeMarkedPartial(node);
CheckModifierCombination(node);
}
override public void LeaveInterfaceDefinition(InterfaceDefinition node)
{
CheckMemberName(node);
CantBeMarkedAbstract(node);
CantBeMarkedTransient(node);
CantBeMarkedPartial(node);
CantBeMarkedFinal(node);
CantBeMarkedStatic(node);
}
override public void LeaveCallableDefinition(CallableDefinition node)
{
MakeStaticIfNeeded(node);
CheckMemberName(node);
CantBeMarkedAbstract(node);
CantBeMarkedTransient(node);
CantBeMarkedPartial(node);
}
public override void LeaveStructDefinition(StructDefinition node)
{
CheckMemberName(node);
CantBeMarkedAbstract(node);
CantBeMarkedFinal(node);
CantBeMarkedStatic(node);
CantBeMarkedPartial(node);
}
override public void LeaveClassDefinition(ClassDefinition node)
{
CheckModifierCombination(node);
CheckMemberName(node);
if(node.IsStatic)
{
node.Modifiers |= TypeMemberModifiers.Abstract | TypeMemberModifiers.Final;
}
}
override public void LeaveTryStatement(TryStatement node)
{
if (node.EnsureBlock == null && node.FailureBlock == null && node.ExceptionHandlers.Count == 0)
{
Error(CompilerErrorFactory.InvalidTryStatement(node));
}
}
override public void LeaveBinaryExpression(BinaryExpression node)
{
if (BinaryOperatorType.Assign == node.Operator
&& (node.Right.NodeType != NodeType.TryCastExpression)
&& (IsTopLevelOfConditional(node)))
{
Warnings.Add(CompilerWarningFactory.EqualsInsteadOfAssign(node));
}
}
bool IsTopLevelOfConditional(Node child)
{
Node parent = child.ParentNode;
return (parent.NodeType == NodeType.IfStatement
|| parent.NodeType == NodeType.UnlessStatement
|| parent.NodeType == NodeType.ConditionalExpression
|| parent.NodeType == NodeType.StatementModifier
|| parent.NodeType == NodeType.ReturnStatement
|| parent.NodeType == NodeType.YieldStatement);
}
override public void LeaveDestructor(Destructor node)
{
if (node.Modifiers != TypeMemberModifiers.None)
{
Error(CompilerErrorFactory.InvalidDestructorModifier(node));
}
if (node.Parameters.Count != 0)
{
Error(CompilerErrorFactory.CantHaveDestructorParameters(node));
}
CannotReturnValue(node);
}
void ConstructorCannotBePolymorphic(Constructor node)
{
if(node.IsAbstract || node.IsOverride || node.IsVirtual)
{
Error(CompilerErrorFactory.ConstructorCantBePolymorphic(node, node.FullName));
}
}
private void CannotReturnValue(Method node)
{
if (node.ReturnType != null)
{
Error(CompilerErrorFactory.CannotReturnValue(node));
}
}
void CantBeMarkedAbstract(TypeMember member)
{
if (member.IsAbstract)
{
Error(CompilerErrorFactory.CantBeMarkedAbstract(member));
}
}
void CantBeMarkedFinal(TypeMember member)
{
if (member.IsFinal)
{
Error(CompilerErrorFactory.CantBeMarkedFinal(member));
}
}
void CantBeMarkedTransient(TypeMember member)
{
if (member.IsTransient)
{
Error(CompilerErrorFactory.CantBeMarkedTransient(member));
}
}
void CheckMemberName(TypeMember node)
{
foreach (string prefix in InvalidMemberPrefixes)
{
if (node.Name.StartsWith(prefix))
{
Error(CompilerErrorFactory.ReservedPrefix(node, prefix));
break;
}
}
}
void MakeStaticIfNeeded(TypeMember node)
{
if(node.DeclaringType.IsStatic)
{
if(node.IsStatic)
{
Warnings.Add(CompilerWarningFactory.StaticClassMemberRedundantlyMarkedStatic(node, node.DeclaringType.Name, node.Name));
}
node.Modifiers |= TypeMemberModifiers.Static;
}
}
void CheckExplicitImpl(IExplicitMember member)
{
ExplicitMemberInfo ei = member.ExplicitInfo;
if (null == ei)
{
return;
}
TypeMember node = (TypeMember)member;
if (TypeMemberModifiers.None != node.Modifiers)
{
Error(
CompilerErrorFactory.ExplicitImplMustNotHaveModifiers(
node,
ei.InterfaceType.Name,
node.Name));
}
}
void CheckModifierCombination(TypeMember member)
{
InvalidCombination(member, TypeMemberModifiers.Static, TypeMemberModifiers.Abstract);
InvalidCombination(member, TypeMemberModifiers.Static, TypeMemberModifiers.Virtual);
InvalidCombination(member, TypeMemberModifiers.Static, TypeMemberModifiers.Override);
InvalidCombination(member, TypeMemberModifiers.Abstract, TypeMemberModifiers.Final);
if (member.NodeType != NodeType.Field)
{
InvalidCombination(member, TypeMemberModifiers.Static, TypeMemberModifiers.Final);
}
}
void InvalidCombination(TypeMember member, TypeMemberModifiers mod1, TypeMemberModifiers mod2)
{
if (!member.IsModifierSet(mod1) || !member.IsModifierSet(mod2)) return;
Error(
CompilerErrorFactory.InvalidCombinationOfModifiers(
member,
member.FullName,
string.Format("{0}, {1}", mod1.ToString().ToLower(), mod2.ToString().ToLower())));
}
void CantBeMarkedPartial(TypeMember member)
{
if (member.IsPartial)
{
Error(CompilerErrorFactory.CantBeMarkedPartial(member));
}
}
void CantBeMarkedStatic(TypeMember member)
{
if (member.IsStatic)
{
Error(CompilerErrorFactory.CantBeMarkedStatic(member));
}
}
}
}
| |
//-------------------------------------------------------------------------
// <copyright file="Constraints.cs">
// Copyright 2008-2010 Louis DeJardin - http://whereslou.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Louis DeJardin</author>
// <author>John Gietzen</author>
//-------------------------------------------------------------------------
namespace Spark.Tests.Parser
{
using System;
using System.Linq;
using NUnit.Framework;
using Spark.Parser;
using Spark.Parser.Markup;
[TestFixture]
public class MarkupGrammarTester
{
private MarkupGrammar grammar;
[SetUp]
public void Init()
{
grammar = new MarkupGrammar();
}
private Position Source(string content)
{
return new Position(new SourceContext(content));
}
[Test]
public void RepDigits()
{
ParseAction<char> digit =
delegate(Position input)
{
if (input.PotentialLength() == 0 || !char.IsDigit(input.Peek())) return null;
return new ParseResult<char>(input.Advance(1), input.Peek());
};
var digits = digit.Rep();
var result = digits(Source("55407"));
Assert.AreEqual(0, result.Rest.PotentialLength());
Assert.AreEqual("55407", new String(result.Value.ToArray()));
}
[Test]
public void TextNode()
{
var result = grammar.Text(Source("hello world"));
Assert.AreEqual("hello world", result.Value.Text);
var result2 = grammar.Text(Source("hello world"));
Assert.AreEqual("hello", result2.Value.Text);
}
[Test]
public void EntityNode()
{
var result = grammar.EntityRef(Source("<"));
Assert.AreEqual("lt", result.Value.Name);
var result2 = grammar.EntityRef(Source("<world"));
Assert.AreEqual("lt", result2.Value.Name);
var result3 = grammar.EntityRef(Source("hello<world"));
Assert.IsNull(result3);
}
[Test]
public void Rep1WontBeNone()
{
var parser = CharGrammar.Ch('x').Rep1();
var three = parser(Source("xxx5"));
Assert.IsNotNull(three);
Assert.AreEqual(3, three.Value.Count);
var nada = parser(Source("yxxx"));
Assert.IsNull(nada);
}
[Test]
public void EntityTextSeries()
{
var result = grammar.Nodes(Source("hello world"));
Assert.IsNotNull(result);
Assert.AreEqual(3, result.Value.Count);
Assert.IsAssignableFrom(typeof(TextNode), result.Value[0]);
Assert.IsAssignableFrom(typeof(EntityNode), result.Value[1]);
Assert.IsAssignableFrom(typeof(TextNode), result.Value[2]);
}
[Test]
public void ParsingAttribute()
{
var result = grammar.Attribute(Source("foo=\"quad\""));
Assert.IsNotNull(result);
Assert.AreEqual("foo", result.Value.Name);
Assert.AreEqual("quad", result.Value.Value);
var result2 = grammar.Attribute(Source("foo2='quad2'"));
Assert.IsNotNull(result2);
Assert.AreEqual("foo2", result2.Value.Name);
Assert.AreEqual("quad2", result2.Value.Value);
var result3 = grammar.Attribute(Source("foo3!='quad2'"));
Assert.IsNull(result3);
}
[Test]
public void ParsingElement()
{
var result = grammar.Element(Source("<blah>"));
Assert.IsNotNull(result);
Assert.AreEqual("blah", result.Value.Name);
}
[Test]
public void ParsingElementWithAttributes()
{
var result = grammar.Element(Source("<blah foo=\"quad\" omg=\"w00t\">"));
Assert.IsNotNull(result);
Assert.AreEqual("blah", result.Value.Name);
Assert.AreEqual(2, result.Value.Attributes.Count);
Assert.AreEqual("foo", result.Value.Attributes[0].Name);
Assert.AreEqual("quad", result.Value.Attributes[0].Value);
Assert.AreEqual("omg", result.Value.Attributes[1].Name);
Assert.AreEqual("w00t", result.Value.Attributes[1].Value);
}
[Test]
public void AttributeWithEntity()
{
var result = grammar.Element(Source("<blah attr=\"foo & bar\" />"));
Assert.IsNotNull(result);
Assert.AreEqual("blah", result.Value.Name);
Assert.AreEqual(1, result.Value.Attributes.Count);
Assert.AreEqual(3, result.Value.Attributes[0].Nodes.Count);
Assert.AreEqual("foo ", (result.Value.Attributes[0].Nodes[0] as TextNode).Text);
Assert.AreEqual("amp", (result.Value.Attributes[0].Nodes[1] as EntityNode).Name);
Assert.AreEqual(" bar", (result.Value.Attributes[0].Nodes[2] as TextNode).Text);
result = grammar.Element(Source("<blah attr='foo & bar' />"));
Assert.IsNotNull(result);
Assert.AreEqual("blah", result.Value.Name);
Assert.AreEqual(1, result.Value.Attributes.Count);
Assert.AreEqual(3, result.Value.Attributes[0].Nodes.Count);
Assert.AreEqual("foo ", (result.Value.Attributes[0].Nodes[0] as TextNode).Text);
Assert.AreEqual("amp", (result.Value.Attributes[0].Nodes[1] as EntityNode).Name);
Assert.AreEqual(" bar", (result.Value.Attributes[0].Nodes[2] as TextNode).Text);
}
[Test]
public void AttributeWithConditionalAnd()
{
var result = grammar.Element(Source("<blah attr=\"foo && bar\" />"));
Assert.IsNotNull(result);
Assert.AreEqual("blah", result.Value.Name);
Assert.AreEqual(1, result.Value.Attributes.Count);
Assert.AreEqual(4, result.Value.Attributes[0].Nodes.Count);
Assert.AreEqual("foo ", (result.Value.Attributes[0].Nodes[0] as TextNode).Text);
Assert.AreEqual("&", (result.Value.Attributes[0].Nodes[1] as TextNode).Text);
Assert.AreEqual("&", (result.Value.Attributes[0].Nodes[2] as TextNode).Text);
Assert.AreEqual(" bar", (result.Value.Attributes[0].Nodes[3] as TextNode).Text);
result = grammar.Element(Source("<blah attr='foo && bar' />"));
Assert.IsNotNull(result);
Assert.AreEqual("blah", result.Value.Name);
Assert.AreEqual(1, result.Value.Attributes.Count);
Assert.AreEqual(4, result.Value.Attributes[0].Nodes.Count);
Assert.AreEqual("foo ", (result.Value.Attributes[0].Nodes[0] as TextNode).Text);
Assert.AreEqual("&", (result.Value.Attributes[0].Nodes[1] as TextNode).Text);
Assert.AreEqual("&", (result.Value.Attributes[0].Nodes[2] as TextNode).Text);
Assert.AreEqual(" bar", (result.Value.Attributes[0].Nodes[3] as TextNode).Text);
}
[Test]
public void ParsingEndElement()
{
var result = grammar.EndElement(Source("</blah>"));
Assert.IsNotNull(result);
Assert.IsAssignableFrom(typeof(EndElementNode), result.Value);
Assert.AreEqual("blah", result.Value.Name);
}
[Test]
public void PassingSimpleMarkup()
{
var result = grammar.Nodes(Source("<foo><bar>one</bar><quad a='1' b='2'>55</quad></foo>"));
Assert.IsNotNull(result);
Assert.AreEqual(0, result.Rest.PotentialLength());
Assert.AreEqual(8, result.Value.Count);
Assert.IsAssignableFrom(typeof(ElementNode), result.Value[4]);
var elt = result.Value[4] as ElementNode;
Assert.AreEqual("quad", elt.Name);
Assert.AreEqual(2, elt.Attributes.Count);
Assert.AreEqual("2", elt.Attributes[1].Value);
}
[Test]
public void SelfEnding()
{
var result = grammar.Nodes(Source("<div><br/></div>"));
Assert.IsAssignableFrom(typeof(ElementNode), result.Value[0]);
Assert.IsAssignableFrom(typeof(ElementNode), result.Value[1]);
Assert.IsAssignableFrom(typeof(EndElementNode), result.Value[2]);
var div = result.Value[0] as ElementNode;
Assert.AreEqual("div", div.Name);
Assert.That(!div.IsEmptyElement);
var br = result.Value[1] as ElementNode;
Assert.AreEqual("br", br.Name);
Assert.That(br.IsEmptyElement);
var ediv = result.Value[2] as EndElementNode;
Assert.AreEqual("div", ediv.Name);
}
[Test]
public void DoctypeParser()
{
var result =
grammar.DoctypeDecl(
Source(
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-strict.dtd\">"));
Assert.IsNotNull(result);
Assert.AreEqual("html", result.Value.Name);
Assert.AreEqual("PUBLIC", result.Value.ExternalId.ExternalIdType);
Assert.AreEqual("-//W3C//DTD XHTML 1.0 Strict//EN", result.Value.ExternalId.PublicId);
Assert.AreEqual("http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-strict.dtd", result.Value.ExternalId.SystemId);
var result2 =
grammar.DoctypeDecl(
Source(
"<!DOCTYPE html PUBLIC \"http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-strict.dtd\">"));
Assert.IsNull(result2);
var result3 =
grammar.DoctypeDecl(
Source(
"<!DOCTYPE html SYSTEM 'hello world'>"));
Assert.IsNotNull(result);
Assert.AreEqual("html", result3.Value.Name);
Assert.AreEqual("SYSTEM", result3.Value.ExternalId.ExternalIdType);
Assert.AreEqual("hello world", result3.Value.ExternalId.SystemId);
var result4 =
grammar.DoctypeDecl(
Source(
"<!DOCTYPE foo >"));
Assert.IsNotNull(result4);
Assert.AreEqual("foo", result4.Value.Name);
Assert.IsNull(result4.Value.ExternalId);
}
[Test]
public void CodeInText()
{
var result = grammar.Nodes(Source("<hello>foo${bar}ex</hello>"));
Assert.IsNotNull(result);
Assert.AreEqual(5, result.Value.Count);
Assert.IsAssignableFrom(typeof(ExpressionNode), result.Value[2]);
var code = (ExpressionNode)result.Value[2];
Assert.AreEqual("bar", (string)code.Code);
result = grammar.Nodes(Source("<hello>foo<%=baaz%>ex</hello>"));
Assert.IsNotNull(result);
Assert.AreEqual(5, result.Value.Count);
Assert.IsAssignableFrom(typeof(ExpressionNode), result.Value[2]);
var code2 = (ExpressionNode)result.Value[2];
Assert.AreEqual("baaz", (string)code2.Code);
result = grammar.Nodes(Source("<hello href='${one}' class=\"<%=two%>\"/>"));
Assert.IsNotNull(result);
Assert.AreEqual(1, result.Value.Count);
Assert.IsAssignableFrom(typeof(ElementNode), result.Value[0]);
var elt = (ElementNode)result.Value[0];
Assert.AreEqual("one", (string)((ExpressionNode)elt.Attributes[0].Nodes[0]).Code);
Assert.AreEqual("two", (string)((ExpressionNode)elt.Attributes[1].Nodes[0]).Code);
}
[Test]
public void AspxStyleOutputInText()
{
var result = grammar.Nodes(Source("<hello>foo<%=bar%>ex</hello>"));
Assert.IsNotNull(result);
Assert.AreEqual(5, result.Value.Count);
Assert.IsAssignableFrom(typeof(ExpressionNode), result.Value[2]);
var code = result.Value[2] as ExpressionNode;
Assert.AreEqual("bar", (string)code.Code);
Assert.AreEqual("foo", ((TextNode)result.Value[1]).Text);
Assert.AreEqual("ex", ((TextNode)result.Value[3]).Text);
}
[Test]
public void CommentParser()
{
var result = grammar.Comment(Source("<!-- hello world -->"));
Assert.IsNotNull(result);
Assert.AreEqual(" hello world ", result.Value.Text);
var result2 = grammar.Comment(Source("<!-- hello-world -->"));
Assert.IsNotNull(result2);
Assert.AreEqual(" hello-world ", result2.Value.Text);
var result3 = grammar.Comment(Source("<!-- hello--world -->"));
Assert.IsNull(result3);
}
[Test]
public void CodeStatementsPercentSyntax()
{
var direct = grammar.Statement(Source("<%int x = 5;%>"));
Assert.AreEqual("int x = 5;", (string)direct.Value.Code);
var result = grammar.Nodes(Source("<div>hello <%int x = 5;%> world</div>"));
Assert.IsNotNull(result);
Assert.AreEqual(5, result.Value.Count);
var stmt = result.Value[2] as StatementNode;
Assert.IsNotNull(stmt);
Assert.AreEqual("int x = 5;", (string)stmt.Code);
}
[Test]
public void CodeStatementsHashSyntax()
{
var direct = grammar.Statement(Source("\n#int x = 5;\n"));
Assert.AreEqual("int x = 5;", (string)direct.Value.Code);
var result = grammar.Nodes(Source("<div>hello\n #int x = 5;\n world</div>"));
Assert.IsNotNull(result);
Assert.AreEqual(5, result.Value.Count);
var stmt = result.Value[2] as StatementNode;
Assert.IsNotNull(stmt);
Assert.AreEqual("int x = 5;", (string)stmt.Code);
}
[Test]
public void SpecialCharactersInAttributes()
{
var attr1 = grammar.Attribute(Source("foo=\"bar$('hello')\""));
Assert.AreEqual("bar$('hello')", attr1.Value.Value);
var attr2 = grammar.Attribute(Source("foo=\"$('#hello')\""));
Assert.AreEqual("$('#hello')", attr2.Value.Value);
var attr3 = grammar.Attribute(Source("foo='#hello'"));
Assert.AreEqual("#hello", attr3.Value.Value);
}
[Test]
public void JQueryIdSelectorInAttribute()
{
var attr1 = grammar.Attribute(Source("foo='javascript:$(\"#diff\").hide()'"));
Assert.AreEqual("javascript:$(\"#diff\").hide()", attr1.Value.Value);
var attr2 = grammar.Attribute(Source("foo=\"javascript:$('#diff').hide()\""));
Assert.AreEqual("javascript:$('#diff').hide()", attr2.Value.Value);
}
[Test]
public void JQueryIdSelectorInText()
{
var nodes1 = grammar.Nodes(Source("<script>\r\n$(\"#diff\").hide();\r\n</script>"));
Assert.AreEqual(3, nodes1.Value.Count);
Assert.That(((TextNode)nodes1.Value[1]).Text, Tests.Contains.InOrder("$(\"#diff\").hide();"));
var nodes2 = grammar.Nodes(Source("<script>\r\n$('#diff').hide();\r\n</script>"));
Assert.AreEqual(3, nodes2.Value.Count);
Assert.That(((TextNode)nodes2.Value[1]).Text, Tests.Contains.InOrder("$('#diff').hide();"));
}
[Test]
public void HashStatementMustBeFirstNonWhitespaceCharacter()
{
var nodes1 = grammar.Nodes(Source("<p>abc\r\n \t#Logger.Warn('Hello World');\r\ndef</p>"));
Assert.AreEqual(5, nodes1.Value.Count);
Assert.AreEqual("Logger.Warn(\"Hello World\");", (string)((StatementNode)nodes1.Value[2]).Code);
var nodes2 = grammar.Nodes(Source("<p>abc\r\n \t x#Logger.Warn('Hello World');\r\ndef</p>"));
Assert.AreEqual(3, nodes2.Value.Count);
Assert.AreEqual("abc\r\n \t x#Logger.Warn('Hello World');\r\ndef", (string)((TextNode)nodes2.Value[1]).Text);
}
[Test]
public void ConditionalSyntaxInAttributes()
{
var attr = grammar.Attribute(Source("foo=\"one?{true}\""));
Assert.AreEqual(0, attr.Rest.PotentialLength());
Assert.AreEqual("foo", attr.Value.Name);
Assert.AreEqual(2, attr.Value.Nodes.Count);
Assert.AreEqual("one?{true}", attr.Value.Value);
Assert.AreEqual("one", ((TextNode)attr.Value.Nodes[0]).Text);
Assert.AreEqual("true", (string)((ConditionNode)attr.Value.Nodes[1]).Code);
}
[Test]
public void XMLDeclParser()
{
var result =
grammar.XMLDecl(
Source("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
Assert.IsNotNull(result);
Assert.AreEqual("UTF-8", result.Value.Encoding);
Assert.IsNull(result.Value.Standalone);
result =
grammar.XMLDecl(
Source("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone='no' ?>"));
Assert.IsNotNull(result);
Assert.AreEqual("UTF-8", result.Value.Encoding);
Assert.AreEqual("no", result.Value.Standalone);
result =
grammar.XMLDecl(
Source("<?xml version=\"1.0\" standalone=\"yes\" ?>"));
Assert.IsNotNull(result);
Assert.IsNull(result.Value.Encoding);
Assert.AreEqual("yes", result.Value.Standalone);
}
[Test]
public void ProcessingInstructionWontParseXMLDecl()
{
var result =
grammar.ProcessingInstruction(
Source("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
Assert.IsNull(result);
}
[Test]
public void ProcessingInstruction()
{
var result = grammar.ProcessingInstruction(
Source("<?foo?>"));
Assert.AreEqual("foo", result.Value.Name);
Assert.That(string.IsNullOrEmpty(result.Value.Body));
result = grammar.ProcessingInstruction(
Source("<?php hello ?>"));
Assert.AreEqual("php", result.Value.Name);
Assert.AreEqual("hello ", result.Value.Body);
}
[Test]
public void LessThanCanBeUsedAsText()
{
var result = grammar.Nodes(
Source("<p class=\"three<four\">One<Two</p>"));
Assert.AreEqual(5, result.Value.Count);
Assert.AreEqual("<", ((TextNode)result.Value[2]).Text);
var elt = (ElementNode) result.Value[0];
Assert.AreEqual(3, elt.Attributes[0].Nodes.Count);
Assert.AreEqual("<", ((TextNode)elt.Attributes[0].Nodes[1]).Text);
}
[Test]
public void StatementAtStartOfFile()
{
var result1 = grammar.Nodes(
Source("#alpha\r\n"));
Assert.AreEqual(2, result1.Value.Count);
Assert.IsInstanceOf(typeof(StatementNode), result1.Value[0]);
Assert.AreEqual("alpha", (string)((StatementNode)result1.Value[0]).Code);
Assert.IsInstanceOf(typeof(TextNode), result1.Value[1]);
Assert.AreEqual("\r\n", ((TextNode)result1.Value[1]).Text);
var result2 = grammar.Nodes(
Source("#alpha\r\ntext\r\n#beta"));
Assert.AreEqual(3, result2.Value.Count);
Assert.IsInstanceOf(typeof(StatementNode), result2.Value[0]);
Assert.AreEqual("alpha", (string)((StatementNode)result2.Value[0]).Code);
Assert.IsInstanceOf(typeof(TextNode), result2.Value[1]);
Assert.AreEqual("\r\ntext", ((TextNode)result2.Value[1]).Text);
Assert.IsInstanceOf(typeof(StatementNode), result2.Value[2]);
Assert.AreEqual("beta", (string)((StatementNode)result2.Value[2]).Code);
var result3 = grammar.Nodes(
Source("\r\n#alpha\r\ntext\r\n#beta\r\n"));
Assert.AreEqual(4, result3.Value.Count);
Assert.IsInstanceOf(typeof(StatementNode), result3.Value[0]);
Assert.AreEqual("alpha", (string)((StatementNode)result3.Value[0]).Code);
Assert.IsInstanceOf(typeof(TextNode), result3.Value[1]);
Assert.AreEqual("\r\ntext", ((TextNode)result3.Value[1]).Text);
Assert.IsInstanceOf(typeof(StatementNode), result3.Value[2]);
Assert.AreEqual("beta", (string)((StatementNode)result3.Value[2]).Code);
Assert.IsInstanceOf(typeof(TextNode), result3.Value[3]);
Assert.AreEqual("\r\n", ((TextNode)result3.Value[3]).Text);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WebRequest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.IO;
using System.Net.Cache;
using System.Net.Configuration;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Security;
using System.ComponentModel;
using System.Security;
//
// WebRequest - the base class of all Web resource/protocol objects. Provides
// common methods, data and proprties for making the top level request
//
/// <devdoc>
/// <para>A request to a Uniform Resource Identifier (Uri). This
/// is an abstract class.</para>
/// </devdoc>
[Serializable]
public abstract class WebRequest : MarshalByRefObject, ISerializable
{
#if FEATURE_PAL // ROTORTODO - after speed ups (like real JIT and GC) remove this one
#if DEBUG
internal const int DefaultTimeout = 100000 * 10;
#else // DEBUG
internal const int DefaultTimeout = 100000 * 5;
#endif // DEBUG
#else // FEATURE_PAL
internal const int DefaultTimeout = 100000; // default timeout is 100 seconds (ASP .NET is 90 seconds)
#endif // FEATURE_PAL
private static volatile ArrayList s_PrefixList;
private static Object s_InternalSyncObject;
private static TimerThread.Queue s_DefaultTimerQueue = TimerThread.CreateQueue(DefaultTimeout);
#if !FEATURE_PAL
private AuthenticationLevel m_AuthenticationLevel;
private TokenImpersonationLevel m_ImpersonationLevel;
#endif
private RequestCachePolicy m_CachePolicy;
private RequestCacheProtocol m_CacheProtocol;
private RequestCacheBinding m_CacheBinding;
#region designer support for System.Windows.dll
internal class DesignerWebRequestCreate : IWebRequestCreate
{
public WebRequest Create(Uri uri)
{
return WebRequest.Create(uri);
}
}
private static DesignerWebRequestCreate webRequestCreate = new DesignerWebRequestCreate();
//introduced for supporting design-time loading of System.Windows.dll
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual IWebRequestCreate CreatorInstance { get { return webRequestCreate; } }
//introduced for supporting design-time loading of System.Windows.dll
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static void RegisterPortableWebRequestCreator(IWebRequestCreate creator) { }
#endregion
private static Object InternalSyncObject {
get {
if (s_InternalSyncObject == null) {
Object o = new Object();
Interlocked.CompareExchange(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
internal static TimerThread.Queue DefaultTimerQueue {
get {
return s_DefaultTimerQueue;
}
}
/*++
Create - Create a WebRequest.
This is the main creation routine. We take a Uri object, look
up the Uri in the prefix match table, and invoke the appropriate
handler to create the object. We also have a parameter that
tells us whether or not to use the whole Uri or just the
scheme portion of it.
Input:
RequestUri - Uri object for request.
UseUriBase - True if we're only to look at the scheme
portion of the Uri.
Returns:
Newly created WebRequest.
--*/
private static WebRequest Create(Uri requestUri, bool useUriBase) {
if(Logging.On)Logging.Enter(Logging.Web, "WebRequest", "Create", requestUri.ToString());
string LookupUri;
WebRequestPrefixElement Current = null;
bool Found = false;
if (!useUriBase)
{
LookupUri = requestUri.AbsoluteUri;
}
else {
//
// schemes are registered as <schemeName>":", so add the separator
// to the string returned from the Uri object
//
LookupUri = requestUri.Scheme + ':';
}
int LookupLength = LookupUri.Length;
// Copy the prefix list so that if it is updated it will
// not affect us on this thread.
ArrayList prefixList = PrefixList;
// Look for the longest matching prefix.
// Walk down the list of prefixes. The prefixes are kept longest
// first. When we find a prefix that is shorter or the same size
// as this Uri, we'll do a compare to see if they match. If they
// do we'll break out of the loop and call the creator.
for (int i = 0; i < prefixList.Count; i++) {
Current = (WebRequestPrefixElement)prefixList[i];
//
// See if this prefix is short enough.
//
if (LookupLength >= Current.Prefix.Length) {
//
// It is. See if these match.
//
if (String.Compare(Current.Prefix,
0,
LookupUri,
0,
Current.Prefix.Length,
StringComparison.OrdinalIgnoreCase ) == 0) {
//
// These match. Remember that we found it and break
// out.
//
Found = true;
break;
}
}
}
WebRequest webRequest = null;
if (Found) {
//
// We found a match, so just call the creator and return what it
// does.
//
webRequest = Current.Creator.Create(requestUri);
if(Logging.On)Logging.Exit(Logging.Web, "WebRequest", "Create", webRequest);
return webRequest;
}
if(Logging.On)Logging.Exit(Logging.Web, "WebRequest", "Create", null);
//
// Otherwise no match, throw an exception.
//
throw new NotSupportedException(SR.GetString(SR.net_unknown_prefix));
}
/*++
Create - Create a WebRequest.
An overloaded utility version of the real Create that takes a
string instead of an Uri object.
Input:
RequestString - Uri string to create.
Returns:
Newly created WebRequest.
--*/
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Net.WebRequest'/>
/// instance for
/// the specified Uri scheme.
/// </para>
/// </devdoc>
public static WebRequest Create(string requestUriString) {
if (requestUriString == null) {
throw new ArgumentNullException("requestUriString");
}
// In .NET FX v4.0, custom IWebRequestCreate implementations can
// cause this to return null. Consider tightening this in the future.
//Contract.Ensures(Contract.Result<WebRequest>() != null);
return Create(new Uri(requestUriString), false);
}
/*++
Create - Create a WebRequest.
Another overloaded version of the Create function that doesn't
take the UseUriBase parameter.
Input:
RequestUri - Uri object for request.
Returns:
Newly created WebRequest.
--*/
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Net.WebRequest'/> instance for the specified Uri scheme.
/// </para>
/// </devdoc>
public static WebRequest Create(Uri requestUri) {
if (requestUri == null) {
throw new ArgumentNullException("requestUri");
}
// In .NET FX v4.0, custom IWebRequestCreate implementations can
// cause this to return null. Consider tightening this in the future.
//Contract.Ensures(Contract.Result<WebRequest>() != null);
return Create(requestUri, false);
}
/*++
CreateDefault - Create a default WebRequest.
This is the creation routine that creates a default WebRequest.
We take a Uri object and pass it to the base create routine,
setting the useUriBase parameter to true.
Input:
RequestUri - Uri object for request.
Returns:
Newly created WebRequest.
--*/
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static WebRequest CreateDefault(Uri requestUri) {
if (requestUri == null) {
throw new ArgumentNullException("requestUri");
}
// In .NET FX v4.0, custom IWebRequestCreate implementations can
// cause this to return null. Consider tightening this in the future.
//Contract.Ensures(Contract.Result<WebRequest>() != null);
return Create(requestUri, true);
}
// For portability
public static HttpWebRequest CreateHttp(string requestUriString) {
if (requestUriString == null) {
throw new ArgumentNullException("requestUriString");
}
return CreateHttp(new Uri(requestUriString));
}
// For portability
public static HttpWebRequest CreateHttp(Uri requestUri) {
if (requestUri == null) {
throw new ArgumentNullException("requestUri");
}
if ((requestUri.Scheme != Uri.UriSchemeHttp) && (requestUri.Scheme != Uri.UriSchemeHttps)) {
throw new NotSupportedException(SR.GetString(SR.net_unknown_prefix));
}
return (HttpWebRequest)CreateDefault(requestUri);
}
/*++
RegisterPrefix - Register an Uri prefix for creating WebRequests.
This function registers a prefix for creating WebRequests. When an
user wants to create a WebRequest, we scan a table looking for a
longest prefix match for the Uri they're passing. We then invoke
the sub creator for that prefix. This function puts entries in
that table.
We don't allow duplicate entries, so if there is a dup this call
will fail.
Input:
Prefix - Represents Uri prefix being registered.
Creator - Interface for sub creator.
Returns:
True if the registration worked, false otherwise.
--*/
/// <devdoc>
/// <para>
/// Registers a <see cref='System.Net.WebRequest'/> descendent
/// for a specific Uniform Resource Identifier.
/// </para>
/// </devdoc>
public static bool RegisterPrefix(string prefix, IWebRequestCreate creator) {
bool Error = false;
int i;
WebRequestPrefixElement Current;
if (prefix == null) {
throw new ArgumentNullException("prefix");
}
if (creator == null) {
throw new ArgumentNullException("creator");
}
ExceptionHelper.WebPermissionUnrestricted.Demand();
// Lock this object, then walk down PrefixList looking for a place to
// to insert this prefix.
lock(InternalSyncObject) {
//
// clone the object and update the clone thus
// allowing other threads to still read from it
//
ArrayList prefixList = (ArrayList)PrefixList.Clone();
// As AbsoluteUri is used later for Create, account for formating changes
// like Unicode escaping, default ports, etc.
Uri tempUri;
if (Uri.TryCreate(prefix, UriKind.Absolute, out tempUri))
{
String cookedUri = tempUri.AbsoluteUri;
// Special case for when a partial host matching is requested, drop the added trailing slash
// IE: http://host could match host or host.domain
if (!prefix.EndsWith("/", StringComparison.Ordinal)
&& tempUri.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment,
UriFormat.UriEscaped)
.Equals("/"))
cookedUri = cookedUri.Substring(0, cookedUri.Length - 1);
prefix = cookedUri;
}
i = 0;
// The prefix list is sorted with longest entries at the front. We
// walk down the list until we find a prefix shorter than this
// one, then we insert in front of it. Along the way we check
// equal length prefixes to make sure this isn't a dupe.
while (i < prefixList.Count) {
Current = (WebRequestPrefixElement)prefixList[i];
// See if the new one is longer than the one we're looking at.
if (prefix.Length > Current.Prefix.Length) {
// It is. Break out of the loop here.
break;
}
// If these are of equal length, compare them.
if (prefix.Length == Current.Prefix.Length) {
// They're the same length.
if (String.Compare(Current.Prefix, prefix, StringComparison.OrdinalIgnoreCase) == 0) {
// ...and the strings are identical. This is an error.
Error = true;
break;
}
}
i++;
}
// When we get here either i contains the index to insert at or
// we've had an error, in which case Error is true.
if (!Error) {
// No error, so insert.
prefixList.Insert(i,
new WebRequestPrefixElement(prefix, creator)
);
//
// no error, assign the clone to the static object, other
// threads using it will have copied the oriignal object already
//
PrefixList = prefixList;
}
}
return !Error;
}
/*
public static bool UnregisterPrefix(string prefix) {
if (prefix == null) {
throw new ArgumentNullException("prefix");
}
ExceptionHelper.WebPermissionUnrestricted.Demand();
// Lock this object, then walk down PrefixList looking for a place to
// to insert this prefix.
lock(InternalSyncObject) {
//
// clone the object and update the clone thus
// allowing other threads to still read from it
//
ArrayList prefixList = (ArrayList) PrefixList.Clone();
int i = 0;
WebRequestPrefixElement Current;
// The prefix list is sorted with longest entries at the front. We
// walk down the list until we find a prefix shorter than this
// one, then we insert in front of it. Along the way we check
// equal length prefixes to make sure this isn't a dupe.
while (i < prefixList.Count) {
Current = (WebRequestPrefixElement)prefixList[i];
// See if the new one is longer than the one we're looking at.
if (prefix.Length > Current.Prefix.Length) {
return fasle;
}
// If these are of equal length, compare them.
if (prefix.Length == Current.Prefix.Length) {
// They're the same length.
if (String.Compare(Current.Prefix, prefix, StringComparison.OrdinalIgnoreCase ) == 0) {
prefixList.RemoveAt(i);
PrefixList = prefixList;
return true;
}
}
i++;
}
}
return false;
}
*/
/*++
PrefixList - Returns And Initialize our prefix list.
This is the method that initializes the prefix list. We create
an ArrayList for the PrefixList, then an HttpRequestCreator object,
and then we register the HTTP and HTTPS prefixes.
Input: Nothing
Returns: true
--*/
internal static ArrayList PrefixList {
get {
//
// GetConfig() might use us, so we have a circular dependency issue,
// that causes us to nest here, we grab the lock, only
// if we haven't initialized.
//
if (s_PrefixList == null) {
lock (InternalSyncObject) {
if (s_PrefixList == null) {
GlobalLog.Print("WebRequest::Initialize(): calling ConfigurationManager.GetSection()");
s_PrefixList = WebRequestModulesSectionInternal.GetSection().WebRequestModules;
}
}
}
return s_PrefixList;
}
set {
s_PrefixList = value;
}
}
// constructors
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Net.WebRequest'/>
/// class.
/// </para>
/// </devdoc>
protected WebRequest()
{
#if !FEATURE_PAL
// Defautl values are set as per V1.0 behavior
m_ImpersonationLevel = TokenImpersonationLevel.Delegation;
m_AuthenticationLevel= AuthenticationLevel.MutualAuthRequested;
#endif
}
//
// ISerializable constructor
//
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected WebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) {
}
//
// ISerializable method
//
/// <internalonly/>
[SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")]
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)]
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
GetObjectData(serializationInfo, streamingContext);
}
//
// FxCop: Provide a way for inherited classes to access base.GetObjectData in case they also implement ISerializable.
//
[SecurityPermission(SecurityAction.Demand, SerializationFormatter=true)]
protected virtual void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
}
// This is a shortcut that would set the default policy for HTTP/HTTPS.
// The default policy is overridden by any prefix-registered policy.
// Will demand permission for set{}
public static RequestCachePolicy DefaultCachePolicy {
get {
return RequestCacheManager.GetBinding(string.Empty).Policy;
}
set {
// This is a replacement of RequestCachePermission demand since we are not including the latest in the product.
ExceptionHelper.WebPermissionUnrestricted.Demand();
RequestCacheBinding binding = RequestCacheManager.GetBinding(string.Empty);
RequestCacheManager.SetBinding(string.Empty, new RequestCacheBinding(binding.Cache, binding.Validator, value));
}
}
//
//
public virtual RequestCachePolicy CachePolicy {
get {
return m_CachePolicy;
}
set
{
// Delayed creation of CacheProtocol until caching is actually turned on.
InternalSetCachePolicy(value);
}
}
void InternalSetCachePolicy(RequestCachePolicy policy){
// Delayed creation of CacheProtocol until caching is actually turned on.
if (m_CacheBinding != null &&
m_CacheBinding.Cache != null &&
m_CacheBinding.Validator != null &&
CacheProtocol == null &&
policy != null &&
policy.Level != RequestCacheLevel.BypassCache)
{
CacheProtocol = new RequestCacheProtocol(m_CacheBinding.Cache, m_CacheBinding.Validator.CreateValidator());
}
m_CachePolicy = policy;
}
/// <devdoc>
/// <para>When overridden in a derived class, gets and
/// sets
/// the
/// protocol method used in this request. Default value should be
/// "GET".</para>
/// </devdoc>
public virtual string Method {
get {
throw ExceptionHelper.PropertyNotImplementedException;
}
set {
throw ExceptionHelper.PropertyNotImplementedException;
}
}
/// <devdoc>
/// <para>When overridden in a derived class, gets a <see cref='Uri'/>
/// instance representing the resource associated with
/// the request.</para>
/// </devdoc>
public virtual Uri RequestUri { // read-only
get {
throw ExceptionHelper.PropertyNotImplementedException;
}
}
//
// This is a group of connections that may need to be used for
// grouping connecitons.
//
/// <devdoc>
/// </devdoc>
public virtual string ConnectionGroupName {
get {
throw ExceptionHelper.PropertyNotImplementedException;
}
set {
throw ExceptionHelper.PropertyNotImplementedException;
}
}
/*++
Headers - Gets any request specific headers associated
with this request, this is simply a name/value pair collection
Input: Nothing.
Returns: This property returns WebHeaderCollection.
read-only
--*/
/// <devdoc>
/// <para>When overridden in a derived class,
/// gets
/// a collection of header name-value pairs associated with this
/// request.</para>
/// </devdoc>
public virtual WebHeaderCollection Headers {
get {
Contract.Ensures(Contract.Result<WebHeaderCollection>() != null);
throw ExceptionHelper.PropertyNotImplementedException;
}
set {
throw ExceptionHelper.PropertyNotImplementedException;
}
}
/// <devdoc>
/// <para>When
/// overridden in a derived class, gets
/// and sets
/// the
/// content length of request data being sent.</para>
/// </devdoc>
public virtual long ContentLength {
get {
throw ExceptionHelper.PropertyNotImplementedException;
}
set {
throw ExceptionHelper.PropertyNotImplementedException;
}
}
/// <devdoc>
/// <para>When
/// overridden in a derived class, gets
/// and
/// sets
/// the content type of the request data being sent.</para>
/// </devdoc>
public virtual string ContentType {
get {
throw ExceptionHelper.PropertyNotImplementedException;
}
set {
throw ExceptionHelper.PropertyNotImplementedException;
}
}
/// <devdoc>
/// <para>When overridden in a derived class, gets and sets the network
/// credentials used for authentication to this Uri.</para>
/// </devdoc>
public virtual ICredentials Credentials {
get {
throw ExceptionHelper.PropertyNotImplementedException;
}
set {
throw ExceptionHelper.PropertyNotImplementedException;
}
}
/// <devdoc>
/// <para>Sets Credentials to CredentialCache.DefaultCredentials</para>
/// </devdoc>
public virtual bool UseDefaultCredentials {
get {
throw ExceptionHelper.PropertyNotImplementedException;
}
set {
throw ExceptionHelper.PropertyNotImplementedException;
}
}
/// <devdoc>
/// <para>When overridden in a derived class,
/// gets and set proxy info. </para>
/// </devdoc>
public virtual IWebProxy Proxy {
get {
throw ExceptionHelper.PropertyNotImplementedException;
}
set {
throw ExceptionHelper.PropertyNotImplementedException;
}
}
/// <devdoc>
/// <para>When overridden in a derived class,
/// enables or disables pre-authentication.</para>
/// </devdoc>
public virtual bool PreAuthenticate {
get {
throw ExceptionHelper.PropertyNotImplementedException;
}
set {
throw ExceptionHelper.PropertyNotImplementedException;
}
}
//
// Timeout in milliseconds, if request takes longer
// than timeout, a WebException is thrown
//
//UEUE
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual int Timeout {
get {
throw ExceptionHelper.PropertyNotImplementedException;
}
set {
throw ExceptionHelper.PropertyNotImplementedException;
}
}
/// <devdoc>
/// <para>When overridden in a derived class,
/// returns a <see cref='System.IO.Stream'/> object that is used for writing data
/// to the resource identified by <see cref='WebRequest.RequestUri'/>
/// .</para>
/// </devdoc>
public virtual Stream GetRequestStream() {
throw ExceptionHelper.MethodNotImplementedException;
}
/// <devdoc>
/// <para>When overridden in a derived class,
/// returns the response
/// to an Internet request.</para>
/// </devdoc>
public virtual WebResponse GetResponse() {
Contract.Ensures(Contract.Result<WebResponse>() != null);
throw ExceptionHelper.MethodNotImplementedException;
}
/// <devdoc>
/// <para>Asynchronous version of GetResponse.</para>
/// </devdoc>
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginGetResponse(AsyncCallback callback, object state) {
throw ExceptionHelper.MethodNotImplementedException;
}
/// <devdoc>
/// <para>Returns a WebResponse object.</para>
/// </devdoc>
public virtual WebResponse EndGetResponse(IAsyncResult asyncResult) {
throw ExceptionHelper.MethodNotImplementedException;
}
/// <devdoc>
/// <para>Asynchronous version of GetRequestStream
/// method.</para>
/// </devdoc>
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginGetRequestStream(AsyncCallback callback, Object state) {
throw ExceptionHelper.MethodNotImplementedException;
}
/// <devdoc>
/// <para>Returns a <see cref='System.IO.Stream'/> object that is used for writing data to the resource
/// identified by <see cref='System.Net.WebRequest.RequestUri'/>
/// .</para>
/// </devdoc>
public virtual Stream EndGetRequestStream(IAsyncResult asyncResult) {
throw ExceptionHelper.MethodNotImplementedException;
}
// Offload to a different thread to avoid blocking the caller durring request submission.
[HostProtection(ExternalThreading = true)]
public virtual Task<Stream> GetRequestStreamAsync()
{
IWebProxy proxy = null;
try { proxy = Proxy; }
catch (NotImplementedException) { }
// Preserve context for authentication
if (ExecutionContext.IsFlowSuppressed()
&& (UseDefaultCredentials || Credentials != null
|| (proxy != null && proxy.Credentials != null)))
{
WindowsIdentity currentUser = SafeCaptureIdenity();
// When flow is suppressed we would lose track of the current user across this thread switch.
// Flow manually so that UseDefaultCredentials will work. BeginGetRequestStream will
// take over from there.
return Task.Run(() =>
{
using (currentUser)
{
using (currentUser.Impersonate())
{
return Task<Stream>.Factory.FromAsync(this.BeginGetRequestStream,
this.EndGetRequestStream, null);
}
}
});
}
else
{
return Task.Run(() => Task<Stream>.Factory.FromAsync(this.BeginGetRequestStream,
this.EndGetRequestStream, null));
}
}
// Offload to a different thread to avoid blocking the caller durring request submission.
[HostProtection(ExternalThreading = true)]
public virtual Task<WebResponse> GetResponseAsync()
{
IWebProxy proxy = null;
try { proxy = Proxy; }
catch (NotImplementedException) { }
// Preserve context for authentication
if (ExecutionContext.IsFlowSuppressed()
&& (UseDefaultCredentials || Credentials != null
|| (proxy != null && proxy.Credentials != null)))
{
WindowsIdentity currentUser = SafeCaptureIdenity();
// When flow is suppressed we would lose track of the current user across this thread switch.
// Flow manually so that UseDefaultCredentials will work. BeginGetResponse will
// take over from there.
return Task.Run(() =>
{
using (currentUser)
{
using (currentUser.Impersonate())
{
return Task<WebResponse>.Factory.FromAsync(this.BeginGetResponse,
this.EndGetResponse, null);
}
}
});
}
else
{
return Task.Run(() => Task<WebResponse>.Factory.FromAsync(this.BeginGetResponse,
this.EndGetResponse, null));
}
}
// Security: We need an assert for a call into WindowsIdentity.GetCurrent
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.ControlPrincipal)]
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "Needed for identity flow.")]
private WindowsIdentity SafeCaptureIdenity()
{
return WindowsIdentity.GetCurrent();
}
/// <summary>
/// <para>Aborts the Request</para>
/// </summary>
public virtual void Abort() {
throw ExceptionHelper.MethodNotImplementedException;
}
//
//
//
internal RequestCacheProtocol CacheProtocol
{
get
{
return m_CacheProtocol;
}
set
{
m_CacheProtocol = value;
}
}
#if !FEATURE_PAL
//
//
//
public AuthenticationLevel AuthenticationLevel {
get {
return m_AuthenticationLevel;
}
set {
m_AuthenticationLevel = value;
}
}
// Methods to retrieve the context of the "reading phase" and of the "writing phase" of the request.
// Each request type can define what goes into what phase. Typically, the writing phase corresponds to
// GetRequestStream() and the reading phase to GetResponse(), but if there's no request body, both phases
// may happen inside GetResponse().
//
// Return null only on [....] (if we're on the [....] thread). Otherwise throw if no context is available.
internal virtual ContextAwareResult GetConnectingContext()
{
throw ExceptionHelper.MethodNotImplementedException;
}
internal virtual ContextAwareResult GetWritingContext()
{
throw ExceptionHelper.MethodNotImplementedException;
}
internal virtual ContextAwareResult GetReadingContext()
{
throw ExceptionHelper.MethodNotImplementedException;
}
//
//
//
public TokenImpersonationLevel ImpersonationLevel {
get {
return m_ImpersonationLevel;
}
set {
m_ImpersonationLevel = value;
}
}
#endif // !FEATURE_PAL
/// <summary>
/// <para>Provides an abstract way of having Async code callback into the request (saves a delegate)</para>
/// </summary>
internal virtual void RequestCallback(object obj) {
throw ExceptionHelper.MethodNotImplementedException;
}
//
// Default Web Proxy implementation.
//
private static volatile IWebProxy s_DefaultWebProxy;
private static volatile bool s_DefaultWebProxyInitialized;
internal static IWebProxy InternalDefaultWebProxy
{
get
{
if (!s_DefaultWebProxyInitialized)
{
lock (InternalSyncObject)
{
if (!s_DefaultWebProxyInitialized)
{
GlobalLog.Print("WebRequest::get_InternalDefaultWebProxy(): Getting config.");
DefaultProxySectionInternal section = DefaultProxySectionInternal.GetSection();
if (section != null)
{
s_DefaultWebProxy = section.WebProxy;
}
s_DefaultWebProxyInitialized = true;
}
}
}
return s_DefaultWebProxy;
}
set
{
// Same lock as above. Avoid hitting config if the proxy is set first.
if (!s_DefaultWebProxyInitialized)
{
lock (InternalSyncObject)
{
s_DefaultWebProxy = value;
s_DefaultWebProxyInitialized = true;
}
}
else
{
s_DefaultWebProxy = value;
}
}
}
//
// Get and set the global default proxy. Use this instead of the old GlobalProxySelection.
//
public static IWebProxy DefaultWebProxy
{
get
{
ExceptionHelper.WebPermissionUnrestricted.Demand();
return InternalDefaultWebProxy;
}
set
{
ExceptionHelper.WebPermissionUnrestricted.Demand();
InternalDefaultWebProxy = value;
}
}
//
// This returns an "IE Proxy" based on the currently impersonated user's proxy settings.
//
public static IWebProxy GetSystemWebProxy()
{
ExceptionHelper.WebPermissionUnrestricted.Demand();
return InternalGetSystemWebProxy();
}
internal static IWebProxy InternalGetSystemWebProxy()
{
return new WebProxyWrapperOpaque(new WebProxy(true));
}
//
// To maintain backwards-compatibility, GlobalProxySelection.Select must return a proxy castable to WebProxy.
// To get away from that restriction in the future, new APIs wrap the WebProxy in an internal wrapper.
// Once Select is removed, the system-proxy functionality can be factored out of the WebProxy class.
//
//
// This doesn't expose the WebProxy. It's used by GetSystemWebProxy(), which should never be castable to WebProxy.
//
internal class WebProxyWrapperOpaque : IAutoWebProxy
{
protected readonly WebProxy webProxy;
internal WebProxyWrapperOpaque(WebProxy webProxy)
{
this.webProxy = webProxy;
}
public Uri GetProxy(Uri destination)
{
return webProxy.GetProxy(destination);
}
public bool IsBypassed(Uri host)
{
return webProxy.IsBypassed(host);
}
public ICredentials Credentials
{
get
{
return webProxy.Credentials;
}
set
{
webProxy.Credentials = value;
}
}
public ProxyChain GetProxies(Uri destination)
{
return ((IAutoWebProxy) webProxy).GetProxies(destination);
}
}
//
// Select returns the WebProxy out of this one.
//
internal class WebProxyWrapper : WebProxyWrapperOpaque
{
internal WebProxyWrapper(WebProxy webProxy) :
base(webProxy)
{ }
internal WebProxy WebProxy
{
get
{
return webProxy;
}
}
}
//
internal void SetupCacheProtocol(Uri uri)
{
m_CacheBinding = RequestCacheManager.GetBinding(uri.Scheme);
// Note if the cache is disabled it will give back a bypass policy.
InternalSetCachePolicy( m_CacheBinding.Policy);
if (m_CachePolicy == null)
{
// If the protocol cache policy is not specifically configured, grab from the base class.
InternalSetCachePolicy(WebRequest.DefaultCachePolicy);
}
}
delegate void DelEtwFireBeginWRGet(object id, string uri);
delegate void DelEtwFireEndWRGet(object id);
static DelEtwFireBeginWRGet s_EtwFireBeginGetResponse;
static DelEtwFireEndWRGet s_EtwFireEndGetResponse;
static DelEtwFireBeginWRGet s_EtwFireBeginGetRequestStream;
static DelEtwFireEndWRGet s_EtwFireEndGetRequestStream;
static volatile bool s_TriedGetEtwDelegates;
private static void InitEtwMethods()
{
Type fest = typeof(FrameworkEventSource);
var beginParamTypes = new Type[] { typeof(object), typeof(string) };
var endParamTypes = new Type[] { typeof(object) };
var bindingFlags = BindingFlags.Instance|BindingFlags.NonPublic|BindingFlags.Public;
var mi1 = fest.GetMethod("BeginGetResponse", bindingFlags, null, beginParamTypes, null);
var mi2 = fest.GetMethod("EndGetResponse", bindingFlags, null, endParamTypes, null);
var mi3 = fest.GetMethod("BeginGetRequestStream", bindingFlags, null, beginParamTypes, null);
var mi4 = fest.GetMethod("EndGetRequestStream", bindingFlags, null, endParamTypes, null);
if (mi1 != null && mi2 != null && mi3 != null && mi4 != null)
{
s_EtwFireBeginGetResponse = (DelEtwFireBeginWRGet) mi1.CreateDelegate(typeof(DelEtwFireBeginWRGet),
FrameworkEventSource.Log);
s_EtwFireEndGetResponse = (DelEtwFireEndWRGet) mi2.CreateDelegate(typeof(DelEtwFireEndWRGet),
FrameworkEventSource.Log);
s_EtwFireBeginGetRequestStream = (DelEtwFireBeginWRGet) mi3.CreateDelegate(typeof(DelEtwFireBeginWRGet),
FrameworkEventSource.Log);
s_EtwFireEndGetRequestStream = (DelEtwFireEndWRGet) mi4.CreateDelegate(typeof(DelEtwFireEndWRGet),
FrameworkEventSource.Log);
}
s_TriedGetEtwDelegates = true;
}
internal void LogBeginGetResponse(string uri)
{
if (!s_TriedGetEtwDelegates)
InitEtwMethods();
if (s_EtwFireBeginGetResponse != null)
s_EtwFireBeginGetResponse(this, uri);
}
internal void LogEndGetResponse()
{
if (!s_TriedGetEtwDelegates)
InitEtwMethods();
if (s_EtwFireEndGetResponse != null)
s_EtwFireEndGetResponse(this);
}
internal void LogBeginGetRequestStream(string uri)
{
if (!s_TriedGetEtwDelegates)
InitEtwMethods();
if (s_EtwFireBeginGetRequestStream != null)
s_EtwFireBeginGetRequestStream(this, uri);
}
internal void LogEndGetRequestStream()
{
if (!s_TriedGetEtwDelegates)
InitEtwMethods();
if (s_EtwFireEndGetRequestStream != null)
s_EtwFireEndGetRequestStream(this);
}
} // class WebRequest
} // namespace System.Net
| |
// 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.
#if INCLUDE_UNSAFE_ANALYSIS
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.Research.AbstractDomains.Numerical;
using Microsoft.Research.AbstractDomains;
using ADomainKind = Microsoft.Research.CodeAnalysis.Analyzers.DomainKind;
using Microsoft.Research.AbstractDomains.Expressions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using Microsoft.Research.DataStructures;
namespace Microsoft.Research.CodeAnalysis
{
public static partial class AnalysisWrapper
{
/// <summary>
/// Entry point to run the Buffer analysis
/// </summary>
public static IMethodResult<Variable> RunBufferAnalysis<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>
(
string methodName,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> driver,
List<Analyzers.Buffers.Options> options,
Predicate<APC> cachePCs, DFAController controller
)
where Variable : IEquatable<Variable>
where Expression : IEquatable<Expression>
where Type : IEquatable<Type>
{
var analysis =
new TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>.BufferAnalysis(methodName, driver, options, cachePCs, controller);
return TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>.RunTheAnalysis(methodName, driver, analysis, controller);
}
/// <summary>
/// This class is just for binding types for the internal clases
/// </summary>
public static partial class TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>
where Variable : IEquatable<Variable>
where Expression : IEquatable<Expression>
where Type : IEquatable<Type>
{
#region Facility to forward operations on the abstract domain (implementation of IAbstractDomainOperations)
public class AbstractOperationsImplementationBuffer : IAbstractDomainOperations<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression,Variable, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression>>
{
public bool LookupState(IMethodResult<Variable> mr, APC pc, out INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> astate)
{
astate = null;
BufferAnalysis an = mr as BufferAnalysis;
if (an == null)
return false;
return an.PreStateLookup(pc, out astate);
}
public INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Join(IMethodResult<Variable> mr, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> astate1, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> astate2)
{
BufferAnalysis an = mr as BufferAnalysis;
if (an == null)
return null;
bool bWeaker;
return an.Join(new Pair<APC, APC>(), astate1, astate2, out bWeaker, false);
}
public List<BoxedExpression> ExtractAssertions(
IMethodResult<Variable> mr,
INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> astate,
IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable> context,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> metaDataDecoder)
{
BufferAnalysis an = mr as BufferAnalysis;
if (an == null)
return null;
BoxedExpressionReader<Local, Parameter, Method, Field, Property, Event, Type, Variable, Expression, Attribute, Assembly> br = new BoxedExpressionReader<Local, Parameter, Method, Field, Property, Event, Type, Variable, Expression, Attribute, Assembly>(context, metaDataDecoder);
return an.ToListOfBoxedExpressions(astate, br);
}
public bool AssignInParallel(IMethodResult<Variable> mr, ref INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> astate, Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> mapping, Converter<BoxedVariable<Variable>, BoxedExpression> convert)
{
BufferAnalysis an = mr as BufferAnalysis;
if (an == null)
return false;
astate.AssignInParallel(mapping, convert);
return true;
}
}
#endregion
public class BufferAnalysis :
GenericNumericalAnalysis<Analyzers.Buffers.Options>
//NumericalAnalysis<Analyzers.Buffers.BufferOptions>
{
#region private state
readonly private List<Analyzers.Buffers.Options> specificoptions;
#endregion
internal BufferAnalysis(
string methodName,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver,
List<Analyzers.Buffers.Options> optionsList,
Predicate<APC> cachePCs, DFAController controller
)
: base(methodName, mdriver, optionsList[0], cachePCs, controller)
// : base(methodName, mdriver, optionsList)
{
Contract.Requires(mdriver != null);
Contract.Requires(optionsList.Count > 0);
this.specificoptions = optionsList;
}
#region Transfer functions for instructions
/// <summary>
/// WB(dest) == size
/// </summary>
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Localloc(APC pc, Variable dest, Variable size, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
Variable WB_dest;
if (this.Context.ValueContext.TryGetWritableBytes(this.Context.MethodContext.CFG.Post(pc), dest, out WB_dest))
{
var sizeExp = ToBoxedExpression(pc, size);
var tryConst = data.BoundsFor(sizeExp);
if (tryConst.IsSingleton)
{
data.AssumeInDisInterval(new BoxedVariable<Variable>(WB_dest), tryConst);
}
data = data.TestTrueGeqZero(sizeExp);
data = data.TestTrueEqual(ToBoxedExpression(pc, WB_dest), sizeExp);
}
return data;
}
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Ldflda(APC pc, Field field, Variable dest, Variable obj, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
return HandleFldInstruction(pc, obj, data);
}
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Ldfld(APC pc, Field field, bool @volatile, Variable dest, Variable obj, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
return HandleFldInstruction(pc, obj, data);
}
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Stfld(APC pc, Field field, bool @volatile, Variable obj, Variable value, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
return HandleFldInstruction(pc, obj, data);
}
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Ldind(APC pc, Type type, bool @volatile, Variable dest, Variable ptr, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
return HandleIndInstruction(pc, type, ptr, data);
}
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Stind(APC pc, Type type, bool @volatile, Variable ptr, Variable value, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
return HandleIndInstruction(pc, type, ptr, data);
}
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Ldarga(APC pc, Parameter argument, bool isOld, Variable dest, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
return HandleLoadAddrInstruction(pc, dest, this.DecoderForMetaData.ParameterType(argument), data);
}
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Ldloca(APC pc, Local local, Variable dest, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
return HandleLoadAddrInstruction(pc, dest, this.DecoderForMetaData.LocalType(local), data);
}
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Ldelema(APC pc, Type type, bool @readonly, Variable dest, Variable array, Variable index, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
// WB(dest) == (array.Length -index) * typesize
var postPC = this.Context.MethodContext.CFG.Post(pc);
var arrType = this.Context.ValueContext.GetType(postPC, array);
Variable len_arr, wb_dest;
if (arrType.IsNormal
&& this.Context.ValueContext.TryGetWritableBytes(postPC, dest, out wb_dest)
&& this.Context.ValueContext.TryGetArrayLength(postPC, array, out len_arr))
{
var typesize = this.DecoderForMetaData.TypeSize(this.DecoderForMetaData.ElementType(arrType.Value));
if (typesize != -1)
{
var elements = BoxedExpression.Binary(BinaryOperator.Sub, ToBoxedExpression(pc, len_arr), ToBoxedExpression(pc, index));
var bytes = BoxedExpression.Binary(BinaryOperator.Mul, elements, BoxedExpression.Const(typesize, this.DecoderForMetaData.System_UInt32, this.DecoderForMetaData));
data = data.TestTrueEqual(ToBoxedExpression(postPC, wb_dest), bytes);
}
}
return data;
}
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Newarray<ArgList>(APC pc, Type type, Variable dest, ArgList lengths, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
var result = base.Newarray<ArgList>(pc, type, dest, lengths, data);
// F: HACK HACK HACK to cut some paths in fixed statements
result = result.TestTrueEqual(ToBoxedExpression(pc, dest), BoxedExpression.Const(1, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData));
return result;
}
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Unary(APC pc, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Variable source, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
data = base.Unary(pc, op, overflow, unsigned, dest, source, data);
switch (op)
{
case UnaryOperator.Conv_i:
{
}
break;
default:
break;
}
return data;
}
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Binary(APC pc, BinaryOperator op, Variable dest, Variable s1, Variable s2, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
if (!this.Options.FastCheck)
{
// This will introduce a lot more facts,
data = base.Binary(pc, op, dest, s1, s2, data);
}
var postPC = this.Context.MethodContext.CFG.Post(pc);
var destType = this.Context.ValueContext.GetType(postPC, dest);
if (destType.IsNormal && this.DecoderForMetaData.IsUnmanagedPointer(destType.Value))
{
Variable wb_dest;
if (this.Context.ValueContext.TryGetWritableBytes(this.Context.MethodContext.CFG.Post(pc), dest, out wb_dest))
{
// Two cases, depending if it is a pointer arithmetic, or a string
var sourcetype = this.Context.ValueContext.GetType(postPC, s1);
if (sourcetype.IsNormal && sourcetype.Value.Equals(this.DecoderForMetaData.System_String))
{
Variable source_Len;
if (this.Context.ValueContext.TryGetArrayLength(postPC, s1, out source_Len))
{
data = data.TestTrueEqual(
ToBoxedExpression(postPC, wb_dest),
BoxedExpression.Binary(BinaryOperator.Mul,
BoxedExpression.Const(2, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData), ToBoxedExpression(postPC, source_Len)
)
);
}
}
else
{
Variable left, right;
if (!this.Context.ValueContext.TryGetWritableBytes(pc, s1, out left))
{
left = s1;
}
if (!this.Context.ValueContext.TryGetWritableBytes(pc, s2, out right))
{
right = s2;
}
var wb_destExp = ToBoxedExpression(pc, wb_dest);
var leftExp = ToBoxedExpression(pc, left);
var rightExp = ToBoxedExpression(pc, right);
// We should be careful that wb_destExp can be negative!
// we van have wb_destExp == wb + k, with k > 0
// if we do not know anything about wb, it is unsound to assume that wb_destExp >= 0, because this will imply that wb >= k, which is wrong (in general)
BoxedExpression newConstraint;
if (TryBuildNewWB(op, wb_destExp, leftExp, rightExp, out newConstraint))
{
data = data.TestTrue(newConstraint) as INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression>;
}
}
}
}
return data;
}
private bool TryBuildNewWB(BinaryOperator op, BoxedExpression wb_destExp, BoxedExpression leftExp, BoxedExpression rightExp, out BoxedExpression newConstraint)
{
BinaryOperator flippedOp;
switch (op)
{
case BinaryOperator.Add:
flippedOp = BinaryOperator.Sub;
break;
case BinaryOperator.Sub:
flippedOp = BinaryOperator.Add;
break;
default:
newConstraint = default(BoxedExpression);
return false;
}
newConstraint = BoxedExpression.Binary(
BinaryOperator.Ceq,
wb_destExp,
BoxedExpression.Binary(flippedOp, leftExp, rightExp));
return true;
}
private INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> HandleFldInstruction(APC pc, Variable obj, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
var type = this.Context.ValueContext.GetType(pc, obj);
if (type.IsNormal)
{
data = HandleIndInstruction(pc, type.Value, obj, data);
}
return data;
}
private INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> HandleIndInstruction(APC pc, Type type, Variable ptr, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
BoxedExpression lowerbound, upperbound;
if (this.TryInferSafeBufferAccessConstraints(pc, type, ptr, out lowerbound, out upperbound))
{
data = (INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression>)data.TestTrue(lowerbound).TestTrue(upperbound);
}
return data;
}
private INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> HandleLoadAddrInstruction(APC pc, Variable dest, FlatDomain<Type> t, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
if (!t.IsNormal)
return data;
return HandleLoadAddrInstruction(pc, dest, t.Value, data);
}
/// <summary>
/// wb(ptr) == sizeof(type)
/// </summary>
private INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> HandleLoadAddrInstruction(APC pc, Variable ptr, Type type, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data)
{
Variable wb_ptr;
var typeSize = this.DecoderForMetaData.TypeSize(type);
if (typeSize != -1 && this.Context.ValueContext.TryGetWritableBytes(this.Context.MethodContext.CFG.Post(pc), ptr, out wb_ptr))
{
data = data.TestTrueEqual(ToBoxedExpression(pc, wb_ptr), BoxedExpression.Const(typeSize, this.DecoderForMetaData.System_UInt32, this.DecoderForMetaData));
}
return data;
}
#endregion
#region refined ParallelAssign
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression>
HelperForAssignInParallel(INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> state,
Pair<APC, APC> edge, Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> refinedMap,
Converter<BoxedVariable<Variable>, BoxedExpression> convert)
{
state = base.HelperForAssignInParallel(state, edge, refinedMap, convert);
foreach (var pair in refinedMap)
{
Variable fromVar, strLenVar;
if (pair.Key.TryUnpackVariable(out fromVar))
{
if (this.Context.ValueContext.IsZero(edge.One, fromVar))
{
var t = this.Context.ValueContext.GetType(edge.One, fromVar);
if (t.IsNormal)
{
// If we know that it is a null pointer, then we add the information that the WB(...) == 0
if (CanBeAPointer(t.Value))
{
foreach (var toVarBoxed in pair.Value.GetEnumerable())
{
Variable toVar, toVar_WB;
if (toVarBoxed.TryUnpackVariable(out toVar) && this.Context.ValueContext.TryGetWritableBytes(edge.Two, toVar, out toVar_WB))
{
// Add the constraint WB(toVar) == 0
state = state.TestTrueEqual(ToBoxedExpression(edge.Two, toVar_WB), BoxedExpression.Const(0, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData));
}
}
}
// If we know that it is a null array, then we add the information that ArrayLength(...) == 0
else if (IsAnArray(t.Value))
{
foreach (var toVarBoxed in pair.Value.GetEnumerable())
{
Variable toVar, toVar_Len;
if (toVarBoxed.TryUnpackVariable(out toVar) && this.Context.ValueContext.TryGetArrayLength(edge.Two, toVar, out toVar_Len))
{
// Add the constraint toVar.Length == 0
state = state.TestTrueEqual(ToBoxedExpression(edge.Two, toVar_Len), BoxedExpression.Const(0, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData));
}
}
}
}
}
// This is a special case to handle fixed(char* charPtr = str), with str a string)
// We look for assignments "charPtr = (conv_i str) + string_offset" or "charPtr = (conv_i str)"
if (TryFindStringExpression(edge, fromVar, out strLenVar))
{
foreach(var charPtrCandidateBoxed in pair.Value.GetEnumerable())
{
Variable charPtrCandidate, charPtrCandidate_WB;
if (charPtrCandidateBoxed.TryUnpackVariable(out charPtrCandidate)
&& this.Context.ValueContext.TryGetWritableBytes(edge.Two, charPtrCandidate, out charPtrCandidate_WB))
{
// WB(charPtr) = 2 * str.Len
state = state.TestTrueEqual(ToBoxedExpression(edge.Two, charPtrCandidate_WB),
BoxedExpression.Binary(BinaryOperator.Mul, ToBoxedExpression(edge.Two, strLenVar), BoxedExpression.Const(2, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData)));
}
}
}
}
}
return state;
}
#endregion
#region Common methods
/// <summary>
/// Because of expression reconstruction, ptr is refined to exp[base]
/// We generate the two proof obligations:
/// offset >= 0 (lower bound)
/// offset + sizeof(type) \leq WB(base)
/// </summary>
/// <returns>false if no proof obligation could be inferred</returns>
public bool TryInferSafeBufferAccessConstraints(APC pc, Type type, Variable ptr, out BoxedExpression lowerBound, out BoxedExpression upperBound)
{
var ptrType = this.Context.ValueContext.GetType(pc, ptr);
// If we do not have a type, or it is a managed pointer, we are done
if (!ptrType.IsNormal || this.DecoderForMetaData.IsManagedPointer(ptrType.Value))
{
return FailedToInferObligation(out lowerBound, out upperBound);
}
// F: need to consider when sizeof is there?
Polynomial<BoxedVariable<Variable>, BoxedExpression> pol;
if (Polynomial<BoxedVariable<Variable>, BoxedExpression>.TryToPolynomialForm(ToBoxedExpression(pc, ptr), this.Decoder, out pol))
{
Contract.Assume(!object.ReferenceEquals(pol, null));
BoxedExpression basePtr, wbPtr, offset;
if (!TrySplitBaseWBAndOffset(pc, pol, out basePtr, out wbPtr, out offset))
{
return FailedToInferObligation(out lowerBound, out upperBound);
}
// 0 <= offset
lowerBound = BoxedExpression.Binary(BinaryOperator.Cle, BoxedExpression.Const(0, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData), offset);
// offset + sizeof(T) <= WB
var size = this.DecoderForMetaData.TypeSize(type);
if(size >= 0)
{
//var neededbytes = BoxedExpression.Binary(BinaryOperator.Add, offset, BoxedExpression.SizeOf(type, size));
var neededbytes = BoxedExpression.Binary(BinaryOperator.Add,
offset, BoxedExpression.Const(size, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData));
upperBound = BoxedExpression.Binary(BinaryOperator.Cle, neededbytes, wbPtr);
}
else // We cannot get the size statically, and we create an expression with the size expressed symbolically
{
var neededbytes = BoxedExpression.Binary(BinaryOperator.Add, offset, BoxedExpression.SizeOf(type, size));
upperBound = BoxedExpression.Binary(BinaryOperator.Cle, neededbytes, wbPtr);
}
return true;
}
else
{
// TODO: Consider the non-polynomial case
// F: for instance "*(p + a/b)" we do not infer any proof obligation.
return FailedToInferObligation(out lowerBound, out upperBound);
}
}
private bool FailedToInferObligation(out BoxedExpression a, out BoxedExpression b)
{
a = b = default(BoxedExpression);
return false;
}
private bool TrySplitBaseWBAndOffset(APC pc, Polynomial<BoxedVariable<Variable>, BoxedExpression> pol, out BoxedExpression basePtr, out BoxedExpression wbPtr, out BoxedExpression offset)
{
var foundAPointer = false;
var offsets = new List<Monomial<BoxedVariable<Variable>>>(pol.Left.Length);
var basePtrVar = default(Variable);
// 1. Fetch the pointer
foreach (var m in pol.Left)
{
BoxedVariable<Variable> tryVar;
Variable v;
if (m.IsVariable(out tryVar) && tryVar.TryUnpackVariable(out v))
{
var type = this.Context.ValueContext.GetType(this.Context.MethodContext.CFG.Post(pc), v);
if(type.IsNormal && (this.DecoderForMetaData.IsUnmanagedPointer(type.Value) || this.DecoderForMetaData.IsReferenceType(type.Value)))
{
basePtrVar = v;
Contract.Assume(foundAPointer == false);
foundAPointer = true;
continue;
}
}
offsets.Add(m);
}
if (!foundAPointer)
{
basePtr = offset = wbPtr = default(BoxedExpression);
return false;
}
// 2. Get the WB
Variable varForWB;
if (!this.Context.ValueContext.TryGetWritableBytes(this.Context.MethodContext.CFG.Post(pc), basePtrVar, out varForWB))
{
basePtr = offset = wbPtr = default(BoxedExpression);
return false;
}
// 3. Construct the offset
Polynomial<BoxedVariable<Variable>, BoxedExpression> tmpPol;
if (!Polynomial<BoxedVariable<Variable>, BoxedExpression>.TryToPolynomialForm(offsets.ToArray(), out tmpPol))
{
throw new AbstractInterpretationException("Impossible case?");
}
Contract.Assert(this.Encoder != null);
basePtr = BoxedExpression.Var(basePtrVar);
wbPtr = BoxedExpression.Var(varForWB);
offset = tmpPol.ToPureExpression(this.Encoder);
return true;
}
private bool TryFindStringExpression(Pair<APC, APC> edge, Variable var, out Variable strLenVar)
{
var pc = edge.One;
var be = ToBoxedExpression(pc, var);
strLenVar = default(Variable);
return TryFindStringExpressionInternal(pc, be, ref strLenVar);
}
private bool TryFindStringExpressionInternal(APC pc, BoxedExpression be, ref Variable strLenVar)
{
if (be.IsUnary)
{
return TryFindStringExpressionInternal(pc, be.UnaryArgument, ref strLenVar);
}
if (be.IsBinary)
{
if(be.BinaryOp != BinaryOperator.Add)
{
return false;
}
if (!TryFindStringExpressionInternal(pc, be.BinaryLeft, ref strLenVar))
{
return TryFindStringExpressionInternal(pc, be.BinaryRight, ref strLenVar);
}
return true;
}
if(be.IsVariable)
{
Variable v;
if (be.TryGetFrameworkVariable(out v))
{
var vType = this.Context.ValueContext.GetType(pc, v);
if (vType.IsNormal
&& vType.Value.Equals(this.DecoderForMetaData.System_String)
&& this.Context.ValueContext.TryGetArrayLength(pc, v, out strLenVar))
{
return true;
}
}
}
return false;
}
private bool CanBeAPointer(Type t)
{
return this.DecoderForMetaData.IsUnmanagedPointer(t)
|| this.DecoderForMetaData.IsManagedPointer(t)
|| this.DecoderForMetaData.System_UIntPtr.Equals(t)
|| this.DecoderForMetaData.System_IntPtr.Equals(t);
}
private bool IsAnArray(Type p)
{
return this.DecoderForMetaData.IsArray(p);
}
#endregion
#region Interface for the dataflow analysis
public override INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> GetTopValue()
{
switch (this.specificoptions[0].type)
{
case Analyzers.DomainKind.SubPolyhedra:
{
var intervals = new IntervalEnvironment<BoxedVariable<Variable>, BoxedExpression>(this.ExpressionManager);
var karr = new LinearEqualitiesForSubpolyhedraEnvironment<BoxedVariable<Variable>, BoxedExpression>(this.ExpressionManager);
var subpolyhedra = new SubPolyhedra<BoxedVariable<Variable>, BoxedExpression>(karr, intervals, this.ExpressionManager);
return subpolyhedra;
}
default:
throw new AbstractInterpretationException("Abstract domain not supported");
}
}
public override IFactQuery<BoxedExpression, Variable> FactQuery(IFixpointInfo<APC, INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression>> fixpoint)
{
return new AILogicInference<INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression>>(this.Decoder,
this.Options, fixpoint, this.Context, this.DecoderForMetaData, this.Options.TraceNumericalAnalysis);
}
#endregion
}
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class Goto : GotoExpressionTests
{
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void JustGotoValue(object value, bool useInterpreter)
{
Type type = value.GetType();
LabelTarget target = Expression.Label(type);
Expression block = Expression.Block(
Expression.Goto(target, Expression.Constant(value)),
Expression.Label(target, Expression.Default(type))
);
Expression equals = Expression.Equal(Expression.Constant(value), block);
Assert.True(Expression.Lambda<Func<bool>>(equals).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void GotoToMiddle(bool useInterpreter)
{
// The behaviour is that return jumps to a label, but does not necessarily leave a block.
LabelTarget target = Expression.Label(typeof(int));
Expression block = Expression.Block(
Expression.Goto(target, Expression.Constant(1)),
Expression.Label(target, Expression.Constant(2)),
Expression.Constant(3)
);
Assert.Equal(3, Expression.Lambda<Func<int>>(block).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void GotoJumps(object value, bool useInterpreter)
{
Type type = value.GetType();
LabelTarget target = Expression.Label(type);
Expression block = Expression.Block(
Expression.Goto(target, Expression.Constant(value)),
Expression.Throw(Expression.Constant(new InvalidOperationException())),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value), block)).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(TypesData))]
public void NonVoidTargetGotoHasNoValue(Type type)
{
LabelTarget target = Expression.Label(type);
AssertExtensions.Throws<ArgumentException>("target", () => Expression.Goto(target));
}
[Theory]
[MemberData(nameof(TypesData))]
public void NonVoidTargetGotoHasNoValueTypeExplicit(Type type)
{
LabelTarget target = Expression.Label(type);
AssertExtensions.Throws<ArgumentException>("target", () => Expression.Goto(target, type));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void GotoVoidNoValue(bool useInterpreter)
{
LabelTarget target = Expression.Label();
Expression block = Expression.Block(
Expression.Goto(target),
Expression.Throw(Expression.Constant(new InvalidOperationException())),
Expression.Label(target)
);
Expression.Lambda<Action>(block).Compile(useInterpreter)();
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void GotoExplicitVoidNoValue(bool useInterpreter)
{
LabelTarget target = Expression.Label();
Expression block = Expression.Block(
Expression.Goto(target, typeof(void)),
Expression.Throw(Expression.Constant(new InvalidOperationException())),
Expression.Label(target)
);
Expression.Lambda<Action>(block).Compile(useInterpreter)();
}
[Theory]
[MemberData(nameof(TypesData))]
public void NullValueOnNonVoidGoto(Type type)
{
AssertExtensions.Throws<ArgumentException>("target", () => Expression.Goto(Expression.Label(type)));
AssertExtensions.Throws<ArgumentException>("target", () => Expression.Goto(Expression.Label(type), default(Expression)));
AssertExtensions.Throws<ArgumentException>("target", () => Expression.Goto(Expression.Label(type), null, type));
}
[Theory]
[MemberData(nameof(ConstantValueData))]
public void ExplicitNullTypeWithValue(object value)
{
AssertExtensions.Throws<ArgumentException>("target", () => Expression.Goto(Expression.Label(value.GetType()), default(Type)));
}
[Fact]
public void UnreadableLabel()
{
Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly");
LabelTarget target = Expression.Label(typeof(string));
AssertExtensions.Throws<ArgumentException>("value", () => Expression.Goto(target, value));
AssertExtensions.Throws<ArgumentException>("value", () => Expression.Goto(target, value, typeof(string)));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void CanAssignAnythingToVoid(object value, bool useInterpreter)
{
LabelTarget target = Expression.Label();
BlockExpression block = Expression.Block(
Expression.Goto(target, Expression.Constant(value)),
Expression.Label(target)
);
Assert.Equal(typeof(void), block.Type);
Expression.Lambda<Action>(block).Compile(useInterpreter)();
}
[Theory]
[MemberData(nameof(NonObjectAssignableConstantValueData))]
public void CannotAssignValueTypesToObject(object value)
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Goto(Expression.Label(typeof(object)), Expression.Constant(value)));
}
[Theory]
[PerCompilationType(nameof(ObjectAssignableConstantValueData))]
public void ExplicitTypeAssigned(object value, bool useInterpreter)
{
LabelTarget target = Expression.Label(typeof(object));
BlockExpression block = Expression.Block(
Expression.Goto(target, Expression.Constant(value), typeof(object)),
Expression.Label(target, Expression.Default(typeof(object)))
);
Assert.Equal(typeof(object), block.Type);
Assert.Equal(value, Expression.Lambda<Func<object>>(block).Compile(useInterpreter)());
}
[Fact]
public void GotoQuotesIfNecessary()
{
LabelTarget target = Expression.Label(typeof(Expression<Func<int>>));
BlockExpression block = Expression.Block(
Expression.Goto(target, Expression.Lambda<Func<int>>(Expression.Constant(0))),
Expression.Label(target, Expression.Default(typeof(Expression<Func<int>>)))
);
Assert.Equal(typeof(Expression<Func<int>>), block.Type);
}
[Fact]
public void UpdateSameIsSame()
{
LabelTarget target = Expression.Label(typeof(int));
Expression value = Expression.Constant(0);
GotoExpression ret = Expression.Goto(target, value);
Assert.Same(ret, ret.Update(target, value));
Assert.Same(ret, NoOpVisitor.Instance.Visit(ret));
}
[Fact]
public void UpdateDiferentValueIsDifferent()
{
LabelTarget target = Expression.Label(typeof(int));
GotoExpression ret = Expression.Goto(target, Expression.Constant(0));
Assert.NotSame(ret, ret.Update(target, Expression.Constant(0)));
}
[Fact]
public void UpdateDifferentTargetIsDifferent()
{
Expression value = Expression.Constant(0);
GotoExpression ret = Expression.Goto(Expression.Label(typeof(int)), value);
Assert.NotSame(ret, ret.Update(Expression.Label(typeof(int)), value));
}
[Fact]
public void OpenGenericType()
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Goto(Expression.Label(typeof(void)), typeof(List<>)));
}
[Fact]
public static void TypeContainsGenericParameters()
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Goto(Expression.Label(typeof(void)), typeof(List<>.Enumerator)));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Goto(Expression.Label(typeof(void)), typeof(List<>).MakeGenericType(typeof(List<>))));
}
[Fact]
public void PointerType()
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Goto(Expression.Label(typeof(void)), typeof(int).MakePointerType()));
}
[Fact]
public void ByRefType()
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Goto(Expression.Label(typeof(void)), typeof(int).MakeByRefType()));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void UndefinedLabel(bool useInterpreter)
{
Expression<Action> goNowhere = Expression.Lambda<Action>(Expression.Goto(Expression.Label()));
Assert.Throws<InvalidOperationException>(() => goNowhere.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void AmbiguousJump(bool useInterpreter)
{
LabelTarget target = Expression.Label();
Expression<Action> exp = Expression.Lambda<Action>(
Expression.Block(
Expression.Goto(target),
Expression.Block(Expression.Label(target)),
Expression.Block(Expression.Label(target))
)
);
Assert.Throws<InvalidOperationException>(() => exp.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void MultipleDefinitionsInSeparateBlocks(bool useInterpreter)
{
LabelTarget target = Expression.Label(typeof(int));
Func<int> add = Expression.Lambda<Func<int>>(
Expression.Add(
Expression.Add(
Expression.Block(
Expression.Goto(target, Expression.Constant(6)),
Expression.Throw(Expression.Constant(new Exception())),
Expression.Label(target, Expression.Constant(0))
),
Expression.Block(
Expression.Goto(target, Expression.Constant(4)),
Expression.Throw(Expression.Constant(new Exception())),
Expression.Label(target, Expression.Constant(0))
)
),
Expression.Block(
Expression.Goto(target, Expression.Constant(5)),
Expression.Throw(Expression.Constant(new Exception())),
Expression.Label(target, Expression.Constant(0))
)
)
).Compile(useInterpreter);
Assert.Equal(15, add());
}
[Theory, ClassData(typeof(CompilationTypes))]
public void JumpIntoExpression(bool useInterpreter)
{
LabelTarget target = Expression.Label();
Expression<Func<bool>> isInt = Expression.Lambda<Func<bool>>(
Expression.Block(
Expression.Goto(target),
Expression.TypeIs(Expression.Label(target), typeof(int))
)
);
Assert.Throws<InvalidOperationException>(() => isInt.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void JumpInWithValue(bool useInterpreter)
{
LabelTarget target = Expression.Label(typeof(int));
Expression<Func<int>> exp = Expression.Lambda<Func<int>>(
Expression.Block(
Expression.Goto(target, Expression.Constant(2)),
Expression.Block(
Expression.Label(target, Expression.Constant(3)))
)
);
Assert.Throws<InvalidOperationException>(() => exp.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void AmbiguousJumpBack(bool useInterpreter)
{
LabelTarget label = Expression.Label(typeof(void));
BlockExpression block = Expression.Block(
Expression.Block(Expression.Label(label)), Expression.Block(Expression.Label(label)),
Expression.Block(Expression.Block(Expression.Goto(label))));
Expression<Action> exp = Expression.Lambda<Action>(block);
Assert.Throws<InvalidOperationException>(() => exp.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void AmbiguousJumpSplit(bool useInterpreter)
{
LabelTarget label = Expression.Label(typeof(void));
BlockExpression block = Expression.Block(
Expression.Block(Expression.Label(label)), Expression.Block(Expression.Block(Expression.Goto(label))),
Expression.Block(Expression.Label(label)));
Expression<Action> exp = Expression.Lambda<Action>(block);
Assert.Throws<InvalidOperationException>(() => exp.Compile(useInterpreter));
}
}
}
| |
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Realms.Native;
using LazyMethod = System.Lazy<System.Reflection.MethodInfo>;
namespace Realms
{
internal class RealmResultsVisitor : ExpressionVisitor
{
private readonly Realm _realm;
private readonly RealmObject.Metadata _metadata;
internal QueryHandle CoreQueryHandle; // set when recurse down to VisitConstant
internal SortDescriptorBuilder OptionalSortDescriptorBuilder; // set only when get OrderBy*
private static class Methods
{
internal static LazyMethod Capture<T>(Expression<Action<T>> lambda)
{
return new LazyMethod(() =>
{
var method = (lambda.Body as MethodCallExpression).Method;
if (method.IsGenericMethod)
{
method = method.GetGenericMethodDefinition();
}
return method;
});
}
internal static class String
{
internal static readonly LazyMethod Contains = Capture<string>(s => s.Contains(string.Empty));
internal static readonly LazyMethod ContainsStringComparison = Capture<string>(s => s.Contains(string.Empty, StringComparison.Ordinal));
internal static readonly LazyMethod Like = Capture<string>(s => s.Like(string.Empty, true));
internal static readonly LazyMethod StartsWith = Capture<string>(s => s.StartsWith(string.Empty));
internal static readonly LazyMethod StartsWithStringComparison = Capture<string>(s => s.StartsWith(string.Empty, StringComparison.Ordinal));
internal static readonly LazyMethod EndsWith = Capture<string>(s => s.EndsWith(string.Empty));
internal static readonly LazyMethod EndsWithStringComparison = Capture<string>(s => s.EndsWith(string.Empty, StringComparison.Ordinal));
internal static readonly LazyMethod IsNullOrEmpty = Capture<string>(s => string.IsNullOrEmpty(s));
internal static readonly LazyMethod EqualsMethod = Capture<string>(s => s.Equals(string.Empty));
internal static readonly LazyMethod EqualsStringComparison = Capture<string>(s => s.Equals(string.Empty, StringComparison.Ordinal));
}
}
internal RealmResultsVisitor(Realm realm, RealmObject.Metadata metadata)
{
_realm = realm;
_metadata = metadata;
}
private static Expression StripQuotes(Expression e)
{
while (e.NodeType == ExpressionType.Quote)
{
e = ((UnaryExpression)e).Operand;
}
return e;
}
/*
Expressions will typically be in a form:
- with embedded Lambda `Count(p => !p.IsInteresting)`
- at the end of a Where `Where(p => !p.IsInteresting).Where()`
The latter form is handled by recursion where evaluation of Visit will
take us back into VisitMethodCall to evaluate the Where call.
*/
private void RecurseToWhereOrRunLambda(MethodCallExpression m)
{
Visit(m.Arguments[0]); // creates the query or recurse to "Where"
if (m.Arguments.Count > 1)
{
var lambda = (LambdaExpression)StripQuotes(m.Arguments[1]);
Visit(lambda.Body);
}
}
private void AddSort(LambdaExpression lambda, bool isStarting, bool ascending)
{
var body = lambda.Body as MemberExpression;
if (body == null)
{
throw new NotSupportedException($"The expression {lambda} cannot be used in an Order clause");
}
if (isStarting)
{
if (OptionalSortDescriptorBuilder == null)
{
OptionalSortDescriptorBuilder = new SortDescriptorBuilder(_metadata.Table);
}
else
{
var badCall = ascending ? "ThenBy" : "ThenByDescending";
throw new NotSupportedException($"You can only use one OrderBy or OrderByDescending clause, subsequent sort conditions should be {badCall}");
}
}
var propertyChain = TraverseSort(body).Select(n =>
{
var metadata = _realm.Metadata[n.Item1.Name];
return metadata.PropertyIndices[n.Item2];
});
OptionalSortDescriptorBuilder.AddClause(propertyChain, ascending);
}
private static IEnumerable<Tuple<Type, string>> TraverseSort(MemberExpression expression)
{
var chain = new List<Tuple<Type, string>>();
while (expression != null)
{
chain.Add(Tuple.Create(expression.Member.DeclaringType, expression.Member.Name));
expression = expression.Expression as MemberExpression;
}
chain.Reverse();
return chain;
}
internal override Expression VisitMethodCall(MethodCallExpression m)
{
if (m.Method.DeclaringType == typeof(Queryable))
{
if (m.Method.Name == nameof(Queryable.Where))
{
Visit(m.Arguments[0]);
var lambda = (LambdaExpression)StripQuotes(m.Arguments[1]);
Visit(lambda.Body);
return m;
}
if (m.Method.Name == nameof(Queryable.OrderBy))
{
Visit(m.Arguments[0]);
AddSort((LambdaExpression)StripQuotes(m.Arguments[1]), true, true);
return m;
}
if (m.Method.Name == nameof(Queryable.OrderByDescending))
{
Visit(m.Arguments[0]);
AddSort((LambdaExpression)StripQuotes(m.Arguments[1]), true, false);
return m;
}
if (m.Method.Name == nameof(Queryable.ThenBy))
{
Visit(m.Arguments[0]);
AddSort((LambdaExpression)StripQuotes(m.Arguments[1]), false, true);
return m;
}
if (m.Method.Name == nameof(Queryable.ThenByDescending))
{
Visit(m.Arguments[0]);
AddSort((LambdaExpression)StripQuotes(m.Arguments[1]), false, false);
return m;
}
if (m.Method.Name == nameof(Queryable.Count))
{
RecurseToWhereOrRunLambda(m);
var foundCount = CoreQueryHandle.Count();
return Expression.Constant(foundCount);
}
if (m.Method.Name == nameof(Queryable.Any))
{
RecurseToWhereOrRunLambda(m);
var foundAny = CoreQueryHandle.FindDirect(_realm.SharedRealmHandle) != IntPtr.Zero;
return Expression.Constant(foundAny);
}
if (m.Method.Name.StartsWith(nameof(Queryable.First)))
{
RecurseToWhereOrRunLambda(m);
var firstObjectPtr = IntPtr.Zero;
if (OptionalSortDescriptorBuilder == null)
{
firstObjectPtr = CoreQueryHandle.FindDirect(_realm.SharedRealmHandle);
}
else
{
using (ResultsHandle rh = _realm.MakeResultsForQuery(CoreQueryHandle, OptionalSortDescriptorBuilder))
{
firstObjectPtr = rh.GetObjectAtIndex(0);
}
}
if (firstObjectPtr != IntPtr.Zero)
{
return Expression.Constant(_realm.MakeObject(_metadata, firstObjectPtr));
}
if (m.Method.Name == nameof(Queryable.First))
{
throw new InvalidOperationException("Sequence contains no matching element");
}
Debug.Assert(m.Method.Name == nameof(Queryable.FirstOrDefault), $"The method {m.Method.Name} is not supported. We expected {nameof(Queryable.FirstOrDefault)}.");
return Expression.Constant(null);
}
/*
// FIXME: See discussion in the test DefaultIfEmptyReturnsDefault
// kept because it shows part of what might be a viable implementation if can work out architectural issues
if (m.Method.Name == nameof(Queryable.DefaultIfEmpty))
{
RecurseToWhereOrRunLambda(m);
IntPtr firstObjectPtr = _coreQueryHandle.FindDirect(IntPtr.Zero);
if (firstObjectPtr != IntPtr.Zero)
return m; // as if just a "Where"
var innerType = m.Type.GetGenericArguments()[0];
var listType = typeof(List<>).MakeGenericType(innerType);
var singleNullItemList = Activator.CreateInstance(listType);
((IList)singleNullItemList).Add(null);
return Expression.Constant(singleNullItemList);
}
*/
if (m.Method.Name.StartsWith(nameof(Queryable.Single))) // same as unsorted First with extra checks
{
RecurseToWhereOrRunLambda(m);
var firstObjectPtr = CoreQueryHandle.FindDirect(_realm.SharedRealmHandle);
if (firstObjectPtr == IntPtr.Zero)
{
if (m.Method.Name == nameof(Queryable.Single))
{
throw new InvalidOperationException("Sequence contains no matching element");
}
Debug.Assert(m.Method.Name == nameof(Queryable.SingleOrDefault), $"The method {m.Method.Name} is not supported. We expected {nameof(Queryable.SingleOrDefault)}.");
return Expression.Constant(null);
}
var firstObject = Realm.CreateObjectHandle(firstObjectPtr, _realm.SharedRealmHandle);
var nextObjectPtr = CoreQueryHandle.FindNext(firstObject);
if (nextObjectPtr != IntPtr.Zero)
{
throw new InvalidOperationException("Sequence contains more than one matching element");
}
return Expression.Constant(_realm.MakeObject(_metadata, firstObject));
}
if (m.Method.Name.StartsWith(nameof(Queryable.Last)))
{
RecurseToWhereOrRunLambda(m);
var lastObjectPtr = IntPtr.Zero;
using (ResultsHandle rh = _realm.MakeResultsForQuery(CoreQueryHandle, OptionalSortDescriptorBuilder))
{
var lastIndex = rh.Count() - 1;
if (lastIndex >= 0)
{
lastObjectPtr = rh.GetObjectAtIndex(lastIndex);
}
}
if (lastObjectPtr != IntPtr.Zero)
{
return Expression.Constant(_realm.MakeObject(_metadata, lastObjectPtr));
}
if (m.Method.Name == nameof(Queryable.Last))
{
throw new InvalidOperationException("Sequence contains no matching element");
}
Debug.Assert(m.Method.Name == nameof(Queryable.LastOrDefault), $"The method {m.Method.Name} is not supported. We expected {nameof(Queryable.LastOrDefault)}.");
return Expression.Constant(null);
}
if (m.Method.Name.StartsWith(nameof(Queryable.ElementAt)))
{
Visit(m.Arguments.First());
object argument;
if (!TryExtractConstantValue(m.Arguments.Last(), out argument) || argument.GetType() != typeof(int))
{
throw new NotSupportedException($"The method '{m.Method}' has to be invoked with a single integer constant argument or closure variable");
}
IntPtr objectPtr;
var index = (int)argument;
if (OptionalSortDescriptorBuilder == null)
{
objectPtr = CoreQueryHandle.FindDirect(_realm.SharedRealmHandle, (IntPtr)index);
}
else
{
using (var rh = _realm.MakeResultsForQuery(CoreQueryHandle, OptionalSortDescriptorBuilder))
{
objectPtr = rh.GetObjectAtIndex(index);
}
}
if (objectPtr != IntPtr.Zero)
{
var objectHandle = Realm.CreateObjectHandle(objectPtr, _realm.SharedRealmHandle);
return Expression.Constant(_realm.MakeObject(_metadata, objectHandle));
}
if (m.Method.Name == nameof(Queryable.ElementAt))
{
throw new ArgumentOutOfRangeException();
}
Debug.Assert(m.Method.Name == nameof(Queryable.ElementAtOrDefault), $"The method {m.Method.Name} is not supported. We expected {nameof(Queryable.ElementAtOrDefault)}.");
return Expression.Constant(null);
}
}
if (m.Method.DeclaringType == typeof(string) ||
m.Method.DeclaringType == typeof(StringExtensions))
{
QueryHandle.Operation<string> queryMethod = null;
// For extension methods, member should be m.Arguments[0] as MemberExpression;
MemberExpression member = null;
// For extension methods, that should be 1
var stringArgumentIndex = 0;
if (AreMethodsSame(m.Method, Methods.String.Contains.Value))
{
queryMethod = (q, c, v) => q.StringContains(c, v, caseSensitive: true);
}
else if (AreMethodsSame(m.Method, Methods.String.ContainsStringComparison.Value))
{
member = m.Arguments[0] as MemberExpression;
stringArgumentIndex = 1;
queryMethod = (q, c, v) => q.StringContains(c, v, GetComparisonCaseSensitive(m));
}
else if (AreMethodsSame(m.Method, Methods.String.StartsWith.Value))
{
queryMethod = (q, c, v) => q.StringStartsWith(c, v, caseSensitive: true);
}
else if (AreMethodsSame(m.Method, Methods.String.StartsWithStringComparison.Value))
{
queryMethod = (q, c, v) => q.StringStartsWith(c, v, GetComparisonCaseSensitive(m));
}
else if (AreMethodsSame(m.Method, Methods.String.EndsWith.Value))
{
queryMethod = (q, c, v) => q.StringEndsWith(c, v, caseSensitive: true);
}
else if (AreMethodsSame(m.Method, Methods.String.EndsWithStringComparison.Value))
{
queryMethod = (q, c, v) => q.StringEndsWith(c, v, GetComparisonCaseSensitive(m));
}
else if (AreMethodsSame(m.Method, Methods.String.IsNullOrEmpty.Value))
{
member = m.Arguments.SingleOrDefault() as MemberExpression;
if (member == null)
{
throw new NotSupportedException($"The method '{m.Method}' has to be invoked with a RealmObject member");
}
var columnIndex = CoreQueryHandle.GetColumnIndex(member.Member.Name);
CoreQueryHandle.GroupBegin();
CoreQueryHandle.NullEqual(columnIndex);
CoreQueryHandle.Or();
CoreQueryHandle.StringEqual(columnIndex, string.Empty, caseSensitive: true);
CoreQueryHandle.GroupEnd();
return m;
}
else if (AreMethodsSame(m.Method, Methods.String.EqualsMethod.Value))
{
queryMethod = (q, c, v) => q.StringEqual(c, v, caseSensitive: true);
}
else if (AreMethodsSame(m.Method, Methods.String.EqualsStringComparison.Value))
{
queryMethod = (q, c, v) => q.StringEqual(c, v, GetComparisonCaseSensitive(m));
}
else if (AreMethodsSame(m.Method, Methods.String.Like.Value))
{
member = m.Arguments[0] as MemberExpression;
stringArgumentIndex = 1;
object caseSensitive;
if (!TryExtractConstantValue(m.Arguments.Last(), out caseSensitive) || !(caseSensitive is bool))
{
throw new NotSupportedException($"The method '{m.Method}' has to be invoked with a string and boolean constant arguments.");
}
queryMethod = (q, c, v) => q.StringLike(c, v, (bool)caseSensitive);
}
if (queryMethod != null)
{
member = member ?? m.Object as MemberExpression;
if (member == null)
{
throw new NotSupportedException($"The method '{m.Method}' has to be invoked on a RealmObject member");
}
var columnIndex = CoreQueryHandle.GetColumnIndex(member.Member.Name);
object argument;
if (!TryExtractConstantValue(m.Arguments[stringArgumentIndex], out argument) ||
(argument != null && argument.GetType() != typeof(string)))
{
throw new NotSupportedException($"The method '{m.Method}' has to be invoked with a single string constant argument or closure variable");
}
queryMethod(CoreQueryHandle, columnIndex, (string)argument);
return m;
}
}
throw new NotSupportedException($"The method '{m.Method.Name}' is not supported");
}
// Compares two methods for equality. .NET Native's == doesn't return expected results.
private static bool AreMethodsSame(MethodInfo first, MethodInfo second)
{
if (first == second)
{
return true;
}
if (first.Name != second.Name ||
first.DeclaringType != second.DeclaringType)
{
return false;
}
var firstParameters = first.GetParameters();
var secondParameters = second.GetParameters();
if (firstParameters.Length != secondParameters.Length)
{
return false;
}
for (var i = 0; i < firstParameters.Length; i++)
{
if (firstParameters[i].ParameterType != secondParameters[i].ParameterType)
{
return false;
}
}
return true;
}
internal override Expression VisitUnary(UnaryExpression u)
{
switch (u.NodeType)
{
case ExpressionType.Not:
CoreQueryHandle.Not();
Visit(u.Operand); // recurse into richer expression, expect to VisitCombination
break;
default:
throw new NotSupportedException($"The unary operator '{u.NodeType}' is not supported");
}
return u;
}
protected void VisitCombination(BinaryExpression b, Action<QueryHandle> combineWith)
{
CoreQueryHandle.GroupBegin();
Visit(b.Left);
combineWith(CoreQueryHandle);
Visit(b.Right);
CoreQueryHandle.GroupEnd();
}
internal static bool TryExtractConstantValue(Expression expr, out object value)
{
var constant = expr as ConstantExpression;
if (constant != null)
{
value = constant.Value;
return true;
}
var memberAccess = expr as MemberExpression;
var fieldInfo = memberAccess?.Member as FieldInfo;
if (fieldInfo != null)
{
if (fieldInfo.Attributes.HasFlag(FieldAttributes.Static))
{
// Handle static fields (e.g. string.Empty)
value = fieldInfo.GetValue(null);
return true;
}
object targetObject;
if (TryExtractConstantValue(memberAccess.Expression, out targetObject))
{
value = fieldInfo.GetValue(targetObject);
return true;
}
}
var propertyInfo = memberAccess?.Member as PropertyInfo;
if (propertyInfo != null)
{
if (propertyInfo.GetMethod != null && propertyInfo.GetMethod.Attributes.HasFlag(MethodAttributes.Static))
{
value = propertyInfo.GetValue(null);
return true;
}
object targetObject;
if (TryExtractConstantValue(memberAccess.Expression, out targetObject))
{
value = propertyInfo.GetValue(targetObject);
return true;
}
}
value = null;
return false;
}
internal override Expression VisitBinary(BinaryExpression b)
{
if (b.NodeType == ExpressionType.AndAlso) // Boolean And with short-circuit
{
VisitCombination(b, (qh) => { /* noop -- AND is the default combinator */ });
}
else if (b.NodeType == ExpressionType.OrElse) // Boolean Or with short-circuit
{
VisitCombination(b, qh => qh.Or());
}
else
{
var memberExpression = b.Left as MemberExpression;
// bit of a hack to cope with the way LINQ changes the RHS of a char literal to an Int32
// so an incoming lambda looks like {p => (Convert(p.CharProperty) == 65)}
// from Where(p => p.CharProperty == 'A')
if (memberExpression == null && b.Left.NodeType == ExpressionType.Convert)
{
memberExpression = ((UnaryExpression)b.Left).Operand as MemberExpression;
}
var leftName = memberExpression?.Member.GetCustomAttribute<MapToAttribute>()?.Mapping ??
memberExpression?.Member.Name;
if (leftName == null ||
!(memberExpression.Member is PropertyInfo) ||
!_metadata.Schema.PropertyNames.Contains(leftName))
{
throw new NotSupportedException($"The left-hand side of the {b.NodeType} operator must be a direct access to a persisted property in Realm.\nUnable to process '{b.Left}'.");
}
object rightValue;
if (!TryExtractConstantValue(b.Right, out rightValue))
{
throw new NotSupportedException($"The rhs of the binary operator '{b.NodeType}' should be a constant or closure variable expression. \nUnable to process `{b.Right}`");
}
switch (b.NodeType)
{
case ExpressionType.Equal:
AddQueryEqual(CoreQueryHandle, leftName, rightValue);
break;
case ExpressionType.NotEqual:
AddQueryNotEqual(CoreQueryHandle, leftName, rightValue);
break;
case ExpressionType.LessThan:
AddQueryLessThan(CoreQueryHandle, leftName, rightValue);
break;
case ExpressionType.LessThanOrEqual:
AddQueryLessThanOrEqual(CoreQueryHandle, leftName, rightValue);
break;
case ExpressionType.GreaterThan:
AddQueryGreaterThan(CoreQueryHandle, leftName, rightValue);
break;
case ExpressionType.GreaterThanOrEqual:
AddQueryGreaterThanOrEqual(CoreQueryHandle, leftName, rightValue);
break;
default:
throw new NotSupportedException($"The binary operator '{b.NodeType}' is not supported");
}
}
return b;
}
private static void AddQueryEqual(QueryHandle queryHandle, string columnName, object value)
{
var columnIndex = queryHandle.GetColumnIndex(columnName);
if (value == null)
{
queryHandle.NullEqual(columnIndex);
}
else if (value is string)
{
queryHandle.StringEqual(columnIndex, (string)value, caseSensitive: true);
}
else if (value is bool)
{
queryHandle.BoolEqual(columnIndex, (bool)value);
}
else if (value is char)
{
queryHandle.IntEqual(columnIndex, (int)value);
}
else if (value is int)
{
queryHandle.IntEqual(columnIndex, (int)value);
}
else if (value is long)
{
queryHandle.LongEqual(columnIndex, (long)value);
}
else if (value is float)
{
queryHandle.FloatEqual(columnIndex, (float)value);
}
else if (value is double)
{
queryHandle.DoubleEqual(columnIndex, (double)value);
}
else if (value is DateTimeOffset)
{
queryHandle.TimestampTicksEqual(columnIndex, (DateTimeOffset)value);
}
else if (value is byte[])
{
var buffer = (byte[])value;
if (buffer.Length == 0)
{
// see RealmObject.SetByteArrayValue
queryHandle.BinaryEqual(columnIndex, (IntPtr)0x1, IntPtr.Zero);
return;
}
unsafe
{
fixed (byte* bufferPtr = (byte[])value)
{
queryHandle.BinaryEqual(columnIndex, (IntPtr)bufferPtr, (IntPtr)buffer.LongCount());
}
}
}
else if (value is RealmObject)
{
queryHandle.ObjectEqual(columnIndex, ((RealmObject)value).ObjectHandle);
}
else
{
throw new NotImplementedException();
}
}
private static void AddQueryNotEqual(QueryHandle queryHandle, string columnName, object value)
{
var columnIndex = queryHandle.GetColumnIndex(columnName);
if (value == null)
{
queryHandle.NullNotEqual(columnIndex);
}
else if (value is string)
{
queryHandle.StringNotEqual(columnIndex, (string)value, caseSensitive: true);
}
else if (value is bool)
{
queryHandle.BoolNotEqual(columnIndex, (bool)value);
}
else if (value is char)
{
queryHandle.IntNotEqual(columnIndex, (int)value);
}
else if (value is int)
{
queryHandle.IntNotEqual(columnIndex, (int)value);
}
else if (value is long)
{
queryHandle.LongNotEqual(columnIndex, (long)value);
}
else if (value is float)
{
queryHandle.FloatNotEqual(columnIndex, (float)value);
}
else if (value is double)
{
queryHandle.DoubleNotEqual(columnIndex, (double)value);
}
else if (value is DateTimeOffset)
{
queryHandle.TimestampTicksNotEqual(columnIndex, (DateTimeOffset)value);
}
else if (value is byte[])
{
var buffer = (byte[])value;
if (buffer.Length == 0)
{
// see RealmObject.SetByteArrayValue
queryHandle.BinaryNotEqual(columnIndex, (IntPtr)0x1, IntPtr.Zero);
return;
}
unsafe
{
fixed (byte* bufferPtr = (byte[])value)
{
queryHandle.BinaryNotEqual(columnIndex, (IntPtr)bufferPtr, (IntPtr)buffer.LongCount());
}
}
}
else if (value is RealmObject)
{
queryHandle.Not();
queryHandle.ObjectEqual(columnIndex, ((RealmObject)value).ObjectHandle);
}
else
{
throw new NotImplementedException();
}
}
private static void AddQueryLessThan(QueryHandle queryHandle, string columnName, object value)
{
var columnIndex = queryHandle.GetColumnIndex(columnName);
if (value is char)
{
queryHandle.IntLess(columnIndex, (int)value);
}
else if (value is int)
{
queryHandle.IntLess(columnIndex, (int)value);
}
else if (value is long)
{
queryHandle.LongLess(columnIndex, (long)value);
}
else if (value is float)
{
queryHandle.FloatLess(columnIndex, (float)value);
}
else if (value is double)
{
queryHandle.DoubleLess(columnIndex, (double)value);
}
else if (value is DateTimeOffset)
{
queryHandle.TimestampTicksLess(columnIndex, (DateTimeOffset)value);
}
else if (value is string || value is bool)
{
throw new Exception($"Unsupported type {value.GetType().Name}");
}
else
{
throw new NotImplementedException();
}
}
private static void AddQueryLessThanOrEqual(QueryHandle queryHandle, string columnName, object value)
{
var columnIndex = queryHandle.GetColumnIndex(columnName);
if (value is char)
{
queryHandle.IntLessEqual(columnIndex, (int)value);
}
else if (value is int)
{
queryHandle.IntLessEqual(columnIndex, (int)value);
}
else if (value is long)
{
queryHandle.LongLessEqual(columnIndex, (long)value);
}
else if (value is float)
{
queryHandle.FloatLessEqual(columnIndex, (float)value);
}
else if (value is double)
{
queryHandle.DoubleLessEqual(columnIndex, (double)value);
}
else if (value is DateTimeOffset)
{
queryHandle.TimestampTicksLessEqual(columnIndex, (DateTimeOffset)value);
}
else if (value is string || value is bool)
{
throw new Exception($"Unsupported type {value.GetType().Name}");
}
else
{
throw new NotImplementedException();
}
}
private static void AddQueryGreaterThan(QueryHandle queryHandle, string columnName, object value)
{
var columnIndex = queryHandle.GetColumnIndex(columnName);
if (value is char)
{
queryHandle.IntGreater(columnIndex, (int)value);
}
else if (value is int)
{
queryHandle.IntGreater(columnIndex, (int)value);
}
else if (value is long)
{
queryHandle.LongGreater(columnIndex, (long)value);
}
else if (value is float)
{
queryHandle.FloatGreater(columnIndex, (float)value);
}
else if (value is double)
{
queryHandle.DoubleGreater(columnIndex, (double)value);
}
else if (value is DateTimeOffset)
{
queryHandle.TimestampTicksGreater(columnIndex, (DateTimeOffset)value);
}
else if (value is string || value is bool)
{
throw new Exception($"Unsupported type {value.GetType().Name}");
}
else
{
throw new NotImplementedException();
}
}
private static void AddQueryGreaterThanOrEqual(QueryHandle queryHandle, string columnName, object value)
{
var columnIndex = queryHandle.GetColumnIndex(columnName);
if (value is char)
{
queryHandle.IntGreaterEqual(columnIndex, (int)value);
}
else if (value is int)
{
queryHandle.IntGreaterEqual(columnIndex, (int)value);
}
else if (value is long)
{
queryHandle.LongGreaterEqual(columnIndex, (long)value);
}
else if (value is float)
{
queryHandle.FloatGreaterEqual(columnIndex, (float)value);
}
else if (value is double)
{
queryHandle.DoubleGreaterEqual(columnIndex, (double)value);
}
else if (value is DateTimeOffset)
{
queryHandle.TimestampTicksGreaterEqual(columnIndex, (DateTimeOffset)value);
}
else if (value is string || value is bool)
{
throw new Exception($"Unsupported type {value.GetType().Name}");
}
else
{
throw new NotImplementedException();
}
}
private static bool GetComparisonCaseSensitive(MethodCallExpression m)
{
object argument;
if (!TryExtractConstantValue(m.Arguments.Last(), out argument) || !(argument is StringComparison))
{
throw new NotSupportedException($"The method '{m.Method}' has to be invoked with a string and StringComparison constant arguments.");
}
var comparison = (StringComparison)argument;
bool caseSensitive;
switch (comparison)
{
case StringComparison.Ordinal:
caseSensitive = true;
break;
case StringComparison.OrdinalIgnoreCase:
caseSensitive = false;
break;
default:
throw new NotSupportedException($"The comparison {comparison} is not yet supported. Use {StringComparison.Ordinal} or {StringComparison.OrdinalIgnoreCase}.");
}
return caseSensitive;
}
// strange as it may seem, this is also called for the LHS when simply iterating All<T>()
internal override Expression VisitConstant(ConstantExpression c)
{
var results = c.Value as IQueryableCollection;
if (results != null)
{
// assume constant nodes w/ IQueryables are table references
if (CoreQueryHandle != null)
{
throw new Exception("We already have a table...");
}
CoreQueryHandle = results.CreateQuery();
}
else if (c.Value?.GetType() == typeof(object))
{
throw new NotSupportedException($"The constant for '{c.Value}' is not supported");
}
return c;
}
internal override Expression VisitMemberAccess(MemberExpression m)
{
if (m.Expression != null && m.Expression.NodeType == ExpressionType.Parameter)
{
if (m.Type == typeof(bool))
{
object rhs = true; // box value
var leftName = m.Member.Name;
AddQueryEqual(CoreQueryHandle, leftName, rhs);
}
return m;
}
throw new NotSupportedException($"The member '{m.Member.Name}' is not supported");
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using Cassandra.DataStax.Graph;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Cassandra.Serialization.Graph.GraphSON2
{
internal class GraphSONNode : INode
{
private readonly IGraphTypeSerializer _graphSerializer;
private static readonly JTokenEqualityComparer Comparer = new JTokenEqualityComparer();
private readonly JToken _token;
private readonly string _graphsonType;
internal static readonly JsonSerializerSettings GraphSONSerializerSettings = new JsonSerializerSettings
{
Culture = CultureInfo.InvariantCulture,
DateParseHandling = DateParseHandling.None
};
public bool DeserializeGraphNodes => _graphSerializer.DefaultDeserializeGraphNodes;
public bool IsArray => _token is JArray;
public bool IsObjectTree => !IsScalar && !IsArray;
public bool IsScalar => _token is JValue
|| (_token is JObject jobj && jobj[GraphTypeSerializer.ValueKey] is JValue);
public long Bulk { get; }
internal GraphSONNode(IGraphTypeSerializer graphTypeSerializer, string json)
{
if (json == null)
{
throw new ArgumentNullException(nameof(json));
}
_graphSerializer = graphTypeSerializer ?? throw new ArgumentNullException(nameof(graphTypeSerializer));
var parsedJson = (JObject)JsonConvert.DeserializeObject(json, GraphSONNode.GraphSONSerializerSettings);
_token = parsedJson["result"];
if (_token is JObject jobj)
{
_graphsonType = jobj[GraphTypeSerializer.TypeKey]?.ToString();
}
var bulkToken = parsedJson["bulk"];
Bulk = bulkToken != null ? GetTokenValue<long>(bulkToken) : 1L;
}
internal GraphSONNode(IGraphTypeSerializer graphTypeSerializer, JToken parsedGraphItem)
{
_graphSerializer = graphTypeSerializer ?? throw new ArgumentNullException(nameof(graphTypeSerializer));
_token = parsedGraphItem ?? throw new ArgumentNullException(nameof(parsedGraphItem));
if (_token is JObject jobj)
{
_graphsonType = jobj[GraphTypeSerializer.TypeKey]?.ToString();
}
}
public T Get<T>(string propertyName, bool throwIfNotFound)
{
var value = GetPropertyValue(propertyName, throwIfNotFound);
if (value == null)
{
if (default(T) != null)
{
throw new NullReferenceException(string.Format(
"Cannot convert null to {0} because it is a value type, try using Nullable<{0}>",
typeof(T).Name));
}
return (T)(object)null;
}
return GetTokenValue<T>(value);
}
private JObject GetTypedValue()
{
var value = _token[GraphTypeSerializer.ValueKey];
if (value != null && GetGraphSONType() != null)
{
// The token represents a GraphSON2/GraphSON3 object {"@type": "g:...", "@value": {}}
return value as JObject;
}
return null;
}
private JProperty GetProperty(string name)
{
var graphObject = _token as JObject;
var typedValue = GetTypedValue();
if (typedValue != null)
{
graphObject = typedValue;
}
if (graphObject == null)
{
throw new KeyNotFoundException($"Cannot retrieve property '{name}' of instance: '{_token}'");
}
return graphObject.Property(name);
}
private JToken GetPropertyValue(string name, bool throwIfNotFound)
{
var property = GetProperty(name);
if (property == null)
{
if (throwIfNotFound)
{
throw new KeyNotFoundException($"Graph result has no top-level property '{name}'");
}
return null;
}
return property.Value;
}
public dynamic GetRaw()
{
return _token;
}
/// <summary>
/// Returns either a scalar value or an array representing the token value, performing conversions when required.
/// </summary>
private T GetTokenValue<T>(JToken token)
{
return _graphSerializer.FromDb<T>(token);
}
private object GetTokenValue(JToken token, Type type)
{
return _graphSerializer.FromDb(token, type);
}
/// <summary>
/// Returns true if the property is defined in this instance.
/// </summary>
/// <exception cref="InvalidOperationException">When the underlying value is not an object tree</exception>
public bool HasProperty(string name)
{
return GetProperty(name) != null;
}
/// <summary>
/// Provides the implementation for operations that get member values.
/// </summary>
public bool TryGetMember(GetMemberBinder binder, out object result)
{
var token = GetPropertyValue(binder.Name, false);
if (token == null)
{
result = null;
return false;
}
var node = new GraphNode(new GraphSONNode(_graphSerializer, token));
result = node.To(binder.ReturnType);
return true;
}
/// <summary>
/// Gets the hash code for this instance, based on its value.
/// </summary>
public override int GetHashCode()
{
return Comparer.GetHashCode(_token);
}
/// <inheritdoc />
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException("Serializing GraphNodes in GraphSON2/GraphSON3 to JSON is not supported.");
}
/// <summary>
/// Gets the a dictionary of properties of this node.
/// </summary>
public IDictionary<string, GraphNode> GetProperties()
{
return GetProperties<GraphNode>(_token);
}
/// <summary>
/// Gets the a dictionary of properties of this node.
/// </summary>
public IDictionary<string, IGraphNode> GetIProperties()
{
return GetProperties<IGraphNode>(_token);
}
private IDictionary<string, T> GetProperties<T>(JToken item) where T : class, IGraphNode
{
var graphObject = GetTypedValue() ?? item as JObject;
if (graphObject == null)
{
throw new InvalidOperationException($"Can not get properties from '{item}'");
}
return graphObject
.Properties()
.ToDictionary(prop => prop.Name, prop => new GraphNode(new GraphSONNode(_graphSerializer, prop.Value)) as T);
}
/// <summary>
/// Returns the representation of the <see cref="GraphNode"/> as an instance of the type provided.
/// </summary>
/// <exception cref="NotSupportedException">
/// Throws NotSupportedException when the target type is not supported
/// </exception>
public object To(Type type)
{
return GetTokenValue(_token, type);
}
/// <summary>
/// Returns the representation of the <see cref="GraphNode"/> as an instance of the type provided.
/// </summary>
/// <exception cref="NotSupportedException">
/// Throws NotSupportedException when the target type is not supported
/// </exception>
public T To<T>()
{
return GetTokenValue<T>(_token);
}
/// <summary>
/// Converts the instance into an array when the internal representation is a json array or a graphson list/set.
/// </summary>
public GraphNode[] ToArray()
{
return _graphSerializer.FromDb<GraphNode[]>(_token);
}
/// <summary>
/// Returns the json representation of the result.
/// </summary>
public override string ToString()
{
if (_token is JValue val)
{
return val.ToString(CultureInfo.InvariantCulture);
}
var tokenValue = _token[GraphTypeSerializer.ValueKey];
switch (tokenValue)
{
case null:
return string.Empty;
case JValue tokenValueVal:
return tokenValueVal.ToString(CultureInfo.InvariantCulture);
default:
return tokenValue.ToString();
}
}
public void WriteJson(JsonWriter writer, JsonSerializer serializer)
{
throw new NotSupportedException("Serializing GraphNodes in GraphSON2/GraphSON3 to JSON is not supported.");
}
/// <inheritdoc />
public string GetGraphSONType()
{
return _graphsonType;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2003 January 11
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the sqlite3_set_authorizer()
** API. This facility is an optional feature of the library. Embedded
** systems that do not need this facility may omit it by recompiling
** the library with -DSQLITE_OMIT_AUTHORIZATION=1
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** All of the code in this file may be omitted by defining a single
** macro.
*/
#if !SQLITE_OMIT_AUTHORIZATION
/*
** Set or clear the access authorization function.
**
** The access authorization function is be called during the compilation
** phase to verify that the user has read and/or write access permission on
** various fields of the database. The first argument to the auth function
** is a copy of the 3rd argument to this routine. The second argument
** to the auth function is one of these constants:
**
** SQLITE_CREATE_INDEX
** SQLITE_CREATE_TABLE
** SQLITE_CREATE_TEMP_INDEX
** SQLITE_CREATE_TEMP_TABLE
** SQLITE_CREATE_TEMP_TRIGGER
** SQLITE_CREATE_TEMP_VIEW
** SQLITE_CREATE_TRIGGER
** SQLITE_CREATE_VIEW
** SQLITE_DELETE
** SQLITE_DROP_INDEX
** SQLITE_DROP_TABLE
** SQLITE_DROP_TEMP_INDEX
** SQLITE_DROP_TEMP_TABLE
** SQLITE_DROP_TEMP_TRIGGER
** SQLITE_DROP_TEMP_VIEW
** SQLITE_DROP_TRIGGER
** SQLITE_DROP_VIEW
** SQLITE_INSERT
** SQLITE_PRAGMA
** SQLITE_READ
** SQLITE_SELECT
** SQLITE_TRANSACTION
** SQLITE_UPDATE
**
** The third and fourth arguments to the auth function are the name of
** the table and the column that are being accessed. The auth function
** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
** means that the SQL statement will never-run - the sqlite3_exec() call
** will return with an error. SQLITE_IGNORE means that the SQL statement
** should run but attempts to read the specified column will return NULL
** and attempts to write the column will be ignored.
**
** Setting the auth function to NULL disables this hook. The default
** setting of the auth function is NULL.
*/
int sqlite3_set_authorizer(
sqlite3 *db,
int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
void *pArg
){
sqlite3_mutex_enter(db->mutex);
db->xAuth = xAuth;
db->pAuthArg = pArg;
sqlite3ExpirePreparedStatements(db);
sqlite3_mutex_leave(db->mutex);
return SQLITE_OK;
}
/*
** Write an error message into pParse->zErrMsg that explains that the
** user-supplied authorization function returned an illegal value.
*/
static void sqliteAuthBadReturnCode(Parse *pParse){
sqlite3ErrorMsg(pParse, "authorizer malfunction");
pParse->rc = SQLITE_ERROR;
}
/*
** Invoke the authorization callback for permission to read column zCol from
** table zTab in database zDb. This function assumes that an authorization
** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
**
** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
** is treated as SQLITE_DENY. In this case an error is left in pParse.
*/
int sqlite3AuthReadCol(
Parse *pParse, /* The parser context */
const char *zTab, /* Table name */
const char *zCol, /* Column name */
int iDb /* Index of containing database. */
){
sqlite3 *db = pParse->db; /* Database handle */
char *zDb = db->aDb[iDb].zName; /* Name of attached database */
int rc; /* Auth callback return code */
rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
if( rc==SQLITE_DENY ){
if( db->nDb>2 || iDb!=0 ){
sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
}else{
sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
}
pParse->rc = SQLITE_AUTH;
}else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
sqliteAuthBadReturnCode(pParse);
}
return rc;
}
/*
** The pExpr should be a TK_COLUMN expression. The table referred to
** is in pTabList or else it is the NEW or OLD table of a trigger.
** Check to see if it is OK to read this particular column.
**
** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
** then generate an error.
*/
void sqlite3AuthRead(
Parse *pParse, /* The parser context */
Expr *pExpr, /* The expression to check authorization on */
Schema *pSchema, /* The schema of the expression */
SrcList *pTabList /* All table that pExpr might refer to */
){
sqlite3 *db = pParse->db;
Table *pTab = 0; /* The table being read */
const char *zCol; /* Name of the column of the table */
int iSrc; /* Index in pTabList->a[] of table being read */
int iDb; /* The index of the database the expression refers to */
int iCol; /* Index of column in table */
if( db->xAuth==0 ) return;
iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
if( iDb<0 ){
/* An attempt to read a column out of a subquery or other
** temporary table. */
return;
}
assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
if( pExpr->op==TK_TRIGGER ){
pTab = pParse->pTriggerTab;
}else{
assert( pTabList );
for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
pTab = pTabList->a[iSrc].pTab;
break;
}
}
}
iCol = pExpr->iColumn;
if( NEVER(pTab==0) ) return;
if( iCol>=0 ){
assert( iCol<pTab->nCol );
zCol = pTab->aCol[iCol].zName;
}else if( pTab->iPKey>=0 ){
assert( pTab->iPKey<pTab->nCol );
zCol = pTab->aCol[pTab->iPKey].zName;
}else{
zCol = "ROWID";
}
assert( iDb>=0 && iDb<db->nDb );
if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
pExpr->op = TK_NULL;
}
}
/*
** Do an authorization check using the code and arguments given. Return
** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
** is returned, then the error count and error message in pParse are
** modified appropriately.
*/
int sqlite3AuthCheck(
Parse *pParse,
int code,
const char *zArg1,
const char *zArg2,
const char *zArg3
){
sqlite3 *db = pParse->db;
int rc;
/* Don't do any authorization checks if the database is initialising
** or if the parser is being invoked from within sqlite3_declare_vtab.
*/
if( db->init.busy || IN_DECLARE_VTAB ){
return SQLITE_OK;
}
if( db->xAuth==0 ){
return SQLITE_OK;
}
rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
if( rc==SQLITE_DENY ){
sqlite3ErrorMsg(pParse, "not authorized");
pParse->rc = SQLITE_AUTH;
}else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
rc = SQLITE_DENY;
sqliteAuthBadReturnCode(pParse);
}
return rc;
}
/*
** Push an authorization context. After this routine is called, the
** zArg3 argument to authorization callbacks will be zContext until
** popped. Or if pParse==0, this routine is a no-op.
*/
void sqlite3AuthContextPush(
Parse *pParse,
AuthContext *pContext,
const char *zContext
){
assert( pParse );
pContext->pParse = pParse;
pContext->zAuthContext = pParse->zAuthContext;
pParse->zAuthContext = zContext;
}
/*
** Pop an authorization context that was previously pushed
** by sqlite3AuthContextPush
*/
void sqlite3AuthContextPop(AuthContext *pContext){
if( pContext->pParse ){
pContext->pParse->zAuthContext = pContext->zAuthContext;
pContext->pParse = 0;
}
}
#endif //* SQLITE_OMIT_AUTHORIZATION */
}
}
| |
//
// MultipartSigned.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (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;
using Org.BouncyCastle.Bcpg.OpenPgp;
using MimeKit.IO;
using MimeKit.IO.Filters;
namespace MimeKit.Cryptography {
/// <summary>
/// A signed multipart, as used by both S/MIME and PGP/MIME protocols.
/// </summary>
/// <remarks>
/// The first child of a multipart/signed is the content while the second child
/// is the detached signature data. Any other children are not defined and could
/// be anything.
/// </remarks>
public class MultipartSigned : Multipart
{
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.MultipartSigned"/> class.
/// </summary>
/// <remarks>This constructor is used by <see cref="MimeKit.MimeParser"/>.</remarks>
/// <param name="args">Information used by the constructor.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="args"/> is <c>null</c>.
/// </exception>
public MultipartSigned (MimeEntityConstructorArgs args) : base (args)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.MultipartSigned"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="MultipartSigned"/>.
/// </remarks>
public MultipartSigned () : base ("signed")
{
}
/// <summary>
/// Dispatches to the specific visit method for this MIME entity.
/// </summary>
/// <remarks>
/// This default implementation for <see cref="MimeKit.Cryptography.MultipartSigned"/> nodes
/// calls <see cref="MimeKit.MimeVisitor.VisitMultipartSigned"/>. Override this
/// method to call into a more specific method on a derived visitor class
/// of the <see cref="MimeKit.MimeVisitor"/> class. However, it should still
/// support unknown visitors by calling
/// <see cref="MimeKit.MimeVisitor.VisitMultipartSigned"/>.
/// </remarks>
/// <param name="visitor">The visitor.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="visitor"/> is <c>null</c>.
/// </exception>
public override void Accept (MimeVisitor visitor)
{
if (visitor == null)
throw new ArgumentNullException ("visitor");
visitor.VisitMultipartSigned (this);
}
/// <summary>
/// Creates a new <see cref="MultipartSigned"/>.
/// </summary>
/// <remarks>
/// Cryptographically signs the entity using the supplied signer and digest algorithm in
/// order to generate a detached signature and then adds the entity along with the
/// detached signature data to a new multipart/signed part.
/// </remarks>
/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
/// <param name="ctx">The cryptography context to use for signing.</param>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="entity">The entity to sign.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="digestAlgo"/> was out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The <paramref name="digestAlgo"/> is not supported.
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// A signing certificate could not be found for <paramref name="signer"/>.
/// </exception>
/// <exception cref="PrivateKeyNotFoundException">
/// The private key could not be found for <paramref name="signer"/>.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static MultipartSigned Create (CryptographyContext ctx, MailboxAddress signer, DigestAlgorithm digestAlgo, MimeEntity entity)
{
if (signer == null)
throw new ArgumentNullException ("signer");
if (entity == null)
throw new ArgumentNullException ("entity");
entity.Prepare (EncodingConstraint.SevenBit, 78);
using (var memory = new MemoryBlockStream ()) {
using (var filtered = new FilteredStream (memory)) {
// Note: see rfc3156, section 3 - second note
filtered.Add (new ArmoredFromFilter ());
// Note: see rfc3156, section 5.4 (this is the main difference between rfc2015 and rfc3156)
filtered.Add (new TrailingWhitespaceFilter ());
// Note: see rfc2015 or rfc3156, section 5.1
filtered.Add (new Unix2DosFilter ());
entity.WriteTo (filtered);
filtered.Flush ();
}
memory.Position = 0;
// Note: we need to parse the modified entity structure to preserve any modifications
var parser = new MimeParser (memory, MimeFormat.Entity);
var parsed = parser.ParseEntity ();
memory.Position = 0;
// sign the cleartext content
var signature = ctx.Sign (signer, digestAlgo, memory);
var micalg = ctx.GetDigestAlgorithmName (digestAlgo);
var signed = new MultipartSigned ();
// set the protocol and micalg Content-Type parameters
signed.ContentType.Parameters["protocol"] = ctx.SignatureProtocol;
signed.ContentType.Parameters["micalg"] = micalg;
// add the modified/parsed entity as our first part
signed.Add (parsed);
// add the detached signature as the second part
signed.Add (signature);
return signed;
}
}
/// <summary>
/// Creates a new <see cref="MultipartSigned"/>.
/// </summary>
/// <remarks>
/// Cryptographically signs the entity using the supplied signer and digest algorithm in
/// order to generate a detached signature and then adds the entity along with the
/// detached signature data to a new multipart/signed part.
/// </remarks>
/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
/// <param name="ctx">The OpenPGP context to use for signing.</param>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="entity">The entity to sign.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="signer"/> cannot be used for signing.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="digestAlgo"/> was out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The <paramref name="digestAlgo"/> is not supported.
/// </exception>
/// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
/// An error occurred in the OpenPGP subsystem.
/// </exception>
public static MultipartSigned Create (OpenPgpContext ctx, PgpSecretKey signer, DigestAlgorithm digestAlgo, MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (signer == null)
throw new ArgumentNullException ("signer");
if (entity == null)
throw new ArgumentNullException ("entity");
entity.Prepare (EncodingConstraint.SevenBit, 78);
using (var memory = new MemoryBlockStream ()) {
using (var filtered = new FilteredStream (memory)) {
// Note: see rfc3156, section 3 - second note
filtered.Add (new ArmoredFromFilter ());
// Note: see rfc3156, section 5.4 (this is the main difference between rfc2015 and rfc3156)
filtered.Add (new TrailingWhitespaceFilter ());
// Note: see rfc2015 or rfc3156, section 5.1
filtered.Add (new Unix2DosFilter ());
entity.WriteTo (filtered);
filtered.Flush ();
}
memory.Position = 0;
// Note: we need to parse the modified entity structure to preserve any modifications
var parser = new MimeParser (memory, MimeFormat.Entity);
var parsed = parser.ParseEntity ();
memory.Position = 0;
// sign the cleartext content
var micalg = ctx.GetDigestAlgorithmName (digestAlgo);
var signature = ctx.Sign (signer, digestAlgo, memory);
var signed = new MultipartSigned ();
// set the protocol and micalg Content-Type parameters
signed.ContentType.Parameters["protocol"] = ctx.SignatureProtocol;
signed.ContentType.Parameters["micalg"] = micalg;
// add the modified/parsed entity as our first part
signed.Add (parsed);
// add the detached signature as the second part
signed.Add (signature);
return signed;
}
}
/// <summary>
/// Creates a new <see cref="MultipartSigned"/>.
/// </summary>
/// <remarks>
/// Cryptographically signs the entity using the supplied signer and digest algorithm in
/// order to generate a detached signature and then adds the entity along with the
/// detached signature data to a new multipart/signed part.
/// </remarks>
/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="entity">The entity to sign.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="signer"/> cannot be used for signing.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="digestAlgo"/> was out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// <para>A cryptography context suitable for signing could not be found.</para>
/// <para>-or-</para>
/// <para>The <paramref name="digestAlgo"/> is not supported.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
/// An error occurred in the OpenPGP subsystem.
/// </exception>
public static MultipartSigned Create (PgpSecretKey signer, DigestAlgorithm digestAlgo, MimeEntity entity)
{
using (var ctx = (OpenPgpContext) CryptographyContext.Create ("application/pgp-signature")) {
return Create (ctx, signer, digestAlgo, entity);
}
}
/// <summary>
/// Creates a new <see cref="MultipartSigned"/>.
/// </summary>
/// <remarks>
/// Cryptographically signs the entity using the supplied signer in order
/// to generate a detached signature and then adds the entity along with
/// the detached signature data to a new multipart/signed part.
/// </remarks>
/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
/// <param name="ctx">The S/MIME context to use for signing.</param>
/// <param name="signer">The signer.</param>
/// <param name="entity">The entity to sign.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static MultipartSigned Create (SecureMimeContext ctx, CmsSigner signer, MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (signer == null)
throw new ArgumentNullException ("signer");
if (entity == null)
throw new ArgumentNullException ("entity");
entity.Prepare (EncodingConstraint.SevenBit, 78);
using (var memory = new MemoryBlockStream ()) {
using (var filtered = new FilteredStream (memory)) {
// Note: see rfc3156, section 3 - second note
filtered.Add (new ArmoredFromFilter ());
// Note: see rfc3156, section 5.4 (this is the main difference between rfc2015 and rfc3156)
filtered.Add (new TrailingWhitespaceFilter ());
// Note: see rfc2015 or rfc3156, section 5.1
filtered.Add (new Unix2DosFilter ());
entity.WriteTo (filtered);
filtered.Flush ();
}
memory.Position = 0;
// Note: we need to parse the modified entity structure to preserve any modifications
var parser = new MimeParser (memory, MimeFormat.Entity);
var parsed = parser.ParseEntity ();
memory.Position = 0;
// sign the cleartext content
var micalg = ctx.GetDigestAlgorithmName (signer.DigestAlgorithm);
var signature = ctx.Sign (signer, memory);
var signed = new MultipartSigned ();
// set the protocol and micalg Content-Type parameters
signed.ContentType.Parameters["protocol"] = ctx.SignatureProtocol;
signed.ContentType.Parameters["micalg"] = micalg;
// add the modified/parsed entity as our first part
signed.Add (parsed);
// add the detached signature as the second part
signed.Add (signature);
return signed;
}
}
/// <summary>
/// Creates a new <see cref="MultipartSigned"/>.
/// </summary>
/// <remarks>
/// Cryptographically signs the entity using the supplied signer in order
/// to generate a detached signature and then adds the entity along with
/// the detached signature data to a new multipart/signed part.
/// </remarks>
/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
/// <param name="signer">The signer.</param>
/// <param name="entity">The entity to sign.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.NotSupportedException">
/// A cryptography context suitable for signing could not be found.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public static MultipartSigned Create (CmsSigner signer, MimeEntity entity)
{
using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-signature")) {
return Create (ctx, signer, entity);
}
}
/// <summary>
/// Prepare the MIME entity for transport using the specified encoding constraints.
/// </summary>
/// <remarks>
/// Prepares the MIME entity for transport using the specified encoding constraints.
/// </remarks>
/// <param name="constraint">The encoding constraint.</param>
/// <param name="maxLineLength">The maximum number of octets allowed per line (not counting the CRLF). Must be between <c>60</c> and <c>998</c> (inclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="maxLineLength"/> is not between <c>60</c> and <c>998</c> (inclusive).</para>
/// <para>-or-</para>
/// <para><paramref name="constraint"/> is not a valid value.</para>
/// </exception>
public override void Prepare (EncodingConstraint constraint, int maxLineLength = 78)
{
if (maxLineLength < FormatOptions.MinimumLineLength || maxLineLength > FormatOptions.MaximumLineLength)
throw new ArgumentOutOfRangeException ("maxLineLength");
// Note: we do not iterate over our children because they are already signed
// and changing them would break the signature. They should already be
// properly prepared, anyway.
}
/// <summary>
/// Verifies the multipart/signed part.
/// </summary>
/// <remarks>
/// Verifies the multipart/signed part using the supplied cryptography context.
/// </remarks>
/// <returns>A signer info collection.</returns>
/// <param name="ctx">The cryptography context to use for verifying the signature.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="ctx"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.FormatException">
/// The multipart is malformed in some way.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// <paramref name="ctx"/> does not support verifying the signature part.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public DigitalSignatureCollection Verify (CryptographyContext ctx)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
var protocol = ContentType.Parameters["protocol"];
if (string.IsNullOrEmpty (protocol))
throw new FormatException ("The multipart/signed part did not specify a protocol.");
if (!ctx.Supports (protocol.Trim ()))
throw new NotSupportedException ("The specified cryptography context does not support the signature protocol.");
if (Count < 2)
throw new FormatException ("The multipart/signed part did not contain the expected children.");
var signature = this[1] as MimePart;
if (signature == null || signature.ContentObject == null)
throw new FormatException ("The signature part could not be found.");
var ctype = signature.ContentType;
var value = string.Format ("{0}/{1}", ctype.MediaType, ctype.MediaSubtype);
if (!ctx.Supports (value))
throw new NotSupportedException (string.Format ("The specified cryptography context does not support '{0}'.", value));
using (var signatureData = new MemoryBlockStream ()) {
signature.ContentObject.DecodeTo (signatureData);
signatureData.Position = 0;
using (var cleartext = new MemoryBlockStream ()) {
// Note: see rfc2015 or rfc3156, section 5.1
var options = FormatOptions.CloneDefault ();
options.NewLineFormat = NewLineFormat.Dos;
this[0].WriteTo (options, cleartext);
cleartext.Position = 0;
return ctx.Verify (cleartext, signatureData);
}
}
}
/// <summary>
/// Verifies the multipart/signed part.
/// </summary>
/// <remarks>
/// Verifies the multipart/signed part using the default cryptography context.
/// </remarks>
/// <returns>A signer info collection.</returns>
/// <exception cref="System.FormatException">
/// <para>The <c>protocol</c> parameter was not specified.</para>
/// <para>-or-</para>
/// <para>The multipart is malformed in some way.</para>
/// </exception>
/// <exception cref="System.NotSupportedException">
/// A cryptography context suitable for verifying the signature could not be found.
/// </exception>
/// <exception cref="Org.BouncyCastle.Cms.CmsException">
/// An error occurred in the cryptographic message syntax subsystem.
/// </exception>
public DigitalSignatureCollection Verify ()
{
var protocol = ContentType.Parameters["protocol"];
if (string.IsNullOrEmpty (protocol))
throw new FormatException ("The multipart/signed part did not specify a protocol.");
protocol = protocol.Trim ().ToLowerInvariant ();
using (var ctx = CryptographyContext.Create (protocol)) {
return Verify (ctx);
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Common.cs" company="Google">
//
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System.Runtime.InteropServices;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Tango
{
/// <summary>
/// This struct holds common global functionality used by
/// this SDK.
/// </summary>
public struct Common
{
/// <summary>
/// Codes returned by Tango API functions.
/// </summary>
public struct ErrorType
{
/// <summary>
/// Camera access not allowed.
/// </summary>
public static readonly int TANGO_NO_CAMERA_PERMISSION = -5;
/// <summary>
/// ADF access not allowed.
/// </summary>
public static readonly int TANGO_NO_ADF_PERMISSION = -4;
/// <summary>
/// Motion tracking not allowed.
/// </summary>
public static readonly int TANGO_NO_MOTION_TRACKING_PERMISSION = -3;
/// <summary>
/// General invalid state.
/// </summary>
public static readonly int TANGO_INVALID = -2;
/// <summary>
/// General error state.
/// </summary>
public static readonly int TANGO_ERROR = -1;
/// <summary>
/// No error, success.
/// </summary>
public static readonly int TANGO_SUCCESS = 0;
}
/// <summary>
/// Metadata keys supported by Tango APIs.
/// </summary>
public struct MetaDataKeyType
{
public const string KEY_UUID = "id";
public const string KEY_NAME = "name";
public const string KEY_DATE = "date_ms_since_epoch";
public const string KEY_TRANSFORMATION = "transformation";
}
/// <summary>
/// Return values from Android actvities.
/// </summary>
public enum AndroidResult
{
SUCCESS = -1,
CANCELED = 0,
DENIED = 1
}
/// <summary>
/// DEPRECATED: Empty string.
/// </summary>
public const string TANGO_PERMISSION_STRING = "";
/// <summary>
/// DEPRECATED: Tango permissions error.
/// </summary>
public const string TANGO_NO_PERMISSIONS_ERROR = "This application requires all Tango permissions to run. Please restart the application and grant Tango permissions.";
//// \cond
//// Collection of deprecated fields that should be removed
public const float UI_LABEL_START_X = 15.0f;
public const float UI_LABEL_START_Y = 15.0f;
public const float UI_LABEL_SIZE_X = 1920.0f;
public const float UI_LABEL_SIZE_Y = 35.0f;
public const float UI_LABEL_GAP_Y = 3.0f;
public const float UI_BUTTON_SIZE_X = 125.0f;
public const float UI_BUTTON_SIZE_Y = 65.0f;
public const float UI_BUTTON_GAP_X = 5.0f;
public const float UI_CAMERA_BUTTON_OFFSET = UI_BUTTON_SIZE_X + UI_BUTTON_GAP_X;
public const float UI_LABEL_OFFSET = UI_LABEL_GAP_Y + UI_LABEL_SIZE_Y;
public const float UI_FPS_LABEL_START_Y = UI_LABEL_START_Y + UI_LABEL_OFFSET;
public const float UI_EVENT_LABEL_START_Y = UI_FPS_LABEL_START_Y + UI_LABEL_OFFSET;
public const float UI_POSE_LABEL_START_Y = UI_EVENT_LABEL_START_Y + UI_LABEL_OFFSET;
public const float UI_DEPTH_LABLE_START_Y = UI_POSE_LABEL_START_Y + UI_LABEL_OFFSET;
public const string UI_FLOAT_FORMAT = "F3";
public const string UI_FONT_SIZE = "<size=25>";
public const float UI_TANGO_VERSION_X = UI_LABEL_START_X;
public const float UI_TANGO_VERSION_Y = UI_LABEL_START_Y;
public const float UI_TANGO_APP_SPECIFIC_START_X = UI_TANGO_VERSION_X;
public const float UI_TANGO_APP_SPECIFIC_START_Y = UI_TANGO_VERSION_Y + (UI_LABEL_OFFSET * 2);
public const string UX_SERVICE_VERSION = "Service version: {0}";
public const string UX_TANGO_SERVICE_VERSION = "Tango service version: {0}";
public const string UX_TANGO_SYSTEM_EVENT = "Tango system event: {0}";
public const string UX_TARGET_TO_BASE_FRAME = "Target->{0}, Base->{1}:";
public const string UX_STATUS = "\tstatus: {0}, count: {1}, delta time(ms): {2}, position (m): [{3}], orientation: [{4}]";
public const float SECOND_TO_MILLISECOND = 1000.0f;
//// \endcond
/// <summary>
/// Name of the Tango C-API library.
/// </summary>
internal const string TANGO_UNITY_DLL = "tango_client_api";
/// <summary>
/// Motion Tracking permission intent string.
/// </summary>
internal const string TANGO_MOTION_TRACKING_PERMISSIONS = "MOTION_TRACKING_PERMISSION";
/// <summary>
/// ADF Load/Save permission intent string.
/// </summary>
internal const string TANGO_ADF_LOAD_SAVE_PERMISSIONS = "ADF_LOAD_SAVE_PERMISSION";
/// <summary>
/// Code used to identify the result came from the Motion Tracking permission request.
/// </summary>
internal const int TANGO_MOTION_TRACKING_PERMISSIONS_REQUEST_CODE = 42;
/// <summary>
/// Code used to identify the result came from the ADF Load/Save permission request.
/// </summary>
internal const int TANGO_ADF_LOAD_SAVE_PERMISSIONS_REQUEST_CODE = 43;
/// <summary>
/// Max number of vertices the Point Cloud supports.
/// </summary>
internal const int UNITY_MAX_SUPPORTED_VERTS_PER_MESH = 65534;
/// <summary>
/// The length of an area description ID string.
/// </summary>
internal const int UUID_LENGTH = 37;
//// Backing for deprecated properties below.
#if (UNITY_EDITOR)
private static bool m_mirroring = true;
#elif (UNITY_ANDROID)
private static bool m_mirroring = false;
#else
private static bool m_mirroring = false;
#endif
private static Resolution m_depthFrameResolution;
private static int m_depthBufferSize;
/// <summary>
/// DEPRECATED: Property for mirroring.
/// </summary>
/// <value> Bool - sets mirroring.</value>
public static bool Mirroring
{
get { return m_mirroring; }
set { m_mirroring = value; }
}
/// <summary>
/// DEPRECATED: Property for the current depth frame resolution.
/// </summary>
/// <value> Resolution - Sets depth frame resolution reference.</value>
public static Resolution DepthFrameResolution
{
get { return m_depthFrameResolution; }
set { m_depthFrameResolution = value; }
}
/// <summary>
/// DEPRECATED: Property for the depth buffer size.
/// </summary>
/// <value> Bool - Sets the size of the depth buffer.</value>
public static int DepthBufferSize
{
get { return m_depthBufferSize; }
set { m_depthBufferSize = value; }
}
/// <summary>
/// DEPRECATED: Get the world rotation.
/// </summary>
/// <returns> Quaternion representing the world rotation.</returns>
public static Quaternion GetWorldRotation()
{
return OrientationManager.GetWorldRotation();
}
/// <summary>
/// DEPRECATED: Get the screen size if the screen was in landscape mode.
///
/// This looks at Screen.width and Screen.height.
/// </summary>
/// <returns>Vector2 containing the screen size.</returns>
public static Vector2 GetWindowResolution()
{
Vector2 screenSize;
if (Screen.width > Screen.height)
{
screenSize = new Vector2(Screen.width, Screen.height);
}
else
{
screenSize = new Vector2(Screen.height, Screen.width);
}
return screenSize;
}
/// <summary>
/// DEPRECATED: Get the aspect ratio of the screen in landscape mode.
/// </summary>
/// <returns>Aspect ratio.</returns>
public static float GetWindowResolutionAspect()
{
Vector2 resolution = GetWindowResolution();
return resolution.x / resolution.y;
}
/// <summary>
/// DEPRECATED: Misspelled version of GetWindowResolutionAspect.
/// </summary>
/// <returns>Aspect ratio.</returns>
public static float GetWindowResoltionAspect()
{
Vector2 resolution = GetWindowResolution();
return resolution.x / resolution.y;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Formatting;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.InteractiveWindow
{
/// <summary>
/// Provides implementation of a Repl Window built on top of the VS editor using projection buffers.
/// </summary>
internal partial class InteractiveWindow
{
private readonly UIThreadOnly _dangerous_uiOnly;
#region Initialization
public InteractiveWindow(
IInteractiveWindowEditorFactoryService host,
IContentTypeRegistryService contentTypeRegistry,
ITextBufferFactoryService bufferFactory,
IProjectionBufferFactoryService projectionBufferFactory,
IEditorOperationsFactoryService editorOperationsFactory,
ITextEditorFactoryService editorFactory,
IRtfBuilderService rtfBuilderService,
IIntellisenseSessionStackMapService intellisenseSessionStackMap,
ISmartIndentationService smartIndenterService,
IInteractiveEvaluator evaluator)
{
if (evaluator == null)
{
throw new ArgumentNullException(nameof(evaluator));
}
_dangerous_uiOnly = new UIThreadOnly(this, host);
this.Properties = new PropertyCollection();
_history = new History();
_intellisenseSessionStackMap = intellisenseSessionStackMap;
_smartIndenterService = smartIndenterService;
var replContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveContentTypes.InteractiveContentTypeName);
var replOutputContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveContentTypes.InteractiveOutputContentTypeName);
_outputBuffer = bufferFactory.CreateTextBuffer(replOutputContentType);
_standardInputBuffer = bufferFactory.CreateTextBuffer();
_promptBuffer = bufferFactory.CreateTextBuffer();
_secondaryPromptBuffer = bufferFactory.CreateTextBuffer();
_standardInputPromptBuffer = bufferFactory.CreateTextBuffer();
_outputLineBreakBuffer = bufferFactory.CreateTextBuffer();
var projBuffer = projectionBufferFactory.CreateProjectionBuffer(
new EditResolver(this),
Array.Empty<object>(),
ProjectionBufferOptions.None,
replContentType);
projBuffer.Properties.AddProperty(typeof(InteractiveWindow), this);
_projectionBuffer = projBuffer;
_dangerous_uiOnly.AppendNewOutputProjectionBuffer(); // Constructor runs on UI thread.
projBuffer.Changed += new EventHandler<TextContentChangedEventArgs>(ProjectionBufferChanged);
var roleSet = editorFactory.CreateTextViewRoleSet(
PredefinedTextViewRoles.Analyzable,
PredefinedTextViewRoles.Editable,
PredefinedTextViewRoles.Interactive,
PredefinedTextViewRoles.Zoomable,
PredefinedInteractiveTextViewRoles.InteractiveTextViewRole);
_textView = host.CreateTextView(this, projBuffer, roleSet);
_textView.Caret.PositionChanged += CaretPositionChanged;
_textView.Options.SetOptionValue(DefaultTextViewHostOptions.HorizontalScrollBarId, false);
_textView.Options.SetOptionValue(DefaultTextViewHostOptions.LineNumberMarginId, false);
_textView.Options.SetOptionValue(DefaultTextViewHostOptions.OutliningMarginId, false);
_textView.Options.SetOptionValue(DefaultTextViewHostOptions.GlyphMarginId, false);
_textView.Options.SetOptionValue(DefaultTextViewOptions.WordWrapStyleId, WordWrapStyles.WordWrap);
_lineBreakString = _textView.Options.GetNewLineCharacter();
_dangerous_uiOnly.EditorOperations = editorOperationsFactory.GetEditorOperations(_textView); // Constructor runs on UI thread.
_buffer = new OutputBuffer(this);
_outputWriter = new InteractiveWindowWriter(this, spans: null);
SortedSpans errorSpans = new SortedSpans();
_errorOutputWriter = new InteractiveWindowWriter(this, errorSpans);
OutputClassifierProvider.AttachToBuffer(_outputBuffer, errorSpans);
_rtfBuilderService = rtfBuilderService;
RequiresUIThread();
evaluator.CurrentWindow = this;
_evaluator = evaluator;
}
async Task<ExecutionResult> IInteractiveWindow.InitializeAsync()
{
RequiresUIThread();
if (_dangerous_uiOnly.State != State.Starting)
{
throw new InvalidOperationException(InteractiveWindowResources.AlreadyInitialized);
}
_dangerous_uiOnly.State = State.Initializing;
// Anything that reads options should wait until after this call so the evaluator can set the options first
ExecutionResult result = await _evaluator.InitializeAsync().ConfigureAwait(continueOnCapturedContext: true);
Debug.Assert(OnUIThread()); // ConfigureAwait should bring us back to the UI thread.
if (result.IsSuccessful)
{
_dangerous_uiOnly.PrepareForInput();
}
return result;
}
#endregion
private sealed class UIThreadOnly
{
private readonly InteractiveWindow _window;
private readonly IInteractiveWindowEditorFactoryService _host;
private readonly TaskScheduler _uiScheduler;
private readonly IReadOnlyRegion[] _outputProtection;
// Pending submissions to be processed whenever the REPL is ready to accept submissions.
private readonly Queue<PendingSubmission> _pendingSubmissions;
private DispatcherTimer _executionTimer;
private Cursor _oldCursor;
private Task<ExecutionResult> _currentTask;
private int _currentOutputProjectionSpan;
private int _outputTrackingCaretPosition;
// Read-only regions protecting initial span of the corresponding buffers:
public readonly IReadOnlyRegion[] StandardInputProtection;
public string UncommittedInput;
private IEditorOperations _editorOperations;
public IEditorOperations EditorOperations
{
get
{
return _editorOperations;
}
set
{
Debug.Assert(_editorOperations == null, "Assignment only happens once.");
Debug.Assert(value != null);
_editorOperations = value;
}
}
public State _state;
public State State
{
get
{
return _state;
}
set
{
_window.StateChanged?.Invoke(value);
_state = value;
}
}
public UIThreadOnly(InteractiveWindow window, IInteractiveWindowEditorFactoryService host)
{
_window = window;
_host = host;
_uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
StandardInputProtection = new IReadOnlyRegion[2];
_outputProtection = new IReadOnlyRegion[2];
_pendingSubmissions = new Queue<PendingSubmission>();
_outputTrackingCaretPosition = -1;
}
public Task<ExecutionResult> ResetAsync(bool initialize)
{
Debug.Assert(State != State.Resetting, "The button should have been disabled.");
if (_window._stdInputStart != null)
{
CancelStandardInput();
}
_window._buffer.Flush();
if (State == State.WaitingForInput)
{
var snapshot = _window._projectionBuffer.CurrentSnapshot;
var spanCount = snapshot.SpanCount;
Debug.Assert(_window.IsLanguage(snapshot.GetSourceSpan(spanCount - 1).Snapshot));
StoreUncommittedInput();
RemoveProjectionSpans(spanCount - 2, 2);
_window._currentLanguageBuffer = null;
}
// replace the task being interrupted by a "reset" task:
State = State.Resetting;
_currentTask = _window._evaluator.ResetAsync(initialize);
_currentTask.ContinueWith(FinishExecute, _uiScheduler);
return _currentTask;
}
public void ClearView()
{
if (_window._stdInputStart != null)
{
CancelStandardInput();
}
_window._adornmentToMinimize = false;
InlineAdornmentProvider.RemoveAllAdornments(_window._textView);
// remove all the spans except our initial span from the projection buffer
UncommittedInput = null;
// Clear the projection and buffers last as this might trigger events that might access other state of the REPL window:
RemoveProtection(_window._outputBuffer, _outputProtection);
RemoveProtection(_window._standardInputBuffer, StandardInputProtection);
using (var edit = _window._outputBuffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag))
{
edit.Delete(0, _window._outputBuffer.CurrentSnapshot.Length);
edit.Apply();
}
_window._buffer.Reset();
OutputClassifierProvider.ClearSpans(_window._outputBuffer);
_outputTrackingCaretPosition = 0;
using (var edit = _window._standardInputBuffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag))
{
edit.Delete(0, _window._standardInputBuffer.CurrentSnapshot.Length);
edit.Apply();
}
RemoveProjectionSpans(0, _window._projectionBuffer.CurrentSnapshot.SpanCount);
// Insert an empty output buffer.
// We do it for two reasons:
// 1) When output is written to asynchronously we need a buffer to store it.
// This may happen when clearing screen while background thread is writing to the console.
// 2) We need at least one non-inert span due to bugs in projection buffer.
AppendNewOutputProjectionBuffer();
_window._history.ForgetOriginalBuffers();
// If we were waiting for input, we need to restore the prompt that we just cleared.
// If we are in any other state, then we'll let normal transitions trigger the next prompt.
if (State == State.WaitingForInput)
{
PrepareForInput();
}
}
private void CancelStandardInput()
{
_window.AppendLineNoPromptInjection(_window._standardInputBuffer);
_window._inputValue = null;
_window._inputEvent.Set();
}
public void InsertCode(string text)
{
if (_window._stdInputStart != null)
{
return;
}
if (State == State.ExecutingInput)
{
AppendUncommittedInput(text);
}
else
{
if (!_window._textView.Selection.IsEmpty)
{
_window.CutOrDeleteSelection(isCut: false);
}
EditorOperations.InsertText(text);
}
}
public void Submit(PendingSubmission[] pendingSubmissions)
{
if (_window._stdInputStart == null)
{
if (State == State.WaitingForInput && _window._currentLanguageBuffer != null)
{
StoreUncommittedInput();
PendSubmissions(pendingSubmissions);
ProcessPendingSubmissions();
}
else
{
PendSubmissions(pendingSubmissions);
}
}
}
private void StoreUncommittedInput()
{
if (UncommittedInput == null)
{
string activeCode = _window.GetActiveCode();
if (!string.IsNullOrEmpty(activeCode))
{
UncommittedInput = activeCode;
}
}
}
private void PendSubmissions(IEnumerable<PendingSubmission> inputs)
{
foreach (var input in inputs)
{
_pendingSubmissions.Enqueue(input);
}
}
public void AddInput(string command)
{
// If the language buffer is readonly then input can not be added. Return immediately.
// The language buffer gets marked as readonly in SubmitAsync method when input on the prompt
// gets submitted. So it would be readonly when the user types #reset on the prompt. In that
// case it is the right thing to bail out of this method.
if (_window._currentLanguageBuffer != null && _window._currentLanguageBuffer.IsReadOnly(0))
{
return;
}
if (State == State.ExecutingInput || _window._currentLanguageBuffer == null)
{
AddLanguageBuffer();
_window._currentLanguageBuffer.Insert(0, command);
}
else
{
StoreUncommittedInput();
_window.SetActiveCode(command);
}
// Add command to history before calling FinishCurrentSubmissionInput as it adds newline
// to the end of the command.
_window._history.Add(_window._currentLanguageBuffer.CurrentSnapshot.GetExtent());
FinishCurrentSubmissionInput();
}
private void AppendUncommittedInput(string text)
{
if (string.IsNullOrEmpty(text))
{
// Do nothing.
}
else if (string.IsNullOrEmpty(UncommittedInput))
{
UncommittedInput = text;
}
else
{
UncommittedInput += text;
}
}
private void RestoreUncommittedInput()
{
if (UncommittedInput != null)
{
_window.SetActiveCode(UncommittedInput);
UncommittedInput = null;
}
}
/// <summary>
/// Pastes from the clipboard into the text view
/// </summary>
public bool Paste()
{
_window.MoveCaretToClosestEditableBuffer();
string format = _window._evaluator.FormatClipboard();
if (format != null)
{
InsertCode(format);
}
else if (Clipboard.ContainsText())
{
InsertCode(Clipboard.GetText());
}
else
{
return false;
}
return true;
}
/// <summary>
/// Appends given text to the last input span (standard input or active code input).
/// </summary>
private void AppendInput(string text)
{
var snapshot = _window._projectionBuffer.CurrentSnapshot;
var spanCount = snapshot.SpanCount;
var inputSpan = snapshot.GetSourceSpan(spanCount - 1);
var kind = _window.GetSpanKind(inputSpan.Snapshot);
Debug.Assert(kind == ReplSpanKind.Language || kind == ReplSpanKind.StandardInput);
var buffer = inputSpan.Snapshot.TextBuffer;
var span = inputSpan.Span;
using (var edit = buffer.CreateEdit())
{
edit.Insert(edit.Snapshot.Length, text);
edit.Apply();
}
var replSpan = new CustomTrackingSpan(
buffer.CurrentSnapshot,
new Span(span.Start, span.Length + text.Length),
PointTrackingMode.Negative,
PointTrackingMode.Positive);
ReplaceProjectionSpan(spanCount - 1, replSpan);
_window.Caret.EnsureVisible();
}
public void PrepareForInput()
{
_window._buffer.Flush();
AddLanguageBuffer();
// we are prepared for processing any postponed submissions there might have been:
ProcessPendingSubmissions();
}
private void ProcessPendingSubmissions()
{
Debug.Assert(_window._currentLanguageBuffer != null);
if (_pendingSubmissions.Count == 0)
{
RestoreUncommittedInput();
// move to the end (it might have been in virtual space):
_window.Caret.MoveTo(GetLastLine(_window.TextBuffer.CurrentSnapshot).End);
_window.Caret.EnsureVisible();
State = State.WaitingForInput;
var ready = _window.ReadyForInput;
if (ready != null)
{
ready();
}
return;
}
var submission = _pendingSubmissions.Dequeue();
// queue new work item:
_window.Dispatcher.Invoke(new Action(() =>
{
_window.SetActiveCode(submission.Input);
var taskDone = SubmitAsync();
if (submission.Completion != null)
{
taskDone.ContinueWith(x => submission.Completion.SetResult(null), TaskScheduler.Current);
}
}));
}
public Task SubmitAsync()
{
RequiresLanguageBuffer();
// TODO: queue submission
// Ensure that the REPL doesn't try to execute if it is already
// executing. If this invariant can no longer be maintained more of
// the code in this method will need to be bullet-proofed
if (State == State.ExecutingInput)
{
return Task.FromResult<object>(null);
}
// get command to save to history before calling FinishCurrentSubmissionInput
// as it adds newline at the end
var historySpan = _window._currentLanguageBuffer.CurrentSnapshot.GetExtent();
FinishCurrentSubmissionInput();
_window._history.UncommittedInput = null;
var snapshotSpan = _window._currentLanguageBuffer.CurrentSnapshot.GetExtent();
var trimmedSpan = snapshotSpan.TrimEnd();
if (trimmedSpan.Length == 0)
{
// TODO: reuse the current language buffer
PrepareForInput();
return Task.FromResult<object>(null);
}
else
{
_window._history.Add(historySpan);
State = State.ExecutingInput;
StartCursorTimer();
Debug.Assert(_currentTask == null, "Shouldn't be either executing or resetting");
_currentTask = _window._evaluator.ExecuteCodeAsync(snapshotSpan.GetText());
return _currentTask.ContinueWith(FinishExecute, _uiScheduler);
}
}
private void RequiresLanguageBuffer()
{
if (_window._currentLanguageBuffer == null)
{
Environment.FailFast("Language buffer not available");
}
}
private void FinishCurrentSubmissionInput()
{
_window.AppendLineNoPromptInjection(_window._currentLanguageBuffer);
ApplyProtection(_window._currentLanguageBuffer, regions: null);
if (_window._adornmentToMinimize)
{
// TODO (tomat): remember the index of the adornment(s) in the current output and minimize those instead of the last one
InlineAdornmentProvider.MinimizeLastInlineAdornment(_window._textView);
_window._adornmentToMinimize = false;
}
NewOutputBuffer();
}
/// <summary>
/// Marks the entire buffer as read-only.
/// </summary>
public void ApplyProtection(ITextBuffer buffer, IReadOnlyRegion[] regions, bool allowAppend = false)
{
using (var readonlyEdit = buffer.CreateReadOnlyRegionEdit())
{
int end = buffer.CurrentSnapshot.Length;
Span span = new Span(0, end);
var region0 = allowAppend ?
readonlyEdit.CreateReadOnlyRegion(span, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Allow) :
readonlyEdit.CreateReadOnlyRegion(span, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny);
// Create a second read-only region to prevent insert at start of buffer.
var region1 = (end > 0) ? readonlyEdit.CreateReadOnlyRegion(new Span(0, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny) : null;
readonlyEdit.Apply();
if (regions != null)
{
regions[0] = region0;
regions[1] = region1;
}
}
}
/// <summary>
/// Removes read-only region from buffer.
/// </summary>
public void RemoveProtection(ITextBuffer buffer, IReadOnlyRegion[] regions)
{
if (regions[0] != null)
{
Debug.Assert(regions[1] != null);
foreach (var region in regions)
{
using (var readonlyEdit = buffer.CreateReadOnlyRegionEdit())
{
readonlyEdit.RemoveReadOnlyRegion(region);
readonlyEdit.Apply();
}
}
}
}
public void NewOutputBuffer()
{
// Stop growing the current output projection span.
var sourceSpan = _window._projectionBuffer.CurrentSnapshot.GetSourceSpan(_currentOutputProjectionSpan);
var sourceSnapshot = sourceSpan.Snapshot;
Debug.Assert(_window.GetSpanKind(sourceSnapshot) == ReplSpanKind.Output);
var nonGrowingSpan = new CustomTrackingSpan(
sourceSnapshot,
sourceSpan.Span,
PointTrackingMode.Negative,
PointTrackingMode.Negative);
ReplaceProjectionSpan(_currentOutputProjectionSpan, nonGrowingSpan);
AppendNewOutputProjectionBuffer();
_outputTrackingCaretPosition = _window._textView.Caret.Position.BufferPosition;
}
public void AppendNewOutputProjectionBuffer()
{
var currentSnapshot = _window._outputBuffer.CurrentSnapshot;
var trackingSpan = new CustomTrackingSpan(
currentSnapshot,
new Span(currentSnapshot.Length, 0),
PointTrackingMode.Negative,
PointTrackingMode.Positive);
_currentOutputProjectionSpan = AppendProjectionSpan(trackingSpan);
}
private int AppendProjectionSpan(ITrackingSpan span)
{
int index = _window._projectionBuffer.CurrentSnapshot.SpanCount;
InsertProjectionSpan(index, span);
return index;
}
private void InsertProjectionSpan(int index, ITrackingSpan span)
{
_window._projectionBuffer.ReplaceSpans(index, 0, new[] { span }, EditOptions.None, editTag: s_suppressPromptInjectionTag);
}
public void ReplaceProjectionSpan(int spanToReplace, ITrackingSpan newSpan)
{
_window._projectionBuffer.ReplaceSpans(spanToReplace, 1, new[] { newSpan }, EditOptions.None, editTag: s_suppressPromptInjectionTag);
}
private void RemoveProjectionSpans(int index, int count)
{
_window._projectionBuffer.ReplaceSpans(index, count, Array.Empty<object>(), EditOptions.None, s_suppressPromptInjectionTag);
}
/// <summary>
/// Appends text to the output buffer and updates projection buffer to include it.
/// WARNING: this has to be the only method that writes to the output buffer so that
/// the output buffering counters are kept in sync.
/// </summary>
internal void AppendOutput(IEnumerable<string> output, int outputLength)
{
Debug.Assert(output.Any());
// we maintain this invariant so that projections don't split "\r\n" in half
// (the editor isn't happy about it and our line counting also gets simpler):
Debug.Assert(!_window._outputBuffer.CurrentSnapshot.EndsWith('\r'));
var projectionSpans = _window._projectionBuffer.CurrentSnapshot.GetSourceSpans();
Debug.Assert(_window.GetSpanKind(projectionSpans[_currentOutputProjectionSpan].Snapshot) == ReplSpanKind.Output);
int lineBreakProjectionSpanIndex = _currentOutputProjectionSpan + 1;
// insert line break projection span if there is none and the output doesn't end with a line break:
bool hasLineBreakProjection = false;
if (lineBreakProjectionSpanIndex < projectionSpans.Count)
{
var oldSpan = projectionSpans[lineBreakProjectionSpanIndex];
hasLineBreakProjection = _window.GetSpanKind(oldSpan.Snapshot) == ReplSpanKind.Output && string.Equals(oldSpan.GetText(), _window._lineBreakString);
}
Debug.Assert(output.Last().Last() != '\r');
bool endsWithLineBreak = output.Last().Last() == '\n';
bool insertLineBreak = !endsWithLineBreak && !hasLineBreakProjection;
bool removeLineBreak = endsWithLineBreak && hasLineBreakProjection;
// insert text to the subject buffer.
int oldBufferLength = _window._outputBuffer.CurrentSnapshot.Length;
InsertOutput(output, oldBufferLength);
if (removeLineBreak)
{
RemoveProjectionSpans(lineBreakProjectionSpanIndex, 1);
}
else if (insertLineBreak)
{
InsertProjectionSpan(lineBreakProjectionSpanIndex, CreateTrackingSpan(_window._outputLineBreakBuffer, _window._lineBreakString));
}
// caret didn't move since last time we moved it to track output:
if (_outputTrackingCaretPosition == _window._textView.Caret.Position.BufferPosition)
{
_window._textView.Caret.EnsureVisible();
_outputTrackingCaretPosition = _window._textView.Caret.Position.BufferPosition;
}
}
private void InsertOutput(IEnumerable<string> output, int position)
{
RemoveProtection(_window._outputBuffer, _outputProtection);
// append the text to output buffer and make sure it ends with a line break:
using (var edit = _window._outputBuffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag))
{
foreach (string text in output)
{
edit.Insert(position, text);
}
edit.Apply();
}
ApplyProtection(_window._outputBuffer, _outputProtection);
}
private void FinishExecute(Task<ExecutionResult> result)
{
// The finished task has been replaced by another task (e.g. reset).
// Do not perform any task finalization, it will be done by the replacement task.
if (_currentTask != result)
{
return;
}
_currentTask = null;
ResetCursor();
if (result.Exception != null || !result.Result.IsSuccessful)
{
if (_window._history.Last != null)
{
_window._history.Last.Failed = true;
}
}
PrepareForInput();
}
public void ExecuteInput()
{
ITextBuffer languageBuffer = GetLanguageBuffer(_window.Caret.Position.BufferPosition);
if (languageBuffer == null)
{
return;
}
if (languageBuffer == _window._currentLanguageBuffer)
{
// TODO (tomat): this should rather send an abstract "finish" command that various features
// can implement as needed (IntelliSense, inline rename would commit, etc.).
// For now, commit IntelliSense:
var completionSession = _window.SessionStack.TopSession as ICompletionSession;
if (completionSession != null)
{
completionSession.Commit();
}
SubmitAsync();
}
else
{
// append text of the target buffer to the current language buffer:
string text = TrimTrailingEmptyLines(languageBuffer.CurrentSnapshot);
_window._currentLanguageBuffer.Replace(new Span(_window._currentLanguageBuffer.CurrentSnapshot.Length, 0), text);
EditorOperations.MoveToEndOfDocument(false);
}
}
private static string TrimTrailingEmptyLines(ITextSnapshot snapshot)
{
var line = GetLastLine(snapshot);
while (line != null && line.Length == 0)
{
line = GetPreviousLine(line);
}
if (line == null)
{
return string.Empty;
}
return line.Snapshot.GetText(0, line.Extent.End.Position);
}
private static ITextSnapshotLine GetPreviousLine(ITextSnapshotLine line)
{
return line.LineNumber > 0 ? line.Snapshot.GetLineFromLineNumber(line.LineNumber - 1) : null;
}
/// <summary>
/// Returns the language or command text buffer that the specified point belongs to.
/// If the point lays in a prompt returns the buffer corresponding to the prompt.
/// </summary>
/// <returns>The language or command buffer or null if the point doesn't belong to any.</returns>
private ITextBuffer GetLanguageBuffer(SnapshotPoint point)
{
var sourceSpans = GetSourceSpans(point.Snapshot);
int promptIndex = _window.GetPromptIndexForPoint(sourceSpans, point);
if (promptIndex < 0)
{
return null;
}
// Grab the span following the prompt (either language or standard input).
var projectionSpan = sourceSpans[promptIndex + 1];
var inputSnapshot = projectionSpan.Snapshot;
if (_window.GetSpanKind(inputSnapshot) != ReplSpanKind.Language)
{
Debug.Assert(_window.GetSpanKind(inputSnapshot) == ReplSpanKind.StandardInput);
return null;
}
var inputBuffer = inputSnapshot.TextBuffer;
var projectedSpans = _window._textView.BufferGraph.MapUpToBuffer(
new SnapshotSpan(inputSnapshot, 0, inputSnapshot.Length),
SpanTrackingMode.EdgePositive,
_window._projectionBuffer);
Debug.Assert(projectedSpans.Count > 0);
var projectedSpansStart = projectedSpans.First().Start;
var projectedSpansEnd = projectedSpans.Last().End;
if (point < projectedSpansStart.GetContainingLine().Start)
{
return null;
}
// If the buffer is the current buffer, the cursor might be in a virtual space behind the buffer
// but logically it belongs to the current submission. Since the current language buffer is the last buffer in the
// projection we don't need to check for its end.
if (inputBuffer == _window._currentLanguageBuffer)
{
return inputBuffer;
}
// if the point is at the end of the buffer it might be on the next line that doesn't logically belong to the input region:
if (point > projectedSpansEnd || (point == projectedSpansEnd && projectedSpansEnd.GetContainingLine().LineBreakLength != 0))
{
return null;
}
return inputBuffer;
}
public void ResetCursor()
{
if (_executionTimer != null)
{
_executionTimer.Stop();
}
if (_oldCursor != null)
{
((ContentControl)_window._textView).Cursor = _oldCursor;
}
_oldCursor = null;
_executionTimer = null;
}
private void StartCursorTimer()
{
var timer = new DispatcherTimer();
timer.Tick += SetRunningCursor;
timer.Interval = TimeSpan.FromMilliseconds(250);
_executionTimer = timer;
timer.Start();
}
private void SetRunningCursor(object sender, EventArgs e)
{
var view = (ContentControl)_window._textView;
// Save the old value of the cursor so it can be restored
// after execution has finished
_oldCursor = view.Cursor;
// TODO: Design work to come up with the correct cursor to use
// Set the repl's cursor to the "executing" cursor
view.Cursor = Cursors.Wait;
// Stop the timer so it doesn't fire again
if (_executionTimer != null)
{
_executionTimer.Stop();
}
}
public int IndexOfLastStandardInputSpan(ReadOnlyCollection<SnapshotSpan> sourceSpans)
{
for (int i = sourceSpans.Count - 1; i >= 0; i--)
{
if (_window.GetSpanKind(sourceSpans[i].Snapshot) == ReplSpanKind.StandardInput)
{
return i;
}
}
return -1;
}
public void RemoveLastInputPrompt()
{
var snapshot = _window._projectionBuffer.CurrentSnapshot;
var spanCount = snapshot.SpanCount;
Debug.Assert(_window.IsPrompt(snapshot.GetSourceSpan(spanCount - SpansPerLineOfInput).Snapshot));
// projection buffer update must be the last operation as it might trigger event that accesses prompt line mapping:
RemoveProjectionSpans(spanCount - SpansPerLineOfInput, SpansPerLineOfInput);
}
/// <summary>
/// Creates and adds a new language buffer to the projection buffer.
/// </summary>
private void AddLanguageBuffer()
{
ITextBuffer buffer = _host.CreateAndActivateBuffer(_window);
buffer.Properties.AddProperty(typeof(IInteractiveEvaluator), _window._evaluator);
buffer.Properties.AddProperty(typeof(InteractiveWindow), _window);
_window._currentLanguageBuffer = buffer;
var bufferAdded = _window.SubmissionBufferAdded;
if (bufferAdded != null)
{
bufferAdded(_window, new SubmissionBufferAddedEventArgs(buffer));
}
// add the whole buffer to the projection buffer and set it up to expand to the right as text is appended
var promptSpan = _window.CreatePrimaryPrompt();
var languageSpan = new CustomTrackingSpan(
_window._currentLanguageBuffer.CurrentSnapshot,
new Span(0, 0),
PointTrackingMode.Negative,
PointTrackingMode.Positive);
// projection buffer update must be the last operation as it might trigger event that accesses prompt line mapping:
_window.AppendProjectionSpans(promptSpan, languageSpan);
}
}
internal enum State
{
/// <summary>
/// Initial state. <see cref="IInteractiveWindow.InitializeAsync"/> hasn't been called.
/// Transition to <see cref="Initializing"/> when <see cref="IInteractiveWindow.InitializeAsync"/> is called.
/// Transition to <see cref="Resetting"/> when <see cref="IInteractiveWindowOperations.ResetAsync"/> is called.
/// </summary>
Starting,
/// <summary>
/// In the process of calling <see cref="IInteractiveWindow.InitializeAsync"/>.
/// Transition to <see cref="WaitingForInput"/> when finished (in <see cref="UIThreadOnly.ProcessPendingSubmissions"/>).
/// Transition to <see cref="Resetting"/> when <see cref="IInteractiveWindowOperations.ResetAsync"/> is called.
/// </summary>
Initializing,
/// <summary>
/// In the process of calling <see cref="IInteractiveWindowOperations.ResetAsync"/>.
/// Transition to <see cref="WaitingForInput"/> when finished (in <see cref="UIThreadOnly.ProcessPendingSubmissions"/>).
/// Note: Should not see <see cref="IInteractiveWindowOperations.ResetAsync"/> calls while in this state.
/// </summary>
Resetting,
/// <summary>
/// Prompt has been displayed - waiting for the user to make the next submission.
/// Transition to <see cref="ExecutingInput"/> when <see cref="IInteractiveWindowOperations.ExecuteInput"/> is called.
/// Transition to <see cref="Resetting"/> when <see cref="IInteractiveWindowOperations.ResetAsync"/> is called.
/// </summary>
WaitingForInput,
/// <summary>
/// Executing the user's submission.
/// Transition to <see cref="WaitingForInput"/> when finished (in <see cref="UIThreadOnly.ProcessPendingSubmissions"/>).
/// Transition to <see cref="Resetting"/> when <see cref="IInteractiveWindowOperations.ResetAsync"/> is called.
/// </summary>
ExecutingInput,
/// <summary>
/// In the process of calling <see cref="IInteractiveWindow.ReadStandardInput"/>.
/// Return to preceding state when finished.
/// Transition to <see cref="Resetting"/> when <see cref="IInteractiveWindowOperations.ResetAsync"/> is called.
/// </summary>
/// <remarks>
/// TODO: When we clean up <see cref="IInteractiveWindow.ReadStandardInput"/> (https://github.com/dotnet/roslyn/issues/3984)
/// we should try to eliminate the "preceding state", since it substantially
/// increases the complexity of the state machine.
/// </remarks>
ReadingStandardInput,
}
}
}
| |
//
// ObstacleTree.cs
// MSAGL class for wrapping a RectangleNode<Obstacle> hierarchy for Rectilinear Edge Routing.
//
// Copyright Microsoft Corporation.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.GraphAlgorithms;
namespace Microsoft.Msagl.Routing.Rectilinear {
using System;
internal class ObstacleTree {
/// <summary>
/// The root of the hierarchy.
/// </summary>
internal RectangleNode<Obstacle> Root { get; private set; }
internal Rectangle GraphBox { get { return Root.Rectangle; } }
/// <summary>
/// Dictionary of sets of ancestors for each shape, for evaluating necessary group-boundary crossings.
/// </summary>
internal Dictionary<Shape, Set<Shape>> AncestorSets;
/// <summary>
/// Indicates whether we adjusted spatial ancestors due to blocked paths.
/// </summary>
internal bool SpatialAncestorsAdjusted;
/// <summary>
/// The map of shapes to obstacles.
/// </summary>
private Dictionary<Shape, Obstacle> shapeIdToObstacleMap;
/// <summary>
/// The map of all group boundary crossings for the current RestrictSegmentWithObstacles call.
/// </summary>
internal readonly GroupBoundaryCrossingMap CurrentGroupBoundaryCrossingMap = new GroupBoundaryCrossingMap();
/// <summary>
/// The list of all obstacles (not just those in the Root, which may have accretions of obstacles in convex hulls).
/// </summary>
private List<Obstacle> allObstacles;
/// <summary>
/// For accreting obstacles for clumps or convex hulls.
/// </summary>
private readonly Set<IntPair> overlapPairs = new Set<IntPair>();
/// <summary>
/// Indicates whether one or more obstacles overlap.
/// </summary>
private bool hasOverlaps;
/// <summary>
/// Member to avoid unnecessary class creation just to do a lookup.
/// </summary>
private readonly IntPair lookupIntPair = new IntPair(-1, -1);
/// <summary>
/// Create the tree hierarchy from the enumeration.
/// </summary>
/// <param name="obstacles"></param>
/// <param name="ancestorSets"></param>
/// <param name="idToObstacleMap"></param>
internal void Init(IEnumerable<Obstacle> obstacles, Dictionary<Shape, Set<Shape>> ancestorSets
, Dictionary<Shape, Obstacle> idToObstacleMap) {
CreateObstacleListAndOrdinals(obstacles);
this.AncestorSets = ancestorSets;
this.CreateRoot();
this.shapeIdToObstacleMap = idToObstacleMap;
}
private void CreateObstacleListAndOrdinals(IEnumerable<Obstacle> obstacles) {
this.allObstacles = obstacles.ToList();
int scanlineOrdinal = Obstacle.FirstNonSentinelOrdinal;
foreach (var obstacle in this.allObstacles) {
obstacle.Ordinal = scanlineOrdinal++;
}
}
private Obstacle OrdinalToObstacle(int index) {
Debug.Assert(index >= Obstacle.FirstNonSentinelOrdinal, "index too small");
Debug.Assert(index < this.allObstacles.Count + Obstacle.FirstNonSentinelOrdinal, "index too large");
return this.allObstacles[index - Obstacle.FirstNonSentinelOrdinal];
}
/// <summary>
/// Create the root with overlapping non-rectangular obstacles converted to their convex hulls, for more reliable calculations.
/// </summary>
private void CreateRoot() {
this.Root = CalculateHierarchy(this.GetAllObstacles());
if (!OverlapsExist()) {
return;
}
AccreteClumps();
AccreteConvexHulls();
GrowGroupsToAccommodateOverlaps();
this.Root = CalculateHierarchy(this.GetAllObstacles().Where(obs => obs.IsPrimaryObstacle));
}
private bool OverlapsExist() {
if (this.Root == null) {
return false;
}
RectangleNodeUtils.CrossRectangleNodes<Obstacle>(this.Root, this.Root, this.CheckForInitialOverlaps);
return this.hasOverlaps;
}
private bool OverlapPairAlreadyFound(Obstacle a, Obstacle b) {
// If we already found it then we'll have enqueued it in the reverse order.
this.lookupIntPair.x = b.Ordinal;
this.lookupIntPair.y = a.Ordinal;
return this.overlapPairs.Contains(this.lookupIntPair);
}
private void CheckForInitialOverlaps(Obstacle a, Obstacle b) {
if (this.hasOverlaps) {
return;
}
bool aIsInsideB, bIsInsideA;
if (ObstaclesIntersect(a, b, out aIsInsideB, out bIsInsideA)) {
this.hasOverlaps = true;
return;
}
if (!aIsInsideB && !bIsInsideA) {
return;
}
// One obstacle is inside the other. If they're both groups, or a non-group is inside a group, nothing
// further is needed; we process groups differently because we can go through their sides.
if (a.IsGroup && b.IsGroup) {
return;
}
if ((a.IsGroup && bIsInsideA) || (b.IsGroup && aIsInsideB)) {
return;
}
this.hasOverlaps = true;
}
private void AccreteClumps() {
// Clumps are only created once. After that, as the result of convex hull creation, we may
// overlap an obstacle of a clump, in which case we enclose the clump in the convex hull as well.
// We only allow clumps of rectangular obstacles, to avoid angled sides in the scanline.
this.AccumulateObstaclesForClumps();
if (this.overlapPairs.Count == 0) {
return;
}
this.CreateClumps();
}
private void AccreteConvexHulls() {
// Convex-hull creation is transitive, because the created hull may overlap additional obstacles.
for (; ; ) {
this.AccumulateObstaclesForConvexHulls();
if (!this.CreateConvexHulls()) {
return;
}
}
}
internal static RectangleNode<Obstacle> CalculateHierarchy(IEnumerable<Obstacle> obstacles) {
var rectNodes = obstacles.Select(obs => new RectangleNode<Obstacle>(obs, obs.VisibilityBoundingBox)).ToList();
return RectangleNode<Obstacle>.CreateRectangleNodeOnListOfNodes(rectNodes);
}
private void AccumulateObstaclesForClumps() {
this.overlapPairs.Clear();
var rectangularObstacles = CalculateHierarchy(this.GetAllObstacles().Where(obs => !obs.IsGroup && obs.IsRectangle));
if (rectangularObstacles == null) {
return;
}
RectangleNodeUtils.CrossRectangleNodes<Obstacle>(rectangularObstacles, rectangularObstacles, this.EvaluateOverlappedPairForClump);
}
private void EvaluateOverlappedPairForClump(Obstacle a, Obstacle b) {
Debug.Assert(!a.IsGroup && !b.IsGroup, "Groups should not come here");
Debug.Assert(a.IsRectangle && b.IsRectangle, "Only rectangles should come here");
if ((a == b) || this.OverlapPairAlreadyFound(a, b)) {
return;
}
bool aIsInsideB, bIsInsideA;
if (!ObstaclesIntersect(a, b, out aIsInsideB, out bIsInsideA) && !aIsInsideB && !bIsInsideA) {
return;
}
this.overlapPairs.Insert(new IntPair(a.Ordinal, b.Ordinal));
}
private void AccumulateObstaclesForConvexHulls() {
this.overlapPairs.Clear();
var allPrimaryNonGroupObstacles = CalculateHierarchy(this.GetAllObstacles().Where(obs => obs.IsPrimaryObstacle && !obs.IsGroup));
if (allPrimaryNonGroupObstacles == null) {
return;
}
RectangleNodeUtils.CrossRectangleNodes<Obstacle>(allPrimaryNonGroupObstacles, allPrimaryNonGroupObstacles, this.EvaluateOverlappedPairForConvexHull);
}
private void EvaluateOverlappedPairForConvexHull(Obstacle a, Obstacle b) {
Debug.Assert(!a.IsGroup && !b.IsGroup, "Groups should not come here");
if ((a == b) || this.OverlapPairAlreadyFound(a, b)) {
return;
}
bool aIsInsideB, bIsInsideA;
if (!ObstaclesIntersect(a, b, out aIsInsideB, out bIsInsideA) && !aIsInsideB && !bIsInsideA) {
return;
}
// If either is in a convex hull, those must be coalesced.
if (!a.IsInConvexHull && !b.IsInConvexHull) {
// If the obstacles are rectangles, we don't need to do anything (for this pair).
if (a.IsRectangle && b.IsRectangle) {
return;
}
}
this.overlapPairs.Insert(new IntPair(a.Ordinal, b.Ordinal));
AddClumpToConvexHull(a);
AddClumpToConvexHull(b);
AddConvexHullToConvexHull(a);
AddConvexHullToConvexHull(b);
}
void GrowGroupsToAccommodateOverlaps() {
// Group growth is transitive, because the created hull may overlap additional obstacles.
for (; ; ) {
this.AccumulateObstaclesForGroupOverlaps();
if (!this.GrowGroupsToResolveOverlaps()) {
return;
}
}
}
private void AccumulateObstaclesForGroupOverlaps() {
var groupObstacles = CalculateHierarchy(this.GetAllObstacles().Where(obs => obs.IsGroup));
var allPrimaryObstacles = CalculateHierarchy(this.GetAllObstacles().Where(obs => obs.IsPrimaryObstacle));
if ((groupObstacles == null) || (allPrimaryObstacles == null)) {
return;
}
RectangleNodeUtils.CrossRectangleNodes<Obstacle>(groupObstacles, allPrimaryObstacles, this.EvaluateOverlappedPairForGroup);
}
private void EvaluateOverlappedPairForGroup(Obstacle a, Obstacle b) {
Debug.Assert(a.IsGroup, "Inconsistency in overlapping group enumeration");
if ((a == b) || this.OverlapPairAlreadyFound(a, b)) {
return;
}
bool aIsInsideB, bIsInsideA;
var curvesIntersect = ObstaclesIntersect(a, b, out aIsInsideB, out bIsInsideA);
if (!curvesIntersect && !aIsInsideB && !bIsInsideA) {
return;
}
if (a.IsRectangle && b.IsRectangle) {
// If these are already rectangles, we don't need to do anything here. Non-group VisibilityPolylines
// will not change by the group operations; we'll just grow the group if needed (if it is already
// nonrectangular, either because it came in that way or because it has intersected a non-rectangle).
// However, SparseVg needs to know about the overlap so it will create interior scansegments if the
// obstacle is not otherwise overlapped.
if (!b.IsGroup) {
if (aIsInsideB || FirstRectangleContainsACornerOfTheOther(b.VisibilityBoundingBox, a.VisibilityBoundingBox)) {
b.OverlapsGroupCorner = true;
}
}
return;
}
if (!curvesIntersect) {
// If the borders don't intersect, we don't need to do anything if both are groups or the
// obstacle or convex hull is inside the group. Otherwise we have to grow group a to encompass b.
if (b.IsGroup || bIsInsideA) {
return;
}
}
this.overlapPairs.Insert(new IntPair(a.Ordinal, b.Ordinal));
}
private static bool FirstRectangleContainsACornerOfTheOther(Rectangle a, Rectangle b) {
return a.Contains(b.LeftBottom) || a.Contains(b.LeftTop) || a.Contains(b.RightTop) || a.Contains(b.RightBottom);
}
private static bool FirstPolylineStartIsInsideSecondPolyline(Polyline first, Polyline second) {
return Curve.PointRelativeToCurveLocation(first.Start, second) != PointLocation.Outside;
}
private void AddClumpToConvexHull(Obstacle obstacle) {
if (obstacle.IsOverlapped) {
foreach (var sibling in obstacle.Clump.Where(sib => sib.Ordinal != obstacle.Ordinal)) {
this.overlapPairs.Insert(new IntPair(obstacle.Ordinal, sibling.Ordinal));
}
// Clear this now so any overlaps with other obstacles in the clump won't doubly insert.
obstacle.Clump.Clear();
}
}
private void AddConvexHullToConvexHull(Obstacle obstacle) {
if (obstacle.IsInConvexHull) {
foreach (var sibling in obstacle.ConvexHull.Obstacles.Where(sib => sib.Ordinal != obstacle.Ordinal)) {
this.overlapPairs.Insert(new IntPair(obstacle.Ordinal, sibling.Ordinal));
}
// Clear this now so any overlaps with other obstacles in the ConvexHull won't doubly insert.
obstacle.ConvexHull.Obstacles.Clear();
}
}
private void CreateClumps() {
var graph = new BasicGraph<IntPair>(this.overlapPairs);
var connectedComponents = ConnectedComponentCalculator<IntPair>.GetComponents(graph);
foreach (var component in connectedComponents) {
// GetComponents returns at least one self-entry for each index - including the < FirstNonSentinelOrdinal ones.
if (component.Count() == 1) {
continue;
}
var clump = new Clump(component.Select(this.OrdinalToObstacle));
foreach (var obstacle in clump) {
obstacle.Clump = clump;
}
}
}
private bool CreateConvexHulls() {
var found = false;
var graph = new BasicGraph<IntPair>(this.overlapPairs);
var connectedComponents = ConnectedComponentCalculator<IntPair>.GetComponents(graph);
foreach (var component in connectedComponents) {
// GetComponents returns at least one self-entry for each index - including the < FirstNonSentinelOrdinal ones.
if (component.Count() == 1) {
continue;
}
found = true;
var obstacles = component.Select(this.OrdinalToObstacle);
var points = obstacles.SelectMany(obs => obs.VisibilityPolyline);
var och = new OverlapConvexHull(ConvexHull.CreateConvexHullAsClosedPolyline(points), obstacles);
foreach (var obstacle in obstacles) {
obstacle.SetConvexHull(och);
}
}
return found;
}
private bool GrowGroupsToResolveOverlaps() {
// This is one-at-a-time so not terribly efficient but there should be a very small number of such overlaps, if any.
var found = false;
foreach (var pair in this.overlapPairs) {
found = true;
var a = this.OrdinalToObstacle(pair.First);
var b = this.OrdinalToObstacle(pair.Second);
if (!ResolveGroupAndGroupOverlap(a, b)) {
ResolveGroupAndObstacleOverlap(a, b);
}
}
this.overlapPairs.Clear();
return found;
}
private static bool ResolveGroupAndGroupOverlap(Obstacle a, Obstacle b) {
// For simplicity, pick the larger group and make grow its convex hull to encompass the smaller.
if (!b.IsGroup) {
return false;
}
if (a.VisibilityPolyline.BoundingBox.Area > b.VisibilityPolyline.BoundingBox.Area) {
ResolveGroupAndObstacleOverlap(a, b);
} else {
ResolveGroupAndObstacleOverlap(b, a);
}
return true;
}
private static void ResolveGroupAndObstacleOverlap(Obstacle group, Obstacle obstacle) {
// Create a convex hull for the group which goes outside the obstacle (which may also be a group).
// It must go outside the obstacle so we don't have coinciding angled sides in the scanline.
var loosePolyline = obstacle.LooseVisibilityPolyline;
GrowGroupAroundLoosePolyline(group, loosePolyline);
// Due to rounding we may still report this to be close or intersecting; grow it again if so.
bool aIsInsideB, bIsInsideA;
while (ObstaclesIntersect(obstacle, group, out aIsInsideB, out bIsInsideA) || !aIsInsideB) {
loosePolyline = Obstacle.CreateLoosePolyline(loosePolyline);
GrowGroupAroundLoosePolyline(group, loosePolyline);
}
return;
}
private static void GrowGroupAroundLoosePolyline(Obstacle group, Polyline loosePolyline) {
var points = group.VisibilityPolyline.Select(p => p).Concat(loosePolyline.Select(p => p));
group.SetConvexHull(new OverlapConvexHull(ConvexHull.CreateConvexHullAsClosedPolyline(points), new[] { group }));
}
internal static bool ObstaclesIntersect(Obstacle a, Obstacle b, out bool aIsInsideB, out bool bIsInsideA) {
if (Curve.CurvesIntersect(a.VisibilityPolyline, b.VisibilityPolyline)) {
aIsInsideB = false;
bIsInsideA = false;
return true;
}
aIsInsideB = FirstPolylineStartIsInsideSecondPolyline(a.VisibilityPolyline, b.VisibilityPolyline);
bIsInsideA = !aIsInsideB && FirstPolylineStartIsInsideSecondPolyline(b.VisibilityPolyline, a.VisibilityPolyline);
if (a.IsRectangle && b.IsRectangle) {
// Rectangles do not require further evaluation.
return false;
}
if (ObstaclesAreCloseEnoughToBeConsideredTouching(a, b, aIsInsideB, bIsInsideA)) {
aIsInsideB = false;
bIsInsideA = false;
return true;
}
return false;
}
private static bool ObstaclesAreCloseEnoughToBeConsideredTouching(Obstacle a, Obstacle b, bool aIsInsideB, bool bIsInsideA) {
// This is only called when the obstacle.VisibilityPolylines don't intersect, thus one is inside the other
// or both are outside. If both are outside then either one's LooseVisibilityPolyline may be used.
if (!aIsInsideB && !bIsInsideA) {
return Curve.CurvesIntersect(a.LooseVisibilityPolyline, b.VisibilityPolyline);
}
// Otherwise see if the inner one is close enough to the outer border to consider them touching.
var innerLoosePolyline = aIsInsideB ? a.LooseVisibilityPolyline : b.LooseVisibilityPolyline;
var outerPolyline = aIsInsideB ? b.VisibilityPolyline : a.VisibilityPolyline;
foreach (Point innerPoint in innerLoosePolyline) {
if (Curve.PointRelativeToCurveLocation(innerPoint, outerPolyline) == PointLocation.Outside) {
var outerParamPoint = Curve.ClosestPoint(outerPolyline, innerPoint);
if (!ApproximateComparer.CloseIntersections(innerPoint, outerParamPoint)) {
return true;
}
}
}
return false;
}
/// <summary>
/// Add ancestors that are spatial parents - they may not be in the hierarchy, but we need to be
/// able to cross their boundaries if we're routing between obstacles on different sides of them.
/// </summary>
internal bool AdjustSpatialAncestors() {
if (this.SpatialAncestorsAdjusted) {
return false;
}
// Add each group to the AncestorSet of any spatial children (duplicate Insert() is ignored).
foreach (var group in GetAllGroups()) {
var groupBox = group.VisibilityBoundingBox;
foreach (var obstacle in Root.GetNodeItemsIntersectingRectangle(groupBox)) {
if ((obstacle != group) && Curve.ClosedCurveInteriorsIntersect(obstacle.VisibilityPolyline, group.VisibilityPolyline)) {
if (obstacle.IsInConvexHull)
{
Debug.Assert(obstacle.IsPrimaryObstacle, "Only primary obstacles should be in the hierarchy");
foreach (var sibling in obstacle.ConvexHull.Obstacles)
{
AncestorSets[sibling.InputShape].Insert(group.InputShape);
}
}
AncestorSets[obstacle.InputShape].Insert(group.InputShape);
}
}
}
// Remove any hierarchical ancestors that are not spatial ancestors. Otherwise, when trying to route to
// obstacles that *are* spatial children of such a non-spatial-but-hierarchical ancestor, we won't enable
// crossing the boundary the first time and will always go to the full "activate all groups" path. By
// removing them here we not only get a better graph (avoiding some spurious crossings) but we're faster
// both in path generation and Nudging.
var nonSpatialGroups = new List<Shape>();
foreach (var child in Root.GetAllLeaves()) {
var childBox = child.VisibilityBoundingBox;
// This has to be two steps because we can't modify the Set during enumeration.
nonSpatialGroups.AddRange(AncestorSets[child.InputShape].Where(anc => !childBox.Intersects(this.shapeIdToObstacleMap[anc].VisibilityBoundingBox)));
foreach (var group in nonSpatialGroups) {
AncestorSets[child.InputShape].Remove(group);
}
nonSpatialGroups.Clear();
}
this.SpatialAncestorsAdjusted = true;
return true;
}
internal IEnumerable<Obstacle> GetAllGroups() {
return GetAllObstacles().Where(obs => obs.IsGroup);
}
/// <summary>
/// Clear the internal state.
/// </summary>
internal void Clear() {
Root = null;
AncestorSets = null;
}
/// <summary>
/// Create a LineSegment that contains the max visibility from startPoint in the desired direction.
/// </summary>
internal LineSegment CreateMaxVisibilitySegment(Point startPoint, Directions dir, out PointAndCrossingsList pacList) {
var graphBoxBorderIntersect = StaticGraphUtility.RectangleBorderIntersect(this.GraphBox, startPoint, dir);
if (PointComparer.GetDirections(startPoint, graphBoxBorderIntersect) == Directions. None) {
pacList = null;
return new LineSegment(startPoint, startPoint);
}
var segment = this.RestrictSegmentWithObstacles(startPoint, graphBoxBorderIntersect);
// Store this off before other operations which overwrite it.
pacList = this.CurrentGroupBoundaryCrossingMap.GetOrderedListBetween(segment.Start, segment.End);
return segment;
}
/// <summary>
/// Convenience functions that call through to RectangleNode.
/// </summary>
/// <returns></returns>
internal IEnumerable<Obstacle> GetAllObstacles() {
return this.allObstacles;
}
/// <summary>
/// Returns a list of all primary obstacles - secondary obstacles inside a convex hull are not needed in the VisibilityGraphGenerator.
/// </summary>
/// <returns></returns>
internal IEnumerable<Obstacle> GetAllPrimaryObstacles() {
return this.Root.GetAllLeaves();
}
// Hit-testing.
internal bool IntersectionIsInsideAnotherObstacle(Obstacle sideObstacle, Obstacle eventObstacle, Point intersect, ScanDirection scanDirection) {
insideHitTestIgnoreObstacle1 = eventObstacle;
insideHitTestIgnoreObstacle2 = sideObstacle;
insideHitTestScanDirection = scanDirection;
RectangleNode<Obstacle> obstacleNode = Root.FirstHitNode(intersect, InsideObstacleHitTest);
return (null != obstacleNode);
}
internal bool PointIsInsideAnObstacle(Point intersect, Directions direction) {
return PointIsInsideAnObstacle(intersect, ScanDirection.GetInstance(direction));
}
internal bool PointIsInsideAnObstacle(Point intersect, ScanDirection scanDirection) {
insideHitTestIgnoreObstacle1 = null;
insideHitTestIgnoreObstacle2 = null;
insideHitTestScanDirection = scanDirection;
RectangleNode<Obstacle> obstacleNode = Root.FirstHitNode(intersect, InsideObstacleHitTest);
return (null != obstacleNode);
}
// Ignore one (always) or both (depending on location) of these obstacles on Obstacle hit testing.
Obstacle insideHitTestIgnoreObstacle1;
Obstacle insideHitTestIgnoreObstacle2;
ScanDirection insideHitTestScanDirection;
HitTestBehavior InsideObstacleHitTest(Point location, Obstacle obstacle) {
if ((obstacle == insideHitTestIgnoreObstacle1) || (obstacle == insideHitTestIgnoreObstacle2)) {
// It's one of the two obstacles we already know about.
return HitTestBehavior.Continue;
}
if (obstacle.IsGroup) {
// Groups are handled differently from overlaps; we create ScanSegments (overlapped
// if within a non-group obstacle, else non-overlapped), and turn on/off access across
// the Group boundary vertices.
return HitTestBehavior.Continue;
}
if (!StaticGraphUtility.PointIsInRectangleInterior(location, obstacle.VisibilityBoundingBox)) {
// The point is on the obstacle boundary, not inside it.
return HitTestBehavior.Continue;
}
// Note: There are rounding issues using Curve.PointRelativeToCurveLocation at angled
// obstacle boundaries, hence this function.
Point high = StaticGraphUtility.RectangleBorderIntersect(obstacle.VisibilityBoundingBox, location
, insideHitTestScanDirection.Direction)
+ insideHitTestScanDirection.DirectionAsPoint;
Point low = StaticGraphUtility.RectangleBorderIntersect(obstacle.VisibilityBoundingBox, location
, insideHitTestScanDirection.OppositeDirection)
- insideHitTestScanDirection.DirectionAsPoint;
var testSeg = new LineSegment(low, high);
IList<IntersectionInfo> xxs = Curve.GetAllIntersections(testSeg, obstacle.VisibilityPolyline, true /*liftIntersections*/);
// If this is an extreme point it can have one intersection, in which case we're either on the border
// or outside; if it's a collinear flat boundary, there can be 3 intersections to this point which again
// means we're on the border (and 3 shouldn't happen anymore with the curve intersection fixes and
// PointIsInsideRectangle check above). So the interesting case is that we have 2 intersections.
if (2 == xxs.Count) {
Point firstInt = SpliceUtility.RawIntersection(xxs[0], location);
Point secondInt = SpliceUtility.RawIntersection(xxs[1], location);
// If we're on either intersection, we're on the border rather than inside.
if (!PointComparer.Equal(location, firstInt) && !PointComparer.Equal(location, secondInt)
&& (location.CompareTo(firstInt) != location.CompareTo(secondInt))) {
// We're inside. However, this may be an almost-flat side, in which case rounding
// could have reported the intersection with the start or end of the same side and
// a point somewhere on the interior of that side. Therefore if both intersections
// are on the same side (integral portion of the parameter), we consider location
// to be on the border. testSeg is always xxs[*].Segment0.
Debug.Assert(testSeg == xxs[0].Segment0, "incorrect parameter ordering to GetAllIntersections");
if (!ApproximateComparer.Close(Math.Floor(xxs[0].Par1), Math.Floor(xxs[1].Par1))) {
return HitTestBehavior.Stop;
}
}
}
return HitTestBehavior.Continue;
}
internal bool SegmentCrossesAnObstacle(Point startPoint, Point endPoint) {
stopAtGroups = true;
wantGroupCrossings = false;
LineSegment obstacleIntersectSeg = RestrictSegmentPrivate(startPoint, endPoint);
return !PointComparer.Equal(obstacleIntersectSeg.End, endPoint);
}
#if DEBUG
internal bool SegmentCrossesANonGroupObstacle(Point startPoint, Point endPoint) {
stopAtGroups = false;
wantGroupCrossings = false;
LineSegment obstacleIntersectSeg = RestrictSegmentPrivate(startPoint, endPoint);
return !PointComparer.Equal(obstacleIntersectSeg.End, endPoint);
}
#endif // DEBUG
internal LineSegment RestrictSegmentWithObstacles(Point startPoint, Point endPoint) {
stopAtGroups = false;
wantGroupCrossings = true;
return RestrictSegmentPrivate(startPoint, endPoint);
}
private LineSegment RestrictSegmentPrivate(Point startPoint, Point endPoint) {
GetRestrictedIntersectionTestSegment(startPoint, endPoint);
currentRestrictedRay = new LineSegment(startPoint, endPoint);
restrictedRayLengthSquared = (startPoint - endPoint).LengthSquared;
CurrentGroupBoundaryCrossingMap.Clear();
RecurseRestrictRayWithObstacles(Root);
return currentRestrictedRay;
}
private void GetRestrictedIntersectionTestSegment(Point startPoint, Point endPoint) {
// Due to rounding issues use a larger line span for intersection calculations.
Directions segDir = PointComparer.GetPureDirection(startPoint, endPoint);
double startX = (Directions.West == segDir) ? GraphBox.Right : ((Directions.East == segDir) ? GraphBox.Left : startPoint.X);
double endX = (Directions.West == segDir) ? GraphBox.Left : ((Directions.East == segDir) ? GraphBox.Right : endPoint.X);
double startY = (Directions.South == segDir) ? GraphBox.Top * 2: ((Directions.North == segDir) ? GraphBox.Bottom : startPoint.Y);
double endY = (Directions.South == segDir) ? GraphBox.Bottom : ((Directions.North == segDir) ? GraphBox.Top : startPoint.Y);
restrictedIntersectionTestSegment = new LineSegment(new Point(startX, startY), new Point(endX, endY));
}
// Due to rounding at the endpoints of the segment on intersection calculations, we need to preserve the original full-length segment.
LineSegment restrictedIntersectionTestSegment;
LineSegment currentRestrictedRay;
bool wantGroupCrossings;
bool stopAtGroups;
double restrictedRayLengthSquared;
private void RecurseRestrictRayWithObstacles(RectangleNode<Obstacle> rectNode) {
// A lineSeg that moves along the boundary of an obstacle is not blocked by it.
if (!StaticGraphUtility.RectangleInteriorsIntersect(currentRestrictedRay.BoundingBox, rectNode.Rectangle)) {
return;
}
Obstacle obstacle = rectNode.UserData;
if (null != obstacle) {
// Leaf node. Get the interior intersections. Use the full-length original segment for the intersection calculation.
IList<IntersectionInfo> intersections = Curve.GetAllIntersections(restrictedIntersectionTestSegment, obstacle.VisibilityPolyline, true /*liftIntersections*/);
if (!obstacle.IsGroup || stopAtGroups) {
LookForCloserNonGroupIntersectionToRestrictRay(intersections);
return;
}
if (wantGroupCrossings) {
AddGroupIntersectionsToRestrictedRay(obstacle, intersections);
}
Debug.Assert(rectNode.IsLeaf, "RectNode with UserData is not a Leaf");
return;
}
// Not a leaf; recurse into children.
RecurseRestrictRayWithObstacles(rectNode.Left);
RecurseRestrictRayWithObstacles(rectNode.Right);
}
private void LookForCloserNonGroupIntersectionToRestrictRay(IList<IntersectionInfo> intersections) {
int numberOfGoodIntersections = 0;
IntersectionInfo closestIntersectionInfo = null;
var localLeastDistSquared = this.restrictedRayLengthSquared;
var testDirection = PointComparer.GetDirections(restrictedIntersectionTestSegment.Start, restrictedIntersectionTestSegment.End);
foreach (var intersectionInfo in intersections) {
var intersect = SpliceUtility.RawIntersection(intersectionInfo, currentRestrictedRay.Start);
var dirToIntersect = PointComparer.GetDirections(currentRestrictedRay.Start, intersect);
if (dirToIntersect == CompassVector.OppositeDir(testDirection)) {
continue;
}
++numberOfGoodIntersections;
if (Directions. None == dirToIntersect) {
localLeastDistSquared = 0.0;
closestIntersectionInfo = intersectionInfo;
continue;
}
var distSquared = (intersect - currentRestrictedRay.Start).LengthSquared;
if (distSquared < localLeastDistSquared) {
// Rounding may falsely report two intersections as different when they are actually "Close",
// e.g. a horizontal vs. vertical intersection on a slanted edge.
var rawDistSquared = (intersectionInfo.IntersectionPoint - currentRestrictedRay.Start).LengthSquared;
if (rawDistSquared < ApproximateComparer.SquareOfDistanceEpsilon) {
continue;
}
localLeastDistSquared = distSquared;
closestIntersectionInfo = intersectionInfo;
}
}
if (null != closestIntersectionInfo) {
// If there was only one intersection and it is quite close to an end, ignore it.
// If there is more than one intersection, we have crossed the obstacle so we want it.
if (numberOfGoodIntersections == 1) {
var intersect = SpliceUtility.RawIntersection(closestIntersectionInfo, currentRestrictedRay.Start);
if (ApproximateComparer.CloseIntersections(intersect, this.currentRestrictedRay.Start) ||
ApproximateComparer.CloseIntersections(intersect, this.currentRestrictedRay.End)) {
return;
}
}
this.restrictedRayLengthSquared = localLeastDistSquared;
currentRestrictedRay.End = SpliceUtility.MungeClosestIntersectionInfo(currentRestrictedRay.Start, closestIntersectionInfo
, !StaticGraphUtility.IsVertical(currentRestrictedRay.Start, currentRestrictedRay.End));
}
}
private void AddGroupIntersectionsToRestrictedRay(Obstacle obstacle, IList<IntersectionInfo> intersections) {
// We'll let the lines punch through any intersections with groups, but track the location so we can enable/disable crossing.
foreach (var intersectionInfo in intersections) {
var intersect = SpliceUtility.RawIntersection(intersectionInfo, currentRestrictedRay.Start);
// Skip intersections that are past the end of the restricted segment (though there may still be some
// there if we shorten it later, but we'll skip them later).
var distSquared = (intersect - currentRestrictedRay.Start).LengthSquared;
if (distSquared > restrictedRayLengthSquared) {
continue;
}
var dirTowardIntersect = PointComparer.GetPureDirection(currentRestrictedRay.Start, currentRestrictedRay.End);
var polyline = (Polyline)intersectionInfo.Segment1; // this is the second arg to GetAllIntersections
var dirsOfSide = CompassVector.VectorDirection(polyline.Derivative(intersectionInfo.Par1));
// The derivative is always clockwise, so if the side contains the rightward rotation of the
// direction from the ray origin, then we're hitting it from the inside; otherwise from the outside.
var dirToInsideOfGroup = dirTowardIntersect;
if (0 != (dirsOfSide & CompassVector.RotateRight(dirTowardIntersect))) {
dirToInsideOfGroup = CompassVector.OppositeDir(dirToInsideOfGroup);
}
CurrentGroupBoundaryCrossingMap.AddIntersection(intersect, obstacle, dirToInsideOfGroup);
}
}
}
}
| |
// 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.Globalization;
using System.Text;
namespace System.Net.Http.Headers
{
public class ContentDispositionHeaderValue : ICloneable
{
#region Fields
private const string fileName = "filename";
private const string name = "name";
private const string fileNameStar = "filename*";
private const string creationDate = "creation-date";
private const string modificationDate = "modification-date";
private const string readDate = "read-date";
private const string size = "size";
// Use ObjectCollection<T> since we may have multiple parameters with the same name.
private ObjectCollection<NameValueHeaderValue> _parameters;
private string _dispositionType;
#endregion Fields
#region Properties
public string DispositionType
{
get { return _dispositionType; }
set
{
CheckDispositionTypeFormat(value, "value");
_dispositionType = value;
}
}
public ICollection<NameValueHeaderValue> Parameters
{
get
{
if (_parameters == null)
{
_parameters = new ObjectCollection<NameValueHeaderValue>();
}
return _parameters;
}
}
public string Name
{
get { return GetName(name); }
set { SetName(name, value); }
}
public string FileName
{
get { return GetName(fileName); }
set { SetName(fileName, value); }
}
public string FileNameStar
{
get { return GetName(fileNameStar); }
set { SetName(fileNameStar, value); }
}
public DateTimeOffset? CreationDate
{
get { return GetDate(creationDate); }
set { SetDate(creationDate, value); }
}
public DateTimeOffset? ModificationDate
{
get { return GetDate(modificationDate); }
set { SetDate(modificationDate, value); }
}
public DateTimeOffset? ReadDate
{
get { return GetDate(readDate); }
set { SetDate(readDate, value); }
}
public long? Size
{
get
{
NameValueHeaderValue sizeParameter = NameValueHeaderValue.Find(_parameters, size);
ulong value;
if (sizeParameter != null)
{
string sizeString = sizeParameter.Value;
if (UInt64.TryParse(sizeString, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
{
return (long)value;
}
}
return null;
}
set
{
NameValueHeaderValue sizeParameter = NameValueHeaderValue.Find(_parameters, size);
if (value == null)
{
// Remove parameter.
if (sizeParameter != null)
{
_parameters.Remove(sizeParameter);
}
}
else if (value < 0)
{
throw new ArgumentOutOfRangeException("value");
}
else if (sizeParameter != null)
{
sizeParameter.Value = value.Value.ToString(CultureInfo.InvariantCulture);
}
else
{
string sizeString = value.Value.ToString(CultureInfo.InvariantCulture);
_parameters.Add(new NameValueHeaderValue(size, sizeString));
}
}
}
#endregion Properties
#region Constructors
internal ContentDispositionHeaderValue()
{
// Used by the parser to create a new instance of this type.
}
protected ContentDispositionHeaderValue(ContentDispositionHeaderValue source)
{
Contract.Requires(source != null);
_dispositionType = source._dispositionType;
if (source._parameters != null)
{
foreach (var parameter in source._parameters)
{
this.Parameters.Add((NameValueHeaderValue)((ICloneable)parameter).Clone());
}
}
}
public ContentDispositionHeaderValue(string dispositionType)
{
CheckDispositionTypeFormat(dispositionType, "dispositionType");
_dispositionType = dispositionType;
}
#endregion Constructors
#region Overloads
public override string ToString()
{
return _dispositionType + NameValueHeaderValue.ToString(_parameters, ';', true);
}
public override bool Equals(object obj)
{
ContentDispositionHeaderValue other = obj as ContentDispositionHeaderValue;
if (other == null)
{
return false;
}
return string.Equals(_dispositionType, other._dispositionType, StringComparison.OrdinalIgnoreCase) &&
HeaderUtilities.AreEqualCollections(_parameters, other._parameters);
}
public override int GetHashCode()
{
// The dispositionType string is case-insensitive.
return StringComparer.OrdinalIgnoreCase.GetHashCode(_dispositionType) ^ NameValueHeaderValue.GetHashCode(_parameters);
}
// Implement ICloneable explicitly to allow derived types to "override" the implementation.
object ICloneable.Clone()
{
return new ContentDispositionHeaderValue(this);
}
#endregion Overloads
#region Parsing
public static ContentDispositionHeaderValue Parse(string input)
{
int index = 0;
return (ContentDispositionHeaderValue)GenericHeaderParser.ContentDispositionParser.ParseValue(input,
null, ref index);
}
public static bool TryParse(string input, out ContentDispositionHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.ContentDispositionParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (ContentDispositionHeaderValue)output;
return true;
}
return false;
}
internal static int GetDispositionTypeLength(string input, int startIndex, out object parsedValue)
{
Contract.Requires(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Caller must remove leading whitespaces. If not, we'll return 0.
string dispositionType = null;
int dispositionTypeLength = GetDispositionTypeExpressionLength(input, startIndex, out dispositionType);
if (dispositionTypeLength == 0)
{
return 0;
}
int current = startIndex + dispositionTypeLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
ContentDispositionHeaderValue contentDispositionHeader = new ContentDispositionHeaderValue();
contentDispositionHeader._dispositionType = dispositionType;
// If we're not done and we have a parameter delimiter, then we have a list of parameters.
if ((current < input.Length) && (input[current] == ';'))
{
current++; // Skip delimiter.
int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';',
(ObjectCollection<NameValueHeaderValue>)contentDispositionHeader.Parameters);
if (parameterLength == 0)
{
return 0;
}
parsedValue = contentDispositionHeader;
return current + parameterLength - startIndex;
}
// We have a ContentDisposition header without parameters.
parsedValue = contentDispositionHeader;
return current - startIndex;
}
private static int GetDispositionTypeExpressionLength(string input, int startIndex, out string dispositionType)
{
Contract.Requires((input != null) && (input.Length > 0) && (startIndex < input.Length));
// This method just parses the disposition type string, it does not parse parameters.
dispositionType = null;
// Parse the disposition type, i.e. <dispositiontype> in content-disposition string
// "<dispositiontype>; param1=value1; param2=value2".
int typeLength = HttpRuleParser.GetTokenLength(input, startIndex);
if (typeLength == 0)
{
return 0;
}
dispositionType = input.Substring(startIndex, typeLength);
return typeLength;
}
private static void CheckDispositionTypeFormat(string dispositionType, string parameterName)
{
if (string.IsNullOrEmpty(dispositionType))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
// When adding values using strongly typed objects, no leading/trailing LWS (whitespaces) are allowed.
string tempDispositionType;
int dispositionTypeLength = GetDispositionTypeExpressionLength(dispositionType, 0, out tempDispositionType);
if ((dispositionTypeLength == 0) || (tempDispositionType.Length != dispositionType.Length))
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_headers_invalid_value, dispositionType));
}
}
#endregion Parsing
#region Helpers
// Gets a parameter of the given name and attempts to extract a date.
// Returns null if the parameter is not present or the format is incorrect.
private DateTimeOffset? GetDate(string parameter)
{
NameValueHeaderValue dateParameter = NameValueHeaderValue.Find(_parameters, parameter);
DateTimeOffset date;
if (dateParameter != null)
{
string dateString = dateParameter.Value;
// Should have quotes, remove them.
if (IsQuoted(dateString))
{
dateString = dateString.Substring(1, dateString.Length - 2);
}
if (HttpRuleParser.TryStringToDate(dateString, out date))
{
return date;
}
}
return null;
}
// Add the given parameter to the list. Remove if date is null.
private void SetDate(string parameter, DateTimeOffset? date)
{
NameValueHeaderValue dateParameter = NameValueHeaderValue.Find(_parameters, parameter);
if (date == null)
{
// Remove parameter.
if (dateParameter != null)
{
_parameters.Remove(dateParameter);
}
}
else
{
// Must always be quoted.
string dateString = string.Format(CultureInfo.InvariantCulture, "\"{0}\"",
HttpRuleParser.DateToString(date.Value));
if (dateParameter != null)
{
dateParameter.Value = dateString;
}
else
{
Parameters.Add(new NameValueHeaderValue(parameter, dateString));
}
}
}
// Gets a parameter of the given name and attempts to decode it if nessisary.
// Returns null if the parameter is not present or the raw value if the encoding is incorrect.
private string GetName(string parameter)
{
NameValueHeaderValue nameParameter = NameValueHeaderValue.Find(_parameters, parameter);
if (nameParameter != null)
{
string result;
// filename*=utf-8'lang'%7FMyString
if (parameter.EndsWith("*", StringComparison.Ordinal))
{
if (TryDecode5987(nameParameter.Value, out result))
{
return result;
}
return null; // Unrecognized encoding.
}
// filename="=?utf-8?B?BDFSDFasdfasdc==?="
if (TryDecodeMime(nameParameter.Value, out result))
{
return result;
}
// May not have been encoded.
return nameParameter.Value;
}
return null;
}
// Add/update the given parameter in the list, encoding if necessary.
// Remove if value is null/Empty
private void SetName(string parameter, string value)
{
NameValueHeaderValue nameParameter = NameValueHeaderValue.Find(_parameters, parameter);
if (string.IsNullOrEmpty(value))
{
// Remove parameter.
if (nameParameter != null)
{
_parameters.Remove(nameParameter);
}
}
else
{
string processedValue = string.Empty;
if (parameter.EndsWith("*", StringComparison.Ordinal))
{
processedValue = Encode5987(value);
}
else
{
processedValue = EncodeAndQuoteMime(value);
}
if (nameParameter != null)
{
nameParameter.Value = processedValue;
}
else
{
Parameters.Add(new NameValueHeaderValue(parameter, processedValue));
}
}
}
// Returns input for decoding failures, as the content might not be encoded.
private string EncodeAndQuoteMime(string input)
{
string result = input;
bool needsQuotes = false;
// Remove bounding quotes, they'll get re-added later.
if (IsQuoted(result))
{
result = result.Substring(1, result.Length - 2);
needsQuotes = true;
}
if (result.IndexOf("\"", 0, StringComparison.Ordinal) >= 0) // Only bounding quotes are allowed.
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
SR.net_http_headers_invalid_value, input));
}
else if (RequiresEncoding(result))
{
needsQuotes = true; // Encoded data must always be quoted, the equals signs are invalid in tokens.
result = EncodeMime(result); // =?utf-8?B?asdfasdfaesdf?=
}
else if (!needsQuotes && HttpRuleParser.GetTokenLength(result, 0) != result.Length)
{
needsQuotes = true;
}
if (needsQuotes)
{
// Re-add quotes "value".
result = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", result);
}
return result;
}
// Returns true if the value starts and ends with a quote.
private bool IsQuoted(string value)
{
Debug.Assert(value != null);
return value.Length > 1 && value.StartsWith("\"", StringComparison.Ordinal)
&& value.EndsWith("\"", StringComparison.Ordinal);
}
// tspecials are required to be in a quoted string. Only non-ascii needs to be encoded.
private bool RequiresEncoding(string input)
{
Debug.Assert(input != null);
foreach (char c in input)
{
if ((int)c > 0x7f)
{
return true;
}
}
return false;
}
// Encode using MIME encoding.
private string EncodeMime(string input)
{
byte[] buffer = Encoding.UTF8.GetBytes(input);
string encodedName = Convert.ToBase64String(buffer);
return string.Format(CultureInfo.InvariantCulture, "=?utf-8?B?{0}?=", encodedName);
}
// Attempt to decode MIME encoded strings.
private bool TryDecodeMime(string input, out string output)
{
Debug.Assert(input != null);
output = null;
string processedInput = input;
// Require quotes, min of "=?e?b??="
if (!IsQuoted(processedInput) || processedInput.Length < 10)
{
return false;
}
string[] parts = processedInput.Split('?');
// "=, encodingName, encodingType, encodedData, ="
if (parts.Length != 5 || parts[0] != "\"=" || parts[4] != "=\"" || parts[2].ToLowerInvariant() != "b")
{
// Not encoded.
// This does not support multi-line encoding.
// Only base64 encoding is supported, not quoted printable.
return false;
}
try
{
Encoding encoding = Encoding.GetEncoding(parts[1]);
byte[] bytes = Convert.FromBase64String(parts[3]);
output = encoding.GetString(bytes, 0, bytes.Length);
return true;
}
catch (ArgumentException)
{
// Unknown encoding or bad characters.
}
catch (FormatException)
{
// Bad base64 decoding.
}
return false;
}
// Encode a string using RFC 5987 encoding.
// encoding'lang'PercentEncodedSpecials
private string Encode5987(string input)
{
StringBuilder builder = new StringBuilder("utf-8\'\'");
foreach (char c in input)
{
// attr-char = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
// ; token except ( "*" / "'" / "%" )
if (c > 0x7F) // Encodes as multiple utf-8 bytes
{
byte[] bytes = Encoding.UTF8.GetBytes(c.ToString());
foreach (byte b in bytes)
{
builder.Append(UriShim.HexEscape((char)b));
}
}
else if (!HttpRuleParser.IsTokenChar(c) || c == '*' || c == '\'' || c == '%')
{
// ASCII - Only one encoded byte.
builder.Append(UriShim.HexEscape(c));
}
else
{
builder.Append(c);
}
}
return builder.ToString();
}
// Attempt to decode using RFC 5987 encoding.
// encoding'language'my%20string
private bool TryDecode5987(string input, out string output)
{
output = null;
string[] parts = input.Split('\'');
if (parts.Length != 3)
{
return false;
}
StringBuilder decoded = new StringBuilder();
try
{
Encoding encoding = Encoding.GetEncoding(parts[0]);
string dataString = parts[2];
byte[] unescapedBytes = new byte[dataString.Length];
int unescapedBytesCount = 0;
for (int index = 0; index < dataString.Length; index++)
{
if (UriShim.IsHexEncoding(dataString, index)) // %FF
{
// Unescape and cache bytes, multi-byte characters must be decoded all at once.
unescapedBytes[unescapedBytesCount++] = (byte)UriShim.HexUnescape(dataString, ref index);
index--; // HexUnescape did +=3; Offset the for loop's ++
}
else
{
if (unescapedBytesCount > 0)
{
// Decode any previously cached bytes.
decoded.Append(encoding.GetString(unescapedBytes, 0, unescapedBytesCount));
unescapedBytesCount = 0;
}
decoded.Append(dataString[index]); // Normal safe character.
}
}
if (unescapedBytesCount > 0)
{
// Decode any previously cached bytes.
decoded.Append(encoding.GetString(unescapedBytes, 0, unescapedBytesCount));
}
}
catch (ArgumentException)
{
return false; // Unknown encoding or bad characters.
}
output = decoded.ToString();
return true;
}
#endregion Helpers
}
}
| |
/*
* 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 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 log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Xml;
using Caps = OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "VivoxVoiceModule")]
public class VivoxVoiceModule : ISharedRegionModule
{
// channel distance model values
public const int CHAN_DIST_NONE = 0; // no attenuation
public const int CHAN_DIST_INVERSE = 1; // inverse distance attenuation
public const int CHAN_DIST_LINEAR = 2; // linear attenuation
public const int CHAN_DIST_EXPONENT = 3; // exponential attenuation
public const int CHAN_DIST_DEFAULT = CHAN_DIST_LINEAR;
// channel type values
public static readonly string CHAN_TYPE_POSITIONAL = "positional";
public static readonly string CHAN_TYPE_CHANNEL = "channel";
public static readonly string CHAN_TYPE_DEFAULT = CHAN_TYPE_POSITIONAL;
// channel mode values
public static readonly string CHAN_MODE_OPEN = "open";
public static readonly string CHAN_MODE_LECTURE = "lecture";
public static readonly string CHAN_MODE_PRESENTATION = "presentation";
public static readonly string CHAN_MODE_AUDITORIUM = "auditorium";
public static readonly string CHAN_MODE_DEFAULT = CHAN_MODE_OPEN;
// unconstrained default values
public const double CHAN_ROLL_OFF_DEFAULT = 2.0; // rate of attenuation
public const double CHAN_ROLL_OFF_MIN = 1.0;
public const double CHAN_ROLL_OFF_MAX = 4.0;
public const int CHAN_MAX_RANGE_DEFAULT = 80; // distance at which channel is silent
public const int CHAN_MAX_RANGE_MIN = 0;
public const int CHAN_MAX_RANGE_MAX = 160;
public const int CHAN_CLAMPING_DISTANCE_DEFAULT = 10; // distance before attenuation applies
public const int CHAN_CLAMPING_DISTANCE_MIN = 0;
public const int CHAN_CLAMPING_DISTANCE_MAX = 160;
// Infrastructure
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly Object vlock = new Object();
// Capability strings
private static readonly string m_parcelVoiceInfoRequestPath = "0107/";
private static readonly string m_provisionVoiceAccountRequestPath = "0108/";
//private static readonly string m_chatSessionRequestPath = "0109/";
// Control info, e.g. vivox server, admin user, admin password
private static bool m_pluginEnabled = false;
private static bool m_adminConnected = false;
private static string m_vivoxServer;
private static string m_vivoxSipUri;
private static string m_vivoxVoiceAccountApi;
private static string m_vivoxAdminUser;
private static string m_vivoxAdminPassword;
private static string m_authToken = String.Empty;
private static int m_vivoxChannelDistanceModel;
private static double m_vivoxChannelRollOff;
private static int m_vivoxChannelMaximumRange;
private static string m_vivoxChannelMode;
private static string m_vivoxChannelType;
private static int m_vivoxChannelClampingDistance;
private static ThreadedClasses.RwLockedDictionary<string, string> m_parents = new ThreadedClasses.RwLockedDictionary<string, string>();
private static bool m_dumpXml;
private IConfig m_config;
private object m_Lock;
public void Initialise(IConfigSource config)
{
m_config = config.Configs["VivoxVoice"];
if (null == m_config)
return;
if (!m_config.GetBoolean("enabled", false))
return;
m_Lock = new object();
try
{
// retrieve configuration variables
m_vivoxServer = m_config.GetString("vivox_server", String.Empty);
m_vivoxSipUri = m_config.GetString("vivox_sip_uri", String.Empty);
m_vivoxAdminUser = m_config.GetString("vivox_admin_user", String.Empty);
m_vivoxAdminPassword = m_config.GetString("vivox_admin_password", String.Empty);
m_vivoxChannelDistanceModel = m_config.GetInt("vivox_channel_distance_model", CHAN_DIST_DEFAULT);
m_vivoxChannelRollOff = m_config.GetDouble("vivox_channel_roll_off", CHAN_ROLL_OFF_DEFAULT);
m_vivoxChannelMaximumRange = m_config.GetInt("vivox_channel_max_range", CHAN_MAX_RANGE_DEFAULT);
m_vivoxChannelMode = m_config.GetString("vivox_channel_mode", CHAN_MODE_DEFAULT).ToLower();
m_vivoxChannelType = m_config.GetString("vivox_channel_type", CHAN_TYPE_DEFAULT).ToLower();
m_vivoxChannelClampingDistance = m_config.GetInt("vivox_channel_clamping_distance",
CHAN_CLAMPING_DISTANCE_DEFAULT);
m_dumpXml = m_config.GetBoolean("dump_xml", false);
// Validate against constraints and default if necessary
if (m_vivoxChannelRollOff < CHAN_ROLL_OFF_MIN || m_vivoxChannelRollOff > CHAN_ROLL_OFF_MAX)
{
m_log.WarnFormat("[VivoxVoice] Invalid value for roll off ({0}), reset to {1}.",
m_vivoxChannelRollOff, CHAN_ROLL_OFF_DEFAULT);
m_vivoxChannelRollOff = CHAN_ROLL_OFF_DEFAULT;
}
if (m_vivoxChannelMaximumRange < CHAN_MAX_RANGE_MIN || m_vivoxChannelMaximumRange > CHAN_MAX_RANGE_MAX)
{
m_log.WarnFormat("[VivoxVoice] Invalid value for maximum range ({0}), reset to {1}.",
m_vivoxChannelMaximumRange, CHAN_MAX_RANGE_DEFAULT);
m_vivoxChannelMaximumRange = CHAN_MAX_RANGE_DEFAULT;
}
if (m_vivoxChannelClampingDistance < CHAN_CLAMPING_DISTANCE_MIN ||
m_vivoxChannelClampingDistance > CHAN_CLAMPING_DISTANCE_MAX)
{
m_log.WarnFormat("[VivoxVoice] Invalid value for clamping distance ({0}), reset to {1}.",
m_vivoxChannelClampingDistance, CHAN_CLAMPING_DISTANCE_DEFAULT);
m_vivoxChannelClampingDistance = CHAN_CLAMPING_DISTANCE_DEFAULT;
}
switch (m_vivoxChannelMode)
{
case "open" : break;
case "lecture" : break;
case "presentation" : break;
case "auditorium" : break;
default :
m_log.WarnFormat("[VivoxVoice] Invalid value for channel mode ({0}), reset to {1}.",
m_vivoxChannelMode, CHAN_MODE_DEFAULT);
m_vivoxChannelMode = CHAN_MODE_DEFAULT;
break;
}
switch (m_vivoxChannelType)
{
case "positional" : break;
case "channel" : break;
default :
m_log.WarnFormat("[VivoxVoice] Invalid value for channel type ({0}), reset to {1}.",
m_vivoxChannelType, CHAN_TYPE_DEFAULT);
m_vivoxChannelType = CHAN_TYPE_DEFAULT;
break;
}
m_vivoxVoiceAccountApi = String.Format("http://{0}/api2", m_vivoxServer);
// Admin interface required values
if (String.IsNullOrEmpty(m_vivoxServer) ||
String.IsNullOrEmpty(m_vivoxSipUri) ||
String.IsNullOrEmpty(m_vivoxAdminUser) ||
String.IsNullOrEmpty(m_vivoxAdminPassword))
{
m_log.Error("[VivoxVoice] plugin mis-configured");
m_log.Info("[VivoxVoice] plugin disabled: incomplete configuration");
return;
}
m_log.InfoFormat("[VivoxVoice] using vivox server {0}", m_vivoxServer);
// Get admin rights and cleanup any residual channel definition
DoAdminLogin();
m_pluginEnabled = true;
m_log.Info("[VivoxVoice] plugin enabled");
}
catch (Exception e)
{
m_log.ErrorFormat("[VivoxVoice] plugin initialization failed: {0}", e.Message);
m_log.DebugFormat("[VivoxVoice] plugin initialization failed: {0}", e.ToString());
return;
}
}
private string lastEpAddress = string.Empty;
public void SimulatorIPChanged(IPAddress ep)
{
if(!m_pluginEnabled)
{
return;
}
if(ep.ToString() != lastEpAddress)
{
lastEpAddress = ep.ToString();
m_adminConnected = false;
DoAdminLogin();
}
}
public void AddRegion(Scene scene)
{
if (m_pluginEnabled)
{
lock (vlock)
{
string channelId;
string sceneUUID = scene.RegionInfo.RegionID.ToString();
string sceneName = scene.RegionInfo.RegionName;
// Make sure that all local channels are deleted.
// So we have to search for the children, and then do an
// iteration over the set of chidren identified.
// This assumes that there is just one directory per
// region.
if (VivoxTryGetDirectory(sceneUUID + "D", out channelId))
{
m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}",
sceneName, sceneUUID, channelId);
XmlElement children = VivoxListChildren(channelId);
string count;
if (XmlFind(children, "response.level0.channel-search.count", out count))
{
int cnum = Convert.ToInt32(count);
for (int i = 0; i < cnum; i++)
{
string id;
if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
{
if (!IsOK(VivoxDeleteChannel(channelId, id)))
m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id);
}
}
}
}
else
{
if (!VivoxTryCreateDirectory(sceneUUID + "D", sceneName, out channelId))
{
m_log.WarnFormat("[VivoxVoice] Create failed <{0}:{1}:{2}>",
"*", sceneUUID, sceneName);
channelId = String.Empty;
}
}
// Create a dictionary entry unconditionally. This eliminates the
// need to check for a parent in the core code. The end result is
// the same, if the parent table entry is an empty string, then
// region channels will be created as first-level channels.
m_parents[sceneUUID] = channelId;
}
// we need to capture scene in an anonymous method
// here as we need it later in the callbacks
scene.EventManager.OnRegisterCaps += delegate(UUID agentID, Caps caps)
{
OnRegisterCaps(scene, agentID, caps);
};
scene.EventManager.OnSimulatorIPChanged += SimulatorIPChanged;
}
}
public void RegionLoaded(Scene scene)
{
// Do nothing.
}
public void RemoveRegion(Scene scene)
{
if (m_pluginEnabled)
{
lock (vlock)
{
string channelId;
string sceneUUID = scene.RegionInfo.RegionID.ToString();
string sceneName = scene.RegionInfo.RegionName;
// Make sure that all local channels are deleted.
// So we have to search for the children, and then do an
// iteration over the set of chidren identified.
// This assumes that there is just one directory per
// region.
if (VivoxTryGetDirectory(sceneUUID + "D", out channelId))
{
m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}",
sceneName, sceneUUID, channelId);
XmlElement children = VivoxListChildren(channelId);
string count;
if (XmlFind(children, "response.level0.channel-search.count", out count))
{
int cnum = Convert.ToInt32(count);
for (int i = 0; i < cnum; i++)
{
string id;
if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
{
if (!IsOK(VivoxDeleteChannel(channelId, id)))
m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id);
}
}
}
}
if (!IsOK(VivoxDeleteChannel(null, channelId)))
m_log.WarnFormat("[VivoxVoice] Parent channel delete failed {0}:{1}:{2}", sceneName, sceneUUID, channelId);
// Remove the channel umbrella entry
m_parents.Remove(sceneUUID);
}
}
}
public void PostInitialise()
{
// Do nothing.
}
public void Close()
{
if (m_pluginEnabled)
VivoxLogout();
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "VivoxVoiceModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
// <summary>
// OnRegisterCaps is invoked via the scene.EventManager
// everytime OpenSim hands out capabilities to a client
// (login, region crossing). We contribute two capabilities to
// the set of capabilities handed back to the client:
// ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest.
//
// ProvisionVoiceAccountRequest allows the client to obtain
// the voice account credentials for the avatar it is
// controlling (e.g., user name, password, etc).
//
// ParcelVoiceInfoRequest is invoked whenever the client
// changes from one region or parcel to another.
//
// Note that OnRegisterCaps is called here via a closure
// delegate containing the scene of the respective region (see
// Initialise()).
// </summary>
public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps)
{
m_log.DebugFormat("[VivoxVoice] OnRegisterCaps: agentID {0} caps {1}", agentID, caps);
string capsBase = "/CAPS/" + caps.CapsObjectPath;
caps.RegisterHandler(
"ProvisionVoiceAccountRequest",
new RestStreamHandler(
"POST",
capsBase + m_provisionVoiceAccountRequestPath,
(request, path, param, httpRequest, httpResponse)
=> ProvisionVoiceAccountRequest(scene, request, path, param, agentID, caps),
"ProvisionVoiceAccountRequest",
agentID.ToString()));
caps.RegisterHandler(
"ParcelVoiceInfoRequest",
new RestStreamHandler(
"POST",
capsBase + m_parcelVoiceInfoRequestPath,
(request, path, param, httpRequest, httpResponse)
=> ParcelVoiceInfoRequest(scene, request, path, param, agentID, caps),
"ParcelVoiceInfoRequest",
agentID.ToString()));
//caps.RegisterHandler(
// "ChatSessionRequest",
// new RestStreamHandler(
// "POST",
// capsBase + m_chatSessionRequestPath,
// (request, path, param, httpRequest, httpResponse)
// => ChatSessionRequest(scene, request, path, param, agentID, caps),
// "ChatSessionRequest",
// agentID.ToString()));
}
/// <summary>
/// Callback for a client request for Voice Account Details
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ProvisionVoiceAccountRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
try
{
ScenePresence avatar = null;
string avatarName = null;
if (scene == null)
throw new Exception("[VivoxVoice][PROVISIONVOICE]: Invalid scene");
avatar = scene.GetScenePresence(agentID);
while (avatar == null)
{
Thread.Sleep(100);
avatar = scene.GetScenePresence(agentID);
}
avatarName = avatar.Name;
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: scene = {0}, agentID = {1}", scene, agentID);
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}",
request, path, param);
XmlElement resp;
bool retry = false;
string agentname = "x" + Convert.ToBase64String(agentID.GetBytes());
string password = new UUID(Guid.NewGuid()).ToString().Replace('-','Z').Substring(0,16);
string code = String.Empty;
agentname = agentname.Replace('+', '-').Replace('/', '_');
do
{
resp = VivoxGetAccountInfo(agentname);
if (XmlFind(resp, "response.level0.status", out code))
{
if (code != "OK")
{
if (XmlFind(resp, "response.level0.body.code", out code))
{
// If the request was recognized, then this should be set to something
switch (code)
{
case "201" : // Account expired
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : expired credentials",
avatarName);
m_adminConnected = false;
retry = DoAdminLogin();
break;
case "202" : // Missing credentials
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : missing credentials",
avatarName);
break;
case "212" : // Not authorized
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : not authorized",
avatarName);
break;
case "300" : // Required parameter missing
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : parameter missing",
avatarName);
break;
case "403" : // Account does not exist
resp = VivoxCreateAccount(agentname,password);
// Note: This REALLY MUST BE status. Create Account does not return code.
if (XmlFind(resp, "response.level0.status", out code))
{
switch (code)
{
case "201" : // Account expired
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : expired credentials",
avatarName);
m_adminConnected = false;
retry = DoAdminLogin();
break;
case "202" : // Missing credentials
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : missing credentials",
avatarName);
break;
case "212" : // Not authorized
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : not authorized",
avatarName);
break;
case "300" : // Required parameter missing
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : parameter missing",
avatarName);
break;
case "400" : // Create failed
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : create failed",
avatarName);
break;
}
}
break;
case "404" : // Failed to retrieve account
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : retrieve failed");
// [AMW] Sleep and retry for a fixed period? Or just abandon?
break;
}
}
}
}
}
while (retry);
if (code != "OK")
{
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: Get Account Request failed for \"{0}\"", avatarName);
throw new Exception("Unable to execute request");
}
// Unconditionally change the password on each request
VivoxPassword(agentname, password);
LLSDVoiceAccountResponse voiceAccountResponse =
new LLSDVoiceAccountResponse(agentname, password, m_vivoxSipUri, m_vivoxVoiceAccountApi);
string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse);
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: avatar \"{0}\": {1}", avatarName, r);
return r;
}
catch (Exception e)
{
m_log.ErrorFormat("[VivoxVoice][PROVISIONVOICE]: : {0}, retry later", e.Message);
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: : {0} failed", e.ToString());
return "<llsd><undef /></llsd>";
}
}
/// <summary>
/// Callback for a client request for ParcelVoiceInfo
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ParcelVoiceInfoRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
ScenePresence avatar = scene.GetScenePresence(agentID);
string avatarName = avatar.Name;
// - check whether we have a region channel in our cache
// - if not:
// create it and cache it
// - send it to the client
// - send channel_uri: as "sip:regionID@m_sipDomain"
try
{
LLSDParcelVoiceInfoResponse parcelVoiceInfo;
string channel_uri;
if (null == scene.LandChannel)
throw new Exception(String.Format("region \"{0}\": avatar \"{1}\": land data not yet available",
scene.RegionInfo.RegionName, avatarName));
// get channel_uri: check first whether estate
// settings allow voice, then whether parcel allows
// voice, if all do retrieve or obtain the parcel
// voice channel
LandData land = scene.GetLandData(avatar.AbsolutePosition);
m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}",
scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param);
// m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: avatar \"{0}\": location: {1} {2} {3}",
// avatarName, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z);
// TODO: EstateSettings don't seem to get propagated...
if (!scene.RegionInfo.EstateSettings.AllowVoice)
{
m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings",
scene.RegionInfo.RegionName);
channel_uri = String.Empty;
}
if ((land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0)
{
//uncommented log, quickfix to stop excesive spamming of logs....
/*m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel",
scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName);
*/
channel_uri = String.Empty;
}
else
{
channel_uri = RegionGetOrCreateChannel(scene, land);
}
// fill in our response to the client
Hashtable creds = new Hashtable();
creds["channel_uri"] = channel_uri;
parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(scene.RegionInfo.RegionName, land.LocalID, creds);
string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo);
m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": {4}",
scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, r);
return r;
}
catch (Exception e)
{
m_log.ErrorFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later",
scene.RegionInfo.RegionName, avatarName, e.Message);
m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2} failed",
scene.RegionInfo.RegionName, avatarName, e.ToString());
return "<llsd><undef /></llsd>";
}
}
/// <summary>
/// Callback for a client request for a private chat channel
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ChatSessionRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
ScenePresence avatar = scene.GetScenePresence(agentID);
string avatarName = avatar.Name;
m_log.DebugFormat("[VivoxVoice][CHATSESSION]: avatar \"{0}\": request: {1}, path: {2}, param: {3}",
avatarName, request, path, param);
return "<llsd>true</llsd>";
}
private string RegionGetOrCreateChannel(Scene scene, LandData land)
{
string channelUri = null;
string channelId = null;
string landUUID;
string landName;
string parentId;
parentId = m_parents[scene.RegionInfo.RegionID.ToString()];
// Create parcel voice channel. If no parcel exists, then the voice channel ID is the same
// as the directory ID. Otherwise, it reflects the parcel's ID.
if (land.LocalID != 1 && (land.Flags & (uint)ParcelFlags.UseEstateVoiceChan) == 0)
{
landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, land.Name);
landUUID = land.GlobalID.ToString();
m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
landName, land.LocalID, landUUID);
}
else
{
landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionName);
landUUID = scene.RegionInfo.RegionID.ToString();
m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
landName, land.LocalID, landUUID);
}
lock (vlock)
{
// Added by Adam to help debug channel not availible errors.
if (VivoxTryGetChannel(parentId, landUUID, out channelId, out channelUri))
m_log.DebugFormat("[VivoxVoice] Found existing channel at " + channelUri);
else if (VivoxTryCreateChannel(parentId, landUUID, landName, out channelUri))
m_log.DebugFormat("[VivoxVoice] Created new channel at " + channelUri);
else
throw new Exception("vivox channel uri not available");
m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parent channel id {1}: retrieved parcel channel_uri {2} ",
landName, parentId, channelUri);
}
return channelUri;
}
private static readonly string m_vivoxLoginPath = "http://{0}/api2/viv_signin.php?userid={1}&pwd={2}";
/// <summary>
/// Perform administrative login for Vivox.
/// Returns a hash table containing values returned from the request.
/// </summary>
private XmlElement VivoxLogin(string name, string password)
{
string requrl = String.Format(m_vivoxLoginPath, m_vivoxServer, name, password);
return VivoxCall(requrl, false);
}
private static readonly string m_vivoxLogoutPath = "http://{0}/api2/viv_signout.php?auth_token={1}";
/// <summary>
/// Perform administrative logout for Vivox.
/// </summary>
private XmlElement VivoxLogout()
{
string requrl = String.Format(m_vivoxLogoutPath, m_vivoxServer, m_authToken);
return VivoxCall(requrl, false);
}
private static readonly string m_vivoxGetAccountPath = "http://{0}/api2/viv_get_acct.php?auth_token={1}&user_name={2}";
/// <summary>
/// Retrieve account information for the specified user.
/// Returns a hash table containing values returned from the request.
/// </summary>
private XmlElement VivoxGetAccountInfo(string user)
{
string requrl = String.Format(m_vivoxGetAccountPath, m_vivoxServer, m_authToken, user);
return VivoxCall(requrl, true);
}
private static readonly string m_vivoxNewAccountPath = "http://{0}/api2/viv_adm_acct_new.php?username={1}&pwd={2}&auth_token={3}";
/// <summary>
/// Creates a new account.
/// For now we supply the minimum set of values, which
/// is user name and password. We *can* supply a lot more
/// demographic data.
/// </summary>
private XmlElement VivoxCreateAccount(string user, string password)
{
string requrl = String.Format(m_vivoxNewAccountPath, m_vivoxServer, user, password, m_authToken);
return VivoxCall(requrl, true);
}
private static readonly string m_vivoxPasswordPath = "http://{0}/api2/viv_adm_password.php?user_name={1}&new_pwd={2}&auth_token={3}";
/// <summary>
/// Change the user's password.
/// </summary>
private XmlElement VivoxPassword(string user, string password)
{
string requrl = String.Format(m_vivoxPasswordPath, m_vivoxServer, user, password, m_authToken);
return VivoxCall(requrl, true);
}
private static readonly string m_vivoxChannelPath = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_name={2}&auth_token={3}";
/// <summary>
/// Create a channel.
/// Once again, there a multitude of options possible. In the simplest case
/// we specify only the name and get a non-persistent cannel in return. Non
/// persistent means that the channel gets deleted if no-one uses it for
/// 5 hours. To accomodate future requirements, it may be a good idea to
/// initially create channels under the umbrella of a parent ID based upon
/// the region name. That way we have a context for side channels, if those
/// are required in a later phase.
///
/// In this case the call handles parent and description as optional values.
/// </summary>
private bool VivoxTryCreateChannel(string parent, string channelId, string description, out string channelUri)
{
string requrl = String.Format(m_vivoxChannelPath, m_vivoxServer, "create", channelId, m_authToken);
if (!string.IsNullOrEmpty(parent))
{
requrl = String.Format("{0}&chan_parent={1}", requrl, parent);
}
if (!string.IsNullOrEmpty(description))
{
requrl = String.Format("{0}&chan_desc={1}", requrl, description);
}
requrl = String.Format("{0}&chan_type={1}", requrl, m_vivoxChannelType);
requrl = String.Format("{0}&chan_mode={1}", requrl, m_vivoxChannelMode);
requrl = String.Format("{0}&chan_roll_off={1}", requrl, m_vivoxChannelRollOff);
requrl = String.Format("{0}&chan_dist_model={1}", requrl, m_vivoxChannelDistanceModel);
requrl = String.Format("{0}&chan_max_range={1}", requrl, m_vivoxChannelMaximumRange);
requrl = String.Format("{0}&chan_clamping_distance={1}", requrl, m_vivoxChannelClampingDistance);
XmlElement resp = VivoxCall(requrl, true);
if (XmlFind(resp, "response.level0.body.chan_uri", out channelUri))
return true;
channelUri = String.Empty;
return false;
}
/// <summary>
/// Create a directory.
/// Create a channel with an unconditional type of "dir" (indicating directory).
/// This is used to create an arbitrary name tree for partitioning of the
/// channel name space.
/// The parent and description are optional values.
/// </summary>
private bool VivoxTryCreateDirectory(string dirId, string description, out string channelId)
{
string requrl = String.Format(m_vivoxChannelPath, m_vivoxServer, "create", dirId, m_authToken);
// if (parent != null && parent != String.Empty)
// {
// requrl = String.Format("{0}&chan_parent={1}", requrl, parent);
// }
if (!string.IsNullOrEmpty(description))
{
requrl = String.Format("{0}&chan_desc={1}", requrl, description);
}
requrl = String.Format("{0}&chan_type={1}", requrl, "dir");
XmlElement resp = VivoxCall(requrl, true);
if (IsOK(resp) && XmlFind(resp, "response.level0.body.chan_id", out channelId))
return true;
channelId = String.Empty;
return false;
}
private static readonly string m_vivoxChannelSearchPath = "http://{0}/api2/viv_chan_search.php?cond_channame={1}&auth_token={2}";
/// <summary>
/// Retrieve a channel.
/// Once again, there a multitude of options possible. In the simplest case
/// we specify only the name and get a non-persistent cannel in return. Non
/// persistent means that the channel gets deleted if no-one uses it for
/// 5 hours. To accomodate future requirements, it may be a good idea to
/// initially create channels under the umbrella of a parent ID based upon
/// the region name. That way we have a context for side channels, if those
/// are required in a later phase.
/// In this case the call handles parent and description as optional values.
/// </summary>
private bool VivoxTryGetChannel(string channelParent, string channelName,
out string channelId, out string channelUri)
{
string count;
string requrl = String.Format(m_vivoxChannelSearchPath, m_vivoxServer, channelName, m_authToken);
XmlElement resp = VivoxCall(requrl, true);
if (XmlFind(resp, "response.level0.channel-search.count", out count))
{
int channels = Convert.ToInt32(count);
// Bug in Vivox Server r2978 where count returns 0
// Found by Adam
if (channels == 0)
{
for (int j=0;j<100;j++)
{
string tmpId;
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", j, out tmpId))
break;
channels = j + 1;
}
}
for (int i = 0; i < channels; i++)
{
string name;
string id;
string type;
string uri;
string parent;
// skip if not a channel
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) ||
(type != "channel" && type != "positional_M"))
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + " as it's not a channel.");
continue;
}
// skip if not the name we are looking for
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.name", i, out name) ||
name != channelName)
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + " as it has no name.");
continue;
}
// skip if parent does not match
if (channelParent != null && !XmlFind(resp, "response.level0.channel-search.channels.channels.level4.parent", i, out parent))
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it's parent doesnt match");
continue;
}
// skip if no channel id available
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", i, out id))
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it has no channel ID");
continue;
}
// skip if no channel uri available
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.uri", i, out uri))
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it has no channel URI");
continue;
}
channelId = id;
channelUri = uri;
return true;
}
}
else
{
m_log.Debug("[VivoxVoice] No count element?");
}
channelId = String.Empty;
channelUri = String.Empty;
// Useful incase something goes wrong.
//m_log.Debug("[VivoxVoice] Could not find channel in XMLRESP: " + resp.InnerXml);
return false;
}
private bool VivoxTryGetDirectory(string directoryName, out string directoryId)
{
string count;
string requrl = String.Format(m_vivoxChannelSearchPath, m_vivoxServer, directoryName, m_authToken);
XmlElement resp = VivoxCall(requrl, true);
if (XmlFind(resp, "response.level0.channel-search.count", out count))
{
int channels = Convert.ToInt32(count);
for (int i = 0; i < channels; i++)
{
string name;
string id;
string type;
// skip if not a directory
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) ||
type != "dir")
continue;
// skip if not the name we are looking for
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.name", i, out name) ||
name != directoryName)
continue;
// skip if no channel id available
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", i, out id))
continue;
directoryId = id;
return true;
}
}
directoryId = String.Empty;
return false;
}
// private static readonly string m_vivoxChannelById = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}";
// private XmlElement VivoxGetChannelById(string parent, string channelid)
// {
// string requrl = String.Format(m_vivoxChannelById, m_vivoxServer, "get", channelid, m_authToken);
// if (parent != null && parent != String.Empty)
// return VivoxGetChild(parent, channelid);
// else
// return VivoxCall(requrl, true);
// }
private static readonly string m_vivoxChannelDel = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}";
/// <summary>
/// Delete a channel.
/// Once again, there a multitude of options possible. In the simplest case
/// we specify only the name and get a non-persistent cannel in return. Non
/// persistent means that the channel gets deleted if no-one uses it for
/// 5 hours. To accomodate future requirements, it may be a good idea to
/// initially create channels under the umbrella of a parent ID based upon
/// the region name. That way we have a context for side channels, if those
/// are required in a later phase.
/// In this case the call handles parent and description as optional values.
/// </summary>
private XmlElement VivoxDeleteChannel(string parent, string channelid)
{
string requrl = String.Format(m_vivoxChannelDel, m_vivoxServer, "delete", channelid, m_authToken);
if (!string.IsNullOrEmpty(parent))
{
requrl = String.Format("{0}&chan_parent={1}", requrl, parent);
}
return VivoxCall(requrl, true);
}
private static readonly string m_vivoxChannelSearch = "http://{0}/api2/viv_chan_search.php?&cond_chanparent={1}&auth_token={2}";
/// <summary>
/// Return information on channels in the given directory
/// </summary>
private XmlElement VivoxListChildren(string channelid)
{
string requrl = String.Format(m_vivoxChannelSearch, m_vivoxServer, channelid, m_authToken);
return VivoxCall(requrl, true);
}
// private XmlElement VivoxGetChild(string parent, string child)
// {
// XmlElement children = VivoxListChildren(parent);
// string count;
// if (XmlFind(children, "response.level0.channel-search.count", out count))
// {
// int cnum = Convert.ToInt32(count);
// for (int i = 0; i < cnum; i++)
// {
// string name;
// string id;
// if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.name", i, out name))
// {
// if (name == child)
// {
// if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
// {
// return VivoxGetChannelById(null, id);
// }
// }
// }
// }
// }
// // One we *know* does not exist.
// return VivoxGetChannel(null, Guid.NewGuid().ToString());
// }
/// <summary>
/// This method handles the WEB side of making a request over the
/// Vivox interface. The returned values are tansferred to a has
/// table which is returned as the result.
/// The outcome of the call can be determined by examining the
/// status value in the hash table.
/// </summary>
private XmlElement VivoxCall(string requrl, bool admin)
{
XmlDocument doc = null;
// If this is an admin call, and admin is not connected,
// and the admin id cannot be connected, then fail.
if (admin && !m_adminConnected && !DoAdminLogin())
return null;
doc = new XmlDocument();
// Let's serialize all calls to Vivox. Most of these are driven by
// the clients (CAPs), when the user arrives at the region. We don't
// want to issue many simultaneous http requests to Vivox, because mono
// doesn't like that
lock (m_Lock)
{
try
{
// Otherwise prepare the request
m_log.DebugFormat("[VivoxVoice] Sending request <{0}>", requrl);
ServicePointManagerTimeoutSupport.ResetHosts();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requrl);
// We are sending just parameters, no content
req.ContentLength = 0;
// Send request and retrieve the response
using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse())
using (Stream s = rsp.GetResponseStream())
using (XmlTextReader rdr = new XmlTextReader(s))
doc.Load(rdr);
}
catch (Exception e)
{
m_log.ErrorFormat("[VivoxVoice] Error in admin call : {0}", e.Message);
}
}
// If we're debugging server responses, dump the whole
// load now
if (m_dumpXml) XmlScanl(doc.DocumentElement,0);
return doc.DocumentElement;
}
/// <summary>
/// Just say if it worked.
/// </summary>
private bool IsOK(XmlElement resp)
{
string status;
XmlFind(resp, "response.level0.status", out status);
return (status == "OK");
}
/// <summary>
/// Login has been factored in this way because it gets called
/// from several places in the module, and we want it to work
/// the same way each time.
/// </summary>
private bool DoAdminLogin()
{
m_log.Debug("[VivoxVoice] Establishing admin connection");
lock (vlock)
{
if (!m_adminConnected)
{
string status = "Unknown";
XmlElement resp = null;
resp = VivoxLogin(m_vivoxAdminUser, m_vivoxAdminPassword);
if (XmlFind(resp, "response.level0.body.status", out status))
{
if (status == "Ok")
{
m_log.Info("[VivoxVoice] Admin connection established");
if (XmlFind(resp, "response.level0.body.auth_token", out m_authToken))
{
if (m_dumpXml) m_log.DebugFormat("[VivoxVoice] Auth Token <{0}>",
m_authToken);
m_adminConnected = true;
}
}
else
{
m_log.WarnFormat("[VivoxVoice] Admin connection failed, status = {0}",
status);
}
}
}
}
return m_adminConnected;
}
/// <summary>
/// The XmlScan routine is provided to aid in the
/// reverse engineering of incompletely
/// documented packets returned by the Vivox
/// voice server. It is only called if the
/// m_dumpXml switch is set.
/// </summary>
private void XmlScanl(XmlElement e, int index)
{
if (e.HasChildNodes)
{
m_log.DebugFormat("<{0}>".PadLeft(index+5), e.Name);
XmlNodeList children = e.ChildNodes;
foreach (XmlNode node in children)
switch (node.NodeType)
{
case XmlNodeType.Element :
XmlScanl((XmlElement)node, index+1);
break;
case XmlNodeType.Text :
m_log.DebugFormat("\"{0}\"".PadLeft(index+5), node.Value);
break;
default :
break;
}
m_log.DebugFormat("</{0}>".PadLeft(index+6), e.Name);
}
else
{
m_log.DebugFormat("<{0}/>".PadLeft(index+6), e.Name);
}
}
private static readonly char[] C_POINT = {'.'};
/// <summary>
/// The Find method is passed an element whose
/// inner text is scanned in an attempt to match
/// the name hierarchy passed in the 'tag' parameter.
/// If the whole hierarchy is resolved, the InnerText
/// value at that point is returned. Note that this
/// may itself be a subhierarchy of the entire
/// document. The function returns a boolean indicator
/// of the search's success. The search is performed
/// by the recursive Search method.
/// </summary>
private bool XmlFind(XmlElement root, string tag, int nth, out string result)
{
if (root == null || tag == null || tag == String.Empty)
{
result = String.Empty;
return false;
}
return XmlSearch(root,tag.Split(C_POINT),0, ref nth, out result);
}
private bool XmlFind(XmlElement root, string tag, out string result)
{
int nth = 0;
if (root == null || tag == null || tag == String.Empty)
{
result = String.Empty;
return false;
}
return XmlSearch(root,tag.Split(C_POINT),0, ref nth, out result);
}
/// <summary>
/// XmlSearch is initially called by XmlFind, and then
/// recursively called by itself until the document
/// supplied to XmlFind is either exhausted or the name hierarchy
/// is matched.
///
/// If the hierarchy is matched, the value is returned in
/// result, and true returned as the function's
/// value. Otherwise the result is set to the empty string and
/// false is returned.
/// </summary>
private bool XmlSearch(XmlElement e, string[] tags, int index, ref int nth, out string result)
{
if (index == tags.Length || e.Name != tags[index])
{
result = String.Empty;
return false;
}
if (tags.Length-index == 1)
{
if (nth == 0)
{
result = e.InnerText;
return true;
}
else
{
nth--;
result = String.Empty;
return false;
}
}
if (e.HasChildNodes)
{
XmlNodeList children = e.ChildNodes;
foreach (XmlNode node in children)
{
switch (node.NodeType)
{
case XmlNodeType.Element :
if (XmlSearch((XmlElement)node, tags, index+1, ref nth, out result))
return true;
break;
default :
break;
}
}
}
result = String.Empty;
return false;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Text.RegularExpressions;
using Xunit;
public class SplitMatchIsMatchTests
{
/*
Class: Regex
Tested Methods:
public static string[] Split(string input, string pattern);
very simple
public static bool IsMatch(string input, string pattern, string options);
"m" option with 5 patterns
public static bool IsMatch(string input, string pattern);
"abc", "^b"
public static Match Match(string input, string pattern); ???
"XSP_TEST_FAILURE SUCCESS", ".*\\b(\\w+)\\b"
*/
[Fact]
public static void SplitMatchIsMatch()
{
//////////// Global Variables used for all tests
String strLoc = "Loc_000oo";
String strValue = String.Empty;
int iCountErrors = 0;
int iCountTestcases = 0;
Match match;
String[] sa;
String[] strMatch1 =
{
"line2\nline3", "line2\nline3", "line3\n\nline4", "line3\n\nline4", "line2\nline3"
}
;
Int32[,] iMatch1 =
{
{
6, 11
}
, {
6, 11
}
, {
12, 12
}
, {
12, 12
}
, {
6, 11
}
}
;
String[] strGroup1 =
{
}
;
String[] strGrpCap1 =
{
}
;
String strMatch2 = "XSP_TEST_FAILURE SUCCESS";
Int32[] iMatch2 =
{
0, 24
}
;
String[] strGroup2 =
{
"XSP_TEST_FAILURE SUCCESS", "SUCCESS"
}
;
Int32[] iGroup2 =
{
17, 7
}
;
String[] strGrpCap2 =
{
"SUCCESS"
}
;
Int32[] iGrpCap2 =
{
17, 7
}
;
try
{
///////////////////////// START TESTS ////////////////////////////
///////////////////////////////////////////////////////////////////
try
{
// [] public static string[] Split(string input, string pattern);
// very simple
//-----------------------------------------------------------------
strLoc = "Loc_498yg";
iCountTestcases++;
sa = Regex.Split("word0 word1 word2 word3", " ");
for (int i = 0; i < sa.Length; i++)
{
String s = "word" + i;
if (String.Compare(sa[i], s) != 0)
{
iCountErrors++;
Console.WriteLine("Err_7654fdgd! Fail : [" + s + "] not equal [" + sa[i] + "]");
}
}
//-----------------------------------------------------------------
}
catch
{
}
try
{
// [] public static bool IsMatch(string input, string pattern, string options);
//"m" option with 5 patterns
//-----------------------------------------------------------------
strLoc = "Loc_298vy";
iCountTestcases++;
sa = new String[5];
sa[0] = "(line2$\n)line3";
sa[1] = "(line2\n^)line3";
sa[2] = "(line3\n$\n)line4";
sa[3] = "(line3\n^\n)line4";
sa[4] = "(line2$\n^)line3";
for (int ii = 0; ii < sa.Length; ii++)
{
strLoc = "Loc_0002." + ii.ToString();
if (!Regex.IsMatch("line1\nline2\nline3\n\nline4", sa[ii], RegexOptions.Multiline))
{
iCountErrors++;
Console.WriteLine("Fail : " + strLoc + " : Pattern not match");
}
else
{
match = Regex.Match("line1\nline2\nline3\n\nline4", sa[ii], RegexOptions.Multiline);
if (!match.Value.Equals(strMatch1[ii]) || (match.Index != iMatch1[ii, 0]) || (match.Length != iMatch1[ii, 1]) || (match.Captures.Count != 1))
{
iCountErrors++;
Console.WriteLine("Err_75234_" + ii + " : unexpected return result");
}
for (int i = 0; i < match.Captures.Count; i++)
{
if (!match.Captures[i].Value.Equals(strMatch1[ii]) || (match.Captures[i].Index != iMatch1[ii, 0]) || (match.Captures[i].Length != iMatch1[ii, 1]))
{
iCountErrors++;
Console.WriteLine("Err_8743fsgd_" + ii + "_" + i + " : unexpected return result");
}
}
if (match.Groups.Count != 2)
{
iCountErrors++;
Console.WriteLine("Err_3976dffd! unexpected return result");
}
}
}
//-----------------------------------------------------------------
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
try
{
// [] public static bool IsMatch(string input, string pattern);
//"abc", "^b"
//-----------------------------------------------------------------
strLoc = "Loc_75rfds";
iCountTestcases++;
if (Regex.IsMatch("abc", "^b"))
{
iCountErrors++;
Console.WriteLine("Err_7356wgd! Fail : " + strLoc + " : unexpected match");
}
//-----------------------------------------------------------------
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
try
{
// [] public static Match Match(string input, string pattern); ???
//"XSP_TEST_FAILURE SUCCESS", ".*\\b(\\w+)\\b"
//-----------------------------------------------------------------
strLoc = "Loc_87423fs";
iCountTestcases++;
match = Regex.Match("XSP_TEST_FAILURE SUCCESS", @".*\b(\w+)\b");
if (!match.Success)
{
iCountErrors++;
Console.WriteLine("Err_753rwef! Unexpected results returned");
}
else
{
if (!match.Value.Equals(strMatch2) || (match.Index != iMatch2[0]) || (match.Length != iMatch2[1]) || (match.Captures.Count != 1))
{
iCountErrors++;
Console.WriteLine("Err_98275dsg: unexpected return result");
}
//Match.Captures always is Match
if (!match.Captures[0].Value.Equals(strMatch2) || (match.Captures[0].Index != iMatch2[0]) || (match.Captures[0].Length != iMatch2[1]))
{
iCountErrors++;
Console.WriteLine("Err_2046gsg! unexpected return result");
}
if (match.Groups.Count != 2)
{
iCountErrors++;
Console.WriteLine("Err_75324sg! unexpected return result");
}
//Group 0 always is the Match
if (!match.Groups[0].Value.Equals(strMatch2) || (match.Groups[0].Index != iMatch2[0]) || (match.Groups[0].Length != iMatch2[1]) || (match.Groups[0].Captures.Count != 1))
{
iCountErrors++;
Console.WriteLine("Err_2046gsg! unexpected return result");
}
//Group 0's Capture is always the Match
if (!match.Groups[0].Captures[0].Value.Equals(strMatch2) || (match.Groups[0].Captures[0].Index != iMatch2[0]) || (match.Groups[0].Captures[0].Length != iMatch2[1]))
{
iCountErrors++;
Console.WriteLine("Err_2975edg!! unexpected return result");
}
for (int i = 1; i < match.Groups.Count; i++)
{
if (!match.Groups[i].Value.Equals(strGroup2[i]) || (match.Groups[i].Index != iGroup2[0]) || (match.Groups[i].Length != iGroup2[1]) || (match.Groups[i].Captures.Count != 1))
{
iCountErrors++;
Console.WriteLine("Err_1954eg_" + i + "! unexpected return result");
}
for (int j = 0; j < match.Groups[i].Captures.Count; j++)
{
if (!match.Groups[i].Captures[j].Value.Equals(strGrpCap2[j]) || (match.Groups[i].Captures[j].Index != iGrpCap2[0]) || (match.Groups[i].Captures[j].Length != iGrpCap2[1]))
{
iCountErrors++;
Console.WriteLine("Err_5072dn_" + i + "_" + j + "!! unexpected return result");
}
}
}
}
//-----------------------------------------------------------------
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
///////////////////////////////////////////////////////////////////
/////////////////////////// END TESTS /////////////////////////////
}
catch (Exception exc_general)
{
++iCountErrors;
Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString());
}
//// Finish Diagnostics
Assert.Equal(0, iCountErrors);
}
}
| |
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
using System.Collections.Generic;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
#region OperationState
/// <summary>
/// Defines the different states of the operation
/// </summary>
internal enum OperationState
{
/// <summary>
/// Start operation completed successfully
/// </summary>
StartComplete = 0,
/// <summary>
/// Stop operation completed successfully
/// </summary>
StopComplete = 1,
}
/// <summary>
/// class describing event args which a helper class
/// implementing IThrottleOperation need to throw
/// </summary>
internal sealed class OperationStateEventArgs : EventArgs
{
/// <summary>
/// operation state
/// </summary>
internal OperationState OperationState { get; set; }
/// <summary>
/// the original event which actually resulted in this
/// event being raised
/// </summary>
internal EventArgs BaseEvent { get; set; }
}
#endregion OperationState
#region IThrottleOperation
/// <summary>
/// Interface which needs to be implemented by a class which wants to
/// submit operations to the throttle manager
/// </summary>
/// <remarks>Any synchronization that needs to be performed between
/// StartOperation and StopOperation in the class that implements this
/// interface should take care of handling the same. For instance,
/// say New-Runspace class internally uses a class A which implements
/// the IThrottleOperation interface. StartOperation of this
/// class opens a runspace asynchronously on a remote machine. Stop
/// operation is supposed to cancel the opening of this runspace. Any
/// synchronization/cleanup issues should be handled by class A.
/// </remarks>
internal abstract class IThrottleOperation
{
/// <summary>
/// This method should handle the actual operation which need to be
/// controlled and performed. Examples of this can be Opening remote
/// runspace, invoking expression in a remote runspace, etc. Once
/// an event is successfully received as a result of this function,
/// the handler has to ensure that it raises an OperationComplete
/// event with StartComplete or StopComplete for the throttle manager
/// to handle
/// </summary>
internal abstract void StartOperation();
/// <summary>
/// This method should handle the situation when a stop signal is sent
/// for this operation. For instance, when trying to open a set of
/// remote runspaces, the user might hit ctrl-C. In which case, the
/// pending runspaces to be opened will actually be signalled through
/// this method to stop operation and return back. This method also
/// needs to be asynchronous. Once an event is successfully received
/// as a result of this function, the handler has to ensure that it
/// raises an OperationComplete event with StopComplete for the
/// throttle manager to handle. It is important that this function
/// does not raise a StartComplete which will then result in the
/// ThrottleComplete event not being raised by the throttle manager
/// </summary>
internal abstract void StopOperation();
/// <summary>
/// Event which will be triggered when the operation is complete. It is
/// assumed that all the operations performed by StartOperation and
/// StopOperation are asynchronous. The submitter of operations may
/// subscribe to this event to know when it's complete (or it can handle
/// the synchronization with its scheduler) and the throttle
/// manager will subscribe to this event to know that it's complete
/// and to start the operation on the next item.
/// </summary>
internal abstract event EventHandler<OperationStateEventArgs> OperationComplete;
/// <summary>
/// This Property indicates whether an operation has been stopped
/// </summary>
/// <remarks>
/// In the initial implementation of ThrottleManager stopping
/// individual operations was not supported. When the support
/// for stopping individual operations was added, there was
/// the following problem - if an operation is not there in
/// the pending queue and in the startOperationQueue as well,
/// then the following two scenarios are possible
/// (a) Operation was started and start completed
/// (b) Operation was started and stopped and both completed
/// This property has been added in order to disambiguate between
/// these two cases. When this property is set, StopOperation
/// need not be called on the operation (this can be when the
/// operation has stop completed or stop has been called and is
/// pending)
///</remarks>
internal bool IgnoreStop
{
get
{
return _ignoreStop;
}
set
{
_ignoreStop = true;
}
}
private bool _ignoreStop = false;
} // IThrottleOperation
#endregion IThrottleOperation
#region ThrottleManager
/// <summary>
/// Class which handles the throttling operations. This class is singleton and therefore
/// when used either across cmdlets or at the infrastructure level it will ensure that
/// there aren't more operations by way of accumulation than what is intended by design.
///
/// This class contains a queue of items, each of which has the
/// <see cref="System.Management.Automation.Remoting.IThrottleOperation">
/// IThrottleOperation</see> interface implemented. To begin with
/// THROTTLE_LIMIT number of items will be taken from the queue and the operations on
/// them will be executed. Subsequently, as and when operations complete, new items from
/// the queue will be taken and their operations executed.
///
/// Whenever a consumer submits or adds operations, the methods will start as much
/// operations from the queue as permitted based on the throttle limit. Also the event
/// handler will start an operation once a previous event is completed.
///
/// The queue used is a generic queue of type IThrottleOperations, as it will offer better
/// performance
///
/// </summary>
/// <remarks>Throttle limit is currently set to 50. This value may be modified later based
/// on a figure that we may arrive at out of experience.</remarks>
internal class ThrottleManager : IDisposable
{
#region Public (internal) Properties
/// <summary>
/// Allows the consumer to override the default throttle limit
/// </summary>
internal Int32 ThrottleLimit
{
set
{
if (value > 0 && value <= s_THROTTLE_LIMIT_MAX)
{
_throttleLimit = value;
}
}
get
{
return _throttleLimit;
}
}
private Int32 _throttleLimit = s_DEFAULT_THROTTLE_LIMIT;
#endregion Public (internal) Properties
#region Public (internal) Methods
/// <summary>
/// Submit a list of operations that need to be throttled
/// </summary>
/// <param name="operations">list of operations to be throttled</param>
/// <remarks>Once the operations are added to the queue, the method will
/// start operations from the queue
/// </remarks>
internal void SubmitOperations(List<IThrottleOperation> operations)
{
lock (_syncObject)
{
// operations can be submitted only until submitComplete
// is not set to true (happens when EndSubmitOperations is called)
if (!_submitComplete)
{
// add items to the queue
foreach (IThrottleOperation operation in operations)
{
Dbg.Assert(operation != null,
"Operation submitComplete to throttle manager cannot be null");
_operationsQueue.Add(operation);
}
}
else
{
throw new InvalidOperationException();
}
}
// schedule operations here if possible
StartOperationsFromQueue();
} // SubmitOperations
/// <summary>
/// Add a single operation to the queue
/// </summary>
/// <param name="operation">Operation to be added</param>
internal void AddOperation(IThrottleOperation operation)
{
// add item to the queue
lock (_syncObject)
{
// operations can be submitted only until submitComplete
// is not set to true (happens when EndSubmitOperations is called)
if (!_submitComplete)
{
Dbg.Assert(operation != null,
"Operation submitComplete to throttle manager cannot be null");
_operationsQueue.Add(operation);
}
else
{
throw new InvalidOperationException();
}
}
// start operations from queue if possible
StartOperationsFromQueue();
}// AddOperation
/// <summary>
/// Stop throttling operations
/// </summary>
/// <remarks>Calling this method will also affect other cmdlets which
/// could have potentially submitComplete operations for processing
/// </remarks>
/// <returns>number of objects cleared from queue without being
/// stopped</returns>
internal void StopAllOperations()
{
// if stopping is already in progress, make it a no op
bool needToReturn = false;
lock (_syncObject)
{
if (!_stopping)
{
_stopping = true;
}
else
{
needToReturn = true;
}
} // lock ...
if (needToReturn)
{
RaiseThrottleManagerEvents();
return;
}
IThrottleOperation[] startOperationsInProcessArray;
lock (_syncObject)
{
// no more submissions possible once stopped
_submitComplete = true;
// Clear all pending operations in queue so that they are not
// scheduled when a stop operation completes
_operationsQueue.Clear();
// Make a copy of the in process queue so as to stop all
// operations in progress
startOperationsInProcessArray =
new IThrottleOperation[_startOperationQueue.Count];
_startOperationQueue.CopyTo(startOperationsInProcessArray);
// stop all operations in process (using the copy)
foreach (IThrottleOperation operation in startOperationsInProcessArray)
{
// When iterating through the array of operations in process
// it is quite possible that a runspace gets to the open state
// before stop is actually called on it. In that case, the
// OperationCompleteHandler will remove it from the
// operationsInProcess queue. Now when the runspace is closed
// the same handler will try removing it again and so there will
// be an exception. Hence adding it a second time before stop
// will ensure that the operation is available in the queue for
// removal. In case the stop succeeds before start succeeds then
// both will get removed (it goes without saying that there cannot
// be a situation where start succeeds after stop succeeded)
_stopOperationQueue.Add(operation);
operation.IgnoreStop = true;
} // foreach...
} // lock...
foreach (IThrottleOperation operation in startOperationsInProcessArray)
{
operation.StopOperation();
}
// Raise event as it can be that at this point, all operations are
// complete
RaiseThrottleManagerEvents();
} // StopAllOperations
/// <summary>
/// Stop the specified operation
/// </summary>
/// <param name="operation">operation which needs to be stopped</param>
internal void StopOperation(IThrottleOperation operation)
{
// StopOperation is being called a second time
// or the stop operation has already completed
// - in either case just return
if (operation.IgnoreStop)
{
return;
}
// If the operation has not yet been started, then
// remove it from the pending queue
if (_operationsQueue.IndexOf(operation) != -1)
{
lock (_syncObject)
{
if (_operationsQueue.IndexOf(operation) != -1)
{
_operationsQueue.Remove(operation);
RaiseThrottleManagerEvents();
return;
}
}
}
// The operation has already started, then add it
// to the inprocess queue and call stop. Refer to
// comment in StopAllOperations() as to why this is
// being added a second time
lock (_syncObject)
{
_stopOperationQueue.Add(operation);
operation.IgnoreStop = true;
}
// stop the operation outside of the lock
operation.StopOperation();
}
/// <summary>
/// Signals that no more operations can be submitComplete
/// for throttling
/// </summary>
internal void EndSubmitOperations()
{
lock (_syncObject)
{
_submitComplete = true;
}
RaiseThrottleManagerEvents();
} // EndSubmitOperations
#endregion Public (internal) Methods
#region Public (internal) Events
/// <summary>
/// Event raised when throttling all operations is complete
/// </summary>
internal event EventHandler<EventArgs> ThrottleComplete;
#endregion Public (internal) Events
#region Constructors
/// <summary>
/// Public constructor
/// </summary>
public ThrottleManager()
{
_operationsQueue = new List<IThrottleOperation>();
_startOperationQueue = new List<IThrottleOperation>();
_stopOperationQueue = new List<IThrottleOperation>();
_syncObject = new Object();
}// ThrottleManager
#endregion Constructors
#region Private Methods
/// <summary>
/// Handler which handles state change for the object which implements
/// the <see cref="System.Management.Automation.Remoting.IThrottleOperation"/>
/// interface
/// </summary>
/// <param name="source">sender of the event</param>
/// <param name="stateEventArgs">Event information object which describes the event
/// which triggered this method</param>
private void OperationCompleteHandler(object source, OperationStateEventArgs stateEventArgs)
{
// An item has completed operation. If it's a start operation which completed
// remove the instance from the startOperationqueue. If it's a stop operation
// which completed, then remove the instance from both queues
lock (_syncObject)
{
IThrottleOperation operation = source as IThrottleOperation;
Dbg.Assert(operation != null, "Source of event should not be null");
int index = -1;
if (stateEventArgs.OperationState == OperationState.StartComplete)
{
// A stop operation can be initiated before a start operation completes.
// A stop operation handler cleans up an outstanding start operation.
// So it is possible that a start operation complete callback will find the
// operation removed from the queue by an earlier stop operation complete.
index = _startOperationQueue.IndexOf(operation);
if (index != -1)
{
_startOperationQueue.RemoveAt(index);
}
}
else
{
// for a stop operation, the same operation object would have been
// added to the stopOperationQueue as well. So we need to
// remove both the instances.
index = _startOperationQueue.IndexOf(operation);
if (index != -1)
{
_startOperationQueue.RemoveAt(index);
}
index = _stopOperationQueue.IndexOf(operation);
if (index != -1)
{
_stopOperationQueue.RemoveAt(index);
}
// if an operation signals a stopcomplete, it can mean
// that the operation has completed. In this case, we
// need to set the isStopped to true
operation.IgnoreStop = true;
}
}
// It's possible that all operations are completed at this point
// and submit is complete. So raise event
RaiseThrottleManagerEvents();
// Do necessary things for starting operation for the next item in the queue
StartOneOperationFromQueue();
} // OperationCompleteHandler
/// <summary>
/// Method used to start the operation on one item in the queue
/// </summary>
private void StartOneOperationFromQueue()
{
IThrottleOperation operation = null;
lock (_syncObject)
{
if (_operationsQueue.Count > 0)
{
operation = _operationsQueue[0];
_operationsQueue.RemoveAt(0);
operation.OperationComplete +=
new EventHandler<OperationStateEventArgs>(OperationCompleteHandler);
_startOperationQueue.Add(operation);
}
}
if (operation != null)
{
operation.StartOperation();
}
} //StartOneOperationFromQueue
/// <summary>
/// Start operations to the limit possible from the queue
/// </summary>
private void StartOperationsFromQueue()
{
int operationsInProcessCount = 0;
int operationsQueueCount = 0;
lock (_syncObject)
{
operationsInProcessCount = _startOperationQueue.Count;
operationsQueueCount = _operationsQueue.Count;
}
int remainingCap = _throttleLimit - operationsInProcessCount;
if (remainingCap > 0)
{
int numOperations = (remainingCap > operationsQueueCount) ? operationsQueueCount : remainingCap;
for (int i = 0; i < numOperations; i++)
{
StartOneOperationFromQueue();
}
}
} // StartOperationsFromQueue
/// <summary>
/// Raise the throttle manager events once the conditions are met
/// </summary>
private void RaiseThrottleManagerEvents()
{
bool readyToRaise = false;
lock (_syncObject)
{
// if submit is complete, there are no operations in progress and
// the pending queue is empty, then raise events
if (_submitComplete &&
_startOperationQueue.Count == 0 &&
_stopOperationQueue.Count == 0 &&
_operationsQueue.Count == 0)
{
readyToRaise = true;
}
}
if (readyToRaise)
{
ThrottleComplete.SafeInvoke(this, EventArgs.Empty);
}
} // RaiseThrottleManagerEvents
#endregion Private Methods
#region Private Members
/// <summary>
/// default throttle limit - the maximum number of operations
/// to be processed at a time
/// </summary>
private static int s_DEFAULT_THROTTLE_LIMIT = 32;
/// <summary>
/// Maximum value that the throttle limit can be set to
/// </summary>
private static int s_THROTTLE_LIMIT_MAX = int.MaxValue;
/// <summary>
/// All pending operations
/// </summary>
private List<IThrottleOperation> _operationsQueue;
/// <summary>
/// List of items on which a StartOperation has
/// been called
/// </summary>
private List<IThrottleOperation> _startOperationQueue;
/// <summary>
/// List of items on which a StopOperation has
/// been called
/// </summary>
private List<IThrottleOperation> _stopOperationQueue;
/// <summary>
/// Object used to synchronize access to the queues
/// </summary>
private Object _syncObject;
private bool _submitComplete = false; // to check if operations have been submitComplete
private bool _stopping = false; // if stop is in process
#endregion Private Members
#region IDisposable Overrides
/// <summary>
/// Dispose method of IDisposable. Any cmdlet that uses
/// the throttle manager needs to call this method from its
/// Dispose method
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Internal dispose method which does the actual dispose
/// operations and finalize suppressions
/// </summary>
/// <param name="disposing">If method is called from
/// disposing of destructor</param>
private void Dispose(bool disposing)
{
if (disposing)
{
StopAllOperations();
}
} // Dispose
#endregion IDisposable Overrides
}
#endregion ThrottleManager
#region Helper Class for Testing
#if !CORECLR // Skip The Helper Class for Testing (Thread.Abort() Not In CoreCLR)
internal class Operation : IThrottleOperation
{
private ThreadStart workerThreadDelegate;
private Thread workerThreadStart;
private Thread workerThreadStop;
public bool Done { set; get; }
public int SleepTime { set; get; } = 100;
private void WorkerThreadMethodStart()
{
Thread.Sleep(SleepTime);
Done = true;
OperationStateEventArgs operationStateEventArgs =
new OperationStateEventArgs();
operationStateEventArgs.OperationState = OperationState.StartComplete;
OperationComplete.SafeInvoke(this, operationStateEventArgs);
}
private void WorkerThreadMethodStop()
{
workerThreadStart.Abort();
OperationStateEventArgs operationStateEventArgs =
new OperationStateEventArgs();
operationStateEventArgs.OperationState = OperationState.StopComplete;
OperationComplete.SafeInvoke(this, operationStateEventArgs);
}
internal Operation()
{
Done = false;
workerThreadDelegate = new ThreadStart(WorkerThreadMethodStart);
workerThreadStart = new Thread(workerThreadDelegate);
workerThreadDelegate = new ThreadStart(WorkerThreadMethodStop);
workerThreadStop = new Thread(workerThreadDelegate);
}
internal override void StartOperation()
{
workerThreadStart.Start();
}
internal override void StopOperation()
{
workerThreadStop.Start();
}
internal override event EventHandler<OperationStateEventArgs> OperationComplete;
internal event EventHandler<EventArgs> InternalEvent = null;
internal event EventHandler<EventArgs> EventHandler
{
add
{
bool firstEntry = (null == InternalEvent);
InternalEvent += value;
if (firstEntry)
{
OperationComplete += new EventHandler<OperationStateEventArgs>(Operation_OperationComplete);
}
}
remove
{
InternalEvent -= value;
}
}
private void Operation_OperationComplete(object sender, OperationStateEventArgs e)
{
InternalEvent.SafeInvoke(sender, e);
}
internal static void SubmitOperations(List<object> operations, ThrottleManager throttleManager)
{
List<IThrottleOperation> newOperations = new List<IThrottleOperation>();
foreach (object operation in operations)
{
newOperations.Add((IThrottleOperation)operation);
}
throttleManager.SubmitOperations(newOperations);
}
internal static void AddOperation(object operation, ThrottleManager throttleManager)
{
throttleManager.AddOperation((IThrottleOperation)operation);
}
}
#endif
#endregion Helper Class for Testing
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticmapreduce-2009-03-31.normal.json service model.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.ElasticMapReduce;
using Amazon.ElasticMapReduce.Model;
using Amazon.ElasticMapReduce.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public class ElasticMapReduceMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("elasticmapreduce-2009-03-31.normal.json", "elasticmapreduce.customizations.json");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void AddInstanceGroupsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<AddInstanceGroupsRequest>();
var marshaller = new AddInstanceGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<AddInstanceGroupsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("AddInstanceGroups").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = AddInstanceGroupsResponseUnmarshaller.Instance.Unmarshall(context)
as AddInstanceGroupsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void AddJobFlowStepsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<AddJobFlowStepsRequest>();
var marshaller = new AddJobFlowStepsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<AddJobFlowStepsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("AddJobFlowSteps").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = AddJobFlowStepsResponseUnmarshaller.Instance.Unmarshall(context)
as AddJobFlowStepsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void AddTagsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<AddTagsRequest>();
var marshaller = new AddTagsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<AddTagsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("AddTags").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = AddTagsResponseUnmarshaller.Instance.Unmarshall(context)
as AddTagsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void DescribeClusterMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeClusterRequest>();
var marshaller = new DescribeClusterRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeClusterRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeCluster").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeClusterResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeClusterResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void DescribeJobFlowsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeJobFlowsRequest>();
var marshaller = new DescribeJobFlowsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeJobFlowsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeJobFlows").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeJobFlowsResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeJobFlowsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void DescribeStepMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeStepRequest>();
var marshaller = new DescribeStepRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeStepRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeStep").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeStepResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeStepResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void ListBootstrapActionsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ListBootstrapActionsRequest>();
var marshaller = new ListBootstrapActionsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ListBootstrapActionsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListBootstrapActions").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ListBootstrapActionsResponseUnmarshaller.Instance.Unmarshall(context)
as ListBootstrapActionsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void ListClustersMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ListClustersRequest>();
var marshaller = new ListClustersRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ListClustersRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListClusters").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ListClustersResponseUnmarshaller.Instance.Unmarshall(context)
as ListClustersResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void ListInstanceGroupsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ListInstanceGroupsRequest>();
var marshaller = new ListInstanceGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ListInstanceGroupsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListInstanceGroups").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ListInstanceGroupsResponseUnmarshaller.Instance.Unmarshall(context)
as ListInstanceGroupsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void ListInstancesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ListInstancesRequest>();
var marshaller = new ListInstancesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ListInstancesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListInstances").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ListInstancesResponseUnmarshaller.Instance.Unmarshall(context)
as ListInstancesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void ListStepsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ListStepsRequest>();
var marshaller = new ListStepsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ListStepsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListSteps").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ListStepsResponseUnmarshaller.Instance.Unmarshall(context)
as ListStepsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void ModifyInstanceGroupsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ModifyInstanceGroupsRequest>();
var marshaller = new ModifyInstanceGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ModifyInstanceGroupsRequest>(request,jsonRequest);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void RemoveTagsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<RemoveTagsRequest>();
var marshaller = new RemoveTagsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<RemoveTagsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("RemoveTags").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = RemoveTagsResponseUnmarshaller.Instance.Unmarshall(context)
as RemoveTagsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void RunJobFlowMarshallTest()
{
var request = InstantiateClassGenerator.Execute<RunJobFlowRequest>();
var marshaller = new RunJobFlowRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<RunJobFlowRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("RunJobFlow").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = RunJobFlowResponseUnmarshaller.Instance.Unmarshall(context)
as RunJobFlowResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void SetTerminationProtectionMarshallTest()
{
var request = InstantiateClassGenerator.Execute<SetTerminationProtectionRequest>();
var marshaller = new SetTerminationProtectionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<SetTerminationProtectionRequest>(request,jsonRequest);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void SetVisibleToAllUsersMarshallTest()
{
var request = InstantiateClassGenerator.Execute<SetVisibleToAllUsersRequest>();
var marshaller = new SetVisibleToAllUsersRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<SetVisibleToAllUsersRequest>(request,jsonRequest);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("ElasticMapReduce")]
public void TerminateJobFlowsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<TerminateJobFlowsRequest>();
var marshaller = new TerminateJobFlowsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<TerminateJobFlowsRequest>(request,jsonRequest);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
$MetricsParamArray[0] = "fps ";
$MetricsParamArray[1] = "shadow ";
$MetricsParamArray[2] = "gfx ";
$MetricsParamArray[3] = "sfx ";
$MetricsParamArray[4] = "terrain ";
$MetricsParamArray[5] = "groundcover ";
$MetricsParamArray[6] = "forest ";
$MetricsParamArray[7] = "net ";
$EnableProfiler = false;
$string = ""; //string used to collet the parameters for metrics function
function showMetrics(%var)
{
$string = "";
if(ppShowFps.getValue())
{
$string = $string @ $MetricsParamArray[0];
}
if(ppShowShadow.getValue())
{
$string = $string @ $MetricsParamArray[1];
}
if(ppShowGfx.getValue())
{
$string = $string @ $MetricsParamArray[2];
}
if(ppShowSfx.getValue())
{
$string = $string @ $MetricsParamArray[3];
}
if(ppShowTerrain.getValue())
{
$string = $string @ $MetricsParamArray[4];
}
if(ppShowForest.getValue())
{
$string = $string @ $MetricsParamArray[5];
}
if(ppShowGroundcover.getValue())
{
$string = $string @ $MetricsParamArray[6];
}
if(ppShowNet.getValue())
{
$string = $string @ $MetricsParamArray[7];
}
if(%var)
{
$EnableProfiler = !($EnableProfiler);
if($EnableProfiler)
{
metrics($string);
}
else if((false == $EnableProfiler))
{
metrics();
}
}
else if($EnableProfiler) //will enter only when the enable/disable button was pressed
{
metrics($string);
}
}
function showMetics(%var)
{
if(%var)
{
metrics($string);
}
else if(true == $EnableProfiler)
{
$EnableProfiler = false;
metrics();
}
}
GlobalActionMap.bind(keyboard, "ctrl F2", showMetics);
%guiContent = new GuiControl(FrameOverlayGui) {
profile = "GuiModelessDialogProfile";
horizSizing = "right";
vertSizing = "bottom";
position = "0 0";
extent = "640 480";
minExtent = "8 8";
visible = "True";
setFirstResponder = "True";
modal = "false";
helpTag = "0";
noCursor = true;
new GuiConsoleTextCtrl(TextOverlayControl) {
profile = "GuiConsoleTextProfile";
horizSizing = "right";
vertSizing = "bottom";
position = "5 5";
extent = "130 18";
minExtent = "4 4";
visible = "True";
setFirstResponder = "True";
modal = "True";
helpTag = "0";
expression = "10";
command = "Canvas.popDialog(FrameOverlayGui);";
accelerator = "escape";
};
};
// Note: To implement your own metrics overlay
// just add a function with a name in the form
// XXXXMetricsCallback which can be enabled via
// metrics( XXXX )
function fpsMetricsCallback()
{
return " | FPS |" @
" " @ $fps::real @
" max: " @ $fps::realMax @
" min: " @ $fps::realMin @
" mspf: " @ 1000 / $fps::real;
}
function gfxMetricsCallback()
{
return " | GFX |" @
" PolyCount: " @ $GFXDeviceStatistics::polyCount @
" DrawCalls: " @ $GFXDeviceStatistics::drawCalls @
" RTChanges: " @ $GFXDeviceStatistics::renderTargetChanges;
}
function terrainMetricsCallback()
{
return " | Terrain |" @
" Cells: " @ $TerrainBlock::cellsRendered @
" Override Cells: " @ $TerrainBlock::overrideCells @
" DrawCalls: " @ $TerrainBlock::drawCalls;
}
function netMetricsCallback()
{
return " | Net |" @
" BitsSent: " @ $Stats::netBitsSent @
" BitsRcvd: " @ $Stats::netBitsReceived @
" GhostUpd: " @ $Stats::netGhostUpdates;
}
function groundCoverMetricsCallback()
{
return " | GroundCover |" @
" Cells: " @ $GroundCover::renderedCells @
" Billboards: " @ $GroundCover::renderedBillboards @
" Batches: " @ $GroundCover::renderedBatches @
" Shapes: " @ $GroundCover::renderedShapes;
}
function forestMetricsCallback()
{
return " | Forest |" @
" Cells: " @ $Forest::totalCells @
" Cells Meshed: " @ $Forest::cellsRendered @
" Cells Billboarded: " @ $Forest::cellsBatched @
" Meshes: " @ $Forest::cellItemsRendered @
" Billboards: " @ $Forest::cellItemsBatched;
}
function sfxMetricsCallback()
{
return " | SFX |" @
" Sounds: " @ $SFX::numSounds @
" Lists: " @ ( $SFX::numSources - $SFX::numSounds - $SFX::Device::fmodNumEventSource ) @
" Events: " @ $SFX::fmodNumEventSources @
" Playing: " @ $SFX::numPlaying @
" Culled: " @ $SFX::numCulled @
" Voices: " @ $SFX::numVoices @
" Buffers: " @ $SFX::Device::numBuffers @
" Memory: " @ ( $SFX::Device::numBufferBytes / 1024.0 / 1024.0 ) @ " MB" @
" Time/S: " @ $SFX::sourceUpdateTime @
" Time/P: " @ $SFX::parameterUpdateTime @
" Time/A: " @ $SFX::ambientUpdateTime;
}
function sfxSourcesMetricsCallback()
{
return sfxDumpSourcesToString();
}
function sfxStatesMetricsCallback()
{
return " | SFXStates |" @ sfxGetActiveStates();
}
function timeMetricsCallback()
{
return " | Time |" @
" Sim Time: " @ getSimTime() @
" Mod: " @ getSimTime() % 32;
}
function reflectMetricsCallback()
{
return " | REFLECT |" @
" Objects: " @ $Reflect::numObjects @
" Visible: " @ $Reflect::numVisible @
" Occluded: " @ $Reflect::numOccluded @
" Updated: " @ $Reflect::numUpdated @
" Elapsed: " @ $Reflect::elapsed NL
" Allocated: " @ $Reflect::renderTargetsAllocated @
" Pooled: " @ $Reflect::poolSize NL
" " @ getWord( $Reflect::textureStats, 1 ) TAB
" " @ getWord( $Reflect::textureStats, 2 ) @ "MB" TAB
" " @ getWord( $Reflect::textureStats, 0 );
}
function decalMetricsCallback()
{
return " | DECAL |" @
" Batches: " @ $Decal::Batches @
" Buffers: " @ $Decal::Buffers @
" DecalsRendered: " @ $Decal::DecalsRendered;
}
function renderMetricsCallback()
{
return " | Render |" @
" Mesh: " @ $RenderMetrics::RIT_Mesh @
" MeshDL: " @ $RenderMetrics::RIT_MeshDynamicLighting @
" Shadow: " @ $RenderMetrics::RIT_Shadow @
" Sky: " @ $RenderMetrics::RIT_Sky @
" Obj: " @ $RenderMetrics::RIT_Object @
" ObjT: " @ $RenderMetrics::RIT_ObjectTranslucent @
" Decal: " @ $RenderMetrics::RIT_Decal @
" Water: " @ $RenderMetrics::RIT_Water @
" Foliage: " @ $RenderMetrics::RIT_Foliage @
" Trans: " @ $RenderMetris::RIT_Translucent @
" Custom: " @ $RenderMetrics::RIT_Custom;
}
function shadowMetricsCallback()
{
return " | Shadow |" @
" Active: " @ $ShadowStats::activeMaps @
" Updated: " @ $ShadowStats::updatedMaps @
" PolyCount: " @ $ShadowStats::polyCount @
" DrawCalls: " @ $ShadowStats::drawCalls @
" RTChanges: " @ $ShadowStats::rtChanges @
" PoolTexCount: " @ $ShadowStats::poolTexCount @
" PoolTexMB: " @ $ShadowStats::poolTexMemory @ "MB";
}
function basicShadowMetricsCallback()
{
return " | Shadow |" @
" Active: " @ $BasicLightManagerStats::activePlugins @
" Updated: " @ $BasicLightManagerStats::shadowsUpdated @
" Elapsed Ms: " @ $BasicLightManagerStats::elapsedUpdateMs;
}
function lightMetricsCallback()
{
return " | Deferred Lights |" @
" Active: " @ $lightMetrics::activeLights @
" Culled: " @ $lightMetrics::culledLights;
}
function particleMetricsCallback()
{
return " | Particles |" @
" # Simulated " @ $particle::numSimulated;
}
function partMetricsCallback()
{
return particleMetricsCallback();
}
function imposterMetricsCallback()
{
return " | IMPOSTER |" @
" Rendered: " @ $ImposterStats::rendered @
" Batches: " @ $ImposterStats::batches @
" DrawCalls: " @ $ImposterStats::drawCalls @
" Polys: " @ $ImposterStats::polyCount @
" RtChanges: " @ $ImposterStats::rtChanges;
}
// alias
function audioMetricsCallback()
{
return sfxMetricsCallback();
}
// alias
function videoMetricsCallback()
{
return gfxMetricsCallback();
}
// Add a metrics HUD. %expr can be a vector of names where each element
// must have a corresponding '<name>MetricsCallback()' function defined
// that will be called on each update of the GUI control. The results
// of each function are stringed together.
//
// Example: metrics( "fps gfx" );
function metrics( %expr )
{
%metricsExpr = "";
if( %expr !$= "" )
{
for( %i = 0;; %i ++ )
{
%name = getWord( %expr, %i );
if( %name $= "" )
break;
else
{
%cb = %name @ "MetricsCallback";
if( !isFunction( %cb ) )
error( "metrics - undefined callback: " @ %cb );
else
{
%cb = %cb @ "()";
if( %i > 0 )
%metricsExpr = %metricsExpr @ " NL ";
%metricsExpr = %metricsExpr @ %cb;
}
}
}
if( %metricsExpr !$= "" )
%metricsExpr = %metricsExpr @ " @ \" \"";
}
if( %metricsExpr !$= "" )
{
$GameCanvas.pushDialog( FrameOverlayGui, 1000 );
TextOverlayControl.setValue( %metricsExpr );
}
else
$GameCanvas.popDialog(FrameOverlayGui);
}
| |
using System.Linq;
using System.Threading.Tasks;
using SfAttendance.Server.Entities;
using SfAttendance.Server.Services.Abstract;
using SfAttendance.Server.ViewModels.ManageViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace SfAttendance.Server.Controllers.api
{
[Authorize]
public class ManageController : BaseController
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
// Generate the token and send it
var user = await GetCurrentUserAsync();
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsTwillioAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return Challenge(properties, provider);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
#endregion
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Junit.Framework.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 Junit.Framework
{
/// <summary>
/// <para>A Listener for test progress </para>
/// </summary>
/// <java-name>
/// junit/framework/TestListener
/// </java-name>
[Dot42.DexImport("junit/framework/TestListener", AccessFlags = 1537)]
public partial interface ITestListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>An error occurred. </para>
/// </summary>
/// <java-name>
/// addError
/// </java-name>
[Dot42.DexImport("addError", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 1025)]
void AddError(global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>A failure occurred. </para>
/// </summary>
/// <java-name>
/// addFailure
/// </java-name>
[Dot42.DexImport("addFailure", "(Ljunit/framework/Test;Ljunit/framework/AssertionFailedError;)V", AccessFlags = 1025)]
void AddFailure(global::Junit.Framework.ITest test, global::Junit.Framework.AssertionFailedError t) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>A test ended. </para>
/// </summary>
/// <java-name>
/// endTest
/// </java-name>
[Dot42.DexImport("endTest", "(Ljunit/framework/Test;)V", AccessFlags = 1025)]
void EndTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>A test started. </para>
/// </summary>
/// <java-name>
/// startTest
/// </java-name>
[Dot42.DexImport("startTest", "(Ljunit/framework/Test;)V", AccessFlags = 1025)]
void StartTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Thrown when an assert equals for Strings failed.</para><para>Inspired by a patch from Alex Chaffee </para>
/// </summary>
/// <java-name>
/// junit/framework/ComparisonFailure
/// </java-name>
[Dot42.DexImport("junit/framework/ComparisonFailure", AccessFlags = 33)]
public partial class ComparisonFailure : global::Junit.Framework.AssertionFailedError
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a comparison failure. </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public ComparisonFailure(string message, string expected, string actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns "..." in place of common prefix and "..." in place of common suffix between expected and actual.</para><para><para>Throwable::getMessage() </para></para>
/// </summary>
/// <java-name>
/// getMessage
/// </java-name>
[Dot42.DexImport("getMessage", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMessage() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Gets the actual string value </para>
/// </summary>
/// <returns>
/// <para>the actual string value </para>
/// </returns>
/// <java-name>
/// getActual
/// </java-name>
[Dot42.DexImport("getActual", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetActual() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Gets the expected string value </para>
/// </summary>
/// <returns>
/// <para>the expected string value </para>
/// </returns>
/// <java-name>
/// getExpected
/// </java-name>
[Dot42.DexImport("getExpected", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetExpected() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ComparisonFailure() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Gets the actual string value </para>
/// </summary>
/// <returns>
/// <para>the actual string value </para>
/// </returns>
/// <java-name>
/// getActual
/// </java-name>
public string Actual
{
[Dot42.DexImport("getActual", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetActual(); }
}
/// <summary>
/// <para>Gets the expected string value </para>
/// </summary>
/// <returns>
/// <para>the expected string value </para>
/// </returns>
/// <java-name>
/// getExpected
/// </java-name>
public string Expected
{
[Dot42.DexImport("getExpected", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetExpected(); }
}
}
/// <summary>
/// <para>A test case defines the fixture to run multiple tests. To define a test case<br></br> <ol><li><para>implement a subclass of <code>TestCase</code> </para></li><li><para>define instance variables that store the state of the fixture </para></li><li><para>initialize the fixture state by overriding setUp() </para></li><li><para>clean-up after a test by overriding tearDown(). </para></li></ol>Each test runs in its own fixture so there can be no side effects among test runs. Here is an example: <pre>
/// public class MathTest extends TestCase {
/// protected double fValue1;
/// protected double fValue2;
///
/// protected void setUp() {
/// fValue1= 2.0;
/// fValue2= 3.0;
/// }
/// }
/// </pre></para><para>For each test implement a method which interacts with the fixture. Verify the expected results with assertions specified by calling junit.framework.Assert#assertTrue(String, boolean) with a boolean. <pre>
/// public void testAdd() {
/// double result= fValue1 + fValue2;
/// assertTrue(result == 5.0);
/// }
/// </pre></para><para>Once the methods are defined you can run them. The framework supports both a static type safe and more dynamic way to run a test. In the static way you override the runTest method and define the method to be invoked. A convenient way to do so is with an anonymous inner class. <pre>
/// TestCase test= new MathTest("add") {
/// public void runTest() {
/// testAdd();
/// }
/// };
/// test.run();
/// </pre></para><para>The dynamic way uses reflection to implement runTest(). It dynamically finds and invokes a method. In this case the name of the test case has to correspond to the test method to be run. <pre>
/// TestCase test= new MathTest("testAdd");
/// test.run();
/// </pre></para><para>The tests to be run can be collected into a TestSuite. JUnit provides different <b>test runners</b> which can run a test suite and collect the results. A test runner either expects a static method <code>suite</code> as the entry point to get a test to run or it will extract the suite automatically. <pre>
/// public static Test suite() {
/// suite.addTest(new MathTest("testAdd"));
/// suite.addTest(new MathTest("testDivideByZero"));
/// return suite;
/// }
/// </pre> <para>TestResult </para><simplesectsep></simplesectsep><para>TestSuite </para></para>
/// </summary>
/// <java-name>
/// junit/framework/TestCase
/// </java-name>
[Dot42.DexImport("junit/framework/TestCase", AccessFlags = 1057)]
public abstract partial class TestCase : global::Junit.Framework.Assert, global::Junit.Framework.ITest
/* scope: __dot42__ */
{
/// <summary>
/// <para>No-arg constructor to enable serialization. This method is not intended to be used by mere mortals without calling setName(). </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public TestCase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a test case with the given name. </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public TestCase(string name) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Counts the number of test cases executed by run(TestResult result). </para>
/// </summary>
/// <java-name>
/// countTestCases
/// </java-name>
[Dot42.DexImport("countTestCases", "()I", AccessFlags = 1)]
public virtual int CountTestCases() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Creates a default TestResult object</para><para><para>TestResult </para></para>
/// </summary>
/// <java-name>
/// createResult
/// </java-name>
[Dot42.DexImport("createResult", "()Ljunit/framework/TestResult;", AccessFlags = 4)]
protected internal virtual global::Junit.Framework.TestResult CreateResult() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.TestResult);
}
/// <summary>
/// <para>A convenience method to run this test, collecting the results with a default TestResult object.</para><para><para>TestResult </para></para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "()Ljunit/framework/TestResult;", AccessFlags = 1)]
public virtual global::Junit.Framework.TestResult Run() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.TestResult);
}
/// <summary>
/// <para>Runs the test case and collects the results in TestResult. </para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "(Ljunit/framework/TestResult;)V", AccessFlags = 1)]
public virtual void Run(global::Junit.Framework.TestResult result) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Runs the bare test sequence. </para>
/// </summary>
/// <java-name>
/// runBare
/// </java-name>
[Dot42.DexImport("runBare", "()V", AccessFlags = 1)]
public virtual void RunBare() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Override to run the test and assert its state. </para>
/// </summary>
/// <java-name>
/// runTest
/// </java-name>
[Dot42.DexImport("runTest", "()V", AccessFlags = 4)]
protected internal virtual void RunTest() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets up the fixture, for example, open a network connection. This method is called before a test is executed. </para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal virtual void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tears down the fixture, for example, close a network connection. This method is called after a test is executed. </para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal virtual void TearDown() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns a string representation of the test case </para>
/// </summary>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Gets the name of a TestCase </para>
/// </summary>
/// <returns>
/// <para>the name of the TestCase </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Sets the name of a TestCase </para>
/// </summary>
/// <java-name>
/// setName
/// </java-name>
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetName(string name) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the name of a TestCase </para>
/// </summary>
/// <returns>
/// <para>the name of the TestCase </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
public string Name
{
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetName(); }
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetName(value); }
}
}
/// <summary>
/// <para>A set of assert methods. Messages are only displayed when an assert fails. </para>
/// </summary>
/// <java-name>
/// junit/framework/Assert
/// </java-name>
[Dot42.DexImport("junit/framework/Assert", AccessFlags = 33)]
public partial class Assert
/* scope: __dot42__ */
{
/// <summary>
/// <para>Protect constructor since it is a static only class </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal Assert() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that a condition is true. If it isn't it throws an AssertionFailedError with the given message. </para>
/// </summary>
/// <java-name>
/// assertTrue
/// </java-name>
[Dot42.DexImport("assertTrue", "(Ljava/lang/String;Z)V", AccessFlags = 9)]
public static void AssertTrue(string message, bool condition) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that a condition is true. If it isn't it throws an AssertionFailedError. </para>
/// </summary>
/// <java-name>
/// assertTrue
/// </java-name>
[Dot42.DexImport("assertTrue", "(Z)V", AccessFlags = 9)]
public static void AssertTrue(bool condition) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that a condition is false. If it isn't it throws an AssertionFailedError with the given message. </para>
/// </summary>
/// <java-name>
/// assertFalse
/// </java-name>
[Dot42.DexImport("assertFalse", "(Ljava/lang/String;Z)V", AccessFlags = 9)]
public static void AssertFalse(string message, bool condition) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that a condition is false. If it isn't it throws an AssertionFailedError. </para>
/// </summary>
/// <java-name>
/// assertFalse
/// </java-name>
[Dot42.DexImport("assertFalse", "(Z)V", AccessFlags = 9)]
public static void AssertFalse(bool condition) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Fails a test with the given message. </para>
/// </summary>
/// <java-name>
/// fail
/// </java-name>
[Dot42.DexImport("fail", "(Ljava/lang/String;)V", AccessFlags = 9)]
public static void Fail(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Fails a test with no message. </para>
/// </summary>
/// <java-name>
/// fail
/// </java-name>
[Dot42.DexImport("fail", "()V", AccessFlags = 9)]
public static void Fail() /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertEquals(string @string, object @object, object object1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertEquals(object expected, object actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 9)]
public static void AssertEquals(string @string, string string1, string string2) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 9)]
public static void AssertEquals(string expected, string actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;DDD)V", AccessFlags = 9)]
public static void AssertEquals(string @string, double @double, double double1, double double2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(DDD)V", AccessFlags = 9)]
public static void AssertEquals(double @double, double double1, double double2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;FFF)V", AccessFlags = 9)]
public static void AssertEquals(string @string, float single, float single1, float single2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(FFF)V", AccessFlags = 9)]
public static void AssertEquals(float single, float single1, float single2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;JJ)V", AccessFlags = 9)]
public static void AssertEquals(string @string, long int64, long int641) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(JJ)V", AccessFlags = 9)]
public static void AssertEquals(long expected, long actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;ZZ)V", AccessFlags = 9)]
public static void AssertEquals(string @string, bool boolean, bool boolean1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(ZZ)V", AccessFlags = 9)]
public static void AssertEquals(bool expected, bool actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;BB)V", AccessFlags = 9)]
public static void AssertEquals(string @string, sbyte sByte, sbyte sByte1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;BB)V", AccessFlags = 9, IgnoreFromJava = true)]
public static void AssertEquals(string @string, byte @byte, byte byte1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(BB)V", AccessFlags = 9)]
public static void AssertEquals(sbyte expected, sbyte actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(BB)V", AccessFlags = 9, IgnoreFromJava = true)]
public static void AssertEquals(byte expected, byte actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;CC)V", AccessFlags = 9)]
public static void AssertEquals(string @string, char @char, char char1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(CC)V", AccessFlags = 9)]
public static void AssertEquals(char expected, char actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;SS)V", AccessFlags = 9)]
public static void AssertEquals(string @string, short int16, short int161) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(SS)V", AccessFlags = 9)]
public static void AssertEquals(short expected, short actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;II)V", AccessFlags = 9)]
public static void AssertEquals(string @string, int int32, int int321) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(II)V", AccessFlags = 9)]
public static void AssertEquals(int expected, int actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that an object isn't null. </para>
/// </summary>
/// <java-name>
/// assertNotNull
/// </java-name>
[Dot42.DexImport("assertNotNull", "(Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotNull(object @object) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that an object isn't null. If it is an AssertionFailedError is thrown with the given message. </para>
/// </summary>
/// <java-name>
/// assertNotNull
/// </java-name>
[Dot42.DexImport("assertNotNull", "(Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotNull(string message, object @object) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that an object is null. If it isn't an AssertionError is thrown. Message contains: Expected: <null> but was: object</para><para></para>
/// </summary>
/// <java-name>
/// assertNull
/// </java-name>
[Dot42.DexImport("assertNull", "(Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNull(object @object) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that an object is null. If it is not an AssertionFailedError is thrown with the given message. </para>
/// </summary>
/// <java-name>
/// assertNull
/// </java-name>
[Dot42.DexImport("assertNull", "(Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNull(string message, object @object) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two objects refer to the same object. If they are not an AssertionFailedError is thrown with the given message. </para>
/// </summary>
/// <java-name>
/// assertSame
/// </java-name>
[Dot42.DexImport("assertSame", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertSame(string message, object expected, object actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two objects refer to the same object. If they are not the same an AssertionFailedError is thrown. </para>
/// </summary>
/// <java-name>
/// assertSame
/// </java-name>
[Dot42.DexImport("assertSame", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertSame(object expected, object actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two objects do not refer to the same object. If they do refer to the same object an AssertionFailedError is thrown with the given message. </para>
/// </summary>
/// <java-name>
/// assertNotSame
/// </java-name>
[Dot42.DexImport("assertNotSame", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotSame(string message, object expected, object actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two objects do not refer to the same object. If they do refer to the same object an AssertionFailedError is thrown. </para>
/// </summary>
/// <java-name>
/// assertNotSame
/// </java-name>
[Dot42.DexImport("assertNotSame", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotSame(object expected, object actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// failSame
/// </java-name>
[Dot42.DexImport("failSame", "(Ljava/lang/String;)V", AccessFlags = 9)]
public static void FailSame(string message) /* MethodBuilder.Create */
{
}
/// <java-name>
/// failNotSame
/// </java-name>
[Dot42.DexImport("failNotSame", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void FailNotSame(string message, object expected, object actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// failNotEquals
/// </java-name>
[Dot42.DexImport("failNotEquals", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void FailNotEquals(string message, object expected, object actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// format
/// </java-name>
[Dot42.DexImport("format", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/String;", AccessFlags = 9)]
public static string Format(string message, object expected, object actual) /* MethodBuilder.Create */
{
return default(string);
}
}
/// <summary>
/// <para>Thrown when an assertion failed. </para>
/// </summary>
/// <java-name>
/// junit/framework/AssertionFailedError
/// </java-name>
[Dot42.DexImport("junit/framework/AssertionFailedError", AccessFlags = 33)]
public partial class AssertionFailedError : global::Java.Lang.AssertionError
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public AssertionFailedError() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public AssertionFailedError(string message) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>A <b>Protectable</b> can be run and can throw a Throwable.</para><para><para>TestResult </para></para>
/// </summary>
/// <java-name>
/// junit/framework/Protectable
/// </java-name>
[Dot42.DexImport("junit/framework/Protectable", AccessFlags = 1537)]
public partial interface IProtectable
/* scope: __dot42__ */
{
/// <summary>
/// <para>Run the the following method protected. </para>
/// </summary>
/// <java-name>
/// protect
/// </java-name>
[Dot42.DexImport("protect", "()V", AccessFlags = 1025)]
void Protect() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>A <code>TestFailure</code> collects a failed test together with the caught exception. <para>TestResult </para></para>
/// </summary>
/// <java-name>
/// junit/framework/TestFailure
/// </java-name>
[Dot42.DexImport("junit/framework/TestFailure", AccessFlags = 33)]
public partial class TestFailure
/* scope: __dot42__ */
{
/// <java-name>
/// fFailedTest
/// </java-name>
[Dot42.DexImport("fFailedTest", "Ljunit/framework/Test;", AccessFlags = 4)]
protected internal global::Junit.Framework.ITest FFailedTest;
/// <java-name>
/// fThrownException
/// </java-name>
[Dot42.DexImport("fThrownException", "Ljava/lang/Throwable;", AccessFlags = 4)]
protected internal global::System.Exception FThrownException;
/// <summary>
/// <para>Constructs a TestFailure with the given test and exception. </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public TestFailure(global::Junit.Framework.ITest failedTest, global::System.Exception thrownException) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the failed test. </para>
/// </summary>
/// <java-name>
/// failedTest
/// </java-name>
[Dot42.DexImport("failedTest", "()Ljunit/framework/Test;", AccessFlags = 1)]
public virtual global::Junit.Framework.ITest FailedTest() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.ITest);
}
/// <summary>
/// <para>Gets the thrown exception. </para>
/// </summary>
/// <java-name>
/// thrownException
/// </java-name>
[Dot42.DexImport("thrownException", "()Ljava/lang/Throwable;", AccessFlags = 1)]
public virtual global::System.Exception ThrownException() /* MethodBuilder.Create */
{
return default(global::System.Exception);
}
/// <summary>
/// <para>Returns a short description of the failure. </para>
/// </summary>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// trace
/// </java-name>
[Dot42.DexImport("trace", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string Trace() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// exceptionMessage
/// </java-name>
[Dot42.DexImport("exceptionMessage", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string ExceptionMessage() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// isFailure
/// </java-name>
[Dot42.DexImport("isFailure", "()Z", AccessFlags = 1)]
public virtual bool IsFailure() /* MethodBuilder.Create */
{
return default(bool);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal TestFailure() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>A <b>Test</b> can be run and collect its results.</para><para><para>TestResult </para></para>
/// </summary>
/// <java-name>
/// junit/framework/Test
/// </java-name>
[Dot42.DexImport("junit/framework/Test", AccessFlags = 1537)]
public partial interface ITest
/* scope: __dot42__ */
{
/// <summary>
/// <para>Counts the number of test cases that will be run by this test. </para>
/// </summary>
/// <java-name>
/// countTestCases
/// </java-name>
[Dot42.DexImport("countTestCases", "()I", AccessFlags = 1025)]
int CountTestCases() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Runs a test and collects its result in a TestResult instance. </para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "(Ljunit/framework/TestResult;)V", AccessFlags = 1025)]
void Run(global::Junit.Framework.TestResult result) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>A <code>TestResult</code> collects the results of executing a test case. It is an instance of the Collecting Parameter pattern. The test framework distinguishes between <b>failures</b> and <b>errors</b>. A failure is anticipated and checked for with assertions. Errors are unanticipated problems like an ArrayIndexOutOfBoundsException.</para><para><para>Test </para></para>
/// </summary>
/// <java-name>
/// junit/framework/TestResult
/// </java-name>
[Dot42.DexImport("junit/framework/TestResult", AccessFlags = 33)]
public partial class TestResult
/* scope: __dot42__ */
{
/// <java-name>
/// fFailures
/// </java-name>
[Dot42.DexImport("fFailures", "Ljava/util/Vector;", AccessFlags = 4)]
protected internal global::Java.Util.Vector<global::Junit.Framework.TestFailure> FFailures;
/// <java-name>
/// fErrors
/// </java-name>
[Dot42.DexImport("fErrors", "Ljava/util/Vector;", AccessFlags = 4)]
protected internal global::Java.Util.Vector<global::Junit.Framework.TestFailure> FErrors;
/// <java-name>
/// fListeners
/// </java-name>
[Dot42.DexImport("fListeners", "Ljava/util/Vector;", AccessFlags = 4)]
protected internal global::Java.Util.Vector<global::Junit.Framework.ITestListener> FListeners;
/// <java-name>
/// fRunTests
/// </java-name>
[Dot42.DexImport("fRunTests", "I", AccessFlags = 4)]
protected internal int FRunTests;
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public TestResult() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Adds an error to the list of errors. The passed in exception caused the error. </para>
/// </summary>
/// <java-name>
/// addError
/// </java-name>
[Dot42.DexImport("addError", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 33)]
public virtual void AddError(global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Adds a failure to the list of failures. The passed in exception caused the failure. </para>
/// </summary>
/// <java-name>
/// addFailure
/// </java-name>
[Dot42.DexImport("addFailure", "(Ljunit/framework/Test;Ljunit/framework/AssertionFailedError;)V", AccessFlags = 33)]
public virtual void AddFailure(global::Junit.Framework.ITest test, global::Junit.Framework.AssertionFailedError t) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Registers a TestListener </para>
/// </summary>
/// <java-name>
/// addListener
/// </java-name>
[Dot42.DexImport("addListener", "(Ljunit/framework/TestListener;)V", AccessFlags = 33)]
public virtual void AddListener(global::Junit.Framework.ITestListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Unregisters a TestListener </para>
/// </summary>
/// <java-name>
/// removeListener
/// </java-name>
[Dot42.DexImport("removeListener", "(Ljunit/framework/TestListener;)V", AccessFlags = 33)]
public virtual void RemoveListener(global::Junit.Framework.ITestListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Informs the result that a test was completed. </para>
/// </summary>
/// <java-name>
/// endTest
/// </java-name>
[Dot42.DexImport("endTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)]
public virtual void EndTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the number of detected errors. </para>
/// </summary>
/// <java-name>
/// errorCount
/// </java-name>
[Dot42.DexImport("errorCount", "()I", AccessFlags = 33)]
public virtual int ErrorCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns an Enumeration for the errors </para>
/// </summary>
/// <java-name>
/// errors
/// </java-name>
[Dot42.DexImport("errors", "()Ljava/util/Enumeration;", AccessFlags = 33, Signature = "()Ljava/util/Enumeration<Ljunit/framework/TestFailure;>;")]
public virtual global::Java.Util.IEnumeration<global::Junit.Framework.TestFailure> Errors() /* MethodBuilder.Create */
{
return default(global::Java.Util.IEnumeration<global::Junit.Framework.TestFailure>);
}
/// <summary>
/// <para>Gets the number of detected failures. </para>
/// </summary>
/// <java-name>
/// failureCount
/// </java-name>
[Dot42.DexImport("failureCount", "()I", AccessFlags = 33)]
public virtual int FailureCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns an Enumeration for the failures </para>
/// </summary>
/// <java-name>
/// failures
/// </java-name>
[Dot42.DexImport("failures", "()Ljava/util/Enumeration;", AccessFlags = 33, Signature = "()Ljava/util/Enumeration<Ljunit/framework/TestFailure;>;")]
public virtual global::Java.Util.IEnumeration<global::Junit.Framework.TestFailure> Failures() /* MethodBuilder.Create */
{
return default(global::Java.Util.IEnumeration<global::Junit.Framework.TestFailure>);
}
/// <summary>
/// <para>Runs a TestCase. </para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "(Ljunit/framework/TestCase;)V", AccessFlags = 4)]
protected internal virtual void Run(global::Junit.Framework.TestCase test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the number of run tests. </para>
/// </summary>
/// <java-name>
/// runCount
/// </java-name>
[Dot42.DexImport("runCount", "()I", AccessFlags = 33)]
public virtual int RunCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Runs a TestCase. </para>
/// </summary>
/// <java-name>
/// runProtected
/// </java-name>
[Dot42.DexImport("runProtected", "(Ljunit/framework/Test;Ljunit/framework/Protectable;)V", AccessFlags = 1)]
public virtual void RunProtected(global::Junit.Framework.ITest test, global::Junit.Framework.IProtectable p) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Checks whether the test run should stop </para>
/// </summary>
/// <java-name>
/// shouldStop
/// </java-name>
[Dot42.DexImport("shouldStop", "()Z", AccessFlags = 33)]
public virtual bool ShouldStop() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Informs the result that a test will be started. </para>
/// </summary>
/// <java-name>
/// startTest
/// </java-name>
[Dot42.DexImport("startTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)]
public virtual void StartTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Marks that the test run should stop. </para>
/// </summary>
/// <java-name>
/// stop
/// </java-name>
[Dot42.DexImport("stop", "()V", AccessFlags = 33)]
public virtual void Stop() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns whether the entire test was successful or not. </para>
/// </summary>
/// <java-name>
/// wasSuccessful
/// </java-name>
[Dot42.DexImport("wasSuccessful", "()Z", AccessFlags = 33)]
public virtual bool WasSuccessful() /* MethodBuilder.Create */
{
return default(bool);
}
}
/// <summary>
/// <para>A <code>TestSuite</code> is a <code>Composite</code> of Tests. It runs a collection of test cases. Here is an example using the dynamic test definition. <pre>
/// TestSuite suite= new TestSuite();
/// suite.addTest(new MathTest("testAdd"));
/// suite.addTest(new MathTest("testDivideByZero"));
/// </pre> </para><para>Alternatively, a TestSuite can extract the tests to be run automatically. To do so you pass the class of your TestCase class to the TestSuite constructor. <pre>
/// TestSuite suite= new TestSuite(MathTest.class);
/// </pre> </para><para>This constructor creates a suite with all the methods starting with "test" that take no arguments.</para><para>A final option is to do the same for a large array of test classes. <pre>
/// Class[] testClasses = { MathTest.class, AnotherTest.class }
/// TestSuite suite= new TestSuite(testClasses);
/// </pre> </para><para><para>Test </para></para>
/// </summary>
/// <java-name>
/// junit/framework/TestSuite
/// </java-name>
[Dot42.DexImport("junit/framework/TestSuite", AccessFlags = 33)]
public partial class TestSuite : global::Junit.Framework.ITest
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs an empty TestSuite. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public TestSuite() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/Class;)V", AccessFlags = 1, Signature = "(Ljava/lang/Class<*>;)V")]
public TestSuite(global::System.Type type) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/Class;Ljava/lang/String;)V", AccessFlags = 1, Signature = "(Ljava/lang/Class<+Ljunit/framework/TestCase;>;Ljava/lang/String;)V")]
public TestSuite(global::System.Type type, string @string) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public TestSuite(string @string) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "([Ljava/lang/Class;)V", AccessFlags = 129, Signature = "([Ljava/lang/Class<*>;)V")]
public TestSuite(params global::System.Type[] type) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "([Ljava/lang/Class;Ljava/lang/String;)V", AccessFlags = 1, Signature = "([Ljava/lang/Class<+Ljunit/framework/TestCase;>;Ljava/lang/String;)V")]
public TestSuite(global::System.Type[] type, string @string) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>...as the moon sets over the early morning Merlin, Oregon mountains, our intrepid adventurers type... </para>
/// </summary>
/// <java-name>
/// createTest
/// </java-name>
[Dot42.DexImport("createTest", "(Ljava/lang/Class;Ljava/lang/String;)Ljunit/framework/Test;", AccessFlags = 9, Signature = "(Ljava/lang/Class<*>;Ljava/lang/String;)Ljunit/framework/Test;")]
public static global::Junit.Framework.ITest CreateTest(global::System.Type theClass, string name) /* MethodBuilder.Create */
{
return default(global::Junit.Framework.ITest);
}
/// <summary>
/// <para>Gets a constructor which takes a single String as its argument or a no arg constructor. </para>
/// </summary>
/// <java-name>
/// getTestConstructor
/// </java-name>
[Dot42.DexImport("getTestConstructor", "(Ljava/lang/Class;)Ljava/lang/reflect/Constructor;", AccessFlags = 9, Signature = "(Ljava/lang/Class<*>;)Ljava/lang/reflect/Constructor<*>;")]
public static global::System.Reflection.ConstructorInfo GetTestConstructor(global::System.Type theClass) /* MethodBuilder.Create */
{
return default(global::System.Reflection.ConstructorInfo);
}
/// <summary>
/// <para>Returns a test which will fail and log a warning message. </para>
/// </summary>
/// <java-name>
/// warning
/// </java-name>
[Dot42.DexImport("warning", "(Ljava/lang/String;)Ljunit/framework/Test;", AccessFlags = 9)]
public static global::Junit.Framework.ITest Warning(string message) /* MethodBuilder.Create */
{
return default(global::Junit.Framework.ITest);
}
/// <summary>
/// <para>Adds a test to the suite. </para>
/// </summary>
/// <java-name>
/// addTest
/// </java-name>
[Dot42.DexImport("addTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)]
public virtual void AddTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Adds the tests from the given class to the suite </para>
/// </summary>
/// <java-name>
/// addTestSuite
/// </java-name>
[Dot42.DexImport("addTestSuite", "(Ljava/lang/Class;)V", AccessFlags = 1, Signature = "(Ljava/lang/Class<+Ljunit/framework/TestCase;>;)V")]
public virtual void AddTestSuite(global::System.Type testClass) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Counts the number of test cases that will be run by this test. </para>
/// </summary>
/// <java-name>
/// countTestCases
/// </java-name>
[Dot42.DexImport("countTestCases", "()I", AccessFlags = 1)]
public virtual int CountTestCases() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns the name of the suite. Not all test suites have a name and this method can return null. </para>
/// </summary>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Runs the tests and collects their result in a TestResult. </para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "(Ljunit/framework/TestResult;)V", AccessFlags = 1)]
public virtual void Run(global::Junit.Framework.TestResult result) /* MethodBuilder.Create */
{
}
/// <java-name>
/// runTest
/// </java-name>
[Dot42.DexImport("runTest", "(Ljunit/framework/Test;Ljunit/framework/TestResult;)V", AccessFlags = 1)]
public virtual void RunTest(global::Junit.Framework.ITest test, global::Junit.Framework.TestResult result) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets the name of the suite. </para>
/// </summary>
/// <java-name>
/// setName
/// </java-name>
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetName(string name) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the test at the given index </para>
/// </summary>
/// <java-name>
/// testAt
/// </java-name>
[Dot42.DexImport("testAt", "(I)Ljunit/framework/Test;", AccessFlags = 1)]
public virtual global::Junit.Framework.ITest TestAt(int index) /* MethodBuilder.Create */
{
return default(global::Junit.Framework.ITest);
}
/// <summary>
/// <para>Returns the number of tests in this suite </para>
/// </summary>
/// <java-name>
/// testCount
/// </java-name>
[Dot42.DexImport("testCount", "()I", AccessFlags = 1)]
public virtual int TestCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns the tests as an enumeration </para>
/// </summary>
/// <java-name>
/// tests
/// </java-name>
[Dot42.DexImport("tests", "()Ljava/util/Enumeration;", AccessFlags = 1, Signature = "()Ljava/util/Enumeration<Ljunit/framework/Test;>;")]
public virtual global::Java.Util.IEnumeration<global::Junit.Framework.ITest> Tests() /* MethodBuilder.Create */
{
return default(global::Java.Util.IEnumeration<global::Junit.Framework.ITest>);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the name of the suite. Not all test suites have a name and this method can return null. </para>
/// </summary>
/// <java-name>
/// getName
/// </java-name>
public string Name
{
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetName(); }
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetName(value); }
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. 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.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapAttributeSet.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
namespace Novell.Directory.Ldap
{
/// <summary>
/// A set of {@link LdapAttribute} objects.
///
/// An <code>LdapAttributeSet</code> is a collection of <code>LdapAttribute</code>
/// classes as returned from an <code>LdapEntry</code> on a search or read
/// operation. <code>LdapAttributeSet</code> may be also used to contruct an entry
/// to be added to a directory. If the <code>add()</code> or <code>addAll()</code>
/// methods are called and one or more of the objects to be added is not
/// an <code>LdapAttribute, ClassCastException</code> is thrown (as discussed in the
/// documentation for <code>java.util.Collection</code>).
///
///
/// </summary>
/// <seealso cref="LdapAttribute">
/// </seealso>
/// <seealso cref="LdapEntry">
/// </seealso>
public class LdapAttributeSet : SupportClass.AbstractSetSupport//, SupportClass.SetSupport
{
/// <summary> Returns the number of attributes in this set.
///
/// </summary>
/// <returns> number of attributes in this set.
/// </returns>
public override int Count
{
get
{
return map.Count;
}
}
/// <summary> This is the underlying data structure for this set.
/// HashSet is similar to the functionality of this set. The difference
/// is we use the name of an attribute as keys in the Map and LdapAttributes
/// as the values. We also do not declare the map as transient, making the
/// map serializable.
/// </summary>
private System.Collections.Hashtable map;
/// <summary> Constructs an empty set of attributes.</summary>
public LdapAttributeSet() : base()
{
map = new System.Collections.Hashtable();
}
// --- methods not defined in Set ---
/// <summary> Returns a deep copy of this attribute set.
///
/// </summary>
/// <returns> A deep copy of this attribute set.
/// </returns>
public override object Clone()
{
try
{
object newObj = MemberwiseClone();
System.Collections.IEnumerator i = GetEnumerator();
while (i.MoveNext())
{
((LdapAttributeSet)newObj).Add(((LdapAttribute)i.Current).Clone());
}
return newObj;
}
catch (Exception ce)
{
throw new Exception("Internal error, cannot create clone");
}
}
/// <summary> Returns the attribute matching the specified attrName.
///
/// For example:
/// <ul>
/// <li><code>getAttribute("cn")</code> returns only the "cn" attribute</li>
/// <li><code>getAttribute("cn;lang-en")</code> returns only the "cn;lang-en"
/// attribute.</li>
/// </ul>
/// In both cases, <code>null</code> is returned if there is no exact match to
/// the specified attrName.
///
/// Note: Novell eDirectory does not currently support language subtypes.
/// It does support the "binary" subtype.
///
/// </summary>
/// <param name="attrName"> The name of an attribute to retrieve, with or without
/// subtype specifications. For example, "cn", "cn;phonetic", and
/// "cn;binary" are valid attribute names.
///
/// </param>
/// <returns> The attribute matching the specified attrName, or <code>null</code>
/// if there is no exact match.
/// </returns>
public virtual LdapAttribute getAttribute(string attrName)
{
return (LdapAttribute)map[attrName.ToUpper()];
}
/// <summary> Returns a single best-match attribute, or <code>null</code> if no match is
/// available in the entry.
///
/// Ldap version 3 allows adding a subtype specification to an attribute
/// name. For example, "cn;lang-ja" indicates a Japanese language
/// subtype of the "cn" attribute and "cn;lang-ja-JP-kanji" may be a subtype
/// of "cn;lang-ja". This feature may be used to provide multiple
/// localizations in the same directory. For attributes which do not vary
/// among localizations, only the base attribute may be stored, whereas
/// for others there may be varying degrees of specialization.
///
/// For example, <code>getAttribute(attrName,lang)</code> returns the
/// <code>LdapAttribute</code> that exactly matches attrName and that
/// best matches lang.
///
/// If there are subtypes other than "lang" subtypes included
/// in attrName, for example, "cn;binary", only attributes with all of
/// those subtypes are returned. If lang is <code>null</code> or empty, the
/// method behaves as getAttribute(attrName). If there are no matching
/// attributes, <code>null</code> is returned.
///
///
/// Assume the entry contains only the following attributes:
///
/// <ul>
/// <li>cn;lang-en</li>
/// <li>cn;lang-ja-JP-kanji</li>
/// <li>sn</li>
/// </ul>
///
/// Examples:
/// <ul>
/// <li><code>getAttribute( "cn" )</code> returns <code>null</code>.</li>
/// <li><code>getAttribute( "sn" )</code> returns the "sn" attribute.</li>
/// <li><code>getAttribute( "cn", "lang-en-us" )</code>
/// returns the "cn;lang-en" attribute.</li>
/// <li><code>getAttribute( "cn", "lang-en" )</code>
/// returns the "cn;lang-en" attribute.</li>
/// <li><code>getAttribute( "cn", "lang-ja" )</code>
/// returns <code>null</code>.</li>
/// <li><code>getAttribute( "sn", "lang-en" )</code>
/// returns the "sn" attribute.</li>
/// </ul>
///
/// Note: Novell eDirectory does not currently support language subtypes.
/// It does support the "binary" subtype.
///
/// </summary>
/// <param name="attrName"> The name of an attribute to retrieve, with or without
/// subtype specifications. For example, "cn", "cn;phonetic", and
/// cn;binary" are valid attribute names.
///
/// </param>
/// <param name="lang"> A language specification with optional subtypes
/// appended using "-" as separator. For example, "lang-en", "lang-en-us",
/// "lang-ja", and "lang-ja-JP-kanji" are valid language specification.
///
/// </param>
/// <returns> A single best-match <code>LdapAttribute</code>, or <code>null</code>
/// if no match is found in the entry.
///
/// </returns>
public virtual LdapAttribute getAttribute(string attrName, string lang)
{
string key = attrName + ";" + lang;
return (LdapAttribute)map[key.ToUpper()];
}
/// <summary> Creates a new attribute set containing only the attributes that have
/// the specified subtypes.
///
/// For example, suppose an attribute set contains the following
/// attributes:
///
/// <ul>
/// <li> cn</li>
/// <li> cn;lang-ja</li>
/// <li> sn;phonetic;lang-ja</li>
/// <li> sn;lang-us</li>
/// </ul>
///
/// Calling the <code>getSubset</code> method and passing lang-ja as the
/// argument, the method returns an attribute set containing the following
/// attributes:
///
/// <ul>
/// <li>cn;lang-ja</li>
/// <li>sn;phonetic;lang-ja</li>
/// </ul>
///
/// </summary>
/// <param name="subtype"> Semi-colon delimited list of subtypes to include. For
/// example:
/// <ul>
/// <li> "lang-ja" specifies only Japanese language subtypes</li>
/// <li> "binary" specifies only binary subtypes</li>
/// <li> "binary;lang-ja" specifies only Japanese language subtypes
/// which also are binary</li>
/// </ul>
///
/// Note: Novell eDirectory does not currently support language subtypes.
/// It does support the "binary" subtype.
///
/// </param>
/// <returns> An attribute set containing the attributes that match the
/// specified subtype.
/// </returns>
public virtual LdapAttributeSet getSubset(string subtype)
{
// Create a new tempAttributeSet
LdapAttributeSet tempAttributeSet = new LdapAttributeSet();
System.Collections.IEnumerator i = GetEnumerator();
// Cycle throught this.attributeSet
while (i.MoveNext())
{
LdapAttribute attr = (LdapAttribute)i.Current;
// Does this attribute have the subtype we are looking for. If
// yes then add it to our AttributeSet, else next attribute
if (attr.hasSubtype(subtype))
tempAttributeSet.Add(attr.Clone());
}
return tempAttributeSet;
}
// --- methods defined in set ---
/// <summary> Returns an iterator over the attributes in this set. The attributes
/// returned from this iterator are not in any particular order.
///
/// </summary>
/// <returns> iterator over the attributes in this set
/// </returns>
public override System.Collections.IEnumerator GetEnumerator()
{
return map.Values.GetEnumerator();
}
/// <summary> Returns <code>true</code> if this set contains no elements
///
/// </summary>
/// <returns> <code>true</code> if this set contains no elements
/// </returns>
public override bool IsEmpty()
{
return (map.Count == 0);
}
/// <summary> Returns <code>true</code> if this set contains an attribute of the same name
/// as the specified attribute.
///
/// </summary>
/// <param name="attr"> Object of type <code>LdapAttribute</code>
///
/// </param>
/// <returns> true if this set contains the specified attribute
///
/// @throws ClassCastException occurs the specified Object
/// is not of type LdapAttribute.
/// </returns>
public override bool Contains(object attr)
{
LdapAttribute attribute = (LdapAttribute)attr;
return map.ContainsKey(attribute.Name.ToUpper());
}
/// <summary> Adds the specified attribute to this set if it is not already present.
/// If an attribute with the same name already exists in the set then the
/// specified attribute will not be added.
///
/// </summary>
/// <param name="attr"> Object of type <code>LdapAttribute</code>
///
/// </param>
/// <returns> true if the attribute was added.
///
/// @throws ClassCastException occurs the specified Object
/// is not of type <code>LdapAttribute</code>.
/// </returns>
public override bool Add(object attr)
{
//We must enforce that attr is an LdapAttribute
LdapAttribute attribute = (LdapAttribute)attr;
string name = attribute.Name.ToUpper();
if (map.ContainsKey(name))
return false;
SupportClass.PutElement(map, name, attribute);
return true;
}
/// <summary> Removes the specified object from this set if it is present.
///
/// If the specified object is of type <code>LdapAttribute</code>, the
/// specified attribute will be removed. If the specified object is of type
/// <code>String</code>, the attribute with a name that matches the string will
/// be removed.
///
/// </summary>
/// <param name="object">LdapAttribute to be removed or <code>String</code> naming
/// the attribute to be removed.
///
/// </param>
/// <returns> true if the object was removed.
///
/// @throws ClassCastException occurs the specified Object
/// is not of type <code>LdapAttribute</code> or of type <code>String</code>.
/// </returns>
public override bool Remove(object object_Renamed)
{
string attributeName; //the name is the key to object in the HashMap
if (object_Renamed is string)
{
attributeName = ((string)object_Renamed);
}
else
{
attributeName = ((LdapAttribute)object_Renamed).Name;
}
if ((object)attributeName == null)
{
return false;
}
return (SupportClass.HashtableRemove(map, attributeName.ToUpper()) != null);
}
/// <summary> Removes all of the elements from this set.</summary>
public override void Clear()
{
map.Clear();
}
/// <summary> Adds all <code>LdapAttribute</code> objects in the specified collection to
/// this collection.
///
/// </summary>
/// <param name="c"> Collection of <code>LdapAttribute</code> objects.
///
/// @throws ClassCastException occurs when an element in the
/// collection is not of type <code>LdapAttribute</code>.
///
/// </param>
/// <returns> true if this set changed as a result of the call.
/// </returns>
public override bool AddAll(System.Collections.ICollection c)
{
bool setChanged = false;
System.Collections.IEnumerator i = c.GetEnumerator();
while (i.MoveNext())
{
// we must enforce that everything in c is an LdapAttribute
// add will return true if the attribute was added
if (Add(i.Current))
{
setChanged = true;
}
}
return setChanged;
}
/// <summary> Returns a string representation of this LdapAttributeSet
///
/// </summary>
/// <returns> a string representation of this LdapAttributeSet
/// </returns>
public override string ToString()
{
System.Text.StringBuilder retValue = new System.Text.StringBuilder("LdapAttributeSet: ");
System.Collections.IEnumerator attrs = GetEnumerator();
bool first = true;
while (attrs.MoveNext())
{
if (!first)
{
retValue.Append(" ");
}
first = false;
LdapAttribute attr = (LdapAttribute)attrs.Current;
retValue.Append(attr.ToString());
}
return retValue.ToString();
}
}
}
| |
using System;
using System.Buffers.Binary;
using System.IO;
using SharpCompress.Crypto;
using SharpCompress.IO;
namespace SharpCompress.Compressors.LZMA
{
// TODO:
// - Write as well as read
// - Multi-volume support
// - Use of the data size / member size values at the end of the stream
/// <summary>
/// Stream supporting the LZIP format, as documented at http://www.nongnu.org/lzip/manual/lzip_manual.html
/// </summary>
public sealed class LZipStream : Stream
{
private readonly Stream _stream;
private readonly CountingWritableSubStream? _countingWritableSubStream;
private bool _disposed;
private bool _finished;
private long _writeCount;
public LZipStream(Stream stream, CompressionMode mode)
{
Mode = mode;
if (mode == CompressionMode.Decompress)
{
int dSize = ValidateAndReadSize(stream);
if (dSize == 0)
{
throw new IOException("Not an LZip stream");
}
byte[] properties = GetProperties(dSize);
_stream = new LzmaStream(properties, stream);
}
else
{
//default
int dSize = 104 * 1024;
WriteHeaderSize(stream);
_countingWritableSubStream = new CountingWritableSubStream(stream);
_stream = new Crc32Stream(new LzmaStream(new LzmaEncoderProperties(true, dSize), false, _countingWritableSubStream));
}
}
public void Finish()
{
if (!_finished)
{
if (Mode == CompressionMode.Compress)
{
var crc32Stream = (Crc32Stream)_stream;
crc32Stream.WrappedStream.Dispose();
crc32Stream.Dispose();
var compressedCount = _countingWritableSubStream!.Count;
Span<byte> intBuf = stackalloc byte[8];
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, crc32Stream.Crc);
_countingWritableSubStream.Write(intBuf.Slice(0, 4));
BinaryPrimitives.WriteInt64LittleEndian(intBuf, _writeCount);
_countingWritableSubStream.Write(intBuf);
//total with headers
BinaryPrimitives.WriteUInt64LittleEndian(intBuf, compressedCount + 6 + 20);
_countingWritableSubStream.Write(intBuf);
}
_finished = true;
}
}
#region Stream methods
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (disposing)
{
Finish();
_stream.Dispose();
}
}
public CompressionMode Mode { get; }
public override bool CanRead => Mode == CompressionMode.Decompress;
public override bool CanSeek => false;
public override bool CanWrite => Mode == CompressionMode.Compress;
public override void Flush()
{
_stream.Flush();
}
// TODO: Both Length and Position are sometimes feasible, but would require
// reading the output length when we initialize.
public override long Length => throw new NotImplementedException();
public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override int Read(byte[] buffer, int offset, int count) => _stream.Read(buffer, offset, count);
public override int ReadByte() => _stream.ReadByte();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotImplementedException();
#if !NETFRAMEWORK && !NETSTANDARD2_0
public override int Read(Span<byte> buffer)
{
return _stream.Read(buffer);
}
public override void Write(ReadOnlySpan<byte> buffer)
{
_stream.Write(buffer);
_writeCount += buffer.Length;
}
#endif
public override void Write(byte[] buffer, int offset, int count)
{
_stream.Write(buffer, offset, count);
_writeCount += count;
}
public override void WriteByte(byte value)
{
_stream.WriteByte(value);
++_writeCount;
}
#endregion
/// <summary>
/// Determines if the given stream is positioned at the start of a v1 LZip
/// file, as indicated by the ASCII characters "LZIP" and a version byte
/// of 1, followed by at least one byte.
/// </summary>
/// <param name="stream">The stream to read from. Must not be null.</param>
/// <returns><c>true</c> if the given stream is an LZip file, <c>false</c> otherwise.</returns>
public static bool IsLZipFile(Stream stream) => ValidateAndReadSize(stream) != 0;
/// <summary>
/// Reads the 6-byte header of the stream, and returns 0 if either the header
/// couldn't be read or it isn't a validate LZIP header, or the dictionary
/// size if it *is* a valid LZIP file.
/// </summary>
public static int ValidateAndReadSize(Stream stream)
{
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
// Read the header
Span<byte> header = stackalloc byte[6];
int n = stream.Read(header);
// TODO: Handle reading only part of the header?
if (n != 6)
{
return 0;
}
if (header[0] != 'L' || header[1] != 'Z' || header[2] != 'I' || header[3] != 'P' || header[4] != 1 /* version 1 */)
{
return 0;
}
int basePower = header[5] & 0x1F;
int subtractionNumerator = (header[5] & 0xE0) >> 5;
return (1 << basePower) - subtractionNumerator * (1 << (basePower - 4));
}
private static readonly byte[] headerBytes = new byte[6] { (byte)'L', (byte)'Z', (byte)'I', (byte)'P', 1, 113 };
public static void WriteHeaderSize(Stream stream)
{
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
// hard coding the dictionary size encoding
stream.Write(headerBytes, 0, 6);
}
/// <summary>
/// Creates a byte array to communicate the parameters and dictionary size to LzmaStream.
/// </summary>
private static byte[] GetProperties(int dictionarySize) =>
new byte[]
{
// Parameters as per http://www.nongnu.org/lzip/manual/lzip_manual.html#Stream-format
// but encoded as a single byte in the format LzmaStream expects.
// literal_context_bits = 3
// literal_pos_state_bits = 0
// pos_state_bits = 2
93,
// Dictionary size as 4-byte little-endian value
(byte)(dictionarySize & 0xff),
(byte)((dictionarySize >> 8) & 0xff),
(byte)((dictionarySize >> 16) & 0xff),
(byte)((dictionarySize >> 24) & 0xff)
};
}
}
| |
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
// ResourceLib Original Code from http://resourcelib.codeplex.com
// Original Copyright (c) 2008-2009 Vestris Inc.
// Changes Copyright (c) 2011 Garrett Serack . All rights reserved.
// </copyright>
// <license>
// MIT License
// You may freely use and distribute this software under the terms of the following license agreement.
//
// 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
// </license>
//-----------------------------------------------------------------------
namespace ClrPlus.Windows.PeBinary.ResourceLib {
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using Api;
using Api.Enumerations;
using Api.Structures;
/// <summary>
/// A device-independent image consists of a BITMAPINFOHEADER where
/// bmWidth is the width of the image andbmHeight is double the height
/// of the image, followed by the bitmap color table, followed by the image
/// pixels, followed by the mask pixels.
/// </summary>
public class DeviceIndependentBitmap {
private Bitmap _color;
private byte[] _data;
private BitmapInfoHeader _header;
private Bitmap _image;
private Bitmap _mask;
/// <summary>
/// A new icon image.
/// </summary>
public DeviceIndependentBitmap() {
}
/// <summary>
/// A device-independent bitmap.
/// </summary>
/// <param name="data">Bitmap data.</param>
public DeviceIndependentBitmap(byte[] data) {
Data = data;
}
/// <summary>
/// Create a copy of an image.
/// </summary>
/// <param name="image">Source image.</param>
public DeviceIndependentBitmap(DeviceIndependentBitmap image) {
_data = new byte[image._data.Length];
Buffer.BlockCopy(image._data, 0, _data, 0, image._data.Length);
_header = image._header;
}
/// <summary>
/// Raw image data.
/// </summary>
public byte[] Data {
get {
return _data;
}
set {
_data = value;
var pData = Marshal.AllocHGlobal(Marshal.SizeOf(_header));
try {
Marshal.Copy(_data, 0, pData, Marshal.SizeOf(_header));
_header = (BitmapInfoHeader)Marshal.PtrToStructure(pData, typeof (BitmapInfoHeader));
} finally {
Marshal.FreeHGlobal(pData);
}
}
}
/// <summary>
/// Bitmap info header.
/// </summary>
public BitmapInfoHeader Header {
get {
return _header;
}
}
/// <summary>
/// Bitmap size in bytes.
/// </summary>
public int Size {
get {
return _data.Length;
}
}
/// <summary>
/// Size of the image mask.
/// </summary>
private Int32 MaskImageSize {
get {
return (_header.biHeight/2*GetDIBRowWidth(_header.biWidth));
}
}
private Int32 XorImageSize {
get {
return (_header.biHeight/2*GetDIBRowWidth(_header.biWidth*_header.biBitCount*_header.biPlanes));
}
}
/// <summary>
/// Position of the DIB bitmap bits within a DIB bitmap array.
/// </summary>
private Int32 XorImageIndex {
get {
return (Int32)(Marshal.SizeOf(_header) + ColorCount*Marshal.SizeOf(new RgbQuad()));
}
}
/// <summary>
/// Number of colors in the palette.
/// </summary>
private UInt32 ColorCount {
get {
if (_header.biClrUsed != 0) {
return _header.biClrUsed;
}
if (_header.biBitCount <= 8) {
return (UInt32)(1 << _header.biBitCount);
}
return 0;
}
}
private Int32 MaskImageIndex {
get {
return XorImageIndex + XorImageSize;
}
}
/// <summary>
/// Bitmap monochrome mask.
/// </summary>
public Bitmap Mask {
get {
if (_mask == null) {
var hdc = IntPtr.Zero;
var hBmp = IntPtr.Zero;
var hBmpOld = IntPtr.Zero;
var bitsInfo = IntPtr.Zero;
var bits = IntPtr.Zero;
try {
// extract monochrome mask
hdc = Gdi32.CreateCompatibleDC(IntPtr.Zero);
if (hdc == null) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
hBmp = Gdi32.CreateCompatibleBitmap(hdc, _header.biWidth, _header.biHeight/2);
if (hBmp == null) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
hBmpOld = Gdi32.SelectObject(hdc, hBmp);
// prepare BitmapInfoHeader for mono bitmap:
var monoBmHdrSize = (int)_header.biSize + Marshal.SizeOf(new RgbQuad())*2;
bitsInfo = Marshal.AllocCoTaskMem(monoBmHdrSize);
Marshal.WriteInt32(bitsInfo, Marshal.SizeOf(_header));
Marshal.WriteInt32(bitsInfo, 4, _header.biWidth);
Marshal.WriteInt32(bitsInfo, 8, _header.biHeight/2);
Marshal.WriteInt16(bitsInfo, 12, 1);
Marshal.WriteInt16(bitsInfo, 14, 1);
Marshal.WriteInt32(bitsInfo, 16, (Int32)BitmapCompression.BI_RGB);
Marshal.WriteInt32(bitsInfo, 20, 0);
Marshal.WriteInt32(bitsInfo, 24, 0);
Marshal.WriteInt32(bitsInfo, 28, 0);
Marshal.WriteInt32(bitsInfo, 32, 0);
Marshal.WriteInt32(bitsInfo, 36, 0);
// black and white color indices
Marshal.WriteInt32(bitsInfo, 40, 0);
Marshal.WriteByte(bitsInfo, 44, 255);
Marshal.WriteByte(bitsInfo, 45, 255);
Marshal.WriteByte(bitsInfo, 46, 255);
Marshal.WriteByte(bitsInfo, 47, 0);
// prepare mask bits
bits = Marshal.AllocCoTaskMem(MaskImageSize);
Marshal.Copy(_data, MaskImageIndex, bits, MaskImageSize);
if (0 ==
Gdi32.SetDIBitsToDevice(hdc, 0, 0, (UInt32)_header.biWidth, (UInt32)_header.biHeight/2, 0, 0, 0, (UInt32)_header.biHeight/2, bits,
bitsInfo, (UInt32)DIBColors.DIB_RGB_COLORS)) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
_mask = System.Drawing.Image.FromHbitmap(hBmp);
} finally {
if (bits != IntPtr.Zero) {
Marshal.FreeCoTaskMem(bits);
}
if (bitsInfo != IntPtr.Zero) {
Marshal.FreeCoTaskMem(bitsInfo);
}
if (hdc != IntPtr.Zero) {
Gdi32.SelectObject(hdc, hBmpOld);
}
if (hdc != IntPtr.Zero) {
Gdi32.DeleteObject(hdc);
}
}
}
return _mask;
}
}
/// <summary>
/// Bitmap color (XOR) part of the image.
/// </summary>
public Bitmap Color {
get {
if (_color == null) {
var hdcDesktop = IntPtr.Zero;
var hdc = IntPtr.Zero;
var hBmp = IntPtr.Zero;
var hBmpOld = IntPtr.Zero;
var bitsInfo = IntPtr.Zero;
var bits = IntPtr.Zero;
try {
hdcDesktop = User32.GetDC(IntPtr.Zero); // Gdi32.CreateDC("DISPLAY", null, null, IntPtr.Zero);
if (hdcDesktop == null) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
hdc = Gdi32.CreateCompatibleDC(hdcDesktop);
if (hdc == null) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
hBmp = Gdi32.CreateCompatibleBitmap(hdcDesktop, _header.biWidth, _header.biHeight/2);
if (hBmp == null) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
hBmpOld = Gdi32.SelectObject(hdc, hBmp);
// bitmap header
bitsInfo = Marshal.AllocCoTaskMem(XorImageIndex);
if (bitsInfo == null) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
Marshal.Copy(_data, 0, bitsInfo, XorImageIndex);
// fix the height
Marshal.WriteInt32(bitsInfo, 8, _header.biHeight/2);
// XOR bits
bits = Marshal.AllocCoTaskMem(XorImageSize);
Marshal.Copy(_data, XorImageIndex, bits, XorImageSize);
if (0 ==
Gdi32.SetDIBitsToDevice(hdc, 0, 0, (UInt32)_header.biWidth, (UInt32)_header.biHeight/2, 0, 0, 0, (UInt32)(_header.biHeight/2),
bits, bitsInfo, (Int32)DIBColors.DIB_RGB_COLORS)) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
_color = System.Drawing.Image.FromHbitmap(hBmp);
} finally {
if (hdcDesktop != IntPtr.Zero) {
Gdi32.DeleteDC(hdcDesktop);
}
if (bits != IntPtr.Zero) {
Marshal.FreeCoTaskMem(bits);
}
if (bitsInfo != IntPtr.Zero) {
Marshal.FreeCoTaskMem(bitsInfo);
}
if (hdc != IntPtr.Zero) {
Gdi32.SelectObject(hdc, hBmpOld);
}
if (hdc != IntPtr.Zero) {
Gdi32.DeleteObject(hdc);
}
}
}
return _color;
}
}
/// <summary>
/// Complete image.
/// </summary>
public Bitmap Image {
get {
if (_image == null) {
var hDCScreen = IntPtr.Zero;
var bits = IntPtr.Zero;
var hDCScreenOUTBmp = IntPtr.Zero;
var hBitmapOUTBmp = IntPtr.Zero;
try {
hDCScreen = User32.GetDC(IntPtr.Zero);
if (hDCScreen == IntPtr.Zero) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
// Image
var bitmapInfo = new BitmapInfo();
bitmapInfo.bmiHeader = _header;
// bitmapInfo.bmiColors = Tools.StandarizePalette(mEncoder.Colors);
hDCScreenOUTBmp = Gdi32.CreateCompatibleDC(hDCScreen);
hBitmapOUTBmp = Gdi32.CreateDIBSection(hDCScreenOUTBmp, ref bitmapInfo, 0, out bits, IntPtr.Zero, 0);
Marshal.Copy(_data, XorImageIndex, bits, XorImageSize);
_image = System.Drawing.Image.FromHbitmap(hBitmapOUTBmp);
} finally {
if (hDCScreen != IntPtr.Zero) {
User32.ReleaseDC(IntPtr.Zero, hDCScreen);
}
if (hBitmapOUTBmp != IntPtr.Zero) {
Gdi32.DeleteObject(hBitmapOUTBmp);
}
if (hDCScreenOUTBmp != IntPtr.Zero) {
Gdi32.DeleteDC(hDCScreenOUTBmp);
}
}
}
return _image;
}
}
/// <summary>
/// Read icon data.
/// </summary>
/// <param name="lpData">Pointer to the beginning of icon data.</param>
/// <param name="size">Icon data size.</param>
internal void Read(IntPtr lpData, uint size) {
_header = (BitmapInfoHeader)Marshal.PtrToStructure(lpData, typeof (BitmapInfoHeader));
_data = new byte[size];
Marshal.Copy(lpData, _data, 0, _data.Length);
}
/// <summary>
/// Returns the width of a row in a DIB Bitmap given the number of bits. DIB Bitmap rows always align on a DWORD boundary.
/// </summary>
/// <param name="width">Number of bits.</param>
/// <returns>Width of a row in bytes.</returns>
private Int32 GetDIBRowWidth(int width) {
return ((width + 31)/32)*4;
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
//
// vp_BodyAnimator.cs
// ?VisionPunk. All Rights Reserved.
// https://twitter.com/VisionPunk
// http://www.visionpunk.com
//
// description: this script animates a human character model that needs to
// move around and use guns a lot! it is designed for use with
// the provided 'UFPSExampleAnimator'.
//
// the script assumes an upright player, logically divided into
// upper and lower body. the upper body is manipulated using a
// head look logic adapted to the UFPS event system and designed
// to be used together with the 'vp_3rdPersonWeaponAim' script
// for hand IK. lower body (legs and feet) rotates independently
// of upper body (spine, arms and head). for example: the player
// can look around quite freely without moving its feet.
//
// PLEASE NOTE: this version of the script is intended for use
// only on 3RD PERSON players such as multiplayer remote players
// and AI. there is a separate version of the script,
// 'vp_FPBodyAnimator', which adds functionality for a local,
// first person player.
//
/////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(Animator))]
public class vp_BodyAnimator : MonoBehaviour
{
protected bool m_IsValid = true;
protected Vector3 m_ValidLookPoint = Vector3.zero;
protected float m_ValidLookPointForward = 0.0f;
protected bool HeadPointDirty = true;
// head look rotation
public GameObject HeadBone; // the bone closest to the center of the head should be assigned here. all bones between this and 'LowestSpineBone' will be used for headlook
public GameObject LowestSpineBone; // the lowest spine bone above the hip should be assigned here. all bones between this and 'HeadBone' will be used for headlook
[Range(0, 90)]
public float HeadPitchCap = 45.0f; // how far up and down can the character bend its head. too high values may have the character bend over backwards or put its chin through its chest
[Range(2, 20)]
public float HeadPitchSpeed = 7.0f; // headlook sensitivity to input. higher values look more alert, but stiff. lower values look more natural, or drowsy.
[Range(0.2f, 20)]
public float HeadYawSpeed = 2.0f; // headlook sensitivity to input. higher values look more alert, but stiff. lower values look more natural, or drowsy.
[Range(0, 1)]
public float LeaningFactor = 0.25f; // the higher the leaning factor, the more the character will lean over / lean backwards when looking down / up respectively
// headlook
protected List<GameObject> m_HeadLookBones = new List<GameObject>();
protected List<Vector3> m_ReferenceUpDirs = null;
protected List<Vector3> m_ReferenceLookDirs = null;
protected float m_CurrentHeadLookYaw = 0.0f;
protected float m_CurrentHeadLookPitch = 0.0f;
protected List<float> m_HeadLookFalloffs = new List<float>();
protected List<float> m_HeadLookCurrentFalloffs = null;
protected List<float> m_HeadLookTargetFalloffs = null;
protected Vector3 m_HeadLookTargetWorldDir;
protected Vector3 m_HeadLookCurrentWorldDir;
protected Vector3 m_HeadLookBackup = Vector3.zero; // work variable
protected Vector3 m_LookPoint = Vector3.zero; // work variable
// lower body rotation
public float FeetAdjustAngle = 80.0f; // when the character turns its head sideways above this angle in relation to its feet direction, the body and feet will be adjusted to the look direction
public float FeetAdjustSpeedStanding = 10.0f; // the speed of foot / lower body adjustment when character is standing still and looking around
public float FeetAdjustSpeedMoving = 12.0f; // the speed of foot / lower body adjustment when character is moving and looking around
protected float m_PrevBodyYaw = 0.0f;
protected float m_BodyYaw = 0.0f;
protected float m_CurrentBodyYawTarget = 0.0f;
protected float m_LastYaw = 0.0f;
// movement
public Vector3 ClimbOffset = Vector3.forward * 0.6f; // the body position will be offset from the character controller by this amount when climbing ladders. used to move the body closer to the ladder than allowed by the character controller
public Vector3 ClimbRotationOffset = Vector3.zero; // the body will be locally rotated by this amount when climbing ladders. used to adapt for animation orientation
protected float m_CurrentForward = 0.0f;
protected float m_CurrentStrafe = 0.0f;
protected float m_CurrentTurn = 0.0f;
protected float m_CurrentTurnTarget = 0.0f;
protected float m_MaxWalkSpeed = 1.0f;
protected float m_MaxRunSpeed = 1.0f;
protected float m_MaxCrouchSpeed = 1.0f;
protected bool m_WasMoving = false;
// grounding
protected RaycastHit m_GroundHit;
protected bool m_Grounded = true;
// timers
protected vp_Timer.Handle m_AttackDoneTimer = new vp_Timer.Handle();
protected float m_NextAllowedUpdateTurnTargetTime = 0;
// constants
protected const float TURNMODIFIER = 0.2f;
protected const float CROUCHTURNMODIFIER = 100.0f;
protected const float MOVEMODIFIER = 100.0f;
// debug
public bool ShowDebugObjects = false; // when on, this toggle will show yellow lines indicating the look vector, and a red ball indicating the current look target
// --- hash IDs ---
// floats
protected int ForwardAmount;
protected int PitchAmount;
protected int StrafeAmount;
protected int TurnAmount;
protected int VerticalMoveAmount;
// booleans
protected int IsAttacking;
protected int IsClimbing;
protected int IsCrouching;
protected int IsGrounded;
protected int IsMoving;
protected int IsOutOfControl;
protected int IsReloading;
protected int IsRunning;
protected int IsSettingWeapon;
protected int IsZooming;
protected int IsFirstPerson;
// triggers
protected int StartClimb;
protected int StartOutOfControl;
protected int StartReload;
// enum indices
protected int WeaponGripIndex;
protected int WeaponTypeIndex;
// --- properties ---
protected vp_WeaponHandler m_WeaponHandler = null;
protected vp_WeaponHandler WeaponHandler
{
get
{
if (m_WeaponHandler == null)
m_WeaponHandler = (vp_WeaponHandler)transform.root.GetComponentInChildren(typeof(vp_WeaponHandler));
return m_WeaponHandler;
}
}
protected Transform m_Transform = null;
protected Transform Transform
{
get
{
if (m_Transform == null)
m_Transform = transform;
return m_Transform;
}
}
protected vp_PlayerEventHandler m_Player = null;
protected vp_PlayerEventHandler Player
{
get
{
if (m_Player == null)
m_Player = (vp_PlayerEventHandler)transform.root.GetComponentInChildren(typeof(vp_PlayerEventHandler));
return m_Player;
}
}
protected SkinnedMeshRenderer m_Renderer = null;
protected SkinnedMeshRenderer Renderer
{
get
{
if (m_Renderer == null)
m_Renderer = transform.root.GetComponentInChildren<SkinnedMeshRenderer>();
return m_Renderer;
}
}
protected Animator m_Animator;
protected Animator Animator
{
get
{
if (m_Animator == null)
m_Animator = GetComponent<Animator>();
return m_Animator;
}
}
protected Vector3 m_LocalVelocity
{
get
{
return vp_MathUtility.SnapToZero(
Transform.root.InverseTransformDirection(Player.Velocity.Get())
/ m_MaxSpeed
);
}
}
protected float m_MaxSpeed
{
get
{
if (Player.Run.Active)
return m_MaxRunSpeed;
if (Player.Crouch.Active)
return m_MaxCrouchSpeed;
return m_MaxWalkSpeed;
}
}
protected GameObject m_HeadPoint = null;
protected GameObject HeadPoint
{
get
{
if (m_HeadPoint == null)
{
m_HeadPoint = new GameObject("HeadPoint");
m_HeadPoint.transform.parent = m_HeadLookBones[0].transform;
m_HeadPoint.transform.localPosition = Vector3.zero;
HeadPoint.transform.eulerAngles = Player.Rotation.Get();
}
return m_HeadPoint;
}
}
protected GameObject m_DebugLookTarget;
protected GameObject DebugLookTarget
{
get
{
if (m_DebugLookTarget == null)
m_DebugLookTarget = vp_3DUtility.DebugBall();
return m_DebugLookTarget;
}
}
protected GameObject m_DebugLookArrow;
protected GameObject DebugLookArrow
{
get
{
if (m_DebugLookArrow == null)
{
m_DebugLookArrow = vp_3DUtility.DebugPointer();
m_DebugLookArrow.transform.parent = HeadPoint.transform;
m_DebugLookArrow.transform.localPosition = Vector3.zero;
m_DebugLookArrow.transform.localRotation = Quaternion.identity;
return m_DebugLookArrow;
}
return m_DebugLookArrow;
}
}
/// <summary>
///
/// </summary>
protected virtual void OnEnable()
{
if (Player != null)
Player.Register(this);
}
/// <summary>
///
/// </summary>
protected virtual void OnDisable()
{
if (Player != null)
Player.Unregister(this);
}
/// <summary>
///
/// </summary>
protected virtual void Awake()
{
#if UNITY_IPHONE || UNITY_ANDROID
Debug.LogError("Error ("+this+") This script from base UFPS is intended for desktop and not supported on mobile. Are you attempting to use a PC/Mac player prefab on IOS/Android?");
Component.DestroyImmediate(this);
return;
#endif
if (!IsValidSetup())
return;
InitHashIDs();
InitHeadLook();
InitMaxSpeeds();
//Player.IsFirstPerson.Set(false); // TEMP: checking to see if commenting this out causes trouble
}
/// <summary>
///
/// </summary>
protected virtual void LateUpdate()
{
if (Time.timeScale == 0.0f)
return;
if (!m_IsValid)
{
this.enabled = false;
return;
}
UpdatePosition();
UpdateGrounding();
UpdateBody();
UpdateSpine();
UpdateAnimationSpeeds();
UpdateAnimator();
UpdateDebugInfo();
UpdateHeadPoint();
}
/// <summary>
/// stores an interpretation of player mouselook and WASD input
/// </summary>
protected virtual void UpdateAnimationSpeeds()
{
// --- turn animation speed ---
if (Time.time > m_NextAllowedUpdateTurnTargetTime)
{
m_CurrentTurnTarget = ((Mathf.DeltaAngle(m_PrevBodyYaw, m_BodyYaw)) * (Player.Crouch.Active ? CROUCHTURNMODIFIER : TURNMODIFIER));
m_NextAllowedUpdateTurnTargetTime = Time.time + 0.1f;
}
if (Player.Platform.Get() == null || !Player.IsLocal.Get())
{
m_CurrentTurn = Mathf.Lerp(m_CurrentTurn, m_CurrentTurnTarget, Time.deltaTime);
if (Mathf.Round(Transform.root.eulerAngles.y) == Mathf.Round(m_LastYaw))
m_CurrentTurn *= 0.6f;
m_LastYaw = Transform.root.eulerAngles.y;
m_CurrentTurn = vp_MathUtility.SnapToZero(m_CurrentTurn);
}
else
m_CurrentTurn = 0.0f; // turn logic does not work very well locally on platforms
// --- forward motion animation speed ---
m_CurrentForward = Mathf.Lerp(m_CurrentForward, m_LocalVelocity.z, Time.deltaTime * MOVEMODIFIER);
m_CurrentForward = Mathf.Abs(m_CurrentForward) > 0.03f ? m_CurrentForward : 0.0f;
// --- strafe animation speed ---
if (Player.Crouch.Active)
{
if (Mathf.Abs(GetStrafeDirection()) < Mathf.Abs(m_CurrentTurn))
m_CurrentStrafe = Mathf.Lerp(m_CurrentStrafe, m_CurrentTurn, Time.deltaTime * 5);
else
m_CurrentStrafe = Mathf.Lerp(m_CurrentStrafe, GetStrafeDirection(), Time.deltaTime * 5);
}
else
m_CurrentStrafe = Mathf.Lerp(m_CurrentStrafe, GetStrafeDirection(), Time.deltaTime * 5);
m_CurrentStrafe = Mathf.Abs(m_CurrentStrafe) > 0.03f ? m_CurrentStrafe : 0.0f;
}
/// <summary>
/// returns -1 if strafing left and 1 if right. NOTE: this is a
/// method rather than a property because it is overridden for
/// more stable input data in first person
/// </summary>
protected virtual float GetStrafeDirection()
{
if (Player.InputMoveVector.Get().x < 0.0f)
return -1.0f;
else if (Player.InputMoveVector.Get().x > 0.0f)
return 1.0f;
return 0.0f;
}
/// <summary>
/// updates variables on the mecanim animator object
/// </summary>
protected virtual void UpdateAnimator()
{
// --- booleans used to transition between blend states ---
// TODO: these should be moved to event callbacks on the next optimization run
Animator.SetBool(IsRunning, Player.Run.Active && GetIsMoving());
Animator.SetBool(IsCrouching, Player.Crouch.Active);
Animator.SetInteger(WeaponTypeIndex, Player.CurrentWeaponType.Get());
Animator.SetInteger(WeaponGripIndex, Player.CurrentWeaponGrip.Get());
Animator.SetBool(IsSettingWeapon, Player.SetWeapon.Active);
Animator.SetBool(IsReloading, Player.Reload.Active);
Animator.SetBool(IsOutOfControl, Player.OutOfControl.Active);
Animator.SetBool(IsClimbing, Player.Climb.Active);
Animator.SetBool(IsZooming, Player.Zoom.Active);
Animator.SetBool(IsGrounded, m_Grounded);
Animator.SetBool(IsMoving, GetIsMoving());
Animator.SetBool(IsFirstPerson, Player.IsFirstPerson.Get());
// --- floats used inside blend states to blend between animations ---
Animator.SetFloat(TurnAmount, m_CurrentTurn);
Animator.SetFloat(ForwardAmount, m_CurrentForward);
Animator.SetFloat(StrafeAmount, m_CurrentStrafe);
Animator.SetFloat(PitchAmount, (-Player.Rotation.Get().x) / 90.0f);
if (m_Grounded)
Animator.SetFloat(VerticalMoveAmount, 0.0f);
else
{
if (Player.Velocity.Get().y < 0.0f)
Animator.SetFloat(VerticalMoveAmount, Mathf.Lerp(Animator.GetFloat(VerticalMoveAmount), -1.0f, Time.deltaTime * 3));
else
Animator.SetFloat(VerticalMoveAmount, Player.MotorThrottle.Get().y * 10.0f);
}
}
/// <summary>
/// (for 3rd person) shows a yellow line indicating the look direction,
/// and a red ball indicating the current look point
/// </summary>
protected virtual void UpdateDebugInfo()
{
if (ShowDebugObjects)
{
DebugLookTarget.transform.position = m_HeadLookBones[0].transform.position
+ (HeadPoint.transform.forward * 1000);
DebugLookArrow.transform.LookAt(DebugLookTarget.transform.position);
if (!vp_Utility.IsActive(m_DebugLookTarget))
vp_Utility.Activate(m_DebugLookTarget);
if (!vp_Utility.IsActive(m_DebugLookArrow))
vp_Utility.Activate(m_DebugLookArrow);
}
else
{
if (m_DebugLookTarget != null)
vp_Utility.Activate(m_DebugLookTarget, false);
if (m_DebugLookArrow != null)
vp_Utility.Activate(m_DebugLookArrow, false);
}
}
/// <summary>
/// maintains proper headlook orientation
/// </summary>
protected virtual void UpdateHeadPoint()
{
if (!HeadPointDirty)
return;
HeadPoint.transform.eulerAngles = Player.Rotation.Get();
HeadPointDirty = false;
}
/// <summary>
/// adjusts the position of the player body when climbing ladders
/// </summary>
protected virtual void UpdatePosition()
{
if (Player.IsFirstPerson.Get())
return;
if (Player.Climb.Active)
Transform.localPosition += ClimbOffset;
}
/// <summary>
/// maintains and animates rotation of the lower body
/// </summary>
protected virtual void UpdateBody()
{
// blend rotation towards target yaw, if active
m_PrevBodyYaw = m_BodyYaw;
m_BodyYaw = Mathf.LerpAngle(m_BodyYaw, m_CurrentBodyYawTarget, Time.deltaTime * ((Player.Velocity.Get().magnitude > 0.1f) ? FeetAdjustSpeedMoving : FeetAdjustSpeedStanding));
m_BodyYaw = m_BodyYaw < -360.0f ? m_BodyYaw += 360.0f : m_BodyYaw;
m_BodyYaw = m_BodyYaw > 360.0f ? m_BodyYaw -= 360.0f : m_BodyYaw;
Transform.eulerAngles = m_BodyYaw * Vector3.up;
// calculate head yaw in relation to body
m_CurrentHeadLookYaw = Mathf.DeltaAngle(Player.Rotation.Get().y, Transform.eulerAngles.y);
// force-rotate bodyYaw if it twists more than 90 degrees away from
// controller yaw to the left or right
if (Mathf.Max(0, m_CurrentHeadLookYaw - 90) > 0) // left
{
Transform.eulerAngles = (Vector3.up * (Transform.root.eulerAngles.y + 90));
m_BodyYaw = m_CurrentBodyYawTarget = Transform.eulerAngles.y;
}
else if (Mathf.Min(0, m_CurrentHeadLookYaw - (-90)) < 0) // right
{
Transform.eulerAngles = (Vector3.up * (Transform.root.eulerAngles.y - 90));
m_BodyYaw = m_CurrentBodyYawTarget = Transform.eulerAngles.y;
}
// detect when yaw and input rotation diverges because of
// 360 degree snap, and fix it or character will twist
float dif = (Player.Rotation.Get().y - m_BodyYaw);
if (Mathf.Abs(dif) > 180)
{
if (m_BodyYaw > 0.0f)
{
m_BodyYaw -= 360;
m_PrevBodyYaw -= 360;
}
else if (m_BodyYaw < 0.0f)
{
m_BodyYaw += 360;
m_PrevBodyYaw += 360;
}
}
// make lower body smoothly face forward in certain cases
if ((m_CurrentHeadLookYaw > FeetAdjustAngle) //
|| (m_CurrentHeadLookYaw < -FeetAdjustAngle) // when turning around to the left
|| (Player.Velocity.Get().magnitude > 0.1f) // when moving around in any way
|| (Player.Crouch.Active && (Player.Attack.Active || Player.Zoom.Active))) // when crouching and aiming (keeps guns without dynamic
// aiming pointed in roughly the right direction)
{
m_CurrentBodyYawTarget =
Mathf.LerpAngle(m_CurrentBodyYawTarget, Transform.root.eulerAngles.y, 0.1f);
}
}
/// <summary>
/// mecanim ik and lookat logic is unity pro only. this method
/// implements a headlook logic that allows us to manipulate the
/// spine in different ways depending on circumstances for a very
/// lifelike appearance
/// </summary>
protected virtual void UpdateSpine()
{
if (Player.Climb.Active)
return;
// NOTE: the underlying headlook 3D math was adapted from the Unity
// 'HeadLookController' example by Rune Skovbo Johansen.
// set head pitch and yaw with bone falloff
for (int v = 0; v < m_HeadLookBones.Count; v++)
{
// --- yaw logic ---
// we rotate the head and spine in three different ways, depending
// on what the character is up to:
//2) if in first person, or attacking, or zooming,
//invert headlookfalloff so shoulders always face the look angle
if (((Player.IsFirstPerson.Get()
// TIP: uncomment this to allow the camera to look at your shoulders in 1st person
// when standing still and unarmed (but beware: stiffer, and glitchy in crouch mode)
//&& ((Player.CurrentWeaponType.Get() > 0) || Player.Crouch.Active)
)
|| Animator.GetBool(IsAttacking)
|| Animator.GetBool(IsZooming))
&& !Animator.GetBool(IsCrouching) // always focus headlook on neck while crouching
)
m_HeadLookTargetFalloffs[v] = m_HeadLookFalloffs[(m_HeadLookFalloffs.Count - 1) - v];
//3) if standing still and relaxing in third person, let head rotate freely
//(as in free of the shoulders) for a less stiff, more life-like appearance
else
m_HeadLookTargetFalloffs[v] = m_HeadLookFalloffs[v];
// if was moving and stopped, snap to target falloff
if (m_WasMoving && !(Animator.GetBool(IsMoving)))
m_HeadLookCurrentFalloffs[v] = m_HeadLookTargetFalloffs[v];
// lerp bones toward the new target angle
m_HeadLookCurrentFalloffs[v] = Mathf.SmoothStep(m_HeadLookCurrentFalloffs[v], Mathf.LerpAngle(m_HeadLookCurrentFalloffs[v], m_HeadLookTargetFalloffs[v], Time.deltaTime * 10.0f), Time.deltaTime * 20);
// multiply world yaw with bone falloff. we use a different,
// stiffer pattern for the model in 1st person, and a more limber
// pattern in 3rd person
if (Player.IsFirstPerson.Get())
{
m_HeadLookTargetWorldDir = (GetLookPoint() - (m_HeadLookBones[0].transform.position));
m_HeadLookCurrentWorldDir = Vector3.Slerp(
m_HeadLookTargetWorldDir,
vp_3DUtility.HorizontalVector(m_HeadLookTargetWorldDir),
(m_HeadLookCurrentFalloffs[v] / m_HeadLookFalloffs[0]) // div by largest value to get into a 0-1 range
);
}
else
{
// make sure the lookpoint is not behind us (this can happen in local
// 3rd person if the camera is pointed at the ground behind the feet
// of the player). if it's behind, push it forward accordingly so the
// player never looks or aims over its shoulder unnaturaly
m_ValidLookPoint = GetLookPoint();
m_ValidLookPointForward = Transform.InverseTransformDirection((m_ValidLookPoint - (m_HeadLookBones[0].transform.position))).z;
if (m_ValidLookPointForward < 0.0f)
m_ValidLookPoint += Transform.forward * -m_ValidLookPointForward;
// multiply world yaw with bone falloff
m_HeadLookTargetWorldDir = Vector3.Slerp(m_HeadLookTargetWorldDir, (m_ValidLookPoint - (m_HeadLookBones[0].transform.position)), Time.deltaTime * HeadYawSpeed);
m_HeadLookCurrentWorldDir = Vector3.Slerp(
m_HeadLookCurrentWorldDir,
vp_3DUtility.HorizontalVector(m_HeadLookTargetWorldDir),
(m_HeadLookCurrentFalloffs[v] / m_HeadLookFalloffs[0]) // div by largest value to get into a 0-1 range
);
}
// perform yaw headlook for this bone in the correct world direction
// regardless of the bone's inherent 3d space
m_HeadLookBones[v].transform.rotation =
vp_3DUtility.GetBoneLookRotationInWorldSpace(
m_HeadLookBones[v].transform.rotation,
m_HeadLookBones[m_HeadLookBones.Count - 1].transform.parent.rotation,
m_HeadLookCurrentWorldDir,
m_HeadLookCurrentFalloffs[v],
m_ReferenceLookDirs[v],
m_ReferenceUpDirs[v],
Quaternion.identity
);
// perform damped pitch headlook if in 3rd person
if (!Player.IsFirstPerson.Get())
{
m_CurrentHeadLookPitch = Mathf.SmoothStep(m_CurrentHeadLookPitch, Mathf.Clamp(Player.Rotation.Get().x, -HeadPitchCap, HeadPitchCap), Time.deltaTime * HeadPitchSpeed);
m_HeadLookBones[v].transform.Rotate(
HeadPoint.transform.right,
m_CurrentHeadLookPitch
* Mathf.Lerp(m_HeadLookFalloffs[v], m_HeadLookCurrentFalloffs[v], LeaningFactor),
Space.World);
}
}
m_WasMoving = Animator.GetBool(IsMoving);
}
/// <summary>
/// this is a method rather than a property to allow overriding
/// </summary>
protected virtual bool GetIsMoving()
{
return (Vector3.Scale(Player.Velocity.Get(), (Vector3.right + Vector3.forward))).magnitude > 0.01f;
}
/// <summary>
/// returns the first look vector intersection with a solid object
/// </summary>
protected virtual Vector3 GetLookPoint()
{
m_HeadLookBackup = HeadPoint.transform.eulerAngles;
HeadPoint.transform.eulerAngles = vp_MathUtility.NaNSafeVector3(Player.Rotation.Get());
m_LookPoint = HeadPoint.transform.position
+ (HeadPoint.transform.forward * 1000);
HeadPoint.transform.eulerAngles = vp_MathUtility.NaNSafeVector3(m_HeadLookBackup);
return m_LookPoint;
}
/// <summary>
/// initializes the falloff variables used to get headlook to
/// gradually affect bones by distance to the head or lowest
/// spine bone
/// </summary>
protected virtual List<float> CalculateBoneFalloffs(List<GameObject> boneList)
{
List<float> boneFalloffs = new List<float>();
float factor = 0.0f;
for (int v = boneList.Count - 1; v > -1; v--)
{
if (boneList[v] == null)
boneList.RemoveAt(v);
else
{
float f = Mathf.Lerp(0, 1, (v + 1) / ((float)boneList.Count));
boneFalloffs.Add(f * f * f);
factor += f * f * f;
}
}
if (boneList.Count == 0)
return boneFalloffs;
for (int v = 0; v < boneFalloffs.Count; v++)
{
boneFalloffs[v] *= (1 / (factor));
}
return boneFalloffs;
}
/// <summary>
/// stores the relative rotations of the headlook bones and the
/// world at startup. necessary to support characer rigs with
/// arbitrary bone rotation spaces
/// </summary>
protected virtual void StoreReferenceDirections()
{
for (int v = 0; v < m_HeadLookBones.Count; v++)
{
Quaternion parentRotInv = Quaternion.Inverse(m_HeadLookBones[m_HeadLookBones.Count - 1].transform.parent.rotation);
m_ReferenceLookDirs.Add(parentRotInv * Transform.rotation * Vector3.forward);
m_ReferenceUpDirs.Add(parentRotInv * Transform.rotation * Vector3.up);
}
}
/// <summary>
/// calculates grounding similarly to the vp_FPController class.
/// exists here so we can have a player body without a controller
/// </summary>
protected virtual void UpdateGrounding()
{
// TODO: now supported in vp_Controller, remove?
Physics.SphereCast(
new Ray(Transform.position + Vector3.up * 0.5f, Vector3.down),
0.4f,
out m_GroundHit,
1.0f,
vp_Layer.Mask.ExternalBlockers);
m_Grounded = (m_GroundHit.collider != null);
}
/// <summary>
/// implements a delay between attacking and relaxing the
/// gun in 3rd person
/// </summary>
protected virtual void RefreshWeaponStates()
{
if (WeaponHandler == null)
return;
if (WeaponHandler.CurrentWeapon == null)
return;
WeaponHandler.CurrentWeapon.SetState("Attack", Player.Attack.Active);
WeaponHandler.CurrentWeapon.SetState("Zoom", Player.Zoom.Active);
}
/// <summary>
/// calculates the maximum running speeds of this controller
/// </summary>
protected virtual void InitMaxSpeeds()
{
if(Player.IsLocal.Get())
{
// get max speed of first vp_FPController that we can find under the ancestor
vp_FPController controller = Transform.root.GetComponentInChildren<vp_FPController>();
m_MaxWalkSpeed = controller.CalculateMaxSpeed();
m_MaxRunSpeed = controller.CalculateMaxSpeed("Run");
m_MaxCrouchSpeed = controller.CalculateMaxSpeed("Crouch");
//Debug.Log("m_MaxWalkSpeed: " + m_MaxWalkSpeed + ", m_MaxRunSpeed: " + m_MaxRunSpeed + ", m_MaxCrouchSpeed: " + m_MaxCrouchSpeed);
}
else
{
// TEMP: hardcoded for remote players
m_MaxWalkSpeed = 3.999999f;
m_MaxRunSpeed = 10.08f;
m_MaxCrouchSpeed = 1.44f;
}
}
/// <summary>
///
/// </summary>
protected virtual void InitHashIDs()
{
// floats
ForwardAmount = Animator.StringToHash("Forward");
PitchAmount = Animator.StringToHash("Pitch");
StrafeAmount = Animator.StringToHash("Strafe");
TurnAmount = Animator.StringToHash("Turn");
VerticalMoveAmount = Animator.StringToHash("VerticalMove");
// booleans
IsAttacking = Animator.StringToHash("IsAttacking");
IsClimbing = Animator.StringToHash("IsClimbing");
IsCrouching = Animator.StringToHash("IsCrouching");
IsGrounded = Animator.StringToHash("IsGrounded");
IsMoving = Animator.StringToHash("IsMoving");
IsOutOfControl = Animator.StringToHash("IsOutOfControl");
IsReloading = Animator.StringToHash("IsReloading");
IsRunning = Animator.StringToHash("IsRunning");
IsSettingWeapon = Animator.StringToHash("IsSettingWeapon");
IsZooming = Animator.StringToHash("IsZooming");
IsFirstPerson = Animator.StringToHash("IsFirstPerson");
// triggers
StartClimb = Animator.StringToHash("StartClimb");
StartOutOfControl = Animator.StringToHash("StartOutOfControl");
StartReload = Animator.StringToHash("StartReload");
// enum indices
WeaponGripIndex = Animator.StringToHash("WeaponGrip");
WeaponTypeIndex = Animator.StringToHash("WeaponType");
}
/// <summary>
///
/// </summary>
protected virtual void InitHeadLook()
{
if (!m_IsValid)
return;
m_HeadLookBones.Clear();
GameObject current = HeadBone;
while (current != LowestSpineBone.transform.parent.gameObject)
{
m_HeadLookBones.Add(current);
current = current.transform.parent.gameObject;
}
m_ReferenceUpDirs = new List<Vector3>();
m_ReferenceLookDirs = new List<Vector3>();
m_HeadLookFalloffs = CalculateBoneFalloffs(m_HeadLookBones);
m_HeadLookCurrentFalloffs = new List<float>(m_HeadLookFalloffs);
m_HeadLookTargetFalloffs = new List<float>(m_HeadLookFalloffs);
StoreReferenceDirections();
}
/// <summary>
/// makes sure the bodyanimator has been set up properly and
/// reports an error and disables the component if not
/// </summary>
protected virtual bool IsValidSetup()
{
if (HeadBone == null)
{
Debug.LogError("Error (" + this + ") No gameobject has been assigned for 'HeadBone'.");
goto abort;
}
if (LowestSpineBone == null)
{
Debug.LogError("Error (" + this + ") No gameobject has been assigned for 'LowestSpineBone'.");
goto abort;
}
if (!vp_Utility.IsDescendant(HeadBone.transform, transform.root))
{
NotInSameHierarchyError(HeadBone);
goto abort;
}
if (!vp_Utility.IsDescendant(LowestSpineBone.transform, transform.root))
{
NotInSameHierarchyError(LowestSpineBone);
goto abort;
}
if (!vp_Utility.IsDescendant(HeadBone.transform, LowestSpineBone.transform))
{
Debug.LogError("Error (" + this + ") 'HeadBone' must be a child or descendant of 'LowestSpineBone'.");
goto abort;
}
return true;
abort:
m_IsValid = false;
this.enabled = false;
return false;
}
/// <summary>
///
/// </summary>
protected virtual void NotInSameHierarchyError(GameObject o)
{
Debug.LogError("Error '" + o + "' can not be used as a bone for " + this + " because it is not part of the same hierarchy.");
}
/// <summary>
/// gets the world Y rotation of the lower body
/// </summary>
protected virtual float OnValue_BodyYaw
{
get
{
return Transform.eulerAngles.y; // return world yaw
}
set
{
m_BodyYaw = value;
}
}
/// <summary>
///
/// </summary>
protected virtual void OnStart_Attack()
{
// TEMP: time body animation better to throwing weapon projectile spawn
if (Player.CurrentWeaponType.Get() == (int)vp_Weapon.Type.Thrown)
{
vp_Timer.In(WeaponHandler.CurrentWeapon.GetComponent<vp_Shooter>().ProjectileSpawnDelay * 0.7f, () =>
{
m_AttackDoneTimer.Cancel();
Animator.SetBool(IsAttacking, true);
OnStop_Attack();
});
}
else
// ---
Animator.SetBool(IsAttacking, true);
}
/// <summary>
///
/// </summary>
protected virtual void OnStop_Attack()
{
// for 'RefreshWeaponStates'
vp_Timer.In(0.5f, delegate()
{
Animator.SetBool(IsAttacking, false);
RefreshWeaponStates();
}, m_AttackDoneTimer);
}
/// <summary>
///
/// </summary>
protected virtual void OnStop_Zoom()
{
// for 'RefreshWeaponStates'
vp_Timer.In(0.5f, delegate()
{
if (!Player.Attack.Active)
Animator.SetBool(IsAttacking, false);
RefreshWeaponStates();
}, m_AttackDoneTimer);
}
/// <summary>
///
/// </summary>
protected virtual void OnStart_Reload()
{
Animator.SetTrigger(StartReload);
}
/// <summary>
///
/// </summary>
protected virtual void OnStart_OutOfControl()
{
Animator.SetTrigger(StartOutOfControl);
}
/// <summary>
///
/// </summary>
protected virtual void OnStart_Climb()
{
Animator.SetTrigger(StartClimb);
}
/// <summary>
///
/// </summary>
protected virtual void OnStart_Dead()
{
// for 'RefreshWeaponStates'
if (m_AttackDoneTimer.Active)
m_AttackDoneTimer.Execute();
}
/// <summary>
///
/// </summary>
protected virtual void OnStop_Dead()
{
// for 'UpdateHeadPoint'
HeadPointDirty = true;
}
/// <summary>
///
/// </summary>
protected virtual void OnMessage_CameraToggle3rdPerson()
{
// for 'UpdateSpine'
m_WasMoving = !m_WasMoving;
// for 'UpdateHeadPoint'
HeadPointDirty = true;
}
/// <summary>
/// returns the direction between the player model's head and the
/// look point. NOTE: _not_ necessarily the direction between the
/// camera and the look point
/// </summary>
protected virtual Vector3 OnValue_HeadLookDirection
{
get
{
return (Player.LookPoint.Get() - HeadPoint.transform.position).normalized;
}
}
/// <summary>
/// returns the contact point on the surface of the first physical
/// object that the camera looks at
/// </summary>
protected virtual Vector3 OnValue_LookPoint
{
get
{
return GetLookPoint();
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace CardGenerator
{
public partial class Page2
{
private global::Gtk.VBox vbox6;
private global::Gtk.Label label12;
private global::Gtk.Frame frame1;
private global::Gtk.Alignment GtkAlignment;
private global::Gtk.HBox hbox1;
private global::Gtk.ScrolledWindow GtkScrolledWindow1;
private global::Gtk.TreeView treeviewCardType;
private global::Gtk.VBox vbox1;
private global::Gtk.Button bnCardTypeAdd;
private global::Gtk.Button bnCardTypeRemove;
private global::Gtk.Label GtkLabelA;
private global::Gtk.Frame frame2;
private global::Gtk.Alignment GtkAlignment1;
private global::Gtk.HBox hbox2;
private global::Gtk.ScrolledWindow GtkScrolledWindow2;
private global::Gtk.TreeView treeviewFace1;
private global::Gtk.VBox vbox2;
private global::Gtk.Button bnFace1Add;
private global::Gtk.Button bnFace1Remove;
private global::Gtk.Label GtkLabel1A;
private global::Gtk.Frame frame3;
private global::Gtk.Alignment GtkAlignment2;
private global::Gtk.HBox hbox3;
private global::Gtk.ScrolledWindow GtkScrolledWindow3;
private global::Gtk.TreeView treeviewFace2;
private global::Gtk.VBox vbox3;
private global::Gtk.Button bnFace2Add;
private global::Gtk.Button bnFace2Remove;
private global::Gtk.Label GtkLabel6;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget CardGenerator.Page2
global::Stetic.BinContainer.Attach (this);
this.Name = "CardGenerator.Page2";
// Container child CardGenerator.Page2.Gtk.Container+ContainerChild
this.vbox6 = new global::Gtk.VBox ();
this.vbox6.Name = "vbox6";
this.vbox6.Spacing = 6;
// Container child vbox6.Gtk.Box+BoxChild
this.label12 = new global::Gtk.Label ();
this.label12.Name = "label12";
this.label12.LabelProp = global.Mono.Unix.Catalog.GetString ("Card Structures");
this.vbox6.Add (this.label12);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox6 [this.label12]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child vbox6.Gtk.Box+BoxChild
this.frame1 = new global::Gtk.Frame ();
this.frame1.Name = "frame1";
this.frame1.ShadowType = ((global::Gtk.ShadowType)(0));
// Container child frame1.Gtk.Container+ContainerChild
this.GtkAlignment = new global::Gtk.Alignment (0F, 0F, 1F, 1F);
this.GtkAlignment.Name = "GtkAlignment";
this.GtkAlignment.LeftPadding = ((uint)(12));
// Container child GtkAlignment.Gtk.Container+ContainerChild
this.hbox1 = new global::Gtk.HBox ();
this.hbox1.Name = "hbox1";
this.hbox1.Spacing = 6;
// Container child hbox1.Gtk.Box+BoxChild
this.GtkScrolledWindow1 = new global::Gtk.ScrolledWindow ();
this.GtkScrolledWindow1.Name = "GtkScrolledWindow1";
this.GtkScrolledWindow1.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child GtkScrolledWindow1.Gtk.Container+ContainerChild
this.treeviewCardType = new global::Gtk.TreeView ();
this.treeviewCardType.CanFocus = true;
this.treeviewCardType.Name = "treeviewCardType";
this.GtkScrolledWindow1.Add (this.treeviewCardType);
this.hbox1.Add (this.GtkScrolledWindow1);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.GtkScrolledWindow1]));
w3.Position = 0;
// Container child hbox1.Gtk.Box+BoxChild
this.vbox1 = new global::Gtk.VBox ();
this.vbox1.Name = "vbox1";
this.vbox1.Spacing = 6;
// Container child vbox1.Gtk.Box+BoxChild
this.bnCardTypeAdd = new global::Gtk.Button ();
this.bnCardTypeAdd.CanFocus = true;
this.bnCardTypeAdd.Name = "bnCardTypeAdd";
this.bnCardTypeAdd.UseUnderline = true;
this.bnCardTypeAdd.Label = global.Mono.Unix.Catalog.GetString ("Add...");
this.vbox1.Add (this.bnCardTypeAdd);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.bnCardTypeAdd]));
w4.Position = 0;
w4.Expand = false;
w4.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.bnCardTypeRemove = new global::Gtk.Button ();
this.bnCardTypeRemove.CanFocus = true;
this.bnCardTypeRemove.Name = "bnCardTypeRemove";
this.bnCardTypeRemove.UseUnderline = true;
this.bnCardTypeRemove.Label = global.Mono.Unix.Catalog.GetString ("Remove");
this.vbox1.Add (this.bnCardTypeRemove);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.bnCardTypeRemove]));
w5.Position = 1;
w5.Expand = false;
w5.Fill = false;
this.hbox1.Add (this.vbox1);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.vbox1]));
w6.Position = 1;
w6.Expand = false;
w6.Fill = false;
this.GtkAlignment.Add (this.hbox1);
this.frame1.Add (this.GtkAlignment);
this.GtkLabelA = new global::Gtk.Label ();
this.GtkLabelA.Name = "GtkLabelA";
this.GtkLabelA.LabelProp = global.Mono.Unix.Catalog.GetString ("Card Type Name");
this.GtkLabelA.UseMarkup = true;
this.frame1.LabelWidget = this.GtkLabelA;
this.vbox6.Add (this.frame1);
global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.vbox6 [this.frame1]));
w9.Position = 2;
// Container child vbox6.Gtk.Box+BoxChild
this.frame2 = new global::Gtk.Frame ();
this.frame2.Name = "frame2";
this.frame2.ShadowType = ((global::Gtk.ShadowType)(0));
// Container child frame2.Gtk.Container+ContainerChild
this.GtkAlignment1 = new global::Gtk.Alignment (0F, 0F, 1F, 1F);
this.GtkAlignment1.Name = "GtkAlignment1";
this.GtkAlignment1.LeftPadding = ((uint)(12));
// Container child GtkAlignment1.Gtk.Container+ContainerChild
this.hbox2 = new global::Gtk.HBox ();
this.hbox2.Name = "hbox2";
this.hbox2.Spacing = 6;
// Container child hbox2.Gtk.Box+BoxChild
this.GtkScrolledWindow2 = new global::Gtk.ScrolledWindow ();
this.GtkScrolledWindow2.Name = "GtkScrolledWindow2";
this.GtkScrolledWindow2.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child GtkScrolledWindow2.Gtk.Container+ContainerChild
this.treeviewFace1 = new global::Gtk.TreeView ();
this.treeviewFace1.CanFocus = true;
this.treeviewFace1.Name = "treeviewFace1";
this.GtkScrolledWindow2.Add (this.treeviewFace1);
this.hbox2.Add (this.GtkScrolledWindow2);
global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.GtkScrolledWindow2]));
w11.Position = 0;
// Container child hbox2.Gtk.Box+BoxChild
this.vbox2 = new global::Gtk.VBox ();
this.vbox2.Name = "vbox2";
this.vbox2.Spacing = 6;
// Container child vbox2.Gtk.Box+BoxChild
this.bnFace1Add = new global::Gtk.Button ();
this.bnFace1Add.CanFocus = true;
this.bnFace1Add.Name = "bnFace1Add";
this.bnFace1Add.UseUnderline = true;
this.bnFace1Add.Label = global.Mono.Unix.Catalog.GetString ("Add...");
this.vbox2.Add (this.bnFace1Add);
global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.bnFace1Add]));
w12.Position = 0;
w12.Expand = false;
w12.Fill = false;
// Container child vbox2.Gtk.Box+BoxChild
this.bnFace1Remove = new global::Gtk.Button ();
this.bnFace1Remove.CanFocus = true;
this.bnFace1Remove.Name = "bnFace1Remove";
this.bnFace1Remove.UseUnderline = true;
this.bnFace1Remove.Label = global.Mono.Unix.Catalog.GetString ("Remove");
this.vbox2.Add (this.bnFace1Remove);
global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.bnFace1Remove]));
w13.Position = 1;
w13.Expand = false;
w13.Fill = false;
this.hbox2.Add (this.vbox2);
global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.vbox2]));
w14.Position = 1;
w14.Expand = false;
w14.Fill = false;
this.GtkAlignment1.Add (this.hbox2);
this.frame2.Add (this.GtkAlignment1);
this.GtkLabel1A = new global::Gtk.Label ();
this.GtkLabel1A.Name = "GtkLabel1A";
this.GtkLabel1A.LabelProp = global.Mono.Unix.Catalog.GetString ("Face 1 (Front face)");
this.GtkLabel1A.UseMarkup = true;
this.frame2.LabelWidget = this.GtkLabel1A;
this.vbox6.Add (this.frame2);
global::Gtk.Box.BoxChild w17 = ((global::Gtk.Box.BoxChild)(this.vbox6 [this.frame2]));
w17.Position = 3;
// Container child vbox6.Gtk.Box+BoxChild
this.frame3 = new global::Gtk.Frame ();
this.frame3.Name = "frame3";
this.frame3.ShadowType = ((global::Gtk.ShadowType)(0));
// Container child frame3.Gtk.Container+ContainerChild
this.GtkAlignment2 = new global::Gtk.Alignment (0F, 0F, 1F, 1F);
this.GtkAlignment2.Name = "GtkAlignment2";
this.GtkAlignment2.LeftPadding = ((uint)(12));
// Container child GtkAlignment2.Gtk.Container+ContainerChild
this.hbox3 = new global::Gtk.HBox ();
this.hbox3.Name = "hbox3";
this.hbox3.Spacing = 6;
// Container child hbox3.Gtk.Box+BoxChild
this.GtkScrolledWindow3 = new global::Gtk.ScrolledWindow ();
this.GtkScrolledWindow3.Name = "GtkScrolledWindow3";
this.GtkScrolledWindow3.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child GtkScrolledWindow3.Gtk.Container+ContainerChild
this.treeviewFace2 = new global::Gtk.TreeView ();
this.treeviewFace2.CanFocus = true;
this.treeviewFace2.Name = "treeviewFace2";
this.GtkScrolledWindow3.Add (this.treeviewFace2);
this.hbox3.Add (this.GtkScrolledWindow3);
global::Gtk.Box.BoxChild w19 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.GtkScrolledWindow3]));
w19.Position = 0;
// Container child hbox3.Gtk.Box+BoxChild
this.vbox3 = new global::Gtk.VBox ();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.bnFace2Add = new global::Gtk.Button ();
this.bnFace2Add.CanFocus = true;
this.bnFace2Add.Name = "bnFace2Add";
this.bnFace2Add.UseUnderline = true;
this.bnFace2Add.Label = global.Mono.Unix.Catalog.GetString ("Add...");
this.vbox3.Add (this.bnFace2Add);
global::Gtk.Box.BoxChild w20 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.bnFace2Add]));
w20.Position = 0;
w20.Expand = false;
w20.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.bnFace2Remove = new global::Gtk.Button ();
this.bnFace2Remove.CanFocus = true;
this.bnFace2Remove.Name = "bnFace2Remove";
this.bnFace2Remove.UseUnderline = true;
this.bnFace2Remove.Label = global.Mono.Unix.Catalog.GetString ("Remove");
this.vbox3.Add (this.bnFace2Remove);
global::Gtk.Box.BoxChild w21 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.bnFace2Remove]));
w21.Position = 1;
w21.Expand = false;
w21.Fill = false;
this.hbox3.Add (this.vbox3);
global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.vbox3]));
w22.Position = 1;
w22.Expand = false;
w22.Fill = false;
this.GtkAlignment2.Add (this.hbox3);
this.frame3.Add (this.GtkAlignment2);
this.GtkLabel6 = new global::Gtk.Label ();
this.GtkLabel6.Name = "GtkLabel6";
this.GtkLabel6.LabelProp = global.Mono.Unix.Catalog.GetString ("Face 2 (Back face)");
this.GtkLabel6.UseMarkup = true;
this.frame3.LabelWidget = this.GtkLabel6;
this.vbox6.Add (this.frame3);
global::Gtk.Box.BoxChild w25 = ((global::Gtk.Box.BoxChild)(this.vbox6 [this.frame3]));
w25.Position = 4;
this.Add (this.vbox6);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.Hide ();
this.treeviewCardType.CursorChanged += new global::System.EventHandler (this.onCardTypeCursorChanged);
this.bnCardTypeAdd.Clicked += new global::System.EventHandler (this.onBnCardTypeAdd);
this.bnCardTypeRemove.Clicked += new global::System.EventHandler (this.onBnCardTypeRemove);
this.bnFace1Add.Clicked += new global::System.EventHandler (this.onBnFace1Add);
this.bnFace1Remove.Clicked += new global::System.EventHandler (this.onBnFace1Remove);
this.bnFace2Add.Clicked += new global::System.EventHandler (this.onBnFace2Add);
this.bnFace2Remove.Clicked += new global::System.EventHandler (this.onBnFace2Remove);
}
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using OpenADK.Library;
using OpenADK.Library.Impl;
using OpenADK.Library.Infra;
using OpenADK.Util;
namespace OpenADK.Web.Http
{
/// <summary>
/// Summary description for HttpPushProtocolHandler.
/// </summary>
internal class AdkHttpPushProtocolHandler : BaseHttpProtocolHandler, IAdkHttpHandler
{
internal AdkHttpPushProtocolHandler( AdkHttpApplicationServer server, HttpTransport transport ) : base(transport)
{
fServer = server;
}
#region Overrides of BaseHttpProtocolHandler
public override void Start()
{
try {
string ctx = this.BuildContextPath();
fServer.AddHandlerContext( "", ctx, this, true );
// TODO: Investigate if we need to implement the anonymous handler
#region Disabled Code
/* if (false)
{
// Also establish a catch-all handler for "/" in case the ZIS
// disregards our URL path of "/zone/{zoneId}/". Any traffic
// received on this handler will be routed as follows: if the
// agent is connected to only one zone in Push mode, the
// traffic is assumed to have come from that zone. If the
// agent is connected to more than one zone in Push mode, the
// traffic is disregarded (i.e. no Ack is returned to the ZIS,
// which means the message will remain in the agent's queue.)
// If the agent is connected to a ZIS that behaves this way
// it must use Pull mode.
//
if (sAnonymousHandler == null)
{
sAnonymousHandler = new AnonymousHttpHandler();
context = server.addContext("/");
context.addHandler(sAnonymousHandler);
server.addContext(context);
context.start();
}
}
*/
#endregion
}
catch ( Exception e ) {
throw new AdkException
( "HttpProtocolHandler could not establish HttpContext: " + e, this.Zone );
}
}
public override void Shutdown()
{
if ( fServer != null ) {
fServer.RemoveHandlerContext( this.BuildContextPath() );
}
}
public override void Close( IZone zone )
{
fServer.RemoveHandlerContext( this.BuildContextPath() );
}
#endregion
private string BuildContextPath()
{
return "/zone/" + this.Zone.ZoneId + "/";
}
private SIF_Ack ProcessPush( SifMessagePayload parsed )
{
try {
// Dispatch. When the result is an Integer it is an ack code to
// return; otherwise it is ack data to return and the code is assumed
// to be 1 for an immediate acknowledgement.
int ackStatus = this.Zone.Dispatcher.dispatch( parsed );
// Ask the original message to generate a SIF_Ack for itself
return parsed.ackStatus( ackStatus );
}
catch ( SifException se ) {
return
parsed.AckError( se );
}
catch ( AdkException adke ) {
return
parsed.AckError
( SifErrorCategoryCode.Generic, SifErrorCodes.GENERIC_GENERIC_ERROR_1,
adke.Message );
}
catch ( Exception thr ) {
if ( (Adk.Debug & AdkDebugFlags.Messaging) != 0 ) {
this.Zone.Log.Debug( "Uncaught exception dispatching push message: " + thr );
}
return
parsed.AckError
( SifErrorCategoryCode.Generic, SifErrorCodes.GENERIC_GENERIC_ERROR_1,
"An unexpected error has occurred", thr.ToString() );
}
}
#region Push Handling
#region IAdkHttpHandler Members
public void ProcessRequest( AdkHttpRequestContext context )
{
if ( (Adk.Debug & AdkDebugFlags.Messaging) != 0 ) {
Zone.Log.Debug
( "Received push message from " + context.Request.RemoteAddress + " (" +
context.Request.Url.Scheme + ")" );
}
SIF_Ack ack = null;
SifMessagePayload parsed = null;
//Check request length and type
if (!SifIOFormatter.IsValidContentLength(context.Request.ContentLength)) {
throw new AdkHttpException
( AdkHttpStatusCode.ClientError_400_Bad_Request,
"Content length Must be greater than zero" );
}
if (!SifIOFormatter.IsValidContentMediaType(context.Request.ContentType)) {
throw new AdkHttpException(AdkHttpStatusCode.ClientError_415_Unsupported_Media_Type,
"Content header does not support the specified media type: " + context.Request.ContentType);
}
// Read raw content
Stream requestStream = context.Request.GetRequestStream();
StringBuilder requestXml = null;
// If we need to convert the request stream to a string for either logging or messaging, do so
if ( (Adk.Debug & AdkDebugFlags.Message_Content) != 0 ) {
requestXml = ConvertRequestToString( requestStream );
Zone.Log.Debug
( "Received " + context.Request.ContentLength + " bytes:\r\n" +
requestXml.ToString() );
}
TextReader requestReader = new StreamReader( requestStream, SifIOFormatter.ENCODING );
Exception parseEx = null;
bool reparse = false;
bool cancelled = false;
int reparsed = 0;
do {
try {
parseEx = null;
// Parse content
parsed = (SifMessagePayload) CreateParser().Parse( requestReader, Zone );
reparse = false;
parsed.LogRecv( Zone.Log );
}
catch ( AdkParsingException adke ) {
parseEx = adke;
}
catch ( Exception ex ) {
parseEx = ex;
}
//
// Notify listeners...
//
// If we're asked to reparse the message, do so but do not notify
// listeners the second time around.
//
if ( reparsed == 0 ) {
ICollection<IMessagingListener> msgList = MessageDispatcher.GetMessagingListeners(Zone);
if ( msgList.Count > 0 ) {
// Convert the stream to a string builder
if ( requestXml == null ) {
requestXml = ConvertRequestToString( requestStream );
}
// Determine message type before parsing
foreach ( IMessagingListener listener in msgList ) {
try {
SifMessageType pload =
Adk.Dtd.GetElementType( parsed.ElementDef.Name );
MessagingReturnCode code =
listener.OnMessageReceived( pload, requestXml );
switch ( code ) {
case MessagingReturnCode.Discard:
cancelled = true;
break;
case MessagingReturnCode.Reparse:
requestReader = new StringReader( requestXml.ToString() );
reparse = true;
break;
}
}
catch ( AdkException adke ) {
parseEx = adke;
}
}
}
}
if ( cancelled ) {
return;
}
reparsed++;
}
while ( reparse );
if ( parseEx != null ) {
// TODO: Handle the case where SIF_OriginalSourceId and SIF_OriginalMsgId
// are not available because parsing failed. See SIFInfra
// Resolution #157.
if( parseEx is SifException && parsed != null )
{
// Specific SIF error already provided to us by SIFParser
ack = parsed.AckError( (SifException)parseEx );
}
else{
String errorMessage = null;
if( parseEx is AdkException )
{
errorMessage = parseEx.Message;
} else {
// Unchecked Throwable
errorMessage = "Could not parse message";
}
if( parsed == null )
{
SifException sifError = null;
if( parseEx is SifException ){
sifError = (SifException) parseEx;
}else {
sifError = new SifException(
SifErrorCategoryCode.Xml,
SifErrorCodes.XML_GENERIC_ERROR_1,
"Could not parse message",
parseEx.ToString(),
this.Zone,
parseEx );
}
if( requestXml == null )
{
requestXml = ConvertRequestToString( requestStream );
}
ack = SIFPrimitives.ackError(
requestXml.ToString( ),
sifError,
this.Zone );
}
else
{
ack = parsed.AckError(
SifErrorCategoryCode.Generic,
SifErrorCodes.GENERIC_GENERIC_ERROR_1,
errorMessage,
parseEx.ToString() );
}
}
if ( (Adk.Debug & AdkDebugFlags.Messaging) != 0 ) {
Zone.Log.Warn
( "Failed to parse push message from zone \"" + Zone + "\": " + parseEx );
}
if ( ack != null ) {
// Ack messages in the same version of SIF as the original message
if ( parsed != null ) {
ack.SifVersion = parsed.SifVersion;
}
AckPush( ack, context.Response );
}
else {
// If we couldn't build a SIF_Ack, returning an HTTP 500 is
// probably the best we can do to let the server know that
// we didn't get the message. Note this should cause the ZIS
// to resend the message, which could result in a deadlock
// condition. The administrator would need to manually remove
// the offending message from the agent's queue.
if ( (Adk.Debug & AdkDebugFlags.Messaging) != 0 ) {
Zone.Log.Debug
( "Could not generate SIF_Ack for failed push message (returning HTTP/1.1 500)" );
}
throw new AdkHttpException
( AdkHttpStatusCode.ServerError_500_Internal_Server_Error,
"Could not generate SIF_Ack for failed push message (returning HTTP/1.1 500)" );
}
return;
}
// Check SourceId to see if it matches this agent's SourceId
String destId = parsed.DestinationId;
if ( destId != null && !destId.Equals( Zone.Agent.Id ) ) {
Zone.Log.Warn
( "Received push message for DestinationId \"" + destId +
"\", but agent is registered as \"" + Zone.Agent.Id + "\"" );
ack = parsed.AckError
(
SifErrorCategoryCode.Transport,
SifErrorCodes.WIRE_GENERIC_ERROR_1,
"Message not intended for this agent (SourceId of agent does not match DestinationId of message)",
"Message intended for \"" + destId + "\" but this agent is registered as \"" +
Zone.Agent.Id + "\"" );
AckPush( ack, context.Response );
return;
}
// Convert content to SIF message object and dispatch it
ack = ProcessPush( parsed );
// Send SIF_Ack reply
AckPush( ack, context.Response );
}
#endregion
private StringBuilder ConvertRequestToString( Stream requestStream )
{
requestStream.Seek( 0, SeekOrigin.Begin );
StreamReader reader = new StreamReader( requestStream, SifIOFormatter.ENCODING );
StringBuilder data = new StringBuilder( reader.ReadToEnd() );
// Reset the stream so that it can be read again.
requestStream.Seek( 0, SeekOrigin.Begin );
return data;
}
private void AckPush( SIF_Ack ack,
AdkHttpResponse response )
{
try {
// Set SIF_Ack / SIF_Header fields
SIF_Header hdr = ack.Header;
hdr.SIF_Timestamp = DateTime.Now;
hdr.SIF_MsgId = SifFormatter.GuidToSifRefID( Guid.NewGuid() );
hdr.SIF_SourceId = this.Zone.Agent.Id;
ack.LogSend( this.Zone.Log );
response.ContentType = SifIOFormatter.CONTENTTYPE;
// TODO: This code may need to change. The ADKHttpResponse should not automatically set the content length
// and other implementations will not do so.
SifWriter w = new SifWriter( response.GetResponseStream() );
w.Write( ack );
w.Flush();
}
catch ( Exception thr ) {
Console.Out.WriteLine
( "HttpProtocolHandler failed to send SIF_Ack for pushed message (zone=" +
this.Zone.ZoneId + "): " + thr );
throw new AdkHttpException
( AdkHttpStatusCode.ServerError_500_Internal_Server_Error, thr.Message, thr );
}
}
#endregion
#region Private Fields
//public static AnonymousHttpHandler sAnonymousHandler;
//private int URI_OFFSET;
/// <summary> The internal http/https server</summary>
protected internal static AdkHttpApplicationServer fServer = null;
#endregion
/// <summary>
/// Returns true if the protocol and underlying transport are currently active
/// for this zone
/// </summary>
/// <param name="zone"></param>
/// <returns>True if the protocol handler and transport are active</returns>
public override bool IsActive( ZoneImpl zone )
{
return fTransport.IsActive( zone ) && fServer != null && fServer.IsStarted;
}
/// <summary>
/// Creates the SIF_Protocol object that will be included with a SIF_Register
/// message sent to the zone associated with this Transport.</Summary>
/// <remarks>
/// The base class implementation creates an empty SIF_Protocol with zero
/// or more SIF_Property elements according to the parameters that have been
/// defined by the client via setParameter. Derived classes should therefore
/// call the superclass implementation first, then add to the resulting
/// SIF_Protocol element as needed.
/// </remarks>
/// <param name="zone"></param>
/// <returns></returns>
public override SIF_Protocol MakeSIF_Protocol( IZone zone )
{
SIF_Protocol proto = new SIF_Protocol();
fTransport.ConfigureSIF_Protocol(proto, zone);
return proto;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using GamePoc0.Areas.HelpPage.ModelDescriptions;
using GamePoc0.Areas.HelpPage.Models;
namespace GamePoc0.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using Xunit;
using Exercism.Tests;
public class TelemetryBufferTests
{
[Fact]
public void ToBuffer_upper_long()
{
var bytes = TelemetryBuffer.ToBuffer(Int64.MaxValue);
Assert.Equal(new byte[] { 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f }, bytes);
}
[Fact]
public void ToBuffer_lower_long()
{
var bytes = TelemetryBuffer.ToBuffer((long)UInt32.MaxValue + 1);
Assert.Equal(new byte[] { 0xf8, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_upper_uint()
{
var bytes = TelemetryBuffer.ToBuffer(UInt32.MaxValue);
Assert.Equal(new byte[] { 0x4, 0xff, 0xff, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_lower_uint()
{
var bytes = TelemetryBuffer.ToBuffer((long)Int32.MaxValue + 1);
Assert.Equal(new byte[] { 0x4, 0x0, 0x0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_upper_int()
{
var bytes = TelemetryBuffer.ToBuffer(Int32.MaxValue);
Assert.Equal(new byte[] { 0xfc, 0xff, 0xff, 0xff, 0x7f, 0x0, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_lower_int()
{
var bytes = TelemetryBuffer.ToBuffer((long)UInt16.MaxValue + 1);
Assert.Equal(new byte[] { 0xfc, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_upper_ushort()
{
var bytes = TelemetryBuffer.ToBuffer(UInt16.MaxValue);
Assert.Equal(new byte[] { 0x2, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_lower_ushort()
{
var bytes = TelemetryBuffer.ToBuffer((long)Int16.MaxValue + 1);
Assert.Equal(new byte[] { 0x2, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_upper_short()
{
var bytes = TelemetryBuffer.ToBuffer(Int16.MaxValue);
Assert.Equal(new byte[] { 0xfe, 0xff, 0x7f, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_Zero()
{
var bytes = TelemetryBuffer.ToBuffer(0);
Assert.Equal(new byte[] { 0xfe, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_upper_neg_short()
{
var bytes = TelemetryBuffer.ToBuffer(-1);
Assert.Equal(new byte[] { 0xfe, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_lower_neg_short()
{
var bytes = TelemetryBuffer.ToBuffer(Int16.MinValue);
Assert.Equal(new byte[] { 0xfe, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_upper_neg_int()
{
int n = Int16.MinValue - 1;
var bytes = TelemetryBuffer.ToBuffer(n);
Assert.Equal(new byte[] { 0xfc, 0xff, 0x7f, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_lower_neg_int()
{
var bytes = TelemetryBuffer.ToBuffer(Int32.MinValue);
Assert.Equal(new byte[] { 0xfc, 0x0, 0x0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0 }, bytes);
}
[Fact]
public void ToBuffer_upper_neg_long()
{
var bytes = TelemetryBuffer.ToBuffer((long)Int32.MinValue - 1);
Assert.Equal(new byte[] { 0xf8, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0xff }, bytes);
}
[Fact]
public void ToBuffer_lower_neg_long()
{
var bytes = TelemetryBuffer.ToBuffer(Int64.MinValue);
Assert.Equal(new byte[] { 0xf8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80 }, bytes);
}
[Fact]
public void FromBuffer_Invalid()
{
Assert.Equal(0,
TelemetryBuffer.FromBuffer(new byte[] { 22, 0xff, 0xff, 0xff, 0x7f, 0, 0, 0, 0 }));
}
[Fact]
public void FromBuffer_upper_long()
{
Assert.Equal(Int64.MaxValue,
TelemetryBuffer.FromBuffer(new byte[] { 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f }));
}
[Fact]
public void FromBuffer_lower_long()
{
Assert.Equal((long)UInt32.MaxValue + 1,
TelemetryBuffer.FromBuffer(new byte[] { 0xf8, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_upper_uint()
{
Assert.Equal(UInt32.MaxValue,
TelemetryBuffer.FromBuffer(new byte[] { 0x4, 0xff, 0xff, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_lower_uint()
{
Assert.Equal((long)Int32.MaxValue + 1,
TelemetryBuffer.FromBuffer(new byte[] { 0x4, 0x0, 0x0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_upper_int()
{
Assert.Equal(Int32.MaxValue,
TelemetryBuffer.FromBuffer(new byte[] { 0xfc, 0xff, 0xff, 0xff, 0x7f, 0x0, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_lower_int()
{
Assert.Equal(UInt16.MaxValue + 1,
TelemetryBuffer.FromBuffer(new byte[] { 0xfc, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_upper_ushort()
{
Assert.Equal(UInt16.MaxValue,
TelemetryBuffer.FromBuffer(new byte[] { 0x2, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_lower_ushort()
{
Assert.Equal(Int16.MaxValue + 1,
TelemetryBuffer.FromBuffer(new byte[] { 0x2, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_upper_short()
{
Assert.Equal(Int16.MaxValue,
TelemetryBuffer.FromBuffer(new byte[] { 0xfe, 0xff, 0x7f, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_Zero()
{
Assert.Equal(0,
TelemetryBuffer.FromBuffer(new byte[] { 0xfe, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_upper_neg_short()
{
Assert.Equal(-1,
TelemetryBuffer.FromBuffer(new byte[] { 0xfe, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_lower_neg_short()
{
Assert.Equal(Int16.MinValue,
TelemetryBuffer.FromBuffer(new byte[] { 0xfe, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_upper_neg_int()
{
Assert.Equal(Int16.MinValue - 1,
TelemetryBuffer.FromBuffer(new byte[] { 0xfc, 0xff, 0x7f, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_lower_neg_int()
{
Assert.Equal(Int32.MinValue,
TelemetryBuffer.FromBuffer(new byte[] { 0xfc, 0x0, 0x0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0 }));
}
[Fact]
public void FromBuffer_upper_neg_long()
{
Assert.Equal((long)Int32.MinValue - 1,
TelemetryBuffer.FromBuffer(new byte[] { 0xf8, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0xff }));
}
[Fact]
public void FromBuffer_lower_neg_long()
{
Assert.Equal(Int64.MinValue,
TelemetryBuffer.FromBuffer(new byte[] { 0xf8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80 }));
}
}
| |
// ***********************************************************************
// Copyright (c) 2017 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using NUnit.Framework;
using System;
namespace TestCentric.Gui.Model
{
[TestFixture]
public class ResultSummaryCreatorTests
{
[Test]
public void WhenResultNodeIsNotForTestRunExceptionIsThrown()
{
Assert.That(() => CreateResultSummary("<anything-other-than-test-run/>"),
Throws.InstanceOf<InvalidOperationException>());
Assert.That(() => CreateResultSummary("<test-run/>"),
Throws.Nothing);
}
[Test]
public void ResultOfTestRunIsValueOfOverallResult()
{
var innerXml = "<test-case result='Passed'/>";
var summary = CreateResultSummary($"<test-run result='Failed'>{innerXml}</test-run>");
Assert.That(summary.OverallResult, Is.EqualTo("Failed"));
}
[Test]
public void WhenResultIsNotSpecified_PassedIsDefault()
{
var innerXml = "<test-case result='Failed'/>";
var summary = CreateResultSummary($"<test-run>{innerXml}</test-run>");
Assert.That(summary.OverallResult, Is.EqualTo("Passed"));
}
[Test]
public void DurationOfTestRunIsValueOfDuration()
{
var innerXml = "<test-case duration='999'/>";
var summary = CreateResultSummary($"<test-run duration='1.9'>{innerXml}</test-run>");
Assert.That(summary.Duration, Is.EqualTo(1.9));
}
[Test]
public void WhenDurationIsNotSpecified_ZeroIsDefault()
{
var innerXml = "<test-case duration='999'/>";
var summary = CreateResultSummary($"<test-run>{innerXml}</test-run>");
Assert.That(summary.Duration, Is.EqualTo(0.0));
}
[Test]
public void StartTimeOfTestRunIsValueOfStartTime()
{
var expectedDate = new DateTime(2017, 7, 8, 6, 19, 23);
var innerXml = $"<test-case start-time='{DateTime.MinValue:u}'/>";
var summary = CreateResultSummary($"<test-run start-time='{expectedDate:u}'>{innerXml}</test-run>");
Assert.That(summary.StartTime, Is.EqualTo(expectedDate));
}
[Test]
public void WhenStartTimeIsNotSpecified_DateTimeMinValueIsDefault()
{
var innerXml = $"<test-case start-time='{DateTime.MaxValue:u}'/>";
var summary = CreateResultSummary($"<test-run>{innerXml}</test-run>");
Assert.That(summary.StartTime, Is.EqualTo(DateTime.MinValue));
}
[Test]
public void EndTimeOfTestRunIsValueOfEndTime()
{
var expectedDate = new DateTime(2017, 7, 8, 6, 19, 23);
var innerXml = $"<test-case end-time='{DateTime.MaxValue:u}'/>";
var summary = CreateResultSummary($"<test-run end-time='{expectedDate:u}'>{innerXml}</test-run>");
Assert.That(summary.EndTime, Is.EqualTo(expectedDate));
}
[Test]
public void WhenEndTimeIsNotSpecified_DateTimeMaxValueIsDefault()
{
var innerXml = $"<test-case end-time='{DateTime.MinValue:u}'/>";
var summary = CreateResultSummary($"<test-run>{innerXml}</test-run>");
Assert.That(summary.EndTime, Is.EqualTo(DateTime.MaxValue));
}
[Test]
public void TestCountIsCountOfEachNestedTestCase()
{
var innerXml =
"<test-case/>" +
"<test-case/>" +
"<test-suite>" +
"<test-case/>" +
"<test-case/>" +
"</test-suite>";
var summary = CreateResultSummary($"<test-run>{innerXml}</test-run>");
Assert.That(summary.TestCount, Is.EqualTo(4));
}
[Test]
public void WhenNoResultIsSpecifiedInTestCase_SkipCountIsIncremented()
{
var innerXml =
"<test-case result='Passed'/>" +
"<test-case/>";
var summary = CreateResultSummary($"<test-run>{innerXml}</test-run>");
Assert.That(summary.TestCount, Is.EqualTo(2));
Assert.That(summary.PassCount, Is.EqualTo(1));
Assert.That(summary.SkipCount, Is.EqualTo(1));
}
[Test]
public void ExtendedFailureInformationAreBasedOnLabel()
{
var innerXml =
"<test-case result='Failed'/>" +
"<test-case result='Failed' label='Invalid'/>" +
"<test-case result='Failed' label='Anything else increases ErrorCount'/>" +
"<test-case result='Failed' label='I am not null'/>";
var summary = CreateResultSummary($"<test-run>{innerXml}</test-run>");
Assert.That(summary.TestCount, Is.EqualTo(4));
Assert.That(summary.FailedCount, Is.EqualTo(4));
Assert.That(summary.FailureCount, Is.EqualTo(1));
Assert.That(summary.InvalidCount, Is.EqualTo(1));
Assert.That(summary.ErrorCount, Is.EqualTo(2));
}
[Test]
public void ExtendedSkipInformationAreBasedOnLabel()
{
var innerXml =
"<test-case result='Skipped'/>" +
"<test-case result='Skipped' label='Ignored'/>" +
"<test-case result='Skipped' label='Explicit'/>" +
"<test-case result='Skipped' label='Anything else increases SkippedCount'/>" +
"<test-case result='Skipped' label='I am not null'/>";
var summary = CreateResultSummary($"<test-run>{innerXml}</test-run>");
Assert.That(summary.TestCount, Is.EqualTo(5));
Assert.That(summary.TotalSkipCount, Is.EqualTo(5));
Assert.That(summary.SkipCount, Is.EqualTo(3));
Assert.That(summary.IgnoreCount, Is.EqualTo(1));
Assert.That(summary.ExplicitCount, Is.EqualTo(1));
}
[Test]
public void InvalidTestSuitesAreTracked()
{
var innerXml =
"<test-suite result='Failed' label='Invalid'/>" +
"<test-suite result='Failed' label='Invalid' type='Assembly'/>";
var summary = CreateResultSummary($"<test-run>{innerXml}</test-run>");
Assert.That(summary.InvalidTestFixtures, Is.EqualTo(1));
Assert.That(summary.InvalidAssemblies, Is.EqualTo(1));
Assert.That(summary.UnexpectedError, Is.False);
}
[Test]
public void ErrorAssembliesMarkSummaryAsUnexpectedError()
{
var innerXml =
"<test-suite result='Failed' label='Invalid' type='Assembly'/>" +
"<test-suite result='Failed' label='Error' type='Assembly'/>";
var summary = CreateResultSummary($"<test-run>{innerXml}</test-run>");
Assert.That(summary.InvalidAssemblies, Is.EqualTo(2));
Assert.That(summary.UnexpectedError, Is.True);
}
private ResultSummary CreateResultSummary(string xml)
{
var resultNode = new ResultNode(xml);
return ResultSummaryCreator.FromResultNode(resultNode);
}
}
}
| |
/*
Copyright (c) 2014, Lars Brubaker, Kevin Pope
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.Agg.Image;
namespace MatterHackers.Agg
{
public class FloodFill
{
protected byte[] destBuffer = null;
protected int imageStride = 0;
protected bool[] pixelsChecked;
private ImageBuffer destImage;
private FillingRule fillRule;
private FirstInFirstOutQueue<Range> ranges = new FirstInFirstOutQueue<Range>(9);
public FloodFill(RGBA_Bytes fillColor)
{
fillRule = new ExactMatch(fillColor);
}
public FloodFill(RGBA_Bytes fillColor, int tolerance0To255)
{
if (tolerance0To255 > 0)
{
fillRule = new ToleranceMatch(fillColor, tolerance0To255);
}
else
{
fillRule = new ExactMatch(fillColor);
}
}
public FloodFill(FillingRule fillRule)
{
this.fillRule = fillRule;
}
public void Fill(ImageBuffer bufferToFillOn, int x, int y)
{
unchecked // this way we can overflow the uint on negative and get a big number
{
if ((uint)x > bufferToFillOn.Width || (uint)y > bufferToFillOn.Height)
{
return;
}
}
destImage = bufferToFillOn;
imageStride = destImage.StrideInBytes();
destBuffer = destImage.GetBuffer();
int imageWidth = destImage.Width;
int imageHeight = destImage.Height;
pixelsChecked = new bool[destImage.Width * destImage.Height];
int startColorBufferOffset = destImage.GetBufferOffsetXY(x, y);
fillRule.SetStartColor(new RGBA_Bytes(destImage.GetBuffer()[startColorBufferOffset + 2], destImage.GetBuffer()[startColorBufferOffset + 1], destImage.GetBuffer()[startColorBufferOffset]));
LinearFill(x, y);
while (ranges.Count > 0)
{
Range range = ranges.Dequeue();
int downY = range.y - 1;
int upY = range.y + 1;
int downPixelOffset = (imageWidth * (range.y - 1)) + range.startX;
int upPixelOffset = (imageWidth * (range.y + 1)) + range.startX;
for (int rangeX = range.startX; rangeX <= range.endX; rangeX++)
{
if (range.y > 0)
{
if (!pixelsChecked[downPixelOffset])
{
int bufferOffset = destImage.GetBufferOffsetXY(rangeX, downY);
if (fillRule.CheckPixel(destBuffer, bufferOffset))
{
LinearFill(rangeX, downY);
}
}
}
if (range.y < (imageHeight - 1))
{
if (!pixelsChecked[upPixelOffset])
{
int bufferOffset = destImage.GetBufferOffsetXY(rangeX, upY);
if (fillRule.CheckPixel(destBuffer, bufferOffset))
{
LinearFill(rangeX, upY);
}
}
}
upPixelOffset++;
downPixelOffset++;
}
}
}
private void LinearFill(int x, int y)
{
int bytesPerPixel = destImage.GetBytesBetweenPixelsInclusive();
int imageWidth = destImage.Width;
int leftFillX = x;
int bufferOffset = destImage.GetBufferOffsetXY(x, y);
int pixelOffset = (imageWidth * y) + x;
while (true)
{
fillRule.SetPixel(destBuffer, bufferOffset);
pixelsChecked[pixelOffset] = true;
leftFillX--;
pixelOffset--;
bufferOffset -= bytesPerPixel;
if (leftFillX <= 0 || (pixelsChecked[pixelOffset]) || !fillRule.CheckPixel(destBuffer, bufferOffset))
{
break;
}
}
leftFillX++;
int rightFillX = x;
bufferOffset = destImage.GetBufferOffsetXY(x, y);
pixelOffset = (imageWidth * y) + x;
while (true)
{
fillRule.SetPixel(destBuffer, bufferOffset);
pixelsChecked[pixelOffset] = true;
rightFillX++;
pixelOffset++;
bufferOffset += bytesPerPixel;
if (rightFillX >= imageWidth || pixelsChecked[pixelOffset] || !fillRule.CheckPixel(destBuffer, bufferOffset))
{
break;
}
}
rightFillX--;
ranges.Enqueue(new Range(leftFillX, rightFillX, y));
}
private struct Range
{
public int endX;
public int startX;
public int y;
public Range(int startX, int endX, int y)
{
this.startX = startX;
this.endX = endX;
this.y = y;
}
}
public class ExactMatch : FillingRule
{
public ExactMatch(RGBA_Bytes fillColor)
: base(fillColor)
{
}
public override bool CheckPixel(byte[] destBuffer, int bufferOffset)
{
return (destBuffer[bufferOffset] == startColor.red) &&
(destBuffer[bufferOffset + 1] == startColor.green) &&
(destBuffer[bufferOffset + 2] == startColor.blue);
}
}
public abstract class FillingRule
{
protected RGBA_Bytes fillColor;
protected RGBA_Bytes startColor;
protected FillingRule(RGBA_Bytes fillColor)
{
this.fillColor = fillColor;
}
public abstract bool CheckPixel(byte[] destBuffer, int bufferOffset);
public virtual void SetPixel(byte[] destBuffer, int bufferOffset)
{
destBuffer[bufferOffset] = fillColor.blue;
destBuffer[bufferOffset + 1] = fillColor.green;
destBuffer[bufferOffset + 2] = fillColor.red;
}
public void SetStartColor(RGBA_Bytes startColor)
{
this.startColor = startColor;
}
}
public class ToleranceMatch : FillingRule
{
private int tolerance0To255;
public ToleranceMatch(RGBA_Bytes fillColor, int tolerance0To255)
: base(fillColor)
{
this.tolerance0To255 = tolerance0To255;
}
public override bool CheckPixel(byte[] destBuffer, int bufferOffset)
{
return (destBuffer[bufferOffset] >= (startColor.red - tolerance0To255)) && destBuffer[bufferOffset] <= (startColor.red + tolerance0To255) &&
(destBuffer[bufferOffset + 1] >= (startColor.green - tolerance0To255)) && destBuffer[bufferOffset + 1] <= (startColor.green + tolerance0To255) &&
(destBuffer[bufferOffset + 2] >= (startColor.blue - tolerance0To255)) && destBuffer[bufferOffset + 2] <= (startColor.blue + tolerance0To255);
}
}
}
}
| |
#region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// 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
using System;
using System.IO;
namespace NodaTime.TimeZones
{
/// <summary>
/// Very specific compressing binary writer for time zones.
/// </summary>
internal class DateTimeZoneCompressionWriter : DateTimeZoneWriter
{
internal const long HalfHoursMask = 0x3fL;
internal const long MaxHalfHours = 0x1fL;
internal const long MinHalfHours = -MaxHalfHours;
internal const int MaxMillisHalfHours = 0x3f;
internal const int MinMillisHalfHours = -MaxMillisHalfHours;
internal const long MaxMinutes = 0x1fffffL;
internal const long MinMinutes = -MaxMinutes;
internal const long MaxSeconds = 0x1fffffffffL;
internal const long MinSeconds = -MaxSeconds;
internal const int MaxMillisSeconds = 0x3ffff;
internal const int MinMillisSeconds = -MaxMillisSeconds;
internal const byte FlagHalfHour = 0x00;
internal const byte FlagMinutes = 0x40;
internal const byte FlagSeconds = 0x80;
internal const byte FlagMillisSeconds = 0x80;
internal const byte FlagTicks = 0xc0;
internal const byte FlagMilliseconds = 0xfd;
internal const byte FlagMaxValue = 0xfe;
internal const byte FlagMinValue = 0xff;
/// <summary>
/// Initializes a new instance of the <see cref="DateTimeZoneCompressionWriter" /> class.
/// </summary>
/// <param name="output">Where to send the serialized output.</param>
internal DateTimeZoneCompressionWriter(Stream output) : base(output)
{
}
/// <summary>
/// Writes the given non-negative integer value to the stream.
/// </summary>
/// <remarks>
/// Negative values are handled but in an inefficient way (5 bytes).
/// </remarks>
/// <param name="value">The value to write.</param>
internal override void WriteCount(int value)
{
unchecked
{
if (value < 0)
{
WriteInt8(0xff);
WriteInt32(value);
return;
}
if (value <= 0x0e)
{
WriteInt8((byte)(0xf0 + value));
return;
}
value -= 0x0f;
if (value <= 0x7f)
{
WriteInt8((byte)value);
return;
}
value -= 0x80;
if (value <= 0x3fff)
{
WriteInt8((byte)(0x80 + (value >> 8)));
WriteInt8((byte)(value & 0xff));
return;
}
value -= 0x4000;
if (value <= 0x1fffff)
{
WriteInt8((byte)(0xc0 + (value >> 16)));
WriteInt16((short)(value & 0xffff));
return;
}
value -= 0x200000;
if (value <= 0x0fffffff)
{
WriteInt8((byte)(0xe0 + (value >> 24)));
WriteInt8((byte)((value >> 16) & 0xff));
WriteInt16((short)(value & 0xffff));
return;
}
WriteInt8(0xff);
WriteInt32(value + 0x200000 + 0x4000 + 0x80 + 0x0f);
}
}
/// <summary>
/// Writes the integer milliseconds value to the stream.
/// </summary>
/// <param name="value">The value to write.</param>
internal override void WriteMilliseconds(int value)
{
/*
* Milliseconds encoding formats:
*
* upper bits units field length approximate range
* ---------------------------------------------------------------
* 0xxxxxxx 30 minutes 1 byte +/- 24 hours
* 10xxxxxx seconds 3 bytes +/- 24 hours
* 11111101 0xfd millis 5 byte Full range
* 11111110 0xfe 1 byte Int32.MaxValue
* 11111111 0xff 1 byte Int32.MinValue
*
* Remaining bits in field form signed offset from 1970-01-01T00:00:00Z.
*/
unchecked
{
if (value == Int32.MinValue)
{
WriteInt8(FlagMinValue);
return;
}
if (value == Int32.MaxValue)
{
WriteInt8(FlagMaxValue);
return;
}
if (value % (30 * NodaConstants.MillisecondsPerMinute) == 0)
{
// Try to write in 30 minute units.
int units = value / (30 * NodaConstants.MillisecondsPerMinute);
if (MinMillisHalfHours <= units && units <= MaxMillisHalfHours)
{
units = units + MaxMillisHalfHours;
WriteInt8((byte)(units & 0x7f));
return;
}
}
if (value % NodaConstants.MillisecondsPerSecond == 0)
{
// Try to write seconds.
int seconds = value / NodaConstants.MillisecondsPerSecond;
if (MinMillisSeconds <= seconds && seconds <= MaxMillisSeconds)
{
seconds = seconds + MaxMillisSeconds;
WriteInt8((byte)(FlagMillisSeconds | (byte)((seconds >> 16) & 0x3f)));
WriteInt16((short)(seconds & 0xffff));
return;
}
}
// Write milliseconds either because the additional precision is
// required or the minutes didn't fit in the field.
// Form 11 (64 bits effective precision, but write as if 70 bits)
WriteInt8(FlagMilliseconds);
WriteInt32(value);
}
}
/// <summary>
/// Writes the long ticks value to the stream.
/// </summary>
/// <param name="value">The value to write.</param>
internal override void WriteTicks(long value)
{
/*
* Ticks encoding formats:
*
* upper two bits units field length approximate range
* ---------------------------------------------------------------
* 00 30 minutes 1 byte +/- 16 hours
* 01 minutes 4 bytes +/- 1020 years
* 10 seconds 5 bytes +/- 4355 years
* 11000000 ticks 9 bytes +/- 292,000 years
* 11111100 0xfc 1 byte Offset.MaxValue
* 11111101 0xfd 1 byte Offset.MinValue
* 11111110 0xfe 1 byte Instant, LocalInstant, Duration MaxValue
* 11111111 0xff 1 byte Instant, LocalInstant, Duration MinValue
*
* Remaining bits in field form signed offset from 1970-01-01T00:00:00Z.
*/
unchecked
{
if (value == Int64.MinValue)
{
WriteInt8(FlagMinValue);
return;
}
if (value == Int64.MaxValue)
{
WriteInt8(FlagMaxValue);
return;
}
if (value % (30 * NodaConstants.TicksPerMinute) == 0)
{
// Try to write in 30 minute units.
long units = value / (30 * NodaConstants.TicksPerMinute);
if (MinHalfHours <= units && units <= MaxHalfHours)
{
units = units + MaxHalfHours;
WriteInt8((byte)(units & 0x3f));
return;
}
}
if (value % NodaConstants.TicksPerMinute == 0)
{
// Try to write minutes.
long minutes = value / NodaConstants.TicksPerMinute;
if (MinMinutes <= minutes && minutes <= MaxMinutes)
{
minutes = minutes + MaxMinutes;
WriteInt8((byte)(FlagMinutes | (byte)((minutes >> 16) & 0x3f)));
WriteInt16((short)(minutes & 0xffff));
return;
}
}
if (value % NodaConstants.TicksPerSecond == 0)
{
// Try to write seconds.
long seconds = value / NodaConstants.TicksPerSecond;
if (MinSeconds <= seconds && seconds <= MaxSeconds)
{
seconds = seconds + MaxSeconds;
WriteInt8((byte)(FlagSeconds | (byte)((seconds >> 32) & 0x3f)));
WriteInt32((int)(seconds & 0xffffffff));
return;
}
}
// Write milliseconds either because the additional precision is
// required or the minutes didn't fit in the field.
// Form 11 (64 bits effective precision, but write as if 70 bits)
WriteInt8(FlagTicks);
WriteInt64(value);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsRequiredOptional
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// ImplicitModel operations.
/// </summary>
public partial class ImplicitModel : IServiceOperations<AutoRestRequiredOptionalTestService>, IImplicitModel
{
/// <summary>
/// Initializes a new instance of the ImplicitModel class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public ImplicitModel(AutoRestRequiredOptionalTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestRequiredOptionalTestService
/// </summary>
public AutoRestRequiredOptionalTestService Client { get; private set; }
/// <summary>
/// Test implicitly required path parameter
/// </summary>
/// <param name='pathParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Error>> GetRequiredPathWithHttpMessagesAsync(string pathParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (pathParameter == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "pathParameter");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("pathParameter", pathParameter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetRequiredPath", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/implicit/required/path/{pathParameter}").ToString();
_url = _url.Replace("{pathParameter}", Uri.EscapeDataString(pathParameter));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Test implicitly optional query parameter
/// </summary>
/// <param name='queryParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutOptionalQueryWithHttpMessagesAsync(string queryParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("queryParameter", queryParameter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutOptionalQuery", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/implicit/optional/query").ToString();
List<string> _queryParameters = new List<string>();
if (queryParameter != null)
{
_queryParameters.Add(string.Format("queryParameter={0}", Uri.EscapeDataString(queryParameter)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Test implicitly optional header parameter
/// </summary>
/// <param name='queryParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutOptionalHeaderWithHttpMessagesAsync(string queryParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("queryParameter", queryParameter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutOptionalHeader", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/implicit/optional/header").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (queryParameter != null)
{
if (_httpRequest.Headers.Contains("queryParameter"))
{
_httpRequest.Headers.Remove("queryParameter");
}
_httpRequest.Headers.TryAddWithoutValidation("queryParameter", queryParameter);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Test implicitly optional body parameter
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutOptionalBodyWithHttpMessagesAsync(string bodyParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("bodyParameter", bodyParameter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutOptionalBody", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/implicit/optional/body").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Test implicitly required path parameter
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Error>> GetRequiredGlobalPathWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.RequiredGlobalPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.RequiredGlobalPath");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetRequiredGlobalPath", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/global/required/path/{required-global-path}").ToString();
_url = _url.Replace("{required-global-path}", Uri.EscapeDataString(this.Client.RequiredGlobalPath));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Test implicitly required query parameter
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Error>> GetRequiredGlobalQueryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.RequiredGlobalQuery == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.RequiredGlobalQuery");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetRequiredGlobalQuery", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/global/required/query").ToString();
List<string> _queryParameters = new List<string>();
if (this.Client.RequiredGlobalQuery != null)
{
_queryParameters.Add(string.Format("required-global-query={0}", Uri.EscapeDataString(this.Client.RequiredGlobalQuery)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Test implicitly optional query parameter
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Error>> GetOptionalGlobalQueryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetOptionalGlobalQuery", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "reqopt/global/optional/query").ToString();
List<string> _queryParameters = new List<string>();
if (this.Client.OptionalGlobalQuery != null)
{
_queryParameters.Add(string.Format("optional-global-query={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(this.Client.OptionalGlobalQuery, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//******************************************
// Copyright (C) 2014-2015 Charles Nurse *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using FamilyTreeProject.GEDCOM.Common;
using FamilyTreeProject.GEDCOM.IO;
using FamilyTreeProject.GEDCOM.Records;
// ReSharper disable ConvertPropertyToExpressionBody
namespace FamilyTreeProject.GEDCOM
{
/// <summary>
/// This Class provides utilities for working with GEDCOM 5.5 data
/// </summary>
public class GEDCOMDocument
{
#region Private Members
private GEDCOMRecordList _familyRecords;
private GEDCOMHeaderRecord _headerRecord;
private GEDCOMRecordList _individualRecords;
private GEDCOMRecordList _multimediaRecords;
private GEDCOMRecordList _noteRecords;
private GEDCOMRecordList _records = new GEDCOMRecordList();
private GEDCOMRecordList _repositoryRecords;
private GEDCOMRecordList _sourceRecords;
private GEDCOMRecordList _submitterRecords;
private GEDCOMRecord _trailerRecord;
#endregion
#region Public Properties
public GEDCOMRecordList FamilyRecords
{
get { return _familyRecords ?? (_familyRecords = _records.GetLinesByTag(GEDCOMTag.FAM)); }
}
public GEDCOMRecordList IndividualRecords
{
get { return _individualRecords ?? (_individualRecords = _records.GetLinesByTag(GEDCOMTag.INDI)); }
}
public GEDCOMRecordList MultimediaRecords
{
get { return _multimediaRecords ?? (_multimediaRecords = _records.GetLinesByTag(GEDCOMTag.OBJE)); }
}
public GEDCOMRecordList NoteRecords
{
get { return _noteRecords ?? (_noteRecords = _records.GetLinesByTag(GEDCOMTag.NOTE)); }
}
public GEDCOMRecordList Records
{
get { return _records; }
}
public GEDCOMRecordList RepositoryRecords
{
get { return _repositoryRecords ?? (_repositoryRecords = _records.GetLinesByTag(GEDCOMTag.REPO)); }
}
public GEDCOMRecordList SourceRecords
{
get { return _sourceRecords ?? (_sourceRecords = _records.GetLinesByTag(GEDCOMTag.SOUR)); }
}
public GEDCOMSubmissionRecord Submission
{
get { return _records.GetLineByTag<GEDCOMSubmissionRecord>(GEDCOMTag.SUBN); }
}
public GEDCOMRecordList SubmitterRecords
{
get { return _submitterRecords ?? (_submitterRecords = _records.GetLinesByTag(GEDCOMTag.SUBM)); }
}
#endregion
#region Public Methods
/// <summary>
/// Adds a record to the GEDCOM Document
/// </summary>
/// <param name = "record">The record to add</param>
public void AddRecord(GEDCOMRecord record)
{
if (record == null)
{
throw new ArgumentNullException(typeof(GEDCOMRecord).Name);
}
_records.Add(record);
//clear the assoicated RecordList so it is refreshed next time around
ClearList(record.TagName);
}
/// <summary>
/// Adds a List of records to the GEDCOM Document
/// </summary>
/// <param name = "records">The list of records to add</param>
public void AddRecords(GEDCOMRecordList records)
{
if (records == null)
{
throw new ArgumentNullException(typeof(GEDCOMRecordList).Name);
}
_records.AddRange(records);
}
/// <summary>
/// Loads the GEDCOM Document from a Stream
/// </summary>
/// <param name = "stream">The stream to load</param>
public void Load(Stream stream)
{
using (var reader = GEDCOMReader.Create(stream))
{
_records = reader.Read();
}
}
/// <summary>
/// Loads the GEDCOM Document from a TextReader
/// </summary>
/// <param name = "reader">The TextReader to load</param>
public void Load(TextReader reader)
{
Load(GEDCOMReader.Create(reader));
}
/// <summary>
/// Loads the GEDCOM Document from a GEDCOMReader
/// </summary>
/// <param name = "reader">The GEDCOMReader to load.</param>
public void Load(GEDCOMReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
//Read the GEDCOM file into a GEDCOMRecords Collection
_records = reader.Read();
}
/// <summary>
/// Loads the GEDCOM Document from a String
/// </summary>
/// <param name = "text">The String to load</param>
public void LoadGEDCOM(string text)
{
//Load(GEDCOMReader.Create(text));
using (var reader = GEDCOMReader.Create(text))
{
_records = reader.Read();
}
}
/// <summary>
/// Removes a single record from the Document
/// </summary>
/// <param name = "record"></param>
public void RemoveRecord(GEDCOMRecord record)
{
if (record == null)
{
throw new ArgumentNullException(typeof(GEDCOMRecord).Name);
}
if (_records.Remove(record))
{
//clear the assoicated RecordList so it is refreshed next time around
ClearList(record.TagName);
}
else
{
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Save the GEDCOM Document to a Stream.
/// </summary>
/// <param name = "stream">The streanm to save to.</param>
public void Save(Stream stream)
{
using (var writer = GEDCOMWriter.Create(stream))
{
Save(writer);
}
}
/// <summary>
/// Save the GEDCOM Document to a TextWriter
/// </summary>
/// <param name = "writer">The TextWriter to save to</param>
public void Save(TextWriter writer)
{
Save(GEDCOMWriter.Create(writer));
}
/// <summary>
/// Save the GEDCOM Document to a GEDCOMWriter
/// </summary>
/// <param name = "writer">The GEDCOMWriter to save to.</param>
public void Save(GEDCOMWriter writer)
{
if (writer == null)
{
throw new ArgumentNullException(typeof(GEDCOMWriter).Name);
}
writer.NewLine = "\n";
if (SelectTrailer() == null)
{
AddRecord(new GEDCOMRecord(0, "", "", "TRLR", ""));
}
//Write Header
writer.WriteRecord(SelectHeader());
//Write Submitters
writer.WriteRecords(SubmitterRecords, true);
//Write individuals
writer.WriteRecords(IndividualRecords, true);
//Write families
writer.WriteRecords(FamilyRecords, true);
//Write Trailer
writer.WriteRecord(SelectTrailer());
writer.Flush();
}
/// <summary>
/// Save the GEDCOM Document to a String
/// </summary>
/// <returns>The String representation of the document</returns>
public string SaveGEDCOM()
{
var sb = new StringBuilder();
using (var writer = GEDCOMWriter.Create(sb))
{
Save(writer);
}
return sb.ToString();
}
public GEDCOMFamilyRecord SelectChildsFamilyRecord(string childId)
{
if (String.IsNullOrEmpty(childId))
{
throw new ArgumentNullException(typeof(string).Name);
}
return (from GEDCOMFamilyRecord familyRecord in FamilyRecords
where familyRecord.Children.Contains(childId)
select familyRecord)
.SingleOrDefault();
}
public GEDCOMFamilyRecord SelectFamilyRecord(string id)
{
GEDCOMFamilyRecord family;
try
{
family = FamilyRecords[id] as GEDCOMFamilyRecord;
}
catch (ArgumentOutOfRangeException)
{
family = null;
}
return family;
}
public GEDCOMFamilyRecord SelectFamilyRecord(string husbandId, string wifeId)
{
if (husbandId == null)
{
throw new ArgumentNullException(typeof(string).Name);
}
if (wifeId == null)
{
throw new ArgumentNullException(typeof(string).Name);
}
return (from GEDCOMFamilyRecord familyRecord in FamilyRecords
where familyRecord.Husband == husbandId && familyRecord.Wife == wifeId
select familyRecord)
.SingleOrDefault();
}
public IEnumerable<GEDCOMFamilyRecord> SelectFamilyRecords(string individualId)
{
if (String.IsNullOrEmpty(individualId))
{
throw new ArgumentNullException(typeof(string).Name);
}
return from GEDCOMFamilyRecord familyRecord in FamilyRecords
where (familyRecord.Husband == individualId) || (familyRecord.Wife == individualId)
select familyRecord;
}
public GEDCOMHeaderRecord SelectHeader()
{
return _headerRecord ?? (_headerRecord = _records.GetLineByTag<GEDCOMHeaderRecord>(GEDCOMTag.HEAD));
}
public IEnumerable<GEDCOMFamilyRecord> SelectHusbandsFamilyRecords(string husbandId)
{
if (husbandId == null)
{
throw new ArgumentNullException(typeof(string).Name);
}
return from GEDCOMFamilyRecord familyRecord in FamilyRecords
where familyRecord.Husband == husbandId
select familyRecord;
}
public GEDCOMIndividualRecord SelectIndividualRecord(string id)
{
GEDCOMIndividualRecord individual;
try
{
individual = IndividualRecords[id] as GEDCOMIndividualRecord;
}
catch (ArgumentOutOfRangeException)
{
individual = null;
}
return individual;
}
public GEDCOMMultimediaRecord SelectMultimediaRecord(string id)
{
return MultimediaRecords[id] as GEDCOMMultimediaRecord;
}
public GEDCOMNoteRecord SelectNoteRecord(string id)
{
return NoteRecords[id] as GEDCOMNoteRecord;
}
public GEDCOMRecord SelectRecord(string id)
{
GEDCOMRecord record;
try
{
record = _records[id];
}
catch (ArgumentOutOfRangeException)
{
record = null;
}
return record;
}
public GEDCOMRepositoryRecord SelectRepositoryRecord(string id)
{
return RepositoryRecords[id] as GEDCOMRepositoryRecord;
}
public GEDCOMSourceRecord SelectSourceRecord(string id)
{
return SourceRecords[id] as GEDCOMSourceRecord;
}
public GEDCOMSubmitterRecord SelectSubmitterRecord(string id)
{
return SubmitterRecords[id] as GEDCOMSubmitterRecord;
}
public GEDCOMRecord SelectTrailer()
{
return _trailerRecord ?? (_trailerRecord = _records.GetLineByTag<GEDCOMRecord>(GEDCOMTag.TRLR));
}
public IEnumerable<GEDCOMFamilyRecord> SelectWifesFamilyRecords(string wifeId)
{
if (wifeId == null)
{
throw new ArgumentNullException(typeof(string).Name);
}
return from GEDCOMFamilyRecord familyRecord in FamilyRecords
where familyRecord.Wife == wifeId
select familyRecord;
}
/// <summary>
/// ToString creates a string represenattion of the GEDCOMDocument
/// </summary>
/// <returns>a String</returns>
public override string ToString()
{
return _records.ToString();
}
#endregion
private void ClearList(GEDCOMTag tag)
{
switch (tag)
{
case GEDCOMTag.INDI:
_individualRecords = null;
break;
case GEDCOMTag.FAM:
_familyRecords = null;
break;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
namespace System.Net.Http.Headers
{
public class WarningHeaderValue : ICloneable
{
private int _code;
private string _agent;
private string _text;
private DateTimeOffset? _date;
public int Code
{
get { return _code; }
}
public string Agent
{
get { return _agent; }
}
public string Text
{
get { return _text; }
}
public DateTimeOffset? Date
{
get { return _date; }
}
public WarningHeaderValue(int code, string agent, string text)
{
CheckCode(code);
CheckAgent(agent);
HeaderUtilities.CheckValidQuotedString(text, "text");
_code = code;
_agent = agent;
_text = text;
}
public WarningHeaderValue(int code, string agent, string text, DateTimeOffset date)
{
CheckCode(code);
CheckAgent(agent);
HeaderUtilities.CheckValidQuotedString(text, "text");
_code = code;
_agent = agent;
_text = text;
_date = date;
}
private WarningHeaderValue()
{
}
private WarningHeaderValue(WarningHeaderValue source)
{
Contract.Requires(source != null);
_code = source._code;
_agent = source._agent;
_text = source._text;
_date = source._date;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
// Warning codes are always 3 digits according to RFC2616
sb.Append(_code.ToString("000", NumberFormatInfo.InvariantInfo));
sb.Append(' ');
sb.Append(_agent);
sb.Append(' ');
sb.Append(_text);
if (_date.HasValue)
{
sb.Append(" \"");
sb.Append(HttpRuleParser.DateToString(_date.Value));
sb.Append('\"');
}
return sb.ToString();
}
public override bool Equals(object obj)
{
WarningHeaderValue other = obj as WarningHeaderValue;
if (other == null)
{
return false;
}
// 'agent' is a host/token, i.e. use case-insensitive comparison. Use case-sensitive comparison for 'text'
// since it is a quoted string.
if ((_code != other._code) || (string.Compare(_agent, other._agent, StringComparison.OrdinalIgnoreCase) != 0) ||
(string.CompareOrdinal(_text, other._text) != 0))
{
return false;
}
// We have a date set. Verify 'other' has also a date that matches our value.
if (_date.HasValue)
{
return other._date.HasValue && (_date.Value == other._date.Value);
}
// We don't have a date. If 'other' has a date, we're not equal.
return !other._date.HasValue;
}
public override int GetHashCode()
{
int result = _code.GetHashCode() ^ _agent.ToLowerInvariant().GetHashCode() ^ _text.GetHashCode();
if (_date.HasValue)
{
result = result ^ _date.Value.GetHashCode();
}
return result;
}
public static WarningHeaderValue Parse(string input)
{
int index = 0;
return (WarningHeaderValue)GenericHeaderParser.SingleValueWarningParser.ParseValue(input, null, ref index);
}
public static bool TryParse(string input, out WarningHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.SingleValueWarningParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (WarningHeaderValue)output;
return true;
}
return false;
}
internal static int GetWarningLength(string input, int startIndex, out object parsedValue)
{
Contract.Requires(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Read <code> in '<code> <agent> <text> ["<date>"]'
int code;
int current = startIndex;
if (!TryReadCode(input, ref current, out code))
{
return 0;
}
// Read <agent> in '<code> <agent> <text> ["<date>"]'
string agent;
if (!TryReadAgent(input, current, ref current, out agent))
{
return 0;
}
// Read <text> in '<code> <agent> <text> ["<date>"]'
int textLength = 0;
int textStartIndex = current;
if (HttpRuleParser.GetQuotedStringLength(input, current, out textLength) != HttpParseResult.Parsed)
{
return 0;
}
current = current + textLength;
// Read <date> in '<code> <agent> <text> ["<date>"]'
DateTimeOffset? date = null;
if (!TryReadDate(input, ref current, out date))
{
return 0;
}
WarningHeaderValue result = new WarningHeaderValue();
result._code = code;
result._agent = agent;
result._text = input.Substring(textStartIndex, textLength);
result._date = date;
parsedValue = result;
return current - startIndex;
}
private static bool TryReadAgent(string input, int startIndex, ref int current, out string agent)
{
agent = null;
int agentLength = HttpRuleParser.GetHostLength(input, startIndex, true, out agent);
if (agentLength == 0)
{
return false;
}
current = current + agentLength;
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
// At least one whitespace required after <agent>. Also make sure we have characters left for <text>
if ((whitespaceLength == 0) || (current == input.Length))
{
return false;
}
return true;
}
private static bool TryReadCode(string input, ref int current, out int code)
{
code = 0;
int codeLength = HttpRuleParser.GetNumberLength(input, current, false);
// code must be a 3 digit value. We accept less digits, but we don't accept more.
if ((codeLength == 0) || (codeLength > 3))
{
return false;
}
if (!HeaderUtilities.TryParseInt32(input.Substring(current, codeLength), out code))
{
Debug.Assert(false, "Unable to parse value even though it was parsed as <=3 digits string. Input: '" +
input + "', Current: " + current + ", CodeLength: " + codeLength);
return false;
}
current = current + codeLength;
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
// Make sure the number is followed by at least one whitespace and that we have characters left to parse.
if ((whitespaceLength == 0) || (current == input.Length))
{
return false;
}
return true;
}
private static bool TryReadDate(string input, ref int current, out DateTimeOffset? date)
{
date = null;
// Make sure we have at least one whitespace between <text> and <date> (if we have <date>)
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
// Read <date> in '<code> <agent> <text> ["<date>"]'
if ((current < input.Length) && (input[current] == '"'))
{
if (whitespaceLength == 0)
{
return false; // we have characters after <text> but they were not separated by a whitespace
}
current++; // skip opening '"'
// Find the closing '"'
int dateStartIndex = current;
while (current < input.Length)
{
if (input[current] == '"')
{
break;
}
current++;
}
if ((current == input.Length) || (current == dateStartIndex))
{
return false; // we couldn't find the closing '"' or we have an empty quoted string.
}
DateTimeOffset temp;
if (!HttpRuleParser.TryStringToDate(input.Substring(dateStartIndex, current - dateStartIndex), out temp))
{
return false;
}
date = temp;
current++; // skip closing '"'
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
return true;
}
object ICloneable.Clone()
{
return new WarningHeaderValue(this);
}
private static void CheckCode(int code)
{
if ((code < 0) || (code > 999))
{
throw new ArgumentOutOfRangeException("code");
}
}
private static void CheckAgent(string agent)
{
if (string.IsNullOrEmpty(agent))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "agent");
}
// 'receivedBy' can either be a host or a token. Since a token is a valid host, we only verify if the value
// is a valid host.
string host = null;
if (HttpRuleParser.GetHostLength(agent, 0, true, out host) != agent.Length)
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, agent));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using CodeRuse.Email.Client.Areas.HelpPage.ModelDescriptions;
using CodeRuse.Email.Client.Areas.HelpPage.Models;
namespace CodeRuse.Email.Client.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Monitor.Management
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Monitor;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ActivityLogAlertsOperations.
/// </summary>
public static partial class ActivityLogAlertsOperationsExtensions
{
/// <summary>
/// Create a new activity log alert or update an existing one.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='activityLogAlertName'>
/// The name of the activity log alert.
/// </param>
/// <param name='activityLogAlert'>
/// The activity log alert to create or use for the update.
/// </param>
public static ActivityLogAlertResource CreateOrUpdate(this IActivityLogAlertsOperations operations, string resourceGroupName, string activityLogAlertName, ActivityLogAlertResource activityLogAlert)
{
return operations.CreateOrUpdateAsync(resourceGroupName, activityLogAlertName, activityLogAlert).GetAwaiter().GetResult();
}
/// <summary>
/// Create a new activity log alert or update an existing one.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='activityLogAlertName'>
/// The name of the activity log alert.
/// </param>
/// <param name='activityLogAlert'>
/// The activity log alert to create or use for the update.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ActivityLogAlertResource> CreateOrUpdateAsync(this IActivityLogAlertsOperations operations, string resourceGroupName, string activityLogAlertName, ActivityLogAlertResource activityLogAlert, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, activityLogAlertName, activityLogAlert, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get an activity log alert.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='activityLogAlertName'>
/// The name of the activity log alert.
/// </param>
public static ActivityLogAlertResource Get(this IActivityLogAlertsOperations operations, string resourceGroupName, string activityLogAlertName)
{
return operations.GetAsync(resourceGroupName, activityLogAlertName).GetAwaiter().GetResult();
}
/// <summary>
/// Get an activity log alert.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='activityLogAlertName'>
/// The name of the activity log alert.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ActivityLogAlertResource> GetAsync(this IActivityLogAlertsOperations operations, string resourceGroupName, string activityLogAlertName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, activityLogAlertName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete an activity log alert.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='activityLogAlertName'>
/// The name of the activity log alert.
/// </param>
public static void Delete(this IActivityLogAlertsOperations operations, string resourceGroupName, string activityLogAlertName)
{
operations.DeleteAsync(resourceGroupName, activityLogAlertName).GetAwaiter().GetResult();
}
/// <summary>
/// Delete an activity log alert.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='activityLogAlertName'>
/// The name of the activity log alert.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IActivityLogAlertsOperations operations, string resourceGroupName, string activityLogAlertName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, activityLogAlertName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Updates an existing ActivityLogAlertResource's tags. To update other fields
/// use the CreateOrUpdate method.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='activityLogAlertName'>
/// The name of the activity log alert.
/// </param>
/// <param name='activityLogAlertPatch'>
/// Parameters supplied to the operation.
/// </param>
public static ActivityLogAlertResource Update(this IActivityLogAlertsOperations operations, string resourceGroupName, string activityLogAlertName, ActivityLogAlertPatchBody activityLogAlertPatch)
{
return operations.UpdateAsync(resourceGroupName, activityLogAlertName, activityLogAlertPatch).GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing ActivityLogAlertResource's tags. To update other fields
/// use the CreateOrUpdate method.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='activityLogAlertName'>
/// The name of the activity log alert.
/// </param>
/// <param name='activityLogAlertPatch'>
/// Parameters supplied to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ActivityLogAlertResource> UpdateAsync(this IActivityLogAlertsOperations operations, string resourceGroupName, string activityLogAlertName, ActivityLogAlertPatchBody activityLogAlertPatch, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, activityLogAlertName, activityLogAlertPatch, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get a list of all activity log alerts in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IEnumerable<ActivityLogAlertResource> ListBySubscriptionId(this IActivityLogAlertsOperations operations)
{
return operations.ListBySubscriptionIdAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of all activity log alerts in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<ActivityLogAlertResource>> ListBySubscriptionIdAsync(this IActivityLogAlertsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBySubscriptionIdWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get a list of all activity log alerts in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IEnumerable<ActivityLogAlertResource> ListByResourceGroup(this IActivityLogAlertsOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of all activity log alerts in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<ActivityLogAlertResource>> ListByResourceGroupAsync(this IActivityLogAlertsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2017 Daniel Liew
//
// This file is licensed under the MIT license.
// See LICENSE.txt for details.
//------------------------------------------------------------------------------
using System;
using System.Numerics;
using System.Collections.Generic;
using Microsoft.Boogie;
using System.Diagnostics;
using System.Linq;
namespace Symbooglix
{
public class LimitLoopBoundScheduler : IStateScheduler
{
IStateScheduler UnderlyingScheduler;
Dictionary<ExecutionState, ExecutionStateNestedLoopInfo> StateToCurrentLoops;
public readonly BigInteger LoopBound;
protected Executor Executor;
public ProgramLoopInfo ProgramLoopInfo { get; private set; }
public LimitLoopBoundScheduler(IStateScheduler underlyingScheduler, BigInteger loopBound)
{
this.UnderlyingScheduler = underlyingScheduler;
this.LoopBound = loopBound;
if (this.LoopBound < 0)
{
throw new ArgumentException("Invalid loop bound");
}
this.StateToCurrentLoops = new Dictionary<ExecutionState, ExecutionStateNestedLoopInfo>();
this.ProgramLoopInfo = null; // Set elsewhere
this.Executor = null; // Set elsewhere
}
private bool InitLoopInfoFor(ExecutionState state)
{
if (StateToCurrentLoops.ContainsKey(state))
return false;
StateToCurrentLoops.Add(state, new ExecutionStateNestedLoopInfo(state));
return true;
}
public ExecutionState GetNextState()
{
ExecutionState state = UnderlyingScheduler.GetNextState();
while (state != null)
{
if (!CheckLoopBoundExceeded(state))
{
// Still in bounds.
return state;
}
// Bound exceeded
// Get location for termination
var currentInstruction = state.Mem.Stack.Last().CurrentInstruction;
// FIXME: This is an implementation detail of the Executor that we shouldn't
// have to deal with.
if (currentInstruction.Current == null)
currentInstruction.MoveNext();
var progLocation = currentInstruction.Current.GetProgramLocation();
var terminationType = new TerminatedWithDisallowedLoopBound(progLocation, LoopBound);
// Kill state and let the Executor call us to remove the states.
Executor.TerminateState(/*state=*/ state, /*type=*/ terminationType, /*removeFromStateScheduler=*/true);
// Try another state
state = UnderlyingScheduler.GetNextState();
}
return null;
}
public void AddState(ExecutionState toAdd)
{
InitLoopInfoFor(toAdd);
UnderlyingScheduler.AddState(toAdd);
}
public void RemoveState(ExecutionState toRemove)
{
StateToCurrentLoops.Remove(toRemove);
UnderlyingScheduler.RemoveState(toRemove);
}
public void RemoveAll()
{
StateToCurrentLoops.Clear();
UnderlyingScheduler.RemoveAll();
}
public int GetNumberOfStates()
{
return UnderlyingScheduler.GetNumberOfStates();
}
public void ReceiveExecutor(Executor executor)
{
this.Executor = executor;
// Guard just in case the Executor calls us again. This can
// happen if there are multiple entry points.
if (this.ProgramLoopInfo == null)
{
this.ProgramLoopInfo = new ProgramLoopInfo(executor.TheProgram);
// Register the callbacks we need
executor.BasicBlockChanged += Executor_BasicBlockChanged;
executor.ForkOccurred += Executor_ForkOccurred;
executor.ImplementationEntered += Executor_ImplementationEntered;
}
// Give the underlying executor access to the scheduler
UnderlyingScheduler.ReceiveExecutor(executor);
}
void Executor_ImplementationEntered(object sender, Symbooglix.Executor.EnterImplementationEventArgs e)
{
// Handle the case where we enter a new implementation and the first block
// is a loop header. This is the only case we don't get notified of a basic block
// change.
var state = Executor.CurrentState; // FIXME: The state should be part of the event arg
var sf = state.Mem.Stack.Last();
var loopInfo = ProgramLoopInfo.GetLoopInfoForHeader(sf.CurrentBlock);
if (loopInfo == null)
return; // Not a loop. Nothing to do.
var executionStateSingleLoopInfo = new ExecutionStateSingleLoopInfo(sf, loopInfo);
StateToCurrentLoops[state].NestedLoops.Push(executionStateSingleLoopInfo);
}
void Executor_BasicBlockChanged(object sender, Symbooglix.Executor.TransferToBlockEventArgs eventArgs)
{
// Control flow has transferred to a different basic block
var state = eventArgs.State;
var sf = state.Mem.Stack.Last();
var executionStateNestedLoopInfo = StateToCurrentLoops[state];
// Cases:
// * No existing loops, enter loop header
// * No existing loops, do not enter loop header
// * Existing loop, stackframe doesn't match (i.e. a call must have happenend), enter loop header
// * Existing loop, stackframe doesn't match (i.e. a call must have happenend), do not enter loop header
// * Existing loop, stackframe matches, enter loop header (must increment counter)
// * Existing loop, stackframe matches, leave loop via exit basic block (we are leaving the current loop)
// * Existing loop, stackframe matches, enter nested loop header (must push new loop on to stack)
// * Existing loop, stackframe matches, stay in current loop (nothing to do)
bool stackframeMatches = false;
if (executionStateNestedLoopInfo.NestedLoops.Count > 0)
{
stackframeMatches = object.ReferenceEquals(executionStateNestedLoopInfo.NestedLoops.Peek().Stack,
sf);
}
ExecutionStateSingleLoopInfo executionStateSingleLoopInfo = null;
if (!stackframeMatches)
{
// This handles the case that there are no existing loops on the stack or
// there are existing loops but they are in another stackframe (i.e. we were in a loop
// and then called into another implementation).
var loopInfo = ProgramLoopInfo.GetLoopInfoForHeader(eventArgs.NewBlock);
if (loopInfo == null)
{
// The block we've entered is not a loop header and there are no
// existing loops we are in that we can enter/exit so there is nothing
// left to do
return;
}
// We've enterred a new loop push it on to the loop stack
executionStateSingleLoopInfo = new ExecutionStateSingleLoopInfo(sf, loopInfo);
executionStateNestedLoopInfo.NestedLoops.Push(executionStateSingleLoopInfo);
return;
}
// We are currently inside a loop and are still in the context of that loop's stackframe on the
// call stack.
executionStateSingleLoopInfo = executionStateNestedLoopInfo.NestedLoops.Peek();
if (object.ReferenceEquals(executionStateSingleLoopInfo.LInfo.Header, eventArgs.NewBlock)) {
// We are going to the loop header so we must have just completed one iteration
// of the loop. Increment the counter.
executionStateSingleLoopInfo.IncrementCounter();
// Don't check bound here. The executor will misbehave (see goto look ahead)
// if we try to terminate state here.
return;
}
else if (executionStateSingleLoopInfo.LInfo.EscapingBlocks.Contains(eventArgs.NewBlock))
{
// We are in a loop but are about to jump to a basic block that escapes from the loop.
// So pop this loop from the stack.
executionStateNestedLoopInfo.NestedLoops.Pop();
return;
}
var newLoopInfo = ProgramLoopInfo.GetLoopInfoForHeader(eventArgs.NewBlock);
if (newLoopInfo == null)
{
// We are in a loop but we are jumping to a basic block that
// * does not escape the current loop
// * does not go to the loop head
// * does not enter a nested loop (i.e. another loop head)
// So there is nothing left to do.
return;
}
// We are entering a nested loop. Push this loop onto the stack.
var newExecutionStateSingleLoopInfo = new ExecutionStateSingleLoopInfo(sf, newLoopInfo);
executionStateNestedLoopInfo.NestedLoops.Push(newExecutionStateSingleLoopInfo);
return;
}
bool CheckLoopBoundExceeded(ExecutionState state)
{
var executionStateNestedLoopInfo = StateToCurrentLoops[state];
if (executionStateNestedLoopInfo.NestedLoops.Count == 0)
return false;
if (executionStateNestedLoopInfo.NestedLoops.Peek().Counter <= LoopBound)
return false;
// Loop bound exceeded
return true;
}
void Executor_ForkOccurred(object sender, Symbooglix.Executor.ForkEventArgs eventArgs)
{
if (StateToCurrentLoops.ContainsKey(eventArgs.Child))
throw new ArgumentException("Child ExecutionState should not already be stored");
if (!StateToCurrentLoops.ContainsKey(eventArgs.Parent))
throw new ArgumentException("Parent ExecutionState should have been stored already");
// Make a copy of the parent's `ExecutionStateNestedLoopInfo` but replace
// references to stackframes so they point to the child's
var childLoopInfo = StateToCurrentLoops[eventArgs.Parent].Clone(eventArgs.Child);
StateToCurrentLoops.Add(eventArgs.Child, childLoopInfo);
}
public void WriteAsYAML(System.CodeDom.Compiler.IndentedTextWriter TW)
{
TW.WriteLine("name : \"{0}\"", this.GetType().ToString());
TW.WriteLine("loop_bound: {0}", this.LoopBound);
TW.WriteLine("underlying_scheduler:");
TW.Indent += 1;
UnderlyingScheduler.WriteAsYAML(TW);
TW.Indent -= 1;
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
public partial class Backoffice_Tarif_ListKL : System.Web.UI.Page
{
public int NoKe = 0;
protected string dsReportSessionName = "dsTarifKL";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["TarifManagement"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
if (Session["AddTarif"] != null)
{
btnNew.Visible = true;
btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddTarif");
}
else
btnNew.Visible = false;
btnSearch.Text = Resources.GetString("", "Search");
ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif";
ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif";
ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif";
ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif";
GetListKelompokLayanan();
UpdateDataView(true);
}
}
public void GetListKelompokLayanan()
{
string KelompokLayananId = "";
SIMRS.DataAccess.RS_KelompokLayanan myObj = new SIMRS.DataAccess.RS_KelompokLayanan();
DataTable dt = myObj.GetList();
cmbKelompokLayanan.Items.Clear();
int i = 0;
cmbKelompokLayanan.Items.Add("");
cmbKelompokLayanan.Items[i].Text = "";
cmbKelompokLayanan.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbKelompokLayanan.Items.Add("");
cmbKelompokLayanan.Items[i].Text = dr["Nama"].ToString();
cmbKelompokLayanan.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == KelompokLayananId)
cmbKelompokLayanan.SelectedIndex = i;
i++;
}
}
//public void GetListJenisLayanan()
//{
// string JenisLayananId = "";
// SIMRS.DataAccess.RS_JenisLayanan myObj = new SIMRS.DataAccess.RS_JenisLayanan();
// DataTable dt = myObj.GetList();
// cmbJenisLayanan.Items.Clear();
// int i = 0;
// cmbJenisLayanan.Items.Add("");
// cmbJenisLayanan.Items[i].Text = "";
// cmbJenisLayanan.Items[i].Value = "";
// i++;
// foreach (DataRow dr in dt.Rows)
// {
// cmbJenisLayanan.Items.Add("");
// cmbJenisLayanan.Items[i].Text = dr["Nama"].ToString();
// cmbJenisLayanan.Items[i].Value = dr["Id"].ToString();
// if (dr["Id"].ToString() == JenisLayananId)
// cmbJenisLayanan.SelectedIndex = i;
// i++;
// }
//}
#region .Update View Data
//////////////////////////////////////////////////////////////////////
// PhysicalDataRead
// ------------------------------------------------------------------
/// <summary>
/// This function is responsible for loading data from database.
/// </summary>
/// <returns>DataSet</returns>
public DataSet PhysicalDataRead()
{
// Local variables
DataSet oDS = new DataSet();
// Get Data
SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan();
myObj.JenisLayananId = 7;//Kesehatan Lain(KUBT,Khelasi, Alergi dan Akupuntur)
DataTable myData = myObj.SelectAllWJenisLayananIdLogic();
oDS.Tables.Add(myData);
return oDS;
}
/// <summary>
/// This function is responsible for binding data to Datagrid.
/// </summary>
/// <param name="dv"></param>
private void BindData(DataView dv)
{
// Sets the sorting order
dv.Sort = DataGridList.Attributes["SortField"];
if (DataGridList.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
DataGridList.ShowFooter = false;
int intRowCount = dv.Count;
int intPageSaze = DataGridList.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (DataGridList.CurrentPageIndex >= intPageCount)
DataGridList.CurrentPageIndex = intPageCount - 1;
}
else
{
DataGridList.ShowFooter = true;
DataGridList.CurrentPageIndex = 0;
}
// Re-binds the grid
NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex;
DataGridList.DataSource = dv;
DataGridList.DataBind();
int CurrentPage = DataGridList.CurrentPageIndex + 1;
lblCurrentPage.Text = CurrentPage.ToString();
lblTotalPage.Text = DataGridList.PageCount.ToString();
lblTotalRecord.Text = dv.Count.ToString();
}
/// <summary>
/// This function is responsible for loading data from database and store to Session.
/// </summary>
/// <param name="strDataSessionName"></param>
public void DataFromSourceToMemory(String strDataSessionName)
{
// Gets rows from the data source
DataSet oDS = PhysicalDataRead();
// Stores it in the session cache
Session[strDataSessionName] = oDS;
}
/// <summary>
/// This function is responsible for update data view from datagrid.
/// </summary>
/// <param name="requery">true = get data from database, false= get data from session</param>
public void UpdateDataView(bool requery)
{
// Retrieves the data
if ((Session[dsReportSessionName] == null) || (requery))
{
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString());
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
public void UpdateDataView()
{
// Retrieves the data
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
#endregion
#region .Event DataGridList
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// HANDLERs //
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGridList.CurrentPageIndex = e.NewPageIndex;
DataGridList.SelectedIndex = -1;
UpdateDataView();
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="nPageIndex"></param>
public void GoToPage(Object sender, int nPageIndex)
{
DataGridPageChangedEventArgs evPage;
evPage = new DataGridPageChangedEventArgs(sender, nPageIndex);
PageChanged(sender, evPage);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a first page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToFirst(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, 0);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a previous page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToPrev(Object sender, ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex > 0)
{
GoToPage(sender, DataGridList.CurrentPageIndex - 1);
}
else
{
GoToPage(sender, 0);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a next page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1))
{
GoToPage(sender, DataGridList.CurrentPageIndex + 1);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a last page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToLast(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, DataGridList.PageCount - 1);
}
/// <summary>
/// This function is invoked when you click on a column's header to
/// sort by that. It just saves the current sort field name and
/// refreshes the grid.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SortByColumn(Object sender, DataGridSortCommandEventArgs e)
{
String strSortBy = DataGridList.Attributes["SortField"];
String strSortAscending = DataGridList.Attributes["SortAscending"];
// Sets the new sorting field
DataGridList.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
DataGridList.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
OnClearSelection(null, null);
UpdateDataView();
}
/// <summary>
/// The function gets invoked when a new item is being created in
/// the datagrid. This applies to pager, header, footer, regular
/// and alternating items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageItemCreated(Object sender, DataGridItemEventArgs e)
{
// Get the newly created item
ListItemType itemType = e.Item.ItemType;
//////////////////////////////////////////////////////////
// Is it the HEADER?
if (itemType == ListItemType.Header)
{
for (int i = 0; i < DataGridList.Columns.Count; i++)
{
// draw to reflect sorting
if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression)
{
//////////////////////////////////////////////
// Should be much easier this way:
// ------------------------------------------
// TableCell cell = e.Item.Cells[i];
// Label lblSorted = new Label();
// lblSorted.Font = "webdings";
// lblSorted.Text = strOrder;
// cell.Controls.Add(lblSorted);
//
// but it seems it doesn't work <g>
//////////////////////////////////////////////
// Add a non-clickable triangle to mean desc or asc.
// The </a> ensures that what follows is non-clickable
TableCell cell = e.Item.Cells[i];
LinkButton lb = (LinkButton)cell.Controls[0];
//lb.Text += "</a> <span style=font-family:webdings;>" + GetOrderSymbol() + "</span>";
lb.Text += "</a> <img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >";
}
}
}
//////////////////////////////////////////////////////////
// Is it the PAGER?
if (itemType == ListItemType.Pager)
{
// There's just one control in the list...
TableCell pager = (TableCell)e.Item.Controls[0];
// Enumerates all the items in the pager...
for (int i = 0; i < pager.Controls.Count; i += 2)
{
// It can be either a Label or a Link button
try
{
Label l = (Label)pager.Controls[i];
l.Text = "Hal " + l.Text;
l.CssClass = "CurrentPage";
}
catch
{
LinkButton h = (LinkButton)pager.Controls[i];
h.Text = "[ " + h.Text + " ]";
h.CssClass = "HotLink";
}
}
}
}
/// <summary>
/// Verifies whether the current sort is ascending or descending and
/// returns an appropriate display text (i.e., a webding)
/// </summary>
/// <returns></returns>
private String GetOrderSymbol()
{
bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no");
//return (bDescending ? " 6" : " 5");
return (bDescending ? "downbr.gif" : "upbr.gif");
}
/// <summary>
/// When clicked clears the current selection if any
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnClearSelection(Object sender, EventArgs e)
{
DataGridList.SelectedIndex = -1;
}
#endregion
#region .Event Button
/// <summary>
/// When clicked, redirect to form add for inserts a new record to the database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnNewRecord(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("AddKL.aspx?CurrentPage=" + CurrentPage);
}
/// <summary>
/// When clicked, filter data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSearch(Object sender, System.EventArgs e)
{
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
DataView dv = ds.Tables[0].DefaultView;
string filter = "";
if (cmbKelompokLayanan.SelectedIndex > 0)
{
filter += filter != "" ? " AND " : "";
filter += " KelompokLayananId = " + cmbKelompokLayanan.SelectedItem.Value;
}
dv.RowFilter = filter;
BindData(dv);
}
#endregion
#region .Update Link Item Butom
/// <summary>
/// The function is responsible for get link button form.
/// </summary>
/// <param name="szId"></param>
/// <param name="CurrentPage"></param>
/// <returns></returns>
public string GetLinkButton(string Id, string Nama, string CurrentPage)
{
string szResult = "";
if (Session["EditTarif"] != null)
{
szResult += "<a class=\"toolbar\" href=\"EditKL.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Edit") + "</a>";
}
if (Session["DeleteTarif"] != null)
{
szResult += "<a class=\"toolbar\" href=\"DeleteKL.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Delete") + "</a>";
}
return szResult;
}
#endregion
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dataproc/v1/operations.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Dataproc.V1 {
/// <summary>Holder for reflection information generated from google/cloud/dataproc/v1/operations.proto</summary>
public static partial class OperationsReflection {
#region Descriptor
/// <summary>File descriptor for google/cloud/dataproc/v1/operations.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static OperationsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cilnb29nbGUvY2xvdWQvZGF0YXByb2MvdjEvb3BlcmF0aW9ucy5wcm90bxIY",
"Z29vZ2xlLmNsb3VkLmRhdGFwcm9jLnYxGhxnb29nbGUvYXBpL2Fubm90YXRp",
"b25zLnByb3RvGiNnb29nbGUvbG9uZ3J1bm5pbmcvb3BlcmF0aW9ucy5wcm90",
"bxobZ29vZ2xlL3Byb3RvYnVmL2VtcHR5LnByb3RvGh9nb29nbGUvcHJvdG9i",
"dWYvdGltZXN0YW1wLnByb3RvIvUBChZDbHVzdGVyT3BlcmF0aW9uU3RhdHVz",
"EkUKBXN0YXRlGAEgASgOMjYuZ29vZ2xlLmNsb3VkLmRhdGFwcm9jLnYxLkNs",
"dXN0ZXJPcGVyYXRpb25TdGF0dXMuU3RhdGUSEwoLaW5uZXJfc3RhdGUYAiAB",
"KAkSDwoHZGV0YWlscxgDIAEoCRI0ChBzdGF0ZV9zdGFydF90aW1lGAQgASgL",
"MhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCI4CgVTdGF0ZRILCgdVTktO",
"T1dOEAASCwoHUEVORElORxABEgsKB1JVTk5JTkcQAhIICgRET05FEAMikAMK",
"GENsdXN0ZXJPcGVyYXRpb25NZXRhZGF0YRIUCgxjbHVzdGVyX25hbWUYByAB",
"KAkSFAoMY2x1c3Rlcl91dWlkGAggASgJEkAKBnN0YXR1cxgJIAEoCzIwLmdv",
"b2dsZS5jbG91ZC5kYXRhcHJvYy52MS5DbHVzdGVyT3BlcmF0aW9uU3RhdHVz",
"EkgKDnN0YXR1c19oaXN0b3J5GAogAygLMjAuZ29vZ2xlLmNsb3VkLmRhdGFw",
"cm9jLnYxLkNsdXN0ZXJPcGVyYXRpb25TdGF0dXMSFgoOb3BlcmF0aW9uX3R5",
"cGUYCyABKAkSEwoLZGVzY3JpcHRpb24YDCABKAkSTgoGbGFiZWxzGA0gAygL",
"Mj4uZ29vZ2xlLmNsb3VkLmRhdGFwcm9jLnYxLkNsdXN0ZXJPcGVyYXRpb25N",
"ZXRhZGF0YS5MYWJlbHNFbnRyeRIQCgh3YXJuaW5ncxgOIAMoCRotCgtMYWJl",
"bHNFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBQnMKHGNv",
"bS5nb29nbGUuY2xvdWQuZGF0YXByb2MudjFCD09wZXJhdGlvbnNQcm90b1AB",
"WkBnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Nsb3Vk",
"L2RhdGFwcm9jL3YxO2RhdGFwcm9jYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.LongRunning.OperationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dataproc.V1.ClusterOperationStatus), global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Parser, new[]{ "State", "InnerState", "Details", "StateStartTime" }, null, new[]{ typeof(global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Types.State) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dataproc.V1.ClusterOperationMetadata), global::Google.Cloud.Dataproc.V1.ClusterOperationMetadata.Parser, new[]{ "ClusterName", "ClusterUuid", "Status", "StatusHistory", "OperationType", "Description", "Labels", "Warnings" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, })
}));
}
#endregion
}
#region Messages
/// <summary>
/// The status of the operation.
/// </summary>
public sealed partial class ClusterOperationStatus : pb::IMessage<ClusterOperationStatus> {
private static readonly pb::MessageParser<ClusterOperationStatus> _parser = new pb::MessageParser<ClusterOperationStatus>(() => new ClusterOperationStatus());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ClusterOperationStatus> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Dataproc.V1.OperationsReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ClusterOperationStatus() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ClusterOperationStatus(ClusterOperationStatus other) : this() {
state_ = other.state_;
innerState_ = other.innerState_;
details_ = other.details_;
StateStartTime = other.stateStartTime_ != null ? other.StateStartTime.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ClusterOperationStatus Clone() {
return new ClusterOperationStatus(this);
}
/// <summary>Field number for the "state" field.</summary>
public const int StateFieldNumber = 1;
private global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Types.State state_ = 0;
/// <summary>
/// Output-only. A message containing the operation state.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Types.State State {
get { return state_; }
set {
state_ = value;
}
}
/// <summary>Field number for the "inner_state" field.</summary>
public const int InnerStateFieldNumber = 2;
private string innerState_ = "";
/// <summary>
/// Output-only. A message containing the detailed operation state.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string InnerState {
get { return innerState_; }
set {
innerState_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "details" field.</summary>
public const int DetailsFieldNumber = 3;
private string details_ = "";
/// <summary>
/// Output-only.A message containing any operation metadata details.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Details {
get { return details_; }
set {
details_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "state_start_time" field.</summary>
public const int StateStartTimeFieldNumber = 4;
private global::Google.Protobuf.WellKnownTypes.Timestamp stateStartTime_;
/// <summary>
/// Output-only. The time this state was entered.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp StateStartTime {
get { return stateStartTime_; }
set {
stateStartTime_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ClusterOperationStatus);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ClusterOperationStatus other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (State != other.State) return false;
if (InnerState != other.InnerState) return false;
if (Details != other.Details) return false;
if (!object.Equals(StateStartTime, other.StateStartTime)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (State != 0) hash ^= State.GetHashCode();
if (InnerState.Length != 0) hash ^= InnerState.GetHashCode();
if (Details.Length != 0) hash ^= Details.GetHashCode();
if (stateStartTime_ != null) hash ^= StateStartTime.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (State != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) State);
}
if (InnerState.Length != 0) {
output.WriteRawTag(18);
output.WriteString(InnerState);
}
if (Details.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Details);
}
if (stateStartTime_ != null) {
output.WriteRawTag(34);
output.WriteMessage(StateStartTime);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (State != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) State);
}
if (InnerState.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(InnerState);
}
if (Details.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Details);
}
if (stateStartTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(StateStartTime);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ClusterOperationStatus other) {
if (other == null) {
return;
}
if (other.State != 0) {
State = other.State;
}
if (other.InnerState.Length != 0) {
InnerState = other.InnerState;
}
if (other.Details.Length != 0) {
Details = other.Details;
}
if (other.stateStartTime_ != null) {
if (stateStartTime_ == null) {
stateStartTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
StateStartTime.MergeFrom(other.StateStartTime);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
state_ = (global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Types.State) input.ReadEnum();
break;
}
case 18: {
InnerState = input.ReadString();
break;
}
case 26: {
Details = input.ReadString();
break;
}
case 34: {
if (stateStartTime_ == null) {
stateStartTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(stateStartTime_);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the ClusterOperationStatus message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// The operation state.
/// </summary>
public enum State {
/// <summary>
/// Unused.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 0,
/// <summary>
/// The operation has been created.
/// </summary>
[pbr::OriginalName("PENDING")] Pending = 1,
/// <summary>
/// The operation is running.
/// </summary>
[pbr::OriginalName("RUNNING")] Running = 2,
/// <summary>
/// The operation is done; either cancelled or completed.
/// </summary>
[pbr::OriginalName("DONE")] Done = 3,
}
}
#endregion
}
/// <summary>
/// Metadata describing the operation.
/// </summary>
public sealed partial class ClusterOperationMetadata : pb::IMessage<ClusterOperationMetadata> {
private static readonly pb::MessageParser<ClusterOperationMetadata> _parser = new pb::MessageParser<ClusterOperationMetadata>(() => new ClusterOperationMetadata());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ClusterOperationMetadata> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Dataproc.V1.OperationsReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ClusterOperationMetadata() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ClusterOperationMetadata(ClusterOperationMetadata other) : this() {
clusterName_ = other.clusterName_;
clusterUuid_ = other.clusterUuid_;
Status = other.status_ != null ? other.Status.Clone() : null;
statusHistory_ = other.statusHistory_.Clone();
operationType_ = other.operationType_;
description_ = other.description_;
labels_ = other.labels_.Clone();
warnings_ = other.warnings_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ClusterOperationMetadata Clone() {
return new ClusterOperationMetadata(this);
}
/// <summary>Field number for the "cluster_name" field.</summary>
public const int ClusterNameFieldNumber = 7;
private string clusterName_ = "";
/// <summary>
/// Output-only. Name of the cluster for the operation.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ClusterName {
get { return clusterName_; }
set {
clusterName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "cluster_uuid" field.</summary>
public const int ClusterUuidFieldNumber = 8;
private string clusterUuid_ = "";
/// <summary>
/// Output-only. Cluster UUID for the operation.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ClusterUuid {
get { return clusterUuid_; }
set {
clusterUuid_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "status" field.</summary>
public const int StatusFieldNumber = 9;
private global::Google.Cloud.Dataproc.V1.ClusterOperationStatus status_;
/// <summary>
/// Output-only. Current operation status.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Dataproc.V1.ClusterOperationStatus Status {
get { return status_; }
set {
status_ = value;
}
}
/// <summary>Field number for the "status_history" field.</summary>
public const int StatusHistoryFieldNumber = 10;
private static readonly pb::FieldCodec<global::Google.Cloud.Dataproc.V1.ClusterOperationStatus> _repeated_statusHistory_codec
= pb::FieldCodec.ForMessage(82, global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Dataproc.V1.ClusterOperationStatus> statusHistory_ = new pbc::RepeatedField<global::Google.Cloud.Dataproc.V1.ClusterOperationStatus>();
/// <summary>
/// Output-only. The previous operation status.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Dataproc.V1.ClusterOperationStatus> StatusHistory {
get { return statusHistory_; }
}
/// <summary>Field number for the "operation_type" field.</summary>
public const int OperationTypeFieldNumber = 11;
private string operationType_ = "";
/// <summary>
/// Output-only. The operation type.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OperationType {
get { return operationType_; }
set {
operationType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "description" field.</summary>
public const int DescriptionFieldNumber = 12;
private string description_ = "";
/// <summary>
/// Output-only. Short description of operation.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "labels" field.</summary>
public const int LabelsFieldNumber = 13;
private static readonly pbc::MapField<string, string>.Codec _map_labels_codec
= new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForString(18), 106);
private readonly pbc::MapField<string, string> labels_ = new pbc::MapField<string, string>();
/// <summary>
/// Output-only. Labels associated with the operation
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, string> Labels {
get { return labels_; }
}
/// <summary>Field number for the "warnings" field.</summary>
public const int WarningsFieldNumber = 14;
private static readonly pb::FieldCodec<string> _repeated_warnings_codec
= pb::FieldCodec.ForString(114);
private readonly pbc::RepeatedField<string> warnings_ = new pbc::RepeatedField<string>();
/// <summary>
/// Output-only. Errors encountered during operation execution.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> Warnings {
get { return warnings_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ClusterOperationMetadata);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ClusterOperationMetadata other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ClusterName != other.ClusterName) return false;
if (ClusterUuid != other.ClusterUuid) return false;
if (!object.Equals(Status, other.Status)) return false;
if(!statusHistory_.Equals(other.statusHistory_)) return false;
if (OperationType != other.OperationType) return false;
if (Description != other.Description) return false;
if (!Labels.Equals(other.Labels)) return false;
if(!warnings_.Equals(other.warnings_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ClusterName.Length != 0) hash ^= ClusterName.GetHashCode();
if (ClusterUuid.Length != 0) hash ^= ClusterUuid.GetHashCode();
if (status_ != null) hash ^= Status.GetHashCode();
hash ^= statusHistory_.GetHashCode();
if (OperationType.Length != 0) hash ^= OperationType.GetHashCode();
if (Description.Length != 0) hash ^= Description.GetHashCode();
hash ^= Labels.GetHashCode();
hash ^= warnings_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ClusterName.Length != 0) {
output.WriteRawTag(58);
output.WriteString(ClusterName);
}
if (ClusterUuid.Length != 0) {
output.WriteRawTag(66);
output.WriteString(ClusterUuid);
}
if (status_ != null) {
output.WriteRawTag(74);
output.WriteMessage(Status);
}
statusHistory_.WriteTo(output, _repeated_statusHistory_codec);
if (OperationType.Length != 0) {
output.WriteRawTag(90);
output.WriteString(OperationType);
}
if (Description.Length != 0) {
output.WriteRawTag(98);
output.WriteString(Description);
}
labels_.WriteTo(output, _map_labels_codec);
warnings_.WriteTo(output, _repeated_warnings_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ClusterName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ClusterName);
}
if (ClusterUuid.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ClusterUuid);
}
if (status_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Status);
}
size += statusHistory_.CalculateSize(_repeated_statusHistory_codec);
if (OperationType.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OperationType);
}
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
size += labels_.CalculateSize(_map_labels_codec);
size += warnings_.CalculateSize(_repeated_warnings_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ClusterOperationMetadata other) {
if (other == null) {
return;
}
if (other.ClusterName.Length != 0) {
ClusterName = other.ClusterName;
}
if (other.ClusterUuid.Length != 0) {
ClusterUuid = other.ClusterUuid;
}
if (other.status_ != null) {
if (status_ == null) {
status_ = new global::Google.Cloud.Dataproc.V1.ClusterOperationStatus();
}
Status.MergeFrom(other.Status);
}
statusHistory_.Add(other.statusHistory_);
if (other.OperationType.Length != 0) {
OperationType = other.OperationType;
}
if (other.Description.Length != 0) {
Description = other.Description;
}
labels_.Add(other.labels_);
warnings_.Add(other.warnings_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 58: {
ClusterName = input.ReadString();
break;
}
case 66: {
ClusterUuid = input.ReadString();
break;
}
case 74: {
if (status_ == null) {
status_ = new global::Google.Cloud.Dataproc.V1.ClusterOperationStatus();
}
input.ReadMessage(status_);
break;
}
case 82: {
statusHistory_.AddEntriesFrom(input, _repeated_statusHistory_codec);
break;
}
case 90: {
OperationType = input.ReadString();
break;
}
case 98: {
Description = input.ReadString();
break;
}
case 106: {
labels_.AddEntriesFrom(input, _map_labels_codec);
break;
}
case 114: {
warnings_.AddEntriesFrom(input, _repeated_warnings_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnLengua class.
/// </summary>
[Serializable]
public partial class PnLenguaCollection : ActiveList<PnLengua, PnLenguaCollection>
{
public PnLenguaCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnLenguaCollection</returns>
public PnLenguaCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnLengua o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_lenguas table.
/// </summary>
[Serializable]
public partial class PnLengua : ActiveRecord<PnLengua>, IActiveRecord
{
#region .ctors and Default Settings
public PnLengua()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnLengua(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnLengua(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnLengua(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_lenguas", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdLengua = new TableSchema.TableColumn(schema);
colvarIdLengua.ColumnName = "id_lengua";
colvarIdLengua.DataType = DbType.Int32;
colvarIdLengua.MaxLength = 0;
colvarIdLengua.AutoIncrement = true;
colvarIdLengua.IsNullable = false;
colvarIdLengua.IsPrimaryKey = true;
colvarIdLengua.IsForeignKey = false;
colvarIdLengua.IsReadOnly = false;
colvarIdLengua.DefaultSetting = @"";
colvarIdLengua.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdLengua);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = 80;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = true;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_lenguas",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdLengua")]
[Bindable(true)]
public int IdLengua
{
get { return GetColumnValue<int>(Columns.IdLengua); }
set { SetColumnValue(Columns.IdLengua, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre)
{
PnLengua item = new PnLengua();
item.Nombre = varNombre;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdLengua,string varNombre)
{
PnLengua item = new PnLengua();
item.IdLengua = varIdLengua;
item.Nombre = varNombre;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdLenguaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdLengua = @"id_lengua";
public static string Nombre = @"nombre";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#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.Globalization;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Numerics.Tests
{
public class Vector2Tests
{
[Fact]
public void Vector2MarshalSizeTest()
{
Assert.Equal(8, Marshal.SizeOf<Vector2>());
Assert.Equal(8, Marshal.SizeOf<Vector2>(new Vector2()));
}
[Fact]
public void Vector2CopyToTest()
{
Vector2 v1 = new Vector2(2.0f, 3.0f);
float[] a = new float[3];
float[] b = new float[2];
Assert.Throws<NullReferenceException>(() => v1.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, a.Length));
Assert.Throws<ArgumentException>(() => v1.CopyTo(a, 2));
v1.CopyTo(a, 1);
v1.CopyTo(b);
Assert.Equal(0.0, a[0]);
Assert.Equal(2.0, a[1]);
Assert.Equal(3.0, a[2]);
Assert.Equal(2.0, b[0]);
Assert.Equal(3.0, b[1]);
}
[Fact]
public void Vector2GetHashCodeTest()
{
Vector2 v1 = new Vector2(2.0f, 3.0f);
Vector2 v3 = new Vector2(2.0f, 3.0f);
Vector2 v5 = new Vector2(3.0f, 2.0f);
Assert.True(v1.GetHashCode() == v1.GetHashCode());
Assert.False(v1.GetHashCode() == v5.GetHashCode());
Assert.True(v1.GetHashCode() == v3.GetHashCode());
Vector2 v4 = new Vector2(0.0f, 0.0f);
Vector2 v6 = new Vector2(1.0f, 0.0f);
Vector2 v7 = new Vector2(0.0f, 1.0f);
Vector2 v8 = new Vector2(1.0f, 1.0f);
Assert.False(v4.GetHashCode() == v6.GetHashCode());
Assert.False(v4.GetHashCode() == v7.GetHashCode());
Assert.False(v4.GetHashCode() == v8.GetHashCode());
Assert.False(v7.GetHashCode() == v6.GetHashCode());
Assert.False(v8.GetHashCode() == v6.GetHashCode());
Assert.False(v8.GetHashCode() == v7.GetHashCode());
}
[Fact]
public void Vector2ToStringTest()
{
string separator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;
CultureInfo enUsCultureInfo = new CultureInfo("en-US");
Vector2 v1 = new Vector2(2.0f, 3.0f);
string v1str = v1.ToString();
string expectedv1 = string.Format(CultureInfo.CurrentCulture
, "<{1:G}{0} {2:G}>"
, new object[] { separator, 2, 3 });
Assert.Equal(expectedv1, v1str);
string v1strformatted = v1.ToString("c", CultureInfo.CurrentCulture);
string expectedv1formatted = string.Format(CultureInfo.CurrentCulture
, "<{1:c}{0} {2:c}>"
, new object[] { separator, 2, 3 });
Assert.Equal(expectedv1formatted, v1strformatted);
string v2strformatted = v1.ToString("c", enUsCultureInfo);
string expectedv2formatted = string.Format(enUsCultureInfo
, "<{1:c}{0} {2:c}>"
, new object[] { enUsCultureInfo.NumberFormat.NumberGroupSeparator, 2, 3 });
Assert.Equal(expectedv2formatted, v2strformatted);
string v3strformatted = v1.ToString("c");
string expectedv3formatted = string.Format(CultureInfo.CurrentCulture
, "<{1:c}{0} {2:c}>"
, new object[] { separator, 2, 3 });
Assert.Equal(expectedv3formatted, v3strformatted);
}
// A test for Distance (Vector2f, Vector2f)
[Fact]
public void Vector2DistanceTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
float expected = (float)System.Math.Sqrt(8);
float actual;
actual = Vector2.Distance(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Distance did not return the expected value.");
}
// A test for Distance (Vector2f, Vector2f)
// Distance from the same point
[Fact]
public void Vector2DistanceTest2()
{
Vector2 a = new Vector2(1.051f, 2.05f);
Vector2 b = new Vector2(1.051f, 2.05f);
float actual = Vector2.Distance(a, b);
Assert.Equal(0.0f, actual);
}
// A test for DistanceSquared (Vector2f, Vector2f)
[Fact]
public void Vector2DistanceSquaredTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
float expected = 8.0f;
float actual;
actual = Vector2.DistanceSquared(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.DistanceSquared did not return the expected value.");
}
// A test for Dot (Vector2f, Vector2f)
[Fact]
public void Vector2DotTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
float expected = 11.0f;
float actual;
actual = Vector2.Dot(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Dot did not return the expected value.");
}
// A test for Dot (Vector2f, Vector2f)
// Dot test for perpendicular vector
[Fact]
public void Vector2DotTest1()
{
Vector2 a = new Vector2(1.55f, 1.55f);
Vector2 b = new Vector2(-1.55f, 1.55f);
float expected = 0.0f;
float actual = Vector2.Dot(a, b);
Assert.Equal(expected, actual);
}
// A test for Dot (Vector2f, Vector2f)
// Dot test with specail float values
[Fact]
public void Vector2DotTest2()
{
Vector2 a = new Vector2(float.MinValue, float.MinValue);
Vector2 b = new Vector2(float.MaxValue, float.MaxValue);
float actual = Vector2.Dot(a, b);
Assert.True(float.IsNegativeInfinity(actual), "Vector2f.Dot did not return the expected value.");
}
// A test for Length ()
[Fact]
public void Vector2LengthTest()
{
Vector2 a = new Vector2(2.0f, 4.0f);
Vector2 target = a;
float expected = (float)System.Math.Sqrt(20);
float actual;
actual = target.Length();
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Length did not return the expected value.");
}
// A test for Length ()
// Length test where length is zero
[Fact]
public void Vector2LengthTest1()
{
Vector2 target = new Vector2();
target.X = 0.0f;
target.Y = 0.0f;
float expected = 0.0f;
float actual;
actual = target.Length();
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Length did not return the expected value.");
}
// A test for LengthSquared ()
[Fact]
public void Vector2LengthSquaredTest()
{
Vector2 a = new Vector2(2.0f, 4.0f);
Vector2 target = a;
float expected = 20.0f;
float actual;
actual = target.LengthSquared();
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.LengthSquared did not return the expected value.");
}
// A test for LengthSquared ()
// LengthSquared test where the result is zero
[Fact]
public void Vector2LengthSquaredTest1()
{
Vector2 a = new Vector2(0.0f, 0.0f);
float expected = 0.0f;
float actual = a.LengthSquared();
Assert.Equal(expected, actual);
}
// A test for Min (Vector2f, Vector2f)
[Fact]
public void Vector2MinTest()
{
Vector2 a = new Vector2(-1.0f, 4.0f);
Vector2 b = new Vector2(2.0f, 1.0f);
Vector2 expected = new Vector2(-1.0f, 1.0f);
Vector2 actual;
actual = Vector2.Min(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Min did not return the expected value.");
}
[Fact]
public void Vector2MinMaxCodeCoverageTest()
{
Vector2 min = new Vector2(0, 0);
Vector2 max = new Vector2(1, 1);
Vector2 actual;
// Min.
actual = Vector2.Min(min, max);
Assert.Equal(actual, min);
actual = Vector2.Min(max, min);
Assert.Equal(actual, min);
// Max.
actual = Vector2.Max(min, max);
Assert.Equal(actual, max);
actual = Vector2.Max(max, min);
Assert.Equal(actual, max);
}
// A test for Max (Vector2f, Vector2f)
[Fact]
public void Vector2MaxTest()
{
Vector2 a = new Vector2(-1.0f, 4.0f);
Vector2 b = new Vector2(2.0f, 1.0f);
Vector2 expected = new Vector2(2.0f, 4.0f);
Vector2 actual;
actual = Vector2.Max(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Max did not return the expected value.");
}
// A test for Clamp (Vector2f, Vector2f, Vector2f)
[Fact]
public void Vector2ClampTest()
{
Vector2 a = new Vector2(0.5f, 0.3f);
Vector2 min = new Vector2(0.0f, 0.1f);
Vector2 max = new Vector2(1.0f, 1.1f);
// Normal case.
// Case N1: specified value is in the range.
Vector2 expected = new Vector2(0.5f, 0.3f);
Vector2 actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Normal case.
// Case N2: specified value is bigger than max value.
a = new Vector2(2.0f, 3.0f);
expected = max;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Case N3: specified value is smaller than max value.
a = new Vector2(-1.0f, -2.0f);
expected = min;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Case N4: combination case.
a = new Vector2(-2.0f, 4.0f);
expected = new Vector2(min.X, max.Y);
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// User specified min value is bigger than max value.
max = new Vector2(0.0f, 0.1f);
min = new Vector2(1.0f, 1.1f);
// Case W1: specified value is in the range.
a = new Vector2(0.5f, 0.3f);
expected = min;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Normal case.
// Case W2: specified value is bigger than max and min value.
a = new Vector2(2.0f, 3.0f);
expected = min;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Case W3: specified value is smaller than min and max value.
a = new Vector2(-1.0f, -2.0f);
expected = min;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
[Fact]
public void Vector2LerpTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
float t = 0.5f;
Vector2 expected = new Vector2(2.0f, 3.0f);
Vector2 actual;
actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with factor zero
[Fact]
public void Vector2LerpTest1()
{
Vector2 a = new Vector2(0.0f, 0.0f);
Vector2 b = new Vector2(3.18f, 4.25f);
float t = 0.0f;
Vector2 expected = Vector2.Zero;
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with factor one
[Fact]
public void Vector2LerpTest2()
{
Vector2 a = new Vector2(0.0f, 0.0f);
Vector2 b = new Vector2(3.18f, 4.25f);
float t = 1.0f;
Vector2 expected = new Vector2(3.18f, 4.25f);
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with factor > 1
[Fact]
public void Vector2LerpTest3()
{
Vector2 a = new Vector2(0.0f, 0.0f);
Vector2 b = new Vector2(3.18f, 4.25f);
float t = 2.0f;
Vector2 expected = b * 2.0f;
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with factor < 0
[Fact]
public void Vector2LerpTest4()
{
Vector2 a = new Vector2(0.0f, 0.0f);
Vector2 b = new Vector2(3.18f, 4.25f);
float t = -2.0f;
Vector2 expected = -(b * 2.0f);
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with special float value
[Fact]
public void Vector2LerpTest5()
{
Vector2 a = new Vector2(45.67f, 90.0f);
Vector2 b = new Vector2(float.PositiveInfinity, float.NegativeInfinity);
float t = 0.408f;
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(float.IsPositiveInfinity(actual.X), "Vector2f.Lerp did not return the expected value.");
Assert.True(float.IsNegativeInfinity(actual.Y), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test from the same point
[Fact]
public void Vector2LerpTest6()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
float t = 0.5f;
Vector2 expected = new Vector2(1.0f, 2.0f);
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Transform(Vector2f, Matrix4x4)
[Fact]
public void Vector2TransformTest()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Vector2 expected = new Vector2(10.316987f, 22.183012f);
Vector2 actual;
actual = Vector2.Transform(v, m);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Transform(Vector2f, Matrix3x2)
[Fact]
public void Vector2Transform3x2Test()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
m.M31 = 10.0f;
m.M32 = 20.0f;
Vector2 expected = new Vector2(9.866025f, 22.23205f);
Vector2 actual;
actual = Vector2.Transform(v, m);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for TransformNormal (Vector2f, Matrix4x4)
[Fact]
public void Vector2TransformNormalTest()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Vector2 expected = new Vector2(0.3169873f, 2.18301272f);
Vector2 actual;
actual = Vector2.TransformNormal(v, m);
Assert.Equal(expected, actual);
}
// A test for TransformNormal (Vector2f, Matrix3x2)
[Fact]
public void Vector2TransformNormal3x2Test()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
m.M31 = 10.0f;
m.M32 = 20.0f;
Vector2 expected = new Vector2(-0.133974612f, 2.232051f);
Vector2 actual;
actual = Vector2.TransformNormal(v, m);
Assert.Equal(expected, actual);
}
// A test for Transform (Vector2f, Quaternion)
[Fact]
public void Vector2TransformByQuaternionTest()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
Quaternion q = Quaternion.CreateFromRotationMatrix(m);
Vector2 expected = Vector2.Transform(v, m);
Vector2 actual = Vector2.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Transform (Vector2f, Quaternion)
// Transform Vector2f with zero quaternion
[Fact]
public void Vector2TransformByQuaternionTest1()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Quaternion q = new Quaternion();
Vector2 expected = v;
Vector2 actual = Vector2.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Transform (Vector2f, Quaternion)
// Transform Vector2f with identity quaternion
[Fact]
public void Vector2TransformByQuaternionTest2()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Quaternion q = Quaternion.Identity;
Vector2 expected = v;
Vector2 actual = Vector2.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Normalize (Vector2f)
[Fact]
public void Vector2NormalizeTest()
{
Vector2 a = new Vector2(2.0f, 3.0f);
Vector2 expected = new Vector2(0.554700196225229122018341733457f, 0.8320502943378436830275126001855f);
Vector2 actual;
actual = Vector2.Normalize(a);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Normalize did not return the expected value.");
}
// A test for Normalize (Vector2f)
// Normalize zero length vector
[Fact]
public void Vector2NormalizeTest1()
{
Vector2 a = new Vector2(); // no parameter, default to 0.0f
Vector2 actual = Vector2.Normalize(a);
Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y), "Vector2f.Normalize did not return the expected value.");
}
// A test for Normalize (Vector2f)
// Normalize infinite length vector
[Fact]
public void Vector2NormalizeTest2()
{
Vector2 a = new Vector2(float.MaxValue, float.MaxValue);
Vector2 actual = Vector2.Normalize(a);
Vector2 expected = new Vector2(0, 0);
Assert.Equal(expected, actual);
}
// A test for operator - (Vector2f)
[Fact]
public void Vector2UnaryNegationTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 expected = new Vector2(-1.0f, -2.0f);
Vector2 actual;
actual = -a;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator - did not return the expected value.");
}
// A test for operator - (Vector2f)
// Negate test with special float value
[Fact]
public void Vector2UnaryNegationTest1()
{
Vector2 a = new Vector2(float.PositiveInfinity, float.NegativeInfinity);
Vector2 actual = -a;
Assert.True(float.IsNegativeInfinity(actual.X), "Vector2f.operator - did not return the expected value.");
Assert.True(float.IsPositiveInfinity(actual.Y), "Vector2f.operator - did not return the expected value.");
}
// A test for operator - (Vector2f)
// Negate test with special float value
[Fact]
public void Vector2UnaryNegationTest2()
{
Vector2 a = new Vector2(float.NaN, 0.0f);
Vector2 actual = -a;
Assert.True(float.IsNaN(actual.X), "Vector2f.operator - did not return the expected value.");
Assert.True(float.Equals(0.0f, actual.Y), "Vector2f.operator - did not return the expected value.");
}
// A test for operator - (Vector2f, Vector2f)
[Fact]
public void Vector2SubtractionTest()
{
Vector2 a = new Vector2(1.0f, 3.0f);
Vector2 b = new Vector2(2.0f, 1.5f);
Vector2 expected = new Vector2(-1.0f, 1.5f);
Vector2 actual;
actual = a - b;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator - did not return the expected value.");
}
// A test for operator * (Vector2f, float)
[Fact]
public void Vector2MultiplyOperatorTest()
{
Vector2 a = new Vector2(2.0f, 3.0f);
const float factor = 2.0f;
Vector2 expected = new Vector2(4.0f, 6.0f);
Vector2 actual;
actual = a * factor;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator * did not return the expected value.");
}
// A test for operator * (float, Vector2f)
[Fact]
public void Vector2MultiplyOperatorTest2()
{
Vector2 a = new Vector2(2.0f, 3.0f);
const float factor = 2.0f;
Vector2 expected = new Vector2(4.0f, 6.0f);
Vector2 actual;
actual = factor * a;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator * did not return the expected value.");
}
// A test for operator * (Vector2f, Vector2f)
[Fact]
public void Vector2MultiplyOperatorTest3()
{
Vector2 a = new Vector2(2.0f, 3.0f);
Vector2 b = new Vector2(4.0f, 5.0f);
Vector2 expected = new Vector2(8.0f, 15.0f);
Vector2 actual;
actual = a * b;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator * did not return the expected value.");
}
// A test for operator / (Vector2f, float)
[Fact]
public void Vector2DivisionTest()
{
Vector2 a = new Vector2(2.0f, 3.0f);
float div = 2.0f;
Vector2 expected = new Vector2(1.0f, 1.5f);
Vector2 actual;
actual = a / div;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator / did not return the expected value.");
}
// A test for operator / (Vector2f, Vector2f)
[Fact]
public void Vector2DivisionTest1()
{
Vector2 a = new Vector2(2.0f, 3.0f);
Vector2 b = new Vector2(4.0f, 5.0f);
Vector2 expected = new Vector2(2.0f / 4.0f, 3.0f / 5.0f);
Vector2 actual;
actual = a / b;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator / did not return the expected value.");
}
// A test for operator / (Vector2f, float)
// Divide by zero
[Fact]
public void Vector2DivisionTest2()
{
Vector2 a = new Vector2(-2.0f, 3.0f);
float div = 0.0f;
Vector2 actual = a / div;
Assert.True(float.IsNegativeInfinity(actual.X), "Vector2f.operator / did not return the expected value.");
Assert.True(float.IsPositiveInfinity(actual.Y), "Vector2f.operator / did not return the expected value.");
}
// A test for operator / (Vector2f, Vector2f)
// Divide by zero
[Fact]
public void Vector2DivisionTest3()
{
Vector2 a = new Vector2(0.047f, -3.0f);
Vector2 b = new Vector2();
Vector2 actual = a / b;
Assert.True(float.IsInfinity(actual.X), "Vector2f.operator / did not return the expected value.");
Assert.True(float.IsInfinity(actual.Y), "Vector2f.operator / did not return the expected value.");
}
// A test for operator + (Vector2f, Vector2f)
[Fact]
public void Vector2AdditionTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
Vector2 expected = new Vector2(4.0f, 6.0f);
Vector2 actual;
actual = a + b;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator + did not return the expected value.");
}
// A test for Vector2f (float, float)
[Fact]
public void Vector2ConstructorTest()
{
float x = 1.0f;
float y = 2.0f;
Vector2 target = new Vector2(x, y);
Assert.True(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y), "Vector2f(x,y) constructor did not return the expected value.");
}
// A test for Vector2f ()
// Constructor with no parameter
[Fact]
public void Vector2ConstructorTest2()
{
Vector2 target = new Vector2();
Assert.Equal(target.X, 0.0f);
Assert.Equal(target.Y, 0.0f);
}
// A test for Vector2f (float, float)
// Constructor with special floating values
[Fact]
public void Vector2ConstructorTest3()
{
Vector2 target = new Vector2(float.NaN, float.MaxValue);
Assert.Equal(target.X, float.NaN);
Assert.Equal(target.Y, float.MaxValue);
}
// A test for Vector2f (float)
[Fact]
public void Vector2ConstructorTest4()
{
float value = 1.0f;
Vector2 target = new Vector2(value);
Vector2 expected = new Vector2(value, value);
Assert.Equal(expected, target);
value = 2.0f;
target = new Vector2(value);
expected = new Vector2(value, value);
Assert.Equal(expected, target);
}
// A test for Add (Vector2f, Vector2f)
[Fact]
public void Vector2AddTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(5.0f, 6.0f);
Vector2 expected = new Vector2(6.0f, 8.0f);
Vector2 actual;
actual = Vector2.Add(a, b);
Assert.Equal(expected, actual);
}
// A test for Divide (Vector2f, float)
[Fact]
public void Vector2DivideTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
float div = 2.0f;
Vector2 expected = new Vector2(0.5f, 1.0f);
Vector2 actual;
actual = Vector2.Divide(a, div);
Assert.Equal(expected, actual);
}
// A test for Divide (Vector2f, Vector2f)
[Fact]
public void Vector2DivideTest1()
{
Vector2 a = new Vector2(1.0f, 6.0f);
Vector2 b = new Vector2(5.0f, 2.0f);
Vector2 expected = new Vector2(1.0f / 5.0f, 6.0f / 2.0f);
Vector2 actual;
actual = Vector2.Divide(a, b);
Assert.Equal(expected, actual);
}
// A test for Equals (object)
[Fact]
public void Vector2EqualsTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
// case 1: compare between same values
object obj = b;
bool expected = true;
bool actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare between different types.
obj = new Quaternion();
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare against null.
obj = null;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
}
// A test for Multiply (Vector2f, float)
[Fact]
public void Vector2MultiplyTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
const float factor = 2.0f;
Vector2 expected = new Vector2(2.0f, 4.0f);
Vector2 actual = Vector2.Multiply(a, factor);
Assert.Equal(expected, actual);
}
// A test for Multiply (float, Vector2f)
[Fact]
public void Vector2MultiplyTest2()
{
Vector2 a = new Vector2(1.0f, 2.0f);
const float factor = 2.0f;
Vector2 expected = new Vector2(2.0f, 4.0f);
Vector2 actual = Vector2.Multiply(factor, a);
Assert.Equal(expected, actual);
}
// A test for Multiply (Vector2f, Vector2f)
[Fact]
public void Vector2MultiplyTest3()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(5.0f, 6.0f);
Vector2 expected = new Vector2(5.0f, 12.0f);
Vector2 actual;
actual = Vector2.Multiply(a, b);
Assert.Equal(expected, actual);
}
// A test for Negate (Vector2f)
[Fact]
public void Vector2NegateTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 expected = new Vector2(-1.0f, -2.0f);
Vector2 actual;
actual = Vector2.Negate(a);
Assert.Equal(expected, actual);
}
// A test for operator != (Vector2f, Vector2f)
[Fact]
public void Vector2InequalityTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
// case 1: compare between same values
bool expected = false;
bool actual = a != b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = true;
actual = a != b;
Assert.Equal(expected, actual);
}
// A test for operator == (Vector2f, Vector2f)
[Fact]
public void Vector2EqualityTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a == b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = false;
actual = a == b;
Assert.Equal(expected, actual);
}
// A test for Subtract (Vector2f, Vector2f)
[Fact]
public void Vector2SubtractTest()
{
Vector2 a = new Vector2(1.0f, 6.0f);
Vector2 b = new Vector2(5.0f, 2.0f);
Vector2 expected = new Vector2(-4.0f, 4.0f);
Vector2 actual;
actual = Vector2.Subtract(a, b);
Assert.Equal(expected, actual);
}
// A test for UnitX
[Fact]
public void Vector2UnitXTest()
{
Vector2 val = new Vector2(1.0f, 0.0f);
Assert.Equal(val, Vector2.UnitX);
}
// A test for UnitY
[Fact]
public void Vector2UnitYTest()
{
Vector2 val = new Vector2(0.0f, 1.0f);
Assert.Equal(val, Vector2.UnitY);
}
// A test for One
[Fact]
public void Vector2OneTest()
{
Vector2 val = new Vector2(1.0f, 1.0f);
Assert.Equal(val, Vector2.One);
}
// A test for Zero
[Fact]
public void Vector2ZeroTest()
{
Vector2 val = new Vector2(0.0f, 0.0f);
Assert.Equal(val, Vector2.Zero);
}
// A test for Equals (Vector2f)
[Fact]
public void Vector2EqualsTest1()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a.Equals(b);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = false;
actual = a.Equals(b);
Assert.Equal(expected, actual);
}
// A test for Vector2f comparison involving NaN values
[Fact]
public void Vector2EqualsNanTest()
{
Vector2 a = new Vector2(float.NaN, 0);
Vector2 b = new Vector2(0, float.NaN);
Assert.False(a == Vector2.Zero);
Assert.False(b == Vector2.Zero);
Assert.True(a != Vector2.Zero);
Assert.True(b != Vector2.Zero);
Assert.False(a.Equals(Vector2.Zero));
Assert.False(b.Equals(Vector2.Zero));
// Counterintuitive result - IEEE rules for NaN comparison are weird!
Assert.False(a.Equals(a));
Assert.False(b.Equals(b));
}
// A test for Reflect (Vector2f, Vector2f)
[Fact]
[ActiveIssue(1011)]
public void Vector2ReflectTest()
{
Vector2 a = Vector2.Normalize(new Vector2(1.0f, 1.0f));
// Reflect on XZ plane.
Vector2 n = new Vector2(0.0f, 1.0f);
Vector2 expected = new Vector2(a.X, -a.Y);
Vector2 actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
// Reflect on XY plane.
n = new Vector2(0.0f, 0.0f);
expected = new Vector2(a.X, a.Y);
actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
// Reflect on YZ plane.
n = new Vector2(1.0f, 0.0f);
expected = new Vector2(-a.X, a.Y);
actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
}
// A test for Reflect (Vector2f, Vector2f)
// Reflection when normal and source are the same
[Fact]
[ActiveIssue(1011)]
public void Vector2ReflectTest1()
{
Vector2 n = new Vector2(0.45f, 1.28f);
n = Vector2.Normalize(n);
Vector2 a = n;
Vector2 expected = -n;
Vector2 actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
}
// A test for Reflect (Vector2f, Vector2f)
// Reflection when normal and source are negation
[Fact]
public void Vector2ReflectTest2()
{
Vector2 n = new Vector2(0.45f, 1.28f);
n = Vector2.Normalize(n);
Vector2 a = -n;
Vector2 expected = n;
Vector2 actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
}
[Fact]
public void Vector2AbsTest()
{
Vector2 v1 = new Vector2(-2.5f, 2.0f);
Vector2 v3 = Vector2.Abs(new Vector2(0.0f, Single.NegativeInfinity));
Vector2 v = Vector2.Abs(v1);
Assert.Equal(2.5f, v.X);
Assert.Equal(2.0f, v.Y);
Assert.Equal(0.0f, v3.X);
Assert.Equal(Single.PositiveInfinity, v3.Y);
}
[Fact]
public void Vector2SqrtTest()
{
Vector2 v1 = new Vector2(-2.5f, 2.0f);
Vector2 v2 = new Vector2(5.5f, 4.5f);
Assert.Equal(2, (int)Vector2.SquareRoot(v2).X);
Assert.Equal(2, (int)Vector2.SquareRoot(v2).Y);
Assert.Equal(Single.NaN, Vector2.SquareRoot(v1).X);
}
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[Fact]
public unsafe void Vector2SizeofTest()
{
Assert.Equal(8, sizeof(Vector2));
Assert.Equal(16, sizeof(Vector2_2x));
Assert.Equal(12, sizeof(Vector2PlusFloat));
Assert.Equal(24, sizeof(Vector2PlusFloat_2x));
}
[StructLayout(LayoutKind.Sequential)]
struct Vector2_2x
{
private Vector2 _a;
private Vector2 _b;
}
[StructLayout(LayoutKind.Sequential)]
struct Vector2PlusFloat
{
private Vector2 _v;
private float _f;
}
[StructLayout(LayoutKind.Sequential)]
struct Vector2PlusFloat_2x
{
private Vector2PlusFloat _a;
private Vector2PlusFloat _b;
}
[Fact]
public void SetFieldsTest()
{
Vector2 v3 = new Vector2(4f, 5f);
v3.X = 1.0f;
v3.Y = 2.0f;
Assert.Equal(1.0f, v3.X);
Assert.Equal(2.0f, v3.Y);
Vector2 v4 = v3;
v4.Y = 0.5f;
Assert.Equal(1.0f, v4.X);
Assert.Equal(0.5f, v4.Y);
Assert.Equal(2.0f, v3.Y);
}
[Fact]
public void EmbeddedVectorSetFields()
{
EmbeddedVectorObject evo = new EmbeddedVectorObject();
evo.FieldVector.X = 5.0f;
evo.FieldVector.Y = 5.0f;
Assert.Equal(5.0f, evo.FieldVector.X);
Assert.Equal(5.0f, evo.FieldVector.Y);
}
private class EmbeddedVectorObject
{
public Vector2 FieldVector;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.IndicesStats6
{
public partial class IndicesStats6YamlTests
{
public class IndicesStats615TypesYamlBase : YamlTestsBase
{
public IndicesStats615TypesYamlBase() : base()
{
//do index
_body = new {
bar= "bar",
baz= "baz"
};
this.Do(()=> _client.Index("test1", "bar", "1", _body));
//do index
_body = new {
bar= "bar",
baz= "baz"
};
this.Do(()=> _client.Index("test2", "baz", "1", _body));
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class TypesBlank2Tests : IndicesStats615TypesYamlBase
{
[Test]
public void TypesBlank2Test()
{
//do indices.stats
this.Do(()=> _client.IndicesStatsForAll());
//match _response._all.primaries.indexing.index_total:
this.IsMatch(_response._all.primaries.indexing.index_total, 2);
//is_false _response._all.primaries.indexing.types;
this.IsFalse(_response._all.primaries.indexing.types);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class TypesOne3Tests : IndicesStats615TypesYamlBase
{
[Test]
public void TypesOne3Test()
{
//do indices.stats
this.Do(()=> _client.IndicesStatsForAll(nv=>nv
.AddQueryString("types", @"bar")
));
//match _response._all.primaries.indexing.types.bar.index_total:
this.IsMatch(_response._all.primaries.indexing.types.bar.index_total, 1);
//is_false _response._all.primaries.indexing.types.baz;
this.IsFalse(_response._all.primaries.indexing.types.baz);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class TypesMulti4Tests : IndicesStats615TypesYamlBase
{
[Test]
public void TypesMulti4Test()
{
//do indices.stats
this.Do(()=> _client.IndicesStatsForAll(nv=>nv
.AddQueryString("types", @"bar,baz")
));
//match _response._all.primaries.indexing.types.bar.index_total:
this.IsMatch(_response._all.primaries.indexing.types.bar.index_total, 1);
//match _response._all.primaries.indexing.types.baz.index_total:
this.IsMatch(_response._all.primaries.indexing.types.baz.index_total, 1);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class TypesStar5Tests : IndicesStats615TypesYamlBase
{
[Test]
public void TypesStar5Test()
{
//do indices.stats
this.Do(()=> _client.IndicesStatsForAll(nv=>nv
.AddQueryString("types", @"*")
));
//match _response._all.primaries.indexing.types.bar.index_total:
this.IsMatch(_response._all.primaries.indexing.types.bar.index_total, 1);
//match _response._all.primaries.indexing.types.baz.index_total:
this.IsMatch(_response._all.primaries.indexing.types.baz.index_total, 1);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class TypesPattern6Tests : IndicesStats615TypesYamlBase
{
[Test]
public void TypesPattern6Test()
{
//do indices.stats
this.Do(()=> _client.IndicesStatsForAll(nv=>nv
.AddQueryString("types", @"*r")
));
//match _response._all.primaries.indexing.types.bar.index_total:
this.IsMatch(_response._all.primaries.indexing.types.bar.index_total, 1);
//is_false _response._all.primaries.indexing.types.baz;
this.IsFalse(_response._all.primaries.indexing.types.baz);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class TypesAllMetric7Tests : IndicesStats615TypesYamlBase
{
[Test]
public void TypesAllMetric7Test()
{
//do indices.stats
this.Do(()=> _client.IndicesStatsForAll("_all", nv=>nv
.AddQueryString("types", @"bar")
));
//match _response._all.primaries.indexing.types.bar.index_total:
this.IsMatch(_response._all.primaries.indexing.types.bar.index_total, 1);
//is_false _response._all.primaries.indexing.types.baz;
this.IsFalse(_response._all.primaries.indexing.types.baz);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class TypesIndexingMetric8Tests : IndicesStats615TypesYamlBase
{
[Test]
public void TypesIndexingMetric8Test()
{
//do indices.stats
this.Do(()=> _client.IndicesStatsForAll("indexing", nv=>nv
.AddQueryString("types", @"bar")
));
//match _response._all.primaries.indexing.types.bar.index_total:
this.IsMatch(_response._all.primaries.indexing.types.bar.index_total, 1);
//is_false _response._all.primaries.indexing.types.baz;
this.IsFalse(_response._all.primaries.indexing.types.baz);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class TypesMultiMetric9Tests : IndicesStats615TypesYamlBase
{
[Test]
public void TypesMultiMetric9Test()
{
//do indices.stats
this.Do(()=> _client.IndicesStatsForAll("indexing,search", nv=>nv
.AddQueryString("types", @"bar")
));
//match _response._all.primaries.indexing.types.bar.index_total:
this.IsMatch(_response._all.primaries.indexing.types.bar.index_total, 1);
//is_false _response._all.primaries.indexing.types.baz;
this.IsFalse(_response._all.primaries.indexing.types.baz);
}
}
}
}
| |
// 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.ServiceModel;
using System.ServiceModel.Channels;
public class MockChannelFactory<TChannel> : ChannelFactoryBase<TChannel>, IMockCommunicationObject where TChannel : IChannel
{
public MockChannelFactory(BindingContext context, MessageEncoderFactory encoderFactory)
: base(context.Binding)
{
MessageEncoderFactory = encoderFactory;
OnCreateChannelOverride = DefaultOnCreateChannel;
OpenAsyncResult = new MockAsyncResult();
CloseAsyncResult = new MockAsyncResult();
// Each overrideable method has a delegate property that
// can be set to override it, please a default handler.
// CommunicationObject overrides
DefaultCloseTimeoutOverride = DefaultDefaultCloseTimeout;
DefaultOpenTimeoutOverride = DefaultDefaultOpenTimeout;
OnAbortOverride = DefaultOnAbort;
OnOpenOverride = DefaultOnOpen;
OnCloseOverride = DefaultOnClose;
OnBeginOpenOverride = DefaultOnBeginOpen;
OnEndOpenOverride = DefaultOnEndOpen;
OnBeginCloseOverride = DefaultOnBeginClose;
OnEndCloseOverride = DefaultOnEndClose;
// All the virtuals
OnOpeningOverride = DefaultOnOpening;
OnOpenedOverride = DefaultOnOpened;
OnClosingOverride = DefaultOnClosing;
OnClosedOverride = DefaultOnClosed;
OnFaultedOverride = DefaultOnFaulted;
}
public Func<EndpointAddress, Uri, IChannel> OnCreateChannelOverride { get; set; }
public MessageEncoderFactory MessageEncoderFactory { get; set; }
public MockAsyncResult OpenAsyncResult { get; set; }
public MockAsyncResult CloseAsyncResult { get; set; }
// Abstract overrides
public Func<TimeSpan> DefaultCloseTimeoutOverride { get; set; }
public Func<TimeSpan> DefaultOpenTimeoutOverride { get; set; }
public Action OnAbortOverride { get; set; }
public Func<TimeSpan, AsyncCallback, object, IAsyncResult> OnBeginCloseOverride { get; set; }
public Func<TimeSpan, AsyncCallback, object, IAsyncResult> OnBeginOpenOverride { get; set; }
public Action<TimeSpan> OnOpenOverride { get; set; }
public Action<TimeSpan> OnCloseOverride { get; set; }
public Action<IAsyncResult> OnEndCloseOverride { get; set; }
public Action<IAsyncResult> OnEndOpenOverride { get; set; }
// Virtual overrides
public Action OnOpeningOverride { get; set; }
public Action OnOpenedOverride { get; set; }
public Action OnClosingOverride { get; set; }
public Action OnClosedOverride { get; set; }
public Action OnFaultedOverride { get; set; }
protected override TChannel OnCreateChannel(EndpointAddress address, Uri via)
{
return (TChannel) OnCreateChannelOverride(address, via);
}
public IChannel DefaultOnCreateChannel(EndpointAddress address, Uri via)
{
// Default is a mock IRequestChannel.
// If callers want something else, supply a delegate to OnCreateChannelOverride
// that creates the TChannel needed, and don't call this default.
return new MockRequestChannel(this, MessageEncoderFactory, address, via);
}
protected override TimeSpan DefaultCloseTimeout
{
get
{
return DefaultCloseTimeoutOverride();
}
}
public TimeSpan DefaultDefaultCloseTimeout()
{
return TimeSpan.FromSeconds(30);
}
protected override TimeSpan DefaultOpenTimeout
{
get
{
return DefaultOpenTimeoutOverride();
}
}
public TimeSpan DefaultDefaultOpenTimeout()
{
return TimeSpan.FromSeconds(30);
}
protected override void OnAbort()
{
OnAbortOverride();
}
public void DefaultOnAbort()
{
base.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnBeginCloseOverride(timeout, callback, state);
}
public IAsyncResult DefaultOnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
// Modify the placeholder async result we already instantiated.
CloseAsyncResult.Callback = callback;
CloseAsyncResult.AsyncState = state;
// The mock always Completes the IAsyncResult before handing it back.
// This is done because the sync path has no access to this IAsyncResult
// that happens behind the scenes.
CloseAsyncResult.Complete();
return CloseAsyncResult;
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnBeginOpenOverride(timeout, callback, state);
}
public IAsyncResult DefaultOnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
// Modify the placeholder async result we already instantiated.
OpenAsyncResult.Callback = callback;
OpenAsyncResult.AsyncState = state;
// The mock always Completes the IAsyncResult before handing it back.
// This is done because the sync path has no access to this IAsyncResult
// that happens behind the scenes.
OpenAsyncResult.Complete();
return OpenAsyncResult;
}
protected override void OnClose(TimeSpan timeout)
{
OnCloseOverride(timeout);
}
public void DefaultOnClose(TimeSpan timeout)
{
base.OnClose(timeout);
}
protected override void OnEndClose(IAsyncResult result)
{
OnEndCloseOverride(result);
}
public void DefaultOnEndClose(IAsyncResult result)
{
((MockAsyncResult)result).Complete();
}
protected override void OnEndOpen(IAsyncResult result)
{
OnEndOpenOverride(result);
}
public void DefaultOnEndOpen(IAsyncResult result)
{
((MockAsyncResult)result).Complete();
}
protected override void OnOpen(TimeSpan timeout)
{
OnOpenOverride(timeout);
}
public void DefaultOnOpen(TimeSpan timeout)
{
// abstract -- no base to call
}
// Virtuals
protected override void OnOpening()
{
OnOpeningOverride();
}
public void DefaultOnOpening()
{
base.OnOpening();
}
protected override void OnOpened()
{
OnOpenedOverride();
}
public void DefaultOnOpened()
{
base.OnOpened();
}
protected override void OnClosing()
{
OnClosingOverride();
}
public void DefaultOnClosing()
{
base.OnClosing();
}
protected override void OnClosed()
{
OnClosedOverride();
}
public void DefaultOnClosed()
{
base.OnClosed();
}
protected override void OnFaulted()
{
OnFaultedOverride();
}
public void DefaultOnFaulted()
{
base.OnFaulted();
}
}
| |
#pragma warning disable SA1633 // File should have header - This is an imported file,
// original header with license shall remain the same
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* The following part was imported from https://gitlab.freedesktop.org/uchardet/uchardet
* The implementation of this feature was originally done on https://gitlab.freedesktop.org/uchardet/uchardet/blob/master/src/LangModels/LangTurkishModel.cpp
* and adjusted to language specific support.
*/
namespace UtfUnknown.Core.Models.SingleByte.Turkish;
internal class Iso_8859_3_TurkishModel : TurkishModel
{
// Generated by BuildLangModel.py
// On: 2015-12-04 02:24:44.730727
// Character Mapping Table:
// ILL: illegal character.
// CTR: control character specific to the charset.
// RET: carriage/return.
// SYM: symbol (punctuation) that does not belong to word.
// NUM: 0 - 9.
// Other characters are ordered by probabilities
// (0 is the most common character in the language).
// Orders are generic to a language. So the codepoint with order X in
// CHARSET1 maps to the same character as the codepoint with the same
// order X in CHARSET2 for the same language.
// As such, it is possible to get missing order. For instance the
// ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1
// even though they are both used for French. Same for the euro sign.
private static byte[] CHAR_TO_ORDER_MAP =
{
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
RET,
CTR,
CTR,
RET,
CTR,
CTR, /* 0X */
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR, /* 1X */
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM, /* 2X */
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM, /* 3X */
SYM,
0,
15,
21,
7,
1,
26,
22,
19,
6,
28,
9,
5,
11,
3,
14, /* 4X */
23,
34,
4,
10,
8,
12,
20,
29,
32,
13,
18,
SYM,
SYM,
SYM,
SYM,
SYM, /* 5X */
SYM,
0,
15,
21,
7,
1,
26,
22,
19,
2,
28,
9,
5,
11,
3,
14, /* 6X */
23,
34,
4,
10,
8,
12,
20,
29,
32,
13,
18,
SYM,
SYM,
SYM,
SYM,
CTR, /* 7X */
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR, /* 8X */
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR, /* 9X */
SYM,
48,
SYM,
SYM,
SYM,
ILL,
49,
SYM,
SYM,
2,
17,
25,
50,
SYM,
ILL,
51, /* AX */
SYM,
52,
SYM,
SYM,
SYM,
SYM,
53,
SYM,
SYM,
6,
17,
25,
54,
SYM,
ILL,
55, /* BX */
41,
36,
30,
ILL,
39,
56,
57,
24,
42,
33,
58,
45,
59,
37,
31,
60, /* CX */
ILL,
47,
61,
38,
62,
63,
27,
SYM,
64,
65,
40,
35,
16,
66,
67,
68, /* DX */
41,
36,
30,
ILL,
39,
69,
70,
24,
42,
33,
71,
45,
72,
37,
31,
73, /* EX */
ILL,
47,
74,
38,
75,
76,
27,
SYM,
77,
78,
40,
35,
16,
79,
80,
SYM /* FX */
};
/*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */
public Iso_8859_3_TurkishModel()
: base(
CHAR_TO_ORDER_MAP,
CodepageName.ISO_8859_3) { }
}
| |
// 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.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.Metadata.Tests;
using System.Reflection.PortableExecutable;
using Xunit;
namespace System.Reflection.Metadata.Decoding.Tests
{
public partial class SignatureDecoderTests
{
private static readonly string RuntimeAssemblyName =
#if netstandard
"netstandard";
#else
PlatformDetection.IsFullFramework ? "mscorlib" : "System.Runtime";
#endif
private static readonly string CollectionsAssemblyName =
#if netstandard
"netstandard";
#else
PlatformDetection.IsFullFramework ? "mscorlib" : "System.Collections";
#endif
[Fact]
public unsafe void VerifyMultipleOptionalModifiers()
{
// Type 1: int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl)
// Type 2: char*
// Type 3: uint32
// Type 4: char modopt([mscorlib]System.Runtime.CompilerServices.IsConst)*
var testSignature = new byte[] { 0x20, 0x45, 0x20, 0x69, 0x08, 0x0F, 0x03, 0x09, 0x0F, 0x20, 0x55, 0x03 };
var types = new string[]
{
"int32 modopt(100001A) modopt(1000011)",
"char*",
"uint32",
"char modopt(1000015)*"
};
fixed (byte* testSignaturePtr = &testSignature[0])
{
var signatureBlob = new BlobReader(testSignaturePtr, testSignature.Length);
var provider = new OpaqueTokenTypeProvider();
var decoder = new SignatureDecoder<string, DisassemblingGenericContext>(provider, metadataReader: null, genericContext: null);
foreach (string typeString in types)
{
// Verify that each type is decoded as expected
Assert.Equal(typeString, decoder.DecodeType(ref signatureBlob));
}
// And that nothing is left over to decode
Assert.True(signatureBlob.RemainingBytes == 0);
Assert.Throws<BadImageFormatException>(() => decoder.DecodeType(ref signatureBlob));
}
}
[Theory]
[InlineData(new string[] { "int32", "string" }, new byte[] { 0x0A /*GENERICINST*/, 2 /*count*/, 0x8 /*I4*/, 0xE /*STRING*/ })]
public unsafe void DecodeValidMethodSpecificationSignature(string[] expectedTypes, byte[] testSignature)
{
fixed (byte* testSignaturePtr = &testSignature[0])
{
var signatureBlob = new BlobReader(testSignaturePtr, testSignature.Length);
var provider = new OpaqueTokenTypeProvider();
var decoder = new SignatureDecoder<string, DisassemblingGenericContext>(provider, metadataReader: null, genericContext: null);
IEnumerable<string> actualTypes = decoder.DecodeMethodSpecificationSignature(ref signatureBlob);
Assert.Equal(expectedTypes, actualTypes);
Assert.True(signatureBlob.RemainingBytes == 0);
Assert.Throws<BadImageFormatException>(() => decoder.DecodeType(ref signatureBlob));
}
}
[Theory]
[InlineData(new byte[] { 0 })] // bad header
[InlineData(new byte[] { 0x0A /*GENERICINST*/, 0 /*count*/ })] // no type parameters
public unsafe void DecodeInvalidMethodSpecificationSignature(byte[] testSignature)
{
fixed (byte* testSignaturePtr = &testSignature[0])
{
var signatureBlob = new BlobReader(testSignaturePtr, testSignature.Length);
var provider = new OpaqueTokenTypeProvider();
var decoder = new SignatureDecoder<string, DisassemblingGenericContext>(provider, metadataReader: null, genericContext: null);
}
}
[Fact]
public void DecodeVarArgsDefAndRef()
{
using (FileStream stream = File.OpenRead(typeof(VarArgsToDecode).GetTypeInfo().Assembly.Location))
using (var peReader = new PEReader(stream))
{
MetadataReader metadataReader = peReader.GetMetadataReader();
TypeDefinitionHandle typeDefHandle = TestMetadataResolver.FindTestType(metadataReader, typeof(VarArgsToDecode));
TypeDefinition typeDef = metadataReader.GetTypeDefinition(typeDefHandle);
MethodDefinition methodDef = metadataReader.GetMethodDefinition(typeDef.GetMethods().First());
Assert.Equal("VarArgsCallee", metadataReader.GetString(methodDef.Name));
var provider = new OpaqueTokenTypeProvider();
MethodSignature<string> defSignature = methodDef.DecodeSignature(provider, null);
Assert.Equal(SignatureCallingConvention.VarArgs, defSignature.Header.CallingConvention);
Assert.Equal(1, defSignature.RequiredParameterCount);
Assert.Equal(new[] { "int32" }, defSignature.ParameterTypes);
int refCount = 0;
foreach (MemberReferenceHandle memberRefHandle in metadataReader.MemberReferences)
{
MemberReference memberRef = metadataReader.GetMemberReference(memberRefHandle);
if (metadataReader.StringComparer.Equals(memberRef.Name, "VarArgsCallee"))
{
Assert.Equal(MemberReferenceKind.Method, memberRef.GetKind());
MethodSignature<string> refSignature = memberRef.DecodeMethodSignature(provider, null);
Assert.Equal(SignatureCallingConvention.VarArgs, refSignature.Header.CallingConvention);
Assert.Equal(1, refSignature.RequiredParameterCount);
Assert.Equal(new[] { "int32", "bool", "string", "float64" }, refSignature.ParameterTypes);
refCount++;
}
}
Assert.Equal(1, refCount);
}
}
private static class VarArgsToDecode
{
public static void VarArgsCallee(int i, __arglist)
{
}
public static void VarArgsCaller()
{
VarArgsCallee(1, __arglist(true, "hello", 0.42));
}
}
// Test as much as we can with simple C# examples inline below.
[Fact]
public void SimpleSignatureProviderCoverage()
{
using (FileStream stream = File.OpenRead(typeof(SignaturesToDecode<>).GetTypeInfo().Assembly.Location))
using (var peReader = new PEReader(stream))
{
MetadataReader reader = peReader.GetMetadataReader();
var provider = new DisassemblingTypeProvider();
TypeDefinitionHandle typeHandle = TestMetadataResolver.FindTestType(reader, typeof(SignaturesToDecode<>));
Assert.Equal("System.Reflection.Metadata.Decoding.Tests.SignatureDecoderTests/SignaturesToDecode`1", provider.GetTypeFromHandle(reader, genericContext: null, handle: typeHandle));
TypeDefinition type = reader.GetTypeDefinition(typeHandle);
Dictionary<string, string> expectedFields = GetExpectedFieldSignatures();
ImmutableArray<string> genericTypeParameters = type.GetGenericParameters().Select(h => reader.GetString(reader.GetGenericParameter(h).Name)).ToImmutableArray();
var genericTypeContext = new DisassemblingGenericContext(genericTypeParameters, ImmutableArray<string>.Empty);
foreach (var fieldHandle in type.GetFields())
{
FieldDefinition field = reader.GetFieldDefinition(fieldHandle);
string fieldName = reader.GetString(field.Name);
string expected;
Assert.True(expectedFields.TryGetValue(fieldName, out expected), "Unexpected field: " + fieldName);
Assert.Equal(expected, field.DecodeSignature(provider, genericTypeContext));
}
Dictionary<string, string> expectedMethods = GetExpectedMethodSignatures();
foreach (var methodHandle in type.GetMethods())
{
MethodDefinition method = reader.GetMethodDefinition(methodHandle);
ImmutableArray<string> genericMethodParameters = method.GetGenericParameters().Select(h => reader.GetString(reader.GetGenericParameter(h).Name)).ToImmutableArray();
var genericMethodContext = new DisassemblingGenericContext(genericTypeParameters, genericMethodParameters);
string methodName = reader.GetString(method.Name);
string expected;
Assert.True(expectedMethods.TryGetValue(methodName, out expected), "Unexpected method: " + methodName);
MethodSignature<string> signature = method.DecodeSignature(provider, genericMethodContext);
Assert.True(signature.Header.Kind == SignatureKind.Method);
if (methodName.StartsWith("Generic"))
{
Assert.Equal(1, signature.GenericParameterCount);
}
else
{
Assert.Equal(0, signature.GenericParameterCount);
}
Assert.True(signature.GenericParameterCount <= 1 && (methodName != "GenericMethodParameter" || signature.GenericParameterCount == 1));
Assert.Equal(expected, provider.GetFunctionPointerType(signature));
}
Dictionary<string, string> expectedProperties = GetExpectedPropertySignatures();
foreach (var propertyHandle in type.GetProperties())
{
PropertyDefinition property = reader.GetPropertyDefinition(propertyHandle);
string propertyName = reader.GetString(property.Name);
string expected;
Assert.True(expectedProperties.TryGetValue(propertyName, out expected), "Unexpected property: " + propertyName);
MethodSignature<string> signature = property.DecodeSignature(provider, genericTypeContext);
Assert.True(signature.Header.Kind == SignatureKind.Property);
Assert.Equal(expected, provider.GetFunctionPointerType(signature));
}
Dictionary<string, string> expectedEvents = GetExpectedEventSignatures();
foreach (var eventHandle in type.GetEvents())
{
EventDefinition @event = reader.GetEventDefinition(eventHandle);
string eventName = reader.GetString(@event.Name);
string expected;
Assert.True(expectedEvents.TryGetValue(eventName, out expected), "Unexpected event: " + eventName);
Assert.Equal(expected, provider.GetTypeFromHandle(reader, genericTypeContext, @event.Type));
}
Assert.Equal($"[{CollectionsAssemblyName}]System.Collections.Generic.List`1<!T>", provider.GetTypeFromHandle(reader, genericTypeContext, handle: type.BaseType));
}
}
public unsafe class SignaturesToDecode<T> : List<T>
{
public sbyte SByte;
public byte Byte;
public short Int16;
public ushort UInt16;
public int Int32;
public uint UInt32;
public long Int64;
public ulong UInt64;
public string String;
public object Object;
public float Single;
public double Double;
public IntPtr IntPtr;
public UIntPtr UIntPtr;
public bool Boolean;
public char Char;
public volatile int ModifiedType;
public int* Pointer;
public int[] SZArray;
public int[,] Array;
public void ByReference(ref int i) { }
public T GenericTypeParameter;
public U GenericMethodParameter<U>() { throw null; }
public List<int> GenericInstantiation;
public struct Nested { }
public Nested Property { get { throw null; } }
public event EventHandler<EventArgs> Event { add { } remove { } }
}
[Fact]
public void PinnedAndUnpinnedLocals()
{
using (FileStream stream = File.OpenRead(typeof(PinnedAndUnpinnedLocalsToDecode).GetTypeInfo().Assembly.Location))
using (var peReader = new PEReader(stream))
{
MetadataReader reader = peReader.GetMetadataReader();
var provider = new DisassemblingTypeProvider();
TypeDefinitionHandle typeDefHandle = TestMetadataResolver.FindTestType(reader, typeof(PinnedAndUnpinnedLocalsToDecode));
TypeDefinition typeDef = reader.GetTypeDefinition(typeDefHandle);
MethodDefinition methodDef = reader.GetMethodDefinition(typeDef.GetMethods().First());
Assert.Equal("DoSomething", reader.GetString(methodDef.Name));
MethodBodyBlock body = peReader.GetMethodBody(methodDef.RelativeVirtualAddress);
StandaloneSignature localSignature = reader.GetStandaloneSignature(body.LocalSignature);
ImmutableArray<string> localTypes = localSignature.DecodeLocalSignature(provider, genericContext: null);
// Compiler can generate temporaries or re-order so just check the ones we expect are there.
// (They could get optimized away too. If that happens in practice, change this test to use hard-coded signatures.)
Assert.Contains("uint8[] pinned", localTypes);
Assert.Contains("uint8[]", localTypes);
}
}
public static class PinnedAndUnpinnedLocalsToDecode
{
public static unsafe int DoSomething()
{
byte[] bytes = new byte[] { 1, 2, 3 };
fixed (byte* bytePtr = bytes)
{
return *bytePtr;
}
}
}
[Fact]
public void WrongSignatureType()
{
using (FileStream stream = File.OpenRead(typeof(VarArgsToDecode).GetTypeInfo().Assembly.Location))
using (var peReader = new PEReader(stream))
{
MetadataReader reader = peReader.GetMetadataReader();
var provider = new DisassemblingTypeProvider();
var decoder = new SignatureDecoder<string, DisassemblingGenericContext>(provider, reader, genericContext: null);
BlobReader fieldSignature = reader.GetBlobReader(reader.GetFieldDefinition(MetadataTokens.FieldDefinitionHandle(1)).Signature);
BlobReader methodSignature = reader.GetBlobReader(reader.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).Signature);
BlobReader propertySignature = reader.GetBlobReader(reader.GetPropertyDefinition(MetadataTokens.PropertyDefinitionHandle(1)).Signature);
Assert.Throws<BadImageFormatException>(() => decoder.DecodeMethodSignature(ref fieldSignature));
Assert.Throws<BadImageFormatException>(() => decoder.DecodeFieldSignature(ref methodSignature));
Assert.Throws<BadImageFormatException>(() => decoder.DecodeLocalSignature(ref propertySignature));
}
}
private static Dictionary<string, string> GetExpectedFieldSignatures()
{
// Field name -> signature
return new Dictionary<string, string>()
{
{ "SByte", "int8" },
{ "Byte", "uint8" },
{ "Int16", "int16" },
{ "UInt16", "uint16" },
{ "Int32", "int32" },
{ "UInt32", "uint32" },
{ "Int64", "int64" },
{ "UInt64", "uint64" },
{ "String", "string" },
{ "Object", "object" },
{ "Single", "float32" },
{ "Double", "float64" },
{ "IntPtr", "native int" },
{ "UIntPtr", "native uint" },
{ "Boolean", "bool" },
{ "Char", "char" },
{ "ModifiedType", $"int32 modreq([{RuntimeAssemblyName}]System.Runtime.CompilerServices.IsVolatile)" },
{ "Pointer", "int32*" },
{ "SZArray", "int32[]" },
{ "Array", "int32[0...,0...]" },
{ "GenericTypeParameter", "!T" },
{ "GenericInstantiation", $"[{CollectionsAssemblyName}]System.Collections.Generic.List`1<int32>" },
};
}
private static Dictionary<string, string> GetExpectedMethodSignatures()
{
// method name -> signature
return new Dictionary<string, string>()
{
{ "ByReference", "method void *(int32&)" },
{ "GenericMethodParameter", "method !!U *()" },
{ ".ctor", "method void *()" },
{ "get_Property", "method System.Reflection.Metadata.Decoding.Tests.SignatureDecoderTests/SignaturesToDecode`1/Nested<!T> *()" },
{ "add_Event", $"method void *([{RuntimeAssemblyName}]System.EventHandler`1<[{RuntimeAssemblyName}]System.EventArgs>)" },
{ "remove_Event", $"method void *([{RuntimeAssemblyName}]System.EventHandler`1<[{RuntimeAssemblyName}]System.EventArgs>)" },
};
}
private static Dictionary<string, string> GetExpectedPropertySignatures()
{
// field name -> signature
return new Dictionary<string, string>()
{
{ "Property", "method System.Reflection.Metadata.Decoding.Tests.SignatureDecoderTests/SignaturesToDecode`1/Nested<!T> *()" },
};
}
private static Dictionary<string, string> GetExpectedEventSignatures()
{
// event name -> signature
return new Dictionary<string, string>()
{
{ "Event", $"[{RuntimeAssemblyName}]System.EventHandler`1<[{RuntimeAssemblyName}]System.EventArgs>" },
};
}
[Theory]
[InlineData(new byte[] { 0x12 /*CLASS*/, 0x06 /*encoded type spec*/ })] // not def or ref
[InlineData(new byte[] { 0x11 /*VALUETYPE*/, 0x06 /*encoded type spec*/})] // not def or ref
[InlineData(new byte[] { 0x60 })] // Bad type code
public unsafe void BadTypeSignature(byte[] signature)
{
fixed (byte* bytes = signature)
{
BlobReader reader = new BlobReader(bytes, signature.Length);
Assert.Throws<BadImageFormatException>(() => new SignatureDecoder<string, DisassemblingGenericContext>(new OpaqueTokenTypeProvider(), metadataReader: null, genericContext: null).DecodeType(ref reader));
}
}
[Theory]
[InlineData("method void *()", new byte[] { 0x1B /*FNPTR*/, 0 /*default calling convention*/, 0 /*parameters count*/, 0x1 /* return type (VOID)*/ })]
[InlineData("int32[...]", new byte[] { 0x14 /*ARRAY*/, 0x8 /*I4*/, 1 /*rank*/, 0 /*sizes*/, 0 /*lower bounds*/ })]
[InlineData("int32[...,...,...]", new byte[] { 0x14 /*ARRAY*/, 0x8 /*I4*/, 3 /*rank*/, 0 /*sizes*/, 0/*lower bounds*/ })]
[InlineData("int32[-1...1]", new byte[] { 0x14 /*ARRAY*/, 0x8 /*I4*/, 1 /*rank*/, 1 /*sizes*/, 3 /*size*/, 1 /*lower bounds*/, 0x7F /*lower bound (compressed -1)*/ })]
[InlineData("int32[1...]", new byte[] { 0x14 /*ARRAY*/, 0x8 /*I4*/, 1 /*rank*/, 0 /*sizes*/, 1 /*lower bounds*/, 2 /*lower bound (compressed +1)*/ })]
public unsafe void ExoticTypeSignature(string expected, byte[] signature)
{
fixed (byte* bytes = signature)
{
BlobReader reader = new BlobReader(bytes, signature.Length);
Assert.Equal(expected, new SignatureDecoder<string, DisassemblingGenericContext>(new OpaqueTokenTypeProvider(), metadataReader: null, genericContext: null).DecodeType(ref reader));
}
}
[Fact]
public void ProviderCannotBeNull()
{
AssertExtensions.Throws<ArgumentNullException>("provider", () => new SignatureDecoder<int, object>(provider: null, metadataReader: null, genericContext: null));
}
}
}
| |
/*
* 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.IO;
using System.Reflection;
using System.Timers;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Statistics;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim
{
/// <summary>
/// Interactive OpenSim region server
/// </summary>
public class OpenSim : OpenSimBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_startupCommandsFile;
protected string m_shutdownCommandsFile;
protected bool m_gui = false;
protected string m_consoleType = "local";
protected uint m_consolePort = 0;
private string m_timedScript = "disabled";
private Timer m_scriptTimer;
public OpenSim(IConfigSource configSource) : base(configSource)
{
}
protected override void ReadExtraConfigSettings()
{
base.ReadExtraConfigSettings();
IConfig startupConfig = m_config.Source.Configs["Startup"];
IConfig networkConfig = m_config.Source.Configs["Network"];
int stpMaxThreads = 15;
if (startupConfig != null)
{
m_startupCommandsFile = startupConfig.GetString("startup_console_commands_file", "startup_commands.txt");
m_shutdownCommandsFile = startupConfig.GetString("shutdown_console_commands_file", "shutdown_commands.txt");
if (startupConfig.GetString("console", String.Empty) == String.Empty)
m_gui = startupConfig.GetBoolean("gui", false);
else
m_consoleType= startupConfig.GetString("console", String.Empty);
if (networkConfig != null)
m_consolePort = (uint)networkConfig.GetInt("console_port", 0);
m_timedScript = startupConfig.GetString("timer_Script", "disabled");
if (m_logFileAppender != null)
{
if (m_logFileAppender is log4net.Appender.FileAppender)
{
log4net.Appender.FileAppender appender =
(log4net.Appender.FileAppender)m_logFileAppender;
string fileName = startupConfig.GetString("LogFile", String.Empty);
if (fileName != String.Empty)
{
appender.File = fileName;
appender.ActivateOptions();
}
m_log.InfoFormat("[LOGGING]: Logging started to file {0}", appender.File);
}
}
string asyncCallMethodStr = startupConfig.GetString("async_call_method", String.Empty);
FireAndForgetMethod asyncCallMethod;
if (!String.IsNullOrEmpty(asyncCallMethodStr) && Utils.EnumTryParse<FireAndForgetMethod>(asyncCallMethodStr, out asyncCallMethod))
Util.FireAndForgetMethod = asyncCallMethod;
stpMaxThreads = startupConfig.GetInt("MaxPoolThreads", 15);
}
if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
Util.InitThreadPool(stpMaxThreads);
m_log.Info("[OPENSIM MAIN]: Using async_call_method " + Util.FireAndForgetMethod);
}
/// <summary>
/// Performs initialisation of the scene, such as loading configuration from disk.
/// </summary>
protected override void StartupSpecific()
{
m_log.Info("====================================================================");
m_log.Info("========================= STARTING OPENSIM =========================");
m_log.Info("====================================================================");
m_log.InfoFormat("[OPENSIM MAIN]: Running ");
//m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString());
// http://msdn.microsoft.com/en-us/library/bb384202.aspx
//GCSettings.LatencyMode = GCLatencyMode.Batch;
//m_log.InfoFormat("[OPENSIM MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString());
if (m_gui) // Driven by external GUI
m_console = new CommandConsole("Region");
else
{
switch (m_consoleType)
{
case "basic":
m_console = new CommandConsole("Region");
break;
case "rest":
m_console = new RemoteConsole("Region");
((RemoteConsole)m_console).ReadConfig(m_config.Source);
break;
default:
m_console = new LocalConsole("Region");
break;
}
}
MainConsole.Instance = m_console;
RegisterConsoleCommands();
base.StartupSpecific();
MainServer.Instance.AddStreamHandler(new OpenSim.SimStatusHandler());
MainServer.Instance.AddStreamHandler(new OpenSim.XSimStatusHandler(this));
if (userStatsURI != String.Empty)
MainServer.Instance.AddStreamHandler(new OpenSim.UXSimStatusHandler(this));
if (m_console is RemoteConsole)
{
if (m_consolePort == 0)
{
((RemoteConsole)m_console).SetServer(m_httpServer);
}
else
{
((RemoteConsole)m_console).SetServer(MainServer.GetHttpServer(m_consolePort));
}
}
//Run Startup Commands
if (String.IsNullOrEmpty(m_startupCommandsFile))
{
m_log.Info("[STARTUP]: No startup command script specified. Moving on...");
}
else
{
RunCommandScript(m_startupCommandsFile);
}
// Start timer script (run a script every xx seconds)
if (m_timedScript != "disabled")
{
m_scriptTimer = new Timer();
m_scriptTimer.Enabled = true;
m_scriptTimer.Interval = 1200*1000;
m_scriptTimer.Elapsed += RunAutoTimerScript;
}
// Hook up to the watchdog timer
Watchdog.OnWatchdogTimeout += WatchdogTimeoutHandler;
PrintFileToConsole("startuplogo.txt");
// For now, start at the 'root' level by default
if (m_sceneManager.Scenes.Count == 1) // If there is only one region, select it
ChangeSelectedRegion("region",
new string[] {"change", "region", m_sceneManager.Scenes[0].RegionInfo.RegionName});
else
ChangeSelectedRegion("region", new string[] {"change", "region", "root"});
}
/// <summary>
/// Register standard set of region console commands
/// </summary>
private void RegisterConsoleCommands()
{
m_console.Commands.AddCommand("region", false, "clear assets",
"clear assets",
"Clear the asset cache", HandleClearAssets);
m_console.Commands.AddCommand("region", false, "force update",
"force update",
"Force the update of all objects on clients",
HandleForceUpdate);
m_console.Commands.AddCommand("region", false, "debug packet",
"debug packet <level>",
"Turn on packet debugging",
"If level > 255 then all incoming and outgoing packets are logged.\n"
+ "If level <= 255 then incoming AgentUpdate and outgoing SimStats and SimulatorViewerTimeMessage packets are not logged.\n"
+ "If level <= 200 then incoming RequestImage and outgoing ImagePacket, ImageData, LayerData and CoarseLocationUpdate packets are not logged.\n"
+ "If level <= 100 then incoming ViewerEffect and AgentAnimation and outgoing ViewerEffect and AvatarAnimation packets are not logged.\n"
+ "If level <= 0 then no packets are logged.",
Debug);
m_console.Commands.AddCommand("region", false, "debug scene",
"debug scene <cripting> <collisions> <physics>",
"Turn on scene debugging", Debug);
m_console.Commands.AddCommand("region", false, "change region",
"change region <region name>",
"Change current console region", ChangeSelectedRegion);
m_console.Commands.AddCommand("region", false, "save xml",
"save xml",
"Save a region's data in XML format", SaveXml);
m_console.Commands.AddCommand("region", false, "save xml2",
"save xml2",
"Save a region's data in XML2 format", SaveXml2);
m_console.Commands.AddCommand("region", false, "load xml",
"load xml [-newIDs [<x> <y> <z>]]",
"Load a region's data from XML format", LoadXml);
m_console.Commands.AddCommand("region", false, "load xml2",
"load xml2",
"Load a region's data from XML2 format", LoadXml2);
m_console.Commands.AddCommand("region", false, "save prims xml2",
"save prims xml2 [<prim name> <file name>]",
"Save named prim to XML2", SavePrimsXml2);
m_console.Commands.AddCommand("region", false, "load oar",
"load oar [--merge] [--skip-assets] [<OAR path>]",
"Load a region's data from an OAR archive.",
"--merge will merge the OAR with the existing scene." + Environment.NewLine
+ "--skip-assets will load the OAR but ignore the assets it contains." + Environment.NewLine
+ "The path can be either a filesystem location or a URI."
+ " If this is not given then the command looks for an OAR named region.oar in the current directory.",
LoadOar);
m_console.Commands.AddCommand("region", false, "save oar",
"save oar [-v|version=N] [<OAR path>]",
"Save a region's data to an OAR archive.",
"-v|version=N generates scene objects as per older versions of the serialization (e.g. -v=0)" + Environment.NewLine
+ "The OAR path must be a filesystem path."
+ " If this is not given then the oar is saved to region.oar in the current directory.",
SaveOar);
m_console.Commands.AddCommand("region", false, "edit scale",
"edit scale <name> <x> <y> <z>",
"Change the scale of a named prim", HandleEditScale);
m_console.Commands.AddCommand("region", false, "kick user",
"kick user <first> <last> [message]",
"Kick a user off the simulator", KickUserCommand);
m_console.Commands.AddCommand("region", false, "show assets",
"show assets",
"Show asset data", HandleShow);
m_console.Commands.AddCommand("region", false, "show users",
"show users [full]",
"Show user data", HandleShow);
m_console.Commands.AddCommand("region", false, "show connections",
"show connections",
"Show connection data", HandleShow);
m_console.Commands.AddCommand("region", false, "show users full",
"show users full",
String.Empty, HandleShow);
m_console.Commands.AddCommand("region", false, "show modules",
"show modules",
"Show module data", HandleShow);
m_console.Commands.AddCommand("region", false, "show regions",
"show regions",
"Show region data", HandleShow);
m_console.Commands.AddCommand("region", false, "show queues",
"show queues",
"Show queue data", HandleShow);
m_console.Commands.AddCommand("region", false, "show ratings",
"show ratings",
"Show rating data", HandleShow);
m_console.Commands.AddCommand("region", false, "backup",
"backup",
"Persist objects to the database now", RunCommand);
m_console.Commands.AddCommand("region", false, "create region",
"create region [\"region name\"] <region_file.ini>",
"Create a new region.",
"The settings for \"region name\" are read from <region_file.ini>. Paths specified with <region_file.ini> are relative to your Regions directory, unless an absolute path is given."
+ " If \"region name\" does not exist in <region_file.ini>, it will be added." + Environment.NewLine
+ "Without \"region name\", the first region found in <region_file.ini> will be created." + Environment.NewLine
+ "If <region_file.ini> does not exist, it will be created.",
HandleCreateRegion);
m_console.Commands.AddCommand("region", false, "restart",
"restart",
"Restart all sims in this instance", RunCommand);
m_console.Commands.AddCommand("region", false, "config set",
"config set <section> <field> <value>",
"Set a config option", HandleConfig);
m_console.Commands.AddCommand("region", false, "config get",
"config get <section> <field>",
"Read a config option", HandleConfig);
m_console.Commands.AddCommand("region", false, "config save",
"config save",
"Save current configuration", HandleConfig);
m_console.Commands.AddCommand("region", false, "command-script",
"command-script <script>",
"Run a command script from file", RunCommand);
m_console.Commands.AddCommand("region", false, "remove-region",
"remove-region <name>",
"Remove a region from this simulator", RunCommand);
m_console.Commands.AddCommand("region", false, "delete-region",
"delete-region <name>",
"Delete a region from disk", RunCommand);
m_console.Commands.AddCommand("region", false, "modules list",
"modules list",
"List modules", HandleModules);
m_console.Commands.AddCommand("region", false, "modules load",
"modules load <name>",
"Load a module", HandleModules);
m_console.Commands.AddCommand("region", false, "modules unload",
"modules unload <name>",
"Unload a module", HandleModules);
m_console.Commands.AddCommand("region", false, "Add-InventoryHost",
"Add-InventoryHost <host>",
String.Empty, RunCommand);
m_console.Commands.AddCommand("region", false, "kill uuid",
"kill uuid <UUID>",
"Kill an object by UUID", KillUUID);
}
public override void ShutdownSpecific()
{
if (m_shutdownCommandsFile != String.Empty)
{
RunCommandScript(m_shutdownCommandsFile);
}
base.ShutdownSpecific();
}
/// <summary>
/// Timer to run a specific text file as console commands. Configured in in the main ini file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RunAutoTimerScript(object sender, EventArgs e)
{
if (m_timedScript != "disabled")
{
RunCommandScript(m_timedScript);
}
}
private void WatchdogTimeoutHandler(System.Threading.Thread thread, int lastTick)
{
int now = Environment.TickCount & Int32.MaxValue;
m_log.ErrorFormat("[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago",
thread.Name, thread.ThreadState, now - lastTick);
}
#region Console Commands
/// <summary>
/// Kicks users off the region
/// </summary>
/// <param name="module"></param>
/// <param name="cmdparams">name of avatar to kick</param>
private void KickUserCommand(string module, string[] cmdparams)
{
if (cmdparams.Length < 4)
return;
string alert = null;
if (cmdparams.Length > 4)
alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4));
IList agents = m_sceneManager.GetCurrentSceneAvatars();
foreach (ScenePresence presence in agents)
{
RegionInfo regionInfo = presence.Scene.RegionInfo;
if (presence.Firstname.ToLower().Contains(cmdparams[2].ToLower()) &&
presence.Lastname.ToLower().Contains(cmdparams[3].ToLower()))
{
MainConsole.Instance.Output(
String.Format(
"Kicking user: {0,-16} {1,-16} {2,-37} in region: {3,-16}",
presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName));
// kick client...
if (alert != null)
presence.ControllingClient.Kick(alert);
else
presence.ControllingClient.Kick("\nThe OpenSim manager kicked you out.\n");
// ...and close on our side
presence.Scene.IncomingCloseAgent(presence.UUID);
}
}
MainConsole.Instance.Output("");
}
/// <summary>
/// Run an optional startup list of commands
/// </summary>
/// <param name="fileName"></param>
private void RunCommandScript(string fileName)
{
if (File.Exists(fileName))
{
m_log.Info("[COMMANDFILE]: Running " + fileName);
using (StreamReader readFile = File.OpenText(fileName))
{
string currentCommand;
while ((currentCommand = readFile.ReadLine()) != null)
{
if (currentCommand != String.Empty)
{
m_log.Info("[COMMANDFILE]: Running '" + currentCommand + "'");
m_console.RunCommand(currentCommand);
}
}
}
}
}
/// <summary>
/// Opens a file and uses it as input to the console command parser.
/// </summary>
/// <param name="fileName">name of file to use as input to the console</param>
private static void PrintFileToConsole(string fileName)
{
if (File.Exists(fileName))
{
StreamReader readFile = File.OpenText(fileName);
string currentLine;
while ((currentLine = readFile.ReadLine()) != null)
{
m_log.Info("[!]" + currentLine);
}
}
}
private void HandleClearAssets(string module, string[] args)
{
MainConsole.Instance.Output("Not implemented.");
}
/// <summary>
/// Force resending of all updates to all clients in active region(s)
/// </summary>
/// <param name="module"></param>
/// <param name="args"></param>
private void HandleForceUpdate(string module, string[] args)
{
MainConsole.Instance.Output("Updating all clients");
m_sceneManager.ForceCurrentSceneClientUpdate();
}
/// <summary>
/// Edits the scale of a primative with the name specified
/// </summary>
/// <param name="module"></param>
/// <param name="args">0,1, name, x, y, z</param>
private void HandleEditScale(string module, string[] args)
{
if (args.Length == 6)
{
m_sceneManager.HandleEditCommandOnCurrentScene(args);
}
else
{
MainConsole.Instance.Output("Argument error: edit scale <prim name> <x> <y> <z>");
}
}
/// <summary>
/// Creates a new region based on the parameters specified. This will ask the user questions on the console
/// </summary>
/// <param name="module"></param>
/// <param name="cmd">0,1,region name, region ini or XML file</param>
private void HandleCreateRegion(string module, string[] cmd)
{
string regionName = string.Empty;
string regionFile = string.Empty;
if (cmd.Length == 3)
{
regionFile = cmd[2];
}
else if (cmd.Length > 3)
{
regionName = cmd[2];
regionFile = cmd[3];
}
string extension = Path.GetExtension(regionFile).ToLower();
bool isXml = extension.Equals(".xml");
bool isIni = extension.Equals(".ini");
if (!isXml && !isIni)
{
MainConsole.Instance.Output("Usage: create region [\"region name\"] <region_file.ini>");
return;
}
if (!Path.IsPathRooted(regionFile))
{
string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim();
regionFile = Path.Combine(regionsDir, regionFile);
}
RegionInfo regInfo;
if (isXml)
{
regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source);
}
else
{
regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source, regionName);
}
IScene scene;
PopulateRegionEstateInfo(regInfo);
CreateRegion(regInfo, true, out scene);
regInfo.EstateSettings.Save();
}
/// <summary>
/// Change and load configuration file data.
/// </summary>
/// <param name="module"></param>
/// <param name="cmd"></param>
private void HandleConfig(string module, string[] cmd)
{
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] cmdparams = args.ToArray();
string n = "CONFIG";
if (cmdparams.Length > 0)
{
switch (cmdparams[0].ToLower())
{
case "set":
if (cmdparams.Length < 4)
{
MainConsole.Instance.Output(String.Format("SYNTAX: {0} SET SECTION KEY VALUE",n));
MainConsole.Instance.Output(String.Format("EXAMPLE: {0} SET ScriptEngine.DotNetEngine NumberOfScriptThreads 5",n));
}
else
{
IConfig c;
IConfigSource source = new IniConfigSource();
c = source.AddConfig(cmdparams[1]);
if (c != null)
{
string _value = String.Join(" ", cmdparams, 3, cmdparams.Length - 3);
c.Set(cmdparams[2], _value);
m_config.Source.Merge(source);
MainConsole.Instance.Output(String.Format("{0} {0} {1} {2} {3}",n,cmdparams[1],cmdparams[2],_value));
}
}
break;
case "get":
if (cmdparams.Length < 3)
{
MainConsole.Instance.Output(String.Format("SYNTAX: {0} GET SECTION KEY",n));
MainConsole.Instance.Output(String.Format("EXAMPLE: {0} GET ScriptEngine.DotNetEngine NumberOfScriptThreads",n));
}
else
{
IConfig c = m_config.Source.Configs[cmdparams[1]];
if (c == null)
{
MainConsole.Instance.Output(String.Format("Section \"{0}\" does not exist.",cmdparams[1]));
break;
}
else
{
MainConsole.Instance.Output(String.Format("{0} GET {1} {2} : {3}",n,cmdparams[1],cmdparams[2],
c.GetString(cmdparams[2])));
}
}
break;
case "save":
if (cmdparams.Length < 2)
{
MainConsole.Instance.Output("SYNTAX: " + n + " SAVE FILE");
return;
}
if (Application.iniFilePath == cmdparams[1])
{
MainConsole.Instance.Output("FILE can not be " + Application.iniFilePath);
return;
}
MainConsole.Instance.Output("Saving configuration file: " + cmdparams[1]);
m_config.Save(cmdparams[1]);
break;
}
}
}
/// <summary>
/// Load, Unload, and list Region modules in use
/// </summary>
/// <param name="module"></param>
/// <param name="cmd"></param>
private void HandleModules(string module, string[] cmd)
{
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] cmdparams = args.ToArray();
if (cmdparams.Length > 0)
{
switch (cmdparams[0].ToLower())
{
case "list":
foreach (IRegionModule irm in m_moduleLoader.GetLoadedSharedModules)
{
MainConsole.Instance.Output(String.Format("Shared region module: {0}", irm.Name));
}
break;
case "unload":
if (cmdparams.Length > 1)
{
foreach (IRegionModule rm in new ArrayList(m_moduleLoader.GetLoadedSharedModules))
{
if (rm.Name.ToLower() == cmdparams[1].ToLower())
{
MainConsole.Instance.Output(String.Format("Unloading module: {0}", rm.Name));
m_moduleLoader.UnloadModule(rm);
}
}
}
break;
case "load":
if (cmdparams.Length > 1)
{
foreach (Scene s in new ArrayList(m_sceneManager.Scenes))
{
MainConsole.Instance.Output(String.Format("Loading module: {0}", cmdparams[1]));
m_moduleLoader.LoadRegionModules(cmdparams[1], s);
}
}
break;
}
}
}
/// <summary>
/// Runs commands issued by the server console from the operator
/// </summary>
/// <param name="command">The first argument of the parameter (the command)</param>
/// <param name="cmdparams">Additional arguments passed to the command</param>
public void RunCommand(string module, string[] cmdparams)
{
List<string> args = new List<string>(cmdparams);
if (args.Count < 1)
return;
string command = args[0];
args.RemoveAt(0);
cmdparams = args.ToArray();
switch (command)
{
case "command-script":
if (cmdparams.Length > 0)
{
RunCommandScript(cmdparams[0]);
}
break;
case "backup":
m_sceneManager.BackupCurrentScene();
break;
case "remove-region":
string regRemoveName = CombineParams(cmdparams, 0);
Scene removeScene;
if (m_sceneManager.TryGetScene(regRemoveName, out removeScene))
RemoveRegion(removeScene, false);
else
MainConsole.Instance.Output("no region with that name");
break;
case "delete-region":
string regDeleteName = CombineParams(cmdparams, 0);
Scene killScene;
if (m_sceneManager.TryGetScene(regDeleteName, out killScene))
RemoveRegion(killScene, true);
else
MainConsole.Instance.Output("no region with that name");
break;
case "restart":
m_sceneManager.RestartCurrentScene();
break;
case "Add-InventoryHost":
if (cmdparams.Length > 0)
{
MainConsole.Instance.Output("Not implemented.");
}
break;
}
}
/// <summary>
/// Change the currently selected region. The selected region is that operated upon by single region commands.
/// </summary>
/// <param name="cmdParams"></param>
protected void ChangeSelectedRegion(string module, string[] cmdparams)
{
if (cmdparams.Length > 2)
{
string newRegionName = CombineParams(cmdparams, 2);
if (!m_sceneManager.TrySetCurrentScene(newRegionName))
MainConsole.Instance.Output(String.Format("Couldn't select region {0}", newRegionName));
}
else
{
MainConsole.Instance.Output("Usage: change region <region name>");
}
string regionName = (m_sceneManager.CurrentScene == null ? "root" : m_sceneManager.CurrentScene.RegionInfo.RegionName);
MainConsole.Instance.Output(String.Format("Currently selected region is {0}", regionName));
m_console.DefaultPrompt = String.Format("Region ({0}) ", regionName);
m_console.ConsoleScene = m_sceneManager.CurrentScene;
}
/// <summary>
/// Turn on some debugging values for OpenSim.
/// </summary>
/// <param name="args"></param>
protected void Debug(string module, string[] args)
{
if (args.Length == 1)
return;
switch (args[1])
{
case "packet":
if (args.Length > 2)
{
int newDebug;
if (int.TryParse(args[2], out newDebug))
{
m_sceneManager.SetDebugPacketLevelOnCurrentScene(newDebug);
}
else
{
MainConsole.Instance.Output("packet debug should be 0..255");
}
MainConsole.Instance.Output(String.Format("New packet debug: {0}", newDebug));
}
break;
case "scene":
if (args.Length == 5)
{
if (m_sceneManager.CurrentScene == null)
{
MainConsole.Instance.Output("Please use 'change region <regioname>' first");
}
else
{
bool scriptingOn = !Convert.ToBoolean(args[2]);
bool collisionsOn = !Convert.ToBoolean(args[3]);
bool physicsOn = !Convert.ToBoolean(args[4]);
m_sceneManager.CurrentScene.SetSceneCoreDebug(scriptingOn, collisionsOn, physicsOn);
MainConsole.Instance.Output(
String.Format(
"Set debug scene scripting = {0}, collisions = {1}, physics = {2}",
!scriptingOn, !collisionsOn, !physicsOn));
}
}
else
{
MainConsole.Instance.Output("debug scene <scripting> <collisions> <physics> (where inside <> is true/false)");
}
break;
default:
MainConsole.Instance.Output("Unknown debug");
break;
}
}
// see BaseOpenSimServer
/// <summary>
/// Many commands list objects for debugging. Some of the types are listed here
/// </summary>
/// <param name="mod"></param>
/// <param name="cmd"></param>
public override void HandleShow(string mod, string[] cmd)
{
base.HandleShow(mod, cmd);
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] showParams = args.ToArray();
switch (showParams[0])
{
case "assets":
MainConsole.Instance.Output("Not implemented.");
break;
case "users":
IList agents;
if (showParams.Length > 1 && showParams[1] == "full")
{
agents = m_sceneManager.GetCurrentScenePresences();
}
else
{
agents = m_sceneManager.GetCurrentSceneAvatars();
}
MainConsole.Instance.Output(String.Format("\nAgents connected: {0}\n", agents.Count));
MainConsole.Instance.Output(
String.Format("{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", "Firstname", "Lastname",
"Agent ID", "Root/Child", "Region", "Position"));
foreach (ScenePresence presence in agents)
{
RegionInfo regionInfo = presence.Scene.RegionInfo;
string regionName;
if (regionInfo == null)
{
regionName = "Unresolvable";
}
else
{
regionName = regionInfo.RegionName;
}
MainConsole.Instance.Output(
String.Format(
"{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}",
presence.Firstname,
presence.Lastname,
presence.UUID,
presence.IsChildAgent ? "Child" : "Root",
regionName,
presence.AbsolutePosition.ToString()));
}
MainConsole.Instance.Output(String.Empty);
break;
case "connections":
System.Text.StringBuilder connections = new System.Text.StringBuilder("Connections:\n");
m_sceneManager.ForEachScene(
delegate(Scene scene)
{
scene.ForEachClient(
delegate(IClientAPI client)
{
connections.AppendFormat("{0}: {1} ({2}) from {3} on circuit {4}\n",
scene.RegionInfo.RegionName, client.Name, client.AgentId, client.RemoteEndPoint, client.CircuitCode);
}
);
}
);
MainConsole.Instance.Output(connections.ToString());
break;
case "modules":
MainConsole.Instance.Output("The currently loaded shared modules are:");
foreach (IRegionModule module in m_moduleLoader.GetLoadedSharedModules)
{
MainConsole.Instance.Output("Shared Module: " + module.Name);
}
MainConsole.Instance.Output("");
break;
case "regions":
m_sceneManager.ForEachScene(
delegate(Scene scene)
{
MainConsole.Instance.Output(String.Format(
"Region Name: {0}, Region XLoc: {1}, Region YLoc: {2}, Region Port: {3}",
scene.RegionInfo.RegionName,
scene.RegionInfo.RegionLocX,
scene.RegionInfo.RegionLocY,
scene.RegionInfo.InternalEndPoint.Port));
});
break;
case "queues":
Notice(GetQueuesReport());
break;
case "ratings":
m_sceneManager.ForEachScene(
delegate(Scene scene)
{
string rating = "";
if (scene.RegionInfo.RegionSettings.Maturity == 1)
{
rating = "MATURE";
}
else if (scene.RegionInfo.RegionSettings.Maturity == 2)
{
rating = "ADULT";
}
else
{
rating = "PG";
}
MainConsole.Instance.Output(String.Format(
"Region Name: {0}, Region Rating {1}",
scene.RegionInfo.RegionName,
rating));
});
break;
}
}
/// <summary>
/// print UDP Queue data for each client
/// </summary>
/// <returns></returns>
private string GetQueuesReport()
{
string report = String.Empty;
m_sceneManager.ForEachScene(delegate(Scene scene)
{
scene.ForEachClient(delegate(IClientAPI client)
{
if (client is IStatsCollector)
{
report = report + client.FirstName +
" " + client.LastName;
IStatsCollector stats =
(IStatsCollector) client;
report = report + string.Format("{0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7}\n",
"Send",
"In",
"Out",
"Resend",
"Land",
"Wind",
"Cloud",
"Task",
"Texture",
"Asset");
report = report + stats.Report() +
"\n";
}
});
});
return report;
}
/// <summary>
/// Use XML2 format to serialize data to a file
/// </summary>
/// <param name="module"></param>
/// <param name="cmdparams"></param>
protected void SavePrimsXml2(string module, string[] cmdparams)
{
if (cmdparams.Length > 5)
{
m_sceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]);
}
else
{
m_sceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME);
}
}
/// <summary>
/// Use XML format to serialize data to a file
/// </summary>
/// <param name="module"></param>
/// <param name="cmdparams"></param>
protected void SaveXml(string module, string[] cmdparams)
{
MainConsole.Instance.Output("PLEASE NOTE, save-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use save-xml2, please file a mantis detailing the reason.");
if (cmdparams.Length > 0)
{
m_sceneManager.SaveCurrentSceneToXml(cmdparams[2]);
}
else
{
m_sceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME);
}
}
/// <summary>
/// Loads data and region objects from XML format.
/// </summary>
/// <param name="module"></param>
/// <param name="cmdparams"></param>
protected void LoadXml(string module, string[] cmdparams)
{
MainConsole.Instance.Output("PLEASE NOTE, load-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use load-xml2, please file a mantis detailing the reason.");
Vector3 loadOffset = new Vector3(0, 0, 0);
if (cmdparams.Length > 2)
{
bool generateNewIDS = false;
if (cmdparams.Length > 3)
{
if (cmdparams[3] == "-newUID")
{
generateNewIDS = true;
}
if (cmdparams.Length > 4)
{
loadOffset.X = (float)Convert.ToDecimal(cmdparams[4], Culture.NumberFormatInfo);
if (cmdparams.Length > 5)
{
loadOffset.Y = (float)Convert.ToDecimal(cmdparams[5], Culture.NumberFormatInfo);
}
if (cmdparams.Length > 6)
{
loadOffset.Z = (float)Convert.ToDecimal(cmdparams[6], Culture.NumberFormatInfo);
}
MainConsole.Instance.Output(String.Format("loadOffsets <X,Y,Z> = <{0},{1},{2}>",loadOffset.X,loadOffset.Y,loadOffset.Z));
}
}
m_sceneManager.LoadCurrentSceneFromXml(cmdparams[0], generateNewIDS, loadOffset);
}
else
{
try
{
m_sceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset);
}
catch (FileNotFoundException)
{
MainConsole.Instance.Output("Default xml not found. Usage: load-xml <filename>");
}
}
}
/// <summary>
/// Serialize region data to XML2Format
/// </summary>
/// <param name="module"></param>
/// <param name="cmdparams"></param>
protected void SaveXml2(string module, string[] cmdparams)
{
if (cmdparams.Length > 2)
{
m_sceneManager.SaveCurrentSceneToXml2(cmdparams[2]);
}
else
{
m_sceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME);
}
}
/// <summary>
/// Load region data from Xml2Format
/// </summary>
/// <param name="module"></param>
/// <param name="cmdparams"></param>
protected void LoadXml2(string module, string[] cmdparams)
{
if (cmdparams.Length > 2)
{
try
{
m_sceneManager.LoadCurrentSceneFromXml2(cmdparams[2]);
}
catch (FileNotFoundException)
{
MainConsole.Instance.Output("Specified xml not found. Usage: load xml2 <filename>");
}
}
else
{
try
{
m_sceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME);
}
catch (FileNotFoundException)
{
MainConsole.Instance.Output("Default xml not found. Usage: load xml2 <filename>");
}
}
}
/// <summary>
/// Load a whole region from an opensimulator archive.
/// </summary>
/// <param name="cmdparams"></param>
protected void LoadOar(string module, string[] cmdparams)
{
try
{
m_sceneManager.LoadArchiveToCurrentScene(cmdparams);
}
catch (Exception e)
{
MainConsole.Instance.Output(e.Message);
}
}
/// <summary>
/// Save a region to a file, including all the assets needed to restore it.
/// </summary>
/// <param name="cmdparams"></param>
protected void SaveOar(string module, string[] cmdparams)
{
m_sceneManager.SaveCurrentSceneToArchive(cmdparams);
}
private static string CombineParams(string[] commandParams, int pos)
{
string result = String.Empty;
for (int i = pos; i < commandParams.Length; i++)
{
result += commandParams[i] + " ";
}
result = result.TrimEnd(' ');
return result;
}
/// <summary>
/// Kill an object given its UUID.
/// </summary>
/// <param name="cmdparams"></param>
protected void KillUUID(string module, string[] cmdparams)
{
if (cmdparams.Length > 2)
{
UUID id = UUID.Zero;
SceneObjectGroup grp = null;
Scene sc = null;
if (!UUID.TryParse(cmdparams[2], out id))
{
MainConsole.Instance.Output("[KillUUID]: Error bad UUID format!");
return;
}
m_sceneManager.ForEachScene(
delegate(Scene scene)
{
SceneObjectPart part = scene.GetSceneObjectPart(id);
if (part == null)
return;
grp = part.ParentGroup;
sc = scene;
});
if (grp == null)
{
MainConsole.Instance.Output(String.Format("[KillUUID]: Given UUID {0} not found!", id));
}
else
{
MainConsole.Instance.Output(String.Format("[KillUUID]: Found UUID {0} in scene {1}", id, sc.RegionInfo.RegionName));
try
{
sc.DeleteSceneObject(grp, false);
}
catch (Exception e)
{
m_log.ErrorFormat("[KillUUID]: Error while removing objects from scene: " + e);
}
}
}
else
{
MainConsole.Instance.Output("[KillUUID]: Usage: kill uuid <UUID>");
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace AstroLayout {
[Register ("AstroViewController")]
public class AstroViewController : UIViewController {
NSLayoutConstraint[] regularConstraints;
NSLayoutConstraint[] compactConstraints;
List<NSLayoutConstraint> sharedConstraints;
UIImageView mercury;
UIImageView venus;
UIImageView earth;
UIImageView mars;
UIImageView jupiter;
UIImageView saturn;
UIImageView uranus;
UIImageView neptune;
NSLayoutConstraint mercuryLeadingToTrailing;
NSLayoutConstraint venusLeadingToTrailing;
NSLayoutConstraint earthLeadingToTrailing;
NSLayoutConstraint marsLeadingToTrailing;
NSLayoutConstraint jupiterLeadingToTrailing;
NSLayoutConstraint saturnLeadingToTrailing;
NSLayoutConstraint uranusLeadingToTrailing;
NSLayoutConstraint neptuneLeadingToTrailing;
NSLayoutConstraint mercuryCenter;
NSLayoutConstraint venusCenter;
NSLayoutConstraint earthCenter;
NSLayoutConstraint marsCenter;
NSLayoutConstraint jupiterCenter;
NSLayoutConstraint saturnCenter;
NSLayoutConstraint uranusCenter;
NSLayoutConstraint neptuneCenter;
public AstroViewController (IntPtr handle) : base (handle)
{
}
[Export ("initWithCoder:")]
public AstroViewController (NSCoder coder) : base (coder)
{
}
public override void ViewDidLoad ()
{
View.BackgroundColor = UIColor.Black;
CreatePlanetViews ();
CreateConstraints ();
SetUpGestures ();
}
public override void TraitCollectionDidChange (UITraitCollection previousTraitCollection)
{
if (TraitCollection.Contains (UITraitCollection.FromHorizontalSizeClass (UIUserInterfaceSizeClass.Compact))) {
if (regularConstraints [0].Active) {
NSLayoutConstraint.DeactivateConstraints (regularConstraints);
NSLayoutConstraint.ActivateConstraints (compactConstraints);
}
} else {
if (compactConstraints [0].Active) {
NSLayoutConstraint.DeactivateConstraints (compactConstraints);
NSLayoutConstraint.ActivateConstraints (regularConstraints);
}
}
}
void CreateConstraints ()
{
PlanetSizes ();
CreateCompactConstraints ();
CreateRegularConstraints ();
NSLayoutConstraint.ActivateConstraints (regularConstraints);
NSLayoutConstraint.ActivateConstraints (sharedConstraints.ToArray ());
}
void SetLayoutIdentifierForArray (NSString identifier, NSArray constraintsArray)
{
for (nuint i = 0; i < constraintsArray.Count; i++) {
var constraint = constraintsArray.GetItem<NSLayoutConstraint> (i);
constraint.SetIdentifier (identifier);
}
}
void CreatePlanetViews ()
{
mercury = CreatePlanet ("Mercury");
venus = CreatePlanet ("Venus");
earth = CreatePlanet ("Earth");
mars = CreatePlanet ("Mars");
jupiter = CreatePlanet ("Jupiter");
saturn = CreatePlanet ("Saturn");
uranus = CreatePlanet ("Uranus");
neptune = CreatePlanet ("Neptune");
}
UIImageView CreatePlanet (string planetName)
{
var image = UIImage.FromBundle (planetName);
var planet = new UIImageView (image) {
TranslatesAutoresizingMaskIntoConstraints = false,
ContentMode = UIViewContentMode.ScaleAspectFit,
AccessibilityIdentifier = planetName
};
View.AddSubview (planet);
return planet;
}
void PlanetSizes ()
{
NSLayoutConstraint mercuryHeight = mercury.HeightAnchor.ConstraintEqualTo (earth.HeightAnchor, .38f);
NSLayoutConstraint mercuryWidth = mercury.WidthAnchor.ConstraintEqualTo (mercury.HeightAnchor, 1f);
NSLayoutConstraint venusHeight = venus.HeightAnchor.ConstraintEqualTo (earth.HeightAnchor, .95f);
NSLayoutConstraint venusWidth = venus.WidthAnchor.ConstraintEqualTo (venus.HeightAnchor, 1f);
NSLayoutConstraint marsHeight = mars.HeightAnchor.ConstraintEqualTo (earth.HeightAnchor, .53f);
NSLayoutConstraint marsWidth = mars.WidthAnchor.ConstraintEqualTo (mars.HeightAnchor, 1f);
NSLayoutConstraint jupiterHeight = jupiter.HeightAnchor.ConstraintEqualTo (earth.HeightAnchor, 11.2f);
NSLayoutConstraint jupiterWidth = jupiter.WidthAnchor.ConstraintEqualTo (jupiter.HeightAnchor, 1f);
NSLayoutConstraint saturnHeight = saturn.HeightAnchor.ConstraintEqualTo (earth.HeightAnchor, 9.45f);
NSLayoutConstraint saturnWidth = saturn.WidthAnchor.ConstraintEqualTo (saturn.HeightAnchor, 1.5f);
NSLayoutConstraint uranusHeight = uranus.HeightAnchor.ConstraintEqualTo (earth.HeightAnchor, 4f);
NSLayoutConstraint uranusWidth = uranus.WidthAnchor.ConstraintEqualTo (uranus.HeightAnchor, 1f);
NSLayoutConstraint neptuneHeight = neptune.HeightAnchor.ConstraintEqualTo (earth.HeightAnchor, 3.88f);
NSLayoutConstraint neptuneWidth = neptune.HeightAnchor.ConstraintEqualTo (neptune.HeightAnchor, 1f);
NSLayoutConstraint earthWidth = earth.WidthAnchor.ConstraintEqualTo (earth.HeightAnchor);
mercuryHeight.SetIdentifier ("mercuryHeight");
mercuryHeight.SetIdentifier ("mercuryHeight");
mercuryWidth.SetIdentifier ("mercuryWidth");
venusHeight.SetIdentifier ("venusHeight");
venusWidth.SetIdentifier ("venusWidth");
marsHeight.SetIdentifier ("marsHeight");
marsWidth.SetIdentifier ("marsWidth");
jupiterHeight.SetIdentifier ("jupiterHeight");
jupiterWidth.SetIdentifier ("jupiterWidth");
saturnHeight.SetIdentifier ("saturnHeight");
saturnWidth.SetIdentifier ("saturnWidth");
uranusHeight.SetIdentifier ("uranusHeight");
uranusWidth.SetIdentifier ("uranusWidth");
neptuneHeight.SetIdentifier ("neptuneHeight");
neptuneWidth.SetIdentifier ("neptuneWidth");
earthWidth.SetIdentifier ("earthWidth");
NSLayoutConstraint.ActivateConstraints (new [] {
mercuryHeight, venusHeight, marsHeight, jupiterHeight, saturnHeight,
uranusHeight, neptuneHeight, mercuryWidth, venusWidth, earthWidth,
marsWidth, jupiterWidth, saturnWidth, uranusWidth, neptuneWidth
});
}
void CreateCompactConstraints()
{
if (compactConstraints?.Length > 0)
return;
mercuryCenter = CreateCenterXConstraint (mercury, "mercuryCenterX");
venusCenter = CreateCenterXConstraint (venus, "venusCenterX");
earthCenter = CreateCenterXConstraint (earth, "earthCenterX");
marsCenter = CreateCenterXConstraint (mars, "marsCenterX");
jupiterCenter = CreateCenterXConstraint (jupiter, "jupiterCenterX");
saturnCenter = CreateCenterXConstraint (saturn, "saturnCenterX");
uranusCenter = CreateCenterXConstraint (uranus, "uranusCenterX");
neptuneCenter = CreateCenterXConstraint (neptune, "neptuneCenterX");
compactConstraints = new [] {
mercuryCenter, venusCenter, earthCenter, marsCenter, jupiterCenter, saturnCenter, uranusCenter, neptuneCenter
};
}
NSLayoutConstraint CreateCenterXConstraint (UIView planetToCenter, string identifierName)
{
NSLayoutConstraint newConstraint = planetToCenter.CenterXAnchor.ConstraintEqualTo (View.CenterXAnchor);
newConstraint.SetIdentifier (identifierName);
return newConstraint;
}
void CreateRegularConstraints ()
{
if (regularConstraints?.Length > 0 && sharedConstraints?.Count > 0)
return;
UILayoutGuide leadingMercuryGuide = NewLayoutGuide ("leadingMercuryGuide");
UILayoutGuide leadingVenusGuide = NewLayoutGuide ("leadingVenusGuide");
UILayoutGuide leadingEarthGuide = NewLayoutGuide ("leadingEarthGuide");
UILayoutGuide leadingMarsGuide = NewLayoutGuide ("leadingMarsGuide");
UILayoutGuide leadingJupiterGuide = NewLayoutGuide ("leadingJupiterGuide");
UILayoutGuide leadingSaturnGuide = NewLayoutGuide ("leadingSaturnGuide");
UILayoutGuide leadingUranusGuide = NewLayoutGuide ("leadingUranusGuide");
UILayoutGuide leadingNeptuneGuide = NewLayoutGuide ("leadingNeptuneGuide");
UILayoutGuide trailingMercuryGuide = NewLayoutGuide ("trailingMercuryGuide");
UILayoutGuide trailingVenusGuide = NewLayoutGuide ("trailingVenusGuide");
UILayoutGuide trailingEarthGuide = NewLayoutGuide ("trailingEarthGuide");
UILayoutGuide trailingMarsGuide = NewLayoutGuide ("trailingMarsGuide");
UILayoutGuide trailingJupiterGuide = NewLayoutGuide ("trailingJupiterGuide");
UILayoutGuide trailingSaturnGuide = NewLayoutGuide ("trailingSaturnGuide");
UILayoutGuide trailingUranusGuide = NewLayoutGuide ("trailingUranusGuide");
UILayoutGuide trailingNeptuneGuide = NewLayoutGuide ("trailingNeptuneGuide");
IUILayoutSupport topLayoutGuide = TopLayoutGuide;
var planetsAndGuides = NSDictionary.FromObjectsAndKeys (new object[] {
mercury, venus, earth, mars, jupiter, saturn, uranus, neptune,
leadingMercuryGuide, leadingVenusGuide, leadingEarthGuide, leadingMarsGuide,
leadingJupiterGuide, leadingSaturnGuide, leadingUranusGuide, leadingNeptuneGuide,
trailingMercuryGuide, trailingVenusGuide, trailingEarthGuide, trailingMarsGuide,
trailingJupiterGuide, trailingSaturnGuide, trailingUranusGuide, trailingNeptuneGuide, topLayoutGuide
}, new object[] {
"mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune",
"leadingMercuryGuide", "leadingVenusGuide", "leadingEarthGuide", "leadingMarsGuide",
"leadingJupiterGuide", "leadingSaturnGuide", "leadingUranusGuide", "leadingNeptuneGuide",
"trailingMercuryGuide", "trailingVenusGuide", "trailingEarthGuide", "trailingMarsGuide",
"trailingJupiterGuide", "trailingSaturnGuide", "trailingUranusGuide", "trailingNeptuneGuide", "topLayoutGuide"
});
var topToBottom = NSLayoutConstraint.FromVisualFormat ("V:|[topLayoutGuide]-[leadingMercuryGuide]-" +
"[leadingVenusGuide]-[leadingEarthGuide]-[leadingMarsGuide]-" +
"[leadingJupiterGuide][leadingSaturnGuide][leadingUranusGuide]-" +
"[leadingNeptuneGuide]-20-|", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, planetsAndGuides);
sharedConstraints = new List<NSLayoutConstraint> (topToBottom);
SetLayoutIdentifierForArray ((NSString)"topToBottom", NSArray.FromObjects (topToBottom));
NewHorizontalArray ("|[leadingMercuryGuide][mercury][trailingMercuryGuide]|", "hMercury", planetsAndGuides);
NewHorizontalArray ("|[leadingVenusGuide][venus][trailingVenusGuide]|", "hVenus", planetsAndGuides);
NewHorizontalArray ("|[leadingEarthGuide][earth][trailingEarthGuide]|", "hEarth", planetsAndGuides);
NewHorizontalArray ("|[leadingMarsGuide][mars][trailingMarsGuide]|", "hMars", planetsAndGuides);
NewHorizontalArray ("|[leadingJupiterGuide][jupiter][trailingJupiterGuide]|", "hJupiter", planetsAndGuides);
NewHorizontalArray ("|[leadingSaturnGuide][saturn][trailingSaturnGuide]|", "hSaturn", planetsAndGuides);
NewHorizontalArray ("|[leadingUranusGuide][uranus][trailingUranusGuide]|", "hUranus", planetsAndGuides);
NewHorizontalArray ("|[leadingNeptuneGuide][neptune][trailingNeptuneGuide]|", "hNeptune", planetsAndGuides);
sharedConstraints.Add (GuideHeightToPlanet (leadingMercuryGuide, mercury, "guideHeightToMercury"));
sharedConstraints.Add (GuideHeightToPlanet (leadingVenusGuide, venus, "guideHeightToVenus"));
sharedConstraints.Add (GuideHeightToPlanet (leadingEarthGuide, earth, "guideHeightToEarth"));
sharedConstraints.Add (GuideHeightToPlanet (leadingMarsGuide, mars, "guideHeightToMars"));
sharedConstraints.Add (GuideHeightToPlanet (leadingJupiterGuide, jupiter, "guideHeightToJupiter"));
sharedConstraints.Add (GuideHeightToPlanet (leadingSaturnGuide, saturn, "guideHeightToSaturn"));
sharedConstraints.Add (GuideHeightToPlanet (leadingUranusGuide, uranus, "guideHeightToUranus"));
sharedConstraints.Add (GuideHeightToPlanet (leadingNeptuneGuide, neptune, "guideHeightToNeptune"));
mercuryLeadingToTrailing = leadingMercuryGuide.WidthAnchor.ConstraintEqualTo (trailingMercuryGuide.WidthAnchor, .02f);
venusLeadingToTrailing = leadingVenusGuide.WidthAnchor.ConstraintEqualTo (trailingVenusGuide.WidthAnchor, .03f);
earthLeadingToTrailing = leadingEarthGuide.WidthAnchor.ConstraintEqualTo (trailingEarthGuide.WidthAnchor, .06f);
marsLeadingToTrailing = leadingMarsGuide.WidthAnchor.ConstraintEqualTo (trailingMarsGuide.WidthAnchor, .1f);
jupiterLeadingToTrailing = leadingJupiterGuide.WidthAnchor.ConstraintEqualTo (trailingJupiterGuide.WidthAnchor, .2f);
saturnLeadingToTrailing = leadingSaturnGuide.WidthAnchor.ConstraintEqualTo (trailingSaturnGuide.WidthAnchor, 1f);
uranusLeadingToTrailing = leadingUranusGuide.WidthAnchor.ConstraintEqualTo (trailingUranusGuide.WidthAnchor, 2.7f);
neptuneLeadingToTrailing = leadingNeptuneGuide.WidthAnchor.ConstraintEqualTo (trailingNeptuneGuide.WidthAnchor, 10f);
mercuryLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorMercury");
venusLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorVenus");
earthLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorEarth");
marsLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorMars");
jupiterLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorJupiter");
saturnLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorSaturn");
uranusLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorUranus");
neptuneLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorNeptune");
regularConstraints = new [] {
mercuryLeadingToTrailing, venusLeadingToTrailing, earthLeadingToTrailing, marsLeadingToTrailing,
saturnLeadingToTrailing, jupiterLeadingToTrailing, uranusLeadingToTrailing, neptuneLeadingToTrailing
};
}
void NewHorizontalArray (string layoutString, string arrayID, NSDictionary planetsAndGuides)
{
var horizontalConstraintsArray = NSLayoutConstraint.FromVisualFormat (layoutString, NSLayoutFormatOptions.AlignAllCenterY, null, planetsAndGuides);
sharedConstraints.AddRange (horizontalConstraintsArray);
SetLayoutIdentifierForArray ((NSString)arrayID, NSArray.FromObjects (horizontalConstraintsArray));
}
NSLayoutConstraint GuideHeightToPlanet (UILayoutGuide layoutGuide, UIView planet, string identifier)
{
NSLayoutConstraint guideHeightToPlanet = layoutGuide.HeightAnchor.ConstraintEqualTo (planet.HeightAnchor);
guideHeightToPlanet.SetIdentifier (identifier);
return guideHeightToPlanet;
}
UILayoutGuide NewLayoutGuide (string identifierName)
{
var newGuide = new UILayoutGuide {
Identifier = identifierName
};
View.AddLayoutGuide (newGuide);
return newGuide;
}
void ChangeLayout (UIGestureRecognizer tapGesture)
{
if (tapGesture.State != UIGestureRecognizerState.Ended)
return;
NSLayoutConstraint regularConstraint = regularConstraints.First ();
NSLayoutConstraint compactConstraint = compactConstraints.First ();
if (regularConstraint.Active) {
UIView.Animate (1.0, () => {
NSLayoutConstraint.DeactivateConstraints (regularConstraints);
NSLayoutConstraint.ActivateConstraints (compactConstraints);
View.LayoutIfNeeded ();
});
} else if (compactConstraint.Active) {
UIView.Animate (1.0, () => {
NSLayoutConstraint.DeactivateConstraints (compactConstraints);
NSLayoutConstraint.ActivateConstraints (regularConstraints);
View.LayoutIfNeeded ();
});
}
}
void KeyframeBasedLayoutChange (UIGestureRecognizer twoFingerDoubleTap)
{
if (twoFingerDoubleTap.State != UIGestureRecognizerState.Ended)
return;
NSLayoutConstraint regularConstraint = regularConstraints.First ();
NSLayoutConstraint compactConstraint = compactConstraints.First ();
if (regularConstraint.Active) {
UIView.AnimateKeyframes (1.5, 0.0, UIViewKeyframeAnimationOptions.CalculationModeLinear,
AnimateToCompact, finished => {
});
} else if (compactConstraint.Active) {
UIView.AnimateKeyframes (1.5, 0.0, UIViewKeyframeAnimationOptions.CalculationModeLinear,
AnimateToRegular, finished => {
});
}
}
void AnimateToRegular ()
{
UIView.AddKeyframeWithRelativeStartTime (0.0, 1.0, () => {
NSLayoutConstraint.DeactivateConstraints (new [] { mercuryCenter });
NSLayoutConstraint.ActivateConstraints (new [] { mercuryLeadingToTrailing });
View.LayoutIfNeeded ();
});
UIView.AddKeyframeWithRelativeStartTime (0.0, 0.9, () => {
NSLayoutConstraint.DeactivateConstraints (new [] { venusCenter, neptuneCenter });
NSLayoutConstraint.ActivateConstraints (new [] { venusLeadingToTrailing, neptuneLeadingToTrailing });
View.LayoutIfNeeded ();
});
UIView.AddKeyframeWithRelativeStartTime (0.0, 0.7, () => {
NSLayoutConstraint.DeactivateConstraints (new [] { earthCenter, uranusCenter });
NSLayoutConstraint.ActivateConstraints (new [] { earthLeadingToTrailing, uranusLeadingToTrailing });
View.LayoutIfNeeded ();
});
UIView.AddKeyframeWithRelativeStartTime (0.0, 0.5, () => {
NSLayoutConstraint.DeactivateConstraints (new [] { marsCenter, jupiterCenter, saturnCenter });
NSLayoutConstraint.ActivateConstraints (new [] { marsLeadingToTrailing, jupiterLeadingToTrailing, saturnLeadingToTrailing });
View.LayoutIfNeeded ();
});
}
void AnimateToCompact ()
{
UIView.AddKeyframeWithRelativeStartTime (0.0, 1.0, () => {
NSLayoutConstraint.DeactivateConstraints (new [] { marsLeadingToTrailing, jupiterLeadingToTrailing, saturnLeadingToTrailing });
NSLayoutConstraint.ActivateConstraints (new [] { marsCenter, jupiterCenter, saturnCenter });
View.LayoutIfNeeded ();
});
UIView.AddKeyframeWithRelativeStartTime (0.1, 0.9, () => {
NSLayoutConstraint.DeactivateConstraints (new [] { earthLeadingToTrailing, uranusLeadingToTrailing });
NSLayoutConstraint.ActivateConstraints (new [] { earthCenter, uranusCenter });
View.LayoutIfNeeded ();
});
UIView.AddKeyframeWithRelativeStartTime (0.3, 0.7, () => {
NSLayoutConstraint.DeactivateConstraints (new [] { venusLeadingToTrailing, neptuneLeadingToTrailing });
NSLayoutConstraint.ActivateConstraints (new [] { venusCenter, neptuneCenter });
View.LayoutIfNeeded ();
});
UIView.AddKeyframeWithRelativeStartTime (0.5, 0.5, () => {
NSLayoutConstraint.DeactivateConstraints (new [] { mercuryLeadingToTrailing });
NSLayoutConstraint.ActivateConstraints (new [] { mercuryCenter });
View.LayoutIfNeeded ();
});
}
void SetUpGestures ()
{
UITapGestureRecognizer doubleTap = null;
doubleTap = new UITapGestureRecognizer (() => ChangeLayout (doubleTap)) {
NumberOfTapsRequired = 2,
NumberOfTouchesRequired = 1
};
View.AddGestureRecognizer (doubleTap);
UITapGestureRecognizer twoFingerDoubleTap = null;
twoFingerDoubleTap = new UITapGestureRecognizer (() => KeyframeBasedLayoutChange (twoFingerDoubleTap)) {
NumberOfTapsRequired = 2,
NumberOfTouchesRequired = 2
};
View.AddGestureRecognizer (twoFingerDoubleTap);
}
}
}
| |
using System;
namespace NQuery.Compilation
{
internal sealed class Normalizer : StandardVisitor
{
public override ExpressionNode VisitUnaryExpression(UnaryExpression expression)
{
// First visit arguments
base.VisitUnaryExpression(expression);
if (expression.Op == UnaryOperator.LogicalNot)
{
// Replace "NOT NOT expr" by "expr"
UnaryExpression unOp = expression.Operand as UnaryExpression;
if (unOp != null)
{
if (unOp.Op == UnaryOperator.LogicalNot)
return VisitExpression(unOp.Operand);
}
// Replace "NOT expr IS NULL" and "NOT expr IS NOT NULL" by
// "expr IS NOT NULL" and "expr IS NULL" resp.
IsNullExpression isNull = expression.Operand as IsNullExpression;
if (isNull != null)
{
isNull.Negated = !isNull.Negated;
return VisitExpression(isNull);
}
// Apply negation on EXISTS
ExistsSubselect existsSubselect = expression.Operand as ExistsSubselect;
if (existsSubselect != null)
{
existsSubselect.Negated = !existsSubselect.Negated;
return existsSubselect;
}
// Apply negation on ALL/ANY subquery
AllAnySubselect allAnySubselect = expression.Operand as AllAnySubselect;
if (allAnySubselect != null)
{
allAnySubselect.Op = AstUtil.NegateBinaryOp(allAnySubselect.Op);
allAnySubselect.Type = (allAnySubselect.Type == AllAnySubselect.AllAnyType.All) ? AllAnySubselect.AllAnyType.Any : AllAnySubselect.AllAnyType.All;
return allAnySubselect;
}
// Apply De Morgan's law
BinaryExpression binOp = expression.Operand as BinaryExpression;
if (binOp != null)
{
BinaryOperator negatedOp = AstUtil.NegateBinaryOp(binOp.Op);
if (negatedOp != null)
{
ExpressionNode newLeft;
ExpressionNode newRight;
if (binOp.Op == BinaryOperator.LogicalAnd || binOp.Op == BinaryOperator.LogicalOr)
{
newLeft = new UnaryExpression(expression.Op, binOp.Left);
newRight = new UnaryExpression(expression.Op, binOp.Right);
}
else
{
newLeft = binOp.Left;
newRight = binOp.Right;
}
binOp.Op = negatedOp;
binOp.Left = newLeft;
binOp.Right = newRight;
return VisitExpression(binOp);
}
}
}
return expression;
}
public override ExpressionNode VisitBetweenExpression(BetweenExpression expression)
{
// First visit all expressions
base.VisitBetweenExpression(expression);
// Since a BETWEEN expression can be expressed using an AND expression and two
// <= binary operator nodes we convert them to simplify the join and optimization engine.
BinaryExpression lowerBound = new BinaryExpression(BinaryOperator.LessOrEqual, expression.LowerBound, expression.Expression);
BinaryExpression upperBound = new BinaryExpression(BinaryOperator.LessOrEqual, expression.Expression, expression.UpperBound);
BinaryExpression and = new BinaryExpression(BinaryOperator.LogicalAnd, lowerBound, upperBound);
// Make sure we also resolve the result.
return VisitExpression(and);
}
public override ExpressionNode VisitInExpression(InExpression expression)
{
// First visit right expressions
base.VisitInExpression(expression);
// Check if the IN expression should have been expr = ANY (suquery)
if (expression.RightExpressions.Length == 1)
{
SingleRowSubselect firstElemenAsSubselect = expression.RightExpressions[0] as SingleRowSubselect;
if (firstElemenAsSubselect != null)
{
AllAnySubselect result = new AllAnySubselect();
result.Type = AllAnySubselect.AllAnyType.Any;
result.Left = expression.Left;
result.Op = BinaryOperator.Equal;
result.Query = firstElemenAsSubselect.Query;
return result;
}
}
// IN-expressions can be written as a chain of OR and = expressions:
//
// leftExpr IN (rightExpr1 , ... , rightExprN)
//
// (leftExpr = rightExpr1) OR (...) OR (leftExpr = rightExprN)
ExpressionNode resultNode = null;
foreach (ExpressionNode rightExpression in expression.RightExpressions)
{
ExpressionNode clonedLeft = (ExpressionNode) expression.Left.Clone();
BinaryExpression comparisionNode = new BinaryExpression(BinaryOperator.Equal, clonedLeft, rightExpression);
if (resultNode == null)
resultNode = comparisionNode;
else
{
BinaryExpression orNode = new BinaryExpression(BinaryOperator.LogicalOr, resultNode, comparisionNode);
resultNode = orNode;
}
}
// Visit resulting expression.
return VisitExpression(resultNode);
}
public override ExpressionNode VisitCoalesceExpression(CoalesceExpression expression)
{
// First visit all expressions
base.VisitCoalesceExpression(expression);
// Since a COALESCE expression can be expressed using a CASE expression we convert
// them to simplify the evaluation and optimization engine.
//
// COALESCE(expression1,...,expressionN) is equivalent to this CASE expression:
//
// CASE
// WHEN (expression1 IS NOT NULL) THEN expression1
// ...
// WHEN (expressionN IS NOT NULL) THEN expressionN
// END
CaseExpression caseExpression = new CaseExpression();
caseExpression.WhenExpressions = new ExpressionNode[expression.Expressions.Length];
caseExpression.ThenExpressions = new ExpressionNode[expression.Expressions.Length];
for (int i = 0; i < expression.Expressions.Length; i++)
{
ExpressionNode whenPart = expression.Expressions[i];
ExpressionNode thenPart = (ExpressionNode) whenPart.Clone();
caseExpression.WhenExpressions[i] = new IsNullExpression(true, whenPart);
caseExpression.ThenExpressions[i] = thenPart;
}
return VisitExpression(caseExpression);
}
public override ExpressionNode VisitNullIfExpression(NullIfExpression expression)
{
// First visit all expressions
base.VisitNullIfExpression (expression);
// Since a NULLIF expression can be expressed using a CASE expression we convert
// them to simplify the evaluation and optimization engine.
//
// NULLIF(expression1, expression1) is equivalent to this CASE expression:
//
// CASE
// WHEN expression1 = expression2 THEN NULL
// ELSE expression1
// END
CaseExpression caseExpression = new CaseExpression();
caseExpression.WhenExpressions = new ExpressionNode[1];
caseExpression.ThenExpressions = new ExpressionNode[1];
caseExpression.WhenExpressions[0] = new BinaryExpression(BinaryOperator.Equal, expression.LeftExpression, expression.RightExpression);
caseExpression.ThenExpressions[0] = LiteralExpression.FromNull();
caseExpression.ElseExpression = expression.LeftExpression;
return VisitExpression(caseExpression);
}
public override ExpressionNode VisitCaseExpression(CaseExpression expression)
{
// Replace simple CASE by searched CASE, i.e.
//
// replace
//
// CASE InputExpr
// WHEN Expr1 THEN ThenExpr1 ...
// WHEN ExprN THEN ThenExprN
// [ELSE ElseExpr]
// END
//
// by
//
// CASE
// WHEN InputExpr = Expr1 THEN ThenExpr1 ...
// WHEN InputExpr = ExprN THEN ThenExprN
// [ELSE ElseExpr]
// END
if (expression.InputExpression != null)
{
for (int i = 0; i < expression.WhenExpressions.Length; i++)
{
BinaryExpression binaryExpression = new BinaryExpression();
binaryExpression.Op = BinaryOperator.Equal;
binaryExpression.Left = (ExpressionNode) expression.InputExpression.Clone();
binaryExpression.Right = expression.WhenExpressions[i];
expression.WhenExpressions[i] = binaryExpression;
}
expression.InputExpression = null;
}
return base.VisitCaseExpression(expression);
}
public override QueryNode VisitSortedQuery(SortedQuery query)
{
// Check if the input is select query. In this case we push the ORDER BY clause into the select query.
// This is needed because the semantic of ORDER BY is slightly different for SELECT / UNION SELECT queries.
SelectQuery inputAsSelectQuery = query.Input as SelectQuery;
if (inputAsSelectQuery != null)
{
inputAsSelectQuery.OrderByColumns = query.OrderByColumns;
return VisitQuery(inputAsSelectQuery);
}
return base.VisitSortedQuery(query);
}
}
}
| |
using System;
using System.Linq;
using System.Web;
using MbUnit.Framework;
using Subtext.Extensibility.Interfaces;
using Subtext.Framework;
using Subtext.Framework.Configuration;
namespace UnitTests.Subtext.Framework
{
/// <summary>
/// Tests of the <see cref="Blog"/> class.
/// </summary>
[TestFixture]
public class BlogTests
{
[RowTest]
[Row("example.com", "example.com", "Should not have altered the host because it doesn't start with www.")]
[Row("example.com:1234", "example.com:1234", "should not strip the port number")]
[Row("www.example.com:1234", "example.com:1234", "should not strip the port number, but should strip www.")]
[Row("www.example.com", "example.com", "Should strip www.")]
public void StripWwwPrefixFromHostFunctionsProperly(string host, string expected, string message)
{
Assert.AreEqual(expected, Blog.StripWwwPrefixFromHost(host), message);
}
[Test]
public void StripWwwPrefixFromHost_WithNullHost_ThrowsArgumentNullException()
{
UnitTestHelper.AssertThrowsArgumentNullException(() => Blog.StripWwwPrefixFromHost(null));
}
[RowTest]
[Row("example.com", "example.com", "Should not have altered the host because it doesn't have the port.")]
[Row("example.com:1234", "example.com", "should strip the port number")]
[Row("www.example.com:12345678910", "www.example.com", "should strip the port number.")]
public void StripPortFromHostFunctionsProperly(string host, string expected, string message)
{
Assert.AreEqual(expected, Blog.StripPortFromHost(host), message);
}
[Test]
public void StripPortFromHost_WithNullHost_ThrowsArgumentNullException()
{
UnitTestHelper.AssertThrowsArgumentNullException(() => Blog.StripPortFromHost(null));
}
/// <summary>
/// Makes sure we can setup the fake HttpContext.
/// </summary>
[Test]
public void SetHttpContextWithBlogRequestDoesADecentSimulation()
{
UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "", "");
Assert.AreEqual(HttpContext.Current.Request.Url.Host, "localhost");
Assert.AreEqual(HttpContext.Current.Request.ApplicationPath, "/");
UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "blog", "Subtext.Web");
Assert.AreEqual(HttpContext.Current.Request.Url.Host, "localhost");
Assert.AreEqual(HttpContext.Current.Request.ApplicationPath, "/Subtext.Web");
UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "", "Subtext.Web");
Assert.AreEqual(HttpContext.Current.Request.Url.Host, "localhost");
Assert.AreEqual(HttpContext.Current.Request.ApplicationPath, "/Subtext.Web");
}
[Test]
public void PropertyGetSetTests()
{
var blog = new Blog();
Assert.AreEqual("Subtext Weblog", blog.Author, "Expected the default author name.");
//blog.CustomMetaTags = "Test";
//Assert.AreEqual("Test", blog.CustomMetaTags);
//blog.TrackingCode = "Test";
//Assert.AreEqual("Test", blog.TrackingCode);
//blog.TrackbackNoficationEnabled = true;
//Assert.IsTrue(blog.TrackbackNoficationEnabled);
//blog.TrackbackNoficationEnabled = false;
//Assert.IsFalse(blog.TrackbackNoficationEnabled);
blog.CaptchaEnabled = true;
Assert.IsTrue((blog.Flag & ConfigurationFlags.CaptchaEnabled) == ConfigurationFlags.CaptchaEnabled);
Assert.IsTrue(blog.CaptchaEnabled);
blog.CaptchaEnabled = false;
Assert.IsTrue((blog.Flag & ConfigurationFlags.CaptchaEnabled) != ConfigurationFlags.CaptchaEnabled);
blog.CoCommentsEnabled = true;
Assert.IsTrue(blog.CoCommentsEnabled);
Assert.IsTrue((blog.Flag & ConfigurationFlags.CoCommentEnabled) == ConfigurationFlags.CoCommentEnabled);
blog.CoCommentsEnabled = false;
Assert.IsTrue((blog.Flag & ConfigurationFlags.CoCommentEnabled) != ConfigurationFlags.CoCommentEnabled);
blog.IsActive = true;
Assert.IsTrue(blog.IsActive);
Assert.IsTrue((blog.Flag & ConfigurationFlags.IsActive) == ConfigurationFlags.IsActive);
blog.IsActive = false;
Assert.IsTrue((blog.Flag & ConfigurationFlags.IsActive) != ConfigurationFlags.IsActive);
blog.ShowEmailAddressInRss = true;
Assert.IsTrue(blog.ShowEmailAddressInRss);
Assert.IsTrue((blog.Flag & ConfigurationFlags.ShowAuthorEmailAddressinRss) ==
ConfigurationFlags.ShowAuthorEmailAddressinRss);
blog.ShowEmailAddressInRss = false;
Assert.IsTrue((blog.Flag & ConfigurationFlags.ShowAuthorEmailAddressinRss) !=
ConfigurationFlags.ShowAuthorEmailAddressinRss);
blog.IsAggregated = true;
Assert.IsTrue(blog.IsAggregated);
Assert.IsTrue((blog.Flag & ConfigurationFlags.IsAggregated) == ConfigurationFlags.IsAggregated);
blog.IsAggregated = false;
Assert.IsTrue((blog.Flag & ConfigurationFlags.IsAggregated) != ConfigurationFlags.IsAggregated);
blog.CommentCount = 42;
Assert.AreEqual(42, blog.CommentCount);
blog.PingTrackCount = 8;
Assert.AreEqual(8, blog.PingTrackCount);
blog.NumberOfRecentComments = 2006;
Assert.AreEqual(2006, blog.NumberOfRecentComments);
blog.PostCount = 1997;
Assert.AreEqual(1997, blog.PostCount);
blog.RecentCommentsLength = 1993;
Assert.AreEqual(1993, blog.RecentCommentsLength);
blog.StoryCount = 1975;
Assert.AreEqual(1975, blog.StoryCount);
UnitTestHelper.AssertSimpleProperties(blog, "OpenIdUrl");
}
[Test]
[RollBack2]
public void CanGetBlogs()
{
// arrange
UnitTestHelper.SetupBlog();
// act
IPagedCollection<Blog> blogs = Blog.GetBlogs(0, int.MaxValue, ConfigurationFlags.None);
// assert
Assert.GreaterEqualThan(blogs.Count, 1);
var blog = blogs.First(b => b.Id == Config.CurrentBlog.Id);
Assert.IsNotNull(blog);
}
[Test]
public void CanTestForEquality()
{
var blog = new Blog();
blog.Id = 12;
Assert.IsFalse(blog.Equals(null), "Blog should not equal null");
Assert.IsFalse(blog.Equals("Something Not A Blog"), "Blog should not equal a string");
var blog2 = new Blog();
blog2.Id = 12;
Assert.IsTrue(blog.Equals(blog2));
}
[Test]
public void CanGetDefaultTimeZone()
{
var blog = new Blog();
blog.TimeZoneId = null;
Assert.IsNotNull(blog.TimeZone);
}
[Test]
public void CanGetLanguageAndLanguageCode()
{
var blog = new Blog();
blog.Language = null;
Assert.AreEqual("en-US", blog.Language, "By default, the language is en-US");
Assert.AreEqual("en", blog.LanguageCode);
blog.Language = "fr-FR";
Assert.AreEqual("fr-FR", blog.Language, "The language should have changed.");
Assert.AreEqual("fr", blog.LanguageCode);
}
[Test]
public void HasNewsReturnsProperResult()
{
var blog = new Blog();
Assert.IsFalse(blog.HasNews);
blog.News = "You rock! Story at eleven";
Assert.IsTrue(blog.HasNews);
}
[Test]
public void CanGetHashCode()
{
var blog = new Blog();
blog.Host = "http://subtextproject.com";
blog.Subfolder = "blog";
Assert.AreNotEqual(0, blog.GetHashCode());
}
[Test]
public void CanSetFeedBurnerName()
{
var blog = new Blog();
blog.RssProxyUrl = null;
Assert.IsFalse(blog.RssProxyEnabled);
blog.RssProxyUrl = "Subtext";
Assert.IsTrue(blog.RssProxyEnabled);
}
[Test]
public void GetBlogsByHostThrowsArgumentNullException()
{
UnitTestHelper.AssertThrowsArgumentNullException(() =>
Blog.GetBlogsByHost(null, 0, 10,
ConfigurationFlags.IsActive));
}
[Test]
public void RssProxyUrl_WithInvalidCharacters_ThrowsInvalidOperationException()
{
UnitTestHelper.AssertThrows<InvalidOperationException>(() => new Blog().RssProxyUrl = "\\");
}
[Test]
public void OpenIdUrl_WhenSetToValueWithoutHttp_PrependsHttp()
{
// arrange
var blog = new Blog();
// act
blog.OpenIdUrl = "openid.example.com";
// assert
Assert.AreEqual("http://openid.example.com", blog.OpenIdUrl);
}
[Test]
public void OpenIdUrl_WhenSetToValueWithHttp_SetsUrl()
{
// arrange
var blog = new Blog();
// act
blog.OpenIdUrl = "http://openid.example.com";
// assert
Assert.AreEqual("http://openid.example.com", blog.OpenIdUrl);
}
[Test]
public void OpenIdUrl_WhenSetToNull_IsNull()
{
// arrange
var blog = new Blog();
// act
blog.OpenIdUrl = null;
// assert
Assert.IsNull(blog.OpenIdUrl);
}
}
}
| |
// 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.
#pragma warning disable 0420
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SlimManualResetEvent.cs
//
//
// An manual-reset event that mixes a little spinning with a true Win32 event.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
using System.Runtime.InteropServices;
using Internal.Runtime.Augments;
namespace System.Threading
{
// ManualResetEventSlim wraps a manual-reset event internally with a little bit of
// spinning. When an event will be set imminently, it is often advantageous to avoid
// a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to
// a brief amount of spinning that should, on the average, make using the slim event
// cheaper than using Win32 events directly. This can be reset manually, much like
// a Win32 manual-reset would be.
//
// Notes:
// We lazily allocate the Win32 event internally. Therefore, the caller should
// always call Dispose to clean it up, just in case. This API is a no-op of the
// event wasn't allocated, but if it was, ensures that the event goes away
// eagerly, instead of waiting for finalization.
/// <summary>
/// Provides a slimmed down version of <see cref="T:System.Threading.ManualResetEvent"/>.
/// </summary>
/// <remarks>
/// All public and protected members of <see cref="ManualResetEventSlim"/> are thread-safe and may be used
/// concurrently from multiple threads, with the exception of Dispose, which
/// must only be used when all other operations on the <see cref="ManualResetEventSlim"/> have
/// completed, and Reset, which should only be used when no other threads are
/// accessing the event.
/// </remarks>
[DebuggerDisplay("Set = {IsSet}")]
public class ManualResetEventSlim : IDisposable
{
// These are the default spin counts we use on single-proc and MP machines.
private const int DEFAULT_SPIN_SP = 1;
private const int DEFAULT_SPIN_MP = 10;
private volatile Lock m_lock;
private volatile Condition m_condition;
// A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated()
private volatile ManualResetEvent m_eventObj; // A true Win32 event used for waiting.
// -- State -- //
//For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant.
private volatile int m_combinedState; //ie a UInt32. Used for the state items listed below.
//1-bit for signalled state
private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000
private const int SignalledState_ShiftCount = 31;
//1-bit for disposed state
private const int Dispose_BitMask = unchecked((int)0x40000000);//0100 0000 0000 0000 0000 0000 0000 0000
//11-bits for m_spinCount
private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); //0011 1111 1111 1000 0000 0000 0000 0000
private const int SpinCountState_ShiftCount = 19;
private const int SpinCountState_MaxValue = (1 << 11) - 1; //2047
//19-bits for m_waiters. This allows support of 512K threads waiting which should be ample
private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111
private const int NumWaitersState_ShiftCount = 0;
private const int NumWaitersState_MaxValue = (1 << 19) - 1; //512K-1
// ----------- //
#if DEBUG
private static int s_nextId; // The next id that will be given out.
private int m_id = Interlocked.Increment(ref s_nextId); // A unique id for debugging purposes only.
private long m_lastSetTime;
private long m_lastResetTime;
#endif
/// <summary>
/// Gets the underlying <see cref="T:System.Threading.WaitHandle"/> object for this <see
/// cref="ManualResetEventSlim"/>.
/// </summary>
/// <value>The underlying <see cref="T:System.Threading.WaitHandle"/> event object fore this <see
/// cref="ManualResetEventSlim"/>.</value>
/// <remarks>
/// Accessing this property forces initialization of an underlying event object if one hasn't
/// already been created. To simply wait on this <see cref="ManualResetEventSlim"/>,
/// the public Wait methods should be preferred.
/// </remarks>
public WaitHandle WaitHandle
{
get
{
ThrowIfDisposed();
if (m_eventObj == null)
{
// Lazily initialize the event object if needed.
LazyInitializeEvent();
}
return m_eventObj;
}
}
/// <summary>
/// Gets whether the event is set.
/// </summary>
/// <value>true if the event has is set; otherwise, false.</value>
public bool IsSet
{
get
{
return 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask);
}
private set
{
UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask);
}
}
/// <summary>
/// Gets the number of spin waits that will be occur before falling back to a true wait.
/// </summary>
public int SpinCount
{
get
{
return ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount);
}
private set
{
Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
// Don't worry about thread safety because it's set one time from the constructor
m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount);
}
}
/// <summary>
/// How many threads are waiting.
/// </summary>
private int Waiters
{
get
{
return ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount);
}
set
{
//setting to <0 would indicate an internal flaw, hence Assert is appropriate.
Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
// it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here.
if (value >= NumWaitersState_MaxValue)
throw new InvalidOperationException(String.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue));
UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask);
}
}
//-----------------------------------------------------------------------------------
// Constructs a new event, optionally specifying the initial state and spin count.
// The defaults are that the event is unsignaled and some reasonable default spin.
//
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with an initial state of nonsignaled.
/// </summary>
public ManualResetEventSlim()
: this(false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with a Boolen value indicating whether to set the intial state to signaled.
/// </summary>
/// <param name="initialState">true to set the initial state signaled; false to set the initial state
/// to nonsignaled.</param>
public ManualResetEventSlim(bool initialState)
{
// Specify the defualt spin count, and use default spin if we're
// on a multi-processor machine. Otherwise, we won't.
Initialize(initialState, DEFAULT_SPIN_MP);
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with a Boolen value indicating whether to set the intial state to signaled and a specified
/// spin count.
/// </summary>
/// <param name="initialState">true to set the initial state to signaled; false to set the initial state
/// to nonsignaled.</param>
/// <param name="spinCount">The number of spin waits that will occur before falling back to a true
/// wait.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="spinCount"/> is less than
/// 0 or greater than the maximum allowed value.</exception>
public ManualResetEventSlim(bool initialState, int spinCount)
{
if (spinCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(spinCount));
}
if (spinCount > SpinCountState_MaxValue)
{
throw new ArgumentOutOfRangeException(
nameof(spinCount),
String.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue));
}
// We will suppress default spin because the user specified a count.
Initialize(initialState, spinCount);
}
/// <summary>
/// Initializes the internal state of the event.
/// </summary>
/// <param name="initialState">Whether the event is set initially or not.</param>
/// <param name="spinCount">The spin count that decides when the event will block.</param>
private void Initialize(bool initialState, int spinCount)
{
m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0;
//the spinCount argument has been validated by the ctors.
//but we now sanity check our predefined constants.
Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount;
}
/// <summary>
/// Helper to ensure the lock object is created before first use.
/// </summary>
private void EnsureLockObjectCreated()
{
if (m_lock == null)
{
Lock newObj = new Lock();
Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign.. someone else won the race.
}
if (m_condition == null)
{
Condition newCond = new Condition(m_lock);
Interlocked.CompareExchange(ref m_condition, newCond, null);
}
}
/// <summary>
/// This method lazily initializes the event object. It uses CAS to guarantee that
/// many threads racing to call this at once don't result in more than one event
/// being stored and used. The event will be signaled or unsignaled depending on
/// the state of the thin-event itself, with synchronization taken into account.
/// </summary>
/// <returns>True if a new event was created and stored, false otherwise.</returns>
private bool LazyInitializeEvent()
{
bool preInitializeIsSet = IsSet;
ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet);
// We have to CAS this in case we are racing with another thread. We must
// guarantee only one event is actually stored in this field.
if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null)
{
// We raced with someone else and lost. Destroy the garbage event.
newEventObj.Dispose();
return false;
}
else
{
// Now that the event is published, verify that the state hasn't changed since
// we snapped the preInitializeState. Another thread could have done that
// between our initial observation above and here. The barrier incurred from
// the CAS above (in addition to m_state being volatile) prevents this read
// from moving earlier and being collapsed with our original one.
bool currentIsSet = IsSet;
if (currentIsSet != preInitializeIsSet)
{
Debug.Assert(currentIsSet,
"The only safe concurrent transition is from unset->set: detected set->unset.");
// We saw it as unsignaled, but it has since become set.
lock (newEventObj)
{
// If our event hasn't already been disposed of, we must set it.
if (m_eventObj == newEventObj)
{
newEventObj.Set();
}
}
}
return true;
}
}
/// <summary>
/// Sets the state of the event to signaled, which allows one or more threads waiting on the event to
/// proceed.
/// </summary>
public void Set()
{
Set(false);
}
/// <summary>
/// Private helper to actually perform the Set.
/// </summary>
/// <param name="duringCancellation">Indicates whether we are calling Set() during cancellation.</param>
/// <exception cref="T:System.OperationCanceledException">The object has been canceled.</exception>
private void Set(bool duringCancellation)
{
// We need to ensure that IsSet=true does not get reordered past the read of m_eventObj
// This would be a legal movement according to the .NET memory model.
// The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier.
IsSet = true;
// If there are waiting threads, we need to pulse them.
if (Waiters > 0)
{
Debug.Assert(m_lock != null && m_condition != null); //if waiters>0, then m_lock has already been created.
using (LockHolder.Hold(m_lock))
{
m_condition.SignalAll();
}
}
ManualResetEvent eventObj = m_eventObj;
//Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly
//It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic
if (eventObj != null && !duringCancellation)
{
// We must surround this call to Set in a lock. The reason is fairly subtle.
// Sometimes a thread will issue a Wait and wake up after we have set m_state,
// but before we have gotten around to setting m_eventObj (just below). That's
// because Wait first checks m_state and will only access the event if absolutely
// necessary. However, the coding pattern { event.Wait(); event.Dispose() } is
// quite common, and we must support it. If the waiter woke up and disposed of
// the event object before the setter has finished, however, we would try to set a
// now-disposed Win32 event. Crash! To deal with this race, we use a lock to
// protect access to the event object when setting and disposing of it. We also
// double-check that the event has not become null in the meantime when in the lock.
lock (eventObj)
{
if (m_eventObj != null)
{
// If somebody is waiting, we must set the event.
m_eventObj.Set();
}
}
}
#if DEBUG
m_lastSetTime = Environment.TickCount;
#endif
}
/// <summary>
/// Sets the state of the event to nonsignaled, which causes threads to block.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Reset()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Reset()
{
ThrowIfDisposed();
// If there's an event, reset it.
if (m_eventObj != null)
{
m_eventObj.Reset();
}
// There is a race here. If another thread Sets the event, we will get into a state
// where m_state will be unsignaled, yet the Win32 event object will have been signaled.
// This could cause waiting threads to wake up even though the event is in an
// unsignaled state. This is fine -- those that are calling Reset concurrently are
// responsible for doing "the right thing" -- e.g. rechecking the condition and
// resetting the event manually.
// And finally set our state back to unsignaled.
IsSet = false;
#if DEBUG
m_lastResetTime = DateTime.Now.Ticks;
#endif
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
public void Wait()
{
Wait(Timeout.Infinite, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> receives a signal,
/// while observing a <see cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <exception cref="T:System.OperationCanceledExcepton"><paramref name="cancellationToken"/> was
/// canceled.</exception>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
public void Wait(CancellationToken cancellationToken)
{
Wait(Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.Threading.OperationCanceledException"><paramref
/// name="cancellationToken"/> was canceled.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(TimeSpan timeout, CancellationToken cancellationToken)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// 32-bit signed integer to measure the time interval.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(int millisecondsTimeout)
{
return Wait(millisecondsTimeout, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// 32-bit signed integer to measure the time interval, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <exception cref="T:System.Threading.OperationCanceledException"><paramref
/// name="cancellationToken"/> was canceled.</exception>
public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
{
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested(); // an early convenience check
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
}
if (!IsSet)
{
if (millisecondsTimeout == 0)
{
// For 0-timeouts, we just return immediately.
return false;
}
// We spin briefly before falling back to allocating and/or waiting on a true event.
uint startTime = 0;
bool bNeedTimeoutAdjustment = false;
int realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary.
if (millisecondsTimeout != Timeout.Infinite)
{
// We will account for time spent spinning, so that we can decrement it from our
// timeout. In most cases the time spent in this section will be negligible. But
// we can't discount the possibility of our thread being switched out for a lengthy
// period of time. The timeout adjustments only take effect when and if we actually
// decide to block in the kernel below.
startTime = TimeoutHelper.GetTime();
bNeedTimeoutAdjustment = true;
}
//spin
int HOW_MANY_SPIN_BEFORE_YIELD = 10;
int HOW_MANY_YIELD_EVERY_SLEEP_0 = 5;
int HOW_MANY_YIELD_EVERY_SLEEP_1 = 20;
int spinCount = SpinCount;
for (int i = 0; i < spinCount; i++)
{
if (IsSet)
{
return true;
}
else if (i < HOW_MANY_SPIN_BEFORE_YIELD)
{
if (i == HOW_MANY_SPIN_BEFORE_YIELD / 2)
{
RuntimeThread.Yield();
}
else
{
RuntimeThread.SpinWait(PlatformHelper.ProcessorCount * (4 << i));
}
}
else if (i % HOW_MANY_YIELD_EVERY_SLEEP_1 == 0)
{
RuntimeThread.Sleep(1);
}
else if (i % HOW_MANY_YIELD_EVERY_SLEEP_0 == 0)
{
RuntimeThread.Sleep(0);
}
else
{
RuntimeThread.Yield();
}
if (i >= 100 && i % 10 == 0) // check the cancellation token if the user passed a very large spin count
cancellationToken.ThrowIfCancellationRequested();
}
// Now enter the lock and wait.
EnsureLockObjectCreated();
// We must register and deregister the token outside of the lock, to avoid deadlocks.
using (cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCallback, this))
{
using (LockHolder.Hold(m_lock))
{
// Loop to cope with spurious wakeups from other waits being canceled
while (!IsSet)
{
// If our token was canceled, we must throw and exit.
cancellationToken.ThrowIfCancellationRequested();
//update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled)
if (bNeedTimeoutAdjustment)
{
realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout);
if (realMillisecondsTimeout <= 0)
return false;
}
// There is a race that Set will fail to see that there are waiters as Set does not take the lock,
// so after updating waiters, we must check IsSet again.
// Also, we must ensure there cannot be any reordering of the assignment to Waiters and the
// read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange
// operation which provides a full memory barrier.
// If we see IsSet=false, then we are guaranteed that Set() will see that we are
// waiting and will pulse the monitor correctly.
Waiters = Waiters + 1;
if (IsSet) //This check must occur after updating Waiters.
{
Waiters--; //revert the increment.
return true;
}
// Now finally perform the wait.
try
{
// ** the actual wait **
if (!m_condition.Wait(realMillisecondsTimeout))
return false; //return immediately if the timeout has expired.
}
finally
{
// Clean up: we're done waiting.
Waiters = Waiters - 1;
}
// Now just loop back around, and the right thing will happen. Either:
// 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait)
// or 2. the wait was successful. (the loop will break)
}
}
}
} // automatically disposes (and deregisters) the callback
return true; //done. The wait was satisfied.
}
/// <summary>
/// Releases all resources used by the current instance of <see cref="ManualResetEventSlim"/>.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// When overridden in a derived class, releases the unmanaged resources used by the
/// <see cref="ManualResetEventSlim"/>, and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources;
/// false to release only unmanaged resources.</param>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose(Boolean)"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
if ((m_combinedState & Dispose_BitMask) != 0)
return; // already disposed
m_combinedState |= Dispose_BitMask; //set the dispose bit
if (disposing)
{
// We will dispose of the event object. We do this under a lock to protect
// against the race condition outlined in the Set method above.
ManualResetEvent eventObj = m_eventObj;
if (eventObj != null)
{
lock (eventObj)
{
eventObj.Dispose();
m_eventObj = null;
}
}
}
}
/// <summary>
/// Throw ObjectDisposedException if the MRES is disposed
/// </summary>
private void ThrowIfDisposed()
{
if ((m_combinedState & Dispose_BitMask) != 0)
throw new ObjectDisposedException(SR.ManualResetEventSlim_Disposed);
}
/// <summary>
/// Private helper method to wake up waiters when a cancellationToken gets canceled.
/// </summary>
private static Action<object> s_cancellationTokenCallback = new Action<object>(CancellationTokenCallback);
private static void CancellationTokenCallback(object obj)
{
ManualResetEventSlim mre = obj as ManualResetEventSlim;
Debug.Assert(mre != null, "Expected a ManualResetEventSlim");
Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use.
using (LockHolder.Hold(mre.m_lock))
{
mre.m_condition.SignalAll(); // awaken all waiters
}
}
/// <summary>
/// Private helper method for updating parts of a bit-string state value.
/// Mainly called from the IsSet and Waiters properties setters
/// </summary>
/// <remarks>
/// Note: the parameter types must be int as CompareExchange cannot take a Uint
/// </remarks>
/// <param name="newBits">The new value</param>
/// <param name="updateBitsMask">The mask used to set the bits</param>
private void UpdateStateAtomically(int newBits, int updateBitsMask)
{
SpinWait sw = new SpinWait();
Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask.");
do
{
int oldState = m_combinedState; // cache the old value for testing in CAS
// Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111]
// then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111]
int newState = (oldState & ~updateBitsMask) | newBits;
if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState)
{
return;
}
sw.SpinOnce();
} while (true);
}
/// <summary>
/// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word.
/// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer
///
/// ?? is there a common place to put this rather than being private to MRES?
/// </summary>
/// <param name="state"></param>
/// <param name="mask"></param>
/// <param name="rightBitShiftCount"></param>
/// <returns></returns>
private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount)
{
//convert to uint before shifting so that right-shift does not replicate the sign-bit,
//then convert back to int.
return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount));
}
/// <summary>
/// Performs a Mask operation, but does not perform the shift.
/// This is acceptable for boolean values for which the shift is unnecessary
/// eg (val & Mask) != 0 is an appropriate way to extract a boolean rather than using
/// ((val & Mask) >> shiftAmount) == 1
///
/// ?? is there a common place to put this rather than being private to MRES?
/// </summary>
/// <param name="state"></param>
/// <param name="mask"></param>
private static int ExtractStatePortion(int state, int mask)
{
return state & mask;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
namespace Roslyn.Test.Utilities
{
public class VisualStudioSendKeys
{
/// <summary>
/// Send keys synchronously to visual studio.
/// </summary>
/// <param name="hwnd">The window handle of vs's main window</param>
/// <param name="timeout">How long to wait for the keys to be processed by Visual Studio.</param>
/// <param name="escapedKeys">Only works with Visual Studio. Expects correctly escaped sequences as taken by System.Windows.Forms.SendKeys.</param>
public static void SendWait(IntPtr hwnd, int timeout, string escapedKeys)
{
System.Windows.Forms.SendKeys.SendWait(escapedKeys);
WaitForSendkeys(timeout, hwnd);
}
/// <summary>
/// Splits a piece of code into escaped blocks suitable for use with SendWait.
/// </summary>
/// <param name="code">A piece of code to be broken and escaped.</param>
/// <returns></returns>
public static IEnumerable<string> BreakAndEscape(string code)
{
const int MaxChars = 500;
var returnList = new List<string>();
var lines = code.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
// In the unlikely case where the parsing might reduce the size of the original string (not currently possible, but who knows what the future might bring)
// Padding the count to ensure that we start by adding a new element to the list if any line exists.
var count = 2 * MaxChars;
foreach (var line in lines)
{
var newLine = new System.Text.StringBuilder();
foreach (string charOrEscapeSequence in ParseLineIntoEscapedChars(line))
{
newLine.Append(charOrEscapeSequence);
}
if (count + newLine.Length < MaxChars)
{
// We're still part of the current block, so update the current element to include
// this line.
returnList[returnList.Count - 1] = returnList[returnList.Count - 1] + newLine;
count += newLine.Length;
}
else
{
// This would put us over the block size, so make this line start a new block.
returnList.Add(newLine.ToString());
count = newLine.Length;
}
}
// Signature help sometimes comes up at random times and eats the up/down keys, so add
// an escape in first.
return returnList.Select(s => s.Replace("{UP}", "{ESC}{UP}").Replace("{DOWN}", "{ESC}{DOWN}")).ToList();
}
private const int WM_USER = 0x400;
// The following constants and functions wait for VS to signal that input processing is complete.
// See src\env\msenv\core\propbar.cpp FnwpPropBar(): Case WM_TIMER on how this works.
// These turn __SendKeys into a blocking call.
private const string INPUT_PROCESSED_EVENT = "VSInputProcessed";
private const int INPUT_PROCESSED_MSG = WM_USER + 0xC92;
[DllImport("user32", CharSet = CharSet.Unicode)]
private static extern int SendNotifyMessageW(IntPtr HWnd, int msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32")]
public static extern int SetForegroundWindow(IntPtr hWnd);
private static WaitHandle s_inputProcessedEvent;
private static WaitHandle InputProcessedEvent
{
get
{
return s_inputProcessedEvent ?? (s_inputProcessedEvent = new EventWaitHandle(initialState: false, mode: EventResetMode.AutoReset, name: INPUT_PROCESSED_EVENT));
}
}
public static void WaitForSendkeys(int timeout, IntPtr hwnd)
{
// Note: Ensure the event is created before sending the INPUT_PROCESSED_MSG
WaitHandle waitObject = InputProcessedEvent;
IntPtr apphandle = hwnd;
// The lParam indicates how long VS waits some before responding to the message.
// If zero, the default delay is 500ms, which is quite long for typing scenarios.
// Usually, we want the response to be as fast as possible so that the test case
// isn't waiting unnecessarily if VS is ready. We can't use 0, so specify 1 instead.
// Note that this will probably be rounded up to USER_TIMER_MINIMUM (10ms) by the
// eventual call to SetTimer inside VS. If that happens to be longer than 'timeout'
// then we're almost certainly going to fail.
IntPtr pingDelay = new IntPtr(1);
int notified = SendNotifyMessageW(apphandle, INPUT_PROCESSED_MSG, IntPtr.Zero, lParam: pingDelay);
if (notified == 0)
{
throw new Exception("Couldn't notify the Editor that we are waiting for input processing message");
}
try
{
waitObject.WaitOne(timeout);
}
catch (TimeoutException)
{
throw new Exception("Timed out waiting for notification that SendKeys has been processed by client");
}
}
private static IEnumerable<string> ParseLineIntoEscapedChars(string line)
{
line = line.TrimStart(new[] { ' ', '\t' });
for (var i = 0; i < line.Length; i++)
{
// Skip SendKeys commands included in source.
var count = SkipCommands(line, i);
for (int j = 0; j < count; j++)
{
yield return string.Empty + line[i++];
}
if (i < line.Length)
{
var key = line[i];
yield return ParseKey(key);
}
}
yield return "{ENTER}";
}
private static int SkipCommands(string line, int start)
{
var normalLine = line.ToLowerInvariant();
var commands = new List<string>();
commands.Add("^{end}");
commands.Add("{end}");
commands.Add("{enter}");
commands.Add("^{home}");
commands.Add("{home}");
commands.Add("{up}");
commands.Add("{down}");
commands.Add("{left}");
commands.Add("{right}");
commands.Add("{esc}");
int skipLength = 0;
bool found = true;
while (found)
{
found = false;
foreach (var command in commands)
{
if (start + skipLength < normalLine.Length &&
start + skipLength + command.Length <= normalLine.Length &&
normalLine.Substring(start + skipLength, command.Length).Equals(command))
{
skipLength += command.Length;
found = true;
}
}
}
return skipLength;
}
private static string ParseKey(char key)
{
string outputString = key.ToString();
// Replace Special Characters that need to be escaped
outputString = Regex.Replace(outputString, "(?<specialChar>[" + Regex.Escape("+^%~(){}") + "])", "{${specialChar}}");
// Replace \n with Enter
outputString = Regex.Replace(outputString, "\n", "{ENTER}");
// Replace \t with Tab
outputString = Regex.Replace(outputString, "\t", "{TAB}");
return outputString;
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Layout;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Controls.UnitTests.Presenters
{
public class ItemsPresenterTests_Virtualization
{
[Fact]
public void Should_Not_Create_Items_Before_Added_To_Visual_Tree()
{
var items = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToList();
var target = new TestItemsPresenter(true)
{
Items = items,
ItemsPanel = VirtualizingPanelTemplate(Orientation.Vertical),
ItemTemplate = ItemTemplate(),
VirtualizationMode = ItemVirtualizationMode.Simple,
};
var scroller = new ScrollContentPresenter
{
Content = target,
};
scroller.UpdateChild();
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
Assert.Empty(target.Panel.Children);
var root = new TestRoot
{
Child = scroller,
};
target.InvalidateMeasure();
target.Panel.InvalidateMeasure();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(10, target.Panel.Children.Count);
}
[Fact]
public void Should_Return_IsLogicalScrollEnabled_False_When_Has_No_Virtualizing_Panel()
{
var target = CreateTarget();
target.ClearValue(ItemsPresenter.ItemsPanelProperty);
target.ApplyTemplate();
Assert.False(((ILogicalScrollable)target).IsLogicalScrollEnabled);
}
[Fact]
public void Should_Return_IsLogicalScrollEnabled_False_When_VirtualizationMode_None()
{
var target = CreateTarget(ItemVirtualizationMode.None);
target.ApplyTemplate();
Assert.False(((ILogicalScrollable)target).IsLogicalScrollEnabled);
}
[Fact]
public void Should_Return_IsLogicalScrollEnabled_False_When_Doesnt_Have_ScrollPresenter_Parent()
{
var target = new ItemsPresenter
{
ItemsPanel = VirtualizingPanelTemplate(),
ItemTemplate = ItemTemplate(),
VirtualizationMode = ItemVirtualizationMode.Simple,
};
target.ApplyTemplate();
Assert.False(((ILogicalScrollable)target).IsLogicalScrollEnabled);
}
[Fact]
public void Should_Return_IsLogicalScrollEnabled_True()
{
var target = CreateTarget();
target.ApplyTemplate();
Assert.True(((ILogicalScrollable)target).IsLogicalScrollEnabled);
}
[Fact]
public void Parent_ScrollContentPresenter_Properties_Should_Be_Set()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
var scroll = (ScrollContentPresenter)target.Parent;
Assert.Equal(new Size(10, 20), scroll.Extent);
Assert.Equal(new Size(100, 10), scroll.Viewport);
}
[Fact]
public void Should_Fill_Panel_With_Containers()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(new Size(100, 100));
Assert.Equal(10, target.Panel.Children.Count);
target.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(10, target.Panel.Children.Count);
}
[Fact]
public void Should_Only_Create_Enough_Containers_To_Display_All_Items()
{
var target = CreateTarget(itemCount: 2);
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(2, target.Panel.Children.Count);
}
[Fact]
public void Should_Expand_To_Fit_Containers_When_Flexible_Size()
{
var target = CreateTarget();
target.ApplyTemplate();
target.Measure(Size.Infinity);
target.Arrange(new Rect(target.DesiredSize));
Assert.Equal(new Size(10, 200), target.DesiredSize);
Assert.Equal(new Size(10, 200), target.Bounds.Size);
Assert.Equal(20, target.Panel.Children.Count);
}
[Fact]
public void Initial_Item_DataContexts_Should_Be_Correct()
{
var target = CreateTarget();
var items = (IList<string>)target.Items;
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
for (var i = 0; i < target.Panel.Children.Count; ++i)
{
Assert.Equal(items[i], target.Panel.Children[i].DataContext);
}
}
[Fact]
public void Should_Add_New_Items_When_Control_Is_Enlarged()
{
var target = CreateTarget();
var items = (IList<string>)target.Items;
target.ApplyTemplate();
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(10, target.Panel.Children.Count);
target.Measure(new Size(120, 120));
target.Arrange(new Rect(0, 0, 100, 120));
Assert.Equal(12, target.Panel.Children.Count);
for (var i = 0; i < target.Panel.Children.Count; ++i)
{
Assert.Equal(items[i], target.Panel.Children[i].DataContext);
}
}
[Fact]
public void Changing_VirtualizationMode_None_To_Simple_Should_Update_Control()
{
var target = CreateTarget(mode: ItemVirtualizationMode.None);
var scroll = (ScrollContentPresenter)target.Parent;
scroll.Measure(new Size(100, 100));
scroll.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(20, target.Panel.Children.Count);
Assert.Equal(new Size(10, 200), scroll.Extent);
Assert.Equal(new Size(100, 100), scroll.Viewport);
target.VirtualizationMode = ItemVirtualizationMode.Simple;
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(10, target.Panel.Children.Count);
Assert.Equal(new Size(10, 20), scroll.Extent);
Assert.Equal(new Size(100, 10), scroll.Viewport);
}
[Fact]
public void Changing_VirtualizationMode_None_To_Simple_Should_Add_Correct_Number_Of_Controls()
{
using (UnitTestApplication.Start(TestServices.RealLayoutManager))
{
var target = CreateTarget(mode: ItemVirtualizationMode.None);
var scroll = (ScrollContentPresenter)target.Parent;
scroll.Measure(new Size(100, 100));
scroll.Arrange(new Rect(0, 0, 100, 100));
// Ensure than an intermediate measure pass doesn't add more controls than it
// should. This can happen if target gets measured with Size.Infinity which
// is what the available size should be when VirtualizationMode == None but not
// what it should after VirtualizationMode is changed to Simple.
target.Panel.Children.CollectionChanged += (s, e) =>
{
Assert.InRange(target.Panel.Children.Count, 0, 10);
};
target.VirtualizationMode = ItemVirtualizationMode.Simple;
LayoutManager.Instance.ExecuteLayoutPass();
Assert.Equal(10, target.Panel.Children.Count);
}
}
[Fact]
public void Changing_VirtualizationMode_Simple_To_None_Should_Update_Control()
{
var target = CreateTarget();
var scroll = (ScrollContentPresenter)target.Parent;
scroll.Measure(new Size(100, 100));
scroll.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(10, target.Panel.Children.Count);
Assert.Equal(new Size(10, 20), scroll.Extent);
Assert.Equal(new Size(100, 10), scroll.Viewport);
target.VirtualizationMode = ItemVirtualizationMode.None;
target.Measure(new Size(100, 100));
target.Arrange(new Rect(0, 0, 100, 100));
// Here - unlike changing the other way - we need to do a layout pass on the scroll
// content presenter as non-logical scroll values are only updated on arrange.
scroll.Measure(new Size(100, 100));
scroll.Arrange(new Rect(0, 0, 100, 100));
Assert.Equal(20, target.Panel.Children.Count);
Assert.Equal(new Size(10, 200), scroll.Extent);
Assert.Equal(new Size(100, 100), scroll.Viewport);
}
private static ItemsPresenter CreateTarget(
ItemVirtualizationMode mode = ItemVirtualizationMode.Simple,
Orientation orientation = Orientation.Vertical,
bool useContainers = true,
int itemCount = 20)
{
ItemsPresenter result;
var items = Enumerable.Range(0, itemCount).Select(x => $"Item {x}").ToList();
var scroller = new TestScroller
{
Content = result = new TestItemsPresenter(useContainers)
{
Items = items,
ItemsPanel = VirtualizingPanelTemplate(orientation),
ItemTemplate = ItemTemplate(),
VirtualizationMode = mode,
}
};
scroller.UpdateChild();
return result;
}
private static IDataTemplate ItemTemplate()
{
return new FuncDataTemplate<string>(x => new Canvas
{
Width = 10,
Height = 10,
});
}
private static ITemplate<IPanel> VirtualizingPanelTemplate(
Orientation orientation = Orientation.Vertical)
{
return new FuncTemplate<IPanel>(() => new VirtualizingStackPanel
{
Orientation = orientation,
});
}
private class TestScroller : ScrollContentPresenter, IRenderRoot
{
public IRenderer Renderer { get; }
public Size ClientSize { get; }
public double RenderScaling => 1;
public IRenderTarget CreateRenderTarget()
{
throw new NotImplementedException();
}
public void Invalidate(Rect rect)
{
throw new NotImplementedException();
}
public Point PointToClient(Point point)
{
throw new NotImplementedException();
}
public Point PointToScreen(Point point)
{
throw new NotImplementedException();
}
}
private class TestItemsPresenter : ItemsPresenter
{
private bool _useContainers;
public TestItemsPresenter(bool useContainers)
{
_useContainers = useContainers;
}
protected override IItemContainerGenerator CreateItemContainerGenerator()
{
return _useContainers ?
new ItemContainerGenerator<TestContainer>(this, TestContainer.ContentProperty, null) :
new ItemContainerGenerator(this);
}
}
private class TestContainer : ContentControl
{
public TestContainer()
{
Width = 10;
Height = 10;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.ObjectPool;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.ResponseCaching.Tests
{
internal class TestUtils
{
static TestUtils()
{
// Force sharding in tests
StreamUtilities.BodySegmentSize = 10;
}
private static bool TestRequestDelegate(HttpContext context, string guid)
{
var headers = context.Response.GetTypedHeaders();
var expires = context.Request.Query["Expires"];
if (!string.IsNullOrEmpty(expires))
{
headers.Expires = DateTimeOffset.Now.AddSeconds(int.Parse(expires, CultureInfo.InvariantCulture));
}
if (headers.CacheControl == null)
{
headers.CacheControl = new CacheControlHeaderValue
{
Public = true,
MaxAge = string.IsNullOrEmpty(expires) ? TimeSpan.FromSeconds(10) : (TimeSpan?)null
};
}
else
{
headers.CacheControl.Public = true;
headers.CacheControl.MaxAge = string.IsNullOrEmpty(expires) ? TimeSpan.FromSeconds(10) : (TimeSpan?)null;
}
headers.Date = DateTimeOffset.UtcNow;
headers.Headers["X-Value"] = guid;
var contentLength = context.Request.Query["ContentLength"];
if (!string.IsNullOrEmpty(contentLength))
{
headers.ContentLength = long.Parse(contentLength, CultureInfo.InvariantCulture);
}
if (context.Request.Method != "HEAD")
{
return true;
}
return false;
}
internal static async Task TestRequestDelegateWriteAsync(HttpContext context)
{
var uniqueId = Guid.NewGuid().ToString();
if (TestRequestDelegate(context, uniqueId))
{
await context.Response.WriteAsync(uniqueId);
}
}
internal static async Task TestRequestDelegateSendFileAsync(HttpContext context)
{
var path = Path.Combine(AppContext.BaseDirectory, "TestDocument.txt");
var uniqueId = Guid.NewGuid().ToString();
if (TestRequestDelegate(context, uniqueId))
{
await context.Response.SendFileAsync(path, 0, null);
await context.Response.WriteAsync(uniqueId);
}
}
internal static Task TestRequestDelegateWrite(HttpContext context)
{
var uniqueId = Guid.NewGuid().ToString();
if (TestRequestDelegate(context, uniqueId))
{
var feature = context.Features.Get<IHttpBodyControlFeature>();
if (feature != null)
{
feature.AllowSynchronousIO = true;
}
context.Response.Write(uniqueId);
}
return Task.CompletedTask;
}
internal static IResponseCachingKeyProvider CreateTestKeyProvider()
{
return CreateTestKeyProvider(new ResponseCachingOptions());
}
internal static IResponseCachingKeyProvider CreateTestKeyProvider(ResponseCachingOptions options)
{
return new ResponseCachingKeyProvider(new DefaultObjectPoolProvider(), Options.Create(options));
}
internal static IEnumerable<IHostBuilder> CreateBuildersWithResponseCaching(
Action<IApplicationBuilder> configureDelegate = null,
ResponseCachingOptions options = null,
Action<HttpContext> contextAction = null)
{
return CreateBuildersWithResponseCaching(configureDelegate, options, new RequestDelegate[]
{
context =>
{
contextAction?.Invoke(context);
return TestRequestDelegateWrite(context);
},
context =>
{
contextAction?.Invoke(context);
return TestRequestDelegateWriteAsync(context);
},
context =>
{
contextAction?.Invoke(context);
return TestRequestDelegateSendFileAsync(context);
},
});
}
private static IEnumerable<IHostBuilder> CreateBuildersWithResponseCaching(
Action<IApplicationBuilder> configureDelegate = null,
ResponseCachingOptions options = null,
IEnumerable<RequestDelegate> requestDelegates = null)
{
if (configureDelegate == null)
{
configureDelegate = app => { };
}
if (requestDelegates == null)
{
requestDelegates = new RequestDelegate[]
{
TestRequestDelegateWriteAsync,
TestRequestDelegateWrite
};
}
foreach (var requestDelegate in requestDelegates)
{
// Test with in memory ResponseCache
yield return new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddResponseCaching(responseCachingOptions =>
{
if (options != null)
{
responseCachingOptions.MaximumBodySize = options.MaximumBodySize;
responseCachingOptions.UseCaseSensitivePaths = options.UseCaseSensitivePaths;
responseCachingOptions.SystemClock = options.SystemClock;
}
});
})
.Configure(app =>
{
configureDelegate(app);
app.UseResponseCaching();
app.Run(requestDelegate);
});
});
}
}
internal static ResponseCachingMiddleware CreateTestMiddleware(
RequestDelegate next = null,
IResponseCache cache = null,
ResponseCachingOptions options = null,
TestSink testSink = null,
IResponseCachingKeyProvider keyProvider = null,
IResponseCachingPolicyProvider policyProvider = null)
{
if (next == null)
{
next = httpContext => Task.CompletedTask;
}
if (cache == null)
{
cache = new TestResponseCache();
}
if (options == null)
{
options = new ResponseCachingOptions();
}
if (keyProvider == null)
{
keyProvider = new ResponseCachingKeyProvider(new DefaultObjectPoolProvider(), Options.Create(options));
}
if (policyProvider == null)
{
policyProvider = new TestResponseCachingPolicyProvider();
}
return new ResponseCachingMiddleware(
next,
Options.Create(options),
testSink == null ? (ILoggerFactory)NullLoggerFactory.Instance : new TestLoggerFactory(testSink, true),
policyProvider,
cache,
keyProvider);
}
internal static ResponseCachingContext CreateTestContext()
{
return new ResponseCachingContext(new DefaultHttpContext(), NullLogger.Instance)
{
ResponseTime = DateTimeOffset.UtcNow
};
}
internal static ResponseCachingContext CreateTestContext(ITestSink testSink)
{
return new ResponseCachingContext(new DefaultHttpContext(), new TestLogger("ResponseCachingTests", testSink, true))
{
ResponseTime = DateTimeOffset.UtcNow
};
}
internal static void AssertLoggedMessages(IEnumerable<WriteContext> messages, params LoggedMessage[] expectedMessages)
{
var messageList = messages.ToList();
Assert.Equal(messageList.Count, expectedMessages.Length);
for (var i = 0; i < messageList.Count; i++)
{
Assert.Equal(expectedMessages[i].EventId, messageList[i].EventId);
Assert.Equal(expectedMessages[i].LogLevel, messageList[i].LogLevel);
}
}
public static HttpRequestMessage CreateRequest(string method, string requestUri)
{
return new HttpRequestMessage(new HttpMethod(method), requestUri);
}
}
internal static class HttpResponseWritingExtensions
{
internal static void Write(this HttpResponse response, string text)
{
if (response == null)
{
throw new ArgumentNullException(nameof(response));
}
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
byte[] data = Encoding.UTF8.GetBytes(text);
response.Body.Write(data, 0, data.Length);
}
}
internal class LoggedMessage
{
internal static LoggedMessage RequestMethodNotCacheable => new LoggedMessage(1, LogLevel.Debug);
internal static LoggedMessage RequestWithAuthorizationNotCacheable => new LoggedMessage(2, LogLevel.Debug);
internal static LoggedMessage RequestWithNoCacheNotCacheable => new LoggedMessage(3, LogLevel.Debug);
internal static LoggedMessage RequestWithPragmaNoCacheNotCacheable => new LoggedMessage(4, LogLevel.Debug);
internal static LoggedMessage ExpirationMinFreshAdded => new LoggedMessage(5, LogLevel.Debug);
internal static LoggedMessage ExpirationSharedMaxAgeExceeded => new LoggedMessage(6, LogLevel.Debug);
internal static LoggedMessage ExpirationMustRevalidate => new LoggedMessage(7, LogLevel.Debug);
internal static LoggedMessage ExpirationMaxStaleSatisfied => new LoggedMessage(8, LogLevel.Debug);
internal static LoggedMessage ExpirationMaxAgeExceeded => new LoggedMessage(9, LogLevel.Debug);
internal static LoggedMessage ExpirationExpiresExceeded => new LoggedMessage(10, LogLevel.Debug);
internal static LoggedMessage ResponseWithoutPublicNotCacheable => new LoggedMessage(11, LogLevel.Debug);
internal static LoggedMessage ResponseWithNoStoreNotCacheable => new LoggedMessage(12, LogLevel.Debug);
internal static LoggedMessage ResponseWithNoCacheNotCacheable => new LoggedMessage(13, LogLevel.Debug);
internal static LoggedMessage ResponseWithSetCookieNotCacheable => new LoggedMessage(14, LogLevel.Debug);
internal static LoggedMessage ResponseWithVaryStarNotCacheable => new LoggedMessage(15, LogLevel.Debug);
internal static LoggedMessage ResponseWithPrivateNotCacheable => new LoggedMessage(16, LogLevel.Debug);
internal static LoggedMessage ResponseWithUnsuccessfulStatusCodeNotCacheable => new LoggedMessage(17, LogLevel.Debug);
internal static LoggedMessage NotModifiedIfNoneMatchStar => new LoggedMessage(18, LogLevel.Debug);
internal static LoggedMessage NotModifiedIfNoneMatchMatched => new LoggedMessage(19, LogLevel.Debug);
internal static LoggedMessage NotModifiedIfModifiedSinceSatisfied => new LoggedMessage(20, LogLevel.Debug);
internal static LoggedMessage NotModifiedServed => new LoggedMessage(21, LogLevel.Information);
internal static LoggedMessage CachedResponseServed => new LoggedMessage(22, LogLevel.Information);
internal static LoggedMessage GatewayTimeoutServed => new LoggedMessage(23, LogLevel.Information);
internal static LoggedMessage NoResponseServed => new LoggedMessage(24, LogLevel.Information);
internal static LoggedMessage VaryByRulesUpdated => new LoggedMessage(25, LogLevel.Debug);
internal static LoggedMessage ResponseCached => new LoggedMessage(26, LogLevel.Information);
internal static LoggedMessage ResponseNotCached => new LoggedMessage(27, LogLevel.Information);
internal static LoggedMessage ResponseContentLengthMismatchNotCached => new LoggedMessage(28, LogLevel.Warning);
internal static LoggedMessage ExpirationInfiniteMaxStaleSatisfied => new LoggedMessage(29, LogLevel.Debug);
private LoggedMessage(int evenId, LogLevel logLevel)
{
EventId = evenId;
LogLevel = logLevel;
}
internal int EventId { get; }
internal LogLevel LogLevel { get; }
}
internal class TestResponseCachingPolicyProvider : IResponseCachingPolicyProvider
{
public bool AllowCacheLookupValue { get; set; } = false;
public bool AllowCacheStorageValue { get; set; } = false;
public bool AttemptResponseCachingValue { get; set; } = false;
public bool IsCachedEntryFreshValue { get; set; } = true;
public bool IsResponseCacheableValue { get; set; } = true;
public bool AllowCacheLookup(ResponseCachingContext context) => AllowCacheLookupValue;
public bool AllowCacheStorage(ResponseCachingContext context) => AllowCacheStorageValue;
public bool AttemptResponseCaching(ResponseCachingContext context) => AttemptResponseCachingValue;
public bool IsCachedEntryFresh(ResponseCachingContext context) => IsCachedEntryFreshValue;
public bool IsResponseCacheable(ResponseCachingContext context) => IsResponseCacheableValue;
}
internal class TestResponseCachingKeyProvider : IResponseCachingKeyProvider
{
private readonly string _baseKey;
private readonly StringValues _varyKey;
public TestResponseCachingKeyProvider(string lookupBaseKey = null, StringValues? lookupVaryKey = null)
{
_baseKey = lookupBaseKey;
if (lookupVaryKey.HasValue)
{
_varyKey = lookupVaryKey.Value;
}
}
public IEnumerable<string> CreateLookupVaryByKeys(ResponseCachingContext context)
{
foreach (var varyKey in _varyKey)
{
yield return _baseKey + varyKey;
}
}
public string CreateBaseKey(ResponseCachingContext context)
{
return _baseKey;
}
public string CreateStorageVaryByKey(ResponseCachingContext context)
{
throw new NotImplementedException();
}
}
internal class TestResponseCache : IResponseCache
{
private readonly IDictionary<string, IResponseCacheEntry> _storage = new Dictionary<string, IResponseCacheEntry>();
public int GetCount { get; private set; }
public int SetCount { get; private set; }
public IResponseCacheEntry Get(string key)
{
GetCount++;
try
{
return _storage[key];
}
catch
{
return null;
}
}
public void Set(string key, IResponseCacheEntry entry, TimeSpan validFor)
{
SetCount++;
_storage[key] = entry;
}
}
internal class TestClock : ISystemClock
{
public DateTimeOffset UtcNow { get; set; }
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleETrade.SampleETradePublic
File: MainWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleETrade
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Windows;
using Ecng.Common;
using Ecng.Xaml;
using MoreLinq;
using StockSharp.Messages;
using StockSharp.BusinessEntities;
using StockSharp.ETrade;
using StockSharp.ETrade.Native;
using StockSharp.Logging;
using StockSharp.Xaml;
using StockSharp.Localization;
public partial class MainWindow
{
public static MainWindow Instance { get; private set; }
public static readonly DependencyProperty IsConnectedProperty = DependencyProperty.Register("IsConnected", typeof(bool), typeof(MainWindow), new PropertyMetadata(default(bool)));
public bool IsConnected
{
get { return (bool)GetValue(IsConnectedProperty); }
set { SetValue(IsConnectedProperty, value); }
}
public ETradeTrader Trader { get; private set; }
private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow();
private readonly OrdersWindow _ordersWindow = new OrdersWindow();
private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow();
private readonly StopOrdersWindow _stopOrdersWindow = new StopOrdersWindow();
private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow();
//private Security[] _securities;
private static string ConsumerKey
{
get { return Properties.Settings.Default.ConsumerKey; }
}
private static bool IsSandbox
{
get { return Properties.Settings.Default.Sandbox; }
}
private readonly LogManager _logManager = new LogManager();
public MainWindow()
{
Instance = this;
InitializeComponent();
Title = Title.Put("E*TRADE");
Closing += OnClosing;
_ordersWindow.MakeHideable();
_securitiesWindow.MakeHideable();
_stopOrdersWindow.MakeHideable();
_portfoliosWindow.MakeHideable();
_myTradesWindow.MakeHideable();
var guilistener = new GuiLogListener(_logControl);
guilistener.Filters.Add(msg => msg.Level > LogLevels.Debug);
_logManager.Listeners.Add(guilistener);
var location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var path = Path.Combine(location ?? "", "ETrade", "restdump_{0:yyyyMMdd-HHmmss}.log".Put(DateTime.Now));
_logManager.Listeners.Add(new FileLogListener(path));
Application.Current.MainWindow = this;
}
private void OnClosing(object sender, CancelEventArgs cancelEventArgs)
{
Properties.Settings.Default.Save();
_ordersWindow.DeleteHideable();
_securitiesWindow.DeleteHideable();
_stopOrdersWindow.DeleteHideable();
_portfoliosWindow.DeleteHideable();
_myTradesWindow.DeleteHideable();
_securitiesWindow.Close();
_stopOrdersWindow.Close();
_ordersWindow.Close();
_portfoliosWindow.Close();
_myTradesWindow.Close();
if (Trader != null)
Trader.Dispose();
}
private void ConnectClick(object sender, RoutedEventArgs e)
{
var secret = PwdBox.Password;
if (!IsConnected)
{
if (ConsumerKey.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str3689);
return;
}
if (secret.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str3690);
return;
}
if (Trader == null)
{
// create connector
Trader = new ETradeTrader();
try
{
Trader.AccessToken = null;
var token = OAuthToken.Deserialize(Properties.Settings.Default.AccessToken);
if (token != null && token.ConsumerKey.ToLowerInvariant() == ConsumerKey.ToLowerInvariant())
Trader.AccessToken = token;
}
catch (Exception ex)
{
MessageBox.Show(this, LocalizedStrings.Str3691Params.Put(ex));
}
Trader.LogLevel = LogLevels.Debug;
_logManager.Sources.Add(Trader);
// subscribe on connection successfully event
Trader.Connected += () => this.GuiAsync(() =>
{
Properties.Settings.Default.AccessToken = Trader.AccessToken.Serialize();
OnConnectionChanged(true);
});
// subscribe on connection error event
Trader.ConnectionError += error => this.GuiAsync(() =>
{
OnConnectionChanged(Trader.ConnectionState == ConnectionStates.Connected);
MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
});
Trader.Disconnected += () => this.GuiAsync(() => OnConnectionChanged(false));
// subscribe on error event
Trader.Error += error =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));
// subscribe on error of market data subscription event
Trader.MarketDataSubscriptionFailed += (security, type, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(type, security)));
Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities);
Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades);
Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders);
Trader.NewStopOrders += orders => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders);
Trader.NewPortfolios += portfolios =>
{
// subscribe on portfolio updates
portfolios.ForEach(Trader.RegisterPortfolio);
_portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios);
};
Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions);
// subscribe on error of order registration event
Trader.OrdersRegisterFailed += OrdersFailed;
// subscribe on error of order cancelling event
Trader.OrdersCancelFailed += OrdersFailed;
// subscribe on error of stop-order registration event
Trader.StopOrdersRegisterFailed += OrdersFailed;
// subscribe on error of stop-order cancelling event
Trader.StopOrdersCancelFailed += OrdersFailed;
// set market data provider
_securitiesWindow.SecurityPicker.MarketDataProvider = Trader;
}
Trader.Sandbox = IsSandbox;
//Trader.SandboxSecurities = IsSandbox ? GetSandboxSecurities() : null;
Trader.ConsumerKey = ConsumerKey;
Trader.ConsumerSecret = secret;
Trader.Connect();
}
else
{
Trader.Disconnect();
}
}
private void OnConnectionChanged(bool isConnected)
{
IsConnected = isConnected;
ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect;
}
private void OrdersFailed(IEnumerable<OrderFail> fails)
{
this.GuiAsync(() =>
{
foreach(var fail in fails)
{
var msg = fail.Error.ToString();
MessageBox.Show(this, msg, LocalizedStrings.Str2960);
}
});
}
private void ShowMyTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_myTradesWindow);
}
private void ShowSecuritiesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_securitiesWindow);
}
private void ShowPortfoliosClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_portfoliosWindow);
}
private void ShowOrdersClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_ordersWindow);
}
private void ShowStopOrdersClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_stopOrdersWindow);
}
private static void ShowOrHide(Window window)
{
if (window == null)
throw new ArgumentNullException(nameof(window));
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
}
//private Security[] GetSandboxSecurities()
//{
// return _securities ?? (_securities = new[]
// {
// new Security
// {
// Id = "CSCO@EQ", Code = "CSCO", Name = "CISCO SYS INC", ExchangeBoard = ExchangeBoard.Test,
// Decimals = 2, VolumeStep = 1, StepPrice = 0.01m, PriceStep = 0.01m
// },
// new Security
// {
// Id = "IBM@EQ", Code = "IBM", Name = "INTERNATIONAL BUSINESS MACHS COM", ExchangeBoard = ExchangeBoard.Test,
// Decimals = 2, VolumeStep = 1, StepPrice = 0.01m, PriceStep = 0.01m
// },
// new Security
// {
// Id = "MSFT@EQ", Code = "MSFT", Name = "MICROSOFT CORP COM", ExchangeBoard = ExchangeBoard.Test,
// Decimals = 2, VolumeStep = 1, StepPrice = 0.01m, PriceStep = 0.01m
// }
// });
//}
}
}
| |
using Mvc.Datatables.Reflection;
using System;
using System.Collections.Generic;
namespace Mvc.Datatables.Processing
{
public static class TypeFilters
{
private static readonly Func<string, Type, object> ParseValue =
(input, t) => t.IsEnum ? Enum.Parse(t, input) : Convert.ChangeType(input, t);
internal static string FilterMethod(string q, List<object> parametersForLinqQuery, Type type)
{
Func<string, string, string> makeClause = (method, query) =>
{
parametersForLinqQuery.Add(ParseValue(query, type));
var indexOfParameter = parametersForLinqQuery.Count - 1;
return string.Format("{0}(@{1})", method, indexOfParameter);
};
if (q.StartsWith("^"))
{
if (q.EndsWith("$"))
{
parametersForLinqQuery.Add(ParseValue(q.Substring(1, q.Length - 2), type));
var indexOfParameter = parametersForLinqQuery.Count - 1;
return string.Format("Equals((object)@{0})", indexOfParameter);
}
return makeClause("StartsWith", q.Substring(1));
}
else
{
if (q.EndsWith("$"))
{
return makeClause("EndsWith", q.Substring(0, q.Length - 1));
}
return makeClause("Contains", q);
}
}
public static string NumericFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (query.StartsWith("^")) query = query.TrimStart('^');
if (query.EndsWith("$")) query = query.TrimEnd('$');
if (query == "~") return string.Empty;
if (query.Contains("~"))
{
var parts = query.Split('~');
var clause = null as string;
try
{
parametersForLinqQuery.Add(ChangeType(propertyInfo, parts[0]));
clause = string.Format("{0} >= @{1}", columnname, parametersForLinqQuery.Count - 1);
}
catch (FormatException) { }
try
{
parametersForLinqQuery.Add(ChangeType(propertyInfo, parts[1]));
if (clause != null) clause += " and ";
clause += string.Format("{0} <= @{1}", columnname, parametersForLinqQuery.Count - 1);
}
catch (FormatException) { }
return clause ?? "true";
}
else
{
try
{
parametersForLinqQuery.Add(ChangeType(propertyInfo, query));
return string.Format("{0} == @{1}", columnname, parametersForLinqQuery.Count - 1);
}
catch (FormatException)
{
}
return null;
}
}
private static object ChangeType(DataTablesPropertyInfo propertyInfo, string query)
{
if (propertyInfo.PropertyInfo.PropertyType.IsGenericType && propertyInfo.Type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type u = Nullable.GetUnderlyingType(propertyInfo.Type);
return Convert.ChangeType(query, u);
}
else
{
return Convert.ChangeType(query, propertyInfo.Type);
}
}
public static string DateTimeOffsetFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (query == "~") return string.Empty;
if (query.Contains("~"))
{
var parts = query.Split('~');
var filterString = null as string;
DateTimeOffset start, end;
if (DateTimeOffset.TryParse(parts[0] ?? "", out start))
{
filterString = columnname + " >= @" + parametersForLinqQuery.Count;
parametersForLinqQuery.Add(start);
}
if (DateTimeOffset.TryParse(parts[1] ?? "", out end))
{
filterString = (filterString == null ? null : filterString + " and ") + columnname + " <= @" + parametersForLinqQuery.Count;
parametersForLinqQuery.Add(end);
}
return filterString ?? "";
}
else
{
return string.Format("{1}.ToLocalTime().ToString(\"g\").{0}", FilterMethod(query, parametersForLinqQuery, propertyInfo.Type), columnname);
}
}
public static string DateTimeFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (query == "~") return string.Empty;
if (query.Contains("~"))
{
var parts = query.Split('~');
var filterString = null as string;
DateTime start, end;
if (DateTime.TryParse(parts[0] ?? "", out start))
{
filterString = columnname + " >= @" + parametersForLinqQuery.Count;
parametersForLinqQuery.Add(start);
}
if (DateTime.TryParse(parts[1] ?? "", out end))
{
filterString = (filterString == null ? null : filterString + " and ") + columnname + " <= @" + parametersForLinqQuery.Count;
parametersForLinqQuery.Add(end);
}
return filterString ?? "";
}
else
{
return string.Format("{1}.ToLocalTime().ToString(\"g\").{0}", FilterMethod(query, parametersForLinqQuery, propertyInfo.Type), columnname);
}
}
public static string BoolFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (query != null)
query = query.TrimStart('^').TrimEnd('$');
var lowerCaseQuery = query.ToLowerInvariant();
if (lowerCaseQuery == "false" || lowerCaseQuery == "true")
{
if (query.ToLower() == "true") return columnname + " == true";
return columnname + " == false";
}
if (propertyInfo.Type == typeof(bool?))
{
if (lowerCaseQuery == "null") return columnname + " == null";
}
return null;
}
public static string StringFilter(string q, string columnname, DataTablesPropertyInfo columntype, List<object> parametersforlinqquery)
{
if (q == ".*") return "";
if (q.StartsWith("^"))
{
if (q.EndsWith("$"))
{
parametersforlinqquery.Add(q.Substring(1, q.Length - 2));
var parameterArg = "@" + (parametersforlinqquery.Count - 1);
return string.Format("{0} == {1}", columnname, parameterArg);
}
else
{
parametersforlinqquery.Add(q.Substring(1));
var parameterArg = "@" + (parametersforlinqquery.Count - 1);
return string.Format("({0} != null && {0} != \"\" && ({0} == {1} || {0}.StartsWith({1})))", columnname, parameterArg);
}
}
else
{
parametersforlinqquery.Add(q);
var parameterArg = "@" + (parametersforlinqquery.Count - 1);
//return string.Format("{0} == {1}", columnname, parameterArg);
return
string.Format(
/*
* Gewijzigd door Wietze Sttrik
* Case insensite gemaakt
*/
//"({0} != null && {0} != \"\" && ({0} == {1} || {0}.StartsWith({1}) || {0}.Contains({1})))",
"({0} != null && {0} != \"\" && ({0} == {1} || {0}.StartsWith({1}) || {0}.ToLower().Contains(({1}).ToLower())))",
columnname, parameterArg);
}
}
public static string EnumFilter(string q, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (q.StartsWith("^")) q = q.Substring(1);
if (q.EndsWith("$")) q = q.Substring(0, q.Length - 1);
parametersForLinqQuery.Add(ParseValue(q, propertyInfo.Type));
return columnname + " == @" + (parametersForLinqQuery.Count - 1);
}
}
}
| |
using System;
using System.Collections.Generic;
using FluentAssertions;
using NetFusion.Rest.Client;
using NetFusion.Rest.Resources;
using NetFusion.Rest.Server.Hal;
using WebTests.Rest.Resources.Models;
using Xunit;
namespace WebTests.Rest.Resources
{
/// <summary>
///
/// Contains tests for creating resources from models. This tests the calls
/// that would exist in WebApi controllers as follow:
///
/// - The controller injects a service.
/// - The controller interacts with the server to return one or move domain entities.
/// - Domain entities are mapping into models defining the REST Api.
/// - The models are wrapped within resources containing the following:
///
/// - Embedded Resources: Child resources related to the parent resource.
/// - Links: These are link relations specifying how the resource relates
/// to other resources or actions that can be taken on the resource.
/// - Embedded Models: These are models not wrapped as a resource and therefore
/// do not have embedded items or associated links.
///
/// The HALJsonOutputFormatter checks for returned resources for which link mappings have
/// been defined. The formatter uses the metadata contained with the mappings to add links
/// to the returned resources.
///
/// </summary>
public class CreationTests
{
/// <summary>
/// A resource is just a wrapped model containing additional resource specified
/// information such as links and embedded resources.
/// </summary>
[Fact]
public void Resource_Wraps_Model()
{
// Models populated from domain entities.
var account = new AccountModel
{
AccountNumber = "274823742874234232",
AvailableBalance = 50_000M
};
var payment = new PaymentModel
{
PaymentId = "P24234234",
Amount = 2_000M
};
// Using Factory method to create root resource and delegate to add embedded resources:
var resource = HalResource.New(account, instance =>
{
instance.EmbedResource(payment.AsResource(), "last-payment");
});
resource.Model.Should().BeSameAs(account);
resource.Embedded.Should().ContainKey("last-payment");
// Links will be null. Links are automatically populated by a custom ASP.NET Core OutputFormatter
// based on mappings configured within an ASP.NET Core WebApi project.
resource.Links.Should().BeNull();
// Using Extension Method to create root resource:
var resource2 = account.AsResource();
resource2.EmbedResource(payment.AsResource(), "last-payment");
resource2.Model.Should().BeSameAs(account);
resource2.Embedded.Should().ContainKey("last-payment");
}
/// <summary>
/// The following is an example when a set of related embedded resources are
/// to be returned but when there is no model associated with the parent resource.
/// </summary>
[Fact]
public void EmptyResource_WithEmbedded_Resources()
{
// Models populated from domain entities.
var account = new AccountModel();
var payment = new PaymentModel();
var resource = HalResource.New(instance =>
{
instance.EmbedResource(account.AsResource(), "active-account");
instance.EmbedResource(payment.AsResource(), "largest-payment");
});
resource.ModelValue.Should().BeNull();
resource.Embedded.Keys.Should().HaveCount(2);
resource.HasEmbedded("active-account").Should().BeTrue();
resource.HasEmbedded("largest-payment").Should().BeTrue();
}
/// <summary>
/// The following is an example when a set of related embedded resource or
/// resources collections are to be returned but when there is no model
/// associated with the parent resource.
/// </summary>
[Fact]
public void EmptyResource_WithEmbedded_ResourceCollections()
{
// Models Populated from domain entities:
var account = new AccountModel
{
AccountNumber = "274823742874234232",
AvailableBalance = 50_000M
};
var payments = new[]
{
new PaymentModel { PaymentId = "P24234", Amount = 1_250M},
new PaymentModel { PaymentId = "P82342", Amount = 4_250M},
};
var resource = HalResource.New(instance =>
{
instance.EmbedResource(account.AsResource(), "account");
instance.EmbedResources(payments.AsResources(), "last-payments");
});
resource.ModelValue.Should().BeNull();
resource.Embedded.Keys.Should().HaveCount(2);
resource.Embedded.Should().ContainKeys("account", "last-payments");
}
/// <summary>
/// If a model does not have associated embedded resources and links,
/// it can be directly embedded within the parent resource without
/// having to wrapped within a resource.
/// </summary>
[Fact]
public void Models_CanBeEmbedded_IntoResource()
{
var account = new AccountModel
{
AccountNumber = "274823742874234232",
AvailableBalance = 50_000M
};
var payments = new[]
{
new PaymentModel { PaymentId = "P24234", Amount = 1_250M},
new PaymentModel { PaymentId = "P82342", Amount = 4_250M},
};
var reminder = new ReminderModel
{
Message = "Don't forget to pay on time."
};
var resource = HalResource.New(account, instance =>
{
instance.EmbedModels(payments, "last-payment");
instance.EmbedModel(reminder, "new-reminder");
});
resource.Model.Should().BeSameAs(account);
resource.Embedded.Should().HaveCount(2);
resource.Embedded.Should().ContainKeys("last-payment", "new-reminder");
resource.Embedded.Should().ContainValues(payments, reminder);
}
/// <summary>
/// Embedded names must be specified and convey how the child
/// resource or model is associated with the parent resource.
/// </summary>
[Fact]
public void EmbeddedName_Must_BeSpecified()
{
Assert.Throws<InvalidOperationException>(() =>
{
HalResource.New(instance => { instance.EmbedModel(new PaymentModel(), null); });
})
.Message
.Should()
.Be("The embedded name for type: WebTests.Rest.Resources.Models.PaymentModel was not specified.");
}
/// <summary>
/// Embedded names must be unique.
/// </summary>
[Fact]
public void EmbeddedNames_Must_BeUnique()
{
Assert.Throws<InvalidOperationException>(() =>
{
HalResource.New(instance =>
{
instance.EmbedModel(new PaymentModel(), "firstItem");
instance.EmbedModel(new AccountModel(), "firstItem");
});
})
.Message
.Should()
.Be("The resource already has an embedded value named: firstItem.");
}
[Fact]
public void RestApi_CanHave_EntryResource()
{
var entryModel = new EntryPointModel
{
Version = "10.00.1",
ApiDocUrl = "http://api.docs/finance/accounting.html"
};
var resource = entryModel.AsResource();
resource.Links = new Dictionary<string, Link>
{
{ "payment", new Link { Href = "/api/finance/payments/{id}"} },
{ "account", new Link { Href = "/api/finance/accounts/{id}"} }
};
resource.Model.Should().NotBeNull();
resource.Links.Should().HaveCount(2);
}
}
}
| |
//------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
namespace System.ServiceModel.Configuration
{
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.ServiceModel;
using System.Globalization;
using System.Net;
using System.Net.Security;
using System.Runtime;
using System.Security.Authentication.ExtendedProtection.Configuration;
using System.Security.Principal;
using System.ServiceModel.Channels;
using System.ComponentModel;
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule,
Justification = "The ExtendedProtectionPolicyElement configuration object and the configuration validation is owned by the NCL team.")]
public partial class HttpTransportElement : TransportElement
{
public HttpTransportElement()
{
}
[ConfigurationProperty(ConfigurationStrings.AllowCookies, DefaultValue = HttpTransportDefaults.AllowCookies)]
public bool AllowCookies
{
get { return (bool)base[ConfigurationStrings.AllowCookies]; }
set { base[ConfigurationStrings.AllowCookies] = value; }
}
[ConfigurationProperty(ConfigurationStrings.RequestInitializationTimeout, DefaultValue = HttpTransportDefaults.RequestInitializationTimeoutString)]
[TypeConverter(typeof(TimeSpanOrInfiniteConverter))]
[ServiceModelTimeSpanValidator(MinValueString = ConfigurationStrings.TimeSpanZero)]
public TimeSpan RequestInitializationTimeout
{
get { return (TimeSpan)base[ConfigurationStrings.RequestInitializationTimeout]; }
set { base[ConfigurationStrings.RequestInitializationTimeout] = value; }
}
[ConfigurationProperty(ConfigurationStrings.AuthenticationScheme, DefaultValue = HttpTransportDefaults.AuthenticationScheme)]
[StandardRuntimeFlagEnumValidator(typeof(AuthenticationSchemes))]
public AuthenticationSchemes AuthenticationScheme
{
get { return (AuthenticationSchemes)base[ConfigurationStrings.AuthenticationScheme]; }
set { base[ConfigurationStrings.AuthenticationScheme] = value; }
}
public override Type BindingElementType
{
get { return typeof(HttpTransportBindingElement); }
}
[ConfigurationProperty(ConfigurationStrings.BypassProxyOnLocal, DefaultValue = HttpTransportDefaults.BypassProxyOnLocal)]
public bool BypassProxyOnLocal
{
get { return (bool)base[ConfigurationStrings.BypassProxyOnLocal]; }
set { base[ConfigurationStrings.BypassProxyOnLocal] = value; }
}
[ConfigurationProperty(ConfigurationStrings.DecompressionEnabled, DefaultValue = HttpTransportDefaults.DecompressionEnabled)]
public bool DecompressionEnabled
{
get { return (bool)base[ConfigurationStrings.DecompressionEnabled]; }
set { base[ConfigurationStrings.DecompressionEnabled] = value; }
}
[ConfigurationProperty(ConfigurationStrings.HostNameComparisonMode, DefaultValue = HttpTransportDefaults.HostNameComparisonMode)]
[ServiceModelEnumValidator(typeof(HostNameComparisonModeHelper))]
public HostNameComparisonMode HostNameComparisonMode
{
get { return (HostNameComparisonMode)base[ConfigurationStrings.HostNameComparisonMode]; }
set { base[ConfigurationStrings.HostNameComparisonMode] = value; }
}
[ConfigurationProperty(ConfigurationStrings.KeepAliveEnabled, DefaultValue = HttpTransportDefaults.KeepAliveEnabled)]
public bool KeepAliveEnabled
{
get { return (bool)base[ConfigurationStrings.KeepAliveEnabled]; }
set { base[ConfigurationStrings.KeepAliveEnabled] = value; }
}
[ConfigurationProperty(ConfigurationStrings.MaxBufferSize, DefaultValue = TransportDefaults.MaxBufferSize)]
[IntegerValidator(MinValue = 1)]
public int MaxBufferSize
{
get { return (int)base[ConfigurationStrings.MaxBufferSize]; }
set { base[ConfigurationStrings.MaxBufferSize] = value; }
}
[ConfigurationProperty(ConfigurationStrings.MaxPendingAccepts, DefaultValue = HttpTransportDefaults.DefaultMaxPendingAccepts)]
[IntegerValidator(MinValue = 0, MaxValue = HttpTransportDefaults.MaxPendingAcceptsUpperLimit)]
public int MaxPendingAccepts
{
get { return (int)base[ConfigurationStrings.MaxPendingAccepts]; }
set { base[ConfigurationStrings.MaxPendingAccepts] = value; }
}
[ConfigurationProperty(ConfigurationStrings.MessageHandlerFactory, DefaultValue = HttpTransportDefaults.MessageHandlerFactory)]
[HttpMessageHandlerFactoryValidator]
public HttpMessageHandlerFactoryElement MessageHandlerFactory
{
get { return (HttpMessageHandlerFactoryElement)this[ConfigurationStrings.MessageHandlerFactory]; }
set { base[ConfigurationStrings.MessageHandlerFactory] = value; }
}
[ConfigurationProperty(ConfigurationStrings.ProxyAddress, DefaultValue = HttpTransportDefaults.ProxyAddress)]
public Uri ProxyAddress
{
get { return (Uri)base[ConfigurationStrings.ProxyAddress]; }
set { base[ConfigurationStrings.ProxyAddress] = value; }
}
[ConfigurationProperty(ConfigurationStrings.ProxyAuthenticationScheme, DefaultValue = HttpTransportDefaults.ProxyAuthenticationScheme)]
[StandardRuntimeEnumValidator(typeof(AuthenticationSchemes))]
public AuthenticationSchemes ProxyAuthenticationScheme
{
get { return (AuthenticationSchemes)base[ConfigurationStrings.ProxyAuthenticationScheme]; }
set { base[ConfigurationStrings.ProxyAuthenticationScheme] = value; }
}
[ConfigurationProperty(ConfigurationStrings.Realm, DefaultValue = HttpTransportDefaults.Realm)]
[StringValidator(MinLength = 0)]
public string Realm
{
get { return (string)base[ConfigurationStrings.Realm]; }
set
{
if (String.IsNullOrEmpty(value))
{
value = String.Empty;
}
base[ConfigurationStrings.Realm] = value;
}
}
[ConfigurationProperty(ConfigurationStrings.TransferMode, DefaultValue = HttpTransportDefaults.TransferMode)]
[ServiceModelEnumValidator(typeof(TransferModeHelper))]
public TransferMode TransferMode
{
get { return (TransferMode)base[ConfigurationStrings.TransferMode]; }
set { base[ConfigurationStrings.TransferMode] = value; }
}
[ConfigurationProperty(ConfigurationStrings.UnsafeConnectionNtlmAuthentication, DefaultValue = HttpTransportDefaults.UnsafeConnectionNtlmAuthentication)]
public bool UnsafeConnectionNtlmAuthentication
{
get { return (bool)base[ConfigurationStrings.UnsafeConnectionNtlmAuthentication]; }
set { base[ConfigurationStrings.UnsafeConnectionNtlmAuthentication] = value; }
}
[ConfigurationProperty(ConfigurationStrings.UseDefaultWebProxy, DefaultValue = HttpTransportDefaults.UseDefaultWebProxy)]
public bool UseDefaultWebProxy
{
get { return (bool)base[ConfigurationStrings.UseDefaultWebProxy]; }
set { base[ConfigurationStrings.UseDefaultWebProxy] = value; }
}
[ConfigurationProperty(ConfigurationStrings.ExtendedProtectionPolicy)]
public ExtendedProtectionPolicyElement ExtendedProtectionPolicy
{
get { return (ExtendedProtectionPolicyElement)base[ConfigurationStrings.ExtendedProtectionPolicy]; }
private set { base[ConfigurationStrings.ExtendedProtectionPolicy] = value; }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.Configuration, "Configuration104")]
[ConfigurationProperty(ConfigurationStrings.WebSocketSettingsSectionName)]
public WebSocketTransportSettingsElement WebSocketSettings
{
get { return (WebSocketTransportSettingsElement)base[ConfigurationStrings.WebSocketSettingsSectionName]; }
set { base[ConfigurationStrings.WebSocketSettingsSectionName] = value; }
}
public override void ApplyConfiguration(BindingElement bindingElement)
{
base.ApplyConfiguration(bindingElement);
HttpTransportBindingElement binding = (HttpTransportBindingElement)bindingElement;
binding.AllowCookies = this.AllowCookies;
binding.AuthenticationScheme = this.AuthenticationScheme;
binding.BypassProxyOnLocal = this.BypassProxyOnLocal;
binding.DecompressionEnabled = this.DecompressionEnabled;
binding.KeepAliveEnabled = this.KeepAliveEnabled;
binding.HostNameComparisonMode = this.HostNameComparisonMode;
PropertyInformationCollection propertyInfo = this.ElementInformation.Properties;
if (propertyInfo[ConfigurationStrings.MaxBufferSize].ValueOrigin != PropertyValueOrigin.Default)
{
binding.MaxBufferSize = this.MaxBufferSize;
}
binding.MaxPendingAccepts = this.MaxPendingAccepts;
binding.ProxyAddress = this.ProxyAddress;
binding.ProxyAuthenticationScheme = this.ProxyAuthenticationScheme;
binding.Realm = this.Realm;
binding.RequestInitializationTimeout = this.RequestInitializationTimeout;
binding.TransferMode = this.TransferMode;
binding.UnsafeConnectionNtlmAuthentication = this.UnsafeConnectionNtlmAuthentication;
binding.UseDefaultWebProxy = this.UseDefaultWebProxy;
binding.ExtendedProtectionPolicy = ChannelBindingUtility.BuildPolicy(this.ExtendedProtectionPolicy);
this.WebSocketSettings.ApplyConfiguration(binding.WebSocketSettings);
if (this.MessageHandlerFactory != null)
{
binding.MessageHandlerFactory = HttpMessageHandlerFactory.CreateFromConfigurationElement(this.MessageHandlerFactory);
}
}
public override void CopyFrom(ServiceModelExtensionElement from)
{
base.CopyFrom(from);
HttpTransportElement source = (HttpTransportElement)from;
#pragma warning suppress 56506 // [....], base.CopyFrom() validates the argument
this.AllowCookies = source.AllowCookies;
this.RequestInitializationTimeout = source.RequestInitializationTimeout;
this.AuthenticationScheme = source.AuthenticationScheme;
this.BypassProxyOnLocal = source.BypassProxyOnLocal;
this.DecompressionEnabled = source.DecompressionEnabled;
this.KeepAliveEnabled = source.KeepAliveEnabled;
this.HostNameComparisonMode = source.HostNameComparisonMode;
this.MaxBufferSize = source.MaxBufferSize;
this.MaxPendingAccepts = source.MaxPendingAccepts;
this.ProxyAddress = source.ProxyAddress;
this.ProxyAuthenticationScheme = source.ProxyAuthenticationScheme;
this.Realm = source.Realm;
this.TransferMode = source.TransferMode;
this.UnsafeConnectionNtlmAuthentication = source.UnsafeConnectionNtlmAuthentication;
this.UseDefaultWebProxy = source.UseDefaultWebProxy;
this.WebSocketSettings = source.WebSocketSettings;
this.MessageHandlerFactory = source.MessageHandlerFactory;
ChannelBindingUtility.CopyFrom(source.ExtendedProtectionPolicy, this.ExtendedProtectionPolicy);
}
protected override TransportBindingElement CreateDefaultBindingElement()
{
return new HttpTransportBindingElement();
}
protected internal override void InitializeFrom(BindingElement bindingElement)
{
base.InitializeFrom(bindingElement);
HttpTransportBindingElement source = (HttpTransportBindingElement)bindingElement;
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.AllowCookies, source.AllowCookies);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.AuthenticationScheme, source.AuthenticationScheme);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.DecompressionEnabled, source.DecompressionEnabled);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.BypassProxyOnLocal, source.BypassProxyOnLocal);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.KeepAliveEnabled, source.KeepAliveEnabled);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.HostNameComparisonMode, source.HostNameComparisonMode);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.MaxBufferSize, source.MaxBufferSize);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.MaxPendingAccepts, source.MaxPendingAccepts);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.ProxyAddress, source.ProxyAddress);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.ProxyAuthenticationScheme, source.ProxyAuthenticationScheme);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.Realm, source.Realm);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.RequestInitializationTimeout, source.RequestInitializationTimeout);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.TransferMode, source.TransferMode);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.UnsafeConnectionNtlmAuthentication, source.UnsafeConnectionNtlmAuthentication);
SetPropertyValueIfNotDefaultValue(ConfigurationStrings.UseDefaultWebProxy, source.UseDefaultWebProxy);
this.WebSocketSettings.InitializeFrom(source.WebSocketSettings);
if (source.MessageHandlerFactory != null)
{
this.MessageHandlerFactory = source.MessageHandlerFactory.GenerateConfigurationElement();
}
ChannelBindingUtility.InitializeFrom(source.ExtendedProtectionPolicy, this.ExtendedProtectionPolicy);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using Lucene.Net.Support;
using Document = Lucene.Net.Documents.Document;
using FieldSelector = Lucene.Net.Documents.FieldSelector;
using MultiTermDocs = Lucene.Net.Index.DirectoryReader.MultiTermDocs;
using MultiTermEnum = Lucene.Net.Index.DirectoryReader.MultiTermEnum;
using MultiTermPositions = Lucene.Net.Index.DirectoryReader.MultiTermPositions;
using DefaultSimilarity = Lucene.Net.Search.DefaultSimilarity;
namespace Lucene.Net.Index
{
/// <summary>An IndexReader which reads multiple indexes, appending
/// their content.
/// </summary>
public class MultiReader:IndexReader, System.ICloneable
{
protected internal IndexReader[] subReaders;
private int[] starts; // 1st docno for each segment
private bool[] decrefOnClose; // remember which subreaders to decRef on close
private System.Collections.Generic.IDictionary<string, byte[]> normsCache = new HashMap<string,byte[]>();
private int maxDoc = 0;
private int numDocs = - 1;
private bool hasDeletions = false;
/// <summary> <p/>Construct a MultiReader aggregating the named set of (sub)readers.
/// Directory locking for delete, undeleteAll, and setNorm operations is
/// left to the subreaders. <p/>
/// <p/>Note that all subreaders are closed if this Multireader is closed.<p/>
/// </summary>
/// <param name="subReaders">set of (sub)readers
/// </param>
/// <throws> IOException </throws>
public MultiReader(params IndexReader[] subReaders)
{
Initialize(subReaders, true);
}
/// <summary> <p/>Construct a MultiReader aggregating the named set of (sub)readers.
/// Directory locking for delete, undeleteAll, and setNorm operations is
/// left to the subreaders. <p/>
/// </summary>
/// <param name="closeSubReaders">indicates whether the subreaders should be closed
/// when this MultiReader is closed
/// </param>
/// <param name="subReaders">set of (sub)readers
/// </param>
/// <throws> IOException </throws>
public MultiReader(IndexReader[] subReaders, bool closeSubReaders)
{
Initialize(subReaders, closeSubReaders);
}
private void Initialize(IndexReader[] subReaders, bool closeSubReaders)
{
// Deep copy
this.subReaders = subReaders.ToArray();
starts = new int[subReaders.Length + 1]; // build starts array
decrefOnClose = new bool[subReaders.Length];
for (int i = 0; i < subReaders.Length; i++)
{
starts[i] = maxDoc;
maxDoc += subReaders[i].MaxDoc; // compute maxDocs
if (!closeSubReaders)
{
subReaders[i].IncRef();
decrefOnClose[i] = true;
}
else
{
decrefOnClose[i] = false;
}
if (subReaders[i].HasDeletions)
hasDeletions = true;
}
starts[subReaders.Length] = maxDoc;
}
/// <summary> Tries to reopen the subreaders.
/// <br/>
/// If one or more subreaders could be re-opened (i. e. subReader.reopen()
/// returned a new instance != subReader), then a new MultiReader instance
/// is returned, otherwise this instance is returned.
/// <p/>
/// A re-opened instance might share one or more subreaders with the old
/// instance. Index modification operations result in undefined behavior
/// when performed before the old instance is closed.
/// (see <see cref="IndexReader.Reopen()" />).
/// <p/>
/// If subreaders are shared, then the reference count of those
/// readers is increased to ensure that the subreaders remain open
/// until the last referring reader is closed.
///
/// </summary>
/// <throws> CorruptIndexException if the index is corrupt </throws>
/// <throws> IOException if there is a low-level IO error </throws>
public override IndexReader Reopen()
{
lock (this)
{
return DoReopen(false);
}
}
/// <summary> Clones the subreaders.
/// (see <see cref="IndexReader.Clone()" />).
/// <br/>
/// <p/>
/// If subreaders are shared, then the reference count of those
/// readers is increased to ensure that the subreaders remain open
/// until the last referring reader is closed.
/// </summary>
public override System.Object Clone()
{
try
{
return DoReopen(true);
}
catch (System.Exception ex)
{
throw new System.SystemException(ex.Message, ex);
}
}
/// <summary> If clone is true then we clone each of the subreaders</summary>
/// <param name="doClone">
/// </param>
/// <returns> New IndexReader, or same one (this) if
/// reopen/clone is not necessary
/// </returns>
/// <throws> CorruptIndexException </throws>
/// <throws> IOException </throws>
protected internal virtual IndexReader DoReopen(bool doClone)
{
EnsureOpen();
bool reopened = false;
IndexReader[] newSubReaders = new IndexReader[subReaders.Length];
bool success = false;
try
{
for (int i = 0; i < subReaders.Length; i++)
{
if (doClone)
newSubReaders[i] = (IndexReader) subReaders[i].Clone();
else
newSubReaders[i] = subReaders[i].Reopen();
// if at least one of the subreaders was updated we remember that
// and return a new MultiReader
if (newSubReaders[i] != subReaders[i])
{
reopened = true;
}
}
success = true;
}
finally
{
if (!success && reopened)
{
for (int i = 0; i < newSubReaders.Length; i++)
{
if (newSubReaders[i] != subReaders[i])
{
try
{
newSubReaders[i].Close();
}
catch (System.IO.IOException)
{
// keep going - we want to clean up as much as possible
}
}
}
}
}
if (reopened)
{
bool[] newDecrefOnClose = new bool[subReaders.Length];
for (int i = 0; i < subReaders.Length; i++)
{
if (newSubReaders[i] == subReaders[i])
{
newSubReaders[i].IncRef();
newDecrefOnClose[i] = true;
}
}
MultiReader mr = new MultiReader(newSubReaders);
mr.decrefOnClose = newDecrefOnClose;
return mr;
}
else
{
return this;
}
}
public override ITermFreqVector[] GetTermFreqVectors(int n)
{
EnsureOpen();
int i = ReaderIndex(n); // find segment num
return subReaders[i].GetTermFreqVectors(n - starts[i]); // dispatch to segment
}
public override ITermFreqVector GetTermFreqVector(int n, System.String field)
{
EnsureOpen();
int i = ReaderIndex(n); // find segment num
return subReaders[i].GetTermFreqVector(n - starts[i], field);
}
public override void GetTermFreqVector(int docNumber, System.String field, TermVectorMapper mapper)
{
EnsureOpen();
int i = ReaderIndex(docNumber); // find segment num
subReaders[i].GetTermFreqVector(docNumber - starts[i], field, mapper);
}
public override void GetTermFreqVector(int docNumber, TermVectorMapper mapper)
{
EnsureOpen();
int i = ReaderIndex(docNumber); // find segment num
subReaders[i].GetTermFreqVector(docNumber - starts[i], mapper);
}
public override bool IsOptimized()
{
return false;
}
public override int NumDocs()
{
// Don't call ensureOpen() here (it could affect performance)
// NOTE: multiple threads may wind up init'ing
// numDocs... but that's harmless
if (numDocs == - 1)
{
// check cache
int n = 0; // cache miss--recompute
for (int i = 0; i < subReaders.Length; i++)
n += subReaders[i].NumDocs(); // sum from readers
numDocs = n;
}
return numDocs;
}
public override int MaxDoc
{
get
{
// Don't call ensureOpen() here (it could affect performance)
return maxDoc;
}
}
// inherit javadoc
public override Document Document(int n, FieldSelector fieldSelector)
{
EnsureOpen();
int i = ReaderIndex(n); // find segment num
return subReaders[i].Document(n - starts[i], fieldSelector); // dispatch to segment reader
}
public override bool IsDeleted(int n)
{
// Don't call ensureOpen() here (it could affect performance)
int i = ReaderIndex(n); // find segment num
return subReaders[i].IsDeleted(n - starts[i]); // dispatch to segment reader
}
public override bool HasDeletions
{
get
{
// Don't call ensureOpen() here (it could affect performance)
return hasDeletions;
}
}
protected internal override void DoDelete(int n)
{
numDocs = - 1; // invalidate cache
int i = ReaderIndex(n); // find segment num
subReaders[i].DeleteDocument(n - starts[i]); // dispatch to segment reader
hasDeletions = true;
}
protected internal override void DoUndeleteAll()
{
for (int i = 0; i < subReaders.Length; i++)
subReaders[i].UndeleteAll();
hasDeletions = false;
numDocs = - 1; // invalidate cache
}
private int ReaderIndex(int n)
{
// find reader for doc n:
return DirectoryReader.ReaderIndex(n, this.starts, this.subReaders.Length);
}
public override bool HasNorms(System.String field)
{
EnsureOpen();
for (int i = 0; i < subReaders.Length; i++)
{
if (subReaders[i].HasNorms(field))
return true;
}
return false;
}
public override byte[] Norms(System.String field)
{
lock (this)
{
EnsureOpen();
byte[] bytes = normsCache[field];
if (bytes != null)
return bytes; // cache hit
if (!HasNorms(field))
return null;
bytes = new byte[MaxDoc];
for (int i = 0; i < subReaders.Length; i++)
subReaders[i].Norms(field, bytes, starts[i]);
normsCache[field] = bytes; // update cache
return bytes;
}
}
public override void Norms(System.String field, byte[] result, int offset)
{
lock (this)
{
EnsureOpen();
byte[] bytes = normsCache[field];
for (int i = 0; i < subReaders.Length; i++)
// read from segments
subReaders[i].Norms(field, result, offset + starts[i]);
if (bytes == null && !HasNorms(field))
{
for (int i = offset; i < result.Length; i++)
{
result[i] = (byte) DefaultSimilarity.EncodeNorm(1.0f);
}
}
else if (bytes != null)
{
// cache hit
Array.Copy(bytes, 0, result, offset, MaxDoc);
}
else
{
for (int i = 0; i < subReaders.Length; i++)
{
// read from segments
subReaders[i].Norms(field, result, offset + starts[i]);
}
}
}
}
protected internal override void DoSetNorm(int n, System.String field, byte value_Renamed)
{
lock (normsCache)
{
normsCache.Remove(field); // clear cache
}
int i = ReaderIndex(n); // find segment num
subReaders[i].SetNorm(n - starts[i], field, value_Renamed); // dispatch
}
public override TermEnum Terms()
{
EnsureOpen();
return new MultiTermEnum(this, subReaders, starts, null);
}
public override TermEnum Terms(Term term)
{
EnsureOpen();
return new MultiTermEnum(this, subReaders, starts, term);
}
public override int DocFreq(Term t)
{
EnsureOpen();
int total = 0; // sum freqs in segments
for (int i = 0; i < subReaders.Length; i++)
total += subReaders[i].DocFreq(t);
return total;
}
public override TermDocs TermDocs()
{
EnsureOpen();
return new MultiTermDocs(this, subReaders, starts);
}
public override TermPositions TermPositions()
{
EnsureOpen();
return new MultiTermPositions(this, subReaders, starts);
}
protected internal override void DoCommit(System.Collections.Generic.IDictionary<string, string> commitUserData)
{
for (int i = 0; i < subReaders.Length; i++)
subReaders[i].Commit(commitUserData);
}
protected internal override void DoClose()
{
lock (this)
{
for (int i = 0; i < subReaders.Length; i++)
{
if (decrefOnClose[i])
{
subReaders[i].DecRef();
}
else
{
subReaders[i].Close();
}
}
}
// NOTE: only needed in case someone had asked for
// FieldCache for top-level reader (which is generally
// not a good idea):
Lucene.Net.Search.FieldCache_Fields.DEFAULT.Purge(this);
}
public override System.Collections.Generic.ICollection<string> GetFieldNames(IndexReader.FieldOption fieldNames)
{
EnsureOpen();
return DirectoryReader.GetFieldNames(fieldNames, this.subReaders);
}
/// <summary> Checks recursively if all subreaders are up to date. </summary>
public override bool IsCurrent()
{
for (int i = 0; i < subReaders.Length; i++)
{
if (!subReaders[i].IsCurrent())
{
return false;
}
}
// all subreaders are up to date
return true;
}
/// <summary>Not implemented.</summary>
/// <throws> UnsupportedOperationException </throws>
public override long Version
{
get { throw new System.NotSupportedException("MultiReader does not support this method."); }
}
public override IndexReader[] GetSequentialSubReaders()
{
return subReaders;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Globalization;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// FontCtl
/// </summary>
internal class FontCtl : System.Windows.Forms.UserControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
private bool fHorzAlign, fFormat, fDirection, fWritingMode, fTextDecoration;
private bool fColor, fVerticalAlign, fFontStyle, fFontWeight, fFontSize, fFontFamily;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label lFont;
private System.Windows.Forms.Button bFont;
private System.Windows.Forms.ComboBox cbHorzAlign;
private System.Windows.Forms.ComboBox cbFormat;
private System.Windows.Forms.ComboBox cbDirection;
private System.Windows.Forms.ComboBox cbWritingMode;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox cbTextDecoration;
private System.Windows.Forms.Button bColor;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.ComboBox cbColor;
private System.Windows.Forms.ComboBox cbVerticalAlign;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox cbFontStyle;
private System.Windows.Forms.ComboBox cbFontWeight;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.ComboBox cbFontSize;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.ComboBox cbFontFamily;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button bFamily;
private System.Windows.Forms.Button bStyle;
private System.Windows.Forms.Button bColorEx;
private System.Windows.Forms.Button bSize;
private System.Windows.Forms.Button bWeight;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button bAlignment;
private System.Windows.Forms.Button bDirection;
private System.Windows.Forms.Button bVertical;
private System.Windows.Forms.Button bWrtMode;
private System.Windows.Forms.Button bFormat;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private string[] _names;
internal FontCtl(DesignXmlDraw dxDraw, string[] names, List<XmlNode> styles)
{
_ReportItems = styles;
_Draw = dxDraw;
_names = names;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitTextStyles();
}
private void InitTextStyles()
{
cbColor.Items.AddRange(StaticLists.ColorList);
cbFormat.Items.AddRange(StaticLists.FormatList);
XmlNode sNode = _ReportItems[0];
if (_names != null)
{
sNode = _Draw.FindCreateNextInHierarchy(sNode, _names);
}
sNode = _Draw.GetCreateNamedChildNode(sNode, "Style");
string sFontStyle="Normal";
string sFontFamily="Arial";
string sFontWeight="Normal";
string sFontSize="10pt";
string sTextDecoration="None";
string sHorzAlign="General";
string sVerticalAlign="Top";
string sColor="Black";
string sFormat="";
string sDirection="LTR";
string sWritingMode="lr-tb";
foreach (XmlNode lNode in sNode)
{
if (lNode.NodeType != XmlNodeType.Element)
continue;
switch (lNode.Name)
{
case "FontStyle":
sFontStyle = lNode.InnerText;
break;
case "FontFamily":
sFontFamily = lNode.InnerText;
break;
case "FontWeight":
sFontWeight = lNode.InnerText;
break;
case "FontSize":
sFontSize = lNode.InnerText;
break;
case "TextDecoration":
sTextDecoration = lNode.InnerText;
break;
case "TextAlign":
sHorzAlign = lNode.InnerText;
break;
case "VerticalAlign":
sVerticalAlign = lNode.InnerText;
break;
case "Color":
sColor = lNode.InnerText;
break;
case "Format":
sFormat = lNode.InnerText;
break;
case "Direction":
sDirection = lNode.InnerText;
break;
case "WritingMode":
sWritingMode = lNode.InnerText;
break;
}
}
// Population Font Family dropdown
foreach (FontFamily ff in FontFamily.Families)
{
cbFontFamily.Items.Add(ff.Name);
}
this.cbFontStyle.Text = sFontStyle;
this.cbFontFamily.Text = sFontFamily;
this.cbFontWeight.Text = sFontWeight;
this.cbFontSize.Text = sFontSize;
this.cbTextDecoration.Text = sTextDecoration;
this.cbHorzAlign.Text = sHorzAlign;
this.cbVerticalAlign.Text = sVerticalAlign;
this.cbColor.Text = sColor;
this.cbFormat.Text = sFormat;
this.cbDirection.Text = sDirection;
this.cbWritingMode.Text = sWritingMode;
fHorzAlign = fFormat = fDirection = fWritingMode = fTextDecoration =
fColor = fVerticalAlign = fFontStyle = fFontWeight = fFontSize = fFontFamily = false;
return;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.lFont = new System.Windows.Forms.Label();
this.bFont = new System.Windows.Forms.Button();
this.cbVerticalAlign = new System.Windows.Forms.ComboBox();
this.cbHorzAlign = new System.Windows.Forms.ComboBox();
this.cbFormat = new System.Windows.Forms.ComboBox();
this.cbDirection = new System.Windows.Forms.ComboBox();
this.cbWritingMode = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.cbTextDecoration = new System.Windows.Forms.ComboBox();
this.bColor = new System.Windows.Forms.Button();
this.label9 = new System.Windows.Forms.Label();
this.cbColor = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.cbFontStyle = new System.Windows.Forms.ComboBox();
this.cbFontWeight = new System.Windows.Forms.ComboBox();
this.label10 = new System.Windows.Forms.Label();
this.cbFontSize = new System.Windows.Forms.ComboBox();
this.label11 = new System.Windows.Forms.Label();
this.cbFontFamily = new System.Windows.Forms.ComboBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.button2 = new System.Windows.Forms.Button();
this.bWeight = new System.Windows.Forms.Button();
this.bSize = new System.Windows.Forms.Button();
this.bColorEx = new System.Windows.Forms.Button();
this.bStyle = new System.Windows.Forms.Button();
this.bFamily = new System.Windows.Forms.Button();
this.bAlignment = new System.Windows.Forms.Button();
this.bDirection = new System.Windows.Forms.Button();
this.bVertical = new System.Windows.Forms.Button();
this.bWrtMode = new System.Windows.Forms.Button();
this.bFormat = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// label4
//
this.label4.Location = new System.Drawing.Point(16, 196);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(48, 16);
this.label4.TabIndex = 3;
this.label4.Text = "Format";
//
// label5
//
this.label5.Location = new System.Drawing.Point(216, 132);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(48, 16);
this.label5.TabIndex = 4;
this.label5.Text = "Vertical";
//
// label6
//
this.label6.Location = new System.Drawing.Point(16, 132);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(56, 16);
this.label6.TabIndex = 5;
this.label6.Text = "Alignment";
//
// label7
//
this.label7.Location = new System.Drawing.Point(16, 164);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(56, 16);
this.label7.TabIndex = 6;
this.label7.Text = "Direction";
//
// label8
//
this.label8.Location = new System.Drawing.Point(216, 164);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(80, 16);
this.label8.TabIndex = 7;
this.label8.Text = "Writing Mode";
//
// lFont
//
this.lFont.Location = new System.Drawing.Point(16, 16);
this.lFont.Name = "lFont";
this.lFont.Size = new System.Drawing.Size(40, 16);
this.lFont.TabIndex = 8;
this.lFont.Text = "Family";
//
// bFont
//
this.bFont.Location = new System.Drawing.Point(401, 20);
this.bFont.Name = "bFont";
this.bFont.Size = new System.Drawing.Size(22, 16);
this.bFont.TabIndex = 4;
this.bFont.Text = "...";
this.bFont.Click += new System.EventHandler(this.bFont_Click);
//
// cbVerticalAlign
//
this.cbVerticalAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbVerticalAlign.Items.AddRange(new object[] {
"Top",
"Middle",
"Bottom"});
this.cbVerticalAlign.Location = new System.Drawing.Point(304, 132);
this.cbVerticalAlign.Name = "cbVerticalAlign";
this.cbVerticalAlign.Size = new System.Drawing.Size(72, 21);
this.cbVerticalAlign.TabIndex = 5;
this.cbVerticalAlign.SelectedIndexChanged += new System.EventHandler(this.cbVerticalAlign_TextChanged);
this.cbVerticalAlign.TextChanged += new System.EventHandler(this.cbVerticalAlign_TextChanged);
//
// cbHorzAlign
//
this.cbHorzAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbHorzAlign.Items.AddRange(new object[] {
"Left",
"Center",
"Right",
"General"});
this.cbHorzAlign.Location = new System.Drawing.Point(80, 132);
this.cbHorzAlign.Name = "cbHorzAlign";
this.cbHorzAlign.Size = new System.Drawing.Size(64, 21);
this.cbHorzAlign.TabIndex = 3;
this.cbHorzAlign.SelectedIndexChanged += new System.EventHandler(this.cbHorzAlign_TextChanged);
this.cbHorzAlign.TextChanged += new System.EventHandler(this.cbHorzAlign_TextChanged);
//
// cbFormat
//
this.cbFormat.Location = new System.Drawing.Point(80, 196);
this.cbFormat.Name = "cbFormat";
this.cbFormat.Size = new System.Drawing.Size(296, 21);
this.cbFormat.TabIndex = 11;
this.cbFormat.TextChanged += new System.EventHandler(this.cbFormat_TextChanged);
//
// cbDirection
//
this.cbDirection.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbDirection.Items.AddRange(new object[] {
"LTR",
"RTL"});
this.cbDirection.Location = new System.Drawing.Point(80, 164);
this.cbDirection.Name = "cbDirection";
this.cbDirection.Size = new System.Drawing.Size(64, 21);
this.cbDirection.TabIndex = 7;
this.cbDirection.SelectedIndexChanged += new System.EventHandler(this.cbDirection_TextChanged);
this.cbDirection.TextChanged += new System.EventHandler(this.cbDirection_TextChanged);
//
// cbWritingMode
//
this.cbWritingMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbWritingMode.Items.AddRange(new object[] {
"lr-tb",
"tb-rl"});
this.cbWritingMode.Location = new System.Drawing.Point(304, 164);
this.cbWritingMode.Name = "cbWritingMode";
this.cbWritingMode.Size = new System.Drawing.Size(72, 21);
this.cbWritingMode.TabIndex = 9;
this.cbWritingMode.SelectedIndexChanged += new System.EventHandler(this.cbWritingMode_TextChanged);
this.cbWritingMode.TextChanged += new System.EventHandler(this.cbWritingMode_TextChanged);
//
// label2
//
this.label2.Location = new System.Drawing.Point(224, 80);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(64, 23);
this.label2.TabIndex = 19;
this.label2.Text = "Decoration";
//
// cbTextDecoration
//
this.cbTextDecoration.Items.AddRange(new object[] {
"None",
"Underline",
"Overline",
"LineThrough"});
this.cbTextDecoration.Location = new System.Drawing.Point(288, 80);
this.cbTextDecoration.Name = "cbTextDecoration";
this.cbTextDecoration.Size = new System.Drawing.Size(80, 21);
this.cbTextDecoration.TabIndex = 12;
this.cbTextDecoration.SelectedIndexChanged += new System.EventHandler(this.cbTextDecoration_TextChanged);
this.cbTextDecoration.TextChanged += new System.EventHandler(this.cbTextDecoration_TextChanged);
//
// bColor
//
this.bColor.Location = new System.Drawing.Point(200, 82);
this.bColor.Name = "bColor";
this.bColor.Size = new System.Drawing.Size(22, 16);
this.bColor.TabIndex = 11;
this.bColor.Text = "...";
this.bColor.Click += new System.EventHandler(this.bColor_Click);
//
// label9
//
this.label9.Location = new System.Drawing.Point(16, 80);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(48, 16);
this.label9.TabIndex = 22;
this.label9.Text = "Color";
//
// cbColor
//
this.cbColor.Location = new System.Drawing.Point(72, 80);
this.cbColor.Name = "cbColor";
this.cbColor.Size = new System.Drawing.Size(96, 21);
this.cbColor.TabIndex = 9;
this.cbColor.TextChanged += new System.EventHandler(this.cbColor_TextChanged);
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 48);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(40, 16);
this.label3.TabIndex = 25;
this.label3.Text = "Style";
//
// cbFontStyle
//
this.cbFontStyle.Items.AddRange(new object[] {
"Normal",
"Italic"});
this.cbFontStyle.Location = new System.Drawing.Point(72, 48);
this.cbFontStyle.Name = "cbFontStyle";
this.cbFontStyle.Size = new System.Drawing.Size(96, 21);
this.cbFontStyle.TabIndex = 5;
this.cbFontStyle.TextChanged += new System.EventHandler(this.cbFontStyle_TextChanged);
//
// cbFontWeight
//
this.cbFontWeight.Items.AddRange(new object[] {
"Lighter",
"Normal",
"Bold",
"Bolder",
"100",
"200",
"300",
"400",
"500",
"600",
"700",
"800",
"900"});
this.cbFontWeight.Location = new System.Drawing.Point(270, 48);
this.cbFontWeight.Name = "cbFontWeight";
this.cbFontWeight.Size = new System.Drawing.Size(98, 21);
this.cbFontWeight.TabIndex = 7;
this.cbFontWeight.TextChanged += new System.EventHandler(this.cbFontWeight_TextChanged);
//
// label10
//
this.label10.Location = new System.Drawing.Point(224, 48);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(49, 16);
this.label10.TabIndex = 27;
this.label10.Text = "Weight";
//
// cbFontSize
//
this.cbFontSize.Items.AddRange(new object[] {
"8pt",
"9pt",
"10pt",
"11pt",
"12pt",
"14pt",
"16pt",
"18pt",
"20pt",
"22pt",
"24pt",
"26pt",
"28pt",
"36pt",
"48pt",
"72pt"});
this.cbFontSize.Location = new System.Drawing.Point(270, 16);
this.cbFontSize.Name = "cbFontSize";
this.cbFontSize.Size = new System.Drawing.Size(98, 21);
this.cbFontSize.TabIndex = 2;
this.cbFontSize.TextChanged += new System.EventHandler(this.cbFontSize_TextChanged);
//
// label11
//
this.label11.Location = new System.Drawing.Point(224, 16);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(40, 16);
this.label11.TabIndex = 29;
this.label11.Text = "Size";
//
// cbFontFamily
//
this.cbFontFamily.Items.AddRange(new object[] {
"Arial"});
this.cbFontFamily.Location = new System.Drawing.Point(72, 16);
this.cbFontFamily.Name = "cbFontFamily";
this.cbFontFamily.Size = new System.Drawing.Size(96, 21);
this.cbFontFamily.TabIndex = 0;
this.cbFontFamily.TextChanged += new System.EventHandler(this.cbFontFamily_TextChanged);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.button2);
this.groupBox1.Controls.Add(this.bWeight);
this.groupBox1.Controls.Add(this.bSize);
this.groupBox1.Controls.Add(this.bColorEx);
this.groupBox1.Controls.Add(this.bStyle);
this.groupBox1.Controls.Add(this.bFamily);
this.groupBox1.Controls.Add(this.lFont);
this.groupBox1.Controls.Add(this.bFont);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.cbTextDecoration);
this.groupBox1.Controls.Add(this.bColor);
this.groupBox1.Controls.Add(this.label9);
this.groupBox1.Controls.Add(this.cbColor);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.cbFontStyle);
this.groupBox1.Controls.Add(this.cbFontWeight);
this.groupBox1.Controls.Add(this.label10);
this.groupBox1.Controls.Add(this.cbFontSize);
this.groupBox1.Controls.Add(this.label11);
this.groupBox1.Controls.Add(this.cbFontFamily);
this.groupBox1.Location = new System.Drawing.Point(8, 4);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(432, 112);
this.groupBox1.TabIndex = 2;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Font";
//
// button2
//
this.button2.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button2.Location = new System.Drawing.Point(376, 82);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(22, 16);
this.button2.TabIndex = 13;
this.button2.Tag = "decoration";
this.button2.Text = "fx";
this.button2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.button2.Click += new System.EventHandler(this.bExpr_Click);
//
// bWeight
//
this.bWeight.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bWeight.Location = new System.Drawing.Point(376, 52);
this.bWeight.Name = "bWeight";
this.bWeight.Size = new System.Drawing.Size(22, 16);
this.bWeight.TabIndex = 8;
this.bWeight.Tag = "weight";
this.bWeight.Text = "fx";
this.bWeight.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bWeight.Click += new System.EventHandler(this.bExpr_Click);
//
// bSize
//
this.bSize.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bSize.Location = new System.Drawing.Point(376, 20);
this.bSize.Name = "bSize";
this.bSize.Size = new System.Drawing.Size(22, 16);
this.bSize.TabIndex = 3;
this.bSize.Tag = "size";
this.bSize.Text = "fx";
this.bSize.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bSize.Click += new System.EventHandler(this.bExpr_Click);
//
// bColorEx
//
this.bColorEx.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bColorEx.Location = new System.Drawing.Point(176, 82);
this.bColorEx.Name = "bColorEx";
this.bColorEx.Size = new System.Drawing.Size(22, 16);
this.bColorEx.TabIndex = 10;
this.bColorEx.Tag = "color";
this.bColorEx.Text = "fx";
this.bColorEx.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bColorEx.Click += new System.EventHandler(this.bExpr_Click);
//
// bStyle
//
this.bStyle.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bStyle.Location = new System.Drawing.Point(176, 52);
this.bStyle.Name = "bStyle";
this.bStyle.Size = new System.Drawing.Size(22, 16);
this.bStyle.TabIndex = 6;
this.bStyle.Tag = "style";
this.bStyle.Text = "fx";
this.bStyle.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bStyle.Click += new System.EventHandler(this.bExpr_Click);
//
// bFamily
//
this.bFamily.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bFamily.Location = new System.Drawing.Point(176, 20);
this.bFamily.Name = "bFamily";
this.bFamily.Size = new System.Drawing.Size(22, 16);
this.bFamily.TabIndex = 1;
this.bFamily.Tag = "family";
this.bFamily.Text = "fx";
this.bFamily.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bFamily.Click += new System.EventHandler(this.bExpr_Click);
//
// bAlignment
//
this.bAlignment.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bAlignment.Location = new System.Drawing.Point(152, 134);
this.bAlignment.Name = "bAlignment";
this.bAlignment.Size = new System.Drawing.Size(22, 16);
this.bAlignment.TabIndex = 4;
this.bAlignment.Tag = "halign";
this.bAlignment.Text = "fx";
this.bAlignment.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bAlignment.Click += new System.EventHandler(this.bExpr_Click);
//
// bDirection
//
this.bDirection.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bDirection.Location = new System.Drawing.Point(152, 166);
this.bDirection.Name = "bDirection";
this.bDirection.Size = new System.Drawing.Size(22, 16);
this.bDirection.TabIndex = 8;
this.bDirection.Tag = "direction";
this.bDirection.Text = "fx";
this.bDirection.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bDirection.Click += new System.EventHandler(this.bExpr_Click);
//
// bVertical
//
this.bVertical.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bVertical.Location = new System.Drawing.Point(384, 134);
this.bVertical.Name = "bVertical";
this.bVertical.Size = new System.Drawing.Size(22, 16);
this.bVertical.TabIndex = 6;
this.bVertical.Tag = "valign";
this.bVertical.Text = "fx";
this.bVertical.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bVertical.Click += new System.EventHandler(this.bExpr_Click);
//
// bWrtMode
//
this.bWrtMode.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bWrtMode.Location = new System.Drawing.Point(384, 166);
this.bWrtMode.Name = "bWrtMode";
this.bWrtMode.Size = new System.Drawing.Size(22, 16);
this.bWrtMode.TabIndex = 10;
this.bWrtMode.Tag = "writing";
this.bWrtMode.Text = "fx";
this.bWrtMode.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bWrtMode.Click += new System.EventHandler(this.bExpr_Click);
//
// bFormat
//
this.bFormat.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bFormat.Location = new System.Drawing.Point(384, 198);
this.bFormat.Name = "bFormat";
this.bFormat.Size = new System.Drawing.Size(22, 16);
this.bFormat.TabIndex = 12;
this.bFormat.Tag = "format";
this.bFormat.Text = "fx";
this.bFormat.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bFormat.Click += new System.EventHandler(this.bExpr_Click);
//
// FontCtl
//
this.Controls.Add(this.bFormat);
this.Controls.Add(this.bWrtMode);
this.Controls.Add(this.bVertical);
this.Controls.Add(this.bDirection);
this.Controls.Add(this.bAlignment);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.cbWritingMode);
this.Controls.Add(this.cbDirection);
this.Controls.Add(this.cbFormat);
this.Controls.Add(this.cbHorzAlign);
this.Controls.Add(this.cbVerticalAlign);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Name = "FontCtl";
this.Size = new System.Drawing.Size(456, 236);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
if (fFontSize)
{
try
{
if (!this.cbFontSize.Text.Trim().StartsWith("="))
DesignerUtility.ValidateSize(this.cbFontSize.Text, false, false);
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Invalid Font Size");
return false;
}
}
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
fHorzAlign = fFormat = fDirection = fWritingMode = fTextDecoration =
fColor = fVerticalAlign = fFontStyle = fFontWeight = fFontSize = fFontFamily = false;
}
public void ApplyChanges(XmlNode node)
{
if (_names != null)
{
node = _Draw.FindCreateNextInHierarchy(node, _names);
}
XmlNode sNode = _Draw.GetCreateNamedChildNode(node, "Style");
if (fFontStyle)
_Draw.SetElement(sNode, "FontStyle", cbFontStyle.Text);
if (fFontFamily)
_Draw.SetElement(sNode, "FontFamily", cbFontFamily.Text);
if (fFontWeight)
_Draw.SetElement(sNode, "FontWeight", cbFontWeight.Text);
if (fFontSize)
{
float size=10;
size = DesignXmlDraw.GetSize(cbFontSize.Text);
if (size <= 0)
{
size = DesignXmlDraw.GetSize(cbFontSize.Text+"pt"); // Try assuming pt
if (size <= 0) // still no good
size = 10; // just set default value
}
string rs = string.Format(NumberFormatInfo.InvariantInfo, "{0:0.#}pt", size);
_Draw.SetElement(sNode, "FontSize", rs); // force to string
}
if (fTextDecoration)
_Draw.SetElement(sNode, "TextDecoration", cbTextDecoration.Text);
if (fHorzAlign)
_Draw.SetElement(sNode, "TextAlign", cbHorzAlign.Text);
if (fVerticalAlign)
_Draw.SetElement(sNode, "VerticalAlign", cbVerticalAlign.Text);
if (fColor)
_Draw.SetElement(sNode, "Color", cbColor.Text);
if (fFormat)
{
if (cbFormat.Text.Length == 0) // Don't put out a format if no format value
_Draw.RemoveElement(sNode, "Format");
else
_Draw.SetElement(sNode, "Format", cbFormat.Text);
}
if (fDirection)
_Draw.SetElement(sNode, "Direction", cbDirection.Text);
if (fWritingMode)
_Draw.SetElement(sNode, "WritingMode", cbWritingMode.Text);
return;
}
private void bFont_Click(object sender, System.EventArgs e)
{
FontDialog fd = new FontDialog();
fd.ShowColor = true;
// STYLE
System.Drawing.FontStyle fs = 0;
if (cbFontStyle.Text == "Italic")
fs |= System.Drawing.FontStyle.Italic;
if (cbTextDecoration.Text == "Underline")
fs |= FontStyle.Underline;
else if (cbTextDecoration.Text == "LineThrough")
fs |= FontStyle.Strikeout;
// WEIGHT
switch (cbFontWeight.Text)
{
case "Bold":
case "Bolder":
case "500":
case "600":
case "700":
case "800":
case "900":
fs |= System.Drawing.FontStyle.Bold;
break;
default:
break;
}
float size=10;
size = DesignXmlDraw.GetSize(cbFontSize.Text);
if (size <= 0)
{
size = DesignXmlDraw.GetSize(cbFontSize.Text+"pt"); // Try assuming pt
if (size <= 0) // still no good
size = 10; // just set default value
}
Font drawFont = new Font(cbFontFamily.Text, size, fs); // si.FontSize already in points
fd.Font = drawFont;
fd.Color =
DesignerUtility.ColorFromHtml(cbColor.Text, System.Drawing.Color.Black);
try
{
DialogResult dr = fd.ShowDialog();
if (dr != DialogResult.OK)
{
drawFont.Dispose();
return;
}
// Apply all the font info
cbFontWeight.Text = fd.Font.Bold ? "Bold" : "Normal";
cbFontStyle.Text = fd.Font.Italic ? "Italic" : "Normal";
cbFontFamily.Text = fd.Font.FontFamily.Name;
cbFontSize.Text = fd.Font.Size.ToString() + "pt";
cbColor.Text = ColorTranslator.ToHtml(fd.Color);
if (fd.Font.Underline)
this.cbTextDecoration.Text = "Underline";
else if (fd.Font.Strikeout)
this.cbTextDecoration.Text = "LineThrough";
else
this.cbTextDecoration.Text = "None";
drawFont.Dispose();
}
finally
{
fd.Dispose();
}
return;
}
private void bColor_Click(object sender, System.EventArgs e)
{
ColorDialog cd = new ColorDialog();
cd.AnyColor = true;
cd.FullOpen = true;
cd.CustomColors = RdlDesigner.GetCustomColors();
cd.Color =
DesignerUtility.ColorFromHtml(cbColor.Text, System.Drawing.Color.Black);
try
{
if (cd.ShowDialog() != DialogResult.OK)
return;
RdlDesigner.SetCustomColors(cd.CustomColors);
if (sender == this.bColor)
cbColor.Text = ColorTranslator.ToHtml(cd.Color);
}
finally
{
cd.Dispose();
}
return;
}
private void cbFontFamily_TextChanged(object sender, System.EventArgs e)
{
fFontFamily = true;
}
private void cbFontSize_TextChanged(object sender, System.EventArgs e)
{
fFontSize = true;
}
private void cbFontStyle_TextChanged(object sender, System.EventArgs e)
{
fFontStyle = true;
}
private void cbFontWeight_TextChanged(object sender, System.EventArgs e)
{
fFontWeight = true;
}
private void cbColor_TextChanged(object sender, System.EventArgs e)
{
fColor = true;
}
private void cbTextDecoration_TextChanged(object sender, System.EventArgs e)
{
fTextDecoration = true;
}
private void cbHorzAlign_TextChanged(object sender, System.EventArgs e)
{
fHorzAlign = true;
}
private void cbVerticalAlign_TextChanged(object sender, System.EventArgs e)
{
fVerticalAlign = true;
}
private void cbDirection_TextChanged(object sender, System.EventArgs e)
{
fDirection = true;
}
private void cbWritingMode_TextChanged(object sender, System.EventArgs e)
{
fWritingMode = true;
}
private void cbFormat_TextChanged(object sender, System.EventArgs e)
{
fFormat = true;
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
bool bColor=false;
switch (b.Tag as string)
{
case "family":
c = cbFontFamily;
break;
case "style":
c = cbFontStyle;
break;
case "color":
c = cbColor;
bColor = true;
break;
case "size":
c = cbFontSize;
break;
case "weight":
c = cbFontWeight;
break;
case "decoration":
c = cbTextDecoration;
break;
case "halign":
c = cbHorzAlign;
break;
case "valign":
c = cbVerticalAlign;
break;
case "direction":
c = cbDirection;
break;
case "writing":
c = cbWritingMode;
break;
case "format":
c = cbFormat;
break;
}
if (c == null)
return;
XmlNode sNode = _ReportItems[0];
DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode, bColor);
try
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
c.Text = ee.Expression;
}
finally
{
ee.Dispose();
}
return;
}
}
}
| |
// Copyright (c) Valve Corporation, All rights reserved. ======================================================================================================
#if ( UNITY_EDITOR )
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEditor
{
internal class ValveShaderGUI : ShaderGUI
{
public enum BlendMode
{
Opaque,
AlphaTest,
AlphaBlend,
Glass,
Additive
// TODO: MaskedGlass that will require an additional grayscale texture to act as a standard alpha blend mask
}
public enum SpecularMode
{
None,
BlinnPhong,
Metallic
//Anisotropic
}
private static class Styles
{
public static GUIStyle optionsButton = "PaneOptions";
public static GUIContent uvSetLabel = new GUIContent("UV Set");
public static GUIContent[] uvSetOptions = new GUIContent[] { new GUIContent("UV channel 0"), new GUIContent("UV channel 1") };
public static GUIContent unlitText = new GUIContent( "Unlit", "" );
public static string emptyTootip = "";
public static GUIContent albedoText = new GUIContent("Albedo", "Albedo (RGB) and Transparency (A)");
public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff");
public static GUIContent specularMapText = new GUIContent("Specular", "Reflectance (RGB) and Gloss (A)");
public static GUIContent reflectanceMinText = new GUIContent( "Reflectance Min", "" );
public static GUIContent reflectanceMaxText = new GUIContent( "Reflectance Max", "" );
public static GUIContent metallicMapText = new GUIContent( "Metallic", "Metallic (R) and Gloss (A)" );
public static GUIContent smoothnessText = new GUIContent("Gloss", "");
public static GUIContent normalMapText = new GUIContent("Normal", "Normal Map");
//public static GUIContent heightMapText = new GUIContent("Height Map", "Height Map (G)");
public static GUIContent cubeMapScalarText = new GUIContent( "Cube Map Scalar", "" );
public static GUIContent occlusionText = new GUIContent("Occlusion", "Occlusion (G)");
public static GUIContent occlusionStrengthDirectDiffuseText = new GUIContent( "Occlusion Direct Diffuse", "" );
public static GUIContent occlusionStrengthDirectSpecularText = new GUIContent( "Occlusion Direct Specular", "" );
public static GUIContent occlusionStrengthIndirectDiffuseText = new GUIContent( "Occlusion Indirect Diffuse", "" );
public static GUIContent occlusionStrengthIndirectSpecularText = new GUIContent( "Occlusion Indirect Specular", "" );
public static GUIContent emissionText = new GUIContent( "Emission", "Emission (RGB)" );
public static GUIContent detailMaskText = new GUIContent("Detail Mask", "Mask for Secondary Maps (A)");
public static GUIContent detailAlbedoText = new GUIContent("Detail Albedo", "Detail Albedo (RGB) multiplied by 2");
public static GUIContent detailNormalMapText = new GUIContent("Detail Normal", "Detail Normal Map");
public static GUIContent receiveShadowsText = new GUIContent( "Receive Shadows", "" );
public static GUIContent renderBackfacesText = new GUIContent( "Render Backfaces", "" );
public static GUIContent overrideLightmapText = new GUIContent( "Override Lightmap", "Requires ValveOverrideLightmap.cs scrip on object" );
public static GUIContent worldAlignedTextureText = new GUIContent( "World Aligned Texture", "" );
public static GUIContent worldAlignedTextureSizeText = new GUIContent( "Size", "" );
public static GUIContent worldAlignedTextureNormalText = new GUIContent( "Normal", "" );
public static GUIContent worldAlignedTexturePositionText = new GUIContent( "World Position", "" );
public static string whiteSpaceString = " ";
public static string primaryMapsText = "Main Maps";
public static string secondaryMapsText = "Secondary Maps";
public static string renderingMode = "Rendering Mode";
public static string specularModeText = "Specular Mode";
public static GUIContent emissiveWarning = new GUIContent( "Emissive value is animated but the material has not been configured to support emissive. Please make sure the material itself has some amount of emissive." );
public static GUIContent emissiveColorWarning = new GUIContent ("Ensure emissive color is non-black for emission to have effect.");
public static readonly string[] blendNames = Enum.GetNames (typeof (BlendMode));
public static readonly string[] specularNames = Enum.GetNames( typeof( SpecularMode ) );
}
MaterialProperty unlit = null;
MaterialProperty blendMode = null;
MaterialProperty specularMode = null;
MaterialProperty albedoMap = null;
MaterialProperty albedoColor = null;
MaterialProperty alphaCutoff = null;
MaterialProperty specularMap = null;
MaterialProperty specularColor = null;
MaterialProperty reflectanceMin = null;
MaterialProperty reflectanceMax = null;
MaterialProperty metallicMap = null;
MaterialProperty metallic = null;
MaterialProperty smoothness = null;
MaterialProperty bumpScale = null;
MaterialProperty bumpMap = null;
MaterialProperty cubeMapScalar = null;
MaterialProperty occlusionStrength = null;
MaterialProperty occlusionMap = null;
MaterialProperty occlusionStrengthDirectDiffuse = null;
MaterialProperty occlusionStrengthDirectSpecular = null;
MaterialProperty occlusionStrengthIndirectDiffuse = null;
MaterialProperty occlusionStrengthIndirectSpecular = null;
//MaterialProperty heigtMapScale = null;
//MaterialProperty heightMap = null;
MaterialProperty emissionColorForRendering = null;
MaterialProperty emissionMap = null;
MaterialProperty detailMask = null;
MaterialProperty detailAlbedoMap = null;
MaterialProperty detailNormalMapScale = null;
MaterialProperty detailNormalMap = null;
MaterialProperty uvSetSecondary = null;
MaterialProperty receiveShadows = null;
MaterialProperty renderBackfaces = null;
MaterialProperty overrideLightmap = null;
MaterialProperty worldAlignedTexture = null;
MaterialProperty worldAlignedTextureSize = null;
MaterialProperty worldAlignedTextureNormal = null;
MaterialProperty worldAlignedTexturePosition = null;
MaterialEditor m_MaterialEditor;
ColorPickerHDRConfig m_ColorPickerHDRConfig = new ColorPickerHDRConfig(0f, 99f, 1/99f, 3f);
bool m_FirstTimeApply = true;
public void FindProperties (MaterialProperty[] props)
{
unlit = FindProperty( "g_bUnlit", props );
blendMode = FindProperty( "_Mode", props );
specularMode = FindProperty( "_SpecularMode", props );
albedoMap = FindProperty( "_MainTex", props );
albedoColor = FindProperty ("_Color", props);
alphaCutoff = FindProperty ("_Cutoff", props);
specularMap = FindProperty ("_SpecGlossMap", props, false);
specularColor = FindProperty ("_SpecColor", props, false);
reflectanceMin = FindProperty( "g_flReflectanceMin", props );
reflectanceMax = FindProperty( "g_flReflectanceMax", props );
metallicMap = FindProperty ("_MetallicGlossMap", props, false);
metallic = FindProperty ("_Metallic", props, false);
smoothness = FindProperty ("_Glossiness", props);
bumpScale = FindProperty ("_BumpScale", props);
bumpMap = FindProperty ("_BumpMap", props);
//heigtMapScale = FindProperty ("_Parallax", props);
//heightMap = FindProperty("_ParallaxMap", props);
cubeMapScalar = FindProperty( "g_flCubeMapScalar", props );
occlusionStrength = FindProperty ("_OcclusionStrength", props);
occlusionStrengthDirectDiffuse = FindProperty( "_OcclusionStrengthDirectDiffuse", props );
occlusionStrengthDirectSpecular = FindProperty( "_OcclusionStrengthDirectSpecular", props );
occlusionStrengthIndirectDiffuse = FindProperty( "_OcclusionStrengthIndirectDiffuse", props );
occlusionStrengthIndirectSpecular = FindProperty( "_OcclusionStrengthIndirectSpecular", props );
occlusionMap = FindProperty ("_OcclusionMap", props);
emissionColorForRendering = FindProperty ("_EmissionColor", props);
emissionMap = FindProperty ("_EmissionMap", props);
detailMask = FindProperty ("_DetailMask", props);
detailAlbedoMap = FindProperty ("_DetailAlbedoMap", props);
detailNormalMapScale = FindProperty ("_DetailNormalMapScale", props);
detailNormalMap = FindProperty ("_DetailNormalMap", props);
uvSetSecondary = FindProperty ("_UVSec", props);
receiveShadows = FindProperty( "g_bReceiveShadows", props );
renderBackfaces = FindProperty( "g_bRenderBackfaces", props );
overrideLightmap = FindProperty( "g_tOverrideLightmap", props );
worldAlignedTexture = FindProperty( "g_bWorldAlignedTexture", props, false );
worldAlignedTextureSize = FindProperty( "g_vWorldAlignedTextureSize", props, worldAlignedTexture != null );
worldAlignedTextureNormal = FindProperty( "g_vWorldAlignedTextureNormal", props, worldAlignedTexture != null );
worldAlignedTexturePosition = FindProperty( "g_vWorldAlignedTexturePosition", props, worldAlignedTexture != null );
}
public override void OnGUI (MaterialEditor materialEditor, MaterialProperty[] props)
{
FindProperties (props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly
m_MaterialEditor = materialEditor;
Material material = materialEditor.target as Material;
ShaderPropertiesGUI (material);
// Make sure that needed keywords are set up if we're switching some existing
// material to a standard shader.
if (m_FirstTimeApply)
{
SetMaterialKeywords (material);
m_FirstTimeApply = false;
}
}
public void Vector3GUI( GUIContent label, MaterialProperty materialProperty )
{
Vector4 v4 = materialProperty.vectorValue;
Vector3 v3 = EditorGUILayout.Vector3Field( label, new Vector3( v4.x, v4.y, v4.z ) );
materialProperty.vectorValue = new Vector4( v3.x, v3.y, v3.z, 0.0f );
}
public void ShaderPropertiesGUI (Material material)
{
// Use default labelWidth
EditorGUIUtility.labelWidth = 0f;
// Detect any changes to the material
EditorGUI.BeginChangeCheck();
{
m_MaterialEditor.ShaderProperty( unlit, Styles.unlitText.text );
bool bUnlit = ( unlit.floatValue != 0.0f );
BlendModePopup();
if ( !bUnlit )
{
SpecularModePopup();
}
if ( !bUnlit )
{
m_MaterialEditor.ShaderProperty( receiveShadows, Styles.receiveShadowsText.text );
}
m_MaterialEditor.ShaderProperty( renderBackfaces, Styles.renderBackfacesText.text );
EditorGUILayout.Space();
//GUILayout.Label( Styles.primaryMapsText, EditorStyles.boldLabel );
DoAlbedoArea( material );
if ( !bUnlit )
{
m_MaterialEditor.TexturePropertySingleLine( Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null );
DoSpecularMetallicArea( material );
m_MaterialEditor.TexturePropertySingleLine( Styles.occlusionText, occlusionMap, occlusionMap.textureValue != null ? occlusionStrength : null );
if ( occlusionMap.textureValue != null )
{
m_MaterialEditor.ShaderProperty( occlusionStrengthDirectDiffuse, Styles.occlusionStrengthDirectDiffuseText.text, 2 );
m_MaterialEditor.ShaderProperty( occlusionStrengthDirectSpecular, Styles.occlusionStrengthDirectSpecularText.text, 2 );
m_MaterialEditor.ShaderProperty( occlusionStrengthIndirectDiffuse, Styles.occlusionStrengthIndirectDiffuseText.text, 2 );
m_MaterialEditor.ShaderProperty( occlusionStrengthIndirectSpecular, Styles.occlusionStrengthIndirectSpecularText.text, 2 );
}
m_MaterialEditor.ShaderProperty( cubeMapScalar, Styles.cubeMapScalarText.text, 0 );
}
//m_MaterialEditor.TexturePropertySingleLine(Styles.heightMapText, heightMap, heightMap.textureValue != null ? heigtMapScale : null);
DoEmissionArea( material );
m_MaterialEditor.TexturePropertySingleLine( Styles.detailMaskText, detailMask );
if ( !bUnlit )
{
m_MaterialEditor.TexturePropertySingleLine( Styles.overrideLightmapText, overrideLightmap );
}
EditorGUI.BeginChangeCheck(); // !!! AV - This is from Unity's script. Can these Begin/End calls be nested like this?
m_MaterialEditor.TextureScaleOffsetProperty( albedoMap );
if ( EditorGUI.EndChangeCheck() )
{
emissionMap.textureScaleAndOffset = albedoMap.textureScaleAndOffset; // Apply the main texture scale and offset to the emission texture as well, for Enlighten's sake
}
if ( worldAlignedTexture != null )
{
m_MaterialEditor.ShaderProperty( worldAlignedTexture, Styles.worldAlignedTextureText.text );
if ( worldAlignedTexture.floatValue != 0.0f )
{
EditorGUI.indentLevel = 2;
Vector3GUI( Styles.worldAlignedTextureSizeText, worldAlignedTextureSize );
Vector3GUI( Styles.worldAlignedTextureNormalText, worldAlignedTextureNormal );
Vector3GUI( Styles.worldAlignedTexturePositionText, worldAlignedTexturePosition );
EditorGUI.indentLevel = 0;
}
}
EditorGUILayout.Space();
// Secondary properties
GUILayout.Label( Styles.secondaryMapsText, EditorStyles.boldLabel );
m_MaterialEditor.TexturePropertySingleLine( Styles.detailAlbedoText, detailAlbedoMap );
if ( !bUnlit )
{
m_MaterialEditor.TexturePropertySingleLine( Styles.detailNormalMapText, detailNormalMap, detailNormalMapScale );
}
m_MaterialEditor.TextureScaleOffsetProperty( detailAlbedoMap );
m_MaterialEditor.ShaderProperty( uvSetSecondary, Styles.uvSetLabel.text );
}
if ( EditorGUI.EndChangeCheck() )
{
foreach ( var obj in blendMode.targets )
{
MaterialChanged( ( Material )obj );
}
foreach ( var obj in specularMode.targets )
{
MaterialChanged( ( Material )obj );
}
}
}
public override void AssignNewShaderToMaterial (Material material, Shader oldShader, Shader newShader)
{
base.AssignNewShaderToMaterial( material, oldShader, newShader );
if ( oldShader == null )
return;
// Convert to vr_standard
if ( newShader.name.Equals( "Valve/vr_standard" ) )
{
List<string> unknownShaders = new List<string>();
ValveMenuTools.StandardToValveSingleMaterial( material, oldShader, newShader, false, unknownShaders );
}
// Legacy shaders
if ( !oldShader.name.Contains( "Legacy Shaders/" ) )
return;
BlendMode blendMode = BlendMode.Opaque;
if (oldShader.name.Contains("/Transparent/Cutout/"))
{
blendMode = BlendMode.AlphaTest;
}
else if (oldShader.name.Contains("/Transparent/"))
{
// NOTE: legacy shaders did not provide physically based transparency
// therefore Fade mode
blendMode = BlendMode.AlphaBlend;
}
material.SetFloat("_Mode", (float)blendMode);
MaterialChanged(material);
}
void BlendModePopup()
{
EditorGUI.showMixedValue = blendMode.hasMixedValue;
var mode = (BlendMode)blendMode.floatValue;
EditorGUI.BeginChangeCheck();
mode = (BlendMode)EditorGUILayout.Popup(Styles.renderingMode, (int)mode, Styles.blendNames);
if (EditorGUI.EndChangeCheck())
{
m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode");
blendMode.floatValue = (float)mode;
}
EditorGUI.showMixedValue = false;
}
void SpecularModePopup()
{
EditorGUI.showMixedValue = specularMode.hasMixedValue;
var mode = ( SpecularMode )specularMode.floatValue;
EditorGUI.BeginChangeCheck();
mode = ( SpecularMode )EditorGUILayout.Popup( Styles.specularModeText, ( int )mode, Styles.specularNames );
if ( EditorGUI.EndChangeCheck() )
{
m_MaterialEditor.RegisterPropertyChangeUndo( "Specular Mode" );
specularMode.floatValue = ( float )mode;
}
EditorGUI.showMixedValue = false;
}
void DoAlbedoArea(Material material)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor);
if (((BlendMode)material.GetFloat("_Mode") == BlendMode.AlphaTest))
{
m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel+1);
}
}
void DoEmissionArea(Material material)
{
float brightness = emissionColorForRendering.colorValue.maxColorComponent;
bool showHelpBox = !HasValidEmissiveKeyword(material);
bool showEmissionColorAndGIControls = brightness > 0.0f;
bool hadEmissionTexture = emissionMap.textureValue != null;
// Texture and HDR color controls
m_MaterialEditor.TexturePropertyWithHDRColor(Styles.emissionText, emissionMap, emissionColorForRendering, m_ColorPickerHDRConfig, false);
// If texture was assigned and color was black set color to white
if (emissionMap.textureValue != null && !hadEmissionTexture && brightness <= 0f)
emissionColorForRendering.colorValue = Color.white;
// Dynamic Lightmapping mode
if (showEmissionColorAndGIControls)
{
bool shouldEmissionBeEnabled = ShouldEmissionBeEnabled(emissionColorForRendering.colorValue);
using ( new EditorGUI.DisabledScope( !shouldEmissionBeEnabled ) )
{
m_MaterialEditor.LightmapEmissionProperty( MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1 );
}
}
if (showHelpBox)
{
EditorGUILayout.HelpBox(Styles.emissiveWarning.text, MessageType.Warning);
}
}
void DoSpecularMetallicArea( Material material )
{
SpecularMode specularMode = ( SpecularMode )material.GetInt( "_SpecularMode" );
if ( specularMode == SpecularMode.BlinnPhong )
{
if (specularMap.textureValue == null)
{
m_MaterialEditor.TexturePropertyTwoLines( Styles.specularMapText, specularMap, specularColor, Styles.smoothnessText, smoothness );
}
else
{
m_MaterialEditor.TexturePropertySingleLine( Styles.specularMapText, specularMap );
}
m_MaterialEditor.ShaderProperty( reflectanceMin, Styles.reflectanceMinText.text, 2 );
m_MaterialEditor.ShaderProperty( reflectanceMax, Styles.reflectanceMaxText.text, 2 );
}
else if ( specularMode == SpecularMode.Metallic )
{
if (metallicMap.textureValue == null)
m_MaterialEditor.TexturePropertyTwoLines(Styles.metallicMapText, metallicMap, metallic, Styles.smoothnessText, smoothness);
else
m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicMap);
}
}
public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode)
{
switch (blendMode)
{
case BlendMode.Opaque:
material.SetOverrideTag("RenderType", "");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.SetFloat( "_FogMultiplier", 1.0f );
material.DisableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = -1;
break;
case BlendMode.AlphaTest:
material.SetOverrideTag("RenderType", "TransparentCutout");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.SetFloat( "_FogMultiplier", 1.0f );
material.EnableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = 2450;
break;
case BlendMode.AlphaBlend:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.SetFloat( "_FogMultiplier", 1.0f );
material.DisableKeyword("_ALPHATEST_ON");
material.EnableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = 3000;
break;
case BlendMode.Glass:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.SetFloat( "_FogMultiplier", 1.0f );
material.DisableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = 3000;
break;
case BlendMode.Additive:
material.SetOverrideTag( "RenderType", "Transparent" );
material.SetInt( "_SrcBlend", ( int )UnityEngine.Rendering.BlendMode.One );
material.SetInt( "_DstBlend", ( int )UnityEngine.Rendering.BlendMode.One );
material.SetInt( "_ZWrite", 0 );
material.SetFloat( "_FogMultiplier", 0.0f );
material.DisableKeyword( "_ALPHATEST_ON" );
material.DisableKeyword( "_ALPHABLEND_ON" );
material.DisableKeyword( "_ALPHAPREMULTIPLY_ON" );
material.renderQueue = 3000;
break;
}
}
static bool ShouldEmissionBeEnabled (Color color)
{
return color.maxColorComponent > (0.1f / 255.0f);
}
static void SetMaterialKeywords(Material material)
{
// Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation
// (MaterialProperty value might come from renderer material property block)
SetKeyword (material, "_NORMALMAP", material.GetTexture ("_BumpMap") || material.GetTexture ("_DetailNormalMap"));
SpecularMode specularMode = ( SpecularMode )material.GetInt( "_SpecularMode" );
if ( specularMode == SpecularMode.BlinnPhong )
{
SetKeyword( material, "_SPECGLOSSMAP", material.GetTexture( "_SpecGlossMap" ) );
}
else if ( specularMode == SpecularMode.Metallic )
{
SetKeyword( material, "_METALLICGLOSSMAP", material.GetTexture( "_MetallicGlossMap" ) );
}
SetKeyword( material, "S_SPECULAR_NONE", specularMode == SpecularMode.None );
SetKeyword( material, "S_SPECULAR_BLINNPHONG", specularMode == SpecularMode.BlinnPhong );
SetKeyword( material, "S_SPECULAR_METALLIC", specularMode == SpecularMode.Metallic );
SetKeyword( material, "S_OCCLUSION", material.GetTexture("_OcclusionMap") );
SetKeyword( material, "_PARALLAXMAP", material.GetTexture("_ParallaxMap"));
SetKeyword( material, "_DETAIL_MULX2", material.GetTexture("_DetailAlbedoMap") || material.GetTexture("_DetailNormalMap"));
SetKeyword( material, "S_OVERRIDE_LIGHTMAP", material.GetTexture( "g_tOverrideLightmap" ) );
SetKeyword( material, "S_UNLIT", material.GetInt( "g_bUnlit" ) == 1 );
SetKeyword( material, "S_RECEIVE_SHADOWS", material.GetInt( "g_bReceiveShadows" ) == 1 );
SetKeyword( material, "S_WORLD_ALIGNED_TEXTURE", material.GetInt( "g_bWorldAlignedTexture" ) == 1 );
bool shouldEmissionBeEnabled = ShouldEmissionBeEnabled (material.GetColor("_EmissionColor"));
SetKeyword (material, "_EMISSION", shouldEmissionBeEnabled);
if ( material.IsKeywordEnabled( "S_RENDER_BACKFACES" ) )
{
material.SetInt( "_Cull", ( int )UnityEngine.Rendering.CullMode.Off );
}
else
{
material.SetInt( "_Cull", ( int )UnityEngine.Rendering.CullMode.Back );
}
// Setup lightmap emissive flags
MaterialGlobalIlluminationFlags flags = material.globalIlluminationFlags;
if ((flags & (MaterialGlobalIlluminationFlags.BakedEmissive | MaterialGlobalIlluminationFlags.RealtimeEmissive)) != 0)
{
flags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack;
if (!shouldEmissionBeEnabled)
flags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack;
material.globalIlluminationFlags = flags;
}
// Reflectance constants
float flReflectanceMin = material.GetFloat( "g_flReflectanceMin" );
float flReflectanceMax = material.GetFloat( "g_flReflectanceMax" );
material.SetFloat( "g_flReflectanceScale", Mathf.Max( flReflectanceMin, flReflectanceMax ) - flReflectanceMin );
material.SetFloat( "g_flReflectanceBias", flReflectanceMin );
// World aligned texture constants
Vector4 worldAlignedTextureNormal = material.GetVector( "g_vWorldAlignedTextureNormal" );
Vector3 normal = new Vector3( worldAlignedTextureNormal.x, worldAlignedTextureNormal.y, worldAlignedTextureNormal.z );
normal = ( normal.sqrMagnitude > 0.0f ) ? normal : Vector3.up;
Vector3 tangentU = Vector3.zero, tangentV = Vector3.zero;
Vector3.OrthoNormalize( ref normal, ref tangentU, ref tangentV );
material.SetVector( "g_vWorldAlignedNormalTangentU", new Vector4( tangentU.x, tangentU.y, tangentU.z, 0.0f ) );
material.SetVector( "g_vWorldAlignedNormalTangentV", new Vector4( tangentV.x, tangentV.y, tangentV.z, 0.0f ) );
// Static combo skips
if ( material.GetInt( "g_bUnlit" ) == 1 )
{
material.DisableKeyword( "_NORMALMAP" );
material.EnableKeyword( "S_SPECULAR_NONE" );
material.DisableKeyword( "S_SPECULAR_BLINNPHONG" );
material.DisableKeyword( "S_SPECULAR_METALLIC" );
material.DisableKeyword( "_METALLICGLOSSMAP" );
material.DisableKeyword( "_SPECGLOSSMAP" );
material.DisableKeyword( "S_OVERRIDE_LIGHTMAP" );
material.DisableKeyword( "S_RECEIVE_SHADOWS" );
}
}
bool HasValidEmissiveKeyword (Material material)
{
// Material animation might be out of sync with the material keyword.
// So if the emission support is disabled on the material, but the property blocks have a value that requires it, then we need to show a warning.
// (note: (Renderer MaterialPropertyBlock applies its values to emissionColorForRendering))
bool hasEmissionKeyword = material.IsKeywordEnabled ("_EMISSION");
if (!hasEmissionKeyword && ShouldEmissionBeEnabled (emissionColorForRendering.colorValue))
return false;
else
return true;
}
static void MaterialChanged(Material material)
{
SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode"));
SetMaterialKeywords(material);
}
static void SetKeyword(Material m, string keyword, bool state)
{
if (state)
m.EnableKeyword (keyword);
else
m.DisableKeyword (keyword);
}
}
} // namespace UnityEditor
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine.Experimental.Rendering.HDPipeline.Attributes;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[GenerateHLSL]
public enum FullScreenDebugMode
{
None,
// Lighting
MinLightingFullScreenDebug,
SSAO,
ScreenSpaceReflections,
ContactShadows,
ContactShadowsFade,
PreRefractionColorPyramid,
DepthPyramid,
FinalColorPyramid,
// Raytracing
LightCluster,
RaytracedAreaShadow,
IndirectDiffuse,
PrimaryVisibility,
MaxLightingFullScreenDebug,
// Rendering
MinRenderingFullScreenDebug,
MotionVectors,
NanTracker,
MaxRenderingFullScreenDebug,
//Material
MinMaterialFullScreenDebug,
ValidateDiffuseColor,
ValidateSpecularColor,
MaxMaterialFullScreenDebug
}
public class DebugDisplaySettings : IDebugData
{
static string k_PanelDisplayStats = "Display Stats";
static string k_PanelMaterials = "Material";
static string k_PanelLighting = "Lighting";
static string k_PanelRendering = "Rendering";
static string k_PanelDecals = "Decals";
DebugUI.Widget[] m_DebugDisplayStatsItems;
DebugUI.Widget[] m_DebugMaterialItems;
DebugUI.Widget[] m_DebugLightingItems;
DebugUI.Widget[] m_DebugRenderingItems;
DebugUI.Widget[] m_DebugDecalsItems;
static GUIContent[] s_LightingFullScreenDebugStrings = null;
static int[] s_LightingFullScreenDebugValues = null;
static GUIContent[] s_RenderingFullScreenDebugStrings = null;
static int[] s_RenderingFullScreenDebugValues = null;
static GUIContent[] s_MaterialFullScreenDebugStrings = null;
static int[] s_MaterialFullScreenDebugValues = null;
static GUIContent[] s_MsaaSamplesDebugStrings = null;
static int[] s_MsaaSamplesDebugValues = null;
static List<GUIContent> s_CameraNames = new List<GUIContent>();
static GUIContent[] s_CameraNamesStrings = null;
static int[] s_CameraNamesValues = null;
static bool needsRefreshingCameraFreezeList = true;
public class DebugData
{
public float debugOverlayRatio = 0.33f;
public FullScreenDebugMode fullScreenDebugMode = FullScreenDebugMode.None;
public float fullscreenDebugMip = 0.0f;
public int fullScreenContactShadowLightIndex = 0;
public bool showSSSampledColor = false;
public bool showContactShadowFade = false;
public MaterialDebugSettings materialDebugSettings = new MaterialDebugSettings();
public LightingDebugSettings lightingDebugSettings = new LightingDebugSettings();
public MipMapDebugSettings mipMapDebugSettings = new MipMapDebugSettings();
public ColorPickerDebugSettings colorPickerDebugSettings = new ColorPickerDebugSettings();
public FalseColorDebugSettings falseColorDebugSettings = new FalseColorDebugSettings();
public DecalsDebugSettings decalsDebugSettings = new DecalsDebugSettings();
public MSAASamples msaaSamples = MSAASamples.None;
// Raytracing
#if ENABLE_RAYTRACING
public bool countRays = false;
public bool showRaysPerFrame = false;
public Color raysPerFrameFontColor = Color.white;
#endif
public int debugCameraToFreeze = 0;
//saved enum fields for when repainting
public int lightingDebugModeEnumIndex;
public int lightingFulscreenDebugModeEnumIndex;
public int tileClusterDebugEnumIndex;
public int mipMapsEnumIndex;
public int engineEnumIndex;
public int attributesEnumIndex;
public int propertiesEnumIndex;
public int gBufferEnumIndex;
public int shadowDebugModeEnumIndex;
public int tileClusterDebugByCategoryEnumIndex;
public int lightVolumeDebugTypeEnumIndex;
public int renderingFulscreenDebugModeEnumIndex;
public int terrainTextureEnumIndex;
public int colorPickerDebugModeEnumIndex;
public int msaaSampleDebugModeEnumIndex;
public int debugCameraToFreezeEnumIndex;
}
DebugData m_Data;
public DebugData data { get => m_Data; }
public static GUIContent[] renderingFullScreenDebugStrings => s_RenderingFullScreenDebugStrings;
public static int[] renderingFullScreenDebugValues => s_RenderingFullScreenDebugValues;
public DebugDisplaySettings()
{
FillFullScreenDebugEnum(ref s_LightingFullScreenDebugStrings, ref s_LightingFullScreenDebugValues, FullScreenDebugMode.MinLightingFullScreenDebug, FullScreenDebugMode.MaxLightingFullScreenDebug);
FillFullScreenDebugEnum(ref s_RenderingFullScreenDebugStrings, ref s_RenderingFullScreenDebugValues, FullScreenDebugMode.MinRenderingFullScreenDebug, FullScreenDebugMode.MaxRenderingFullScreenDebug);
FillFullScreenDebugEnum(ref s_MaterialFullScreenDebugStrings, ref s_MaterialFullScreenDebugValues, FullScreenDebugMode.MinMaterialFullScreenDebug, FullScreenDebugMode.MaxMaterialFullScreenDebug);
s_MaterialFullScreenDebugStrings[(int)FullScreenDebugMode.ValidateDiffuseColor - ((int)FullScreenDebugMode.MinMaterialFullScreenDebug)] = new GUIContent("Diffuse Color");
s_MaterialFullScreenDebugStrings[(int)FullScreenDebugMode.ValidateSpecularColor - ((int)FullScreenDebugMode.MinMaterialFullScreenDebug)] = new GUIContent("Metal or SpecularColor");
s_MsaaSamplesDebugStrings = Enum.GetNames(typeof(MSAASamples))
.Select(t => new GUIContent(t))
.ToArray();
s_MsaaSamplesDebugValues = (int[])Enum.GetValues(typeof(MSAASamples));
m_Data = new DebugData();
}
Action IDebugData.GetReset() => () => m_Data = new DebugData();
public float[] GetDebugMaterialIndexes()
{
return data.materialDebugSettings.GetDebugMaterialIndexes();
}
public DebugLightFilterMode GetDebugLightFilterMode()
{
return data.lightingDebugSettings.debugLightFilterMode;
}
public DebugLightingMode GetDebugLightingMode()
{
return data.lightingDebugSettings.debugLightingMode;
}
public ShadowMapDebugMode GetDebugShadowMapMode()
{
return data.lightingDebugSettings.shadowDebugMode;
}
public DebugMipMapMode GetDebugMipMapMode()
{
return data.mipMapDebugSettings.debugMipMapMode;
}
public DebugMipMapModeTerrainTexture GetDebugMipMapModeTerrainTexture()
{
return data.mipMapDebugSettings.terrainTexture;
}
public ColorPickerDebugMode GetDebugColorPickerMode()
{
return data.colorPickerDebugSettings.colorPickerMode;
}
public bool IsCameraFreezeEnabled()
{
return data.debugCameraToFreeze != 0;
}
public string GetFrozenCameraName()
{
return s_CameraNamesStrings[data.debugCameraToFreeze].text;
}
public bool IsDebugDisplayEnabled()
{
return data.materialDebugSettings.IsDebugDisplayEnabled() || data.lightingDebugSettings.IsDebugDisplayEnabled() || data.mipMapDebugSettings.IsDebugDisplayEnabled() || IsDebugFullScreenEnabled();
}
public bool IsDebugDisplayRemovePostprocess()
{
// We want to keep post process when only the override more are enabled and none of the other
return data.materialDebugSettings.IsDebugDisplayEnabled() || data.lightingDebugSettings.IsDebugDisplayRemovePostprocess() || data.mipMapDebugSettings.IsDebugDisplayEnabled() || IsDebugFullScreenEnabled();
}
public bool IsDebugMaterialDisplayEnabled()
{
return data.materialDebugSettings.IsDebugDisplayEnabled();
}
public bool IsDebugFullScreenEnabled()
{
return data.fullScreenDebugMode != FullScreenDebugMode.None;
}
public bool IsMaterialValidationEnabled()
{
return (data.fullScreenDebugMode == FullScreenDebugMode.ValidateDiffuseColor) || (data.fullScreenDebugMode == FullScreenDebugMode.ValidateSpecularColor);
}
public bool IsDebugMipMapDisplayEnabled()
{
return data.mipMapDebugSettings.IsDebugDisplayEnabled();
}
private void DisableNonMaterialDebugSettings()
{
data.lightingDebugSettings.debugLightingMode = DebugLightingMode.None;
data.mipMapDebugSettings.debugMipMapMode = DebugMipMapMode.None;
}
public void SetDebugViewCommonMaterialProperty(MaterialSharedProperty value)
{
if (value != MaterialSharedProperty.None)
DisableNonMaterialDebugSettings();
data.materialDebugSettings.SetDebugViewCommonMaterialProperty(value);
}
public void SetDebugViewMaterial(int value)
{
if (value != 0)
DisableNonMaterialDebugSettings();
data.materialDebugSettings.SetDebugViewMaterial(value);
}
public void SetDebugViewEngine(int value)
{
if (value != 0)
DisableNonMaterialDebugSettings();
data.materialDebugSettings.SetDebugViewEngine(value);
}
public void SetDebugViewVarying(DebugViewVarying value)
{
if (value != 0)
DisableNonMaterialDebugSettings();
data.materialDebugSettings.SetDebugViewVarying(value);
}
public void SetDebugViewProperties(DebugViewProperties value)
{
if (value != 0)
DisableNonMaterialDebugSettings();
data.materialDebugSettings.SetDebugViewProperties(value);
}
public void SetDebugViewGBuffer(int value)
{
if (value != 0)
DisableNonMaterialDebugSettings();
data.materialDebugSettings.SetDebugViewGBuffer(value);
}
public void SetFullScreenDebugMode(FullScreenDebugMode value)
{
if (data.lightingDebugSettings.shadowDebugMode == ShadowMapDebugMode.SingleShadow)
value = 0;
data.fullScreenDebugMode = value;
}
public void SetShadowDebugMode(ShadowMapDebugMode value)
{
// When SingleShadow is enabled, we don't render full screen debug modes
if (value == ShadowMapDebugMode.SingleShadow)
data.fullScreenDebugMode = 0;
data.lightingDebugSettings.shadowDebugMode = value;
}
public void SetDebugLightFilterMode(DebugLightFilterMode value)
{
if (value != 0)
{
data.materialDebugSettings.DisableMaterialDebug();
data.mipMapDebugSettings.debugMipMapMode = DebugMipMapMode.None;
}
data.lightingDebugSettings.debugLightFilterMode = value;
}
public void SetDebugLightingMode(DebugLightingMode value)
{
if (value != 0)
{
data.materialDebugSettings.DisableMaterialDebug();
data.mipMapDebugSettings.debugMipMapMode = DebugMipMapMode.None;
}
data.lightingDebugSettings.debugLightingMode = value;
}
public void SetMipMapMode(DebugMipMapMode value)
{
if (value != 0)
{
data.materialDebugSettings.DisableMaterialDebug();
data.lightingDebugSettings.debugLightingMode = DebugLightingMode.None;
}
data.mipMapDebugSettings.debugMipMapMode = value;
}
public void UpdateMaterials()
{
if (data.mipMapDebugSettings.debugMipMapMode != 0)
Texture.SetStreamingTextureMaterialDebugProperties();
}
public void UpdateCameraFreezeOptions()
{
if (needsRefreshingCameraFreezeList)
{
s_CameraNames.Insert(0, new GUIContent("None"));
s_CameraNamesStrings = s_CameraNames.ToArray();
s_CameraNamesValues = Enumerable.Range(0, s_CameraNames.Count()).ToArray();
UnregisterDebugItems(k_PanelRendering, m_DebugRenderingItems);
RegisterRenderingDebug();
needsRefreshingCameraFreezeList = false;
}
}
public bool DebugNeedsExposure()
{
DebugLightingMode debugLighting = data.lightingDebugSettings.debugLightingMode;
DebugViewGbuffer debugGBuffer = (DebugViewGbuffer)data.materialDebugSettings.debugViewGBuffer;
return (debugLighting == DebugLightingMode.DiffuseLighting || debugLighting == DebugLightingMode.SpecularLighting || debugLighting == DebugLightingMode.VisualizeCascade) ||
(data.lightingDebugSettings.overrideAlbedo || data.lightingDebugSettings.overrideNormal || data.lightingDebugSettings.overrideSmoothness || data.lightingDebugSettings.overrideSpecularColor || data.lightingDebugSettings.overrideEmissiveColor) ||
(debugGBuffer == DebugViewGbuffer.BakeDiffuseLightingWithAlbedoPlusEmissive) ||
(data.fullScreenDebugMode == FullScreenDebugMode.PreRefractionColorPyramid || data.fullScreenDebugMode == FullScreenDebugMode.FinalColorPyramid || data.fullScreenDebugMode == FullScreenDebugMode.ScreenSpaceReflections || data.fullScreenDebugMode == FullScreenDebugMode.LightCluster || data.fullScreenDebugMode == FullScreenDebugMode.RaytracedAreaShadow || data.fullScreenDebugMode == FullScreenDebugMode.NanTracker);
}
void RegisterDisplayStatsDebug()
{
var list = new List<DebugUI.Widget>();
list.Add(new DebugUI.Value { displayName = "Frame Rate (fps)", getter = () => 1f / Time.smoothDeltaTime, refreshRate = 1f / 30f });
list.Add(new DebugUI.Value { displayName = "Frame Time (ms)", getter = () => Time.smoothDeltaTime * 1000f, refreshRate = 1f / 30f });
#if ENABLE_RAYTRACING
list.Add(new DebugUI.BoolField { displayName = "Count Rays", getter = () => data.countRays, setter = value => data.countRays = value, onValueChanged = RefreshDisplayStatsDebug });
if (data.countRays)
{
list.Add(new DebugUI.Value { displayName = "AO (MRays/s)", getter = () => ((float)(RenderPipelineManager.currentPipeline as HDRenderPipeline).GetRaysPerFrame(RayCountManager.RayCountValues.AmbientOcclusion)) / 1e6f, refreshRate = 1f / 30f });
list.Add(new DebugUI.Value { displayName = "Reflection (MRays/s)", getter = () => ((float)(RenderPipelineManager.currentPipeline as HDRenderPipeline).GetRaysPerFrame(RayCountManager.RayCountValues.Reflection)) / 1e6f, refreshRate = 1f / 30f });
list.Add(new DebugUI.Value { displayName = "Area Shadow (MRays/s)", getter = () => ((float)(RenderPipelineManager.currentPipeline as HDRenderPipeline).GetRaysPerFrame(RayCountManager.RayCountValues.AreaShadow)) / 1e6f, refreshRate = 1f / 30f });
list.Add(new DebugUI.Value { displayName = "Total (MRays/s)", getter = () => ((float)(RenderPipelineManager.currentPipeline as HDRenderPipeline).GetRaysPerFrame(RayCountManager.RayCountValues.Total)) / 1e6f, refreshRate = 1f / 30f });
list.Add(new DebugUI.BoolField { displayName = "Display Ray Count", getter = () => data.showRaysPerFrame, setter = value => data.showRaysPerFrame = value, onValueChanged = RefreshDisplayStatsDebug });
list.Add(new DebugUI.ColorField { displayName = "Ray Count Font Color", getter = () => data.raysPerFrameFontColor, setter = value => data.raysPerFrameFontColor = value });
}
#endif
m_DebugDisplayStatsItems = list.ToArray();
var panel = DebugManager.instance.GetPanel(k_PanelDisplayStats, true);
panel.flags = DebugUI.Flags.RuntimeOnly;
panel.children.Add(m_DebugDisplayStatsItems);
}
public void RegisterMaterialDebug()
{
var list = new List<DebugUI.Widget>();
list.Add( new DebugUI.EnumField { displayName = "Common Material Property", getter = () => (int)data.materialDebugSettings.debugViewMaterialCommonValue, setter = value => SetDebugViewCommonMaterialProperty((MaterialSharedProperty)value), autoEnum = typeof(MaterialSharedProperty), getIndex = () => (int)data.materialDebugSettings.debugViewMaterialCommonValue, setIndex = value => data.materialDebugSettings.debugViewMaterialCommonValue = (MaterialSharedProperty)value});
list.Add( new DebugUI.EnumField { displayName = "Material", getter = () => (data.materialDebugSettings.debugViewMaterial[0]) == 0 ? 0 : data.materialDebugSettings.debugViewMaterial[1], setter = value => SetDebugViewMaterial(value), enumNames = MaterialDebugSettings.debugViewMaterialStrings, enumValues = MaterialDebugSettings.debugViewMaterialValues, getIndex = () => data.materialDebugSettings.materialEnumIndex, setIndex = value => data.materialDebugSettings.materialEnumIndex = value});
list.Add( new DebugUI.EnumField { displayName = "Engine", getter = () => data.materialDebugSettings.debugViewEngine, setter = value => SetDebugViewEngine(value), enumNames = MaterialDebugSettings.debugViewEngineStrings, enumValues = MaterialDebugSettings.debugViewEngineValues, getIndex = () => data.engineEnumIndex, setIndex = value => data.engineEnumIndex = value });
list.Add( new DebugUI.EnumField { displayName = "Attributes", getter = () => (int)data.materialDebugSettings.debugViewVarying, setter = value => SetDebugViewVarying((DebugViewVarying)value), autoEnum = typeof(DebugViewVarying), getIndex = () => data.attributesEnumIndex, setIndex = value => data.attributesEnumIndex = value });
list.Add( new DebugUI.EnumField { displayName = "Properties", getter = () => (int)data.materialDebugSettings.debugViewProperties, setter = value => SetDebugViewProperties((DebugViewProperties)value), autoEnum = typeof(DebugViewProperties), getIndex = () => data.propertiesEnumIndex, setIndex = value => data.propertiesEnumIndex = value });
list.Add( new DebugUI.EnumField { displayName = "GBuffer", getter = () => data.materialDebugSettings.debugViewGBuffer, setter = value => SetDebugViewGBuffer(value), enumNames = MaterialDebugSettings.debugViewMaterialGBufferStrings, enumValues = MaterialDebugSettings.debugViewMaterialGBufferValues, getIndex = () => data.gBufferEnumIndex, setIndex = value => data.gBufferEnumIndex = value });
list.Add( new DebugUI.EnumField { displayName = "Material validator", getter = () => (int)data.fullScreenDebugMode, setter = value => SetFullScreenDebugMode((FullScreenDebugMode)value), enumNames = s_MaterialFullScreenDebugStrings, enumValues = s_MaterialFullScreenDebugValues, onValueChanged = RefreshMaterialDebug, getIndex = () => data.lightingFulscreenDebugModeEnumIndex, setIndex = value => data.lightingFulscreenDebugModeEnumIndex = value });
if (data.fullScreenDebugMode == FullScreenDebugMode.ValidateDiffuseColor || data.fullScreenDebugMode == FullScreenDebugMode.ValidateSpecularColor)
{
list.Add(new DebugUI.Container
{
children =
{
new DebugUI.ColorField { displayName = "Too High Color", getter = () => data.materialDebugSettings.materialValidateHighColor, setter = value => data.materialDebugSettings.materialValidateHighColor = value, showAlpha = false, hdr = true },
new DebugUI.ColorField { displayName = "Too Low Color", getter = () => data.materialDebugSettings.materialValidateLowColor, setter = value => data.materialDebugSettings.materialValidateLowColor = value, showAlpha = false, hdr = true },
new DebugUI.ColorField { displayName = "Not True Metal Color", getter = () => data.materialDebugSettings.materialValidateTrueMetalColor, setter = value => data.materialDebugSettings.materialValidateTrueMetalColor = value, showAlpha = false, hdr = true },
new DebugUI.BoolField { displayName = "True Metals", getter = () => data.materialDebugSettings.materialValidateTrueMetal, setter = (v) => data.materialDebugSettings.materialValidateTrueMetal = v },
}
});
}
m_DebugMaterialItems = list.ToArray();
var panel = DebugManager.instance.GetPanel(k_PanelMaterials, true);
panel.children.Add(m_DebugMaterialItems);
}
void RefreshDisplayStatsDebug<T>(DebugUI.Field<T> field, T value)
{
UnregisterDebugItems(k_PanelDisplayStats, m_DebugDisplayStatsItems);
RegisterDisplayStatsDebug();
}
// For now we just rebuild the lighting panel if needed, but ultimately it could be done in a better way
void RefreshLightingDebug<T>(DebugUI.Field<T> field, T value)
{
UnregisterDebugItems(k_PanelLighting, m_DebugLightingItems);
RegisterLightingDebug();
}
void RefreshDecalsDebug<T>(DebugUI.Field<T> field, T value)
{
UnregisterDebugItems(k_PanelDecals, m_DebugDecalsItems);
RegisterDecalsDebug();
}
void RefreshRenderingDebug<T>(DebugUI.Field<T> field, T value)
{
UnregisterDebugItems(k_PanelRendering, m_DebugRenderingItems);
RegisterRenderingDebug();
}
void RefreshMaterialDebug<T>(DebugUI.Field<T> field, T value)
{
UnregisterDebugItems(k_PanelMaterials, m_DebugMaterialItems);
RegisterMaterialDebug();
}
public void RegisterLightingDebug()
{
var list = new List<DebugUI.Widget>();
list.Add(new DebugUI.Foldout
{
displayName = "Show Light By Type",
children = {
new DebugUI.BoolField { displayName = "Show Directional Lights", getter = () => data.lightingDebugSettings.showDirectionalLight, setter = value => data.lightingDebugSettings.showDirectionalLight = value },
new DebugUI.BoolField { displayName = "Show Punctual Lights", getter = () => data.lightingDebugSettings.showPunctualLight, setter = value => data.lightingDebugSettings.showPunctualLight = value },
new DebugUI.BoolField { displayName = "Show Area Lights", getter = () => data.lightingDebugSettings.showAreaLight, setter = value => data.lightingDebugSettings.showAreaLight = value },
new DebugUI.BoolField { displayName = "Show Reflection Probe", getter = () => data.lightingDebugSettings.showReflectionProbe, setter = value => data.lightingDebugSettings.showReflectionProbe = value },
}
});
list.Add(new DebugUI.EnumField { displayName = "Shadow Debug Mode", getter = () => (int)data.lightingDebugSettings.shadowDebugMode, setter = value => SetShadowDebugMode((ShadowMapDebugMode)value), autoEnum = typeof(ShadowMapDebugMode), onValueChanged = RefreshLightingDebug, getIndex = () => data.shadowDebugModeEnumIndex, setIndex = value => data.shadowDebugModeEnumIndex = value });
if (data.lightingDebugSettings.shadowDebugMode == ShadowMapDebugMode.VisualizeShadowMap || data.lightingDebugSettings.shadowDebugMode == ShadowMapDebugMode.SingleShadow)
{
var container = new DebugUI.Container();
container.children.Add(new DebugUI.BoolField { displayName = "Use Selection", getter = () => data.lightingDebugSettings.shadowDebugUseSelection, setter = value => data.lightingDebugSettings.shadowDebugUseSelection = value, flags = DebugUI.Flags.EditorOnly, onValueChanged = RefreshLightingDebug });
if (!data.lightingDebugSettings.shadowDebugUseSelection)
container.children.Add(new DebugUI.UIntField { displayName = "Shadow Map Index", getter = () => data.lightingDebugSettings.shadowMapIndex, setter = value => data.lightingDebugSettings.shadowMapIndex = value, min = () => 0u, max = () => (uint)(RenderPipelineManager.currentPipeline as HDRenderPipeline).GetCurrentShadowCount() - 1u });
list.Add(container);
}
list.Add(new DebugUI.FloatField
{
displayName = "Global Shadow Scale Factor",
getter = () => data.lightingDebugSettings.shadowResolutionScaleFactor,
setter = (v) => data.lightingDebugSettings.shadowResolutionScaleFactor = v,
min = () => 0.01f,
max = () => 4.0f,
});
list.Add(new DebugUI.BoolField{
displayName = "Clear Shadow atlas",
getter = () => data.lightingDebugSettings.clearShadowAtlas,
setter = (v) => data.lightingDebugSettings.clearShadowAtlas = v
});
list.Add(new DebugUI.FloatField { displayName = "Shadow Range Min Value", getter = () => data.lightingDebugSettings.shadowMinValue, setter = value => data.lightingDebugSettings.shadowMinValue = value });
list.Add(new DebugUI.FloatField { displayName = "Shadow Range Max Value", getter = () => data.lightingDebugSettings.shadowMaxValue, setter = value => data.lightingDebugSettings.shadowMaxValue = value });
list.Add(new DebugUI.EnumField { displayName = "Lighting Debug Mode", getter = () => (int)data.lightingDebugSettings.debugLightingMode, setter = value => SetDebugLightingMode((DebugLightingMode)value), autoEnum = typeof(DebugLightingMode), onValueChanged = RefreshLightingDebug, getIndex = () => data.lightingDebugModeEnumIndex, setIndex = value => data.lightingDebugModeEnumIndex = value });
list.Add(new DebugUI.BitField { displayName = "Light Hierarchy Debug Mode", getter = () => data.lightingDebugSettings.debugLightFilterMode, setter = value => SetDebugLightFilterMode((DebugLightFilterMode)value), enumType = typeof(DebugLightFilterMode), onValueChanged = RefreshLightingDebug, });
list.Add(new DebugUI.EnumField { displayName = "Fullscreen Debug Mode", getter = () => (int)data.fullScreenDebugMode, setter = value => SetFullScreenDebugMode((FullScreenDebugMode)value), enumNames = s_LightingFullScreenDebugStrings, enumValues = s_LightingFullScreenDebugValues, onValueChanged = RefreshLightingDebug, getIndex = () => data.lightingFulscreenDebugModeEnumIndex, setIndex = value => data.lightingFulscreenDebugModeEnumIndex = value });
switch (data.fullScreenDebugMode)
{
case FullScreenDebugMode.PreRefractionColorPyramid:
case FullScreenDebugMode.FinalColorPyramid:
case FullScreenDebugMode.DepthPyramid:
{
list.Add(new DebugUI.Container
{
children =
{
new DebugUI.UIntField
{
displayName = "Fullscreen Debug Mip",
getter = () =>
{
int id;
switch (data.fullScreenDebugMode)
{
case FullScreenDebugMode.FinalColorPyramid:
case FullScreenDebugMode.PreRefractionColorPyramid:
id = HDShaderIDs._ColorPyramidScale;
break;
default:
id = HDShaderIDs._DepthPyramidScale;
break;
}
var size = Shader.GetGlobalVector(id);
float lodCount = size.z;
return (uint)(data.fullscreenDebugMip * lodCount);
},
setter = value =>
{
int id;
switch (data.fullScreenDebugMode)
{
case FullScreenDebugMode.FinalColorPyramid:
case FullScreenDebugMode.PreRefractionColorPyramid:
id = HDShaderIDs._ColorPyramidScale;
break;
default:
id = HDShaderIDs._DepthPyramidScale;
break;
}
var size = Shader.GetGlobalVector(id);
float lodCount = size.z;
data.fullscreenDebugMip = (float)Convert.ChangeType(value, typeof(float)) / lodCount;
},
min = () => 0u,
max = () =>
{
int id;
switch (data.fullScreenDebugMode)
{
case FullScreenDebugMode.FinalColorPyramid:
case FullScreenDebugMode.PreRefractionColorPyramid:
id = HDShaderIDs._ColorPyramidScale;
break;
default:
id = HDShaderIDs._DepthPyramidScale;
break;
}
var size = Shader.GetGlobalVector(id);
float lodCount = size.z;
return (uint)lodCount;
}
}
}
});
break;
}
case FullScreenDebugMode.ContactShadows:
list.Add(new DebugUI.Container
{
children =
{
new DebugUI.IntField
{
displayName = "Light Index",
getter = () =>
{
return data.fullScreenContactShadowLightIndex;
},
setter = value =>
{
data.fullScreenContactShadowLightIndex = value;
},
min = () => -1, // -1 will display all contact shadow
max = () => LightDefinitions.s_LightListMaxPrunedEntries - 1
},
}
});
break;
default:
data.fullscreenDebugMip = 0;
break;
}
list.Add(new DebugUI.BoolField { displayName = "Override Smoothness", getter = () => data.lightingDebugSettings.overrideSmoothness, setter = value => data.lightingDebugSettings.overrideSmoothness = value, onValueChanged = RefreshLightingDebug });
if (data.lightingDebugSettings.overrideSmoothness)
{
list.Add(new DebugUI.Container
{
children =
{
new DebugUI.FloatField { displayName = "Smoothness", getter = () => data.lightingDebugSettings.overrideSmoothnessValue, setter = value => data.lightingDebugSettings.overrideSmoothnessValue = value, min = () => 0f, max = () => 1f, incStep = 0.025f }
}
});
}
list.Add(new DebugUI.BoolField { displayName = "Override Albedo", getter = () => data.lightingDebugSettings.overrideAlbedo, setter = value => data.lightingDebugSettings.overrideAlbedo = value, onValueChanged = RefreshLightingDebug });
if (data.lightingDebugSettings.overrideAlbedo)
{
list.Add(new DebugUI.Container
{
children =
{
new DebugUI.ColorField { displayName = "Albedo", getter = () => data.lightingDebugSettings.overrideAlbedoValue, setter = value => data.lightingDebugSettings.overrideAlbedoValue = value, showAlpha = false, hdr = false }
}
});
}
list.Add(new DebugUI.BoolField { displayName = "Override Normal", getter = () => data.lightingDebugSettings.overrideNormal, setter = value => data.lightingDebugSettings.overrideNormal = value });
list.Add(new DebugUI.BoolField { displayName = "Override Specular Color", getter = () => data.lightingDebugSettings.overrideSpecularColor, setter = value => data.lightingDebugSettings.overrideSpecularColor = value, onValueChanged = RefreshLightingDebug });
if (data.lightingDebugSettings.overrideSpecularColor)
{
list.Add(new DebugUI.Container
{
children =
{
new DebugUI.ColorField { displayName = "Specular Color", getter = () => data.lightingDebugSettings.overrideSpecularColorValue, setter = value => data.lightingDebugSettings.overrideSpecularColorValue = value, showAlpha = false, hdr = false }
}
});
}
list.Add(new DebugUI.BoolField { displayName = "Override Emissive Color", getter = () => data.lightingDebugSettings.overrideEmissiveColor, setter = value => data.lightingDebugSettings.overrideEmissiveColor = value, onValueChanged = RefreshLightingDebug });
if (data.lightingDebugSettings.overrideEmissiveColor)
{
list.Add(new DebugUI.Container
{
children =
{
new DebugUI.ColorField { displayName = "Emissive Color", getter = () => data.lightingDebugSettings.overrideEmissiveColorValue, setter = value => data.lightingDebugSettings.overrideEmissiveColorValue = value, showAlpha = false, hdr = true }
}
});
}
list.Add(new DebugUI.EnumField { displayName = "Tile/Cluster Debug", getter = () => (int)data.lightingDebugSettings.tileClusterDebug, setter = value => data.lightingDebugSettings.tileClusterDebug = (LightLoop.TileClusterDebug)value, autoEnum = typeof(LightLoop.TileClusterDebug), onValueChanged = RefreshLightingDebug, getIndex = () => data.tileClusterDebugEnumIndex, setIndex = value => data.tileClusterDebugEnumIndex = value });
if (data.lightingDebugSettings.tileClusterDebug != LightLoop.TileClusterDebug.None && data.lightingDebugSettings.tileClusterDebug != LightLoop.TileClusterDebug.MaterialFeatureVariants)
{
list.Add(new DebugUI.Container
{
children =
{
new DebugUI.EnumField { displayName = "Tile/Cluster Debug By Category", getter = () => (int)data.lightingDebugSettings.tileClusterDebugByCategory, setter = value => data.lightingDebugSettings.tileClusterDebugByCategory = (LightLoop.TileClusterCategoryDebug)value, autoEnum = typeof(LightLoop.TileClusterCategoryDebug), getIndex = () => data.tileClusterDebugByCategoryEnumIndex, setIndex = value => data.tileClusterDebugByCategoryEnumIndex = value }
}
});
}
list.Add(new DebugUI.BoolField { displayName = "Display Sky Reflection", getter = () => data.lightingDebugSettings.displaySkyReflection, setter = value => data.lightingDebugSettings.displaySkyReflection = value, onValueChanged = RefreshLightingDebug });
if (data.lightingDebugSettings.displaySkyReflection)
{
list.Add(new DebugUI.Container
{
children =
{
new DebugUI.FloatField { displayName = "Sky Reflection Mipmap", getter = () => data.lightingDebugSettings.skyReflectionMipmap, setter = value => data.lightingDebugSettings.skyReflectionMipmap = value, min = () => 0f, max = () => 1f, incStep = 0.05f }
}
});
}
list.Add(new DebugUI.BoolField { displayName = "Display Light Volumes", getter = () => data.lightingDebugSettings.displayLightVolumes, setter = value => data.lightingDebugSettings.displayLightVolumes = value, onValueChanged = RefreshLightingDebug });
if (data.lightingDebugSettings.displayLightVolumes)
{
list.Add(new DebugUI.Container
{
children =
{
new DebugUI.EnumField { displayName = "Light Volume Debug Type", getter = () => (int)data.lightingDebugSettings.lightVolumeDebugByCategory, setter = value => data.lightingDebugSettings.lightVolumeDebugByCategory = (LightLoop.LightVolumeDebug)value, autoEnum = typeof(LightLoop.LightVolumeDebug), getIndex = () => data.lightVolumeDebugTypeEnumIndex, setIndex = value => data.lightVolumeDebugTypeEnumIndex = value },
new DebugUI.UIntField { displayName = "Max Debug Light Count", getter = () => (uint)data.lightingDebugSettings.maxDebugLightCount, setter = value => data.lightingDebugSettings.maxDebugLightCount = value, min = () => 0, max = () => 24, incStep = 1 }
}
});
}
if (DebugNeedsExposure())
list.Add(new DebugUI.FloatField { displayName = "Debug Exposure", getter = () => data.lightingDebugSettings.debugExposure, setter = value => data.lightingDebugSettings.debugExposure = value });
m_DebugLightingItems = list.ToArray();
var panel = DebugManager.instance.GetPanel(k_PanelLighting, true);
panel.children.Add(m_DebugLightingItems);
}
public void RegisterRenderingDebug()
{
var widgetList = new List<DebugUI.Widget>();
widgetList.AddRange(new DebugUI.Widget[]
{
new DebugUI.EnumField { displayName = "Fullscreen Debug Mode", getter = () => (int)data.fullScreenDebugMode, setter = value => data.fullScreenDebugMode = (FullScreenDebugMode)value, enumNames = s_RenderingFullScreenDebugStrings, enumValues = s_RenderingFullScreenDebugValues, getIndex = () => data.renderingFulscreenDebugModeEnumIndex, setIndex = value => data.renderingFulscreenDebugModeEnumIndex = value },
new DebugUI.EnumField { displayName = "MipMaps", getter = () => (int)data.mipMapDebugSettings.debugMipMapMode, setter = value => SetMipMapMode((DebugMipMapMode)value), autoEnum = typeof(DebugMipMapMode), onValueChanged = RefreshRenderingDebug, getIndex = () => data.mipMapsEnumIndex, setIndex = value => data.mipMapsEnumIndex = value },
});
if (data.mipMapDebugSettings.debugMipMapMode != DebugMipMapMode.None)
{
widgetList.Add(new DebugUI.Container
{
children =
{
new DebugUI.EnumField { displayName = "Terrain Texture", getter = ()=>(int)data.mipMapDebugSettings.terrainTexture, setter = value => data.mipMapDebugSettings.terrainTexture = (DebugMipMapModeTerrainTexture)value, autoEnum = typeof(DebugMipMapModeTerrainTexture), getIndex = () => data.terrainTextureEnumIndex, setIndex = value => data.terrainTextureEnumIndex = value }
}
});
}
widgetList.AddRange(new []
{
new DebugUI.Container
{
displayName = "Color Picker",
flags = DebugUI.Flags.EditorOnly,
children =
{
new DebugUI.EnumField { displayName = "Debug Mode", getter = () => (int)data.colorPickerDebugSettings.colorPickerMode, setter = value => data.colorPickerDebugSettings.colorPickerMode = (ColorPickerDebugMode)value, autoEnum = typeof(ColorPickerDebugMode), getIndex = () => data.colorPickerDebugModeEnumIndex, setIndex = value => data.colorPickerDebugModeEnumIndex = value },
new DebugUI.ColorField { displayName = "Font Color", flags = DebugUI.Flags.EditorOnly, getter = () => data.colorPickerDebugSettings.fontColor, setter = value => data.colorPickerDebugSettings.fontColor = value }
}
}
});
widgetList.Add(new DebugUI.BoolField { displayName = "False Color Mode", getter = () => data.falseColorDebugSettings.falseColor, setter = value => data.falseColorDebugSettings.falseColor = value, onValueChanged = RefreshRenderingDebug });
if (data.falseColorDebugSettings.falseColor)
{
widgetList.Add(new DebugUI.Container{
flags = DebugUI.Flags.EditorOnly,
children =
{
new DebugUI.FloatField { displayName = "Range Threshold 0", getter = () => data.falseColorDebugSettings.colorThreshold0, setter = value => data.falseColorDebugSettings.colorThreshold0 = Mathf.Min(value, data.falseColorDebugSettings.colorThreshold1) },
new DebugUI.FloatField { displayName = "Range Threshold 1", getter = () => data.falseColorDebugSettings.colorThreshold1, setter = value => data.falseColorDebugSettings.colorThreshold1 = Mathf.Clamp(value, data.falseColorDebugSettings.colorThreshold0, data.falseColorDebugSettings.colorThreshold2) },
new DebugUI.FloatField { displayName = "Range Threshold 2", getter = () => data.falseColorDebugSettings.colorThreshold2, setter = value => data.falseColorDebugSettings.colorThreshold2 = Mathf.Clamp(value, data.falseColorDebugSettings.colorThreshold1, data.falseColorDebugSettings.colorThreshold3) },
new DebugUI.FloatField { displayName = "Range Threshold 3", getter = () => data.falseColorDebugSettings.colorThreshold3, setter = value => data.falseColorDebugSettings.colorThreshold3 = Mathf.Max(value, data.falseColorDebugSettings.colorThreshold2) },
}
});
}
widgetList.AddRange(new DebugUI.Widget[]
{
new DebugUI.EnumField { displayName = "MSAA Samples", getter = () => (int)data.msaaSamples, setter = value => data.msaaSamples = (MSAASamples)value, enumNames = s_MsaaSamplesDebugStrings, enumValues = s_MsaaSamplesDebugValues, getIndex = () => data.msaaSampleDebugModeEnumIndex, setIndex = value => data.msaaSampleDebugModeEnumIndex = value },
});
widgetList.AddRange(new DebugUI.Widget[]
{
new DebugUI.EnumField { displayName = "Freeze Camera for culling", getter = () => data.debugCameraToFreeze, setter = value => data.debugCameraToFreeze = value, enumNames = s_CameraNamesStrings, enumValues = s_CameraNamesValues, getIndex = () => data.debugCameraToFreezeEnumIndex, setIndex = value => data.debugCameraToFreezeEnumIndex = value },
});
m_DebugRenderingItems = widgetList.ToArray();
var panel = DebugManager.instance.GetPanel(k_PanelRendering, true);
panel.children.Add(m_DebugRenderingItems);
}
public void RegisterDecalsDebug()
{
m_DebugDecalsItems = new DebugUI.Widget[]
{
new DebugUI.BoolField { displayName = "Display atlas", getter = () => data.decalsDebugSettings.displayAtlas, setter = value => data.decalsDebugSettings.displayAtlas = value},
new DebugUI.UIntField { displayName = "Mip Level", getter = () => data.decalsDebugSettings.mipLevel, setter = value => data.decalsDebugSettings.mipLevel = value, min = () => 0u, max = () => (uint)(RenderPipelineManager.currentPipeline as HDRenderPipeline).GetDecalAtlasMipCount() }
};
var panel = DebugManager.instance.GetPanel(k_PanelDecals, true);
panel.children.Add(m_DebugDecalsItems);
}
public void RegisterDebug()
{
RegisterDecalsDebug();
RegisterDisplayStatsDebug();
RegisterMaterialDebug();
RegisterLightingDebug();
RegisterRenderingDebug();
DebugManager.instance.RegisterData(this);
}
public void UnregisterDebug()
{
UnregisterDebugItems(k_PanelDecals, m_DebugDecalsItems);
UnregisterDebugItems(k_PanelDisplayStats, m_DebugDisplayStatsItems);
UnregisterDebugItems(k_PanelMaterials, m_DebugMaterialItems);
UnregisterDebugItems(k_PanelLighting, m_DebugLightingItems);
UnregisterDebugItems(k_PanelRendering, m_DebugRenderingItems);
DebugManager.instance.UnregisterData(this);
}
void UnregisterDebugItems(string panelName, DebugUI.Widget[] items)
{
var panel = DebugManager.instance.GetPanel(panelName);
if (panel != null)
panel.children.Remove(items);
}
void FillFullScreenDebugEnum(ref GUIContent[] strings, ref int[] values, FullScreenDebugMode min, FullScreenDebugMode max)
{
int count = max - min - 1;
strings = new GUIContent[count + 1];
values = new int[count + 1];
strings[0] = new GUIContent(FullScreenDebugMode.None.ToString());
values[0] = (int)FullScreenDebugMode.None;
int index = 1;
for (int i = (int)min + 1; i < (int)max; ++i)
{
strings[index] = new GUIContent(((FullScreenDebugMode)i).ToString());
values[index] = i;
index++;
}
}
static string FormatVector(Vector3 v)
{
return string.Format("({0:F6}, {1:F6}, {2:F6})", v.x, v.y, v.z);
}
public static void RegisterCamera(Camera camera, HDAdditionalCameraData additionalData)
{
string name = camera.name;
if (s_CameraNames.FindIndex(x => x.text.Equals(name)) < 0)
{
s_CameraNames.Add(new GUIContent(name));
needsRefreshingCameraFreezeList = true;
}
var history = FrameSettingsHistory.RegisterDebug(camera, additionalData);
DebugManager.instance.RegisterData(history);
}
public static void UnRegisterCamera(Camera camera, HDAdditionalCameraData additionalData)
{
string name = camera.name;
int indexOfCamera = s_CameraNames.FindIndex(x => x.text.Equals(camera.name));
if (indexOfCamera > 0)
{
s_CameraNames.RemoveAt(indexOfCamera);
needsRefreshingCameraFreezeList = true;
}
DebugManager.instance.UnregisterData(FrameSettingsHistory.GetPersistantDebugDataCopy(camera));
FrameSettingsHistory.UnRegisterDebug(camera);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.