context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using System.Drawing;
namespace Wve
{
/// <summary>
/// some tools for working with rtf
/// </summary>
public static class WveRtfStuff
{
/// <summary>
/// sets number of leading and trailing paragraphs
/// (i.e. carriage returns) in the RichTextBox's text
/// </summary>
/// <param name="rtb"></param>
/// <param name="leadingPars"></param>
/// <param name="trailingPars"></param>
public static void SetLeadingAndTrailingPars(
RichTextBox rtb, int leadingPars, int trailingPars)
{
int existingLeadingPars = 0; //to begin
int existingTrailingPars = 0; //to begin
char[] par = new char[] { (char)0x000D };
//;object existingClipboardContents;
//count existing leading pars
while (rtb.Find(par,
existingLeadingPars, //start where last iteration left off
existingLeadingPars + 1 //and look at only one character
) > -1) //-1 indicates not found
{
existingLeadingPars++;
}
//count existing trailing pars
while ((rtb.Text.Length > existingLeadingPars + existingTrailingPars) &&
(rtb.Find(par,
rtb.Text.Length - 1 - existingTrailingPars,
rtb.Text.Length - existingTrailingPars)
> -1))
{
existingTrailingPars++;
}
//now rebuild the text with desired
// number of pars
//select text without leading and trailing pars
rtb.Select(existingLeadingPars,
rtb.Text.Length - existingLeadingPars - existingTrailingPars);
//copy body
string body = "";
if (rtb.SelectionLength > 0)
{
body = rtb.SelectedRtf;
}
//rebuild the rtb
rtb.Clear();
//add leading pars
for (int i = 0; i < leadingPars; i++)
{
rtb.AppendText("\r");
}
//add middle
rtb.SelectedRtf = body;
//and end
/*
//(but notice the rich text box shows an extra line
// if the pasted text has no length, so decrememt if so)
if ((rtb.Text.Length == leadingPars) &&
(trailingPars > 0))
{
trailingPars--;
}
*/
for (int i = 0; i < trailingPars; i++)
{
rtb.AppendText("\r");
}
}
/// <summary>
/// true if material looks like rich text
/// formatted text
/// </summary>
/// <param name="material"></param>
/// <returns></returns>
public static bool IsRtf(string material)
{
return (material.Trim().StartsWith(@"{\rtf"));
}
/// <summary>
/// insert material into current cursor position
/// of rich text box, as RTF if looks like rtf, or
/// as text if not. Returns true if was inserted as rtf
/// </summary>
/// <param name="rtbox"></param>
/// <param name="material"></param>
/// <returns></returns>
public static bool InsertRtf(RichTextBox rtbox, string material)
{
//see if looks like rtf
bool loadedAsRTF = false; //unless changed
//(like IsRtf() above, but rewritten here for speed)
if (material.StartsWith(@"{\rtf"))
{
loadedAsRTF = true;
}
//append material
if ((material != null) || (material != ""))
{
//save as plaintext if doesn't look like rtf
if (!loadedAsRTF)
{
rtbox.SelectedText = material;
}
else
{
rtbox.SelectedRtf = material;
}
}
return loadedAsRTF;
}
/// <summary>
/// appends specified text material into rich text box; as
/// rtf if it is valid rtf material, or as text if not, returning
/// bool to indicate if the material was loaded as rtf
/// </summary>
/// <param name="rtbox"></param>
/// <param name="material"></param>
/// <returns>true if material loaded as rtf</returns>
public static bool AppendRtf(RichTextBox rtbox, string material)
{
//((also consider Clipboard
// as another way to do this...))
//move selection to end of existing text
if (rtbox.Text.Length > 0)
{
rtbox.SelectionStart = rtbox.Text.Length;
rtbox.SelectionLength = 0;
}
bool loadedAsRTF = false; //unless changed
if (material.StartsWith(@"{\rtf"))
{
loadedAsRTF = true;
}
//append material
if ((material != null) || (material != ""))
{
//save as plaintext if doesn't look like rtf
if (!loadedAsRTF)
{
rtbox.SelectedText = material;
}
else
{
rtbox.SelectedRtf = material;
/* This step may be superfluous...
//first try as rtf insertion
try
{
rtbox.SelectedRtf = material;
}
catch
{
//use the clipboard to load it so if rtf markup is bad it
//just loads as text instead of throwing exception
//first store current clipboard
object originalClpContents = Clipboard.GetDataObject();
//allow for text boxes that are read-only
bool existingSetting = rtbox.ReadOnly;
try
{
Clipboard.SetText(material, TextDataFormat.Rtf);
//rtbox.Clear();
rtbox.ReadOnly = false;
rtbox.Paste(DataFormats.GetFormat(DataFormats.Rtf));
}
finally
{
//restore clipboard
Clipboard.SetDataObject(originalClpContents);
//restore readonlyl
rtbox.ReadOnly = existingSetting;
}
} //from try catch
*/
}//from if loaded as rtf or not
/*
//finally, remove the extra trailing paragraph symbol the paste
// operation puts in automatically
rtbox.Select(0, rtbox.Text.Length - 1);
string body = rtbox.SelectedRtf;
rtbox.Clear();
rtbox.SelectedRtf = body;
*/
}
return loadedAsRTF;
}
/// <summary>
/// insert given image into rich text box at SelectedRTF insertion point
/// </summary>
/// <param name="img"></param>
/// <param name="rtb"></param>
public static void AppendImageToRtb(
Image img,
RichTextBox rtb)
{
//this implementation uses clipboard
// A more elegant, complicated and slow method is to convert image to wmf
// and add rtf control words, etc to paste in...
//save existing clp contennts
IDataObject preexistingClipbdContents = Clipboard.GetDataObject();
try
{
Clipboard.SetImage(img);
rtb.Paste();
}
finally
{
//restore clipboard contents
Clipboard.SetDataObject(preexistingClipbdContents);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Diagnostics
{
/// <summary>
/// Performance Counter component.
/// This class provides support for NT Performance counters.
/// It handles both the existing counters (accessible by Perf Registry Interface)
/// and user defined (extensible) counters.
/// This class is a part of a larger framework, that includes the perf dll object and
/// perf service.
/// </summary>
public sealed class PerformanceCounter : Component, ISupportInitialize
{
private string _machineName;
private string _categoryName;
private string _counterName;
private string _instanceName;
private PerformanceCounterInstanceLifetime _instanceLifetime = PerformanceCounterInstanceLifetime.Global;
private bool _isReadOnly;
private bool _initialized = false;
private string _helpMsg = null;
private int _counterType = -1;
// Cached old sample
private CounterSample _oldSample = CounterSample.Empty;
// Cached IP Shared Performanco counter
private SharedPerformanceCounter _sharedCounter;
[ObsoleteAttribute("This field has been deprecated and is not used. Use machine.config or an application configuration file to set the size of the PerformanceCounter file mapping.")]
public static int DefaultFileMappingSize = 524288;
private object _instanceLockObject;
private object InstanceLockObject
{
get
{
if (_instanceLockObject == null)
{
object o = new object();
Interlocked.CompareExchange(ref _instanceLockObject, o, null);
}
return _instanceLockObject;
}
}
/// <summary>
/// The defaut constructor. Creates the perf counter object
/// </summary>
public PerformanceCounter()
{
_machineName = ".";
_categoryName = string.Empty;
_counterName = string.Empty;
_instanceName = string.Empty;
_isReadOnly = true;
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates the Performance Counter Object
/// </summary>
public PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName)
{
MachineName = machineName;
CategoryName = categoryName;
CounterName = counterName;
InstanceName = instanceName;
_isReadOnly = true;
Initialize();
GC.SuppressFinalize(this);
}
internal PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName, bool skipInit)
{
MachineName = machineName;
CategoryName = categoryName;
CounterName = counterName;
InstanceName = instanceName;
_isReadOnly = true;
_initialized = true;
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates the Performance Counter Object on local machine.
/// </summary>
public PerformanceCounter(string categoryName, string counterName, string instanceName) :
this(categoryName, counterName, instanceName, true)
{
}
/// <summary>
/// Creates the Performance Counter Object on local machine.
/// </summary>
public PerformanceCounter(string categoryName, string counterName, string instanceName, bool readOnly)
{
if (!readOnly)
{
VerifyWriteableCounterAllowed();
}
MachineName = ".";
CategoryName = categoryName;
CounterName = counterName;
InstanceName = instanceName;
_isReadOnly = readOnly;
Initialize();
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates the Performance Counter Object, assumes that it's a single instance
/// </summary>
public PerformanceCounter(string categoryName, string counterName) :
this(categoryName, counterName, true)
{
}
/// <summary>
/// Creates the Performance Counter Object, assumes that it's a single instance
/// </summary>
public PerformanceCounter(string categoryName, string counterName, bool readOnly) :
this(categoryName, counterName, "", readOnly)
{
}
/// <summary>
/// Returns the performance category name for this performance counter
/// </summary>
public string CategoryName
{
get
{
return _categoryName;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (_categoryName == null || !string.Equals(_categoryName, value, StringComparison.OrdinalIgnoreCase))
{
_categoryName = value;
Close();
}
}
}
/// <summary>
/// Returns the description message for this performance counter
/// </summary>
public string CounterHelp
{
get
{
string currentCategoryName = _categoryName;
string currentMachineName = _machineName;
Initialize();
if (_helpMsg == null)
_helpMsg = PerformanceCounterLib.GetCounterHelp(currentMachineName, currentCategoryName, _counterName);
return _helpMsg;
}
}
/// <summary>
/// Sets/returns the performance counter name for this performance counter
/// </summary>
public string CounterName
{
get
{
return _counterName;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (_counterName == null || !string.Equals(_counterName, value, StringComparison.OrdinalIgnoreCase))
{
_counterName = value;
Close();
}
}
}
/// <summary>
/// Sets/Returns the counter type for this performance counter
/// </summary>
public PerformanceCounterType CounterType
{
get
{
if (_counterType == -1)
{
string currentCategoryName = _categoryName;
string currentMachineName = _machineName;
// This is the same thing that NextSample does, except that it doesn't try to get the actual counter
// value. If we wanted the counter value, we would need to have an instance name.
Initialize();
using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName))
{
CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(_counterName);
_counterType = counterSample._counterType;
}
}
return (PerformanceCounterType)_counterType;
}
}
public PerformanceCounterInstanceLifetime InstanceLifetime
{
get { return _instanceLifetime; }
set
{
if (value > PerformanceCounterInstanceLifetime.Process || value < PerformanceCounterInstanceLifetime.Global)
throw new ArgumentOutOfRangeException(nameof(value));
if (_initialized)
throw new InvalidOperationException(SR.CantSetLifetimeAfterInitialized);
_instanceLifetime = value;
}
}
/// <summary>
/// Sets/returns an instance name for this performance counter
/// </summary>
public string InstanceName
{
get
{
return _instanceName;
}
set
{
if (value == null && _instanceName == null)
return;
if ((value == null && _instanceName != null) ||
(value != null && _instanceName == null) ||
!string.Equals(_instanceName, value, StringComparison.OrdinalIgnoreCase))
{
_instanceName = value;
Close();
}
}
}
/// <summary>
/// Returns true if counter is read only (system counter, foreign extensible counter or remote counter)
/// </summary>
public bool ReadOnly
{
get
{
return _isReadOnly;
}
set
{
if (value != _isReadOnly)
{
if (value == false)
{
VerifyWriteableCounterAllowed();
}
_isReadOnly = value;
Close();
}
}
}
/// <summary>
/// Set/returns the machine name for this performance counter
/// </summary>
public string MachineName
{
get
{
return _machineName;
}
set
{
if (!SyntaxCheck.CheckMachineName(value))
throw new ArgumentException(SR.Format(SR.InvalidProperty, nameof(MachineName), value), nameof(value));
if (_machineName != value)
{
_machineName = value;
Close();
}
}
}
/// <summary>
/// Directly accesses the raw value of this counter. If counter type is of a 32-bit size, it will truncate
/// the value given to 32 bits. This can be significantly more performant for scenarios where
/// the raw value is sufficient. Note that this only works for custom counters created using
/// this component, non-custom counters will throw an exception if this property is accessed.
/// </summary>
public long RawValue
{
get
{
if (ReadOnly)
{
//No need to initialize or Demand, since NextSample already does.
return NextSample().RawValue;
}
else
{
Initialize();
return _sharedCounter.Value;
}
}
set
{
if (ReadOnly)
ThrowReadOnly();
Initialize();
_sharedCounter.Value = value;
}
}
/// <summary>
/// </summary>
public void BeginInit()
{
Close();
}
/// <summary>
/// Frees all the resources allocated by this counter
/// </summary>
public void Close()
{
_helpMsg = null;
_oldSample = CounterSample.Empty;
_sharedCounter = null;
_initialized = false;
_counterType = -1;
}
/// <summary>
/// Frees all the resources allocated for all performance
/// counters, frees File Mapping used by extensible counters,
/// unloads dll's used to read counters.
/// </summary>
public static void CloseSharedResources()
{
PerformanceCounterLib.CloseAllLibraries();
}
/// <internalonly/>
/// <summary>
/// </summary>
protected override void Dispose(bool disposing)
{
// safe to call while finalizing or disposing
if (disposing)
{
//Dispose managed and unmanaged resources
Close();
}
base.Dispose(disposing);
}
/// <summary>
/// Decrements counter by one using an efficient atomic operation.
/// </summary>
public long Decrement()
{
if (ReadOnly)
ThrowReadOnly();
Initialize();
return _sharedCounter.Decrement();
}
/// <summary>
/// </summary>
public void EndInit()
{
Initialize();
}
/// <summary>
/// Increments the value of this counter. If counter type is of a 32-bit size, it'll truncate
/// the value given to 32 bits. This method uses a mutex to guarantee correctness of
/// the operation in case of multiple writers. This method should be used with caution because of the negative
/// impact on performance due to creation of the mutex.
/// </summary>
public long IncrementBy(long value)
{
if (_isReadOnly)
ThrowReadOnly();
Initialize();
return _sharedCounter.IncrementBy(value);
}
/// <summary>
/// Increments counter by one using an efficient atomic operation.
/// </summary>
public long Increment()
{
if (_isReadOnly)
ThrowReadOnly();
Initialize();
return _sharedCounter.Increment();
}
private void ThrowReadOnly()
{
throw new InvalidOperationException(SR.ReadOnlyCounter);
}
private static void VerifyWriteableCounterAllowed()
{
if (EnvironmentHelpers.IsAppContainerProcess)
{
throw new NotSupportedException(SR.PCNotSupportedUnderAppContainer);
}
}
private void Initialize()
{
// Keep this method small so the JIT will inline it.
if (!_initialized && !DesignMode)
{
InitializeImpl();
}
}
/// <summary>
/// Intializes required resources
/// </summary>
private void InitializeImpl()
{
bool tookLock = false;
try
{
Monitor.Enter(InstanceLockObject, ref tookLock);
if (!_initialized)
{
string currentCategoryName = _categoryName;
string currentMachineName = _machineName;
if (currentCategoryName == string.Empty)
throw new InvalidOperationException(SR.CategoryNameMissing);
if (_counterName == string.Empty)
throw new InvalidOperationException(SR.CounterNameMissing);
if (ReadOnly)
{
if (!PerformanceCounterLib.CounterExists(currentMachineName, currentCategoryName, _counterName))
throw new InvalidOperationException(SR.Format(SR.CounterExists, currentCategoryName, _counterName));
PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
if (categoryType == PerformanceCounterCategoryType.MultiInstance)
{
if (string.IsNullOrEmpty(_instanceName))
throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, currentCategoryName));
}
else if (categoryType == PerformanceCounterCategoryType.SingleInstance)
{
if (!string.IsNullOrEmpty(_instanceName))
throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, currentCategoryName));
}
if (_instanceLifetime != PerformanceCounterInstanceLifetime.Global)
throw new InvalidOperationException(SR.InstanceLifetimeProcessonReadOnly);
_initialized = true;
}
else
{
if (currentMachineName != "." && !string.Equals(currentMachineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(SR.RemoteWriting);
if (!PerformanceCounterLib.IsCustomCategory(currentMachineName, currentCategoryName))
throw new InvalidOperationException(SR.NotCustomCounter);
// check category type
PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
if (categoryType == PerformanceCounterCategoryType.MultiInstance)
{
if (string.IsNullOrEmpty(_instanceName))
throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, currentCategoryName));
}
else if (categoryType == PerformanceCounterCategoryType.SingleInstance)
{
if (!string.IsNullOrEmpty(_instanceName))
throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, currentCategoryName));
}
if (string.IsNullOrEmpty(_instanceName) && InstanceLifetime == PerformanceCounterInstanceLifetime.Process)
throw new InvalidOperationException(SR.InstanceLifetimeProcessforSingleInstance);
_sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLower(CultureInfo.InvariantCulture), _counterName.ToLower(CultureInfo.InvariantCulture), _instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime);
_initialized = true;
}
}
}
finally
{
if (tookLock)
Monitor.Exit(InstanceLockObject);
}
}
// Will cause an update, raw value
/// <summary>
/// Obtains a counter sample and returns the raw value for it.
/// </summary>
public CounterSample NextSample()
{
string currentCategoryName = _categoryName;
string currentMachineName = _machineName;
Initialize();
using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName))
{
CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(_counterName);
_counterType = counterSample._counterType;
if (!categorySample._isMultiInstance)
{
if (_instanceName != null && _instanceName.Length != 0)
throw new InvalidOperationException(SR.Format(SR.InstanceNameProhibited, _instanceName));
return counterSample.GetSingleValue();
}
else
{
if (_instanceName == null || _instanceName.Length == 0)
throw new InvalidOperationException(SR.InstanceNameRequired);
return counterSample.GetInstanceValue(_instanceName);
}
}
}
/// <summary>
/// Obtains a counter sample and returns the calculated value for it.
/// NOTE: For counters whose calculated value depend upon 2 counter reads,
/// the very first read will return 0.0.
/// </summary>
public float NextValue()
{
//No need to initialize or Demand, since NextSample already does.
CounterSample newSample = NextSample();
float retVal = 0.0f;
retVal = CounterSample.Calculate(_oldSample, newSample);
_oldSample = newSample;
return retVal;
}
/// <summary>
/// Removes this counter instance from the shared memory
/// </summary>
public void RemoveInstance()
{
if (_isReadOnly)
throw new InvalidOperationException(SR.ReadOnlyRemoveInstance);
Initialize();
_sharedCounter.RemoveInstance(_instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime);
}
}
}
| |
using System;
using System.Reflection;
using System.Resources;
using System.Security.Cryptography;
namespace NSec.Cryptography
{
internal static class Error
{
private static ResourceManager? s_resourceManager;
private static ResourceManager ResourceManager => s_resourceManager ??= new ResourceManager(typeof(Error).FullName!, typeof(Error).GetTypeInfo().Assembly);
internal static ArgumentException Argument_BadBase16Length(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_BadBase16Length)), paramName);
}
internal static ArgumentException Argument_BadBase32Length(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_BadBase32Length)), paramName);
}
internal static ArgumentException Argument_BadBase64Length(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_BadBase64Length)), paramName);
}
internal static ArgumentException Argument_CiphertextLength(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_CiphertextLength)), paramName);
}
internal static ArgumentException Argument_DeriveInvalidCount(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_DeriveInvalidCount))!, arg0), paramName);
}
internal static ArgumentException Argument_DestinationTooShort(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_DestinationTooShort)), paramName);
}
internal static ArgumentException Argument_FormatNotSupported(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_FormatNotSupported))!, arg0), paramName);
}
internal static ArgumentException Argument_HashLength(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_HashLength))!, arg0), paramName);
}
internal static ArgumentException Argument_InvalidArgon2Parameters(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_InvalidArgon2Parameters)), paramName);
}
internal static ArgumentException Argument_InvalidPbkdf2Parameters(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_InvalidPbkdf2Parameters)), paramName);
}
internal static ArgumentException Argument_InvalidPrkLength(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_InvalidPrkLength))!, arg0), paramName);
}
internal static ArgumentException Argument_InvalidPrkLengthExact(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_InvalidPrkLengthExact))!, arg0), paramName);
}
internal static ArgumentException Argument_InvalidScryptParameters(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_InvalidScryptParameters)), paramName);
}
internal static ArgumentException Argument_KeyAlgorithmMismatch(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_KeyAlgorithmMismatch))!, arg0), paramName);
}
internal static ArgumentException Argument_MacKeyRequired(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_MacKeyRequired)), paramName);
}
internal static ArgumentException Argument_MacLength(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_MacLength))!, arg0), paramName);
}
internal static ArgumentException Argument_MinMaxValue(
string paramName,
object? arg0,
object? arg1)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_MinMaxValue))!, arg0, arg1), paramName);
}
internal static ArgumentException Argument_NonceFixedCounterSize(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_NonceFixedCounterSize))!, arg0), paramName);
}
internal static ArgumentException Argument_NonceFixedSize(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_NonceFixedSize))!, arg0), paramName);
}
internal static ArgumentException Argument_NonceLength(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_NonceLength))!, arg0), paramName);
}
internal static ArgumentException Argument_NonceXorSize(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_NonceXorSize)), paramName);
}
internal static ArgumentException Argument_OverlapCiphertext(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_OverlapCiphertext)), paramName);
}
internal static ArgumentException Argument_OverlapInfo(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_OverlapInfo)), paramName);
}
internal static ArgumentException Argument_OverlapPlaintext(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_OverlapPlaintext)), paramName);
}
internal static ArgumentException Argument_OverlapPrk(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_OverlapPrk)), paramName);
}
internal static ArgumentException Argument_OverlapSalt(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_OverlapSalt)), paramName);
}
internal static ArgumentException Argument_PlaintextLength(
string paramName)
{
return new ArgumentException(ResourceManager.GetString(nameof(Argument_PlaintextLength)), paramName);
}
internal static ArgumentException Argument_PlaintextTooLong(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_PlaintextTooLong))!, arg0), paramName);
}
internal static ArgumentException Argument_PublicKeyAlgorithmMismatch(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_PublicKeyAlgorithmMismatch))!, arg0), paramName);
}
internal static ArgumentException Argument_SaltLength(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_SaltLength))!, arg0), paramName);
}
internal static ArgumentException Argument_SaltLengthRange(
string paramName,
object? arg0,
object? arg1)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_SaltLengthRange))!, arg0, arg1), paramName);
}
internal static ArgumentException Argument_SharedSecretLength(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_SharedSecretLength))!, arg0), paramName);
}
internal static ArgumentException Argument_SignatureLength(
string paramName,
object? arg0)
{
return new ArgumentException(string.Format(ResourceManager.GetString(nameof(Argument_SignatureLength))!, arg0), paramName);
}
internal static ArgumentNullException ArgumentNull_Algorithm(
string paramName)
{
return new ArgumentNullException(paramName, ResourceManager.GetString(nameof(ArgumentNull_Algorithm)));
}
internal static ArgumentNullException ArgumentNull_Key(
string paramName)
{
return new ArgumentNullException(paramName, ResourceManager.GetString(nameof(ArgumentNull_Key)));
}
internal static ArgumentNullException ArgumentNull_Password(
string paramName)
{
return new ArgumentNullException(paramName, ResourceManager.GetString(nameof(ArgumentNull_Password)));
}
internal static ArgumentNullException ArgumentNull_SharedSecret(
string paramName)
{
return new ArgumentNullException(paramName, ResourceManager.GetString(nameof(ArgumentNull_SharedSecret)));
}
internal static ArgumentNullException ArgumentNull_String(
string paramName)
{
return new ArgumentNullException(paramName, ResourceManager.GetString(nameof(ArgumentNull_String)));
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange_DeriveInvalidCount(
string paramName,
object? arg0)
{
return new ArgumentOutOfRangeException(paramName, string.Format(ResourceManager.GetString(nameof(ArgumentOutOfRange_DeriveInvalidCount))!, arg0));
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange_DeriveNegativeCount(
string paramName)
{
return new ArgumentOutOfRangeException(paramName, ResourceManager.GetString(nameof(ArgumentOutOfRange_DeriveNegativeCount)));
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange_GenerateNegativeCount(
string paramName)
{
return new ArgumentOutOfRangeException(paramName, ResourceManager.GetString(nameof(ArgumentOutOfRange_GenerateNegativeCount)));
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange_HashSize(
string paramName,
object? arg0,
object? arg1,
object? arg2)
{
return new ArgumentOutOfRangeException(paramName, string.Format(ResourceManager.GetString(nameof(ArgumentOutOfRange_HashSize))!, arg0, arg1, arg2));
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange_KeySize(
string paramName,
object? arg0,
object? arg1,
object? arg2)
{
return new ArgumentOutOfRangeException(paramName, string.Format(ResourceManager.GetString(nameof(ArgumentOutOfRange_KeySize))!, arg0, arg1, arg2));
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange_MacSize(
string paramName,
object? arg0,
object? arg1,
object? arg2)
{
return new ArgumentOutOfRangeException(paramName, string.Format(ResourceManager.GetString(nameof(ArgumentOutOfRange_MacSize))!, arg0, arg1, arg2));
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange_MustBePositive(
string paramName,
object? arg0)
{
return new ArgumentOutOfRangeException(paramName, string.Format(ResourceManager.GetString(nameof(ArgumentOutOfRange_MustBePositive))!, arg0));
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange_NonceAddend(
string paramName)
{
return new ArgumentOutOfRangeException(paramName, ResourceManager.GetString(nameof(ArgumentOutOfRange_NonceAddend)));
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange_NonceCounterSize(
string paramName,
object? arg0)
{
return new ArgumentOutOfRangeException(paramName, string.Format(ResourceManager.GetString(nameof(ArgumentOutOfRange_NonceCounterSize))!, arg0));
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange_NonceFixedCounterSize(
string paramName,
object? arg0)
{
return new ArgumentOutOfRangeException(paramName, string.Format(ResourceManager.GetString(nameof(ArgumentOutOfRange_NonceFixedCounterSize))!, arg0));
}
internal static CryptographicException Cryptographic_PasswordBasedKeyDerivationFailed()
{
return new CryptographicException(ResourceManager.GetString(nameof(Cryptographic_PasswordBasedKeyDerivationFailed)));
}
internal static FormatException Format_BadBase16()
{
return new FormatException(ResourceManager.GetString(nameof(Format_BadBase16)));
}
internal static FormatException Format_BadBase32()
{
return new FormatException(ResourceManager.GetString(nameof(Format_BadBase32)));
}
internal static FormatException Format_BadBase64()
{
return new FormatException(ResourceManager.GetString(nameof(Format_BadBase64)));
}
internal static FormatException Format_InvalidBlob()
{
return new FormatException(ResourceManager.GetString(nameof(Format_InvalidBlob)));
}
internal static InvalidOperationException InvalidOperation_AlreadyArchived()
{
return new InvalidOperationException(ResourceManager.GetString(nameof(InvalidOperation_AlreadyArchived)));
}
internal static InvalidOperationException InvalidOperation_ExportNotAllowed()
{
return new InvalidOperationException(ResourceManager.GetString(nameof(InvalidOperation_ExportNotAllowed)));
}
internal static InvalidOperationException InvalidOperation_InitializationFailed()
{
return new InvalidOperationException(ResourceManager.GetString(nameof(InvalidOperation_InitializationFailed)));
}
internal static InvalidOperationException InvalidOperation_InitializationFailed_VersionMismatch(
object? arg0,
object? arg1)
{
return new InvalidOperationException(string.Format(ResourceManager.GetString(nameof(InvalidOperation_InitializationFailed_VersionMismatch))!, arg0, arg1));
}
internal static InvalidOperationException InvalidOperation_InternalError()
{
return new InvalidOperationException(ResourceManager.GetString(nameof(InvalidOperation_InternalError)));
}
internal static InvalidOperationException InvalidOperation_NoPublicKey()
{
return new InvalidOperationException(ResourceManager.GetString(nameof(InvalidOperation_NoPublicKey)));
}
internal static InvalidOperationException InvalidOperation_UninitializedState()
{
return new InvalidOperationException(ResourceManager.GetString(nameof(InvalidOperation_UninitializedState)));
}
internal static NotSupportedException NotSupported_CreateKey()
{
return new NotSupportedException(ResourceManager.GetString(nameof(NotSupported_CreateKey)));
}
internal static NotSupportedException NotSupported_ExportKey()
{
return new NotSupportedException(ResourceManager.GetString(nameof(NotSupported_ExportKey)));
}
internal static NotSupportedException NotSupported_ImportKey()
{
return new NotSupportedException(ResourceManager.GetString(nameof(NotSupported_ImportKey)));
}
internal static NotSupportedException NotSupported_KeyConversion(
object? arg0,
object? arg1)
{
return new NotSupportedException(string.Format(ResourceManager.GetString(nameof(NotSupported_KeyConversion))!, arg0, arg1));
}
internal static NotSupportedException NotSupported_Operation()
{
return new NotSupportedException(ResourceManager.GetString(nameof(NotSupported_Operation)));
}
internal static OverflowException Overflow_NonceCounter()
{
return new OverflowException(ResourceManager.GetString(nameof(Overflow_NonceCounter)));
}
internal static PlatformNotSupportedException PlatformNotSupported_Algorithm()
{
return new PlatformNotSupportedException(ResourceManager.GetString(nameof(PlatformNotSupported_Algorithm)));
}
internal static PlatformNotSupportedException PlatformNotSupported_Initialization(
Exception innerException)
{
return new PlatformNotSupportedException(ResourceManager.GetString(nameof(PlatformNotSupported_Initialization)), innerException);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServiceBus.Models
{
using Azure;
using Management;
using ServiceBus;
using Rest;
using Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Description of subscription resource.
/// </summary>
[JsonTransformation]
public partial class SubscriptionResource : Resource
{
/// <summary>
/// Initializes a new instance of the SubscriptionResource class.
/// </summary>
public SubscriptionResource() { }
/// <summary>
/// Initializes a new instance of the SubscriptionResource class.
/// </summary>
/// <param name="id">Resource Id</param>
/// <param name="name">Resource name</param>
/// <param name="location">Resource location.</param>
/// <param name="type">Resource type</param>
/// <param name="accessedAt">Last time there was a receive request to
/// this subscription.</param>
/// <param name="autoDeleteOnIdle">TimeSpan idle interval after which
/// the topic is automatically deleted. The minimum duration is 5
/// minutes.</param>
/// <param name="createdAt">Exact time the message was created.</param>
/// <param name="defaultMessageTimeToLive">Default message time to live
/// value. This is the duration after which the message expires,
/// starting from when the message is sent to Service Bus. This is the
/// default value used when TimeToLive is not set on a message
/// itself.</param>
/// <param name="deadLetteringOnFilterEvaluationExceptions">Value that
/// indicates whether a subscription has dead letter support on filter
/// evaluation exceptions.</param>
/// <param name="deadLetteringOnMessageExpiration">Value that indicates
/// whether a subscription has dead letter support when a message
/// expires.</param>
/// <param name="enableBatchedOperations">Value that indicates whether
/// server-side batched operations are enabled.</param>
/// <param name="entityAvailabilityStatus">Entity availability status
/// for the topic. Possible values include: 'Available', 'Limited',
/// 'Renaming', 'Restoring', 'Unknown'</param>
/// <param name="isReadOnly">Value that indicates whether the entity
/// description is read-only.</param>
/// <param name="lockDuration">The lock duration time span for the
/// subscription.</param>
/// <param name="maxDeliveryCount">Number of maximum
/// deliveries.</param>
/// <param name="messageCount">Number of messages.</param>
/// <param name="requiresSession">Value indicating if a subscription
/// supports the concept of sessions.</param>
/// <param name="status">Enumerates the possible values for the status
/// of a messaging entity. Possible values include: 'Active',
/// 'Creating', 'Deleting', 'Disabled', 'ReceiveDisabled', 'Renaming',
/// 'Restoring', 'SendDisabled', 'Unknown'</param>
/// <param name="updatedAt">The exact time the message was
/// updated.</param>
public SubscriptionResource(string id = default(string), string name = default(string), string location = default(string), string type = default(string), System.DateTime? accessedAt = default(System.DateTime?), string autoDeleteOnIdle = default(string), MessageCountDetails countDetails = default(MessageCountDetails), System.DateTime? createdAt = default(System.DateTime?), string defaultMessageTimeToLive = default(string), bool? deadLetteringOnFilterEvaluationExceptions = default(bool?), bool? deadLetteringOnMessageExpiration = default(bool?), bool? enableBatchedOperations = default(bool?), EntityAvailabilityStatus? entityAvailabilityStatus = default(EntityAvailabilityStatus?), bool? isReadOnly = default(bool?), string lockDuration = default(string), int? maxDeliveryCount = default(int?), long? messageCount = default(long?), bool? requiresSession = default(bool?), EntityStatus? status = default(EntityStatus?), System.DateTime? updatedAt = default(System.DateTime?))
: base(id, name, location, type)
{
AccessedAt = accessedAt;
AutoDeleteOnIdle = autoDeleteOnIdle;
CountDetails = countDetails;
CreatedAt = createdAt;
DefaultMessageTimeToLive = defaultMessageTimeToLive;
DeadLetteringOnFilterEvaluationExceptions = deadLetteringOnFilterEvaluationExceptions;
DeadLetteringOnMessageExpiration = deadLetteringOnMessageExpiration;
EnableBatchedOperations = enableBatchedOperations;
EntityAvailabilityStatus = entityAvailabilityStatus;
IsReadOnly = isReadOnly;
LockDuration = lockDuration;
MaxDeliveryCount = maxDeliveryCount;
MessageCount = messageCount;
RequiresSession = requiresSession;
Status = status;
UpdatedAt = updatedAt;
}
/// <summary>
/// Gets last time there was a receive request to this subscription.
/// </summary>
[JsonProperty(PropertyName = "properties.accessedAt")]
public System.DateTime? AccessedAt { get; protected set; }
/// <summary>
/// Gets or sets timeSpan idle interval after which the topic is
/// automatically deleted. The minimum duration is 5 minutes.
/// </summary>
[JsonProperty(PropertyName = "properties.autoDeleteOnIdle")]
public string AutoDeleteOnIdle { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "properties.countDetails")]
public MessageCountDetails CountDetails { get; protected set; }
/// <summary>
/// Gets exact time the message was created.
/// </summary>
[JsonProperty(PropertyName = "properties.createdAt")]
public System.DateTime? CreatedAt { get; protected set; }
/// <summary>
/// Gets or sets default message time to live value. This is the
/// duration after which the message expires, starting from when the
/// message is sent to Service Bus. This is the default value used when
/// TimeToLive is not set on a message itself.
/// </summary>
[JsonProperty(PropertyName = "properties.defaultMessageTimeToLive")]
public string DefaultMessageTimeToLive { get; set; }
/// <summary>
/// Gets or sets value that indicates whether a subscription has dead
/// letter support on filter evaluation exceptions.
/// </summary>
[JsonProperty(PropertyName = "properties.deadLetteringOnFilterEvaluationExceptions")]
public bool? DeadLetteringOnFilterEvaluationExceptions { get; set; }
/// <summary>
/// Gets or sets value that indicates whether a subscription has dead
/// letter support when a message expires.
/// </summary>
[JsonProperty(PropertyName = "properties.deadLetteringOnMessageExpiration")]
public bool? DeadLetteringOnMessageExpiration { get; set; }
/// <summary>
/// Gets or sets value that indicates whether server-side batched
/// operations are enabled.
/// </summary>
[JsonProperty(PropertyName = "properties.enableBatchedOperations")]
public bool? EnableBatchedOperations { get; set; }
/// <summary>
/// Gets or sets entity availability status for the topic. Possible
/// values include: 'Available', 'Limited', 'Renaming', 'Restoring',
/// 'Unknown'
/// </summary>
[JsonProperty(PropertyName = "properties.entityAvailabilityStatus")]
public EntityAvailabilityStatus? EntityAvailabilityStatus { get; set; }
/// <summary>
/// Gets or sets value that indicates whether the entity description is
/// read-only.
/// </summary>
[JsonProperty(PropertyName = "properties.isReadOnly")]
public bool? IsReadOnly { get; set; }
/// <summary>
/// Gets or sets the lock duration time span for the subscription.
/// </summary>
[JsonProperty(PropertyName = "properties.lockDuration")]
public string LockDuration { get; set; }
/// <summary>
/// Gets or sets number of maximum deliveries.
/// </summary>
[JsonProperty(PropertyName = "properties.maxDeliveryCount")]
public int? MaxDeliveryCount { get; set; }
/// <summary>
/// Gets number of messages.
/// </summary>
[JsonProperty(PropertyName = "properties.messageCount")]
public long? MessageCount { get; protected set; }
/// <summary>
/// Gets or sets value indicating if a subscription supports the
/// concept of sessions.
/// </summary>
[JsonProperty(PropertyName = "properties.requiresSession")]
public bool? RequiresSession { get; set; }
/// <summary>
/// Gets or sets enumerates the possible values for the status of a
/// messaging entity. Possible values include: 'Active', 'Creating',
/// 'Deleting', 'Disabled', 'ReceiveDisabled', 'Renaming', 'Restoring',
/// 'SendDisabled', 'Unknown'
/// </summary>
[JsonProperty(PropertyName = "properties.status")]
public EntityStatus? Status { get; set; }
/// <summary>
/// Gets the exact time the message was updated.
/// </summary>
[JsonProperty(PropertyName = "properties.updatedAt")]
public System.DateTime? UpdatedAt { get; protected set; }
}
}
| |
/* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Xml;
using System.IO;
using System.Collections;
using Google.GData.Client;
using Google.GData.Extensions.Apps;
namespace Google.GData.Apps {
/// <summary>
/// A Google Apps Mailbox Dump Request entry.
/// </summary>
public class MailboxDumpRequest : AppsExtendedEntry {
/// <summary>
/// Constructs a new <code>MailboxDumpRequest</code> object.
/// </summary>
public MailboxDumpRequest()
: base() {
}
/// <summary>
/// BeginDate Property accessor
/// </summary>
public DateTime BeginDate {
get {
PropertyElement property = this.getPropertyByName(AuditNameTable.beginDate);
DateTime dt;
if (property != null && DateTime.TryParse(property.Value, out dt)) {
return dt;
}
return DateTime.MinValue;
}
set {
this.addOrUpdatePropertyValue(AuditNameTable.beginDate, value.ToString(AuditNameTable.dateFormat));
}
}
/// <summary>
/// EndDate Property accessor
/// </summary>
public DateTime EndDate {
get {
PropertyElement property = this.getPropertyByName(AuditNameTable.endDate);
DateTime dt;
if (property != null && DateTime.TryParse(property.Value, out dt)) {
return dt;
}
return DateTime.Now;
}
set {
this.addOrUpdatePropertyValue(AuditNameTable.endDate, value.ToString(AuditNameTable.dateFormat));
}
}
/// <summary>
/// SearchQuery Property accessor
/// </summary>
public string SearchQuery {
get {
PropertyElement property = this.getPropertyByName(AuditNameTable.searchQuery);
return property != null ? property.Value : null;
}
set {
this.addOrUpdatePropertyValue(AuditNameTable.searchQuery, value);
}
}
/// <summary>
/// IncludeDeleted Property accessor
/// </summary>
public bool IncludeDeleted {
get {
PropertyElement property = this.getPropertyByName(AuditNameTable.includeDeleted);
if (property == null || property.Value == null) {
return false;
}
bool value;
if (!bool.TryParse(property.Value, out value)) {
value = false;
}
return value;
}
set {
this.addOrUpdatePropertyValue(AuditNameTable.includeDeleted, value.ToString());
}
}
/// <summary>
/// PackageContent Property accessor
/// </summary>
public MonitorLevel PackageContent {
get {
PropertyElement property = this.getPropertyByName(AuditNameTable.packageContent);
if (property == null || property.Value == null) {
return MonitorLevel.FULL_MESSAGE;
}
return (MonitorLevel)Enum.Parse(typeof(MonitorLevel), property.Value, true);
}
set {
this.addOrUpdatePropertyValue(AuditNameTable.packageContent, value.ToString());
}
}
/// <summary>
/// Status Property accessor
/// </summary>
public RequestStatus Status {
get {
PropertyElement property = this.getPropertyByName(AuditNameTable.status);
if (property == null || property.Value == null) {
return RequestStatus.PENDING;
}
return (RequestStatus)Enum.Parse(typeof(RequestStatus), property.Value, true);
}
internal set {
this.addOrUpdatePropertyValue(AuditNameTable.status, value.ToString());
}
}
/// <summary>
/// RequestId Property accessor
/// </summary>
public string RequestId {
get {
PropertyElement property = this.getPropertyByName(AuditNameTable.requestId);
return property != null ? property.Value : null;
}
internal set {
this.addOrUpdatePropertyValue(AuditNameTable.requestId, value);
}
}
/// <summary>
/// UserEmailAddress Property accessor
/// </summary>
public string UserEmailAddress {
get {
PropertyElement property = this.getPropertyByName(AuditNameTable.userEmailAddress);
return property != null ? property.Value : null;
}
internal set {
this.addOrUpdatePropertyValue(AuditNameTable.userEmailAddress, value);
}
}
/// <summary>
/// AdminEmailAddress Property accessor
/// </summary>
public string AdminEmailAddress {
get {
PropertyElement property = this.getPropertyByName(AuditNameTable.adminEmailAddress);
return property != null ? property.Value : null;
}
internal set {
this.addOrUpdatePropertyValue(AuditNameTable.adminEmailAddress, value);
}
}
/// <summary>
/// RequestDate Property accessor
/// </summary>
public DateTime RequestDate {
get {
PropertyElement property = this.getPropertyByName(AuditNameTable.requestDate);
DateTime dt;
if (property != null && DateTime.TryParse(property.Value, out dt)) {
return dt;
}
return DateTime.Now;
}
internal set {
this.addOrUpdatePropertyValue(AuditNameTable.requestDate, value.ToString(AuditNameTable.dateFormat));
}
}
/// <summary>
/// NumberOfFiles Property accessor
/// </summary>
public int NumberOfFiles {
get {
PropertyElement property = this.getPropertyByName(AuditNameTable.numberOfFiles);
if (property == null || property.Value == null) {
return 0;
}
return Convert.ToInt32(property.Value);
}
internal set {
this.addOrUpdatePropertyValue(AuditNameTable.numberOfFiles, value.ToString());
}
}
/// <summary>
/// Returns the url of file at the given position in the results
/// </summary>
/// <param name="index">The index of the url to be returned</param>
/// <returns>The url of account info results</returns>
public String getFileDownloadUrl(int index) {
return getPropertyValueByName(String.Format("{0}{1}",
AuditNameTable.fileUrl,
index));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
** Class: AsyncStreamReader
**
** Purpose: For reading text from streams using a particular
** encoding in an asychronous manner used by the process class
**
**
===========================================================*/
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Diagnostics
{
internal sealed class AsyncStreamReader : IDisposable
{
internal const int DefaultBufferSize = 1024; // Byte buffer size
private const int MinBufferSize = 128;
private Stream _stream;
private Encoding _encoding;
private Decoder _decoder;
private byte[] _byteBuffer;
private char[] _charBuffer;
// Record the number of valid bytes in the byteBuffer, for a few checks.
// This is the maximum number of chars we can get from one call to
// ReadBuffer. Used so ReadBuffer can tell when to copy data into
// a user's char[] directly, instead of our internal char[].
private int _maxCharsPerBuffer;
// Store a backpointer to the process class, to check for user callbacks
private Process _process;
// Delegate to call user function.
private Action<string> _userCallBack;
// Internal Cancel operation
private bool _cancelOperation;
private ManualResetEvent _eofEvent;
private Queue<string> _messageQueue;
private StringBuilder _sb;
private bool _bLastCarriageReturn;
// Cache the last position scanned in sb when searching for lines.
private int _currentLinePos;
internal AsyncStreamReader(Process process, Stream stream, Action<string> callback, Encoding encoding)
: this(process, stream, callback, encoding, DefaultBufferSize)
{
}
// Creates a new AsyncStreamReader for the given stream. The
// character encoding is set by encoding and the buffer size,
// in number of 16-bit characters, is set by bufferSize.
//
internal AsyncStreamReader(Process process, Stream stream, Action<string> callback, Encoding encoding, int bufferSize)
{
Debug.Assert(process != null && stream != null && encoding != null && callback != null, "Invalid arguments!");
Debug.Assert(stream.CanRead, "Stream must be readable!");
Debug.Assert(bufferSize > 0, "Invalid buffer size!");
Init(process, stream, callback, encoding, bufferSize);
_messageQueue = new Queue<string>();
}
private void Init(Process process, Stream stream, Action<string> callback, Encoding encoding, int bufferSize)
{
_process = process;
_stream = stream;
_encoding = encoding;
_userCallBack = callback;
_decoder = encoding.GetDecoder();
if (bufferSize < MinBufferSize) bufferSize = MinBufferSize;
_byteBuffer = new byte[bufferSize];
_maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize);
_charBuffer = new char[_maxCharsPerBuffer];
_cancelOperation = false;
_eofEvent = new ManualResetEvent(false);
_sb = null;
_bLastCarriageReturn = false;
}
public void Close()
{
Dispose(true);
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (_stream != null)
_stream.Dispose();
}
if (_stream != null)
{
_stream = null;
_encoding = null;
_decoder = null;
_byteBuffer = null;
_charBuffer = null;
}
if (_eofEvent != null)
{
_eofEvent.Dispose();
_eofEvent = null;
}
}
public Encoding CurrentEncoding
{
get { return _encoding; }
}
public Stream BaseStream
{
get { return _stream; }
}
// User calls BeginRead to start the asynchronous read
internal void BeginReadLine()
{
if (_cancelOperation)
{
_cancelOperation = false;
}
if (_sb == null)
{
_sb = new StringBuilder(DefaultBufferSize);
_stream.ReadAsync(_byteBuffer, 0, _byteBuffer.Length).ContinueWith(ReadBuffer, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
}
else
{
FlushMessageQueue();
}
}
internal void CancelOperation()
{
_cancelOperation = true;
}
// This is the async callback function. Only one thread could/should call this.
private void ReadBuffer(Task<int> t)
{
int byteLen;
try
{
byteLen = t.GetAwaiter().GetResult();
}
catch (IOException)
{
// We should ideally consume errors from operations getting cancelled
// so that we don't crash the unsuspecting parent with an unhandled exc.
// This seems to come in 2 forms of exceptions (depending on platform and scenario),
// namely OperationCanceledException and IOException (for errorcode that we don't
// map explicitly).
byteLen = 0; // Treat this as EOF
}
catch (OperationCanceledException)
{
// We should consume any OperationCanceledException from child read here
// so that we don't crash the parent with an unhandled exc
byteLen = 0; // Treat this as EOF
}
if (byteLen == 0)
{
// We're at EOF, we won't call this function again from here on.
lock (_messageQueue)
{
if (_sb.Length != 0)
{
_messageQueue.Enqueue(_sb.ToString());
_sb.Length = 0;
}
_messageQueue.Enqueue(null);
}
try
{
// UserCallback could throw, we should still set the eofEvent
FlushMessageQueue();
}
finally
{
_eofEvent.Set();
}
}
else
{
int charLen = _decoder.GetChars(_byteBuffer, 0, byteLen, _charBuffer, 0);
_sb.Append(_charBuffer, 0, charLen);
GetLinesFromStringBuilder();
_stream.ReadAsync(_byteBuffer, 0, _byteBuffer.Length).ContinueWith(ReadBuffer, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
}
}
// Read lines stored in StringBuilder and the buffer we just read into.
// A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
//
private void GetLinesFromStringBuilder()
{
int currentIndex = _currentLinePos;
int lineStart = 0;
int len = _sb.Length;
// skip a beginning '\n' character of new block if last block ended
// with '\r'
if (_bLastCarriageReturn && (len > 0) && _sb[0] == '\n')
{
currentIndex = 1;
lineStart = 1;
_bLastCarriageReturn = false;
}
while (currentIndex < len)
{
char ch = _sb[currentIndex];
// Note the following common line feed chars:
// \n - UNIX \r\n - DOS \r - Mac
if (ch == '\r' || ch == '\n')
{
string s = _sb.ToString(lineStart, currentIndex - lineStart);
lineStart = currentIndex + 1;
// skip the "\n" character following "\r" character
if ((ch == '\r') && (lineStart < len) && (_sb[lineStart] == '\n'))
{
lineStart++;
currentIndex++;
}
lock (_messageQueue)
{
_messageQueue.Enqueue(s);
}
}
currentIndex++;
}
if (_sb[len - 1] == '\r')
{
_bLastCarriageReturn = true;
}
// Keep the rest characaters which can't form a new line in string builder.
if (lineStart < len)
{
if (lineStart == 0)
{
// we found no breaklines, in this case we cache the position
// so next time we don't have to restart from the beginning
_currentLinePos = currentIndex;
}
else
{
_sb.Remove(0, lineStart);
_currentLinePos = 0;
}
}
else
{
_sb.Length = 0;
_currentLinePos = 0;
}
FlushMessageQueue();
}
private void FlushMessageQueue()
{
while (true)
{
// When we call BeginReadLine, we also need to flush the queue
// So there could be a race between the ReadBuffer and BeginReadLine
// We need to take lock before DeQueue.
if (_messageQueue.Count > 0)
{
lock (_messageQueue)
{
if (_messageQueue.Count > 0)
{
string s = (string)_messageQueue.Dequeue();
// skip if the read is the read is cancelled
// this might happen inside UserCallBack
// However, continue to drain the queue
if (!_cancelOperation)
{
_userCallBack(s);
}
}
}
}
else
{
break;
}
}
}
// Wait until we hit EOF. This is called from Process.WaitForExit
// We will lose some information if we don't do this.
internal void WaitUtilEOF()
{
if (_eofEvent != null)
{
_eofEvent.WaitOne();
_eofEvent.Dispose();
_eofEvent = null;
}
}
}
}
| |
using Signum.Utilities.DataStructures;
using Signum.Entities.Reflection;
using Signum.Utilities.Reflection;
using Signum.Entities.Cache;
using Signum.Engine.Authorization;
using System.Drawing;
using Signum.Entities.Basics;
using System.Xml.Linq;
using Signum.Engine.SchemaInfoTables;
using Signum.Engine.Linq;
using System.IO;
using System.Data;
using Signum.Engine.Scheduler;
using System.Runtime.InteropServices;
using Microsoft.Data.SqlClient;
namespace Signum.Engine.Cache;
public interface IServerBroadcast
{
void Start();
void Send(string methodName, string argument);
event Action<string, string>? Receive;
}
public static class CacheLogic
{
public static IServerBroadcast? ServerBroadcast { get; private set; }
public static bool WithSqlDependency { get; internal set; }
public static bool DropStaleServices = true;
public static FluentInclude<T> WithCache<T>(this FluentInclude<T> fi)
where T : Entity
{
CacheLogic.TryCacheTable(fi.SchemaBuilder, typeof(T));
return fi;
}
public static void AssertStarted(SchemaBuilder sb)
{
sb.AssertDefined(ReflectionTools.GetMethodInfo(() => Start(null!, null, null)));
}
/// <summary>
/// If you have invalidation problems look at exceptions in: select * from sys.transmission_queue
/// If there are exceptions like: 'Could not obtain information about Windows NT group/user'
/// Change login to a SqlServer authentication (i.e.: sa)
/// Change Server Authentication mode and enable SA: http://msdn.microsoft.com/en-us/library/ms188670.aspx
/// Change Database ownership to sa: ALTER AUTHORIZATION ON DATABASE::yourDatabase TO sa
/// </summary>
public static void Start(SchemaBuilder sb, bool? withSqlDependency = null, IServerBroadcast? serverBroadcast = null)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
PermissionAuthLogic.RegisterTypes(typeof(CachePermission));
sb.SwitchGlobalLazyManager(new CacheGlobalLazyManager());
if (withSqlDependency == true && !Connector.Current.SupportsSqlDependency)
throw new InvalidOperationException("Sql Dependency is not supported by the current connection");
WithSqlDependency = withSqlDependency ?? Connector.Current.SupportsSqlDependency;
if (serverBroadcast != null && WithSqlDependency)
throw new InvalidOperationException("cacheInvalidator is only necessary if SqlDependency is not enabled");
ServerBroadcast = serverBroadcast;
if(ServerBroadcast != null)
{
ServerBroadcast!.Receive += ServerBroadcast_Receive;
sb.Schema.BeforeDatabaseAccess += () => ServerBroadcast!.Start();
}
sb.Schema.SchemaCompleted += () => Schema_SchemaCompleted(sb);
sb.Schema.BeforeDatabaseAccess += StartSqlDependencyAndEnableBrocker;
sb.Schema.InvalidateCache += CacheLogic.ForceReset;
}
}
static void Schema_SchemaCompleted(SchemaBuilder sb)
{
foreach (var kvp in VirtualMList.RegisteredVirtualMLists)
{
var type = kvp.Key;
if (controllers.TryGetCN(type) != null)
{
foreach (var vml in kvp.Value)
{
var rType = vml.Value.BackReferenceRoute.RootType;
EntityData data = EntityDataOverrides.TryGetS(rType) ?? EntityKindCache.GetEntityData(rType);
if (data == EntityData.Transactional)
throw new InvalidOperationException($"Type {rType.Name} should be {nameof(EntityData)}.{nameof(EntityData.Master)} because is in a virtual MList of {type.Name} (Master and cached)");
TryCacheTable(sb, rType);
dependencies.Add(type, rType);
inverseDependencies.Add(rType, type);
}
}
}
foreach (var cont in controllers.Values.NotNull())
{
cont.BuildCachedTable();
}
foreach (var cont in controllers.Values.NotNull())
{
cont.CachedTable.SchemaCompleted();
}
}
static void ServerBroadcast_Receive(string methodName, string argument)
{
BroadcastReceivers.TryGetC(methodName)?.Invoke(argument);
}
public static Dictionary<string /*methodName*/, Action<string /*argument*/>> BroadcastReceivers = new Dictionary<string, Action<string>>
{
{ InvalidateTable, ServerBroadcast_InvalidateTable}
};
static void ServerBroadcast_InvalidateTable(string cleanName)
{
Type type = TypeEntity.TryGetType(cleanName)!;
var c = controllers.GetOrThrow(type)!;
c.CachedTable.ResetAll(forceReset: false);
c.NotifyInvalidated();
}
public static TextWriter? LogWriter;
public static List<T> ToListWithInvalidation<T>(this IQueryable<T> simpleQuery, Type type, string exceptionContext, Action<SqlNotificationEventArgs> invalidation)
{
if (!WithSqlDependency)
throw new InvalidOperationException("ToListWithInvalidation requires SqlDependency");
ITranslateResult tr;
using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true }))
tr = ((DbQueryProvider)simpleQuery.Provider).GetRawTranslateResult(simpleQuery.Expression);
void onChange(object sender, SqlNotificationEventArgs args)
{
try
{
if (args.Type != SqlNotificationType.Change)
throw new InvalidOperationException(
"Problems with SqlDependency (Type : {0} Source : {1} Info : {2}) on query: \r\n{3}"
.FormatWith(args.Type, args.Source, args.Info, tr.MainCommand.PlainSql()));
if (args.Info == SqlNotificationInfo.PreviousFire)
throw new InvalidOperationException("The same transaction that loaded the data is invalidating it!") { Data = { { "query", tr.MainCommand.PlainSql() } } };
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine("Change ToListWithInvalidations {0} {1}".FormatWith(typeof(T).TypeName()), exceptionContext);
invalidation(args);
}
catch (Exception e)
{
e.LogException(c => c.ControllerName = exceptionContext);
}
}
SimpleReader? reader = null;
Expression<Func<IProjectionRow, T>> projectorExpression = (Expression<Func<IProjectionRow, T>>)tr.GetMainProjector();
Func<IProjectionRow, T> projector = projectorExpression.Compile();
List<T> list = new List<T>();
CacheLogic.AssertSqlDependencyStarted();
Table table = Schema.Current.Table(type);
DatabaseName? db = table.Name.Schema?.Database;
SqlServerConnector subConnector = (SqlServerConnector)Connector.Current.ForDatabase(db);
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine("Load ToListWithInvalidations {0} {1}".FormatWith(typeof(T).TypeName()), exceptionContext);
using (new EntityCache())
using (var r = EntityCache.NewRetriever())
{
subConnector.ExecuteDataReaderDependency(tr.MainCommand, onChange, StartSqlDependencyAndEnableBrocker, fr =>
{
if (reader == null)
reader = new SimpleReader(fr, r);
list.Add(projector(reader));
}, CommandType.Text);
r.CompleteAll();
}
return list;
}
public static void ExecuteDataReaderOptionalDependency(this Connector connector, SqlPreCommandSimple preCommand, OnChangeEventHandler change, Action<FieldReader> forEach)
{
if (WithSqlDependency)
{
((SqlServerConnector)connector).ExecuteDataReaderDependency(preCommand, change, StartSqlDependencyAndEnableBrocker, forEach, CommandType.Text);
}
else
{
using (var p = preCommand.UnsafeExecuteDataReader())
{
FieldReader reader = new FieldReader(p.Reader);
while (p.Reader.Read())
forEach(reader);
}
}
}
class SimpleReader : IProjectionRow
{
FieldReader reader;
IRetriever retriever;
public SimpleReader(FieldReader reader, IRetriever retriever)
{
this.reader = reader;
this.retriever = retriever;
}
public FieldReader Reader
{
get { return reader; }
}
public IRetriever Retriever
{
get { return retriever; }
}
public IEnumerable<S> Lookup<K, S>(LookupToken token, K key)
{
throw new InvalidOperationException("Subqueries can not be used on simple queries");
}
public MList<S> LookupRequest<K, S>(LookupToken token, K key, MList<S> field)
where K : notnull
{
throw new InvalidOperationException("Subqueries can not be used on simple queries");
}
}
static bool started = false;
internal static void AssertSqlDependencyStarted()
{
if (GloballyDisabled)
return;
if (!started)
throw new InvalidOperationException("call Schema.Current.OnBeforeDatabaseAccess() or Schema.Current.Initialize() before any database access");
}
readonly static object startKeyLock = new object();
public static void StartSqlDependencyAndEnableBrocker()
{
if (!WithSqlDependency)
{
started = true;
return;
}
lock (startKeyLock)
{
SqlServerConnector connector = (SqlServerConnector)Connector.Current;
bool isPostgree = false;
if (DropStaleServices)
{
//to avoid massive logs with SqlQueryNotificationStoredProcedure
//http://rusanu.com/2007/11/10/when-it-rains-it-pours/
var staleServices = (from s in Database.View<SysServiceQueues>()
where s.activation_procedure != null && !Database.View<SysProcedures>().Any(p => "[" + p.Schema().name + "].[" + p.name + "]" == s.activation_procedure)
select new ObjectName(new SchemaName(null, s.Schema().name, isPostgree), s.name, isPostgree)).ToList();
foreach (var s in staleServices)
{
TryDropService(s.Name);
TryDropQueue(s);
}
var oldProcedures = (from p in Database.View<SysProcedures>()
where p.name.Contains("SqlQueryNotificationStoredProcedure-") && !Database.View<SysServiceQueues>().Any(s => "[" + p.Schema().name + "].[" + p.name + "]" == s.activation_procedure)
select new ObjectName(new SchemaName(null, p.Schema().name, isPostgree), p.name, isPostgree)).ToList();
foreach (var item in oldProcedures)
{
try
{
Executor.ExecuteNonQuery(new SqlPreCommandSimple($"DROP PROCEDURE {item}"));
}
catch (SqlException ex)
{
if (ex.Number != 15151)
throw;
}
}
}
foreach (var database in Schema.Current.DatabaseNames())
{
SqlServerConnector sub = (SqlServerConnector)connector.ForDatabase(database);
try
{
try
{
SqlDependency.Start(sub.ConnectionString);
}
catch (InvalidOperationException ex)
{
string databaseName = database?.Name ?? Connector.Current.DatabaseName();
if (ex.Message.Contains("SQL Server Service Broker"))
{
EnableOrCreateBrocker(databaseName);
SqlDependency.Start(sub.ConnectionString);
}
}
}
catch (SqlException e)
{
if (e.Number == 2797)
{
string currentUser = (string)Executor.ExecuteDataTable("SELECT CURRENT_USER").Rows[0][0];
Executor.ExecuteNonQuery("ALTER USER [{0}] WITH DEFAULT_SCHEMA = dbo;".FormatWith(currentUser));
SqlDependency.Start(sub.ConnectionString);
}
else throw;
}
}
RegisterOnShutdown();
started = true;
}
}
private static void TryDropService(string s)
{
try
{
using (var con = (SqlConnection)Connector.Current.CreateConnection())
{
con.Open();
new SqlCommand("DROP SERVICE [{0}]".FormatWith(s), con).ExecuteNonQuery();
}
}
catch (SqlException ex)
{
if (ex.Number != 15151)
throw;
}
}
private static void TryDropQueue(ObjectName s)
{
try
{
using (var con = (SqlConnection)Connector.Current.CreateConnection())
{
con.Open();
new SqlCommand("DROP QUEUE {0}".FormatWith(s), con).ExecuteNonQuery();
}
}
catch (SqlException ex)
{
if (ex.Number != 15151)
throw;
}
}
static void EnableOrCreateBrocker(string databaseName)
{
try
{
using (var tr = Transaction.None())
{
Executor.ExecuteNonQuery("ALTER DATABASE [{0}] SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;".FormatWith(databaseName));
tr.Commit();
}
}
catch (SqlException)
{
using (var tr = Transaction.None())
{
Executor.ExecuteNonQuery("ALTER DATABASE [{0}] SET NEW_BROKER WITH ROLLBACK IMMEDIATE;".FormatWith(databaseName));
tr.Commit();
}
}
}
static bool registered = false;
static void RegisterOnShutdown()
{
if (registered)
return;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
SafeConsole.SetConsoleCtrlHandler(ct =>
{
Shutdown();
return true;
}, true);
}
AppDomain.CurrentDomain.DomainUnload += (o, a) => Shutdown();
registered = true;
}
public static void Shutdown()
{
if (GloballyDisabled || !WithSqlDependency)
return;
var connector = ((SqlServerConnector)Connector.Current);
foreach (var database in Schema.Current.DatabaseNames())
{
SqlServerConnector sub = (SqlServerConnector)connector.ForDatabase(database);
SqlDependency.Stop(sub.ConnectionString);
}
}
class CacheController<T> : CacheControllerBase<T>, ICacheLogicController
where T : Entity
{
public CachedTable<T> cachedTable = null!;
public CachedTableBase CachedTable { get { return cachedTable; } }
public CacheController(Schema schema)
{
var ee = schema.EntityEvents<T>();
ee.CacheController = this;
ee.Saving += ident =>
{
if (ident.IsGraphModified)
DisableAndInvalidate(withUpdates: true); //Even if new, loading the cache afterwars will Timeout
};
ee.PreUnsafeDelete += query => { DisableAndInvalidate(withUpdates: false); return null; };
ee.PreUnsafeUpdate += (update, entityQuery) => { DisableAndInvalidate(withUpdates: true); return null; };
ee.PreUnsafeInsert += (query, constructor, entityQuery) => { DisableAndInvalidate(withUpdates: constructor.Body.Type.IsInstantiationOf(typeof(MListElement<,>))); return constructor; };
ee.PreUnsafeMListDelete += (mlistQuery, entityQuery) => { DisableAndInvalidate(withUpdates: true); return null; };
ee.PreBulkInsert += inMListTable => DisableAndInvalidate(withUpdates: inMListTable);
}
public void BuildCachedTable()
{
cachedTable = new CachedTable<T>(this, new Linq.AliasGenerator(), null, null);
}
private void DisableAndInvalidate(bool withUpdates)
{
if (!withUpdates)
{
DisableTypeInTransaction(typeof(T));
}
else
{
DisableAllConnectedTypesInTransaction(typeof(T));
}
Transaction.PostRealCommit -= Transaction_PostRealCommit;
Transaction.PostRealCommit += Transaction_PostRealCommit;
}
void Transaction_PostRealCommit(Dictionary<string, object> obj)
{
cachedTable.ResetAll(forceReset: false);
NotifyInvalidateAllConnectedTypes(typeof(T));
}
public override bool Enabled
{
get { return !GloballyDisabled && !ExecutionMode.IsCacheDisabled && !IsDisabledInTransaction(typeof(T)) && SystemTime.Current == null; }
}
private void AssertEnabled()
{
if (!Enabled)
throw new InvalidOperationException("Cache for {0} is not enabled".FormatWith(typeof(T).TypeName()));
}
public event EventHandler<CacheEventArgs>? Invalidated;
public void OnChange(object sender, SqlNotificationEventArgs args)
{
NotifyInvalidateAllConnectedTypes(typeof(T));
}
public override void Load()
{
LoadAllConnectedTypes(typeof(T));
}
public void ForceReset()
{
cachedTable.ResetAll(forceReset: true);
}
public override IEnumerable<PrimaryKey> GetAllIds()
{
AssertEnabled();
return cachedTable.GetAllIds();
}
public override string GetToString(PrimaryKey id)
{
AssertEnabled();
return cachedTable.GetToString(id);
}
public override string? TryGetToString(PrimaryKey?/*CSBUG*/ id)
{
AssertEnabled();
return cachedTable.TryGetToString(id!.Value)!;
}
public override void Complete(T entity, IRetriever retriver)
{
AssertEnabled();
cachedTable.Complete(entity, retriver);
}
public void NotifyDisabled()
{
Invalidated?.Invoke(this, CacheEventArgs.Disabled);
}
public void NotifyInvalidated()
{
Invalidated?.Invoke(this, CacheEventArgs.Invalidated);
}
public override List<T> RequestByBackReference<R>(IRetriever retriever, Expression<Func<T, Lite<R>?>> backReference, Lite<R> lite)
{
// throw new InvalidOperationException(); /*CSBUG https://github.com/dotnet/roslyn/issues/33276*/
var dic = this.cachedTable.GetBackReferenceDictionary(backReference);
var ids = dic.TryGetC(lite.Id).EmptyIfNull();
return ids.Select(id => retriever.Complete<T>(id, e => this.Complete(e, retriever))!).ToList();
}
public Type Type
{
get { return typeof(T); }
}
}
public static IEnumerable<Type> SemiControllers { get { return controllers.Where(a=>a.Value == null).Select(a=>a.Key); } }
internal static Dictionary<Type, List<CachedTableBase>> semiControllers = new Dictionary<Type, List<CachedTableBase>>();
static Dictionary<Type, ICacheLogicController?> controllers = new Dictionary<Type, ICacheLogicController?>(); //CachePack
static DirectedGraph<Type> inverseDependencies = new DirectedGraph<Type>();
static DirectedGraph<Type> dependencies = new DirectedGraph<Type>();
public static bool GloballyDisabled { get; set; }
const string DisabledCachesKey = "disabledCaches";
static HashSet<Type> DisabledTypesDuringTransaction()
{
var topUserData = Transaction.TopParentUserData();
if (topUserData.TryGetC(DisabledCachesKey) is not HashSet<Type> hs)
{
topUserData[DisabledCachesKey] = hs = new HashSet<Type>();
}
return hs;
}
static bool IsDisabledInTransaction(Type type)
{
if (!Transaction.HasTransaction)
return false;
return Transaction.TopParentUserData().TryGetC(DisabledCachesKey) is HashSet<Type> disabledTypes && disabledTypes.Contains(type);
}
internal static void DisableTypeInTransaction(Type type)
{
DisabledTypesDuringTransaction().Add(type);
controllers[type]!.NotifyDisabled();
}
internal static void DisableAllConnectedTypesInTransaction(Type type)
{
var connected = inverseDependencies.IndirectlyRelatedTo(type, true);
var hs = DisabledTypesDuringTransaction();
foreach (var stype in connected)
{
hs.Add(stype);
controllers[stype]?.Do(t => t.NotifyDisabled());
}
}
public static Dictionary<Type, EntityData> EntityDataOverrides = new Dictionary<Type, EntityData>();
public static void OverrideEntityData<T>(EntityData data)
{
EntityDataOverrides.AddOrThrow(typeof(T), data, "{0} is already overriden");
}
static void TryCacheTable(SchemaBuilder sb, Type type)
{
if (!controllers.ContainsKey(type))
giCacheTable.GetInvoker(type)(sb);
}
static GenericInvoker<Action<SchemaBuilder>> giCacheTable = new(sb => CacheTable<Entity>(sb));
public static void CacheTable<T>(SchemaBuilder sb) where T : Entity
{
AssertStarted(sb);
EntityData data = EntityDataOverrides.TryGetS(typeof(T)) ?? EntityKindCache.GetEntityData(typeof(T));
if (data == EntityData.Master)
{
var cc = new CacheController<T>(sb.Schema);
controllers.AddOrThrow(typeof(T), cc, "{0} already registered");
TryCacheSubTables(typeof(T), sb);
}
else //data == EntityData.Transactional
{
controllers.AddOrThrow(typeof(T), null, "{0} already registered");
TryCacheSubTables(typeof(T), sb);
}
}
static void TryCacheSubTables(Type type, SchemaBuilder sb)
{
HashSet<Type> relatedTypes = sb.Schema.Table(type)
.DependentTables()
.Where(a => !a.Value.IsEnum)
.Select(t => t.Key.Type)
.ToHashSet();
dependencies.Add(type);
inverseDependencies.Add(type);
foreach (var rType in relatedTypes)
{
TryCacheTable(sb, rType);
dependencies.Add(type, rType);
inverseDependencies.Add(rType, type);
}
}
static ICacheLogicController GetController(Type type)
{
var controller = controllers.GetOrThrow(type, "{0} is not registered in CacheLogic");
if (controller == null)
{
var attr = Schema.Current.Settings.TypeAttribute<EntityKindAttribute>(type);
throw new InvalidOperationException("{0} is just semi cached".FormatWith(type.TypeName()) +
(attr?.EntityData == EntityData.Transactional ? " (consider changing it to EntityData.Master)" : ""));
}
return controller;
}
internal static void LoadAllConnectedTypes(Type type)
{
var connected = dependencies.IndirectlyRelatedTo(type, includeInitialNode: true);
foreach (var stype in connected)
{
var controller = controllers[stype];
if (controller != null)
{
if (controller.CachedTable == null)
throw new InvalidOperationException($@"CacheTable for {stype.Name} is null.
This may be because SchemaCompleted is not yet called and you are accesing some ResetLazy in the Start method.
Remember that the Start could be called with an empty database!");
controller.CachedTable.LoadAll();
}
}
}
const string InvalidateTable = "InvalidateTable";
internal static void NotifyInvalidateAllConnectedTypes(Type type)
{
var connected = inverseDependencies.IndirectlyRelatedTo(type, includeInitialNode: true);
foreach (var stype in connected)
{
var controller = controllers[stype];
if (controller != null)
controller.NotifyInvalidated();
ServerBroadcast?.Send(InvalidateTable, TypeLogic.GetCleanName(stype));
}
}
public static List<CachedTableBase> Statistics()
{
return controllers.Values.NotNull().Select(a => a.CachedTable).OrderByDescending(a => a.Count).ToList();
}
public static CacheType GetCacheType(Type type)
{
if (!type.IsEntity())
throw new ArgumentException("type should be an Entity");
if (!controllers.TryGetValue(type, out ICacheLogicController? controller))
return CacheType.None;
if (controller == null)
return CacheType.Semi;
return CacheType.Cached;
}
public static CachedTableBase GetCachedTable(Type type)
{
return controllers.GetOrThrow(type)!.CachedTable;
}
public static void ForceReset()
{
foreach (var controller in controllers.Values.NotNull())
{
controller.ForceReset();
}
SystemEventLogLogic.Log("CacheLogic.ForceReset");
}
public static XDocument SchemaGraph(Func<Type, bool> cacheHint)
{
var dgml = Schema.Current.ToDirectedGraph().ToDGML(t =>
new[]
{
new XAttribute("Label", t.Name),
new XAttribute("Background", GetColor(t.Type, cacheHint).ToHtml())
}, info => new[]
{
info.IsLite ? new XAttribute("StrokeDashArray", "2 3") : null,
}.NotNull().ToArray());
return dgml;
}
static Color GetColor(Type type, Func<Type, bool> cacheHint)
{
if (type.IsEnumEntityOrSymbol())
return Color.Red;
switch (CacheLogic.GetCacheType(type))
{
case CacheType.Cached: return Color.Purple;
case CacheType.Semi: return Color.Pink;
}
if (typeof(Symbol).IsAssignableFrom(type))
return Color.Orange;
if (cacheHint != null && cacheHint(type))
return Color.Yellow;
return Color.Green;
}
public class CacheGlobalLazyManager : GlobalLazyManager
{
public override void AttachInvalidations(SchemaBuilder sb, InvalidateWith invalidateWith, EventHandler invalidate)
{
if (CacheLogic.GloballyDisabled)
{
base.AttachInvalidations(sb, invalidateWith, invalidate);
}
else
{
void onInvalidation(object? sender, CacheEventArgs args)
{
if (args == CacheEventArgs.Invalidated)
{
invalidate(sender, args);
}
else if (args == CacheEventArgs.Disabled)
{
if (Transaction.InTestTransaction)
{
invalidate(sender, args);
Transaction.Rolledback += dic => invalidate(sender, args);
}
Transaction.PostRealCommit += dic => invalidate(sender, args);
}
}
foreach (var t in invalidateWith.Types)
{
CacheLogic.TryCacheTable(sb, t);
GetController(t).Invalidated += onInvalidation;
}
}
}
public override void OnLoad(SchemaBuilder sb, InvalidateWith invalidateWith)
{
if (CacheLogic.GloballyDisabled)
{
base.OnLoad(sb, invalidateWith);
}
else
{
foreach (var t in invalidateWith.Types)
sb.Schema.CacheController(t)!.Load();
}
}
}
public static void LoadAllControllers()
{
foreach (var c in controllers.Values.NotNull())
{
c.Load();
}
}
internal static ThreadVariable<Dictionary<Type, bool>?> assumeMassiveChangesAsInvalidations = Statics.ThreadVariable<Dictionary<Type, bool>?>("assumeMassiveChangesAsInvalidations");
public static IDisposable AssumeMassiveChangesAsInvalidations<T>(bool assumeInvalidations) where T : Entity
{
var dic = assumeMassiveChangesAsInvalidations.Value;
if (dic == null)
dic = assumeMassiveChangesAsInvalidations.Value = new Dictionary<Type, bool>();
dic.Add(typeof(T), assumeInvalidations);
return new Disposable(() =>
{
dic.Remove(typeof(T));
if (dic.IsEmpty())
assumeMassiveChangesAsInvalidations.Value = null;
});
}
}
internal interface ICacheLogicController : ICacheController
{
Type Type { get; }
event EventHandler<CacheEventArgs> Invalidated;
CachedTableBase CachedTable { get; }
void NotifyDisabled();
void NotifyInvalidated();
void OnChange(object sender, SqlNotificationEventArgs args);
void ForceReset();
void BuildCachedTable();
}
public class CacheEventArgs : EventArgs
{
private CacheEventArgs() { }
public static readonly CacheEventArgs Invalidated = new CacheEventArgs();
public static readonly CacheEventArgs Disabled = new CacheEventArgs();
}
public enum CacheType
{
Cached,
Semi,
None
}
| |
using CommandLine;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace HttpFaultInjector
{
public static class Program
{
private static HttpClient _httpClient;
private static readonly List<(string Option, string Description)> _selectionDescriptions = new List<(string Option, string Description)>()
{
("f", "Full response"),
("p", "Partial Response (full headers, 50% of body), then wait indefinitely"),
("pc", "Partial Response (full headers, 50% of body), then close (TCP FIN)"),
("pa", "Partial Response (full headers, 50% of body), then abort (TCP RST)"),
("pn", "Partial Response (full headers, 50% of body), then finish normally"),
("n", "No response, then wait indefinitely"),
("nc", "No response, then close (TCP FIN)"),
("na", "No response, then abort (TCP RST)")
};
private static readonly string[] _excludedRequestHeaders = new string[] {
// Only applies to request between client and proxy
"Proxy-Connection",
_responseSelectionHeader
};
// Headers which must be set on HttpContent instead of HttpRequestMessage
private static readonly string[] _contentRequestHeaders = new string[] {
"Content-Length",
"Content-Type",
};
private const string _responseSelectionHeader = "x-ms-faultinjector-response-option";
private class Options
{
[Option('i', "insecure", Default = false, HelpText = "Allow insecure upstream SSL certs")]
public bool Insecure { get; set; }
[Option('t', "keep-alive-timeout", Default = 120, HelpText = "Keep-alive timeout (in seconds)")]
public int KeepAliveTimeout { get; set; }
}
public static void Main(string[] args)
{
var parser = new Parser(settings =>
{
settings.CaseSensitive = false;
settings.HelpWriter = Console.Error;
});
parser.ParseArguments<Options>(args).WithParsed(options => Run(options));
}
private static void Run(Options options)
{
if (options.Insecure)
{
_httpClient = new HttpClient(new HttpClientHandler()
{
// Allow insecure SSL certs
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
});
}
else
{
_httpClient = new HttpClient();
}
new WebHostBuilder()
.UseKestrel(kestrelOptions =>
{
kestrelOptions.Listen(IPAddress.Any, 7777);
kestrelOptions.Listen(IPAddress.Any, 7778, listenOptions =>
{
listenOptions.UseHttps("testCert.pfx", "testPassword");
});
kestrelOptions.Limits.KeepAliveTimeout = TimeSpan.FromSeconds(options.KeepAliveTimeout);
})
.Configure(app => app.Run(async context =>
{
try
{
var upstreamResponse = await SendUpstreamRequest(context.Request);
// Attempt to remove the response selection header and use its value to handle the response selection.
if (context.Request.Headers.Remove(_responseSelectionHeader, out var selection))
{
string optionDescription = _selectionDescriptions.FirstOrDefault(kvp => kvp.Option.Equals(selection)).Description;
if (String.IsNullOrEmpty(optionDescription))
{
Console.WriteLine($"Invalid {_responseSelectionHeader} value {selection}.");
}
else if (await TryHandleResponseOption(selection, context, upstreamResponse))
{
Console.WriteLine($"Using response option {optionDescription} from header value.");
return;
}
}
// If we were passed an invalid response selection header, or none, continue prompting the user for input and attempt to handle the response.
while (true)
{
Console.WriteLine();
Console.WriteLine("Select a response then press ENTER:");
foreach (var selectionDescription in _selectionDescriptions)
{
Console.WriteLine($"{selectionDescription.Option}: {selectionDescription.Description}");
}
Console.WriteLine();
selection = Console.ReadLine();
if (await TryHandleResponseOption(selection, context, upstreamResponse))
{
return;
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}))
.Build()
.Run();
}
private static async Task<UpstreamResponse> SendUpstreamRequest(HttpRequest request)
{
var upstreamUriBuilder = new UriBuilder()
{
Scheme = request.Scheme,
Host = request.Host.Host,
Path = request.Path.Value,
Query = request.QueryString.Value,
};
if (request.Host.Port.HasValue)
{
upstreamUriBuilder.Port = request.Host.Port.Value;
}
var upstreamUri = upstreamUriBuilder.Uri;
Console.WriteLine();
Log("Upstream Request");
Log($"URL: {upstreamUri}");
using (var upstreamRequest = new HttpRequestMessage(new HttpMethod(request.Method), upstreamUri))
{
Log("Headers:");
if (request.ContentLength > 0)
{
upstreamRequest.Content = new StreamContent(request.Body);
foreach (var header in request.Headers.Where(h => _contentRequestHeaders.Contains(h.Key)))
{
Log($" {header.Key}:{header.Value.First()}");
upstreamRequest.Content.Headers.Add(header.Key, values: header.Value);
}
}
foreach (var header in request.Headers.Where(h => !_excludedRequestHeaders.Contains(h.Key) && !_contentRequestHeaders.Contains(h.Key)))
{
Log($" {header.Key}:{header.Value.First()}");
if (!upstreamRequest.Headers.TryAddWithoutValidation(header.Key, values: header.Value))
{
throw new InvalidOperationException($"Could not add header {header.Key} with value {header.Value}");
}
}
Log("Sending request to upstream server...");
using (var upstreamResponseMessage = await _httpClient.SendAsync(upstreamRequest))
{
Console.WriteLine();
Log("Upstream Response");
var headers = new List<KeyValuePair<string, StringValues>>();
Log($"StatusCode: {upstreamResponseMessage.StatusCode}");
Log("Headers:");
foreach (var header in upstreamResponseMessage.Headers)
{
Log($" {header.Key}:{header.Value.First()}");
// Must skip "Transfer-Encoding" header, since if it's set manually Kestrel requires you to implement
// your own chunking.
if (string.Equals(header.Key, "Transfer-Encoding", StringComparison.OrdinalIgnoreCase))
{
continue;
}
headers.Add(new KeyValuePair<string, StringValues>(header.Key, header.Value.ToArray()));
}
foreach (var header in upstreamResponseMessage.Content.Headers)
{
Log($" {header.Key}:{header.Value.First()}");
headers.Add(new KeyValuePair<string, StringValues>(header.Key, header.Value.ToArray()));
}
Log("Reading upstream response body...");
var upstreamResponse = new UpstreamResponse()
{
StatusCode = (int)upstreamResponseMessage.StatusCode,
Headers = headers.ToArray(),
Content = await upstreamResponseMessage.Content.ReadAsByteArrayAsync()
};
Log($"ContentLength: {upstreamResponse.Content.Length}");
return upstreamResponse;
}
}
}
private static async Task<bool> TryHandleResponseOption(string selection, HttpContext context, UpstreamResponse upstreamResponse)
{
switch (selection)
{
case "f":
// Full response
await SendDownstreamResponse(upstreamResponse, context.Response);
return true;
case "p":
// Partial Response (full headers, 50% of body), then wait indefinitely
await SendDownstreamResponse(upstreamResponse, context.Response, upstreamResponse.Content.Length / 2);
await Task.Delay(Timeout.InfiniteTimeSpan);
return true;
case "pc":
// Partial Response (full headers, 50% of body), then close (TCP FIN)
await SendDownstreamResponse(upstreamResponse, context.Response, upstreamResponse.Content.Length / 2);
Close(context);
return true;
case "pa":
// Partial Response (full headers, 50% of body), then abort (TCP RST)
await SendDownstreamResponse(upstreamResponse, context.Response, upstreamResponse.Content.Length / 2);
Abort(context);
return true;
case "pn":
// Partial Response (full headers, 50% of body), then finish normally
await SendDownstreamResponse(upstreamResponse, context.Response, upstreamResponse.Content.Length / 2);
return true;
case "n":
// No response, then wait indefinitely
await Task.Delay(Timeout.InfiniteTimeSpan);
return true;
case "nc":
// No response, then close (TCP FIN)
Close(context);
return true;
case "na":
// No response, then abort (TCP RST)
Abort(context);
return true;
default:
Console.WriteLine($"Invalid selection: {selection}");
return false;
}
}
private static async Task SendDownstreamResponse(UpstreamResponse upstreamResponse, HttpResponse response, int? contentBytes = null)
{
Console.WriteLine();
Log("Sending downstream response...");
response.StatusCode = upstreamResponse.StatusCode;
Log($"StatusCode: {upstreamResponse.StatusCode}");
Log("Headers:");
foreach (var header in upstreamResponse.Headers)
{
Log($" {header.Key}:{header.Value}");
response.Headers.Add(header.Key, header.Value);
}
var count = contentBytes ?? upstreamResponse.Content.Length;
Log($"Writing response body of {count} bytes...");
await response.Body.WriteAsync(upstreamResponse.Content, 0, count);
Log($"Finished writing response body");
}
// Close the TCP connection by sending FIN
private static void Close(HttpContext context)
{
context.Abort();
}
// Abort the TCP connection by sending RST
private static void Abort(HttpContext context)
{
// SocketConnection registered "this" as the IConnectionIdFeature among other things.
var socketConnection = context.Features.Get<IConnectionIdFeature>();
var socket = (Socket)socketConnection.GetType().GetField("_socket", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(socketConnection);
socket.LingerState = new LingerOption(true, 0);
socket.Dispose();
}
private static void Log(object value)
{
Console.WriteLine($"[{DateTime.Now:hh:mm:ss.fff}] {value}");
}
private class UpstreamResponse
{
public int StatusCode { get; set; }
public KeyValuePair<string, StringValues>[] Headers { get; set; }
public byte[] Content { get; set; }
}
}
}
| |
//
// Metadata.cs
// s.im.pl serialization
//
// Generated by DotNetTranslator on 11/02/10.
// Copyright 2010 Interface Ecology Lab.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Ecologylab.BigSemantics.MetadataNS.Builtins.Declarations;
using Ecologylab.BigSemantics.MetaMetadataNS;
using Ecologylab.BigSemantics.MetadataNS;
using Ecologylab.BigSemantics.Model.Text;
using Simpl.Fundamental.Net;
using Simpl.Serialization.Attributes;
using Simpl.Serialization;
using Ecologylab.BigSemantics.MetadataNS.Scalar;
namespace Ecologylab.BigSemantics.MetadataNS
{
[SimplInherit]
public class Metadata : MetadataDeclaration, IMetadata
{
private MetaMetadataCompositeField _metaMetadata;
/**
* Hidden reference to the MetaMetadataRepository. DO NOT access this field directly. DO NOT
* create a static public accessor. -- andruid 10/7/09.
*/
private static MetaMetadataRepository _repository;
private MetadataClassDescriptor _classDescriptor;
public Metadata()
{ }
public Metadata(MetaMetadataCompositeField metaMetadata) : this()
{
if (metaMetadata != null)
{
this._metaMetadata = metaMetadata;
string metaMetadataName = metaMetadata.Name;
if (MetadataClassDescriptor.TagName != metaMetadataName)
this.MetaMetadataName = new MetadataString(metaMetadataName);
}
}
public MetaMetadataCompositeField MetaMetadata
{
get { return _metaMetadata ?? GetMetaMetadata(); }
set { _metaMetadata = value; }
}
public virtual MetadataParsedURL Location
{
get { return null; }
}
public virtual bool IsImage
{
get { return false; }
}
private MetaMetadataCompositeField GetMetaMetadata()
{
MetaMetadataCompositeField mm = _metaMetadata;
//mm = await MetaMetadataTranslationScope.Get().Deserialize()
if (_repository == null)
_repository = MetaMetadataRepositoryInit.GetRepository();
if (mm == null && _repository != null)
{
if ( this.MetaMetadataName != null) // get from saved composition
mm = _repository.GetMMByName(this.MetaMetadataName.Value);
if (mm == null)
{
ParsedUri location = Location == null ? null : Location.Value;
if (location != null)
{
mm = IsImage ? _repository.GetImageMM(location) : _repository.GetDocumentMM(location);
// TODO -- also try to resolve by mime type ???
}
if (mm == null)
mm = _repository.GetByClass(this.GetType());
if (mm == null && MetadataClassDescriptor != null)
{
mm = _repository.GetMMByName(MetadataClassDescriptor.TagName);
}
}
if (mm != null)
MetaMetadata = mm;
}
return mm;
}
public MetaMetadataOneLevelNestingEnumerator MetaMetadataIterator(MetaMetadataField metaMetadataField = null)
{
MetaMetadataField firstMetaMetadataField = metaMetadataField ?? this.MetaMetadata;
return new MetaMetadataOneLevelNestingEnumerator(firstMetaMetadataField, this);
}
public void AddMixin(Metadata mixin)
{
if (Mixins == null)
{
Mixins = new List<Metadata>();
}
Mixins.Add(mixin);
}
public MetadataClassDescriptor MetadataClassDescriptor
{
get
{
MetadataClassDescriptor result = this._classDescriptor;
if (result == null)
{
result = (MetadataClassDescriptor) ClassDescriptor.GetClassDescriptor(this);
this._classDescriptor = result;
}
return result;
}
}
public int NumberOfVisibleFields(bool considerAlwaysShow = true)
{
int size = 0;
MetaMetadataOneLevelNestingEnumerator fullEnumerator = FullNonRecursiveMetaMetadataIterator();
// iterate over all fields in this & then in each mixin of this
while (fullEnumerator.MoveNext())
{
MetaMetadataField metaMetadataField = fullEnumerator.Current;
MetaMetadataField metaMetadata = fullEnumerator.CurrentObject(); // stays the same for until we
// iterate over all mfd's for
// it
Metadata currentMetadata = fullEnumerator.CurrentMetadata;
// When the iterator enters the metadata in the mixins "this" in getValueString has to be
// the corresponding metadata in mixin.
bool hasVisibleNonNullField = false;
MetadataFieldDescriptor mfd = metaMetadataField.MetadataFieldDescriptor;
if (metaMetadata.IsChildFieldDisplayed(metaMetadataField.Name))
{
if (mfd.IsScalar && !mfd.IsCollection)
hasVisibleNonNullField = MetadataString.IsNotNullAndEmptyValue(mfd.GetValueString(currentMetadata));
else if (mfd.IsComposite)
{
Metadata nestedMetadata = (Metadata) mfd.GetNestedMetadata(currentMetadata);
hasVisibleNonNullField = (nestedMetadata != null) ? (nestedMetadata.NumberOfVisibleFields() > 0) : false;
}
else if (mfd.IsCollection)
{
ICollection collection = mfd.GetCollection(currentMetadata);
hasVisibleNonNullField = (collection != null) ? (collection.Count > 0) : false;
}
}
// "null" happens with mixins fieldAccessor b'coz getValueString() returns "null".
// TODO use MetaMetadataField.numNonDisplayedFields()
bool isVisibleField = !metaMetadataField.Hide
&& ((considerAlwaysShow && metaMetadataField.AlwaysShow) || hasVisibleNonNullField);
if (isVisibleField)
size++;
}
return size;
}
public MetaMetadataOneLevelNestingEnumerator FullNonRecursiveMetaMetadataIterator(MetaMetadataField metaMetadataField = null)
{
MetaMetadataField firstMetaMetadataField = metaMetadataField ?? MetaMetadata;
return new MetaMetadataOneLevelNestingEnumerator(firstMetaMetadataField, this);
}
#region Implementation of IEnumerable
public IEnumerator<FieldDescriptor> GetEnumerator()
{
return MetadataClassDescriptor.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region Implementation of IMetadata
public ITermVector TermVector
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public ITermVector GetTermVector(HashSet<Metadata> visitedMetadata)
{
throw new NotImplementedException();
}
public void Recycle()
{
throw new NotImplementedException();
}
public void RebuildCompositeTermVector()
{
throw new NotImplementedException();
}
public bool IgnoreInTermVector
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel
{
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Net;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Xml;
using System.IdentityModel.Protocols.WSTrust;
using SafeFreeCredentials = System.IdentityModel.SafeFreeCredentials;
public class ClientCredentialsSecurityTokenManager : SecurityTokenManager
{
ClientCredentials parent;
public ClientCredentialsSecurityTokenManager(ClientCredentials clientCredentials)
{
if (clientCredentials == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("clientCredentials");
}
this.parent = clientCredentials;
}
public ClientCredentials ClientCredentials
{
get { return this.parent; }
}
string GetServicePrincipalName(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement)
{
EndpointAddress targetAddress = initiatorRequirement.TargetAddress;
if (targetAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenRequirementDoesNotSpecifyTargetAddress, initiatorRequirement));
}
IdentityVerifier identityVerifier;
SecurityBindingElement securityBindingElement = initiatorRequirement.SecurityBindingElement;
if (securityBindingElement != null)
{
identityVerifier = securityBindingElement.LocalClientSettings.IdentityVerifier;
}
else
{
identityVerifier = IdentityVerifier.CreateDefault();
}
EndpointIdentity identity;
identityVerifier.TryGetIdentity(targetAddress, out identity);
return SecurityUtils.GetSpnFromIdentity(identity, targetAddress);
}
SspiSecurityToken GetSpnegoClientCredential(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement)
{
InitiatorServiceModelSecurityTokenRequirement sspiCredentialRequirement = new InitiatorServiceModelSecurityTokenRequirement();
sspiCredentialRequirement.TargetAddress = initiatorRequirement.TargetAddress;
sspiCredentialRequirement.TokenType = ServiceModelSecurityTokenTypes.SspiCredential;
sspiCredentialRequirement.Via = initiatorRequirement.Via;
sspiCredentialRequirement.RequireCryptographicToken = false;
sspiCredentialRequirement.SecurityBindingElement = initiatorRequirement.SecurityBindingElement;
sspiCredentialRequirement.MessageSecurityVersion = initiatorRequirement.MessageSecurityVersion;
ChannelParameterCollection parameters;
if (initiatorRequirement.TryGetProperty<ChannelParameterCollection>(ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty, out parameters))
{
sspiCredentialRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = parameters;
}
SecurityTokenProvider sspiTokenProvider = this.CreateSecurityTokenProvider(sspiCredentialRequirement);
SecurityUtils.OpenTokenProviderIfRequired(sspiTokenProvider, TimeSpan.Zero);
SspiSecurityToken sspiToken = (SspiSecurityToken) sspiTokenProvider.GetToken(TimeSpan.Zero);
SecurityUtils.AbortTokenProviderIfRequired(sspiTokenProvider);
return sspiToken;
}
SecurityTokenProvider CreateSpnegoTokenProvider(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement)
{
EndpointAddress targetAddress = initiatorRequirement.TargetAddress;
if (targetAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenRequirementDoesNotSpecifyTargetAddress, initiatorRequirement));
}
SecurityBindingElement securityBindingElement = initiatorRequirement.SecurityBindingElement;
if (securityBindingElement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenProviderRequiresSecurityBindingElement, initiatorRequirement));
}
SspiIssuanceChannelParameter sspiChannelParameter = GetSspiIssuanceChannelParameter(initiatorRequirement);
bool negotiateTokenOnOpen = (sspiChannelParameter == null ? true : sspiChannelParameter.GetTokenOnOpen);
LocalClientSecuritySettings localClientSettings = securityBindingElement.LocalClientSettings;
BindingContext issuerBindingContext = initiatorRequirement.GetProperty<BindingContext>(ServiceModelSecurityTokenRequirement.IssuerBindingContextProperty);
SpnegoTokenProvider spnegoTokenProvider = new SpnegoTokenProvider(sspiChannelParameter != null ? sspiChannelParameter.CredentialsHandle : null, securityBindingElement);
SspiSecurityToken clientSspiToken = GetSpnegoClientCredential(initiatorRequirement);
spnegoTokenProvider.ClientCredential = clientSspiToken.NetworkCredential;
spnegoTokenProvider.IssuerAddress = initiatorRequirement.IssuerAddress;
spnegoTokenProvider.AllowedImpersonationLevel = parent.Windows.AllowedImpersonationLevel;
spnegoTokenProvider.AllowNtlm = clientSspiToken.AllowNtlm;
spnegoTokenProvider.IdentityVerifier = localClientSettings.IdentityVerifier;
spnegoTokenProvider.SecurityAlgorithmSuite = initiatorRequirement.SecurityAlgorithmSuite;
// if this is not a supporting token, authenticate the server
spnegoTokenProvider.AuthenticateServer = !initiatorRequirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.SupportingTokenAttachmentModeProperty);
spnegoTokenProvider.NegotiateTokenOnOpen = negotiateTokenOnOpen;
spnegoTokenProvider.CacheServiceTokens = negotiateTokenOnOpen || localClientSettings.CacheCookies;
spnegoTokenProvider.IssuerBindingContext = issuerBindingContext;
spnegoTokenProvider.MaxServiceTokenCachingTime = localClientSettings.MaxCookieCachingTime;
spnegoTokenProvider.ServiceTokenValidityThresholdPercentage = localClientSettings.CookieRenewalThresholdPercentage;
spnegoTokenProvider.StandardsManager = SecurityUtils.CreateSecurityStandardsManager(initiatorRequirement, this);
spnegoTokenProvider.TargetAddress = targetAddress;
spnegoTokenProvider.Via = initiatorRequirement.GetPropertyOrDefault<Uri>(InitiatorServiceModelSecurityTokenRequirement.ViaProperty, null);
spnegoTokenProvider.ApplicationProtectionRequirements = (issuerBindingContext != null) ? issuerBindingContext.BindingParameters.Find<ChannelProtectionRequirements>() : null;
spnegoTokenProvider.InteractiveNegoExLogonEnabled = this.ClientCredentials.SupportInteractive;
return spnegoTokenProvider;
}
SecurityTokenProvider CreateTlsnegoClientX509TokenProvider(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement)
{
InitiatorServiceModelSecurityTokenRequirement clientX509Requirement = new InitiatorServiceModelSecurityTokenRequirement();
clientX509Requirement.TokenType = SecurityTokenTypes.X509Certificate;
clientX509Requirement.TargetAddress = initiatorRequirement.TargetAddress;
clientX509Requirement.SecurityBindingElement = initiatorRequirement.SecurityBindingElement;
clientX509Requirement.SecurityAlgorithmSuite = initiatorRequirement.SecurityAlgorithmSuite;
clientX509Requirement.RequireCryptographicToken = true;
clientX509Requirement.MessageSecurityVersion = initiatorRequirement.MessageSecurityVersion;
clientX509Requirement.KeyUsage = SecurityKeyUsage.Signature;
clientX509Requirement.KeyType = SecurityKeyType.AsymmetricKey;
clientX509Requirement.Properties[ServiceModelSecurityTokenRequirement.MessageDirectionProperty] = MessageDirection.Output;
ChannelParameterCollection parameters;
if (initiatorRequirement.TryGetProperty<ChannelParameterCollection>(ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty, out parameters))
{
clientX509Requirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = parameters;
}
return this.CreateSecurityTokenProvider(clientX509Requirement);
}
SecurityTokenAuthenticator CreateTlsnegoServerX509TokenAuthenticator(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement)
{
InitiatorServiceModelSecurityTokenRequirement serverX509Requirement = new InitiatorServiceModelSecurityTokenRequirement();
serverX509Requirement.TokenType = SecurityTokenTypes.X509Certificate;
serverX509Requirement.RequireCryptographicToken = true;
serverX509Requirement.SecurityBindingElement = initiatorRequirement.SecurityBindingElement;
serverX509Requirement.MessageSecurityVersion = initiatorRequirement.MessageSecurityVersion;
serverX509Requirement.KeyUsage = SecurityKeyUsage.Exchange;
serverX509Requirement.KeyType = SecurityKeyType.AsymmetricKey;
serverX509Requirement.Properties[ServiceModelSecurityTokenRequirement.MessageDirectionProperty] = MessageDirection.Input;
ChannelParameterCollection parameters;
if (initiatorRequirement.TryGetProperty<ChannelParameterCollection>(ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty, out parameters))
{
serverX509Requirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = parameters;
}
SecurityTokenResolver dummy;
return this.CreateSecurityTokenAuthenticator(serverX509Requirement, out dummy);
}
SspiIssuanceChannelParameter GetSspiIssuanceChannelParameter(SecurityTokenRequirement initiatorRequirement)
{
ChannelParameterCollection channelParameters;
if (initiatorRequirement.TryGetProperty<ChannelParameterCollection>(ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty, out channelParameters))
{
if (channelParameters != null)
{
for (int i = 0; i < channelParameters.Count; ++i)
{
if (channelParameters[i] is SspiIssuanceChannelParameter)
{
return (SspiIssuanceChannelParameter)channelParameters[i];
}
}
}
}
return null;
}
SecurityTokenProvider CreateTlsnegoTokenProvider(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement, bool requireClientCertificate)
{
EndpointAddress targetAddress = initiatorRequirement.TargetAddress;
if (targetAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenRequirementDoesNotSpecifyTargetAddress, initiatorRequirement));
}
SecurityBindingElement securityBindingElement = initiatorRequirement.SecurityBindingElement;
if (securityBindingElement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenProviderRequiresSecurityBindingElement, initiatorRequirement));
}
SspiIssuanceChannelParameter sspiChannelParameter = GetSspiIssuanceChannelParameter(initiatorRequirement);
bool negotiateTokenOnOpen = sspiChannelParameter != null && sspiChannelParameter.GetTokenOnOpen;
LocalClientSecuritySettings localClientSettings = securityBindingElement.LocalClientSettings;
BindingContext issuerBindingContext = initiatorRequirement.GetProperty<BindingContext>(ServiceModelSecurityTokenRequirement.IssuerBindingContextProperty);
TlsnegoTokenProvider tlsnegoTokenProvider = new TlsnegoTokenProvider();
tlsnegoTokenProvider.IssuerAddress = initiatorRequirement.IssuerAddress;
tlsnegoTokenProvider.NegotiateTokenOnOpen = negotiateTokenOnOpen;
tlsnegoTokenProvider.CacheServiceTokens = negotiateTokenOnOpen || localClientSettings.CacheCookies;
if (requireClientCertificate)
{
tlsnegoTokenProvider.ClientTokenProvider = this.CreateTlsnegoClientX509TokenProvider(initiatorRequirement);
}
tlsnegoTokenProvider.IssuerBindingContext = issuerBindingContext;
tlsnegoTokenProvider.ApplicationProtectionRequirements = (issuerBindingContext != null) ? issuerBindingContext.BindingParameters.Find<ChannelProtectionRequirements>() : null;
tlsnegoTokenProvider.MaxServiceTokenCachingTime = localClientSettings.MaxCookieCachingTime;
tlsnegoTokenProvider.SecurityAlgorithmSuite = initiatorRequirement.SecurityAlgorithmSuite;
tlsnegoTokenProvider.ServerTokenAuthenticator = this.CreateTlsnegoServerX509TokenAuthenticator(initiatorRequirement);
tlsnegoTokenProvider.ServiceTokenValidityThresholdPercentage = localClientSettings.CookieRenewalThresholdPercentage;
tlsnegoTokenProvider.StandardsManager = SecurityUtils.CreateSecurityStandardsManager(initiatorRequirement, this);
tlsnegoTokenProvider.TargetAddress = initiatorRequirement.TargetAddress;
tlsnegoTokenProvider.Via = initiatorRequirement.GetPropertyOrDefault<Uri>(InitiatorServiceModelSecurityTokenRequirement.ViaProperty, null);
return tlsnegoTokenProvider;
}
SecurityTokenProvider CreateSecureConversationSecurityTokenProvider(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement)
{
EndpointAddress targetAddress = initiatorRequirement.TargetAddress;
if (targetAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenRequirementDoesNotSpecifyTargetAddress, initiatorRequirement));
}
SecurityBindingElement securityBindingElement = initiatorRequirement.SecurityBindingElement;
if (securityBindingElement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenProviderRequiresSecurityBindingElement, initiatorRequirement));
}
LocalClientSecuritySettings localClientSettings = securityBindingElement.LocalClientSettings;
BindingContext issuerBindingContext = initiatorRequirement.GetProperty<BindingContext>(ServiceModelSecurityTokenRequirement.IssuerBindingContextProperty);
ChannelParameterCollection channelParameters = initiatorRequirement.GetPropertyOrDefault<ChannelParameterCollection>(ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty, null);
bool isSessionMode = initiatorRequirement.SupportSecurityContextCancellation;
if (isSessionMode)
{
SecuritySessionSecurityTokenProvider sessionTokenProvider = new SecuritySessionSecurityTokenProvider(GetCredentialsHandle(initiatorRequirement));
sessionTokenProvider.BootstrapSecurityBindingElement = SecurityUtils.GetIssuerSecurityBindingElement(initiatorRequirement);
sessionTokenProvider.IssuedSecurityTokenParameters = initiatorRequirement.GetProperty<SecurityTokenParameters>(ServiceModelSecurityTokenRequirement.IssuedSecurityTokenParametersProperty);
sessionTokenProvider.IssuerBindingContext = issuerBindingContext;
sessionTokenProvider.KeyEntropyMode = securityBindingElement.KeyEntropyMode;
sessionTokenProvider.SecurityAlgorithmSuite = initiatorRequirement.SecurityAlgorithmSuite;
sessionTokenProvider.StandardsManager = SecurityUtils.CreateSecurityStandardsManager(initiatorRequirement, this);
sessionTokenProvider.TargetAddress = targetAddress;
sessionTokenProvider.Via = initiatorRequirement.GetPropertyOrDefault<Uri>(InitiatorServiceModelSecurityTokenRequirement.ViaProperty, null);
Uri privacyNoticeUri;
if (initiatorRequirement.TryGetProperty<Uri>(ServiceModelSecurityTokenRequirement.PrivacyNoticeUriProperty, out privacyNoticeUri))
{
sessionTokenProvider.PrivacyNoticeUri = privacyNoticeUri;
}
int privacyNoticeVersion;
if (initiatorRequirement.TryGetProperty<int>(ServiceModelSecurityTokenRequirement.PrivacyNoticeVersionProperty, out privacyNoticeVersion))
{
sessionTokenProvider.PrivacyNoticeVersion = privacyNoticeVersion;
}
EndpointAddress localAddress;
if (initiatorRequirement.TryGetProperty<EndpointAddress>(ServiceModelSecurityTokenRequirement.DuplexClientLocalAddressProperty, out localAddress))
{
sessionTokenProvider.LocalAddress = localAddress;
}
sessionTokenProvider.ChannelParameters = channelParameters;
sessionTokenProvider.WebHeaders = initiatorRequirement.WebHeaders;
return sessionTokenProvider;
}
else
{
AcceleratedTokenProvider acceleratedTokenProvider = new AcceleratedTokenProvider(GetCredentialsHandle(initiatorRequirement));
acceleratedTokenProvider.IssuerAddress = initiatorRequirement.IssuerAddress;
acceleratedTokenProvider.BootstrapSecurityBindingElement = SecurityUtils.GetIssuerSecurityBindingElement(initiatorRequirement);
acceleratedTokenProvider.CacheServiceTokens = localClientSettings.CacheCookies;
acceleratedTokenProvider.IssuerBindingContext = issuerBindingContext;
acceleratedTokenProvider.KeyEntropyMode = securityBindingElement.KeyEntropyMode;
acceleratedTokenProvider.MaxServiceTokenCachingTime = localClientSettings.MaxCookieCachingTime;
acceleratedTokenProvider.SecurityAlgorithmSuite = initiatorRequirement.SecurityAlgorithmSuite;
acceleratedTokenProvider.ServiceTokenValidityThresholdPercentage = localClientSettings.CookieRenewalThresholdPercentage;
acceleratedTokenProvider.StandardsManager = SecurityUtils.CreateSecurityStandardsManager(initiatorRequirement, this);
acceleratedTokenProvider.TargetAddress = targetAddress;
acceleratedTokenProvider.Via = initiatorRequirement.GetPropertyOrDefault<Uri>(InitiatorServiceModelSecurityTokenRequirement.ViaProperty, null);
Uri privacyNoticeUri;
if (initiatorRequirement.TryGetProperty<Uri>(ServiceModelSecurityTokenRequirement.PrivacyNoticeUriProperty, out privacyNoticeUri))
{
acceleratedTokenProvider.PrivacyNoticeUri = privacyNoticeUri;
}
acceleratedTokenProvider.ChannelParameters = channelParameters;
int privacyNoticeVersion;
if (initiatorRequirement.TryGetProperty<int>(ServiceModelSecurityTokenRequirement.PrivacyNoticeVersionProperty, out privacyNoticeVersion))
{
acceleratedTokenProvider.PrivacyNoticeVersion = privacyNoticeVersion;
}
return acceleratedTokenProvider;
}
}
SecurityTokenProvider CreateServerX509TokenProvider(EndpointAddress targetAddress)
{
X509Certificate2 targetServerCertificate = null;
if (targetAddress != null)
{
parent.ServiceCertificate.ScopedCertificates.TryGetValue(targetAddress.Uri, out targetServerCertificate);
}
if (targetServerCertificate == null)
{
targetServerCertificate = parent.ServiceCertificate.DefaultCertificate;
}
if ((targetServerCertificate == null) && (targetAddress.Identity != null) && (targetAddress.Identity.GetType() == typeof(X509CertificateEndpointIdentity)))
{
targetServerCertificate = ((X509CertificateEndpointIdentity)targetAddress.Identity).Certificates[0];
}
if (targetServerCertificate != null)
{
return new X509SecurityTokenProvider(targetServerCertificate);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ServiceCertificateNotProvidedOnClientCredentials, targetAddress.Uri)));
}
}
X509SecurityTokenAuthenticator CreateServerX509TokenAuthenticator()
{
return new X509SecurityTokenAuthenticator(parent.ServiceCertificate.Authentication.GetCertificateValidator(), false);
}
X509SecurityTokenAuthenticator CreateServerSslX509TokenAuthenticator()
{
if (parent.ServiceCertificate.SslCertificateAuthentication != null)
{
return new X509SecurityTokenAuthenticator(parent.ServiceCertificate.SslCertificateAuthentication.GetCertificateValidator(), false);
}
return CreateServerX509TokenAuthenticator();
}
bool IsDigestAuthenticationScheme(SecurityTokenRequirement requirement)
{
if (requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty))
{
AuthenticationSchemes authScheme = (AuthenticationSchemes)requirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty];
if (!authScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.HttpRequiresSingleAuthScheme, authScheme));
}
return (authScheme == AuthenticationSchemes.Digest);
}
else
{
return false;
}
}
internal protected bool IsIssuedSecurityTokenRequirement(SecurityTokenRequirement requirement)
{
if (requirement != null && requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.IssuerAddressProperty))
{
// handle all issued token requirements except for spnego, tlsnego and secure conversation
if (requirement.TokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego || requirement.TokenType == ServiceModelSecurityTokenTypes.MutualSslnego
|| requirement.TokenType == ServiceModelSecurityTokenTypes.SecureConversation || requirement.TokenType == ServiceModelSecurityTokenTypes.Spnego)
{
return false;
}
else
{
return true;
}
}
return false;
}
void CopyIssuerChannelBehaviorsAndAddSecurityCredentials(IssuedSecurityTokenProvider federationTokenProvider, KeyedByTypeCollection<IEndpointBehavior> issuerChannelBehaviors, EndpointAddress issuerAddress)
{
if (issuerChannelBehaviors != null)
{
foreach (IEndpointBehavior behavior in issuerChannelBehaviors)
{
if (behavior is SecurityCredentialsManager)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.IssuerChannelBehaviorsCannotContainSecurityCredentialsManager, issuerAddress, typeof(SecurityCredentialsManager))));
}
federationTokenProvider.IssuerChannelBehaviors.Add(behavior);
}
}
federationTokenProvider.IssuerChannelBehaviors.Add(parent);
}
SecurityKeyEntropyMode GetIssuerBindingKeyEntropyModeOrDefault(Binding issuerBinding)
{
BindingElementCollection bindingElements = issuerBinding.CreateBindingElements();
SecurityBindingElement securityBindingElement = bindingElements.Find<SecurityBindingElement>();
if (securityBindingElement != null)
{
return securityBindingElement.KeyEntropyMode;
}
else
{
return parent.IssuedToken.DefaultKeyEntropyMode;
}
}
void GetIssuerBindingSecurityVersion(Binding issuerBinding, MessageSecurityVersion issuedTokenParametersDefaultMessageSecurityVersion, SecurityBindingElement outerSecurityBindingElement, out MessageSecurityVersion messageSecurityVersion, out SecurityTokenSerializer tokenSerializer)
{
// Logic for setting version is:
// 1. use issuer SBE
// 2. use ITSP
// 3. use outer SBE
//
messageSecurityVersion = null;
if (issuerBinding != null)
{
BindingElementCollection bindingElements = issuerBinding.CreateBindingElements();
SecurityBindingElement securityBindingElement = bindingElements.Find<SecurityBindingElement>();
if (securityBindingElement != null)
{
messageSecurityVersion = securityBindingElement.MessageSecurityVersion;
}
}
if (messageSecurityVersion == null)
{
if (issuedTokenParametersDefaultMessageSecurityVersion != null)
{
messageSecurityVersion = issuedTokenParametersDefaultMessageSecurityVersion;
}
else if (outerSecurityBindingElement != null)
{
messageSecurityVersion = outerSecurityBindingElement.MessageSecurityVersion;
}
}
if (messageSecurityVersion == null)
{
messageSecurityVersion = MessageSecurityVersion.Default;
}
tokenSerializer = this.CreateSecurityTokenSerializer(messageSecurityVersion.SecurityTokenVersion);
}
IssuedSecurityTokenProvider CreateIssuedSecurityTokenProvider(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement, FederatedClientCredentialsParameters actAsOnBehalfOfParameters)
{
if (initiatorRequirement.TargetAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenRequirementDoesNotSpecifyTargetAddress, initiatorRequirement));
}
SecurityBindingElement securityBindingElement = initiatorRequirement.SecurityBindingElement;
if (securityBindingElement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenProviderRequiresSecurityBindingElement, initiatorRequirement));
}
EndpointAddress issuerAddress = initiatorRequirement.IssuerAddress;
Binding issuerBinding = initiatorRequirement.IssuerBinding;
//
// If the issuer address is indeed anonymous or null, we will try the local issuer
//
bool isLocalIssuer = (issuerAddress == null || issuerAddress.Equals(EndpointAddress.AnonymousAddress));
if (isLocalIssuer)
{
issuerAddress = parent.IssuedToken.LocalIssuerAddress;
issuerBinding = parent.IssuedToken.LocalIssuerBinding;
}
if (issuerAddress == null)
{
// if issuer address is still null then the user forgot to specify the local issuer
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.StsAddressNotSet, initiatorRequirement.TargetAddress)));
}
if (issuerBinding == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.StsBindingNotSet, issuerAddress)));
}
Uri issuerUri = issuerAddress.Uri;
KeyedByTypeCollection<IEndpointBehavior> issuerChannelBehaviors;
if (!parent.IssuedToken.IssuerChannelBehaviors.TryGetValue(issuerAddress.Uri, out issuerChannelBehaviors) && isLocalIssuer)
{
issuerChannelBehaviors = parent.IssuedToken.LocalIssuerChannelBehaviors;
}
IssuedSecurityTokenProvider federationTokenProvider = new IssuedSecurityTokenProvider(GetCredentialsHandle(initiatorRequirement));
federationTokenProvider.TokenHandlerCollectionManager = this.parent.SecurityTokenHandlerCollectionManager;
federationTokenProvider.TargetAddress = initiatorRequirement.TargetAddress;
CopyIssuerChannelBehaviorsAndAddSecurityCredentials(federationTokenProvider, issuerChannelBehaviors, issuerAddress);
federationTokenProvider.CacheIssuedTokens = parent.IssuedToken.CacheIssuedTokens;
federationTokenProvider.IdentityVerifier = securityBindingElement.LocalClientSettings.IdentityVerifier;
federationTokenProvider.IssuerAddress = issuerAddress;
federationTokenProvider.IssuerBinding = issuerBinding;
federationTokenProvider.KeyEntropyMode = GetIssuerBindingKeyEntropyModeOrDefault(issuerBinding);
federationTokenProvider.MaxIssuedTokenCachingTime = parent.IssuedToken.MaxIssuedTokenCachingTime;
federationTokenProvider.SecurityAlgorithmSuite = initiatorRequirement.SecurityAlgorithmSuite;
MessageSecurityVersion issuerSecurityVersion;
SecurityTokenSerializer issuerSecurityTokenSerializer;
IssuedSecurityTokenParameters issuedTokenParameters = initiatorRequirement.GetProperty<IssuedSecurityTokenParameters>(ServiceModelSecurityTokenRequirement.IssuedSecurityTokenParametersProperty);
GetIssuerBindingSecurityVersion(issuerBinding, issuedTokenParameters.DefaultMessageSecurityVersion, initiatorRequirement.SecurityBindingElement, out issuerSecurityVersion, out issuerSecurityTokenSerializer);
federationTokenProvider.MessageSecurityVersion = issuerSecurityVersion;
federationTokenProvider.SecurityTokenSerializer = issuerSecurityTokenSerializer;
federationTokenProvider.IssuedTokenRenewalThresholdPercentage = parent.IssuedToken.IssuedTokenRenewalThresholdPercentage;
IEnumerable<XmlElement> tokenRequestParameters = issuedTokenParameters.CreateRequestParameters(issuerSecurityVersion, issuerSecurityTokenSerializer);
if (tokenRequestParameters != null)
{
foreach (XmlElement requestParameter in tokenRequestParameters)
{
federationTokenProvider.TokenRequestParameters.Add(requestParameter);
}
}
ChannelParameterCollection channelParameters;
if (initiatorRequirement.TryGetProperty<ChannelParameterCollection>(ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty, out channelParameters))
{
federationTokenProvider.ChannelParameters = channelParameters;
}
federationTokenProvider.SetupActAsOnBehalfOfParameters(actAsOnBehalfOfParameters);
return federationTokenProvider;
}
public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement)
{
return this.CreateSecurityTokenProvider(tokenRequirement, false);
}
internal SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement, bool disableInfoCard)
{
if (tokenRequirement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement");
}
SecurityTokenProvider result = null;
if (disableInfoCard || !CardSpaceTryCreateSecurityTokenProviderStub(tokenRequirement, this, out result))
{
if (tokenRequirement is RecipientServiceModelSecurityTokenRequirement && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate && tokenRequirement.KeyUsage == SecurityKeyUsage.Exchange)
{
// this is the uncorrelated duplex case
if (parent.ClientCertificate.Certificate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ClientCertificateNotProvidedOnClientCredentials)));
}
result = new X509SecurityTokenProvider(parent.ClientCertificate.Certificate);
}
else if (tokenRequirement is InitiatorServiceModelSecurityTokenRequirement)
{
InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement;
#pragma warning suppress 56506 // initiatorRequirement will never be null due to the preceding 'is' validation.
string tokenType = initiatorRequirement.TokenType;
if (IsIssuedSecurityTokenRequirement(initiatorRequirement))
{
FederatedClientCredentialsParameters additionalParameters = this.FindFederatedChannelParameters(tokenRequirement);
if (additionalParameters != null && additionalParameters.IssuedSecurityToken != null)
{
return new SimpleSecurityTokenProvider(additionalParameters.IssuedSecurityToken, tokenRequirement);
}
result = CreateIssuedSecurityTokenProvider(initiatorRequirement, additionalParameters);
}
else if (tokenType == SecurityTokenTypes.X509Certificate)
{
if (initiatorRequirement.Properties.ContainsKey(SecurityTokenRequirement.KeyUsageProperty) && initiatorRequirement.KeyUsage == SecurityKeyUsage.Exchange)
{
result = CreateServerX509TokenProvider(initiatorRequirement.TargetAddress);
}
else
{
if (parent.ClientCertificate.Certificate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ClientCertificateNotProvidedOnClientCredentials)));
}
result = new X509SecurityTokenProvider(parent.ClientCertificate.Certificate);
}
}
else if (tokenType == SecurityTokenTypes.Kerberos)
{
string spn = GetServicePrincipalName(initiatorRequirement);
result = new KerberosSecurityTokenProviderWrapper(
new KerberosSecurityTokenProvider(spn, parent.Windows.AllowedImpersonationLevel, SecurityUtils.GetNetworkCredentialOrDefault(parent.Windows.ClientCredential)),
GetCredentialsHandle(initiatorRequirement));
}
else if (tokenType == SecurityTokenTypes.UserName)
{
if (parent.UserName.UserName == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UserNamePasswordNotProvidedOnClientCredentials)));
}
result = new UserNameSecurityTokenProvider(parent.UserName.UserName, parent.UserName.Password);
}
else if (tokenType == ServiceModelSecurityTokenTypes.SspiCredential)
{
if (IsDigestAuthenticationScheme(initiatorRequirement))
{
result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(parent.HttpDigest.ClientCredential), true, parent.HttpDigest.AllowedImpersonationLevel);
}
else
{
#pragma warning disable 618 // to disable AllowNtlm obsolete wanring.
result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(parent.Windows.ClientCredential),
parent.Windows.AllowNtlm,
parent.Windows.AllowedImpersonationLevel);
#pragma warning restore 618
}
}
else if (tokenType == ServiceModelSecurityTokenTypes.Spnego)
{
result = CreateSpnegoTokenProvider(initiatorRequirement);
}
else if (tokenType == ServiceModelSecurityTokenTypes.MutualSslnego)
{
result = CreateTlsnegoTokenProvider(initiatorRequirement, true);
}
else if (tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego)
{
result = CreateTlsnegoTokenProvider(initiatorRequirement, false);
}
else if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation)
{
result = CreateSecureConversationSecurityTokenProvider(initiatorRequirement);
}
}
}
if ((result == null) && !tokenRequirement.IsOptionalToken)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenManagerCannotCreateProviderForRequirement, tokenRequirement)));
}
return result;
}
bool CardSpaceTryCreateSecurityTokenProviderStub(SecurityTokenRequirement tokenRequirement, ClientCredentialsSecurityTokenManager clientCredentialsTokenManager, out SecurityTokenProvider provider)
{
return InfoCardHelper.TryCreateSecurityTokenProvider(tokenRequirement, clientCredentialsTokenManager, out provider);
}
protected SecurityTokenSerializer CreateSecurityTokenSerializer(SecurityVersion version)
{
if (version == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version"));
}
return this.CreateSecurityTokenSerializer(MessageSecurityTokenVersion.GetSecurityTokenVersion(version, true));
}
public override SecurityTokenSerializer CreateSecurityTokenSerializer(SecurityTokenVersion version)
{
if (version == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version");
}
if (this.parent != null && this.parent.UseIdentityConfiguration)
{
return this.WrapTokenHandlersAsSecurityTokenSerializer(version);
}
MessageSecurityTokenVersion wsVersion = version as MessageSecurityTokenVersion;
if (wsVersion != null)
{
return new WSSecurityTokenSerializer(wsVersion.SecurityVersion, wsVersion.TrustVersion, wsVersion.SecureConversationVersion, wsVersion.EmitBspRequiredAttributes, null, null, null);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenManagerCannotCreateSerializerForVersion, version)));
}
}
private SecurityTokenSerializer WrapTokenHandlersAsSecurityTokenSerializer(SecurityTokenVersion version)
{
TrustVersion trustVersion = TrustVersion.WSTrust13;
SecureConversationVersion scVersion = SecureConversationVersion.WSSecureConversation13;
SecurityVersion securityVersion = SecurityVersion.WSSecurity11;
foreach (string securitySpecification in version.GetSecuritySpecifications())
{
if (StringComparer.Ordinal.Equals(securitySpecification, WSTrustFeb2005Constants.NamespaceURI))
{
trustVersion = TrustVersion.WSTrustFeb2005;
}
else if (StringComparer.Ordinal.Equals(securitySpecification, WSTrust13Constants.NamespaceURI))
{
trustVersion = TrustVersion.WSTrust13;
}
else if (StringComparer.Ordinal.Equals(securitySpecification, System.IdentityModel.WSSecureConversationFeb2005Constants.Namespace))
{
scVersion = SecureConversationVersion.WSSecureConversationFeb2005;
}
else if (StringComparer.Ordinal.Equals(securitySpecification, System.IdentityModel.WSSecureConversation13Constants.Namespace))
{
scVersion = SecureConversationVersion.WSSecureConversation13;
}
}
securityVersion = FederatedSecurityTokenManager.GetSecurityVersion(version);
//
//
SecurityTokenHandlerCollectionManager sthcm = this.parent.SecurityTokenHandlerCollectionManager;
WsSecurityTokenSerializerAdapter adapter = new WsSecurityTokenSerializerAdapter(sthcm[SecurityTokenHandlerCollectionManager.Usage.Default], securityVersion, trustVersion, scVersion, false, null, null, null);
return adapter;
}
public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver)
{
if (tokenRequirement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement");
}
outOfBandTokenResolver = null;
SecurityTokenAuthenticator result = null;
InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement;
if (initiatorRequirement != null)
{
string tokenType = initiatorRequirement.TokenType;
if (IsIssuedSecurityTokenRequirement(initiatorRequirement))
{
return new GenericXmlSecurityTokenAuthenticator();
}
else if (tokenType == SecurityTokenTypes.X509Certificate)
{
if (initiatorRequirement.IsOutOfBandToken)
{
// when the client side soap security asks for a token authenticator, its for doing
// identity checks on the out of band server certificate
result = new X509SecurityTokenAuthenticator(X509CertificateValidator.None);
}
else if (initiatorRequirement.PreferSslCertificateAuthenticator)
{
result = CreateServerSslX509TokenAuthenticator();
}
else
{
result = CreateServerX509TokenAuthenticator();
}
}
else if (tokenType == SecurityTokenTypes.Rsa)
{
result = new RsaSecurityTokenAuthenticator();
}
else if (tokenType == SecurityTokenTypes.Kerberos)
{
result = new KerberosRequestorSecurityTokenAuthenticator();
}
else if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation
|| tokenType == ServiceModelSecurityTokenTypes.MutualSslnego
|| tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego
|| tokenType == ServiceModelSecurityTokenTypes.Spnego)
{
result = new GenericXmlSecurityTokenAuthenticator();
}
}
else if ((tokenRequirement is RecipientServiceModelSecurityTokenRequirement) && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate)
{
// uncorrelated duplex case
result = CreateServerX509TokenAuthenticator();
}
if (result == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenManagerCannotCreateAuthenticatorForRequirement, tokenRequirement)));
}
return result;
}
SafeFreeCredentials GetCredentialsHandle(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement)
{
SspiIssuanceChannelParameter sspiChannelParameter = GetSspiIssuanceChannelParameter(initiatorRequirement);
return sspiChannelParameter != null ? sspiChannelParameter.CredentialsHandle : null;
}
/// <summary>
/// Looks for the first FederatedClientCredentialsParameters object in the ChannelParameterCollection
/// property on the tokenRequirement.
/// </summary>
internal FederatedClientCredentialsParameters FindFederatedChannelParameters(SecurityTokenRequirement tokenRequirement)
{
FederatedClientCredentialsParameters issuedTokenClientCredentialsParameters = null;
ChannelParameterCollection channelParameterCollection = null;
if (tokenRequirement.TryGetProperty<ChannelParameterCollection>(
ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty,
out channelParameterCollection))
{
if (channelParameterCollection != null)
{
foreach (object obj in channelParameterCollection)
{
issuedTokenClientCredentialsParameters = obj as FederatedClientCredentialsParameters;
if (issuedTokenClientCredentialsParameters != null)
{
break;
}
}
}
}
return issuedTokenClientCredentialsParameters;
}
internal class KerberosSecurityTokenProviderWrapper : CommunicationObjectSecurityTokenProvider
{
KerberosSecurityTokenProvider innerProvider;
SafeFreeCredentials credentialsHandle;
bool ownCredentialsHandle = false;
public KerberosSecurityTokenProviderWrapper(KerberosSecurityTokenProvider innerProvider, SafeFreeCredentials credentialsHandle)
{
this.innerProvider = innerProvider;
this.credentialsHandle = credentialsHandle;
}
public override void OnOpening()
{
base.OnOpening();
if (this.credentialsHandle == null)
{
this.credentialsHandle = SecurityUtils.GetCredentialsHandle("Kerberos", this.innerProvider.NetworkCredential, false);
this.ownCredentialsHandle = true;
}
}
public override void OnClose(TimeSpan timeout)
{
base.OnClose(timeout);
FreeCredentialsHandle();
}
public override void OnAbort()
{
base.OnAbort();
FreeCredentialsHandle();
}
void FreeCredentialsHandle()
{
if (this.credentialsHandle != null)
{
if (this.ownCredentialsHandle)
{
this.credentialsHandle.Close();
}
this.credentialsHandle = null;
}
}
internal SecurityToken GetToken(TimeSpan timeout, ChannelBinding channelbinding)
{
return new KerberosRequestorSecurityToken(this.innerProvider.ServicePrincipalName,
this.innerProvider.TokenImpersonationLevel, this.innerProvider.NetworkCredential,
SecurityUniqueId.Create().Value, this.credentialsHandle, channelbinding);
}
protected override SecurityToken GetTokenCore(TimeSpan timeout)
{
return this.GetToken(timeout, null);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AddDouble()
{
var test = new SimpleBinaryOpTest__AddDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddDouble
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[ElementCount];
private static Double[] _data2 = new Double[ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double> _dataTable;
static SimpleBinaryOpTest__AddDouble()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AddDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.Add(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.Add(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.Add(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Add), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Add), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Add), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AddDouble();
var result = Avx.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(left[0] + right[0]) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.DoubleToInt64Bits(left[i] + right[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Add)}<Double>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpClientMiniStress
{
private static bool HttpStressEnabled => Configuration.Http.StressEnabled;
[ConditionalTheory(nameof(HttpStressEnabled))]
[MemberData(nameof(GetStressOptions))]
public void SingleClient_ManyGets_Sync(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
using (var client = new HttpClient())
{
Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ =>
{
CreateServerAndGet(client, completionOption, responseText);
});
}
}
[ConditionalTheory(nameof(HttpStressEnabled))]
public async Task SingleClient_ManyGets_Async(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
using (var client = new HttpClient())
{
await ForCountAsync(numRequests, dop, i => CreateServerAndGetAsync(client, completionOption, responseText));
}
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[MemberData(nameof(GetStressOptions))]
public void ManyClients_ManyGets(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ =>
{
using (var client = new HttpClient())
{
CreateServerAndGet(client, completionOption, responseText);
}
});
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[MemberData(nameof(PostStressOptions))]
public async Task ManyClients_ManyPosts_Async(int numRequests, int dop, int numBytes)
{
string responseText = CreateResponse("");
await ForCountAsync(numRequests, dop, async i =>
{
using (HttpClient client = new HttpClient())
{
await CreateServerAndPostAsync(client, numBytes, responseText);
}
});
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[InlineData(1000000)]
public void CreateAndDestroyManyClients(int numClients)
{
for (int i = 0; i < numClients; i++)
{
new HttpClient().Dispose();
}
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[InlineData(5000)]
public async Task MakeAndFaultManyRequests(int numRequests)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (var client = new HttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var ep = (IPEndPoint)server.LocalEndPoint;
Task<string>[] tasks =
(from i in Enumerable.Range(0, numRequests)
select client.GetStringAsync($"http://{ep.Address}:{ep.Port}"))
.ToArray();
Assert.All(tasks, t => Assert.Equal(TaskStatus.WaitingForActivation, t.Status));
server.Dispose();
foreach (Task<string> task in tasks)
{
await Assert.ThrowsAnyAsync<HttpRequestException>(() => task);
}
}
}, new LoopbackServer.Options { ListenBacklog = numRequests });
}
public static IEnumerable<object[]> GetStressOptions()
{
foreach (int numRequests in new[] { 5000 }) // number of requests
foreach (int dop in new[] { 1, 32 }) // number of threads
foreach (var completionoption in new[] { HttpCompletionOption.ResponseContentRead, HttpCompletionOption.ResponseHeadersRead })
yield return new object[] { numRequests, dop, completionoption };
}
private static void CreateServerAndGet(HttpClient client, HttpCompletionOption completionOption, string responseText)
{
LoopbackServer.CreateServerAsync((server, url) =>
{
Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption);
LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(reader.ReadLine())) ;
writer.Write(responseText);
s.Shutdown(SocketShutdown.Send);
return Task.FromResult<List<string>>(null);
}).GetAwaiter().GetResult();
getAsync.GetAwaiter().GetResult().Dispose();
return Task.CompletedTask;
}).GetAwaiter().GetResult();
}
private static async Task CreateServerAndGetAsync(HttpClient client, HttpCompletionOption completionOption, string responseText)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync().ConfigureAwait(false))) ;
await writer.WriteAsync(responseText).ConfigureAwait(false);
s.Shutdown(SocketShutdown.Send);
return null;
});
(await getAsync.ConfigureAwait(false)).Dispose();
});
}
public static IEnumerable<object[]> PostStressOptions()
{
foreach (int numRequests in new[] { 5000 }) // number of requests
foreach (int dop in new[] { 1, 32 }) // number of threads
foreach (int numBytes in new[] { 0, 100 }) // number of bytes to post
yield return new object[] { numRequests, dop, numBytes };
}
private static async Task CreateServerAndPostAsync(HttpClient client, int numBytes, string responseText)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var content = new ByteArrayContent(new byte[numBytes]);
Task<HttpResponseMessage> postAsync = client.PostAsync(url, content);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync().ConfigureAwait(false))) ;
for (int i = 0; i < numBytes; i++) Assert.NotEqual(-1, reader.Read());
await writer.WriteAsync(responseText).ConfigureAwait(false);
s.Shutdown(SocketShutdown.Send);
return null;
});
(await postAsync.ConfigureAwait(false)).Dispose();
});
}
[ConditionalFact(nameof(HttpStressEnabled))]
public async Task UnreadResponseMessage_Collectible()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (var client = new HttpClient())
{
Func<Task<WeakReference>> getAsync = async () => new WeakReference(await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead));
Task<WeakReference> wrt = getAsync();
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
await writer.WriteAsync(CreateResponse(new string('a', 32 * 1024)));
WeakReference wr = wrt.GetAwaiter().GetResult();
Assert.True(SpinWait.SpinUntil(() =>
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
return !wr.IsAlive;
}, 10 * 1000), "Response object should have been collected");
return null;
});
}
});
}
private static string CreateResponse(string asciiBody) =>
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Type: text/plain\r\n" +
$"Content-Length: {asciiBody.Length}\r\n" +
"\r\n" +
$"{asciiBody}\r\n";
private static Task ForCountAsync(int count, int dop, Func<int, Task> bodyAsync)
{
var sched = new ThreadPerTaskScheduler();
int nextAvailableIndex = 0;
return Task.WhenAll(Enumerable.Range(0, dop).Select(_ => Task.Factory.StartNew(async delegate
{
int index;
while ((index = Interlocked.Increment(ref nextAvailableIndex) - 1) < count)
{
try { await bodyAsync(index); }
catch
{
Volatile.Write(ref nextAvailableIndex, count); // avoid any further iterations
throw;
}
}
}, CancellationToken.None, TaskCreationOptions.None, sched).Unwrap()));
}
private sealed class ThreadPerTaskScheduler : TaskScheduler
{
protected override void QueueTask(Task task) =>
Task.Factory.StartNew(() => TryExecuteTask(task), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => TryExecuteTask(task);
protected override IEnumerable<Task> GetScheduledTasks() => null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using System.IO;
using BEPUphysics;
using BEPUphysics.Entities;
using Microsoft.Win32;
using ApathyEngine.IO;
using ApathyEngine.Input;
using ApathyEngine.Media;
using ApathyEngine.Menus;
using ApathyEngine.Achievements;
namespace ApathyEngine
{
public abstract class BaseGame : Game
{
/// <summary>
/// Gets the primary GraphicsDeviceManager.
/// </summary>
public GraphicsDeviceManager GDM { get; private set; }
/// <summary>
/// Defines the preferred screen height for the game.
/// </summary>
public virtual static int PreferredScreenHeight { get { return 720; } }
/// <summary>
/// Defines the preferred screen width for the game.
/// </summary>
public virtual static int PreferredScreenWidth { get { return 1280; } }
/// <summary>
/// Gets the game's current state.
/// </summary>
public GameState State { get; protected set; }
/// <summary>
/// Gets the game's previous state.
/// </summary>
public GameState PreviousState { get; protected set; }
/// <summary>
/// Fires when the game state is changed. Passes the current BaseGame instance.
/// </summary>
public event Action<BaseGame> StateChanged;
public SaveManager<T> Manager { get; private set; }
public Loader Loader { get; private set; }
public bool Loading { get; private set; }
protected LoadingScreen LoadingScreen { get; private set; }
protected Texture2D backgroundTex;
protected int alpha = 0;
protected bool readyToLoad = false;
protected bool beenDrawn = false;
/// <summary>
/// Gets a value indicating if the game can current pause while running.
/// </summary>
protected virtual bool canPause
{
get
{
return InputManager.KeyboardState.WasKeyJustPressed(Manager.CurrentSaveWindowsOptions.PauseKey) ||
InputManager.CurrentPad.WasButtonJustPressed(Manager.CurrentSaveXboxOptions.PauseKey);
}
}
/// <summary>
/// Gets the screen clear color.
/// </summary>
protected virtual Color backgroundColor { get { return Color.Black; } }
protected bool successfulRender;
protected bool locked = false;
protected GameState stateLastFrame;
public BaseGame()
{
IsMouseVisible = true;
#if XBOX
Components.Add(new GamerServicesComponent(this));
#endif
Content = new ContentManager(Services);
GDM = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
GDM.PreferredBackBufferWidth = PreferredScreenWidth;
GDM.PreferredBackBufferHeight = PreferredScreenHeight;
// supported resolutions are 800x600, 1280x720, 1366x768, 1980x1020, and 1024x768
int width = GraphicsDevice.DisplayMode.Width;
int height = GraphicsDevice.DisplayMode.Height;
if(width > 800) // this setup doesn't account for aspect ratios, which may be a problem
{
if(width > 1024)
{
if(width > 1280)
{
if(width > 1366)
{
GDM.PreferredBackBufferWidth = 1366;
GDM.PreferredBackBufferHeight = 768;
}
else
{
GDM.PreferredBackBufferWidth = 1280;
GDM.PreferredBackBufferHeight = 720;
}
}
else
{
GDM.PreferredBackBufferWidth = 1024;
GDM.PreferredBackBufferHeight = 768;
}
}
}
else if(width < 800)
{
ShowMissingRequirementMessage(new Exception("The game requires at least an 800x600 screen resolution."));
Exit();
}
else
{
GDM.PreferredBackBufferWidth = 800;
GDM.PreferredBackBufferHeight = 600;
}
GameManager.FirstStageInitialization(this);
AchievementManager.Initialize();
try { Manager = new IOManager(); }
catch { }
if(Manager != null && Manager.SuccessfulLoad)
MenuHandler.SaveLoaded();
GDM.ApplyChanges();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
RenderingDevice.Initialize(GDM, GameManager.Space, Content.Load<Effect>("Shaders/shadowmap"));
LoadingScreen = new LoadingScreen(Content, GraphicsDevice);
backgroundTex = Content.Load<Texture2D>("2D/Splashes and Overlays/Logo");
ApathyExtensions.Initialize(GraphicsDevice);
Resources.Initialize(Content);
#if WINDOWS
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
GDM.DeviceCreated += onGDMCreation;
#endif
}
/// <summary>
/// Provides boilerplate updating code for a game using the Apathy Engine.
/// </summary>
/// <remarks>Put actual update code inside <pre>updateRunning(gameTime)</pre>.</remarks>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
if(stateLastFrame == GameState.Running && game.State == GameState.Paused)
MediaSystem.PlaySoundEffect(SFXOptions.Pause);
stateLastFrame = game.State;
if((!IsActive && Loader != null) || locked)
{
base.Update(gameTime);
return;
}
InputManager.Update(gameTime, MenuHandler.IsSelectingSave);
MediaSystem.Update(gameTime, IsActive);
if(Manager.SaveLoaded)
AccomplishmentManager.Update(gameTime);
if(LoadingScreen != null)
{
IsMouseVisible = false;
if(LoadingScreen.FadeComplete)
{
Loading = true;
IsFixedTimeStep = false;
Loader = LoadingScreen.Update(gameTime);
if(Loader != null)
onLoadComplete();
}
}
else
{
if(game.State == GameState.MainMenu && Loading)
this.IsMouseVisible = false;
else
this.IsMouseVisible = true;
GameState statePrior = game.State;
MenuHandler.Update(gameTime);
bool stateChanged = game.State != statePrior;
if(game.State == GameState.Running)
{
if(canPause && !stateChanged)
game.ChangeState(GameState.Paused);
else
updateRunning(gameTime);
}
}
base.Update(gameTime);
}
/// <summary>
/// Provides standard boilerplate for games using the Apathy Engine. Put actual draw code in
/// <pre>drawRunning()</pre>.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
if(!beenDrawn)
{
MediaSystem.Ready(Content);
beenDrawn = true;
}
if(Loading || !readyToLoad)
{
LoadingScreen.Draw();
return;
}
GraphicsDevice.Clear(backgroundColor);
if(game.State == GameState.Running)
DrawRunning(gameTime);
MenuHandler.Draw(gameTime);
AccomplishmentManager.Draw();
base.Draw(gameTime);
}
/// <summary>
/// Called during Update() when the game is running and needs to be updated.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected virtual void updateRunning(GameTime gameTime)
{
Manager.CurrentSave.Playtime += gameTime.ElapsedGameTime;
GameManager.Space.Update((float)(gameTime.ElapsedGameTime.TotalSeconds));
#if DEBUG
if(InputManager.KeyboardState.IsKeyDown(Keys.Q))
GameManager.Space.Update((float)(gameTime.ElapsedGameTime.TotalSeconds));
#endif
RenderingDevice.Update(gameTime);
if(GameManager.CurrentLevel != null)
GameManager.CurrentLevel.Update(gameTime);
}
/// <summary>
/// Changes the state and raises the StateChanged event. Sets PreviousState accordingly.
/// </summary>
/// <param name="newState">New state to be changed to.</param>
public virtual void ChangeState(GameState newState)
{
PreviousState = State;
State = newState;
if(StateChanged != null)
StateChanged(this);
}
/// <summary>
/// Called during Draw() when the game is running and needs to be drawn.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public virtual void DrawRunning(GameTime gameTime)
{
GameManager.DrawLevel();
}
/// <summary>
/// Executed when loading is completed.
/// </summary>
protected virtual void onLoadComplete()
{
// Content loaded. Use loader members to get at the loaded content.
LoadingScreen = null;
IsFixedTimeStep = true;
Loading = false;
MenuHandler.Create(Loader);
GameManager.Initialize(Loader.Font, Manager);
AchievementManager.Ready();
}
#region Miscellaneous
public void RestartLoad()
{
LoadingScreen = new LoadingScreen(Content, GraphicsDevice);
backgroundTex = Content.Load<Texture2D>("2D/Splashes and Overlays/Logo");
Extensions.Initialize(GraphicsDevice);
Resources.Initialize(Content);
}
protected void onGDMCreation(object sender, EventArgs e)
{
Loader.FullReload();
RenderingDevice.OnGDMCreation(Content.Load<Effect>("Shaders/shadowmap"));
}
protected override void OnExiting(object sender, EventArgs args)
{
try
{
Manager.Save(false);
}
// Ignore errors, it's too late to do anything about them.
catch { }
base.OnExiting(sender, args);
}
protected override void OnActivated(object sender, EventArgs args)
{
if(PreviousState == GameState.Running && Manager.CurrentSaveWindowsOptions.ResumeOnFocus)
ChangeState(GameState.Running);
if(State == GameState.Running)
MediaSystem.PlayAll();
else
MediaSystem.ResumeBGM();
base.OnActivated(sender, args);
}
protected override void OnDeactivated(object sender, EventArgs args)
{
if(State == GameState.Running)
ChangeState(GameState.Paused);
MediaSystem.PauseAll();
base.OnDeactivated(sender, args);
}
#if WINDOWS
/// <summary>
/// Called when the system is locked or unlocked and performs appropriate tasks.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
if(e.Reason == SessionSwitchReason.SessionLock)
{
OnDeactivated(sender, e);
locked = true;
}
else if(e.Reason == SessionSwitchReason.SessionUnlock)
{
OnActivated(sender, e);
locked = false;
}
}
#endif
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using QueryBuilder.Clauses;
namespace QueryBuilder
{
public class SelectQueryBuilder : IQueryBuilder
{
protected bool _distinct = false;
protected TopClause _topClause = new TopClause(100, TopUnit.Percent);
protected List<string> _selectedColumns = new List<string>(); // array of string
protected List<string> _selectedTables = new List<string>(); // array of string
protected List<JoinClause> _joins = new List<JoinClause>(); // array of JoinClause
protected WhereStatement _whereStatement = new WhereStatement();
protected List<OrderByClause> _orderByStatement = new List<OrderByClause>(); // array of OrderByClause
protected List<string> _groupByColumns = new List<string>(); // array of string
protected WhereStatement _havingStatement = new WhereStatement();
internal WhereStatement WhereStatement
{
get { return _whereStatement; }
set { _whereStatement = value; }
}
public SelectQueryBuilder() { }
public SelectQueryBuilder(DbProviderFactory factory)
{
_dbProviderFactory = factory;
}
private DbProviderFactory _dbProviderFactory;
public void SetDbProviderFactory(DbProviderFactory factory)
{
_dbProviderFactory = factory;
}
public bool Distinct
{
get { return _distinct; }
set { _distinct = value; }
}
public int TopRecords
{
get { return _topClause.Quantity; }
set
{
_topClause.Quantity = value;
_topClause.Unit = TopUnit.Records;
}
}
public TopClause TopClause
{
get { return _topClause; }
set { _topClause = value; }
}
public string[] SelectedColumns
{
get
{
if (_selectedColumns.Count > 0)
return _selectedColumns.ToArray();
else
return new string[1] { "*" };
}
}
public string[] SelectedTables
{
get { return _selectedTables.ToArray(); }
}
public void SelectAllColumns()
{
_selectedColumns.Clear();
}
public void SelectCount()
{
SelectColumn("count(1)");
}
public void SelectColumn(string column)
{
_selectedColumns.Clear();
_selectedColumns.Add(column);
}
public void SelectColumns(params string[] columns)
{
_selectedColumns.Clear();
foreach (string column in columns)
{
_selectedColumns.Add(column);
}
}
public void SelectFromTable(string table)
{
_selectedTables.Clear();
_selectedTables.Add(table);
}
public void SelectFromTables(params string[] tables)
{
_selectedTables.Clear();
foreach (string Table in tables)
{
_selectedTables.Add(Table);
}
}
public void AddJoin(JoinClause newJoin)
{
_joins.Add(newJoin);
}
public void AddJoin(JoinType join, string toTableName, string toColumnName, Comparison @operator, string fromTableName, string fromColumnName)
{
JoinClause NewJoin = new JoinClause(join, toTableName, toColumnName, @operator, fromTableName, fromColumnName);
_joins.Add(NewJoin);
}
public WhereStatement Where
{
get { return _whereStatement; }
set { _whereStatement = value; }
}
public void AddWhere(WhereClause clause) { AddWhere(clause, 1); }
public void AddWhere(WhereClause clause, int level)
{
_whereStatement.Add(clause, level);
}
public WhereClause AddWhere(string field, Comparison @operator, object compareValue) { return AddWhere(field, @operator, compareValue, 1); }
public WhereClause AddWhere(Enum field, Comparison @operator, object compareValue) { return AddWhere(field.ToString(), @operator, compareValue, 1); }
public WhereClause AddWhere(string field, Comparison @operator, object compareValue, int level)
{
WhereClause NewWhereClause = new WhereClause(field, @operator, compareValue);
_whereStatement.Add(NewWhereClause, level);
return NewWhereClause;
}
public void AddOrderBy(OrderByClause clause)
{
_orderByStatement.Add(clause);
}
public void AddOrderBy(Enum field, Sorting order) { this.AddOrderBy(field.ToString(), order); }
public void AddOrderBy(string field, Sorting order)
{
OrderByClause NewOrderByClause = new OrderByClause(field, order);
_orderByStatement.Add(NewOrderByClause);
}
public void GroupBy(params string[] columns)
{
foreach (string Column in columns)
{
_groupByColumns.Add(Column);
}
}
public WhereStatement Having
{
get { return _havingStatement; }
set { _havingStatement = value; }
}
public void AddHaving(WhereClause clause) { AddHaving(clause, 1); }
public void AddHaving(WhereClause clause, int level)
{
_havingStatement.Add(clause, level);
}
public WhereClause AddHaving(string field, Comparison @operator, object compareValue) { return AddHaving(field, @operator, compareValue, 1); }
public WhereClause AddHaving(Enum field, Comparison @operator, object compareValue) { return AddHaving(field.ToString(), @operator, compareValue, 1); }
public WhereClause AddHaving(string field, Comparison @operator, object compareValue, int level)
{
WhereClause NewWhereClause = new WhereClause(field, @operator, compareValue);
_havingStatement.Add(NewWhereClause, level);
return NewWhereClause;
}
public DbCommand BuildCommand()
{
return (DbCommand)this.BuildQuery(true);
}
public string BuildQuery()
{
return (string)this.BuildQuery(false);
}
/// <summary>
/// Builds the select query
/// </summary>
/// <returns>Returns a string containing the query, or a DbCommand containing a command with parameters</returns>
private object BuildQuery(bool buildCommand)
{
if (buildCommand && _dbProviderFactory == null)
throw new Exception("Cannot build a command when the Db Factory hasn't been specified. Call SetDbProviderFactory first.");
DbCommand command = null;
if (buildCommand)
command = _dbProviderFactory.CreateCommand();
string Query = "SELECT ";
// Output Distinct
if (_distinct)
{
Query += "DISTINCT ";
}
// Output Top clause
if (!(_topClause.Quantity == 100 & _topClause.Unit == TopUnit.Percent))
{
Query += "TOP " + _topClause.Quantity;
if (_topClause.Unit == TopUnit.Percent)
{
Query += " PERCENT";
}
Query += " ";
}
// Output column names
if (_selectedColumns.Count == 0)
{
if (_selectedTables.Count == 1)
Query += _selectedTables[0] + "."; // By default only select * from the table that was selected. If there are any joins, it is the responsibility of the user to select the needed columns.
Query += "*";
}
else
{
foreach (string ColumnName in _selectedColumns)
{
Query += ColumnName + ',';
}
Query = Query.TrimEnd(','); // Trim de last comma inserted by foreach loop
Query += ' ';
}
// Output table names
if (_selectedTables.Count > 0)
{
Query += " FROM ";
foreach (string TableName in _selectedTables)
{
Query += TableName + ',';
}
Query = Query.TrimEnd(','); // Trim de last comma inserted by foreach loop
Query += ' ';
}
// Output joins
if (_joins.Count > 0)
{
foreach (JoinClause Clause in _joins)
{
string JoinString = "";
switch (Clause.JoinType)
{
case JoinType.InnerJoin: JoinString = "INNER JOIN"; break;
case JoinType.OuterJoin: JoinString = "OUTER JOIN"; break;
case JoinType.LeftJoin: JoinString = "LEFT JOIN"; break;
case JoinType.RightJoin: JoinString = "RIGHT JOIN"; break;
}
JoinString += " " + Clause.ToTable + " ON ";
JoinString += WhereStatement.CreateComparisonClause(Clause.FromTable + '.' + Clause.FromColumn, Clause.ComparisonOperator, new SqlLiteral(Clause.ToTable + '.' + Clause.ToColumn));
Query += JoinString + ' ';
}
}
// Output where statement
if (_whereStatement.ClauseLevels > 0)
{
if (buildCommand)
Query += " WHERE " + _whereStatement.BuildWhereStatement(true, ref command);
else
Query += " WHERE " + _whereStatement.BuildWhereStatement();
}
// Output GroupBy statement
if (_groupByColumns.Count > 0)
{
Query += " GROUP BY ";
foreach (string Column in _groupByColumns)
{
Query += Column + ',';
}
Query = Query.TrimEnd(',');
Query += ' ';
}
// Output having statement
if (_havingStatement.ClauseLevels > 0)
{
// Check if a Group By Clause was set
if (_groupByColumns.Count == 0)
{
throw new Exception("Having statement was set without Group By");
}
if (buildCommand)
Query += " HAVING " + _havingStatement.BuildWhereStatement(true, ref command);
else
Query += " HAVING " + _havingStatement.BuildWhereStatement();
}
// Output OrderBy statement
if (_orderByStatement.Count > 0)
{
Query += " ORDER BY ";
foreach (OrderByClause Clause in _orderByStatement)
{
string OrderByClause = "";
switch (Clause.SortOrder)
{
case Sorting.Ascending:
OrderByClause = Clause.FieldName + " ASC"; break;
case Sorting.Descending:
OrderByClause = Clause.FieldName + " DESC"; break;
}
Query += OrderByClause + ',';
}
Query = Query.TrimEnd(','); // Trim de last AND inserted by foreach loop
Query += ' ';
}
if (buildCommand)
{
// Return the build command
command.CommandText = Query;
return command;
}
else
{
// Return the built query
return Query.Trim();
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/groups/group_bookings_invoices.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 HOLMS.Types.Booking.Groups {
/// <summary>Holder for reflection information generated from booking/groups/group_bookings_invoices.proto</summary>
public static partial class GroupBookingsInvoicesReflection {
#region Descriptor
/// <summary>File descriptor for booking/groups/group_bookings_invoices.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static GroupBookingsInvoicesReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cixib29raW5nL2dyb3Vwcy9ncm91cF9ib29raW5nc19pbnZvaWNlcy5wcm90",
"bxIaaG9sbXMudHlwZXMuYm9va2luZy5ncm91cHMaMGJvb2tpbmcvaW5kaWNh",
"dG9ycy9ncm91cF9ib29raW5nX2luZGljYXRvci5wcm90bxoUcHJpbWl0aXZl",
"L3V1aWQucHJvdG8aFmlhbS9zdGFmZl9tZW1iZXIucHJvdG8aH2dvb2dsZS9w",
"cm90b2J1Zi90aW1lc3RhbXAucHJvdG8iiAMKGkdyb3VwQm9va2luZ0ludm9p",
"Y2VNYXBwaW5nEk8KEGdyb3VwX2Jvb2tpbmdfaWQYASABKAsyNS5ob2xtcy50",
"eXBlcy5ib29raW5nLmluZGljYXRvcnMuR3JvdXBCb29raW5nSW5kaWNhdG9y",
"EhYKDmludm9pY2VfbnVtYmVyGAIgASgFEi8KCmludm9pY2VfaWQYAyABKAsy",
"Gy5ob2xtcy50eXBlcy5wcmltaXRpdmUuVXVpZBIOCgZ2b2lkZWQYBCABKAgS",
"MAoKY3JlYXRlZF9ieRgFIAEoCzIcLmhvbG1zLnR5cGVzLmlhbS5TdGFmZk1l",
"bWJlchIvCgl2b2lkZWRfYnkYBiABKAsyHC5ob2xtcy50eXBlcy5pYW0uU3Rh",
"ZmZNZW1iZXISLQoJdm9pZGVkX2F0GAcgASgLMhouZ29vZ2xlLnByb3RvYnVm",
"LlRpbWVzdGFtcBIuCgpjcmVhdGVkX2F0GAggASgLMhouZ29vZ2xlLnByb3Rv",
"YnVmLlRpbWVzdGFtcEItWg5ib29raW5nL2dyb3Vwc6oCGkhPTE1TLlR5cGVz",
"LkJvb2tpbmcuR3JvdXBzYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.GroupBookingIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.UuidReflection.Descriptor, global::HOLMS.Types.IAM.StaffMemberReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Groups.GroupBookingInvoiceMapping), global::HOLMS.Types.Booking.Groups.GroupBookingInvoiceMapping.Parser, new[]{ "GroupBookingId", "InvoiceNumber", "InvoiceId", "Voided", "CreatedBy", "VoidedBy", "VoidedAt", "CreatedAt" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class GroupBookingInvoiceMapping : pb::IMessage<GroupBookingInvoiceMapping> {
private static readonly pb::MessageParser<GroupBookingInvoiceMapping> _parser = new pb::MessageParser<GroupBookingInvoiceMapping>(() => new GroupBookingInvoiceMapping());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GroupBookingInvoiceMapping> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.Groups.GroupBookingsInvoicesReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GroupBookingInvoiceMapping() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GroupBookingInvoiceMapping(GroupBookingInvoiceMapping other) : this() {
GroupBookingId = other.groupBookingId_ != null ? other.GroupBookingId.Clone() : null;
invoiceNumber_ = other.invoiceNumber_;
InvoiceId = other.invoiceId_ != null ? other.InvoiceId.Clone() : null;
voided_ = other.voided_;
CreatedBy = other.createdBy_ != null ? other.CreatedBy.Clone() : null;
VoidedBy = other.voidedBy_ != null ? other.VoidedBy.Clone() : null;
VoidedAt = other.voidedAt_ != null ? other.VoidedAt.Clone() : null;
CreatedAt = other.createdAt_ != null ? other.CreatedAt.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GroupBookingInvoiceMapping Clone() {
return new GroupBookingInvoiceMapping(this);
}
/// <summary>Field number for the "group_booking_id" field.</summary>
public const int GroupBookingIdFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator groupBookingId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator GroupBookingId {
get { return groupBookingId_; }
set {
groupBookingId_ = value;
}
}
/// <summary>Field number for the "invoice_number" field.</summary>
public const int InvoiceNumberFieldNumber = 2;
private int invoiceNumber_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int InvoiceNumber {
get { return invoiceNumber_; }
set {
invoiceNumber_ = value;
}
}
/// <summary>Field number for the "invoice_id" field.</summary>
public const int InvoiceIdFieldNumber = 3;
private global::HOLMS.Types.Primitive.Uuid invoiceId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.Uuid InvoiceId {
get { return invoiceId_; }
set {
invoiceId_ = value;
}
}
/// <summary>Field number for the "voided" field.</summary>
public const int VoidedFieldNumber = 4;
private bool voided_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Voided {
get { return voided_; }
set {
voided_ = value;
}
}
/// <summary>Field number for the "created_by" field.</summary>
public const int CreatedByFieldNumber = 5;
private global::HOLMS.Types.IAM.StaffMember createdBy_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.IAM.StaffMember CreatedBy {
get { return createdBy_; }
set {
createdBy_ = value;
}
}
/// <summary>Field number for the "voided_by" field.</summary>
public const int VoidedByFieldNumber = 6;
private global::HOLMS.Types.IAM.StaffMember voidedBy_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.IAM.StaffMember VoidedBy {
get { return voidedBy_; }
set {
voidedBy_ = value;
}
}
/// <summary>Field number for the "voided_at" field.</summary>
public const int VoidedAtFieldNumber = 7;
private global::Google.Protobuf.WellKnownTypes.Timestamp voidedAt_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp VoidedAt {
get { return voidedAt_; }
set {
voidedAt_ = value;
}
}
/// <summary>Field number for the "created_at" field.</summary>
public const int CreatedAtFieldNumber = 8;
private global::Google.Protobuf.WellKnownTypes.Timestamp createdAt_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp CreatedAt {
get { return createdAt_; }
set {
createdAt_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GroupBookingInvoiceMapping);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GroupBookingInvoiceMapping other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(GroupBookingId, other.GroupBookingId)) return false;
if (InvoiceNumber != other.InvoiceNumber) return false;
if (!object.Equals(InvoiceId, other.InvoiceId)) return false;
if (Voided != other.Voided) return false;
if (!object.Equals(CreatedBy, other.CreatedBy)) return false;
if (!object.Equals(VoidedBy, other.VoidedBy)) return false;
if (!object.Equals(VoidedAt, other.VoidedAt)) return false;
if (!object.Equals(CreatedAt, other.CreatedAt)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (groupBookingId_ != null) hash ^= GroupBookingId.GetHashCode();
if (InvoiceNumber != 0) hash ^= InvoiceNumber.GetHashCode();
if (invoiceId_ != null) hash ^= InvoiceId.GetHashCode();
if (Voided != false) hash ^= Voided.GetHashCode();
if (createdBy_ != null) hash ^= CreatedBy.GetHashCode();
if (voidedBy_ != null) hash ^= VoidedBy.GetHashCode();
if (voidedAt_ != null) hash ^= VoidedAt.GetHashCode();
if (createdAt_ != null) hash ^= CreatedAt.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 (groupBookingId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(GroupBookingId);
}
if (InvoiceNumber != 0) {
output.WriteRawTag(16);
output.WriteInt32(InvoiceNumber);
}
if (invoiceId_ != null) {
output.WriteRawTag(26);
output.WriteMessage(InvoiceId);
}
if (Voided != false) {
output.WriteRawTag(32);
output.WriteBool(Voided);
}
if (createdBy_ != null) {
output.WriteRawTag(42);
output.WriteMessage(CreatedBy);
}
if (voidedBy_ != null) {
output.WriteRawTag(50);
output.WriteMessage(VoidedBy);
}
if (voidedAt_ != null) {
output.WriteRawTag(58);
output.WriteMessage(VoidedAt);
}
if (createdAt_ != null) {
output.WriteRawTag(66);
output.WriteMessage(CreatedAt);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (groupBookingId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(GroupBookingId);
}
if (InvoiceNumber != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(InvoiceNumber);
}
if (invoiceId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(InvoiceId);
}
if (Voided != false) {
size += 1 + 1;
}
if (createdBy_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(CreatedBy);
}
if (voidedBy_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(VoidedBy);
}
if (voidedAt_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(VoidedAt);
}
if (createdAt_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(CreatedAt);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GroupBookingInvoiceMapping other) {
if (other == null) {
return;
}
if (other.groupBookingId_ != null) {
if (groupBookingId_ == null) {
groupBookingId_ = new global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator();
}
GroupBookingId.MergeFrom(other.GroupBookingId);
}
if (other.InvoiceNumber != 0) {
InvoiceNumber = other.InvoiceNumber;
}
if (other.invoiceId_ != null) {
if (invoiceId_ == null) {
invoiceId_ = new global::HOLMS.Types.Primitive.Uuid();
}
InvoiceId.MergeFrom(other.InvoiceId);
}
if (other.Voided != false) {
Voided = other.Voided;
}
if (other.createdBy_ != null) {
if (createdBy_ == null) {
createdBy_ = new global::HOLMS.Types.IAM.StaffMember();
}
CreatedBy.MergeFrom(other.CreatedBy);
}
if (other.voidedBy_ != null) {
if (voidedBy_ == null) {
voidedBy_ = new global::HOLMS.Types.IAM.StaffMember();
}
VoidedBy.MergeFrom(other.VoidedBy);
}
if (other.voidedAt_ != null) {
if (voidedAt_ == null) {
voidedAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
VoidedAt.MergeFrom(other.VoidedAt);
}
if (other.createdAt_ != null) {
if (createdAt_ == null) {
createdAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
CreatedAt.MergeFrom(other.CreatedAt);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (groupBookingId_ == null) {
groupBookingId_ = new global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator();
}
input.ReadMessage(groupBookingId_);
break;
}
case 16: {
InvoiceNumber = input.ReadInt32();
break;
}
case 26: {
if (invoiceId_ == null) {
invoiceId_ = new global::HOLMS.Types.Primitive.Uuid();
}
input.ReadMessage(invoiceId_);
break;
}
case 32: {
Voided = input.ReadBool();
break;
}
case 42: {
if (createdBy_ == null) {
createdBy_ = new global::HOLMS.Types.IAM.StaffMember();
}
input.ReadMessage(createdBy_);
break;
}
case 50: {
if (voidedBy_ == null) {
voidedBy_ = new global::HOLMS.Types.IAM.StaffMember();
}
input.ReadMessage(voidedBy_);
break;
}
case 58: {
if (voidedAt_ == null) {
voidedAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(voidedAt_);
break;
}
case 66: {
if (createdAt_ == null) {
createdAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(createdAt_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Elasticsearch.Net.Connection;
using Elasticsearch.Net.ConnectionPool;
using Nest.CommonAbstractions.ConnectionSettings;
using Nest.Resolvers;
using Newtonsoft.Json;
using Elasticsearch.Net.Serialization;
namespace Nest
{
/// <summary>
/// Provides NEST's ElasticClient with configurationsettings
/// </summary>
public class ConnectionSettings : ConnectionSettings<ConnectionSettings>
{
public ConnectionSettings(Uri uri = null)
: this(new SingleNodeConnectionPool(uri ?? new Uri("http://localhost:9200"))) { }
public ConnectionSettings(IConnectionPool connectionPool)
: this(connectionPool, null, null) { }
public ConnectionSettings(IConnectionPool connectionPool, IConnection connection)
: this(connectionPool, connection, null) { }
public ConnectionSettings(IConnectionPool connectionPool, IElasticsearchSerializer serializer)
: this(connectionPool, null, serializer) { }
public ConnectionSettings(IConnectionPool connectionPool, IConnection connection, IElasticsearchSerializer serializer)
: base(connectionPool, connection, serializer) { }
}
/// <summary>
/// Control how NEST's behaviour.
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class ConnectionSettings<TConnectionSettings> : ConnectionConfiguration<TConnectionSettings>, IConnectionSettingsValues
where TConnectionSettings : ConnectionSettings<TConnectionSettings>
{
private string _defaultIndex;
string IConnectionSettingsValues.DefaultIndex => this._defaultIndex;
private ElasticInferrer _inferrer;
ElasticInferrer IConnectionSettingsValues.Inferrer => _inferrer;
private Func<Type, string> _defaultTypeNameInferrer;
Func<Type, string> IConnectionSettingsValues.DefaultTypeNameInferrer => _defaultTypeNameInferrer;
private FluentDictionary<Type, string> _defaultIndices;
FluentDictionary<Type, string> IConnectionSettingsValues.DefaultIndices => _defaultIndices;
private FluentDictionary<Type, string> _defaultTypeNames;
FluentDictionary<Type, string> IConnectionSettingsValues.DefaultTypeNames => _defaultTypeNames;
private Func<string, string> _defaultFieldNameInferrer;
Func<string, string> IConnectionSettingsValues.DefaultFieldNameInferrer => _defaultFieldNameInferrer;
//Serializer settings
private Action<JsonSerializerSettings> _modifyJsonSerializerSettings;
Action<JsonSerializerSettings> IConnectionSettingsValues.ModifyJsonSerializerSettings => _modifyJsonSerializerSettings;
private ReadOnlyCollection<Func<Type, JsonConverter>> _contractConverters;
ReadOnlyCollection<Func<Type, JsonConverter>> IConnectionSettingsValues.ContractConverters => _contractConverters;
private FluentDictionary<Type, string> _idProperties = new FluentDictionary<Type, string>();
FluentDictionary<Type, string> IConnectionSettingsValues.IdProperties => _idProperties;
private FluentDictionary<MemberInfo, IPropertyMapping> _propertyMappings = new FluentDictionary<MemberInfo, IPropertyMapping>();
FluentDictionary<MemberInfo, IPropertyMapping> IConnectionSettingsValues.PropertyMappings => _propertyMappings;
ConnectionSettings<TConnectionSettings> _assign(Action<IConnectionSettingsValues> assigner) => Fluent.Assign(this, assigner);
protected ConnectionSettings(IConnectionPool connectionPool, IConnection connection, IElasticsearchSerializer serializer)
: base(connectionPool, connection, serializer)
{
this._defaultTypeNameInferrer = (t => t.Name.ToLowerInvariant());
this._defaultFieldNameInferrer = (p => p.ToCamelCase());
this._defaultIndices = new FluentDictionary<Type, string>();
this._defaultTypeNames = new FluentDictionary<Type, string>();
this._modifyJsonSerializerSettings = (j) => { };
this._contractConverters = Enumerable.Empty<Func<Type, JsonConverter>>().ToList().AsReadOnly();
this._inferrer = new ElasticInferrer(this);
}
protected override IElasticsearchSerializer DefaultSerializer() => new NestSerializer(this);
/// <summary>
/// This calls SetDefaultTypenameInferrer with an implementation that will pluralize type names. This used to be the default prior to Nest 0.90
/// </summary>
public TConnectionSettings PluralizeTypeNames()
{
this._defaultTypeNameInferrer = this.LowerCaseAndPluralizeTypeNameInferrer;
return (TConnectionSettings)this;
}
/// <summary>
/// Allows you to update internal the json.net serializer settings to your liking
/// </summary>
public TConnectionSettings SetJsonSerializerSettingsModifier(Action<JsonSerializerSettings> modifier)
{
if (modifier == null)
return (TConnectionSettings)this;
this._modifyJsonSerializerSettings = modifier;
return (TConnectionSettings)this;
}
/// <summary>
/// Add a custom JsonConverter to the build in json serialization by passing in a predicate for a type.
/// </summary>
public TConnectionSettings AddContractJsonConverters(params Func<Type, JsonConverter>[] contractSelectors)
{
this._contractConverters = contractSelectors.ToList().AsReadOnly();
return (TConnectionSettings)this;
}
/// <summary>
/// Index to default to when no index is specified.
/// </summary>
/// <param name="defaultIndex">When null/empty/not set might throw NRE later on
/// when not specifying index explicitly while indexing.
/// </param>
public TConnectionSettings SetDefaultIndex(string defaultIndex)
{
this._defaultIndex = defaultIndex;
return (TConnectionSettings)this;
}
private string LowerCaseAndPluralizeTypeNameInferrer(Type type)
{
type.ThrowIfNull(nameof(type));
return type.Name.MakePlural().ToLowerInvariant();
}
/// <summary>
/// By default NEST camelCases property name (EmailAddress => emailAddress) expressions
/// either via an ElasticProperty attribute or because they are part of Dictionary where the keys should be treated verbatim.
/// <pre>
/// Here you can register a function that transforms these expressions (default casing, pre- or suffixing)
/// </pre>
/// </summary>
public TConnectionSettings SetDefaultFieldNameInferrer(Func<string, string> FieldNameSelector)
{
this._defaultFieldNameInferrer = FieldNameSelector;
return (TConnectionSettings)this;
}
/// <summary>
/// Allows you to override how type names should be represented, the default will call .ToLowerInvariant() on the type's name.
/// </summary>
public TConnectionSettings SetDefaultTypeNameInferrer(Func<Type, string> defaultTypeNameInferrer)
{
defaultTypeNameInferrer.ThrowIfNull(nameof(defaultTypeNameInferrer));
this._defaultTypeNameInferrer = defaultTypeNameInferrer;
return (TConnectionSettings)this;
}
/// <summary>
/// Map types to a index names. Takes precedence over SetDefaultIndex().
/// </summary>
[Obsolete("Will be removed in NEST 3.0, please move to InferMappingFor<T>()")]
public TConnectionSettings MapDefaultTypeIndices(Action<FluentDictionary<Type, string>> mappingSelector)
{
mappingSelector.ThrowIfNull(nameof(mappingSelector));
mappingSelector(this._defaultIndices);
return (TConnectionSettings)this;
}
/// <summary>
/// Allows you to override typenames, takes priority over the global SetDefaultTypeNameInferrer()
/// </summary>
[Obsolete("Will be removed in NEST 3.0, please move to InferMappingFor<T>()")]
public TConnectionSettings MapDefaultTypeNames(Action<FluentDictionary<Type, string>> mappingSelector)
{
mappingSelector.ThrowIfNull(nameof(mappingSelector));
mappingSelector(this._defaultTypeNames);
return (TConnectionSettings)this;
}
[Obsolete("Will be removed in NEST 3.0, please move to InferMappingFor<T>()")]
public TConnectionSettings MapIdPropertyFor<TDocument>(Expression<Func<TDocument, object>> objectPath)
{
objectPath.ThrowIfNull(nameof(objectPath));
var memberInfo = new MemberInfoResolver(this, objectPath);
var fieldName = memberInfo.Members.Single().Name;
if (this._idProperties.ContainsKey(typeof(TDocument)))
{
if (this._idProperties[typeof(TDocument)].Equals(fieldName))
return (TConnectionSettings)this;
throw new ArgumentException("Cannot map '{0}' as the id property for type '{1}': it already has '{2}' mapped."
.F(fieldName, typeof(TDocument).Name, this._idProperties[typeof(TDocument)]));
}
this._idProperties.Add(typeof(TDocument), fieldName);
return (TConnectionSettings)this;
}
[Obsolete("Will be removed in NEST 3.0, please move to InferMappingFor<T>()")]
public TConnectionSettings MapPropertiesFor<TDocument>(Action<PropertyMappingDescriptor<TDocument>> propertiesSelector)
where TDocument : class
{
propertiesSelector.ThrowIfNull(nameof(propertiesSelector));
var mapper = new PropertyMappingDescriptor<TDocument>();
propertiesSelector(mapper);
ApplyPropertyMappings(mapper.Mappings);
return (TConnectionSettings) this;
}
private void ApplyPropertyMappings<TDocument>(IList<IClrTypePropertyMapping<TDocument>> mappings)
where TDocument : class
{
foreach (var mapping in mappings)
{
var e = mapping.Property;
var memberInfoResolver = new MemberInfoResolver(this, e);
if (memberInfoResolver.Members.Count > 1)
throw new ArgumentException("MapFieldNameFor can only map direct properties");
if (memberInfoResolver.Members.Count < 1)
throw new ArgumentException("Expression {0} does contain any member access".F(e));
var memberInfo = memberInfoResolver.Members.Last();
if (_propertyMappings.ContainsKey(memberInfo))
{
var newName = mapping.NewName;
var mappedAs = _propertyMappings[memberInfo].Name;
var typeName = typeof (TDocument).Name;
if (mappedAs.IsNullOrEmpty() && newName.IsNullOrEmpty())
throw new ArgumentException("Property mapping '{0}' on type is already ignored"
.F(e, newName, mappedAs, typeName));
if (mappedAs.IsNullOrEmpty())
throw new ArgumentException("Property mapping '{0}' on type {3} can not be mapped to '{1}' it already has an ignore mapping"
.F(e, newName, mappedAs, typeName));
if (newName.IsNullOrEmpty())
throw new ArgumentException("Property mapping '{0}' on type {3} can not be ignored it already has a mapping to '{2}'"
.F(e, newName, mappedAs, typeName));
throw new ArgumentException("Property mapping '{0}' on type {3} can not be mapped to '{1}' already mapped as '{2}'"
.F(e, newName, mappedAs, typeName));
}
_propertyMappings.Add(memberInfo, mapping.ToPropertyMapping());
}
}
public TConnectionSettings InferMappingFor<TDocument>(Func<ClrTypeMappingDescriptor<TDocument>, IClrTypeMapping<TDocument>> selector)
where TDocument : class
{
var inferMapping = selector(new ClrTypeMappingDescriptor<TDocument>());
if (!inferMapping.IndexName.IsNullOrEmpty())
this._defaultIndices.Add(inferMapping.Type, inferMapping.IndexName);
if (!inferMapping.TypeName.IsNullOrEmpty())
this._defaultTypeNames.Add(inferMapping.Type, inferMapping.TypeName);
if (inferMapping.IdProperty != null)
#pragma warning disable CS0618 // Type or member is obsolete but will be private in the future OK to call here
this.MapIdPropertyFor<TDocument>(inferMapping.IdProperty);
#pragma warning restore CS0618
if (inferMapping.Properties != null)
this.ApplyPropertyMappings<TDocument>(inferMapping.Properties);
return (TConnectionSettings) this;
}
}
}
| |
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
///
$SSAOPostFx::overallStrength = 2.0;
// TODO: Add small/large param docs.
// The small radius SSAO settings.
$SSAOPostFx::sRadius = 0.1;
$SSAOPostFx::sStrength = 6.0;
$SSAOPostFx::sDepthMin = 0.1;
$SSAOPostFx::sDepthMax = 1.0;
$SSAOPostFx::sDepthPow = 1.0;
$SSAOPostFx::sNormalTol = 0.0;
$SSAOPostFx::sNormalPow = 1.0;
// The large radius SSAO settings.
$SSAOPostFx::lRadius = 1.0;
$SSAOPostFx::lStrength = 10.0;
$SSAOPostFx::lDepthMin = 0.2;
$SSAOPostFx::lDepthMax = 2.0;
$SSAOPostFx::lDepthPow = 0.2;
$SSAOPostFx::lNormalTol = -0.5;
$SSAOPostFx::lNormalPow = 2.0;
/// Valid values: 0, 1, 2
$SSAOPostFx::quality = 0;
///
$SSAOPostFx::blurDepthTol = 0.001;
///
$SSAOPostFx::blurNormalTol = 0.95;
///
$SSAOPostFx::targetScale = "0.5 0.5";
function SSAOPostFx::onAdd( %this )
{
%this.wasVis = "Uninitialized";
%this.quality = "Uninitialized";
}
function SSAOPostFx::preProcess( %this )
{
if ( $SSAOPostFx::quality !$= %this.quality )
{
%this.quality = mClamp( mRound( $SSAOPostFx::quality ), 0, 2 );
%this.setShaderMacro( "QUALITY", %this.quality );
}
%this.targetScale = $SSAOPostFx::targetScale;
}
function SSAOPostFx::setShaderConsts( %this )
{
%this.setShaderConst( "$overallStrength", $SSAOPostFx::overallStrength );
// Abbreviate is s-small l-large.
%this.setShaderConst( "$sRadius", $SSAOPostFx::sRadius );
%this.setShaderConst( "$sStrength", $SSAOPostFx::sStrength );
%this.setShaderConst( "$sDepthMin", $SSAOPostFx::sDepthMin );
%this.setShaderConst( "$sDepthMax", $SSAOPostFx::sDepthMax );
%this.setShaderConst( "$sDepthPow", $SSAOPostFx::sDepthPow );
%this.setShaderConst( "$sNormalTol", $SSAOPostFx::sNormalTol );
%this.setShaderConst( "$sNormalPow", $SSAOPostFx::sNormalPow );
%this.setShaderConst( "$lRadius", $SSAOPostFx::lRadius );
%this.setShaderConst( "$lStrength", $SSAOPostFx::lStrength );
%this.setShaderConst( "$lDepthMin", $SSAOPostFx::lDepthMin );
%this.setShaderConst( "$lDepthMax", $SSAOPostFx::lDepthMax );
%this.setShaderConst( "$lDepthPow", $SSAOPostFx::lDepthPow );
%this.setShaderConst( "$lNormalTol", $SSAOPostFx::lNormalTol );
%this.setShaderConst( "$lNormalPow", $SSAOPostFx::lNormalPow );
%blur = %this->blurY;
%blur.setShaderConst( "$blurDepthTol", $SSAOPostFx::blurDepthTol );
%blur.setShaderConst( "$blurNormalTol", $SSAOPostFx::blurNormalTol );
%blur = %this->blurX;
%blur.setShaderConst( "$blurDepthTol", $SSAOPostFx::blurDepthTol );
%blur.setShaderConst( "$blurNormalTol", $SSAOPostFx::blurNormalTol );
%blur = %this->blurY2;
%blur.setShaderConst( "$blurDepthTol", $SSAOPostFx::blurDepthTol );
%blur.setShaderConst( "$blurNormalTol", $SSAOPostFx::blurNormalTol );
%blur = %this->blurX2;
%blur.setShaderConst( "$blurDepthTol", $SSAOPostFx::blurDepthTol );
%blur.setShaderConst( "$blurNormalTol", $SSAOPostFx::blurNormalTol );
}
function SSAOPostFx::onEnabled( %this )
{
// This tells the AL shaders to reload and sample
// from our #ssaoMask texture target.
$AL::UseSSAOMask = true;
return true;
}
function SSAOPostFx::onDisabled( %this )
{
$AL::UseSSAOMask = false;
}
//-----------------------------------------------------------------------------
// GFXStateBlockData / ShaderData
//-----------------------------------------------------------------------------
singleton GFXStateBlockData( SSAOStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerWrapLinear;
samplerStates[2] = SamplerClampPoint;
};
singleton GFXStateBlockData( SSAOBlurStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampPoint;
};
singleton ShaderData( SSAOShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/postFxV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/SSAO_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/gl/postFxV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/gl/SSAO_P.glsl";
samplerNames[0] = "$deferredMap";
samplerNames[1] = "$randNormalTex";
samplerNames[2] = "$powTable";
pixVersion = 3.0;
};
singleton ShaderData( SSAOBlurYShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/SSAO_Blur_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/SSAO_Blur_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/gl/SSAO_Blur_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/gl/SSAO_Blur_P.glsl";
samplerNames[0] = "$occludeMap";
samplerNames[1] = "$deferredMap";
pixVersion = 3.0;
defines = "BLUR_DIR=float2(0.0,1.0)";
};
singleton ShaderData( SSAOBlurXShader : SSAOBlurYShader )
{
defines = "BLUR_DIR=float2(1.0,0.0)";
};
//-----------------------------------------------------------------------------
// PostEffects
//-----------------------------------------------------------------------------
singleton PostEffect( SSAOPostFx )
{
allowReflectPass = false;
renderTime = "PFXBeforeBin";
renderBin = "AL_LightBinMgr";
renderPriority = 10;
shader = SSAOShader;
stateBlock = SSAOStateBlock;
texture[0] = "#deferred";
texture[1] = "core/images/noise.png";
texture[2] = "#ssao_pow_table";
target = "$outTex";
targetScale = "0.5 0.5";
targetViewport = "PFXTargetViewport_NamedInTexture0";
singleton PostEffect()
{
internalName = "blurY";
shader = SSAOBlurYShader;
stateBlock = SSAOBlurStateBlock;
texture[0] = "$inTex";
texture[1] = "#deferred";
target = "$outTex";
};
singleton PostEffect()
{
internalName = "blurX";
shader = SSAOBlurXShader;
stateBlock = SSAOBlurStateBlock;
texture[0] = "$inTex";
texture[1] = "#deferred";
target = "$outTex";
};
singleton PostEffect()
{
internalName = "blurY2";
shader = SSAOBlurYShader;
stateBlock = SSAOBlurStateBlock;
texture[0] = "$inTex";
texture[1] = "#deferred";
target = "$outTex";
};
singleton PostEffect()
{
internalName = "blurX2";
shader = SSAOBlurXShader;
stateBlock = SSAOBlurStateBlock;
texture[0] = "$inTex";
texture[1] = "#deferred";
// We write to a mask texture which is then
// read by the lighting shaders to mask ambient.
target = "#ssaoMask";
};
};
/// Just here for debug visualization of the
/// SSAO mask texture used during lighting.
singleton PostEffect( SSAOVizPostFx )
{
allowReflectPass = false;
shader = PFX_PassthruShader;
stateBlock = PFX_DefaultStateBlock;
texture[0] = "#ssaoMask";
target = "$backbuffer";
};
singleton ShaderData( SSAOPowTableShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/SSAO_PowerTable_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/SSAO_PowerTable_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/gl/SSAO_PowerTable_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/gl/SSAO_PowerTable_P.glsl";
pixVersion = 2.0;
};
singleton PostEffect( SSAOPowTablePostFx )
{
shader = SSAOPowTableShader;
stateBlock = PFX_DefaultStateBlock;
renderTime = "PFXTexGenOnDemand";
target = "#ssao_pow_table";
targetFormat = "GFXFormatR16F";
targetSize = "256 1";
};
| |
//! \file Checksum.cs
//! \date Sun Apr 24 18:09:11 2016
//! \brief Various checksum algorithms implementations.
//
// Copyright (C) 2014-2016 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.IO;
namespace GameRes.Utility
{
public interface ICheckSum
{
uint Value { get; }
void Update (byte[] buf, int pos, int len);
}
public sealed class Crc32 : ICheckSum
{
/* Table of CRCs of all 8-bit messages. */
private static readonly uint[] crc_table = InitializeTable();
public static uint[] Table { get { return crc_table; } }
/* Make the table for a fast CRC. */
private static uint[] InitializeTable ()
{
uint[] table = new uint[256];
for (uint n = 0; n < 256; n++)
{
uint c = n;
for (int k = 0; k < 8; k++)
{
if (0 != (c & 1))
c = 0xedb88320 ^ (c >> 1);
else
c = c >> 1;
}
table[n] = c;
}
return table;
}
/* Update a running CRC with the bytes buf[0..len-1]--the CRC
should be initialized to all 1's, and the transmitted value
is the 1's complement of the final running CRC (see the
crc() routine below)). */
public static uint UpdateCrc (uint crc, byte[] buf, int pos, int len)
{
uint c = crc;
for (int n = 0; n < len; n++)
c = crc_table[(c ^ buf[pos+n]) & 0xff] ^ (c >> 8);
return c;
}
/* Return the CRC of the bytes buf[0..len-1]. */
public static uint Compute (byte[] buf, int pos, int len)
{
return UpdateCrc (0xffffffff, buf, pos, len) ^ 0xffffffff;
}
private uint m_crc = 0xffffffff;
public uint Value { get { return m_crc^0xffffffff; } }
public void Update (byte[] buf, int pos, int len)
{
m_crc = UpdateCrc (m_crc, buf, pos, len);
}
}
/* Adler32 implementation -- borrowed from the 'zlib' compression library.
Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
public sealed class Adler32 : ICheckSum
{
const uint BASE = 65521; /* largest prime smaller than 65536 */
const int NMAX = 5552;
public static uint Compute (byte[] buf, int pos, int len)
{
if (0 == len)
return 1;
unsafe
{
fixed (byte* ptr = &buf[pos])
{
return Update (1, ptr, len);
}
}
}
public unsafe static uint Compute (byte* buf, int len)
{
return Update (1, buf, len);
}
private unsafe static uint Update (uint adler, byte* buf, int len)
{
/* split Adler-32 into component sums */
uint sum2 = (adler >> 16) & 0xffff;
adler &= 0xffff;
/* in case user likes doing a byte at a time, keep it fast */
if (1 == len) {
adler += *buf;
if (adler >= BASE)
adler -= BASE;
sum2 += adler;
if (sum2 >= BASE)
sum2 -= BASE;
return adler | (sum2 << 16);
}
/* in case short lengths are provided, keep it somewhat fast */
if (len < 16) {
while (0 != len--) {
adler += *buf++;
sum2 += adler;
}
if (adler >= BASE)
adler -= BASE;
sum2 %= BASE; /* only added so many BASE's */
return adler | (sum2 << 16);
}
/* do length NMAX blocks -- requires just one modulo operation */
while (len >= NMAX) {
len -= NMAX;
int n = NMAX / 16; /* NMAX is divisible by 16 */
do {
/* 16 sums unrolled */
adler += buf[0]; sum2 += adler;
adler += buf[1]; sum2 += adler;
adler += buf[2]; sum2 += adler;
adler += buf[3]; sum2 += adler;
adler += buf[4]; sum2 += adler;
adler += buf[5]; sum2 += adler;
adler += buf[6]; sum2 += adler;
adler += buf[7]; sum2 += adler;
adler += buf[8]; sum2 += adler;
adler += buf[9]; sum2 += adler;
adler += buf[10]; sum2 += adler;
adler += buf[11]; sum2 += adler;
adler += buf[12]; sum2 += adler;
adler += buf[13]; sum2 += adler;
adler += buf[14]; sum2 += adler;
adler += buf[15]; sum2 += adler;
buf += 16;
} while (0 != --n);
adler %= BASE;
sum2 %= BASE;
}
/* do remaining bytes (less than NMAX, still just one modulo) */
if (0 != len) { /* avoid modulos if none remaining */
while (len >= 16) {
len -= 16;
adler += buf[0]; sum2 += adler;
adler += buf[1]; sum2 += adler;
adler += buf[2]; sum2 += adler;
adler += buf[3]; sum2 += adler;
adler += buf[4]; sum2 += adler;
adler += buf[5]; sum2 += adler;
adler += buf[6]; sum2 += adler;
adler += buf[7]; sum2 += adler;
adler += buf[8]; sum2 += adler;
adler += buf[9]; sum2 += adler;
adler += buf[10]; sum2 += adler;
adler += buf[11]; sum2 += adler;
adler += buf[12]; sum2 += adler;
adler += buf[13]; sum2 += adler;
adler += buf[14]; sum2 += adler;
adler += buf[15]; sum2 += adler;
buf += 16;
}
while (0 != len--) {
adler += *buf++;
sum2 += adler;
}
adler %= BASE;
sum2 %= BASE;
}
/* return recombined sums */
return adler | (sum2 << 16);
}
private uint m_adler = 1;
public uint Value { get { return m_adler; } }
public void Update (byte[] buf, int pos, int len)
{
if (0 == len)
return;
unsafe
{
fixed (byte* ptr = &buf[pos])
{
m_adler = Update (m_adler, ptr, len);
}
}
}
public unsafe uint Update (byte* buf, int len)
{
m_adler = Update (m_adler, buf, len);
return m_adler;
}
}
public class CheckedStream : Stream
{
Stream m_stream;
ICheckSum m_checksum;
public override bool CanRead { get { return m_stream.CanRead; } }
public override bool CanWrite { get { return m_stream.CanWrite; } }
public override bool CanSeek { get { return m_stream.CanSeek; } }
public override long Length { get { return m_stream.Length; } }
public Stream BaseStream { get { return m_stream; } }
public uint CheckSumValue { get { return m_checksum.Value; } }
public CheckedStream (Stream stream, ICheckSum algorithm)
{
m_stream = stream;
m_checksum = algorithm;
}
public override int Read (byte[] buffer, int offset, int count)
{
int read = m_stream.Read (buffer, offset, count);
if (read > 0)
m_checksum.Update (buffer, offset, read);
return read;
}
public override void Write (byte[] buffer, int offset, int count)
{
m_stream.Write (buffer, offset, count);
m_checksum.Update (buffer, offset, count);
}
public override long Position
{
get { return m_stream.Position; }
set { m_stream.Position = value; }
}
public override void SetLength (long value)
{
m_stream.SetLength (value);
}
public override long Seek (long offset, SeekOrigin origin)
{
return m_stream.Seek (offset, origin);
}
public override void Flush ()
{
m_stream.Flush();
}
}
}
| |
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using PositionType = UnityEngine.UIElements.Position;
namespace UnityEditor.VFX.UIElements
{
class VFXColorField : ValueControl<Color>
{
VisualElement m_ColorDisplay;
VisualElement m_AlphaDisplay;
VisualElement m_NotAlphaDisplay;
VisualElement m_AlphaContainer;
VisualElement m_HDRLabel;
VisualElement m_IndeterminateLabel;
VisualElement m_Container;
VisualElement CreateColorContainer()
{
m_Container = new VisualElement();
m_Container.style.flexDirection = FlexDirection.Column;
m_Container.style.alignItems = Align.Stretch;
m_Container.style.flexGrow = 1f;
m_Container.AddToClassList("colorcontainer");
m_ColorDisplay = new VisualElement();
m_ColorDisplay.style.height = 10;
m_ColorDisplay.AddToClassList("colordisplay");
m_AlphaDisplay = new VisualElement();
m_AlphaDisplay.style.height = 3;
m_AlphaDisplay.style.backgroundColor = Color.white;
m_AlphaDisplay.AddToClassList("alphadisplay");
m_NotAlphaDisplay = new VisualElement();
m_NotAlphaDisplay.style.height = 3;
m_NotAlphaDisplay.style.backgroundColor = Color.black;
m_NotAlphaDisplay.AddToClassList("notalphadisplay");
m_AlphaContainer = new VisualElement();
m_AlphaContainer.style.flexDirection = FlexDirection.Row;
m_AlphaContainer.style.height = 3;
m_ColorDisplay.AddManipulator(new Clickable(OnColorClick));
m_AlphaDisplay.AddManipulator(new Clickable(OnColorClick));
m_HDRLabel = new Label() {
pickingMode = PickingMode.Ignore,
text = "HDR"
};
m_IndeterminateLabel = new Label() {
pickingMode = PickingMode.Ignore,
name = "indeterminate",
text = VFXControlConstants.indeterminateText
};
m_HDRLabel.style.unityTextAlign = TextAnchor.MiddleCenter;
m_HDRLabel.style.position = PositionType.Absolute;
m_HDRLabel.style.top = 0f;
m_HDRLabel.style.bottom = 0f;
m_HDRLabel.style.left = 0f;
m_HDRLabel.style.right = 0f;
m_IndeterminateLabel.style.unityTextAlign = TextAnchor.MiddleLeft;
m_IndeterminateLabel.style.position = PositionType.Absolute;
m_IndeterminateLabel.style.top = 0f;
m_IndeterminateLabel.style.bottom = 0f;
m_IndeterminateLabel.style.left = 0f;
m_IndeterminateLabel.style.right = 0f;
m_HDRLabel.AddToClassList("hdr");
m_Container.Add(m_ColorDisplay);
m_Container.Add(m_AlphaContainer);
m_Container.Add(m_HDRLabel);
m_Container.Add(m_IndeterminateLabel);
m_AlphaContainer.Add(m_AlphaDisplay);
m_AlphaContainer.Add(m_NotAlphaDisplay);
return m_Container;
}
bool m_ShowAlpha = true;
public bool showAlpha
{
get { return m_ShowAlpha; }
set
{
if (m_ShowAlpha != value)
{
m_ShowAlpha = value;
if (m_ShowAlpha)
{
m_Container.Add(m_AlphaContainer);
}
else
{
m_AlphaContainer.RemoveFromHierarchy();
}
}
}
}
void OnColorClick()
{
if (enabledInHierarchy)
ColorPicker.Show(OnColorChanged, m_Value, m_ShowAlpha, true);
}
VisualElement CreateEyeDropper()
{
Texture2D eyeDropperIcon = EditorGUIUtility.IconContent("EyeDropper.Large").image as Texture2D;
VisualElement eyeDropper = new VisualElement();
eyeDropper.style.backgroundImage = eyeDropperIcon;
eyeDropper.style.width = eyeDropperIcon.width;
eyeDropper.style.height = eyeDropperIcon.height;
eyeDropper.RegisterCallback<MouseDownEvent>(OnEyeDropperStart);
return eyeDropper;
}
IVisualElementScheduledItem m_EyeDropperScheduler;
void OnEyeDropperStart(MouseDownEvent e)
{
EyeDropper.Start(OnGammaColorChanged);
m_EyeDropperScheduler = this.schedule.Execute(OnEyeDropperMove).Every(10).StartingIn(10);
m_EyeDropper.UnregisterCallback<MouseDownEvent>(OnEyeDropperStart);
}
void OnEyeDropperMove(TimerState state)
{
Color pickerColor = EyeDropper.GetPickedColor();
if (pickerColor != GetValue())
{
SetValue(pickerColor.linear);
}
}
VisualElement m_EyeDropper;
public VFXColorField(string label) : base(label)
{
VisualElement container = CreateColorContainer();
Add(container);
m_EyeDropper = CreateEyeDropper();
Add(m_EyeDropper);
}
public VFXColorField(Label existingLabel) : base(existingLabel)
{
VisualElement container = CreateColorContainer();
Add(container);
m_EyeDropper = CreateEyeDropper();
Add(m_EyeDropper);
}
void OnGammaColorChanged(Color color)
{
OnColorChanged(color.linear);
}
void OnColorChanged(Color color)
{
SetValue(color);
if (m_EyeDropperScheduler != null)
{
m_EyeDropperScheduler.Pause();
m_EyeDropperScheduler = null;
m_EyeDropper.RegisterCallback<MouseDownEvent>(OnEyeDropperStart);
}
if (OnValueChanged != null)
OnValueChanged();
}
bool m_Indeterminate;
public bool indeterminate
{
get {return m_Indeterminate; }
set
{
m_Indeterminate = value;
ValueToGUI(true);
}
}
protected override void ValueToGUI(bool force)
{
if (indeterminate)
{
m_ColorDisplay.style.backgroundColor = VFXControlConstants.indeterminateTextColor;
m_AlphaDisplay.style.flexGrow = 1f;
m_NotAlphaDisplay.style.flexGrow = 0f;
m_NotAlphaDisplay.style.flexShrink = 0f;
m_HDRLabel.RemoveFromHierarchy();
if (m_IndeterminateLabel.parent == null)
m_Container.Add(m_IndeterminateLabel);
}
else
{
m_IndeterminateLabel.RemoveFromHierarchy();
Color displayedColor = (new Color(m_Value.r, m_Value.g, m_Value.b, 1)).gamma;
m_ColorDisplay.style.backgroundColor = displayedColor;
m_AlphaDisplay.style.flexGrow = m_Value.a;
m_AlphaDisplay.style.flexShrink = 0f;
m_NotAlphaDisplay.style.flexGrow = 1 - m_Value.a;
m_NotAlphaDisplay.style.flexShrink = 0f;
bool hdr = m_Value.r > 1 || m_Value.g > 1 || m_Value.b > 1;
if ((m_HDRLabel.parent != null) != hdr)
{
if (hdr)
{
if (m_HDRLabel.parent == null)
m_Container.Add(m_HDRLabel);
}
else
m_HDRLabel.RemoveFromHierarchy();
}
}
}
}
}
| |
// 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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Microsoft.Tools.ServiceModel.Svcutil
{
internal class OptionBase
{
public OptionBase(string name, params string[] aliases) : this(name, null, aliases)
{
}
/// <summary>
/// .ctr
/// </summary>
/// <param name="name">the option main name.</param>
/// <param name="originalValue">Mainly used for initializaing options which value is a collection.</param>
/// <param name="aliases">Used for identifying the option with different names, this allows for supporting different property names in the JSON schema.</param>
public OptionBase(string name, object originalValue, params string[] aliases)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentNullException(nameof(name));
}
this.Name = name;
_serializationName = name;
_value = originalValue;
this.Aliases = new List<string>();
if (aliases != null && aliases.Length > 0)
{
this.Aliases.AddRange(aliases);
}
this.IsInitialized = true;
}
#region Properties and events
// This property ensures an option is deserialized only once (in case it is defined multiple times in the JSON).
internal bool IsInitialized { get; set; }
// Aliases allows for deserializing a property that is referred to with a different name in the json file.
public List<string> Aliases { get; private set; }
public string Name { get; }
private object _value;
public object Value
{
get { return _value; }
set { SetValue(value); }
}
// this is used in serialization to avoid serializing the option when unset.
public virtual bool HasValue { get { return this.Value != null; } }
// this is used in serialization to avoid serializing the option when it set to its default value.
// obseve that this can be different from the CLR type's default value (Enum with a default different from the first value).
public object DefaultValue { get; set; }
// This allows for supporting a JSON schema with different property names (WCFCS vs SVCUTIL naming conventions).
private string _serializationName;
public string SerializationName
{
get { return _serializationName; }
set { if (value != null && !Aliases.Contains(value)) Aliases.Add(value); _serializationName = value; }
}
// Determines whether the option can be serialized.
// This can be a static value for options that should not be automatically serialized like the 'options' options.
private bool _canSerialize = true;
public virtual bool CanSerialize
{
get { return _canSerialize && this.Value != null && !this.Value.Equals(this.DefaultValue); }
set { _canSerialize = value; }
}
// events
public event EventHandler<OptionEventArgs> ValueChanging;
public event EventHandler<OptionEventArgs> ValueChanged;
public event EventHandler<OptionEventArgs> Serializing;
public event EventHandler<OptionEventArgs> Serialized;
public event EventHandler<OptionDeserializingEventArgs> Deserializing;
public event EventHandler<EventArgs> Deserialized;
#endregion
public bool HasSameId(string optionId)
{
return StringComparer.OrdinalIgnoreCase.Compare(this.Name, optionId) == 0 ||
this.Aliases.Any(a => StringComparer.OrdinalIgnoreCase.Compare(a, optionId) == 0);
}
public virtual void CopyTo(OptionBase other)
{
// serialization name should not be copied as options may define different serialization names for their options.
// other._serializationName = this._serializationName;
// copy the canserialize field, not the property. The field contains a hardcoded value while the property may be computed dynamically!
other._canSerialize = _canSerialize;
other.Value = this.Value;
other.DefaultValue = this.DefaultValue;
other.ValueChanging = this.ValueChanging;
other.ValueChanged = this.ValueChanged;
other.Serializing = this.Serializing;
other.Serialized = this.Serialized;
other.Deserializing = this.Deserializing;
other.Deserialized = this.Deserialized;
}
public OptionBase Clone()
{
var other = new OptionBase((string)this.Name, this.Aliases.ToArray());
CopyTo(other);
return other;
}
protected virtual void SetValue(object value)
{
if (this.Value == null || !this.Value.Equals(value))
{
var oldValue = this.Value;
// notify event handlers (if any) to pre-process the value.
value = OnValueChanging(value);
_value = value;
if (oldValue != _value)
{
OnValueChanged(oldValue);
}
}
}
internal void Deserialize(JToken jToken)
{
// Raise event for handlers to preprocess the JSON value.
var value = OnDeserializing(jToken);
// validate value; observe that null values are not allowed during deserialization.
var stringValue = value as string;
OptionValueParser.ThrowInvalidValueIf(value == null || (stringValue != null && string.IsNullOrWhiteSpace(stringValue)), jToken, this);
_value = value;
OnDeserialized();
}
internal void Serialize(JsonWriter writer, JsonSerializer serializer)
{
if (this.CanSerialize)
{
// ensure the value is converted to a primitive type or a collection of primitive types
// that can be safely serialized.
var value = OptionValueParser.GetSerializationValue(this.Value);
// notify event handlers (if any) to pre-process the JSON value.
value = OnSerializing(value);
serializer.Serialize(writer, value, value?.GetType());
OnSerialized(value);
}
}
protected virtual object OnDeserializing(JToken jToken)
{
if (this.IsInitialized)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Shared.Resources.ErrorOptionAlreadyDeserializedFormat, this.SerializationName));
}
object value = null;
if (Deserializing != null)
{
var e = new OptionDeserializingEventArgs(jToken);
Deserializing(this, e);
value = e.Value;
}
return value;
}
protected virtual void OnDeserialized()
{
this.IsInitialized = true;
this.Deserialized?.Invoke(this, new EventArgs());
}
protected virtual object OnSerializing(object value)
{
if (Serializing != null)
{
var e = new OptionEventArgs(value);
Serializing(this, e);
value = e.Value;
}
return value;
}
protected virtual void OnSerialized(object value)
{
// provide the actual serialized value.
this.Serialized?.Invoke(this, new OptionEventArgs(value));
}
protected virtual object OnValueChanging(object value)
{
if (this.IsInitialized && this.ValueChanging != null)
{
var eventArgs = new OptionEventArgs(value);
this.ValueChanging.Invoke(this, eventArgs);
value = eventArgs.Value;
}
return value;
}
protected virtual void OnValueChanged(object oldValue)
{
if (this.IsInitialized)
{
this.ValueChanged?.Invoke(this, new OptionEventArgs(oldValue));
}
}
public override string ToString()
{
var value = string.Format(CultureInfo.CurrentCulture, "{0}: {1}", this.Name, this.Value?.ToString());
return value;
}
}
public class OptionEventArgs : EventArgs
{
public object Value { get; set; }
public OptionEventArgs(object value)
{
Value = value;
}
}
public class OptionDeserializingEventArgs : OptionEventArgs
{
public JToken JToken { get; set; }
public OptionDeserializingEventArgs(JToken jToken) : base(null)
{
JToken = jToken;
}
}
}
| |
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace Elasticsearch.Client
{
public partial class ElasticsearchClient
{
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesShrinkPut(string index, string target, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesShrinkPutAsync(string index, string target, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="body">The configuration for the target index (`settings` and `aliases`)</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesShrinkPut(string index, string target, Stream body, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="body">The configuration for the target index (`settings` and `aliases`)</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesShrinkPutAsync(string index, string target, Stream body, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="body">The configuration for the target index (`settings` and `aliases`)</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesShrinkPut(string index, string target, byte[] body, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="body">The configuration for the target index (`settings` and `aliases`)</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesShrinkPutAsync(string index, string target, byte[] body, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="body">The configuration for the target index (`settings` and `aliases`)</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesShrinkPutString(string index, string target, string body, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="body">The configuration for the target index (`settings` and `aliases`)</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesShrinkPutStringAsync(string index, string target, string body, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesShrinkPost(string index, string target, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesShrinkPostAsync(string index, string target, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="body">The configuration for the target index (`settings` and `aliases`)</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesShrinkPost(string index, string target, Stream body, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="body">The configuration for the target index (`settings` and `aliases`)</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesShrinkPostAsync(string index, string target, Stream body, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="body">The configuration for the target index (`settings` and `aliases`)</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesShrinkPost(string index, string target, byte[] body, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="body">The configuration for the target index (`settings` and `aliases`)</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesShrinkPostAsync(string index, string target, byte[] body, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="body">The configuration for the target index (`settings` and `aliases`)</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesShrinkPostString(string index, string target, string body, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html"/></summary>
///<param name="index">The name of the source index to shrink</param>
///<param name="target">The name of the target index to shrink into</param>
///<param name="body">The configuration for the target index (`settings` and `aliases`)</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesShrinkPostStringAsync(string index, string target, string body, Func<IndicesShrinkParameters, IndicesShrinkParameters> options = null)
{
var uri = string.Format("/{0}/_shrink/{1}", index, target);
if (options != null)
{
uri = options.Invoke(new IndicesShrinkParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Provisioning.Cloud.Async.WebJobWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class LongKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStackAlloc()
{
await VerifyKeywordAsync(
@"class C {
int* foo = stackalloc $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOuterConst()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInnerConst()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFixedStatement()
{
await VerifyKeywordAsync(
@"fixed ($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEnumBaseTypes()
{
await VerifyKeywordAsync(
@"enum E : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType4()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IFoo<int?,byte*>,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = foo is $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = foo as $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
{
await VerifyAbsenceAsync(@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLocalVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"for ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForeachVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUsingVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"using ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFromVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInJoinVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from a in b
join $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Foo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Foo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Foo(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Foo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Foo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Foo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Foo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Foo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Foo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInImplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNewInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTypeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefault()
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInSizeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContext()
{
await VerifyKeywordAsync(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContextNotAfterDot()
{
await VerifyAbsenceAsync(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
{
await VerifyKeywordAsync(@"class c { async $$ }");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
{
await VerifyAbsenceAsync(@"class c { async async $$ }");
}
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInCrefTypeParameter()
{
await VerifyAbsenceAsync(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
}
}
| |
using SFML.Window;
using SFML.System;
using SFML.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Iris
{
class NetPlayer : Actor
{
Animation idle, running, jumpUp, jumpDown, backpedal;
public Vector2f oldPosition;
public int animPadding; //Wait a slight bit before changing animations since position may be unreliable
public int weaponIndex = 0;
public NetPlayer(Deathmatch dm, long UID)
: base(dm)
{
model = MainGame.Char1Model;
this.UID = UID;
idle = new Animation(Content.GetTexture(model.idleFile), 4, 120, 1);
running = new Animation(Content.GetTexture(model.runFile), 6, 60, 2);
backpedal = new Animation(Content.GetTexture(model.runFile), 6, 60, 2, false);
jumpUp = new Animation(Content.GetTexture(model.jumpUpFile), 1, 60, 0);
jumpDown = new Animation(Content.GetTexture(model.jumpDownFile), 3, 60, -5);
animation = idle;
Texture = Content.GetTexture("idle.png");
Alive = true;
//.Color = Color.Red;
weapons = new List<Weapon>()
{
new Revolver(this),
new Shotgun(this),
new MachineGun(this),
new BombWeapon(this),
};
}
public override void Update()
{
HandleDeath();
base.Update();
if (!Alive)
return;
this.weapon = weapons[weaponIndex];
animation.Update();
HandleAnimationSetting();
CheckProjectiles();
oldPosition = Pos;
}
public override void Draw()
{
if (!Alive)
return;
Core = Pos - new Vector2f(-1, 35);
this.Texture = animation.Texture;
Render.renderStates = Actor.shader;
Texture pistolHand = Content.GetTexture(model.pistolHand);
Texture weaponTexture = weapon.texture;
if (ouchTimer > 0)
{
shader.Shader.SetParameter("ouch", 1f);
}
else
{
shader.Shader.SetParameter("ouch", 0f);
}
shader.Shader.SetParameter("sampler", pistolHand);
Render.Draw(pistolHand, Core, Color.White, new Vector2f(2, 4), 1, AimAngle, 1, Facing == -1);
shader.Shader.SetParameter("sampler", weaponTexture);
Render.Draw(weaponTexture, Core, Color.White, new Vector2f(2, 4), 1, AimAngle, 1, Facing == -1);
shader.Shader.SetParameter("sampler", Texture);
Render.DrawAnimation(Texture, this.Pos, Color.White, new Vector2f(Texture.Size.X / (animation.Count * 4),
Texture.Size.Y - animation.YOffset), Facing, animation.Count, animation.Frame, 1);
Render.renderStates = null;
//Render.DrawString(Content.GetFont("Font1.ttf"), Name, Core - new Vector2f(0, 40), Color.White, .3f, true, 1);
if (!Name.Equals(null))
Render.DrawString(Content.GetFont("PixelSix.ttf"), Name, this.Core - new Vector2f(0, 40), Color.White, .3f, true, 1);
base.Draw();
}
public void CheckProjectiles()
{
for (int i = 0; i < MainGame.dm.Projectiles.Count; i++)
{
if (Helper.Distance(MainGame.dm.Projectiles[i].Pos, Core) < 20)
{
this.Killer = MainGame.dm.Projectiles[i].Owner;
MainGame.dm.Projectiles[i].Destroy();
ouchTimer = 10;
}
}
}
public override void UpdateCollisionBox()
{
collisionBox.Left = (int)Pos.X - 9;
collisionBox.Top = (int)Pos.Y - 55;
collisionBox.Width = 18;
collisionBox.Height = 55;
base.UpdateCollisionBox();
}
public void HandleDeath()
{
if (Alive)
{
if (Health <= 0)
{
Alive = false;
for (int i = 0; i < MainGame.gibCount; i++)
{
int gibNum = MainGame.rand.Next(1, 4);
Gib g = new Gib(new Texture(Content.GetTexture("gib" + gibNum + ".png")), Core - new Vector2f(0, 4) +
new Vector2f(MainGame.rand.Next(-4, 5), MainGame.rand.Next(-4, 5)), (float)MainGame.rand.NextDouble() * 4.5f,
Helper.angleBetween(Core, Core - new Vector2f(0, 4)) + (float)Math.PI + (float)(i - 5 / 10f) + (float)MainGame.rand.NextDouble());
g.addVel = new Vector2f(Velocity.X / 15, Velocity.Y / 35); //Trauma
MainGame.dm.GameObjects.Add(g);
}
MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibHead.png")), Core - new Vector2f(0, 4), 3,
Helper.angleBetween(Core, Core - new Vector2f(0, 4)) + (float)Math.PI));
MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibBody.png")), Core - new Vector2f(0, 1), 2,
Helper.angleBetween(Core, Core - new Vector2f(1, 2)) + (float)Math.PI));
MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibUpperLeg.png")), Core + new Vector2f(0, 1), 3.2f,
Helper.angleBetween(Core, Core - new Vector2f(.5f, 1)) + (float)Math.PI));
MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibUpperLeg.png")), Core + new Vector2f(0, 1), 3.2f,
Helper.angleBetween(Core, Core - new Vector2f(-.5f, 1)) + (float)Math.PI));
MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibLowerLeg.png")), Core + new Vector2f(0, 1), 3.2f,
Helper.angleBetween(Core, Core - new Vector2f(.15f, 3)) + (float)Math.PI));
MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibLowerLeg.png")), Core + new Vector2f(0, 1), 3.2f,
Helper.angleBetween(Core, Core - new Vector2f(-.20f, 2)) + (float)Math.PI));
MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibArm.png")), Core + new Vector2f(0, 1), 3.2f,
Helper.angleBetween(Core, Core - new Vector2f(.04f, 3)) + (float)Math.PI));
MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibArm.png")), Core + new Vector2f(0, 1), 3.2f,
Helper.angleBetween(Core, Core - new Vector2f(-.55f, 2)) + (float)Math.PI));
}
}
}
public void HandleAnimationSetting()
{
OnGround = false;
if (dm.MapCollide((int)this.Pos.X, (int)this.Pos.Y + 1, CollideTypes.HardOrSoft))
OnGround = true;
animPadding--;
if (animPadding <= -5)
{
//if (Helper.Distance(oldPosition,Pos) < 2)
animation = idle;
if (OnGround) //On Ground
{
if (Facing == 1)
{
if (oldPosition.X - Pos.X < -.2f)
{
animation = running;
animPadding = 5;
}
if (oldPosition.X - Pos.X > .2f)
{
animation = backpedal;
animPadding = 5;
}
}
if (Facing == -1)
{
if (oldPosition.X - Pos.X < -.2f)
{
animation = backpedal;
animPadding = 5;
}
if (oldPosition.X - Pos.X > .2f)
{
animation = running;
animPadding = 5;
}
}
}
if (!OnGround) // Not on Ground
{
if ((oldPosition.Y - Pos.Y) > 2)
{
animation = jumpUp;
animPadding = 5;
}
if ((oldPosition.Y - Pos.Y) < 2)
{
animation = jumpDown;
animPadding = 5;
}
}
}
}
public override void OnProjectileHit(Projectile hit)
{
hit.Destroy();
//Probably wont do anything
base.OnProjectileHit(hit);
}
public void UpdateToCurrentModel()
{
idle = new Animation(Content.GetTexture(model.idleFile), 4, 120, 1);
running = new Animation(Content.GetTexture(model.runFile), 6, 60, 2);
backpedal = new Animation(Content.GetTexture(model.runFile), 6, 60, 2, false);
jumpUp = new Animation(Content.GetTexture(model.jumpUpFile), 1, 60, 0);
jumpDown = new Animation(Content.GetTexture(model.jumpDownFile), 3, 60, -5);
}
}
}
| |
using System;
using System.Globalization;
#if FRB_MDX
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Direct3D=Microsoft.DirectX.Direct3D;
using Microsoft.DirectX.DirectInput;
using Texture2D = FlatRedBall.Texture2D;
using Keys = Microsoft.DirectX.DirectInput.Key;
#elif FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
#elif SILVERLIGHT
#endif
using FlatRedBall.ManagedSpriteGroups;
using FlatRedBall.Graphics;
using FlatRedBall.Input;
using System.Collections.Generic;
namespace FlatRedBall.Gui
{
/// <summary>
/// Summary description for TextBox.
/// </summary>
///
public class TextBox : Window, IInputReceiver
{
#region Enums
public enum FormatTypes{ NoFormat, Integer, Decimal }
#endregion
#region Fields
// the complete text may be longer than the window to display the text. Therefore, the mDisplayedText
// holds only what is visible
private string mCompleteText;
private string mDisplayedText;
private string mCompleteTextOnLastGainFocus;
public FormatTypes Format;
int mAbsoluteCursorPosition;
int mFirstLetterShowing;
int mLastLetterShowing;
int mHighlightStartPosition;
int mHighlightEndPosition;
// int decimalPrecision;
public bool fixedLength;
// public bool losingInput;
int maxLength;
bool mTakingInput = true;
IInputReceiver mNextInTabSequence;
HorizontalAlignment mHorizontalAlignment;
float mSpacing;
float mScale;
//float mTextRed;
//float mTextGreen;
//float mTextBlue;
#region if not drawn by the Gui man, these are necessary
Sprite mCursorSprite;
Text mTextObject;
#endregion
List<string> mAllOptions = new List<string>();
#if !SILVERLIGHT
ListBox mOptionsListBox;
#endif
int mIndexPushed = -1;
List<Keys> mIgnoredKeys = new List<Keys>();
#endregion
#region Properties
public HorizontalAlignment Alignment
{
set {mHorizontalAlignment = value; }
get {return mHorizontalAlignment;}
}
public Sprite CursorSprite
{
get { return mCursorSprite; }
}
#region XML Docs
/// <summary>
/// Gets the position of the visible text cursor given the mAbsoluteCursorPosition.
/// </summary>
#endregion
private float CursorXPosition
{
get
{
if (mAbsoluteCursorPosition == -1)
{
throw new System.IndexOutOfRangeException("The TextBox's cursor position is -1. This is an invalid value");
}
if (SpriteFrame != null)
{
mSpacing = mTextObject.Spacing;
mScale = mTextObject.Scale;
#if SILVERLIGHT
float leftBorder = SpriteFrame.X - SpriteFrame.ScaleX + mSpacing/2.0f;
#else
float leftBorder = SpriteFrame.X - SpriteFrame.ScaleX + mSpacing;
#endif
if (CompleteText == "")
return leftBorder;
else
{
#if SILVERLIGHT
string substring = CompleteText.Substring(
mFirstLetterShowing,
System.Math.Min(
mAbsoluteCursorPosition - mFirstLetterShowing,
CompleteText.Length - mFirstLetterShowing));
return leftBorder +
TextManager.GetWidth(
substring,
mSpacing,
TextManager.DefaultSpriteFont);
#else
return leftBorder +
TextManager.GetWidth(
CompleteText.Substring(
mFirstLetterShowing,
System.Math.Min(mAbsoluteCursorPosition - mFirstLetterShowing, CompleteText.Length - mFirstLetterShowing)),
mSpacing,
Font);
#endif
}
}
else
{
try
{
float leftBorder = mWorldUnitX;
switch (Alignment)
{
case HorizontalAlignment.Left:
leftBorder = mWorldUnitX - mScaleX + mSpacing;
break;
case HorizontalAlignment.Center:
leftBorder -= .5f * TextManager.GetWidth(
DisplayedText,
mSpacing,
Font);
break;
case HorizontalAlignment.Right:
leftBorder = mWorldUnitX + mScaleX - mSpacing;
break;
}
if (string.IsNullOrEmpty(DisplayedText) == false && Alignment == HorizontalAlignment.Left)
{
#if SILVERLIGHT
leftBorder -= TextManager.DefaultFont.GetCharacterWidth(DisplayedText[0]) *
mSpacing / 2.0f;
#else
leftBorder -= TextManager.DefaultFont.GetCharacterWidth(DisplayedText[0]) *
GuiManager.TextSpacing / 2.0f;
#endif
}
if (CompleteText == "")
{
return leftBorder;
}
else if (HideCharacters)
{
if (Alignment == HorizontalAlignment.Left)
{
return leftBorder + TextManager.GetWidth(DisplayedText, mSpacing, Font);
}
else if (Alignment == HorizontalAlignment.Center)
{
return leftBorder + TextManager.GetWidth(DisplayedText, mSpacing, Font);
}
else
{
return leftBorder;
}
}
else
{
float textWidth = TextManager.GetWidth(
CompleteText.Substring(
mFirstLetterShowing,
System.Math.Min(mAbsoluteCursorPosition - mFirstLetterShowing, CompleteText.Length - mFirstLetterShowing)),
mSpacing,
Font);
if (Alignment == HorizontalAlignment.Left)
{
return leftBorder + textWidth;
}
else if (Alignment == HorizontalAlignment.Center)
{
return leftBorder + textWidth;
}
else
{
return leftBorder;
}
}
}
catch(Exception)
{
//int m = 3;
return 0;
}
}
}
}
private string CompleteText
{
get { return mCompleteText; }
set
{
SetCompleteText(value, true);
}
}
private string DisplayedText
{
get
{
if (HideCharacters)
{
return new string('*', mDisplayedText.Length);
}
else
{
return mDisplayedText;
}
}
set
{
mDisplayedText = value;
if (mTextObject != null)
mTextObject.DisplayText = DisplayedText;
}
}
#if SILVERLIGHT
public SpriteFont Font
{
get
{
return TextManager.DefaultSpriteFont;
}
}
#else
public BitmapFont Font
{
get
{
if (mTextObject != null)
return mTextObject.Font;
else
return null;
}
set
{
if (mTextObject != null)
mTextObject.Font = value;
else
{
throw new InvalidOperationException("Custom Fonts can only be set when usint GuiSkins. The default rendering does not support custom fonts.");
}
}
}
#endif
public bool HideCharacters
{
get;
set;
}
public List<Keys> IgnoredKeys
{
get { return mIgnoredKeys; }
}
public float Spacing
{
get
{
return mSpacing;
}
set
{
mSpacing = value;
}
}
public float Scale
{
get { return mScale; }
set { mScale = value; }
}
public override float ScaleY
{
get { return base.ScaleY; }
set
{
base.ScaleY = value;
if (mCursorSprite != null)
{
mCursorSprite.ScaleX = ScaleY * .1f;
mCursorSprite.ScaleY = ScaleY - .1f;
}
}
}
public string Text
{
get{ return mCompleteText; }
set
{
if(value == null)
{
Text = "";
}
else
{
// reset the highlight start and end
mHighlightStartPosition = -1;
mHighlightEndPosition = -1;
mFirstLetterShowing = 0;
#if SILVERLIGHT
mLastLetterShowing = mFirstLetterShowing - 1 +
TextManager.GetNumberOfCharsIn(TextAreaWidth, value, mSpacing,
mFirstLetterShowing, Font, mHorizontalAlignment);
#else
mLastLetterShowing = mFirstLetterShowing - 1 +
TextManager.GetNumberOfCharsIn(TextAreaWidth, value, GuiManager.TextSpacing,
mFirstLetterShowing, Font, mHorizontalAlignment);
#endif
if (fixedLength == true && value.Length > maxLength)
{
CompleteText = value.Remove(maxLength, value.Length - maxLength);
DisplayedText = CompleteText;
}
else
{
CompleteText = value;
RegulateCursorPosition();
}
}
}
}
private float TextAreaWidth
{
#if SILVERLIGHT
get { return (ScaleX) * 2 - mSpacing; }
#else
get { return (ScaleX) * 2 - GuiManager.TextHeight/2.0f; }
#endif
}
public override bool Visible
{
get
{
return base.Visible;
}
set
{
base.Visible = value;
if (mTextObject != null)
{
mTextObject.Visible = value;
}
}
}
#region XML Docs
/// <summary>
/// The position of the cursor on the text in the TextBox. This is always greater than 0 and less than
/// the length of the text.
/// </summary>
#endregion
public int AbsoluteCursorPosition
{
get { return mAbsoluteCursorPosition; }
}
public bool HasTextChangedSinceLastGainFocus
{
get { return mCompleteText != mCompleteTextOnLastGainFocus; }
}
public IInputReceiver NextInTabSequence
{
get { return mNextInTabSequence; }
set { mNextInTabSequence = value; }
}
#endregion
#region Events
public event GuiMessage GainFocus;
public event FocusUpdateDelegate FocusUpdate;
public event GuiMessage EnterPressed = null;
public event GuiMessage EscapeRelease = null;
#region XML Docs
/// <summary>
/// Raised when the displayed text changes. This will be called for every
/// letter typed when the user is typing - it does not wait for an Enter or
/// loss of focus.
/// </summary>
#endregion
public event GuiMessage TextChange;
#endregion
#region Event Methods
public void ShowCursor(Window callingWindow)
{
if (mCursorSprite != null && TakingInput)
mCursorSprite.Visible = true;
}
public void HideCursor(Window callingWindow)
{
if (this.mCursorSprite != null)
mCursorSprite.Visible = false;
}
#if !SILVERLIGHT
private void OptionsHighlight(Window callingWindow)
{
CollapseItem collapseItem = ((ListBox)callingWindow).GetFirstHighlightedItem();
if (collapseItem == null)
{
return;
}
else if (collapseItem.ReferenceObject != null)
{
double valueHighlighted = (double)collapseItem.ReferenceObject;
this.Text = valueHighlighted.ToString();
}
else
{
this.Text = collapseItem.Text;
}
// This simulates that we lost focus of the text box - like pushing enter
OnLosingFocus();
}
#endif
public void OnResize(Window callingWindow)
{
// This refreshes how much of the text is seen.
Text = Text;
}
public void OnFocusUpdate()
{
if (FocusUpdate != null)
FocusUpdate(this);
}
private void TextBoxClick(Window callingWindow)
{
if (TakingInput)
{
InputManager.ReceivingInput = this;
// here we find where to put the cursor
mAbsoluteCursorPosition = GetAbsoluteIndexAtCursorPosition();
if (mAbsoluteCursorPosition < mFirstLetterShowing)
{
// Throw an exception?
}
if (!mCursor.PrimaryDoubleClick && mIndexPushed == -1)
{
mHighlightStartPosition = -1;
mHighlightEndPosition = -1;
}
mIndexPushed = -1;
}
}
private void TextBoxDoubleClick(Window callingWindow)
{
if (TakingInput)
{
mHighlightStartPosition = 0;
mHighlightEndPosition = CompleteText.Length;
mAbsoluteCursorPosition = mHighlightEndPosition;
}
}
private void TextBoxDrag(Window callingWindow)
{
if (mIndexPushed != -1)
{
int indexOver = GetAbsoluteIndexAtCursorPosition();
mHighlightStartPosition = System.Math.Min(mIndexPushed, indexOver);
mHighlightEndPosition = System.Math.Max(mIndexPushed, indexOver);
}
}
private void TextBoxPush(Window callingWindow)
{
TextBoxClick(callingWindow);
mHighlightStartPosition = mHighlightEndPosition = -1;
mIndexPushed = GetAbsoluteIndexAtCursorPosition();
}
#endregion
#region Methods
#region Constructors
public TextBox(Cursor cursor) :
base(cursor)
{
mFirstLetterShowing = 0;
mLastLetterShowing = -1;
CompleteText = "";
fixedLength = false;
mHighlightStartPosition = mHighlightEndPosition = -1;
mSpacing = GuiManager.TextSpacing;
mScale = GuiManager.TextHeight / 2.0f;
// leave this next line in or else text will be white
// Update June 25, 2011
// Why do we need this in? It doesn't seem to do anything.
//mTextRed = mTextGreen = mTextBlue = 0;
this.LosingFocus += new GuiMessage(RemoveHighlight);
// decimalPosition = 9;
ScaleY = 1;
Push += TextBoxPush;
Dragging += TextBoxDrag;
Click += TextBoxClick;
DoubleClick += TextBoxDoubleClick;
this.Resizing += OnResize;
}
// Vic says: This method may no longer be needed now that we are using GuiSkins
// to customize the UI.
//public TextBox(string baseTexture, string cursorTexture,
// Camera camera, Cursor cursor, string contentManagerName)
// : base(baseTexture, cursor, contentManagerName)
//{
// mFirstLetterShowing = 0;
// mLastLetterShowing = -1;
// CompleteText = "";
// mTextObject = TextManager.AddText("", SpriteFrame.LayerBelongingTo);
// mCursorSprite = SpriteManager.AddSprite(
// FlatRedBallServices.Load<Texture2D>(cursorTexture, contentManagerName)
// );
// mCursorSprite.ScaleX = .1f;
// mCursorSprite.ScaleY = 1;
// mCursorSprite.Z = -.01f;
// mCursorSprite.Visible = false;
// fixedLength = false;
// mHighlightStartPosition = mHighlightEndPosition = -1;
// mTextObject.AttachTo(SpriteFrame, false);
// mTextRed = mTextGreen = mTextBlue = 0;
// mTextObject.RelativeY = .1f;
// LosingFocus += new GuiMessage(RemoveHighlight);
// LosingFocus += new GuiMessage(HideCursor);
// Click += new GuiMessage(ShowCursor);
// this.Resizing += OnResize;
//}
public TextBox(GuiSkin guiSkin, Cursor cursor)
: base(guiSkin, cursor)
{
mFirstLetterShowing = 0;
mLastLetterShowing = -1;
CompleteText = "";
mTextObject = TextManager.AddText("", SpriteFrame.LayerBelongingTo);
mCursorSprite = SpriteManager.AddSprite(
guiSkin.TextBoxSkin.Texture,
SpriteFrame.LayerBelongingTo);
// cursorSprite = SpriteManager.AddSprite("redball.bmp");
mCursorSprite.ScaleX = .1f;
mCursorSprite.ScaleY = SpriteFrame.ScaleY - .1f ;
mCursorSprite.Z = SpriteFrame.Z -.1f * FlatRedBall.Math.MathFunctions.ForwardVector3.Z;
mCursorSprite.Visible = false;
fixedLength = false;
mHighlightStartPosition = mHighlightEndPosition = -1;
mTextObject.AttachTo(SpriteFrame, false);
mTextObject.RelativeY = .1f;
mTextObject.RelativeZ = -.01f * FlatRedBall.Math.MathFunctions.ForwardVector3.Z;
//mTextRed = mTextGreen = mTextBlue = 0;
// Now that the text object is created, let's call SetTexturePropertiesFromSkin
SetTexturePropertiesFromSkin(guiSkin);
LosingFocus += new GuiMessage(RemoveHighlight);
LosingFocus += new GuiMessage(HideCursor);
Click += new GuiMessage(ShowCursor);
Push += TextBoxPush;
Dragging += TextBoxDrag;
Click += TextBoxClick;
DoubleClick += TextBoxDoubleClick;
this.Resizing += OnResize;
}
#endregion
#region Public Methods
public override void Activity(Camera camera)
{
base.Activity(camera);
if (GuiManagerDrawn == false)
{
if (mHorizontalAlignment == HorizontalAlignment.Left)
{
#if SILVERLIGHT
mTextObject.RelativeX = -ScaleX + mTextObject.Scale/2.0f;
#else
mTextObject.RelativeX = -ScaleX + mTextObject.Scale;
#endif
}
else
{
mTextObject.RelativeX = 0;
}
if (InputManager.ReceivingInput == this)
{
mCursorSprite.X = CursorXPosition;
mCursorSprite.Y = mWorldUnitY;
}
}
}
public override void ClearEvents()
{
base.ClearEvents();
GainFocus = null;
EnterPressed = null;
EscapeRelease = null;
TextChange = null;
FocusUpdate = null;
}
public bool CurrentlyReceivingInput()
{
return InputManager.ReceivingInput == this;
}
public void OnGainFocus()
{
mCompleteTextOnLastGainFocus = mCompleteText;
if (GainFocus != null)
GainFocus(this);
}
public void SetOptions(IList<string> options)
{
mAllOptions.Clear();
mAllOptions.AddRange(options);
}
public void SetCompleteText(string value, bool raiseTextChangeEvent)
{
if (mCompleteText != value)
{
mCompleteText = value;
// Make sure it's not beyond the end of the word
// Update: Vic says - I'm not sure why this is here,
// but when setting the Text in code, the mLastLetterShowing
// will never increase.
// I'm going to comment it out and hopefully we figure out why this
// was needed and we can come up with logic that will both fix the original
// bug this was solving as well as the situation where the user sets the CompleteText
// through code instead of typing
//mLastLetterShowing = System.Math.Min(value.Length - 1, mLastLetterShowing);
mLastLetterShowing = value.Length - 1;
// Make sure it's not beyond the visible boundaries
#if SILVERLIGHT
int numberOfCharactersInArea =
TextManager.GetNumberOfCharsIn(TextAreaWidth, value, mSpacing,
mFirstLetterShowing, TextManager.DefaultSpriteFont, mHorizontalAlignment);
mLastLetterShowing = System.Math.Min(mLastLetterShowing, mFirstLetterShowing - 1 +
numberOfCharactersInArea);
#else
mLastLetterShowing = System.Math.Min(mLastLetterShowing, mFirstLetterShowing - 1 +
TextManager.GetNumberOfCharsIn(TextAreaWidth, value, GuiManager.TextSpacing,
mFirstLetterShowing, Font, mHorizontalAlignment));
#endif
mFirstLetterShowing = System.Math.Min(mFirstLetterShowing, mLastLetterShowing);
mFirstLetterShowing = System.Math.Max(0, mFirstLetterShowing);
if (raiseTextChangeEvent && TextChange != null)
{
TextChange(this);
}
}
if (mLastLetterShowing == -1)
DisplayedText = "";
else
DisplayedText = CompleteText.Substring(mFirstLetterShowing, 1 + mLastLetterShowing - mFirstLetterShowing);
}
public int TruncateText()
{
int difference = 0;
if (fixedLength)
{
#if SILVERLIGHT
maxLength = TextManager.GetNumberOfCharsIn(TextAreaWidth, Text, mSpacing, mFirstLetterShowing);
#else
maxLength = TextManager.GetNumberOfCharsIn(TextAreaWidth, Text, GuiManager.TextSpacing, mFirstLetterShowing);
#endif
difference = Text.Length - maxLength;
Text = Text.Substring(0, maxLength);
}
else
{
int lastFirstLetterShowing = mFirstLetterShowing;
Text = Text; // the property refreshes the start and end so the text fits in the window
difference = mFirstLetterShowing - lastFirstLetterShowing;
}
return difference;
}
public void UpdateFormat()
{
switch(Format)
{
case FormatTypes.NoFormat:
break;
case FormatTypes.Integer:
break;
case FormatTypes.Decimal:
break;
}
}
public override string ToString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("Text: ").Append(Text).Append("\n");
sb.Append("Absolute Cursor Position: ").Append(mAbsoluteCursorPosition).Append("\n");
sb.Append("First Letter Showing: ").Append(mFirstLetterShowing).Append("\n");
sb.Append("Last Letter Showing: ").Append(mLastLetterShowing).Append("\n");
return sb.ToString();
}
#endregion
#region Internal Methods (called by the GuiManager)
internal override void Destroy()
{
base.Destroy();
if (mCursorSprite != null)
{
SpriteManager.RemoveSprite(mCursorSprite);
}
if (mTextObject != null)
{
TextManager.RemoveText(this.mTextObject);
}
}
internal protected override void Destroy(bool keepEvents)
{
base.Destroy(keepEvents);
if (mCursorSprite != null)
{
SpriteManager.RemoveSprite(mCursorSprite);
}
if (mTextObject != null)
{
TextManager.RemoveText(this.mTextObject);
}
}
#if !SILVERLIGHT
internal override void DrawSelfAndChildren(Camera camera)
{
if (Visible == false) return;
float xToUse = mWorldUnitX;
float yToUse = mWorldUnitY;
mScale = GuiManager.TextHeight / 2.0f;
mSpacing = GuiManager.TextSpacing;
DrawBase(camera);
#region next we draw the highlight box if text is highlighted
if(mHighlightStartPosition != -1)
{
float startXPos = (float)(xToUse -mScaleX+.5f)+(mScale * TextManager.GetRelativeOffset(mHighlightStartPosition, mFirstLetterShowing, CompleteText));
float endXPos = (float)
(mWorldUnitX - mScaleX+.5f) +
(mScale *
TextManager.GetRelativeOffset( System.Math.Min(mHighlightEndPosition, mLastLetterShowing +1), mFirstLetterShowing, CompleteText));
float highlightScaleX = (endXPos - startXPos)/2.0f;
float highlightXPos = (startXPos + endXPos)/2.0f;
StaticVertices[0].Position.X = highlightXPos - highlightScaleX;
StaticVertices[0].Position.Y = yToUse - 1;
StaticVertices[0].TextureCoordinate.X = .0234375f;
StaticVertices[0].TextureCoordinate.Y = .65f;
StaticVertices[1].Position.X = highlightXPos - highlightScaleX;
StaticVertices[1].Position.Y = yToUse + 1;
StaticVertices[1].TextureCoordinate.X = .0234375f;
StaticVertices[1].TextureCoordinate.Y = .65f;
StaticVertices[2].Position.X = highlightXPos + highlightScaleX;
StaticVertices[2].Position.Y = yToUse + 1;
StaticVertices[2].TextureCoordinate.X = .02734375f;
StaticVertices[2].TextureCoordinate.Y = .66f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = highlightXPos + highlightScaleX;
StaticVertices[5].Position.Y = yToUse - 1;
StaticVertices[5].TextureCoordinate.X = .02734375f;
StaticVertices[5].TextureCoordinate.Y = .65f;
GuiManager.WriteVerts(StaticVertices);
}
#endregion
#region next we draw the text
if (Text.Length != 0 && 1 + mLastLetterShowing - mFirstLetterShowing > 0 &&
mFirstLetterShowing < Text.Length)
{
string stringToWrite = DisplayedText;
DrawTextLine(ref stringToWrite, mWorldUnitY);
}
#endregion
#region finally we draw the cursor
if (InputManager.ReceivingInput == this)
{// we draw a text cursor
// on FRB MDX the camera.X part throws off the cursor when the camera is at a non-zero position. What's it do in FRB XNA?
float xPos = CursorXPosition;// (float)(si.X + camera.X - si.ScaleX + .57f) + (mScale * TextManager.GetRelX(cursorPosition, firstLetterShowing, Text));
float cursorScaleY = this.ScaleY - .1f;
float cursorScaleX = .1f * ScaleY;
#region cursor vertices
StaticVertices[0].Position.X = xPos - cursorScaleX;
StaticVertices[0].Position.Y = yToUse - cursorScaleY;
StaticVertices[0].TextureCoordinate.X = .219f;
StaticVertices[0].TextureCoordinate.Y = .649f;
StaticVertices[1].Position.X = xPos - cursorScaleX;
StaticVertices[1].Position.Y = yToUse + cursorScaleY;
StaticVertices[1].TextureCoordinate.X = .219f;
StaticVertices[1].TextureCoordinate.Y = .648f;
StaticVertices[2].Position.X = xPos + cursorScaleX;
StaticVertices[2].Position.Y = yToUse + cursorScaleY;
StaticVertices[2].TextureCoordinate.X = .22f;
StaticVertices[2].TextureCoordinate.Y = .648f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xPos + cursorScaleX;
StaticVertices[5].Position.Y = yToUse - cursorScaleY;
StaticVertices[5].TextureCoordinate.X = .22f;
StaticVertices[5].TextureCoordinate.Y = .649f;
GuiManager.WriteVerts(StaticVertices);
#endregion
}
#endregion
}
internal void DrawBase(Camera camera)
{
float xToUse = mWorldUnitX;
float yToUse = mWorldUnitY;
#region first we draw the base window
#if FRB_MDX
if (Enabled)
{
StaticVertices[0].Color = StaticVertices[1].Color = StaticVertices[2].Color = StaticVertices[3].Color = StaticVertices[4].Color = StaticVertices[5].Color = 0xff000000;
}
else
{
StaticVertices[0].Color = StaticVertices[1].Color = StaticVertices[2].Color = StaticVertices[3].Color = StaticVertices[4].Color = StaticVertices[5].Color = 0x88000000;
}
#else
if (Enabled)
{
StaticVertices[0].Color.PackedValue = StaticVertices[1].Color.PackedValue = StaticVertices[2].Color.PackedValue =
StaticVertices[3].Color.PackedValue = StaticVertices[4].Color.PackedValue = StaticVertices[5].Color.PackedValue = 0xff000000;
}
else
{
StaticVertices[0].Color.PackedValue = StaticVertices[1].Color.PackedValue = StaticVertices[2].Color.PackedValue =
StaticVertices[3].Color.PackedValue = StaticVertices[4].Color.PackedValue = StaticVertices[5].Color.PackedValue = 0x88000000;
}
#endif
StaticVertices[0].Position.Z = StaticVertices[1].Position.Z = StaticVertices[2].Position.Z =
StaticVertices[3].Position.Z = StaticVertices[4].Position.Z = StaticVertices[5].Position.Z =
camera.Z + FlatRedBall.Math.MathFunctions.ForwardVector3.Z * 100;
#region LeftBorder
StaticVertices[0].Position.X = xToUse - ScaleX;
StaticVertices[0].Position.Y = yToUse - ScaleY;
StaticVertices[0].TextureCoordinate.X = .5273438f;
StaticVertices[0].TextureCoordinate.Y = .6445313f;
StaticVertices[1].Position.X = xToUse - ScaleX;
StaticVertices[1].Position.Y = yToUse + ScaleY;
StaticVertices[1].TextureCoordinate.X = .5273438f;
StaticVertices[1].TextureCoordinate.Y = .5703125f;
StaticVertices[2].Position.X = xToUse - ScaleX + .2f;
StaticVertices[2].Position.Y = yToUse + ScaleY;
StaticVertices[2].TextureCoordinate.X = .5351563f;
StaticVertices[2].TextureCoordinate.Y = .5703125f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse - ScaleX + .2f;
StaticVertices[5].Position.Y = yToUse - ScaleY;
StaticVertices[5].TextureCoordinate.X = .5351563f;
StaticVertices[5].TextureCoordinate.Y = .6445313f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Center
StaticVertices[0].Position.X = xToUse - ScaleX + .2f;
StaticVertices[0].Position.Y = yToUse - ScaleY;
StaticVertices[0].TextureCoordinate.X = .5351563f;
StaticVertices[0].TextureCoordinate.Y = .6445313f;
StaticVertices[1].Position.X = xToUse - ScaleX + .2f;
StaticVertices[1].Position.Y = yToUse + ScaleY;
StaticVertices[1].TextureCoordinate.X = .5351563f;
StaticVertices[1].TextureCoordinate.Y = .5703125f;
StaticVertices[2].Position.X = xToUse + ScaleX - .2f;
StaticVertices[2].Position.Y = yToUse + ScaleY;
StaticVertices[2].TextureCoordinate.X = .5390625f;
StaticVertices[2].TextureCoordinate.Y = .5703125f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX - .2f;
StaticVertices[5].Position.Y = yToUse - ScaleY;
StaticVertices[5].TextureCoordinate.X = .5390625f;
StaticVertices[5].TextureCoordinate.Y = .6445313f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region RightBorder
StaticVertices[0].Position.X = xToUse + ScaleX - .2f;
StaticVertices[0].Position.Y = yToUse - ScaleY;
StaticVertices[0].TextureCoordinate.X = .5390625f;
StaticVertices[0].TextureCoordinate.Y = .6445313f;
StaticVertices[1].Position.X = xToUse + ScaleX - .2f;
StaticVertices[1].Position.Y = yToUse + ScaleY;
StaticVertices[1].TextureCoordinate.X = .5390625f;
StaticVertices[1].TextureCoordinate.Y = .5703125f;
StaticVertices[2].Position.X = xToUse + ScaleX;
StaticVertices[2].Position.Y = yToUse + ScaleY;
StaticVertices[2].TextureCoordinate.X = .546875f;
StaticVertices[2].TextureCoordinate.Y = .5703125f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX;
StaticVertices[5].Position.Y = yToUse - ScaleY;
StaticVertices[5].TextureCoordinate.X = .546875f;
StaticVertices[5].TextureCoordinate.Y = .6445313f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#endregion
}
#endif
internal void DrawTextLine(ref string textToDraw, float worldYPosition)
{
TextManager.mRedForVertexBuffer = .1f * GraphicalEnumerations.MaxColorComponentValue;
TextManager.mGreenForVertexBuffer = .1f * GraphicalEnumerations.MaxColorComponentValue;
TextManager.mBlueForVertexBuffer = .1f * GraphicalEnumerations.MaxColorComponentValue;
TextManager.mAlphaForVertexBuffer = 1f * GraphicalEnumerations.MaxColorComponentValue;
TextManager.mAlignmentForVertexBuffer = this.Alignment;// HorizontalAlignment.Left;
switch (Alignment)
{
case HorizontalAlignment.Left:
TextManager.mXForVertexBuffer = (mWorldUnitX - mScaleX + mSpacing);
break;
case HorizontalAlignment.Center:
TextManager.mXForVertexBuffer = mWorldUnitX;
break;
case HorizontalAlignment.Right:
TextManager.mXForVertexBuffer = (mWorldUnitX + mScaleX - mSpacing);
break;
}
TextManager.mYForVertexBuffer = (worldYPosition);
TextManager.mZForVertexBuffer = AbsoluteWorldUnitZ;
TextManager.mScaleForVertexBuffer = GuiManager.TextHeight / 2.0f;
TextManager.mSpacingForVertexBuffer = GuiManager.TextSpacing;
// The TextBox will worry about truncating strings
TextManager.mMaxWidthForVertexBuffer = float.PositiveInfinity;
TextManager.Draw(ref textToDraw);
}
#if !SILVERLIGHT
internal override int GetNumberOfVerticesToDraw()
{
int numVertices = 3 * 6; // base window
if (this.mHighlightStartPosition != -1)
numVertices += 6;
if (this.DisplayedText.Length != 0)
{
numVertices += DisplayedText.Replace(" ", "").Length * 6;
}
if (InputManager.ReceivingInput == this)
{
numVertices += 6;
}
return numVertices;
}
#endif
internal void RegulateCursorPosition()
{
mAbsoluteCursorPosition = System.Math.Min(mAbsoluteCursorPosition, this.CompleteText.Length);
if (mAbsoluteCursorPosition < mFirstLetterShowing)
{
//int m = 3;
//
}
}
internal void RemoveHighlight(Window callingWindow)
{
mHighlightStartPosition = -1;
mHighlightEndPosition = -1;
}
#endregion
#region Private Methods
/// <summary>
/// Makes sure the current text can be successfully parsed, and if not, changes it to 0.
/// </summary>
private void FixNumericalInput()
{
if ((this.Format == TextBox.FormatTypes.Integer || this.Format == TextBox.FormatTypes.Decimal))
{
if((this.Text == "" || this.Text == "-" || this.Text == "." || this.Text == ","))
this.Text = "0";
// If the text starts with a period and the text box is an integer, make the displayed value a 0.
if (this.Format == FormatTypes.Integer && this.Text.StartsWith("."))
this.Text = "0";
}
}
private int GetAbsoluteIndexAtCursorPosition()
{
float cursorrelX = 0;
float width = 0;
switch (Alignment)
{
case HorizontalAlignment.Left:
cursorrelX = -mScale / 2.0f + mCursor.XForUI - (mWorldUnitX - mScaleX);
break;
case HorizontalAlignment.Center:
width = TextManager.GetWidth(
DisplayedText,
mSpacing,
Font);
cursorrelX = -mScale / 2.0f + mCursor.XForUI - (mWorldUnitX - width/2.0f);
break;
case HorizontalAlignment.Right:
width = TextManager.GetWidth(
DisplayedText,
mSpacing,
Font);
cursorrelX = -mScale / 2.0f + mCursor.XForUI - (mWorldUnitX + mScale - width);
break;
}
// if this TextBox is not GuiManagerDrawn, then it is probably not at 100 units away from the camera.
if (!GuiManagerDrawn)
{
float temporaryY = 0;
float temporaryX = 0;
mCursor.GetCursorPosition(out temporaryX, out temporaryY, SpriteFrame.Z);
cursorrelX = -mScale / 2.0f + temporaryX - (mWorldUnitX - mScaleX);
}
return mFirstLetterShowing +
TextManager.GetCursorPosition(cursorrelX, CompleteText, mScale, mFirstLetterShowing);
}
#endregion
#region Protected Methods
public override void SetSkin(GuiSkin guiSkin)
{
SetFromWindowSkin(guiSkin.TextBoxSkin);
SetTexturePropertiesFromSkin(guiSkin);
}
private void SetTexturePropertiesFromSkin(GuiSkin guiSkin)
{
if (mTextObject != null)
{
mTextObject.Font = guiSkin.TextBoxSkin.Font;
mTextObject.Scale = guiSkin.TextBoxSkin.TextScale;
mTextObject.Spacing = guiSkin.TextBoxSkin.TextSpacing;
mTextObject.Red = guiSkin.TextBoxSkin.TextRed;
mTextObject.Green = guiSkin.TextBoxSkin.TextGreen;
mTextObject.Blue = guiSkin.TextBoxSkin.TextBlue;
}
}
#endregion
#region IInputReceiver Methods
public void LoseFocus()
{
if (mCursorSprite != null)
mCursorSprite.Visible = false;
base.OnLosingFocus();
}
public void ReceiveInput()
{
HorizontalAlignment alignment = HorizontalAlignment.Center;
bool wasSomethingTyped = false;
#region Copy: CTRL + C
if (InputManager.Keyboard.ControlCPushed())
{
#if !XBOX360 && !SILVERLIGHT && !WINDOWS_PHONE && !MONODROID
bool isSTAThreadUsed =
System.Threading.Thread.CurrentThread.GetApartmentState() == System.Threading.ApartmentState.STA;
#if DEBUG
if (!isSTAThreadUsed)
{
GuiManager.ShowMessageBox("Need to set [STAThread] on Main to support copy/paste", "Error Copying");
}
#endif
if (isSTAThreadUsed &&
this.mHighlightStartPosition != -1 && this.mHighlightEndPosition != -1 &&
mHighlightStartPosition != mHighlightEndPosition)
{
System.Windows.Forms.Clipboard.SetText(CompleteText.Substring(
mHighlightStartPosition, mHighlightEndPosition - mHighlightStartPosition));
}
#endif
}
#endregion
#region Select All: CTRL + A
if (InputManager.Keyboard.KeyPushed(Keys.A) &&
(InputManager.Keyboard.KeyDown(Keys.LeftControl) || InputManager.Keyboard.KeyDown(Keys.RightControl)))
{
// Highlight the entire thing
HighlightCompleteText();
}
#endregion
#region backspace
#if FRB_MDX
if (InputManager.Keyboard.KeyTyped(Keys.BackSpace))
#else
if (InputManager.Keyboard.KeyTyped(Keys.Back))
#endif
{
wasSomethingTyped = true;
if(mHighlightStartPosition != -1)
{
// Text is highlighted so delete everything.
CompleteText = CompleteText.Remove(mHighlightStartPosition, mHighlightEndPosition - mHighlightStartPosition);
//mAbsoluteCursorPosition = 0;
mAbsoluteCursorPosition = mHighlightStartPosition;
mHighlightStartPosition = mHighlightEndPosition= -1;
// for now assume the highlight removed everything
//mFirstLetterShowing = 0;
//mLastLetterShowing = -1;
}
else if(mAbsoluteCursorPosition > 0)
{
// Not at the very beginning where backspace is not possible.
if (mAbsoluteCursorPosition == mLastLetterShowing + 1 && mFirstLetterShowing != 0)
{
int absoluteCursorPosition = mAbsoluteCursorPosition;
// the cursor is on the right side of the text box and the text can "scroll" to the left
CompleteText = CompleteText.Remove(mAbsoluteCursorPosition - 1, 1);
#if SILVERLIGHT
mFirstLetterShowing = System.Math.Max(0, 1 + mLastLetterShowing - TextManager.GetNumberOfCharsIn(
TextAreaWidth, CompleteText, mSpacing, mLastLetterShowing, Font, HorizontalAlignment.Right));
#else
mFirstLetterShowing = System.Math.Max(0, 1 + mLastLetterShowing - TextManager.GetNumberOfCharsIn(
TextAreaWidth, CompleteText, GuiManager.TextSpacing, mLastLetterShowing, Font, HorizontalAlignment.Right));
#endif
//refresh the complete text
CompleteText = CompleteText;
if (Text == "")
mLastLetterShowing = -1;
// make sure that the last letter showing is not greater than the last letter in the Text object.
mLastLetterShowing = System.Math.Min(mLastLetterShowing, CompleteText.Length - 1);
mAbsoluteCursorPosition--;
}
else
{
int oldFirstLetterShowing = mFirstLetterShowing;
int oldAbsoluteCursorPosition = mAbsoluteCursorPosition;
CompleteText = CompleteText.Remove(mAbsoluteCursorPosition - 1, 1);
// make sure that the last letter showing is not greater than the last letter in the Text object.
mLastLetterShowing = System.Math.Min(mLastLetterShowing, CompleteText.Length - 1);
if (mLastLetterShowing == CompleteText.Length - 1)
{
#if SILVERLIGHT
// this means that the text box is showing the end of the text, so we need to adjust the firstLetterShowing
mFirstLetterShowing = System.Math.Max(0, 1 + mLastLetterShowing - TextManager.GetNumberOfCharsIn(
TextAreaWidth, CompleteText, mSpacing, mLastLetterShowing, Font, HorizontalAlignment.Right));
#else
// this means that the text box is showing the end of the text, so we need to adjust the firstLetterShowing
mFirstLetterShowing = System.Math.Max(0, 1 + mLastLetterShowing - TextManager.GetNumberOfCharsIn(
TextAreaWidth, CompleteText, GuiManager.TextSpacing, mLastLetterShowing, Font, HorizontalAlignment.Right));
#endif
}
CompleteText = CompleteText;
if (oldAbsoluteCursorPosition == mAbsoluteCursorPosition)
{
// When the CompleteText is set, this can raise an event, which could
// regulate the cursor. This automatically moves the cursor back.
// Calling this code if the cursor position has changed will make it move
// back two.
mAbsoluteCursorPosition--;
}
}
}
}
#endregion
#region delete
if (InputManager.Keyboard.KeyTyped(Keys.Delete))
{
wasSomethingTyped = true;
if (mHighlightStartPosition != -1)
{
CompleteText = CompleteText.Remove(mHighlightStartPosition, mHighlightEndPosition - mHighlightStartPosition);
mAbsoluteCursorPosition = mHighlightStartPosition;
mHighlightStartPosition = mHighlightEndPosition = -1;
}
else if (mAbsoluteCursorPosition < CompleteText.Length)
{
CompleteText = CompleteText.Remove(mAbsoluteCursorPosition, 1);
if (mAbsoluteCursorPosition + mFirstLetterShowing == mLastLetterShowing)
{
int oldFirstLetterShowing = mFirstLetterShowing;
#if SILVERLIGHT
mFirstLetterShowing = System.Math.Max(0, 1 + mLastLetterShowing - TextManager.GetNumberOfCharsIn(
TextAreaWidth, CompleteText, mSpacing, mLastLetterShowing, Font, HorizontalAlignment.Right));
#else
mFirstLetterShowing = System.Math.Max(0, 1 + mLastLetterShowing - TextManager.GetNumberOfCharsIn(
TextAreaWidth, CompleteText, GuiManager.TextSpacing, mLastLetterShowing, Font, HorizontalAlignment.Right));
#endif
}
CompleteText = CompleteText;
}
}
#endregion
#region right arrow
#if FRB_MDX
if (InputManager.Keyboard.KeyTyped(Keys.RightArrow))
#else
if (InputManager.Keyboard.KeyTyped(Keys.Right))
#endif
{
mHighlightStartPosition = -1;
mHighlightEndPosition = -1;
if (mAbsoluteCursorPosition < this.CompleteText.Length)
{
mAbsoluteCursorPosition++;
}
if (mAbsoluteCursorPosition > mLastLetterShowing+1)
{
alignment = HorizontalAlignment.Right;
mLastLetterShowing++;
}
}
#endregion
#region End
if (InputManager.Keyboard.KeyTyped(Keys.End))
{
mAbsoluteCursorPosition = this.CompleteText.Length;
mHighlightStartPosition = -1;
mHighlightEndPosition = -1;
if (mAbsoluteCursorPosition > mLastLetterShowing + 1)
{
alignment = HorizontalAlignment.Right;
mLastLetterShowing = mAbsoluteCursorPosition - 1;
}
}
#endregion
#region left arrow
#if FRB_MDX
if (InputManager.Keyboard.KeyTyped(Keys.LeftArrow))
#else
if (InputManager.Keyboard.KeyTyped(Keys.Left))
#endif
{
mHighlightStartPosition = -1;
mHighlightEndPosition = -1;
if (mAbsoluteCursorPosition > 0)
{
mAbsoluteCursorPosition--;
}
if(mAbsoluteCursorPosition < mFirstLetterShowing)
{
mFirstLetterShowing--;
alignment = HorizontalAlignment.Left;
}
}
#endregion
#region Home
if (InputManager.Keyboard.KeyTyped(Keys.Home))
{
mHighlightStartPosition = -1;
mHighlightEndPosition = -1;
mAbsoluteCursorPosition = 0;
if(mAbsoluteCursorPosition < mFirstLetterShowing)
{
mFirstLetterShowing = 0;
alignment = HorizontalAlignment.Left;
}
}
#endregion
#region return/enter
#if FRB_MDX
if (InputManager.Keyboard.KeyReleased(Keys.Return) || InputManager.Keyboard.KeyReleased(Key.NumPadEnter))
#else
if(InputManager.Keyboard.KeyReleased(Keys.Enter))
#endif
{
GuiManager.mLastWindowWithFocus = null;
FixNumericalInput();
InputManager.ReceivingInput = null;
if(EnterPressed != null)
EnterPressed(this);
}
#endregion
#region tab
if (InputManager.Keyboard.KeyPushed(Keys.Tab))
{
InputManager.ReceivingInput = this.NextInTabSequence;
while(InputManager.ReceivingInput != null && InputManager.ReceivingInput is Window &&
!((Window)InputManager.ReceivingInput).Enabled)
{
InputManager.ReceivingInput = InputManager.ReceivingInput.NextInTabSequence;
}
FixNumericalInput();
OnLosingFocus();
if (InputManager.ReceivingInput != null && InputManager.ReceivingInput is TextBox)
{
((TextBox)InputManager.ReceivingInput).mHighlightStartPosition = 0;
((TextBox)InputManager.ReceivingInput).mHighlightEndPosition =
((TextBox)InputManager.ReceivingInput).CompleteText.Length;
}
}
#endregion
#region escape release
if (InputManager.Keyboard.KeyReleased(Keys.Escape) && this.EscapeRelease != null)
{
EscapeRelease(this);
}
#endregion
else
{
string typed = InputManager.Keyboard.GetStringTyped();
foreach(char c in typed)
{
wasSomethingTyped = true;
#region we have text highlighted, so we need to get rid of it before typing something
if (mHighlightStartPosition != -1)
{
CompleteText = CompleteText.Remove(mHighlightStartPosition, mHighlightEndPosition - mHighlightStartPosition);
mAbsoluteCursorPosition = mHighlightStartPosition;
mHighlightStartPosition = mHighlightEndPosition = -1;
if (mAbsoluteCursorPosition < 0)
{
mAbsoluteCursorPosition = 0;
}
}
#endregion
#region if shift is not down
if(Format == FormatTypes.NoFormat)
{
// The CompletedText property uses mLastLetterShowing to limit the displayed text.
// I'm not sure I understand completely what's going on with mLastLetterShowing, but
// incrementing it fixes the problem. If more problems arise, see if mLastLetterShowing
// can be completely eliminated.
mLastLetterShowing++;
CompleteText = CompleteText.Insert(mAbsoluteCursorPosition, c.ToString());
mAbsoluteCursorPosition++;
}
else if(Format == FormatTypes.Integer)
{
if (c > 47 && c < 58)
{
CompleteText = CompleteText.Insert(mAbsoluteCursorPosition, c.ToString());
mAbsoluteCursorPosition++;
}
else if (c == '-' && mAbsoluteCursorPosition == 0)
{
CompleteText = CompleteText.Insert(mAbsoluteCursorPosition, c.ToString());
mAbsoluteCursorPosition++;
}
}
else if(Format == FormatTypes.Decimal)
{
NumberFormatInfo LocalFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
char decimalSeparator = LocalFormat.NumberDecimalSeparator[0];
if( (c > 47 && c < 58))
{
CompleteText = CompleteText.Insert(mAbsoluteCursorPosition, c.ToString());
mAbsoluteCursorPosition++;
}
else if(c == decimalSeparator)
{
int position = -1;
position = CompleteText.IndexOf(decimalSeparator);
#region if there is no decimal separator
if (position == -1)
{
CompleteText = CompleteText.Insert(mAbsoluteCursorPosition, c.ToString());
mAbsoluteCursorPosition++;
}
#endregion
#region else, there is, so remove it then re-add it
else
{
mCompleteText = CompleteText.Remove(position, 1);
CompleteText = CompleteText.Insert(mAbsoluteCursorPosition - 1, c.ToString());
}
#endregion
}
else if (c == (int)'-' &&
(mAbsoluteCursorPosition == 0 ||
(mAbsoluteCursorPosition == 1 && mDisplayedText[0] == '0') ))
{
CompleteText = CompleteText.Insert(0, c.ToString());
mAbsoluteCursorPosition++;
}
else
{
#if !SILVERLIGHT
mOptionsListBox = GuiManager.AddPerishableListBox();
mOptionsListBox.ScaleX = System.Math.Max(this.ScaleX, 4);
mOptionsListBox.ScaleY = 5;
mOptionsListBox.X = this.ScreenRelativeX;
mOptionsListBox.Y = this.ScreenRelativeY + this.ScaleY + mOptionsListBox.ScaleY;
mOptionsListBox.AddItem("PI", System.Math.PI);
mOptionsListBox.AddItem("-PI", -System.Math.PI);
mOptionsListBox.AddItem("PI/2", System.Math.PI/2.0);
mOptionsListBox.AddItem("-PI/2", -System.Math.PI/2.0);
mOptionsListBox.Highlight += OptionsHighlight;
mOptionsListBox.Click += GuiManager.RemoveWindow;
#endif
}
}
#endregion
// cursorPosition -= TruncateText();
if (mAbsoluteCursorPosition > mLastLetterShowing + 1)
{
alignment = HorizontalAlignment.Right;
mLastLetterShowing++;
}
}
}
#if !SILVERLIGHT
#region Show the options list box if appropraite
if ( mAllOptions.Count != 0)
{
if (wasSomethingTyped || !GuiManager.PerishableWindows.Contains(mOptionsListBox))
{
if (!GuiManager.PerishableWindows.Contains(mOptionsListBox))
{
mOptionsListBox = GuiManager.AddPerishableListBox();
mOptionsListBox.CurrentToolTipOption = ListBoxBase.ToolTipOption.CursorOver;
mOptionsListBox.ScaleX = System.Math.Max(this.ScaleX, 4);
mOptionsListBox.ScaleY = 10;
mOptionsListBox.X = this.ScreenRelativeX;
mOptionsListBox.Y = this.ScreenRelativeY + this.ScaleY + mOptionsListBox.ScaleY;
mOptionsListBox.HighlightOnRollOver = true;
mOptionsListBox.Click += OptionsHighlight;
mOptionsListBox.Click += GuiManager.RemoveWindow;
}
mOptionsListBox.Clear();
bool isNullOrEmpty = string.IsNullOrEmpty(Text);
string textAsLower = Text.ToLower();
foreach (string s in mAllOptions)
{
bool matches = isNullOrEmpty || s.ToLower().Contains(textAsLower);
if (matches)
{
mOptionsListBox.AddItem(s);
}
}
}
}
#endregion
#endif
if (alignment == HorizontalAlignment.Right)
{
#if SILVERLIGHT
mFirstLetterShowing = mLastLetterShowing + 1 -
TextManager.GetNumberOfCharsIn(TextAreaWidth, CompleteText, mSpacing,
mLastLetterShowing, this.Font, alignment);
#else
mFirstLetterShowing = mLastLetterShowing + 1 -
TextManager.GetNumberOfCharsIn(TextAreaWidth, CompleteText, GuiManager.TextSpacing,
mLastLetterShowing, null, alignment);
#endif
DisplayedText = CompleteText.Substring(mFirstLetterShowing, mLastLetterShowing - mFirstLetterShowing + 1);
}
else if (alignment == HorizontalAlignment.Left)
{
#if SILVERLIGHT
mLastLetterShowing = mFirstLetterShowing - 1 +
TextManager.GetNumberOfCharsIn(TextAreaWidth, CompleteText, GuiManager.TextSpacing,
mFirstLetterShowing, null, alignment);
#else
mLastLetterShowing = mFirstLetterShowing - 1 +
TextManager.GetNumberOfCharsIn(TextAreaWidth, CompleteText, GuiManager.TextSpacing,
mFirstLetterShowing, null, alignment);
#endif
DisplayedText = CompleteText.Substring(mFirstLetterShowing, mLastLetterShowing - mFirstLetterShowing + 1);
}
}
public void HighlightCompleteText()
{
mHighlightStartPosition = 0;
mHighlightEndPosition = CompleteText.Length;
}
#region XML Docs
/// <summary>
/// Whether the user can type in this Text Box. Setting this to false makes the TextBox "read only".
/// </summary>
#endregion
public bool TakingInput
{
get
{
return mTakingInput;
}
set
{
mTakingInput = value;
}
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Fabric;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Actors;
using Microsoft.ServiceFabric.Actors.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
using SoCreate.ServiceFabric.PubSub.Helpers;
using SoCreate.ServiceFabric.PubSub.State;
namespace SoCreate.ServiceFabric.PubSub
{
public class BrokerClient : IBrokerClient
{
private readonly IBrokerServiceLocator _brokerServiceLocator;
/// <summary>
/// The message types that this service subscribes to and their respective handler methods.
/// </summary>
protected Dictionary<Type, Func<object, Task>> Handlers { get; set; } = new Dictionary<Type, Func<object, Task>>();
/// <summary>
/// A list of QueueStats for each queue on the Broker Service. Hold up to <see cref="QueueStatCapacity"/> items at a time.
/// </summary>
private readonly Dictionary<string, List<QueueStats>> _queueStats = new Dictionary<string, List<QueueStats>>();
/// <summary>
/// A dictionary of Reference Wrappers, keyed by queue name, representing all queues on the Broker Service.
/// </summary>
private Dictionary<string, ReferenceWrapper> _subscriberReferences = new Dictionary<string, ReferenceWrapper>();
public int QueueStatCapacity { get; set; } = 100;
/// <summary>
/// Create a BrokerClient
/// </summary>
/// <param name="brokerServiceLocator"></param>
public BrokerClient(IBrokerServiceLocator brokerServiceLocator = null)
{
_brokerServiceLocator = brokerServiceLocator ?? new BrokerServiceLocator();
}
/// <inheritdoc />
public async Task PublishMessageAsync<T>(T message) where T : class
{
var brokerService = await _brokerServiceLocator.GetBrokerServiceForMessageAsync(message);
await brokerService.PublishMessageAsync(message.CreateMessageWrapper());
}
/// <inheritdoc />
public async Task SubscribeAsync<T>(ReferenceWrapper referenceWrapper, Type messageType, Func<T, Task> handler, bool isOrdered = true) where T : class
{
Handlers[messageType] = message => handler((T)message);
var brokerService = await _brokerServiceLocator.GetBrokerServiceForMessageAsync(messageType.FullName);
await brokerService.SubscribeAsync(referenceWrapper, messageType.FullName, isOrdered);
}
/// <inheritdoc />
public async Task UnsubscribeAsync(ReferenceWrapper referenceWrapper, Type messageType)
{
var brokerService = await _brokerServiceLocator.GetBrokerServiceForMessageAsync(messageType);
await brokerService.UnsubscribeAsync(referenceWrapper, messageType.FullName);
}
/// <inheritdoc />
public Task ProcessMessageAsync(MessageWrapper messageWrapper)
{
var message = messageWrapper.CreateMessage();
var messageType = message.GetType();
while (messageType != null)
{
if (Handlers.TryGetValue(messageType, out var handler))
{
return handler(message);
}
messageType = messageType.BaseType;
}
return Task.FromResult(true);
}
/// <inheritdoc />
public async Task<Dictionary<string, List<QueueStats>>> GetBrokerStatsAsync()
{
foreach (var stat in await GetAllBrokerStatsAsync())
{
if (!_queueStats.ContainsKey(stat.QueueName))
{
_queueStats[stat.QueueName] = new List<QueueStats>();
}
_queueStats[stat.QueueName].Add(stat);
if (_queueStats[stat.QueueName].Count > QueueStatCapacity)
{
_queueStats[stat.QueueName].RemoveRange(0, _queueStats[stat.QueueName].Count - QueueStatCapacity);
}
}
return _queueStats;
}
/// <inheritdoc />
public async Task UnsubscribeByQueueNameAsync(string queueName)
{
if (!_subscriberReferences.ContainsKey(queueName))
{
await GetAllBrokerStatsAsync();
}
if (_subscriberReferences.TryGetValue(queueName, out var referenceWrapper))
{
var messageType = queueName.Split('_')[0];
var brokerService = await _brokerServiceLocator.GetBrokerServiceForMessageAsync(messageType);
await brokerService.UnsubscribeAsync(referenceWrapper, messageType);
_subscriberReferences.Remove(queueName);
_queueStats.Remove(queueName);
}
}
private async Task<IEnumerable<QueueStats>> GetAllBrokerStatsAsync()
{
var tasks = from brokerService in await _brokerServiceLocator.GetBrokerServicesForAllPartitionsAsync()
select brokerService.GetBrokerStatsAsync();
var allStats = await Task.WhenAll(tasks.ToList());
_subscriberReferences = allStats.SelectMany(stat => stat.Queues).ToDictionary(i => i.Key, i => i.Value);
return allStats.SelectMany(stat => stat.Stats);
}
}
public static class BrokerClientExtensions
{
// subscribe/unsubscribe using Generic type (useful when subscribing manually)
/// <summary>
/// Registers this StatelessService as a subscriber for messages of type <typeparam name="T"/> with the <see cref="BrokerService"/>.
/// </summary>
/// <param name="brokerClient"></param>
/// <param name="service"></param>
/// <param name="handler"></param>
/// <param name="isOrdered"></param>
/// <param name="listenerName"></param>
/// <param name="routingKey">Optional routing key to filter messages based on content. 'Key=Value' where Key is a message property path and Value is the value to match with message payload content.</param>
/// <returns></returns>
public static Task SubscribeAsync<T>(this IBrokerClient brokerClient, StatelessService service, Func<T, Task> handler, bool isOrdered = true, string listenerName = null, string routingKey = null) where T : class
{
return brokerClient.SubscribeAsync(CreateReferenceWrapper(service, listenerName, routingKey), typeof(T), handler, isOrdered);
}
/// <summary>
/// Registers this StatefulService as a subscriber for messages of type <typeparam name="T"/> with the <see cref="BrokerService"/>.
/// </summary>
/// <param name="brokerClient"></param>
/// <param name="service"></param>
/// <param name="handler"></param>
/// <param name="isOrdered"></param>
/// <param name="listenerName"></param>
/// <param name="routingKey">Optional routing key to filter messages based on content. 'Key=Value' where Key is a message property path and Value is the value to match with message payload content.</param>
/// <returns></returns>
public static Task SubscribeAsync<T>(this IBrokerClient brokerClient, StatefulService service, Func<T, Task> handler, bool isOrdered = true, string listenerName = null, string routingKey = null) where T : class
{
return brokerClient.SubscribeAsync(CreateReferenceWrapper(service, listenerName, routingKey), typeof(T), handler, isOrdered);
}
/// <summary>
/// Registers this Actor as a subscriber for messages of type <typeparam name="T"/> with the <see cref="BrokerService"/>.
/// </summary>
/// <param name="brokerClient"></param>
/// <param name="actor"></param>
/// <param name="handler"></param>
/// <param name="isOrdered"></param>
/// <param name="routingKey">Optional routing key to filter messages based on content. 'Key=Value' where Key is a message property path and Value is the value to match with message payload content.</param>
/// <returns></returns>
public static Task SubscribeAsync<T>(this IBrokerClient brokerClient, ActorBase actor, Func<T, Task> handler, bool isOrdered = true, string routingKey = null) where T : class
{
return brokerClient.SubscribeAsync(CreateReferenceWrapper(actor, routingKey), typeof(T), handler, isOrdered);
}
/// <summary>
/// Unregisters this StatelessService as a subscriber for messages of type <typeparam name="T"/> with the <see cref="BrokerService"/>.
/// </summary>
/// <param name="brokerClient"></param>
/// <param name="service"></param>
/// <returns></returns>
public static Task UnsubscribeAsync<T>(this IBrokerClient brokerClient, StatelessService service) where T : class
{
return brokerClient.UnsubscribeAsync(CreateReferenceWrapper(service), typeof(T));
}
/// <summary>
/// Unregisters this StatefulService as a subscriber for messages of type <typeparam name="T"/> with the <see cref="BrokerService"/>.
/// </summary>
/// <param name="brokerClient"></param>
/// <param name="service"></param>
/// <returns></returns>
public static Task UnsubscribeAsync<T>(this IBrokerClient brokerClient, StatefulService service) where T : class
{
return brokerClient.UnsubscribeAsync(CreateReferenceWrapper(service), typeof(T));
}
/// <summary>
/// Unregisters this Actor as a subscriber for messages of type <typeparam name="T"/> with the <see cref="BrokerService"/>.
/// </summary>
/// <param name="brokerClient"></param>
/// <param name="actor"></param>
/// <returns></returns>
public static Task UnsubscribeAsync<T>(this IBrokerClient brokerClient, ActorBase actor) where T : class
{
return brokerClient.UnsubscribeAsync(CreateReferenceWrapper(actor), typeof(T));
}
// subscribe/unsubscribe using Type (useful when processing Subscribe attributes)
internal static Task SubscribeAsync<T>(this IBrokerClient brokerClient, StatelessService service, Type messageType, Func<T, Task> handler, string listenerName = null, string routingKey = null, bool isOrdered = true) where T : class
{
return brokerClient.SubscribeAsync(CreateReferenceWrapper(service, listenerName, routingKey), messageType, handler, isOrdered);
}
internal static Task SubscribeAsync<T>(this IBrokerClient brokerClient, StatefulService service, Type messageType, Func<T, Task> handler, string listenerName = null, string routingKey = null, bool isOrdered = true) where T : class
{
return brokerClient.SubscribeAsync(CreateReferenceWrapper(service, listenerName, routingKey), messageType, handler, isOrdered);
}
internal static Task SubscribeAsync<T>(this IBrokerClient brokerClient, ActorBase actor, Type messageType, Func<T, Task> handler, string routingKey = null, bool isOrdered = true) where T : class
{
return brokerClient.SubscribeAsync(CreateReferenceWrapper(actor, routingKey), messageType, handler, isOrdered);
}
internal static Task UnsubscribeAsync(this IBrokerClient brokerClient, StatelessService service, Type messageType)
{
return brokerClient.UnsubscribeAsync(CreateReferenceWrapper(service), messageType);
}
internal static Task UnsubscribeAsync(this IBrokerClient brokerClient, StatefulService service, Type messageType)
{
return brokerClient.UnsubscribeAsync(CreateReferenceWrapper(service), messageType);
}
internal static Task UnsubscribeAsync(this IBrokerClient brokerClient, ActorBase actor, Type messageType)
{
return brokerClient.UnsubscribeAsync(CreateReferenceWrapper(actor), messageType);
}
/// <summary>
/// Create a ReferenceWrapper object given this StatelessService.
/// </summary>
/// <param name="service"></param>
/// <param name="listenerName"></param>
/// <param name="routingKey">Optional routing key to filter messages based on content. 'Key=Value' where Key is a message property path and Value is the value to match with message payload content.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static ReferenceWrapper CreateReferenceWrapper(this StatelessService service, string listenerName = null, string routingKey = null)
{
if (service == null) throw new ArgumentNullException(nameof(service));
var servicePartition = GetPropertyValue<StatelessService, IServicePartition>(service, "Partition");
return new ServiceReferenceWrapper(CreateServiceReference(service.Context, servicePartition.PartitionInfo, listenerName), routingKey);
}
/// <summary>
/// Create a ReferenceWrapper object given this StatefulService.
/// </summary>
/// <param name="service"></param>
/// <param name="listenerName"></param>
/// <param name="routingKey">Optional routing key to filter messages based on content. 'Key=Value' where Key is a message property path and Value is the value to match with message payload content.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static ReferenceWrapper CreateReferenceWrapper(this StatefulService service, string listenerName = null, string routingKey = null)
{
if (service == null) throw new ArgumentNullException(nameof(service));
var servicePartition = GetPropertyValue<StatefulService, IServicePartition>(service, "Partition");
return new ServiceReferenceWrapper(CreateServiceReference(service.Context, servicePartition.PartitionInfo, listenerName), routingKey);
}
/// <summary>
/// Create a ReferenceWrapper object given this Actor.
/// </summary>
/// <param name="actor"></param>
/// <param name="routingKey">Optional routing key to filter messages based on content. 'Key=Value' where Key is a message property path and Value is the value to match with message payload content.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static ReferenceWrapper CreateReferenceWrapper(this ActorBase actor, string routingKey = null)
{
if (actor == null) throw new ArgumentNullException(nameof(actor));
return new ActorReferenceWrapper(ActorReference.Get(actor), routingKey);
}
/// <summary>
/// Creates a <see cref="ServiceReference"/> for the provided service context and partition info.
/// </summary>
/// <param name="context"></param>
/// <param name="info"></param>
/// <param name="listenerName">(optional) The name of the listener that is used to communicate with the service</param>
/// <returns></returns>
private static ServiceReference CreateServiceReference(ServiceContext context, ServicePartitionInformation info, string listenerName = null)
{
var serviceReference = new ServiceReference
{
ApplicationName = context.CodePackageActivationContext.ApplicationName,
PartitionKind = info.Kind,
ServiceUri = context.ServiceName,
PartitionGuid = context.PartitionId,
ListenerName = listenerName
};
if (info is Int64RangePartitionInformation longInfo)
{
serviceReference.PartitionKey = longInfo.LowKey;
}
else if (info is NamedPartitionInformation stringInfo)
{
serviceReference.PartitionName = stringInfo.Name;
}
return serviceReference;
}
private static TProperty GetPropertyValue<TClass, TProperty>(TClass instance, string propertyName)
{
return (TProperty)(typeof(TClass)
.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic)?
.GetValue(instance) ?? throw new ArgumentNullException($"Unable to find property: '{propertyName}' on: '{instance}'"));
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion License
using System;
using System.Reflection;
using Irony.Interpreter.Ast;
/*
* Unfinished, work in progress, file disabled for now
*/
namespace Irony.Interpreter
{
public enum ClrTargetType
{
Namespace,
Type,
Method,
Property,
Field,
}
/// <summary>
/// Method for adding methods to BuiltIns table in Runtime
/// </summary>
public static partial class BindingSourceTableExtensions
{
public static void ImportStaticMembers(this BindingSourceTable targets, Type fromType)
{
var members = fromType.GetMembers(BindingFlags.Public | BindingFlags.Static);
foreach (var member in members)
{
if (targets.ContainsKey(member.Name))
// Do not import overloaded methods several times
continue;
switch (member.MemberType)
{
case MemberTypes.Method:
targets.Add(member.Name, new ClrMethodBindingTargetInfo(fromType, member.Name));
break;
case MemberTypes.Property:
targets.Add(member.Name, new ClrPropertyBindingTargetInfo(member as PropertyInfo, null));
break;
case MemberTypes.Field:
targets.Add(member.Name, new ClrFieldBindingTargetInfo(member as FieldInfo, null));
break;
}
}
}
}
public class ClrFieldBindingTargetInfo : ClrInteropBindingTargetInfo
{
public FieldInfo Field;
public object Instance;
private Binding binding;
public ClrFieldBindingTargetInfo(FieldInfo field, object instance) : base(field.Name, ClrTargetType.Field)
{
this.Field = field;
this.Instance = instance;
this.binding = new Binding(this);
this.binding.GetValueRef = this.GetPropertyValue;
this.binding.SetValueRef = this.SetPropertyValue;
}
public override Binding Bind(BindingRequest request)
{
return this.binding;
}
private object GetPropertyValue(ScriptThread thread)
{
var result = this.Field.GetValue(this.Instance);
return result;
}
private void SetPropertyValue(ScriptThread thread, object value)
{
this.Field.SetValue(this.Instance, value);
}
}
public class ClrInteropBindingTargetInfo : BindingTargetInfo, IBindingSource
{
public ClrTargetType TargetSubType;
public ClrInteropBindingTargetInfo(string symbol, ClrTargetType targetSubType) : base(symbol, BindingTargetType.ClrInterop)
{
this.TargetSubType = targetSubType;
}
public virtual Binding Bind(BindingRequest request)
{
throw new NotImplementedException();
}
}
public class ClrMethodBindingTargetInfo : ClrInteropBindingTargetInfo, ICallTarget
{
public Type DeclaringType;
/// <summary>
/// The object works as ICallTarget itself
/// </summary>
public object Instance;
private Binding binding;
private readonly BindingFlags invokeFlags;
public ClrMethodBindingTargetInfo(Type declaringType, string methodName, object instance = null) : base(methodName, ClrTargetType.Method)
{
this.DeclaringType = declaringType;
this.Instance = instance;
this.invokeFlags = BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.NonPublic;
if (this.Instance == null)
this.invokeFlags |= BindingFlags.Static;
else
this.invokeFlags |= BindingFlags.Instance;
this.binding = new ConstantBinding(target: this as ICallTarget, targetInfo: this);
// The object works as CallTarget itself; the "as" conversion is not needed in fact, we do it just to underline the role
}
public override Binding Bind(BindingRequest request)
{
return this.binding;
}
#region ICalllable.Call implementation
public object Call(ScriptThread thread, object[] args)
{
// TODO: fix this. Currently doing it slow but easy way, through reflection
if (args != null && args.Length == 0)
args = null;
var result = DeclaringType.InvokeMember(this.Symbol, this.invokeFlags, null, this.Instance, args);
return result;
}
#endregion ICalllable.Call implementation
}
public class ClrNamespaceBindingTargetInfo : ClrInteropBindingTargetInfo
{
private readonly ConstantBinding binding;
public ClrNamespaceBindingTargetInfo(string ns) : base(ns, ClrTargetType.Namespace)
{
this.binding = new ConstantBinding(ns, this);
}
public override Binding Bind(BindingRequest request)
{
return this.binding;
}
}
public class ClrPropertyBindingTargetInfo : ClrInteropBindingTargetInfo
{
public object Instance;
public PropertyInfo Property;
private Binding binding;
public ClrPropertyBindingTargetInfo(PropertyInfo property, object instance) : base(property.Name, ClrTargetType.Property)
{
this.Property = property;
this.Instance = instance;
this.binding = new Binding(this);
this.binding.GetValueRef = this.GetPropertyValue;
this.binding.SetValueRef = this.SetPropertyValue;
}
public override Binding Bind(BindingRequest request)
{
return this.binding;
}
private object GetPropertyValue(ScriptThread thread)
{
var result = this.Property.GetValue(this.Instance, null);
return result;
}
private void SetPropertyValue(ScriptThread thread, object value)
{
this.Property.SetValue(this.Instance, value, null);
}
}
public class ClrTypeBindingTargetInfo : ClrInteropBindingTargetInfo
{
private readonly ConstantBinding binding;
public ClrTypeBindingTargetInfo(Type type) : base(type.Name, ClrTargetType.Type)
{
this.binding = new ConstantBinding(type, this);
}
public override Binding Bind(BindingRequest request)
{
return this.binding;
}
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Config
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using NLog.Filters;
using NLog.Targets;
/// <summary>
/// Represents a logging rule. An equivalent of <logger /> configuration element.
/// </summary>
[NLogConfigurationItem]
public class LoggingRule
{
private readonly bool[] _logLevels = new bool[LogLevel.MaxLevel.Ordinal + 1];
private string _loggerNamePattern;
private MatchMode _loggerNameMatchMode;
private string _loggerNameMatchArgument;
/// <summary>
/// Create an empty <see cref="LoggingRule" />.
/// </summary>
public LoggingRule()
{
Filters = new List<Filter>();
ChildRules = new List<LoggingRule>();
Targets = new List<Target>();
}
/// <summary>
/// Create a new <see cref="LoggingRule" /> with a <paramref name="minLevel"/> and <paramref name="maxLevel"/> which writes to <paramref name="target"/>.
/// </summary>
/// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
/// <param name="minLevel">Minimum log level needed to trigger this rule.</param>
/// <param name="maxLevel">Maximum log level needed to trigger this rule.</param>
/// <param name="target">Target to be written to when the rule matches.</param>
public LoggingRule(string loggerNamePattern, LogLevel minLevel, LogLevel maxLevel, Target target)
: this()
{
LoggerNamePattern = loggerNamePattern;
Targets.Add(target);
EnableLoggingForLevels(minLevel, maxLevel);
}
/// <summary>
/// Create a new <see cref="LoggingRule" /> with a <paramref name="minLevel"/> which writes to <paramref name="target"/>.
/// </summary>
/// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
/// <param name="minLevel">Minimum log level needed to trigger this rule.</param>
/// <param name="target">Target to be written to when the rule matches.</param>
public LoggingRule(string loggerNamePattern, LogLevel minLevel, Target target)
: this()
{
LoggerNamePattern = loggerNamePattern;
Targets.Add(target);
EnableLoggingForLevels(minLevel, LogLevel.MaxLevel);
}
/// <summary>
/// Create a (disabled) <see cref="LoggingRule" />. You should call <see cref="EnableLoggingForLevel"/> or see cref="EnableLoggingForLevels"/> to enable logging.
/// </summary>
/// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
/// <param name="target">Target to be written to when the rule matches.</param>
public LoggingRule(string loggerNamePattern, Target target)
: this()
{
LoggerNamePattern = loggerNamePattern;
Targets.Add(target);
}
internal enum MatchMode
{
All,
None,
Equals,
StartsWith,
EndsWith,
Contains,
}
/// <summary>
/// Gets a collection of targets that should be written to when this rule matches.
/// </summary>
public IList<Target> Targets { get; }
/// <summary>
/// Gets a collection of child rules to be evaluated when this rule matches.
/// </summary>
public IList<LoggingRule> ChildRules { get; }
internal List<LoggingRule> GetChildRulesThreadSafe() { lock (ChildRules) return ChildRules.ToList(); }
internal List<Target> GetTargetsThreadSafe() { lock (Targets) return Targets.ToList(); }
internal bool RemoveTargetThreadSafe(Target target) { lock (Targets) return Targets.Remove(target); }
/// <summary>
/// Gets a collection of filters to be checked before writing to targets.
/// </summary>
public IList<Filter> Filters { get; }
/// <summary>
/// Gets or sets a value indicating whether to quit processing any further rule when this one matches.
/// </summary>
public bool Final { get; set; }
/// <summary>
/// Gets or sets logger name pattern.
/// </summary>
/// <remarks>
/// Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends but not anywhere else.
/// </remarks>
public string LoggerNamePattern
{
get => _loggerNamePattern;
set
{
_loggerNamePattern = value;
int firstPos = _loggerNamePattern.IndexOf('*');
int lastPos = _loggerNamePattern.LastIndexOf('*');
if (firstPos < 0)
{
_loggerNameMatchMode = MatchMode.Equals;
_loggerNameMatchArgument = value;
return;
}
if (firstPos == lastPos)
{
string before = LoggerNamePattern.Substring(0, firstPos);
string after = LoggerNamePattern.Substring(firstPos + 1);
if (before.Length > 0)
{
_loggerNameMatchMode = MatchMode.StartsWith;
_loggerNameMatchArgument = before;
return;
}
if (after.Length > 0)
{
_loggerNameMatchMode = MatchMode.EndsWith;
_loggerNameMatchArgument = after;
return;
}
return;
}
// *text*
if (firstPos == 0 && lastPos == LoggerNamePattern.Length - 1)
{
string text = LoggerNamePattern.Substring(1, LoggerNamePattern.Length - 2);
_loggerNameMatchMode = MatchMode.Contains;
_loggerNameMatchArgument = text;
return;
}
_loggerNameMatchMode = MatchMode.None;
_loggerNameMatchArgument = string.Empty;
}
}
/// <summary>
/// Gets the collection of log levels enabled by this rule.
/// </summary>
public ReadOnlyCollection<LogLevel> Levels
{
get
{
var levels = new List<LogLevel>();
for (int i = LogLevel.MinLevel.Ordinal; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
if (_logLevels[i])
{
levels.Add(LogLevel.FromOrdinal(i));
}
}
return levels.AsReadOnly();
}
}
/// <summary>
/// Enables logging for a particular level.
/// </summary>
/// <param name="level">Level to be enabled.</param>
public void EnableLoggingForLevel(LogLevel level)
{
if (level == LogLevel.Off)
{
return;
}
_logLevels[level.Ordinal] = true;
}
/// <summary>
/// Enables logging for a particular levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>.
/// </summary>
/// <param name="minLevel">Minimum log level needed to trigger this rule.</param>
/// <param name="maxLevel">Maximum log level needed to trigger this rule.</param>
public void EnableLoggingForLevels(LogLevel minLevel, LogLevel maxLevel)
{
for (int i = minLevel.Ordinal; i <= maxLevel.Ordinal; ++i)
{
EnableLoggingForLevel(LogLevel.FromOrdinal(i));
}
}
/// <summary>
/// Disables logging for a particular level.
/// </summary>
/// <param name="level">Level to be disabled.</param>
public void DisableLoggingForLevel(LogLevel level)
{
if (level == LogLevel.Off)
{
return;
}
_logLevels[level.Ordinal] = false;
}
/// <summary>
/// Disables logging for particular levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>.
/// </summary>
/// <param name="minLevel">Minimum log level to be disables.</param>
/// <param name="maxLevel">Maximum log level to de disabled.</param>
public void DisableLoggingForLevels(LogLevel minLevel, LogLevel maxLevel)
{
for (int i = minLevel.Ordinal; i <= maxLevel.Ordinal; i++)
{
DisableLoggingForLevel(LogLevel.FromOrdinal(i));
}
}
/// <summary>
/// Enables logging the levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>. All the other levels will be disabled.
/// </summary>
/// <param name="minLevel">>Minimum log level needed to trigger this rule.</param>
/// <param name="maxLevel">Maximum log level needed to trigger this rule.</param>
public void SetLoggingLevels(LogLevel minLevel, LogLevel maxLevel)
{
DisableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel);
EnableLoggingForLevels(minLevel, maxLevel);
}
/// <summary>
/// Returns a string representation of <see cref="LoggingRule"/>. Used for debugging.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendFormat(CultureInfo.InvariantCulture, "logNamePattern: ({0}:{1})", _loggerNameMatchArgument, _loggerNameMatchMode);
sb.Append(" levels: [ ");
for (int i = 0; i < _logLevels.Length; ++i)
{
if (_logLevels[i])
{
sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", LogLevel.FromOrdinal(i).ToString());
}
}
sb.Append("] appendTo: [ ");
foreach (Target app in GetTargetsThreadSafe())
{
sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", app.Name);
}
sb.Append("]");
return sb.ToString();
}
/// <summary>
/// Checks whether te particular log level is enabled for this rule.
/// </summary>
/// <param name="level">Level to be checked.</param>
/// <returns>A value of <see langword="true"/> when the log level is enabled, <see langword="false" /> otherwise.</returns>
public bool IsLoggingEnabledForLevel(LogLevel level)
{
if (level == LogLevel.Off)
{
return false;
}
return _logLevels[level.Ordinal];
}
/// <summary>
/// Checks whether given name matches the logger name pattern.
/// </summary>
/// <param name="loggerName">String to be matched.</param>
/// <returns>A value of <see langword="true"/> when the name matches, <see langword="false" /> otherwise.</returns>
public bool NameMatches(string loggerName)
{
switch (_loggerNameMatchMode)
{
case MatchMode.All:
return true;
default:
case MatchMode.None:
return false;
case MatchMode.Equals:
return loggerName.Equals(_loggerNameMatchArgument, StringComparison.Ordinal);
case MatchMode.StartsWith:
return loggerName.StartsWith(_loggerNameMatchArgument, StringComparison.Ordinal);
case MatchMode.EndsWith:
return loggerName.EndsWith(_loggerNameMatchArgument, StringComparison.Ordinal);
case MatchMode.Contains:
return loggerName.IndexOf(_loggerNameMatchArgument, StringComparison.Ordinal) >= 0;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Publishing;
namespace Umbraco.Core.Services
{
/// <summary>
/// Defines the ContentService, which is an easy access to operations involving <see cref="IContent"/>
/// </summary>
public interface IContentService : IService
{
/// <summary>
/// Used to bulk update the permissions set for a content item. This will replace all permissions
/// assigned to an entity with a list of user id & permission pairs.
/// </summary>
/// <param name="permissionSet"></param>
void ReplaceContentPermissions(EntityPermissionSet permissionSet);
/// <summary>
/// Assigns a single permission to the current content item for the specified user ids
/// </summary>
/// <param name="entity"></param>
/// <param name="permission"></param>
/// <param name="userIds"></param>
void AssignContentPermission(IContent entity, char permission, IEnumerable<int> userIds);
/// <summary>
/// Gets the list of permissions for the content item
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
IEnumerable<EntityPermission> GetPermissionsForEntity(IContent content);
bool SendToPublication(IContent content, int userId = 0);
IEnumerable<IContent> GetByIds(IEnumerable<int> ids);
/// <summary>
/// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/>
/// that this Content should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IContent without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new content objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Content object</param>
/// <param name="parentId">Id of Parent for the new Content</param>
/// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param>
/// <param name="userId">Optional id of the user creating the content</param>
/// <returns><see cref="IContent"/></returns>
IContent CreateContent(string name, int parentId, string contentTypeAlias, int userId = 0);
/// <summary>
/// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/>
/// that this Content should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IContent without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new content objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Content object</param>
/// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param>
/// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param>
/// <param name="userId">Optional id of the user creating the content</param>
/// <returns><see cref="IContent"/></returns>
IContent CreateContent(string name, IContent parent, string contentTypeAlias, int userId = 0);
/// <summary>
/// Gets an <see cref="IContent"/> object by Id
/// </summary>
/// <param name="id">Id of the Content to retrieve</param>
/// <returns><see cref="IContent"/></returns>
IContent GetById(int id);
/// <summary>
/// Gets an <see cref="IContent"/> object by its 'UniqueId'
/// </summary>
/// <param name="key">Guid key of the Content to retrieve</param>
/// <returns><see cref="IContent"/></returns>
IContent GetById(Guid key);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by the Id of the <see cref="IContentType"/>
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetContentOfContentType(int id);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Level
/// </summary>
/// <param name="level">The level to retrieve Content from</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetByLevel(int level);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetChildren(int id);
/// <summary>
/// Gets a collection of an <see cref="IContent"/> objects versions by its Id
/// </summary>
/// <param name="id"></param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetVersions(int id);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which reside at the first level / root
/// </summary>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetRootContent();
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which has an expiration date greater then today
/// </summary>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetContentForExpiration();
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which has a release date greater then today
/// </summary>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetContentForRelease();
/// <summary>
/// Gets a collection of an <see cref="IContent"/> objects, which resides in the Recycle Bin
/// </summary>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetContentInRecycleBin();
/// <summary>
/// Saves a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save</param>
/// <param name="userId">Optional Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
void Save(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Saves a collection of <see cref="IContent"/> objects.
/// </summary>
/// <param name="contents">Collection of <see cref="IContent"/> to save</param>
/// <param name="userId">Optional Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
void Save(IEnumerable<IContent> contents, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Deletes all content of specified type. All children of deleted content is moved to Recycle Bin.
/// </summary>
/// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks>
/// <param name="contentTypeId">Id of the <see cref="IContentType"/></param>
/// <param name="userId">Optional Id of the user issueing the delete operation</param>
void DeleteContentOfType(int contentTypeId, int userId = 0);
/// <summary>
/// Permanently deletes versions from an <see cref="IContent"/> object prior to a specific date.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> object to delete versions from</param>
/// <param name="versionDate">Latest version date</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
void DeleteVersions(int id, DateTime versionDate, int userId = 0);
/// <summary>
/// Permanently deletes a specific version from an <see cref="IContent"/> object.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> object to delete a version from</param>
/// <param name="versionId">Id of the version to delete</param>
/// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0);
/// <summary>
/// Deletes an <see cref="IContent"/> object by moving it to the Recycle Bin
/// </summary>
/// <remarks>Move an item to the Recycle Bin will result in the item being unpublished</remarks>
/// <param name="content">The <see cref="IContent"/> to delete</param>
/// <param name="userId">Optional Id of the User deleting the Content</param>
void MoveToRecycleBin(IContent content, int userId = 0);
/// <summary>
/// Moves an <see cref="IContent"/> object to a new location
/// </summary>
/// <param name="content">The <see cref="IContent"/> to move</param>
/// <param name="parentId">Id of the Content's new Parent</param>
/// <param name="userId">Optional Id of the User moving the Content</param>
void Move(IContent content, int parentId, int userId = 0);
/// <summary>
/// Empties the Recycle Bin by deleting all <see cref="IContent"/> that resides in the bin
/// </summary>
void EmptyRecycleBin();
/// <summary>
/// Rollback an <see cref="IContent"/> object to a previous version.
/// This will create a new version, which is a copy of all the old data.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/>being rolled back</param>
/// <param name="versionId">Id of the version to rollback to</param>
/// <param name="userId">Optional Id of the User issueing the rollback of the Content</param>
/// <returns>The newly created <see cref="IContent"/> object</returns>
IContent Rollback(int id, Guid versionId, int userId = 0);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by its name or partial name
/// </summary>
/// <param name="parentId">Id of the Parent to retrieve Children from</param>
/// <param name="name">Full or partial name of the children</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetChildrenByName(int parentId, string name);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Descendants from</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetDescendants(int id);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="content"><see cref="IContent"/> item to retrieve Descendants from</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetDescendants(IContent content);
/// <summary>
/// Gets a specific version of an <see cref="IContent"/> item.
/// </summary>
/// <param name="versionId">Id of the version to retrieve</param>
/// <returns>An <see cref="IContent"/> item</returns>
IContent GetByVersion(Guid versionId);
/// <summary>
/// Gets the published version of an <see cref="IContent"/> item
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> to retrieve version from</param>
/// <returns>An <see cref="IContent"/> item</returns>
IContent GetPublishedVersion(int id);
/// <summary>
/// Checks whether an <see cref="IContent"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/></param>
/// <returns>True if the content has any children otherwise False</returns>
bool HasChildren(int id);
/// <summary>
/// Checks whether an <see cref="IContent"/> item has any published versions
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/></param>
/// <returns>True if the content has any published version otherwise False</returns>
bool HasPublishedVersion(int id);
/// <summary>
/// Re-Publishes all Content
/// </summary>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
bool RePublishAll(int userId = 0);
/// <summary>
/// Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
bool Publish(IContent content, int userId = 0);
/// <summary>
/// Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>The published status attempt</returns>
Attempt<PublishStatus> PublishWithStatus(IContent content, int userId = 0);
/// <summary>
/// Publishes a <see cref="IContent"/> object and all its children
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish along with its children</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
[Obsolete("Use PublishWithChildrenWithStatus instead, that method will provide more detailed information on the outcome and also allows the includeUnpublished flag")]
bool PublishWithChildren(IContent content, int userId = 0);
/// <summary>
/// Publishes a <see cref="IContent"/> object and all its children
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish along with its children</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="includeUnpublished"></param>
/// <returns>The list of statuses for all published items</returns>
IEnumerable<Attempt<PublishStatus>> PublishWithChildrenWithStatus(IContent content, int userId = 0, bool includeUnpublished = false);
/// <summary>
/// UnPublishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if unpublishing succeeded, otherwise False</returns>
bool UnPublish(IContent content, int userId = 0);
/// <summary>
/// Saves and Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save and publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
[Obsolete("Use SaveAndPublishWithStatus instead, that method will provide more detailed information on the outcome")]
bool SaveAndPublish(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Saves and Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save and publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
Attempt<PublishStatus> SaveAndPublishWithStatus(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Permanently deletes an <see cref="IContent"/> object.
/// </summary>
/// <remarks>
/// This method will also delete associated media files, child content and possibly associated domains.
/// </remarks>
/// <remarks>Please note that this method will completely remove the Content from the database</remarks>
/// <param name="content">The <see cref="IContent"/> to delete</param>
/// <param name="userId">Optional Id of the User deleting the Content</param>
void Delete(IContent content, int userId = 0);
/// <summary>
/// Copies an <see cref="IContent"/> object by creating a new Content object of the same type and copies all data from the current
/// to the new copy which is returned.
/// </summary>
/// <param name="content">The <see cref="IContent"/> to copy</param>
/// <param name="parentId">Id of the Content's new Parent</param>
/// <param name="relateToOriginal">Boolean indicating whether the copy should be related to the original</param>
/// <param name="userId">Optional Id of the User copying the Content</param>
/// <returns>The newly created <see cref="IContent"/> object</returns>
IContent Copy(IContent content, int parentId, bool relateToOriginal, int userId = 0);
/// <summary>
/// Checks if the passed in <see cref="IContent"/> can be published based on the anscestors publish state.
/// </summary>
/// <param name="content"><see cref="IContent"/> to check if anscestors are published</param>
/// <returns>True if the Content can be published, otherwise False</returns>
bool IsPublishable(IContent content);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetAncestors(int id);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content.
/// </summary>
/// <param name="content"><see cref="IContent"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetAncestors(IContent content);
/// <summary>
/// Sorts a collection of <see cref="IContent"/> objects by updating the SortOrder according
/// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>.
/// </summary>
/// <remarks>
/// Using this method will ensure that the Published-state is maintained upon sorting
/// so the cache is updated accordingly - as needed.
/// </remarks>
/// <param name="items"></param>
/// <param name="userId"></param>
/// <param name="raiseEvents"></param>
/// <returns>True if sorting succeeded, otherwise False</returns>
bool Sort(IEnumerable<IContent> items, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Gets the parent of the current content as an <see cref="IContent"/> item.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> to retrieve the parent from</param>
/// <returns>Parent <see cref="IContent"/> object</returns>
IContent GetParent(int id);
/// <summary>
/// Gets the parent of the current content as an <see cref="IContent"/> item.
/// </summary>
/// <param name="content"><see cref="IContent"/> to retrieve the parent from</param>
/// <returns>Parent <see cref="IContent"/> object</returns>
IContent GetParent(IContent content);
/// <summary>
/// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/>
/// that this Content should based on.
/// </summary>
/// <remarks>
/// This method returns an <see cref="IContent"/> object that has been persisted to the database
/// and therefor has an identity.
/// </remarks>
/// <param name="name">Name of the Content object</param>
/// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param>
/// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param>
/// <param name="userId">Optional id of the user creating the content</param>
/// <returns><see cref="IContent"/></returns>
IContent CreateContentWithIdentity(string name, IContent parent, string contentTypeAlias, int userId = 0);
/// <summary>
/// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/>
/// that this Content should based on.
/// </summary>
/// <remarks>
/// This method returns an <see cref="IContent"/> object that has been persisted to the database
/// and therefor has an identity.
/// </remarks>
/// <param name="name">Name of the Content object</param>
/// <param name="parentId">Id of Parent for the new Content</param>
/// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param>
/// <param name="userId">Optional id of the user creating the content</param>
/// <returns><see cref="IContent"/></returns>
IContent CreateContentWithIdentity(string name, int parentId, string contentTypeAlias, int userId = 0);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
namespace PushSharp.Apple
{
public class AppleNotificationPayload
{
public AppleNotificationAlert Alert { get; set; }
public int? ContentAvailable { get; set; }
public int? Badge { get; set; }
public string Sound { get; set; }
public bool HideActionButton { get; set; }
public string Category { get; set; }
public bool HasMutableContent { get; set; }
public Dictionary<string, object[]> CustomItems
{
get;
private set;
}
public AppleNotificationPayload()
{
HideActionButton = false;
Alert = new AppleNotificationAlert();
CustomItems = new Dictionary<string, object[]>();
}
public AppleNotificationPayload(string alert)
{
HideActionButton = false;
Alert = new AppleNotificationAlert() { Body = alert };
CustomItems = new Dictionary<string, object[]>();
}
public AppleNotificationPayload(string alert, int badge)
{
HideActionButton = false;
Alert = new AppleNotificationAlert() { Body = alert };
Badge = badge;
CustomItems = new Dictionary<string, object[]>();
}
public AppleNotificationPayload(string alert, int badge, string sound)
{
HideActionButton = false;
Alert = new AppleNotificationAlert() { Body = alert };
Badge = badge;
Sound = sound;
CustomItems = new Dictionary<string, object[]>();
}
public AppleNotificationPayload(string alert, int badge, string sound, string category)
: this(alert, badge, sound)
{
Category = category;
}
public void AddCustom(string key, params object[] values)
{
if (values != null)
this.CustomItems.Add(key, values);
}
public string ToJson()
{
JObject json = new JObject();
JObject aps = new JObject();
if (!this.Alert.IsEmpty)
{
if (this.Alert.ShouldSerializeAsString(this.HideActionButton))
{
aps["alert"] = new JValue(this.Alert.Body);
}
else
{
JObject jsonAlert = new JObject();
if (!string.IsNullOrEmpty(this.Alert.Title))
jsonAlert["title"] = new JValue(this.Alert.Title);
if (!string.IsNullOrEmpty(this.Alert.TitleLocalizedKey))
jsonAlert["title-loc-key"] = new JValue(this.Alert.TitleLocalizedKey);
if (this.Alert.LocalizedArgs != null && this.Alert.TitleLocalizedArgs.Count > 0)
jsonAlert["title-loc-args"] = new JArray(this.Alert.TitleLocalizedArgs.ToArray());
if (!string.IsNullOrEmpty(this.Alert.LocalizedKey))
jsonAlert["loc-key"] = new JValue(this.Alert.LocalizedKey);
if (this.Alert.LocalizedArgs != null && this.Alert.LocalizedArgs.Count > 0)
jsonAlert["loc-args"] = new JArray(this.Alert.LocalizedArgs.ToArray());
if (!string.IsNullOrEmpty(this.Alert.Body))
jsonAlert["body"] = new JValue(this.Alert.Body);
if (this.HideActionButton)
jsonAlert["action-loc-key"] = new JValue((string)null);
else if (!string.IsNullOrEmpty(this.Alert.ActionLocalizedKey))
jsonAlert["action-loc-key"] = new JValue(this.Alert.ActionLocalizedKey);
if (!string.IsNullOrEmpty(this.Alert.LaunchImage))
jsonAlert["launch-image"] = new JValue(this.Alert.LaunchImage);
aps["alert"] = jsonAlert;
}
}
if (this.Badge.HasValue)
aps["badge"] = new JValue(this.Badge.Value);
if (!string.IsNullOrEmpty(this.Sound))
aps["sound"] = new JValue(this.Sound);
if (this.ContentAvailable.HasValue)
{
aps["content-available"] = new JValue(this.ContentAvailable.Value);
}
if (!string.IsNullOrEmpty(this.Category))
{
// iOS8 Interactive Notifications
aps["category"] = new JValue(this.Category);
}
if (HasMutableContent)
aps["mutable-content"] = new JValue(1);
if (aps.Count > 0)
json["aps"] = aps;
foreach (string key in this.CustomItems.Keys)
{
if (this.CustomItems[key].Length == 1)
{
object custom = this.CustomItems[key][0];
json[key] = custom is JToken ? (JToken) custom : new JValue(custom);
}
else if (this.CustomItems[key].Length > 1)
json[key] = new JArray(this.CustomItems[key]);
}
var rawString = json.ToString(Newtonsoft.Json.Formatting.None, null);
var encodedString = new StringBuilder();
foreach (char c in rawString)
{
if ((int)c < 32 || (int)c > 127)
encodedString.Append("\\u" + $"{Convert.ToUInt32(c):x4}");
else
encodedString.Append(c);
}
return rawString;// encodedString.ToString();
}
//public string ToJson()
//{
// bool tmpBool;
// double tmpDbl;
// var json = new StringBuilder();
// var aps = new StringBuilder();
// if (!this.Alert.IsEmpty)
// {
// if (!string.IsNullOrEmpty(this.Alert.Body)
// && string.IsNullOrEmpty(this.Alert.LocalizedKey)
// && string.IsNullOrEmpty(this.Alert.ActionLocalizedKey)
// && (this.Alert.LocalizedArgs == null || this.Alert.LocalizedArgs.Count <= 0)
// && !this.HideActionButton)
// {
// aps.AppendFormat("\"alert\":\"{0}\",", this.Alert.Body);
// }
// else
// {
// var jsonAlert = new StringBuilder();
// if (!string.IsNullOrEmpty(this.Alert.LocalizedKey))
// jsonAlert.AppendFormat("\"loc-key\":\"{0}\",", this.Alert.LocalizedKey);
// if (this.Alert.LocalizedArgs != null && this.Alert.LocalizedArgs.Count > 0)
// {
// var locArgs = new StringBuilder();
// foreach (var larg in this.Alert.LocalizedArgs)
// {
// if (double.TryParse(larg.ToString(), out tmpDbl)
// || bool.TryParse(larg.ToString(), out tmpBool))
// locArgs.AppendFormat("{0},", larg.ToString());
// else
// locArgs.AppendFormat("\"{0}\",", larg.ToString());
// }
// jsonAlert.AppendFormat("\"loc-args\":[{0}],", locArgs.ToString().TrimEnd(','));
// }
// if (!string.IsNullOrEmpty(this.Alert.Body))
// jsonAlert.AppendFormat("\body\":\"{0}\",", this.Alert.Body);
// if (this.HideActionButton)
// jsonAlert.AppendFormat("\"action-loc-key\":null,");
// else if (!string.IsNullOrEmpty(this.Alert.ActionLocalizedKey))
// jsonAlert.AppendFormat("\action-loc-key\":\"{0}\",", this.Alert.ActionLocalizedKey);
// aps.Append("\"alert\":{");
// aps.Append(jsonAlert.ToString().TrimEnd(','));
// aps.Append("},");
// }
// }
// if (this.Badge.HasValue)
// aps.AppendFormat("\"badge\":{0},", this.Badge.Value.ToString());
// if (!string.IsNullOrEmpty(this.Sound))
// aps.AppendFormat("\"sound\":\"{0}\",", this.Sound);
// if (this.ContentAvailable.HasValue)
// aps.AppendFormat("\"content-available\":{0},", this.ContentAvailable.Value.ToString());
// json.Append("\"aps\":{");
// json.Append(aps.ToString().TrimEnd(','));
// json.Append("},");
// foreach (string key in this.CustomItems.Keys)
// {
// if (this.CustomItems[key].Length == 1)
// {
// if (double.TryParse(this.CustomItems[key].ToString(), out tmpDbl)
// || bool.TryParse(this.CustomItems[key].ToString(), out tmpBool))
// json.AppendFormat("\"{0}\":[{1}],", key, this.CustomItems[key][0].ToString());
// else
// json.AppendFormat("\"{0}\":[\"{1}\",", key, this.CustomItems[key][0].ToString());
// }
// else if (this.CustomItems[key].Length > 1)
// {
// var jarr = new StringBuilder();
// foreach (var item in this.CustomItems[key])
// {
// if (double.TryParse(item.ToString(), out tmpDbl)
// || bool.TryParse(item.ToString(), out tmpBool))
// jarr.AppendFormat("{0},", item.ToString());
// else
// jarr.AppendFormat("\"{0}\",", item.ToString());
// }
// json.AppendFormat("\"{0}\":[{1}],", key, jarr.ToString().Trim(','));
// }
// }
// string rawString = "{" + json.ToString().TrimEnd(',') + "}";
// StringBuilder encodedString = new StringBuilder();
// foreach (char c in rawString)
// {
// if ((int)c < 32 || (int)c > 127)
// encodedString.Append("\\u" + String.Format("{0:x4}", Convert.ToUInt32(c)));
// else
// encodedString.Append(c);
// }
// return rawString;// encodedString.ToString();
//}
public override string ToString()
{
return ToJson();
}
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using NodaTime.Calendars;
using NodaTime.Globalization;
using NodaTime.Test.Text;
using NUnit.Framework;
namespace NodaTime.Test.Globalization
{
[TestFixture]
public class NodaFormatInfoTest
{
private readonly CultureInfo enUs = CultureInfo.GetCultureInfo("en-US");
private readonly CultureInfo enGb = CultureInfo.GetCultureInfo("en-GB");
private sealed class EmptyFormatProvider : IFormatProvider
{
#region IFormatProvider Members
public object GetFormat(Type formatType)
{
return null;
}
#endregion
}
// Just check we can actually build a NodaFormatInfo for every culture, outside
// text-specific tests.
[Test]
[TestCaseSource(typeof(Cultures), "AllCultures")]
public void ConvertCulture(CultureInfo culture)
{
NodaFormatInfo.GetFormatInfo(culture);
}
[Test]
public void TestCachingWithReadOnly()
{
var original = new CultureInfo("en-US");
// Use a read-only wrapper so that it gets cached
var wrapper = CultureInfo.ReadOnly(original);
var nodaWrapper1 = NodaFormatInfo.GetFormatInfo(wrapper);
var nodaWrapper2 = NodaFormatInfo.GetFormatInfo(wrapper);
Assert.AreSame(nodaWrapper1, nodaWrapper2);
}
[Test]
public void TestCachingWithClonedCulture()
{
var original = new CultureInfo("en-US");
var clone = (CultureInfo) original.Clone();
Assert.AreEqual(original.Name, clone.Name);
clone.DateTimeFormat.DateSeparator = "@@@";
// Fool Noda Time into believing both are read-only, so it can use a cache...
original = CultureInfo.ReadOnly(original);
clone = CultureInfo.ReadOnly(clone);
var nodaOriginal = NodaFormatInfo.GetFormatInfo(original);
var nodaClone = NodaFormatInfo.GetFormatInfo(clone);
Assert.AreEqual(original.DateTimeFormat.DateSeparator, nodaOriginal.DateSeparator);
Assert.AreEqual(clone.DateTimeFormat.DateSeparator, nodaClone.DateSeparator);
}
[Test]
public void TestConstructor()
{
var info = new NodaFormatInfo(enUs);
Assert.AreSame(enUs, info.CultureInfo);
Assert.NotNull(info.NumberFormat);
Assert.NotNull(info.DateTimeFormat);
Assert.AreEqual("+", info.PositiveSign);
Assert.AreEqual("-", info.NegativeSign);
Assert.AreEqual(":", info.TimeSeparator);
Assert.AreEqual("/", info.DateSeparator);
Assert.IsInstanceOf<string>(info.OffsetPatternLong);
Assert.IsInstanceOf<string>(info.OffsetPatternMedium);
Assert.IsInstanceOf<string>(info.OffsetPatternShort);
Assert.AreEqual("NodaFormatInfo[en-US]", info.ToString());
}
[Test]
public void TestConstructor_null()
{
Assert.Throws<ArgumentNullException>(() => new NodaFormatInfo(null));
}
[Test]
public void TestDateTimeFormat()
{
var format = DateTimeFormatInfo.InvariantInfo;
var info = new NodaFormatInfo(enUs);
Assert.AreNotEqual(format, info.DateTimeFormat);
}
[Test]
public void TestGetFormatInfo()
{
NodaFormatInfo.ClearCache();
var info1 = NodaFormatInfo.GetFormatInfo(enUs);
Assert.NotNull(info1);
var info2 = NodaFormatInfo.GetFormatInfo(enUs);
Assert.AreSame(info1, info2);
var info3 = NodaFormatInfo.GetFormatInfo(enGb);
Assert.AreNotSame(info1, info3);
}
[Test]
public void TestGetFormatInfo_null()
{
NodaFormatInfo.ClearCache();
Assert.Throws<ArgumentNullException>(() => NodaFormatInfo.GetFormatInfo(null));
}
[Test]
public void TestGetInstance_CultureInfo()
{
NodaFormatInfo.ClearCache();
using (CultureSaver.SetCultures(enUs, FailingCultureInfo.Instance))
{
var actual = NodaFormatInfo.GetInstance(enGb);
Assert.AreSame(enGb, actual.CultureInfo);
}
}
[Test]
public void TestGetInstance_IFormatProvider()
{
NodaFormatInfo.ClearCache();
using (CultureSaver.SetCultures(enUs, FailingCultureInfo.Instance))
{
var provider = new EmptyFormatProvider();
var actual = NodaFormatInfo.GetInstance(provider);
Assert.AreSame(enUs, actual.CultureInfo);
}
}
[Test]
public void TestGetInstance_null()
{
NodaFormatInfo.ClearCache();
using (CultureSaver.SetCultures(enUs, FailingCultureInfo.Instance))
{
var info = NodaFormatInfo.GetInstance(null);
Assert.AreEqual(Thread.CurrentThread.CurrentCulture, info.CultureInfo);
}
using (CultureSaver.SetCultures(enGb, FailingCultureInfo.Instance))
{
var info = NodaFormatInfo.GetInstance(null);
Assert.AreEqual(Thread.CurrentThread.CurrentCulture, info.CultureInfo);
}
}
[Test]
public void TestNumberFormat()
{
var format = NumberFormatInfo.InvariantInfo;
var info = new NodaFormatInfo(enUs);
Assert.AreNotEqual(format, info.NumberFormat);
}
[Test]
public void TestOffsetPatternLong()
{
const string pattern = "This is a test";
var info = new NodaFormatInfo(enUs);
Assert.AreNotEqual(pattern, info.OffsetPatternLong);
}
[Test]
public void TestOffsetPatternMedium()
{
const string pattern = "This is a test";
var info = new NodaFormatInfo(enUs);
Assert.AreNotEqual(pattern, info.OffsetPatternMedium);
}
[Test]
public void TestOffsetPatternShort()
{
const string pattern = "This is a test";
var info = new NodaFormatInfo(enUs);
Assert.AreNotEqual(pattern, info.OffsetPatternShort);
}
[Test]
public void TestGetEraNames()
{
var info = NodaFormatInfo.GetFormatInfo(enUs);
IList<string> names = info.GetEraNames(Era.BeforeCommon);
CollectionAssert.AreEqual(new[] { "B.C.E.", "B.C.", "BCE", "BC" }, names);
}
[Test]
public void TestGetEraNames_NoSuchEra()
{
var info = NodaFormatInfo.GetFormatInfo(enUs);
Assert.AreEqual(0, info.GetEraNames(new Era("Ignored", "NonExistantResource")).Count);
}
[Test]
public void TestEraGetNames_Null()
{
var info = NodaFormatInfo.GetFormatInfo(enUs);
Assert.Throws<ArgumentNullException>(() => info.GetEraNames(null));
}
[Test]
public void TestGetEraPrimaryName()
{
var info = NodaFormatInfo.GetFormatInfo(enUs);
Assert.AreEqual("B.C.", info.GetEraPrimaryName(Era.BeforeCommon));
}
[Test]
public void TestGetEraPrimaryName_NoSuchEra()
{
var info = NodaFormatInfo.GetFormatInfo(enUs);
Assert.AreEqual("", info.GetEraPrimaryName(new Era("Ignored", "NonExistantResource")));
}
[Test]
public void TestEraGetEraPrimaryName_Null()
{
var info = NodaFormatInfo.GetFormatInfo(enUs);
Assert.Throws<ArgumentNullException>(() => info.GetEraPrimaryName(null));
}
}
}
| |
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Amazon Software License (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/asl/
//
// or in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, 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.IO;
using System.Text;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal.Util;
using Amazon.Runtime.Internal.Auth;
using Amazon.Util;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Default implementation of the IRequest interface.
/// <para>
/// This class is only intended for internal use inside the AWS client libraries.
/// Callers shouldn't ever interact directly with objects of this class.
/// </para>
/// </summary>
public class DefaultRequest : IRequest
{
readonly IDictionary<string, string> parameters = new Dictionary<string, string>(StringComparer.Ordinal);
readonly IDictionary<string, string> headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
readonly IDictionary<string, string> subResources = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Uri endpoint;
string resourcePath;
string serviceName;
readonly AmazonWebServiceRequest originalRequest;
byte[] content;
Stream contentStream;
string contentStreamHash;
string httpMethod = "POST";
bool useQueryString = false;
string requestName;
string canonicalResource;
RegionEndpoint alternateRegion;
long originalStreamLength;
/// <summary>
/// Constructs a new DefaultRequest with the specified service name and the
/// original, user facing request object.
/// </summary>
/// <param name="request">The orignal request that is being wrapped</param>
/// <param name="serviceName">The service name</param>
public DefaultRequest(AmazonWebServiceRequest request, String serviceName)
{
if (request == null) throw new ArgumentNullException("request");
if (string.IsNullOrEmpty(serviceName)) throw new ArgumentNullException("serviceName");
this.serviceName = serviceName;
this.originalRequest = request;
this.requestName = this.originalRequest.GetType().Name;
this.UseSigV4 = ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)this.originalRequest).UseSigV4;
}
/// <summary>
/// The name of the request
/// </summary>
public string RequestName
{
get { return this.requestName; }
}
/// <summary>
/// Gets and sets the type of http request to make, whether it should be POST,GET or DELETE
/// </summary>
public string HttpMethod
{
get
{
return this.httpMethod;
}
set
{
this.httpMethod = value;
}
}
/// <summary>
/// Gets and sets a flag that indicates whether the request is sent as a query string instead of the request body.
/// </summary>
public bool UseQueryString
{
get
{
if (this.HttpMethod == "GET")
return true;
return this.useQueryString;
}
set
{
this.useQueryString = value;
}
}
/// <summary>
/// Returns the original, user facing request object which this internal
/// request object is representing.
/// </summary>
public AmazonWebServiceRequest OriginalRequest
{
get
{
return originalRequest;
}
}
/// <summary>
/// Returns a dictionary of the headers included in this request.
/// </summary>
public IDictionary<string, string> Headers
{
get
{
return this.headers;
}
}
/// <summary>
/// Returns a dictionary of the parameters included in this request.
/// </summary>
public IDictionary<string, string> Parameters
{
get
{
return this.parameters;
}
}
/// <summary>
/// Returns the subresources that should be appended to the resource path.
/// This is used primarily for Amazon S3, where object keys can contain '?'
/// characters, making string-splitting of a resource path potentially
/// hazardous.
/// </summary>
public IDictionary<string, string> SubResources
{
get
{
return this.subResources;
}
}
/// <summary>
/// Adds a new null entry to the SubResources collection for the request
/// </summary>
/// <param name="subResource">The name of the subresource</param>
public void AddSubResource(string subResource)
{
AddSubResource(subResource, null);
}
/// <summary>
/// Adds a new entry to the SubResources collection for the request
/// </summary>
/// <param name="subResource">The name of the subresource</param>
/// <param name="value">Value of the entry</param>
public void AddSubResource(string subResource, string value)
{
SubResources.Add(subResource, value);
}
/// <summary>
/// Gets and Sets the endpoint for this request.
/// </summary>
public Uri Endpoint
{
get
{
return this.endpoint;
}
set
{
this.endpoint = value;
}
}
/// <summary>
/// Gets and Sets the resource path added on to the endpoint.
/// </summary>
public string ResourcePath
{
get
{
return this.resourcePath;
}
set
{
this.resourcePath = value;
}
}
public string CanonicalResource
{
get
{
return this.canonicalResource;
}
set
{
this.canonicalResource = value;
}
}
/// <summary>
/// Gets and Sets the content for this request.
/// </summary>
public byte[] Content
{
get
{
return this.content;
}
set
{
this.content = value;
}
}
/// <summary>
/// Flag that signals that Content was and should be set
/// from the Parameters collection.
/// </summary>
public bool SetContentFromParameters { get; set; }
/// <summary>
/// Gets and sets the content stream.
/// </summary>
public Stream ContentStream
{
get { return this.contentStream; }
set
{
this.contentStream = value;
OriginalStreamPosition = -1;
if (this.contentStream != null)
{
Stream baseStream = HashStream.GetNonWrapperBaseStream(this.contentStream);
if (baseStream.CanSeek)
OriginalStreamPosition = baseStream.Position;
}
}
}
/// <summary>
/// Gets and sets the original stream position.
/// If ContentStream is null or does not support seek, this propery
/// should be equal to -1.
/// </summary>
public long OriginalStreamPosition
{
get { return this.originalStreamLength; }
set { this.originalStreamLength = value; }
}
/// <summary>
/// Computes the SHA 256 hash of the content stream. If the stream is not
/// seekable, it searches the parent stream hierarchy to find a seekable
/// stream prior to computation. Once computed, the hash is cached for future
/// use. If a suitable stream cannot be found to use, null is returned.
/// </summary>
public string ComputeContentStreamHash()
{
if (this.contentStream == null)
return null;
if (this.contentStreamHash == null)
{
var seekableStream = WrapperStream.SearchWrappedStream(this.contentStream, s => s.CanSeek);
if (seekableStream != null)
{
var position = seekableStream.Position;
byte[] payloadHashBytes = CryptoUtilFactory.CryptoInstance.ComputeSHA256Hash(seekableStream);
this.contentStreamHash = AWSSDKUtils.ToHex(payloadHashBytes, true);
seekableStream.Seek(position, SeekOrigin.Begin);
}
}
return this.contentStreamHash;
}
/// <summary>
/// The name of the service to which this request is being sent.
/// </summary>
public string ServiceName
{
get
{
return this.serviceName;
}
}
/// <summary>
/// Alternate endpoint to use for this request, if any.
/// </summary>
public RegionEndpoint AlternateEndpoint
{
get
{
return this.alternateRegion;
}
set
{
this.alternateRegion = value;
}
}
/// <summary>
/// Gets and sets the Suppress404Exceptions property. If true then 404s return back from AWS will not cause an exception and
/// an empty response object will be returned.
/// </summary>
public bool Suppress404Exceptions
{
get;
set;
}
/// <summary>
/// If using AWS4 signing protocol, contains the resultant parts of the
/// signature that we may need to make use of if we elect to do a chunked
/// encoding upload.
/// </summary>
public AWS4SigningResult AWS4SignerResult { get; set; }
/// <summary>
/// Determine whether to use a chunked encoding upload for the request
/// (applies to Amazon S3 PutObject and UploadPart requests only).
/// </summary>
/// <returns></returns>
public bool UseChunkEncoding { get; set; }
/// <summary>
/// Used for Amazon S3 requests where the bucket name is removed from
/// the marshalled resource path into the host header. To comply with
/// AWS2 signature calculation, we need to recover the bucket name
/// and include it in the resource canonicalization, which we do using
/// this field.
/// </summary>
public string CanonicalResourcePrefix
{
get;
set;
}
/// <summary>
/// This flag specifies if SigV4 is required for the current request.
/// </summary>
public bool UseSigV4 { get; set; }
/// <summary>
/// The authentication region to use for the request.
/// Set from Config.AuthenticationRegion.
/// </summary>
public string AuthenticationRegion { get; set; }
/// <summary>
/// Checks if the request stream can be rewinded.
/// </summary>
/// <returns>Returns true if the request stream can be rewinded ,
/// else false.</returns>
public bool IsRequestStreamRewindable()
{
var stream = this.ContentStream;
// Retries may not be possible with a stream
if (stream != null)
{
// Pull out the underlying non-wrapper stream
stream = WrapperStream.GetNonWrapperBaseStream(stream);
// Retry is possible if stream is seekable
return stream.CanSeek;
}
return true;
}
/// <summary>
/// Returns true if the request can contain a request body, else false.
/// </summary>
/// <returns>Returns true if the currect request can contain a request body, else false.</returns>
public bool MayContainRequestBody()
{
return !this.UseQueryString &&
(this.HttpMethod == "POST" ||
this.HttpMethod == "PUT");
}
/// <summary>
/// Returns true if the request has a body, else false.
/// </summary>
/// <returns>Returns true if the request has a body, else false.</returns>
public bool HasRequestBody()
{
var isPutPost = (this.HttpMethod == "POST" || this.HttpMethod == "PUT");
var hasContent = this.HasRequestData();
return (isPutPost && hasContent);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace TestMySkills.WebAPI.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.Common;
using ReactNative.Tracing;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace ReactNative.Chakra.Executor
{
/// <summary>
/// JavaScript runtime wrapper.
/// </summary>
public sealed class ChakraJavaScriptExecutor : IJavaScriptExecutor
{
private const string MagicFileName = "UNBUNDLE";
private const uint MagicFileHeader = 0xFB0BD1E5;
private const string JsonName = "JSON";
private const string FBBatchedBridgeVariableName = "__fbBatchedBridge";
private readonly JavaScriptRuntime _runtime;
private IJavaScriptUnbundle _unbundle;
private JavaScriptSourceContext _context;
private JavaScriptNativeFunction _nativeLoggingHook;
private JavaScriptNativeFunction _nativeRequire;
private JavaScriptNativeFunction _nativeCallSyncHook;
private JavaScriptNativeFunction _nativeFlushQueueImmediate;
private JavaScriptValue _globalObject;
private JavaScriptValue _callFunctionAndReturnFlushedQueueFunction;
private JavaScriptValue _invokeCallbackAndReturnFlushedQueueFunction;
private JavaScriptValue _flushedQueueFunction;
private JavaScriptValue _fbBatchedBridge;
#if !NATIVE_JSON_MARSHALING
private JavaScriptValue _parseFunction;
private JavaScriptValue _stringifyFunction;
#endif
private Func<int, int, JArray, JToken> _callSyncHook;
private Action<JToken> _flushQueueImmediate;
/// <summary>
/// Callback for bundle modification from outside.
/// </summary>
private readonly Func<string, string> _modifyBundle;
/// <summary>
/// Instantiates the <see cref="ChakraJavaScriptExecutor"/>.
/// </summary>
/// <param name="modifyBundle">Callback for bundle modification from outside.</param>
public ChakraJavaScriptExecutor(Func<string, string> modifyBundle)
{
this._modifyBundle = modifyBundle;
_runtime = JavaScriptRuntime.Create();
_context = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);
InitializeChakra();
}
/// <summary>
/// Call the JavaScript method from the given module.
/// </summary>
/// <param name="moduleName">The module name.</param>
/// <param name="methodName">The method name.</param>
/// <param name="arguments">The arguments.</param>
/// <returns>The flushed queue of native operations.</returns>
public JToken CallFunctionReturnFlushedQueue(string moduleName, string methodName, JArray arguments)
{
if (moduleName == null)
throw new ArgumentNullException(nameof(moduleName));
if (methodName == null)
throw new ArgumentNullException(nameof(methodName));
if (arguments == null)
throw new ArgumentNullException(nameof(arguments));
var moduleNameValue = JavaScriptValue.FromString(moduleName);
moduleNameValue.AddRef();
var methodNameValue = JavaScriptValue.FromString(methodName);
methodNameValue.AddRef();
var argumentsValue = ConvertJson(arguments);
argumentsValue.AddRef();
var callArguments = new JavaScriptValue[4];
callArguments[0] = EnsureGlobalObject();
callArguments[1] = moduleNameValue;
callArguments[2] = methodNameValue;
callArguments[3] = argumentsValue;
var method = EnsureCallFunction();
var flushedQueue = ConvertJson(method.CallFunction(callArguments));
argumentsValue.Release();
methodNameValue.Release();
moduleNameValue.Release();
return flushedQueue;
}
/// <summary>
/// Flush the queue.
/// </summary>
/// <returns>The flushed queue of native operations.</returns>
public JToken FlushedQueue()
{
var method = EnsureFlushedQueueFunction();
var callArguments = new JavaScriptValue[1];
callArguments[0] = EnsureGlobalObject();
return ConvertJson(method.CallFunction(callArguments));
}
/// <summary>
/// Invoke the JavaScript callback.
/// </summary>
/// <param name="callbackId">The callback identifier.</param>
/// <param name="arguments">The arguments.</param>
/// <returns>The flushed queue of native operations.</returns>
public JToken InvokeCallbackAndReturnFlushedQueue(int callbackId, JArray arguments)
{
if (arguments == null)
throw new ArgumentNullException(nameof(arguments));
var callbackIdValue = JavaScriptValue.FromInt32(callbackId);
callbackIdValue.AddRef();
var argumentsValue = ConvertJson(arguments);
argumentsValue.AddRef();
var callArguments = new JavaScriptValue[3];
callArguments[0] = EnsureGlobalObject();
callArguments[1] = callbackIdValue;
callArguments[2] = argumentsValue;
var method = EnsureInvokeFunction();
var flushedQueue = ConvertJson(method.CallFunction(callArguments));
argumentsValue.Release();
callbackIdValue.Release();
return flushedQueue;
}
/// <summary>
/// Runs the script at the given path.
/// </summary>
/// <param name="sourcePath">The source path.</param>
/// <param name="sourceUrl">The source URL.</param>
public void RunScript(string sourcePath, string sourceUrl)
{
if (sourcePath == null)
throw new ArgumentNullException(nameof(sourcePath));
if (sourceUrl == null)
throw new ArgumentNullException(nameof(sourceUrl));
var startupCode = default(string);
if (IsUnbundle(sourcePath))
{
_unbundle = new FileBasedJavaScriptUnbundle(sourcePath);
InstallNativeRequire();
startupCode = _unbundle.GetStartupCode();
}
else if (IsIndexedUnbundle(sourcePath))
{
_unbundle = new IndexedJavaScriptUnbundle(sourcePath);
InstallNativeRequire();
startupCode = _unbundle.GetStartupCode();
}
else
{
startupCode = LoadScript(sourcePath);
try
{
if (this._modifyBundle != null)
{
//Modify bundle function returns modified bundle.
var updatedBundle = this._modifyBundle(startupCode);
startupCode = updatedBundle;
}
}
catch (Exception ex)
{
RnLog.Error("Native", ex, @"Exception during bundle modification.");
#if DEBUG
throw;
#endif
}
}
EvaluateScript(startupCode, sourceUrl);
}
/// <summary>
/// Sets a global variable in the JavaScript runtime.
/// </summary>
/// <param name="propertyName">The global variable name.</param>
/// <param name="value">The value.</param>
public void SetGlobalVariable(string propertyName, string value)
{
if (propertyName == null)
throw new ArgumentNullException(nameof(propertyName));
if (value == null)
throw new ArgumentNullException(nameof(value));
var javaScriptValue = ConvertJson(value);
var propertyId = JavaScriptPropertyId.FromString(propertyName);
EnsureGlobalObject().SetProperty(propertyId, javaScriptValue, true);
}
/// <summary>
/// Gets a global variable from the JavaScript runtime.
/// </summary>
/// <param name="propertyName">The global variable name.</param>
/// <returns>The value.</returns>
public JToken GetGlobalVariable(string propertyName)
{
if (propertyName == null)
throw new ArgumentNullException(nameof(propertyName));
var propertyId = JavaScriptPropertyId.FromString(propertyName);
return ConvertJson(EnsureGlobalObject().GetProperty(propertyId));
}
/// <summary>
/// Sets a callback for synchronous native methods.
/// </summary>
/// <param name="callSyncHook">The sync hook for native methods.</param>
public void SetCallSyncHook(Func<int, int, JArray, JToken> callSyncHook)
{
_callSyncHook = callSyncHook;
}
/// <summary>
/// Sets a callback for immediate queue flushes.
/// </summary>
/// <param name="flushQueueImmediate">The callback.</param>
public void SetFlushQueueImmediate(Action<JToken> flushQueueImmediate)
{
_flushQueueImmediate = flushQueueImmediate;
}
/// <summary>
/// Disposes the <see cref="ChakraJavaScriptExecutor"/> instance.
/// </summary>
public void Dispose()
{
JavaScriptContext.Current = JavaScriptContext.Invalid;
_runtime.Dispose();
_unbundle?.Dispose();
}
private void InitializeChakra()
{
JavaScriptContext.Current = _runtime.CreateContext();
_nativeLoggingHook = NativeLoggingHook;
EnsureGlobalObject().SetProperty(
JavaScriptPropertyId.FromString("nativeLoggingHook"),
JavaScriptValue.CreateFunction(_nativeLoggingHook),
true);
_nativeCallSyncHook = NativeCallSyncHook;
EnsureGlobalObject().SetProperty(
JavaScriptPropertyId.FromString("nativeCallSyncHook"),
JavaScriptValue.CreateFunction(_nativeCallSyncHook),
true);
_nativeFlushQueueImmediate = NativeFlushQueueImmediate;
EnsureGlobalObject().SetProperty(
JavaScriptPropertyId.FromString("nativeFlushQueueImmediate"),
JavaScriptValue.CreateFunction(_nativeFlushQueueImmediate),
true);
}
private void EvaluateScript(string script, string sourceUrl)
{
try
{
_context = JavaScriptSourceContext.Increment(_context);
JavaScriptContext.RunScript(script, _context, sourceUrl);
}
catch (JavaScriptScriptException ex)
{
var jsonError = JavaScriptValueToJTokenConverter.Convert(ex.Error);
var message = jsonError.Value<string>("message");
var stackTrace = jsonError.Value<string>("stack");
throw new Modules.Core.JavaScriptException(message ?? ex.Message, stackTrace, ex);
}
}
#region JSON Marshaling
#if NATIVE_JSON_MARSHALING
private JavaScriptValue ConvertJson(JToken token)
{
return JTokenToJavaScriptValueConverter.Convert(token);
}
private JToken ConvertJson(JavaScriptValue value)
{
return JavaScriptValueToJTokenConverter.Convert(value);
}
#else
private JavaScriptValue ConvertJson(JToken token)
{
var jsonString = token?.ToString(Formatting.None) ?? "null";
return ConvertJson(jsonString);
}
private JavaScriptValue ConvertJson(string jsonString)
{
var jsonStringValue = JavaScriptValue.FromString(jsonString);
jsonStringValue.AddRef();
var parseFunction = EnsureParseFunction();
var jsonValue = parseFunction.CallFunction(_globalObject, jsonStringValue);
jsonStringValue.Release();
return jsonValue;
}
private JToken ConvertJson(JavaScriptValue value)
{
var stringifyFunction = EnsureStringifyFunction();
var jsonStringValue = stringifyFunction.CallFunction(_globalObject, value);
jsonStringValue.AddRef();
var jsonString = jsonStringValue.ToString();
jsonStringValue.Release();
return JToken.Parse(jsonString);
}
#endif
#endregion
#region Console Callbacks
private JavaScriptValue NativeLoggingHook(
JavaScriptValue callee,
bool isConstructCall,
JavaScriptValue[] arguments,
ushort argumentCount,
IntPtr callbackData)
{
try
{
var message = arguments[1].ToString();
var logLevel = (LogLevel)(int)arguments[2].ToDouble();
RnLog.Info("JS", $"{logLevel} {message}");
}
catch
{
RnLog.Error("JS", $"Unable to process JavaScript console statement");
}
return JavaScriptValue.Undefined;
}
#endregion
#region Native Flush Queue Immediate Hook
private JavaScriptValue NativeFlushQueueImmediate(
JavaScriptValue callee,
bool isConstructCall,
JavaScriptValue[] arguments,
ushort argumentCount,
IntPtr callbackData)
{
if (argumentCount != 2)
{
throw new ArgumentOutOfRangeException(nameof(argumentCount), "Expected exactly two arguments (global, flushedQueue)");
}
if (_flushQueueImmediate == null)
{
throw new InvalidOperationException("Callback hook for `nativeFlushQueueImmediate` has not been set.");
}
_flushQueueImmediate(ConvertJson(arguments[1]));
return JavaScriptValue.Undefined;
}
#endregion
#region Native Call Sync Hook
private JavaScriptValue NativeCallSyncHook(
JavaScriptValue callee,
bool isConstructCall,
JavaScriptValue[] arguments,
ushort argumentCount,
IntPtr callbackData)
{
if (argumentCount != 4)
{
throw new ArgumentOutOfRangeException(nameof(argumentCount), "Expected exactly four arguments (global, moduleId, methodId, and args).");
}
if (_callSyncHook == null)
{
throw new InvalidOperationException("Sync hook has not been set.");
}
var moduleId = (int)arguments[1].ToDouble();
var methodId = (int)arguments[2].ToDouble();
var args = (JArray)ConvertJson(arguments[3]);
var result = _callSyncHook(moduleId, methodId, args);
return ConvertJson(result);
}
#endregion
#region Native Require
private void InstallNativeRequire()
{
_nativeRequire = NativeRequire;
EnsureGlobalObject().SetProperty(
JavaScriptPropertyId.FromString("nativeRequire"),
JavaScriptValue.CreateFunction(_nativeRequire),
true);
}
private JavaScriptValue NativeRequire(
JavaScriptValue callee,
bool isConstructCall,
JavaScriptValue[] arguments,
ushort argumentCount,
IntPtr callbackData)
{
if (argumentCount != 2)
{
throw new ArgumentOutOfRangeException(nameof(argumentCount), "Expected exactly two arguments (global and moduleId).");
}
var moduleId = arguments[1].ToDouble();
if (moduleId <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(arguments),
$"Received invalid module ID '{moduleId}'.");
}
var module = _unbundle.GetModule((int)moduleId);
EvaluateScript(module.Source, module.SourceUrl);
return JavaScriptValue.Invalid;
}
#endregion
#region Global Helpers
private JavaScriptValue EnsureGlobalObject()
{
if (!_globalObject.IsValid)
{
_globalObject = JavaScriptValue.GlobalObject;
}
return _globalObject;
}
private JavaScriptValue EnsureParseFunction()
{
if (!_parseFunction.IsValid)
{
var globalObject = EnsureGlobalObject();
var jsonObject = globalObject.GetProperty(JavaScriptPropertyId.FromString(JsonName));
_parseFunction = jsonObject.GetProperty(JavaScriptPropertyId.FromString("parse"));
}
return _parseFunction;
}
private JavaScriptValue EnsureBatchedBridge()
{
if (!_fbBatchedBridge.IsValid)
{
var globalObject = EnsureGlobalObject();
var propertyId = JavaScriptPropertyId.FromString(FBBatchedBridgeVariableName);
var fbBatchedBridge = globalObject.GetProperty(propertyId);
if (fbBatchedBridge.ValueType != JavaScriptValueType.Object)
{
throw new InvalidOperationException($"Could not resolve '{FBBatchedBridgeVariableName}' object. Check the JavaScript bundle to ensure it is generated correctly.");
}
_fbBatchedBridge = fbBatchedBridge;
}
return _fbBatchedBridge;
}
private JavaScriptValue EnsureStringifyFunction()
{
if (!_stringifyFunction.IsValid)
{
var globalObject = EnsureGlobalObject();
var jsonObject = globalObject.GetProperty(JavaScriptPropertyId.FromString(JsonName));
_stringifyFunction = jsonObject.GetProperty(JavaScriptPropertyId.FromString("stringify"));
}
return _stringifyFunction;
}
private JavaScriptValue EnsureCallFunction()
{
if (!_callFunctionAndReturnFlushedQueueFunction.IsValid)
{
var fbBatchedBridge = EnsureBatchedBridge();
var functionPropertyId = JavaScriptPropertyId.FromString("callFunctionReturnFlushedQueue");
_callFunctionAndReturnFlushedQueueFunction = fbBatchedBridge.GetProperty(functionPropertyId);
}
return _callFunctionAndReturnFlushedQueueFunction;
}
private JavaScriptValue EnsureInvokeFunction()
{
if (!_invokeCallbackAndReturnFlushedQueueFunction.IsValid)
{
var fbBatchedBridge = EnsureBatchedBridge();
var functionPropertyId = JavaScriptPropertyId.FromString("invokeCallbackAndReturnFlushedQueue");
_invokeCallbackAndReturnFlushedQueueFunction = fbBatchedBridge.GetProperty(functionPropertyId);
}
return _invokeCallbackAndReturnFlushedQueueFunction;
}
private JavaScriptValue EnsureFlushedQueueFunction()
{
if (!_flushedQueueFunction.IsValid)
{
var fbBatchedBridge = EnsureBatchedBridge();
var functionPropertyId = JavaScriptPropertyId.FromString("flushedQueue");
_flushedQueueFunction = fbBatchedBridge.GetProperty(functionPropertyId);
}
return _flushedQueueFunction;
}
#endregion
#region File IO
private static string LoadScript(string fileName)
{
try
{
return File.ReadAllText(fileName);
}
catch (Exception ex)
{
var exceptionMessage = $"File read exception for asset '{fileName}'.";
throw new InvalidOperationException(exceptionMessage, ex);
}
}
#endregion
#region Unbundle
class JavaScriptUnbundleModule
{
public JavaScriptUnbundleModule(string source, string sourceUrl)
{
SourceUrl = sourceUrl;
Source = source;
}
public string SourceUrl { get; }
public string Source { get; }
}
interface IJavaScriptUnbundle : IDisposable
{
JavaScriptUnbundleModule GetModule(int index);
string GetStartupCode();
}
class FileBasedJavaScriptUnbundle : IJavaScriptUnbundle
{
private readonly string _sourcePath;
private readonly string _modulesPath;
public FileBasedJavaScriptUnbundle(string sourcePath)
{
_sourcePath = sourcePath;
_modulesPath = GetUnbundleModulesDirectory(sourcePath);
}
public JavaScriptUnbundleModule GetModule(int index)
{
var sourceUrl = index + ".js";
var fileName = Path.Combine(_modulesPath, sourceUrl);
var source = LoadScript(fileName);
return new JavaScriptUnbundleModule(source, sourceUrl);
}
public string GetStartupCode()
{
return LoadScript(_sourcePath);
}
public void Dispose()
{
}
}
class IndexedJavaScriptUnbundle : IJavaScriptUnbundle
{
private const int HeaderSize = 12;
private readonly string _sourcePath;
private Stream _stream;
private byte[] _moduleTable;
private int _baseOffset;
public IndexedJavaScriptUnbundle(string sourcePath)
{
_sourcePath = sourcePath;
}
public JavaScriptUnbundleModule GetModule(int index)
{
var offset = InetHelpers.LittleEndianToHost(BitConverter.ToUInt32(_moduleTable, index * 8));
var length = InetHelpers.LittleEndianToHost(BitConverter.ToUInt32(_moduleTable, index * 8 + 4));
_stream.Seek(_baseOffset + offset, SeekOrigin.Begin);
var moduleData = new byte[length];
if (_stream.Read(moduleData, 0, (int) length) < length)
{
throw new InvalidOperationException("Reached end of file before end of unbundle module.");
}
var source = Encoding.UTF8.GetString(moduleData);
var sourceUrl = index + ".js";
return new JavaScriptUnbundleModule(source, sourceUrl);
}
public string GetStartupCode()
{
_stream = File.OpenRead(_sourcePath);
var header = new byte[HeaderSize];
if (_stream.Read(header, 0, HeaderSize) < HeaderSize)
{
throw new InvalidOperationException("Reached end of file before end of indexed unbundle header.");
}
var numberOfTableEntries = InetHelpers.LittleEndianToHost(BitConverter.ToUInt32(header, 4));
var startupCodeSize = InetHelpers.LittleEndianToHost(BitConverter.ToUInt32(header, 8));
var moduleTableSize = numberOfTableEntries * 8 /* bytes per entry */;
_baseOffset = HeaderSize + (int)moduleTableSize;
_moduleTable = new byte[moduleTableSize];
if (_stream.Read(_moduleTable, 0, (int)moduleTableSize) < moduleTableSize)
{
throw new InvalidOperationException("Reached end of file before end of indexed unbundle module table.");
}
var startupCodeBuffer = new byte[startupCodeSize];
if (_stream.Read(startupCodeBuffer, 0, (int)startupCodeSize) < startupCodeSize)
{
throw new InvalidOperationException("Reached end of file before end of startup code.");
}
return Encoding.UTF8.GetString(startupCodeBuffer);
}
public void Dispose()
{
_stream.Dispose();
}
}
private static bool IsUnbundle(string sourcePath)
{
var magicFilePath = Path.Combine(GetUnbundleModulesDirectory(sourcePath), MagicFileName);
if (!File.Exists(magicFilePath))
{
return false;
}
using (var stream = File.OpenRead(magicFilePath))
{
var header = new byte[4];
var read = stream.Read(header, 0, 4);
if (read < 4)
{
return false;
}
var magicHeader = BitConverter.ToUInt32(header, 0);
return InetHelpers.LittleEndianToHost(magicHeader) == MagicFileHeader;
}
}
private static bool IsIndexedUnbundle(string sourcePath)
{
using (var stream = File.OpenRead(sourcePath))
{
var header = new byte[4];
var read = stream.Read(header, 0, 4);
if (read < 4)
{
return false;
}
var magic = InetHelpers.LittleEndianToHost(BitConverter.ToUInt32(header, 0));
return magic == MagicFileHeader;
}
}
private static string GetUnbundleModulesDirectory(string sourcePath)
{
return Path.Combine(Path.GetDirectoryName(sourcePath), "js-modules");
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace BrokenShoeLeague.Web.API.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
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 AprMotivoVisitaDomiciliarium class.
/// </summary>
[Serializable]
public partial class AprMotivoVisitaDomiciliariumCollection : ActiveList<AprMotivoVisitaDomiciliarium, AprMotivoVisitaDomiciliariumCollection>
{
public AprMotivoVisitaDomiciliariumCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>AprMotivoVisitaDomiciliariumCollection</returns>
public AprMotivoVisitaDomiciliariumCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
AprMotivoVisitaDomiciliarium 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 APR_MotivoVisitaDomiciliaria table.
/// </summary>
[Serializable]
public partial class AprMotivoVisitaDomiciliarium : ActiveRecord<AprMotivoVisitaDomiciliarium>, IActiveRecord
{
#region .ctors and Default Settings
public AprMotivoVisitaDomiciliarium()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public AprMotivoVisitaDomiciliarium(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public AprMotivoVisitaDomiciliarium(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public AprMotivoVisitaDomiciliarium(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("APR_MotivoVisitaDomiciliaria", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdMotivoVisitaDomiciliaria = new TableSchema.TableColumn(schema);
colvarIdMotivoVisitaDomiciliaria.ColumnName = "idMotivoVisitaDomiciliaria";
colvarIdMotivoVisitaDomiciliaria.DataType = DbType.Int32;
colvarIdMotivoVisitaDomiciliaria.MaxLength = 0;
colvarIdMotivoVisitaDomiciliaria.AutoIncrement = true;
colvarIdMotivoVisitaDomiciliaria.IsNullable = false;
colvarIdMotivoVisitaDomiciliaria.IsPrimaryKey = true;
colvarIdMotivoVisitaDomiciliaria.IsForeignKey = false;
colvarIdMotivoVisitaDomiciliaria.IsReadOnly = false;
colvarIdMotivoVisitaDomiciliaria.DefaultSetting = @"";
colvarIdMotivoVisitaDomiciliaria.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdMotivoVisitaDomiciliaria);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = 50;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema);
colvarCreatedBy.ColumnName = "CreatedBy";
colvarCreatedBy.DataType = DbType.AnsiString;
colvarCreatedBy.MaxLength = 50;
colvarCreatedBy.AutoIncrement = false;
colvarCreatedBy.IsNullable = true;
colvarCreatedBy.IsPrimaryKey = false;
colvarCreatedBy.IsForeignKey = false;
colvarCreatedBy.IsReadOnly = false;
colvarCreatedBy.DefaultSetting = @"";
colvarCreatedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedBy);
TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema);
colvarCreatedOn.ColumnName = "CreatedOn";
colvarCreatedOn.DataType = DbType.DateTime;
colvarCreatedOn.MaxLength = 0;
colvarCreatedOn.AutoIncrement = false;
colvarCreatedOn.IsNullable = true;
colvarCreatedOn.IsPrimaryKey = false;
colvarCreatedOn.IsForeignKey = false;
colvarCreatedOn.IsReadOnly = false;
colvarCreatedOn.DefaultSetting = @"";
colvarCreatedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedOn);
TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema);
colvarModifiedBy.ColumnName = "ModifiedBy";
colvarModifiedBy.DataType = DbType.AnsiString;
colvarModifiedBy.MaxLength = 50;
colvarModifiedBy.AutoIncrement = false;
colvarModifiedBy.IsNullable = true;
colvarModifiedBy.IsPrimaryKey = false;
colvarModifiedBy.IsForeignKey = false;
colvarModifiedBy.IsReadOnly = false;
colvarModifiedBy.DefaultSetting = @"";
colvarModifiedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedBy);
TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema);
colvarModifiedOn.ColumnName = "ModifiedOn";
colvarModifiedOn.DataType = DbType.DateTime;
colvarModifiedOn.MaxLength = 0;
colvarModifiedOn.AutoIncrement = false;
colvarModifiedOn.IsNullable = true;
colvarModifiedOn.IsPrimaryKey = false;
colvarModifiedOn.IsForeignKey = false;
colvarModifiedOn.IsReadOnly = false;
colvarModifiedOn.DefaultSetting = @"";
colvarModifiedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedOn);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("APR_MotivoVisitaDomiciliaria",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdMotivoVisitaDomiciliaria")]
[Bindable(true)]
public int IdMotivoVisitaDomiciliaria
{
get { return GetColumnValue<int>(Columns.IdMotivoVisitaDomiciliaria); }
set { SetColumnValue(Columns.IdMotivoVisitaDomiciliaria, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("CreatedBy")]
[Bindable(true)]
public string CreatedBy
{
get { return GetColumnValue<string>(Columns.CreatedBy); }
set { SetColumnValue(Columns.CreatedBy, value); }
}
[XmlAttribute("CreatedOn")]
[Bindable(true)]
public DateTime? CreatedOn
{
get { return GetColumnValue<DateTime?>(Columns.CreatedOn); }
set { SetColumnValue(Columns.CreatedOn, value); }
}
[XmlAttribute("ModifiedBy")]
[Bindable(true)]
public string ModifiedBy
{
get { return GetColumnValue<string>(Columns.ModifiedBy); }
set { SetColumnValue(Columns.ModifiedBy, value); }
}
[XmlAttribute("ModifiedOn")]
[Bindable(true)]
public DateTime? ModifiedOn
{
get { return GetColumnValue<DateTime?>(Columns.ModifiedOn); }
set { SetColumnValue(Columns.ModifiedOn, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.AprVisitaDomiciliariumCollection colAprVisitaDomiciliaria;
public DalSic.AprVisitaDomiciliariumCollection AprVisitaDomiciliaria
{
get
{
if(colAprVisitaDomiciliaria == null)
{
colAprVisitaDomiciliaria = new DalSic.AprVisitaDomiciliariumCollection().Where(AprVisitaDomiciliarium.Columns.IdMotivoVisitaDomiciliaria, IdMotivoVisitaDomiciliaria).Load();
colAprVisitaDomiciliaria.ListChanged += new ListChangedEventHandler(colAprVisitaDomiciliaria_ListChanged);
}
return colAprVisitaDomiciliaria;
}
set
{
colAprVisitaDomiciliaria = value;
colAprVisitaDomiciliaria.ListChanged += new ListChangedEventHandler(colAprVisitaDomiciliaria_ListChanged);
}
}
void colAprVisitaDomiciliaria_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colAprVisitaDomiciliaria[e.NewIndex].IdMotivoVisitaDomiciliaria = IdMotivoVisitaDomiciliaria;
}
}
#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,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn)
{
AprMotivoVisitaDomiciliarium item = new AprMotivoVisitaDomiciliarium();
item.Nombre = varNombre;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
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 varIdMotivoVisitaDomiciliaria,string varNombre,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn)
{
AprMotivoVisitaDomiciliarium item = new AprMotivoVisitaDomiciliarium();
item.IdMotivoVisitaDomiciliaria = varIdMotivoVisitaDomiciliaria;
item.Nombre = varNombre;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
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 IdMotivoVisitaDomiciliariaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn CreatedByColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn CreatedOnColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn ModifiedByColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn ModifiedOnColumn
{
get { return Schema.Columns[5]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdMotivoVisitaDomiciliaria = @"idMotivoVisitaDomiciliaria";
public static string Nombre = @"nombre";
public static string CreatedBy = @"CreatedBy";
public static string CreatedOn = @"CreatedOn";
public static string ModifiedBy = @"ModifiedBy";
public static string ModifiedOn = @"ModifiedOn";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colAprVisitaDomiciliaria != null)
{
foreach (DalSic.AprVisitaDomiciliarium item in colAprVisitaDomiciliaria)
{
if (item.IdMotivoVisitaDomiciliaria != IdMotivoVisitaDomiciliaria)
{
item.IdMotivoVisitaDomiciliaria = IdMotivoVisitaDomiciliaria;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colAprVisitaDomiciliaria != null)
{
colAprVisitaDomiciliaria.SaveAll();
}
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.IO;
namespace OpenLiveWriter.FileDestinations
{
/// <summary>
/// Summary description for FileSystemDestination.
/// </summary>
public class FileSystemDestination : FileDestination
{
/// <summary>
/// FileSystemDestination Constructor
/// </summary>
/// <param name="path">The path to the destination.</param>
public FileSystemDestination( string path)
: base( path, 5, 1000)
{
if(!Directory.Exists(path))
{
throw new NoSuchDirectoryException(path);
}
}
/// <summary>
/// FileSystemDestination Constructor
/// </summary>
/// <param name="path">The path to the destination.</param>
/// <param name="retryCount">The number of times to retry the file copy</param>
/// <param name="retryPause">The length of time in milliseconds to pause between retries</param>
public FileSystemDestination( string path, int retryCount, int retryPause)
: base( path, retryCount, retryPause)
{
if(!Directory.Exists(path))
{
throw new NoSuchDirectoryException(path);
}
}
/// <summary>
/// Copies files to a local destination
/// </summary>
/// <param name="fromPath">The path from which to copy files (relative to basePath)</param>
/// <param name="toPath">The path to which to copy files (relative to basePath)</param>
/// <param name="overwrite">Whether or not to overwrite existing files</param>
/// <returns>True indicates success, False indicates non fatal error</returns>
public override bool CopyFile(string fromPath, string toPath, bool overwrite)
{
fromPath = Path.Combine(m_path, fromPath);
toPath = Path.Combine(m_path, toPath);
try
{
// Delete existing file if we're supposed to overwrite
if (overwrite && File.Exists(toPath))
File.Delete(toPath);
// Move the file
File.Copy(fromPath, toPath);
return true;
}
catch (Exception e)
{
if (RetryOnException(e))
return false;
else
{
SiteDestinationException ex = new SiteDestinationException(e, SiteDestinationException.TransferException, GetType().Name, 0);
ex.DestinationExtendedMessage = e.Message;
throw ex;
}
}
}
/// <summary>
/// Retrieves a file from the destination and copies it to the specified path.
/// </summary>
/// <param name="fromPath">the file to retrieve from the destination (relative to basePath)</param>
/// <param name="toPath">the local location to save the contents of the file (fully-qualifed path)</param>
/// <param name="isBinary">true if the file is binary</param>
override public bool GetFile(String fromPath, string toPath, bool isBinary)
{
fromPath = Path.Combine(m_path, fromPath);
FileInfo fromFile = new FileInfo(fromPath);
FileInfo toFile = new FileInfo(fromPath);
if(fromFile.Equals(toFile))
{
//then the source is the same as the destination, so ignore
return true;
}
try
{
// Delete existing file
if (File.Exists(toPath))
File.Delete(toPath);
// Copy the file
File.Copy(fromPath, toPath);
return true;
}
catch (Exception e)
{
if (RetryOnException(e))
return false;
else
{
SiteDestinationException ex = new SiteDestinationException(e, SiteDestinationException.TransferException, GetType().Name, 0);
ex.DestinationExtendedMessage = e.Message;
throw ex;
}
}
}
/// <summary>
/// Determines whether file transfer operations should retry
/// given an exception.
/// </summary>
/// <param name="e">The exception that has occurred</param>
/// <returns>True indicates to retry operation, otherwise false</returns>
public virtual bool RetryOnException(Exception e)
{
return false;
}
/// <summary>
/// This method is called to determine whether a directory exists. This is used to
/// determine whether to create a new directory or not.
/// </summary>
/// <param name="path">The directory</param>
/// <returns>true indicates the directory exists, false indicates it doesn't</returns>
public override bool DirectoryExists(string path)
{
return Directory.Exists(Path.Combine(m_path, path));
}
/// <summary>
/// This method is called to determine whether a file exists.
/// </summary>
/// <param name="Path">The file</param>
/// <returns>true indicates the file exists, false indicates it doesn't</returns>
override public bool FileExists(string path)
{
return File.Exists(Path.Combine(m_path, path));
}
/// <summary>
/// Deletes a file from the filesysytem.
/// </summary>
/// <param name="path">The file</param>
public override void DeleteFile(string path)
{
File.Delete(Path.Combine(m_path, path));
}
/// <summary>
/// Creates a local directory
/// </summary>
/// <param name="path">The path of the directory to create (typically
/// relative to the current directory)</param>
/// <returns>true indicates success, otherwise false</returns>
public override void CreateDirectory (string path)
{
Directory.CreateDirectory(Path.Combine(m_path, path));
}
public override string[] ListDirectories(string path)
{
path = Path.Combine(m_path, path);
string[] dirs = Directory.GetDirectories(path);
//trim off the parental path information so that only the file name is returned.
for(int i=0; i<dirs.Length; i++)
{
string directory = dirs[i];
dirs[i] = directory.Substring(directory.LastIndexOf(@"\", StringComparison.OrdinalIgnoreCase)+1);
}
return dirs;
}
/// <summary>
/// List the names of the files in the specified directory.
/// </summary>
/// <param name="path">the directory path</param>
/// <returns></returns>
public override string[] ListFiles(string path)
{
path = Path.Combine(m_path, path);
string[] files = Directory.GetFiles(path);
//trim off the parental path information so that only the file name is returned.
for(int i=0; i<files.Length; i++)
{
string file = files[i];
files[i] = file.Substring(file.LastIndexOf(@"\", StringComparison.OrdinalIgnoreCase)+1);
}
return files;
}
}
}
| |
// Copyright (c) 2017-2018 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
using SIL.PlatformUtilities;
using SIL.Reporting;
namespace SIL.IO
{
/// <summary>
/// Desktop-specific utility methods for processing directories, e.g. methods that report to the user.
/// </summary>
public static class DirectoryUtilities
{
/// <summary>
/// Makes a full copy of the specified directory in the system's temporary directory.
/// If the copy fails at any point in the process, the user is notified of the
/// problem and an attempt is made to remove the destination directory if the failure
/// happened part way through the process.
/// </summary>
/// <param name="srcDirectory">Directory to copy</param>
/// <returns>Null if the copy was unsuccessful, otherwise the path to the copied directory</returns>
public static string CopyDirectoryToTempDirectory(string srcDirectory)
{
string dstDirectory;
return (CopyDirectory(srcDirectory, Path.GetTempPath(), out dstDirectory) ? dstDirectory : null);
}
/// <summary>
/// Makes a copy of the specifed source directory and its contents in the specified
/// destination directory. The copy has the same directory name as the source, but ends up
/// as a sub directory of the specified destination directory. The destination directory must
/// already exist. If the copy fails at any point in the process, the user is notified
/// of the problem and an attempt is made to remove the destination directory if the
/// failure happened part way through the process.
/// </summary>
/// <param name="srcDirectory">Directory being copied</param>
/// <param name="dstDirectoryParent">Destination directory where source directory and its contents are copied</param>
/// <returns>true if successful, otherwise, false.</returns>
public static bool CopyDirectory(string srcDirectory, string dstDirectoryParent)
{
string dstDirectory;
return CopyDirectory(srcDirectory, dstDirectoryParent, out dstDirectory);
}
private static bool CopyDirectory(string srcDirectory, string dstDirectoryParent, out string dstDirectory)
{
dstDirectory = Path.Combine(dstDirectoryParent, Path.GetFileName(srcDirectory));
if (!Directory.Exists(dstDirectoryParent))
{
ErrorReport.NotifyUserOfProblem(new DirectoryNotFoundException(dstDirectoryParent + " not found."),
"{0} was unable to copy the directory {1} to {2}", EntryAssembly.ProductName, srcDirectory, dstDirectoryParent);
return false;
}
if (DirectoryHelper.AreEquivalent(srcDirectory, dstDirectory))
{
ErrorReport.NotifyUserOfProblem(new Exception("Cannot copy directory to itself."),
"{0} was unable to copy the directory {1} to {2}", EntryAssembly.ProductName, srcDirectory, dstDirectoryParent);
return false;
}
return CopyDirectoryContents(srcDirectory, dstDirectory);
}
/// <summary>
/// Copies the specified source directory's contents to the specified destination directory.
/// If the destination directory does not exist, it will be created first. If the source
/// directory contains sub directories, those and their content will also be copied. If the
/// copy fails at any point in the process, the user is notified of the problem and
/// an attempt is made to remove the destination directory if the failure happened part
/// way through the process.
/// </summary>
/// <param name="sourcePath">Directory whose contents will be copied</param>
/// <param name="destinationPath">Destination directory receiving the content of the source directory</param>
/// <returns>true if successful, otherwise, false.</returns>
public static bool CopyDirectoryContents(string sourcePath, string destinationPath)
{
try
{
DirectoryHelper.Copy(sourcePath,destinationPath);
}
catch (Exception e)
{
//Review: generally, it's better if Palaso doesn't undertake to make these kind of UI decisions.
//I've extracted CopyDirectoryWithException, so as not to mess up whatever client is using this version
ReportFailedCopyAndCleanUp(e, sourcePath, destinationPath);
return false;
}
return true;
}
private static void ReportFailedCopyAndCleanUp(Exception error, string srcDirectory, string dstDirectory)
{
ErrorReport.NotifyUserOfProblem(error, "{0} was unable to copy the directory {1} to {2}",
EntryAssembly.ProductName, srcDirectory, dstDirectory);
try
{
if (!Directory.Exists(dstDirectory))
return;
// Clean up by removing the partially copied directory.
Directory.Delete(dstDirectory, true);
}
catch { }
}
/// <summary>
/// Sets the permissions for this directory so that everyone has full control
/// </summary>
/// <param name="fullDirectoryPath"></param>
/// <param name="showErrorMessage"></param>
/// <returns>True if able to set access, False otherwise</returns>
public static bool SetFullControl(string fullDirectoryPath, bool showErrorMessage = true)
{
if (!Platform.IsWindows)
return false;
// get current settings
var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
var security = Directory.GetAccessControl(fullDirectoryPath, AccessControlSections.Access);
var currentRules = security.GetAccessRules(true, true, typeof(SecurityIdentifier));
// if everyone already has full control, return now
if (currentRules.Cast<FileSystemAccessRule>()
.Where(rule => rule.IdentityReference.Value == everyone.Value)
.Any(rule => rule.FileSystemRights == FileSystemRights.FullControl))
{
return true;
}
// initialize
var returnVal = false;
try
{
// set the permissions so everyone can read and write to this directory
var fullControl = new FileSystemAccessRule(everyone,
FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow);
security.AddAccessRule(fullControl);
Directory.SetAccessControl(fullDirectoryPath, security);
returnVal = true;
}
catch (Exception ex)
{
if (showErrorMessage)
{
ErrorReport.NotifyUserOfProblem(ex, "{0} was not able to set directory security for '{1}' to 'full control' for everyone.",
EntryAssembly.ProductName, fullDirectoryPath);
}
}
return returnVal;
}
[Obsolete("Use DirectoryHelper.Copy()")]
public static void CopyDirectoryWithException(string sourcePath, string destinationPath, bool overwrite = false)
{
DirectoryHelper.Copy(sourcePath, destinationPath, overwrite);
}
[Obsolete("Use DirectoryHelper.AreEquivalent()")]
public static bool AreDirectoriesEquivalent(string dir1, string dir2)
{
return DirectoryHelper.AreEquivalent(dir1, dir2);
}
[Obsolete("Use DirectoryHelper.AreEquivalent()")]
public static bool AreDirectoriesEquivalent(DirectoryInfo dirInfo1, DirectoryInfo dirInfo2)
{
return DirectoryHelper.AreEquivalent(dirInfo1, dirInfo2);
}
/// <summary>
/// Move <paramref name="sourcePath"/> to <paramref name="destinationPath"/>. If src
/// and dest are on different partitions (e.g., temp and documents are on different
/// drives) then this method will do a copy followed by a delete. This is in contrast
/// to Directory.Move which fails if src and dest are on different partitions.
/// </summary>
/// <param name="sourcePath">The source directory or file, similar to Directory.Move</param>
/// <param name="destinationPath">The destination directory or file. If <paramref name="sourcePath"/>
/// is a file then <paramref name="destinationPath"/> also needs to be a file.</param>
[Obsolete("Use DirectoryHelper.Move()")]
public static void MoveDirectorySafely(string sourcePath, string destinationPath)
{
DirectoryHelper.Move(sourcePath, destinationPath);
}
/// <summary>
/// Return subdirectories of <paramref name="path"/> that are not system or hidden.
/// There are some cases where our call to Directory.GetDirectories() throws.
/// For example, when the access permissions on a folder are set so that it can't be read.
/// Another possible example may be Windows Backup files, which apparently look like directories.
/// </summary>
/// <param name="path">Directory path to look in.</param>
/// <returns>Zero or more directory names that are not system or hidden.</returns>
/// <exception cref="System.UnauthorizedAccessException">E.g. when the user does not have
/// read permission.</exception>
[Obsolete("Use DirectoryHelper.GetSafeDirectories()")]
public static string[] GetSafeDirectories(string path)
{
return DirectoryHelper.GetSafeDirectories(path);
}
/// <summary>
/// There are various things which can prevent a simple directory deletion, mostly timing related things which are hard to debug.
/// This method uses all the tricks to do its best.
/// </summary>
/// <returns>returns true if the directory is fully deleted</returns>
[Obsolete("Use RobustIO.DeleteDirectoryAndContents()")]
public static bool DeleteDirectoryRobust(string path, bool overrideReadOnly = true)
{
return RobustIO.DeleteDirectoryAndContents(path, overrideReadOnly);
}
/// <summary>
/// If necessary, append a number to make the folder path unique.
/// </summary>
/// <param name="folderPath">Source folder pathname.</param>
/// <returns>A unique folder pathname at the same level as <paramref name="folderPath"/>. It may have a number apended to <paramref name="folderPath"/>, or it may be <paramref name="folderPath"/>.</returns>
[Obsolete("Use PathHelper.GetUniqueFolderPath()")]
public static string GetUniqueFolderPath(string folderPath)
{
return PathHelper.GetUniqueFolderPath(folderPath);
}
/// <summary>
/// Checks if there are any entries in a directory
/// </summary>
/// <param name="path">Path to the directory to check</param>
/// <param name="onlyCheckForFiles">if this is TRUE, a directory that contains subdirectories but no files will be considered empty.
/// Subdirectories are not checked, so if onlyCheckForFiles is TRUE and there is a subdirectory that contains a file, the directory
/// will still be considered empty.</param>
/// <returns></returns>
[Obsolete("Use DirectoryHelper.IsEmpty()")]
public static bool DirectoryIsEmpty(string path, bool onlyCheckForFiles = false)
{
return DirectoryHelper.IsEmpty(path, onlyCheckForFiles);
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using StructureMap;
using System.Text;
namespace Sep.Git.Tfs.Core
{
public class GitHelpers : IGitHelpers
{
protected readonly TextWriter realStdout;
private readonly IContainer _container;
/// <summary>
/// Starting with version 1.7.10, Git uses UTF-8.
/// Use this encoding for Git input and output.
/// </summary>
private static Encoding _encoding = new UTF8Encoding(false, true);
public GitHelpers(TextWriter stdout, IContainer container)
{
realStdout = stdout;
_container = container;
}
/// <summary>
/// Runs the given git command, and returns the contents of its STDOUT.
/// </summary>
public string Command(params string[] command)
{
string retVal = null;
CommandOutputPipe(stdout => retVal = stdout.ReadToEnd(), command);
return retVal;
}
/// <summary>
/// Runs the given git command, and returns the first line of its STDOUT.
/// </summary>
public string CommandOneline(params string[] command)
{
string retVal = null;
CommandOutputPipe(stdout => retVal = stdout.ReadLine(), command);
return retVal;
}
/// <summary>
/// Runs the given git command, and passes STDOUT through to the current process's STDOUT.
/// </summary>
public void CommandNoisy(params string[] command)
{
CommandOutputPipe(stdout => realStdout.Write(stdout.ReadToEnd()), command);
}
/// <summary>
/// Runs the given git command, and redirects STDOUT to the provided action.
/// </summary>
public void CommandOutputPipe(Action<TextReader> handleOutput, params string[] command)
{
Time(command, () =>
{
AssertValidCommand(command);
var process = Start(command, RedirectStdout);
handleOutput(process.StandardOutput);
Close(process);
});
}
/// <summary>
/// Runs the given git command, and returns a reader for STDOUT. NOTE: The returned value MUST be disposed!
/// </summary>
public TextReader CommandOutputPipe(params string[] command)
{
AssertValidCommand(command);
var process = Start(command, RedirectStdout);
return new ProcessStdoutReader(this, process);
}
class ProcessStdoutReader : TextReader
{
private readonly GitProcess process;
private readonly GitHelpers helper;
public ProcessStdoutReader(GitHelpers helper, GitProcess process)
{
this.helper = helper;
this.process = process;
}
public override void Close()
{
helper.Close(process);
}
public override System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
{
return process.StandardOutput.CreateObjRef(requestedType);
}
protected override void Dispose(bool disposing)
{
if(disposing && process != null)
{
Close();
}
base.Dispose(disposing);
}
public override bool Equals(object obj)
{
return process.StandardOutput.Equals(obj);
}
public override int GetHashCode()
{
return process.StandardOutput.GetHashCode();
}
public override object InitializeLifetimeService()
{
return process.StandardOutput.InitializeLifetimeService();
}
public override int Peek()
{
return process.StandardOutput.Peek();
}
public override int Read()
{
return process.StandardOutput.Read();
}
public override int Read(char[] buffer, int index, int count)
{
return process.StandardOutput.Read(buffer, index, count);
}
public override int ReadBlock(char[] buffer, int index, int count)
{
return process.StandardOutput.ReadBlock(buffer, index, count);
}
public override string ReadLine()
{
return process.StandardOutput.ReadLine();
}
public override string ReadToEnd()
{
return process.StandardOutput.ReadToEnd();
}
public override string ToString()
{
return process.StandardOutput.ToString();
}
}
public void CommandInputPipe(Action<TextWriter> action, params string[] command)
{
Time(command, () =>
{
AssertValidCommand(command);
var process = Start(command, RedirectStdin);
action(process.StandardInput.WithEncoding(_encoding));
Close(process);
});
}
public void CommandInputOutputPipe(Action<TextWriter, TextReader> interact, params string[] command)
{
Time(command, () =>
{
AssertValidCommand(command);
var process = Start(command, Ext.And<ProcessStartInfo>(RedirectStdin, RedirectStdout));
interact(process.StandardInput.WithEncoding(_encoding), process.StandardOutput);
Close(process);
});
}
private void Time(string[] command, Action action)
{
var start = DateTime.Now;
try
{
action();
}
finally
{
var end = DateTime.Now;
Trace.WriteLine(String.Format("[{0}] {1}", end - start, String.Join(" ", command)), "git command time");
}
}
private void Close(GitProcess process)
{
// if caller doesn't read entire stdout to the EOF - it is possible that
// child process will hang waiting until there will be free space in stdout
// buffer to write the rest of the output.
// See https://github.com/git-tfs/git-tfs/issues/121 for details.
if (process.StartInfo.RedirectStandardOutput)
{
process.StandardOutput.BaseStream.CopyTo(Stream.Null);
process.StandardOutput.Close();
}
if (!process.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds))
throw new GitCommandException("Command did not terminate.", process);
if(process.ExitCode != 0)
throw new GitCommandException(string.Format("Command exited with error code: {0}\n{1}", process.ExitCode, process.StandardErrorString), process);
}
private void RedirectStdout(ProcessStartInfo startInfo)
{
startInfo.RedirectStandardOutput = true;
startInfo.StandardOutputEncoding = _encoding;
}
private void RedirectStderr(ProcessStartInfo startInfo)
{
startInfo.RedirectStandardError= true;
startInfo.StandardErrorEncoding = _encoding;
}
private void RedirectStdin(ProcessStartInfo startInfo)
{
startInfo.RedirectStandardInput = true;
// there is no StandardInputEncoding property, use extension method StreamWriter.WithEncoding instead
}
private GitProcess Start(string[] command)
{
return Start(command, x => {});
}
protected virtual GitProcess Start(string [] command, Action<ProcessStartInfo> initialize)
{
var startInfo = new ProcessStartInfo();
startInfo.FileName = "git";
startInfo.SetArguments(command);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.EnvironmentVariables.Add("GIT_PAGER", "cat");
RedirectStderr(startInfo);
initialize(startInfo);
Trace.WriteLine("Starting process: " + startInfo.FileName + " " + startInfo.Arguments, "git command");
var process = new GitProcess(Process.Start(startInfo));
process.ConsumeStandardError();
return process;
}
/// <summary>
/// WrapGitCommandErrors the actions, and if there are any git exceptions, rethrow a new exception with the given message.
/// </summary>
/// <param name="exceptionMessage">A friendlier message to wrap the GitCommandException with. {0} is replaced with the command line and {1} is replaced with the exit code.</param>
/// <param name="action"></param>
public void WrapGitCommandErrors(string exceptionMessage, Action action)
{
try
{
action();
}
catch (GitCommandException e)
{
throw new Exception(String.Format(exceptionMessage, e.Process.StartInfo.FileName + " " + e.Process.StartInfo.Arguments, e.Process.ExitCode), e);
}
}
public IGitRepository MakeRepository(string dir)
{
return _container
.With("gitDir").EqualTo(dir)
.GetInstance<IGitRepository>();
}
private static readonly Regex ValidCommandName = new Regex("^[a-z0-9A-Z_-]+$");
private static void AssertValidCommand(string[] command)
{
if(command.Length < 1 || !ValidCommandName.IsMatch(command[0]))
throw new Exception("bad git command: " + (command.Length == 0 ? "" : command[0]));
}
protected class GitProcess
{
Process _process;
public GitProcess(Process process)
{
_process = process;
}
public static implicit operator Process(GitProcess process)
{
return process._process;
}
public string StandardErrorString { get; private set; }
public void ConsumeStandardError()
{
StandardErrorString = "";
_process.ErrorDataReceived += StdErrReceived;
_process.BeginErrorReadLine();
}
private void StdErrReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null && e.Data.Trim() != "")
{
var data = e.Data;
Trace.WriteLine(data.TrimEnd(), "git stderr");
StandardErrorString += data;
}
}
// Delegate a bunch of things to the Process.
public ProcessStartInfo StartInfo { get { return _process.StartInfo; } }
public int ExitCode { get { return _process.ExitCode; } }
public StreamWriter StandardInput { get { return _process.StandardInput; } }
public StreamReader StandardOutput { get { return _process.StandardOutput; } }
public bool WaitForExit(int milliseconds)
{
return _process.WaitForExit(milliseconds);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using FluentValidation;
using GoldenEye.Commands;
using GoldenEye.Queries;
using GoldenEye.Registration;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace GoldenEye.Tests.Validation;
public class ValidationPipelineTests
{
public class CommandTests
{
private class CreateUser: ICommand
{
public CreateUser(string userName)
{
UserName = userName;
}
public string UserName { get; }
}
private class CreateUserValidator: AbstractValidator<CreateUser>
{
public CreateUserValidator()
{
RuleFor(c => c.UserName).NotEmpty();
}
}
private class RemoveAllUsers: ICommand
{
}
public class DataContext
{
public List<string> Users = new List<string>();
}
private class UserCommandHandler: ICommandHandler<CreateUser>,
ICommandHandler<RemoveAllUsers>
{
private readonly DataContext context;
public UserCommandHandler(DataContext context)
{
this.context = context;
}
public Task<Unit> Handle(CreateUser command, CancellationToken cancellationToken)
{
context.Users.Add(command.UserName);
return Unit.Task;
}
public Task<Unit> Handle(RemoveAllUsers command, CancellationToken cancellationToken)
{
context.Users.Clear();
return Unit.Task;
}
}
[Fact]
public async Task
GivenValidationPipelineSetUp_WhenCommandWithoutValidatorWasSent_ThenCommandIsNotValidatedAndHandledByCommandHandler()
{
//Given
var services = new ServiceCollection();
services.AddDDD();
services.AddValidationPipeline();
services.AddSingleton(new DataContext {Users = new List<string> {"John Doe"}});
services.AddCommandHandler<RemoveAllUsers, UserCommandHandler>();
//No validator Registered
using (var sp = services.BuildServiceProvider())
{
var commandBus = sp.GetService<ICommandBus>();
var command = new RemoveAllUsers();
//When
await commandBus.Send(command);
//Then
var context = sp.GetService<DataContext>();
context.Users.Should().NotContain("John Doe");
context.Users.Should().BeEmpty();
}
}
[Fact]
public async Task
GivenValidationPipelineSetUp_WhenInValidCommandWasSent_ThenCommandWasValidatedAndValidationExceptionWasThrown()
{
//Given
var services = new ServiceCollection();
services.AddDDD();
services.AddValidationPipeline();
services.AddSingleton<DataContext>();
services.AddCommandHandler<CreateUser, UserCommandHandler>();
services.AddTransient<IValidator<CreateUser>, CreateUserValidator>();
using (var sp = services.BuildServiceProvider())
{
var commandBus = sp.GetService<ICommandBus>();
var invalidCommand = new CreateUser(null);
Func<Task> sendCommandAsync = async () => await commandBus.Send(invalidCommand);
//When
//Then
await sendCommandAsync.Should().ThrowAsync<ValidationException>();
var context = sp.GetService<DataContext>();
context.Users.Should().BeEmpty();
}
}
[Fact]
public async Task
GivenValidationPipelineSetUp_WhenValidCommandWasSent_ThenCommandIsValidatedAndHandledByCommandHandler()
{
//Given
var services = new ServiceCollection();
services.AddDDD();
services.AddValidationPipeline();
services.AddSingleton<DataContext>();
services.AddCommandHandler<CreateUser, UserCommandHandler>();
services.AddTransient<IValidator<CreateUser>, CreateUserValidator>();
using (var sp = services.BuildServiceProvider())
{
var commandBus = sp.GetService<ICommandBus>();
var command = new CreateUser("John Doe");
//When
await commandBus.Send(command);
//Then
var context = sp.GetService<DataContext>();
context.Users.Should().Contain(command.UserName);
}
}
}
public class QueriesTests
{
private class GetUser: IQuery<string>
{
public GetUser(int id)
{
Id = id;
}
public int Id { get; }
}
private class GetUserValidator: AbstractValidator<GetUser>
{
public GetUserValidator()
{
RuleFor(c => c.Id)
.GreaterThanOrEqualTo(0);
}
}
private class GetAllUsers: IListQuery<string>
{
}
public class DataContext
{
public List<string> Users = new List<string>();
}
private class UserQueryHandler: IQueryHandler<GetUser, string>,
IQueryHandler<GetAllUsers, IReadOnlyList<string>>
{
private readonly DataContext context;
public UserQueryHandler(DataContext context)
{
this.context = context;
}
public Task<IReadOnlyList<string>> Handle(GetAllUsers query, CancellationToken cancellationToken)
{
return Task.FromResult<IReadOnlyList<string>>(context.Users);
}
public Task<string> Handle(GetUser query, CancellationToken cancellationToken)
{
return Task.FromResult(context.Users[query.Id]);
}
}
[Fact]
public async Task
GivenValidationPipelineSetUp_WhenInValidQueryWasSent_ThenQueryWasValidatedAndValidationExceptionWasThrown()
{
//Given
var services = new ServiceCollection();
services.AddDDD();
services.AddValidationPipeline();
services.AddSingleton(new DataContext {Users = new List<string> {"John Doe"}});
services.AddQueryHandler<GetUser, string, UserQueryHandler>();
services.AddTransient<IValidator<GetUser>, GetUserValidator>();
using (var sp = services.BuildServiceProvider())
{
var queryBus = sp.GetService<IQueryBus>();
var invalidQuery = new GetUser(-1);
Func<Task> sendQueryAsync = async () => await queryBus.Send<GetUser, string>(invalidQuery);
//When
//Then
await sendQueryAsync.Should().ThrowAsync<ValidationException>();
}
}
[Fact]
public async Task
GivenValidationPipelineSetUp_WhenQueryWithoutValidatorWasSent_ThenQueryIsNotValidatedAndHandledByQueryHandler()
{
//Given
var services = new ServiceCollection();
services.AddDDD();
services.AddValidationPipeline();
services.AddSingleton(new DataContext {Users = new List<string> {"John Doe"}});
services.AddQueryHandler<GetAllUsers, IReadOnlyList<string>, UserQueryHandler>();
using (var sp = services.BuildServiceProvider())
{
var queryBus = sp.GetService<IQueryBus>();
var query = new GetAllUsers();
//When
var result = await queryBus.Send<GetAllUsers, IReadOnlyList<string>>(query);
//Then
result.Should().HaveCount(1);
result[0].Should().Be("John Doe");
}
}
[Fact]
public async Task
GivenValidationPipelineSetUp_WhenValidQueryWasSent_ThenQueryIsValidatedAndHandledByQueryHandler()
{
//Given
var services = new ServiceCollection();
services.AddDDD();
services.AddValidationPipeline();
services.AddSingleton(new DataContext {Users = new List<string> {"John Doe"}});
services.AddQueryHandler<GetUser, string, UserQueryHandler>();
services.AddTransient<IValidator<GetUser>, GetUserValidator>();
using (var sp = services.BuildServiceProvider())
{
var queryBus = sp.GetService<IQueryBus>();
var query = new GetUser(0);
//When
var result = await queryBus.Send<GetUser, string>(query);
//Then
result.Should().NotBeNull();
result.Should().Be("John Doe");
}
}
[Fact]
public async Task
GivenValidationPipelineSetUp_WhenValidQueryWithoutValidatorWasSent_ThenQueryIsValidatedAndHandledByQueryHandler()
{
//Given
var services = new ServiceCollection();
services.AddDDD();
services.AddValidationPipeline();
services.AddSingleton(new DataContext {Users = new List<string> {"John Doe"}});
services.AddQueryHandler<GetUser, string, UserQueryHandler>();
services.AddTransient<IValidator<GetUser>, GetUserValidator>();
using (var sp = services.BuildServiceProvider())
{
var queryBus = sp.GetService<IQueryBus>();
var query = new GetUser(0);
//When
var result = await queryBus.Send<GetUser, string>(query);
//Then
result.Should().NotBeNull();
result.Should().Be("John Doe");
}
}
}
}
| |
using System;
using System.Diagnostics;
using BITVEC_TELEM = System.Byte;
using i64 = System.Int64;
using u32 = System.UInt32;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2008 February 16
**
** 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 implements an object that represents a fixed-length
** bitmap. Bits are numbered starting with 1.
**
** A bitmap is used to record which pages of a database file have been
** journalled during a transaction, or which pages have the "dont-write"
** property. Usually only a few pages are meet either condition.
** So the bitmap is usually sparse and has low cardinality.
** But sometimes (for example when during a DROP of a large table) most
** or all of the pages in a database can get journalled. In those cases,
** the bitmap becomes dense with high cardinality. The algorithm needs
** to handle both cases well.
**
** The size of the bitmap is fixed when the object is created.
**
** All bits are clear when the bitmap is created. Individual bits
** may be set or cleared one at a time.
**
** Test operations are about 100 times more common that set operations.
** Clear operations are exceedingly rare. There are usually between
** 5 and 500 set operations per Bitvec object, though the number of sets can
** sometimes grow into tens of thousands or larger. The size of the
** Bitvec object is the number of pages in the database file at the
** start of a transaction, and is thus usually less than a few thousand,
** but can be as large as 2 billion for a really big database.
*************************************************************************
** 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"
/* Size of the Bitvec structure in bytes. */
private static int BITVEC_SZ = 512;
/* Round the union size down to the nearest pointer boundary, since that's how
** it will be aligned within the Bitvec struct. */
//#define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
private static int BITVEC_USIZE = (((BITVEC_SZ - (3 * sizeof(u32))) / 4) * 4);
/* Type of the array "element" for the bitmap representation.
** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
** Setting this to the "natural word" size of your CPU may improve
** performance. */
//#define BITVEC_TELEM u8
//using BITVEC_TELEM = System.Byte;
/* Size, in bits, of the bitmap element. */
//#define BITVEC_SZELEM 8
private const int BITVEC_SZELEM = 8;
/* Number of elements in a bitmap array. */
//#define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
private static int BITVEC_NELEM = (int)(BITVEC_USIZE / sizeof(BITVEC_TELEM));
/* Number of bits in the bitmap array. */
//#define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
private static int BITVEC_NBIT = (BITVEC_NELEM * BITVEC_SZELEM);
/* Number of u32 values in hash table. */
//#define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
private static u32 BITVEC_NINT = (u32)(BITVEC_USIZE / sizeof(u32));
/* Maximum number of entries in hash table before
** sub-dividing and re-hashing. */
//#define BITVEC_MXHASH (BITVEC_NINT/2)
private static int BITVEC_MXHASH = (int)(BITVEC_NINT / 2);
/* Hashing function for the aHash representation.
** Empirical testing showed that the *37 multiplier
** (an arbitrary prime)in the hash function provided
** no fewer collisions than the no-op *1. */
//#define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
private static u32 BITVEC_HASH(u32 X)
{
return (u32)(((X) * 1) % BITVEC_NINT);
}
private static int BITVEC_NPTR = (int)(BITVEC_USIZE / 4);//sizeof(Bitvec *));
/*
** A bitmap is an instance of the following structure.
**
** This bitmap records the existence of zero or more bits
** with values between 1 and iSize, inclusive.
**
** There are three possible representations of the bitmap.
** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
** bitmap. The least significant bit is bit 1.
**
** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
** a hash table that will hold up to BITVEC_MXHASH distinct values.
**
** Otherwise, the value i is redirected into one of BITVEC_NPTR
** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
** handles up to iDivisor separate values of i. apSub[0] holds
** values between 1 and iDivisor. apSub[1] holds values between
** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
** to hold deal with values between 1 and iDivisor.
*/
public class _u
{
public BITVEC_TELEM[] aBitmap = new byte[BITVEC_NELEM]; /* Bitmap representation */
public u32[] aHash = new u32[BITVEC_NINT]; /* Hash table representation */
public Bitvec[] apSub = new Bitvec[BITVEC_NPTR]; /* Recursive representation */
}
public class Bitvec
{
public u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
public u32 nSet; /* Number of bits that are set - only valid for aHash
** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
** this would be 125. */
public u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
/* Should >=0 for apSub element. */
/* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
/* For a BITVEC_SZ of 512, this would be 34,359,739. */
public _u u = new _u();
public static implicit operator bool(Bitvec b)
{
return (b != null);
}
};
/*
** Create a new bitmap object able to handle bits between 0 and iSize,
** inclusive. Return a pointer to the new object. Return NULL if
** malloc fails.
*/
private static Bitvec sqlite3BitvecCreate(u32 iSize)
{
Bitvec p;
//Debug.Assert( sizeof(p)==BITVEC_SZ );
p = new Bitvec();//sqlite3MallocZero( sizeof(p) );
if (p != null)
{
p.iSize = iSize;
}
return p;
}
/*
** Check to see if the i-th bit is set. Return true or false.
** If p is NULL (if the bitmap has not been created) or if
** i is out of range, then return false.
*/
private static int sqlite3BitvecTest(Bitvec p, u32 i)
{
if (p == null || i == 0)
return 0;
if (i > p.iSize)
return 0;
i--;
while (p.iDivisor != 0)
{
u32 bin = i / p.iDivisor;
i = i % p.iDivisor;
p = p.u.apSub[bin];
if (null == p)
{
return 0;
}
}
if (p.iSize <= BITVEC_NBIT)
{
return ((p.u.aBitmap[i / BITVEC_SZELEM] & (1 << (int)(i & (BITVEC_SZELEM - 1)))) != 0) ? 1 : 0;
}
else
{
u32 h = BITVEC_HASH(i++);
while (p.u.aHash[h] != 0)
{
if (p.u.aHash[h] == i)
return 1;
h = (h + 1) % BITVEC_NINT;
}
return 0;
}
}
/*
** Set the i-th bit. Return 0 on success and an error code if
** anything goes wrong.
**
** This routine might cause sub-bitmaps to be allocated. Failing
** to get the memory needed to hold the sub-bitmap is the only
** that can go wrong with an insert, assuming p and i are valid.
**
** The calling function must ensure that p is a valid Bitvec object
** and that the value for "i" is within range of the Bitvec object.
** Otherwise the behavior is undefined.
*/
private static int sqlite3BitvecSet(Bitvec p, u32 i)
{
u32 h;
if (p == null)
return SQLITE_OK;
Debug.Assert(i > 0);
Debug.Assert(i <= p.iSize);
i--;
while ((p.iSize > BITVEC_NBIT) && p.iDivisor != 0)
{
u32 bin = i / p.iDivisor;
i = i % p.iDivisor;
if (p.u.apSub[bin] == null)
{
p.u.apSub[bin] = sqlite3BitvecCreate(p.iDivisor);
//if ( p.u.apSub[bin] == null )
// return SQLITE_NOMEM;
}
p = p.u.apSub[bin];
}
if (p.iSize <= BITVEC_NBIT)
{
p.u.aBitmap[i / BITVEC_SZELEM] |= (byte)(1 << (int)(i & (BITVEC_SZELEM - 1)));
return SQLITE_OK;
}
h = BITVEC_HASH(i++);
/* if there wasn't a hash collision, and this doesn't */
/* completely fill the hash, then just add it without */
/* worring about sub-dividing and re-hashing. */
if (0 == p.u.aHash[h])
{
if (p.nSet < (BITVEC_NINT - 1))
{
goto bitvec_set_end;
}
else
{
goto bitvec_set_rehash;
}
}
/* there was a collision, check to see if it's already */
/* in hash, if not, try to find a spot for it */
do
{
if (p.u.aHash[h] == i)
return SQLITE_OK;
h++;
if (h >= BITVEC_NINT)
h = 0;
} while (p.u.aHash[h] != 0);
/* we didn't find it in the hash. h points to the first */
/* available free spot. check to see if this is going to */
/* make our hash too "full". */
bitvec_set_rehash:
if (p.nSet >= BITVEC_MXHASH)
{
u32 j;
int rc;
u32[] aiValues = new u32[BITVEC_NINT];// = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
//if ( aiValues == null )
//{
// return SQLITE_NOMEM;
//}
//else
{
Buffer.BlockCopy(p.u.aHash, 0, aiValues, 0, aiValues.Length * (sizeof(u32)));// memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
p.u.apSub = new Bitvec[BITVEC_NPTR];//memset(p->u.apSub, 0, sizeof(p->u.apSub));
p.iDivisor = (u32)((p.iSize + BITVEC_NPTR - 1) / BITVEC_NPTR);
rc = sqlite3BitvecSet(p, i);
for (j = 0; j < BITVEC_NINT; j++)
{
if (aiValues[j] != 0)
rc |= sqlite3BitvecSet(p, aiValues[j]);
}
//sqlite3StackFree( null, aiValues );
return rc;
}
}
bitvec_set_end:
p.nSet++;
p.u.aHash[h] = i;
return SQLITE_OK;
}
/*
** Clear the i-th bit.
**
** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
** that BitvecClear can use to rebuilt its hash table.
*/
private static void sqlite3BitvecClear(Bitvec p, u32 i, u32[] pBuf)
{
if (p == null)
return;
Debug.Assert(i > 0);
i--;
while (p.iDivisor != 0)
{
u32 bin = i / p.iDivisor;
i = i % p.iDivisor;
p = p.u.apSub[bin];
if (null == p)
{
return;
}
}
if (p.iSize <= BITVEC_NBIT)
{
p.u.aBitmap[i / BITVEC_SZELEM] &= (byte)~((1 << (int)(i & (BITVEC_SZELEM - 1))));
}
else
{
u32 j;
u32[] aiValues = pBuf;
Array.Copy(p.u.aHash, aiValues, p.u.aHash.Length);//memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
p.u.aHash = new u32[aiValues.Length];// memset(p->u.aHash, 0, sizeof(p->u.aHash));
p.nSet = 0;
for (j = 0; j < BITVEC_NINT; j++)
{
if (aiValues[j] != 0 && aiValues[j] != (i + 1))
{
u32 h = BITVEC_HASH(aiValues[j] - 1);
p.nSet++;
while (p.u.aHash[h] != 0)
{
h++;
if (h >= BITVEC_NINT)
h = 0;
}
p.u.aHash[h] = aiValues[j];
}
}
}
}
/*
** Destroy a bitmap object. Reclaim all memory used.
*/
private static void sqlite3BitvecDestroy(ref Bitvec p)
{
if (p == null)
return;
if (p.iDivisor != 0)
{
u32 i;
for (i = 0; i < BITVEC_NPTR; i++)
{
sqlite3BitvecDestroy(ref p.u.apSub[i]);
}
}
//sqlite3_free( ref p );
}
/*
** Return the value of the iSize parameter specified when Bitvec *p
** was created.
*/
private static u32 sqlite3BitvecSize(Bitvec p)
{
return p.iSize;
}
#if !SQLITE_OMIT_BUILTIN_TEST
/*
** Let V[] be an array of unsigned characters sufficient to hold
** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
** Then the following macros can be used to set, clear, or test
** individual bits within V.
*/
//#define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
private static void SETBIT(byte[] V, int I)
{
V[I >> 3] |= (byte)(1 << (I & 7));
}
//#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
private static void CLEARBIT(byte[] V, int I)
{
V[I >> 3] &= (byte)~(1 << (I & 7));
}
//#define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
private static int TESTBIT(byte[] V, int I)
{
return (V[I >> 3] & (1 << (I & 7))) != 0 ? 1 : 0;
}
/*
** This routine runs an extensive test of the Bitvec code.
**
** The input is an array of integers that acts as a program
** to test the Bitvec. The integers are opcodes followed
** by 0, 1, or 3 operands, depending on the opcode. Another
** opcode follows immediately after the last operand.
**
** There are 6 opcodes numbered from 0 through 5. 0 is the
** "halt" opcode and causes the test to end.
**
** 0 Halt and return the number of errors
** 1 N S X Set N bits beginning with S and incrementing by X
** 2 N S X Clear N bits beginning with S and incrementing by X
** 3 N Set N randomly chosen bits
** 4 N Clear N randomly chosen bits
** 5 N S X Set N bits from S increment X in array only, not in bitvec
**
** The opcodes 1 through 4 perform set and clear operations are performed
** on both a Bitvec object and on a linear array of bits obtained from malloc.
** Opcode 5 works on the linear array only, not on the Bitvec.
** Opcode 5 is used to deliberately induce a fault in order to
** confirm that error detection works.
**
** At the conclusion of the test the linear array is compared
** against the Bitvec object. If there are any differences,
** an error is returned. If they are the same, zero is returned.
**
** If a memory allocation error occurs, return -1.
*/
private static int sqlite3BitvecBuiltinTest(u32 sz, int[] aOp)
{
Bitvec pBitvec = null;
byte[] pV = null;
int rc = -1;
int i, nx, pc, op;
u32[] pTmpSpace;
/* Allocate the Bitvec to be tested and a linear array of
** bits to act as the reference */
pBitvec = sqlite3BitvecCreate(sz);
pV = sqlite3_malloc((int)(sz + 7) / 8 + 1);
pTmpSpace = new u32[BITVEC_SZ];// sqlite3_malloc( BITVEC_SZ );
if (pBitvec == null || pV == null || pTmpSpace == null)
goto bitvec_end;
Array.Clear(pV, 0, (int)(sz + 7) / 8 + 1);// memset( pV, 0, ( sz + 7 ) / 8 + 1 );
/* NULL pBitvec tests */
sqlite3BitvecSet(null, (u32)1);
sqlite3BitvecClear(null, 1, pTmpSpace);
/* Run the program */
pc = 0;
while ((op = aOp[pc]) != 0)
{
switch (op)
{
case 1:
case 2:
case 5:
{
nx = 4;
i = aOp[pc + 2] - 1;
aOp[pc + 2] += aOp[pc + 3];
break;
}
case 3:
case 4:
default:
{
nx = 2;
i64 i64Temp = 0;
sqlite3_randomness(sizeof(i64), ref i64Temp);
i = (int)i64Temp;
break;
}
}
if ((--aOp[pc + 1]) > 0)
nx = 0;
pc += nx;
i = (int)((i & 0x7fffffff) % sz);
if ((op & 1) != 0)
{
SETBIT(pV, (i + 1));
if (op != 5)
{
if (sqlite3BitvecSet(pBitvec, (u32)i + 1) != 0)
goto bitvec_end;
}
}
else
{
CLEARBIT(pV, (i + 1));
sqlite3BitvecClear(pBitvec, (u32)i + 1, pTmpSpace);
}
}
/* Test to make sure the linear array exactly matches the
** Bitvec object. Start with the assumption that they do
** match (rc==0). Change rc to non-zero if a discrepancy
** is found.
*/
rc = sqlite3BitvecTest(null, 0) + sqlite3BitvecTest(pBitvec, sz + 1)
+ sqlite3BitvecTest(pBitvec, 0)
+ (int)(sqlite3BitvecSize(pBitvec) - sz);
for (i = 1; i <= sz; i++)
{
if ((TESTBIT(pV, i)) != sqlite3BitvecTest(pBitvec, (u32)i))
{
rc = i;
break;
}
}
/* Free allocated structure */
bitvec_end:
//sqlite3_free( ref pTmpSpace );
//sqlite3_free( ref pV );
sqlite3BitvecDestroy(ref pBitvec);
return rc;
}
#endif //* SQLITE_OMIT_BUILTIN_TEST */
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Tests.Common;
using log4net;
namespace OpenSim.Region.Framework.Scenes.Tests
{
[TestFixture]
public class SceneObjectLinkingTests : OpenSimTestCase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Links to self should be ignored.
/// </summary>
[Test]
public void TestLinkToSelf()
{
TestHelpers.InMethod();
UUID ownerId = TestHelpers.ParseTail(0x1);
int nParts = 3;
TestScene scene = new SceneHelpers().SetupScene();
SceneObjectGroup sog1 = SceneHelpers.CreateSceneObject(nParts, ownerId, "TestLinkToSelf_", 0x10);
scene.AddSceneObject(sog1);
scene.LinkObjects(ownerId, sog1.LocalId, new List<uint>() { sog1.Parts[1].LocalId });
// sog1.LinkToGroup(sog1);
Assert.That(sog1.Parts.Length, Is.EqualTo(nParts));
}
[Test]
public void TestLinkDelink2SceneObjects()
{
TestHelpers.InMethod();
bool debugtest = false;
Scene scene = new SceneHelpers().SetupScene();
SceneObjectGroup grp1 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part1 = grp1.RootPart;
SceneObjectGroup grp2 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part2 = grp2.RootPart;
grp1.AbsolutePosition = new Vector3(10, 10, 10);
grp2.AbsolutePosition = Vector3.Zero;
// <90,0,0>
// grp1.UpdateGroupRotationR(Quaternion.CreateFromEulers(90 * Utils.DEG_TO_RAD, 0, 0));
// <180,0,0>
grp2.UpdateGroupRotationR(Quaternion.CreateFromEulers(180 * Utils.DEG_TO_RAD, 0, 0));
// Required for linking
grp1.RootPart.ClearUpdateSchedule();
grp2.RootPart.ClearUpdateSchedule();
// Link grp2 to grp1. part2 becomes child prim to grp1. grp2 is eliminated.
Assert.IsFalse(grp1.GroupContainsForeignPrims);
grp1.LinkToGroup(grp2);
Assert.IsTrue(grp1.GroupContainsForeignPrims);
scene.Backup(true);
Assert.IsFalse(grp1.GroupContainsForeignPrims);
// FIXME: Can't do this test yet since group 2 still has its root part! We can't yet null this since
// it might cause SOG.ProcessBackup() to fail due to the race condition. This really needs to be fixed.
Assert.That(grp2.IsDeleted, "SOG 2 was not registered as deleted after link.");
Assert.That(grp2.Parts.Length, Is.EqualTo(0), "Group 2 still contained children after delink.");
Assert.That(grp1.Parts.Length == 2);
if (debugtest)
{
m_log.Debug("parts: " + grp1.Parts.Length);
m_log.Debug("Group1: Pos:"+grp1.AbsolutePosition+", Rot:"+grp1.GroupRotation);
m_log.Debug("Group1: Prim1: OffsetPosition:"+ part1.OffsetPosition+", OffsetRotation:"+part1.RotationOffset);
m_log.Debug("Group1: Prim2: OffsetPosition:"+part2.OffsetPosition+", OffsetRotation:"+part2.RotationOffset);
}
// root part should have no offset position or rotation
Assert.That(part1.OffsetPosition == Vector3.Zero && part1.RotationOffset == Quaternion.Identity,
"root part should have no offset position or rotation");
// offset position should be root part position - part2.absolute position.
Assert.That(part2.OffsetPosition == new Vector3(-10, -10, -10),
"offset position should be root part position - part2.absolute position.");
float roll = 0;
float pitch = 0;
float yaw = 0;
// There's a euler anomoly at 180, 0, 0 so expect 180 to turn into -180.
part1.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
Vector3 rotEuler1 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG);
if (debugtest)
m_log.Debug(rotEuler1);
part2.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
Vector3 rotEuler2 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG);
if (debugtest)
m_log.Debug(rotEuler2);
Assert.That(rotEuler2.ApproxEquals(new Vector3(-180, 0, 0), 0.001f) || rotEuler2.ApproxEquals(new Vector3(180, 0, 0), 0.001f),
"Not exactly sure what this is asserting...");
// Delink part 2
SceneObjectGroup grp3 = grp1.DelinkFromGroup(part2.LocalId);
if (debugtest)
m_log.Debug("Group2: Prim2: OffsetPosition:" + part2.AbsolutePosition + ", OffsetRotation:" + part2.RotationOffset);
Assert.That(grp1.Parts.Length, Is.EqualTo(1), "Group 1 still contained part2 after delink.");
Assert.That(part2.AbsolutePosition == Vector3.Zero, "The absolute position should be zero");
Assert.NotNull(grp3);
}
[Test]
public void TestLinkDelink2groups4SceneObjects()
{
TestHelpers.InMethod();
bool debugtest = false;
Scene scene = new SceneHelpers().SetupScene();
SceneObjectGroup grp1 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part1 = grp1.RootPart;
SceneObjectGroup grp2 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part2 = grp2.RootPart;
SceneObjectGroup grp3 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part3 = grp3.RootPart;
SceneObjectGroup grp4 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part4 = grp4.RootPart;
grp1.AbsolutePosition = new Vector3(10, 10, 10);
grp2.AbsolutePosition = Vector3.Zero;
grp3.AbsolutePosition = new Vector3(20, 20, 20);
grp4.AbsolutePosition = new Vector3(40, 40, 40);
// <90,0,0>
// grp1.UpdateGroupRotationR(Quaternion.CreateFromEulers(90 * Utils.DEG_TO_RAD, 0, 0));
// <180,0,0>
grp2.UpdateGroupRotationR(Quaternion.CreateFromEulers(180 * Utils.DEG_TO_RAD, 0, 0));
// <270,0,0>
// grp3.UpdateGroupRotationR(Quaternion.CreateFromEulers(270 * Utils.DEG_TO_RAD, 0, 0));
// <0,90,0>
grp4.UpdateGroupRotationR(Quaternion.CreateFromEulers(0, 90 * Utils.DEG_TO_RAD, 0));
// Required for linking
grp1.RootPart.ClearUpdateSchedule();
grp2.RootPart.ClearUpdateSchedule();
grp3.RootPart.ClearUpdateSchedule();
grp4.RootPart.ClearUpdateSchedule();
// Link grp2 to grp1. part2 becomes child prim to grp1. grp2 is eliminated.
grp1.LinkToGroup(grp2);
// Link grp4 to grp3.
grp3.LinkToGroup(grp4);
// At this point we should have 4 parts total in two groups.
Assert.That(grp1.Parts.Length == 2, "Group1 children count should be 2");
Assert.That(grp2.IsDeleted, "Group 2 was not registered as deleted after link.");
Assert.That(grp2.Parts.Length, Is.EqualTo(0), "Group 2 still contained parts after delink.");
Assert.That(grp3.Parts.Length == 2, "Group3 children count should be 2");
Assert.That(grp4.IsDeleted, "Group 4 was not registered as deleted after link.");
Assert.That(grp4.Parts.Length, Is.EqualTo(0), "Group 4 still contained parts after delink.");
if (debugtest)
{
m_log.Debug("--------After Link-------");
m_log.Debug("Group1: parts:" + grp1.Parts.Length);
m_log.Debug("Group1: Pos:"+grp1.AbsolutePosition+", Rot:"+grp1.GroupRotation);
m_log.Debug("Group1: Prim1: OffsetPosition:" + part1.OffsetPosition + ", OffsetRotation:" + part1.RotationOffset);
m_log.Debug("Group1: Prim2: OffsetPosition:"+part2.OffsetPosition+", OffsetRotation:"+ part2.RotationOffset);
m_log.Debug("Group3: parts:" + grp3.Parts.Length);
m_log.Debug("Group3: Pos:"+grp3.AbsolutePosition+", Rot:"+grp3.GroupRotation);
m_log.Debug("Group3: Prim1: OffsetPosition:"+part3.OffsetPosition+", OffsetRotation:"+part3.RotationOffset);
m_log.Debug("Group3: Prim2: OffsetPosition:"+part4.OffsetPosition+", OffsetRotation:"+part4.RotationOffset);
}
// Required for linking
grp1.RootPart.ClearUpdateSchedule();
grp3.RootPart.ClearUpdateSchedule();
// root part should have no offset position or rotation
Assert.That(part1.OffsetPosition == Vector3.Zero && part1.RotationOffset == Quaternion.Identity,
"root part should have no offset position or rotation (again)");
// offset position should be root part position - part2.absolute position.
Assert.That(part2.OffsetPosition == new Vector3(-10, -10, -10),
"offset position should be root part position - part2.absolute position (again)");
float roll = 0;
float pitch = 0;
float yaw = 0;
// There's a euler anomoly at 180, 0, 0 so expect 180 to turn into -180.
part1.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
Vector3 rotEuler1 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG);
if (debugtest)
m_log.Debug(rotEuler1);
part2.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
Vector3 rotEuler2 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG);
if (debugtest)
m_log.Debug(rotEuler2);
Assert.That(rotEuler2.ApproxEquals(new Vector3(-180, 0, 0), 0.001f) || rotEuler2.ApproxEquals(new Vector3(180, 0, 0), 0.001f),
"Not sure what this assertion is all about...");
// Now we're linking the first group to the third group. This will make the first group child parts of the third one.
grp3.LinkToGroup(grp1);
// Delink parts 2 and 3
grp3.DelinkFromGroup(part2.LocalId);
grp3.DelinkFromGroup(part3.LocalId);
if (debugtest)
{
m_log.Debug("--------After De-Link-------");
m_log.Debug("Group1: parts:" + grp1.Parts.Length);
m_log.Debug("Group1: Pos:" + grp1.AbsolutePosition + ", Rot:" + grp1.GroupRotation);
m_log.Debug("Group1: Prim1: OffsetPosition:" + part1.OffsetPosition + ", OffsetRotation:" + part1.RotationOffset);
m_log.Debug("Group1: Prim2: OffsetPosition:" + part2.OffsetPosition + ", OffsetRotation:" + part2.RotationOffset);
m_log.Debug("Group3: parts:" + grp3.Parts.Length);
m_log.Debug("Group3: Pos:" + grp3.AbsolutePosition + ", Rot:" + grp3.GroupRotation);
m_log.Debug("Group3: Prim1: OffsetPosition:" + part3.OffsetPosition + ", OffsetRotation:" + part3.RotationOffset);
m_log.Debug("Group3: Prim2: OffsetPosition:" + part4.OffsetPosition + ", OffsetRotation:" + part4.RotationOffset);
}
Assert.That(part2.AbsolutePosition == Vector3.Zero, "Badness 1");
Assert.That(part4.OffsetPosition == new Vector3(20, 20, 20), "Badness 2");
Quaternion compareQuaternion = new Quaternion(0, 0.7071068f, 0, 0.7071068f);
Assert.That((part4.RotationOffset.X - compareQuaternion.X < 0.00003)
&& (part4.RotationOffset.Y - compareQuaternion.Y < 0.00003)
&& (part4.RotationOffset.Z - compareQuaternion.Z < 0.00003)
&& (part4.RotationOffset.W - compareQuaternion.W < 0.00003),
"Badness 3");
}
/// <summary>
/// Test that a new scene object which is already linked is correctly persisted to the persistence layer.
/// </summary>
[Test]
public void TestNewSceneObjectLinkPersistence()
{
TestHelpers.InMethod();
//log4net.Config.XmlConfigurator.Configure();
TestScene scene = new SceneHelpers().SetupScene();
string rootPartName = "rootpart";
UUID rootPartUuid = new UUID("00000000-0000-0000-0000-000000000001");
string linkPartName = "linkpart";
UUID linkPartUuid = new UUID("00000000-0000-0000-0001-000000000000");
SceneObjectPart rootPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = rootPartName, UUID = rootPartUuid };
SceneObjectPart linkPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = linkPartName, UUID = linkPartUuid };
SceneObjectGroup sog = new SceneObjectGroup(rootPart);
sog.AddPart(linkPart);
scene.AddNewSceneObject(sog, true);
// In a test, we have to crank the backup handle manually. Normally this would be done by the timer invoked
// scene backup thread.
scene.Backup(true);
List<SceneObjectGroup> storedObjects = scene.SimulationDataService.LoadObjects(scene.RegionInfo.RegionID);
Assert.That(storedObjects.Count, Is.EqualTo(1));
Assert.That(storedObjects[0].Parts.Length, Is.EqualTo(2));
Assert.That(storedObjects[0].ContainsPart(rootPartUuid));
Assert.That(storedObjects[0].ContainsPart(linkPartUuid));
}
/// <summary>
/// Test that a delink of a previously linked object is correctly persisted to the database
/// </summary>
[Test]
public void TestDelinkPersistence()
{
TestHelpers.InMethod();
//log4net.Config.XmlConfigurator.Configure();
TestScene scene = new SceneHelpers().SetupScene();
string rootPartName = "rootpart";
UUID rootPartUuid = new UUID("00000000-0000-0000-0000-000000000001");
string linkPartName = "linkpart";
UUID linkPartUuid = new UUID("00000000-0000-0000-0001-000000000000");
SceneObjectPart rootPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = rootPartName, UUID = rootPartUuid };
SceneObjectPart linkPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = linkPartName, UUID = linkPartUuid };
SceneObjectGroup linkGroup = new SceneObjectGroup(linkPart);
scene.AddNewSceneObject(linkGroup, true);
SceneObjectGroup sog = new SceneObjectGroup(rootPart);
scene.AddNewSceneObject(sog, true);
Assert.IsFalse(sog.GroupContainsForeignPrims);
sog.LinkToGroup(linkGroup);
Assert.IsTrue(sog.GroupContainsForeignPrims);
scene.Backup(true);
Assert.AreEqual(1, scene.SimulationDataService.LoadObjects(scene.RegionInfo.RegionID).Count);
// These changes should occur immediately without waiting for a backup pass
SceneObjectGroup groupToDelete = sog.DelinkFromGroup(linkPart, false);
Assert.IsFalse(groupToDelete.GroupContainsForeignPrims);
/* backup is async
scene.DeleteSceneObject(groupToDelete, false);
List<SceneObjectGroup> storedObjects = scene.SimulationDataService.LoadObjects(scene.RegionInfo.RegionID);
Assert.AreEqual(1, storedObjects.Count);
Assert.AreEqual(1, storedObjects[0].Parts.Length);
Assert.IsTrue(storedObjects[0].ContainsPart(rootPartUuid));
*/
}
}
}
| |
using Saga.Map;
using Saga.Network.Packets;
using Saga.Packets;
using Saga.PrimaryTypes;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Common
{
public static class Experience
{
[DebuggerNonUserCode()]
[CLSCompliant(false)]
public static void GiveWeaponExperience(Character target, uint wexp)
{
byte index = target.weapons.ActiveWeaponIndex == 1 ? target.weapons.SeconairyWeaponIndex : target.weapons.PrimaryWeaponIndex;
if (index < target.weapons.UnlockedWeaponSlots)
{
Weapon weapon = target.weapons[index];
if (weapon == null || weapon._weaponlevel >= Singleton.experience.MaxWLVL) return;
//Checks if the weapon is at already at max experience
uint ReqWexp = Singleton.experience.FindRequiredWexp(weapon._weaponlevel + 1);
if (weapon._experience == ReqWexp)
{
return;
}
//Adds the experience and check if we gain a level
weapon._experience += wexp;
if (weapon._experience > ReqWexp)
{
weapon._experience = ReqWexp;
}
//Adds the weapon experience
SMSG_WEAPONADJUST spkt = new SMSG_WEAPONADJUST();
spkt.Function = 2;
spkt.Value = weapon._experience;
spkt.Slot = (byte)index;
spkt.SessionId = target.id;
target.client.Send((byte[])spkt);
}
}
[DebuggerNonUserCode()]
[CLSCompliant(false)]
public static void GiveSkillExperience(Character target, uint skillid, uint experiencepoints)
{
throw new NotImplementedException();
}
[DebuggerNonUserCode()]
[CLSCompliant(false)]
public static void GiveJobExperience(Character target, uint experiencepoints)
{
throw new NotImplementedException();
}
[DebuggerNonUserCode()]
[CLSCompliant(false)]
public static void GiveCharacterExperience(Character target, uint experiencepoints)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a set of exp to your character.
/// </summary>
/// <param name="character"></param>
/// <param name="cexp"></param>
/// <param name="jexp"></param>
public static void Add(Character character, uint cexp, uint jexp, uint wexp)
{
byte clvl_up = 0;
byte jlvl_up = 0;
int result = 0;
GiveWeaponExperience(character, wexp);
try
{
#region Check for character-level
if (character._level + 1 <= Singleton.experience.MaxCLVL)
{
uint req_cexp = Singleton.experience.FindRequiredCexp((byte)(character._level + 1));
if (cexp > 0)
{
result |= 32;
result |= (character.Cexp + cexp >= req_cexp) ? 16 : 0;
}
}
else
{
cexp = 0;
}
#endregion Check for character-level
#region Check for job-level
if (character.jlvl + 1 <= Singleton.experience.MaxJLVL)
{
uint req_jexp = Singleton.experience.FindRequiredJexp((byte)(character.jlvl + 1));
if (jexp > 0)
{
result |= 4;
result |= (character.Jexp + jexp >= req_jexp) ? 1 : 0;
}
}
else
{
jexp = 0;
}
#endregion Check for job-level
#region Quick Lock For updates
lock (character)
{
//CALCULATE EXPERIENCE
uint newCexp = character.Cexp + cexp;
uint newJexp = character.Jexp + jexp;
//COMPUTE THE LEVEL DIFFERENCE (FORWARD ONLY)
if ((result & 1) == 1) jlvl_up = Singleton.experience.FindJlvlDifference(character.jlvl, newJexp);
if ((result & 16) == 16) clvl_up = Singleton.experience.FindClvlDifference(character._level, newCexp);
//RECALCULATE THE SP / HP ON CLVL UP
if (clvl_up > 0)
{
//CALCULATE BASE MAX HP/SP
ushort _HPMAX = Singleton.CharacterConfiguration.CalculateMaximumHP(character);
ushort _SPMAX = Singleton.CharacterConfiguration.CalculateMaximumSP(character);
//SUBSTRACT FROM CURRENT MAX HP/SP
character._status.MaxHP -= _HPMAX;
character._status.MaxSP -= _SPMAX;
//ADD CLVL'S
character._level += clvl_up;
//CALCULATE NEW BASE MAX HP/SP
ushort _HPMAX2 = Singleton.CharacterConfiguration.CalculateMaximumHP(character);
ushort _SPMAX2 = Singleton.CharacterConfiguration.CalculateMaximumSP(character);
//GENERATE STATS
character._status.MaxHP += _HPMAX2;
character._status.MaxSP += _SPMAX2;
character.stats.REMAINING += (ushort)(clvl_up * 2);
//FINALIZE SEND UPDATE
CommonFunctions.SendExtStats(character);
CommonFunctions.SendBattleStatus(character);
if (character.sessionParty != null)
{
SMSG_PARTYMEMBERCLVL spkt = new SMSG_PARTYMEMBERCLVL();
spkt.Index = 1;
spkt.ActorId = character.id;
spkt.Lp = character.jlvl;
foreach (Character target in character.sessionParty.GetCharacters())
{
spkt.SessionId = target.id;
target.client.Send((byte[])spkt);
}
}
}
if (jlvl_up > 0)
{
character.jlvl += jlvl_up;
if (character.sessionParty != null)
{
SMSG_PARTYMEMBERJLVL spkt = new SMSG_PARTYMEMBERJLVL();
spkt.Index = 1;
spkt.ActorId = character.id;
spkt.Jvl = character.jlvl;
foreach (Character target in character.sessionParty.GetCharacters())
{
spkt.SessionId = target.id;
target.client.Send((byte[])spkt);
}
}
}
//SET THE EXP
character.Cexp = newCexp;
character.Jexp = newJexp;
if (clvl_up > 0 || jlvl_up > 0)
{
//RESET HP AND SP
character.HP = character.HPMAX;
character.SP = character.SPMAX;
}
//FINALIZE SEND UPDATE
CommonFunctions.UpdateCharacterInfo(character, (byte)result);
}
#endregion Quick Lock For updates
#region Structurize Buffer
List<RelayPacket> buffer = new List<RelayPacket>();
if (clvl_up > 0)
{
//LEVEL UP CHARACTER-BASE LEVEL
SMSG_LEVELUP spkt = new SMSG_LEVELUP();
spkt.ActorID = character.id;
spkt.Levels = clvl_up;
spkt.LevelType = 1;
buffer.Add(spkt);
}
if (jlvl_up > 0)
{
//LEVEL UP CHARACTER-JOB LEVEL
SMSG_LEVELUP spkt = new SMSG_LEVELUP();
spkt.ActorID = character.id;
spkt.Levels = jlvl_up;
spkt.LevelType = 2;
buffer.Add(spkt);
}
#endregion Structurize Buffer
#region Flush all updates
foreach (MapObject c in character.currentzone.GetObjectsInRegionalRange(character))
if (MapObject.IsPlayer(c))
{
Character current = c as Character;
foreach (RelayPacket buffered_packet in buffer)
{
buffered_packet.SessionId = current.id;
current.client.Send((byte[])buffered_packet);
}
}
#endregion Flush all updates
}
catch (Exception e)
{
Trace.TraceError(e.ToString());
}
}
}
}
| |
//
// Term.cs
//
// Author:
// Gabriel Burt <gabriel.burt@gmail.com>
// Stephane Delcroix <stephane@delcroix.org>
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (C) 2007-2009 Novell, Inc.
// Copyright (C) 2007 Gabriel Burt
// Copyright (C) 2007-2009 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// This has to do with Finding photos based on tags
// http://mail.gnome.org/archives/f-spot-list/2005-November/msg00053.html
// http://bugzilla-attachments.gnome.org/attachment.cgi?id=54566
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Unix;
using Gtk;
using Hyena;
using FSpot.Core;
namespace FSpot
{
public abstract class Term
{
private Term parent = null;
protected bool is_negated = false;
protected Tag tag = null;
public Term (Term parent, Literal after)
{
this.parent = parent;
SubTerms = new List<Term> ();
if (parent != null)
if (after == null) {
parent.Add (this);
} else {
parent.SubTerms.Insert (parent.SubTerms.IndexOf (after) + 1, this);
}
}
#region Properties
public bool HasMultiple {
get {
return (SubTerms.Count > 1);
}
}
public List<Term> SubTerms { get; private set; }
/// <summary>
/// Returns the last Literal in term
/// </summary>
/// <value>
/// last Literal in term, else null
/// </value>
public Term Last {
get
{
return SubTerms.Count > 0 ? SubTerms [SubTerms.Count - 1] : null;
}
}
public int Count {
get {
return SubTerms.Count;
}
}
public Term Parent {
get { return parent; }
set {
if (parent == value)
return;
// If our parent was already set, remove ourself from it
if (parent != null)
parent.Remove (this);
// Add ourself to our new parent
parent = value;
parent.Add (this);
}
}
public virtual bool IsNegated {
get { return is_negated; }
set {
if (is_negated != value)
Invert (false);
is_negated = value;
}
}
#endregion
#region Methods
public void Add (Term term)
{
SubTerms.Add (term);
}
public void Remove (Term term)
{
SubTerms.Remove (term);
// Remove ourselves if we're now empty
if (SubTerms.Count == 0 && Parent != null)
Parent.Remove (this);
}
public void CopyAndInvertSubTermsFrom (Term term, bool recurse)
{
is_negated = true;
List<Term> termsToMove = new List<Term> (term.SubTerms);
foreach (Term subterm in termsToMove) {
if (recurse)
subterm.Invert (true).Parent = this;
else
subterm.Parent = this;
}
}
public List<Term> FindByTag (Tag t)
{
return FindByTag (t, true);
}
public List<Term> FindByTag (Tag t, bool recursive)
{
List<Term> results = new List<Term> ();
if (tag != null && tag == t)
results.Add (this);
if (recursive)
foreach (Term term in SubTerms) {
results.AddRange (term.FindByTag (t, true));
}
else
foreach (Term term in SubTerms) {
foreach (Term literal in SubTerms) {
if (literal.tag != null && literal.tag == t) {
results.Add (literal);
}
}
if (term.tag != null && term.tag == t) {
results.Add (term);
}
}
return results;
}
public List<Term> LiteralParents ()
{
List<Term> results = new List<Term> ();
bool meme = false;
foreach (Term term in SubTerms) {
if (term is Literal)
meme = true;
results.AddRange (term.LiteralParents ());
}
if (meme)
results.Add (this);
return results;
}
public bool TagIncluded (Tag t)
{
List<Term> parents = LiteralParents ();
if (parents.Count == 0)
return false;
foreach (Term term in parents) {
bool termHasTag = false;
bool onlyTerm = true;
foreach (Term literal in term.SubTerms) {
if (literal.tag != null)
if (literal.tag == t) {
termHasTag = true;
} else {
onlyTerm = false;
}
}
if (termHasTag && onlyTerm)
return true;
}
return false;
}
public bool TagRequired (Tag t)
{
int count, grouped_with;
return TagRequired (t, out count, out grouped_with);
}
public bool TagRequired (Tag t, out int num_terms, out int grouped_with)
{
List<Term> parents = LiteralParents ();
num_terms = 0;
grouped_with = 100;
int min_grouped_with = 100;
if (parents.Count == 0)
return false;
foreach (Term term in parents) {
bool termHasTag = false;
// Don't count it as required if it's the only subterm..though it is..
// it is more clearly identified as Included at that point.
if (term.Count > 1)
foreach (Term literal in term.SubTerms) {
if (literal.tag != null) {
if (literal.tag == t) {
num_terms++;
termHasTag = true;
grouped_with = term.SubTerms.Count;
break;
}
}
}
if (grouped_with < min_grouped_with)
min_grouped_with = grouped_with;
if (!termHasTag)
return false;
}
grouped_with = min_grouped_with;
return true;
}
public abstract Term Invert (bool recurse);
/// <summary>
/// Recursively generate the SQL condition clause that this term represents.
/// </summary>
/// <returns>
/// The condition string
/// </returns>
public virtual string SqlCondition ()
{
StringBuilder condition = new StringBuilder ("(");
for (int i = 0; i < SubTerms.Count; i++) {
Term term = SubTerms [i];
condition.Append (term.SqlCondition ());
if (i != SubTerms.Count - 1)
condition.Append (SQLOperator ());
}
condition.Append (")");
return condition.ToString ();
}
public virtual Gtk.Widget SeparatorWidget ()
{
return null;
}
public virtual string SQLOperator ()
{
return String.Empty;
}
public static Term TermFromOperator (string op, Term parent, Literal after)
{
//Console.WriteLine ("finding type for operator {0}", op);
//op = op.Trim ();
op = op.ToLower ();
if (AndTerm.Operators.Contains (op))
//Console.WriteLine ("AND!");
return new AndTerm (parent, after);
if (OrTerm.Operators.Contains (op))
//Console.WriteLine ("OR!");
return new OrTerm (parent, after);
Log.DebugFormat ("Do not have Term for operator {0}", op);
return null;
}
#endregion
}
public class AndTerm : Term
{
public static List<string> Operators { get; private set; }
static AndTerm ()
{
Operators = new List<string> ();
Operators.Add (Catalog.GetString (" and "));
//Operators.Add (Catalog.GetString (" && "));
Operators.Add (Catalog.GetString (", "));
}
public AndTerm (Term parent, Literal after) : base (parent, after)
{
}
public override Term Invert (bool recurse)
{
OrTerm newme = new OrTerm (Parent, null);
newme.CopyAndInvertSubTermsFrom (this, recurse);
if (Parent != null)
Parent.Remove (this);
return newme;
}
public override Widget SeparatorWidget ()
{
Widget separator = new Label (String.Empty);
separator.SetSizeRequest (3, 1);
separator.Show ();
return separator;
}
public override string SqlCondition ()
{
StringBuilder condition = new StringBuilder ("(");
condition.Append (base.SqlCondition ());
Tag hidden = App.Instance.Database.Tags.Hidden;
if (hidden != null)
if (FindByTag (hidden, true).Count == 0) {
condition.Append (String.Format (
" AND id NOT IN (SELECT photo_id FROM photo_tags WHERE tag_id = {0})", hidden.Id
));
}
condition.Append (")");
return condition.ToString ();
}
public override string SQLOperator ()
{
return " AND ";
}
}
public class OrTerm : Term
{
public static List<string> Operators { get; private set; }
static OrTerm ()
{
Operators = new List<string> ();
Operators.Add (Catalog.GetString (" or "));
//Operators.Add (Catalog.GetString (" || "));
}
public OrTerm (Term parent, Literal after) : base (parent, after)
{
}
public static OrTerm FromTags (Tag [] from_tags)
{
if (from_tags == null || from_tags.Length == 0)
return null;
OrTerm or = new OrTerm (null, null);
foreach (Literal l in from_tags.Select(t => new Literal (t)))
{
l.Parent = or;
}
return or;
}
private static string OR = Catalog.GetString ("or");
public override Term Invert (bool recurse)
{
AndTerm newme = new AndTerm (Parent, null);
newme.CopyAndInvertSubTermsFrom (this, recurse);
if (Parent != null)
Parent.Remove (this);
return newme;
}
public override Gtk.Widget SeparatorWidget ()
{
Widget label = new Label (" " + OR + " ");
label.Show ();
return label;
}
public override string SQLOperator ()
{
return " OR ";
}
}
}
| |
//
// 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.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.DataFactories.Core;
using Microsoft.Azure.Management.DataFactories.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.DataFactories.Core
{
/// <summary>
/// Operations for managing data factories.
/// </summary>
internal partial class DataFactoryOperations : IServiceOperations<DataFactoryManagementClient>, IDataFactoryOperations
{
/// <summary>
/// Initializes a new instance of the DataFactoryOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DataFactoryOperations(DataFactoryManagementClient client)
{
this._client = client;
}
private DataFactoryManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.DataFactories.Core.DataFactoryManagementClient.
/// </summary>
public DataFactoryManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create or update a data factory.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a data
/// factory.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The create or update data factory operation response.
/// </returns>
public async Task<DataFactoryCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, DataFactoryCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.DataFactory != null)
{
if (parameters.DataFactory.Location == null)
{
throw new ArgumentNullException("parameters.DataFactory.Location");
}
if (parameters.DataFactory.Name == null)
{
throw new ArgumentNullException("parameters.DataFactory.Name");
}
if (parameters.DataFactory.Name != null && parameters.DataFactory.Name.Length > 63)
{
throw new ArgumentOutOfRangeException("parameters.DataFactory.Name");
}
if (Regex.IsMatch(parameters.DataFactory.Name, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false)
{
throw new ArgumentOutOfRangeException("parameters.DataFactory.Name");
}
}
// 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("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", 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/Microsoft.DataFactory/datafactories/";
if (parameters.DataFactory != null && parameters.DataFactory.Name != null)
{
url = url + Uri.EscapeDataString(parameters.DataFactory.Name);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-08-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject dataFactoryCreateOrUpdateParametersValue = new JObject();
requestDoc = dataFactoryCreateOrUpdateParametersValue;
if (parameters.DataFactory != null)
{
if (parameters.DataFactory.Id != null)
{
dataFactoryCreateOrUpdateParametersValue["id"] = parameters.DataFactory.Id;
}
dataFactoryCreateOrUpdateParametersValue["name"] = parameters.DataFactory.Name;
dataFactoryCreateOrUpdateParametersValue["location"] = parameters.DataFactory.Location;
if (parameters.DataFactory.Tags != null)
{
if (parameters.DataFactory.Tags is ILazyCollection == false || ((ILazyCollection)parameters.DataFactory.Tags).IsInitialized)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.DataFactory.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
dataFactoryCreateOrUpdateParametersValue["tags"] = tagsDictionary;
}
}
if (parameters.DataFactory.Properties != null)
{
JObject propertiesValue = new JObject();
dataFactoryCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.DataFactory.Properties.ProvisioningState != null)
{
propertiesValue["provisioningState"] = parameters.DataFactory.Properties.ProvisioningState;
}
if (parameters.DataFactory.Properties.ErrorMessage != null)
{
propertiesValue["errorMessage"] = parameters.DataFactory.Properties.ErrorMessage;
}
if (parameters.DataFactory.Properties.DataFactoryId != null)
{
propertiesValue["dataFactoryId"] = parameters.DataFactory.Properties.DataFactoryId;
}
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
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
DataFactoryCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DataFactoryCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DataFactory dataFactoryInstance = new DataFactory();
result.DataFactory = dataFactoryInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dataFactoryInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dataFactoryInstance.Name = nameInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
dataFactoryInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
dataFactoryInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
DataFactoryProperties propertiesInstance = new DataFactoryProperties();
dataFactoryInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue2["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken errorMessageValue = propertiesValue2["errorMessage"];
if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null)
{
string errorMessageInstance = ((string)errorMessageValue);
propertiesInstance.ErrorMessage = errorMessageInstance;
}
JToken dataFactoryIdValue = propertiesValue2["dataFactoryId"];
if (dataFactoryIdValue != null && dataFactoryIdValue.Type != JTokenType.Null)
{
string dataFactoryIdInstance = ((string)dataFactoryIdValue);
propertiesInstance.DataFactoryId = dataFactoryIdInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
result.Location = url;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create or update a data factory.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a data
/// factory.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The create or update data factory operation response.
/// </returns>
public async Task<DataFactoryCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, DataFactoryCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
DataFactoryManagementClient client = this.Client;
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("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
DataFactoryCreateOrUpdateResponse response = await client.DataFactories.BeginCreateOrUpdateAsync(resourceGroupName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
DataFactoryCreateOrUpdateResponse result = await client.DataFactories.GetCreateOrUpdateStatusAsync(response.Location, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 5;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.DataFactories.GetCreateOrUpdateStatusAsync(response.Location, cancellationToken).ConfigureAwait(false);
delayInSeconds = 5;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Delete a data factory instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </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 dataFactoryName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
if (dataFactoryName != null && dataFactoryName.Length > 63)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
// 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("dataFactoryName", dataFactoryName);
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/Microsoft.DataFactory/datafactories/";
url = url + Uri.EscapeDataString(dataFactoryName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-08-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// 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 a data factory instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get data factory operation response.
/// </returns>
public async Task<DataFactoryGetResponse> GetAsync(string resourceGroupName, string dataFactoryName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
if (dataFactoryName != null && dataFactoryName.Length > 63)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
// 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("dataFactoryName", dataFactoryName);
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/Microsoft.DataFactory/datafactories/";
url = url + Uri.EscapeDataString(dataFactoryName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-08-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// 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
DataFactoryGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DataFactoryGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DataFactory dataFactoryInstance = new DataFactory();
result.DataFactory = dataFactoryInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dataFactoryInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dataFactoryInstance.Name = nameInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
dataFactoryInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
dataFactoryInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DataFactoryProperties propertiesInstance = new DataFactoryProperties();
dataFactoryInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken errorMessageValue = propertiesValue["errorMessage"];
if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null)
{
string errorMessageInstance = ((string)errorMessageValue);
propertiesInstance.ErrorMessage = errorMessageInstance;
}
JToken dataFactoryIdValue = propertiesValue["dataFactoryId"];
if (dataFactoryIdValue != null && dataFactoryIdValue.Type != JTokenType.Null)
{
string dataFactoryIdInstance = ((string)dataFactoryIdValue);
propertiesInstance.DataFactoryId = dataFactoryIdInstance;
}
}
}
}
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>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The create or update data factory operation response.
/// </returns>
public async Task<DataFactoryCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetCreateOrUpdateStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
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("x-ms-client-request-id", Guid.NewGuid().ToString());
httpRequest.Headers.Add("x-ms-version", "2015-08-01");
// 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
DataFactoryCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DataFactoryCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DataFactory dataFactoryInstance = new DataFactory();
result.DataFactory = dataFactoryInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dataFactoryInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dataFactoryInstance.Name = nameInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
dataFactoryInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
dataFactoryInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DataFactoryProperties propertiesInstance = new DataFactoryProperties();
dataFactoryInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken errorMessageValue = propertiesValue["errorMessage"];
if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null)
{
string errorMessageInstance = ((string)errorMessageValue);
propertiesInstance.ErrorMessage = errorMessageInstance;
}
JToken dataFactoryIdValue = propertiesValue["dataFactoryId"];
if (dataFactoryIdValue != null && dataFactoryIdValue.Type != JTokenType.Null)
{
string dataFactoryIdInstance = ((string)dataFactoryIdValue);
propertiesInstance.DataFactoryId = dataFactoryIdInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
result.Location = url;
if (result.DataFactory != null && result.DataFactory.Properties != null && result.DataFactory.Properties.ProvisioningState == "Failed")
{
result.Status = OperationStatus.Failed;
}
if (result.DataFactory != null && result.DataFactory.Properties != null && result.DataFactory.Properties.ProvisioningState == "Succeeded")
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the first page of data factory instances with the link to the
/// next page.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factories.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List data factories operation response.
/// </returns>
public async Task<DataFactoryListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
// 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);
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/Microsoft.DataFactory/datafactories";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-08-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// 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
DataFactoryListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DataFactoryListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DataFactory dataFactoryInstance = new DataFactory();
result.DataFactories.Add(dataFactoryInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dataFactoryInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dataFactoryInstance.Name = nameInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
dataFactoryInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
dataFactoryInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DataFactoryProperties propertiesInstance = new DataFactoryProperties();
dataFactoryInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken errorMessageValue = propertiesValue["errorMessage"];
if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null)
{
string errorMessageInstance = ((string)errorMessageValue);
propertiesInstance.ErrorMessage = errorMessageInstance;
}
JToken dataFactoryIdValue = propertiesValue["dataFactoryId"];
if (dataFactoryIdValue != null && dataFactoryIdValue.Type != JTokenType.Null)
{
string dataFactoryIdInstance = ((string)dataFactoryIdValue);
propertiesInstance.DataFactoryId = dataFactoryIdInstance;
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.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>
/// Gets the next page of data factory instances with the link to the
/// next page.
/// </summary>
/// <param name='nextLink'>
/// Required. The url to the next data factories page.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List data factories operation response.
/// </returns>
public async Task<DataFactoryListResponse> 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
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// 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
DataFactoryListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DataFactoryListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DataFactory dataFactoryInstance = new DataFactory();
result.DataFactories.Add(dataFactoryInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dataFactoryInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dataFactoryInstance.Name = nameInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
dataFactoryInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
dataFactoryInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DataFactoryProperties propertiesInstance = new DataFactoryProperties();
dataFactoryInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken errorMessageValue = propertiesValue["errorMessage"];
if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null)
{
string errorMessageInstance = ((string)errorMessageValue);
propertiesInstance.ErrorMessage = errorMessageInstance;
}
JToken dataFactoryIdValue = propertiesValue["dataFactoryId"];
if (dataFactoryIdValue != null && dataFactoryIdValue.Type != JTokenType.Null)
{
string dataFactoryIdInstance = ((string)dataFactoryIdValue);
propertiesInstance.DataFactoryId = dataFactoryIdInstance;
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.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();
}
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.UI.Xaml;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Rooijakkers.MeditationTimer.Data.Contracts;
using Rooijakkers.MeditationTimer.Messages;
using Rooijakkers.MeditationTimer.Model;
namespace Rooijakkers.MeditationTimer.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class TimerViewModel : ViewModelBase
{
private static readonly TimeSpan OneSecond = new TimeSpan(0, 0, 1);
// While debugging we want 10 seconds to last 5 times as short
#if DEBUG
private static readonly TimeSpan TenSeconds = new TimeSpan(0, 0, 2);
#else
private static readonly TimeSpan TenSeconds = new TimeSpan(0, 0, 10);
#endif
private static readonly TimeSpan FiveMinutes = new TimeSpan(0, 5, 0);
private static readonly TimeSpan TenMinutes = new TimeSpan(0, 10, 0);
private readonly IMeditationDiaryRepository _repository;
private readonly ISettings _settings;
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public TimerViewModel(IMeditationDiaryRepository repository, ISettings settings)
{
if (repository == null)
{
throw new ArgumentNullException(nameof(repository));
}
_repository = repository;
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
_settings = settings;
StartTimerCommand = new RelayCommand(StartTimer);
StopTimerCommand = new RelayCommand(StopTimer);
AddFiveMinutesCommand = new RelayCommand(AddFiveMinutes);
ResetInitialTimeCommand = new RelayCommand(ResetInitialTime);
InitializeDispatcherTimer();
CountdownTimerValue = InitialMeditationTime;
}
private void InitializeDispatcherTimer()
{
DispatcherTimer = new DispatcherTimer
{
Interval = OneSecond
};
DispatcherTimer.Tick += TimerTick;
DispatcherTimer.Tick += (s, e) =>
RingBellOnMoment(InitialMeditationTime, TimeSpan.Zero);
DispatcherTimer.Tick += (s, e) =>
PlayNotificationSoundOnMoments(TimeSpan.Zero.Add(FiveMinutes));
DispatcherTimer.Tick += StopTimerOnEnd;
DispatcherTimer.Tick += DisplaySitReadyMessageAtBegin;
}
public ICommand StartTimerCommand { get; private set; }
public ICommand StopTimerCommand { get; private set; }
public ICommand AddFiveMinutesCommand { get; private set; }
public ICommand ResetInitialTimeCommand { get; private set; }
public DispatcherTimer DispatcherTimer { get; private set; }
private TimeSpan _initialMeditationTime;
public TimeSpan InitialMeditationTime
{
get
{
if (_initialMeditationTime == default(TimeSpan))
{
_initialMeditationTime = TenMinutes;
}
return _initialMeditationTime;
}
set
{
_initialMeditationTime = value;
}
}
private TimeSpan _countdownTimerValue;
public TimeSpan CountdownTimerValue
{
get
{
RaisePropertyChanged(nameof(TimerText));
return _countdownTimerValue;
}
set
{
_countdownTimerValue = value;
RaisePropertyChanged(nameof(TimerText));
}
}
// Ensure TimeMeditated is not a negative value if there is meditated for less than the
// time to sit ready
public TimeSpan TimeMeditated => CountdownTimerValue < InitialMeditationTime
? InitialMeditationTime.Subtract(CountdownTimerValue)
: TimeSpan.Zero;
public bool MeditatedForLongerThanTimeToSitReady => TimeMeditated > TimeSpan.Zero;
public string TimerText
{
get
{
var totalMinutes = (int)CountdownTimerValue.TotalMinutes;
var seconds = CountdownTimerValue.Seconds % 60;
var minutesText = totalMinutes < 10 ? "0" + totalMinutes : totalMinutes.ToString();
var secondsText = seconds < 10 ? "0" + seconds : seconds.ToString();
return minutesText + ":" + secondsText;
}
}
private void StartTimer()
{
CountdownTimerValue = CountdownTimerValue += _settings.TimeToGetReady;
DispatcherTimer.Start();
Messenger.Default.Send(new StartTimerMessage());
}
private void StopTimer()
{
if (MeditatedForLongerThanTimeToSitReady)
{
AddMeditationEntry();
Messenger.Default.Send(new UpdateDiaryMessage());
}
CountdownTimerValue = InitialMeditationTime;
DispatcherTimer.Stop();
Messenger.Default.Send(new StopTimerMessage());
Messenger.Default.Send(new DisplaySitReadyMessage(false));
}
private void ResetInitialTime()
{
InitialMeditationTime = TenMinutes;
CountdownTimerValue = TenMinutes;
}
private void AddMeditationEntry()
{
var meditationEntry = new MeditationEntry
{
StartTime = DateTime.Now.Subtract(TimeMeditated),
TimeMeditated = TimeMeditated
};
var task = Task.Run(async () =>
{
await _repository.AddEntryAsync(meditationEntry);
});
task.Wait();
}
private void AddFiveMinutes()
{
InitialMeditationTime += FiveMinutes;
CountdownTimerValue += FiveMinutes;
}
private void TimerTick(object sender, object e)
{
CountdownTimerValue = CountdownTimerValue.Subtract(OneSecond);
}
private void DisplaySitReadyMessageAtBegin(object sender, object e)
{
Messenger.Default.Send(CountdownTimerValue > InitialMeditationTime
? new DisplaySitReadyMessage(true)
: new DisplaySitReadyMessage(false));
}
private void RingBellOnMoment(params TimeSpan[] moments)
{
if (moments.Contains(CountdownTimerValue))
{
RingBell();
}
}
private void PlayNotificationSoundOnMoments(params TimeSpan[] moments)
{
// We need to check the setting every time, since it might have changed.
// There is probably a cleaner way to do it, but the performance penalty is minimal.
if (_settings.NotificationBeforeEnd && moments.Contains(CountdownTimerValue))
{
PlayNotificationSound();
}
}
private void StopTimerOnEnd(object sender, object e)
{
if (CountdownTimerValue == TimeSpan.Zero)
{
StopTimer();
}
}
private void RingBell()
{
Messenger.Default.Send(new PlayMessage(_settings.BellSound));
}
private void PlayNotificationSound()
{
Messenger.Default.Send(new PlayNotificationMessage(_settings.NotificationSound));
}
}
}
| |
using OpenTK;
using SageCS.Graphics;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// TODO:
// fix the ReadString method
// unknown chunks:
// 64 size of 4 bytes
// 96 vertex normals for bump mapping? (specular and diffuse normals)
// 97 vertex normals for bump mapping? (specular and diffuse normals)
namespace SageCS.Core.Loaders
{
class W3DLoader
{
private static string modelName = "";
private static Model model;
private static string hierarchyName = "";
private static Hierarchy hierarchy;
private static W3DMesh mesh;
private static string texName = "";
private static string matName = "";
//######################################################################################
//# structs
//######################################################################################
struct Version
{
public long major;
public long minor;
}
//######################################################################################
//# basic methods
//######################################################################################
private static string ReadString(BinaryReader br)
{
List<byte> data = new List<byte>();
byte b = br.ReadByte();
while (b != 0)
{
data.Add(b);
b = br.ReadByte();
}
return System.Text.Encoding.UTF8.GetString(data.ToArray<byte>());
}
private static string ReadFixedString(BinaryReader br)
{
byte[] data = br.ReadBytes(16);
return System.Text.Encoding.UTF8.GetString(data);
}
private static string ReadLongFixedString(BinaryReader br)
{
byte[] data = br.ReadBytes(32);
return System.Text.Encoding.UTF8.GetString(data);
}
private static Vector4 ReadRGBA(BinaryReader br)
{
return new Vector4(br.ReadByte(), br.ReadByte(), br.ReadByte(), br.ReadByte());
}
private static uint getChunkSize(uint data)
{
return (data & 0x7FFFFFFF);
}
private static uint ReadLong(BinaryReader br)
{
return br.ReadUInt32();
}
private static uint[] ReadLongArray(BinaryReader br, uint ChunkEnd)
{
List<uint> data = new List<uint>();
while (br.BaseStream.Position < ChunkEnd)
{
data.Add(ReadLong(br));
}
return data.ToArray();
}
private static uint ReadShort(BinaryReader br)
{
return br.ReadUInt16();
}
private static float ReadFloat(BinaryReader br)
{
return (float)br.ReadSingle();
}
private static byte ReadByte(BinaryReader br)
{
return br.ReadByte();
}
private static Vector3 ReadVector(BinaryReader br)
{
return new Vector3(ReadFloat(br), ReadFloat(br), ReadFloat(br));
}
private static Quaternion ReadQuaternion(BinaryReader br)
{
return new Quaternion(ReadFloat(br), ReadFloat(br), ReadFloat(br), ReadFloat(br));
}
private static Version GetVersion(long data)
{
Version v = new Version();
v.major = data >> 16;
v.minor = data & 0xFFFF;
return v;
}
//#######################################################################################
//# Hierarchy
//#######################################################################################
private static void ReadHierarchyHeader(BinaryReader br)
{
Version version = GetVersion(ReadLong(br));
hierarchyName = ReadFixedString(br);
long pivotCount = ReadLong(br);
Vector3 centerPos = ReadVector(br);
hierarchy = new Hierarchy(pivotCount, centerPos);
}
private static void ReadPivots(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
string name = ReadFixedString(br);
long parentID = ReadLong(br);
Vector3 position = ReadVector(br);
Vector3 eulerAngles = ReadVector(br);
Quaternion rotation = ReadQuaternion(br);
hierarchy.addPivot(name, parentID, position, eulerAngles, rotation);
}
}
private static void ReadPivotFixups(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
Vector3 pivot_fixup = ReadVector(br);
}
}
private static void ReadHierarchy(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 257:
ReadHierarchyHeader(br);
break;
case 258:
ReadPivots(br, subChunkEnd);
break;
case 259:
ReadPivotFixups(br, subChunkEnd);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in Hierarchy");
br.ReadBytes((int)Chunksize);
break;
}
}
Hierarchy.AddHierarchy(hierarchyName, hierarchy);
}
//#######################################################################################
//# Animation
//#######################################################################################
private static void ReadAnimationHeader(BinaryReader br)
{
Version version = GetVersion(ReadLong(br));
string name = ReadFixedString(br);
string hieraName = ReadFixedString(br);
long numFrames = ReadLong(br);
long frameRate = ReadLong(br);
}
private static void ReadAnimationChannel(BinaryReader br, uint ChunkEnd)
{
uint firstFrame = ReadShort(br);
uint lastFrame = ReadShort(br);
uint vectorLen = ReadShort(br);
uint type = ReadShort(br);
uint pivot = ReadShort(br);
uint pad = ReadShort(br);
switch (vectorLen)
{
case 1:
while (br.BaseStream.Position < ChunkEnd)
{
ReadFloat(br);
}
break;
case 4:
while (br.BaseStream.Position < ChunkEnd)
{
ReadQuaternion(br);
}
break;
default:
Console.WriteLine("invalid vector len: " + vectorLen + "in AnimationChannel");
while (br.BaseStream.Position < ChunkEnd)
{
ReadByte(br);
}
break;
}
}
private static void ReadAnimation(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 513:
ReadAnimationHeader(br);
break;
case 514:
ReadAnimationChannel(br, subChunkEnd);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in Animation");
br.ReadBytes((int)Chunksize);
break;
}
}
}
private static void ReadCompressedAnimationHeader(BinaryReader br)
{
Version version = GetVersion(ReadLong(br));
string name = ReadFixedString(br);
string hieraName = ReadFixedString(br);
long numFrames = ReadLong(br);
uint frameRate = ReadShort(br);
uint flavor = ReadShort(br);
}
private static void ReadTimeCodedAnimationChannel(BinaryReader br, uint ChunkEnd)
{
long TimeCodesCount = ReadLong(br);
uint Pivot = ReadShort(br);
byte VectorLen = ReadByte(br);
byte Type = ReadByte(br);
while (br.BaseStream.Position < ChunkEnd)
{
long frame = ReadLong(br);
if (Type == 6)
ReadQuaternion(br);
else
ReadFloat(br);
}
}
private static void ReadTimeCodedAnimationVector(BinaryReader br, uint ChunkEnd)
{
// A time code is a uint32 that prefixes each vector
// the MSB is used to indicate a binary (non interpolated) movement
uint magigNum = ReadShort(br); //0 or 256 or 512 -> interpolation type? /compression of the Q-Channels? (0, 256, 512) -> (0, 8, 16 bit)
byte vectorLen = ReadByte(br);
byte flag = ReadByte(br); //is x or y or z or quat
uint timeCodesCount = ReadShort(br);
uint pivot = ReadShort(br);
// will be (NumTimeCodes * ((VectorLen * 4) + 4)) -> works if the magic num is 0
// so only the Q-Channels are compressed?
switch (vectorLen)
{
case 1:
while (br.BaseStream.Position < ChunkEnd)
{
ReadByte(br);
}
break;
case 4:
while (br.BaseStream.Position < ChunkEnd)
{
ReadByte(br);
}
break;
default:
Console.WriteLine("invalid vector len: " + vectorLen + "in TimeCodedAnimVector");
while (br.BaseStream.Position < ChunkEnd)
{
ReadByte(br);
}
break;
}
}
private static void ReadCompressedAnimation(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
/*
case 641:
ReadCompressedAnimationHeader(br);
break;
case 642:
ReadTimeCodedAnimationChannel(br, subChunkEnd);
break;
*/
case 643:
Console.WriteLine("chunk 643!!!");
br.ReadBytes((int)Chunksize);
break;
/*
case 644:
ReadTimeCodedAnimationVector(br, subChunkEnd);
break;
*/
default:
//Console.WriteLine("unknown chunktype: " + Chunktype + " in CompressedAnimation");
br.ReadBytes((int)Chunksize);
break;
}
}
}
//#######################################################################################
//# HLod
//#######################################################################################
private static void ReadHLodHeader(BinaryReader br)
{
Version version = GetVersion(ReadLong(br));
long lodCount = ReadLong(br);
string modelName = ReadFixedString(br);
string HTreeName = ReadFixedString(br);
}
private static void ReadHLodArrayHeader(BinaryReader br)
{
long modelCount = ReadLong(br);
float maxScreenSize = ReadFloat(br);
}
private static void ReadHLodSubObject(BinaryReader br)
{
long boneIndex = ReadLong(br);
string name = ReadLongFixedString(br);
}
private static void ReadHLodArray(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 1795:
ReadHLodArrayHeader(br);
break;
case 1796:
ReadHLodSubObject(br);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in HLodArray");
br.ReadBytes((int)Chunksize);
break;
}
}
}
private static void ReadHLod(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 1793:
ReadHLodHeader(br);
break;
case 1794:
ReadHLodArray(br, subChunkEnd);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in HLod");
br.ReadBytes((int)Chunksize);
break;
}
}
}
//#######################################################################################
//# Box
//#######################################################################################
private static void ReadBox(BinaryReader br)
{
Model.Box box = new Model.Box();
Version version = GetVersion(ReadLong(br));
long attributes = ReadLong(br);
string name = ReadLongFixedString(br);
Vector4 color = ReadRGBA(br);
box.center = ReadVector(br);
box.extend = ReadVector(br);
model.box = box;
}
//#######################################################################################
//# Texture
//#######################################################################################
private static void ReadTexture(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
W3DMesh.Texture tex = new W3DMesh.Texture();
switch (Chunktype)
{
case 50:
texName = ReadString(br);
tex.type = W3DMesh.textureType.standard;
break;
case 51:
tex.attributes = ReadShort(br);
tex.animType = ReadShort(br);
tex.frameCount = ReadLong(br);
tex.frameRate = ReadFloat(br);
tex.type = W3DMesh.textureType.animated;
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshTexture");
br.ReadBytes((int)Chunksize);
break;
}
mesh.textures.Add(texName, tex);
}
}
private static void ReadTextureArray(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 49:
ReadTexture(br, subChunkEnd);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshTextureArray");
br.ReadBytes((int)Chunksize);
break;
}
}
}
//#######################################################################################
//# Material
//#######################################################################################
private static void ReadMeshTextureCoordArray(BinaryReader br, uint ChunkEnd)
{
List<Vector2> txCoords = new List<Vector2>();
while (br.BaseStream.Position < ChunkEnd)
{
txCoords.Add(new Vector2(ReadFloat(br), ReadFloat(br)));
}
mesh.texCoords.Add(txCoords.ToArray<Vector2>());
}
private static void ReadMeshTextureStage(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 73:
//texture ids
ReadLongArray(br, subChunkEnd);
break;
case 74:
ReadMeshTextureCoordArray(br, subChunkEnd);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshTextureStage");
br.ReadBytes((int)Chunksize);
break;
}
}
}
private static void ReadMeshMaterialPass(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 57:
//vertex material ids
ReadLongArray(br, subChunkEnd);
break;
case 58:
//shader ids
ReadLongArray(br, subChunkEnd);
break;
case 59:
//vertex colors
//do nothing with them
br.ReadBytes((int)Chunksize);
break;
case 63:
//unknown chunk
//size seems to be always 4
br.ReadBytes((int)Chunksize);
break;
case 72:
ReadMeshTextureStage(br, subChunkEnd);
break;
case 74:
ReadMeshTextureCoordArray(br, subChunkEnd);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshMaterialPass");
br.ReadBytes((int)Chunksize);
break;
}
}
}
private static void ReadMaterial(BinaryReader br, uint ChunkEnd)
{
W3DMesh.Material mat = new W3DMesh.Material();
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 44:
matName = ReadString(br);
break;
case 45:
mat.vmAttributes = ReadLong(br);
mat.ambient = ReadRGBA(br);
mat.diffuse = ReadRGBA(br);
mat.specular = ReadRGBA(br);
mat.emissive = ReadRGBA(br);
mat.shininess = ReadFloat(br);
mat.opacity = ReadFloat(br);
mat.translucency = ReadFloat(br);
break;
case 46:
mat.vmArgs0 = ReadString(br);
break;
case 47:
mat.vmArgs1 = ReadString(br);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshMaterial");
br.ReadBytes((int)Chunksize);
break;
}
}
mesh.materials.Add(matName, mat);
}
private static void ReadMeshMaterialArray(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 43:
ReadMaterial(br, subChunkEnd);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshMaterialArray");
br.ReadBytes((int)Chunksize);
break;
}
}
}
//#######################################################################################
//# Vertices
//#######################################################################################
private static Vector3[] ReadMeshVerticesArray(BinaryReader br, uint ChunkEnd)
{
List<Vector3> vecs = new List<Vector3>();
while (br.BaseStream.Position < ChunkEnd)
{
vecs.Add(ReadVector(br));
}
return vecs.ToArray<Vector3>();
}
private static void ReadMeshVertexInfluences(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint boneIdx = ReadShort(br);
uint xtraIdx = ReadShort(br);
uint boneInf = ReadShort(br)/100;
uint xtraInf = ReadShort(br)/100;
}
}
//#######################################################################################
//# Faces
//#######################################################################################
private static void ReadMeshFaceArray(BinaryReader br, uint ChunkEnd)
{
List<uint> vertIds = new List<uint>();
while (br.BaseStream.Position < ChunkEnd)
{
vertIds.Add(ReadLong(br));
vertIds.Add(ReadLong(br));
vertIds.Add(ReadLong(br));
uint attrs = ReadLong(br);
Vector3 normal = ReadVector(br);
float distance = ReadFloat(br);
}
mesh.vertIDs = vertIds.ToArray<uint>();
}
//#######################################################################################
//# Shader
//#######################################################################################
private static void ReadMeshShaderArray(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
W3DMesh.Shader shader = new W3DMesh.Shader();
shader.depthCompare = ReadByte(br);
shader.depthMask = ReadByte(br);
shader.colorMask = ReadByte(br);
shader.destBlend = ReadByte(br);
shader.fogFunc = ReadByte(br);
shader.priGradient = ReadByte(br);
shader.secGradient = ReadByte(br);
shader.srcBlend = ReadByte(br);
shader.texturing = ReadByte(br);
shader.detailColorFunc = ReadByte(br);
shader.detailAlphaFunc = ReadByte(br);
shader.shaderPreset = ReadByte(br);
shader.alphaTest = ReadByte(br);
shader.postDetailColorFunc = ReadByte(br);
shader.postDetailAlphaFunc = ReadByte(br);
byte pad = ReadByte(br);
mesh.shaders.Add(shader);
}
}
//#######################################################################################
//# Bump Maps
//#######################################################################################
private static void ReadNormalMapHeader(BinaryReader br)
{
byte number = ReadByte(br);
string typeName = ReadLongFixedString(br);
long reserved = ReadLong(br);
}
private static void ReadNormalMapEntryStruct(BinaryReader br, uint ChunkEnd, W3DMesh.Texture tex)
{
long type = ReadLong(br); //1 texture, 2 bumpScale/ specularExponent, 5 color, 7 alphaTest
long size = ReadLong(br);
string name = ReadString(br);
switch (name)
{
case "DiffuseTexture":
long unknown = ReadLong(br);
texName = ReadString(br);
break;
case "NormalMap":
long unknown_nrm = ReadLong(br);
tex.normalMap = ReadString(br);
break;
case "BumpScale":
tex.bumpScale = ReadFloat(br);
break;
case "AmbientColor":
tex.ambientColor = ReadRGBA(br);
break;
case "DiffuseColor":
tex.diffuseColor = ReadRGBA(br);
break;
case "SpecularColor":
tex.specularColor = ReadRGBA(br);
break;
case "SpecularExponent":
tex.specularExponent = ReadFloat(br);
break;
case "AlphaTestEnable":
tex.alphaTestEnable = ReadByte(br);
break;
default:
//Console.WriteLine("##W3D: unknown entryStruct: " + name + " in MeshNormalMapEntryStruct (size: " + size + ")");
while (br.BaseStream.Position < ChunkEnd)
ReadByte(br);
break;
}
}
private static void ReadNormalMap(BinaryReader br, uint ChunkEnd)
{
W3DMesh.Texture tex = new W3DMesh.Texture();
tex.type = W3DMesh.textureType.bumpMapped;
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 82:
ReadNormalMapHeader(br);
break;
case 83:
ReadNormalMapEntryStruct(br, subChunkEnd, tex);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshNormalMap");
br.ReadBytes((int)Chunksize);
break;
}
}
mesh.textures.Add(texName, tex);
}
private static void ReadBumpMapArray(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 81:
ReadNormalMap(br, subChunkEnd);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshBumpMapArray");
br.ReadBytes((int)Chunksize);
break;
}
}
}
//#######################################################################################
//# AABTree (Axis-aligned-bounding-box)
//#######################################################################################
private static void ReadAABTreeHeader(BinaryReader br, uint ChunkEnd)
{
long nodeCount = ReadLong(br);
long polyCount = ReadLong(br);
//padding of the header
while (br.BaseStream.Position < ChunkEnd)
{
br.ReadBytes(4);
}
}
private static void ReadAABTreePolyIndices(BinaryReader br, uint ChunkEnd)
{
List<long> polyIndices = new List<long>();
while (br.BaseStream.Position < ChunkEnd)
{
polyIndices.Add(ReadLong(br));
}
}
private static void ReadAABTreeNodes(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
Vector3 min = ReadVector(br);
Vector3 max = ReadVector(br);
long frontOrPoly0 = ReadLong(br);
long backOrPoly = ReadLong(br);
// if within these, check their children
// etc bis du irgendwann angekommen bist wos nur noch poly eintraege gibt dann hast du nen index und nen count parameter der dir sagt wo die polys die von dieser bounding box umschlossen sind liegen und wie viele es sind
// die gehst du dann alle durch wo du halt einfach nen test machst ob deine position xyz in dem poly liegt oder ausserhalb
}
}
private static void ReadAABTree(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 145:
ReadAABTreeHeader(br, subChunkEnd);
break;
case 146:
ReadAABTreePolyIndices(br, subChunkEnd);
break;
case 147:
ReadAABTreeNodes(br, subChunkEnd);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshAABTree");
br.ReadBytes((int)Chunksize);
break;
}
}
}
//######################################################################################
//# mesh
//######################################################################################
private static void ReadMeshHeader(BinaryReader br)
{
Version version = GetVersion(ReadLong(br));
uint attrs = ReadLong(br);
string meshName = ReadFixedString(br);
string containerName = ReadFixedString(br);
uint faceCount = ReadLong(br);
uint vertCount = ReadLong(br);
uint matlCount = ReadLong(br);
uint damageStageCount = ReadLong(br);
uint sortLevel = ReadLong(br);
uint prelitVersion = ReadLong(br);
uint futureCount = ReadLong(br);
uint vertChannelCount = ReadLong(br);
uint faceChannelCount = ReadLong(br);
Vector3 minCorner = ReadVector(br);
Vector3 maxCorner = ReadVector(br);
Vector3 sphCenter = ReadVector(br);
float sphRadius = ReadFloat(br);
mesh = new W3DMesh(faceCount);
modelName = containerName;
}
private static void ReadMesh(BinaryReader br, uint ChunkEnd)
{
while (br.BaseStream.Position < ChunkEnd)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize;
switch (Chunktype)
{
case 2:
//mesh vertices
mesh.vertices = ReadMeshVerticesArray(br, subChunkEnd);
break;
case 3072:
//mesh vertices copy
//unused
br.ReadBytes((int)Chunksize);
break;
case 3:
//mesh normals
ReadMeshVerticesArray(br, subChunkEnd);
break;
case 3073:
//mesh normals copy
//unused
br.ReadBytes((int)Chunksize);
break;
case 12:
//mesh user text -> contains sometimes shader settings?
//unused
br.ReadBytes((int)Chunksize);
break;
case 14:
//mesh vertices infs
ReadMeshVertexInfluences(br, subChunkEnd);
break;
case 31:
//mesh header
ReadMeshHeader(br);
break;
case 32:
//mesh faces
ReadMeshFaceArray(br, subChunkEnd);
break;
case 34:
//mesh shade indices
ReadLongArray(br, subChunkEnd);
break;
case 40:
//mesh material set info
//unused
br.ReadBytes((int)Chunksize);
break;
case 41:
//mesh shader array
ReadMeshShaderArray(br, subChunkEnd);
break;
case 42:
//mesh material array
ReadMeshMaterialArray(br, subChunkEnd);
break;
case 48:
//mesh texture array
ReadTextureArray(br, subChunkEnd);
break;
case 56:
//mesh material pass
ReadMeshMaterialPass(br, subChunkEnd);
break;
case 80:
//mesh bump map array
ReadBumpMapArray(br, subChunkEnd);
break;
case 96:
//unknown chunk -> specular or diffuse normals??
br.ReadBytes((int)Chunksize);
break;
case 97:
//unknown chunk -> specular or diffuse normals??
br.ReadBytes((int)Chunksize);
break;
case 144:
//mesh aabtree
ReadAABTree(br, subChunkEnd);
break;
default:
Console.WriteLine("unknown chunktype: " + Chunktype + " in Mesh");
br.ReadBytes((int)Chunksize);
break;
}
}
model.meshes.Add(mesh);
}
//######################################################################################
//# main import
//######################################################################################
public static void Load(Stream s)
{
BinaryReader br = new BinaryReader(s);
long filesize = s.Length;
while (s.Position < filesize)
{
uint Chunktype = ReadLong(br);
uint Chunksize = getChunkSize(ReadLong(br));
uint ChunkEnd = (uint)s.Position + Chunksize;
switch (Chunktype)
{
/*
case 0:
//mesh
//if the w3d file contains mesh data create a new model object
if (model == null)
{
model = new Model();
Model.AddModel(modelName, model);
}
ReadMesh(br, ChunkEnd);
break;
case 256:
//Hierarchy
ReadHierarchy(br, ChunkEnd);
break;
case 512:
//Animation
ReadAnimation(br, ChunkEnd);
break;
*/
case 640:
//CompressedAnimation
ReadCompressedAnimation(br, ChunkEnd);
break;
/*
case 1792:
//HLod
ReadHLod(br, ChunkEnd);
break;
case 1856:
//Box
ReadBox(br);
break;
*/
default:
//Console.WriteLine("unknown chunktype: " + Chunktype + " in File");
br.ReadBytes((int)Chunksize);
break;
}
}
}
}
}
| |
/*
* Exception.cs - Implementation of the "System.Exception" class.
*
* Copyright (C) 2001, 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System
{
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Diagnostics;
/*
Note on Exception messages:
--------------------------
This class library takes a slightly different approach for determining
what the default message text should be for internal exceptions. Other
implementations override "Message" and "ToString()", and then back-patch
the "message" field in the base class if it is null. This is a pain to
implement, especially for "ToString()" which must include the stack trace
in the result, amongst other things.
Instead, we provide two "internal" properties that only classes
in this library can access. "MessageDefault" provides a default message
if "message" is null. "MessageExtra" provides extra information to be
inserted into the "ToString()" result just after the message and before
the stack trace.
A similar approach is used to get the HResult values.
This design is cleaner to implement throughout the library. Because the
extra properties are "internal", they will not pollute the name space of
applications that didn't expect them to be present.
*/
#if CONFIG_COM_INTEROP
[ClassInterface(ClassInterfaceType.AutoDual)]
#if CONFIG_FRAMEWORK_1_2 && CONFIG_REFLECTION
[ComDefaultInterface(typeof(_Exception))]
#endif
#endif
public class Exception
#if CONFIG_SERIALIZATION
: ISerializable
#if CONFIG_COM_INTEROP && CONFIG_FRAMEWORK_1_2 && CONFIG_REFLECTION
, _Exception
#endif
#elif CONFIG_COM_INTEROP && CONFIG_FRAMEWORK_1_2 && CONFIG_REFLECTION
: _Exception
#endif
{
// Private members.
private String message;
private Exception innerException;
private PackedStackFrame[] stackTrace;
#if !ECMA_COMPAT
private String source;
private String helpLink;
private int hresult;
private bool hresultSet;
private String stackTraceString;
private String remoteStackTraceString;
private int remoteStackIndex;
private String exceptionMethodString;
#endif
// Constructors.
public Exception() : this(null, null) {}
public Exception(String msg) : this(msg, null) {}
public Exception(String msg, Exception inner)
{
message = msg;
innerException = inner;
}
#if CONFIG_SERIALIZATION
protected Exception(SerializationInfo info, StreamingContext context)
{
if(info == null)
{
throw new ArgumentNullException("info");
}
message = info.GetString("Message");
innerException = (Exception)(info.GetValue("InnerException",
typeof(Exception)));
helpLink = info.GetString("HelpURL");
source = info.GetString("Source");
stackTraceString = info.GetString("StackTraceString");
remoteStackTraceString = info.GetString("RemoteStackTraceString");
remoteStackIndex = info.GetInt32("RemoteStackIndex");
exceptionMethodString = info.GetString("ExceptionMethod");
hresult = info.GetInt32("HResult");
if(hresult != 0)
{
hresultSet = true;
}
}
#endif
// Private constructor that is used for subclasses that
// don't want stack traces. e.g. OutOfMemoryException.
internal Exception(String msg, Exception inner, bool wantTrace)
{
message = msg;
innerException = inner;
if(wantTrace)
{
try
{
stackTrace = StackFrame.GetExceptionStackTrace();
}
catch(NotImplementedException)
{
stackTrace = null;
}
}
}
// Get the base exception upon which this exception is based.
public virtual Exception GetBaseException()
{
Exception result = this;
Exception inner;
while((inner = result.InnerException) != null)
{
result = inner;
}
return result;
}
// Convert the exception into a string.
public override String ToString()
{
String className;
String result;
String temp;
String message = Message;
try
{
className = GetType().ToString();
}
catch(NotImplementedException)
{
// The runtime engine does not have reflection support.
className = String.Empty;
}
if(message != null && message.Length > 0)
{
if(className != null && className.Length > 0)
{
result = className + ": " + message;
}
else
{
result = message;
}
}
else if(className != null && className.Length > 0)
{
result = className;
}
else
{
// Default message if we cannot get a message from
// the underlying resource sub-system.
result = "Exception was thrown";
}
temp = MessageExtra;
if(temp != null)
{
result = result + Environment.NewLine + temp;
}
if(innerException != null)
{
result = result + " ---> " + innerException.ToString();
}
temp = StackTrace;
if(temp != null)
{
result = result + Environment.NewLine + temp;
}
return result;
}
// Properties.
#if !ECMA_COMPAT
protected int HResult
{
get
{
if(!hresultSet)
{
hresult = (int)HResultDefault;
hresultSet = true;
}
return hresult;
}
set
{
hresult = value;
hresultSet = true;
}
}
public virtual String HelpLink
{
get
{
return helpLink;
}
set
{
helpLink = value;
}
}
public virtual String Source
{
get
{
if(source == null && stackTrace != null &&
stackTrace.Length > 0)
{
MethodBase method = MethodBase.GetMethodFromHandle
(stackTrace[0].method);
source = method.DeclaringType.Module.Assembly.FullName;
}
return source;
}
set
{
source = value;
}
}
public MethodBase TargetSite
{
get
{
if(stackTrace != null && stackTrace.Length > 0)
{
return MethodBase.GetMethodFromHandle
(stackTrace[0].method);
}
else
{
return null;
}
}
}
#endif
public Exception InnerException
{
get
{
return innerException;
}
}
public virtual String Message
{
get
{
if(message != null)
{
return message;
}
else if((message = MessageDefault) != null)
{
return message;
}
else
{
try
{
return String.Format
(_("Exception_WasThrown"), GetType().ToString());
}
catch(NotImplementedException)
{
return String.Empty;
}
}
}
}
public virtual String StackTrace
{
get
{
if(stackTrace != null)
{
return (new StackTrace(this, true)).ToString();
}
#if !ECMA_COMPAT
else if(stackTraceString != null)
{
return stackTraceString;
}
#endif
else
{
return String.Empty;
}
}
}
// Get the packed stack trace information from this exception.
internal PackedStackFrame[] GetPackedStackTrace()
{
return stackTrace;
}
// Get the extra data to be inserted into the "ToString" representation.
internal virtual String MessageExtra
{
get
{
return null;
}
}
// Get the default message to use if "message" was initialized to null.
internal virtual String MessageDefault
{
get
{
return null;
}
}
// Get the default HResult value for this type of exception.
internal virtual uint HResultDefault
{
get
{
return 0x80131500;
}
}
#if CONFIG_SERIALIZATION
// Get the serialization data for this exception object.
public virtual void GetObjectData(SerializationInfo info,
StreamingContext context)
{
if(info == null)
{
throw new ArgumentNullException("info");
}
info.AddValue("ClassName", GetType().FullName, typeof(String));
info.AddValue("Message", message, typeof(String));
info.AddValue("InnerException", innerException, typeof(Exception));
info.AddValue("HelpURL", helpLink, typeof(String));
info.AddValue("Source", Source, typeof(String));
info.AddValue("StackTraceString", StackTrace, typeof(String));
info.AddValue("RemoteStackTraceString", remoteStackTraceString,
typeof(String));
info.AddValue("RemoteStackIndex", remoteStackIndex);
info.AddValue("ExceptionMethod", exceptionMethodString);
info.AddValue("HResult", HResult);
}
#endif // CONFIG_SERIALIZATION
}; // class Exception
}; // namespace System
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
internal sealed unsafe class HttpRequestStream : Stream
{
private readonly HttpListenerContext _httpContext;
private uint _dataChunkOffset;
private int _dataChunkIndex;
private bool _closed;
internal const int MaxReadSize = 0x20000; //http.sys recommends we limit reads to 128k
private bool _inOpaqueMode;
internal HttpRequestStream(HttpListenerContext httpContext)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"httpContextt:{httpContext}");
_httpContext = httpContext;
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override bool CanRead
{
get
{
return true;
}
}
internal bool Closed
{
get
{
return _closed;
}
}
internal bool BufferedDataChunksAvailable
{
get
{
return _dataChunkIndex > -1;
}
}
// This low level API should only be consumed if the caller can make sure that the state is not corrupted
// WebSocketHttpListenerDuplexStream (a duplex wrapper around HttpRequestStream/HttpResponseStream)
// is currenlty the only consumer of this API
internal HttpListenerContext InternalHttpContext
{
get
{
return _httpContext;
}
}
public override void Flush()
{
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public override long Length
{
get
{
throw new NotSupportedException(SR.net_noseek);
}
}
public override long Position
{
get
{
throw new NotSupportedException(SR.net_noseek);
}
set
{
throw new NotSupportedException(SR.net_noseek);
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.net_noseek);
}
public override void SetLength(long value)
{
throw new NotSupportedException(SR.net_noseek);
}
public override int Read(byte[] buffer, int offset, int size)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
NetEventSource.Info(this, "size:" + size + " offset:" + offset);
}
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
if (size == 0 || _closed)
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, "dataRead:0");
return 0;
}
uint dataRead = 0;
if (_dataChunkIndex != -1)
{
dataRead = Interop.HttpApi.GetChunks(_httpContext.Request.RequestBuffer, _httpContext.Request.OriginalBlobAddress, ref _dataChunkIndex, ref _dataChunkOffset, buffer, offset, size);
}
if (_dataChunkIndex == -1 && dataRead < size)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "size:" + size + " offset:" + offset);
uint statusCode = 0;
uint extraDataRead = 0;
offset += (int)dataRead;
size -= (int)dataRead;
//the http.sys team recommends that we limit the size to 128kb
if (size > MaxReadSize)
{
size = MaxReadSize;
}
fixed (byte* pBuffer = buffer)
{
// issue unmanaged blocking call
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveRequestEntityBody");
uint flags = 0;
if (!_inOpaqueMode)
{
flags = (uint)Interop.HttpApi.HTTP_FLAGS.HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY;
}
statusCode =
Interop.HttpApi.HttpReceiveRequestEntityBody(
_httpContext.RequestQueueHandle,
_httpContext.RequestId,
flags,
(void*)(pBuffer + offset),
(uint)size,
out extraDataRead,
null);
dataRead += extraDataRead;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveRequestEntityBody returned:" + statusCode + " dataRead:" + dataRead);
}
if (statusCode != Interop.HttpApi.ERROR_SUCCESS && statusCode != Interop.HttpApi.ERROR_HANDLE_EOF)
{
Exception exception = new HttpListenerException((int)statusCode);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception.ToString());
throw exception;
}
UpdateAfterRead(statusCode, dataRead);
}
if (NetEventSource.IsEnabled)
{
NetEventSource.DumpBuffer(this, buffer, offset, (int)dataRead);
NetEventSource.Info(this, "returning dataRead:" + dataRead);
NetEventSource.Exit(this, "dataRead:" + dataRead);
}
return (int)dataRead;
}
private void UpdateAfterRead(uint statusCode, uint dataRead)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "statusCode:" + statusCode + " _closed:" + _closed);
if (statusCode == Interop.HttpApi.ERROR_HANDLE_EOF || dataRead == 0)
{
Close();
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "statusCode:" + statusCode + " _closed:" + _closed);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "buffer.Length:" + buffer.Length + " size:" + size + " offset:" + offset);
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
if (size == 0 || _closed)
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
HttpRequestStreamAsyncResult result = new HttpRequestStreamAsyncResult(this, state, callback);
result.InvokeCallback((uint)0);
return result;
}
HttpRequestStreamAsyncResult asyncResult = null;
uint dataRead = 0;
if (_dataChunkIndex != -1)
{
dataRead = Interop.HttpApi.GetChunks(_httpContext.Request.RequestBuffer, _httpContext.Request.OriginalBlobAddress, ref _dataChunkIndex, ref _dataChunkOffset, buffer, offset, size);
if (_dataChunkIndex != -1 && dataRead == size)
{
asyncResult = new HttpRequestStreamAsyncResult(_httpContext.RequestQueueBoundHandle, this, state, callback, buffer, offset, (uint)size, 0);
asyncResult.InvokeCallback(dataRead);
}
}
if (_dataChunkIndex == -1 && dataRead < size)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "size:" + size + " offset:" + offset);
uint statusCode = 0;
offset += (int)dataRead;
size -= (int)dataRead;
//the http.sys team recommends that we limit the size to 128kb
if (size > MaxReadSize)
{
size = MaxReadSize;
}
asyncResult = new HttpRequestStreamAsyncResult(_httpContext.RequestQueueBoundHandle, this, state, callback, buffer, offset, (uint)size, dataRead);
uint bytesReturned;
try
{
fixed (byte* pBuffer = buffer)
{
// issue unmanaged blocking call
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveRequestEntityBody");
uint flags = 0;
if (!_inOpaqueMode)
{
flags = (uint)Interop.HttpApi.HTTP_FLAGS.HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY;
}
statusCode =
Interop.HttpApi.HttpReceiveRequestEntityBody(
_httpContext.RequestQueueHandle,
_httpContext.RequestId,
flags,
asyncResult._pPinnedBuffer,
(uint)size,
out bytesReturned,
asyncResult._pOverlapped);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveRequestEntityBody returned:" + statusCode + " dataRead:" + dataRead);
}
}
catch (Exception e)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e.ToString());
asyncResult.InternalCleanup();
throw;
}
if (statusCode != Interop.HttpApi.ERROR_SUCCESS && statusCode != Interop.HttpApi.ERROR_IO_PENDING)
{
asyncResult.InternalCleanup();
if (statusCode == Interop.HttpApi.ERROR_HANDLE_EOF)
{
asyncResult = new HttpRequestStreamAsyncResult(this, state, callback, dataRead);
asyncResult.InvokeCallback((uint)0);
}
else
{
Exception exception = new HttpListenerException((int)statusCode);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception.ToString());
asyncResult.InternalCleanup();
throw exception;
}
}
else if (statusCode == Interop.HttpApi.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
// IO operation completed synchronously - callback won't be called to signal completion.
asyncResult.IOCompleted(statusCode, bytesReturned);
}
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return asyncResult;
}
public override int EndRead(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
NetEventSource.Info(this, $"asyncResult: {asyncResult}");
}
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
HttpRequestStreamAsyncResult castedAsyncResult = asyncResult as HttpRequestStreamAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndRead)));
}
castedAsyncResult.EndCalled = true;
// wait & then check for errors
object returnValue = castedAsyncResult.InternalWaitForCompletion();
Exception exception = returnValue as Exception;
if (exception != null)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, "Rethrowing exception:" + exception);
NetEventSource.Error(this, exception.ToString());
}
ExceptionDispatchInfo.Throw(exception);
}
uint dataRead = (uint)returnValue;
UpdateAfterRead((uint)castedAsyncResult.ErrorCode, dataRead);
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"returnValue:{returnValue}");
NetEventSource.Exit(this);
}
return (int)dataRead + (int)castedAsyncResult._dataAlreadyRead;
}
public override void Write(byte[] buffer, int offset, int size)
{
throw new InvalidOperationException(SR.net_readonlystream);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
{
throw new InvalidOperationException(SR.net_readonlystream);
}
public override void EndWrite(IAsyncResult asyncResult)
{
throw new InvalidOperationException(SR.net_readonlystream);
}
protected override void Dispose(bool disposing)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "_closed:" + _closed);
_closed = true;
}
finally
{
base.Dispose(disposing);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
internal void SwitchToOpaqueMode()
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
_inOpaqueMode = true;
}
// This low level API should only be consumed if the caller can make sure that the state is not corrupted
// WebSocketHttpListenerDuplexStream (a duplex wrapper around HttpRequestStream/HttpResponseStream)
// is currenlty the only consumer of this API
internal uint GetChunks(byte[] buffer, int offset, int size)
{
return Interop.HttpApi.GetChunks(_httpContext.Request.RequestBuffer,
_httpContext.Request.OriginalBlobAddress,
ref _dataChunkIndex,
ref _dataChunkOffset,
buffer,
offset,
size);
}
private sealed unsafe class HttpRequestStreamAsyncResult : LazyAsyncResult
{
private ThreadPoolBoundHandle _boundHandle;
internal NativeOverlapped* _pOverlapped;
internal void* _pPinnedBuffer;
internal uint _dataAlreadyRead = 0;
private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(Callback);
internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback) : base(asyncObject, userState, callback)
{
}
internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback, uint dataAlreadyRead) : base(asyncObject, userState, callback)
{
_dataAlreadyRead = dataAlreadyRead;
}
internal HttpRequestStreamAsyncResult(ThreadPoolBoundHandle boundHandle, object asyncObject, object userState, AsyncCallback callback, byte[] buffer, int offset, uint size, uint dataAlreadyRead) : base(asyncObject, userState, callback)
{
_dataAlreadyRead = dataAlreadyRead;
_boundHandle = boundHandle;
_pOverlapped = boundHandle.AllocateNativeOverlapped(s_IOCallback, state: this, pinData: buffer);
_pPinnedBuffer = (void*)(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset));
}
internal void IOCompleted(uint errorCode, uint numBytes)
{
IOCompleted(this, errorCode, numBytes);
}
private static void IOCompleted(HttpRequestStreamAsyncResult asyncResult, uint errorCode, uint numBytes)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes}");
object result = null;
try
{
if (errorCode != Interop.HttpApi.ERROR_SUCCESS && errorCode != Interop.HttpApi.ERROR_HANDLE_EOF)
{
asyncResult.ErrorCode = (int)errorCode;
result = new HttpListenerException((int)errorCode);
}
else
{
result = numBytes;
if (NetEventSource.IsEnabled) NetEventSource.DumpBuffer(asyncResult, (IntPtr)asyncResult._pPinnedBuffer, (int)numBytes);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"asyncResult: {asyncResult} calling Complete()");
}
catch (Exception e)
{
result = e;
}
asyncResult.InvokeCallback(result);
}
private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
HttpRequestStreamAsyncResult asyncResult = (HttpRequestStreamAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped);
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes} nativeOverlapped:0x {((IntPtr)nativeOverlapped).ToString("x8")}");
IOCompleted(asyncResult, errorCode, numBytes);
}
// Will be called from the base class upon InvokeCallback()
protected override void Cleanup()
{
base.Cleanup();
if (_pOverlapped != null)
{
_boundHandle.FreeNativeOverlapped(_pOverlapped);
}
}
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using Autofac.Builder;
using Autofac.Core;
using System;
using System.Abstract;
using System.Collections.Generic;
using System.Linq;
namespace Autofac.Abstract
{
/// <summary>
/// IAutofacServiceRegistrar
/// </summary>
public interface IAutofacServiceRegistrar : IServiceRegistrar { }
/// <summary>
/// AutofacServiceRegistrar
/// </summary>
public class AutofacServiceRegistrar : IAutofacServiceRegistrar, IDisposable, ICloneable, IServiceRegistrarBehaviorAccessor
{
readonly AutofacServiceLocator _parent;
ContainerBuilder _builder;
IContainer _container;
/// <summary>
/// Initializes a new instance of the <see cref="AutofacServiceRegistrar"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="container">The container.</param>
public AutofacServiceRegistrar(AutofacServiceLocator parent, IContainer container)
{
_parent = parent;
_container = container;
LifetimeForRegisters = ServiceRegistrarLifetime.Transient;
}
/// <summary>
/// Initializes a new instance of the <see cref="AutofacServiceRegistrar"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="builder">The builder.</param>
/// <param name="containerBuilder">The container builder.</param>
public AutofacServiceRegistrar(AutofacServiceLocator parent, ContainerBuilder builder, out Func<IContainer> containerBuilder)
: this(parent, null)
{
_builder = builder;
containerBuilder = (() => _container = _builder.Build());
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose() { }
object ICloneable.Clone() { return MemberwiseClone(); }
// locator
/// <summary>
/// Gets the locator.
/// </summary>
public IServiceLocator Locator
{
get { return _parent; }
}
// enumerate
/// <summary>
/// Determines whether this instance has registered.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns>
/// <c>true</c> if this instance has registered; otherwise, <c>false</c>.
/// </returns>
public bool HasRegistered<TService>() { return _parent.Container.IsRegistered<TService>(); }
/// <summary>
/// Determines whether the specified service type has registered.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <returns>
/// <c>true</c> if the specified service type has registered; otherwise, <c>false</c>.
/// </returns>
public bool HasRegistered(Type serviceType) { return _parent.Container.IsRegistered(serviceType); }
/// <summary>
/// Gets the registrations for.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <returns></returns>
public IEnumerable<ServiceRegistration> GetRegistrationsFor(Type serviceType)
{
return _parent.Container.ComponentRegistry.Registrations
.SelectMany(x => x.Services.OfType<TypedService>())
.Where(x => serviceType.IsAssignableFrom(x.ServiceType))
.Select(x => new ServiceRegistration { ServiceType = serviceType, ImplementationType = x.ServiceType, Name = x.Description });
}
/// <summary>
/// Gets the registrations.
/// </summary>
public IEnumerable<ServiceRegistration> Registrations
{
get
{
return _parent.Container.ComponentRegistry.Registrations
.SelectMany(x => x.Services.OfType<TypedService>())
.Select(x => new ServiceRegistration { ImplementationType = x.ServiceType, Name = x.Description });
}
}
// register type
/// <summary>
/// Gets the lifetime for registers.
/// </summary>
public ServiceRegistrarLifetime LifetimeForRegisters { get; private set; }
/// <summary>
/// Registers the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
public void Register(Type serviceType)
{
SetLifestyle(_builder.RegisterType(serviceType));
if (_container != null)
UpdateAndClearBuilder();
}
/// <summary>
/// Registers the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <param name="name">The name.</param>
public void Register(Type serviceType, string name)
{
SetLifestyle(_builder.RegisterType(serviceType).Named(name, serviceType));
if (_container != null)
UpdateAndClearBuilder();
}
// register implementation
/// <summary>
/// Registers this instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
public void Register<TService, TImplementation>()
where TService : class
where TImplementation : class, TService
{
if (_container == null)
SetLifestyle(_builder.RegisterType<TImplementation>().As<TService>());
else
_container.ComponentRegistry.Register(SetLifestyle(RegistrationBuilder.ForType<TImplementation>().As<TService>()).CreateRegistration());
}
/// <summary>
/// Registers the specified name.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <param name="name">The name.</param>
public void Register<TService, TImplementation>(string name)
where TService : class
where TImplementation : class, TService
{
Register<TService, TImplementation>();
if (_container == null)
SetLifestyle(_builder.RegisterType<TImplementation>().Named<TService>(name));
else
_container.ComponentRegistry.Register(SetLifestyle(RegistrationBuilder.ForType<TImplementation>().Named<TService>(name)).CreateRegistration());
}
/// <summary>
/// Registers the specified implementation type.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="implementationType">Type of the implementation.</param>
public void Register<TService>(Type implementationType)
where TService : class
{
if (_container == null)
SetLifestyle(_builder.RegisterType(implementationType).As<TService>());
else
_container.ComponentRegistry.Register(SetLifestyle(RegistrationBuilder.ForType(implementationType).As<TService>()).CreateRegistration());
}
/// <summary>
/// Registers the specified implementation type.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="implementationType">Type of the implementation.</param>
/// <param name="name">The name.</param>
public void Register<TService>(Type implementationType, string name)
where TService : class
{
Register<TService>(implementationType);
if (_container == null)
SetLifestyle(_builder.RegisterType(implementationType).Named<TService>(name));
else
_container.ComponentRegistry.Register(SetLifestyle(RegistrationBuilder.ForType(implementationType).Named<TService>(name)).CreateRegistration());
}
/// <summary>
/// Registers the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <param name="implementationType">Type of the implementation.</param>
public void Register(Type serviceType, Type implementationType)
{
if (_container == null)
SetLifestyle(_builder.RegisterType(implementationType).As(serviceType));
else
_container.ComponentRegistry.Register(SetLifestyle(RegistrationBuilder.ForType(implementationType).As(serviceType)).CreateRegistration());
}
/// <summary>
/// Registers the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <param name="implementationType">Type of the implementation.</param>
/// <param name="name">The name.</param>
public void Register(Type serviceType, Type implementationType, string name)
{
Register(serviceType, implementationType);
if (_container == null)
SetLifestyle(_builder.RegisterType(implementationType).Named(name, serviceType));
else
_container.ComponentRegistry.Register(SetLifestyle(RegistrationBuilder.ForType(implementationType).Named(name, serviceType)).CreateRegistration());
}
// register instance
/// <summary>
/// Registers the instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
public void RegisterInstance<TService>(TService instance)
where TService : class
{
EnsureTransientLifestyle();
_builder.RegisterInstance(instance).As<TService>().ExternallyOwned();
if (_container != null)
UpdateAndClearBuilder();
}
/// <summary>
/// Registers the instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
/// <param name="name">The name.</param>
public void RegisterInstance<TService>(TService instance, string name)
where TService : class
{
EnsureTransientLifestyle();
_builder.RegisterInstance(instance).Named(name, typeof(TService)).ExternallyOwned();
if (_container != null)
UpdateAndClearBuilder();
}
/// <summary>
/// Registers the instance.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <param name="instance">The instance.</param>
public void RegisterInstance(Type serviceType, object instance)
{
EnsureTransientLifestyle();
_builder.RegisterInstance(instance).As(serviceType).ExternallyOwned();
if (_container != null)
UpdateAndClearBuilder();
}
/// <summary>
/// Registers the instance.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <param name="instance">The instance.</param>
/// <param name="name">The name.</param>
public void RegisterInstance(Type serviceType, object instance, string name)
{
EnsureTransientLifestyle();
_builder.RegisterInstance(instance).Named(name, serviceType).ExternallyOwned();
if (_container != null)
UpdateAndClearBuilder();
}
// register method
/// <summary>
/// Registers the specified factory method.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="factoryMethod">The factory method.</param>
public void Register<TService>(Func<IServiceLocator, TService> factoryMethod)
where TService : class
{
SetLifestyle(_builder.Register(x => factoryMethod(_parent)).As<TService>());
if (_container != null)
UpdateAndClearBuilder();
}
/// <summary>
/// Registers the specified factory method.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="factoryMethod">The factory method.</param>
/// <param name="name">The name.</param>
public void Register<TService>(Func<IServiceLocator, TService> factoryMethod, string name)
where TService : class
{
SetLifestyle(_builder.Register(x => factoryMethod(_parent)).Named<TService>(name));
if (_container != null)
UpdateAndClearBuilder();
}
/// <summary>
/// Registers the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <param name="factoryMethod">The factory method.</param>
public void Register(Type serviceType, Func<IServiceLocator, object> factoryMethod)
{
SetLifestyle(_builder.Register(x => factoryMethod(_parent)).As(serviceType));
if (_container != null)
UpdateAndClearBuilder();
}
/// <summary>
/// Registers the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <param name="factoryMethod">The factory method.</param>
/// <param name="name">The name.</param>
public void Register(Type serviceType, Func<IServiceLocator, object> factoryMethod, string name)
{
SetLifestyle(_builder.Register(x => factoryMethod(_parent)).Named(name, serviceType));
if (_container != null)
UpdateAndClearBuilder();
}
// interceptor
/// <summary>
/// Registers the interceptor.
/// </summary>
/// <param name="interceptor">The interceptor.</param>
public void RegisterInterceptor(IServiceLocatorInterceptor interceptor)
{
EnsureTransientLifestyle();
_builder.RegisterModule(new Interceptor(interceptor));
if (_container != null)
UpdateAndClearBuilder();
}
#region Domain specific
private void UpdateAndClearBuilder()
{
_builder.Update(_container);
_builder = new ContainerBuilder();
}
#endregion
#region Behavior
bool IServiceRegistrarBehaviorAccessor.RegisterInLocator
{
get { return true; }
}
ServiceRegistrarLifetime IServiceRegistrarBehaviorAccessor.Lifetime
{
get { return LifetimeForRegisters; }
set { LifetimeForRegisters = value; }
}
#endregion
private void EnsureTransientLifestyle()
{
if (LifetimeForRegisters != ServiceRegistrarLifetime.Transient)
throw new NotSupportedException();
}
private IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> SetLifestyle<TLimit, TActivatorData, TRegistrationStyle>(IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> b)
{
// must cast to IServiceRegistrar for behavior wrappers
switch (LifetimeForRegisters)
{
case ServiceRegistrarLifetime.Transient: break; // b.InstancePerDependency();
case ServiceRegistrarLifetime.Singleton: b.SingleInstance(); break;
default: throw new NotSupportedException();
}
return b;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityObject = UnityEngine.Object;
using UnityEvent= UnityEngine.Event;
namespace Zios.Interface{
using UnityEditor;
using Event;
public enum HoverResponse{None=1,Slow,Moderate,Instant};
[InitializeOnLoad][NotSerialized]
public partial class Theme{
public static string revision = "[r{revision}]";
public static string storagePath = "Assets/@Themes/";
public static int themeIndex;
public static int paletteIndex;
public static int fontsetIndex;
public static int iconsetIndex;
public static int skinsetIndex;
public static HoverResponse hoverResponse = HoverResponse.None;
public static bool delayUpdate;
public static bool singleUpdate;
public static bool separatePlaymodeSettings;
public static bool showColorsAdvanced;
public static bool showFontsAdvanced;
public static bool changed;
public static bool initialized;
public static bool setup;
public static bool loaded;
public static bool lazyLoaded;
public static bool disabled;
public static bool debug;
public static ThemeWindow window;
public static string suffix;
private static bool liveEdit;
private static bool needsRefresh;
private static bool needsRebuild;
private static bool needsInstantRefresh;
private static bool setupPreferences;
private static Vector2 scroll = Vector2.zero;
private static float colorChangeTime;
private static int colorChangeCount;
private static Action undoCallback;
private static List<string> paletteNames = new List<string>();
private static List<string> fontsetNames = new List<string>();
private static List<string> fontNames = new List<string>();
private static Font[] fonts = new Font[0];
private static Font[] builtinFonts = new Font[0];
static Theme(){
EditorApplication.playmodeStateChanged += Theme.CheckUpdate;
EditorApplication.update += ThemeWindow.ShowWindow;
AppDomain.CurrentDomain.DomainUnload += ThemeWindow.CloseWindow;
Events.Add("On Window Reordered",ThemeWindow.CloseWindow);
Events.Add("On GUISkin Changed",()=>{
if(Theme.liveEdit){
Utility.DelayCall(Theme.DelayedInstantRefresh,0.5f);
}
});
}
public static void Update(){
if(Theme.disabled){return;}
if(!Theme.needsRefresh && !Theme.needsRebuild && Theme.needsInstantRefresh){
Theme.needsInstantRefresh = false;
Theme.InstantRefresh();
}
if(Theme.needsRebuild){
Theme.RebuildStyles();
Theme.Refresh();
if(!Theme.active.IsNull() && !Theme.active.iconset.IsNull()){
Theme.active.iconset.Apply(false);
}
Utility.CallEditorPref("EditorTheme-Rebuild",Theme.debug);
Theme.needsRebuild = false;
Theme.Update();
}
else if(Theme.needsRefresh){
Theme.ApplySettings();
Utility.CallEditorPref("EditorTheme-Refresh",Theme.debug);
Utility.RepaintAll();
Utility.DelayCall(Utility.RepaintAll,0.25f);
Theme.Cleanup();
Theme.needsRefresh = false;
}
else if(!Theme.setup){
var themes = FileManager.Find("*.unitytheme",Theme.debug);
if(themes.IsNull()){
Debug.LogWarning("[Themes] No .unityTheme files found. Disabling until refreshed.");
Theme.setup = true;
Theme.disabled = true;
return;
}
Theme.storagePath = themes.path.GetDirectory()+"/";
Theme.Load(!Theme.initialized);
Theme.LoadSettings();
Theme.Rebuild();
Theme.fontNames.Clear();
Theme.fontsetNames.Clear();
Theme.paletteNames.Clear();
Theme.setupPreferences = false;
if(Theme.separatePlaymodeSettings){Utility.DelayCall(Theme.Rebuild,0.25f);}
Utility.CallEditorPref("EditorTheme-Setup",Theme.debug);
Theme.setup = true;
Theme.initialized = true;
Theme.Update();
}
}
public static void LoadCheck(){
if(Theme.lazyLoaded){
Theme.Load(false);
Theme.LoadSettings();
Theme.ApplySettings();
}
}
public static void Load(bool lazy=false){
Theme.separatePlaymodeSettings = Utility.GetPref("EditorTheme-SeparatePlaymodeSettings",false);
Theme.suffix = EditorApplication.isPlayingOrWillChangePlaymode && Theme.separatePlaymodeSettings ? "-Playmode" : "";
var theme = Utility.GetPref("EditorTheme"+Theme.suffix,"Default").ToPascalCase();
var suffix = "-"+theme+Theme.suffix;
if(!Utility.HasPref("EditorSkinset"+suffix)){lazy = false;}
var fontset = lazy ? Utility.GetPref("EditorFontset"+suffix,"Classic") + ".unityFontset" : null;
var palette = lazy ? Utility.GetPref("EditorPalette"+suffix,"Classic") + ".unityPalette" : null;
var iconset = lazy ? FileManager.Find("Iconsets/"+Utility.GetPref("EditorIconset"+suffix,"Default")) : null;
var skinset = lazy ? FileManager.Find("Skinsets/"+Utility.GetPref("EditorSkinset"+suffix,"Default")) : null;
var unityTheme = lazy ? theme + ".unitytheme" : null;
ThemeFontset.all = ThemeFontset.Import(fontset);
ThemePalette.all = ThemePalette.Import(palette);
ThemeSkinset.all = skinset.IsNull() ? ThemeSkinset.Import() : ThemeSkinset.Import(skinset.path).AsList();
ThemeIconset.all = iconset.IsNull() ? ThemeIconset.Import() : ThemeIconset.Import(iconset.path).AsList();
Theme.all = Theme.Import(unityTheme).OrderBy(x=>x.name!="Default").ToList();
Theme.loaded = true;
Theme.lazyLoaded = lazy;
}
public static void LoadSettings(){
FileManager.monitor = false;
RelativeColor.autoBalance = Utility.GetPref("EditorTheme-AutobalanceColors",1).As<AutoBalance>();
Theme.showColorsAdvanced = Utility.GetPref("EditorTheme-ShowAdvancedColors",false);
Theme.showFontsAdvanced = Utility.GetPref("EditorTheme-ShowAdvancedFonts",false);
Theme.hoverResponse = Utility.GetPref("EditorTheme-HoverResponse",1).As<HoverResponse>();
Theme.themeIndex = Theme.all.FindIndex(x=>x.name==Utility.GetPref("EditorTheme"+Theme.suffix,"Default")).Max(0);
var theme = Theme.all[Theme.themeIndex];
Theme.suffix = "-"+theme.name+Theme.suffix;
if(!Theme.lazyLoaded){
Theme.fontsetIndex = ThemeFontset.all.FindIndex(x=>x.name==Utility.GetPref<string>("EditorFontset"+Theme.suffix,theme.fontset.name)).Max(0);
Theme.paletteIndex = ThemePalette.all.FindIndex(x=>x.name==Utility.GetPref<string>("EditorPalette"+Theme.suffix,theme.palette.name)).Max(0);
Theme.skinsetIndex = ThemeSkinset.all.FindIndex(x=>x.name==Utility.GetPref<string>("EditorSkinset"+Theme.suffix,theme.skinset.name)).Max(0);
Theme.iconsetIndex = ThemeIconset.all.FindIndex(x=>x.name==Utility.GetPref<string>("EditorIconset"+Theme.suffix,theme.iconset.name)).Max(0);
}
}
public static void Refresh(){Theme.needsRefresh = true;}
public static void Rebuild(){Theme.needsRebuild = true;}
public static void RebuildStyles(){
var terms = new string[]{"Styles","styles","s_GOStyles","s_Current","s_Styles","m_Styles","ms_Styles","constants","s_Defaults"};
foreach(var type in typeof(Editor).Assembly.GetTypes()){
if(type.Name.Contains("LookDev")){continue;}
foreach(var term in terms){
type.ClearVariable(term,ObjectExtension.staticFlags);
}
}
typeof(EditorStyles).SetVariable<EditorStyles>("s_CachedStyles",null,0);
typeof(EditorStyles).SetVariable<EditorStyles>("s_CachedStyles",null,1);
typeof(EditorGUIUtility).CallMethod("SkinChanged");
}
//=================================
// Updating
//=================================
public static void CheckUpdate(){
if(Theme.separatePlaymodeSettings && !EditorApplication.isPlayingOrWillChangePlaymode){
Theme.Reset(true);
}
}
public static void UpdateColors(){
if(Theme.active.IsNull()){return;}
RelativeColor.UpdateSystem();
foreach(var color in Theme.active.palette.colors["*"]){
color.Value.ApplyOffset();
Utility.SetPref<bool>("EditorTheme-Dark-"+color.Key,color.Value.value.GetIntensity() < 0.4f);
}
Utility.SetPref<bool>("EditorTheme-Dark",Theme.active.palette.Get("Window").GetIntensity() < 0.4f);
}
public static void ApplySettings(){
if(Theme.all.Count < 1){return;}
var baseTheme = Theme.all[Theme.themeIndex];
var theme = Theme.active = new Theme().Use(baseTheme);
if(theme.customizablePalette && ThemePalette.all.Count > 0){
var basePalette = ThemePalette.all[Theme.paletteIndex];
theme.palette = new ThemePalette().Use(basePalette);
Theme.LoadColors();
Theme.UpdateColors();
}
if(theme.customizableFontset && ThemeFontset.all.Count > 0){
var baseFontset = ThemeFontset.all[Theme.fontsetIndex];
theme.fontset = new ThemeFontset(baseFontset).UseBuffer(theme.fontset);
Theme.LoadFontset();
}
if(Theme.changed){
foreach(var variant in Theme.active.skinset.variants){Undo.RecordPref<bool>("EditorVariant"+Theme.suffix+"-"+variant.name,false);}
foreach(var variant in Theme.active.defaultVariants){Undo.RecordPref<bool>("EditorVariant"+Theme.suffix+"-"+variant,true);}
Theme.changed = false;
}
foreach(var variant in theme.skinset.variants){
variant.active = Utility.GetPref<bool>("EditorVariant"+Theme.suffix+"-"+variant.name,false);
}
Utility.SetPref<string>("EditorSkinset"+Theme.suffix,theme.skinset.name);
if(!Utility.HasPref("EditorFontset"+Theme.suffix)){Utility.SetPref<string>("EditorFontset"+Theme.suffix,theme.fontset.name);}
if(!Utility.HasPref("EditorPalette"+Theme.suffix)){Utility.SetPref<string>("EditorPalette"+Theme.suffix,theme.palette.name);}
if(!Utility.HasPref("EditorIconset"+Theme.suffix)){Utility.SetPref<string>("EditorIconset"+Theme.suffix,theme.iconset.name);}
Theme.Apply();
}
public static void Apply(string themeName="",bool forceWrite=false){
if(Theme.active.IsNull()){return;}
var theme = Theme.active;
theme.skinset.Apply(theme);
forceWrite = !Utility.IsPlaying() && (forceWrite || Theme.singleUpdate);
var shouldUpdate = !Utility.IsPlaying() || Theme.singleUpdate || Theme.separatePlaymodeSettings;
if(theme.name != "Default" && shouldUpdate){
foreach(var color in theme.palette.colors["*"]){
if(color.Value.skipTexture){continue;}
color.Value.UpdateTexture(Theme.storagePath);
}
Action UpdateDynamic = ()=>{
if(theme.palette.swap.Count < 1){return;}
var variants = Theme.active.skinset.variants.Where(x=>x.active).Select(x=>x.name).ToArray();
foreach(var file in FileManager.FindAll("#*.png")){
if(file.path.Contains("+") && !variants.Contains(file.path.Parse("+","/"))){
continue;
}
theme.palette.ApplyTexture(file.path,file.GetAsset<Texture2D>(),forceWrite);
}
};
Utility.DelayCall("UpdateDynamic",UpdateDynamic,Theme.delayUpdate ? 0.25f : 0);
}
Theme.delayUpdate = false;
Theme.singleUpdate = false;
}
public static void Cleanup(){
foreach(var guiSkin in Resources.FindObjectsOfTypeAll<GUISkin>()){
if(!Utility.IsAsset(guiSkin)){
UnityObject.DestroyImmediate(guiSkin);
}
}
//GC.Collect();
}
//=================================
// Preferences
//=================================
[PreferenceItem("Themes")]
public static void DrawPreferences(){
EditorUI.Reset();
Theme.LoadCheck();
if(!Theme.separatePlaymodeSettings && EditorApplication.isPlayingOrWillChangePlaymode){
"Theme Settings are not available while in play mode unless \"Separate play mode\" active.".DrawHelp();
return;
}
if(Theme.disabled){
Theme.disabled = Theme.disabled.Draw("Disable System");
Undo.RecordPref<bool>("EditorTheme-Disabled",Theme.disabled);
"Disabling existing themes requires Unity to be restarted.".DrawHelp("Info");
}
if(Theme.disabled){return;}
if(Theme.active.IsNull()){
ThemeWindow.ShowWindow();
Theme.Reset(true);
Theme.InstantRefresh();
if(Theme.active.IsNull()){
Theme.disabled = true;
return;
}
}
var current = Theme.themeIndex;
var window = EditorWindow.focusedWindow;
if(!Theme.setupPreferences){
Theme.PrepareFonts();
Theme.setupPreferences = true;
}
if(Theme.active.name != "Default" && !window.IsNull() && window.GetType().Name.Contains("Preferences")){
window.maxSize = new Vector2(9999999,9999999);
}
Undo.RecordStart(typeof(Theme));
Theme.undoCallback = Theme.Refresh;
Theme.scroll = EditorGUILayout.BeginScrollView(Theme.scroll,false,false,GUI.skin.horizontalScrollbar,GUI.skin.verticalScrollbar,new GUIStyle().Padding(0,16,0,0));
Theme.UpdateColors();
Theme.DrawThemes();
Theme.DrawIconsets();
Theme.DrawPalettes();
Theme.DrawFontsets();
Theme.DrawOptions();
Theme.DrawVariants();
Theme.DrawColors();
Theme.DrawFonts();
if(current != Theme.themeIndex){
var suffix = Theme.suffix.Remove("-"+Theme.active.name);
Undo.RecordPref<string>("EditorTheme"+suffix,Theme.all[Theme.themeIndex].name);
Theme.changed = true;
Theme.InstantRefresh();
Utility.DelayCall(Theme.Rebuild,0.25f);
Theme.undoCallback = ()=>{
Theme.DelayedInstantRefresh();
Utility.DelayCall(Theme.Rebuild,0.25f);
};
}
else if(!Theme.needsRebuild && GUI.changed){
Theme.Rebuild();
Theme.undoCallback += Theme.Rebuild;
}
EditorGUILayout.EndScrollView();
Undo.RecordEnd("Theme Changes",typeof(Theme),Theme.undoCallback);
}
public static void DrawThemes(){
EditorGUIUtility.labelWidth = 200;
var themeNames = Theme.all.Select(x=>x.name).ToList();
var themeIndex = Theme.themeIndex + 1 < 2 ? 0 : Theme.themeIndex + 1;
themeNames.Insert(1,"/");
Theme.themeIndex = (themeNames.Draw(themeIndex,"Theme")-1).Max(0);
GUILayout.Space(3);
}
public static void DrawIconsets(){
var theme = Theme.active;
if(theme.customizableIconset){
Theme.iconsetIndex = ThemeIconset.all.Select(x=>x.name).Draw(Theme.iconsetIndex,"Iconset");
GUILayout.Space(3);
if(EditorUI.lastChanged){
Theme.ApplyIconset();
Theme.undoCallback = Theme.ApplyIconset;
}
}
}
public static void DrawPalettes(){
var theme = Theme.active;
int index = Theme.paletteIndex;
bool hasPalettes = ThemePalette.all.Count > 0;
bool paletteAltered = !theme.palette.Matches(ThemePalette.all[index]);
if(theme.customizablePalette && hasPalettes){
if(Theme.paletteNames.Count < 1){
var palettePath = Theme.storagePath+"Palettes/";
Theme.paletteNames = ThemePalette.all.Select(x=>{
var path = x.path.Remove(palettePath,".unitypalette");
if(x.usesSystem && RelativeColor.system == Color.clear){
return path.Replace(path.GetPathTerm(),"/").Trim("/");
}
return path;
}).ToList();
}
var paletteNames = Theme.paletteNames.Copy();
var popupStyle = EditorStyles.popup;
if(paletteAltered){
var name = paletteNames[index];
popupStyle = EditorStyles.popup.FontStyle("boldanditalic");
paletteNames[index] = name + " *";
}
Theme.paletteIndex = paletteNames.Draw(index,"Palette",popupStyle);
Theme.DrawPaletteMenu(true);
GUILayout.Space(3);
if(EditorUI.lastChanged){
Theme.AdjustPalette();
}
}
}
public static void DrawPaletteMenu(bool showAdjusters=false){
var theme = Theme.active;
if(GUILayoutUtility.GetLastRect().Clicked(1)){
var menu = new EditorMenu();
var clipboard = EditorGUIUtility.systemCopyBuffer;
menu.Add("Copy Palette",()=>EditorGUIUtility.systemCopyBuffer=theme.palette.Serialize());
if(clipboard.Contains("[Textured]")){
menu.Add("Paste Palette",()=>{
Theme.RecordAction(()=>{
theme.palette.Deserialize(clipboard);
Theme.SaveColors();
Theme.UpdateColors();
Theme.Rebuild();
});
});
}
menu.AddSeparator();
if(showAdjusters){
menu.Add("Previous Palette &F1",Theme.PreviousPalette);
menu.Add("Next Palette &F2",Theme.NextPalette);
}
else{
menu.Add("Randomize &F3",Theme.RandomizeColors);
}
menu.Draw();
}
}
public static void DrawFontsets(){
var theme = Theme.active;
bool hasFontsets = ThemeFontset.all.Count > 0;
bool fontsetAltered = !theme.fontset.Matches(ThemeFontset.all[Theme.fontsetIndex]);
if(theme.customizableFontset && hasFontsets){
if(Theme.fontsetNames.Count < 1){
var fontsetsPath = Theme.storagePath+"Fontsets/";
Theme.fontsetNames = ThemeFontset.all.Select(x=>x.path.Remove(fontsetsPath,".unityfontset").GetAssetPath()).ToList();
}
var fontsetNames = Theme.fontsetNames.Copy();
var popupStyle = EditorStyles.popup;
if(fontsetAltered){
var name = fontsetNames[Theme.fontsetIndex];
popupStyle = EditorStyles.popup.FontStyle("boldanditalic");
fontsetNames[Theme.fontsetIndex] = name + " *";
}
Theme.fontsetIndex = fontsetNames.Draw(Theme.fontsetIndex,"Fontset",popupStyle);
Theme.DrawFontsetMenu(true);
GUILayout.Space(3);
if(EditorUI.lastChanged){
var selectedFontset = ThemeFontset.all[Theme.fontsetIndex];
theme.fontset = new ThemeFontset(selectedFontset).UseBuffer(theme.fontset);
Undo.RecordPref<string>("EditorFontset"+Theme.suffix,selectedFontset.name);
Theme.SaveFontset();
Theme.Rebuild();
}
}
}
public static void DrawFontsetMenu(bool showAdjusters=false){
var theme = Theme.active;
if(GUILayoutUtility.GetLastRect().Clicked(1)){
var menu = new EditorMenu();
var clipboard = EditorGUIUtility.systemCopyBuffer;
menu.Add("Copy Fontset",()=>EditorGUIUtility.systemCopyBuffer=theme.fontset.Serialize());
if(clipboard.Contains("Font = ")){
menu.Add("Paste Fontset",()=>{
Theme.RecordAction(()=>{
theme.fontset.Deserialize(clipboard);
Theme.SaveFontset();
Theme.Rebuild();
});
});
}
if(showAdjusters){
menu.AddSeparator();
menu.Add("Previous Fontset %F1",Theme.PreviousFontset);
menu.Add("Next Fontset %F2",Theme.NextFontset);
}
menu.Draw();
}
}
public static void DrawVariants(){
if(Theme.active.name == "Default" || Theme.active.skinset.variants.Count < 1){return;}
var theme = Theme.active;
bool open = "Variants".ToLabel().DrawFoldout("Theme.Variants");
if(EditorUI.lastChanged){GUI.changed=false;}
if(open){
EditorGUI.indentLevel += 1;
foreach(var variant in theme.skinset.variants){
variant.active = variant.active.Draw(variant.name.ToTitleCase());
if(EditorUI.lastChanged){
Theme.Refresh();
Undo.RecordPref<bool>("EditorVariant"+Theme.suffix+"-"+variant.name,variant.active);
}
}
EditorGUI.indentLevel -= 1;
}
}
public static void DrawOptions(){
bool open = "Options".ToLabel().DrawFoldout("Theme.Options");
if(EditorUI.lastChanged){GUI.changed=false;}
if(open){
EditorGUI.indentLevel += 1;
//Theme.verticalSpacing = Theme.verticalSpacing.Draw("Vertical Spacing");
Theme.hoverResponse = Theme.hoverResponse.Draw("Hover Response").As<HoverResponse>();
Theme.separatePlaymodeSettings = Theme.separatePlaymodeSettings.Draw("Separate Playmode Settings");
if(EditorUI.lastChanged){
Undo.RecordPref<bool>("EditorTheme-SeparatePlaymodeSettings",Theme.separatePlaymodeSettings);
Theme.Reset(true);
return;
}
Theme.disabled = Theme.disabled.Draw("Disable System");
if(!Theme.window.IsNull()){
Theme.window.wantsMouseMove = Theme.hoverResponse != HoverResponse.None;
}
Undo.RecordPref<int>("EditorTheme-HoverResponse",Theme.hoverResponse.ToInt());
Undo.RecordPref<bool>("EditorTheme-Disabled",Theme.disabled);
GUILayout.Space(2);
EditorGUI.indentLevel -= 1;
}
}
public static void DrawColors(){
var theme = Theme.active;
bool hasPalettes = ThemePalette.all.Count > 0;
bool paletteAltered = !theme.palette.Matches(ThemePalette.all[Theme.paletteIndex]);
var existingChanges = GUI.changed;
if(theme.customizablePalette && hasPalettes){
bool open = "Colors".ToLabel().DrawFoldout("Theme.Colors");
if(EditorUI.lastChanged){GUI.changed=false;}
Theme.DrawPaletteMenu();
if(!open){return;}
EditorGUI.indentLevel += 1;
Theme.showColorsAdvanced = Theme.showColorsAdvanced.Draw("Advanced");
if(Theme.showColorsAdvanced){RelativeColor.autoBalance = RelativeColor.autoBalance.Draw("Autobalance").As<AutoBalance>();}
foreach(var group in theme.palette.colors.Where(x=>x.Key!="*")){
var groupName = group.Key;
var isGroup = groupName != "Default";
var colorCount = theme.palette.colors[groupName].Count(x=>x.Value.source.IsNull());
var canExpand = Theme.showColorsAdvanced || colorCount > 3;
if(!Theme.showColorsAdvanced && colorCount < 1){continue;}
if(canExpand){
var drawFoldout = groupName.ToLabel().DrawFoldout("Theme.Colors."+groupName);
if(EditorUI.lastChanged){GUI.changed=false;}
if(isGroup && !drawFoldout){continue;}
if(isGroup){
EditorGUI.indentLevel += 1;
}
}
var names = theme.palette.colors["*"].Keys.ToList();
if(Application.platform == RuntimePlatform.WindowsEditor){
names = "@System".AsArray().Concat(names).ToList();
}
foreach(var item in theme.palette.colors[groupName]){
var color = item.Value;
Rect area = new Rect(1,1,1,1);
if(!color.sourceName.IsEmpty()){
if(!Theme.showColorsAdvanced){continue;}
var index = names.IndexOf(color.sourceName);
EditorGUILayout.BeginHorizontal();
if(index == -1){
var message = "[" + color.sourceName + " not found]";
index = names.Unshift(message).Draw(0,item.Key.ToTitleCase());
if(index != 0){color.sourceName = names[index];}
}
else{
color.sourceName = names[names.Draw(index,color.name.ToTitleCase())];
EditorUI.SetLayoutOnce(35);
if(color.blendMode == ColorBlend.Normal){color.offset = color.offset.Draw(null,null,false);}
color.Assign(theme.palette,color.sourceName);
if(color.blendMode != ColorBlend.Normal){
EditorUI.SetLayoutOnce(100);
color.blendMode = color.blendMode.Draw(null,null,false).As<ColorBlend>();
EditorUI.SetLayoutOnce(35);
color.offset = color.offset.Draw("",null,false).Clamp(0,1);
EditorUI.SetLayoutOnce(80);
color.blend = color.blend.Draw("",false);
}
}
EditorGUILayout.EndHorizontal();
area = GUILayoutUtility.GetLastRect();
GUILayout.Space(2);
}
else{
color.value = color.value.Draw(color.name.ToTitleCase());
area = GUILayoutUtility.GetLastRect();
}
if(area.Clicked(1)){
GenericMenu menu = new GenericMenu();
menu.AddItem(new GUIContent("Normal"),color.sourceName.IsEmpty(),()=>{
color.blendMode = ColorBlend.Normal;
color.sourceName = "";
});
menu.AddItem(new GUIContent("Inherited"),!color.sourceName.IsEmpty()&&color.blendMode==ColorBlend.Normal,()=>{
color.blendMode = ColorBlend.Normal;
if(color.sourceName.IsEmpty()){color.sourceName = names[0];}
});
menu.AddItem(new GUIContent("Blended"),color.blendMode!=ColorBlend.Normal,()=>{
color.blendMode = ColorBlend.Lighten;
if(color.sourceName.IsEmpty()){color.sourceName = names[0];}
});
menu.ShowAsContext();
UnityEvent.current.Use();
}
}
if(canExpand && isGroup){
EditorGUI.indentLevel -= 1;
}
}
if(paletteAltered){
EditorGUILayout.BeginHorizontal();
GUILayout.Space(15);
if(GUILayout.Button("Save As",GUILayout.Width(100))){theme.palette.Export();}
if(GUILayout.Button("Reset",GUILayout.Width(100))){Theme.LoadColors(true);}
if(GUILayout.Button("Apply",GUILayout.Width(100))){theme.palette.Export(theme.palette.path);}
EditorGUILayout.EndHorizontal();
}
if(!existingChanges && GUI.changed){
Theme.SaveColors();
Undo.RecordPref<int>("EditorTheme-AutobalanceColors",RelativeColor.autoBalance.ToInt());
Undo.RecordPref<bool>("EditorTheme-ShowAdvancedColors",Theme.showColorsAdvanced);
Utility.DelayCall(Theme.Refresh,0.1f);
GUI.changed = false;
}
EditorGUI.indentLevel -=1;
}
}
public static void PrepareFonts(){
var fontPath = Theme.storagePath+"Fonts/";
var fontFiles = FileManager.FindAll("*.*tf").Where(x=>!x.path.Contains("Fontsets")).ToArray();
Theme.builtinFonts = Locate.GetAssets<Font>().Where(x=>FileManager.GetPath(x).Contains("Library/unity")).ToArray();
Theme.fontNames = Theme.builtinFonts.Select(x=>"@Builtin/"+x.name).Concat(fontFiles.Select(x=>x.path)).ToList();
Func<string,string> FixFontNames = (data)=>{
data = data.Remove(fontPath,".ttf",".otf");
if(data.Contains("/")){
var folder = data.GetDirectory();
var folderPascal = folder.ToPascalCase();
data = folder + "/" + data.Split("/").Last().Remove(folderPascal+"-",folderPascal);
if(Theme.fontNames.Count(x=>x.Contains(folder+"/"))==1){
data = folder;
}
}
return data.GetAssetPath().Trim("/");
};
Theme.fontNames = Theme.fontNames.Select(x=>FixFontNames(x)).ToList();
Theme.fonts = Theme.builtinFonts.Concat(fontFiles.Select(x=>x.GetAsset<Font>())).ToArray();
}
public static void DrawFonts(){
var theme = Theme.active;
bool hasFontsets = ThemeFontset.all.Count > 0;
bool fontsetAltered = !theme.fontset.Matches(ThemeFontset.all[Theme.fontsetIndex]);
var existingChanges = GUI.changed;
if(theme.customizableFontset && hasFontsets){
bool open = "Fonts".ToLabel().DrawFoldout("Theme.Fonts");
if(EditorUI.lastChanged){GUI.changed=false;}
Theme.DrawFontsetMenu();
if(!open){return;}
EditorGUI.indentLevel += 1;
var fonts = Theme.fonts;
var fontNames = Theme.fontNames.Copy();
if(fontNames.Count < 1){fontNames.Add("No fonts found.");}
Theme.showFontsAdvanced = Theme.showFontsAdvanced.Draw("Advanced");
if(EditorUI.lastChanged){
Theme.SaveFontset();
GUI.changed = false;
}
foreach(var item in theme.fontset.fonts){
if(item.Value.font.IsNull()){continue;}
var themeFont = item.Value;
var fontName = item.Key.ToTitleCase();
var showRenderMode = Theme.showFontsAdvanced && !Theme.builtinFonts.Contains(themeFont.font);
EditorGUILayout.BeginHorizontal();
var index = fonts.IndexOf(themeFont.font);
if(index == -1){
EditorGUILayout.EndHorizontal();
var message = "[" + themeFont.name + " not found]";
index = fontNames.Unshift(message).Draw(0,item.Key.ToTitleCase());
if(index != 0){themeFont.font = fonts[index-1];}
continue;
}
if(showRenderMode){
var fontPath = FileManager.GetPath(themeFont.font);
var importer = Locate.GetImporter<TrueTypeFontImporter>(fontPath);
EditorUI.SetLayoutOnce(310);
var mode = importer.fontRenderingMode.Draw(fontName).As<FontRenderingMode>();
if(EditorUI.lastChanged){
Utility.RecordObject(importer,"Font Render Mode");
importer.fontRenderingMode = mode;
AssetDatabase.WriteImportSettingsIfDirty(fontPath);
AssetDatabase.Refresh();
}
fontName = null;
EditorUI.SetFieldSize(-1,1);
}
themeFont.font = fonts[fontNames.Draw(index,fontName,null,!showRenderMode)];
if(Theme.showFontsAdvanced){
EditorUI.SetFieldSize(0,35,false);
EditorUI.SetLayout(70);
themeFont.sizeOffset = themeFont.sizeOffset.DrawInt("Size",null,false);
EditorUI.SetFieldSize(0,20,false);
EditorUI.SetLayout(55);
themeFont.offsetX = themeFont.offsetX.Draw("X",null,false);
themeFont.offsetY = themeFont.offsetY.Draw("Y",null,false);
EditorUI.SetLayout(0);
EditorUI.SetFieldSize(0,200,false);
}
EditorGUILayout.EndHorizontal();
}
if(fontsetAltered){
EditorGUILayout.BeginHorizontal();
GUILayout.Space(15);
if(GUILayout.Button("Save As",GUILayout.Width(100))){theme.fontset.Export();}
if(GUILayout.Button("Reset",GUILayout.Width(100))){Theme.LoadFontset(true);}
if(GUILayout.Button("Apply",GUILayout.Width(100))){theme.fontset.Export(theme.fontset.path);}
EditorGUILayout.EndHorizontal();
}
EditorGUI.indentLevel -=1;
if(!existingChanges && GUI.changed){Theme.SaveFontset();}
GUILayout.Space(10);
}
}
//=================================
// Iconset
//=================================
public static void ApplyIconset(){
if(Theme.active.IsNull()){return;}
Theme.active.iconset = ThemeIconset.all[Theme.iconsetIndex];
if(!Theme.lazyLoaded && Theme.active.customizableIconset){
Undo.RecordPref<string>("EditorIconset"+Theme.suffix,Theme.active.iconset.name);
}
Theme.active.iconset.Apply();
}
//=================================
// Fonts
//=================================
public static void SaveFontset(){
var theme = Theme.active;
Undo.RecordPref<string>("EditorFontset-Settings"+Theme.suffix,theme.fontset.Serialize());
Undo.RecordPref<bool>("EditorTheme-ShowAdvancedFonts",Theme.showFontsAdvanced);
}
public static void LoadFontset(bool reset=false){
var theme = Theme.active;
if(reset){
var original = ThemeFontset.all[Theme.fontsetIndex];
theme.fontset = new ThemeFontset(original).UseBuffer(theme.fontset);
return;
}
var value = Utility.GetPref<string>("EditorFontset-Settings"+Theme.suffix,"");
theme.fontset.Deserialize(value);
}
[MenuItem("Edit/Themes/Development/Export/Fontset")]
public static void ExportFontset(){Theme.active.fontset.Export();}
//=================================
// Colors
//=================================
public static void SaveColors(){
var theme = Theme.active;
foreach(var group in theme.palette.colors.Where(x=>x.Key!="*")){
foreach(var color in group.Value){
Undo.RecordPref<string>("EditorTheme"+Theme.suffix+"-Color-"+group.Key+"-"+color.Key,color.Value.Serialize());
}
}
}
public static void LoadColors(bool reset=false){
var theme = Theme.active;
if(reset){
var original = ThemePalette.all[Theme.paletteIndex];
theme.palette = new ThemePalette().Use(original);
return;
}
foreach(var group in theme.palette.colors.Where(x=>x.Key!="*")){
foreach(var color in group.Value){
var value = Utility.GetPref<string>("EditorTheme"+Theme.suffix+"-Color-"+group.Key+"-"+color.Key,color.Value.Serialize());
theme.palette.colors["*"][color.Key] = theme.palette.colors[group.Key][color.Key].Deserialize(value);
}
}
foreach(var color in theme.palette.colors["*"].Copy()){
var name = color.Value.sourceName;
if(name.IsEmpty()){continue;}
var source = name == "@System" ? RelativeColor.system : theme.palette.colors["*"][name];
theme.palette.colors["*"][color.Key].Assign(source);
}
}
[MenuItem("Edit/Themes/Development/Export/Palette")]
public static void ExportPalette(){Theme.active.palette.Export();}
//=================================
// Shortcuts
//=================================
public static void DelayedInstantRefresh(){
Theme.needsInstantRefresh = true;
}
public static void InstantRefresh(){
Theme.setup = false;
Theme.Update();
Utility.DelayCall(Utility.RepaintAll,0.25f);
Theme.ApplyIconset();
}
public static void Reset(){Theme.Reset(false);}
public static void Reset(bool force){
if(force || Utility.IsPlaying()){
Theme.loaded = false;
Theme.setup = false;
}
}
[MenuItem("Edit/Themes/Development/Refresh #F1")]
public static void DebugRefresh(){
Theme.LoadCheck();
Debug.Log("[Themes] Example Info message.");
Debug.LogError("[Themes] Example Error message.");
Debug.LogWarning("[Themes] Example Warning message.");
Theme.Reset(true);
Theme.disabled = false;
}
[MenuItem("Edit/Themes/Development/Toggle Debug #F2")]
public static void ToggleDebug(){
Theme.debug = !Theme.debug;
Debug.Log("[Themes] Debug messages : " + Theme.debug);
}
[MenuItem("Edit/Themes/Development/Toggle Live Edit #F3")]
public static void ToggleLiveEdit(){
Theme.liveEdit = !Theme.liveEdit;
Debug.Log("[Themes] Live edit : " + Theme.liveEdit);
}
[MenuItem("Edit/Themes/Previous Palette &F1")]
public static void PreviousPalette(){Theme.RecordAction(()=>Theme.AdjustPalette(-1));}
[MenuItem("Edit/Themes/Next Palette &F2")]
public static void NextPalette(){Theme.RecordAction(()=>Theme.AdjustPalette(1));}
public static void AdjustPalette(){Theme.AdjustPalette(0);}
public static void AdjustPalette(int adjust){
Theme.LoadCheck();
var theme = Theme.active;
if(!theme.IsNull() && theme.customizablePalette){
var usable = false;
ThemePalette palette = null;
while(!usable){
Theme.paletteIndex = (Theme.paletteIndex + adjust) % ThemePalette.all.Count;
if(Theme.paletteIndex < 0){Theme.paletteIndex = ThemePalette.all.Count-1;}
palette = ThemePalette.all[Theme.paletteIndex];
usable = !palette.usesSystem || (RelativeColor.system != Color.clear);
}
theme.palette = new ThemePalette().Use(palette);
Undo.RecordPref<string>("EditorPalette"+Theme.suffix,palette.name);
Theme.SaveColors();
Theme.singleUpdate = true;
Theme.UpdateColors();
Theme.Refresh();
Utility.DelayCall(Theme.Rebuild,0.5f);
}
}
[MenuItem("Edit/Themes/Development/Randomize Colors &F3")]
public static void RandomizeColors(){
foreach(var color in Theme.active.palette.colors["*"]){
if(color.Value.skipTexture || !color.Value.sourceName.IsEmpty()){continue;}
color.Value.value = Color.white.Random(0);
}
Theme.SaveColors();
Theme.Refresh();
Theme.delayUpdate = true;
Theme.singleUpdate = true;
var time = Time.realtimeSinceStartup;
if(Theme.colorChangeCount > 35){
Application.OpenURL("https://goo.gl/gg9609");
Theme.colorChangeCount = -9609;
}
if(time < Theme.colorChangeTime){Theme.colorChangeCount += 1;}
else if(Theme.colorChangeCount > 0){Theme.colorChangeCount = 0;}
Theme.colorChangeTime = time + 1;
}
[MenuItem("Edit/Themes/Previous Fontset %F1")]
public static void PreviousFontset(){Theme.RecordAction(()=>Theme.AdjustFontset(-1));}
[MenuItem("Edit/Themes/Next Fontset %F2")]
public static void NextFontset(){Theme.RecordAction(()=>Theme.AdjustFontset(1));}
public static void AdjustFontset(int adjust){
Theme.LoadCheck();
var theme = Theme.active;
if(!theme.IsNull() && theme.customizableFontset){
Theme.fontsetIndex = (Theme.fontsetIndex + adjust) % ThemeFontset.all.Count;
if(Theme.fontsetIndex < 0){Theme.fontsetIndex = ThemeFontset.all.Count-1;}
var defaultFontset = ThemeFontset.all[Theme.fontsetIndex];
theme.fontset = new ThemeFontset(defaultFontset).UseBuffer(theme.fontset);
Undo.RecordPref("EditorFontset"+Theme.suffix,defaultFontset.name);
Theme.SaveFontset();
Theme.Rebuild();
}
}
public static void RecordAction(Action method){
Undo.RecordStart(typeof(Theme));
Theme.undoCallback = Theme.Rebuild;
method();
Undo.RecordEnd("Theme Changes",typeof(Theme),Theme.undoCallback);
}
}
public class ThemesAbout : EditorWindow{
[MenuItem("Edit/Themes/About",false,1)]
public static void Init(){
var window = ScriptableObject.CreateInstance<ThemesAbout>();
window.position = new Rect(100,100,1,1);
window.minSize = window.maxSize = new Vector2(190,120);
window.ShowAuxWindow();
}
public void OnGUI(){
this.SetTitle("About Zios Themes");
string buildText = "Build <b>"+ Theme.revision+"</b>";
EditorGUILayout.BeginVertical(new GUIStyle().Padding(15,15,15,0));
buildText.ToLabel().DrawLabel(EditorStyles.label.RichText(true).Clipping("Overflow").FontSize(15).Alignment("UpperCenter"));
"Part of the <i>Zios</i> framework. Developed by Brad Smithee.".ToLabel().DrawLabel(EditorStyles.wordWrappedLabel.FontSize(12).RichText(true));
if("Source Repository".ToLabel().DrawButton(GUI.skin.button.FixedWidth(150).Margin(12,0,5,0))){
Application.OpenURL("https://github.com/zios/unity-themes");
}
EditorGUILayout.EndVertical();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Nini.Config;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModules.SharedBase;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.PhysicsModule.POS
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "POSPhysicsScene")]
public class POSScene : PhysicsScene, INonSharedRegionModule
{
private List<POSCharacter> _characters = new List<POSCharacter>();
private List<POSPrim> _prims = new List<POSPrim>();
private float[] _heightMap;
private const float gravity = -9.8f;
private bool m_Enabled = false;
//protected internal string sceneIdentifier;
#region INonSharedRegionModule
public string Name
{
get { return "POS"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
// TODO: Move this out of Startup
IConfig config = source.Configs["Startup"];
if (config != null)
{
string physics = config.GetString("physics", string.Empty);
if (physics == Name)
m_Enabled = true;
}
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
EngineType = Name;
PhysicsSceneName = EngineType + "/" + scene.RegionInfo.RegionName;
scene.RegisterModuleInterface<PhysicsScene>(this);
base.Initialise(scene.PhysicsRequestAsset,
(scene.Heightmap != null ? scene.Heightmap.GetFloatsSerialised() : new float[Constants.RegionSize * Constants.RegionSize]),
(float)scene.RegionInfo.RegionSettings.WaterHeight);
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
}
#endregion
public override void Dispose()
{
}
public override PhysicsActor AddAvatar(
string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying)
{
POSCharacter act = new POSCharacter();
act.Position = position;
act.Flying = isFlying;
_characters.Add(act);
return act;
}
public override void RemovePrim(PhysicsActor prim)
{
POSPrim p = (POSPrim) prim;
if (_prims.Contains(p))
{
_prims.Remove(p);
}
}
public override void RemoveAvatar(PhysicsActor character)
{
POSCharacter act = (POSCharacter) character;
if (_characters.Contains(act))
{
_characters.Remove(act);
}
}
/*
public override PhysicsActor AddPrim(Vector3 position, Vector3 size, Quaternion rotation)
{
return null;
}
*/
public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
Vector3 size, Quaternion rotation, bool isPhysical, uint localid)
{
POSPrim prim = new POSPrim();
prim.Position = position;
prim.Orientation = rotation;
prim.Size = size;
_prims.Add(prim);
return prim;
}
private bool isColliding(POSCharacter c, POSPrim p)
{
Vector3 rotatedPos = new Vector3(c.Position.X - p.Position.X, c.Position.Y - p.Position.Y,
c.Position.Z - p.Position.Z) * Quaternion.Inverse(p.Orientation);
Vector3 avatarSize = new Vector3(c.Size.X, c.Size.Y, c.Size.Z) * Quaternion.Inverse(p.Orientation);
return (Math.Abs(rotatedPos.X) < (p.Size.X*0.5 + Math.Abs(avatarSize.X)) &&
Math.Abs(rotatedPos.Y) < (p.Size.Y*0.5 + Math.Abs(avatarSize.Y)) &&
Math.Abs(rotatedPos.Z) < (p.Size.Z*0.5 + Math.Abs(avatarSize.Z)));
}
private bool isCollidingWithPrim(POSCharacter c)
{
foreach (POSPrim p in _prims)
{
if (isColliding(c, p))
{
return true;
}
}
return false;
}
public override void AddPhysicsActorTaint(PhysicsActor prim)
{
}
public override float Simulate(float timeStep)
{
float fps = 0;
for (int i = 0; i < _characters.Count; ++i)
{
fps++;
POSCharacter character = _characters[i];
float oldposX = character.Position.X;
float oldposY = character.Position.Y;
float oldposZ = character.Position.Z;
if (!character.Flying)
{
character._target_velocity.Z += gravity * timeStep;
}
Vector3 characterPosition = character.Position;
characterPosition.X += character._target_velocity.X * timeStep;
characterPosition.Y += character._target_velocity.Y * timeStep;
characterPosition.X = Util.Clamp(character.Position.X, 0.01f, Constants.RegionSize - 0.01f);
characterPosition.Y = Util.Clamp(character.Position.Y, 0.01f, Constants.RegionSize - 0.01f);
bool forcedZ = false;
float terrainheight = _heightMap[(int)character.Position.Y * Constants.RegionSize + (int)character.Position.X];
if (character.Position.Z + (character._target_velocity.Z * timeStep) < terrainheight + 2)
{
characterPosition.Z = terrainheight + character.Size.Z;
forcedZ = true;
}
else
{
characterPosition.Z += character._target_velocity.Z*timeStep;
}
/// this is it -- the magic you've all been waiting for! Ladies and gentlemen --
/// Completely Bogus Collision Detection!!!
/// better known as the CBCD algorithm
if (isCollidingWithPrim(character))
{
characterPosition.Z = oldposZ; // first try Z axis
if (isCollidingWithPrim(character))
{
characterPosition.Z = oldposZ + character.Size.Z / 4.4f; // try harder
if (isCollidingWithPrim(character))
{
characterPosition.Z = oldposZ + character.Size.Z / 2.2f; // try very hard
if (isCollidingWithPrim(character))
{
characterPosition.X = oldposX;
characterPosition.Y = oldposY;
characterPosition.Z = oldposZ;
characterPosition.X += character._target_velocity.X * timeStep;
if (isCollidingWithPrim(character))
{
characterPosition.X = oldposX;
}
characterPosition.Y += character._target_velocity.Y * timeStep;
if (isCollidingWithPrim(character))
{
characterPosition.Y = oldposY;
}
}
else
{
forcedZ = true;
}
}
else
{
forcedZ = true;
}
}
else
{
forcedZ = true;
}
}
characterPosition.X = Util.Clamp(character.Position.X, 0.01f, Constants.RegionSize - 0.01f);
characterPosition.Y = Util.Clamp(character.Position.Y, 0.01f, Constants.RegionSize - 0.01f);
character.Position = characterPosition;
character._velocity.X = (character.Position.X - oldposX)/timeStep;
character._velocity.Y = (character.Position.Y - oldposY)/timeStep;
if (forcedZ)
{
character._velocity.Z = 0;
character._target_velocity.Z = 0;
((PhysicsActor)character).IsColliding = true;
character.RequestPhysicsterseUpdate();
}
else
{
((PhysicsActor)character).IsColliding = false;
character._velocity.Z = (character.Position.Z - oldposZ)/timeStep;
}
}
return fps;
}
public override void GetResults()
{
}
public override bool IsThreaded
{
// for now we won't be multithreaded
get { return (false); }
}
public override void SetTerrain(float[] heightMap)
{
_heightMap = heightMap;
}
public override void DeleteTerrain()
{
}
public override void SetWaterLevel(float baseheight)
{
}
public override Dictionary<uint, float> GetTopColliders()
{
Dictionary<uint, float> returncolliders = new Dictionary<uint, float>();
return returncolliders;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Linq;
using Csla;
using Csla.Data;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// ProductTypeUpdatedByRootList (read only list).<br/>
/// This is a generated base class of <see cref="ProductTypeUpdatedByRootList"/> business object.
/// This class is a root collection.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="ProductTypeUpdatedByRootInfo"/> objects.
/// Updated by ProductTypeEdit
/// </remarks>
[Serializable]
#if WINFORMS
public partial class ProductTypeUpdatedByRootList : ReadOnlyBindingListBase<ProductTypeUpdatedByRootList, ProductTypeUpdatedByRootInfo>
#else
public partial class ProductTypeUpdatedByRootList : ReadOnlyListBase<ProductTypeUpdatedByRootList, ProductTypeUpdatedByRootInfo>
#endif
{
#region Event handler properties
[NotUndoable]
private static bool _singleInstanceSavedHandler = true;
/// <summary>
/// Gets or sets a value indicating whether only a single instance should handle the Saved event.
/// </summary>
/// <value>
/// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>.
/// </value>
public static bool SingleInstanceSavedHandler
{
get { return _singleInstanceSavedHandler; }
set { _singleInstanceSavedHandler = value; }
}
#endregion
#region Collection Business Methods
/// <summary>
/// Determines whether a <see cref="ProductTypeUpdatedByRootInfo"/> item is in the collection.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to search for.</param>
/// <returns><c>true</c> if the ProductTypeUpdatedByRootInfo is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int productTypeId)
{
foreach (var productTypeUpdatedByRootInfo in this)
{
if (productTypeUpdatedByRootInfo.ProductTypeId == productTypeId)
{
return true;
}
}
return false;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="ProductTypeUpdatedByRootList"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="ProductTypeUpdatedByRootList"/> collection.</returns>
public static ProductTypeUpdatedByRootList GetProductTypeUpdatedByRootList()
{
return DataPortal.Fetch<ProductTypeUpdatedByRootList>();
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="ProductTypeUpdatedByRootList"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetProductTypeUpdatedByRootList(EventHandler<DataPortalResult<ProductTypeUpdatedByRootList>> callback)
{
DataPortal.BeginFetch<ProductTypeUpdatedByRootList>(callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeUpdatedByRootList"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductTypeUpdatedByRootList()
{
// Use factory methods and do not use direct creation.
ProductTypeEditSaved.Register(this);
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = false;
AllowEdit = false;
AllowRemove = false;
RaiseListChangedEvents = rlce;
}
#endregion
#region Saved Event Handler
/// <summary>
/// Handle Saved events of <see cref="ProductTypeEdit"/> to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
internal void ProductTypeEditSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
var obj = (ProductTypeEdit)e.NewObject;
if (((ProductTypeEdit)sender).IsNew)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
Add(ProductTypeUpdatedByRootInfo.LoadInfo(obj));
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
else if (((ProductTypeEdit)sender).IsDeleted)
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.ProductTypeId == obj.ProductTypeId)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
this.RemoveItem(index);
RaiseListChangedEvents = rlce;
IsReadOnly = true;
break;
}
}
}
else
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.ProductTypeId == obj.ProductTypeId)
{
child.UpdatePropertiesOnSaved(obj);
#if !WINFORMS
var notifyCollectionChangedEventArgs =
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index);
OnCollectionChanged(notifyCollectionChangedEventArgs);
#else
var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index);
OnListChanged(listChangedEventArgs);
#endif
break;
}
}
}
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="ProductTypeUpdatedByRootList"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
var args = new DataPortalHookArgs();
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<IProductTypeUpdatedByRootListDal>();
var data = dal.Fetch();
LoadCollection(data);
}
OnFetchPost(args);
}
private void LoadCollection(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="ProductTypeUpdatedByRootList"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(DataPortal.FetchChild<ProductTypeUpdatedByRootInfo>(dr));
}
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
#region ProductTypeEditSaved nested class
// TODO: edit "ProductTypeUpdatedByRootList.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: ProductTypeEditSaved.Register(this);
/// <summary>
/// Nested class to manage the Saved events of <see cref="ProductTypeEdit"/>
/// to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects.
/// </summary>
private static class ProductTypeEditSaved
{
private static List<WeakReference> _references;
private static bool Found(object obj)
{
return _references.Any(reference => Equals(reference.Target, obj));
}
/// <summary>
/// Registers a ProductTypeUpdatedByRootList instance to handle Saved events.
/// to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects.
/// </summary>
/// <param name="obj">The ProductTypeUpdatedByRootList instance.</param>
public static void Register(ProductTypeUpdatedByRootList obj)
{
var mustRegister = _references == null;
if (mustRegister)
_references = new List<WeakReference>();
if (ProductTypeUpdatedByRootList.SingleInstanceSavedHandler)
_references.Clear();
if (!Found(obj))
_references.Add(new WeakReference(obj));
if (mustRegister)
ProductTypeEdit.ProductTypeEditSaved += ProductTypeEditSavedHandler;
}
/// <summary>
/// Handles Saved events of <see cref="ProductTypeEdit"/>.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
public static void ProductTypeEditSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
foreach (var reference in _references)
{
if (reference.IsAlive)
((ProductTypeUpdatedByRootList) reference.Target).ProductTypeEditSavedHandler(sender, e);
}
}
/// <summary>
/// Removes event handling and clears all registered ProductTypeUpdatedByRootList instances.
/// </summary>
public static void Unregister()
{
ProductTypeEdit.ProductTypeEditSaved -= ProductTypeEditSavedHandler;
_references = null;
}
}
#endregion
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type MessageExtensionsCollectionRequest.
/// </summary>
public partial class MessageExtensionsCollectionRequest : BaseRequest, IMessageExtensionsCollectionRequest
{
/// <summary>
/// Constructs a new MessageExtensionsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public MessageExtensionsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Extension to the collection via POST.
/// </summary>
/// <param name="extension">The Extension to add.</param>
/// <returns>The created Extension.</returns>
public System.Threading.Tasks.Task<Extension> AddAsync(Extension extension)
{
return this.AddAsync(extension, CancellationToken.None);
}
/// <summary>
/// Adds the specified Extension to the collection via POST.
/// </summary>
/// <param name="extension">The Extension to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Extension.</returns>
public System.Threading.Tasks.Task<Extension> AddAsync(Extension extension, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
extension.ODataType = string.Concat("#", StringHelper.ConvertTypeToLowerCamelCase(extension.GetType().FullName));
return this.SendAsync<Extension>(extension, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IMessageExtensionsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IMessageExtensionsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<MessageExtensionsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Expand(Expression<Func<Extension, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Select(Expression<Func<Extension, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using HaloSharp.Converter;
using Newtonsoft.Json;
namespace HaloSharp.Model.Stats.Common
{
[Serializable]
public class FlexibleStats : IEquatable<FlexibleStats>
{
/// <summary>
/// The set of flexible stats that are derived from impulse events.
/// </summary>
[JsonProperty(PropertyName = "ImpulseStatCounts")]
public List<StatCount> ImpulseStatCounts { get; set; }
/// <summary>
/// The set of flexible stats that are derived from impulse time lapses.
/// </summary>
[JsonProperty(PropertyName = "ImpulseTimelapses")]
public List<StatTimelapse> ImpulseTimelapses { get; set; }
/// <summary>
/// The set of flexible stats that are derived from medal events.
/// </summary>
[JsonProperty(PropertyName = "MedalStatCounts")]
public List<StatCount> MedalStatCounts { get; set; }
/// <summary>
/// The set of flexible stats that are derived from medal time lapses.
/// </summary>
[JsonProperty(PropertyName = "MedalTimelapses")]
public List<StatTimelapse> MedalTimelapses { get; set; }
public bool Equals(FlexibleStats other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return ImpulseStatCounts.OrderBy(isc => isc.Id).SequenceEqual(other.ImpulseStatCounts.OrderBy(isc => isc.Id))
&& ImpulseTimelapses.OrderBy(it => it.Id).SequenceEqual(other.ImpulseTimelapses.OrderBy(it => it.Id))
&& MedalStatCounts.OrderBy(msc => msc.Id).SequenceEqual(other.MedalStatCounts.OrderBy(msc => msc.Id))
&& MedalTimelapses.OrderBy(mt => mt.Id).SequenceEqual(other.MedalTimelapses.OrderBy(mt => mt.Id));
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof (FlexibleStats))
{
return false;
}
return Equals((FlexibleStats) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = ImpulseStatCounts?.GetHashCode() ?? 0;
hashCode = (hashCode*397) ^ (ImpulseTimelapses?.GetHashCode() ?? 0);
hashCode = (hashCode*397) ^ (MedalStatCounts?.GetHashCode() ?? 0);
hashCode = (hashCode*397) ^ (MedalTimelapses?.GetHashCode() ?? 0);
return hashCode;
}
}
public static bool operator ==(FlexibleStats left, FlexibleStats right)
{
return Equals(left, right);
}
public static bool operator !=(FlexibleStats left, FlexibleStats right)
{
return !Equals(left, right);
}
}
[Serializable]
public class StatTimelapse : IEquatable<StatTimelapse>
{
/// <summary>
/// The ID of the flexible stat.
/// </summary>
[JsonProperty(PropertyName = "Id")]
public Guid Id { get; set; }
/// <summary>
/// The amount of time the flexible stat was earned for.
/// </summary>
[JsonProperty(PropertyName = "Timelapse")]
[JsonConverter(typeof (TimeSpanConverter))]
public TimeSpan Timelapse { get; set; }
public bool Equals(StatTimelapse other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Id.Equals(other.Id)
&& Timelapse.Equals(other.Timelapse);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof (StatTimelapse))
{
return false;
}
return Equals((StatTimelapse) obj);
}
public override int GetHashCode()
{
unchecked
{
return (Id.GetHashCode()*397) ^ Timelapse.GetHashCode();
}
}
public static bool operator ==(StatTimelapse left, StatTimelapse right)
{
return Equals(left, right);
}
public static bool operator !=(StatTimelapse left, StatTimelapse right)
{
return !Equals(left, right);
}
}
[Serializable]
public class StatCount : IEquatable<StatCount>
{
/// <summary>
/// The number of times this flexible stat was earned.
/// </summary>
[JsonProperty(PropertyName = "Count")]
public int Count { get; set; }
/// <summary>
/// The ID of the flexible stat.
/// </summary>
[JsonProperty(PropertyName = "Id")]
public Guid Id { get; set; }
public bool Equals(StatCount other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Count == other.Count
&& Id.Equals(other.Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof (StatCount))
{
return false;
}
return Equals((StatCount) obj);
}
public override int GetHashCode()
{
unchecked
{
return (Count*397) ^ Id.GetHashCode();
}
}
public static bool operator ==(StatCount left, StatCount right)
{
return Equals(left, right);
}
public static bool operator !=(StatCount left, StatCount right)
{
return !Equals(left, right);
}
}
}
| |
// RichTextBoxEx.cs
// ------------------------------------------------------------------
//
// An extended RichTextBox that provides a few extra capabilities:
//
// 1. line numbering, fast and easy. It numbers the lines "as
// displayed" or according to the hard newlines in the text. The UI
// of the line numbers is configurable: color, font, width, leading
// zeros or not, etc. One limitation: the line #'s are always
// displayed to the left.
//
// 2. Programmatic scrolling
//
// 3. BeginUpdate/EndUpdate and other bells and whistles. Theres also
// BeginUpdateAndSateState()/EndUpdateAndRestoreState(), to keep the
// cursor in place across select/updates.
//
// 4. properties: FirstVisibleLine / NumberOfVisibleLines - in support of
// line numbering.
//
//
// Copyright (c) 2010 Dino Chiesa.
// All rights reserved.
//
// This file is part of the source code disribution for Ionic's
// XPath Visualizer Tool.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.rtf or License.txt for the license details.
// More info on: http://XPathVisualizer.codeplex.com
//
// ------------------------------------------------------------------
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace Ionic.WinForms
{
/// <summary>
/// Defines methods for performing operations on RichTextBox.
/// </summary>
///
/// <remarks>
/// <para>
/// The methods in this class could be defined as "extension methods" but
/// for efficiency I'd like to retain some state between calls - for
/// example the handle on the richtextbox or the buffer and structure for
/// the EM_SETCHARFORMAT message, which can be called many times in quick
/// succession.
/// </para>
///
/// <para>
/// We define these in a separate class for speed and efficiency. For the
/// RichTextBox, in order to make a change in format of some portion of
/// the text, the app must select the text. When the RTB has focus, it
/// will scroll when the selection is updated. If we want to retain state
/// while highlighting text then, we'll have to restore the scroll state
/// after a highlight is applied. But this will produce an ugly UI effect
/// where the scroll jumps forward and back repeatedly. To avoid that, we
/// need to suppress updates to the RTB, using the WM_SETREDRAW message.
/// </para>
///
/// <para>
/// As a complement to that, we also have some speedy methods to get and
/// set the scroll state, and the selection state.
/// </para>
///
/// </remarks>
[ToolboxBitmap(typeof(RichTextBox))]
public class RichTextBoxEx : RichTextBox
{
private User32.CHARFORMAT charFormat;
private IntPtr lParam1;
private int _savedScrollLine;
private int _savedSelectionStart;
private int _savedSelectionEnd;
private Pen _borderPen;
private System.Drawing.StringFormat _stringDrawingFormat;
private System.Security.Cryptography.HashAlgorithm alg; // used for comparing text values
public RichTextBoxEx()
{
charFormat = new User32.CHARFORMAT()
{
cbSize = Marshal.SizeOf(typeof(User32.CHARFORMAT)),
szFaceName= new char[32]
};
lParam1= Marshal.AllocCoTaskMem( charFormat.cbSize );
// defaults
NumberFont= new System.Drawing.Font("Consolas",
9.75F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point, ((byte)(0)));
NumberColor = Color.FromName("DarkGray");
NumberLineCounting = LineCounting.CRLF;
NumberAlignment = StringAlignment.Center;
NumberBorder = SystemColors.ControlDark;
NumberBorderThickness = 1;
NumberPadding = 2;
NumberBackground1 = SystemColors.ControlLight;
NumberBackground2= SystemColors.Window;
SetStringDrawingFormat();
alg = System.Security.Cryptography.SHA1.Create();
}
~RichTextBoxEx()
{
// Free the allocated memory
Marshal.FreeCoTaskMem(lParam1);
}
private void SetStringDrawingFormat()
{
_stringDrawingFormat = new System.Drawing.StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = NumberAlignment,
Trimming = StringTrimming.None,
};
}
protected override void OnTextChanged(EventArgs e)
{
NeedRecomputeOfLineNumbers();
base.OnTextChanged(e);
}
public void BeginUpdate()
{
User32.SendMessage(this.Handle, (int)User32.Msgs.WM_SETREDRAW, 0, IntPtr.Zero);
}
public void EndUpdate()
{
User32.SendMessage(this.Handle, (int)User32.Msgs.WM_SETREDRAW, 1, IntPtr.Zero);
}
public IntPtr BeginUpdateAndSuspendEvents()
{
// Stop redrawing:
User32.SendMessage(this.Handle, (int) User32.Msgs.WM_SETREDRAW, 0, IntPtr.Zero);
// Stop sending of events:
IntPtr eventMask = User32.SendMessage(this.Handle, User32.Msgs.EM_GETEVENTMASK, 0, IntPtr.Zero);
return eventMask;
}
public void EndUpdateAndResumeEvents(IntPtr eventMask)
{
// turn on events
User32.SendMessage(this.Handle, User32.Msgs.EM_SETEVENTMASK, 0, eventMask);
// turn on redrawing
User32.SendMessage(this.Handle, User32.Msgs.WM_SETREDRAW, 1, IntPtr.Zero);
NeedRecomputeOfLineNumbers();
this.Invalidate();
}
public void GetSelection(out int start, out int end)
{
User32.SendMessageRef(this.Handle, (int)User32.Msgs.EM_GETSEL, out start, out end);
}
public void SetSelection(int start, int end)
{
User32.SendMessage(this.Handle, (int)User32.Msgs.EM_SETSEL, start, end);
}
public void BeginUpdateAndSaveState()
{
User32.SendMessage(this.Handle, (int)User32.Msgs.WM_SETREDRAW, 0, IntPtr.Zero);
// save scroll position
_savedScrollLine = FirstVisibleDisplayLine;
// save selection
GetSelection(out _savedSelectionStart, out _savedSelectionEnd);
}
public void EndUpdateAndRestoreState()
{
// restore scroll position
int Line1 = FirstVisibleDisplayLine;
Scroll(_savedScrollLine - Line1);
// restore the selection/caret
SetSelection(_savedSelectionStart, _savedSelectionEnd);
// allow redraw
User32.SendMessage(this.Handle, (int)User32.Msgs.WM_SETREDRAW, 1, IntPtr.Zero);
// explicitly ask for a redraw?
Refresh();
}
private String _sformat;
private int _ndigits;
private int _lnw = -1;
private int LineNumberWidth
{
get
{
if (_lnw > 0) return _lnw;
if (NumberLineCounting == LineCounting.CRLF)
{
_ndigits = (CharIndexForTextLine.Length == 0)
? 1
: (int)(1 + Math.Log((double)CharIndexForTextLine.Length, 10));
}
else
{
int n = GetDisplayLineCount();
_ndigits = (n == 0)
? 1
: (int)(1 + Math.Log((double)n, 10));
}
var s = new String('0', _ndigits);
var b = new Bitmap(400,400); // in pixels
var g = Graphics.FromImage(b);
SizeF size = g.MeasureString(s, NumberFont);
g.Dispose();
_lnw = NumberPadding * 2 + 4 + (int) (size.Width + 0.5 + NumberBorderThickness);
_sformat = "{0:D" + _ndigits + "}";
return _lnw;
}
}
public bool _lineNumbers;
public bool ShowLineNumbers
{
get
{
return _lineNumbers;
}
set
{
if (value == _lineNumbers) return;
SetLeftMargin(value ? LineNumberWidth + Margin.Left : Margin.Left);
_lineNumbers = value;
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
}
}
private void NeedRecomputeOfLineNumbers()
{
//System.Console.WriteLine("Need Recompute of line numbers...");
_CharIndexForTextLine = null;
_Text2 = null;
_lnw = -1;
if (_paintingDisabled) return;
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
}
private Font _NumberFont;
public Font NumberFont
{
get { return _NumberFont; }
set
{
if (_NumberFont == value) return;
_lnw = -1;
_NumberFont = value;
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
}
}
private LineCounting _NumberLineCounting;
public LineCounting NumberLineCounting
{
get { return _NumberLineCounting; }
set
{
if (_NumberLineCounting == value) return;
_lnw = -1;
_NumberLineCounting = value;
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
}
}
private StringAlignment _NumberAlignment;
public StringAlignment NumberAlignment
{
get { return _NumberAlignment; }
set
{
if (_NumberAlignment == value) return;
_NumberAlignment = value;
SetStringDrawingFormat();
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
}
}
private Color _NumberColor;
public Color NumberColor
{
get { return _NumberColor; }
set
{
if (_NumberColor.ToArgb() == value.ToArgb()) return;
_NumberColor = value;
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
}
}
private bool _NumberLeadingZeroes;
public bool NumberLeadingZeroes
{
get { return _NumberLeadingZeroes; }
set
{
if (_NumberLeadingZeroes == value) return;
_NumberLeadingZeroes = value;
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
}
}
private Color _NumberBorder;
public Color NumberBorder
{
get { return _NumberBorder; }
set
{
if (_NumberBorder.ToArgb() == value.ToArgb()) return;
_NumberBorder = value;
NewBorderPen();
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
}
}
private int _NumberPadding;
public int NumberPadding
{
get { return _NumberPadding; }
set
{
if (_NumberPadding == value) return;
_lnw = -1;
_NumberPadding = value;
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
}
}
public Single _NumberBorderThickness;
public Single NumberBorderThickness
{
get { return _NumberBorderThickness; }
set
{
if (_NumberBorderThickness == value) return;
_lnw = -1;
_NumberBorderThickness = value;
NewBorderPen();
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
}
}
private Color _NumberBackground1;
public Color NumberBackground1
{
get { return _NumberBackground1; }
set
{
if (_NumberBackground1.ToArgb() == value.ToArgb()) return;
_NumberBackground1 = value;
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
}
}
private Color _NumberBackground2;
public Color NumberBackground2
{
get { return _NumberBackground2; }
set
{
if (_NumberBackground2.ToArgb() == value.ToArgb()) return;
_NumberBackground2 = value;
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
}
}
private bool _paintingDisabled;
public void SuspendLineNumberPainting()
{
_paintingDisabled = true;
}
public void ResumeLineNumberPainting()
{
_paintingDisabled = false;
}
private void NewBorderPen()
{
_borderPen = new Pen(NumberBorder);
_borderPen.Width = NumberBorderThickness;
_borderPen.SetLineCap(LineCap.Round, LineCap.Round, DashCap.Round);
}
private DateTime _lastMsgRecd = new DateTime(1901,1,1);
protected override void WndProc(ref Message m)
{
bool handled = false;
switch (m.Msg)
{
case (int)User32.Msgs.WM_PAINT:
//System.Console.WriteLine("{0}", User32.Mnemonic(m.Msg));
//System.Console.Write(".");
if (_paintingDisabled) return;
if (_lineNumbers)
{
base.WndProc(ref m);
this.PaintLineNumbers();
handled = true;
}
break;
case (int)User32.Msgs.WM_CHAR:
// the text is being modified
NeedRecomputeOfLineNumbers();
break;
// case (int)User32.Msgs.EM_POSFROMCHAR:
// case (int)User32.Msgs.WM_GETDLGCODE:
// case (int)User32.Msgs.WM_ERASEBKGND:
// case (int)User32.Msgs.OCM_COMMAND:
// case (int)User32.Msgs.OCM_NOTIFY:
// case (int)User32.Msgs.EM_CHARFROMPOS:
// case (int)User32.Msgs.EM_LINEINDEX:
// case (int)User32.Msgs.WM_NCHITTEST:
// case (int)User32.Msgs.WM_SETCURSOR:
// case (int)User32.Msgs.WM_KEYUP:
// case (int)User32.Msgs.WM_KEYDOWN:
// case (int)User32.Msgs.WM_MOUSEMOVE:
// case (int)User32.Msgs.WM_MOUSEACTIVATE:
// case (int)User32.Msgs.WM_NCMOUSEMOVE:
// case (int)User32.Msgs.WM_NCMOUSEHOVER:
// case (int)User32.Msgs.WM_NCMOUSELEAVE:
// case (int)User32.Msgs.WM_NCLBUTTONDOWN:
// break;
//
// default:
// // divider
// var now = DateTime.Now;
// if ((now - _lastMsgRecd) > TimeSpan.FromMilliseconds(850))
// System.Console.WriteLine("------------ {0}", now.ToString("G"));
// _lastMsgRecd = now;
//
// System.Console.WriteLine("{0}", User32.Mnemonic(m.Msg));
// break;
}
if (!handled)
base.WndProc(ref m);
}
int _lastWidth = 0;
private void PaintLineNumbers()
{
//System.Console.WriteLine(">> PaintLineNumbers");
// To reduce flicker, double-buffer the output
if (_paintingDisabled) return;
int w = LineNumberWidth;
if (w!=_lastWidth)
{
//System.Console.WriteLine(" WIDTH change {0} != {1}", _lastWidth, w);
SetLeftMargin(w + Margin.Left);
_lastWidth = w;
// Don't bother painting line numbers - the margin isn't wide enough currently.
// Ask for a new paint, and paint them next time round.
User32.SendMessage(this.Handle, User32.Msgs.WM_PAINT, 0, 0);
return;
}
Bitmap buffer = new Bitmap(w, this.Bounds.Height);
Graphics g = Graphics.FromImage(buffer);
Brush forebrush = new SolidBrush(NumberColor);
var rect = new Rectangle (0, 0, w, this.Bounds.Height);
bool wantDivider = NumberBackground1.ToArgb() == NumberBackground2.ToArgb();
Brush backBrush = (wantDivider)
? (Brush) new SolidBrush(NumberBackground2)
: SystemBrushes.Window;
g.FillRectangle(backBrush, rect);
int n = (NumberLineCounting == LineCounting.CRLF)
? NumberOfVisibleTextLines
: NumberOfVisibleDisplayLines;
int first = (NumberLineCounting == LineCounting.CRLF)
? FirstVisibleTextLine
: FirstVisibleDisplayLine+1;
int py = 0;
int w2 = w - 2 - (int)NumberBorderThickness;
LinearGradientBrush brush;
Pen dividerPen = new Pen(NumberColor);
for (int i=0; i <= n; i++)
{
int ix = first + i;
int c = (NumberLineCounting == LineCounting.CRLF)
? GetCharIndexForTextLine(ix)
: GetCharIndexForDisplayLine(ix)-1;
var p = GetPosFromCharIndex(c+1);
Rectangle r4 = Rectangle.Empty;
if (i==n) // last line?
{
if (this.Bounds.Height <= py) continue;
r4 = new Rectangle (1, py, w2, this.Bounds.Height-py);
}
else
{
if (p.Y <= py) continue;
r4 = new Rectangle (1, py, w2, p.Y-py);
}
if (wantDivider)
{
if (i!=n)
g.DrawLine(dividerPen, 1, p.Y+1, w2, p.Y+1); // divider line
}
else
{
// new brush each time for gradient across variable rect sizes
brush = new LinearGradientBrush( r4,
NumberBackground1,
NumberBackground2,
LinearGradientMode.Vertical);
g.FillRectangle(brush, r4);
}
if (NumberLineCounting == LineCounting.CRLF) ix++;
// conditionally slide down
if (NumberAlignment == StringAlignment.Near)
rect.Offset(0, 3);
var s = (NumberLeadingZeroes) ? String.Format(_sformat, ix) : ix.ToString();
g.DrawString(s, NumberFont, forebrush, r4, _stringDrawingFormat);
py = p.Y;
}
if (NumberBorderThickness != 0.0)
{
int t = (int)(w-(NumberBorderThickness+0.5)/2) - 1;
g.DrawLine(_borderPen, t, 0, t, this.Bounds.Height);
//g.DrawLine(_borderPen, w-2, 0, w-2, this.Bounds.Height);
}
// paint that buffer to the screen
Graphics g1 = this.CreateGraphics();
g1.DrawImage(buffer, new Point(0,0));
g1.Dispose();
g.Dispose();
}
private int GetCharIndexFromPos(int x, int y)
{
var p = new User32.POINTL { X= x, Y = y };
int rawSize = Marshal.SizeOf( typeof(User32.POINTL) );
IntPtr lParam = Marshal.AllocHGlobal( rawSize );
Marshal.StructureToPtr(p, lParam, false);
int r = User32.SendMessage(this.Handle, (int)User32.Msgs.EM_CHARFROMPOS, 0, lParam);
Marshal.FreeHGlobal( lParam );
return r;
}
private Point GetPosFromCharIndex(int ix)
{
int rawSize = Marshal.SizeOf( typeof(User32.POINTL) );
IntPtr wParam = Marshal.AllocHGlobal( rawSize );
int r = User32.SendMessage(this.Handle, (int)User32.Msgs.EM_POSFROMCHAR, (int)wParam, ix);
User32.POINTL p1 = (User32.POINTL) Marshal.PtrToStructure(wParam, typeof(User32.POINTL));
Marshal.FreeHGlobal( wParam );
var p = new Point { X= p1.X, Y = p1.Y };
return p;
}
private int GetLengthOfLineContainingChar(int charIndex)
{
int r = User32.SendMessage(this.Handle, (int)User32.Msgs.EM_LINELENGTH, 0,0);
return r;
}
private int GetLineFromChar(int charIndex)
{
return User32.SendMessage(this.Handle, (int)User32.Msgs.EM_LINEFROMCHAR, charIndex, 0);
}
private int GetCharIndexForDisplayLine(int line)
{
return User32.SendMessage(this.Handle, (int)User32.Msgs.EM_LINEINDEX, line, 0);
}
private int GetDisplayLineCount()
{
return User32.SendMessage(this.Handle, (int)User32.Msgs.EM_GETLINECOUNT, 0, 0);
}
/// <summary>
/// Sets the color of the characters in the given range.
/// </summary>
///
/// <remarks>
/// Calling this is equivalent to calling
/// <code>
/// richTextBox.Select(start, end-start);
/// this.richTextBox1.SelectionColor = color;
/// </code>
/// ...but without the error and bounds checking.
/// </remarks>
///
public void SetSelectionColor(int start, int end, System.Drawing.Color color)
{
User32.SendMessage(this.Handle, (int)User32.Msgs.EM_SETSEL, start, end);
charFormat.dwMask = 0x40000000;
charFormat.dwEffects = 0;
charFormat.crTextColor = System.Drawing.ColorTranslator.ToWin32(color);
Marshal.StructureToPtr(charFormat, lParam1, false);
User32.SendMessage(this.Handle, (int)User32.Msgs.EM_SETCHARFORMAT, User32.SCF_SELECTION, lParam1);
}
private void SetLeftMargin(int widthInPixels)
{
User32.SendMessage(this.Handle, (int)User32.Msgs.EM_SETMARGINS, User32.EC_LEFTMARGIN,
widthInPixels);
}
public Tuple<int,int> GetMargins()
{
int r = User32.SendMessage(this.Handle, (int)User32.Msgs.EM_GETMARGINS, 0,0);
return Tuple.New(r & 0x0000FFFF, (int)((r>>16) & 0x0000FFFF));
}
public void Scroll(int delta)
{
User32.SendMessage(this.Handle, (int)User32.Msgs.EM_LINESCROLL, 0, delta);
}
private int FirstVisibleDisplayLine
{
get
{
return User32.SendMessage(this.Handle, (int)User32.Msgs.EM_GETFIRSTVISIBLELINE, 0, 0);
}
set
{
// scroll
int current = FirstVisibleDisplayLine;
int delta = value - current;
User32.SendMessage(this.Handle, (int)User32.Msgs.EM_LINESCROLL, 0, delta);
}
}
private int NumberOfVisibleDisplayLines
{
get
{
int topIndex = this.GetCharIndexFromPosition(new System.Drawing.Point(1, 1));
int bottomIndex = this.GetCharIndexFromPosition(new System.Drawing.Point(1, this.Height - 1));
int topLine = this.GetLineFromCharIndex(topIndex);
int bottomLine = this.GetLineFromCharIndex(bottomIndex);
int n = bottomLine - topLine + 1;
return n;
}
}
private int FirstVisibleTextLine
{
get
{
int c = GetCharIndexFromPos(1,1);
for (int i=0; i < CharIndexForTextLine.Length; i++)
{
if (c < CharIndexForTextLine[i]) return i;
}
return CharIndexForTextLine.Length;
}
}
private int LastVisibleTextLine
{
get
{
int c = GetCharIndexFromPos(1,this.Bounds.Y+this.Bounds.Height);
for (int i=0; i < CharIndexForTextLine.Length; i++)
{
if (c < CharIndexForTextLine[i]) return i;
}
return CharIndexForTextLine.Length;
}
}
private int NumberOfVisibleTextLines
{
get
{
return LastVisibleTextLine - FirstVisibleTextLine;
}
}
public int FirstVisibleLine
{
get
{
if (this.NumberLineCounting == LineCounting.CRLF)
return FirstVisibleTextLine;
else
return FirstVisibleDisplayLine;
}
}
public int NumberOfVisibleLines
{
get
{
if (this.NumberLineCounting == LineCounting.CRLF)
return NumberOfVisibleTextLines;
else
return NumberOfVisibleDisplayLines;
}
}
private int GetCharIndexForTextLine(int ix)
{
if (ix >= CharIndexForTextLine.Length) return 0;
if (ix < 0) return 0;
return CharIndexForTextLine[ix];
}
// The char index is expensive to compute.
private int[] _CharIndexForTextLine;
private int[] CharIndexForTextLine
{
get
{
if (_CharIndexForTextLine == null)
{
var list = new List<int>();
int ix = 0;
foreach( var c in Text2 )
{
if ( c == '\n' ) list.Add(ix);
ix++;
}
_CharIndexForTextLine = list.ToArray();
}
return _CharIndexForTextLine;
}
}
private String _Text2;
private String Text2
{
get
{
if (_Text2 == null)
_Text2 = this.Text;
return _Text2;
}
}
private bool CompareHashes(byte[] a, byte[] b)
{
if (a.Length != b.Length) return false;
for (int i=0; i < a.Length; i++)
{
if (a[i]!=b[i]) return false;
}
return true; // they are equal
}
public enum LineCounting
{
CRLF,
AsDisplayed
}
}
public static class Tuple
{
// Allows Tuple.New(1, "2") instead of new Tuple<int, string>(1, "2")
public static Tuple<T1, T2> New<T1, T2>(T1 v1, T2 v2)
{
return new Tuple<T1, T2>(v1, v2);
}
}
public class Tuple<T1, T2>
{
public Tuple(T1 v1, T2 v2)
{
V1 = v1;
V2 = v2;
}
public T1 V1 { get; set; }
public T2 V2 { get; set; }
}
}
| |
// 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.Numerics;
using System.Runtime.CompilerServices;
// GitHub 20211: bug with lowering SIMDIntrinsicGetItem on ARM64
// when INS_mov (move w/o sign-extension) was used to copy signed value
// from Vn.b[i] (or Vn.h[i]) to general register Wd (or Xd) instead of
// INS_smov (move with sign-extension).
namespace GitHub_20211
{
class Program
{
[MethodImpl(MethodImplOptions.NoInlining)]
static unsafe sbyte SquareRootAt0(Vector<sbyte> arg)
{
return (sbyte)Math.Sqrt(arg[0]);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static unsafe byte SquareRootAt0(Vector<byte> arg)
{
return (byte)Math.Sqrt(arg[0]);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static unsafe short SquareRootAt0(Vector<short> arg)
{
return (short)Math.Sqrt(arg[0]);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static unsafe ushort SquareRootAt0(Vector<ushort> arg)
{
return (ushort)Math.Sqrt(arg[0]);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static unsafe int SquareRootAt0(Vector<int> arg)
{
return (int)Math.Sqrt(arg[0]);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static unsafe uint SquareRootAt0(Vector<uint> arg)
{
return (uint)Math.Sqrt(arg[0]);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static unsafe long SquareRootAt0(Vector<long> arg)
{
return (long)Math.Sqrt(arg[0]);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static unsafe ulong SquareRootAt0(Vector<ulong> arg)
{
return (ulong)Math.Sqrt(arg[0]);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static unsafe float SquareRootAt0(Vector<float> arg)
{
return (float)Math.Sqrt(arg[0]);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static unsafe double SquareRootAt0(Vector<double> arg)
{
return (double)Math.Sqrt(arg[0]);
}
enum Result { Pass, Fail }
struct TestRunner
{
void TestSquareRootAt0(sbyte arg0)
{
Vector<sbyte> arg = new Vector<sbyte>(arg0);
sbyte actual = SquareRootAt0(arg);
sbyte expected = (sbyte)Math.Sqrt(arg0);
if (actual != expected)
{
Console.WriteLine($"Fail: sbyte (actual={actual}, expected={expected})");
result = Result.Fail;
}
}
void TestSquareRootAt0(byte arg0)
{
Vector<byte> arg = new Vector<byte>(arg0);
byte actual = SquareRootAt0(arg);
byte expected = (byte)Math.Sqrt(arg0);
if (actual != expected)
{
Console.WriteLine($"Fail: byte (actual={actual}, expected={expected})");
result = Result.Fail;
}
}
void TestSquareRootAt0(short arg0)
{
Vector<short> arg = new Vector<short>(arg0);
short actual = SquareRootAt0(arg);
short expected = (short)Math.Sqrt(arg0);
if (actual != expected)
{
Console.WriteLine($"Fail: short (actual={actual}, expected={expected})");
result = Result.Fail;
}
}
void TestSquareRootAt0(ushort arg0)
{
Vector<ushort> arg = new Vector<ushort>(arg0);
ushort actual = SquareRootAt0(arg);
ushort expected = (ushort)Math.Sqrt(arg0);
if (actual != expected)
{
Console.WriteLine($"Fail: ushort (actual={actual}, expected={expected})");
result = Result.Fail;
}
}
void TestSquareRootAt0(int arg0)
{
Vector<int> arg = new Vector<int>(arg0);
int actual = SquareRootAt0(arg);
int expected = (int)Math.Sqrt(arg0);
if (actual != expected)
{
Console.WriteLine($"Fail: int (actual={actual}, expected={expected})");
result = Result.Fail;
}
}
void TestSquareRootAt0(uint arg0)
{
Vector<uint> arg = new Vector<uint>(arg0);
uint actual = SquareRootAt0(arg);
uint expected = (uint)Math.Sqrt(arg0);
if (actual != expected)
{
Console.WriteLine($"Fail: uint (actual={actual}, expected={expected})");
result = Result.Fail;
}
}
void TestSquareRootAt0(long arg0)
{
Vector<long> arg = new Vector<long>(arg0);
long actual = SquareRootAt0(arg);
long expected = (long)Math.Sqrt(arg0);
if (actual != expected)
{
Console.WriteLine($"Fail: long (actual={actual}, expected={expected})");
result = Result.Fail;
}
}
void TestSquareRootAt0(ulong arg0)
{
Vector<ulong> arg = new Vector<ulong>(arg0);
ulong actual = SquareRootAt0(arg);
ulong expected = (ulong)Math.Sqrt(arg0);
if (actual != expected)
{
Console.WriteLine($"Fail: ulong (actual={actual}, expected={expected})");
result = Result.Fail;
}
}
void TestSquareRootAt0(float arg0)
{
Vector<float> arg = new Vector<float>(arg0);
float actual = SquareRootAt0(arg);
float expected = (float)Math.Sqrt(arg0);
if (actual != expected)
{
Console.WriteLine($"Fail: float (actual={actual}, expected={expected})");
result = Result.Fail;
}
}
void TestSquareRootAt0(double arg0)
{
Vector<double> arg = new Vector<double>(arg0);
double actual = SquareRootAt0(arg);
double expected = (double)Math.Sqrt(arg0);
if (actual != expected)
{
Console.WriteLine($"Fail: double (actual={actual}, expected={expected})");
result = Result.Fail;
}
}
Result result;
public Result Run()
{
result = Result.Pass;
TestSquareRootAt0((sbyte)-1);
TestSquareRootAt0((short)-1);
TestSquareRootAt0((int)-1);
TestSquareRootAt0((long)-1);
TestSquareRootAt0((sbyte)1);
TestSquareRootAt0((byte)1);
TestSquareRootAt0((short)1);
TestSquareRootAt0((ushort)1);
TestSquareRootAt0((int)1);
TestSquareRootAt0((uint)1);
TestSquareRootAt0((long)1);
TestSquareRootAt0((ulong)1);
TestSquareRootAt0((float)4);
TestSquareRootAt0((double)4);
return result;
}
}
static int Main(string[] args)
{
if (new TestRunner().Run() == Result.Pass)
{
Console.WriteLine("Pass");
return 100;
}
else
{
return 0;
}
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Collections.Specialized
{
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct BitVector32
{
public BitVector32(System.Collections.Specialized.BitVector32 value) { throw null; }
public BitVector32(int data) { throw null; }
public int Data { get { throw null; } }
public int this[System.Collections.Specialized.BitVector32.Section section] { get { throw null; } set { } }
public bool this[int bit] { get { throw null; } set { } }
public static int CreateMask() { throw null; }
public static int CreateMask(int previous) { throw null; }
public static System.Collections.Specialized.BitVector32.Section CreateSection(short maxValue) { throw null; }
public static System.Collections.Specialized.BitVector32.Section CreateSection(short maxValue, System.Collections.Specialized.BitVector32.Section previous) { throw null; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
public override string ToString() { throw null; }
public static string ToString(System.Collections.Specialized.BitVector32 value) { throw null; }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct Section
{
public short Mask { get { throw null; } }
public short Offset { get { throw null; } }
public bool Equals(System.Collections.Specialized.BitVector32.Section obj) { throw null; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Collections.Specialized.BitVector32.Section a, System.Collections.Specialized.BitVector32.Section b) { throw null; }
public static bool operator !=(System.Collections.Specialized.BitVector32.Section a, System.Collections.Specialized.BitVector32.Section b) { throw null; }
public override string ToString() { throw null; }
public static string ToString(System.Collections.Specialized.BitVector32.Section value) { throw null; }
}
}
public partial class HybridDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public HybridDictionary() { }
public HybridDictionary(bool caseInsensitive) { }
public HybridDictionary(int initialSize) { }
public HybridDictionary(int initialSize, bool caseInsensitive) { }
public int Count { get { throw null; } }
public bool IsFixedSize { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public object this[object key] { get { throw null; } set { } }
public System.Collections.ICollection Keys { get { throw null; } }
public object SyncRoot { get { throw null; } }
public System.Collections.ICollection Values { get { throw null; } }
public void Add(object key, object value) { }
public void Clear() { }
public bool Contains(object key) { throw null; }
public void CopyTo(System.Array array, int index) { }
public System.Collections.IDictionaryEnumerator GetEnumerator() { throw null; }
public void Remove(object key) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public partial interface IOrderedDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
object this[int index] { get; set; }
new System.Collections.IDictionaryEnumerator GetEnumerator();
void Insert(int index, object key, object value);
void RemoveAt(int index);
}
public partial class ListDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public ListDictionary() { }
public ListDictionary(System.Collections.IComparer comparer) { }
public int Count { get { throw null; } }
public bool IsFixedSize { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public object this[object key] { get { throw null; } set { } }
public System.Collections.ICollection Keys { get { throw null; } }
public object SyncRoot { get { throw null; } }
public System.Collections.ICollection Values { get { throw null; } }
public void Add(object key, object value) { }
public void Clear() { }
public bool Contains(object key) { throw null; }
public void CopyTo(System.Array array, int index) { }
public System.Collections.IDictionaryEnumerator GetEnumerator() { throw null; }
public void Remove(object key) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public abstract partial class NameObjectCollectionBase : System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback
{
protected NameObjectCollectionBase() { }
protected NameObjectCollectionBase(System.Collections.IEqualityComparer equalityComparer) { }
[System.ObsoleteAttribute("Please use NameObjectCollectionBase(IEqualityComparer) instead.")]
protected NameObjectCollectionBase(System.Collections.IHashCodeProvider hashProvider, System.Collections.IComparer comparer) { }
protected NameObjectCollectionBase(int capacity) { }
protected NameObjectCollectionBase(int capacity, System.Collections.IEqualityComparer equalityComparer) { }
[System.ObsoleteAttribute("Please use NameObjectCollectionBase(Int32, IEqualityComparer) instead.")]
protected NameObjectCollectionBase(int capacity, System.Collections.IHashCodeProvider hashProvider, System.Collections.IComparer comparer) { }
protected NameObjectCollectionBase(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public virtual int Count { get { throw null; } }
protected bool IsReadOnly { get { throw null; } set { } }
public virtual System.Collections.Specialized.NameObjectCollectionBase.KeysCollection Keys { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
protected void BaseAdd(string name, object value) { }
protected void BaseClear() { }
protected object BaseGet(int index) { throw null; }
protected object BaseGet(string name) { throw null; }
protected string[] BaseGetAllKeys() { throw null; }
protected object[] BaseGetAllValues() { throw null; }
protected object[] BaseGetAllValues(System.Type type) { throw null; }
protected string BaseGetKey(int index) { throw null; }
protected bool BaseHasKeys() { throw null; }
protected void BaseRemove(string name) { }
protected void BaseRemoveAt(int index) { }
protected void BaseSet(int index, object value) { }
protected void BaseSet(string name, object value) { }
public virtual System.Collections.IEnumerator GetEnumerator() { throw null; }
public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public virtual void OnDeserialization(object sender) { }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
public partial class KeysCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal KeysCollection() { }
public int Count { get { throw null; } }
public string this[int index] { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public virtual string Get(int index) { throw null; }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
}
}
public partial class NameValueCollection : System.Collections.Specialized.NameObjectCollectionBase
{
public NameValueCollection() { }
public NameValueCollection(System.Collections.IEqualityComparer equalityComparer) { }
[System.ObsoleteAttribute("Please use NameValueCollection(IEqualityComparer) instead.")]
public NameValueCollection(System.Collections.IHashCodeProvider hashProvider, System.Collections.IComparer comparer) { }
public NameValueCollection(System.Collections.Specialized.NameValueCollection col) { }
public NameValueCollection(int capacity) { }
public NameValueCollection(int capacity, System.Collections.IEqualityComparer equalityComparer) { }
[System.ObsoleteAttribute("Please use NameValueCollection(Int32, IEqualityComparer) instead.")]
public NameValueCollection(int capacity, System.Collections.IHashCodeProvider hashProvider, System.Collections.IComparer comparer) { }
public NameValueCollection(int capacity, System.Collections.Specialized.NameValueCollection col) { }
protected NameValueCollection(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public virtual string[] AllKeys { get { throw null; } }
public string this[int index] { get { throw null; } }
public string this[string name] { get { throw null; } set { } }
public void Add(System.Collections.Specialized.NameValueCollection c) { }
public virtual void Add(string name, string value) { }
public virtual void Clear() { }
public void CopyTo(System.Array dest, int index) { }
public virtual string Get(int index) { throw null; }
public virtual string Get(string name) { throw null; }
public virtual string GetKey(int index) { throw null; }
public virtual string[] GetValues(int index) { throw null; }
public virtual string[] GetValues(string name) { throw null; }
public bool HasKeys() { throw null; }
protected void InvalidateCachedArrays() { }
public virtual void Remove(string name) { }
public virtual void Set(string name, string value) { }
}
public partial class OrderedDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable, System.Collections.Specialized.IOrderedDictionary, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback
{
public OrderedDictionary() { }
public OrderedDictionary(System.Collections.IEqualityComparer comparer) { }
public OrderedDictionary(int capacity) { }
public OrderedDictionary(int capacity, System.Collections.IEqualityComparer comparer) { }
protected OrderedDictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public int Count { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public object this[int index] { get { throw null; } set { } }
public object this[object key] { get { throw null; } set { } }
public System.Collections.ICollection Keys { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
bool System.Collections.IDictionary.IsFixedSize { get { throw null; } }
public System.Collections.ICollection Values { get { throw null; } }
public void Add(object key, object value) { }
public System.Collections.Specialized.OrderedDictionary AsReadOnly() { throw null; }
public void Clear() { }
public bool Contains(object key) { throw null; }
public void CopyTo(System.Array array, int index) { }
public virtual System.Collections.IDictionaryEnumerator GetEnumerator() { throw null; }
public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public void Insert(int index, object key, object value) { }
protected virtual void OnDeserialization(object sender) { }
void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { }
public void Remove(object key) { }
public void RemoveAt(int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public partial class StringCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
public StringCollection() { }
public int Count { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public string this[int index] { get { throw null; } set { } }
public object SyncRoot { get { throw null; } }
bool System.Collections.IList.IsFixedSize { get { throw null; } }
bool System.Collections.IList.IsReadOnly { get { throw null; } }
object System.Collections.IList.this[int index] { get { throw null; } set { } }
public int Add(string value) { throw null; }
public void AddRange(string[] value) { }
public void Clear() { }
public bool Contains(string value) { throw null; }
public void CopyTo(string[] array, int index) { }
public System.Collections.Specialized.StringEnumerator GetEnumerator() { throw null; }
public int IndexOf(string value) { throw null; }
public void Insert(int index, string value) { }
public void Remove(string value) { }
public void RemoveAt(int index) { }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
int System.Collections.IList.Add(object value) { throw null; }
bool System.Collections.IList.Contains(object value) { throw null; }
int System.Collections.IList.IndexOf(object value) { throw null; }
void System.Collections.IList.Insert(int index, object value) { }
void System.Collections.IList.Remove(object value) { }
}
public partial class StringDictionary : System.Collections.IEnumerable
{
public StringDictionary() { }
public virtual int Count { get { throw null; } }
public virtual bool IsSynchronized { get { throw null; } }
public virtual string this[string key] { get { throw null; } set { } }
public virtual System.Collections.ICollection Keys { get { throw null; } }
public virtual object SyncRoot { get { throw null; } }
public virtual System.Collections.ICollection Values { get { throw null; } }
public virtual void Add(string key, string value) { }
public virtual void Clear() { }
public virtual bool ContainsKey(string key) { throw null; }
public virtual bool ContainsValue(string value) { throw null; }
public virtual void CopyTo(System.Array array, int index) { }
public virtual System.Collections.IEnumerator GetEnumerator() { throw null; }
public virtual void Remove(string key) { }
}
public partial class StringEnumerator
{
internal StringEnumerator() { }
public string Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if SUPPORTS_WINDOWSIDENTITY
using System.Collections.Generic;
using System.IdentityModel.Policy;
using System.Runtime;
using System.Security;
using System.Security.Principal;
using System.ServiceModel;
namespace System.IdentityModel.Claims
{
public class WindowsClaimSet : ClaimSet, IIdentityInfo, IDisposable
{
internal const bool DefaultIncludeWindowsGroups = true;
private WindowsIdentity _windowsIdentity;
private DateTime _expirationTime;
private bool _includeWindowsGroups;
private IList<Claim> _claims;
private bool _disposed = false;
private string _authenticationType;
public WindowsClaimSet(WindowsIdentity windowsIdentity)
: this(windowsIdentity, DefaultIncludeWindowsGroups)
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, bool includeWindowsGroups)
: this(windowsIdentity, includeWindowsGroups, DateTime.UtcNow.AddHours(10))
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, DateTime expirationTime)
: this(windowsIdentity, DefaultIncludeWindowsGroups, expirationTime)
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, bool includeWindowsGroups, DateTime expirationTime)
: this(windowsIdentity, null, includeWindowsGroups, expirationTime, true)
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, DateTime expirationTime)
: this( windowsIdentity, authenticationType, includeWindowsGroups, expirationTime, true )
{
}
internal WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, bool clone)
: this( windowsIdentity, authenticationType, includeWindowsGroups, DateTime.UtcNow.AddHours( 10 ), clone )
{
}
internal WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, DateTime expirationTime, bool clone)
{
if (windowsIdentity == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("windowsIdentity");
_windowsIdentity = clone ? SecurityUtils.CloneWindowsIdentityIfNecessary(windowsIdentity, authenticationType) : windowsIdentity;
_includeWindowsGroups = includeWindowsGroups;
_expirationTime = expirationTime;
_authenticationType = authenticationType;
}
private WindowsClaimSet(WindowsClaimSet from)
: this(from.WindowsIdentity, from._authenticationType, from._includeWindowsGroups, from._expirationTime, true)
{
}
public override Claim this[int index]
{
get
{
ThrowIfDisposed();
EnsureClaims();
return _claims[index];
}
}
public override int Count
{
get
{
ThrowIfDisposed();
EnsureClaims();
return _claims.Count;
}
}
IIdentity IIdentityInfo.Identity
{
get
{
ThrowIfDisposed();
return _windowsIdentity;
}
}
public WindowsIdentity WindowsIdentity
{
get
{
ThrowIfDisposed();
return _windowsIdentity;
}
}
public override ClaimSet Issuer
{
get { return ClaimSet.Windows; }
}
public DateTime ExpirationTime
{
get { return _expirationTime; }
}
internal WindowsClaimSet Clone()
{
ThrowIfDisposed();
return new WindowsClaimSet(this);
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
_windowsIdentity.Dispose();
}
}
IList<Claim> InitializeClaimsCore()
{
if (_windowsIdentity.AccessToken == null)
return new List<Claim>();
List<Claim> claims = new List<Claim>(3);
claims.Add(new Claim(ClaimTypes.Sid, _windowsIdentity.User, Rights.Identity));
Claim claim;
if (TryCreateWindowsSidClaim(_windowsIdentity, out claim))
{
claims.Add(claim);
}
claims.Add(Claim.CreateNameClaim(_windowsIdentity.Name));
if (_includeWindowsGroups)
{
// claims.AddRange(Groups);
}
return claims;
}
void EnsureClaims()
{
if (_claims != null)
return;
_claims = InitializeClaimsCore();
}
void ThrowIfDisposed()
{
if (_disposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
}
static bool SupportedClaimType(string claimType)
{
return claimType == null ||
ClaimTypes.Sid == claimType ||
ClaimTypes.DenyOnlySid == claimType ||
ClaimTypes.Name == claimType;
}
// Note: null string represents any.
public override IEnumerable<Claim> FindClaims(string claimType, string right)
{
ThrowIfDisposed();
if (!SupportedClaimType(claimType) || !ClaimSet.SupportedRight(right))
{
yield break;
}
else if (_claims == null && (ClaimTypes.Sid == claimType || ClaimTypes.DenyOnlySid == claimType))
{
if (ClaimTypes.Sid == claimType)
{
if (right == null || Rights.Identity == right)
{
yield return new Claim(ClaimTypes.Sid, _windowsIdentity.User, Rights.Identity);
}
}
if (right == null || Rights.PossessProperty == right)
{
Claim sid;
if (TryCreateWindowsSidClaim(_windowsIdentity, out sid))
{
if (claimType == sid.ClaimType)
{
yield return sid;
}
}
}
if (_includeWindowsGroups && (right == null || Rights.PossessProperty == right))
{
// Not sure yet if GroupSidClaimCollections are necessary in .NET Core, but default
// _includeWindowsGroups is true; don't throw here or we bust the default case on UWP/.NET Core
}
}
else
{
EnsureClaims();
bool anyClaimType = (claimType == null);
bool anyRight = (right == null);
for (int i = 0; i < _claims.Count; ++i)
{
Claim claim = _claims[i];
if ((claim != null) &&
(anyClaimType || claimType == claim.ClaimType) &&
(anyRight || right == claim.Right))
{
yield return claim;
}
}
}
}
public override IEnumerator<Claim> GetEnumerator()
{
ThrowIfDisposed();
EnsureClaims();
return _claims.GetEnumerator();
}
public override string ToString()
{
return _disposed ? base.ToString() : SecurityUtils.ClaimSetToString(this);
}
public static bool TryCreateWindowsSidClaim(WindowsIdentity windowsIdentity, out Claim claim)
{
throw ExceptionHelper.PlatformNotSupported("CreateWindowsSidClaim is not yet supported");
}
}
}
#endif // SUPPORTS_WINDOWSIDENTITY
| |
// 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.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Http
{
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyCreate")]
public static extern SafeCurlHandle EasyCreate();
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyDestroy")]
private static extern void EasyDestroy(IntPtr handle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionString", CharSet = CharSet.Ansi)]
public static extern CURLcode EasySetOptionString(SafeCurlHandle curl, CURLoption option, string value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionLong")]
public static extern CURLcode EasySetOptionLong(SafeCurlHandle curl, CURLoption option, long value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionPointer")]
public static extern CURLcode EasySetOptionPointer(SafeCurlHandle curl, CURLoption option, IntPtr value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionPointer")]
public static extern CURLcode EasySetOptionPointer(SafeCurlHandle curl, CURLoption option, SafeHandle value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetErrorString")]
public static extern IntPtr EasyGetErrorString(int code);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoPointer")]
public static extern CURLcode EasyGetInfoPointer(IntPtr handle, CURLINFO info, out IntPtr value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoLong")]
public static extern CURLcode EasyGetInfoLong(SafeCurlHandle handle, CURLINFO info, out long value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyPerform")]
public static extern CURLcode EasyPerform(SafeCurlHandle curl);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyUnpause")]
public static extern CURLcode EasyUnpause(SafeCurlHandle easy);
public delegate CurlSeekResult SeekCallback(IntPtr userPointer, long offset, int origin);
public delegate ulong ReadWriteCallback(IntPtr buffer, ulong bufferSize, ulong nitems, IntPtr userPointer);
public delegate CURLcode SslCtxCallback(IntPtr curl, IntPtr sslCtx, IntPtr userPointer);
public delegate void DebugCallback(IntPtr curl, CurlInfoType type, IntPtr data, ulong size, IntPtr userPointer);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterSeekCallback")]
public static extern void RegisterSeekCallback(
SafeCurlHandle curl,
SeekCallback callback,
IntPtr userPointer,
ref SafeCallbackHandle callbackHandle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterReadWriteCallback")]
public static extern void RegisterReadWriteCallback(
SafeCurlHandle curl,
ReadWriteFunction functionType,
ReadWriteCallback callback,
IntPtr userPointer,
ref SafeCallbackHandle callbackHandle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterSslCtxCallback")]
public static extern CURLcode RegisterSslCtxCallback(
SafeCurlHandle curl,
SslCtxCallback callback,
IntPtr userPointer,
ref SafeCallbackHandle callbackHandle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterDebugCallback")]
public static extern CURLcode RegisterDebugCallback(
SafeCurlHandle curl,
DebugCallback callback,
IntPtr userPointer,
ref SafeCallbackHandle callbackHandle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_FreeCallbackHandle")]
private static extern void FreeCallbackHandle(IntPtr handle);
// Curl options are of the format <type base> + <n>
private const int CurlOptionLongBase = 0;
private const int CurlOptionObjectPointBase = 10000;
// Enum for constants defined for the enum CURLoption in curl.h
internal enum CURLoption
{
CURLOPT_INFILESIZE = CurlOptionLongBase + 14,
CURLOPT_VERBOSE = CurlOptionLongBase + 41,
CURLOPT_NOBODY = CurlOptionLongBase + 44,
CURLOPT_UPLOAD = CurlOptionLongBase + 46,
CURLOPT_POST = CurlOptionLongBase + 47,
CURLOPT_FOLLOWLOCATION = CurlOptionLongBase + 52,
CURLOPT_PROXYPORT = CurlOptionLongBase + 59,
CURLOPT_POSTFIELDSIZE = CurlOptionLongBase + 60,
CURLOPT_MAXREDIRS = CurlOptionLongBase + 68,
CURLOPT_HTTP_VERSION = CurlOptionLongBase + 84,
CURLOPT_NOSIGNAL = CurlOptionLongBase + 99,
CURLOPT_PROXYTYPE = CurlOptionLongBase + 101,
CURLOPT_HTTPAUTH = CurlOptionLongBase + 107,
CURLOPT_PROTOCOLS = CurlOptionLongBase + 181,
CURLOPT_REDIR_PROTOCOLS = CurlOptionLongBase + 182,
CURLOPT_URL = CurlOptionObjectPointBase + 2,
CURLOPT_PROXY = CurlOptionObjectPointBase + 4,
CURLOPT_PROXYUSERPWD = CurlOptionObjectPointBase + 6,
CURLOPT_COOKIE = CurlOptionObjectPointBase + 22,
CURLOPT_HTTPHEADER = CurlOptionObjectPointBase + 23,
CURLOPT_CUSTOMREQUEST = CurlOptionObjectPointBase + 36,
CURLOPT_ACCEPT_ENCODING = CurlOptionObjectPointBase + 102,
CURLOPT_PRIVATE = CurlOptionObjectPointBase + 103,
CURLOPT_COPYPOSTFIELDS = CurlOptionObjectPointBase + 165,
CURLOPT_USERNAME = CurlOptionObjectPointBase + 173,
CURLOPT_PASSWORD = CurlOptionObjectPointBase + 174,
}
internal enum ReadWriteFunction
{
Write = 0,
Read = 1,
Header = 2,
}
// Curl info are of the format <type base> + <n>
private const int CurlInfoStringBase = 0x100000;
private const int CurlInfoLongBase = 0x200000;
// Enum for constants defined for CURL_HTTP_VERSION
internal enum CurlHttpVersion
{
CURL_HTTP_VERSION_NONE = 0,
CURL_HTTP_VERSION_1_0 = 1,
CURL_HTTP_VERSION_1_1 = 2,
CURL_HTTP_VERSION_2_0 = 3,
};
// Enum for constants defined for the enum CURLINFO in curl.h
internal enum CURLINFO
{
CURLINFO_PRIVATE = CurlInfoStringBase + 21,
CURLINFO_HTTPAUTH_AVAIL = CurlInfoLongBase + 23,
}
// AUTH related constants
[Flags]
internal enum CURLAUTH
{
None = 0,
Basic = 1 << 0,
Digest = 1 << 1,
Negotiate = 1 << 2,
NTLM = 1 << 3,
}
// Enum for constants defined for the enum curl_proxytype in curl.h
internal enum curl_proxytype
{
CURLPROXY_HTTP = 0,
}
[Flags]
internal enum CurlProtocols
{
CURLPROTO_HTTP = (1 << 0),
CURLPROTO_HTTPS = (1 << 1),
}
// Enum for constants defined for the results of CURL_SEEKFUNCTION
internal enum CurlSeekResult : int
{
CURL_SEEKFUNC_OK = 0,
CURL_SEEKFUNC_FAIL = 1,
CURL_SEEKFUNC_CANTSEEK = 2,
}
internal enum CurlInfoType : int
{
CURLINFO_TEXT = 0,
CURLINFO_HEADER_IN = 1,
CURLINFO_HEADER_OUT = 2,
CURLINFO_DATA_IN = 3,
CURLINFO_DATA_OUT = 4,
CURLINFO_SSL_DATA_IN = 5,
CURLINFO_SSL_DATA_OUT = 6,
};
// constants defined for the results of a CURL_READ or CURL_WRITE function
internal const ulong CURL_READFUNC_ABORT = 0x10000000;
internal const ulong CURL_READFUNC_PAUSE = 0x10000001;
internal const ulong CURL_WRITEFUNC_PAUSE = 0x10000001;
internal const ulong CURL_MAX_HTTP_HEADER = 100 * 1024;
internal sealed class SafeCurlHandle : SafeHandle
{
public SafeCurlHandle() : base(IntPtr.Zero, true)
{
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
EasyDestroy(handle);
SetHandle(IntPtr.Zero);
return true;
}
}
internal sealed class SafeCallbackHandle : SafeHandle
{
public SafeCallbackHandle()
: base(IntPtr.Zero, true)
{
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
FreeCallbackHandle(handle);
SetHandle(IntPtr.Zero);
return true;
}
}
}
}
| |
using System;
using Sifteo;
using Nini.Config;
namespace sifteo4devops
{
public class SetupCube
{
public enum Screen
{
Exit, DeployJob, JenkinsJobs, ZenossGroups
};
public bool Active = false;
private Cube c;
public Cube Cube
{
set
{
if ( value == null )
{
this.c.ButtonEvent -= this.DoButton;
this.c.TiltEvent -= this.OnTilt;
this.Active = false;
this.LoadingTime = 0;
this.CurrentScreen = Screen.Exit;
Log.Debug("reset setupcube");
}
else
{
Log.Debug("new setupcube");
this.LastLoadingTime = DateTime.Now;
value.ButtonEvent += this.OnButton;
value.TiltEvent += this.OnTilt;
this.Tick();
}
this.c = value;
}
get
{
if ( this.c == null )
{
return null;
}
else
{
return this.c;
}
}
}
private int LoadingTime = 5;
private DateTime LastLoadingTime;
private Screen CurrentScreen = Screen.Exit;
private ButtonEventHandler OnButton;
private TiltEventHandler OnTilt;
private int Element = 0;
public SetupCube()
{
OnButton = new ButtonEventHandler(DoButton);
OnTilt = new TiltEventHandler(DoTilt);
}
public void Loading()
{
TimeSpan setupspan = DateTime.Now - this.LastLoadingTime;
if ( setupspan.Seconds > 5 )
{
this.Active = true;
this.Redraw();
}
else
{
if ( setupspan.Seconds > this.LoadingTime + 1)
{
int color = 50 * this.LoadingTime;
Color col = new Color(255, color, color);
this.c.FillScreen(col);
Util.DrawString(c, 5, 25, "Hold For Setup" + (5 - this.LoadingTime).ToString() + "s");
Util.DrawString(c, 5, 35, "To enter Setup Mode");
this.c.Paint();
this.LoadingTime += 1;
}
}
}
public bool Tick()
{
if ( this.c != null )
{
if ( ! this.Active )
{
this.Loading();
}
return true;
}
else
{
return false;
}
}
public void DoButton(Cube c, bool pressed)
{
if ( CurrentScreen == Screen.Exit )
{
if ( pressed )
{
c = null;
}
}
}
public void DoTilt(Cube c, int x, int y, int z)
{
}
private void Redraw()
{
Color col = new Color(255, 255, 255);
this.c.FillScreen(col);
Util.DrawString(c, 5, 5, "@~+~~ Config");
if ( CurrentScreen == Screen.Exit )
{
Util.DrawString(c, 5, 15, "Click to Exit");
}
else if ( CurrentScreen == Screen.DeployJob )
{
if ( this.Element < Deployinator.Jenkins.Count() && this.Element >= 0 )
{
this.Element = 0;
}
JenkinsJob j = Deployinator.Jenkins.Job(this.Element);
Util.DrawString(c, 5, 15, "Click to select");
Util.DrawString(c, 5, 25, j.GetName());
}
}
}
public class Config
{
private string _DeployJob;
public string DeployJob
{
get
{
return _DeployJob;
}
set
{
this._DeployJob = value;
}
}
private bool _Danger;
public bool Danger
{
get
{
return _Danger;
}
set
{
this._Danger = value;
}
}
private string _JenkinsUrl;
public string JenkinsUrl
{
get
{
return _JenkinsUrl;
}
}
private string _ZenossUrl;
public string ZenossUrl
{
get
{
return _ZenossUrl;
}
}
private string _ZenossUser;
public string ZenossUser
{
get
{
return _ZenossUser;
}
}
private string _ZenossPass;
public string ZenossPass
{
get
{
return _ZenossPass;
}
}
private int _CycleEvery;
public int CycleEvery
{
get
{
return _CycleEvery;
}
set
{
this._CycleEvery = value;
}
}
private int _ScoreEvery;
public int ScoreEvery
{
get
{
return _ScoreEvery;
}
set
{
this._ScoreEvery = value;
}
}
public Config()
{
IConfigSource source = new IniConfigSource("deployinator.ini");
string d = source.Configs["Displays"].Get("Danger");
if ( d == "true" )
{
this._Danger = true;
}
else
{
this._Danger = false;
}
this._JenkinsUrl = source.Configs["Jenkins"].Get("URL");
this._ZenossUrl = source.Configs["Zenoss"].Get("URL");
this._ZenossUser = source.Configs["Zenoss"].Get("User");
this._ZenossPass = source.Configs["Zenoss"].Get("Pass");
this._CycleEvery = Convert.ToInt32(source.Configs["Displays"].Get("CycleEvery"));
this._ScoreEvery = Convert.ToInt32(source.Configs["Displays"].Get("ScoreEvery"));
this._DeployJob = source.Configs["Displays"].Get("DeployJob");
for ( int i = 0 ; i < source.Configs.Count ; i++ )
{
Log.Debug(source.Configs[i].ToString());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Principal;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SecurityUtils = System.ServiceModel.Security.SecurityUtils;
namespace System.ServiceModel.Channels
{
internal class HttpChannelFactory<TChannel>
: TransportChannelFactory<TChannel>,
IHttpTransportFactorySettings
{
private static CacheControlHeaderValue s_requestCacheHeader = new CacheControlHeaderValue { NoCache = true, MaxAge = new TimeSpan(0) };
protected readonly ClientWebSocketFactory _clientWebSocketFactory;
private HttpCookieContainerManager _httpCookieContainerManager;
// Double-checked locking pattern requires volatile for read/write synchronization
private volatile MruCache<Uri, Uri> _credentialCacheUriPrefixCache;
private volatile MruCache<string, string> _credentialHashCache;
private volatile MruCache<string, HttpClient> _httpClientCache;
private IWebProxy _proxy;
private WebProxyFactory _proxyFactory;
private SecurityCredentialsManager _channelCredentials;
private ISecurityCapabilities _securityCapabilities;
private Func<HttpClientHandler, HttpMessageHandler> _httpMessageHandlerFactory;
private Lazy<string> _webSocketSoapContentType;
private SHA512 _hashAlgorithm;
private bool _keepAliveEnabled;
internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
: base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
{
// validate setting interactions
if (bindingElement.TransferMode == TransferMode.Buffered)
{
if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
SR.MaxReceivedMessageSizeMustBeInIntegerRange));
}
if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.MaxBufferSizeMustMatchMaxReceivedMessageSize);
}
}
else
{
if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize);
}
}
if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.HttpAuthDoesNotSupportRequestStreaming);
}
AllowCookies = bindingElement.AllowCookies;
if (AllowCookies)
{
_httpCookieContainerManager = new HttpCookieContainerManager();
}
if (!bindingElement.AuthenticationScheme.IsSingleton() && bindingElement.AuthenticationScheme != AuthenticationSchemes.IntegratedWindowsAuthentication)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme,
bindingElement.AuthenticationScheme));
}
AuthenticationScheme = bindingElement.AuthenticationScheme;
DecompressionEnabled = bindingElement.DecompressionEnabled;
MaxBufferSize = bindingElement.MaxBufferSize;
TransferMode = bindingElement.TransferMode;
_keepAliveEnabled = bindingElement.KeepAliveEnabled;
if (bindingElement.Proxy != null)
{
_proxy = bindingElement.Proxy;
}
else if (bindingElement.ProxyAddress != null)
{
if (bindingElement.UseDefaultWebProxy)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.UseDefaultWebProxyCantBeUsedWithExplicitProxyAddress));
}
if (bindingElement.ProxyAuthenticationScheme == AuthenticationSchemes.Anonymous)
{
_proxy = new WebProxy(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal);
}
else
{
_proxy = null;
_proxyFactory =
new WebProxyFactory(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal,
bindingElement.ProxyAuthenticationScheme);
}
}
else if (!bindingElement.UseDefaultWebProxy)
{
_proxy = new WebProxy();
}
_channelCredentials = context.BindingParameters.Find<SecurityCredentialsManager>();
_securityCapabilities = bindingElement.GetProperty<ISecurityCapabilities>(context);
_httpMessageHandlerFactory = context.BindingParameters.Find<Func<HttpClientHandler, HttpMessageHandler>>();
WebSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings);
_clientWebSocketFactory = ClientWebSocketFactory.GetFactory();
_webSocketSoapContentType = new Lazy<string>(() => MessageEncoderFactory.CreateSessionEncoder().ContentType, LazyThreadSafetyMode.ExecutionAndPublication);
_httpClientCache = bindingElement.GetProperty<MruCache<string, HttpClient>>(context);
}
public bool AllowCookies { get; }
public AuthenticationSchemes AuthenticationScheme { get; }
public bool DecompressionEnabled { get; }
public virtual bool IsChannelBindingSupportEnabled
{
get
{
return false;
}
}
public SecurityTokenManager SecurityTokenManager { get; private set; }
public int MaxBufferSize { get; }
public TransferMode TransferMode { get; }
public override string Scheme
{
get
{
return UriEx.UriSchemeHttp;
}
}
public WebSocketTransportSettings WebSocketSettings { get; }
internal string WebSocketSoapContentType
{
get
{
return _webSocketSoapContentType.Value;
}
}
private HashAlgorithm HashAlgorithm
{
[SecurityCritical]
get
{
if (_hashAlgorithm == null)
{
_hashAlgorithm = SHA512.Create();
}
else
{
_hashAlgorithm.Initialize();
}
return _hashAlgorithm;
}
}
protected ClientWebSocketFactory ClientWebSocketFactory
{
get
{
return _clientWebSocketFactory;
}
}
private bool AuthenticationSchemeMayRequireResend()
{
return AuthenticationScheme != AuthenticationSchemes.Anonymous;
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ISecurityCapabilities))
{
return (T)(object)_securityCapabilities;
}
if (typeof(T) == typeof(IHttpCookieContainerManager))
{
return (T)(object)GetHttpCookieContainerManager();
}
return base.GetProperty<T>();
}
private HttpCookieContainerManager GetHttpCookieContainerManager()
{
return _httpCookieContainerManager;
}
private Uri GetCredentialCacheUriPrefix(Uri via)
{
Uri result;
if (_credentialCacheUriPrefixCache == null)
{
lock (ThisLock)
{
if (_credentialCacheUriPrefixCache == null)
{
_credentialCacheUriPrefixCache = new MruCache<Uri, Uri>(10);
}
}
}
lock (_credentialCacheUriPrefixCache)
{
if (!_credentialCacheUriPrefixCache.TryGetValue(via, out result))
{
result = new UriBuilder(via.Scheme, via.Host, via.Port).Uri;
_credentialCacheUriPrefixCache.Add(via, result);
}
}
return result;
}
internal async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via,
SecurityTokenProviderContainer tokenProvider, SecurityTokenProviderContainer proxyTokenProvider,
SecurityTokenContainer clientCertificateToken, TimeSpan timeout)
{
var impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
var authenticationLevelWrapper = new OutWrapper<AuthenticationLevel>();
NetworkCredential credential = await HttpChannelUtilities.GetCredentialAsync(AuthenticationScheme,
tokenProvider, impersonationLevelWrapper, authenticationLevelWrapper, timeout);
HttpClient httpClient;
string connectionGroupName = GetConnectionGroupName(credential, authenticationLevelWrapper.Value,
impersonationLevelWrapper.Value,
clientCertificateToken);
X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity;
if (remoteCertificateIdentity != null)
{
connectionGroupName = string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", connectionGroupName,
remoteCertificateIdentity.Certificates[0].Thumbprint);
}
connectionGroupName = connectionGroupName ?? string.Empty;
bool foundHttpClient;
lock (_httpClientCache)
{
foundHttpClient = _httpClientCache.TryGetValue(connectionGroupName, out httpClient);
}
if (!foundHttpClient)
{
var clientHandler = GetHttpClientHandler(to, clientCertificateToken);
if (DecompressionEnabled)
{
clientHandler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
}
else
{
clientHandler.AutomaticDecompression = DecompressionMethods.None;
}
if (clientHandler.SupportsProxy)
{
if (_proxy != null)
{
clientHandler.Proxy = _proxy;
clientHandler.UseProxy = true;
}
else if (_proxyFactory != null)
{
clientHandler.Proxy = await _proxyFactory.CreateWebProxyAsync(authenticationLevelWrapper.Value,
impersonationLevelWrapper.Value, proxyTokenProvider, timeout);
clientHandler.UseProxy = true;
}
}
clientHandler.UseCookies = AllowCookies;
if (AllowCookies)
{
clientHandler.CookieContainer = _httpCookieContainerManager.CookieContainer;
}
clientHandler.PreAuthenticate = true;
clientHandler.UseDefaultCredentials = false;
if (credential == CredentialCache.DefaultCredentials || credential == null)
{
if (AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
clientHandler.UseDefaultCredentials = true;
}
}
else
{
if (Fx.IsUap)
{
clientHandler.Credentials = credential;
}
else
{
CredentialCache credentials = new CredentialCache();
Uri credentialCacheUriPrefix = GetCredentialCacheUriPrefix(via);
if (AuthenticationScheme == AuthenticationSchemes.IntegratedWindowsAuthentication)
{
credentials.Add(credentialCacheUriPrefix, AuthenticationSchemesHelper.ToString(AuthenticationSchemes.Negotiate),
credential);
credentials.Add(credentialCacheUriPrefix, AuthenticationSchemesHelper.ToString(AuthenticationSchemes.Ntlm),
credential);
}
else
{
credentials.Add(credentialCacheUriPrefix, AuthenticationSchemesHelper.ToString(AuthenticationScheme),
credential);
}
clientHandler.Credentials = credentials;
}
}
HttpMessageHandler handler = clientHandler;
if (_httpMessageHandlerFactory != null)
{
handler = _httpMessageHandlerFactory(clientHandler);
}
httpClient = new HttpClient(handler);
if (!_keepAliveEnabled)
{
httpClient.DefaultRequestHeaders.ConnectionClose = true;
}
if (IsExpectContinueHeaderRequired && !Fx.IsUap)
{
httpClient.DefaultRequestHeaders.ExpectContinue = true;
}
// We provide our own CancellationToken for each request. Setting HttpClient.Timeout to -1
// prevents a call to CancellationToken.CancelAfter that HttpClient does internally which
// causes TimerQueue contention at high load.
httpClient.Timeout = Timeout.InfiniteTimeSpan;
lock (_httpClientCache)
{
HttpClient tempHttpClient;
if (_httpClientCache.TryGetValue(connectionGroupName, out tempHttpClient))
{
httpClient.Dispose();
httpClient = tempHttpClient;
}
else
{
_httpClientCache.Add(connectionGroupName, httpClient);
}
}
}
return httpClient;
}
internal virtual bool IsExpectContinueHeaderRequired => AuthenticationSchemeMayRequireResend();
internal virtual HttpClientHandler GetHttpClientHandler(EndpointAddress to, SecurityTokenContainer clientCertificateToken)
{
return new HttpClientHandler();
}
internal ICredentials GetCredentials()
{
ICredentials creds = null;
if (AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
creds = CredentialCache.DefaultCredentials;
ClientCredentials credentials = _channelCredentials as ClientCredentials;
if (credentials != null)
{
switch (AuthenticationScheme)
{
case AuthenticationSchemes.Basic:
if (credentials.UserName.UserName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(ClientCredentials.UserName.UserName));
}
if (credentials.UserName.UserName == string.Empty)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.UserNameCannotBeEmpty);
}
creds = new NetworkCredential(credentials.UserName.UserName, credentials.UserName.Password);
break;
case AuthenticationSchemes.Digest:
if (credentials.HttpDigest.ClientCredential.UserName != string.Empty)
{
creds = credentials.HttpDigest.ClientCredential;
}
break;
case AuthenticationSchemes.Ntlm:
case AuthenticationSchemes.IntegratedWindowsAuthentication:
case AuthenticationSchemes.Negotiate:
if (credentials.Windows.ClientCredential.UserName != string.Empty)
{
creds = credentials.Windows.ClientCredential;
}
break;
}
}
}
return creds;
}
internal Exception CreateToMustEqualViaException(Uri to, Uri via)
{
return new ArgumentException(SR.Format(SR.HttpToMustEqualVia, to, via));
}
public override int GetMaxBufferSize()
{
return MaxBufferSize;
}
private SecurityTokenProviderContainer CreateAndOpenTokenProvider(TimeSpan timeout, AuthenticationSchemes authenticationScheme,
EndpointAddress target, Uri via, ChannelParameterCollection channelParameters)
{
SecurityTokenProvider tokenProvider = null;
switch (authenticationScheme)
{
case AuthenticationSchemes.Anonymous:
break;
case AuthenticationSchemes.Basic:
tokenProvider = TransportSecurityHelpers.GetUserNameTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Negotiate:
case AuthenticationSchemes.Ntlm:
case AuthenticationSchemes.IntegratedWindowsAuthentication:
tokenProvider = TransportSecurityHelpers.GetSspiTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Digest:
tokenProvider = TransportSecurityHelpers.GetDigestTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
default:
// The setter for this property should prevent this.
throw Fx.AssertAndThrow("CreateAndOpenTokenProvider: Invalid authentication scheme");
}
SecurityTokenProviderContainer result;
if (tokenProvider != null)
{
result = new SecurityTokenProviderContainer(tokenProvider);
result.Open(timeout);
}
else
{
result = null;
}
return result;
}
protected virtual void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
{
if (string.Compare(via.Scheme, "ws", StringComparison.OrdinalIgnoreCase) != 0)
{
ValidateScheme(via);
}
if (MessageVersion.Addressing == AddressingVersion.None && remoteAddress.Uri != via)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateToMustEqualViaException(remoteAddress.Uri, via));
}
}
protected override TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via)
{
if (typeof(TChannel) != typeof(IRequestChannel))
{
remoteAddress = remoteAddress != null && !WebSocketHelper.IsWebSocketUri(remoteAddress.Uri) ?
new EndpointAddress(WebSocketHelper.NormalizeHttpSchemeWithWsScheme(remoteAddress.Uri), remoteAddress) :
remoteAddress;
via = !WebSocketHelper.IsWebSocketUri(via) ? WebSocketHelper.NormalizeHttpSchemeWithWsScheme(via) : via;
}
return OnCreateChannelCore(remoteAddress, via);
}
protected virtual TChannel OnCreateChannelCore(EndpointAddress remoteAddress, Uri via)
{
ValidateCreateChannelParameters(remoteAddress, via);
ValidateWebSocketTransportUsage();
if (typeof(TChannel) == typeof(IRequestChannel))
{
return (TChannel)(object)new HttpClientRequestChannel((HttpChannelFactory<IRequestChannel>)(object)this, remoteAddress, via, ManualAddressing);
}
else
{
return (TChannel)(object)new ClientWebSocketTransportDuplexSessionChannel((HttpChannelFactory<IDuplexSessionChannel>)(object)this, _clientWebSocketFactory, remoteAddress, via);
}
}
protected void ValidateWebSocketTransportUsage()
{
Type channelType = typeof(TChannel);
if (channelType == typeof(IRequestChannel) && WebSocketSettings.TransportUsage == WebSocketTransportUsage.Always)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
WebSocketSettings.TransportUsage)));
}
if (channelType == typeof(IDuplexSessionChannel))
{
if (WebSocketSettings.TransportUsage == WebSocketTransportUsage.Never)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
WebSocketSettings.TransportUsage)));
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void InitializeSecurityTokenManager()
{
if (_channelCredentials == null)
{
_channelCredentials = ClientCredentials.CreateDefaultCredentials();
}
SecurityTokenManager = _channelCredentials.CreateSecurityTokenManager();
}
protected virtual bool IsSecurityTokenManagerRequired()
{
if (AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
return true;
}
if (_proxyFactory != null && _proxyFactory.AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
return true;
}
else
{
return false;
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnOpenAsync(timeout).ToApm(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
result.ToApmEnd();
}
protected override void OnOpen(TimeSpan timeout)
{
if (IsSecurityTokenManagerRequired())
{
InitializeSecurityTokenManager();
}
if (AllowCookies &&
!_httpCookieContainerManager.IsInitialized) // We don't want to overwrite the CookieContainer if someone has set it already.
{
_httpCookieContainerManager.CookieContainer = new CookieContainer();
}
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
OnOpen(timeout);
return TaskHelpers.CompletedTask();
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
return base.OnCloseAsync(timeout);
}
protected override void OnClosed()
{
base.OnClosed();
if (_httpClientCache != null && !_httpClientCache.IsDisposed)
{
lock (_httpClientCache)
{
_httpClientCache.Dispose();
_httpClientCache = null;
}
}
}
private string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential,
AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel)
{
return SecurityUtils.AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
protected virtual string OnGetConnectionGroupPrefix(SecurityTokenContainer clientCertificateToken)
{
return string.Empty;
}
internal static bool IsWindowsAuth(AuthenticationSchemes authScheme)
{
Fx.Assert(authScheme.IsSingleton() || authScheme == AuthenticationSchemes.IntegratedWindowsAuthentication, "authenticationScheme used in an Http(s)ChannelFactory must be a singleton value.");
return authScheme == AuthenticationSchemes.Negotiate ||
authScheme == AuthenticationSchemes.Ntlm ||
authScheme == AuthenticationSchemes.IntegratedWindowsAuthentication;
}
private string GetConnectionGroupName(NetworkCredential credential, AuthenticationLevel authenticationLevel,
TokenImpersonationLevel impersonationLevel, SecurityTokenContainer clientCertificateToken)
{
if (_credentialHashCache == null)
{
lock (ThisLock)
{
if (_credentialHashCache == null)
{
_credentialHashCache = new MruCache<string, string>(5);
}
}
}
string inputString = TransferModeHelper.IsRequestStreamed(TransferMode) ? "streamed" : string.Empty;
if (IsWindowsAuth(AuthenticationScheme))
{
inputString = AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
inputString = string.Concat(OnGetConnectionGroupPrefix(clientCertificateToken), inputString);
string credentialHash = null;
// we have to lock around each call to TryGetValue since the MruCache modifies the
// contents of it's mruList in a single-threaded manner underneath TryGetValue
if (!string.IsNullOrEmpty(inputString))
{
lock (_credentialHashCache)
{
if (!_credentialHashCache.TryGetValue(inputString, out credentialHash))
{
byte[] inputBytes = new UTF8Encoding().GetBytes(inputString);
byte[] digestBytes = HashAlgorithm.ComputeHash(inputBytes);
credentialHash = Convert.ToBase64String(digestBytes);
_credentialHashCache.Add(inputString, credentialHash);
}
}
}
return credentialHash;
}
internal HttpRequestMessage GetHttpRequestMessage(Uri via)
{
Uri httpRequestUri = via;
var requestMessage = new HttpRequestMessage(HttpMethod.Post, httpRequestUri);
if (TransferModeHelper.IsRequestStreamed(TransferMode))
{
requestMessage.Headers.TransferEncodingChunked = true;
}
requestMessage.Headers.CacheControl = s_requestCacheHeader;
return requestMessage;
}
private void ApplyManualAddressing(ref EndpointAddress to, ref Uri via, Message message)
{
if (ManualAddressing)
{
Uri toHeader = message.Headers.To;
if (toHeader == null)
{
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.ManualAddressingRequiresAddressedMessages), message);
}
to = new EndpointAddress(toHeader);
if (MessageVersion.Addressing == AddressingVersion.None)
{
via = toHeader;
}
}
// now apply query string property
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
if (!string.IsNullOrEmpty(requestProperty.QueryString))
{
UriBuilder uriBuilder = new UriBuilder(via);
if (requestProperty.QueryString.StartsWith("?", StringComparison.Ordinal))
{
uriBuilder.Query = requestProperty.QueryString.Substring(1);
}
else
{
uriBuilder.Query = requestProperty.QueryString;
}
via = uriBuilder.Uri;
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void CreateAndOpenTokenProvidersCore(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
tokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), AuthenticationScheme, to, via, channelParameters);
if (_proxyFactory != null)
{
proxyTokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), _proxyFactory.AuthenticationScheme, to, via, channelParameters);
}
else
{
proxyTokenProvider = null;
}
}
internal void CreateAndOpenTokenProviders(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider)
{
if (!IsSecurityTokenManagerRequired())
{
tokenProvider = null;
proxyTokenProvider = null;
}
else
{
CreateAndOpenTokenProvidersCore(to, via, channelParameters, timeout, out tokenProvider, out proxyTokenProvider);
}
}
internal static bool MapIdentity(EndpointAddress target, AuthenticationSchemes authenticationScheme)
{
if (target.Identity == null)
{
return false;
}
return IsWindowsAuth(authenticationScheme);
}
private bool MapIdentity(EndpointAddress target)
{
return MapIdentity(target, AuthenticationScheme);
}
protected class HttpClientRequestChannel : RequestChannel
{
private SecurityTokenProviderContainer _tokenProvider;
private SecurityTokenProviderContainer _proxyTokenProvider;
public HttpClientRequestChannel(HttpChannelFactory<IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing)
: base(factory, to, via, manualAddressing)
{
Factory = factory;
}
public HttpChannelFactory<IRequestChannel> Factory { get; }
protected ChannelParameterCollection ChannelParameters { get; private set; }
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ChannelParameterCollection))
{
if (State == CommunicationState.Created)
{
lock (ThisLock)
{
if (ChannelParameters == null)
{
ChannelParameters = new ChannelParameterCollection();
}
}
}
return (T)(object)ChannelParameters;
}
return base.GetProperty<T>();
}
private void PrepareOpen()
{
Factory.MapIdentity(RemoteAddress);
}
private void CreateAndOpenTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (!ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(RemoteAddress, Via, ChannelParameters, timeoutHelper.RemainingTime(), out _tokenProvider, out _proxyTokenProvider);
}
}
private void CloseTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (_tokenProvider != null)
{
_tokenProvider.Close(timeoutHelper.RemainingTime());
}
}
private void AbortTokenProviders()
{
if (_tokenProvider != null)
{
_tokenProvider.Abort();
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginOpen(this, timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected override void OnOpen(TimeSpan timeout)
{
CommunicationObjectInternal.OnOpen(this, timeout);
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
PrepareOpen();
CreateAndOpenTokenProviders(timeout);
return TaskHelpers.CompletedTask();
}
private void PrepareClose(bool aborting)
{
}
protected override void OnAbort()
{
PrepareClose(true);
AbortTokenProviders();
base.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginClose(this, timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected override void OnClose(TimeSpan timeout)
{
CommunicationObjectInternal.OnClose(this, timeout);
}
protected internal override async Task OnCloseAsync(TimeSpan timeout)
{
var timeoutHelper = new TimeoutHelper(timeout);
PrepareClose(false);
CloseTokenProviders(timeoutHelper.RemainingTime());
await WaitForPendingRequestsAsync(timeoutHelper.RemainingTime());
}
protected override IAsyncRequest CreateAsyncRequest(Message message)
{
return new HttpClientChannelAsyncRequest(this);
}
internal virtual Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, TimeoutHelper timeoutHelper)
{
return GetHttpClientAsync(to, via, null, timeoutHelper);
}
protected async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, TimeoutHelper timeoutHelper)
{
SecurityTokenProviderContainer requestTokenProvider;
SecurityTokenProviderContainer requestProxyTokenProvider;
if (ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(to, via, ChannelParameters, timeoutHelper.RemainingTime(),
out requestTokenProvider, out requestProxyTokenProvider);
}
else
{
requestTokenProvider = _tokenProvider;
requestProxyTokenProvider = _proxyTokenProvider;
}
try
{
return await Factory.GetHttpClientAsync(to, via, requestTokenProvider, requestProxyTokenProvider, clientCertificateToken, timeoutHelper.RemainingTime());
}
finally
{
if (ManualAddressing)
{
if (requestTokenProvider != null)
{
requestTokenProvider.Abort();
}
}
}
}
internal HttpRequestMessage GetHttpRequestMessage(Uri via)
{
return Factory.GetHttpRequestMessage(via);
}
internal virtual void OnHttpRequestCompleted(HttpRequestMessage request)
{
// empty
}
internal class HttpClientChannelAsyncRequest : IAsyncRequest
{
private static readonly Action<object> s_cancelCts = state =>
{
try
{
((CancellationTokenSource)state).Cancel();
}
catch (ObjectDisposedException)
{
// ignore
}
};
private HttpClientRequestChannel _channel;
private HttpChannelFactory<IRequestChannel> _factory;
private EndpointAddress _to;
private Uri _via;
private HttpRequestMessage _httpRequestMessage;
private HttpResponseMessage _httpResponseMessage;
private HttpAbortReason _abortReason;
private TimeoutHelper _timeoutHelper;
private int _httpRequestCompleted;
private HttpClient _httpClient;
private readonly CancellationTokenSource _httpSendCts;
public HttpClientChannelAsyncRequest(HttpClientRequestChannel channel)
{
_channel = channel;
_to = channel.RemoteAddress;
_via = channel.Via;
_factory = channel.Factory;
_httpSendCts = new CancellationTokenSource();
}
public async Task SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
{
_timeoutHelper = timeoutHelper;
if (_channel.Factory.MapIdentity(_to))
{
HttpTransportSecurityHelpers.AddIdentityMapping(_to, message);
}
_factory.ApplyManualAddressing(ref _to, ref _via, message);
_httpClient = await _channel.GetHttpClientAsync(_to, _via, _timeoutHelper);
// The _httpRequestMessage field will be set to null by Cleanup() due to faulting
// or aborting, so use a local copy for exception handling within this method.
HttpRequestMessage httpRequestMessage = _channel.GetHttpRequestMessage(_via);
_httpRequestMessage = httpRequestMessage;
Message request = message;
try
{
if (_channel.State != CommunicationState.Opened)
{
// if we were aborted while getting our request or doing correlation,
// we need to abort the request and bail
Cleanup();
_channel.ThrowIfDisposedOrNotOpen();
}
bool suppressEntityBody = PrepareMessageHeaders(request);
if (!suppressEntityBody)
{
httpRequestMessage.Content = MessageContent.Create(_factory, request, _timeoutHelper);
}
if (Fx.IsUap)
{
try
{
// There is a possibility that a HEAD pre-auth request might fail when the actual request
// will succeed. For example, when the web service refuses HEAD requests. We don't want
// to fail the actual request because of some subtlety which causes the HEAD request.
await SendPreauthenticationHeadRequestIfNeeded();
}
catch { /* ignored */ }
}
bool success = false;
var timeoutToken = await _timeoutHelper.GetCancellationTokenAsync();
try
{
using (timeoutToken.Register(s_cancelCts, _httpSendCts))
{
_httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, _httpSendCts.Token);
}
// As we have the response message and no exceptions have been thrown, the request message has completed it's job.
// Calling Dispose() on the request message to free up resources in HttpContent, but keeping the object around
// as we can still query properties once dispose'd.
httpRequestMessage.Dispose();
success = true;
}
catch (HttpRequestException requestException)
{
HttpChannelUtilities.ProcessGetResponseWebException(requestException, httpRequestMessage,
_abortReason);
}
catch (OperationCanceledException)
{
if (timeoutToken.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
SR.HttpRequestTimedOut, httpRequestMessage.RequestUri, _timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutToken and needs to be handled differently.
throw;
}
}
finally
{
if (!success)
{
Abort(_channel);
}
}
}
finally
{
if (!ReferenceEquals(request, message))
{
request.Close();
}
}
}
private void Cleanup()
{
s_cancelCts(_httpSendCts);
if (_httpRequestMessage != null)
{
var httpRequestMessageSnapshot = _httpRequestMessage;
_httpRequestMessage = null;
TryCompleteHttpRequest(httpRequestMessageSnapshot);
httpRequestMessageSnapshot.Dispose();
}
}
public void Abort(RequestChannel channel)
{
Cleanup();
_abortReason = HttpAbortReason.Aborted;
}
public void Fault(RequestChannel channel)
{
Cleanup();
}
public async Task<Message> ReceiveReplyAsync(TimeoutHelper timeoutHelper)
{
try
{
_timeoutHelper = timeoutHelper;
var responseHelper = new HttpResponseMessageHelper(_httpResponseMessage, _factory);
var replyMessage = await responseHelper.ParseIncomingResponse(timeoutHelper);
TryCompleteHttpRequest(_httpRequestMessage);
return replyMessage;
}
catch (OperationCanceledException)
{
var cancelToken = _timeoutHelper.GetCancellationToken();
if (cancelToken.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
SR.HttpResponseTimedOut, _httpRequestMessage.RequestUri, timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
throw;
}
}
}
private bool PrepareMessageHeaders(Message message)
{
string action = message.Headers.Action;
if (action != null)
{
action = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", UrlUtility.UrlPathEncode(action));
}
bool suppressEntityBody = message is NullMessage;
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
_httpRequestMessage.Method = new HttpMethod(requestProperty.Method);
// Query string was applied in HttpChannelFactory.ApplyManualAddressing
WebHeaderCollection requestHeaders = requestProperty.Headers;
suppressEntityBody = suppressEntityBody || requestProperty.SuppressEntityBody;
var headerKeys = requestHeaders.AllKeys;
for (int i = 0; i < headerKeys.Length; i++)
{
string name = headerKeys[i];
string value = requestHeaders[name];
if (string.Compare(name, "accept", StringComparison.OrdinalIgnoreCase) == 0)
{
_httpRequestMessage.Headers.Accept.TryParseAdd(value);
}
else if (string.Compare(name, "connection", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.ConnectionClose = false;
}
else
{
_httpRequestMessage.Headers.Connection.TryParseAdd(value);
}
}
else if (string.Compare(name, "SOAPAction", StringComparison.OrdinalIgnoreCase) == 0)
{
if (action == null)
{
action = value;
}
else
{
if (!String.IsNullOrEmpty(value) && string.Compare(value, action, StringComparison.Ordinal) != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.HttpSoapActionMismatch, action, value)));
}
}
}
else if (string.Compare(name, "content-length", StringComparison.OrdinalIgnoreCase) == 0)
{
// this will be taken care of by System.Net when we write to the content
}
else if (string.Compare(name, "content-type", StringComparison.OrdinalIgnoreCase) == 0)
{
// Handled by MessageContent
}
else if (string.Compare(name, "expect", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.ToUpperInvariant().IndexOf("100-CONTINUE", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.ExpectContinue = true;
}
else
{
_httpRequestMessage.Headers.Expect.TryParseAdd(value);
}
}
else if (string.Compare(name, "referer", StringComparison.OrdinalIgnoreCase) == 0)
{
// referrer is proper spelling, but referer is the what is in the protocol.
_httpRequestMessage.Headers.Referrer = new Uri(value);
}
else if (string.Compare(name, "transfer-encoding", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.ToUpperInvariant().IndexOf("CHUNKED", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.TransferEncodingChunked = true;
}
else
{
_httpRequestMessage.Headers.TransferEncoding.TryParseAdd(value);
}
}
else if (string.Compare(name, "user-agent", StringComparison.OrdinalIgnoreCase) == 0)
{
_httpRequestMessage.Headers.Add(name, value);
}
else if (string.Compare(name, "if-modified-since", StringComparison.OrdinalIgnoreCase) == 0)
{
DateTimeOffset modifiedSinceDate;
if (DateTimeOffset.TryParse(value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeLocal, out modifiedSinceDate))
{
_httpRequestMessage.Headers.IfModifiedSince = modifiedSinceDate;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.HttpIfModifiedSinceParseError, value)));
}
}
else if (string.Compare(name, "date", StringComparison.OrdinalIgnoreCase) == 0)
{
// this will be taken care of by System.Net when we make the request
}
else if (string.Compare(name, "proxy-connection", StringComparison.OrdinalIgnoreCase) == 0)
{
throw ExceptionHelper.PlatformNotSupported("proxy-connection");
}
else if (string.Compare(name, "range", StringComparison.OrdinalIgnoreCase) == 0)
{
// specifying a range doesn't make sense in the context of WCF
}
else
{
try
{
_httpRequestMessage.Headers.Add(name, value);
}
catch (Exception addHeaderException)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.CopyHttpHeaderFailed,
name,
value,
HttpChannelUtilities.HttpRequestHeadersTypeName),
addHeaderException));
}
}
}
}
if (action != null)
{
if (message.Version.Envelope == EnvelopeVersion.Soap11)
{
_httpRequestMessage.Headers.TryAddWithoutValidation("SOAPAction", action);
}
else if (message.Version.Envelope == EnvelopeVersion.Soap12)
{
// Handled by MessageContent
}
else if (message.Version.Envelope != EnvelopeVersion.None)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.EnvelopeVersionUnknown,
message.Version.Envelope.ToString())));
}
}
// since we don't get the output stream in send when retVal == true,
// we need to disable chunking for some verbs (DELETE/PUT)
if (suppressEntityBody)
{
_httpRequestMessage.Headers.TransferEncodingChunked = false;
}
return suppressEntityBody;
}
public void OnReleaseRequest()
{
TryCompleteHttpRequest(_httpRequestMessage);
}
private void TryCompleteHttpRequest(HttpRequestMessage request)
{
if (request == null)
{
return;
}
if (Interlocked.CompareExchange(ref _httpRequestCompleted, 1, 0) == 0)
{
_channel.OnHttpRequestCompleted(request);
}
}
private async Task SendPreauthenticationHeadRequestIfNeeded()
{
if (!_factory.AuthenticationSchemeMayRequireResend())
{
return;
}
var requestUri = _httpRequestMessage.RequestUri;
// sends a HEAD request to the specificed requestUri for authentication purposes
Contract.Assert(requestUri != null);
HttpRequestMessage headHttpRequestMessage = new HttpRequestMessage()
{
Method = HttpMethod.Head,
RequestUri = requestUri
};
var cancelToken = await _timeoutHelper.GetCancellationTokenAsync();
await _httpClient.SendAsync(headHttpRequestMessage, cancelToken);
}
}
}
private class WebProxyFactory
{
private Uri _address;
private bool _bypassOnLocal;
public WebProxyFactory(Uri address, bool bypassOnLocal, AuthenticationSchemes authenticationScheme)
{
_address = address;
_bypassOnLocal = bypassOnLocal;
if (!authenticationScheme.IsSingleton() && authenticationScheme != AuthenticationSchemes.IntegratedWindowsAuthentication)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(nameof(authenticationScheme), SR.Format(SR.HttpRequiresSingleAuthScheme,
authenticationScheme));
}
AuthenticationScheme = authenticationScheme;
}
internal AuthenticationSchemes AuthenticationScheme { get; }
public async Task<IWebProxy> CreateWebProxyAsync(AuthenticationLevel requestAuthenticationLevel, TokenImpersonationLevel requestImpersonationLevel, SecurityTokenProviderContainer tokenProvider, TimeSpan timeout)
{
WebProxy result = new WebProxy(_address, _bypassOnLocal);
if (AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
var impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
var authenticationLevelWrapper = new OutWrapper<AuthenticationLevel>();
NetworkCredential credential = await HttpChannelUtilities.GetCredentialAsync(AuthenticationScheme,
tokenProvider, impersonationLevelWrapper, authenticationLevelWrapper, timeout);
// The impersonation level for target auth is also used for proxy auth (by System.Net). Therefore,
// fail if the level stipulated for proxy auth is more restrictive than that for target auth.
if (!TokenImpersonationLevelHelper.IsGreaterOrEqual(impersonationLevelWrapper.Value, requestImpersonationLevel))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
SR.ProxyImpersonationLevelMismatch, impersonationLevelWrapper.Value, requestImpersonationLevel)));
}
// The authentication level for target auth is also used for proxy auth (by System.Net).
// Therefore, fail if proxy auth requires mutual authentication but target auth does not.
if ((authenticationLevelWrapper.Value == AuthenticationLevel.MutualAuthRequired) &&
(requestAuthenticationLevel != AuthenticationLevel.MutualAuthRequired))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
SR.ProxyAuthenticationLevelMismatch, authenticationLevelWrapper.Value, requestAuthenticationLevel)));
}
CredentialCache credentials = new CredentialCache();
if (AuthenticationScheme == AuthenticationSchemes.IntegratedWindowsAuthentication)
{
credentials.Add(_address, AuthenticationSchemesHelper.ToString(AuthenticationSchemes.Negotiate),
credential);
credentials.Add(_address, AuthenticationSchemesHelper.ToString(AuthenticationSchemes.Ntlm),
credential);
}
else
{
credentials.Add(_address, AuthenticationSchemesHelper.ToString(AuthenticationScheme),
credential);
}
result.Credentials = credentials;
}
return result;
}
}
}
}
| |
namespace Nancy.Bootstrappers.Ninject
{
using System;
using System.Collections.Generic;
using global::Ninject;
using global::Ninject.Extensions.ChildKernel;
using global::Ninject.Infrastructure;
using Bootstrapper;
using Configuration;
using Diagnostics;
/// <summary>
/// Nancy bootstrapper for the Ninject container.
/// </summary>
public abstract class NinjectNancyBootstrapper : NancyBootstrapperWithRequestContainerBase<IKernel>
{
/// <summary>
/// Gets the diagnostics for intialisation
/// </summary>
/// <returns>An <see cref="IDiagnostics"/> implementation</returns>
protected override IDiagnostics GetDiagnostics()
{
return this.ApplicationContainer.Get<IDiagnostics>();
}
/// <summary>
/// Gets all registered application startup tasks
/// </summary>
/// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IApplicationStartup"/> instances. </returns>
protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks()
{
return this.ApplicationContainer.GetAll<IApplicationStartup>();
}
/// <summary>
/// Gets all registered request startup tasks
/// </summary>
/// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IRequestStartup"/> instances.</returns>
protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(IKernel container, Type[] requestStartupTypes)
{
foreach (var requestStartupType in requestStartupTypes)
{
container.Bind(typeof(IRequestStartup)).To(requestStartupType).InSingletonScope();
}
return container.GetAll<IRequestStartup>();
}
/// <summary>
/// Gets all registered application registration tasks
/// </summary>
/// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IRegistrations"/> instances.</returns>
protected override IEnumerable<IRegistrations> GetRegistrationTasks()
{
return this.ApplicationContainer.GetAll<IRegistrations>();
}
/// <summary>
/// Get INancyEngine
/// </summary>
/// <returns>An <see cref="INancyEngine"/> implementation</returns>
protected override sealed INancyEngine GetEngineInternal()
{
return this.ApplicationContainer.Get<INancyEngine>();
}
/// <summary>
/// Gets the <see cref="INancyEnvironmentConfigurator"/> used by th.
/// </summary>
/// <returns>An <see cref="INancyEnvironmentConfigurator"/> instance.</returns>
protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator()
{
return this.ApplicationContainer.Get<INancyEnvironmentConfigurator>();
}
/// <summary>
/// Registers an <see cref="INancyEnvironment"/> instance in the container.
/// </summary>
/// <param name="container">The container to register into.</param>
/// <param name="environment">The <see cref="INancyEnvironment"/> instance to register.</param>
protected override void RegisterNancyEnvironment(IKernel container, INancyEnvironment environment)
{
container.Bind<INancyEnvironment>().ToConstant(environment);
}
/// <summary>
/// Create a default, unconfigured, container
/// </summary>
/// <returns>Container instance</returns>
protected override IKernel GetApplicationContainer()
{
return new StandardKernel(new[] { new FactoryModule() });
}
/// <summary>
/// Bind the bootstrapper's implemented types into the container.
/// This is necessary so a user can pass in a populated container but not have
/// to take the responsibility of registering things like <see cref="INancyModuleCatalog"/> manually.
/// </summary>
/// <param name="applicationContainer">Application container to register into</param>
protected override sealed void RegisterBootstrapperTypes(IKernel applicationContainer)
{
applicationContainer.Bind<INancyModuleCatalog>().ToConstant(this);
}
/// <summary>
/// Bind the default implementations of internally used types into the container as singletons
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="typeRegistrations">Type registrations to register</param>
protected override sealed void RegisterTypes(IKernel container, IEnumerable<TypeRegistration> typeRegistrations)
{
foreach (var typeRegistration in typeRegistrations)
{
switch (typeRegistration.Lifetime)
{
case Lifetime.Transient:
container.Bind(typeRegistration.RegistrationType).To(typeRegistration.ImplementationType).InTransientScope();
break;
case Lifetime.Singleton:
container.Bind(typeRegistration.RegistrationType).To(typeRegistration.ImplementationType).InSingletonScope();
break;
case Lifetime.PerRequest:
throw new InvalidOperationException("Unable to directly register a per request lifetime.");
default:
throw new ArgumentOutOfRangeException();
}
}
}
/// <summary>
/// Bind the various collections into the container as singletons to later be resolved
/// by IEnumerable{Type} constructor dependencies.
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="collectionTypeRegistrations">Collection type registrations to register</param>
protected override sealed void RegisterCollectionTypes(IKernel container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations)
{
foreach (var collectionTypeRegistration in collectionTypeRegistrations)
{
foreach (var implementationType in collectionTypeRegistration.ImplementationTypes)
{
switch (collectionTypeRegistration.Lifetime)
{
case Lifetime.Transient:
container.Bind(collectionTypeRegistration.RegistrationType).To(implementationType).InTransientScope();
break;
case Lifetime.Singleton:
container.Bind(collectionTypeRegistration.RegistrationType).To(implementationType).InSingletonScope();
break;
case Lifetime.PerRequest:
throw new InvalidOperationException("Unable to directly register a per request lifetime.");
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
/// <summary>
/// Bind the given module types into the container
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="moduleRegistrationTypes"><see cref="INancyModule"/> types</param>
protected override sealed void RegisterRequestContainerModules(IKernel container, IEnumerable<ModuleRegistration> moduleRegistrationTypes)
{
foreach (var moduleRegistrationType in moduleRegistrationTypes)
{
container.Bind(typeof(INancyModule)).To(moduleRegistrationType.ModuleType).Named(moduleRegistrationType.ModuleType.FullName);
}
}
/// <summary>
/// Bind the given instances into the container
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="instanceRegistrations">Instance registration types</param>
protected override void RegisterInstances(IKernel container, IEnumerable<InstanceRegistration> instanceRegistrations)
{
foreach (var instanceRegistration in instanceRegistrations)
{
container.Bind(instanceRegistration.RegistrationType).ToConstant(instanceRegistration.Implementation);
}
}
/// <summary>
/// Creates a per request child/nested container
/// </summary>
/// <param name="context">Current context</param>
/// <returns>Request container instance</returns>
protected override IKernel CreateRequestContainer(NancyContext context)
{
return new ChildKernel(this.ApplicationContainer, new NinjectSettings { DefaultScopeCallback = StandardScopeCallbacks.Singleton });
}
/// <summary>
/// Retrieve all module instances from the container
/// </summary>
/// <param name="container">Container to use</param>
/// <returns>Collection of <see cref="INancyModule"/> instances</returns>
protected override sealed IEnumerable<INancyModule> GetAllModules(IKernel container)
{
return container.GetAll<INancyModule>();
}
/// <summary>
/// Retrieve a specific module instance from the container
/// </summary>
/// <param name="container">Container to use</param>
/// <param name="moduleType">Type of the module</param>
/// <returns>An <see cref="INancyModule"/> instance</returns>
protected override INancyModule GetModule(IKernel container, Type moduleType)
{
container.Bind<INancyModule>().To(moduleType);
return container.Get(moduleType) as INancyModule;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using NDesk.Options;
using Nini.Config;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.World.Archiver
{
/// <summary>
/// This module loads and saves OpenSimulator region archives
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ArchiverModule")]
public class ArchiverModule : INonSharedRegionModule, IRegionArchiverModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public Scene Scene { get; private set; }
public IRegionCombinerModule RegionCombinerModule { get; private set; }
/// <value>
/// The file used to load and save an opensimulator archive if no filename has been specified
/// </value>
protected const string DEFAULT_OAR_BACKUP_FILENAME = "region.oar";
public string Name
{
get { return "RegionArchiverModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
//m_log.Debug("[ARCHIVER] Initialising");
}
public void AddRegion(Scene scene)
{
Scene = scene;
Scene.RegisterModuleInterface<IRegionArchiverModule>(this);
//m_log.DebugFormat("[ARCHIVER]: Enabled for region {0}", scene.RegionInfo.RegionName);
}
public void RegionLoaded(Scene scene)
{
RegionCombinerModule = scene.RequestModuleInterface<IRegionCombinerModule>();
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
/// <summary>
/// Load a whole region from an opensimulator archive.
/// </summary>
/// <param name="cmdparams"></param>
public void HandleLoadOarConsoleCommand(string module, string[] cmdparams)
{
bool mergeOar = false;
bool skipAssets = false;
bool forceTerrain = false;
bool forceParcels = false;
bool noObjects = false;
Vector3 displacement = new Vector3(0f, 0f, 0f);
String defaultUser = "";
float rotation = 0f;
Vector3 rotationCenter = new Vector3(Scene.RegionInfo.RegionSizeX / 2f, Scene.RegionInfo.RegionSizeY / 2f, 0);
Vector3 boundingOrigin = new Vector3(0f, 0f, 0f);
Vector3 boundingSize = new Vector3(Scene.RegionInfo.RegionSizeX, Scene.RegionInfo.RegionSizeY, Constants.RegionHeight);
bool debug = false;
OptionSet options = new OptionSet();
options.Add("m|merge", delegate(string v) { mergeOar = (v != null); });
options.Add("s|skip-assets", delegate(string v) { skipAssets = (v != null); });
options.Add("force-terrain", delegate(string v) { forceTerrain = (v != null); });
options.Add("forceterrain", delegate(string v) { forceTerrain = (v != null); }); // downward compatibility
options.Add("force-parcels", delegate(string v) { forceParcels = (v != null); });
options.Add("forceparcels", delegate(string v) { forceParcels = (v != null); }); // downward compatibility
options.Add("no-objects", delegate(string v) { noObjects = (v != null); });
options.Add("default-user=", delegate(string v) { defaultUser = (v == null) ? "" : v; });
options.Add("displacement=", delegate(string v)
{
try
{
displacement = v == null ? Vector3.Zero : Vector3.Parse(v);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing displacement");
m_log.ErrorFormat("[ARCHIVER MODULE] Must be represented as vector3: --displacement \"<128,128,0>\"");
return;
}
});
options.Add("rotation=", delegate(string v)
{
try
{
rotation = v == null ? 0f : float.Parse(v);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing rotation");
m_log.ErrorFormat("[ARCHIVER MODULE] Must be an angle in degrees between -360 and +360: --rotation 45");
return;
}
//pass this in as degrees now, convert to radians later during actual work phase
rotation = Util.Clamp<float>(rotation, -359f, 359f);
});
options.Add("rotation-center=", delegate(string v)
{
try
{
m_log.Info("[ARCHIVER MODULE] Warning: --rotation-center no longer does anything and will be removed soon!");
rotationCenter = v == null ? Vector3.Zero : Vector3.Parse(v);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing rotation displacement");
m_log.ErrorFormat("[ARCHIVER MODULE] Must be represented as vector3: --rotation-center \"<128,128,0>\"");
return;
}
});
options.Add("bounding-origin=", delegate(string v)
{
try
{
boundingOrigin = v == null ? Vector3.Zero : Vector3.Parse(v);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing bounding cube origin");
m_log.ErrorFormat("[ARCHIVER MODULE] Must be represented as vector3: --bounding-origin \"<128,128,0>\"");
return;
}
});
options.Add("bounding-size=", delegate(string v)
{
try
{
boundingSize = v == null ? new Vector3(Scene.RegionInfo.RegionSizeX, Scene.RegionInfo.RegionSizeY, Constants.RegionHeight) : Vector3.Parse(v);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing bounding cube size");
m_log.ErrorFormat("[ARCHIVER MODULE] Must be represented as a positive vector3: --bounding-size \"<256,256,4096>\"");
return;
}
});
options.Add("d|debug", delegate(string v) { debug = (v != null); });
// Send a message to the region ready module
/* bluewall* Disable this for the time being
IRegionReadyModule rready = m_scene.RequestModuleInterface<IRegionReadyModule>();
if (rready != null)
{
rready.OarLoadingAlert("load");
}
*/
List<string> mainParams = options.Parse(cmdparams);
// m_log.DebugFormat("MERGE OAR IS [{0}]", mergeOar);
//
// foreach (string param in mainParams)
// m_log.DebugFormat("GOT PARAM [{0}]", param);
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
if (mergeOar) archiveOptions.Add("merge", null);
if (skipAssets) archiveOptions.Add("skipAssets", null);
if (forceTerrain) archiveOptions.Add("force-terrain", null);
if (forceParcels) archiveOptions.Add("force-parcels", null);
if (noObjects) archiveOptions.Add("no-objects", null);
if (defaultUser != "")
{
UUID defaultUserUUID = UUID.Zero;
try
{
defaultUserUUID = Scene.UserManagementModule.GetUserIdByName(defaultUser);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] default user must be in format \"First Last\"", defaultUser);
}
if (defaultUserUUID == UUID.Zero)
{
m_log.ErrorFormat("[ARCHIVER MODULE] cannot find specified default user {0}", defaultUser);
return;
}
else
{
archiveOptions.Add("default-user", defaultUserUUID);
}
}
archiveOptions.Add("displacement", displacement);
archiveOptions.Add("rotation", rotation);
archiveOptions.Add("rotation-center", rotationCenter);
archiveOptions.Add("bounding-origin", boundingOrigin);
archiveOptions.Add("bounding-size", boundingSize);
if (debug) archiveOptions.Add("debug", null);
if (mainParams.Count > 2)
{
DearchiveRegion(mainParams[2], Guid.Empty, archiveOptions);
}
else
{
DearchiveRegion(DEFAULT_OAR_BACKUP_FILENAME, Guid.Empty, archiveOptions);
}
}
/// <summary>
/// Save a region to a file, including all the assets needed to restore it.
/// </summary>
/// <param name="cmdparams"></param>
public void HandleSaveOarConsoleCommand(string module, string[] cmdparams)
{
Dictionary<string, object> options = new Dictionary<string, object>();
OptionSet ops = new OptionSet();
// legacy argument [obsolete]
ops.Add("p|profile=", delegate(string v) { Console.WriteLine("\n WARNING: -profile option is obsolete and it will not work. Use -home instead.\n"); });
// preferred
ops.Add("h|home=", delegate(string v) { options["home"] = v; });
ops.Add("noassets", delegate(string v) { options["noassets"] = v != null; });
ops.Add("publish", v => options["wipe-owners"] = v != null);
ops.Add("perm=", delegate(string v) { options["checkPermissions"] = v; });
ops.Add("all", delegate(string v) { options["all"] = v != null; });
List<string> mainParams = ops.Parse(cmdparams);
string path;
if (mainParams.Count > 2)
path = mainParams[2];
else
path = DEFAULT_OAR_BACKUP_FILENAME;
// Not doing this right now as this causes some problems with auto-backup systems. Maybe a force flag is
// needed
// if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, path))
// return;
ArchiveRegion(path, options);
}
public void ArchiveRegion(string savePath, Dictionary<string, object> options)
{
ArchiveRegion(savePath, Guid.Empty, options);
}
public void ArchiveRegion(string savePath, Guid requestId, Dictionary<string, object> options)
{
m_log.InfoFormat(
"[ARCHIVER]: Writing archive for region {0} to {1}", Scene.RegionInfo.RegionName, savePath);
new ArchiveWriteRequest(Scene, savePath, requestId).ArchiveRegion(options);
}
public void ArchiveRegion(Stream saveStream)
{
ArchiveRegion(saveStream, Guid.Empty);
}
public void ArchiveRegion(Stream saveStream, Guid requestId)
{
ArchiveRegion(saveStream, requestId, new Dictionary<string, object>());
}
public void ArchiveRegion(Stream saveStream, Guid requestId, Dictionary<string, object> options)
{
new ArchiveWriteRequest(Scene, saveStream, requestId).ArchiveRegion(options);
}
public void DearchiveRegion(string loadPath)
{
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
DearchiveRegion(loadPath, Guid.Empty, archiveOptions);
}
public void DearchiveRegion(string loadPath, Guid requestId, Dictionary<string, object> options)
{
m_log.InfoFormat(
"[ARCHIVER]: Loading archive to region {0} from {1}", Scene.RegionInfo.RegionName, loadPath);
new ArchiveReadRequest(Scene, loadPath, requestId, options).DearchiveRegion();
}
public void DearchiveRegion(Stream loadStream)
{
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
DearchiveRegion(loadStream, Guid.Empty, archiveOptions);
}
public void DearchiveRegion(Stream loadStream, Guid requestId, Dictionary<string, object> options)
{
new ArchiveReadRequest(Scene, loadStream, requestId, options).DearchiveRegion();
}
}
}
| |
#region License
// Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
namespace SourceCode.Clay.Data.SqlParser
{
public static class SqlTokenizer
{
/// <summary>
/// Tokenizes the provided sql statement.
/// </summary>
/// <param name="sql">The tsql statement to tokenize.</param>
/// <param name="skipSundry">Do not emit sundry tokens (such as comments and whitespace) in the output.</param>
public static IReadOnlyCollection<SqlTokenInfo> Tokenize(string sql, bool skipSundry)
{
if (sql is null) throw new ArgumentNullException(nameof(sql));
using (var reader = new SqlCharReader(sql))
{
IReadOnlyCollection<SqlTokenInfo> tokens = Tokenize(reader, skipSundry);
return tokens;
}
}
/// <summary>
/// Tokenizes the provided sql statement.
/// </summary>
/// <param name="reader">A reader providing the tsql statement to tokenize.</param>
/// <param name="skipSundry">Do not emit sundry tokens (such as comments and whitespace) in the output.</param>
public static IReadOnlyCollection<SqlTokenInfo> Tokenize(TextReader reader, bool skipSundry)
{
if (reader is null) throw new ArgumentNullException(nameof(reader));
using (var cr = new SqlCharReader(reader))
{
IReadOnlyCollection<SqlTokenInfo> tokens = Tokenize(cr, skipSundry);
return tokens;
}
}
/// <summary>
/// Encodes an identifier using tsql [square-delimited-name] convention.
/// </summary>
/// <param name="identifier">The identifier to encode.</param>
public static string EncodeNameSquare(string identifier)
{
if (string.IsNullOrEmpty(identifier)) return identifier;
const string openSquare = "[";
const string closeSquare = "]";
const string closeSquareEscaped = closeSquare + closeSquare;
// Need 2 delimiters. Assume 1 escape.
var capacity = identifier.Length + 2 + 1;
var sb = new StringBuilder(openSquare, capacity);
{
sb.Append(identifier);
sb.Replace(closeSquare, closeSquareEscaped); // Escape embedded delimiters
}
sb.Append(closeSquare);
var quoted = sb.ToString();
return quoted;
}
/// <summary>
/// Encodes an identifier using tsql "quoted-name" convention.
/// </summary>
/// <param name="identifier">The identifier to encode.</param>
public static string EncodeNameQuotes(string identifier)
{
if (string.IsNullOrEmpty(identifier)) return identifier;
const string quote = "\"";
const string quoteEscaped = quote + quote;
// Need 2 delimiters. Assume 1 escape.
var capacity = identifier.Length + 2 + 1;
var sb = new StringBuilder("~", capacity); // Placeholder. See #1 below
{
sb.Append(identifier);
sb.Replace(quote, quoteEscaped); // Escape embedded delimiters
}
sb[0] = quote[0]; // Replace placeholder. See #1 above
sb.Append(quote);
var quoted = sb.ToString();
return quoted;
}
/// <summary>
/// Encodes an identifier using tsql naming conventions.
/// </summary>
/// <param name="identifier">The identifier to encode.</param>
/// <param name="useQuotes">If true, uses "quotes" else uses [square] delimiters.</param>
public static string EncodeName(string identifier, bool useQuotes)
=> useQuotes ?
EncodeNameQuotes(identifier) :
EncodeNameSquare(identifier);
/// <summary>
/// Tokenizes the provided sql statement.
/// </summary>
/// <param name="reader"></param>
/// <param name="skipSundry">Do not emit sundry tokens (such as comments and whitespace) in the output.</param>
private static IReadOnlyCollection<SqlTokenInfo> Tokenize(SqlCharReader reader, bool skipSundry)
{
Debug.Assert(!(reader is null));
Span<char> peekBuffer = stackalloc char[2];
var tokens = new List<SqlTokenInfo>();
while (true)
{
reader.FillLength(peekBuffer, peekBuffer.Length, out var peekLength);
if (peekLength <= 0) break;
SqlTokenInfo token;
SqlTokenKind kind = Peek(peekBuffer.Slice(0, peekLength));
switch (kind)
{
case SqlTokenKind.Whitespace:
token = ReadWhitespace(peekBuffer, peekLength, reader, skipSundry);
if (skipSundry) continue;
break;
case SqlTokenKind.LineComment:
token = ReadLineComment(reader, skipSundry);
if (skipSundry) continue;
break;
case SqlTokenKind.BlockComment:
token = ReadBlockComment(reader, skipSundry);
if (skipSundry) continue;
break;
case SqlTokenKind.Literal:
token = ReadLiteral(peekBuffer, peekLength, reader);
break;
case SqlTokenKind.Symbol:
token = ReadSymbol(peekBuffer, peekLength, reader);
break;
case SqlTokenKind.SquareString:
token = ReadSquareString(peekBuffer, peekLength, reader);
break;
case SqlTokenKind.QuotedString:
token = ReadQuotedString(peekBuffer, peekLength, reader);
break;
default:
throw new InvalidOperationException($"Unknown {nameof(SqlTokenKind)}: {kind}");
}
tokens.Add(token);
}
return tokens;
}
private static SqlTokenKind Peek(ReadOnlySpan<char> peekBuffer)
{
Debug.Assert(peekBuffer.Length >= 1);
var canPeekDouble = peekBuffer.Length >= 2;
switch (peekBuffer[0])
{
// Line Comment
case '-':
return canPeekDouble && peekBuffer[1] == '-' ? SqlTokenKind.LineComment : SqlTokenKind.Symbol;
// Block Comment
case '/':
return canPeekDouble && peekBuffer[1] == '*' ? SqlTokenKind.BlockComment : SqlTokenKind.Symbol;
// Quoted String
case 'N':
return canPeekDouble && peekBuffer[1] == '\'' ? SqlTokenKind.QuotedString : SqlTokenKind.Literal;
// Quoted String
case '"':
case '\'':
return SqlTokenKind.QuotedString;
// Square String
case '[':
return SqlTokenKind.SquareString;
// Math
case '+':
case '*':
case '%':
// Logical
case '&':
case '|':
case '^':
case '~':
// Comparison
case '>':
case '<':
case '=':
// Symbol
case ',':
case '.':
case ';':
case '(':
case ')':
return SqlTokenKind.Symbol;
}
if (canPeekDouble)
{
var s2 = new string(peekBuffer.Slice(0, 2));
switch (s2)
{
// Math
case "+=":
case "-=":
case "*=":
case "/=":
case "%=":
// Logical
case "&=":
case "|=":
case "^=":
// Comparison
case ">=":
case "<=":
case "<>":
case "!<":
case "!=":
case "!>":
// Symbol
case "::":
return SqlTokenKind.Symbol;
}
}
return char.IsWhiteSpace(peekBuffer[0]) ? SqlTokenKind.Whitespace : SqlTokenKind.Literal;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool Contains(ReadOnlySpan<char> buffer, char c0)
=> buffer.Length >= 1
&& buffer[0] == c0;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool Contains(ReadOnlySpan<char> buffer, char c0, char c1)
=> buffer.Length >= 2
&& buffer[0] == c0
&& buffer[1] == c1;
/// <summary>
///
/// </summary>
/// <param name="peekBuffer"></param>
/// <param name="peekLength"></param>
/// <param name="reader"></param>
/// <param name="skipSundry">Do not emit sundry tokens (such as comments and whitespace) in the output.</param>
private static SqlTokenInfo ReadWhitespace(ReadOnlySpan<char> peekBuffer, int peekLength, SqlCharReader reader, bool skipSundry)
{
Debug.Assert(peekBuffer.Length >= 1);
Debug.Assert(peekLength >= 1);
Debug.Assert(!(reader is null));
// Fast path for single whitespace
if (peekLength >= 2
&& !char.IsWhiteSpace(peekBuffer[1]))
{
// Undo any extraneous data
reader.Undo(peekBuffer.Slice(1, peekLength - 1));
var t0 = new SqlTokenInfo(SqlTokenKind.Whitespace, peekBuffer[0]);
return t0;
}
// Perf: Assume whitespace is N chars
const int averageLen = 10;
var cap = peekLength + averageLen;
Span<char> buffer = stackalloc char[cap];
StringBuilder sb = skipSundry ? null : new StringBuilder(cap);
// We already know the incoming data is "<whitespace>", so keep it
if (!skipSundry)
sb.Append(peekBuffer.Slice(0, peekLength));
while (true)
{
reader.FillRemaining(buffer, out var count);
if (count <= 0) break;
// Try find any non-whitespace in current batch
var idx = -1;
for (var i = 0; i < count; i++)
{
if (!char.IsWhiteSpace(buffer[i]))
{
idx = i;
break;
}
}
// If we found any non-whitespace
if (idx >= 0)
{
// Undo any extraneous data and exit the loop
if (!skipSundry)
sb.Append(buffer.Slice(0, idx));
reader.Undo(buffer.Slice(idx, count - idx));
break;
}
// Else keep the whitespace and check next batch
if (!skipSundry)
sb.Append(buffer.Slice(0, count));
}
var token = new SqlTokenInfo(SqlTokenKind.Whitespace, sb);
return token;
}
private static SqlTokenInfo ReadSquareString(ReadOnlySpan<char> peekBuffer, int peekLength, SqlCharReader reader)
{
Debug.Assert(peekBuffer.Length >= 1);
Debug.Assert(peekBuffer[0] == '[');
Debug.Assert(peekLength >= 1);
Debug.Assert(!(reader is null));
// Sql Identifiers are max 128 chars
var cap = peekLength + 128;
Span<char> buffer = stackalloc char[cap];
var sb = new StringBuilder(cap);
// We already know the incoming data is [, so keep it
sb.Append(peekBuffer[0]);
// Undo any extraneous data
if (peekLength > 1)
{
reader.Undo(peekBuffer.Slice(1, peekLength - 1));
}
while (true)
{
reader.FillLength(buffer, 4, out var count);
if (count <= 0) break;
var eof = count <= 3;
var cnt = eof ? count : count - 3;
// Try find a delimiter
var idx = -1;
for (var i = 0; i < cnt; i++)
{
if (!Contains(buffer.Slice(i, count - i), ']'))
continue;
idx = i;
break;
}
// If we found a delimiter
if (idx >= 0)
{
// If it is an escaped delimiter
// https://docs.microsoft.com/en-us/sql/t-sql/functions/quotename-transact-sql
if (idx >= 1 && Contains(buffer.Slice(idx, count - idx), ']', ']'))
{
// Keep going
sb.Append(buffer.Slice(0, idx + 2));
reader.Undo(buffer.Slice(idx + 2, count - idx - 2));
continue;
}
// Else undo any extraneous data and exit the loop
sb.Append(buffer.Slice(0, idx + 1));
reader.Undo(buffer.Slice(idx + 1, count - idx - 1));
break;
}
sb.Append(buffer.Slice(0, cnt));
// Exit if no more data
if (eof) break;
// Ensure we can peek again
reader.Undo(buffer.Slice(cnt, 3));
}
var token = new SqlTokenInfo(SqlTokenKind.SquareString, sb);
return token;
}
private static SqlTokenInfo ReadQuotedString(ReadOnlySpan<char> peekBuffer, int peekLength, SqlCharReader reader)
{
Debug.Assert(peekBuffer.Length >= 1);
Debug.Assert(peekLength >= 1);
Debug.Assert(!(reader is null));
// Perf: Assume string is N chars
const int averageLen = 256;
var cap = peekLength + averageLen;
var sb = new StringBuilder(cap);
// We already know the incoming data is "<quote>", so keep it
var len = peekBuffer[0] == '\'' || peekBuffer[0] == '"' ? 1 : 2;
sb.Append(peekBuffer.Slice(0, len));
// Undo any extraneous data
if (peekLength > len)
{
reader.Undo(peekBuffer.Slice(len, peekLength - len));
}
// Read string value
switch (peekBuffer[0])
{
case '"': // "abc"
{
SqlTokenInfo token = ReadQuotedString(sb, '"', reader);
return token;
}
case '\'': // 'abc'
{
SqlTokenInfo token = ReadQuotedString(sb, '\'', reader);
return token;
}
case 'N': // N'abc'
if (peekLength >= 2 && peekBuffer[1] == '\'')
{
SqlTokenInfo token = ReadQuotedString(sb, '\'', reader);
return token;
}
break;
}
throw new ArgumentException("Invalid quoted string: " + new string(peekBuffer.Slice(0, peekLength)));
}
private static SqlTokenInfo ReadQuotedString(StringBuilder sb, char delimiter, SqlCharReader reader)
{
Debug.Assert(!(sb is null));
Debug.Assert(!(reader is null));
Span<char> buffer = stackalloc char[sb.Capacity];
while (true)
{
reader.FillLength(buffer, 4, out var count);
if (count <= 0) break;
var eof = count <= 3;
var cnt = eof ? count : count - 3;
// Try find a delimiter
var idx = -1;
for (var i = 0; i < cnt; i++)
{
if (!Contains(buffer.Slice(i, count - i), delimiter))
continue;
idx = i;
break;
}
// If we found a delimiter
if (idx >= 0)
{
// If it is an escaped delimiter
if (idx >= 1 && Contains(buffer.Slice(idx - 1, count - idx + 1), delimiter, delimiter))
{
// Keep going
sb.Append(buffer.Slice(0, idx + 2));
reader.Undo(buffer.Slice(idx + 2, count - idx - 2));
continue;
}
// Else undo any extraneous data and exit the loop
sb.Append(buffer.Slice(0, idx + 1));
reader.Undo(buffer.Slice(idx + 1, count - idx - 1));
break;
}
sb.Append(buffer.Slice(0, cnt));
// Exit if no more data
if (eof) break;
// Ensure we can peek again
reader.Undo(buffer.Slice(cnt, 3));
}
var token = new SqlTokenInfo(SqlTokenKind.QuotedString, sb);
return token;
}
/// <summary>
///
/// </summary>
/// <param name="peekBuffer"></param>
/// <param name="reader"></param>
/// <param name="skipSundry">Do not emit sundry tokens (such as comments and whitespace) in the output.</param>
private static SqlTokenInfo ReadBlockComment(SqlCharReader reader, bool skipSundry)
{
Debug.Assert(!(reader is null));
// Perf: Assume comment is N chars
const int bufferLen = 50;
Span<char> buffer = stackalloc char[bufferLen];
StringBuilder sb = skipSundry ? null : new StringBuilder(2 + bufferLen);
// We already know the peeked token is /*, so keep it
if (!skipSundry)
sb.Append("/*");
while (true)
{
reader.FillLength(buffer, bufferLen, out var count);
if (count <= 0) break;
// Try find a delimiter
var idx = -1;
for (var i = 0; i < count; i++)
{
if (!Contains(buffer.Slice(i, count - i), '*', '/'))
continue;
idx = i;
break;
}
// If we found a delimiter
if (idx >= 0)
{
// Undo any extraneous data and exit the loop
if (!skipSundry)
sb.Append(buffer.Slice(0, idx + 2));
reader.Undo(buffer.Slice(idx + 2, count - idx - 2));
break;
}
if (!skipSundry)
sb.Append(buffer.Slice(0, count));
// Exit if eof
if (count < bufferLen) break;
}
var token = new SqlTokenInfo(SqlTokenKind.BlockComment, sb);
return token;
}
/// <summary>
///
/// </summary>
/// <param name="peekBuffer"></param>
/// <param name="reader"></param>
/// <param name="skipSundry">Do not emit sundry tokens (such as comments and whitespace) in the output.</param>
private static SqlTokenInfo ReadLineComment(SqlCharReader reader, bool skipSundry)
{
Debug.Assert(!(reader is null));
// Perf: Assume comment is N chars
const int bufferLen = 30;
Span<char> buffer = stackalloc char[bufferLen];
StringBuilder sb = skipSundry ? null : new StringBuilder(2 + bufferLen);
// We already know the peeked token is --, so keep it
if (!skipSundry)
sb.Append("--");
while (true)
{
reader.FillLength(buffer, bufferLen, out var count);
if (count <= 0) break;
// Try find a delimiter
var idx = -1;
for (var i = 0; i < count; i++)
{
// Final character in both Windows (\r\n) and Linux (\n) line-endings is \n.
if (!Contains(buffer.Slice(i, count - i), '\n'))
continue;
idx = i;
break;
}
// If we found a delimiter
if (idx >= 0)
{
// Undo any extraneous data and exit the loop
if (!skipSundry)
sb.Append(buffer.Slice(0, idx + 1));
reader.Undo(buffer.Slice(idx + 1, count - idx - 1));
break;
}
if (!skipSundry)
sb.Append(buffer.Slice(0, count));
// Exit if eof
if (count < bufferLen) break;
}
var token = new SqlTokenInfo(SqlTokenKind.LineComment, sb);
return token;
}
private static SqlTokenInfo ReadSymbol(ReadOnlySpan<char> peekBuffer, int peekLength, SqlCharReader reader)
{
Debug.Assert(peekBuffer.Length >= 1);
Debug.Assert(peekLength >= 1);
Debug.Assert(!(reader is null));
if (peekLength >= 2)
{
// First check if it's a double-symbol
var peek = new string(peekBuffer.Slice(0, 2));
switch (peek)
{
// Math
case "+=":
case "-=":
case "*=":
case "/=":
case "%=":
// Logical
case "&=":
case "|=":
case "^=":
// Comparison
case ">=":
case "<=":
case "<>":
case "!<":
case "!=":
case "!>":
// Programmatic
case "::":
var doubleToken = new SqlTokenInfo(SqlTokenKind.Symbol, peekBuffer.Slice(0, peekLength));
return doubleToken;
}
}
// It must have been a single symbol
reader.Undo(peekBuffer.Slice(1, peekLength - 1));
var token = new SqlTokenInfo(SqlTokenKind.Symbol, peekBuffer[0]);
return token;
}
private static SqlTokenInfo ReadLiteral(ReadOnlySpan<char> peekBuffer, int peekLength, SqlCharReader reader)
{
Debug.Assert(peekBuffer.Length >= 1);
Debug.Assert(peekLength >= 1);
Debug.Assert(!(reader is null));
// Sql literals are generally short
var cap = peekLength + 32;
Span<char> buffer = stackalloc char[cap];
var sb = new StringBuilder(cap);
// We already know the incoming data is "<literal>", so keep it
sb.Append(peekBuffer[0]);
// Undo any extraneous data
if (peekLength >= 2)
{
reader.Undo(peekBuffer.Slice(1, peekLength - 1));
}
while (true)
{
reader.FillRemaining(buffer, out var count);
if (count <= 0) break;
for (var i = 0; i < count; i++)
{
switch (buffer[i])
{
// Math
case '+':
case '-':
case '*':
case '/':
case '%':
// Logical
case '&':
case '|':
case '^':
case '~':
// Comparison
case '>':
case '<':
case '!':
case '=':
// Quote
case '\'':
case '"':
// Symbol
case ',':
case '.':
case ';':
case ':':
case '(':
case ')':
// Exit if delimiter
break;
default:
// Exit if whitespace
if (char.IsWhiteSpace(buffer[i])) break;
// Loop if not whitespace
continue;
}
if (i >= 1)
sb.Append(buffer.Slice(0, i));
reader.Undo(buffer.Slice(i, count - i));
var t1 = new SqlTokenInfo(SqlTokenKind.Literal, sb);
return t1;
}
sb.Append(buffer.Slice(0, count));
}
var token = new SqlTokenInfo(SqlTokenKind.Literal, sb);
return token;
}
}
}
| |
// ------------------------------------------------------------------------
// ========================================================================
// THIS CODE AND INFORMATION ARE GENERATED BY AUTOMATIC CODE GENERATOR
// ========================================================================
// Template: ViewModel.tt
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
using Controls=WPAppStudio.Controls;
using Entities=WPAppStudio.Entities;
using EntitiesBase=WPAppStudio.Entities.Base;
using IServices=WPAppStudio.Services.Interfaces;
using IViewModels=WPAppStudio.ViewModel.Interfaces;
using Localization=WPAppStudio.Localization;
using Repositories=WPAppStudio.Repositories;
using Services=WPAppStudio.Services;
using ViewModelsBase=WPAppStudio.ViewModel.Base;
using WPAppStudio;
using WPAppStudio.Shared;
namespace WPAppStudio.ViewModel
{
/// <summary>
/// Implementation of Main_Detail ViewModel.
/// </summary>
[CompilerGenerated]
[GeneratedCode("Radarc", "4.0")]
public partial class Main_DetailViewModel : ViewModelsBase.VMBase, IViewModels.IMain_DetailViewModel, ViewModelsBase.INavigable
{
private readonly Repositories.Main_mainrssfeed _main_mainrssfeed;
private readonly IServices.IDialogService _dialogService;
private readonly IServices.INavigationService _navigationService;
private readonly IServices.ISpeechService _speechService;
private readonly IServices.IShareService _shareService;
private readonly IServices.ILiveTileService _liveTileService;
/// <summary>
/// Initializes a new instance of the <see cref="Main_DetailViewModel" /> class.
/// </summary>
/// <param name="main_mainrssfeed">The Main_mainrssfeed.</param>
/// <param name="dialogService">The Dialog Service.</param>
/// <param name="navigationService">The Navigation Service.</param>
/// <param name="speechService">The Speech Service.</param>
/// <param name="shareService">The Share Service.</param>
/// <param name="liveTileService">The Live Tile Service.</param>
public Main_DetailViewModel(Repositories.Main_mainrssfeed main_mainrssfeed, IServices.IDialogService dialogService, IServices.INavigationService navigationService, IServices.ISpeechService speechService, IServices.IShareService shareService, IServices.ILiveTileService liveTileService)
{
_main_mainrssfeed = main_mainrssfeed;
_dialogService = dialogService;
_navigationService = navigationService;
_speechService = speechService;
_shareService = shareService;
_liveTileService = liveTileService;
}
private EntitiesBase.RssSearchResult _currentRssSearchResult;
/// <summary>
/// CurrentRssSearchResult property.
/// </summary>
public EntitiesBase.RssSearchResult CurrentRssSearchResult
{
get
{
return _currentRssSearchResult;
}
set
{
SetProperty(ref _currentRssSearchResult, value);
}
}
private bool _hasNextpanoramaMain_Detail0;
/// <summary>
/// HasNextpanoramaMain_Detail0 property.
/// </summary>
public bool HasNextpanoramaMain_Detail0
{
get
{
return _hasNextpanoramaMain_Detail0;
}
set
{
SetProperty(ref _hasNextpanoramaMain_Detail0, value);
}
}
private bool _hasPreviouspanoramaMain_Detail0;
/// <summary>
/// HasPreviouspanoramaMain_Detail0 property.
/// </summary>
public bool HasPreviouspanoramaMain_Detail0
{
get
{
return _hasPreviouspanoramaMain_Detail0;
}
set
{
SetProperty(ref _hasPreviouspanoramaMain_Detail0, value);
}
}
/// <summary>
/// Delegate method for the TextToSpeechMain_DetailStaticControlCommand command.
/// </summary>
public void TextToSpeechMain_DetailStaticControlCommandDelegate()
{
_speechService.TextToSpeech(CurrentRssSearchResult.Title + " " + CurrentRssSearchResult.Content);
}
private ICommand _textToSpeechMain_DetailStaticControlCommand;
/// <summary>
/// Gets the TextToSpeechMain_DetailStaticControlCommand command.
/// </summary>
public ICommand TextToSpeechMain_DetailStaticControlCommand
{
get { return _textToSpeechMain_DetailStaticControlCommand = _textToSpeechMain_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(TextToSpeechMain_DetailStaticControlCommandDelegate); }
}
/// <summary>
/// Delegate method for the ShareMain_DetailStaticControlCommand command.
/// </summary>
public void ShareMain_DetailStaticControlCommandDelegate()
{
_shareService.Share(CurrentRssSearchResult.Title, CurrentRssSearchResult.Content, CurrentRssSearchResult.FeedUrl, CurrentRssSearchResult.ImageUrl);
}
private ICommand _shareMain_DetailStaticControlCommand;
/// <summary>
/// Gets the ShareMain_DetailStaticControlCommand command.
/// </summary>
public ICommand ShareMain_DetailStaticControlCommand
{
get { return _shareMain_DetailStaticControlCommand = _shareMain_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(ShareMain_DetailStaticControlCommandDelegate); }
}
/// <summary>
/// Delegate method for the PinToStartMain_DetailStaticControlCommand command.
/// </summary>
public void PinToStartMain_DetailStaticControlCommandDelegate()
{
_liveTileService.PinToStart(typeof(IViewModels.IMain_DetailViewModel), CreateTileInfoMain_DetailStaticControl());
}
private ICommand _pinToStartMain_DetailStaticControlCommand;
/// <summary>
/// Gets the PinToStartMain_DetailStaticControlCommand command.
/// </summary>
public ICommand PinToStartMain_DetailStaticControlCommand
{
get { return _pinToStartMain_DetailStaticControlCommand = _pinToStartMain_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(PinToStartMain_DetailStaticControlCommandDelegate); }
}
/// <summary>
/// Delegate method for the GoToSourceMain_DetailStaticControlCommand command.
/// </summary>
public void GoToSourceMain_DetailStaticControlCommandDelegate()
{
_navigationService.NavigateTo(string.IsNullOrEmpty(CurrentRssSearchResult.FeedUrl) ? null : new Uri(CurrentRssSearchResult.FeedUrl));
}
private ICommand _goToSourceMain_DetailStaticControlCommand;
/// <summary>
/// Gets the GoToSourceMain_DetailStaticControlCommand command.
/// </summary>
public ICommand GoToSourceMain_DetailStaticControlCommand
{
get { return _goToSourceMain_DetailStaticControlCommand = _goToSourceMain_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(GoToSourceMain_DetailStaticControlCommandDelegate); }
}
/// <summary>
/// Delegate method for the NextpanoramaMain_Detail0 command.
/// </summary>
public async void NextpanoramaMain_Detail0Delegate()
{
LoadingCurrentRssSearchResult = true;
var next = await _main_mainrssfeed.Next(CurrentRssSearchResult);
if(next != null)
CurrentRssSearchResult = next;
RefreshHasPrevNext();
}
private bool _loadingCurrentRssSearchResult;
public bool LoadingCurrentRssSearchResult
{
get { return _loadingCurrentRssSearchResult; }
set { SetProperty(ref _loadingCurrentRssSearchResult, value); }
}
private ICommand _nextpanoramaMain_Detail0;
/// <summary>
/// Gets the NextpanoramaMain_Detail0 command.
/// </summary>
public ICommand NextpanoramaMain_Detail0
{
get { return _nextpanoramaMain_Detail0 = _nextpanoramaMain_Detail0 ?? new ViewModelsBase.DelegateCommand(NextpanoramaMain_Detail0Delegate); }
}
/// <summary>
/// Delegate method for the PreviouspanoramaMain_Detail0 command.
/// </summary>
public async void PreviouspanoramaMain_Detail0Delegate()
{
LoadingCurrentRssSearchResult = true;
var prev = await _main_mainrssfeed.Previous(CurrentRssSearchResult);
if(prev != null)
CurrentRssSearchResult = prev;
RefreshHasPrevNext();
}
private ICommand _previouspanoramaMain_Detail0;
/// <summary>
/// Gets the PreviouspanoramaMain_Detail0 command.
/// </summary>
public ICommand PreviouspanoramaMain_Detail0
{
get { return _previouspanoramaMain_Detail0 = _previouspanoramaMain_Detail0 ?? new ViewModelsBase.DelegateCommand(PreviouspanoramaMain_Detail0Delegate); }
}
private async void RefreshHasPrevNext()
{
HasPreviouspanoramaMain_Detail0 = await _main_mainrssfeed.HasPrevious(CurrentRssSearchResult);
HasNextpanoramaMain_Detail0 = await _main_mainrssfeed.HasNext(CurrentRssSearchResult);
LoadingCurrentRssSearchResult = false;
}
public object NavigationContext
{
set
{
if (!(value is EntitiesBase.RssSearchResult)) { return; }
CurrentRssSearchResult = value as EntitiesBase.RssSearchResult;
RefreshHasPrevNext();
}
}
/// <summary>
/// Initializes a <see cref="Services.TileInfo" /> object for the Main_DetailStaticControl control.
/// </summary>
/// <returns>A <see cref="Services.TileInfo" /> object.</returns>
public Services.TileInfo CreateTileInfoMain_DetailStaticControl()
{
var tileInfo = new Services.TileInfo
{
CurrentId = CurrentRssSearchResult.Title,
Title = CurrentRssSearchResult.Title,
BackTitle = CurrentRssSearchResult.Title,
BackContent = CurrentRssSearchResult.Content,
Count = 0,
BackgroundImagePath = CurrentRssSearchResult.ImageUrl,
BackBackgroundImagePath = CurrentRssSearchResult.ImageUrl,
LogoPath = "Logo-242457de-80da-42c9-9fbb-98b5451c622c.png"
};
return tileInfo;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Xml;
using VersionOne.Profile;
using VersionOne.SDK.APIClient;
using VersionOne.ServiceHost.Core.Services;
using VersionOne.ServiceHost.Core.Utility;
using VersionOne.ServiceHost.Eventing;
using Attribute = VersionOne.SDK.APIClient.Attribute;
namespace VersionOne.ServiceHost.SubversionServices
{
public class LinkInfo
{
public readonly string Name;
public readonly bool OnMenu;
public readonly string Url;
public LinkInfo(string name, string url, bool onmenu)
{
Name = name;
Url = url;
OnMenu = onmenu;
}
}
public class ChangeSetWriterService : V1WriterServiceBase
{
private const string ChangeCommentField = "ChangeComment";
private const string ReferenceAttributeField = "ReferenceAttribute";
private const string AlwaysCreateField = "AlwaysCreate";
private bool alwaysCreate;
private string changecomment;
private string referencename;
public override void Initialize(XmlElement config, IEventManager eventManager, IProfile profile)
{
base.Initialize(config, eventManager, profile);
changecomment = config[ChangeCommentField].InnerText;
referencename = config[ReferenceAttributeField].InnerText;
bool alwaysCreateValue = false;
if(config[AlwaysCreateField] != null)
{
bool.TryParse(config[AlwaysCreateField].InnerText, out alwaysCreateValue);
}
alwaysCreate = alwaysCreateValue;
VerifyMeta();
eventManager.Subscribe(typeof(ChangeSetInfo), ChangeSetListener);
}
protected override void VerifyRuntimeMeta()
{
base.VerifyRuntimeMeta();
var refdef = PrimaryWorkitemReferenceDef;
}
private void ChangeSetListener(object pubobj)
{
var info = (ChangeSetInfo)pubobj;
try
{
ProcessChangeSetInfo(info);
}
catch(Exception ex)
{
Logger.Log(string.Format("Process Change Set {0} Info Failed: {1}", info.Revision, ex));
}
}
private void ProcessChangeSetInfo(ChangeSetInfo info)
{
IList<Oid> affectedworkitems = GetAffectedWorkitems(info.References);
Asset changeSet = GetChangeSet(info, affectedworkitems);
if(changeSet == null)
{
return;
}
Asset savedAsset = SaveChangeSetAsset(changeSet, info, affectedworkitems);
if(info.Link != null)
{
SaveChangeSetLink(info, savedAsset);
}
}
private Asset GetChangeSet(ChangeSetInfo info, IList<Oid> affectedworkitems)
{
Asset changeSet = null;
AssetList list = FindExistingChangeset(info.Revision).Assets;
if(list.Count > 0)
{
changeSet = list[0];
Logger.Log(string.Format("Using existing Change Set: {0} ({1})", info.Revision, changeSet.Oid));
}
else
{
if(ShouldCreate(affectedworkitems))
{
changeSet = Services.New(ChangeSetType, Oid.Null);
changeSet.SetAttributeValue(ChangeSetReferenceDef, info.Revision);
}
else
{
Logger.Log("No Change Set References. Ignoring Change Set: " + info.Revision);
}
}
return changeSet;
}
private bool ShouldCreate(IList<Oid> affectedworkitems)
{
return (alwaysCreate || (affectedworkitems.Count > 0));
}
private QueryResult FindExistingChangeset(int revision)
{
var q = new Query(ChangeSetType);
q.Selection.Add(ChangeSetType.GetAttributeDefinition("Reference"));
q.Selection.Add(ChangeSetType.GetAttributeDefinition("Links.URL"));
var referenceTerm = new FilterTerm(ChangeSetType.GetAttributeDefinition("Reference"));
referenceTerm.Equal(revision);
IFilterTerm term = referenceTerm;
q.Filter = term;
q.Paging = new Paging(0, 1);
return Services.Retrieve(q);
}
private IList<Oid> FindWorkitemOid(string reference)
{
var oids = new List<Oid>();
var q = new Query(PrimaryWorkitemType);
var term = new FilterTerm(PrimaryWorkitemReferenceDef);
term.Equal(reference);
q.Filter = term;
var list = Services.Retrieve(q).Assets;
foreach(var asset in list)
{
if(!oids.Contains(asset.Oid))
{
oids.Add(asset.Oid);
}
}
return oids;
}
private IList<Oid> GetAffectedWorkitems(IEnumerable<string> references)
{
var primaryworkitems = new List<Oid>();
foreach(var reference in references)
{
var workitemoids = FindWorkitemOid(reference);
if(workitemoids == null || workitemoids.Count == 0)
{
Logger.Log(string.Format("No {0} or {1} related to reference: {2}", StoryName, DefectName, reference));
continue;
}
primaryworkitems.AddRange(workitemoids);
}
return primaryworkitems;
}
private static string GetFormattedTime(DateTime dateTime)
{
var localTime = TimeZone.CurrentTimeZone.ToLocalTime(dateTime);
var offset = TimeZone.CurrentTimeZone.GetUtcOffset(localTime);
var result = string.Format("{0} UTC{1}{2}:{3:00}", localTime, offset.TotalMinutes >= 0 ? "+" : string.Empty, offset.Hours, offset.Minutes);
return result;
}
private Asset SaveChangeSetAsset(Asset changeSet, ChangeSetInfo info, IEnumerable<Oid> primaryworkitems)
{
changeSet.SetAttributeValue(ChangeSetNameDef, string.Format("'{0}' on '{1}'", info.Author, GetFormattedTime(info.ChangeDate)));
changeSet.SetAttributeValue(ChangeSetDescriptionDef, info.Message);
foreach(Oid oid in primaryworkitems)
{
changeSet.AddAttributeValue(ChangeSetPrimaryWorkitemsDef, oid);
}
Services.Save(changeSet, changecomment);
return changeSet;
}
private void SaveChangeSetLink(ChangeSetInfo info, Asset savedAsset)
{
var name = string.Format(info.Link.Name, info.Revision);
var url = string.Format(info.Link.Url, info.Revision);
var linkUrlAttribute = savedAsset.GetAttribute(ChangeSetType.GetAttributeDefinition("Links.URL"));
if(linkUrlAttribute != null)
{
foreach(string value in linkUrlAttribute.Values)
{
if(value.Equals(url, StringComparison.InvariantCultureIgnoreCase))
{
return;
}
}
}
var newlink = Services.New(LinkType, savedAsset.Oid.Momentless);
newlink.SetAttributeValue(LinkNameDef, name);
newlink.SetAttributeValue(LinkUrlDef, url);
newlink.SetAttributeValue(LinkOnMenuDef, info.Link.OnMenu);
Services.Save(newlink, changecomment);
}
#region Meta Properties
private static readonly NeededAssetType[] neededassettypes =
{
new NeededAssetType("ChangeSet", new[] {"PrimaryWorkitems", "Name", "Reference", "Description"}),
new NeededAssetType("PrimaryWorkitem", new string[] {}),
new NeededAssetType("Link", new[] {"Name", "URL", "OnMenu"}),
};
private IAssetType ChangeSetType { get { return Services.Meta.GetAssetType("ChangeSet"); } }
private IAttributeDefinition ChangeSetPrimaryWorkitemsDef { get { return Services.Meta.GetAttributeDefinition("ChangeSet.PrimaryWorkitems"); } }
private IAttributeDefinition ChangeSetNameDef { get { return Services.Meta.GetAttributeDefinition("ChangeSet.Name"); } }
private IAttributeDefinition ChangeSetReferenceDef { get { return Services.Meta.GetAttributeDefinition("ChangeSet.Reference"); } }
private IAttributeDefinition ChangeSetDescriptionDef { get { return Services.Meta.GetAttributeDefinition("ChangeSet.Description"); } }
private IAssetType PrimaryWorkitemType { get { return Services.Meta.GetAssetType("PrimaryWorkitem"); } }
private IAttributeDefinition PrimaryWorkitemReferenceDef { get { return Services.Meta.GetAttributeDefinition("PrimaryWorkitem.ChildrenMeAndDown." + referencename); } }
private IAttributeDefinition LinkNameDef { get { return Services.Meta.GetAttributeDefinition("Link.Name"); } }
private IAttributeDefinition LinkUrlDef { get { return Services.Meta.GetAttributeDefinition("Link.URL"); } }
private IAttributeDefinition LinkOnMenuDef { get { return Services.Meta.GetAttributeDefinition("Link.OnMenu"); } }
private new string StoryName { get { return Services.Localization("Plural'Story"); } }
private new string DefectName { get { return Services.Localization("Plural'Defect"); } }
protected override IEnumerable<NeededAssetType> NeededAssetTypes { get { return neededassettypes; } }
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Neleus.LambdaCompare
{
internal static class Comparer
{
public static bool ExpressionsEqual(Expression x, Expression y, LambdaExpression rootX, LambdaExpression rootY)
{
if (ReferenceEquals(x, y)) return true;
if (x == null || y == null) return false;
var valueX = TryCalculateConstant(x);
var valueY = TryCalculateConstant(y);
if (valueX.IsDefined && valueY.IsDefined)
return ValuesEqual(valueX.Value, valueY.Value);
if (x.NodeType != y.NodeType
|| x.Type != y.Type)
{
if (IsAnonymousType(x.Type) && IsAnonymousType(y.Type))
throw new NotImplementedException("Comparison of Anonymous Types is not supported");
return false;
}
if (x is LambdaExpression)
{
var lx = (LambdaExpression)x;
var ly = (LambdaExpression)y;
var paramsX = lx.Parameters;
var paramsY = ly.Parameters;
return CollectionsEqual(paramsX, paramsY, lx, ly) && ExpressionsEqual(lx.Body, ly.Body, lx, ly);
}
if (x is MemberExpression)
{
var mex = (MemberExpression)x;
var mey = (MemberExpression)y;
return Equals(mex.Member, mey.Member) && ExpressionsEqual(mex.Expression, mey.Expression, rootX, rootY);
}
if (x is BinaryExpression)
{
var bx = (BinaryExpression)x;
var by = (BinaryExpression)y;
return bx.Method == by.Method && ExpressionsEqual(bx.Left, by.Left, rootX, rootY) && ExpressionsEqual(bx.Right, by.Right, rootX, rootY);
}
if (x is UnaryExpression)
{
var ux = (UnaryExpression)x;
var uy = (UnaryExpression)y;
return ux.Method == uy.Method && ExpressionsEqual(ux.Operand, uy.Operand, rootX, rootY);
}
if (x is ParameterExpression)
{
var px = (ParameterExpression)x;
var py = (ParameterExpression)y;
return rootX.Parameters.IndexOf(px) == rootY.Parameters.IndexOf(py);
}
if (x is MethodCallExpression)
{
var cx = (MethodCallExpression)x;
var cy = (MethodCallExpression)y;
return cx.Method == cy.Method
&& ExpressionsEqual(cx.Object, cy.Object, rootX, rootY)
&& CollectionsEqual(cx.Arguments, cy.Arguments, rootX, rootY);
}
if (x is MemberInitExpression)
{
var mix = (MemberInitExpression)x;
var miy = (MemberInitExpression)y;
return ExpressionsEqual(mix.NewExpression, miy.NewExpression, rootX, rootY)
&& MemberInitsEqual(mix.Bindings, miy.Bindings, rootX, rootY);
}
if (x is NewArrayExpression)
{
var nx = (NewArrayExpression)x;
var ny = (NewArrayExpression)y;
return CollectionsEqual(nx.Expressions, ny.Expressions, rootX, rootY);
}
if (x is NewExpression)
{
var nx = (NewExpression)x;
var ny = (NewExpression)y;
return Equals(nx.Constructor, ny.Constructor)
&& CollectionsEqual(nx.Arguments, ny.Arguments, rootX, rootY)
&& (nx.Members == null && ny.Members == null
|| nx.Members != null && ny.Members != null && CollectionsEqual(nx.Members, ny.Members));
}
if (x is ConditionalExpression)
{
var cx = (ConditionalExpression)x;
var cy = (ConditionalExpression)y;
return ExpressionsEqual(cx.Test, cy.Test, rootX, rootY)
&& ExpressionsEqual(cx.IfFalse, cy.IfFalse, rootX, rootY)
&& ExpressionsEqual(cx.IfTrue, cy.IfTrue, rootX, rootY);
}
throw new NotImplementedException(x.ToString());
}
private static bool IsAnonymousType(Type type)
{
var hasCompilerGeneratedAttribute = type.GetTypeInfo().GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any();
var nameContainsAnonymousType = type.FullName.Contains("AnonymousType");
var isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;
return isAnonymousType;
}
private static bool MemberInitsEqual(ICollection<MemberBinding> bx, ICollection<MemberBinding> by, LambdaExpression rootX, LambdaExpression rootY)
{
if (bx.Count != by.Count)
{
return false;
}
if (bx.Concat(by).Any(b => b.BindingType != MemberBindingType.Assignment))
throw new NotImplementedException("Only MemberBindingType.Assignment is supported");
return
bx.Cast<MemberAssignment>().OrderBy(b => b.Member.Name).Select((b, i) => new { Expr = b.Expression, b.Member, Index = i })
.Join(
by.Cast<MemberAssignment>().OrderBy(b => b.Member.Name).Select((b, i) => new { Expr = b.Expression, b.Member, Index = i }),
o => o.Index, o => o.Index, (xe, ye) => new { XExpr = xe.Expr, XMember = xe.Member, YExpr = ye.Expr, YMember = ye.Member })
.All(o => Equals(o.XMember, o.YMember) && ExpressionsEqual(o.XExpr, o.YExpr, rootX, rootY));
}
private static bool ValuesEqual(object x, object y)
{
if (ReferenceEquals(x, y))
return true;
if (x is ICollection && y is ICollection)
return CollectionsEqual((ICollection)x, (ICollection)y);
return Equals(x, y);
}
private static ConstantValue TryCalculateConstant(Expression e)
{
if (e is ConstantExpression)
return new ConstantValue(true, ((ConstantExpression)e).Value);
if (e is MemberExpression)
{
var me = (MemberExpression)e;
var parentValue = TryCalculateConstant(me.Expression);
if (parentValue.IsDefined)
{
var result =
me.Member is FieldInfo
? ((FieldInfo)me.Member).GetValue(parentValue.Value)
: ((PropertyInfo)me.Member).GetValue(parentValue.Value);
return new ConstantValue(true, result);
}
}
if (e is NewArrayExpression)
{
var ae = ((NewArrayExpression)e);
var result = ae.Expressions.Select(TryCalculateConstant);
if (result.All(i => i.IsDefined))
return new ConstantValue(true, result.Select(i => i.Value).ToArray<object>());
}
if (e is ConditionalExpression)
{
var ce = (ConditionalExpression)e;
var evaluatedTest = TryCalculateConstant(ce.Test);
if (evaluatedTest.IsDefined)
{
return TryCalculateConstant(Equals(evaluatedTest.Value, true) ? ce.IfTrue : ce.IfFalse);
}
}
return default(ConstantValue);
}
private static bool CollectionsEqual(IEnumerable<Expression> x, IEnumerable<Expression> y, LambdaExpression rootX, LambdaExpression rootY)
{
return x.Count() == y.Count()
&& x.Select((e, i) => new { Expr = e, Index = i })
.Join(y.Select((e, i) => new { Expr = e, Index = i }),
o => o.Index, o => o.Index, (xe, ye) => new { X = xe.Expr, Y = ye.Expr })
.All(o => ExpressionsEqual(o.X, o.Y, rootX, rootY));
}
private static bool CollectionsEqual(ICollection x, ICollection y)
{
return x.Count == y.Count
&& x.Cast<object>().Select((e, i) => new { Expr = e, Index = i })
.Join(y.Cast<object>().Select((e, i) => new { Expr = e, Index = i }),
o => o.Index, o => o.Index, (xe, ye) => new { X = xe.Expr, Y = ye.Expr })
.All(o => Equals(o.X, o.Y));
}
private struct ConstantValue
{
public ConstantValue(bool isDefined, object value)
: this()
{
IsDefined = isDefined;
Value = value;
}
public bool IsDefined { get; }
public object Value { get; }
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.DataFactories.Common.Models;
using Microsoft.Azure.Management.DataFactories.Core;
using Microsoft.Azure.Management.DataFactories.Core.Models;
namespace Microsoft.Azure.Management.DataFactories.Core
{
public static partial class DatasetOperationsExtensions
{
/// <summary>
/// Create a new dataset instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a dataset.
/// </param>
/// <returns>
/// The CreateOrUpdate dataset operation response.
/// </returns>
public static DatasetCreateOrUpdateResponse BeginCreateOrUpdate(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, DatasetCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatasetOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a new dataset instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a dataset.
/// </param>
/// <returns>
/// The CreateOrUpdate dataset operation response.
/// </returns>
public static Task<DatasetCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, DatasetCreateOrUpdateParameters parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None);
}
/// <summary>
/// Create a new dataset instance or update an existing instance with
/// raw json content.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='datasetName'>
/// Required. A unique dataset instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a dataset.
/// </param>
/// <returns>
/// The CreateOrUpdate dataset operation response.
/// </returns>
public static DatasetCreateOrUpdateResponse BeginCreateOrUpdateWithRawJsonContent(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, string datasetName, DatasetCreateOrUpdateWithRawJsonContentParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatasetOperations)s).BeginCreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, datasetName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a new dataset instance or update an existing instance with
/// raw json content.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='datasetName'>
/// Required. A unique dataset instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a dataset.
/// </param>
/// <returns>
/// The CreateOrUpdate dataset operation response.
/// </returns>
public static Task<DatasetCreateOrUpdateResponse> BeginCreateOrUpdateWithRawJsonContentAsync(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, string datasetName, DatasetCreateOrUpdateWithRawJsonContentParameters parameters)
{
return operations.BeginCreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, datasetName, parameters, CancellationToken.None);
}
/// <summary>
/// Delete a dataset instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='datasetName'>
/// Required. Name of the dataset.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse BeginDelete(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, string datasetName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatasetOperations)s).BeginDeleteAsync(resourceGroupName, dataFactoryName, datasetName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a dataset instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='datasetName'>
/// Required. Name of the dataset.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> BeginDeleteAsync(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, string datasetName)
{
return operations.BeginDeleteAsync(resourceGroupName, dataFactoryName, datasetName, CancellationToken.None);
}
/// <summary>
/// Create a new dataset instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a dataset.
/// </param>
/// <returns>
/// The CreateOrUpdate dataset operation response.
/// </returns>
public static DatasetCreateOrUpdateResponse CreateOrUpdate(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, DatasetCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatasetOperations)s).CreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a new dataset instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a dataset.
/// </param>
/// <returns>
/// The CreateOrUpdate dataset operation response.
/// </returns>
public static Task<DatasetCreateOrUpdateResponse> CreateOrUpdateAsync(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, DatasetCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None);
}
/// <summary>
/// Create a new dataset instance or update an existing instance with
/// raw json content.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='datasetName'>
/// Required. A unique dataset instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a dataset.
/// </param>
/// <returns>
/// The CreateOrUpdate dataset operation response.
/// </returns>
public static DatasetCreateOrUpdateResponse CreateOrUpdateWithRawJsonContent(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, string datasetName, DatasetCreateOrUpdateWithRawJsonContentParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatasetOperations)s).CreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, datasetName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a new dataset instance or update an existing instance with
/// raw json content.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='datasetName'>
/// Required. A unique dataset instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a dataset.
/// </param>
/// <returns>
/// The CreateOrUpdate dataset operation response.
/// </returns>
public static Task<DatasetCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, string datasetName, DatasetCreateOrUpdateWithRawJsonContentParameters parameters)
{
return operations.CreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, datasetName, parameters, CancellationToken.None);
}
/// <summary>
/// Delete a dataset instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='datasetName'>
/// Required. Name of the dataset.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse Delete(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, string datasetName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatasetOperations)s).DeleteAsync(resourceGroupName, dataFactoryName, datasetName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a dataset instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='datasetName'>
/// Required. Name of the dataset.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> DeleteAsync(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, string datasetName)
{
return operations.DeleteAsync(resourceGroupName, dataFactoryName, datasetName, CancellationToken.None);
}
/// <summary>
/// Gets a dataset instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='datasetName'>
/// Required. Name of the dataset.
/// </param>
/// <returns>
/// The Get dataset operation response.
/// </returns>
public static DatasetGetResponse Get(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, string datasetName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatasetOperations)s).GetAsync(resourceGroupName, dataFactoryName, datasetName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a dataset instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='datasetName'>
/// Required. Name of the dataset.
/// </param>
/// <returns>
/// The Get dataset operation response.
/// </returns>
public static Task<DatasetGetResponse> GetAsync(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName, string datasetName)
{
return operations.GetAsync(resourceGroupName, dataFactoryName, datasetName, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// The CreateOrUpdate dataset operation response.
/// </returns>
public static DatasetCreateOrUpdateResponse GetCreateOrUpdateStatus(this IDatasetOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatasetOperations)s).GetCreateOrUpdateStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// The CreateOrUpdate dataset operation response.
/// </returns>
public static Task<DatasetCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(this IDatasetOperations operations, string operationStatusLink)
{
return operations.GetCreateOrUpdateStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Gets all the dataset instances in a data factory with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <returns>
/// The List datasets operation response.
/// </returns>
public static DatasetListResponse List(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatasetOperations)s).ListAsync(resourceGroupName, dataFactoryName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the dataset instances in a data factory with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <returns>
/// The List datasets operation response.
/// </returns>
public static Task<DatasetListResponse> ListAsync(this IDatasetOperations operations, string resourceGroupName, string dataFactoryName)
{
return operations.ListAsync(resourceGroupName, dataFactoryName, CancellationToken.None);
}
/// <summary>
/// Gets the next page of dataset instances with the link to the next
/// page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The url to the next datasets page.
/// </param>
/// <returns>
/// The List datasets operation response.
/// </returns>
public static DatasetListResponse ListNext(this IDatasetOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatasetOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the next page of dataset instances with the link to the next
/// page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IDatasetOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The url to the next datasets page.
/// </param>
/// <returns>
/// The List datasets operation response.
/// </returns>
public static Task<DatasetListResponse> ListNextAsync(this IDatasetOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
using System;
using Microsoft.Azure.Management.StorSimple8000Series;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Network;
using System.Collections.Generic;
using Microsoft.Azure.Management.StorSimple8000Series.Models;
using Microsoft.Azure.Management.Network.Models;
using Microsoft.Azure.Management.Compute.Models;
using System.Text;
using Xunit;
using System.Linq;
using Xunit.Abstractions;
using Microsoft.Rest.Azure;
using System.Threading;
namespace StorSimple8000Series.Tests
{
public class CloudApplianceTests : StorSimpleTestBase
{
private const string DefaultModelNumber = "8020";
protected ComputeManagementClient ComputeClient { get; set; }
protected NetworkManagementClient NetworkClient { get; set; }
public CloudApplianceTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
{
this.ComputeClient = this.Context.GetServiceClient<ComputeManagementClient>();
this.NetworkClient = this.Context.GetServiceClient<NetworkManagementClient>();
}
[Fact]
public void TestCreateStorSimpleCloudAppliance()
{
var deviceName = TestConstants.DeviceForSCATests;
try
{
// Prepare
// Get Activation Key, to be used as Device Registration Key for Cloud Appliance.
var activationKey = this.Client.Managers.GetActivationKey(this.ResourceGroupName, this.ManagerName);
// Get Cloud Appliance Configurations
var configuration = this.GetScaConfigurationForModel();
// Create Vnet if not exist already
this.CreateDefaultVnetIfNotExist();
// Act
// Trigger Cloud Appliance creation Job
var jobName = this.TriggerScaCreationAndReturnName(deviceName);
//Create NIC required for VM creation
var nicId = this.CreateNicAndReturnId(deviceName);
//Create VM
this.CreateVm(deviceName, activationKey.ActivationKey, nicId, configuration);
// Validate
// Track job to completion on the basis of device status
var device = this.TrackScaJobByDeviceStatus(deviceName);
// Validate device status to be Ready to Setup
Assert.NotNull(device);
Assert.Equal(device.Status, DeviceStatus.ReadyToSetup);
// Get job and validate if status is succeeded
var job = this.Client.Jobs.Get(deviceName, jobName, this.ResourceGroupName, this.ManagerName);
Assert.Equal(job.JobType, JobType.CreateCloudAppliance);
Assert.Equal(job.Status, JobStatus.Succeeded);
}
catch (Exception ex)
{
Assert.True(false, ex.Message);
}
finally
{
try
{
// Deactivate device
this.Client.Devices.Deactivate(deviceName, this.ResourceGroupName, this.ManagerName);
// Delete device
this.Client.Devices.Delete(deviceName, this.ResourceGroupName, this.ManagerName);
// Delete VM
this.ComputeClient.VirtualMachines.Delete(this.ResourceGroupName, deviceName);
// Delete NIC
this.NetworkClient.NetworkInterfaces.Delete(this.ResourceGroupName, deviceName);
}
catch (Exception ex)
{
Assert.True(false, ex.Message);
}
}
}
[Fact]
public void TestConfigureCloudAppliance()
{
//checking for prerequisites
var device = Helpers.CheckAndGetDevice(this, DeviceType.Series8000VirtualAppliance, DeviceStatus.ReadyToSetup);
var deviceName = device.Name;
//the service data encryption key from rollovered device
var serviceDataEncryptionKey = "ZJOCJNA3k0g5WSHqskiMug==";
try
{
// Device admin password and snapshot manager password
AsymmetricEncryptedSecret deviceAdminpassword = this.Client.Managers.GetAsymmetricEncryptedSecret(this.ResourceGroupName, this.ManagerName, "test-adminp13");
AsymmetricEncryptedSecret snapshotmanagerPassword = this.Client.Managers.GetAsymmetricEncryptedSecret(this.ResourceGroupName, this.ManagerName, "test-ssmpas1235");
//cloud appliance settings
CloudApplianceSettings cloudApplianceSettings = new CloudApplianceSettings();
cloudApplianceSettings.ServiceDataEncryptionKey = EncryptSecretUsingDEK(this.ResourceGroupName, this.ManagerName, deviceName, serviceDataEncryptionKey);
var managerExtendedInfo = this.Client.Managers.GetExtendedInfo(this.ResourceGroupName, this.ManagerName);
cloudApplianceSettings.ChannelIntegrityKey = EncryptSecretUsingDEK(this.ResourceGroupName, this.ManagerName, deviceName, managerExtendedInfo.IntegrityKey);
//security settings patch
SecuritySettingsPatch securitySettingsPatch = new SecuritySettingsPatch()
{
DeviceAdminPassword = deviceAdminpassword,
SnapshotPassword = snapshotmanagerPassword,
CloudApplianceSettings = cloudApplianceSettings
};
//update security settings - this will configure the SCA too.
this.Client.DeviceSettings.UpdateSecuritySettings(
deviceName.GetDoubleEncoded(),
securitySettingsPatch,
this.ResourceGroupName,
this.ManagerName);
var securitySettings = this.Client.DeviceSettings.GetSecuritySettings(
deviceName.GetDoubleEncoded(),
this.ResourceGroupName,
this.ManagerName);
//validation
Assert.True(securitySettings != null, "Creation of Security Setting was not successful.");
//validate that SCA got configured, by checking device is online now.
Helpers.CheckAndGetConfiguredDevice(this, deviceName);
}
catch (Exception e)
{
Assert.Null(e);
}
}
[Fact]
public void TestUpdateServiceDataEncryptionKeyOnCloudAppliance()
{
//checking for prerequisites
var device = Helpers.CheckAndGetDevice(this, DeviceType.Series8000VirtualAppliance);
var deviceName = device.Name;
//the new service data encryption key from rollovered device
var newServiceDataEncryptionKey = "ZJOCJNA3k0g5WSHqskiMug==";
try
{
//cloud appliance settings
CloudApplianceSettings cloudApplianceSettings = new CloudApplianceSettings();
cloudApplianceSettings.ServiceDataEncryptionKey = EncryptSecretUsingDEK(this.ResourceGroupName, this.ManagerName, deviceName, newServiceDataEncryptionKey);
var managerExtendedInfo = this.Client.Managers.GetExtendedInfo(this.ResourceGroupName, this.ManagerName);
cloudApplianceSettings.ChannelIntegrityKey = EncryptSecretUsingDEK(this.ResourceGroupName, this.ManagerName, deviceName, managerExtendedInfo.IntegrityKey);
//security settings patch
SecuritySettingsPatch securitySettingsPatch = new SecuritySettingsPatch()
{
CloudApplianceSettings = cloudApplianceSettings
};
//update security settings
this.Client.DeviceSettings.UpdateSecuritySettings(
deviceName.GetDoubleEncoded(),
securitySettingsPatch,
this.ResourceGroupName,
this.ManagerName);
var securitySettings = this.Client.DeviceSettings.GetSecuritySettings(
deviceName.GetDoubleEncoded(),
this.ResourceGroupName,
this.ManagerName);
//validation
Assert.True(securitySettings != null, "Creation of Security Setting was not successful.");
}
catch (Exception e)
{
Assert.Null(e);
}
}
#region Helper methods
public Device TrackScaJobByDeviceStatus(string deviceName)
{
Device device = null;
//wait till device status changes to 'ReadyToSetup' state
while(true)
{
device = this.Client.Devices.Get(deviceName, this.ResourceGroupName, this.ManagerName);
if (device != null && device.Status == DeviceStatus.ReadyToSetup)
{
break;
}
//wait and then retry
Thread.Sleep(DefaultWaitingTimeInMs);
}
return device;
}
protected string TriggerScaCreationAndReturnName(string name)
{
var cloudAppliance = new CloudAppliance()
{
Name = name,
ModelNumber = DefaultModelNumber,
VnetRegion = "West US" // hardcoding as no funcitonal significance
};
this.Client.CloudAppliances.BeginProvision(cloudAppliance, this.ResourceGroupName, this.ManagerName);
// Only one job will be there for this device
var deviceJobs = this.Client.Jobs.ListByDevice(name, this.ResourceGroupName, this.ManagerName);
return deviceJobs.ElementAt(0).Name;
}
protected CloudApplianceConfiguration GetScaConfigurationForModel(string modelNumber = DefaultModelNumber)
{
var configurations = this.Client.CloudAppliances.ListSupportedConfigurations(this.ResourceGroupName, this.ManagerName);
return configurations.FirstOrDefault(c => c.ModelNumber == modelNumber);
}
protected string CreateNicAndReturnId(string name, string vnetName = TestConstants.DefaultVirtualNetworkName, string subnetName = TestConstants.DefaultSubnetName)
{
var subnet = this.NetworkClient.Subnets.Get(this.ResourceGroupName, vnetName, subnetName);
var availableIpAddress = this.NetworkClient.VirtualNetworks.CheckIPAddressAvailability(this.ResourceGroupName,
vnetName, subnet.AddressPrefix.Split('/')[0]);
var nic = this.NetworkClient.NetworkInterfaces.CreateOrUpdate(this.ResourceGroupName, name, new NetworkInterface()
{
Location = "West US",
IpConfigurations = new List<NetworkInterfaceIPConfiguration>()
{
new NetworkInterfaceIPConfiguration()
{
Name = "ipconfig1",
PrivateIPAllocationMethod = "Static",
PrivateIPAddress = availableIpAddress.AvailableIPAddresses[0],
Subnet = subnet
}
}
});
return nic.Id;
}
protected void CreateVm(string deviceName, string activationKey, string networkInterfaceId, CloudApplianceConfiguration configuration)
{
this.ComputeClient.VirtualMachines.CreateOrUpdate(this.ResourceGroupName, deviceName, new VirtualMachine()
{
Location = "West US",
OsProfile = new OSProfile()
{
AdminUsername = "hcstestuser",
AdminPassword = "StorSime1StorSim1",
ComputerName = deviceName,
CustomData = GetVmCustomData(deviceName, activationKey, configuration)
},
HardwareProfile = new HardwareProfile()
{
VmSize = configuration.SupportedVmTypes[0]
},
NetworkProfile = new NetworkProfile()
{
NetworkInterfaces = new List<NetworkInterfaceReference>()
{
new NetworkInterfaceReference()
{
Id = networkInterfaceId
}
}
},
StorageProfile = new StorageProfile()
{
ImageReference = new ImageReference()
{
Offer = configuration.SupportedVmImages[0].Offer,
Publisher = configuration.SupportedVmImages[0].Publisher,
Sku = configuration.SupportedVmImages[0].Sku,
Version = configuration.SupportedVmImages[0].Version
},
OsDisk = new OSDisk()
{
Name = deviceName + "os",
CreateOption = DiskCreateOptionTypes.FromImage,
Caching = CachingTypes.ReadWrite,
ManagedDisk = new ManagedDiskParameters()
{
StorageAccountType = StorageAccountTypes.PremiumLRS //configuration.SupportedStorageAccountTypes[0]
}
},
DataDisks = GetVmDataDisks(4, configuration, deviceName)
}
});
}
protected void CreateDefaultVnetIfNotExist()
{
VirtualNetwork vnet = null;
try
{
vnet = this.NetworkClient.VirtualNetworks.Get(this.ResourceGroupName, TestConstants.DefaultVirtualNetworkName);
}
catch (CloudException ex)
{
// Error code is not ResourceNotFound, then unexpected failure and hence rethrowing exception
if (ex.Body.Code != "ResourceNotFound")
{
throw;
}
}
if (vnet == null)
{
var vnetName = TestConstants.DefaultVirtualNetworkName;
var subnetName = TestConstants.DefaultSubnetName;
this.NetworkClient.VirtualNetworks.CreateOrUpdate(this.ResourceGroupName, vnetName, new VirtualNetwork()
{
Location = "West US",
AddressSpace = new AddressSpace()
{
AddressPrefixes = new List<string> { "10.1.0.0/16" }
},
Subnets = new List<Subnet>{
new Subnet(){
Name = subnetName,
AddressPrefix = "10.1.0.0/24"
}
}
});
}
}
private static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
private static string GetVmCustomData(string trackingDetails, string activationKey, CloudApplianceConfiguration configuration)
{
var strBuilder = new StringBuilder();
strBuilder.AppendLine();
strBuilder.AppendLine($"ModelNumber={configuration.ModelNumber}");
strBuilder.AppendLine($"TrackingId={Guid.NewGuid()}");
strBuilder.AppendLine($"RegistrationKey={activationKey}");
return Base64Encode(strBuilder.ToString());
}
private static IList<DataDisk> GetVmDataDisks(int numberOfDisks, CloudApplianceConfiguration configuration, string name)
{
var disks = new List<DataDisk>();
for (int i = 0; i < numberOfDisks; i++)
{
disks.Add(new DataDisk()
{
CreateOption = DiskCreateOptionTypes.Empty,
Lun = i,
Name = name + "datadisk" + (i + 1),
ManagedDisk = new ManagedDiskParameters()
{
StorageAccountType = StorageAccountTypes.PremiumLRS //configuration.SupportedStorageAccountTypes[0]
},
DiskSizeGB = 1023
});
}
return disks;
}
private AsymmetricEncryptedSecret EncryptSecretUsingDEK(string resourceGroupName, string managerName, string deviceName, string plainTextSecret)
{
PublicKey devicePublicEncryptionInfo = this.Client.Managers.GetDevicePublicEncryptionKey(deviceName.GetDoubleEncoded(), resourceGroupName, managerName);
var encryptedSecret = CryptoHelper.EncryptSecretRSAPKCS(plainTextSecret, devicePublicEncryptionInfo.Key);
AsymmetricEncryptedSecret secret = new AsymmetricEncryptedSecret(encryptedSecret, EncryptionAlgorithm.RSAESPKCS1V15, String.Empty);
return secret;
}
#endregion
// Dispose all disposable objects
public override void Dispose()
{
this.NetworkClient.Dispose();
this.ComputeClient.Dispose();
base.Dispose();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Win32;
namespace System
{
public sealed partial class TimeZoneInfo
{
// registry constants for the 'Time Zones' hive
//
private const string TimeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones";
private const string DisplayValue = "Display";
private const string DaylightValue = "Dlt";
private const string StandardValue = "Std";
private const string MuiDisplayValue = "MUI_Display";
private const string MuiDaylightValue = "MUI_Dlt";
private const string MuiStandardValue = "MUI_Std";
private const string TimeZoneInfoValue = "TZI";
private const string FirstEntryValue = "FirstEntry";
private const string LastEntryValue = "LastEntry";
private const int MaxKeyLength = 255;
private const int RegByteLength = 44;
#pragma warning disable 0420
private sealed partial class CachedData
{
private static TimeZoneInfo GetCurrentOneYearLocal()
{
// load the data from the OS
Win32Native.TimeZoneInformation timeZoneInformation;
long result = UnsafeNativeMethods.GetTimeZoneInformation(out timeZoneInformation);
return result == Win32Native.TIME_ZONE_ID_INVALID ?
CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId) :
GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled: false);
}
private volatile OffsetAndRule _oneYearLocalFromUtc;
public OffsetAndRule GetOneYearLocalFromUtc(int year)
{
OffsetAndRule oneYearLocFromUtc = _oneYearLocalFromUtc;
if (oneYearLocFromUtc == null || oneYearLocFromUtc.Year != year)
{
TimeZoneInfo currentYear = GetCurrentOneYearLocal();
AdjustmentRule rule = currentYear._adjustmentRules == null ? null : currentYear._adjustmentRules[0];
oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule);
_oneYearLocalFromUtc = oneYearLocFromUtc;
}
return oneYearLocFromUtc;
}
}
#pragma warning restore 0420
private sealed class OffsetAndRule
{
public readonly int Year;
public readonly TimeSpan Offset;
public readonly AdjustmentRule Rule;
public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule rule)
{
Year = year;
Offset = offset;
Rule = rule;
}
}
/// <summary>
/// Returns a cloned array of AdjustmentRule objects
/// </summary>
public AdjustmentRule[] GetAdjustmentRules()
{
if (_adjustmentRules == null)
{
return Array.Empty<AdjustmentRule>();
}
return (AdjustmentRule[])_adjustmentRules.Clone();
}
private static void PopulateAllSystemTimeZones(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
{
if (reg != null)
{
foreach (string keyName in reg.GetSubKeyNames())
{
TimeZoneInfo value;
Exception ex;
TryGetTimeZone(keyName, false, out value, out ex, cachedData); // populate the cache
}
}
}
}
private TimeZoneInfo(Win32Native.TimeZoneInformation zone, bool dstDisabled)
{
if (string.IsNullOrEmpty(zone.StandardName))
{
_id = LocalId; // the ID must contain at least 1 character - initialize _id to "Local"
}
else
{
_id = zone.StandardName;
}
_baseUtcOffset = new TimeSpan(0, -(zone.Bias), 0);
if (!dstDisabled)
{
// only create the adjustment rule if DST is enabled
Win32Native.RegistryTimeZoneInformation regZone = new Win32Native.RegistryTimeZoneInformation(zone);
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(regZone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias);
if (rule != null)
{
_adjustmentRules = new AdjustmentRule[1];
_adjustmentRules[0] = rule;
}
}
ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
_displayName = zone.StandardName;
_standardDisplayName = zone.StandardName;
_daylightDisplayName = zone.DaylightName;
}
/// <summary>
/// Helper function to check if the current TimeZoneInformation struct does not support DST.
/// This check returns true when the DaylightDate == StandardDate.
/// This check is only meant to be used for "Local".
/// </summary>
private static bool CheckDaylightSavingTimeNotSupported(Win32Native.TimeZoneInformation timeZone) =>
timeZone.DaylightDate.Year == timeZone.StandardDate.Year &&
timeZone.DaylightDate.Month == timeZone.StandardDate.Month &&
timeZone.DaylightDate.DayOfWeek == timeZone.StandardDate.DayOfWeek &&
timeZone.DaylightDate.Day == timeZone.StandardDate.Day &&
timeZone.DaylightDate.Hour == timeZone.StandardDate.Hour &&
timeZone.DaylightDate.Minute == timeZone.StandardDate.Minute &&
timeZone.DaylightDate.Second == timeZone.StandardDate.Second &&
timeZone.DaylightDate.Milliseconds == timeZone.StandardDate.Milliseconds;
/// <summary>
/// Converts a Win32Native.RegistryTimeZoneInformation (REG_TZI_FORMAT struct) to an AdjustmentRule.
/// </summary>
private static AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(Win32Native.RegistryTimeZoneInformation timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset)
{
bool supportsDst = timeZoneInformation.StandardDate.Month != 0;
if (!supportsDst)
{
if (timeZoneInformation.Bias == defaultBaseUtcOffset)
{
// this rule will not contain any information to be used to adjust dates. just ignore it
return null;
}
return AdjustmentRule.CreateAdjustmentRule(
startDate,
endDate,
TimeSpan.Zero, // no daylight saving transition
TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1),
TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1),
new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), // Bias delta is all what we need from this rule
noDaylightTransitions: false);
}
//
// Create an AdjustmentRule with TransitionTime objects
//
TransitionTime daylightTransitionStart;
if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, readStartDate: true))
{
return null;
}
TransitionTime daylightTransitionEnd;
if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, readStartDate: false))
{
return null;
}
if (daylightTransitionStart.Equals(daylightTransitionEnd))
{
// this happens when the time zone does support DST but the OS has DST disabled
return null;
}
return AdjustmentRule.CreateAdjustmentRule(
startDate,
endDate,
new TimeSpan(0, -timeZoneInformation.DaylightBias, 0),
daylightTransitionStart,
daylightTransitionEnd,
new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0),
noDaylightTransitions: false);
}
/// <summary>
/// Helper function that searches the registry for a time zone entry
/// that matches the TimeZoneInformation struct.
/// </summary>
private static string FindIdFromTimeZoneInformation(Win32Native.TimeZoneInformation timeZone, out bool dstDisabled)
{
dstDisabled = false;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
{
if (key == null)
{
return null;
}
foreach (string keyName in key.GetSubKeyNames())
{
if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled))
{
return keyName;
}
}
}
return null;
}
/// <summary>
/// Helper function for retrieving the local system time zone.
/// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.
/// Assumes cachedData lock is taken.
/// </summary>
/// <returns>A new TimeZoneInfo instance.</returns>
private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
string id = null;
//
// Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id"
//
var dynamicTimeZoneInformation = new Win32Native.DynamicTimeZoneInformation();
// call kernel32!GetDynamicTimeZoneInformation...
long result = UnsafeNativeMethods.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation);
if (result == Win32Native.TIME_ZONE_ID_INVALID)
{
// return a dummy entry
return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
}
var timeZoneInformation = new Win32Native.TimeZoneInformation(dynamicTimeZoneInformation);
bool dstDisabled = dynamicTimeZoneInformation.DynamicDaylightTimeDisabled;
// check to see if we can use the key name returned from the API call
if (!string.IsNullOrEmpty(dynamicTimeZoneInformation.TimeZoneKeyName))
{
TimeZoneInfo zone;
Exception ex;
if (TryGetTimeZone(dynamicTimeZoneInformation.TimeZoneKeyName, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
{
// successfully loaded the time zone from the registry
return zone;
}
}
// the key name was not returned or it pointed to a bogus entry - search for the entry ourselves
id = FindIdFromTimeZoneInformation(timeZoneInformation, out dstDisabled);
if (id != null)
{
TimeZoneInfo zone;
Exception ex;
if (TryGetTimeZone(id, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
{
// successfully loaded the time zone from the registry
return zone;
}
}
// We could not find the data in the registry. Fall back to using
// the data from the Win32 API
return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled);
}
/// <summary>
/// Helper function used by 'GetLocalTimeZone()' - this function wraps a bunch of
/// try/catch logic for handling the TimeZoneInfo private constructor that takes
/// a Win32Native.TimeZoneInformation structure.
/// </summary>
private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(Win32Native.TimeZoneInformation timeZoneInformation, bool dstDisabled)
{
// first try to create the TimeZoneInfo with the original 'dstDisabled' flag
try
{
return new TimeZoneInfo(timeZoneInformation, dstDisabled);
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
// if 'dstDisabled' was false then try passing in 'true' as a last ditch effort
if (!dstDisabled)
{
try
{
return new TimeZoneInfo(timeZoneInformation, dstDisabled: true);
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
}
// the data returned from Windows is completely bogus; return a dummy entry
return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
}
/// <summary>
/// Helper function for retrieving a TimeZoneInfo object by <time_zone_name>.
/// This function wraps the logic necessary to keep the private
/// SystemTimeZones cache in working order
///
/// This function will either return a valid TimeZoneInfo instance or
/// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.
/// </summary>
public static TimeZoneInfo FindSystemTimeZoneById(string id)
{
// Special case for Utc as it will not exist in the dictionary with the rest
// of the system time zones. There is no need to do this check for Local.Id
// since Local is a real time zone that exists in the dictionary cache
if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase))
{
return Utc;
}
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
else if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains("\0"))
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));
}
TimeZoneInfo value;
Exception e;
TimeZoneInfoResult result;
CachedData cachedData = s_cachedData;
lock (cachedData)
{
result = TryGetTimeZone(id, false, out value, out e, cachedData);
}
if (result == TimeZoneInfoResult.Success)
{
return value;
}
else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
{
throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidRegistryData, id), e);
}
else if (result == TimeZoneInfoResult.SecurityException)
{
throw new SecurityException(SR.Format(SR.Security_CannotReadRegistryData, id), e);
}
else
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);
}
}
// DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst)
{
bool isDaylightSavings = false;
isAmbiguousLocalDst = false;
TimeSpan baseOffset;
int timeYear = time.Year;
OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear);
baseOffset = match.Offset;
if (match.Rule != null)
{
baseOffset = baseOffset + match.Rule.BaseUtcOffsetDelta;
if (match.Rule.HasDaylightSaving)
{
isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.Offset, match.Rule, null, out isAmbiguousLocalDst, Local);
baseOffset += (isDaylightSavings ? match.Rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
}
}
return baseOffset;
}
/// <summary>
/// Converts a Win32Native.RegistryTimeZoneInformation (REG_TZI_FORMAT struct) to a TransitionTime
/// - When the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read
/// - When the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read
/// </summary>
private static bool TransitionTimeFromTimeZoneInformation(Win32Native.RegistryTimeZoneInformation timeZoneInformation, out TransitionTime transitionTime, bool readStartDate)
{
//
// SYSTEMTIME -
//
// If the time zone does not support daylight saving time or if the caller needs
// to disable daylight saving time, the wMonth member in the SYSTEMTIME structure
// must be zero. If this date is specified, the DaylightDate value in the
// TIME_ZONE_INFORMATION structure must also be specified. Otherwise, the system
// assumes the time zone data is invalid and no changes will be applied.
//
bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);
if (!supportsDst)
{
transitionTime = default(TransitionTime);
return false;
}
//
// SYSTEMTIME -
//
// * FixedDateRule -
// If the Year member is not zero, the transition date is absolute; it will only occur one time
//
// * FloatingDateRule -
// To select the correct day in the month, set the Year member to zero, the Hour and Minute
// members to the transition time, the DayOfWeek member to the appropriate weekday, and the
// Day member to indicate the occurence of the day of the week within the month (first through fifth).
//
// Using this notation, specify the 2:00a.m. on the first Sunday in April as follows:
// Hour = 2,
// Month = 4,
// DayOfWeek = 0,
// Day = 1.
//
// Specify 2:00a.m. on the last Thursday in October as follows:
// Hour = 2,
// Month = 10,
// DayOfWeek = 4,
// Day = 5.
//
if (readStartDate)
{
//
// read the "daylightTransitionStart"
//
if (timeZoneInformation.DaylightDate.Year == 0)
{
transitionTime = TransitionTime.CreateFloatingDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.DaylightDate.Hour,
timeZoneInformation.DaylightDate.Minute,
timeZoneInformation.DaylightDate.Second,
timeZoneInformation.DaylightDate.Milliseconds),
timeZoneInformation.DaylightDate.Month,
timeZoneInformation.DaylightDate.Day, /* Week 1-5 */
(DayOfWeek)timeZoneInformation.DaylightDate.DayOfWeek);
}
else
{
transitionTime = TransitionTime.CreateFixedDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.DaylightDate.Hour,
timeZoneInformation.DaylightDate.Minute,
timeZoneInformation.DaylightDate.Second,
timeZoneInformation.DaylightDate.Milliseconds),
timeZoneInformation.DaylightDate.Month,
timeZoneInformation.DaylightDate.Day);
}
}
else
{
//
// read the "daylightTransitionEnd"
//
if (timeZoneInformation.StandardDate.Year == 0)
{
transitionTime = TransitionTime.CreateFloatingDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.StandardDate.Hour,
timeZoneInformation.StandardDate.Minute,
timeZoneInformation.StandardDate.Second,
timeZoneInformation.StandardDate.Milliseconds),
timeZoneInformation.StandardDate.Month,
timeZoneInformation.StandardDate.Day, /* Week 1-5 */
(DayOfWeek)timeZoneInformation.StandardDate.DayOfWeek);
}
else
{
transitionTime = TransitionTime.CreateFixedDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.StandardDate.Hour,
timeZoneInformation.StandardDate.Minute,
timeZoneInformation.StandardDate.Second,
timeZoneInformation.StandardDate.Milliseconds),
timeZoneInformation.StandardDate.Month,
timeZoneInformation.StandardDate.Day);
}
}
return true;
}
/// <summary>
/// Helper function that takes:
/// 1. A string representing a <time_zone_name> registry key name.
/// 2. A RegistryTimeZoneInformation struct containing the default rule.
/// 3. An AdjustmentRule[] out-parameter.
/// </summary>
private static bool TryCreateAdjustmentRules(string id, Win32Native.RegistryTimeZoneInformation defaultTimeZoneInformation, out AdjustmentRule[] rules, out Exception e, int defaultBaseUtcOffset)
{
e = null;
try
{
// Optional, Dynamic Time Zone Registry Data
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// HKLM
// Software
// Microsoft
// Windows NT
// CurrentVersion
// Time Zones
// <time_zone_name>
// Dynamic DST
// * "FirstEntry" REG_DWORD "1980"
// First year in the table. If the current year is less than this value,
// this entry will be used for DST boundaries
// * "LastEntry" REG_DWORD "2038"
// Last year in the table. If the current year is greater than this value,
// this entry will be used for DST boundaries"
// * "<year1>" REG_BINARY REG_TZI_FORMAT
// See Win32Native.RegistryTimeZoneInformation
// * "<year2>" REG_BINARY REG_TZI_FORMAT
// See Win32Native.RegistryTimeZoneInformation
// * "<year3>" REG_BINARY REG_TZI_FORMAT
// See Win32Native.RegistryTimeZoneInformation
//
using (RegistryKey dynamicKey = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id + "\\Dynamic DST", writable: false))
{
if (dynamicKey == null)
{
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(
defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
rules = rule == null ? null : new[] { rule };
return true;
}
//
// loop over all of the "<time_zone_name>\Dynamic DST" hive entries
//
// read FirstEntry {MinValue - (year1, 12, 31)}
// read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)}
// read LastEntry {(yearN, 1, 1) - MaxValue }
// read the FirstEntry and LastEntry key values (ex: "1980", "2038")
int first = (int)dynamicKey.GetValue(FirstEntryValue, -1, RegistryValueOptions.None);
int last = (int)dynamicKey.GetValue(LastEntryValue, -1, RegistryValueOptions.None);
if (first == -1 || last == -1 || first > last)
{
rules = null;
return false;
}
// read the first year entry
Win32Native.RegistryTimeZoneInformation dtzi;
byte[] regValue = dynamicKey.GetValue(first.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as byte[];
if (regValue == null || regValue.Length != RegByteLength)
{
rules = null;
return false;
}
dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
if (first == last)
{
// there is just 1 dynamic rule for this time zone.
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
rules = rule == null ? null : new[] { rule };
return true;
}
List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);
// there are more than 1 dynamic rules for this time zone.
AdjustmentRule firstRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
DateTime.MinValue.Date, // MinValue
new DateTime(first, 12, 31), // December 31, <FirstYear>
defaultBaseUtcOffset);
if (firstRule != null)
{
rulesList.Add(firstRule);
}
// read the middle year entries
for (int i = first + 1; i < last; i++)
{
regValue = dynamicKey.GetValue(i.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as byte[];
if (regValue == null || regValue.Length != RegByteLength)
{
rules = null;
return false;
}
dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
AdjustmentRule middleRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
new DateTime(i, 1, 1), // January 01, <Year>
new DateTime(i, 12, 31), // December 31, <Year>
defaultBaseUtcOffset);
if (middleRule != null)
{
rulesList.Add(middleRule);
}
}
// read the last year entry
regValue = dynamicKey.GetValue(last.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as byte[];
dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
if (regValue == null || regValue.Length != RegByteLength)
{
rules = null;
return false;
}
AdjustmentRule lastRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
new DateTime(last, 1, 1), // January 01, <LastYear>
DateTime.MaxValue.Date, // MaxValue
defaultBaseUtcOffset);
if (lastRule != null)
{
rulesList.Add(lastRule);
}
// convert the ArrayList to an AdjustmentRule array
rules = rulesList.ToArray();
if (rules != null && rules.Length == 0)
{
rules = null;
}
} // end of: using (RegistryKey dynamicKey...
}
catch (InvalidCastException ex)
{
// one of the RegistryKey.GetValue calls could not be cast to an expected value type
rules = null;
e = ex;
return false;
}
catch (ArgumentOutOfRangeException ex)
{
rules = null;
e = ex;
return false;
}
catch (ArgumentException ex)
{
rules = null;
e = ex;
return false;
}
return true;
}
/// <summary>
/// Helper function that compares the StandardBias and StandardDate portion a
/// TimeZoneInformation struct to a time zone registry entry.
/// </summary>
private static bool TryCompareStandardDate(Win32Native.TimeZoneInformation timeZone, Win32Native.RegistryTimeZoneInformation registryTimeZoneInfo) =>
timeZone.Bias == registryTimeZoneInfo.Bias &&
timeZone.StandardBias == registryTimeZoneInfo.StandardBias &&
timeZone.StandardDate.Year == registryTimeZoneInfo.StandardDate.Year &&
timeZone.StandardDate.Month == registryTimeZoneInfo.StandardDate.Month &&
timeZone.StandardDate.DayOfWeek == registryTimeZoneInfo.StandardDate.DayOfWeek &&
timeZone.StandardDate.Day == registryTimeZoneInfo.StandardDate.Day &&
timeZone.StandardDate.Hour == registryTimeZoneInfo.StandardDate.Hour &&
timeZone.StandardDate.Minute == registryTimeZoneInfo.StandardDate.Minute &&
timeZone.StandardDate.Second == registryTimeZoneInfo.StandardDate.Second &&
timeZone.StandardDate.Milliseconds == registryTimeZoneInfo.StandardDate.Milliseconds;
/// <summary>
/// Helper function that compares a TimeZoneInformation struct to a time zone registry entry.
/// </summary>
private static bool TryCompareTimeZoneInformationToRegistry(Win32Native.TimeZoneInformation timeZone, string id, out bool dstDisabled)
{
dstDisabled = false;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
{
if (key == null)
{
return false;
}
Win32Native.RegistryTimeZoneInformation registryTimeZoneInfo;
byte[] regValue = key.GetValue(TimeZoneInfoValue, null, RegistryValueOptions.None) as byte[];
if (regValue == null || regValue.Length != RegByteLength) return false;
registryTimeZoneInfo = new Win32Native.RegistryTimeZoneInformation(regValue);
//
// first compare the bias and standard date information between the data from the Win32 API
// and the data from the registry...
//
bool result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);
if (!result)
{
return false;
}
result = dstDisabled || CheckDaylightSavingTimeNotSupported(timeZone) ||
//
// since Daylight Saving Time is not "disabled", do a straight comparision between
// the Win32 API data and the registry data ...
//
(timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias &&
timeZone.DaylightDate.Year == registryTimeZoneInfo.DaylightDate.Year &&
timeZone.DaylightDate.Month == registryTimeZoneInfo.DaylightDate.Month &&
timeZone.DaylightDate.DayOfWeek == registryTimeZoneInfo.DaylightDate.DayOfWeek &&
timeZone.DaylightDate.Day == registryTimeZoneInfo.DaylightDate.Day &&
timeZone.DaylightDate.Hour == registryTimeZoneInfo.DaylightDate.Hour &&
timeZone.DaylightDate.Minute == registryTimeZoneInfo.DaylightDate.Minute &&
timeZone.DaylightDate.Second == registryTimeZoneInfo.DaylightDate.Second &&
timeZone.DaylightDate.Milliseconds == registryTimeZoneInfo.DaylightDate.Milliseconds);
// Finally compare the "StandardName" string value...
//
// we do not compare "DaylightName" as this TimeZoneInformation field may contain
// either "StandardName" or "DaylightName" depending on the time of year and current machine settings
//
if (result)
{
string registryStandardName = key.GetValue(StandardValue, string.Empty, RegistryValueOptions.None) as string;
result = string.Equals(registryStandardName, timeZone.StandardName, StringComparison.Ordinal);
}
return result;
}
}
/// <summary>
/// Helper function for retrieving a localized string resource via MUI.
/// The function expects a string in the form: "@resource.dll, -123"
///
/// "resource.dll" is a language-neutral portable executable (LNPE) file in
/// the %windir%\system32 directory. The OS is queried to find the best-fit
/// localized resource file for this LNPE (ex: %windir%\system32\en-us\resource.dll.mui).
/// If a localized resource file exists, we LoadString resource ID "123" and
/// return it to our caller.
/// </summary>
private static string TryGetLocalizedNameByMuiNativeResource(string resource)
{
if (string.IsNullOrEmpty(resource))
{
return string.Empty;
}
// parse "@tzres.dll, -100"
//
// filePath = "C:\Windows\System32\tzres.dll"
// resourceId = -100
//
string[] resources = resource.Split(',');
if (resources.Length != 2)
{
return string.Empty;
}
string filePath;
int resourceId;
// get the path to Windows\System32
string system32 = Environment.SystemDirectory;
// trim the string "@tzres.dll" => "tzres.dll"
string tzresDll = resources[0].TrimStart('@');
try
{
filePath = Path.Combine(system32, tzresDll);
}
catch (ArgumentException)
{
// there were probably illegal characters in the path
return string.Empty;
}
if (!int.TryParse(resources[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out resourceId))
{
return string.Empty;
}
resourceId = -resourceId;
try
{
StringBuilder fileMuiPath = StringBuilderCache.Acquire(Path.MaxPath);
fileMuiPath.Length = Path.MaxPath;
int fileMuiPathLength = Path.MaxPath;
int languageLength = 0;
long enumerator = 0;
bool succeeded = UnsafeNativeMethods.GetFileMUIPath(
Win32Native.MUI_PREFERRED_UI_LANGUAGES,
filePath, null /* language */, ref languageLength,
fileMuiPath, ref fileMuiPathLength, ref enumerator);
if (!succeeded)
{
StringBuilderCache.Release(fileMuiPath);
return string.Empty;
}
return TryGetLocalizedNameByNativeResource(StringBuilderCache.GetStringAndRelease(fileMuiPath), resourceId);
}
catch (EntryPointNotFoundException)
{
return string.Empty;
}
}
/// <summary>
/// Helper function for retrieving a localized string resource via a native resource DLL.
/// The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll"
///
/// "resource.dll" is a language-specific resource DLL.
/// If the localized resource DLL exists, LoadString(resource) is returned.
/// </summary>
private static string TryGetLocalizedNameByNativeResource(string filePath, int resource)
{
using (SafeLibraryHandle handle =
UnsafeNativeMethods.LoadLibraryEx(filePath, IntPtr.Zero, Win32Native.LOAD_LIBRARY_AS_DATAFILE))
{
if (!handle.IsInvalid)
{
StringBuilder localizedResource = StringBuilderCache.Acquire(Win32Native.LOAD_STRING_MAX_LENGTH);
localizedResource.Length = Win32Native.LOAD_STRING_MAX_LENGTH;
int result = UnsafeNativeMethods.LoadString(handle, resource,
localizedResource, localizedResource.Length);
if (result != 0)
{
return StringBuilderCache.GetStringAndRelease(localizedResource);
}
}
}
return string.Empty;
}
/// <summary>
/// Helper function for retrieving the DisplayName, StandardName, and DaylightName from the registry
///
/// The function first checks the MUI_ key-values, and if they exist, it loads the strings from the MUI
/// resource dll(s). When the keys do not exist, the function falls back to reading from the standard
/// key-values
/// </summary>
private static bool TryGetLocalizedNamesByRegistryKey(RegistryKey key, out string displayName, out string standardName, out string daylightName)
{
displayName = string.Empty;
standardName = string.Empty;
daylightName = string.Empty;
// read the MUI_ registry keys
string displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty, RegistryValueOptions.None) as string;
string standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty, RegistryValueOptions.None) as string;
string daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty, RegistryValueOptions.None) as string;
// try to load the strings from the native resource DLL(s)
if (!string.IsNullOrEmpty(displayNameMuiResource))
{
displayName = TryGetLocalizedNameByMuiNativeResource(displayNameMuiResource);
}
if (!string.IsNullOrEmpty(standardNameMuiResource))
{
standardName = TryGetLocalizedNameByMuiNativeResource(standardNameMuiResource);
}
if (!string.IsNullOrEmpty(daylightNameMuiResource))
{
daylightName = TryGetLocalizedNameByMuiNativeResource(daylightNameMuiResource);
}
// fallback to using the standard registry keys
if (string.IsNullOrEmpty(displayName))
{
displayName = key.GetValue(DisplayValue, string.Empty, RegistryValueOptions.None) as string;
}
if (string.IsNullOrEmpty(standardName))
{
standardName = key.GetValue(StandardValue, string.Empty, RegistryValueOptions.None) as string;
}
if (string.IsNullOrEmpty(daylightName))
{
daylightName = key.GetValue(DaylightValue, string.Empty, RegistryValueOptions.None) as string;
}
return true;
}
/// <summary>
/// Helper function that takes a string representing a <time_zone_name> registry key name
/// and returns a TimeZoneInfo instance.
/// </summary>
private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo value, out Exception e)
{
e = null;
// Standard Time Zone Registry Data
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// HKLM
// Software
// Microsoft
// Windows NT
// CurrentVersion
// Time Zones
// <time_zone_name>
// * STD, REG_SZ "Standard Time Name"
// (For OS installed zones, this will always be English)
// * MUI_STD, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for Standard Time,
// add "%windir%\system32\" after "@"
// * DLT, REG_SZ "Daylight Time Name"
// (For OS installed zones, this will always be English)
// * MUI_DLT, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for Daylight Time,
// add "%windir%\system32\" after "@"
// * Display, REG_SZ "Display Name like (GMT-8:00) Pacific Time..."
// * MUI_Display, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for the Display,
// add "%windir%\system32\" after "@"
// * TZI, REG_BINARY REG_TZI_FORMAT
// See Win32Native.RegistryTimeZoneInformation
//
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
{
if (key == null)
{
value = null;
return TimeZoneInfoResult.TimeZoneNotFoundException;
}
Win32Native.RegistryTimeZoneInformation defaultTimeZoneInformation;
byte[] regValue = key.GetValue(TimeZoneInfoValue, null, RegistryValueOptions.None) as byte[];
if (regValue == null || regValue.Length != RegByteLength)
{
// the registry value could not be cast to a byte array
value = null;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
defaultTimeZoneInformation = new Win32Native.RegistryTimeZoneInformation(regValue);
AdjustmentRule[] adjustmentRules;
if (!TryCreateAdjustmentRules(id, defaultTimeZoneInformation, out adjustmentRules, out e, defaultTimeZoneInformation.Bias))
{
value = null;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
string displayName;
string standardName;
string daylightName;
if (!TryGetLocalizedNamesByRegistryKey(key, out displayName, out standardName, out daylightName))
{
value = null;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
try
{
value = new TimeZoneInfo(
id,
new TimeSpan(0, -(defaultTimeZoneInformation.Bias), 0),
displayName,
standardName,
daylightName,
adjustmentRules,
disableDaylightSavingTime: false);
return TimeZoneInfoResult.Success;
}
catch (ArgumentException ex)
{
// TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
value = null;
e = ex;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
catch (InvalidTimeZoneException ex)
{
// TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
value = null;
e = ex;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
}
}
}
}
| |
/*
* Deed API
*
* Land Registry Deed API
*
* OpenAPI spec version: 1.3.8
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace IO.Swagger.Model
{
/// <summary>
/// Unique deed, consisting of property, borrower and charge information as well as clauses for the deed.
/// </summary>
[DataContract]
public partial class OperativeDeedDeed : IEquatable<OperativeDeedDeed>
{
/// <summary>
/// Initializes a new instance of the <see cref="OperativeDeedDeed" /> class.
/// </summary>
/// <param name="TitleNumber">Unique Land Registry identifier for the registered estate..</param>
/// <param name="MdRef">Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345).</param>
/// <param name="Borrowers">Borrowers.</param>
/// <param name="ChargeClause">ChargeClause.</param>
/// <param name="AdditionalProvisions">AdditionalProvisions.</param>
/// <param name="Lender">Lender.</param>
/// <param name="EffectiveClause">Text to display the make effective clause.</param>
/// <param name="PropertyAddress">The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA.</param>
/// <param name="DeedStatus">Current state of the deed.</param>
/// <param name="EffectiveDate">An effective date is shown if the deed is made effective.</param>
public OperativeDeedDeed(string TitleNumber = null, string MdRef = null, OpBorrowers Borrowers = null, ChargeClause ChargeClause = null, AdditionalProvisions AdditionalProvisions = null, Lender Lender = null, string EffectiveClause = null, string PropertyAddress = null, string DeedStatus = null, string EffectiveDate = null)
{
this.TitleNumber = TitleNumber;
this.MdRef = MdRef;
this.Borrowers = Borrowers;
this.ChargeClause = ChargeClause;
this.AdditionalProvisions = AdditionalProvisions;
this.Lender = Lender;
this.EffectiveClause = EffectiveClause;
this.PropertyAddress = PropertyAddress;
this.DeedStatus = DeedStatus;
this.EffectiveDate = EffectiveDate;
}
/// <summary>
/// Unique Land Registry identifier for the registered estate.
/// </summary>
/// <value>Unique Land Registry identifier for the registered estate.</value>
[DataMember(Name="title_number", EmitDefaultValue=false)]
public string TitleNumber { get; set; }
/// <summary>
/// Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345)
/// </summary>
/// <value>Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345)</value>
[DataMember(Name="md_ref", EmitDefaultValue=false)]
public string MdRef { get; set; }
/// <summary>
/// Gets or Sets Borrowers
/// </summary>
[DataMember(Name="borrowers", EmitDefaultValue=false)]
public OpBorrowers Borrowers { get; set; }
/// <summary>
/// Gets or Sets ChargeClause
/// </summary>
[DataMember(Name="charge_clause", EmitDefaultValue=false)]
public ChargeClause ChargeClause { get; set; }
/// <summary>
/// Gets or Sets AdditionalProvisions
/// </summary>
[DataMember(Name="additional_provisions", EmitDefaultValue=false)]
public AdditionalProvisions AdditionalProvisions { get; set; }
/// <summary>
/// Gets or Sets Lender
/// </summary>
[DataMember(Name="lender", EmitDefaultValue=false)]
public Lender Lender { get; set; }
/// <summary>
/// Text to display the make effective clause
/// </summary>
/// <value>Text to display the make effective clause</value>
[DataMember(Name="effective_clause", EmitDefaultValue=false)]
public string EffectiveClause { get; set; }
/// <summary>
/// The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA
/// </summary>
/// <value>The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA</value>
[DataMember(Name="property_address", EmitDefaultValue=false)]
public string PropertyAddress { get; set; }
/// <summary>
/// Current state of the deed
/// </summary>
/// <value>Current state of the deed</value>
[DataMember(Name="deed_status", EmitDefaultValue=false)]
public string DeedStatus { get; set; }
/// <summary>
/// An effective date is shown if the deed is made effective
/// </summary>
/// <value>An effective date is shown if the deed is made effective</value>
[DataMember(Name="effective_date", EmitDefaultValue=false)]
public string EffectiveDate { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OperativeDeedDeed {\n");
sb.Append(" TitleNumber: ").Append(TitleNumber).Append("\n");
sb.Append(" MdRef: ").Append(MdRef).Append("\n");
sb.Append(" Borrowers: ").Append(Borrowers).Append("\n");
sb.Append(" ChargeClause: ").Append(ChargeClause).Append("\n");
sb.Append(" AdditionalProvisions: ").Append(AdditionalProvisions).Append("\n");
sb.Append(" Lender: ").Append(Lender).Append("\n");
sb.Append(" EffectiveClause: ").Append(EffectiveClause).Append("\n");
sb.Append(" PropertyAddress: ").Append(PropertyAddress).Append("\n");
sb.Append(" DeedStatus: ").Append(DeedStatus).Append("\n");
sb.Append(" EffectiveDate: ").Append(EffectiveDate).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as OperativeDeedDeed);
}
/// <summary>
/// Returns true if OperativeDeedDeed instances are equal
/// </summary>
/// <param name="other">Instance of OperativeDeedDeed to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OperativeDeedDeed other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.TitleNumber == other.TitleNumber ||
this.TitleNumber != null &&
this.TitleNumber.Equals(other.TitleNumber)
) &&
(
this.MdRef == other.MdRef ||
this.MdRef != null &&
this.MdRef.Equals(other.MdRef)
) &&
(
this.Borrowers == other.Borrowers ||
this.Borrowers != null &&
this.Borrowers.Equals(other.Borrowers)
) &&
(
this.ChargeClause == other.ChargeClause ||
this.ChargeClause != null &&
this.ChargeClause.Equals(other.ChargeClause)
) &&
(
this.AdditionalProvisions == other.AdditionalProvisions ||
this.AdditionalProvisions != null &&
this.AdditionalProvisions.Equals(other.AdditionalProvisions)
) &&
(
this.Lender == other.Lender ||
this.Lender != null &&
this.Lender.Equals(other.Lender)
) &&
(
this.EffectiveClause == other.EffectiveClause ||
this.EffectiveClause != null &&
this.EffectiveClause.Equals(other.EffectiveClause)
) &&
(
this.PropertyAddress == other.PropertyAddress ||
this.PropertyAddress != null &&
this.PropertyAddress.Equals(other.PropertyAddress)
) &&
(
this.DeedStatus == other.DeedStatus ||
this.DeedStatus != null &&
this.DeedStatus.Equals(other.DeedStatus)
) &&
(
this.EffectiveDate == other.EffectiveDate ||
this.EffectiveDate != null &&
this.EffectiveDate.Equals(other.EffectiveDate)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.TitleNumber != null)
hash = hash * 59 + this.TitleNumber.GetHashCode();
if (this.MdRef != null)
hash = hash * 59 + this.MdRef.GetHashCode();
if (this.Borrowers != null)
hash = hash * 59 + this.Borrowers.GetHashCode();
if (this.ChargeClause != null)
hash = hash * 59 + this.ChargeClause.GetHashCode();
if (this.AdditionalProvisions != null)
hash = hash * 59 + this.AdditionalProvisions.GetHashCode();
if (this.Lender != null)
hash = hash * 59 + this.Lender.GetHashCode();
if (this.EffectiveClause != null)
hash = hash * 59 + this.EffectiveClause.GetHashCode();
if (this.PropertyAddress != null)
hash = hash * 59 + this.PropertyAddress.GetHashCode();
if (this.DeedStatus != null)
hash = hash * 59 + this.DeedStatus.GetHashCode();
if (this.EffectiveDate != null)
hash = hash * 59 + this.EffectiveDate.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using MiniTrello.Win8Phone.Areas.HelpPage.Models;
namespace MiniTrello.Win8Phone.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 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 that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Text.RegularExpressions;
using Bridge.Html5;
using Bridge.Test.NUnit;
namespace Bridge.ClientTest.Batch3.BridgeIssues
{
[Category(Constants.MODULE_ISSUES)]
[TestFixture(TestNameFormat = "#2638A - {0}")]
public class Bridge2638A
{
class BaseClass { }
class DerivedClass : BaseClass { }
public interface I1<T>
{
int Prop1
{
get; set;
}
int this[int idx] { get; set; }
event Action e1;
int M1();
}
public interface I2<in T>
{
int Prop1
{
get; set;
}
int this[int idx] { get; set; }
event Action e1;
int M1();
}
public class G1<T> : I1<T>
{
int I1<T>.this[int idx]
{
get
{
return 1;
}
set
{
throw new NotImplementedException();
}
}
int I1<T>.Prop1
{
get
{
return 2;
}
set
{
throw new NotImplementedException();
}
}
event Action I1<T>.e1
{
add
{
throw new NotImplementedException();
}
remove
{
throw new NotImplementedException();
}
}
int I1<T>.M1()
{
return 3;
}
}
private static string baseClassAlias = "Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$BaseClass";
private static string stringAlias = "System$String";
[Test]
public void TestG1()
{
var c = new G1<BaseClass>();
I1<BaseClass> i = c;
Assert.AreEqual(1, i[0]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$getItem"]);
Assert.Null(c["getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + baseClassAlias + "$getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$setItem"]);
Assert.Null(c["setItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + baseClassAlias + "$setItem"]);
Assert.AreEqual(2, i.Prop1);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$Prop1"]);
Assert.Null(c["Prop1"]);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + baseClassAlias + "$Prop1"]);
Assert.Throws<NotImplementedException>(() => { i.e1 += () => { }; });
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$adde1"]);
Assert.Null(c["adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + baseClassAlias + "$adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$removee1"]);
Assert.Null(c["removee1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + baseClassAlias + "$removee1"]);
Assert.AreEqual(3, i.M1());
Assert.Null(c["M1"]);
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$M1"].As<Func<int>>()());
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + baseClassAlias + "$M1"].As<Func<int>>()());
}
public class G2<T> : I1<T>
{
public int this[int idx]
{
get
{
return 1;
}
set
{
throw new NotImplementedException();
}
}
public int Prop1
{
get
{
return 2;
}
set
{
throw new NotImplementedException();
}
}
public event Action e1
{
add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }
}
public int M1()
{
return 3;
}
}
[Test]
public void TestG2()
{
var c = new G2<BaseClass>();
I1<BaseClass> i = c;
Assert.AreEqual(1, i[0]);
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$getItem"]);
Assert.NotNull(c["getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + baseClassAlias + "$getItem"]);
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$setItem"]);
Assert.NotNull(c["setItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + baseClassAlias + "$setItem"]);
Assert.AreEqual(2, i.Prop1);
Assert.AreEqual(i.Prop1, c["Prop1"]);
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$Prop1"]);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + baseClassAlias + "$Prop1"]);
Assert.Throws<NotImplementedException>(() => { i.e1 += () => { }; });
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$adde1"]);
Assert.NotNull(c["adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + baseClassAlias + "$adde1"]);
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$removee1"]);
Assert.NotNull(c["removee1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + baseClassAlias + "$removee1"]);
Assert.AreEqual(3, i.M1());
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$M1"]);
Assert.AreEqual(i.M1(), c["M1"].As<Func<int>>()());
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + baseClassAlias + "$M1"].As<Func<int>>()());
}
public class G3 : I1<string>
{
int I1<string>.this[int idx]
{
get
{
return 1;
}
set
{
throw new NotImplementedException();
}
}
int I1<string>.Prop1
{
get
{
return 2;
}
set
{
throw new NotImplementedException();
}
}
event Action I1<string>.e1
{
add
{
throw new NotImplementedException();
}
remove
{
throw new NotImplementedException();
}
}
int I1<string>.M1()
{
return 3;
}
}
[Test]
public void TestG3()
{
var c = new G3();
I1<string> i = c;
Assert.AreEqual(1, i[0]);
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$getItem"]);
Assert.Null(c["getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + stringAlias + "$getItem"]);
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$setItem"]);
Assert.Null(c["setItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + stringAlias + "$setItem"]);
Assert.AreEqual(2, i.Prop1);
Assert.Null(c["Prop1"]);
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$Prop1"]);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + stringAlias + "$Prop1"]);
Assert.Throws<NotImplementedException>(() => { i.e1 += () => { }; });
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$adde1"]);
Assert.Null(c["adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + stringAlias + "$adde1"]);
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$removee1"]);
Assert.Null(c["removee1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + stringAlias + "$removee1"]);
Assert.AreEqual(3, i.M1());
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$M1"]);
Assert.Null(c["M1"]);
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + stringAlias + "$M1"].As<Func<int>>()());
}
public class G4 : I1<string>
{
public int this[int idx]
{
get
{
return 1;
}
set
{
throw new NotImplementedException();
}
}
public int Prop1
{
get
{
return 2;
}
set
{
throw new NotImplementedException();
}
}
public event Action e1
{
add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }
}
public int M1()
{
return 3;
}
}
[Test]
public void TestG4()
{
var c = new G4();
I1<string> i = c;
Assert.AreEqual(1, i[0]);
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$getItem"]);
Assert.NotNull(c["getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + stringAlias + "$getItem"]);
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$setItem"]);
Assert.NotNull(c["setItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + stringAlias + "$setItem"]);
Assert.AreEqual(2, i.Prop1);
Assert.AreEqual(i.Prop1, c["Prop1"]);
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$Prop1"]);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + stringAlias + "$Prop1"]);
Assert.Throws<NotImplementedException>(() => { i.e1 += () => { }; });
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$adde1"]);
Assert.NotNull(c["adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + stringAlias + "$adde1"]);
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$removee1"]);
Assert.NotNull(c["removee1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + stringAlias + "$removee1"]);
Assert.AreEqual(3, i.M1());
Assert.Null(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$M1"]);
Assert.AreEqual(i.M1(), c["M1"].As<Func<int>>()());
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I1$1$" + stringAlias + "$M1"].As<Func<int>>()());
}
public class G5<T> : I2<T>
{
int I2<T>.this[int idx]
{
get
{
return 1;
}
set
{
throw new NotImplementedException();
}
}
int I2<T>.Prop1
{
get
{
return 2;
}
set
{
throw new NotImplementedException();
}
}
event Action I2<T>.e1
{
add
{
throw new NotImplementedException();
}
remove
{
throw new NotImplementedException();
}
}
int I2<T>.M1()
{
return 3;
}
}
[Test]
public void TestG5()
{
var c = new G5<BaseClass>();
I2<BaseClass> i = c;
I2<DerivedClass> id = c;
Assert.AreEqual(1, i[0]);
Assert.AreEqual(1, id[0]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$getItem"]);
Assert.Null(c["getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$setItem"]);
Assert.Null(c["setItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$setItem"]);
Assert.AreEqual(2, i.Prop1);
Assert.AreEqual(2, id.Prop1);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$Prop1"]);
Assert.Null(c["Prop1"]);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$Prop1"]);
Assert.Throws<NotImplementedException>(() => { i.e1 += () => { }; });
Assert.Throws<NotImplementedException>(() => { id.e1 += () => { }; });
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$adde1"]);
Assert.Null(c["adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$removee1"]);
Assert.Null(c["removee1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$removee1"]);
Assert.AreEqual(3, i.M1());
Assert.AreEqual(3, id.M1());
Assert.Null(c["M1"]);
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$M1"].As<Func<int>>()());
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$M1"].As<Func<int>>()());
}
public class G6<T> : I2<T>
{
public int this[int idx]
{
get
{
return 1;
}
set
{
throw new NotImplementedException();
}
}
public int Prop1
{
get
{
return 2;
}
set
{
throw new NotImplementedException();
}
}
public event Action e1
{
add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }
}
public int M1()
{
return 3;
}
}
[Test]
public void TestG6()
{
var c = new G6<BaseClass>();
I2<BaseClass> i = c;
I2<DerivedClass> id = c;
Assert.AreEqual(1, i[0]);
Assert.AreEqual(1, id[0]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$getItem"]);
Assert.NotNull(c["getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$setItem"]);
Assert.NotNull(c["setItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$setItem"]);
Assert.AreEqual(2, i.Prop1);
Assert.AreEqual(2, id.Prop1);
Assert.AreEqual(i.Prop1, c["Prop1"]);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$Prop1"]);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$Prop1"]);
Assert.Throws<NotImplementedException>(() => { i.e1 += () => { }; });
Assert.Throws<NotImplementedException>(() => { id.e1 += () => { }; });
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$adde1"]);
Assert.NotNull(c["adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$removee1"]);
Assert.NotNull(c["removee1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$removee1"]);
Assert.AreEqual(3, i.M1());
Assert.AreEqual(3, id.M1());
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$M1"].As<Func<int>>()());
Assert.AreEqual(i.M1(), c["M1"].As<Func<int>>()());
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$M1"].As<Func<int>>()());
}
public class G7 : I2<BaseClass>
{
int I2<BaseClass>.this[int idx]
{
get
{
return 1;
}
set
{
throw new NotImplementedException();
}
}
int I2<BaseClass>.Prop1
{
get
{
return 2;
}
set
{
throw new NotImplementedException();
}
}
event Action I2<BaseClass>.e1
{
add
{
throw new NotImplementedException();
}
remove
{
throw new NotImplementedException();
}
}
int I2<BaseClass>.M1()
{
return 3;
}
}
[Test]
public void TestG7()
{
var c = new G7();
I2<BaseClass> i = c;
I2<DerivedClass> id = c;
Assert.AreEqual(1, i[0]);
Assert.AreEqual(1, id[0]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$getItem"]);
Assert.Null(c["getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$setItem"]);
Assert.Null(c["setItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$setItem"]);
Assert.AreEqual(2, i.Prop1);
Assert.AreEqual(2, id.Prop1);
Assert.Null(c["Prop1"]);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$Prop1"]);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$Prop1"]);
Assert.Throws<NotImplementedException>(() => { i.e1 += () => { }; });
Assert.Throws<NotImplementedException>(() => { id.e1 += () => { }; });
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$adde1"]);
Assert.Null(c["adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$removee1"]);
Assert.Null(c["removee1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$removee1"]);
Assert.AreEqual(3, i.M1());
Assert.AreEqual(3, id.M1());
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$M1"].As<Func<int>>()());
Assert.Null(c["M1"]);
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$M1"].As<Func<int>>()());
}
public class G8 : I2<BaseClass>
{
public int this[int idx]
{
get
{
return 1;
}
set
{
throw new NotImplementedException();
}
}
public int Prop1
{
get
{
return 2;
}
set
{
throw new NotImplementedException();
}
}
public event Action e1
{
add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }
}
public int M1()
{
return 3;
}
}
[Test]
public void TestG8()
{
var c = new G8();
I2<BaseClass> i = c;
I2<DerivedClass> id = c;
Assert.AreEqual(1, i[0]);
Assert.AreEqual(1, id[0]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$getItem"]);
Assert.NotNull(c["getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$getItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$setItem"]);
Assert.NotNull(c["setItem"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$setItem"]);
Assert.AreEqual(2, i.Prop1);
Assert.AreEqual(2, id.Prop1);
Assert.AreEqual(i.Prop1, c["Prop1"]);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$Prop1"]);
Assert.AreEqual(i.Prop1, c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$Prop1"]);
Assert.Throws<NotImplementedException>(() => { i.e1 += () => { }; });
Assert.Throws<NotImplementedException>(() => { id.e1 += () => { }; });
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$adde1"]);
Assert.NotNull(c["adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$adde1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$removee1"]);
Assert.NotNull(c["removee1"]);
Assert.NotNull(c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$removee1"]);
Assert.AreEqual(3, i.M1());
Assert.AreEqual(3, id.M1());
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$M1"].As<Func<int>>()());
Assert.AreEqual(i.M1(), c["M1"].As<Func<int>>()());
Assert.AreEqual(i.M1(), c["Bridge$ClientTest$Batch3$BridgeIssues$Bridge2638A$I2$1$" + baseClassAlias + "$M1"].As<Func<int>>()());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using ServiceStack.Text.Common;
using ServiceStack.Text.Jsv;
using ServiceStack.Text.Reflection;
namespace ServiceStack.Text
{
public class CsvSerializer
{
private static readonly UTF8Encoding UTF8EncodingWithoutBom = new UTF8Encoding(false);
private static Dictionary<Type, WriteObjectDelegate> WriteFnCache = new Dictionary<Type, WriteObjectDelegate>();
internal static WriteObjectDelegate GetWriteFn(Type type)
{
try
{
WriteObjectDelegate writeFn;
if (WriteFnCache.TryGetValue(type, out writeFn)) return writeFn;
var genericType = typeof(CsvSerializer<>).MakeGenericType(type);
var mi = genericType.GetMethod("WriteFn", BindingFlags.Public | BindingFlags.Static);
var writeFactoryFn = (Func<WriteObjectDelegate>)Delegate.CreateDelegate(
typeof(Func<WriteObjectDelegate>), mi);
writeFn = writeFactoryFn();
Dictionary<Type, WriteObjectDelegate> snapshot, newCache;
do
{
snapshot = WriteFnCache;
newCache = new Dictionary<Type, WriteObjectDelegate>(WriteFnCache);
newCache[type] = writeFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref WriteFnCache, newCache, snapshot), snapshot));
return writeFn;
}
catch (Exception ex)
{
Tracer.Instance.WriteError(ex);
throw;
}
}
public static string SerializeToCsv<T>(IEnumerable<T> records)
{
var sb = new StringBuilder();
using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture))
{
writer.WriteCsv(records);
return sb.ToString();
}
}
public static string SerializeToString<T>(T value)
{
if (value == null) return null;
if (typeof(T) == typeof(string)) return value as string;
var sb = new StringBuilder();
using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture))
{
CsvSerializer<T>.WriteObject(writer, value);
}
return sb.ToString();
}
public static void SerializeToWriter<T>(T value, TextWriter writer)
{
if (value == null) return;
if (typeof(T) == typeof(string))
{
writer.Write(value);
return;
}
CsvSerializer<T>.WriteObject(writer, value);
}
public static void SerializeToStream<T>(T value, Stream stream)
{
if (value == null) return;
using (var writer = new StreamWriter(stream, UTF8EncodingWithoutBom))
{
CsvSerializer<T>.WriteObject(writer, value);
}
}
public static void SerializeToStream(object obj, Stream stream)
{
if (obj == null) return;
using (var writer = new StreamWriter(stream, UTF8EncodingWithoutBom))
{
var writeFn = GetWriteFn(obj.GetType());
writeFn(writer, obj);
}
}
public static T DeserializeFromStream<T>(Stream stream)
{
throw new NotImplementedException();
}
public static object DeserializeFromStream(Type type, Stream stream)
{
throw new NotImplementedException();
}
public static void WriteLateBoundObject(TextWriter writer, object value)
{
if (value == null) return;
var writeFn = GetWriteFn(value.GetType());
writeFn(writer, value);
}
}
internal static class CsvSerializer<T>
{
private static readonly WriteObjectDelegate CacheFn;
public static WriteObjectDelegate WriteFn()
{
return CacheFn;
}
private const string IgnoreResponseStatus = "ResponseStatus";
private static Func<object, object> valueGetter = null;
private static WriteObjectDelegate writeElementFn = null;
private static WriteObjectDelegate GetWriteFn()
{
PropertyInfo firstCandidate = null;
Type bestCandidateEnumerableType = null;
PropertyInfo bestCandidate = null;
if (typeof(T).IsValueType)
{
return JsvWriter<T>.WriteObject;
}
//If type is an enumerable property itself write that
bestCandidateEnumerableType = typeof(T).GetTypeWithGenericTypeDefinitionOf(typeof(IEnumerable<>));
if (bestCandidateEnumerableType != null)
{
var elementType = bestCandidateEnumerableType.GetGenericArguments()[0];
writeElementFn = CreateWriteFn(elementType);
return WriteEnumerableType;
}
//Look for best candidate property if DTO
if (typeof(T).IsDto())
{
var properties = TypeConfig<T>.Properties;
foreach (var propertyInfo in properties)
{
if (propertyInfo.Name == IgnoreResponseStatus) continue;
if (propertyInfo.PropertyType == typeof(string)
|| propertyInfo.PropertyType.IsValueType
|| propertyInfo.PropertyType == typeof(byte[])) continue;
if (firstCandidate == null)
{
firstCandidate = propertyInfo;
}
var enumProperty = propertyInfo.PropertyType
.GetTypeWithGenericTypeDefinitionOf(typeof(IEnumerable<>));
if (enumProperty != null)
{
bestCandidateEnumerableType = enumProperty;
bestCandidate = propertyInfo;
break;
}
}
}
//If is not DTO or no candidates exist, write self
var noCandidatesExist = bestCandidate == null && firstCandidate == null;
if (noCandidatesExist)
{
return WriteSelf;
}
//If is DTO and has an enumerable property serialize that
if (bestCandidateEnumerableType != null)
{
valueGetter = bestCandidate.GetValueGetter(typeof(T));
var elementType = bestCandidateEnumerableType.GetGenericArguments()[0];
writeElementFn = CreateWriteFn(elementType);
return WriteEnumerableProperty;
}
//If is DTO and has non-enumerable, reference type property serialize that
valueGetter = firstCandidate.GetValueGetter(typeof(T));
writeElementFn = CreateWriteRowFn(firstCandidate.PropertyType);
return WriteNonEnumerableType;
}
private static WriteObjectDelegate CreateWriteFn(Type elementType)
{
return CreateCsvWriterFn(elementType, "WriteObject");
}
private static WriteObjectDelegate CreateWriteRowFn(Type elementType)
{
return CreateCsvWriterFn(elementType, "WriteObjectRow");
}
private static WriteObjectDelegate CreateCsvWriterFn(Type elementType, string methodName)
{
var genericType = typeof(CsvWriter<>).MakeGenericType(elementType);
var mi = genericType.GetMethod(methodName,
BindingFlags.Static | BindingFlags.Public);
var writeFn = (WriteObjectDelegate)Delegate.CreateDelegate(typeof(WriteObjectDelegate), mi);
return writeFn;
}
public static void WriteEnumerableType(TextWriter writer, object obj)
{
writeElementFn(writer, obj);
}
public static void WriteSelf(TextWriter writer, object obj)
{
CsvWriter<T>.WriteRow(writer, (T)obj);
}
public static void WriteEnumerableProperty(TextWriter writer, object obj)
{
if (obj == null) return; //AOT
var enumerableProperty = valueGetter(obj);
writeElementFn(writer, enumerableProperty);
}
public static void WriteNonEnumerableType(TextWriter writer, object obj)
{
var nonEnumerableType = valueGetter(obj);
writeElementFn(writer, nonEnumerableType);
}
static CsvSerializer()
{
if (typeof(T) == typeof(object))
{
CacheFn = CsvSerializer.WriteLateBoundObject;
}
else
{
CacheFn = GetWriteFn();
}
}
public static void WriteObject(TextWriter writer, object value)
{
CacheFn(writer, value);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis;
namespace Roslyn.Utilities
{
/// <summary>
/// A class that reads both primitive values and non-cyclical object graphs from a stream that was constructed using
/// the ObjectWriter class.
/// </summary>
internal sealed class ObjectReader : ObjectReaderWriterBase, IDisposable
{
private readonly BinaryReader _reader;
private readonly ObjectReaderData _dataMap;
private readonly ObjectBinder _binder;
internal ObjectReader(
Stream stream,
ObjectReaderData defaultData = null,
ObjectBinder binder = null)
{
// String serialization assumes both reader and writer to be of the same endianness.
// It can be adjusted for BigEndian if needed.
Debug.Assert(BitConverter.IsLittleEndian);
_reader = new BinaryReader(stream, Encoding.UTF8);
_dataMap = new ObjectReaderData(defaultData);
_binder = binder;
}
public void Dispose()
{
_dataMap.Dispose();
}
/// <summary>
/// Read a Boolean value from the stream. This value must have been written using <see cref="ObjectWriter.WriteBoolean(bool)"/>.
/// </summary>
public bool ReadBoolean()
{
return _reader.ReadBoolean();
}
/// <summary>
/// Read a Byte value from the stream. This value must have been written using <see cref="ObjectWriter.WriteByte(byte)"/>.
/// </summary>
public byte ReadByte()
{
return _reader.ReadByte();
}
/// <summary>
/// Read a Char value from the stream. This value must have been written using <see cref="ObjectWriter.WriteChar(char)"/>.
/// </summary>
public char ReadChar()
{
// char was written as UInt16 because BinaryWriter fails on characters that are unicode surrogates.
return (char)_reader.ReadUInt16();
}
/// <summary>
/// Read a Decimal value from the stream. This value must have been written using <see cref="ObjectWriter.WriteDecimal(decimal)"/>.
/// </summary>
public decimal ReadDecimal()
{
return _reader.ReadDecimal();
}
/// <summary>
/// Read a Double value from the stream. This value must have been written using <see cref="ObjectWriter.WriteDouble(double)"/>.
/// </summary>
public double ReadDouble()
{
return _reader.ReadDouble();
}
/// <summary>
/// Read a Single value from the stream. This value must have been written using <see cref="ObjectWriter.WriteSingle(float)"/>.
/// </summary>
public float ReadSingle()
{
return _reader.ReadSingle();
}
/// <summary>
/// Read a Int32 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteInt32(int)"/>.
/// </summary>
public int ReadInt32()
{
return _reader.ReadInt32();
}
/// <summary>
/// Read a Int64 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteInt64(long)"/>.
/// </summary>
public long ReadInt64()
{
return _reader.ReadInt64();
}
/// <summary>
/// Read a SByte value from the stream. This value must have been written using <see cref="ObjectWriter.WriteSByte(sbyte)"/>.
/// </summary>
public sbyte ReadSByte()
{
return _reader.ReadSByte();
}
/// <summary>
/// Read a Int16 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteInt16(short)"/>.
/// </summary>
public short ReadInt16()
{
return _reader.ReadInt16();
}
/// <summary>
/// Read a UInt32 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteUInt32(uint)"/>.
/// </summary>
public uint ReadUInt32()
{
return _reader.ReadUInt32();
}
/// <summary>
/// Read a UInt64 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteUInt64(ulong)"/>.
/// </summary>
public ulong ReadUInt64()
{
return _reader.ReadUInt64();
}
/// <summary>
/// Read a UInt16 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteUInt16(ushort)"/>.
/// </summary>
public ushort ReadUInt16()
{
return _reader.ReadUInt16();
}
/// <summary>
/// Read a DateTime value from the stream. This value must have been written using the <see cref="ObjectWriter.WriteDateTime(DateTime)"/>.
/// </summary>
public DateTime ReadDateTime()
{
return DateTime.FromBinary(this.ReadInt64());
}
/// <summary>
/// Read a compressed 30-bit integer value from the stream. This value must have been written using <see cref="ObjectWriter.WriteCompressedUInt(uint)"/>.
/// </summary>
public uint ReadCompressedUInt()
{
var info = _reader.ReadByte();
byte marker = (byte)(info & ByteMarkerMask);
byte byte0 = (byte)(info & ~ByteMarkerMask);
if (marker == Byte1Marker)
{
return byte0;
}
if (marker == Byte2Marker)
{
var byte1 = _reader.ReadByte();
return (((uint)byte0) << 8) | byte1;
}
if (marker == Byte4Marker)
{
var byte1 = _reader.ReadByte();
var byte2 = _reader.ReadByte();
var byte3 = _reader.ReadByte();
return (((uint)byte0) << 24) | (((uint)byte1) << 16) | (((uint)byte2) << 8) | byte3;
}
throw ExceptionUtilities.UnexpectedValue(marker);
}
/// <summary>
/// Read a value from the stream. The value must have been written using ObjectWriter.WriteValue.
/// </summary>
public object ReadValue()
{
var kind = (DataKind)_reader.ReadByte();
switch (kind)
{
case DataKind.Null:
return null;
case DataKind.Boolean_T:
return Boxes.BoxedTrue;
case DataKind.Boolean_F:
return Boxes.BoxedFalse;
case DataKind.Int8:
return _reader.ReadSByte();
case DataKind.UInt8:
return _reader.ReadByte();
case DataKind.Int16:
return _reader.ReadInt16();
case DataKind.UInt16:
return _reader.ReadUInt16();
case DataKind.Int32:
return _reader.ReadInt32();
case DataKind.Int32_B:
return (int)_reader.ReadByte();
case DataKind.Int32_S:
return (int)_reader.ReadUInt16();
case DataKind.Int32_Z:
return Boxes.BoxedInt32Zero;
case DataKind.UInt32:
return _reader.ReadUInt32();
case DataKind.Int64:
return _reader.ReadInt64();
case DataKind.UInt64:
return _reader.ReadUInt64();
case DataKind.Float4:
return _reader.ReadSingle();
case DataKind.Float8:
return _reader.ReadDouble();
case DataKind.Decimal:
return _reader.ReadDecimal();
case DataKind.DateTime:
return this.ReadDateTime();
case DataKind.Char:
return this.ReadChar();
case DataKind.StringUtf8:
case DataKind.StringUtf16:
case DataKind.StringRef:
case DataKind.StringRef_B:
case DataKind.StringRef_S:
return ReadString(kind);
case DataKind.Object_W:
case DataKind.ObjectRef:
case DataKind.ObjectRef_B:
case DataKind.ObjectRef_S:
return ReadObject(kind);
case DataKind.Type:
case DataKind.TypeRef:
case DataKind.TypeRef_B:
case DataKind.TypeRef_S:
return ReadType(kind);
case DataKind.Enum:
return ReadEnum();
case DataKind.Array:
case DataKind.Array_0:
case DataKind.Array_1:
case DataKind.Array_2:
case DataKind.Array_3:
return ReadArray(kind);
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
/// <summary>
/// Read a String value from the stream. This value must have been written using ObjectWriter.WriteString.
/// </summary>
public string ReadString()
{
var kind = (DataKind)_reader.ReadByte();
return kind == DataKind.Null ? null : ReadString(kind);
}
private string ReadString(DataKind kind)
{
switch (kind)
{
case DataKind.StringRef_B:
return (string)_dataMap.GetValue(_reader.ReadByte());
case DataKind.StringRef_S:
return (string)_dataMap.GetValue(_reader.ReadUInt16());
case DataKind.StringRef:
return (string)_dataMap.GetValue(_reader.ReadInt32());
case DataKind.StringUtf16:
case DataKind.StringUtf8:
return ReadStringLiteral(kind);
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private unsafe string ReadStringLiteral(DataKind kind)
{
int id = _dataMap.GetNextId();
string value;
if (kind == DataKind.StringUtf8)
{
value = _reader.ReadString();
}
else
{
// This is rare, just allocate UTF16 bytes for simplicity.
int characterCount = (int)ReadCompressedUInt();
byte[] bytes = _reader.ReadBytes(characterCount * sizeof(char));
fixed (byte* bytesPtr = bytes)
{
value = new string((char*)bytesPtr, 0, characterCount);
}
}
_dataMap.AddValue(id, value);
return value;
}
private Array ReadArray(DataKind kind)
{
int length;
switch (kind)
{
case DataKind.Array_0:
length = 0;
break;
case DataKind.Array_1:
length = 1;
break;
case DataKind.Array_2:
length = 2;
break;
case DataKind.Array_3:
length = 3;
break;
default:
length = (int)this.ReadCompressedUInt();
break;
}
var elementKind = (DataKind)_reader.ReadByte();
// optimization for primitive type array
Type elementType;
if (s_reverseTypeMap.TryGetValue(elementKind, out elementType))
{
return this.ReadPrimitiveTypeArrayElements(elementType, elementKind, length);
}
// custom type case
elementType = this.ReadType(elementKind);
Array array = Array.CreateInstance(elementType, length);
for (int i = 0; i < length; i++)
{
var value = this.ReadValue();
array.SetValue(value, i);
}
return array;
}
private Array ReadPrimitiveTypeArrayElements(Type type, DataKind kind, int length)
{
Debug.Assert(s_reverseTypeMap[kind] == type);
// optimizations for supported array type by binary reader
if (type == typeof(byte))
{
return _reader.ReadBytes(length);
}
if (type == typeof(char))
{
return _reader.ReadChars(length);
}
// optimizations for string where object reader/writer has its own mechanism to
// reduce duplicated strings
if (type == typeof(string))
{
return ReadPrimitiveTypeArrayElements(length, ReadString);
}
if (type == typeof(bool))
{
return ReadBooleanArray(length);
}
// otherwise, read elements directly from underlying binary writer
switch (kind)
{
case DataKind.Int8:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadSByte);
case DataKind.Int16:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadInt16);
case DataKind.Int32:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadInt32);
case DataKind.Int64:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadInt64);
case DataKind.UInt16:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadUInt16);
case DataKind.UInt32:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadUInt32);
case DataKind.UInt64:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadUInt64);
case DataKind.Float4:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadSingle);
case DataKind.Float8:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadDouble);
case DataKind.Decimal:
return ReadPrimitiveTypeArrayElements(length, _reader.ReadDecimal);
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private bool[] ReadBooleanArray(int length)
{
if (length == 0)
{
// simple check
return Array.Empty<bool>();
}
var array = new bool[length];
var wordLength = BitVector.WordsRequired(length);
var count = 0;
for (var i = 0; i < wordLength; i++)
{
var word = _reader.ReadUInt32();
for (var p = 0; p < BitVector.BitsPerWord; p++)
{
if (count >= length)
{
return array;
}
array[count++] = BitVector.IsTrue(word, p);
}
}
return array;
}
private static T[] ReadPrimitiveTypeArrayElements<T>(int length, Func<T> read)
{
if (length == 0)
{
// quick check
return Array.Empty<T>();
}
var array = new T[length];
for (var i = 0; i < array.Length; i++)
{
array[i] = read();
}
return array;
}
private Type ReadType()
{
var kind = (DataKind)_reader.ReadByte();
return ReadType(kind);
}
private Type ReadType(DataKind kind)
{
switch (kind)
{
case DataKind.TypeRef_B:
return (Type)_dataMap.GetValue(_reader.ReadByte());
case DataKind.TypeRef_S:
return (Type)_dataMap.GetValue(_reader.ReadUInt16());
case DataKind.TypeRef:
return (Type)_dataMap.GetValue(_reader.ReadInt32());
case DataKind.Type:
int id = _dataMap.GetNextId();
var assemblyName = this.ReadString();
var typeName = this.ReadString();
if (_binder == null)
{
throw NoBinderException(typeName);
}
var type = _binder.GetType(assemblyName, typeName);
_dataMap.AddValue(id, type);
return type;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private object ReadEnum()
{
var enumType = this.ReadType();
var type = Enum.GetUnderlyingType(enumType);
if (type == typeof(int))
{
return Enum.ToObject(enumType, _reader.ReadInt32());
}
if (type == typeof(short))
{
return Enum.ToObject(enumType, _reader.ReadInt16());
}
if (type == typeof(byte))
{
return Enum.ToObject(enumType, _reader.ReadByte());
}
if (type == typeof(long))
{
return Enum.ToObject(enumType, _reader.ReadInt64());
}
if (type == typeof(sbyte))
{
return Enum.ToObject(enumType, _reader.ReadSByte());
}
if (type == typeof(ushort))
{
return Enum.ToObject(enumType, _reader.ReadUInt16());
}
if (type == typeof(uint))
{
return Enum.ToObject(enumType, _reader.ReadUInt32());
}
if (type == typeof(ulong))
{
return Enum.ToObject(enumType, _reader.ReadUInt64());
}
throw ExceptionUtilities.UnexpectedValue(enumType);
}
private object ReadObject(DataKind kind)
{
switch (kind)
{
case DataKind.ObjectRef_B:
return _dataMap.GetValue(_reader.ReadByte());
case DataKind.ObjectRef_S:
return _dataMap.GetValue(_reader.ReadUInt16());
case DataKind.ObjectRef:
return _dataMap.GetValue(_reader.ReadInt32());
case DataKind.Object_W:
return this.ReadReadableObject();
case DataKind.Array:
return this.ReadArray(kind);
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private object ReadReadableObject()
{
int id = _dataMap.GetNextId();
Type type = this.ReadType();
var instance = CreateInstance(type);
_dataMap.AddValue(id, instance);
return instance;
}
private object CreateInstance(Type type)
{
if (_binder == null)
{
return NoBinderException(type.FullName);
}
var reader = _binder.GetReader(type);
if (reader == null)
{
return NoReaderException(type.FullName);
}
return reader(this);
}
private static Exception NoBinderException(string typeName)
{
#if COMPILERCORE
throw new InvalidOperationException(string.Format(CodeAnalysisResources.NoBinderException, typeName));
#else
throw new InvalidOperationException(string.Format(Microsoft.CodeAnalysis.WorkspacesResources.Cannot_deserialize_type_0_no_binder_supplied, typeName));
#endif
}
private static Exception NoReaderException(string typeName)
{
#if COMPILERCORE
throw new InvalidOperationException(string.Format(CodeAnalysisResources.NoReaderException, typeName));
#else
throw new InvalidOperationException(string.Format(Microsoft.CodeAnalysis.WorkspacesResources.Cannot_deserialize_type_0_it_has_no_deserialization_reader, typeName));
#endif
}
}
}
| |
#region MIT License
/*
* Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Collections.Generic;
namespace Physics2DDotNet.Ignorers
{
/// <summary>
/// A collection that stores ints that represent groups
/// </summary>
[Serializable]
public class GroupCollection : ICollection<int>
{
public static bool Intersect(GroupCollection groups1, GroupCollection groups2)
{
List<int> g1 = groups1.groups;
List<int> g2 = groups2.groups;
int index1 = 0;
int index2 = 0;
while (index1 < g1.Count && index2 < g2.Count)
{
if (g1[index1] == g2[index2])
{
return true;
}
else if (g1[index1] < g2[index2])
{
index1++;
}
else
{
index2++;
}
}
return false;
}
List<int> groups = new List<int>();
public GroupCollection()
{
groups = new List<int>();
}
public GroupCollection(GroupCollection copy)
{
this.groups = new List<int>(copy.groups);
}
/// <summary>
/// Gets the number of collison Groups the ignorer is part of.
/// </summary>
public int Count
{
get { return groups.Count; }
}
bool ICollection<int>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Trys to add a group.
/// </summary>
/// <param name="item">The group ID to add.</param>
/// <returns>false if the ignorer was already part of the group; otherwise false.</returns>
public bool Add(int item)
{
for (int index = 0; index < groups.Count; ++index)
{
if (groups[index] == item)
{
return false;
}
if (groups[index] > item)
{
groups.Insert(index, item);
return true;
}
}
groups.Add(item);
return true;
}
/// <summary>
/// adds an array of group ids.
/// </summary>
/// <param name="array">The array of group IDs. (this will be sorted)</param>
/// <returns>the number of IDs that were not already part of the group.</returns>
public int AddRange(int[] array)
{
if (array == null) { throw new ArgumentNullException("collection"); }
Array.Sort(array);
List<int> newGroups = new List<int>(groups.Count + array.Length);
int newIndex = 0;
int oldIndex = 0;
int index = 0;
int count = 0;
while ((newIndex < array.Length) && (oldIndex < groups.Count))
{
if (array[newIndex] == groups[oldIndex])
{
oldIndex++;
}
else if (array[newIndex] > groups[oldIndex])
{
newGroups.Add(groups[oldIndex]);
oldIndex++;
index++;
}
else
{
newGroups.Add(array[newIndex]);
newIndex++;
index++;
count++;
}
}
for (; newIndex < array.Length; ++newIndex)
{
if (index == 0 || newGroups[index - 1] != array[newIndex])
{
newGroups.Add(array[newIndex]);
index++;
count++;
}
}
for (; oldIndex < groups.Count; ++oldIndex)
{
if (index == 0 || newGroups[index - 1] != groups[oldIndex])
{
newGroups.Add(groups[oldIndex]);
index++;
}
}
this.groups = newGroups;
return count;
}
/// <summary>
/// returns true if the ignorer is part of the group.
/// </summary>
/// <param name="item">The group ID.</param>
/// <returns>true if the ignorer is part of the group; otherwise false.</returns>
public bool Contains(int item)
{
return groups.BinarySearch(item) >= 0;
}
/// <summary>
/// returns the number of groups in the array it is part of.
/// </summary>
/// <param name="array">The array of group IDs. (this will be sorted)</param>
/// <returns>The number of groups in the array it is part of.</returns>
public int ContainsRange(int[] array)
{
if (array == null) { throw new ArgumentNullException("collection"); }
Array.Sort(array);
int index1 = 0;
int index2 = 0;
int count = 0;
while (index1 < groups.Count && index2 < array.Length)
{
if (groups[index1] == array[index2])
{
count++;
index1++;
index2++;
}
else if (groups[index1] < array[index2])
{
index1++;
}
else
{
index2++;
}
}
return count;
}
/// <summary>
/// Trys to remove the ignorer from a group.
/// </summary>
/// <param name="item">The group ID.</param>
/// <returns>true if the ignore was part of the group; otherwise false.</returns>
public bool Remove(int item)
{
int index = groups.BinarySearch(item);
if (index < 0) { return false; }
groups.RemoveAt(index);
return true;
}
/// <summary>
/// Trys to remove the ignorer from a range of groups.
/// </summary>
/// <param name="array">The array of group IDs. (this will be sorted)</param>
/// <returns>the number of groups the ignore was removed from.</returns>
public int RemoveRange(int[] array)
{
if (array == null) { throw new ArgumentNullException("collection"); }
Array.Sort(array);
int index = 0;
return groups.RemoveAll(delegate(int value)
{
while (index < array.Length)
{
if (value == array[index])
{
index++;
return true;
}
else if (value > array[index])
{
index++;
}
else
{
return false;
}
}
return false;
});
}
/// <summary>
/// returns if the 2 ignores are not part of the same group.
/// </summary>
/// <param name="other">the other CollisionGroupIgnorer</param>
/// <returns>true if they are not part of the same group; otherwiase false.</returns>
void ICollection<int>.Add(int item)
{
Add(item);
}
/// <summary>
/// removes the ignorer from all groups.
/// </summary>
public void Clear()
{
groups.Clear();
}
public void CopyTo(int[] array, int arrayIndex)
{
groups.CopyTo(array, arrayIndex);
}
public IEnumerator<int> GetEnumerator()
{
return groups.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using Belikov.GenuineChannels.DotNetRemotingLayer;
using Belikov.GenuineChannels.Messaging;
using Belikov.GenuineChannels.TransportContext;
using Belikov.GenuineChannels.Utilities;
using Zyan.SafeDeserializationHelpers;
namespace Belikov.GenuineChannels.Security.SSPI
{
/// <summary>
/// Implements client-side SSPI Security Session that
/// establishes SSPI security context and can encrypt and/or sign content.
/// </summary>
public class SecuritySession_SspiClient : SecuritySession
{
/// <summary>
/// Constructs an instance of the SecuritySession_SspiClient class.
/// </summary>
/// <param name="name">The name of the Security Session.</param>
/// <param name="remote">The remote host.</param>
/// <param name="keyProvider_SspiClient">Parent KeyProvider_SspiClient instance to get settings from.</param>
public SecuritySession_SspiClient(string name, HostInformation remote, KeyProvider_SspiClient keyProvider_SspiClient)
: base(name, remote)
{
this.KeyProvider_SspiClient = keyProvider_SspiClient;
}
/// <summary>
/// Parent KeyProvider_SspiClient instance to get settings from.
/// </summary>
public KeyProvider_SspiClient KeyProvider_SspiClient;
/// <summary>
/// SSPI security context.
/// </summary>
public SspiClientSecurityContext SspiSecurityContext;
/// <summary>
/// Initialization process will be restarted if authentication was not finished within this
/// time span.
/// </summary>
public static TimeSpan MaxSpanToPerformAuthentication = TimeSpan.FromMinutes(3);
#region -- Establish security context ------------------------------------------------------
/// <summary>
/// Initiates or continues establishing of the Security Session.
/// Implementation notes: receiving of exceptions no more breaks up the connection like
/// it was in the previous versions.
/// </summary>
/// <param name="input">A null reference or an incoming stream.</param>
/// <param name="connectionLevel">Indicates whether the Security Session operates on connection level.</param>
/// <returns>A stream containing data for sending to the remote host or a null reference if Security Session is established.</returns>
public override GenuineChunkedStream EstablishSession(Stream input, bool connectionLevel)
{
bool passException = false;
// a dance is over
if (this.IsEstablished)
return null;
GenuineChunkedStream outputStream = null;
var binaryFormatter = new BinaryFormatter().Safe();
// skip the status flag
if (connectionLevel)
{
if (input != null)
input.ReadByte();
outputStream = new GenuineChunkedStream(false);
}
else
outputStream = this.CreateOutputStream();
// write session is being established flag
BinaryWriter binaryWriter = new BinaryWriter(outputStream);
binaryWriter.Write((byte) 0);
try
{
lock(this)
{
if (input == Stream.Null)
{
if (this.KeyProvider_SspiClient.DelegatedContext != null)
{
try
{
SspiApi.ImpersonateSecurityContext(this.KeyProvider_SspiClient.DelegatedContext.SspiSecurityContext._phContext);
// start new session
this.SspiSecurityContext = new SspiClientSecurityContext(this.KeyProvider_SspiClient);
binaryWriter.Write((byte) SspiPacketStatusFlags.InitializeFromScratch);
this.SspiSecurityContext.BuildUpSecurityContext(null, outputStream);
return outputStream;
}
finally
{
SspiApi.RevertSecurityContext(this.KeyProvider_SspiClient.DelegatedContext.SspiSecurityContext._phContext);
}
}
// start new session
this.SspiSecurityContext = new SspiClientSecurityContext(this.KeyProvider_SspiClient);
binaryWriter.Write((byte) SspiPacketStatusFlags.InitializeFromScratch);
this.SspiSecurityContext.BuildUpSecurityContext(null, outputStream);
return outputStream;
}
SspiPacketStatusFlags sspiPacketStatusFlags = (SspiPacketStatusFlags) input.ReadByte();
switch (sspiPacketStatusFlags)
{
case SspiPacketStatusFlags.ContinueAuthentication:
// continue building a security context
GenuineChunkedStream sspiData = new GenuineChunkedStream(false);
this.SspiSecurityContext.BuildUpSecurityContext(input, sspiData);
if (sspiData.Length == 0)
{
// SSPI session has been built up
outputStream.WriteByte((byte) SspiPacketStatusFlags.SessionEstablished);
this.SessionEstablished();
}
else
{
outputStream.WriteByte((byte) SspiPacketStatusFlags.ContinueAuthentication);
outputStream.WriteStream(sspiData);
}
return outputStream;
case SspiPacketStatusFlags.ExceptionThrown:
Exception receivedException = GenuineUtility.ReadException(input);
#if DEBUG
// this.Remote.ITransportContext.IEventLogger.Log(LogMessageCategory.Security, receivedException, "SecuritySession_SspiServer.EstablishSession",
// null, "SSPI initialization ends up with an exception at the remote host. Remote host: {0}.",
// this.Remote.ToString());
#endif
if (this.Remote != null)
this.Remote.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(
GenuineEventType.SecuritySessionFailed, receivedException, this.Remote, this));
this.DispatchException(receivedException);
passException = true;
throw receivedException;
case SspiPacketStatusFlags.ForceInitialization:
return this.EstablishSession(Stream.Null, connectionLevel);
case SspiPacketStatusFlags.InitializeFromScratch:
throw GenuineExceptions.Get_Processing_LogicError(
string.Format("The remote host must have the Security Session of the type SecuritySession_SspiServer registered with the name {0}. SecuritySession_SspiServer never sends SspiPacketMark.InitializeFromScratch packet marker.",
this.Name));
case SspiPacketStatusFlags.SessionEstablished:
this.SessionEstablished();
break;
}
}
}
catch(Exception opEx)
{
#if DEBUG
// this.Remote.ITransportContext.IEventLogger.Log(LogMessageCategory.Security, opEx, "SecuritySession_SspiServer.EstablishSession",
// null, "Exception was thrown while establishing security context.");
#endif
if (this.Remote != null)
this.Remote.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(
GenuineEventType.SecuritySessionFailed, opEx, this.Remote, this));
this.DispatchException(opEx);
if (passException)
throw;
binaryWriter.Write((byte) SspiPacketStatusFlags.ExceptionThrown);
binaryFormatter.Serialize(outputStream, opEx);
return outputStream;
}
return null;
}
#endregion
#region -- Cryptography --------------------------------------------------------------------
/// <summary>
/// Encrypts the message data and put a result into the specified output stream.
/// </summary>
/// <param name="input">The stream containing the serialized message.</param>
/// <param name="output">The result stream with the data being sent to the remote host.</param>
public override void Encrypt(Stream input, GenuineChunkedStream output)
{
// write session established flag
output.WriteByte(1);
// serialize messages into separate stream
this.SspiSecurityContext.EncryptMessage(input, output, this.KeyProvider_SspiClient.RequiredFeatures);
}
/// <summary>
/// Creates and returns a stream containing decrypted data.
/// </summary>
/// <param name="input">A stream containing encrypted data.</param>
/// <returns>A stream with decrypted data.</returns>
public override Stream Decrypt(Stream input)
{
if (input.ReadByte() == 0)
{
Stream outputStream = this.EstablishSession(input, false);
if (outputStream != null)
GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.SendMessage), outputStream, false);
return null;
}
return this.SspiSecurityContext.DecryptMessage(input, this.KeyProvider_SspiClient.RequiredFeatures);
}
#endregion
}
}
| |
//
// MultipartDocumentReader.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
/**
* Original iOS version by Jens Alfke
* Ported to Android by Marty Schoch, Traun Leyden
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Couchbase.Lite;
using Couchbase.Lite.Support;
using Couchbase.Lite.Util;
using Sharpen;
using System.Net.Http;
using System.Linq;
namespace Couchbase.Lite.Support
{
internal class MultipartDocumentReader : IMultipartReaderDelegate
{
/// <summary>The response which contains the input stream we need to read from</summary>
private HttpResponseMessage response;
private MultipartReader multipartReader;
private BlobStoreWriter curAttachment;
private List<Byte> jsonBuffer;
private IDictionary<String, Object> document;
private Database database;
private IDictionary<String, BlobStoreWriter> attachmentsByName;
private IDictionary<String, BlobStoreWriter> attachmentsByMd5Digest;
public MultipartDocumentReader(HttpResponseMessage response, Database database)
{
this.response = response;
this.database = database;
}
public IDictionary<String, Object> GetDocumentProperties()
{
return document;
}
public void ParseJsonBuffer()
{
try
{
document = Manager.GetObjectMapper().ReadValue<IDictionary<String, Object>>(jsonBuffer.ToArray());
}
catch (IOException e)
{
throw new InvalidOperationException("Failed to parse json buffer", e);
}
jsonBuffer = null;
}
public void SetContentType(String contentType)
{
if (!contentType.StartsWith ("multipart/", StringComparison.InvariantCultureIgnoreCase))
{
throw new ArgumentException("contentType must start with multipart/");
}
multipartReader = new MultipartReader(contentType, this);
attachmentsByName = new Dictionary<String, BlobStoreWriter>();
attachmentsByMd5Digest = new Dictionary<String, BlobStoreWriter>();
}
public void AppendData(byte[] data)
{
if (multipartReader != null)
{
multipartReader.AppendData(data);
}
else
{
jsonBuffer.AddRange(data);
}
}
public void Finish()
{
if (multipartReader != null)
{
if (!multipartReader.Finished())
{
throw new InvalidOperationException("received incomplete MIME multipart response");
}
RegisterAttachments();
}
else
{
ParseJsonBuffer();
}
}
private void RegisterAttachments()
{
var numAttachmentsInDoc = 0;
var attachments = (IDictionary<String, Object>)document.Get("_attachments");
if (attachments == null)
{
return;
}
foreach (var attachmentName in attachments.Keys)
{
var attachment = (IDictionary<String, Object>)attachments.Get(attachmentName);
int length = 0;
if (attachment.ContainsKey("length"))
{
length = ((int)attachment.Get("length"));
}
if (attachment.ContainsKey("encoded_length"))
{
length = ((int)attachment.Get("encoded_length"));
}
if (attachment.ContainsKey ("follows") && (bool)attachment.Get ("follows"))
{
// Check that each attachment in the JSON corresponds to an attachment MIME body.
// Look up the attachment by either its MIME Content-Disposition header or MD5 digest:
var digest = (String)attachment.Get("digest");
var writer = attachmentsByName.Get(attachmentName);
if (writer != null)
{
// Identified the MIME body by the filename in its Disposition header:
var actualDigest = writer.MD5DigestString();
if (digest != null && !digest.Equals(actualDigest) && !digest.Equals(writer.SHA1DigestString()))
{
var errMsg = String.Format("Attachment '{0}' has incorrect MD5 digest ({1}; should be {2})", attachmentName, digest, actualDigest);
throw new InvalidOperationException(errMsg);
}
attachment.Put("digest", actualDigest);
}
else
{
if (digest != null)
{
writer = attachmentsByMd5Digest.Get(digest);
if (writer == null)
{
var errMsg = String.Format("Attachment '{0}' does not appear in MIME body ", attachmentName);
throw new InvalidOperationException(errMsg);
}
}
else
{
if (attachments.Count == 1 && attachmentsByMd5Digest.Count == 1)
{
// Else there's only one attachment, so just assume it matches & use it:
writer = attachmentsByMd5Digest.Values.First();
attachment.Put("digest", writer.MD5DigestString());
}
else
{
// No digest metatata, no filename in MIME body; give up:
var errMsg = String.Format("Attachment '{0}' has no digest metadata; cannot identify MIME body", attachmentName);
throw new InvalidOperationException(errMsg);
}
}
}
// Check that the length matches:
if (writer.GetLength() != length)
{
var errMsg = String.Format("Attachment '{0}' has incorrect length field {1} (should be {2})", attachmentName, length, writer.GetLength());
throw new InvalidOperationException(errMsg);
}
++numAttachmentsInDoc;
}
else
{
if (attachment.ContainsKey("data") && length > 1000)
{
var msg = String.Format("Attachment '{0}' sent inline (len={1}). Large attachments "
+ "should be sent in MIME parts for reduced memory overhead.", attachmentName);
Log.W(Database.Tag, msg);
}
}
}
if (numAttachmentsInDoc < attachmentsByMd5Digest.Count)
{
var msg = String.Format("More MIME bodies ({0}) than attachments ({1}) ", attachmentsByMd5Digest.Count, numAttachmentsInDoc);
throw new InvalidOperationException(msg);
}
// hand over the (uninstalled) blobs to the database to remember:
database.RememberAttachmentWritersForDigests(attachmentsByMd5Digest);
}
public void StartedPart(IDictionary<String, String> headers)
{
if (document == null)
{
jsonBuffer = new List<Byte>(1024);
}
else
{
curAttachment = database.GetAttachmentWriter();
var contentDisposition = headers.Get("Content-Disposition");
if (contentDisposition != null && contentDisposition.StartsWith("attachment; filename="))
{
// TODO: Parse this less simplistically. Right now it assumes it's in exactly the same
// format generated by -[CBL_Pusher uploadMultipartRevision:]. CouchDB (as of 1.2) doesn't
// output any headers at all on attachments so there's no compatibility issue yet.
var contentDispositionUnquoted = Misc.UnquoteString(contentDisposition);
var name = contentDispositionUnquoted.Substring(21);
if (name != null)
{
attachmentsByName.Put(name, curAttachment);
}
}
}
}
public void AppendToPart(IEnumerable<Byte> data)
{
if (jsonBuffer != null)
{
jsonBuffer.AddRange(data);
}
else
{
curAttachment.AppendData(data.ToArray());
}
}
public void FinishedPart()
{
if (jsonBuffer != null)
{
ParseJsonBuffer();
}
else
{
curAttachment.Finish();
String md5String = curAttachment.MD5DigestString();
attachmentsByMd5Digest.Put(md5String, curAttachment);
curAttachment = null;
}
}
}
}
| |
//
// Copyright (c) 2012 Krueger Systems, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if false
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace SQLite
{
public partial class SQLiteAsyncConnection
{
SQLiteConnectionString _connectionString;
public SQLiteAsyncConnection (string databasePath, bool storeDateTimeAsTicks = false)
{
_connectionString = new SQLiteConnectionString (databasePath, storeDateTimeAsTicks);
}
SQLiteConnectionWithLock GetConnection ()
{
return SQLiteConnectionPool.Shared.GetConnection (_connectionString);
}
public Task<CreateTablesResult> CreateTableAsync<T> ()
where T : new ()
{
return CreateTablesAsync (typeof (T));
}
public Task<CreateTablesResult> CreateTablesAsync<T, T2> ()
where T : new ()
where T2 : new ()
{
return CreateTablesAsync (typeof (T), typeof (T2));
}
public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3> ()
where T : new ()
where T2 : new ()
where T3 : new ()
{
return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3));
}
public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4> ()
where T : new ()
where T2 : new ()
where T3 : new ()
where T4 : new ()
{
return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3), typeof (T4));
}
public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4, T5> ()
where T : new ()
where T2 : new ()
where T3 : new ()
where T4 : new ()
where T5 : new ()
{
return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5));
}
public Task<CreateTablesResult> CreateTablesAsync (params Type[] types)
{
return Task.Factory.StartNew (() => {
CreateTablesResult result = new CreateTablesResult ();
var conn = GetConnection ();
using (conn.Lock ()) {
foreach (Type type in types) {
int aResult = conn.CreateTable (type);
result.Results[type] = aResult;
}
}
return result;
});
}
public Task<int> DropTableAsync<T> ()
where T : new ()
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.DropTable<T> ();
}
});
}
public Task<int> InsertAsync (object item)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Insert (item);
}
});
}
public Task<int> UpdateAsync (object item)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Update (item);
}
});
}
public Task<int> DeleteAsync (object item)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Delete (item);
}
});
}
public Task<T> GetAsync<T>(object pk)
where T : new()
{
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.Get<T>(pk);
}
});
}
public Task<T> FindAsync<T> (object pk)
where T : new ()
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Find<T> (pk);
}
});
}
public Task<T> GetAsync<T> (Expression<Func<T, bool>> predicate)
where T : new()
{
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.Get<T> (predicate);
}
});
}
public Task<T> FindAsync<T> (Expression<Func<T, bool>> predicate)
where T : new ()
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Find<T> (predicate);
}
});
}
public Task<int> ExecuteAsync (string query, params object[] args)
{
return Task<int>.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Execute (query, args);
}
});
}
public Task<int> InsertAllAsync (IEnumerable items)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.InsertAll (items);
}
});
}
[Obsolete("Will cause a deadlock if any call in action ends up in a different thread. Use RunInTransactionAsync(Action<SQLiteConnection>) instead.")]
public Task RunInTransactionAsync (Action<SQLiteAsyncConnection> action)
{
return Task.Factory.StartNew (() => {
var conn = this.GetConnection ();
using (conn.Lock ()) {
conn.BeginTransaction ();
try {
action (this);
conn.Commit ();
}
catch (Exception) {
conn.Rollback ();
throw;
}
}
});
}
public Task RunInTransactionAsync(Action<SQLiteConnection> action)
{
return Task.Factory.StartNew(() =>
{
var conn = this.GetConnection();
using (conn.Lock())
{
conn.BeginTransaction();
try
{
action(conn);
conn.Commit();
}
catch (Exception)
{
conn.Rollback();
throw;
}
}
});
}
public AsyncTableQuery<T> Table<T> ()
where T : new ()
{
//
// This isn't async as the underlying connection doesn't go out to the database
// until the query is performed. The Async methods are on the query iteself.
//
var conn = GetConnection ();
return new AsyncTableQuery<T> (conn.Table<T> ());
}
public Task<T> ExecuteScalarAsync<T> (string sql, params object[] args)
{
return Task<T>.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
var command = conn.CreateCommand (sql, args);
return command.ExecuteScalar<T> ();
}
});
}
public Task<List<T>> QueryAsync<T> (string sql, params object[] args)
where T : new ()
{
return Task<List<T>>.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Query<T> (sql, args);
}
});
}
}
//
// TODO: Bind to AsyncConnection.GetConnection instead so that delayed
// execution can still work after a Pool.Reset.
//
public class AsyncTableQuery<T>
where T : new ()
{
TableQuery<T> _innerQuery;
public AsyncTableQuery (TableQuery<T> innerQuery)
{
_innerQuery = innerQuery;
}
public AsyncTableQuery<T> Where (Expression<Func<T, bool>> predExpr)
{
return new AsyncTableQuery<T> (_innerQuery.Where (predExpr));
}
public AsyncTableQuery<T> Skip (int n)
{
return new AsyncTableQuery<T> (_innerQuery.Skip (n));
}
public AsyncTableQuery<T> Take (int n)
{
return new AsyncTableQuery<T> (_innerQuery.Take (n));
}
public AsyncTableQuery<T> OrderBy<U> (Expression<Func<T, U>> orderExpr)
{
return new AsyncTableQuery<T> (_innerQuery.OrderBy<U> (orderExpr));
}
public AsyncTableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr)
{
return new AsyncTableQuery<T> (_innerQuery.OrderByDescending<U> (orderExpr));
}
public Task<List<T>> ToListAsync ()
{
return Task.Factory.StartNew (() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.ToList ();
}
});
}
public Task<int> CountAsync ()
{
return Task.Factory.StartNew (() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.Count ();
}
});
}
public Task<T> ElementAtAsync (int index)
{
return Task.Factory.StartNew (() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.ElementAt (index);
}
});
}
public Task<T> FirstAsync ()
{
return Task<T>.Factory.StartNew(() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.First ();
}
});
}
public Task<T> FirstOrDefaultAsync ()
{
return Task<T>.Factory.StartNew(() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.FirstOrDefault ();
}
});
}
}
public class CreateTablesResult
{
public Dictionary<Type, int> Results { get; private set; }
internal CreateTablesResult ()
{
this.Results = new Dictionary<Type, int> ();
}
}
class SQLiteConnectionPool
{
class Entry
{
public SQLiteConnectionString ConnectionString { get; private set; }
public SQLiteConnectionWithLock Connection { get; private set; }
public Entry (SQLiteConnectionString connectionString)
{
ConnectionString = connectionString;
Connection = new SQLiteConnectionWithLock (connectionString);
}
public void OnApplicationSuspended ()
{
Connection.Dispose ();
Connection = null;
}
}
readonly Dictionary<string, Entry> _entries = new Dictionary<string, Entry> ();
readonly object _entriesLock = new object ();
static readonly SQLiteConnectionPool _shared = new SQLiteConnectionPool ();
/// <summary>
/// Gets the singleton instance of the connection tool.
/// </summary>
public static SQLiteConnectionPool Shared
{
get
{
return _shared;
}
}
public SQLiteConnectionWithLock GetConnection (SQLiteConnectionString connectionString)
{
lock (_entriesLock) {
Entry entry;
string key = connectionString.ConnectionString;
if (!_entries.TryGetValue (key, out entry)) {
entry = new Entry (connectionString);
_entries[key] = entry;
}
return entry.Connection;
}
}
/// <summary>
/// Closes all connections managed by this pool.
/// </summary>
public void Reset ()
{
lock (_entriesLock) {
foreach (var entry in _entries.Values) {
entry.OnApplicationSuspended ();
}
_entries.Clear ();
}
}
/// <summary>
/// Call this method when the application is suspended.
/// </summary>
/// <remarks>Behaviour here is to close any open connections.</remarks>
public void ApplicationSuspended ()
{
Reset ();
}
}
class SQLiteConnectionWithLock : SQLiteConnection
{
readonly object _lockPoint = new object ();
public SQLiteConnectionWithLock (SQLiteConnectionString connectionString)
: base (connectionString.DatabasePath, connectionString.StoreDateTimeAsTicks)
{
}
public IDisposable Lock ()
{
return new LockWrapper (_lockPoint);
}
private class LockWrapper : IDisposable
{
object _lockPoint;
public LockWrapper (object lockPoint)
{
_lockPoint = lockPoint;
Monitor.Enter (_lockPoint);
}
public void Dispose ()
{
Monitor.Exit (_lockPoint);
}
}
}
}
#endif
| |
#if !UNIX
//
// Copyright (C) Microsoft. All rights reserved.
//
using System.Globalization;
using System.Management.Automation.Internal;
using System.Collections.Generic;
namespace System.Management.Automation.Tracing
{
/// <summary>
/// ETW logging API
/// </summary>
internal static class PSEtwLog
{
private static PSEtwLogProvider provider;
/// <summary>
/// Class constructor
/// </summary>
static PSEtwLog()
{
provider = new PSEtwLogProvider();
}
/// <summary>
/// Provider interface function for logging health event
/// </summary>
/// <param name="logContext"></param>
/// <param name="eventId"></param>
/// <param name="exception"></param>
/// <param name="additionalInfo"></param>
///
internal static void LogEngineHealthEvent(LogContext logContext, int eventId, Exception exception, Dictionary<String, String> additionalInfo)
{
provider.LogEngineHealthEvent(logContext, eventId, exception, additionalInfo);
}
/// <summary>
/// Provider interface function for logging engine lifecycle event
/// </summary>
/// <param name="logContext"></param>
/// <param name="newState"></param>
/// <param name="previousState"></param>
///
internal static void LogEngineLifecycleEvent(LogContext logContext, EngineState newState, EngineState previousState)
{
provider.LogEngineLifecycleEvent(logContext, newState, previousState);
}
/// <summary>
/// Provider interface function for logging command health event
/// </summary>
/// <param name="logContext"></param>
/// <param name="exception"></param>
internal static void LogCommandHealthEvent(LogContext logContext, Exception exception)
{
provider.LogCommandHealthEvent(logContext, exception);
}
/// <summary>
/// Provider interface function for logging command lifecycle event
/// </summary>
/// <param name="logContext"></param>
/// <param name="newState"></param>
///
internal static void LogCommandLifecycleEvent(LogContext logContext, CommandState newState)
{
provider.LogCommandLifecycleEvent(() => logContext, newState);
}
/// <summary>
/// Provider interface function for logging pipeline execution detail.
/// </summary>
/// <param name="logContext"></param>
/// <param name="pipelineExecutionDetail"></param>
internal static void LogPipelineExecutionDetailEvent(LogContext logContext, List<String> pipelineExecutionDetail)
{
provider.LogPipelineExecutionDetailEvent(logContext, pipelineExecutionDetail);
}
/// <summary>
/// Provider interface function for logging provider health event
/// </summary>
/// <param name="logContext"></param>
/// <param name="providerName"></param>
/// <param name="exception"></param>
internal static void LogProviderHealthEvent(LogContext logContext, string providerName, Exception exception)
{
provider.LogProviderHealthEvent(logContext, providerName, exception);
}
/// <summary>
/// Provider interface function for logging provider lifecycle event
/// </summary>
/// <param name="logContext"></param>
/// <param name="providerName"></param>
/// <param name="newState"></param>
///
internal static void LogProviderLifecycleEvent(LogContext logContext, string providerName, ProviderState newState)
{
provider.LogProviderLifecycleEvent(logContext, providerName, newState);
}
/// <summary>
/// Provider interface function for logging settings event
/// </summary>
/// <param name="logContext"></param>
/// <param name="variableName"></param>
/// <param name="value"></param>
/// <param name="previousValue"></param>
///
internal static void LogSettingsEvent(LogContext logContext, string variableName, string value, string previousValue)
{
provider.LogSettingsEvent(logContext, variableName, value, previousValue);
}
/// <summary>
/// Logs information to the operational channel
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogOperationalInformation(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Informational, task, keyword, args);
}
/// <summary>
/// Logs information to the operational channel
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Warning, task, keyword, args);
}
/// <summary>
/// Logs Verbose to the operational channel
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Verbose, task, keyword, args);
}
/// <summary>
/// Logs error message to the analytic channel
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogAnalyticError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Error, task, keyword, args);
}
/// <summary>
/// Logs warning message to the analytic channel
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogAnalyticWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Warning, task, keyword, args);
}
/// <summary>
/// Logs remoting fragment data to verbose channel.
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="objectId"></param>
/// <param name="fragmentId"></param>
/// <param name="isStartFragment"></param>
/// <param name="isEndFragment"></param>
/// <param name="fragmentLength"></param>
/// <param name="fragmentData"></param>
internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword,
Int64 objectId,
Int64 fragmentId,
int isStartFragment,
int isEndFragment,
UInt32 fragmentLength,
PSETWBinaryBlob fragmentData)
{
if (provider.IsEnabled(PSLevel.Verbose, keyword))
{
string payLoadData = BitConverter.ToString(fragmentData.blob, fragmentData.offset, fragmentData.length);
payLoadData = string.Format(CultureInfo.InvariantCulture, "0x{0}", payLoadData.Replace("-", ""));
provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword,
objectId, fragmentId, isStartFragment, isEndFragment, fragmentLength,
payLoadData);
}
}
/// <summary>
/// Logs verbose message to the analytic channel
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, args);
}
/// <summary>
/// Logs informational message to the analytic channel
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Informational, task, keyword, args);
}
/// <summary>
/// Logs error message to operation channel.
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="keyword"></param>
/// <param name="args"></param>
internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args)
{
provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Error, task, keyword, args);
}
/// <summary>
/// Logs error message to the operational channel
/// </summary>
/// <param name="id"></param>
/// <param name="opcode"></param>
/// <param name="task"></param>
/// <param name="logContext"></param>
/// <param name="payLoad"></param>
internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad)
{
provider.WriteEvent(id, PSChannel.Operational, opcode, task, logContext, payLoad);
}
internal static void SetActivityIdForCurrentThread(Guid newActivityId)
{
provider.SetActivityIdForCurrentThread(newActivityId);
}
internal static void ReplaceActivityIdForCurrentThread(Guid newActivityId,
PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task)
{
// set the new activity id
provider.SetActivityIdForCurrentThread(newActivityId);
// Once the activity id is set, write the transfer event
WriteTransferEvent(newActivityId, eventForOperationalChannel, eventForAnalyticChannel, keyword, task);
}
/// <summary>
/// Writes a transfer event mapping current activity id
/// with a related activity id
/// This function writes a transfer event for both the
/// operational and analytic channels
/// </summary>
/// <param name="relatedActivityId"></param>
/// <param name="eventForOperationalChannel"></param>
/// <param name="eventForAnalyticChannel"></param>
/// <param name="keyword"></param>
/// <param name="task"></param>
internal static void WriteTransferEvent(Guid relatedActivityId, PSEventId eventForOperationalChannel,
PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task)
{
provider.WriteEvent(eventForOperationalChannel, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, task,
PSKeyword.UseAlwaysOperational);
provider.WriteEvent(eventForAnalyticChannel, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, task,
PSKeyword.UseAlwaysAnalytic);
}
/// <summary>
/// Writes a transfer event
/// </summary>
/// <param name="parentActivityId"></param>
internal static void WriteTransferEvent(Guid parentActivityId)
{
provider.WriteTransferEvent(parentActivityId);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml;
using IdSharp.Common.Utils;
namespace IdSharp.WebLookup.Amazon
{
/// <summary>
/// Amazon images
/// </summary>
public class AmazonImages : INotifyPropertyChanged
{
private readonly AmazonServer _amazonServer;
private readonly string _awsAccessKeyId;
private readonly string _secretAccessKey;
private readonly string _asin;
private bool _imageUrlsDownloaded;
private bool _smallImageDownloaded;
private bool _mediumImageDownloaded;
private bool _largeImageDownloaded;
private byte[] _smallImageBytes;
private byte[] _mediumImageBytes;
private byte[] _largeImageBytes;
private string _smallImageUrl;
private string _mediumImageUrl;
private string _largeImageUrl;
private bool? _hasImage;
private Size? _largestImageSize;
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
internal AmazonImages(AmazonServer server, string awsAccessKeyId, string secretAccessKey, string asin)
{
if (string.IsNullOrWhiteSpace(awsAccessKeyId))
throw new ArgumentNullException("awsAccessKeyId");
if (string.IsNullOrWhiteSpace(secretAccessKey))
throw new ArgumentNullException("secretAccessKey");
if (string.IsNullOrWhiteSpace(asin))
throw new ArgumentNullException("asin");
_amazonServer = server;
_awsAccessKeyId = awsAccessKeyId;
_secretAccessKey = secretAccessKey;
_asin = asin;
}
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Gets the small image URL.
/// </summary>
/// <value>The small image URL.</value>
public string SmallImageUrl
{
get
{
GetImageUrls();
return _smallImageUrl;
}
}
/// <summary>
/// Gets the medium image URL.
/// </summary>
/// <value>The medium image URL.</value>
public string MediumImageUrl
{
get
{
GetImageUrls();
return _mediumImageUrl;
}
}
/// <summary>
/// Gets the large image URL.
/// </summary>
/// <value>The large image URL.</value>
public string LargeImageUrl
{
get
{
GetImageUrls();
return _largeImageUrl;
}
}
/// <summary>
/// Gets the small image.
/// </summary>
public byte[] SmallImageBytes
{
get
{
GetSmallImage();
return _smallImageBytes;
}
}
/// <summary>
/// Gets the medium image.
/// </summary>
public byte[] MediumImageBytes
{
get
{
GetMediumImage();
return _mediumImageBytes;
}
}
/// <summary>
/// Gets the large image.
/// </summary>
public byte[] LargeImageBytes
{
get
{
GetLargeImage();
return _largeImageBytes;
}
}
/// <summary>
/// Gets the largest image.
/// </summary>
public byte[] GetLargestImageBytes()
{
byte[] imageBytes = LargeImageBytes;
if (imageBytes == null)
imageBytes = MediumImageBytes;
if (imageBytes == null)
imageBytes = SmallImageBytes;
if (imageBytes == null)
{
HasImage = false;
LargestImageSize = Size.Empty;
}
else
{
try
{
ImageSource imageSource = GetImageSourceFromBytes(imageBytes);
LargestImageSize = new Size(imageSource.Width, imageSource.Height);
}
catch
{
}
HasImage = true;
}
return imageBytes;
}
/// <summary>
/// Gets a value indicating where this instance contains images. Returns <c>null</c> if unchecked.
/// </summary>
/// <value>A value indicating where this instance contains images. Returns <c>null</c> if unchecked.</value>
public bool? HasImage
{
get { return _hasImage; }
private set
{
if (_hasImage != value)
{
_hasImage = value;
OnPropertyChanged("HasImage");
}
}
}
/// <summary>
/// Gets the largest image size. Returns <c>null</c> if unchecked.
/// </summary>
/// <value>The largest image size. Returns <c>null</c> if unchecked.</value>
public Size? LargestImageSize
{
get { return _largestImageSize; }
set
{
if (_largestImageSize != value)
{
_largestImageSize = value;
OnPropertyChanged("LargestImageSize");
}
}
}
/// <summary>
/// Gets an <see cref="ImageSource"/> from an array of bytes.
/// </summary>
/// <param name="imageBytes">The array of bytes.</param>
/// <returns>An <see cref="ImageSource"/> from an array of bytes.</returns>
public static ImageSource GetImageSourceFromBytes(byte[] imageBytes)
{
if (imageBytes == null)
return null;
MemoryStream ms = new MemoryStream(imageBytes);
BitmapImage src = new BitmapImage();
src.BeginInit();
src.StreamSource = ms;
src.EndInit();
return src;
}
private void GetSmallImage()
{
if (_smallImageDownloaded)
return;
GetImageUrls();
if (_smallImageUrl != null)
{
_smallImageBytes = Http.Get(_smallImageUrl);
}
_smallImageDownloaded = true;
}
private void GetMediumImage()
{
if (_mediumImageDownloaded)
return;
GetImageUrls();
if (_mediumImageUrl != null)
{
_mediumImageBytes = Http.Get(_mediumImageUrl);
}
_mediumImageDownloaded = true;
}
private void GetLargeImage()
{
if (_largeImageDownloaded)
return;
GetImageUrls();
if (_largeImageUrl != null)
{
_largeImageBytes = Http.Get(_largeImageUrl);
}
_largeImageDownloaded = true;
}
private void GetImageUrls()
{
// TODO: Good candidate for System.Xml.Linq
if (_imageUrlsDownloaded)
return;
List<PostData> postData = new List<PostData>();
postData.Add(new PostData("Service", "AWSECommerceService"));
postData.Add(new PostData("AWSAccessKeyId", _awsAccessKeyId));
postData.Add(new PostData("Operation", "ItemLookup"));
postData.Add(new PostData("ItemId", _asin));
postData.Add(new PostData("ResponseGroup", "Images"));
postData.Add(new PostData("Timestamp", string.Format("{0:yyyy-MM-dd}T{0:HH:mm:ss}Z", DateTime.UtcNow)));
string amazonDomain = Amazon.GetDomain(_amazonServer);
string hostHeader = string.Format("ecs.{0}", amazonDomain);
string signature = Amazon.GetSignature(postData, hostHeader, _secretAccessKey);
postData.Add(new PostData("Signature", signature));
//postData = GetOrderedPostData(postData);
string requestUri = String.Format("http://{0}{1}", hostHeader, Amazon.HttpRequestUri);
requestUri = Http.GetQueryString(requestUri, postData);
byte[] byteResponse = Http.Get(requestUri);
string response = Encoding.UTF8.GetString(byteResponse);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(response);
foreach (XmlNode node in xmlDocument.ChildNodes)
{
if (node.Name == "ItemLookupResponse")
{
foreach (XmlNode responseNode in node.ChildNodes)
{
if (responseNode.Name == "Items")
{
foreach (XmlNode itemNode in responseNode.ChildNodes)
{
if (itemNode.Name == "Item")
{
foreach (XmlNode itemDetail in itemNode.ChildNodes)
{
if (itemDetail.Name == "SmallImage")
{
foreach (XmlNode imageNode in itemDetail.ChildNodes)
{
if (imageNode.Name == "URL")
_smallImageUrl = imageNode.InnerText;
}
}
else if (itemDetail.Name == "MediumImage")
{
foreach (XmlNode imageNode in itemDetail.ChildNodes)
{
if (imageNode.Name == "URL")
_mediumImageUrl = imageNode.InnerText;
}
}
else if (itemDetail.Name == "LargeImage")
{
foreach (XmlNode imageNode in itemDetail.ChildNodes)
{
if (imageNode.Name == "URL")
_largeImageUrl = imageNode.InnerText;
}
}
}
}
}
}
}
}
}
_imageUrlsDownloaded = true;
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Internal
{
using System;
using System.Collections;
using System.Collections.Generic;
#if DYNAMIC_OBJECT
using System.Dynamic;
#endif
using System.Linq;
using System.Reflection;
using NLog.Common;
using NLog.Config;
/// <summary>
/// Converts object into a List of property-names and -values using reflection
/// </summary>
internal class ObjectReflectionCache : IObjectTypeTransformer
{
readonly MruCache<Type, ObjectPropertyInfos> _objectTypeCache = new MruCache<Type, ObjectPropertyInfos>(10000);
private IObjectTypeTransformer ObjectTypeTransformation => _objectTypeTransformation ?? (_objectTypeTransformation = ConfigurationItemFactory.Default.ObjectTypeTransformer);
private IObjectTypeTransformer _objectTypeTransformation;
public static IObjectTypeTransformer Instance { get; } = new ObjectReflectionCache();
object IObjectTypeTransformer.TryTransformObject(object obj)
{
return null;
}
public ObjectPropertyList LookupObjectProperties(object value)
{
if (TryLookupExpandoObject(value, out var propertyValues))
{
return propertyValues;
}
if (!ReferenceEquals(ObjectTypeTransformation, Instance))
{
var result = ObjectTypeTransformation.TryTransformObject(value);
if (result != null)
{
if (result is IConvertible)
{
return new ObjectPropertyList(result, ObjectPropertyInfos.SimpleToString.Properties, ObjectPropertyInfos.SimpleToString.FastLookup);
}
if (TryLookupExpandoObject(result, out propertyValues))
{
return propertyValues;
}
value = result;
}
}
var objectType = value.GetType();
var propertyInfos = BuildObjectPropertyInfos(value, objectType);
_objectTypeCache.TryAddValue(objectType, propertyInfos);
return new ObjectPropertyList(value, propertyInfos.Properties, propertyInfos.FastLookup);
}
public bool TryLookupExpandoObject(object value, out ObjectPropertyList objectPropertyList)
{
if (value is IDictionary<string, object> expando)
{
objectPropertyList = new ObjectPropertyList(expando);
return true;
}
#if DYNAMIC_OBJECT
if (value is DynamicObject d)
{
var dictionary = DynamicObjectToDict(d);
objectPropertyList = new ObjectPropertyList(dictionary);
return true;
}
#endif
Type objectType = value.GetType();
if (_objectTypeCache.TryGetValue(objectType, out var propertyInfos))
{
if (!propertyInfos.HasFastLookup)
{
var fastLookup = BuildFastLookup(propertyInfos.Properties, false);
propertyInfos = new ObjectPropertyInfos(propertyInfos.Properties, fastLookup);
_objectTypeCache.TryAddValue(objectType, propertyInfos);
}
objectPropertyList = new ObjectPropertyList(value, propertyInfos.Properties, propertyInfos.FastLookup);
return true;
}
if (TryExtractExpandoObject(objectType, out propertyInfos))
{
_objectTypeCache.TryAddValue(objectType, propertyInfos);
objectPropertyList = new ObjectPropertyList(value, propertyInfos.Properties, propertyInfos.FastLookup);
return true;
}
objectPropertyList = default(ObjectPropertyList);
return false;
}
private static bool TryExtractExpandoObject(Type objectType, out ObjectPropertyInfos propertyInfos)
{
foreach (var interfaceType in objectType.GetInterfaces())
{
if (interfaceType.IsGenericType() && interfaceType.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
if (interfaceType.GetGenericArguments()[0] == typeof(string))
{
var dictionaryEnumerator = (IDictionaryEnumerator)Activator.CreateInstance(typeof(DictionaryEnumerator<,>).MakeGenericType(interfaceType.GetGenericArguments()));
propertyInfos = new ObjectPropertyInfos(null, new[] { new FastPropertyLookup(string.Empty, TypeCode.Object, (o, p) => dictionaryEnumerator.GetEnumerator(o)) });
return true;
}
}
}
propertyInfos = default(ObjectPropertyInfos);
return false;
}
private static ObjectPropertyInfos BuildObjectPropertyInfos(object value, Type objectType)
{
ObjectPropertyInfos propertyInfos;
if (ConvertSimpleToString(objectType))
{
propertyInfos = ObjectPropertyInfos.SimpleToString;
}
else
{
var properties = GetPublicProperties(objectType);
if (value is Exception)
{
// Special handling of Exception (Include Exception-Type as artificial first property)
var fastLookup = BuildFastLookup(properties, true);
propertyInfos = new ObjectPropertyInfos(properties, fastLookup);
}
else if (properties.Length == 0)
{
propertyInfos = ObjectPropertyInfos.SimpleToString;
}
else
{
propertyInfos = new ObjectPropertyInfos(properties, null);
}
}
return propertyInfos;
}
private static bool ConvertSimpleToString(Type objectType)
{
if (typeof(IFormattable).IsAssignableFrom(objectType))
return true;
if (typeof(Uri).IsAssignableFrom(objectType))
return true;
if (typeof(MemberInfo).IsAssignableFrom(objectType))
return true;
if (typeof(Assembly).IsAssignableFrom(objectType))
return true;
return false;
}
private static PropertyInfo[] GetPublicProperties(Type type)
{
PropertyInfo[] properties = null;
try
{
properties = type.GetProperties(PublicProperties);
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "Failed to get object properties for type: {0}", type);
}
// Skip Index-Item-Properties (Ex. public string this[int Index])
if (properties != null)
{
foreach (var prop in properties)
{
if (!prop.IsValidPublicProperty())
{
properties = properties.Where(p => p.IsValidPublicProperty()).ToArray();
break;
}
}
}
return properties ?? ArrayHelper.Empty<PropertyInfo>();
}
private static FastPropertyLookup[] BuildFastLookup(PropertyInfo[] properties, bool includeType)
{
int fastAccessIndex = includeType ? 1 : 0;
FastPropertyLookup[] fastLookup = new FastPropertyLookup[properties.Length + fastAccessIndex];
if (includeType)
{
fastLookup[0] = new FastPropertyLookup("Type", TypeCode.String, (o, p) => o.GetType().ToString());
}
foreach (var prop in properties)
{
var getterMethod = prop.GetGetMethod();
Type propertyType = getterMethod.ReturnType;
ReflectionHelpers.LateBoundMethod valueLookup = ReflectionHelpers.CreateLateBoundMethod(getterMethod);
#if NETSTANDARD1_3
TypeCode typeCode = propertyType == typeof(string) ? TypeCode.String : (propertyType == typeof(int) ? TypeCode.Int32 : TypeCode.Object);
#else
TypeCode typeCode = Type.GetTypeCode(propertyType); // Skip cyclic-reference checks when not TypeCode.Object
#endif
fastLookup[fastAccessIndex++] = new FastPropertyLookup(prop.Name, typeCode, valueLookup);
}
return fastLookup;
}
private const BindingFlags PublicProperties = BindingFlags.Instance | BindingFlags.Public;
public struct ObjectPropertyList : IEnumerable<ObjectPropertyList.PropertyValue>
{
internal static readonly StringComparer NameComparer = StringComparer.Ordinal;
private static readonly FastPropertyLookup[] CreateIDictionaryEnumerator = new[] { new FastPropertyLookup(string.Empty, TypeCode.Object, (o, p) => ((IDictionary<string, object>)o).GetEnumerator()) };
private readonly object _object;
private readonly PropertyInfo[] _properties;
private readonly FastPropertyLookup[] _fastLookup;
public struct PropertyValue
{
public readonly string Name;
public readonly object Value;
public TypeCode TypeCode => Value == null ? TypeCode.Empty : _typecode;
private readonly TypeCode _typecode;
public PropertyValue(string name, object value, TypeCode typeCode)
{
Name = name;
Value = value;
_typecode = typeCode;
}
public PropertyValue(object owner, PropertyInfo propertyInfo)
{
Name = propertyInfo.Name;
Value = propertyInfo.GetValue(owner, null);
_typecode = TypeCode.Object;
}
public PropertyValue(object owner, FastPropertyLookup fastProperty)
{
Name = fastProperty.Name;
Value = fastProperty.ValueLookup(owner, null);
_typecode = fastProperty.TypeCode;
}
}
public bool ConvertToString => _properties?.Length == 0;
internal ObjectPropertyList(object value, PropertyInfo[] properties, FastPropertyLookup[] fastLookup)
{
_object = value;
_properties = properties;
_fastLookup = fastLookup;
}
public ObjectPropertyList(IDictionary<string, object> value)
{
_object = value; // Expando objects
_properties = null;
_fastLookup = CreateIDictionaryEnumerator;
}
public bool TryGetPropertyValue(string name, out PropertyValue propertyValue)
{
if (_properties != null)
{
if (_fastLookup != null)
{
return TryFastLookupPropertyValue(name, out propertyValue);
}
else
{
return TrySlowLookupPropertyValue(name, out propertyValue);
}
}
else if (_object is IDictionary<string, object> expandoObject)
{
if (expandoObject.TryGetValue(name, out var objectValue))
{
propertyValue = new PropertyValue(name, objectValue, TypeCode.Object);
return true;
}
propertyValue = default(PropertyValue);
return false;
}
else
{
return TryListLookupPropertyValue(name, out propertyValue);
}
}
/// <summary>
/// Scans properties for name (Skips string-compare and value-lookup until finding match)
/// </summary>
private bool TryFastLookupPropertyValue(string name, out PropertyValue propertyValue)
{
int nameHashCode = NameComparer.GetHashCode(name);
foreach (var fastProperty in _fastLookup)
{
if (fastProperty.NameHashCode == nameHashCode && NameComparer.Equals(fastProperty.Name, name))
{
propertyValue = new PropertyValue(_object, fastProperty);
return true;
}
}
propertyValue = default(PropertyValue);
return false;
}
/// <summary>
/// Scans properties for name (Skips property value lookup until finding match)
/// </summary>
private bool TrySlowLookupPropertyValue(string name, out PropertyValue propertyValue)
{
foreach (var propInfo in _properties)
{
if (NameComparer.Equals(propInfo.Name, name))
{
propertyValue = new PropertyValue(_object, propInfo);
return true;
}
}
propertyValue = default(PropertyValue);
return false;
}
/// <summary>
/// Scans properties for name
/// </summary>
private bool TryListLookupPropertyValue(string name, out PropertyValue propertyValue)
{
foreach (var item in this)
{
if (NameComparer.Equals(item.Name, name))
{
propertyValue = item;
return true;
}
}
propertyValue = default(PropertyValue);
return false;
}
public override string ToString()
{
return _object?.ToString() ?? "null";
}
public Enumerator GetEnumerator()
{
if (_properties != null)
return new Enumerator(_object, _properties, _fastLookup);
else
return new Enumerator((IEnumerator<KeyValuePair<string, object>>)_fastLookup[0].ValueLookup(_object, null));
}
IEnumerator<PropertyValue> IEnumerable<PropertyValue>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public struct Enumerator : IEnumerator<PropertyValue>
{
private readonly object _owner;
private readonly PropertyInfo[] _properties;
private readonly FastPropertyLookup[] _fastLookup;
private readonly IEnumerator<KeyValuePair<string, object>> _enumerator;
private int _index;
internal Enumerator(object owner, PropertyInfo[] properties, FastPropertyLookup[] fastLookup)
{
_owner = owner;
_properties = properties;
_fastLookup = fastLookup;
_index = -1;
_enumerator = null;
}
internal Enumerator(IEnumerator<KeyValuePair<string, object>> enumerator)
{
_owner = enumerator;
_properties = null;
_fastLookup = null;
_index = 0;
_enumerator = enumerator;
}
public PropertyValue Current
{
get
{
try
{
if (_fastLookup != null)
return new PropertyValue(_owner, _fastLookup[_index]);
else if (_properties != null)
return new PropertyValue(_owner, _properties[_index]);
else
return new PropertyValue(_enumerator.Current.Key, _enumerator.Current.Value, TypeCode.Object);
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "Failed to get property value for object: {0}", _owner);
return default(PropertyValue);
}
}
}
object IEnumerator.Current => Current;
public void Dispose()
{
_enumerator?.Dispose();
}
public bool MoveNext()
{
if (_properties != null)
return ++_index < (_fastLookup?.Length ?? _properties.Length);
else
return _enumerator.MoveNext();
}
public void Reset()
{
if (_properties != null)
_index = -1;
else
_enumerator.Reset();
}
}
}
internal struct FastPropertyLookup
{
public readonly string Name;
public readonly ReflectionHelpers.LateBoundMethod ValueLookup;
public readonly TypeCode TypeCode;
public readonly int NameHashCode;
public FastPropertyLookup(string name, TypeCode typeCode, ReflectionHelpers.LateBoundMethod valueLookup)
{
Name = name;
ValueLookup = valueLookup;
TypeCode = typeCode;
NameHashCode = ObjectPropertyList.NameComparer.GetHashCode(name);
}
}
private struct ObjectPropertyInfos : IEquatable<ObjectPropertyInfos>
{
public readonly PropertyInfo[] Properties;
public readonly FastPropertyLookup[] FastLookup;
public static readonly ObjectPropertyInfos SimpleToString = new ObjectPropertyInfos(ArrayHelper.Empty<PropertyInfo>(), ArrayHelper.Empty<FastPropertyLookup>());
public ObjectPropertyInfos(PropertyInfo[] properties, FastPropertyLookup[] fastLookup)
{
Properties = properties;
FastLookup = fastLookup;
}
public bool HasFastLookup => FastLookup != null;
public bool Equals(ObjectPropertyInfos other)
{
return ReferenceEquals(Properties, other.Properties) && FastLookup?.Length == other.FastLookup?.Length;
}
}
#if DYNAMIC_OBJECT
private static Dictionary<string, object> DynamicObjectToDict(DynamicObject d)
{
var newVal = new Dictionary<string, object>();
foreach (var propName in d.GetDynamicMemberNames())
{
if (d.TryGetMember(new GetBinderAdapter(propName), out var result))
{
newVal[propName] = result;
}
}
return newVal;
}
/// <summary>
/// Binder for retrieving value of <see cref="DynamicObject"/>
/// </summary>
private sealed class GetBinderAdapter : GetMemberBinder
{
internal GetBinderAdapter(string name)
: base(name, false)
{
}
/// <inheritdoc />
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
return target;
}
}
#endif
private interface IDictionaryEnumerator
{
IEnumerator<KeyValuePair<string,object>> GetEnumerator(object value);
}
private static readonly IDictionary<string, object> EmptyDictionary = new NLog.Internal.SortHelpers.ReadOnlySingleBucketDictionary<string, object>();
internal sealed class DictionaryEnumerator<TKey, TValue> : IDictionaryEnumerator
{
public IEnumerator<KeyValuePair<string, object>> GetEnumerator(object value)
{
if (value is IDictionary<TKey, TValue> dictionary)
{
return YieldEnumerator(dictionary);
}
return EmptyDictionary.GetEnumerator();
}
private IEnumerator<KeyValuePair<string, object>> YieldEnumerator(IDictionary<TKey,TValue> dictionary)
{
foreach (var item in dictionary)
yield return new KeyValuePair<string, object>(item.Key.ToString(), item.Value);
}
}
}
}
| |
//------------------------------------------------------------------------------
//
// <copyright file="CompositionTarget.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
//
// History:
// 03/22/2004 : ABaioura - Created.
//
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Diagnostics;
using System.Threading;
using System.Windows.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Automation.Provider;
using System.Windows.Media.Composition;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Security;
using MS.Internal;
using MS.Win32;
using MS.Utility;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Media
{
/// <summary>
///
/// </summary>
/// <SecurityNote>
/// CompositionTarget subclassing is not allowed in Partial Trust - Demands UIPermissionWindow.AllWindows for inheritance
/// </SecurityNote>
[UIPermissionAttribute(SecurityAction.InheritanceDemand,Window=UIPermissionWindow.AllWindows)]
public abstract class CompositionTarget : DispatcherObject, IDisposable, ICompositionTarget
{
//
// Data types for communicating state information between
// CompositionTarget and its host.
//
internal enum HostStateFlags : uint
{
None = 0,
WorldTransform = 1,
ClipBounds = 2
};
//----------------------------------------------------------------------
//
// Constructors
//
//----------------------------------------------------------------------
#region Constructors
/// <summary>
/// CompositionTarget
/// </summary>
internal CompositionTarget()
{
#if TRACE_MVR
markVisibleCountTotal = 0;
#endif
}
/// <summary>
/// This method is used to create all uce resources either on Startup or session connect
/// </summary>
internal virtual void CreateUCEResources(DUCE.Channel channel, DUCE.Channel outOfBandChannel)
{
Debug.Assert(channel != null);
Debug.Assert(!_contentRoot.IsOnChannel(channel));
Debug.Assert(outOfBandChannel != null);
Debug.Assert(!_contentRoot.IsOnChannel(outOfBandChannel));
//
// Create root visual on the current channel and send
// this command out of band to ensure that composition node is
// created by the time this visual target is available for hosting
// and to avoid life-time issues when we are working with this node
// from the different channels.
//
bool resourceCreated = _contentRoot.CreateOrAddRefOnChannel(this, outOfBandChannel, s_contentRootType);
Debug.Assert(resourceCreated);
_contentRoot.DuplicateHandle(outOfBandChannel, channel);
outOfBandChannel.CloseBatch();
outOfBandChannel.Commit();
}
/// <summary>
/// This method is used to release all uce resources either on Shutdown or session disconnect
/// </summary>
internal virtual void ReleaseUCEResources(DUCE.Channel channel, DUCE.Channel outOfBandChannel)
{
if (_rootVisual.Value != null)
{
((DUCE.IResource)(_rootVisual.Value)).ReleaseOnChannel(channel);
}
//
// Release the root visual.
//
if (_contentRoot.IsOnChannel(channel))
{
_contentRoot.ReleaseOnChannel(channel);
}
if (_contentRoot.IsOnChannel(outOfBandChannel))
{
_contentRoot.ReleaseOnChannel(outOfBandChannel);
}
}
#endregion Constructors
//----------------------------------------------------------------------
//
// Public Methods
//
//----------------------------------------------------------------------
#region Public Methods
/// <summary>
/// Disposes CompositionTarget.
/// </summary>
public virtual void Dispose()
{
//
// Here we cannot use VerifyAPI methods because they check
// for the disposed state.
//
VerifyAccess();
if (!_isDisposed)
{
//
// Disconnect the root visual so that all of the child
// animations and resources are cleaned up.
//
_isDisposed = true;
GC.SuppressFinalize(this);
}
}
/// <summary>
/// Returns true if the CompositionTarget is disposed; otherwise returns false.
/// </summary>
internal bool IsDisposed { get { return _isDisposed; } }
#endregion Public Methods
//----------------------------------------------------------------------
//
// Public Properties
//
//----------------------------------------------------------------------
#region Public Properties
/// <summary>
/// Gets and sets the root Visual of the CompositionTarget.
/// </summary>
/// <value></value>
/// <remarks>
/// Callers must have UIPermission(UIPermissionWindow.AllWindows) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: This code sets a rootvisual which is risky to do because
/// it can destabilize assumptions made in popup code
/// PublicOK: The getter is safe and the setter has a link demand and is critical
/// </SecurityNote>
public virtual Visual RootVisual
{
[SecurityCritical]
get
{
VerifyAPIReadOnly();
return (_rootVisual.Value);
}
[UIPermissionAttribute(SecurityAction.LinkDemand,Window=UIPermissionWindow.AllWindows)]
[SecurityCritical]
set
{
VerifyAPIReadWrite();
if (_rootVisual.Value != value)
{
SetRootVisual(value);
MediaContext.From(Dispatcher).PostRender();
}
}
}
/// <summary>
/// Returns matrix that can be used to transform coordinates from this
/// target to the rendering destination device.
/// </summary>
public abstract Matrix TransformToDevice { get; }
/// <summary>
/// Returns matrix that can be used to transform coordinates from
/// the rendering destination device to this target.
/// </summary>
public abstract Matrix TransformFromDevice { get; }
#endregion Public Properties
//----------------------------------------------------------------------
//
// Internal Methods
//
//----------------------------------------------------------------------
#region Internal Methods
/// <summary>
///
/// </summary>
internal object StateChangedCallback(object arg)
{
object[] argArray = arg as object[];
HostStateFlags stateFlags = (HostStateFlags)argArray[0];
//
// Check if world transform of the host has changed and
// update cached value accordingly.
//
if ((stateFlags & HostStateFlags.WorldTransform) != 0)
{
_worldTransform = (Matrix)argArray[1];
}
//
// Check if clip bounds have changed, update cached value.
//
if ((stateFlags & HostStateFlags.ClipBounds) != 0)
{
_worldClipBounds = (Rect)argArray[2];
}
//
// Set corresponding flags on the root visual and schedule
// render if one has not already been scheduled.
//
if (_rootVisual.Value != null)
{
//
// When replacing the root visual, we need to re-realize all
// content in the new tree
//
Visual.PropagateFlags(
_rootVisual.Value,
VisualFlags.IsSubtreeDirtyForPrecompute,
VisualProxyFlags.IsSubtreeDirtyForRender
);
}
return null;
}
void ICompositionTarget.AddRefOnChannel(DUCE.Channel channel, DUCE.Channel outOfBandChannel)
{
// create all uce resources.
CreateUCEResources(channel, outOfBandChannel);
}
void ICompositionTarget.ReleaseOnChannel(DUCE.Channel channel, DUCE.Channel outOfBandChannel)
{
// release all the uce resources.
ReleaseUCEResources(channel, outOfBandChannel);
}
/// <summary>
/// Render method renders the visual tree.
/// </summary>
//[CodeAnalysis("AptcaMethodsShouldOnlyCallAptcaMethods")] //Tracking Bug: 29647
void ICompositionTarget.Render(bool inResize, DUCE.Channel channel)
{
#if DEBUG_CLR_MEM
bool clrTracingEnabled = false;
if (CLRProfilerControl.ProcessIsUnderCLRProfiler &&
(CLRProfilerControl.CLRLoggingLevel >= CLRProfilerControl.CLRLogState.Performance))
{
clrTracingEnabled = true;
++_renderCLRPass;
CLRProfilerControl.CLRLogWriteLine("Begin_FullRender_{0}", _renderCLRPass);
}
#endif // DEBUG_CLR_MEM
//
// Now we render the scene
//
#if MEDIA_PERFORMANCE_COUNTERS
_frameRateTimer.Begin();
#endif
if (_rootVisual.Value != null)
{
bool etwTracingEnabled = false;
if (EventTrace.IsEnabled(EventTrace.Keyword.KeywordGeneral | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info))
{
etwTracingEnabled = true;
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientPrecomputeSceneBegin, EventTrace.Keyword.KeywordGraphics | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info, PerfService.GetPerfElementID(this));
}
#if MEDIA_PERFORMANCE_COUNTERS
_precomputeRateTimer.Begin();
#endif
// precompute is channel agnostic
_rootVisual.Value.Precompute();
#if MEDIA_PERFORMANCE_COUNTERS
_precomputeRateTimer.End();
#endif
if (etwTracingEnabled)
{
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientPrecomputeSceneEnd, EventTrace.Keyword.KeywordGraphics | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info);
}
#if DEBUG
MediaTrace.RenderPass.Trace("Full Update");
#endif
if (etwTracingEnabled)
{
EventTrace.EventProvider.TraceEvent(
EventTrace.Event.WClientCompileSceneBegin, EventTrace.Keyword.KeywordGraphics | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info, PerfService.GetPerfElementID(this));
}
#if MEDIA_PERFORMANCE_COUNTERS
_renderRateTimer.Begin();
#endif
Compile(channel);
#if MEDIA_PERFORMANCE_COUNTERS
_renderRateTimer.End();
#endif
if (etwTracingEnabled)
{
EventTrace.EventProvider.TraceEvent(
EventTrace.Event.WClientCompileSceneEnd, EventTrace.Keyword.KeywordGraphics | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info);
}
}
#if DEBUG_CLR_MEM
if (clrTracingEnabled &&
CLRProfilerControl.CLRLoggingLevel >= CLRProfilerControl.CLRLogState.Performance)
{
CLRProfilerControl.CLRLogWriteLine("End_FullRender_{0}", _renderCLRPass);
}
#endif // DEBUG_CLR_MEM
#if MEDIA_PERFORMANCE_COUNTERS
_frameRateTimer.End();
System.Console.WriteLine("RENDERING PERFORMANCE DATA");
System.Console.WriteLine("Frame rendering time: " + _frameRateTimer.TimeOfLastPeriod + "ms");
System.Console.WriteLine("Frame precompute time: " + _precomputeRateTimer.TimeOfLastPeriod + "ms");
System.Console.WriteLine("Frame render time: " + _renderRateTimer.TimeOfLastPeriod + "ms");
#endif
}
#endregion Internal Methods
//----------------------------------------------------------------------
//
// Internal Properties
//
//----------------------------------------------------------------------
#region Internal Properties
internal DUCE.MultiChannelResource _contentRoot = new DUCE.MultiChannelResource();
internal const DUCE.ResourceType s_contentRootType = DUCE.ResourceType.TYPE_VISUAL;
/// <summary>
///
/// </summary>
internal Matrix WorldTransform
{
get
{
return _worldTransform;
}
}
internal Rect WorldClipBounds
{
get
{
return _worldClipBounds;
}
}
#endregion Internal Properties
//----------------------------------------------------------------------
//
// Private Methods
//
//----------------------------------------------------------------------
#region Private Methods
/// <summary>
/// The compile method transforms the Visual Scene Graph into the Composition Scene Graph.
/// </summary>
/// <SecurityNote>
/// Critical - calls critical code, access critical resources (handles)
/// TreatAsSafe - safe to compile the visual at anytime
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private void Compile(DUCE.Channel channel)
{
MediaContext mctx = MediaContext.From(Dispatcher);
Invariant.Assert(_rootVisual.Value!=null);
// 1) Check if we have a cached render context.
// 2) Initialize the render context.
// 3) Call to render the scene graph (transforming it into the composition scene graph).
// 4) Deinitalize the render context and cache it if possible.
// ------------------------------------------------------------------------------------
// 1) Get cached render context if possible.
// For performance reasons the render context is cached between frames. Here we check if
// we have a cached one. If we don't we just create a new one. If we do have one, we use
// the render context. Note that we null out the _cachedRenderContext field. This means
// that in failure cases we will always recreate the render context.
RenderContext rc = null;
Invariant.Assert(channel != null);
if (_cachedRenderContext != null)
{
rc = _cachedRenderContext;
_cachedRenderContext = null;
}
else
{
rc = new RenderContext();
}
// ------------------------------------------------------------------------------------
// 2) Prepare the render context.
rc.Initialize(channel, _contentRoot.GetHandle(channel));
// ------------------------------------------------------------------------------------
// 3) Compile the scene.
if (mctx.IsConnected)
{
_rootVisual.Value.Render(rc, 0);
}
// ------------------------------------------------------------------------------------
// 4) Cache the render context.
Debug.Assert(_cachedRenderContext == null);
_cachedRenderContext = rc;
}
/// <summary>
/// Internal method to set the root visual.
/// </summary>
/// <param name="visual">Root visual, can be null, but can not be a child of another
/// Visual.</param>
/// <SecurityNote>
/// Critical - calls critical code, access critical resources
/// TreatAsSafe - safe to reparent a visual
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private void SetRootVisual(Visual visual)
{
//
if (visual != null &&
(visual._parent != null
|| visual.IsRootElement))
{
// If a Visual has already a parent it can not be the root in a CompositionTarget because
// otherwise we would have two CompositionTargets party on the same Visual tree.
// If want to allow this we need to explicitly add support for this.
throw new System.ArgumentException(SR.Get(SRID.CompositionTarget_RootVisual_HasParent));
}
DUCE.ChannelSet channelSet = MediaContext.From(Dispatcher).GetChannels();
DUCE.Channel channel = channelSet.Channel;
if (_rootVisual.Value != null && _contentRoot.IsOnChannel(channel))
{
ClearRootNode(channel);
((DUCE.IResource)_rootVisual.Value).ReleaseOnChannel(channel);
_rootVisual.Value.IsRootElement = false;
}
_rootVisual.Value = visual;
if (_rootVisual.Value != null)
{
_rootVisual.Value.IsRootElement = true;
_rootVisual.Value.SetFlagsOnAllChannels(
true,
VisualProxyFlags.IsSubtreeDirtyForRender);
}
}
/// <summary>
/// Removes all children from the current root node.
/// </summary>
private void ClearRootNode(DUCE.Channel channel)
{
//
// Currently we enqueue this command on the channel immediately
// because if we put it in the delayed release queue, then
// the _contentRoot might have been disposed by the time we
// process the queue.
//
// Note: Currently we might flicker when replacing the root of the
// compositionTarget.
DUCE.CompositionNode.RemoveAllChildren(
_contentRoot.GetHandle(channel),
channel);
}
/// <summary>
/// Verifies that the CompositionTarget can be accessed.
/// </summary>
internal void VerifyAPIReadOnly()
{
VerifyAccess();
if (_isDisposed)
{
throw new System.ObjectDisposedException("CompositionTarget");
}
}
/// <summary>
/// Verifies that the CompositionTarget can be accessed.
/// </summary>
internal void VerifyAPIReadWrite()
{
VerifyAccess();
if (_isDisposed)
{
throw new System.ObjectDisposedException("CompositionTarget");
}
MediaContext.From(Dispatcher).VerifyWriteAccess();
}
#endregion
//----------------------------------------------------------------------
//
// Private Fields
//
//----------------------------------------------------------------------
#region Private Fields
private bool _isDisposed;
private SecurityCriticalDataForSet<Visual> _rootVisual;
private RenderContext _cachedRenderContext;
private Matrix _worldTransform = Matrix.Identity;
//
// ISSUE-ABaioura-10/19/2004: For now we assume a very large client
// rect, because currently clip infromation cannot be robustly
// communicated from the host. When this is fixed, we can start off
// an empty rect; clip bounds will be updated based on the host clip.
//
private Rect _worldClipBounds = new Rect(
Double.MinValue / 2.0,
Double.MinValue / 2.0,
Double.MaxValue,
Double.MaxValue);
#if DEBUG_CLR_MEM
//
// Used for CLRProfiler comments.
//
private static int _renderCLRPass = 0;
#endif // DEBUG_CLR_MEM
#if MEDIA_PERFORMANCE_COUNTERS
private HFTimer _frameRateTimer;
private HFTimer _precomputeRateTimer;
private HFTimer _renderRateTimer;
#endif
#endregion Private Fields
//----------------------------------------------------------------------
//
// Static Events
//
//----------------------------------------------------------------------
#region Static Events
/// <summary>
/// Rendering event. Registers a delegate to be notified after animation and layout but before rendering
/// </summary>
public static event EventHandler Rendering
{
add
{
MediaContext mc = MediaContext.From(Dispatcher.CurrentDispatcher);
mc.Rendering += value;
// We need to get a new rendering operation queued.
mc.PostRender();
}
remove
{
MediaContext mc = MediaContext.From(Dispatcher.CurrentDispatcher);
mc.Rendering -= value;
}
}
#endregion
}
}
| |
namespace Azure.AI.Language.Conversations
{
public partial class AnalyzeConversationOptions
{
public AnalyzeConversationOptions(string projectName, string deploymentName, string query) { }
public string DeploymentName { get { throw null; } }
public string DirectTarget { get { throw null; } set { } }
public bool? IsLoggingEnabled { get { throw null; } set { } }
public string Language { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, Azure.AI.Language.Conversations.Models.AnalyzeParameters> Parameters { get { throw null; } }
public string ProjectName { get { throw null; } }
public string Query { get { throw null; } }
public bool? Verbose { get { throw null; } set { } }
}
public partial class ConversationAnalysisClient
{
protected ConversationAnalysisClient() { }
public ConversationAnalysisClient(System.Uri endpoint, Azure.AzureKeyCredential credential) { }
public ConversationAnalysisClient(System.Uri endpoint, Azure.AzureKeyCredential credential, Azure.AI.Language.Conversations.ConversationAnalysisClientOptions options) { }
public virtual System.Uri Endpoint { get { throw null; } }
public virtual Azure.Response<Azure.AI.Language.Conversations.Models.AnalyzeConversationResult> AnalyzeConversation(Azure.AI.Language.Conversations.AnalyzeConversationOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.AI.Language.Conversations.Models.AnalyzeConversationResult> AnalyzeConversation(string projectName, string deploymentName, string query, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.AI.Language.Conversations.Models.AnalyzeConversationResult>> AnalyzeConversationAsync(Azure.AI.Language.Conversations.AnalyzeConversationOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.AI.Language.Conversations.Models.AnalyzeConversationResult>> AnalyzeConversationAsync(string projectName, string deploymentName, string query, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class ConversationAnalysisClientOptions : Azure.Core.ClientOptions
{
public ConversationAnalysisClientOptions(Azure.AI.Language.Conversations.ConversationAnalysisClientOptions.ServiceVersion version = Azure.AI.Language.Conversations.ConversationAnalysisClientOptions.ServiceVersion.V2021_07_15_Preview) { }
public enum ServiceVersion
{
V2021_07_15_Preview = 1,
}
}
}
namespace Azure.AI.Language.Conversations.Models
{
public partial class AnalyzeConversationResult
{
internal AnalyzeConversationResult() { }
public string DetectedLanguage { get { throw null; } }
public Azure.AI.Language.Conversations.Models.BasePrediction Prediction { get { throw null; } }
public string Query { get { throw null; } }
}
public partial class AnalyzeParameters
{
public AnalyzeParameters() { }
public string ApiVersion { get { throw null; } set { } }
}
public partial class BasePrediction
{
internal BasePrediction() { }
public Azure.AI.Language.Conversations.Models.ProjectKind ProjectKind { get { throw null; } set { } }
public string TopIntent { get { throw null; } }
}
public static partial class ConversationsModelFactory
{
public static Azure.AI.Language.Conversations.Models.AnalyzeConversationResult AnalyzeConversationResult(string query = null, string detectedLanguage = null, Azure.AI.Language.Conversations.Models.BasePrediction prediction = null) { throw null; }
public static Azure.AI.Language.Conversations.Models.BasePrediction BasePrediction(Azure.AI.Language.Conversations.Models.ProjectKind projectKind = default(Azure.AI.Language.Conversations.Models.ProjectKind), string topIntent = null) { throw null; }
public static Azure.AI.Language.Conversations.Models.DeepstackEntity DeepstackEntity(string category = null, string text = null, int offset = 0, int length = 0, float confidenceScore = 0f, System.Collections.Generic.IEnumerable<Azure.AI.Language.Conversations.Models.DeepStackEntityResolution> resolution = null) { throw null; }
public static Azure.AI.Language.Conversations.Models.DeepStackEntityResolution DeepStackEntityResolution(Azure.AI.Language.Conversations.Models.ResolutionKind resolutionKind = default(Azure.AI.Language.Conversations.Models.ResolutionKind), System.Collections.Generic.IReadOnlyDictionary<string, object> additionalProperties = null) { throw null; }
public static Azure.AI.Language.Conversations.Models.DeepstackIntent DeepstackIntent(string category = null, float confidenceScore = 0f) { throw null; }
public static Azure.AI.Language.Conversations.Models.DeepstackPrediction DeepstackPrediction(Azure.AI.Language.Conversations.Models.ProjectKind projectKind = default(Azure.AI.Language.Conversations.Models.ProjectKind), string topIntent = null, System.Collections.Generic.IEnumerable<Azure.AI.Language.Conversations.Models.DeepstackIntent> intents = null, System.Collections.Generic.IEnumerable<Azure.AI.Language.Conversations.Models.DeepstackEntity> entities = null) { throw null; }
public static Azure.AI.Language.Conversations.Models.DeepstackResult DeepstackResult(string query = null, string detectedLanguage = null, Azure.AI.Language.Conversations.Models.DeepstackPrediction prediction = null) { throw null; }
public static Azure.AI.Language.Conversations.Models.DictionaryNormalizedValueResolution DictionaryNormalizedValueResolution(Azure.AI.Language.Conversations.Models.ResolutionKind resolutionKind = default(Azure.AI.Language.Conversations.Models.ResolutionKind), System.Collections.Generic.IReadOnlyDictionary<string, object> additionalProperties = null, System.Collections.Generic.IEnumerable<string> values = null) { throw null; }
public static Azure.AI.Language.Conversations.Models.DSTargetIntentResult DSTargetIntentResult(Azure.AI.Language.Conversations.Models.TargetKind targetKind = default(Azure.AI.Language.Conversations.Models.TargetKind), string apiVersion = null, double confidenceScore = 0, Azure.AI.Language.Conversations.Models.DeepstackResult result = null) { throw null; }
public static Azure.AI.Language.Conversations.Models.LuisTargetIntentResult LuisTargetIntentResult(Azure.AI.Language.Conversations.Models.TargetKind targetKind = default(Azure.AI.Language.Conversations.Models.TargetKind), string apiVersion = null, double confidenceScore = 0, object result = null) { throw null; }
public static Azure.AI.Language.Conversations.Models.QuestionAnsweringTargetIntentResult QuestionAnsweringTargetIntentResult(Azure.AI.Language.Conversations.Models.TargetKind targetKind = default(Azure.AI.Language.Conversations.Models.TargetKind), string apiVersion = null, double confidenceScore = 0, object result = null) { throw null; }
public static Azure.AI.Language.Conversations.Models.TargetIntentResult TargetIntentResult(Azure.AI.Language.Conversations.Models.TargetKind targetKind = default(Azure.AI.Language.Conversations.Models.TargetKind), string apiVersion = null, double confidenceScore = 0) { throw null; }
public static Azure.AI.Language.Conversations.Models.WorkflowPrediction WorkflowPrediction(Azure.AI.Language.Conversations.Models.ProjectKind projectKind = default(Azure.AI.Language.Conversations.Models.ProjectKind), string topIntent = null, System.Collections.Generic.IReadOnlyDictionary<string, Azure.AI.Language.Conversations.Models.TargetIntentResult> intents = null) { throw null; }
}
public partial class DeepstackCallingOptions
{
public DeepstackCallingOptions() { }
public bool? IsLoggingEnabled { get { throw null; } set { } }
public string Language { get { throw null; } set { } }
public bool? Verbose { get { throw null; } set { } }
}
public partial class DeepstackEntity
{
internal DeepstackEntity() { }
public string Category { get { throw null; } }
public float ConfidenceScore { get { throw null; } }
public int Length { get { throw null; } }
public int Offset { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.AI.Language.Conversations.Models.DeepStackEntityResolution> Resolution { get { throw null; } }
public string Text { get { throw null; } }
}
public partial class DeepStackEntityResolution
{
internal DeepStackEntityResolution() { }
public System.Collections.Generic.IReadOnlyDictionary<string, object> AdditionalProperties { get { throw null; } }
public Azure.AI.Language.Conversations.Models.ResolutionKind ResolutionKind { get { throw null; } }
}
public partial class DeepstackIntent
{
internal DeepstackIntent() { }
public string Category { get { throw null; } }
public float ConfidenceScore { get { throw null; } }
}
public partial class DeepstackParameters : Azure.AI.Language.Conversations.Models.AnalyzeParameters
{
public DeepstackParameters() { }
public Azure.AI.Language.Conversations.Models.DeepstackCallingOptions CallingOptions { get { throw null; } set { } }
}
public partial class DeepstackPrediction : Azure.AI.Language.Conversations.Models.BasePrediction
{
internal DeepstackPrediction() { }
public System.Collections.Generic.IReadOnlyList<Azure.AI.Language.Conversations.Models.DeepstackEntity> Entities { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.AI.Language.Conversations.Models.DeepstackIntent> Intents { get { throw null; } }
}
public partial class DeepstackResult
{
internal DeepstackResult() { }
public string DetectedLanguage { get { throw null; } }
public Azure.AI.Language.Conversations.Models.DeepstackPrediction Prediction { get { throw null; } }
public string Query { get { throw null; } }
}
public partial class DictionaryNormalizedValueResolution : Azure.AI.Language.Conversations.Models.DeepStackEntityResolution
{
internal DictionaryNormalizedValueResolution() { }
public System.Collections.Generic.IReadOnlyList<string> Values { get { throw null; } }
}
public partial class DSTargetIntentResult : Azure.AI.Language.Conversations.Models.TargetIntentResult
{
internal DSTargetIntentResult() { }
public Azure.AI.Language.Conversations.Models.DeepstackResult Result { get { throw null; } }
}
public partial class LuisCallingOptions
{
public LuisCallingOptions() { }
public string BingSpellCheckSubscriptionKey { get { throw null; } set { } }
public bool? Log { get { throw null; } set { } }
public bool? ShowAllIntents { get { throw null; } set { } }
public bool? SpellCheck { get { throw null; } set { } }
public float? TimezoneOffset { get { throw null; } set { } }
public bool? Verbose { get { throw null; } set { } }
}
public partial class LuisParameters : Azure.AI.Language.Conversations.Models.AnalyzeParameters
{
public LuisParameters() { }
public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { throw null; } }
public Azure.AI.Language.Conversations.Models.LuisCallingOptions CallingOptions { get { throw null; } set { } }
public string Query { get { throw null; } set { } }
}
public partial class LuisTargetIntentResult : Azure.AI.Language.Conversations.Models.TargetIntentResult
{
internal LuisTargetIntentResult() { }
public object Result { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ProjectKind : System.IEquatable<Azure.AI.Language.Conversations.Models.ProjectKind>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public ProjectKind(string value) { throw null; }
public static Azure.AI.Language.Conversations.Models.ProjectKind Conversation { get { throw null; } }
public static Azure.AI.Language.Conversations.Models.ProjectKind Workflow { get { throw null; } }
public bool Equals(Azure.AI.Language.Conversations.Models.ProjectKind other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.AI.Language.Conversations.Models.ProjectKind left, Azure.AI.Language.Conversations.Models.ProjectKind right) { throw null; }
public static implicit operator Azure.AI.Language.Conversations.Models.ProjectKind (string value) { throw null; }
public static bool operator !=(Azure.AI.Language.Conversations.Models.ProjectKind left, Azure.AI.Language.Conversations.Models.ProjectKind right) { throw null; }
public override string ToString() { throw null; }
}
public partial class QuestionAnsweringParameters : Azure.AI.Language.Conversations.Models.AnalyzeParameters
{
public QuestionAnsweringParameters() { }
public object CallingOptions { get { throw null; } set { } }
}
public partial class QuestionAnsweringTargetIntentResult : Azure.AI.Language.Conversations.Models.TargetIntentResult
{
internal QuestionAnsweringTargetIntentResult() { }
public object Result { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ResolutionKind : System.IEquatable<Azure.AI.Language.Conversations.Models.ResolutionKind>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public ResolutionKind(string value) { throw null; }
public static Azure.AI.Language.Conversations.Models.ResolutionKind DictionaryNormalizedValue { get { throw null; } }
public bool Equals(Azure.AI.Language.Conversations.Models.ResolutionKind other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.AI.Language.Conversations.Models.ResolutionKind left, Azure.AI.Language.Conversations.Models.ResolutionKind right) { throw null; }
public static implicit operator Azure.AI.Language.Conversations.Models.ResolutionKind (string value) { throw null; }
public static bool operator !=(Azure.AI.Language.Conversations.Models.ResolutionKind left, Azure.AI.Language.Conversations.Models.ResolutionKind right) { throw null; }
public override string ToString() { throw null; }
}
public partial class TargetIntentResult
{
internal TargetIntentResult() { }
public string ApiVersion { get { throw null; } }
public double ConfidenceScore { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct TargetKind : System.IEquatable<Azure.AI.Language.Conversations.Models.TargetKind>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public TargetKind(string value) { throw null; }
public static Azure.AI.Language.Conversations.Models.TargetKind Luis { get { throw null; } }
public static Azure.AI.Language.Conversations.Models.TargetKind LuisDeepstack { get { throw null; } }
public static Azure.AI.Language.Conversations.Models.TargetKind QuestionAnswering { get { throw null; } }
public bool Equals(Azure.AI.Language.Conversations.Models.TargetKind other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.AI.Language.Conversations.Models.TargetKind left, Azure.AI.Language.Conversations.Models.TargetKind right) { throw null; }
public static implicit operator Azure.AI.Language.Conversations.Models.TargetKind (string value) { throw null; }
public static bool operator !=(Azure.AI.Language.Conversations.Models.TargetKind left, Azure.AI.Language.Conversations.Models.TargetKind right) { throw null; }
public override string ToString() { throw null; }
}
public partial class WorkflowPrediction : Azure.AI.Language.Conversations.Models.BasePrediction
{
internal WorkflowPrediction() { }
public System.Collections.Generic.IReadOnlyDictionary<string, Azure.AI.Language.Conversations.Models.TargetIntentResult> Intents { get { throw null; } }
}
}
namespace Microsoft.Extensions.Azure
{
public static partial class ConversationAnalysisClientExtensions
{
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.AI.Language.Conversations.ConversationAnalysisClient, Azure.AI.Language.Conversations.ConversationAnalysisClientOptions> AddConversationAnalysisClient<TBuilder>(this TBuilder builder, System.Uri endpoint, Azure.AzureKeyCredential credential) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.AI.Language.Conversations.ConversationAnalysisClient, Azure.AI.Language.Conversations.ConversationAnalysisClientOptions> AddConversationAnalysisClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace AspNetCoreTest.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
LockoutEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
PasswordHash = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
SecurityStamp = table.Column<string>(nullable: true),
TwoFactorEnabled = table.Column<bool>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName");
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_UserId",
table: "AspNetUserRoles",
column: "UserId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Constraint.cs" company="Microsoft">
// (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// MSAGL Constraint class for Projection solutions.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// Remove this from project build and uncomment here to selectively enable per-class.
//#define VERBOSE
using System;
using System.Diagnostics;
namespace Microsoft.Msagl.Core.ProjectionSolver
{
/// <summary>
/// A Constraint defines the required minimal separation between two Variables
/// (thus is essentially a wrapper around the require minimal separation between
/// two nodes).
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1036:OverrideMethodsOnComparableTypes")]
public class Constraint : IComparable<Constraint>
{
/// <summary>
/// The Left (if horizontal; Top, if vertical) variable of the constraint.
/// </summary>
public Variable Left { get; private set; }
/// <summary>
/// The Right (if horizontal; Bottom, if vertical) variable of the constraint.
/// </summary>
public Variable Right { get; private set; }
/// <summary>
/// The required separation of the points of the two Variables along the current axis.
/// </summary>
public double Gap { get; private set; }
/// <summary>
/// Indicates if the distance between the two variables must be equal to the gap
/// (rather than greater or equal to).
/// </summary>
public bool IsEquality { get; private set; }
internal double Lagrangian { get; set; }
internal bool IsActive { get; private set; }
#if DEBUG
internal int IdDfDv { get; set; }
#endif // DEBUG
internal bool IsUnsatisfiable { get; set; }
// Index in Solver.AllConstraints, to segregate active from inactive constraints.
internal int VectorIndex { get; private set; }
internal void SetActiveState(bool activeState, int newVectorIndex)
{
// Note: newVectorIndex may be the same as the old one if we are changing the state
// of the last inactive or first active constraint.
Debug.Assert(IsActive != activeState, "Constraint is already set to activationState");
IsActive = activeState;
VectorIndex = newVectorIndex;
if (IsActive)
{
++Left.ActiveConstraintCount;
++Right.ActiveConstraintCount;
}
else
{
--Left.ActiveConstraintCount;
--Right.ActiveConstraintCount;
}
}
internal void SetVectorIndex(int vectorIndex)
{
// This is separate from set_VectorIndex because we can't restrict the caller to a specific
// class and we only want ConstraintVector to be able to call this.
this.VectorIndex = vectorIndex;
}
internal void Reinitialize()
{
// Called by Qpsc or equivalence-constraint-regapping initial block restructuring.
// All variables have been moved to their own blocks again, so reset solution states.
IsActive = false;
IsUnsatisfiable = false;
this.ClearDfDv();
}
// This is an internal function, not a propset, because we only want it called by the Solver.
internal void UpdateGap(double newGap) { this.Gap = newGap; }
#if VERIFY || VERBOSE
internal uint Id { get; private set; }
#endif // VERIFY || VERBOSE
// The Constraint constructor takes the two variables and their required distance.
// The constraints will be generated either manually or by ConstraintGenerator,
// both of which know about the sizes when the constraints are generated (as
// well as any necessary padding), so the sizes are accounted for at that time
// and ProjectionSolver classes are not aware of Variable sizes.
internal Constraint(Variable left, Variable right, double gap, bool isEquality
#if VERIFY || VERBOSE
, uint constraintId
#endif // VERIFY || VERBOSE
)
{
this.Left = left;
this.Right = right;
this.Gap = gap;
this.IsEquality = isEquality;
#if VERIFY || VERBOSE
Id = constraintId;
#endif // VERIFY || VERBOSE
this.Lagrangian = 0.0;
this.IsActive = false;
}
// For Solver.ComputeDfDv's DummyParentNode's constraint only.
internal Constraint(Variable variable)
{
this.Left = this.Right = variable;
}
internal bool IsDummy { get { return this.Left == this.Right; } }
/// <summary>
/// Generates a string representation of the Constraint.
/// </summary>
/// <returns>A string representation of the Constraint.</returns>
public override string ToString()
{
#if VERIFY || VERBOSE
return string.Format(System.Globalization.CultureInfo.InvariantCulture,
" Cst ({8}/{9}-{10}): [{0}] [{1}] {2} {3:F5} vio {4:F5} Lm {5:F5}/{6:F5} {7}actv",
this.Left, this.Right, this.IsEquality ? "==" : ">=", this.Gap,
this.Violation, this.Lagrangian, this.Lagrangian * 2,
this.IsActive ? "+" : (this.IsUnsatisfiable ? "!" : "-"),
this.Id, this.Left.Block.Id, this.Right.Block.Id);
#else // VERIFY || VERBOSE
return string.Format(System.Globalization.CultureInfo.InvariantCulture,
" Cst: [{0}] [{1}] {2} {3:F5} vio {4:F5} Lm {5:F5}/{6:F5} {7}actv",
this.Left, this.Right, this.IsEquality ? "==" : ">=", this.Gap,
this.Violation, this.Lagrangian, this.Lagrangian * 2,
this.IsActive ? "+" : (this.IsUnsatisfiable ? "!" : "-"));
#endif // VERIFY || VERBOSE
}
internal double Violation
{
// If the difference in position is negative or zero, it means the startpos of the Rhs
// node is greater than or equal to the gap and thus there's no violation.
// This uses an absolute (unscaled) positional comparison (multiplying by scale
// "undoes" the division-by-scale in Block.UpdateVariablePositions).
// Note: this is too big for the CLR to inline so it is "manually inlined" in
// high-call-volume places; these are marked with Inline_Violation.
get { return (this.Left.ActualPos * this.Left.Scale) + this.Gap - (this.Right.ActualPos * this.Right.Scale); }
}
internal void ClearDfDv()
{
#if DEBUG
this.IdDfDv = 0;
#endif // DEBUG
this.Lagrangian = 0.0;
}
#region IComparable<Constraint> Members
/// <summary>
/// Compare this Constraint to rhs by their Variables in ascending order (this == lhs, other == rhs).
/// </summary>
/// <param name="other">The object being compared to.</param>
/// <returns>-1 if this.Left/Right are "less"; +1 if this.Left/Right are "greater"; 0 if this.Left/Right
/// and rhs.Left/Right are equal.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", MessageId = "System.String.CompareTo(System.String)")]
public int CompareTo(Constraint other)
{
ValidateArg.IsNotNull(other, "other");
int cmp = this.Left.CompareTo(other.Left);
if (0 == cmp)
{
cmp = this.Right.CompareTo(other.Right);
}
if (0 == cmp)
{
cmp = this.Gap.CompareTo(other.Gap);
}
return cmp;
}
#endregion // IComparable<Constraint> Members
#if NOTNEEDED_FXCOP // This entails a perf hit due to ==/!= becoming a non-inlined function call in some cases.
// We only create one Constraint object per constraint so do not need anything but reference
// ==/!=, so we suppress:1036 above. Add UnitTests for these if they're enabled.
#region RequiredOverridesForIComparable
// Omitting getHashCode violates rule: OverrideGetHashCodeOnOverridingEquals.
public override int GetHashCode() {
return this.Left.GetHashCode() ^ this.Right.GetHashCode();
}
// Omitting any of the following violates rule: OverrideMethodsOnComparableTypes.
public override bool Equals(Object obj) {
if (!(obj is Constraint))
return false;
return (this.CompareTo((Constraint)obj) == 0);
}
public static bool operator ==(Constraint lhs, Constraint rhs) {
if (null == (object)lhs) { // Cast to object to avoid recursive op==
return (null == (object)rhs);
}
return lhs.Equals(rhs);
}
public static bool operator !=(Constraint lhs, Constraint rhs) {
return !(lhs == rhs);
}
public static bool operator <(Constraint lhs, Constraint rhs) {
return (lhs.CompareTo(rhs) < 0);
}
public static bool operator >(Constraint lhs, Constraint rhs) {
return (lhs.CompareTo(rhs) > 0);
}
#endregion // RequiredOverridesForIComparable
#endif // NOTNEEDED_FXCOP
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Text;
using System.Xml;
using System.Linq;
using Svg.ExCSS;
using Svg.Css;
using System.Threading;
using System.Globalization;
using Svg.Exceptions;
using System.Runtime.InteropServices;
namespace Svg
{
/// <summary>
/// The class used to create and load SVG documents.
/// </summary>
public class SvgDocument : SvgFragment, ITypeDescriptorContext
{
public static readonly int PointsPerInch = GetSystemDpi();
private SvgElementIdManager _idManager;
private Dictionary<string, IEnumerable<SvgFontFace>> _fontDefns = null;
private static int GetSystemDpi()
{
IntPtr hDC = GetDC(IntPtr.Zero);
const int LOGPIXELSY = 90;
int result = GetDeviceCaps(hDC, LOGPIXELSY);
ReleaseDC(IntPtr.Zero, hDC);
return result;
}
[DllImport("gdi32.dll")]
private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
internal Dictionary<string, IEnumerable<SvgFontFace>> FontDefns()
{
if (_fontDefns == null)
{
_fontDefns = (from f in Descendants().OfType<SvgFontFace>()
group f by f.FontFamily into family
select family).ToDictionary(f => f.Key, f => (IEnumerable<SvgFontFace>)f);
}
return _fontDefns;
}
/// <summary>
/// Initializes a new instance of the <see cref="SvgDocument"/> class.
/// </summary>
public SvgDocument()
{
Ppi = PointsPerInch;
}
public Uri BaseUri { get; set; }
/// <summary>
/// Gets an <see cref="SvgElementIdManager"/> for this document.
/// </summary>
protected internal virtual SvgElementIdManager IdManager
{
get
{
if (_idManager == null)
{
_idManager = new SvgElementIdManager(this);
}
return _idManager;
}
}
/// <summary>
/// Overwrites the current IdManager with a custom implementation.
/// Be careful with this: If elements have been inserted into the document before,
/// you have to take care that the new IdManager also knows of them.
/// </summary>
/// <param name="manager"></param>
public void OverwriteIdManager(SvgElementIdManager manager)
{
_idManager = manager;
}
/// <summary>
/// Gets or sets the Pixels Per Inch of the rendered image.
/// </summary>
public int Ppi { get; set; }
/// <summary>
/// Gets or sets an external Cascading Style Sheet (CSS)
/// </summary>
public string ExternalCSSHref { get; set; }
#region ITypeDescriptorContext Members
IContainer ITypeDescriptorContext.Container
{
get { throw new NotImplementedException(); }
}
object ITypeDescriptorContext.Instance
{
get { return this; }
}
void ITypeDescriptorContext.OnComponentChanged()
{
throw new NotImplementedException();
}
bool ITypeDescriptorContext.OnComponentChanging()
{
throw new NotImplementedException();
}
PropertyDescriptor ITypeDescriptorContext.PropertyDescriptor
{
get { throw new NotImplementedException(); }
}
object IServiceProvider.GetService(Type serviceType)
{
throw new NotImplementedException();
}
#endregion
/// <summary>
/// Retrieves the <see cref="SvgElement"/> with the specified ID.
/// </summary>
/// <param name="id">A <see cref="string"/> containing the ID of the element to find.</param>
/// <returns>An <see cref="SvgElement"/> of one exists with the specified ID; otherwise false.</returns>
public virtual SvgElement GetElementById(string id)
{
return IdManager.GetElementById(id);
}
/// <summary>
/// Retrieves the <see cref="SvgElement"/> with the specified ID.
/// </summary>
/// <param name="id">A <see cref="string"/> containing the ID of the element to find.</param>
/// <returns>An <see cref="SvgElement"/> of one exists with the specified ID; otherwise false.</returns>
public virtual TSvgElement GetElementById<TSvgElement>(string id) where TSvgElement : SvgElement
{
return (this.GetElementById(id) as TSvgElement);
}
/// <summary>
/// Opens the document at the specified path and loads the SVG contents.
/// </summary>
/// <param name="path">A <see cref="string"/> containing the path of the file to open.</param>
/// <returns>An <see cref="SvgDocument"/> with the contents loaded.</returns>
/// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
public static SvgDocument Open(string path)
{
return Open<SvgDocument>(path, null);
}
/// <summary>
/// Opens the document at the specified path and loads the SVG contents.
/// </summary>
/// <param name="path">A <see cref="string"/> containing the path of the file to open.</param>
/// <returns>An <see cref="SvgDocument"/> with the contents loaded.</returns>
/// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
public static T Open<T>(string path) where T : SvgDocument, new()
{
return Open<T>(path, null);
}
/// <summary>
/// Opens the document at the specified path and loads the SVG contents.
/// </summary>
/// <param name="path">A <see cref="string"/> containing the path of the file to open.</param>
/// <param name="entities">A dictionary of custom entity definitions to be used when resolving XML entities within the document.</param>
/// <returns>An <see cref="SvgDocument"/> with the contents loaded.</returns>
/// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
public static T Open<T>(string path, Dictionary<string, string> entities) where T : SvgDocument, new()
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
if (!File.Exists(path))
{
throw new FileNotFoundException("The specified document cannot be found.", path);
}
using (var stream = File.OpenRead(path))
{
var doc = Open<T>(stream, entities);
doc.BaseUri = new Uri(System.IO.Path.GetFullPath(path));
return doc;
}
}
/// <summary>
/// Attempts to open an SVG document from the specified <see cref="Stream"/>.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> containing the SVG document to open.</param>
public static T Open<T>(Stream stream) where T : SvgDocument, new()
{
return Open<T>(stream, null);
}
/// <summary>
/// Attempts to create an SVG document from the specified string data.
/// </summary>
/// <param name="svg">The SVG data.</param>
public static T FromSvg<T>(string svg) where T : SvgDocument, new()
{
if (string.IsNullOrEmpty(svg))
{
throw new ArgumentNullException("svg");
}
using (var strReader = new System.IO.StringReader(svg))
{
var reader = new SvgTextReader(strReader, null);
reader.XmlResolver = new SvgDtdResolver();
reader.WhitespaceHandling = WhitespaceHandling.None;
return Open<T>(reader);
}
}
/// <summary>
/// Opens an SVG document from the specified <see cref="Stream"/> and adds the specified entities.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> containing the SVG document to open.</param>
/// <param name="entities">Custom entity definitions.</param>
/// <exception cref="ArgumentNullException">The <paramref name="stream"/> parameter cannot be <c>null</c>.</exception>
public static T Open<T>(Stream stream, Dictionary<string, string> entities) where T : SvgDocument, new()
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
// Don't close the stream via a dispose: that is the client's job.
var reader = new SvgTextReader(stream, entities);
reader.XmlResolver = new SvgDtdResolver();
reader.WhitespaceHandling = WhitespaceHandling.None;
return Open<T>(reader);
}
private static T Open<T>(XmlReader reader) where T : SvgDocument, new()
{
var elementStack = new Stack<SvgElement>();
bool elementEmpty;
SvgElement element = null;
SvgElement parent;
T svgDocument = null;
var elementFactory = new SvgElementFactory();
var styles = new List<ISvgNode>();
while (reader.Read())
{
try
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
// Does this element have a value or children
// (Must do this check here before we progress to another node)
elementEmpty = reader.IsEmptyElement;
// Create element
if (elementStack.Count > 0)
{
element = elementFactory.CreateElement(reader, svgDocument);
}
else
{
svgDocument = elementFactory.CreateDocument<T>(reader);
element = svgDocument;
}
// Add to the parents children
if (elementStack.Count > 0)
{
parent = elementStack.Peek();
if (parent != null && element != null)
{
parent.Children.Add(element);
parent.Nodes.Add(element);
}
}
// Push element into stack
elementStack.Push(element);
// Need to process if the element is empty
if (elementEmpty)
{
goto case XmlNodeType.EndElement;
}
break;
case XmlNodeType.EndElement:
// Pop the element out of the stack
element = elementStack.Pop();
if (element.Nodes.OfType<SvgContentNode>().Any())
{
element.Content = (from e in element.Nodes select e.Content).Aggregate((p, c) => p + c);
}
else
{
element.Nodes.Clear(); // No sense wasting the space where it isn't needed
}
var unknown = element as SvgUnknownElement;
if (unknown != null && unknown.ElementName == "style")
{
styles.Add(unknown);
}
break;
case XmlNodeType.CDATA:
case XmlNodeType.Text:
element = elementStack.Peek();
element.Nodes.Add(new SvgContentNode() { Content = reader.Value });
break;
case XmlNodeType.EntityReference:
reader.ResolveEntity();
element = elementStack.Peek();
element.Nodes.Add(new SvgContentNode() { Content = reader.Value });
break;
}
}
catch (Exception exc)
{
Trace.TraceError(exc.Message);
}
}
if (styles.Any())
{
var cssTotal = styles.Select((s) => s.Content).Aggregate((p, c) => p + Environment.NewLine + c);
var cssParser = new Parser();
var sheet = cssParser.Parse(cssTotal);
AggregateSelectorList aggList;
IEnumerable<BaseSelector> selectors;
IEnumerable<SvgElement> elemsToStyle;
foreach (var rule in sheet.StyleRules)
{
aggList = rule.Selector as AggregateSelectorList;
if (aggList != null && aggList.Delimiter == ",")
{
selectors = aggList;
}
else
{
selectors = Enumerable.Repeat(rule.Selector, 1);
}
foreach (var selector in selectors)
{
elemsToStyle = svgDocument.QuerySelectorAll(rule.Selector.ToString(), elementFactory);
foreach (var elem in elemsToStyle)
{
foreach (var decl in rule.Declarations)
{
elem.AddStyle(decl.Name, decl.Term.ToString(), rule.Selector.GetSpecificity());
}
}
}
}
}
if (svgDocument != null) FlushStyles(svgDocument);
return svgDocument;
}
private static void FlushStyles(SvgElement elem)
{
elem.FlushStyles();
foreach (var child in elem.Children)
{
FlushStyles(child);
}
}
/// <summary>
/// Opens an SVG document from the specified <see cref="XmlDocument"/>.
/// </summary>
/// <param name="document">The <see cref="XmlDocument"/> containing the SVG document XML.</param>
/// <exception cref="ArgumentNullException">The <paramref name="document"/> parameter cannot be <c>null</c>.</exception>
public static SvgDocument Open(XmlDocument document)
{
if (document == null)
{
throw new ArgumentNullException("document");
}
var reader = new SvgNodeReader(document.DocumentElement, null);
return Open<SvgDocument>(reader);
}
public static Bitmap OpenAsBitmap(string path)
{
return null;
}
public static Bitmap OpenAsBitmap(XmlDocument document)
{
return null;
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> to the specified <see cref="ISvgRenderer"/>.
/// </summary>
/// <param name="renderer">The <see cref="ISvgRenderer"/> to render the document with.</param>
/// <exception cref="ArgumentNullException">The <paramref name="renderer"/> parameter cannot be <c>null</c>.</exception>
public void Draw(ISvgRenderer renderer)
{
if (renderer == null)
{
throw new ArgumentNullException("renderer");
}
renderer.SetBoundable(this);
this.Render(renderer);
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> to the specified <see cref="Graphics"/>.
/// </summary>
/// <param name="graphics">The <see cref="Graphics"/> to be rendered to.</param>
/// <exception cref="ArgumentNullException">The <paramref name="graphics"/> parameter cannot be <c>null</c>.</exception>
public void Draw(Graphics graphics)
{
Draw(graphics, null);
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> to the specified <see cref="Graphics"/>.
/// </summary>
/// <param name="graphics">The <see cref="Graphics"/> to be rendered to.</param>
/// <param name="size">The <see cref="SizeF"/> to render the document. If <c>null</c> document is rendered at the default document size.</param>
/// <exception cref="ArgumentNullException">The <paramref name="graphics"/> parameter cannot be <c>null</c>.</exception>
public void Draw(Graphics graphics, SizeF? size)
{
if (graphics == null)
{
throw new ArgumentNullException("graphics");
}
var renderer = SvgRenderer.FromGraphics(graphics);
if (size.HasValue)
{
renderer.SetBoundable(new GenericBoundable(0, 0, size.Value.Width, size.Value.Height));
}
else
{
renderer.SetBoundable(this);
}
this.Render(renderer);
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> and returns the image as a <see cref="Bitmap"/>.
/// </summary>
/// <returns>A <see cref="Bitmap"/> containing the rendered document.</returns>
public virtual Bitmap Draw()
{
//Trace.TraceInformation("Begin Render");
var size = GetDimensions();
Bitmap bitmap = null;
try
{
bitmap = new Bitmap((int) Math.Round(size.Width), (int) Math.Round(size.Height));
}
catch (ArgumentException e)
{
//When processing too many files at one the system can run out of memory
throw new SvgMemoryException("Cannot process SVG file, cannot allocate the required memory", e);
}
// bitmap.SetResolution(300, 300);
try
{
Draw(bitmap);
}
catch
{
bitmap.Dispose();
throw;
}
//Trace.TraceInformation("End Render");
return bitmap;
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> into a given Bitmap <see cref="Bitmap"/>.
/// </summary>
public virtual void Draw(Bitmap bitmap)
{
//Trace.TraceInformation("Begin Render");
try
{
using (var renderer = SvgRenderer.FromImage(bitmap))
{
renderer.SetBoundable(new GenericBoundable(0, 0, bitmap.Width, bitmap.Height));
//EO, 2014-12-05: Requested to ensure proper zooming out (reduce size). Otherwise it clip the image.
this.Overflow = SvgOverflow.Auto;
this.Render(renderer);
}
}
catch
{
throw;
}
//Trace.TraceInformation("End Render");
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> in given size and returns the image as a <see cref="Bitmap"/>.
/// If one of rasterWidth and rasterHeight is zero, the image is scaled preserving aspect ratio,
/// otherwise the aspect ratio is ignored.
/// </summary>
/// <returns>A <see cref="Bitmap"/> containing the rendered document.</returns>
public virtual Bitmap Draw(int rasterWidth, int rasterHeight)
{
var imageSize = GetDimensions();
var bitmapSize = imageSize;
RasterizeDimensions(ref bitmapSize, rasterWidth, rasterHeight);
if (bitmapSize.Width == 0 || bitmapSize.Height == 0)
return null;
var bitmap = new Bitmap((int)Math.Round(bitmapSize.Width), (int)Math.Round(bitmapSize.Height));
try
{
var renderer = SvgRenderer.FromImage(bitmap);
renderer.ScaleTransform(bitmapSize.Width / imageSize.Width, bitmapSize.Height / imageSize.Height);
Draw(renderer);
}
catch
{
bitmap.Dispose();
throw;
}
return bitmap;
}
/// <summary>
/// If both or one of raster height and width is not given (0), calculate that missing value from original SVG size
/// while keeping original SVG size ratio
/// </summary>
/// <param name="size"></param>
/// <param name="rasterWidth"></param>
/// <param name="rasterHeight"></param>
public virtual void RasterizeDimensions(ref SizeF size, int rasterWidth, int rasterHeight)
{
if (size == null || size.Width == 0)
return;
// Ratio of height/width of the original SVG size, to be used for scaling transformation
float ratio = size.Height / size.Width;
size.Width = rasterWidth > 0 ? (float)rasterWidth : size.Width;
size.Height = rasterHeight > 0 ? (float)rasterHeight : size.Height;
if (rasterHeight == 0 && rasterWidth > 0)
{
size.Height = (int)(rasterWidth * ratio);
}
else if (rasterHeight > 0 && rasterWidth == 0)
{
size.Width = (int)(rasterHeight / ratio);
}
}
public override void Write(XmlTextWriter writer)
{
//Save previous culture and switch to invariant for writing
var previousCulture = Thread.CurrentThread.CurrentCulture;
try {
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
base.Write(writer);
}
finally
{
// Make sure to set back the old culture even an error occurred.
//Switch culture back
Thread.CurrentThread.CurrentCulture = previousCulture;
}
}
public void Write(Stream stream, bool useBom = true)
{
var xmlWriter = new XmlTextWriter(stream, useBom ? Encoding.UTF8 : new System.Text.UTF8Encoding(false));
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument();
xmlWriter.WriteDocType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", null);
if (!String.IsNullOrEmpty(this.ExternalCSSHref))
xmlWriter.WriteProcessingInstruction("xml-stylesheet", String.Format("type=\"text/css\" href=\"{0}\"", this.ExternalCSSHref));
this.Write(xmlWriter);
xmlWriter.Flush();
}
public void Write(string path, bool useBom = true)
{
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
this.Write(fs, useBom);
}
}
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Joints
{
// Linear constraint (point-to-line)
// d = p2 - p1 = x2 + r2 - x1 - r1
// C = dot(perp, d)
// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1))
// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2)
// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)]
//
// Angular constraint
// C = a2 - a1 + a_initial
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
//
// K = J * invM * JT
//
// J = [-a -s1 a s2]
// [0 -1 0 1]
// a = perp
// s1 = cross(d + r1, a) = cross(p2 - x1, a)
// s2 = cross(r2, a) = cross(p2 - x2, a)
// Motor/Limit linear constraint
// C = dot(ax1, d)
// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2)
// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)]
// Block Solver
// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even
// when the mass has poor distribution (leading to large torques about the joint anchor points).
//
// The Jacobian has 3 rows:
// J = [-uT -s1 uT s2] // linear
// [0 -1 0 1] // angular
// [-vT -a1 vT a2] // limit
//
// u = perp
// v = axis
// s1 = cross(d + r1, u), s2 = cross(r2, u)
// a1 = cross(d + r1, v), a2 = cross(r2, v)
// M * (v2 - v1) = JT * df
// J * v2 = bias
//
// v2 = v1 + invM * JT * df
// J * (v1 + invM * JT * df) = bias
// K * df = bias - J * v1 = -Cdot
// K = J * invM * JT
// Cdot = J * v1 - bias
//
// Now solve for f2.
// df = f2 - f1
// K * (f2 - f1) = -Cdot
// f2 = invK * (-Cdot) + f1
//
// Clamp accumulated limit impulse.
// lower: f2(3) = max(f2(3), 0)
// upper: f2(3) = min(f2(3), 0)
//
// Solve for correct f2(1:2)
// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1
// = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3)
// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2)
// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2)
//
// Now compute impulse to be applied:
// df = f2 - f1
/// <summary>
/// A prismatic joint. This joint provides one degree of freedom: translation
/// along an axis fixed in body1. Relative rotation is prevented. You can
/// use a joint limit to restrict the range of motion and a joint motor to
/// drive the motion or to model joint friction.
/// </summary>
public class PrismaticJoint : Joint
{
private Mat33 _K;
private float _a1, _a2;
private Vector2 _axis;
private bool _enableLimit;
private bool _enableMotor;
private Vector3 _impulse;
private LimitState _limitState;
private Vector2 _localXAxis1;
private Vector2 _localYAxis1;
private float _lowerTranslation;
private float _maxMotorForce;
private float _motorImpulse;
private float _motorMass; // effective mass for motor/limit translational constraint.
private float _motorSpeed;
private Vector2 _perp;
private float _refAngle;
private float _s1, _s2;
private float _upperTranslation;
/// <summary>
/// This requires defining a line of
/// motion using an axis and an anchor point. The definition uses local
/// anchor points and a local axis so that the initial configuration
/// can violate the constraint slightly. The joint translation is zero
/// when the local anchor points coincide in world space. Using local
/// anchors and a local axis helps when saving and loading a game.
/// </summary>
/// <param name="bodyA">The first body.</param>
/// <param name="bodyB">The second body.</param>
/// <param name="anchorA">The first body anchor.</param>
/// <param name="anchorB">The second body anchor.</param>
/// <param name="axis">The axis.</param>
public PrismaticJoint(Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB, Vector2 axis)
: base(bodyA, bodyB)
{
JointType = JointType.Prismatic;
LocalAnchorA = anchorA;
LocalAnchorB = anchorB;
_localXAxis1 = BodyA.GetLocalVector(axis);
_localYAxis1 = MathUtils.Cross(1.0f, _localXAxis1);
_refAngle = BodyB.Rotation - BodyA.Rotation;
_limitState = LimitState.Inactive;
}
public Vector2 LocalAnchorA { get; set; }
public Vector2 LocalAnchorB { get; set; }
public override Vector2 WorldAnchorA
{
get { return BodyA.GetWorldPoint(LocalAnchorA); }
}
public override Vector2 WorldAnchorB
{
get { return BodyB.GetWorldPoint(LocalAnchorB); }
}
/// <summary>
/// Get the current joint translation, usually in meters.
/// </summary>
/// <value></value>
public float JointTranslation
{
get
{
Vector2 d = BodyB.GetWorldPoint(LocalAnchorB) - BodyA.GetWorldPoint(LocalAnchorA);
Vector2 axis = BodyA.GetWorldVector(ref _localXAxis1);
return Vector2.Dot(d, axis);
}
}
/// <summary>
/// Get the current joint translation speed, usually in meters per second.
/// </summary>
/// <value></value>
public float JointSpeed
{
get
{
Transform xf1, xf2;
BodyA.GetTransform(out xf1);
BodyB.GetTransform(out xf2);
Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - BodyA.LocalCenter);
Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - BodyB.LocalCenter);
Vector2 p1 = BodyA.Sweep.C + r1;
Vector2 p2 = BodyB.Sweep.C + r2;
Vector2 d = p2 - p1;
Vector2 axis = BodyA.GetWorldVector(ref _localXAxis1);
Vector2 v1 = BodyA.LinearVelocityInternal;
Vector2 v2 = BodyB.LinearVelocityInternal;
float w1 = BodyA.AngularVelocityInternal;
float w2 = BodyB.AngularVelocityInternal;
float speed = Vector2.Dot(d, MathUtils.Cross(w1, axis)) +
Vector2.Dot(axis, v2 + MathUtils.Cross(w2, r2) - v1 - MathUtils.Cross(w1, r1));
return speed;
}
}
/// <summary>
/// Is the joint limit enabled?
/// </summary>
/// <value><c>true</c> if [limit enabled]; otherwise, <c>false</c>.</value>
public bool LimitEnabled
{
get { return _enableLimit; }
set
{
WakeBodies();
_enableLimit = value;
}
}
/// <summary>
/// Get the lower joint limit, usually in meters.
/// </summary>
/// <value></value>
public float LowerLimit
{
get { return _lowerTranslation; }
set
{
WakeBodies();
_lowerTranslation = value;
}
}
/// <summary>
/// Get the upper joint limit, usually in meters.
/// </summary>
/// <value></value>
public float UpperLimit
{
get { return _upperTranslation; }
set
{
WakeBodies();
_upperTranslation = value;
}
}
/// <summary>
/// Is the joint motor enabled?
/// </summary>
/// <value><c>true</c> if [motor enabled]; otherwise, <c>false</c>.</value>
public bool MotorEnabled
{
get { return _enableMotor; }
set
{
WakeBodies();
_enableMotor = value;
}
}
/// <summary>
/// Set the motor speed, usually in meters per second.
/// </summary>
/// <value>The speed.</value>
public float MotorSpeed
{
set
{
WakeBodies();
_motorSpeed = value;
}
get { return _motorSpeed; }
}
/// <summary>
/// Set the maximum motor force, usually in N.
/// </summary>
/// <value>The force.</value>
public float MaxMotorForce
{
set
{
WakeBodies();
_maxMotorForce = value;
}
}
/// <summary>
/// Get the current motor force, usually in N.
/// </summary>
/// <value></value>
public float MotorForce
{
get { return _motorImpulse; }
set { _motorImpulse = value; }
}
public Vector2 LocalXAxis1
{
get { return _localXAxis1; }
set
{
_localXAxis1 = BodyA.GetLocalVector(value);
_localYAxis1 = MathUtils.Cross(1.0f, _localXAxis1);
}
}
public override Vector2 GetReactionForce(float inv_dt)
{
return inv_dt * (_impulse.X * _perp + (_motorImpulse + _impulse.Z) * _axis);
}
public override float GetReactionTorque(float inv_dt)
{
return inv_dt * _impulse.Y;
}
internal override void InitVelocityConstraints(ref TimeStep step)
{
Body b1 = BodyA;
Body b2 = BodyB;
LocalCenterA = b1.LocalCenter;
LocalCenterB = b2.LocalCenter;
Transform xf1, xf2;
b1.GetTransform(out xf1);
b2.GetTransform(out xf2);
// Compute the effective masses.
Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - LocalCenterA);
Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - LocalCenterB);
Vector2 d = b2.Sweep.C + r2 - b1.Sweep.C - r1;
InvMassA = b1.InvMass;
InvIA = b1.InvI;
InvMassB = b2.InvMass;
InvIB = b2.InvI;
// Compute motor Jacobian and effective mass.
{
_axis = MathUtils.Multiply(ref xf1.R, _localXAxis1);
_a1 = MathUtils.Cross(d + r1, _axis);
_a2 = MathUtils.Cross(r2, _axis);
_motorMass = InvMassA + InvMassB + InvIA * _a1 * _a1 + InvIB * _a2 * _a2;
if (_motorMass > Settings.Epsilon)
{
_motorMass = 1.0f / _motorMass;
}
}
// Prismatic constraint.
{
_perp = MathUtils.Multiply(ref xf1.R, _localYAxis1);
_s1 = MathUtils.Cross(d + r1, _perp);
_s2 = MathUtils.Cross(r2, _perp);
float m1 = InvMassA, m2 = InvMassB;
float i1 = InvIA, i2 = InvIB;
float k11 = m1 + m2 + i1 * _s1 * _s1 + i2 * _s2 * _s2;
float k12 = i1 * _s1 + i2 * _s2;
float k13 = i1 * _s1 * _a1 + i2 * _s2 * _a2;
float k22 = i1 + i2;
float k23 = i1 * _a1 + i2 * _a2;
float k33 = m1 + m2 + i1 * _a1 * _a1 + i2 * _a2 * _a2;
_K.Col1 = new Vector3(k11, k12, k13);
_K.Col2 = new Vector3(k12, k22, k23);
_K.Col3 = new Vector3(k13, k23, k33);
}
// Compute motor and limit terms.
if (_enableLimit)
{
float jointTranslation = Vector2.Dot(_axis, d);
if (Math.Abs(_upperTranslation - _lowerTranslation) < 2.0f * Settings.LinearSlop)
{
_limitState = LimitState.Equal;
}
else if (jointTranslation <= _lowerTranslation)
{
if (_limitState != LimitState.AtLower)
{
_limitState = LimitState.AtLower;
_impulse.Z = 0.0f;
}
}
else if (jointTranslation >= _upperTranslation)
{
if (_limitState != LimitState.AtUpper)
{
_limitState = LimitState.AtUpper;
_impulse.Z = 0.0f;
}
}
else
{
_limitState = LimitState.Inactive;
_impulse.Z = 0.0f;
}
}
else
{
_limitState = LimitState.Inactive;
}
if (_enableMotor == false)
{
_motorImpulse = 0.0f;
}
if (Settings.EnableWarmstarting)
{
// Account for variable time step.
_impulse *= step.dtRatio;
_motorImpulse *= step.dtRatio;
Vector2 P = _impulse.X * _perp + (_motorImpulse + _impulse.Z) * _axis;
float L1 = _impulse.X * _s1 + _impulse.Y + (_motorImpulse + _impulse.Z) * _a1;
float L2 = _impulse.X * _s2 + _impulse.Y + (_motorImpulse + _impulse.Z) * _a2;
b1.LinearVelocityInternal -= InvMassA * P;
b1.AngularVelocityInternal -= InvIA * L1;
b2.LinearVelocityInternal += InvMassB * P;
b2.AngularVelocityInternal += InvIB * L2;
}
else
{
_impulse = Vector3.Zero;
_motorImpulse = 0.0f;
}
}
internal override void SolveVelocityConstraints(ref TimeStep step)
{
Body b1 = BodyA;
Body b2 = BodyB;
Vector2 v1 = b1.LinearVelocityInternal;
float w1 = b1.AngularVelocityInternal;
Vector2 v2 = b2.LinearVelocityInternal;
float w2 = b2.AngularVelocityInternal;
// Solve linear motor constraint.
if (_enableMotor && _limitState != LimitState.Equal)
{
float Cdot = Vector2.Dot(_axis, v2 - v1) + _a2 * w2 - _a1 * w1;
float impulse = _motorMass * (_motorSpeed - Cdot);
float oldImpulse = _motorImpulse;
float maxImpulse = step.dt * _maxMotorForce;
_motorImpulse = MathUtils.Clamp(_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = _motorImpulse - oldImpulse;
Vector2 P = impulse * _axis;
float L1 = impulse * _a1;
float L2 = impulse * _a2;
v1 -= InvMassA * P;
w1 -= InvIA * L1;
v2 += InvMassB * P;
w2 += InvIB * L2;
}
Vector2 Cdot1 = new Vector2(Vector2.Dot(_perp, v2 - v1) + _s2 * w2 - _s1 * w1, w2 - w1);
if (_enableLimit && _limitState != LimitState.Inactive)
{
// Solve prismatic and limit constraint in block form.
float Cdot2 = Vector2.Dot(_axis, v2 - v1) + _a2 * w2 - _a1 * w1;
Vector3 Cdot = new Vector3(Cdot1.X, Cdot1.Y, Cdot2);
Vector3 f1 = _impulse;
Vector3 df = _K.Solve33(-Cdot);
_impulse += df;
if (_limitState == LimitState.AtLower)
{
_impulse.Z = Math.Max(_impulse.Z, 0.0f);
}
else if (_limitState == LimitState.AtUpper)
{
_impulse.Z = Math.Min(_impulse.Z, 0.0f);
}
// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2)
Vector2 b = -Cdot1 - (_impulse.Z - f1.Z) * new Vector2(_K.Col3.X, _K.Col3.Y);
Vector2 f2r = _K.Solve22(b) + new Vector2(f1.X, f1.Y);
_impulse.X = f2r.X;
_impulse.Y = f2r.Y;
df = _impulse - f1;
Vector2 P = df.X * _perp + df.Z * _axis;
float L1 = df.X * _s1 + df.Y + df.Z * _a1;
float L2 = df.X * _s2 + df.Y + df.Z * _a2;
v1 -= InvMassA * P;
w1 -= InvIA * L1;
v2 += InvMassB * P;
w2 += InvIB * L2;
}
else
{
// Limit is inactive, just solve the prismatic constraint in block form.
Vector2 df = _K.Solve22(-Cdot1);
_impulse.X += df.X;
_impulse.Y += df.Y;
Vector2 P = df.X * _perp;
float L1 = df.X * _s1 + df.Y;
float L2 = df.X * _s2 + df.Y;
v1 -= InvMassA * P;
w1 -= InvIA * L1;
v2 += InvMassB * P;
w2 += InvIB * L2;
}
b1.LinearVelocityInternal = v1;
b1.AngularVelocityInternal = w1;
b2.LinearVelocityInternal = v2;
b2.AngularVelocityInternal = w2;
}
internal override bool SolvePositionConstraints()
{
Body b1 = BodyA;
Body b2 = BodyB;
Vector2 c1 = b1.Sweep.C;
float a1 = b1.Sweep.A;
Vector2 c2 = b2.Sweep.C;
float a2 = b2.Sweep.A;
// Solve linear limit constraint.
float linearError = 0.0f;
bool active = false;
float C2 = 0.0f;
Mat22 R1 = new Mat22(a1);
Mat22 R2 = new Mat22(a2);
Vector2 r1 = MathUtils.Multiply(ref R1, LocalAnchorA - LocalCenterA);
Vector2 r2 = MathUtils.Multiply(ref R2, LocalAnchorB - LocalCenterB);
Vector2 d = c2 + r2 - c1 - r1;
if (_enableLimit)
{
_axis = MathUtils.Multiply(ref R1, _localXAxis1);
_a1 = MathUtils.Cross(d + r1, _axis);
_a2 = MathUtils.Cross(r2, _axis);
float translation = Vector2.Dot(_axis, d);
if (Math.Abs(_upperTranslation - _lowerTranslation) < 2.0f * Settings.LinearSlop)
{
// Prevent large angular corrections
C2 = MathUtils.Clamp(translation, -Settings.MaxLinearCorrection, Settings.MaxLinearCorrection);
linearError = Math.Abs(translation);
active = true;
}
else if (translation <= _lowerTranslation)
{
// Prevent large linear corrections and allow some slop.
C2 = MathUtils.Clamp(translation - _lowerTranslation + Settings.LinearSlop,
-Settings.MaxLinearCorrection, 0.0f);
linearError = _lowerTranslation - translation;
active = true;
}
else if (translation >= _upperTranslation)
{
// Prevent large linear corrections and allow some slop.
C2 = MathUtils.Clamp(translation - _upperTranslation - Settings.LinearSlop, 0.0f,
Settings.MaxLinearCorrection);
linearError = translation - _upperTranslation;
active = true;
}
}
_perp = MathUtils.Multiply(ref R1, _localYAxis1);
_s1 = MathUtils.Cross(d + r1, _perp);
_s2 = MathUtils.Cross(r2, _perp);
Vector3 impulse;
Vector2 C1 = new Vector2(Vector2.Dot(_perp, d), a2 - a1 - _refAngle);
linearError = Math.Max(linearError, Math.Abs(C1.X));
float angularError = Math.Abs(C1.Y);
if (active)
{
float m1 = InvMassA, m2 = InvMassB;
float i1 = InvIA, i2 = InvIB;
float k11 = m1 + m2 + i1 * _s1 * _s1 + i2 * _s2 * _s2;
float k12 = i1 * _s1 + i2 * _s2;
float k13 = i1 * _s1 * _a1 + i2 * _s2 * _a2;
float k22 = i1 + i2;
float k23 = i1 * _a1 + i2 * _a2;
float k33 = m1 + m2 + i1 * _a1 * _a1 + i2 * _a2 * _a2;
_K.Col1 = new Vector3(k11, k12, k13);
_K.Col2 = new Vector3(k12, k22, k23);
_K.Col3 = new Vector3(k13, k23, k33);
Vector3 C = new Vector3(-C1.X, -C1.Y, -C2);
impulse = _K.Solve33(C); // negated above
}
else
{
float m1 = InvMassA, m2 = InvMassB;
float i1 = InvIA, i2 = InvIB;
float k11 = m1 + m2 + i1 * _s1 * _s1 + i2 * _s2 * _s2;
float k12 = i1 * _s1 + i2 * _s2;
float k22 = i1 + i2;
_K.Col1 = new Vector3(k11, k12, 0.0f);
_K.Col2 = new Vector3(k12, k22, 0.0f);
Vector2 impulse1 = _K.Solve22(-C1);
impulse.X = impulse1.X;
impulse.Y = impulse1.Y;
impulse.Z = 0.0f;
}
Vector2 P = impulse.X * _perp + impulse.Z * _axis;
float L1 = impulse.X * _s1 + impulse.Y + impulse.Z * _a1;
float L2 = impulse.X * _s2 + impulse.Y + impulse.Z * _a2;
c1 -= InvMassA * P;
a1 -= InvIA * L1;
c2 += InvMassB * P;
a2 += InvIB * L2;
// TODO_ERIN remove need for this.
b1.Sweep.C = c1;
b1.Sweep.A = a1;
b2.Sweep.C = c2;
b2.Sweep.A = a2;
b1.SynchronizeTransform();
b2.SynchronizeTransform();
return linearError <= Settings.LinearSlop && angularError <= Settings.AngularSlop;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Debug.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Configuration {
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
internal static class Debug {
internal const string TAG_INTERNAL = "Internal";
internal const string TAG_EXTERNAL = "External";
internal const string TAG_ALL = "*";
internal const string DATE_FORMAT = @"yyyy/MM/dd HH:mm:ss.ffff";
internal const string TIME_FORMAT = @"HH:mm:ss:ffff";
#if DBG
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
private static class NativeMethods {
[DllImport("kernel32.dll")]
[ResourceExposure(ResourceScope.Process)]
internal extern static int GetCurrentProcessId();
[DllImport("kernel32.dll")]
[Obsolete("Don't use this - fiber mode issues.")]
[ResourceExposure(ResourceScope.Process)]
internal extern static int GetCurrentThreadId();
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
[ResourceExposure(ResourceScope.Process)]
internal extern static IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError=true)]
[ResourceExposure(ResourceScope.Process)]
internal extern static bool TerminateProcess(HandleRef processHandle, int exitCode);
[DllImport("kernel32.dll", CharSet=CharSet.Auto, BestFitMapping=false)]
[ResourceExposure(ResourceScope.None)]
internal extern static void OutputDebugString(string message);
internal const int PM_NOREMOVE = 0x0000;
internal const int PM_REMOVE = 0x0001;
[StructLayout(LayoutKind.Sequential)]
internal struct MSG {
internal IntPtr hwnd;
internal int message;
internal IntPtr wParam;
internal IntPtr lParam;
internal int time;
internal int pt_x;
internal int pt_y;
}
[DllImport("user32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
internal extern static bool PeekMessage([In, Out] ref MSG msg, HandleRef hwnd, int msgMin, int msgMax, int remove);
internal const int
MB_OK = 0x00000000,
MB_OKCANCEL = 0x00000001,
MB_ABORTRETRYIGNORE = 0x00000002,
MB_YESNOCANCEL = 0x00000003,
MB_YESNO = 0x00000004,
MB_RETRYCANCEL = 0x00000005,
MB_ICONHAND = 0x00000010,
MB_ICONQUESTION = 0x00000020,
MB_ICONEXCLAMATION = 0x00000030,
MB_ICONASTERISK = 0x00000040,
MB_USERICON = 0x00000080,
MB_ICONWARNING = 0x00000030,
MB_ICONERROR = 0x00000010,
MB_ICONINFORMATION = 0x00000040,
MB_DEFBUTTON1 = 0x00000000,
MB_DEFBUTTON2 = 0x00000100,
MB_DEFBUTTON3 = 0x00000200,
MB_DEFBUTTON4 = 0x00000300,
MB_APPLMODAL = 0x00000000,
MB_SYSTEMMODAL = 0x00001000,
MB_TASKMODAL = 0x00002000,
MB_HELP = 0x00004000,
MB_NOFOCUS = 0x00008000,
MB_SETFOREGROUND = 0x00010000,
MB_DEFAULT_DESKTOP_ONLY = 0x00020000,
MB_TOPMOST = 0x00040000,
MB_RIGHT = 0x00080000,
MB_RTLREADING = 0x00100000,
MB_SERVICE_NOTIFICATION = 0x00200000,
MB_SERVICE_NOTIFICATION_NT3X = 0x00040000,
MB_TYPEMASK = 0x0000000F,
MB_ICONMASK = 0x000000F0,
MB_DEFMASK = 0x00000F00,
MB_MODEMASK = 0x00003000,
MB_MISCMASK = 0x0000C000;
internal const int
IDOK = 1,
IDCANCEL = 2,
IDABORT = 3,
IDRETRY = 4,
IDIGNORE = 5,
IDYES = 6,
IDNO = 7,
IDCLOSE = 8,
IDHELP = 9;
[DllImport("user32.dll", CharSet=CharSet.Auto, BestFitMapping=false)]
[ResourceExposure(ResourceScope.None)]
internal extern static int MessageBox(HandleRef hWnd, string text, string caption, int type);
internal static readonly IntPtr HKEY_LOCAL_MACHINE = unchecked((IntPtr)(int)0x80000002);
internal const int READ_CONTROL = 0x00020000;
internal const int STANDARD_RIGHTS_READ = READ_CONTROL;
internal const int SYNCHRONIZE = 0x00100000;
internal const int KEY_QUERY_VALUE = 0x0001;
internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008;
internal const int KEY_NOTIFY = 0x0010;
internal const int KEY_READ = ((STANDARD_RIGHTS_READ |
KEY_QUERY_VALUE |
KEY_ENUMERATE_SUB_KEYS |
KEY_NOTIFY)
&
(~SYNCHRONIZE));
internal const int REG_NOTIFY_CHANGE_NAME = 1;
internal const int REG_NOTIFY_CHANGE_LAST_SET = 4;
[DllImport("advapi32.dll", CharSet=CharSet.Auto, BestFitMapping=false, SetLastError=true)]
[ResourceExposure(ResourceScope.Machine)]
internal extern static int RegOpenKeyEx(IntPtr hKey, string lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult);
[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true)]
[ResourceExposure(ResourceScope.None)]
internal extern static int RegNotifyChangeKeyValue(SafeRegistryHandle hKey, bool watchSubTree, uint notifyFilter, SafeWaitHandle regEvent, bool async);
}
private class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid {
// Note: Officially -1 is the recommended invalid handle value for
// registry keys, but we'll also get back 0 as an invalid handle from
// RegOpenKeyEx.
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode=true)]
internal SafeRegistryHandle() : base(true) {}
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode=true)]
internal SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) {
SetHandle(preexistingHandle);
}
[DllImport("advapi32.dll"),
SuppressUnmanagedCodeSecurity,
ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
private static extern int RegCloseKey(IntPtr hKey);
override protected bool ReleaseHandle()
{
// Returns a Win32 error code, 0 for success
int r = RegCloseKey(handle);
return r == 0;
}
}
private enum TagValue {
Disabled = 0,
Enabled = 1,
Break = 2,
Min = Disabled,
Max = Break,
}
private const string TAG_ASSERT = "Assert";
private const string TAG_ASSERT_BREAK = "AssertBreak";
private const string TAG_DEBUG_VERBOSE = "DebugVerbose";
private const string TAG_DEBUG_MONITOR = "DebugMonitor";
private const string TAG_DEBUG_PREFIX = "DebugPrefix";
private const string TAG_DEBUG_THREAD_PREFIX = "DebugThreadPrefix";
private const string PRODUCT = "Microsoft .NET Framework";
private const string COMPONENT = "System.Configuration";
private static string s_regKeyName = @"Software\Microsoft\ASP.NET\Debug";
private static string s_listenKeyName = @"Software\Microsoft";
private static volatile bool s_assert;
private static volatile bool s_assertBreak;
private static volatile bool s_includePrefix;
private static volatile bool s_includeThreadPrefix;
private static volatile bool s_monitor;
private static object s_lock;
private static volatile bool s_inited;
private static ReadOnlyCollection<Tag> s_tagDefaults;
private static volatile List<Tag> s_tags;
private static volatile AutoResetEvent s_notifyEvent;
private static volatile RegisteredWaitHandle s_waitHandle;
private static volatile SafeRegistryHandle s_regHandle;
private static volatile bool s_stopMonitoring;
private static volatile Hashtable s_tableAlwaysValidate;
private static volatile Type[] s_DumpArgs;
private static volatile Type[] s_ValidateArgs;
private class Tag {
string _name;
TagValue _value;
int _prefixLength;
internal Tag(string name, TagValue value) {
_name = name;
_value = value;
if (_name[_name.Length - 1] == '*') {
_prefixLength = _name.Length - 1;
}
else {
_prefixLength = -1;
}
}
internal string Name {
get {return _name;}
}
internal TagValue Value {
get {return _value;}
}
internal int PrefixLength {
get {return _prefixLength;}
}
}
static Debug() {
s_lock = new object();
}
private static void EnsureInit() {
bool continueInit = false;
if (!s_inited) {
lock (s_lock) {
if (!s_inited) {
s_tableAlwaysValidate = new Hashtable();
s_DumpArgs = new Type[1] {typeof(string)};
s_ValidateArgs = new Type[0];
List<Tag> tagDefaults = new List<Tag>();
tagDefaults.Add(new Tag(TAG_ALL, TagValue.Disabled));
tagDefaults.Add(new Tag(TAG_INTERNAL, TagValue.Enabled));
tagDefaults.Add(new Tag(TAG_EXTERNAL, TagValue.Enabled));
tagDefaults.Add(new Tag(TAG_ASSERT, TagValue.Break));
tagDefaults.Add(new Tag(TAG_ASSERT_BREAK, TagValue.Disabled));
tagDefaults.Add(new Tag(TAG_DEBUG_VERBOSE, TagValue.Enabled));
tagDefaults.Add(new Tag(TAG_DEBUG_MONITOR, TagValue.Enabled));
tagDefaults.Add(new Tag(TAG_DEBUG_PREFIX, TagValue.Enabled));
tagDefaults.Add(new Tag(TAG_DEBUG_THREAD_PREFIX, TagValue.Enabled));
s_tagDefaults = tagDefaults.AsReadOnly();
s_tags = new List<Tag>(s_tagDefaults);
GetBuiltinTagValues();
continueInit = true;
s_inited = true;
}
}
}
// Work to do outside the init lock.
if (continueInit) {
ReadTagsFromRegistry();
Trace(TAG_DEBUG_VERBOSE, "Debugging package initialized");
// Need to read tags before starting to monitor in order to get TAG_DEBUG_MONITOR
StartRegistryMonitor();
}
}
private static bool StringEqualsIgnoreCase(string s1, string s2) {
return StringComparer.OrdinalIgnoreCase.Equals(s1, s2);
}
[RegistryPermission(SecurityAction.Assert, Unrestricted=true)]
private static void WriteTagsToRegistry() {
try {
using (RegistryKey key = Registry.LocalMachine.CreateSubKey(s_regKeyName)) {
List<Tag> tags = s_tags;
foreach (Tag tag in tags) {
key.SetValue(tag.Name, tag.Value, RegistryValueKind.DWord);
}
}
}
catch {
}
}
private static void GetBuiltinTagValues() {
// Use GetTagValue instead of IsTagEnabled because it does not call EnsureInit
// and potentially recurse.
s_assert = (GetTagValue(TAG_ASSERT) != TagValue.Disabled);
s_assertBreak = (GetTagValue(TAG_ASSERT_BREAK) != TagValue.Disabled);
s_includePrefix = (GetTagValue(TAG_DEBUG_PREFIX) != TagValue.Disabled);
s_includeThreadPrefix = (GetTagValue(TAG_DEBUG_THREAD_PREFIX) != TagValue.Disabled);
s_monitor = (GetTagValue(TAG_DEBUG_MONITOR) != TagValue.Disabled);
}
[RegistryPermission(SecurityAction.Assert, Unrestricted=true)]
private static void ReadTagsFromRegistry() {
lock (s_lock) {
try {
List<Tag> tags = new List<Tag>(s_tagDefaults);
string[] names = null;
bool writeTags = false;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(s_regKeyName, false)) {
if (key != null) {
names = key.GetValueNames();
foreach (string name in names) {
TagValue value = TagValue.Disabled;
try {
TagValue keyvalue = (TagValue) key.GetValue(name);
if (TagValue.Min <= keyvalue && keyvalue <= TagValue.Max) {
value = keyvalue;
}
else {
writeTags = true;
}
}
catch {
writeTags = true;
}
// Add tag to list, making sure it is unique.
Tag tag = new Tag(name, (TagValue) value);
bool found = false;
for (int i = 0; i < s_tagDefaults.Count; i++) {
if (StringEqualsIgnoreCase(name, tags[i].Name)) {
found = true;
tags[i] = tag;
break;
}
}
if (!found) {
tags.Add(tag);
}
}
}
}
s_tags = tags;
GetBuiltinTagValues();
// Write tags out if there was an invalid value or
// not all default tags are present.
if (writeTags || (names != null && names.Length < tags.Count)) {
WriteTagsToRegistry();
}
}
catch {
s_tags = new List<Tag>(s_tagDefaults);
}
}
}
private static void StartRegistryMonitor() {
if (!s_monitor) {
Trace(TAG_DEBUG_VERBOSE, "WARNING: Registry monitoring disabled, changes during process execution will not be recognized.");
return;
}
Trace(TAG_DEBUG_VERBOSE, "Monitoring registry key " + s_listenKeyName + " for changes.");
// Event used to notify of changes.
s_notifyEvent = new AutoResetEvent(false);
// Register a wait on the event.
s_waitHandle = ThreadPool.RegisterWaitForSingleObject(s_notifyEvent, OnRegChangeKeyValue, null, -1, false);
// Monitor the registry.
MonitorRegistryForOneChange();
}
private static void StopRegistryMonitor() {
// Cleanup allocated handles
s_stopMonitoring = true;
if (s_regHandle != null) {
s_regHandle.Close();
s_regHandle = null;
}
if (s_waitHandle != null) {
s_waitHandle.Unregister(s_notifyEvent);
s_waitHandle = null;
}
if (s_notifyEvent != null) {
s_notifyEvent.Close();
s_notifyEvent = null;
}
Trace(TAG_DEBUG_VERBOSE, "Registry monitoring stopped.");
}
public static void OnRegChangeKeyValue(object state, bool timedOut) {
if (!s_stopMonitoring) {
if (timedOut) {
StopRegistryMonitor();
}
else {
// Monitor again
MonitorRegistryForOneChange();
// Once we're monitoring, read the changes to the registry.
// We have to do this after we start monitoring in order
// to catch all changes to the registry.
ReadTagsFromRegistry();
}
}
}
private static void MonitorRegistryForOneChange() {
// Close the open reg handle
if (s_regHandle != null) {
s_regHandle.Close();
s_regHandle = null;
}
// Open the reg key
SafeRegistryHandle regHandle;
int result = NativeMethods.RegOpenKeyEx(NativeMethods.HKEY_LOCAL_MACHINE, s_listenKeyName, 0, NativeMethods.KEY_READ, out regHandle);
s_regHandle = regHandle;
if (result != 0) {
StopRegistryMonitor();
return;
}
// Listen for changes.
result = NativeMethods.RegNotifyChangeKeyValue(
s_regHandle,
true,
NativeMethods.REG_NOTIFY_CHANGE_NAME | NativeMethods.REG_NOTIFY_CHANGE_LAST_SET,
s_notifyEvent.SafeWaitHandle,
true);
if (result != 0) {
StopRegistryMonitor();
}
}
private static Tag FindMatchingTag(string name, bool exact) {
List<Tag> tags = s_tags;
// Look for exact match first
foreach (Tag tag in tags) {
if (StringEqualsIgnoreCase(name, tag.Name)) {
return tag;
}
}
if (exact) {
return null;
}
Tag longestTag = null;
int longestPrefix = -1;
foreach (Tag tag in tags) {
if ( tag.PrefixLength > longestPrefix &&
0 == string.Compare(name, 0, tag.Name, 0, tag.PrefixLength, StringComparison.OrdinalIgnoreCase)) {
longestTag = tag;
longestPrefix = tag.PrefixLength;
}
}
return longestTag;
}
private static TagValue GetTagValue(string name) {
Tag tag = FindMatchingTag(name, false);
if (tag != null) {
return tag.Value;
}
else {
return TagValue.Disabled;
}
}
private static bool TraceBreak(string tagName, string message, Exception e, bool includePrefix) {
EnsureInit();
TagValue tagValue = GetTagValue(tagName);
if (tagValue == TagValue.Disabled) {
return false;
}
bool isAssert = object.ReferenceEquals(tagName, TAG_ASSERT);
if (isAssert) {
tagName = "";
}
string exceptionMessage = null;
if (e != null) {
string errorCode = null;
if (e is ExternalException) {
errorCode = "_hr=0x" + ((ExternalException)e).ErrorCode.ToString("x", CultureInfo.InvariantCulture);
}
// Use e.ToString() in order to get inner exception
if (errorCode != null) {
exceptionMessage = "Exception " + e.ToString() + "\n" + errorCode;
}
else {
exceptionMessage = "Exception " + e.ToString();
}
}
if (string.IsNullOrEmpty(message) & exceptionMessage != null) {
message = exceptionMessage;
exceptionMessage = null;
}
string traceFormat;
int idThread = 0;
int idProcess = 0;
if (!includePrefix || !s_includePrefix) {
traceFormat = "{4}\n{5}";
}
else {
if (s_includeThreadPrefix) {
// GetCurrentThreadId() is marked as obsolete, but this code is only used in debug builds,
// so it's OK to disable the obsoletion warning.
#pragma warning disable 0618
idThread = NativeMethods.GetCurrentThreadId();
#pragma warning restore 0618
idProcess = NativeMethods.GetCurrentProcessId();
traceFormat = "[0x{0:x}.{1:x} {2} {3}] {4}\n{5}";
}
else {
traceFormat = "[{2} {3}] {4}\n{5}";
}
}
string suffix = "";
if (exceptionMessage != null) {
suffix += exceptionMessage + "\n";
}
bool doBreak = (tagValue == TagValue.Break);
if (doBreak && !isAssert) {
suffix += "Breaking into debugger...\n";
}
string traceMessage = string.Format(CultureInfo.InvariantCulture, traceFormat, idProcess, idThread, COMPONENT, tagName, message, suffix);
NativeMethods.OutputDebugString(traceMessage);
return doBreak;
}
private class MBResult {
internal int Result;
}
static bool DoAssert(string message) {
if (!s_assert) {
return false;
}
// Skip 2 frames - one for this function, one for
// the public Assert function that called this function.
System.Diagnostics.StackFrame frame = new System.Diagnostics.StackFrame(2, true);
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(2, true);
string fileName = frame.GetFileName();
int lineNumber = frame.GetFileLineNumber();
string traceFormat;
if (!string.IsNullOrEmpty(fileName)) {
traceFormat = "ASSERTION FAILED: {0}\nFile: {1}:{2}\nStack trace:\n{3}";
}
else {
traceFormat = "ASSERTION FAILED: {0}\nStack trace:\n{3}";
}
string traceMessage = string.Format(CultureInfo.InvariantCulture, traceFormat, message, fileName, lineNumber, trace.ToString());
if (!TraceBreak(TAG_ASSERT, traceMessage, null, true)) {
// If the value of "Assert" is not TagValue.Break, then don't even ask user.
return false;
}
if (s_assertBreak) {
// If "AssertBreak" is enabled, then always break.
return true;
}
string dialogFormat;
if (!string.IsNullOrEmpty(fileName)) {
dialogFormat =
@"Failed expression: {0}
File: {1}:{2}
Component: {3}
PID={4} TID={5}
Stack trace:
{6}
A=Exit process R=Debug I=Continue";
}
else {
dialogFormat =
@"Failed expression: {0}
(no file information available)
Component: {3}
PID={4} TID={5}
Stack trace:
{6}
A=Exit process R=Debug I=Continue";
}
// GetCurrentThreadId() is marked as obsolete, but this code is only used in debug builds,
// so it's OK to disable the obsoletion warning.
#pragma warning disable 0618
string dialogMessage = string.Format(
CultureInfo.InvariantCulture,
dialogFormat,
message,
fileName, lineNumber,
COMPONENT,
NativeMethods.GetCurrentProcessId(), NativeMethods.GetCurrentThreadId(),
trace.ToString());
#pragma warning restore 0618
MBResult mbResult = new MBResult();
Thread thread = new Thread(
delegate() {
for (int i = 0; i < 100; i++) {
NativeMethods.MSG msg = new NativeMethods.MSG();
NativeMethods.PeekMessage(ref msg, new HandleRef(mbResult, IntPtr.Zero), 0, 0, NativeMethods.PM_REMOVE);
}
mbResult.Result = NativeMethods.MessageBox(new HandleRef(mbResult, IntPtr.Zero), dialogMessage, PRODUCT + " Assertion",
NativeMethods.MB_SERVICE_NOTIFICATION |
NativeMethods.MB_TOPMOST |
NativeMethods.MB_ABORTRETRYIGNORE |
NativeMethods.MB_ICONEXCLAMATION);
}
);
thread.Start();
thread.Join();
if (mbResult.Result == NativeMethods.IDABORT) {
IntPtr currentProcess = NativeMethods.GetCurrentProcess();
NativeMethods.TerminateProcess(new HandleRef(mbResult, currentProcess), 1);
}
return mbResult.Result == NativeMethods.IDRETRY;
}
#endif
//
// Sends the message to the debugger if the tag is enabled.
// Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
//
[System.Diagnostics.Conditional("DBG")]
internal static void Trace(string tagName, string message) {
#if DBG
if (TraceBreak(tagName, message, null, true)) {
Break();
}
#endif
}
//
// Sends the message to the debugger if the tag is enabled.
// Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
//
[System.Diagnostics.Conditional("DBG")]
internal static void Trace(string tagName, string message, bool includePrefix) {
#if DBG
if (TraceBreak(tagName, message, null, includePrefix)) {
Break();
}
#endif
}
//
// Sends the message to the debugger if the tag is enabled.
// Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
//
[System.Diagnostics.Conditional("DBG")]
internal static void Trace(string tagName, string message, Exception e) {
#if DBG
if (TraceBreak(tagName, message, e, true)) {
Break();
}
#endif
}
//
// Sends the message to the debugger if the tag is enabled.
// Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
//
[System.Diagnostics.Conditional("DBG")]
internal static void Trace(string tagName, Exception e) {
#if DBG
if (TraceBreak(tagName, null, e, true)) {
Break();
}
#endif
}
//
// Sends the message to the debugger if the tag is enabled.
// Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
//
[System.Diagnostics.Conditional("DBG")]
internal static void Trace(string tagName, string message, Exception e, bool includePrefix) {
#if DBG
if (TraceBreak(tagName, message, e, includePrefix)) {
Break();
}
#endif
}
#if DBG
#endif
#if UNUSED_CODE
[System.Diagnostics.Conditional("DBG")]
public static void TraceException(String tagName, Exception e) {
#if DBG
if (TraceBreak(tagName, null, e, true)) {
Break();
}
#endif
}
#endif
//
// If the assertion is false and the 'Assert' tag is enabled:
// * Send a message to the debugger.
// * If the 'AssertBreak' tag is enabled, immediately break into the debugger
// * Else display a dialog box asking the user to Abort, Retry (break), or Ignore
//
[System.Diagnostics.Conditional("DBG")]
internal static void Assert(bool assertion, string message) {
#if DBG
EnsureInit();
if (assertion == false) {
if (DoAssert(message)) {
Break();
}
}
#endif
}
//
// If the assertion is false and the 'Assert' tag is enabled:
// * Send a message to the debugger.
// * If the 'AssertBreak' tag is enabled, immediately break into the debugger
// * Else display a dialog box asking the user to Abort, Retry (break), or Ignore
//
[System.Diagnostics.Conditional("DBG")]
internal static void Assert(bool assertion) {
#if DBG
EnsureInit();
if (assertion == false) {
if (DoAssert(null)) {
Break();
}
}
#endif
}
//
// Like Assert, but the assertion is always considered to be false.
//
[System.Diagnostics.Conditional("DBG")]
internal static void Fail(string message) {
#if DBG
Assert(false, message);
#endif
}
//
// Returns true if the tag is enabled, false otherwise.
// Note that the tag needn't be an exact match.
//
internal static bool IsTagEnabled(string tagName) {
#if DBG
EnsureInit();
return GetTagValue(tagName) != TagValue.Disabled;
#else
return false;
#endif
}
//
// Returns true if the tag present.
// This function chekcs for an exact match.
//
internal static bool IsTagPresent(string tagName) {
#if DBG
EnsureInit();
return FindMatchingTag(tagName, true) != null;
#else
return false;
#endif
}
//
// Breaks into the debugger, or launches one if not yet attached.
//
[System.Diagnostics.Conditional("DBG")]
internal static void Break() {
#if DBG
if (!System.Diagnostics.Debugger.IsAttached) {
System.Diagnostics.Debugger.Launch();
}
else {
System.Diagnostics.Debugger.Break();
}
#endif
}
//
// Tells the debug system to always validate calls for a
// particular tag. This is useful for temporarily enabling
// validation in stress tests or other situations where you
// may not have control over the debug tags that are enabled
// on a particular machine.
//
[System.Diagnostics.Conditional("DBG")]
internal static void AlwaysValidate(string tagName) {
#if DBG
EnsureInit();
s_tableAlwaysValidate[tagName] = tagName;
#endif
}
//
// Throws an exception if the assertion is not valid.
// Use this function from a DebugValidate method where
// you would otherwise use Assert.
//
[System.Diagnostics.Conditional("DBG")]
internal static void CheckValid(bool assertion, string message) {
#if DBG
if (!assertion) {
throw new Exception(message);
}
#endif
}
//
// Calls DebugValidate on an object if such a method exists.
//
// This method should be used from implementations of DebugValidate
// where it is unknown whether an object has a DebugValidate method.
// For example, the DoubleLink class uses it to validate the
// item of type Object which it points to.
//
// This method should NOT be used when code wants to conditionally
// validate an object and have a failed validation caught in an assert.
// Use Debug.Validate(tagName, obj) for that purpose.
//
[System.Diagnostics.Conditional("DBG")]
internal static void Validate(Object obj) {
#if DBG
Type type;
MethodInfo mi;
if (obj != null) {
type = obj.GetType();
mi = type.GetMethod(
"DebugValidate",
BindingFlags.NonPublic | BindingFlags.Instance,
null,
s_ValidateArgs,
null);
if (mi != null) {
object[] tempIndex = null;
mi.Invoke(obj, tempIndex);
}
}
#endif
}
//
// Validates an object is the "Validate" tag is enabled, or when
// the "Validate" tag is not disabled and the given 'tag' is enabled.
// An Assertion is made if the validation fails.
//
[System.Diagnostics.Conditional("DBG")]
internal static void Validate(string tagName, Object obj) {
#if DBG
EnsureInit();
if ( obj != null
&& ( IsTagEnabled("Validate")
|| ( !IsTagPresent("Validate")
&& ( s_tableAlwaysValidate[tagName] != null
|| IsTagEnabled(tagName))))) {
try {
Debug.Validate(obj);
}
catch (Exception e) {
Debug.Assert(false, "Validate failed: " + e.InnerException.Message);
}
}
#endif
}
#if DBG
//
// Calls DebugDescription on an object to get its description.
//
// This method should only be used in implementations of DebugDescription
// where it is not known whether a nested objects has an implementation
// of DebugDescription. For example, the double linked list class uses
// GetDescription to get the description of the item it points to.
//
// This method should NOT be used when you want to conditionally
// dump an object. Use Debug.Dump instead.
//
// @param obj The object to call DebugDescription on. May be null.
// @param indent A prefix for each line in the description. This is used
// to allow the nested display of objects within other objects.
// The indent is usually a multiple of four spaces.
//
// @return The description.
//
[ReflectionPermission(SecurityAction.Assert, Unrestricted=true)]
internal static string GetDescription(Object obj, string indent) {
string description;
Type type;
MethodInfo mi;
Object[] parameters;
if (obj == null) {
description = "\n";
}
else {
type = obj.GetType();
mi = type.GetMethod(
"DebugDescription",
BindingFlags.NonPublic | BindingFlags.Instance,
null,
s_DumpArgs,
null);
if (mi == null || mi.ReturnType != typeof(string)) {
description = indent + obj.ToString();
}
else {
parameters = new Object[1] {(Object) indent};
description = (string) mi.Invoke(obj, parameters);
}
}
return description;
}
#endif
//
// Dumps an object to the debugger if the "Dump" tag is enabled,
// or if the "Dump" tag is not present and the 'tag' is enabled.
//
// @param tagName The tag to Dump with.
// @param obj The object to dump.
//
[System.Diagnostics.Conditional("DBG")]
internal static void Dump(string tagName, Object obj) {
#if DBG
EnsureInit();
string description;
string traceTag = null;
bool dumpEnabled, dumpPresent;
if (obj != null) {
dumpEnabled = IsTagEnabled("Dump");
dumpPresent = IsTagPresent("Dump");
if (dumpEnabled || !dumpPresent) {
if (IsTagEnabled(tagName)) {
traceTag = tagName;
}
else if (dumpEnabled) {
traceTag = "Dump";
}
if (traceTag != null) {
description = GetDescription(obj, string.Empty);
Debug.Trace(traceTag, "Dump\n" + description);
}
}
}
#endif
}
#if UNUSED_CODE
#if DBG
static internal string ToStringMaybeNull(object o) {
if (o != null) {
return o.ToString();
}
return "<null>";
}
#endif
static internal string FormatUtcDate(DateTime utcTime) {
#if DBG
DateTime localTime = DateTimeUtil.ConvertToLocalTime(utcTime);
return localTime.ToString(DATE_FORMAT, CultureInfo.InvariantCulture);
#else
return string.Empty;
#endif
}
static internal string FormatLocalDate(DateTime localTime) {
#if DBG
return localTime.ToString(DATE_FORMAT, CultureInfo.InvariantCulture);
#else
return string.Empty;
#endif
}
#endif // UNUSED_CODE
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace KaoriStudio.Core.IO
{
/// <summary>
/// Random access stream welder
/// </summary>
public class WeldStream : Stream
{
long position;
StreamFactory factory;
/// <summary>
/// Welds multiple streams togeter
/// </summary>
/// <param name="streams">The streams to be welded</param>
/// <param name="leaveOpen">If false, streams are disposed with the weld</param>
/// <param name="closeBehind">If true, streams are closed after they are passed over</param>
public WeldStream(IEnumerable<Stream> streams, bool leaveOpen, bool closeBehind)
{
this.factory = new StreamFactory(streams.GetEnumerator(), leaveOpen, closeBehind);
}
/// <inheritdoc cref="WeldStream.WeldStream(IEnumerable{Stream}, bool, bool)"/>
public WeldStream(IEnumerable<Stream> streams, bool leaveOpen) : this(streams, leaveOpen, false) { }
/// <inheritdoc cref="WeldStream.WeldStream(IEnumerable{Stream}, bool, bool)"/>
public WeldStream(IEnumerable<Stream> streams) : this(streams, false, false)
{
}
/// <summary>
/// Greedily evaluate all remaining streams and calculate the total length.
/// </summary>
public override long Length
{
get
{
return factory.ProduceUntil(long.MaxValue);
}
}
/// <inheritdoc/>
public override bool CanRead
{
get
{
return true;
}
}
/// <inheritdoc/>
public override bool CanSeek
{
get
{
return true;
}
}
/// <inheritdoc/>
public override bool CanWrite
{
get
{
return true;
}
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
factory.Dispose();
}
/// <summary>
/// The logical position of the weld.
/// </summary>
public override long Position
{
get
{
return position;
}
set
{
factory.Synchronize(position = value);
}
}
/// <inheritdoc/>
public override void Flush()
{
factory.Flush();
}
/// <inheritdoc/>
public override long Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
return Position = offset;
case SeekOrigin.Current:
return Position += offset;
case SeekOrigin.End:
return Position = Length + offset;
default:
throw new ArgumentOutOfRangeException("origin");
}
}
/// <inheritdoc/>
public override void SetLength(long value)
{
var length = Length;
var change = value - Length;
var lastStream = factory.Last.Value;
lastStream.SetLength(lastStream.Length + change);
}
/// <inheritdoc/>
public override int Read(byte[] buffer, int offset, int count)
{
int total = 0;
while(total < count)
{
var product = factory.Synchronize(position);
if (product.Key == -1 || !product.Value.CanRead)
break;
int ramount = count - total;
int amount = product.Value.Read(buffer, offset + total, ramount);
total += amount;
position += amount;
if (amount < ramount)
break;
}
return total;
}
/// <inheritdoc/>
public override int ReadByte()
{
var product = factory.Synchronize(position);
if (product.Key == -1 || !product.Value.CanRead)
return -1;
return product.Value.ReadByte();
}
/// <inheritdoc/>
public override void Write(byte[] buffer, int offset, int count)
{
int total = 0;
while(total < count)
{
var product = factory.Synchronize(position);
if (product.Key == -1 || !product.Value.CanWrite)
break;
int amount = (int)(product.Key + product.Value.Length);
if ((amount + total) > count)
{
amount = count - total;
}
product.Value.Write(buffer, offset + total, amount);
total += amount;
}
}
/// <inheritdoc/>
public override void WriteByte(byte value)
{
var product = factory.Synchronize(position);
if (product.Key == -1 || !product.Value.CanRead)
return;
product.Value.WriteByte(value);
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using ESRI.ArcGIS.Analyst3D;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using System.Runtime.InteropServices;
namespace sceneTools
{
[ClassInterface(ClassInterfaceType.None)]
[Guid("7B9ECCAC-4B67-4795-9E1E-1EAF7CC64CE4")]
public sealed class SelectFeatures : BaseTool
{
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType);
//
// TODO: Add any COM registration code here
//
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType);
//
// TODO: Add any COM unregistration code here
//
}
#region ArcGIS Component Category Registrar generated code
/// <summary>
/// Required method for ArcGIS Component Category registration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryRegistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ControlsCommands.Register(regKey);
}
/// <summary>
/// Required method for ArcGIS Component Category unregistration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryUnregistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ControlsCommands.Unregister(regKey);
}
#endregion
#endregion
private System.Windows.Forms.Cursor m_pCursor;
private ISceneHookHelper m_pSceneHookHelper;
public SelectFeatures()
{
base.m_category = "Sample_SceneControl(C#)";
base.m_caption = "Select Features";
base.m_toolTip = "Select Features";
base.m_name = "Sample_SceneControl(C#)/SelectFeatures";
base.m_message = "Select features by clicking";
//Load resources
string[] res = GetType().Assembly.GetManifestResourceNames();
if(res.GetLength(0) > 0)
{
base.m_bitmap = new System.Drawing.Bitmap(GetType().Assembly.GetManifestResourceStream("sceneTools.SelectFeatures.bmp"));
}
m_pCursor = new System.Windows.Forms.Cursor(GetType().Assembly.GetManifestResourceStream("sceneTools.SelectFeatures.cur"));
m_pSceneHookHelper = new SceneHookHelperClass ();
}
public override void OnCreate(object hook)
{
m_pSceneHookHelper.Hook = hook;
}
public override bool Enabled
{
get
{
if(m_pSceneHookHelper.Hook == null || m_pSceneHookHelper.Scene == null)
return false;
else
{
IScene pScene = (IScene) m_pSceneHookHelper.Scene;
//Disable if no layer
if(pScene.LayerCount == 0)
return false;
//Enable if any selectable layers
bool bSelectable = false;
IEnumLayer pEnumLayer;
pEnumLayer = pScene.get_Layers(null, true);
pEnumLayer.Reset();
ILayer pLayer = (ILayer) pEnumLayer.Next();
//Loop through the scene layers
do
{
//Determine if there is a selectable feature layer
if(pLayer is IFeatureLayer)
{
IFeatureLayer pFeatureLayer = (IFeatureLayer) pLayer;
if(pFeatureLayer.Selectable == true)
{
bSelectable = true;
break;
}
}
pLayer = pEnumLayer.Next();
}
while(pLayer != null);
return bSelectable;
}
}
}
public override int Cursor
{
get
{
return m_pCursor.Handle.ToInt32();
}
}
public override bool Deactivate()
{
return true;
}
public override void OnMouseUp(int Button, int Shift, int X, int Y)
{
//Get the scene graph
ISceneGraph pSceneGraph = m_pSceneHookHelper.SceneGraph;
//Get the scene
IScene pScene = (IScene) m_pSceneHookHelper.Scene;
IPoint pPoint;
object pOwner, pObject;
//Translate screen coordinates into a 3D point
pSceneGraph.Locate(pSceneGraph.ActiveViewer, X, Y, esriScenePickMode.esriScenePickGeography, true, out pPoint, out pOwner, out pObject);
//Get a selection environment
ISelectionEnvironment pSelectionEnv;
pSelectionEnv = new SelectionEnvironmentClass();
if(Shift == 0)
{
pSelectionEnv.CombinationMethod = ESRI.ArcGIS.Carto.esriSelectionResultEnum.esriSelectionResultNew;
//Clear previous selection
if(pOwner == null)
{
pScene.ClearSelection();
return;
}
}
else
pSelectionEnv.CombinationMethod = ESRI.ArcGIS.Carto.esriSelectionResultEnum.esriSelectionResultAdd;
//If the layer is a selectable feature layer
if(pOwner is IFeatureLayer)
{
IFeatureLayer pFeatureLayer = (IFeatureLayer) pOwner;
if(pFeatureLayer.Selectable == true)
{
//Select by Shape
pScene.SelectByShape(pPoint, pSelectionEnv, false);
}
}
//Refresh the scene viewer
pSceneGraph.RefreshViewers();
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NonSilo.Tests.Utilities;
using NSubstitute;
using Orleans;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.MembershipService;
using TestExtensions;
using Xunit;
using Xunit.Abstractions;
namespace NonSilo.Tests.Membership
{
[TestCategory("BVT"), TestCategory("Membership")]
public class ClusterHealthMonitorTests
{
private readonly ITestOutputHelper output;
private readonly LoggerFactory loggerFactory;
private readonly ILocalSiloDetails localSiloDetails;
private readonly SiloAddress localSilo;
private readonly IFatalErrorHandler fatalErrorHandler;
private readonly IMembershipGossiper membershipGossiper;
private readonly SiloLifecycleSubject lifecycle;
private readonly List<DelegateAsyncTimer> timers;
private readonly ConcurrentQueue<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)> timerCalls;
private readonly DelegateAsyncTimerFactory timerFactory;
private readonly IRemoteSiloProber prober;
private readonly InMemoryMembershipTable membershipTable;
private readonly MembershipTableManager manager;
public ClusterHealthMonitorTests(ITestOutputHelper output)
{
MessagingStatisticsGroup.Init(true);
this.output = output;
this.loggerFactory = new LoggerFactory(new[] { new XunitLoggerProvider(this.output) });
this.localSiloDetails = Substitute.For<ILocalSiloDetails>();
this.localSilo = Silo("127.0.0.1:100@100");
this.localSiloDetails.SiloAddress.Returns(this.localSilo);
this.localSiloDetails.DnsHostName.Returns("MyServer11");
this.localSiloDetails.Name.Returns(Guid.NewGuid().ToString("N"));
this.fatalErrorHandler = Substitute.For<IFatalErrorHandler>();
this.membershipGossiper = Substitute.For<IMembershipGossiper>();
this.lifecycle = new SiloLifecycleSubject(this.loggerFactory.CreateLogger<SiloLifecycleSubject>());
this.timers = new List<DelegateAsyncTimer>();
this.timerCalls = new ConcurrentQueue<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)>();
this.timerFactory = new DelegateAsyncTimerFactory(
(period, name) =>
{
var t = new DelegateAsyncTimer(
overridePeriod =>
{
var task = new TaskCompletionSource<bool>();
this.timerCalls.Enqueue((overridePeriod, task));
return task.Task;
});
this.timers.Add(t);
return t;
});
this.prober = Substitute.For<IRemoteSiloProber>();
this.membershipTable = new InMemoryMembershipTable(new TableVersion(1, "1"));
this.manager = new MembershipTableManager(
localSiloDetails: this.localSiloDetails,
clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()),
membershipTable: membershipTable,
fatalErrorHandler: this.fatalErrorHandler,
gossiper: this.membershipGossiper,
log: this.loggerFactory.CreateLogger<MembershipTableManager>(),
timerFactory: new AsyncTimerFactory(this.loggerFactory),
this.lifecycle);
((ILifecycleParticipant<ISiloLifecycle>)this.manager).Participate(this.lifecycle);
}
/// <summary>
/// Tests basic operation of <see cref="ClusterHealthMonitor"/> and <see cref="SiloHealthMonitor"/>.
/// </summary>
[Fact]
public async Task ClusterHealthMonitor_BasicScenario()
{
var probeCalls = new ConcurrentQueue<(SiloAddress, int)>();
this.prober.Probe(default, default).ReturnsForAnyArgs(info =>
{
probeCalls.Enqueue((info.ArgAt<SiloAddress>(0), info.ArgAt<int>(1)));
return Task.CompletedTask;
});
var clusterMembershipOptions = new ClusterMembershipOptions();
var monitor = new ClusterHealthMonitor(
this.localSiloDetails,
this.manager,
this.loggerFactory.CreateLogger<ClusterHealthMonitor>(),
Options.Create(clusterMembershipOptions),
this.fatalErrorHandler,
null,
this.timerFactory);
((ILifecycleParticipant<ISiloLifecycle>)monitor).Participate(this.lifecycle);
var testAccessor = (ClusterHealthMonitor.ITestAccessor)monitor;
testAccessor.CreateMonitor = s => new SiloHealthMonitor(s, this.loggerFactory, this.prober);
await this.lifecycle.OnStart();
Assert.NotEmpty(this.timers);
Assert.Empty(testAccessor.MonitoredSilos);
var otherSilos = new[]
{
Entry(Silo("127.0.0.200:100@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:200@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:300@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:400@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:500@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:600@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:700@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:800@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:900@100"), SiloStatus.Active)
};
var lastVersion = testAccessor.ObservedVersion;
// Add the new silos
foreach (var entry in otherSilos)
{
var table = await this.membershipTable.ReadAll();
Assert.True(await this.membershipTable.InsertRow(entry, table.Version.Next()));
}
await this.manager.Refresh();
(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion) timer = (default, default);
while (!this.timerCalls.TryDequeue(out timer)) await Task.Delay(1);
timer.Completion.TrySetResult(true);
await Until(() => testAccessor.ObservedVersion > lastVersion);
lastVersion = testAccessor.ObservedVersion;
// No silos should be monitored by this silo until it becomes active.
Assert.Empty(testAccessor.MonitoredSilos);
await this.manager.UpdateStatus(SiloStatus.Active);
await Until(() => testAccessor.ObservedVersion > lastVersion);
lastVersion = testAccessor.ObservedVersion;
// Now that this silo is active, it should be monitoring some fraction of the other active silos
Assert.NotEmpty(testAccessor.MonitoredSilos);
Assert.DoesNotContain(testAccessor.MonitoredSilos, s => s.Key.Equals(this.localSilo));
Assert.Equal(clusterMembershipOptions.NumProbedSilos, testAccessor.MonitoredSilos.Count);
Assert.All(testAccessor.MonitoredSilos, m => m.Key.Equals(m.Value.SiloAddress));
Assert.Empty(probeCalls);
// Check that those silos are actually being probed periodically
while (!this.timerCalls.TryDequeue(out timer)) await Task.Delay(1);
timer.Completion.TrySetResult(true);
await Until(() => probeCalls.Count == clusterMembershipOptions.NumProbedSilos);
Assert.Equal(clusterMembershipOptions.NumProbedSilos, probeCalls.Count);
while (probeCalls.TryDequeue(out var call)) Assert.Contains(testAccessor.MonitoredSilos, k => k.Key.Equals(call.Item1));
foreach (var siloMonitor in testAccessor.MonitoredSilos.Values)
{
Assert.Equal(0, ((SiloHealthMonitor.ITestAccessor)siloMonitor).MissedProbes);
}
// Make the probes fail.
this.prober.Probe(default, default).ReturnsForAnyArgs(info =>
{
probeCalls.Enqueue((info.ArgAt<SiloAddress>(0), info.ArgAt<int>(1)));
return Task.FromException(new Exception("no"));
});
// The above call to specify the probe behaviour also enqueued a value, so clear it here.
while (probeCalls.TryDequeue(out _)) ;
for (var expectedMissedProbes = 1; expectedMissedProbes <= clusterMembershipOptions.NumMissedProbesLimit; expectedMissedProbes++)
{
var now = DateTime.UtcNow;
this.membershipTable.ClearCalls();
while (!this.timerCalls.TryDequeue(out timer)) await Task.Delay(1);
timer.Completion.TrySetResult(true);
// Wait for probes to be fired
await Until(() => probeCalls.Count == clusterMembershipOptions.NumProbedSilos);
while (probeCalls.TryDequeue(out var call)) ;
// Check that probes match the expected missed probes
var table = await this.membershipTable.ReadAll();
foreach (var siloMonitor in testAccessor.MonitoredSilos.Values)
{
Assert.Equal(expectedMissedProbes, ((SiloHealthMonitor.ITestAccessor)siloMonitor).MissedProbes);
var entry = table.Members.Single(m => m.Item1.SiloAddress.Equals(siloMonitor.SiloAddress)).Item1;
var votes = entry.GetFreshVotes(now, clusterMembershipOptions.DeathVoteExpirationTimeout);
if (expectedMissedProbes < clusterMembershipOptions.NumMissedProbesLimit)
{
Assert.Empty(votes);
}
else
{
// After a certain number of failures, a vote should be added to the table.
Assert.Single(votes);
}
}
}
// Make the probes succeed again.
this.prober.Probe(default, default).ReturnsForAnyArgs(info =>
{
probeCalls.Enqueue((info.ArgAt<SiloAddress>(0), info.ArgAt<int>(1)));
return Task.CompletedTask;
});
// The above call to specify the probe behaviour also enqueued a value, so clear it here.
while (probeCalls.TryDequeue(out _)) ;
while (!this.timerCalls.TryDequeue(out timer)) await Task.Delay(1);
timer.Completion.TrySetResult(true);
// Wait for probes to be fired
await Until(() => probeCalls.Count == clusterMembershipOptions.NumProbedSilos);
while (probeCalls.TryDequeue(out var call)) ;
foreach (var siloMonitor in testAccessor.MonitoredSilos.Values)
{
Assert.Equal(0, ((SiloHealthMonitor.ITestAccessor)siloMonitor).MissedProbes);
}
await StopLifecycle();
}
private static SiloAddress Silo(string value) => SiloAddress.FromParsableString(value);
private static MembershipEntry Entry(SiloAddress address, SiloStatus status) => new MembershipEntry { SiloAddress = address, Status = status };
private static async Task Until(Func<bool> condition)
{
var maxTimeout = 40_000;
while (!condition() && (maxTimeout -= 10) > 0) await Task.Delay(10);
Assert.True(maxTimeout > 0);
}
private async Task StopLifecycle(CancellationToken cancellation = default)
{
var stopped = this.lifecycle.OnStop(cancellation);
while (!stopped.IsCompleted)
{
while (this.timerCalls.TryDequeue(out var call)) call.Completion.TrySetResult(false);
await Task.Delay(15);
}
await stopped;
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder - Generate Inherited Documentation
// File : IndexedCommentsCache.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 12/06/2009
// Note : Copyright 2008-2009, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a class that is used to cache indexed XML comments files
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.6.0.5 02/27/2008 EFW Created the code
//=============================================================================
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Xml.XPath;
namespace SandcastleBuilder.Utils.InheritedDocumentation
{
/// <summary>
/// This is used to cache indexed XML comments files
/// </summary>
public class IndexedCommentsCache
{
#region Private data members
//=====================================================================
private Dictionary<string, string> index;
private Dictionary<string, IndexedCommentsFile> cache;
private List<string> lruList;
private int cacheSize, filesIndexed;
#endregion
#region Properties
//=====================================================================
/// <summary>
/// This read-only property returns the number of items indexed
/// </summary>
public int IndexCount
{
get { return index.Count; }
}
/// <summary>
/// This read-only property returns the number of comments files
/// that were indexed.
/// </summary>
public int FilesIndexed
{
get
{
return filesIndexed;
}
}
#endregion
#region Events
//=====================================================================
/// <summary>
/// This is used by the cache to report duplicate key warnings
/// </summary>
public event EventHandler<CommentsCacheEventArgs> ReportWarning;
/// <summary>
/// This is used to raise the <see cref="ReportWarning" /> event
/// </summary>
/// <param name="args">The event arguments</param>
protected virtual void OnReportWarning(CommentsCacheEventArgs args)
{
var handler = ReportWarning;
if(handler != null)
handler(this, args);
}
#endregion
#region Methods, etc
//=====================================================================
/// <summary>
/// Constructor
/// </summary>
/// <param name="size">The maximum size of the cache</param>
public IndexedCommentsCache(int size)
{
if(size < 0)
throw new ArgumentOutOfRangeException("size");
cacheSize = size;
index = new Dictionary<string, string>();
cache = new Dictionary<string, IndexedCommentsFile>(cacheSize);
lruList = new List<string>(cacheSize);
}
/// <summary>
/// Index all comments files found in the specified folder.
/// </summary>
/// <param name="path">The path to search. If null or empty, the
/// current directory is assumed.</param>
/// <param name="wildcard">The wildcard to use. If null or empty,
/// "*.xml" is assumed.</param>
/// <param name="recurse">True to recurse subfolders or false to only
/// use the given folder.</param>
/// <param name="commentsFiles">Optional. If not null, an
/// <see cref="XPathDocument"/> is added to the collection for each
/// file indexed.</param>
public void IndexCommentsFiles(string path, string wildcard,
bool recurse, Collection<XPathNavigator> commentsFiles)
{
XPathDocument xpathDoc;
string[] files, folders, keys;
if(String.IsNullOrEmpty(path))
path = Environment.CurrentDirectory;
else
path = Path.GetFullPath(path);
if(String.IsNullOrEmpty(wildcard))
wildcard = "*.xml";
files = Directory.GetFiles(path, wildcard);
// Index the file
foreach(string filename in files)
{
if(!filename.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
{
this.OnReportWarning(new CommentsCacheEventArgs(
"SHFB: Warning GID0007: Ignoring non-XML comments " +
"file: " + filename));
continue;
}
keys = new IndexedCommentsFile(filename).GetKeys();
if(commentsFiles != null)
{
xpathDoc = new XPathDocument(filename);
commentsFiles.Add(xpathDoc.CreateNavigator());
}
// Check for duplicates. If found, the last one in wins.
foreach(string key in keys)
{
if(index.ContainsKey(key))
this.OnReportWarning(new CommentsCacheEventArgs(
String.Format(CultureInfo.InvariantCulture,
"SHFB: Warning GID0008: Entries for the key " +
"'{0}' occur in both '{1}' and '{2}'. The " +
"entries in '{2}' will be used.", key, index[key],
filename)));
index[key] = filename;
}
}
filesIndexed += files.Length;
if(recurse)
{
folders = Directory.GetDirectories(path);
foreach(string folder in folders)
this.IndexCommentsFiles(folder, wildcard, recurse,
commentsFiles);
}
}
/// <summary>
/// Get the comments for the specified key
/// </summary>
/// <param name="key">The key for which to retrieve comments</param>
/// <returns>An <see cref="XPathNavigator"/> for the comments or null
/// if not found.</returns>
public XPathNavigator GetComments(string key)
{
IndexedCommentsFile document = this.GetCommentsFile(key);
if(document == null)
return null;
return document.GetContent(key);
}
/// <summary>
/// Get the comments file from the index cache that contains the given
/// key.
/// </summary>
/// <param name="key">The key for which to retrieve the file</param>
/// <returns>The indexed comments file or null if not found</returns>
public IndexedCommentsFile GetCommentsFile(string key)
{
IndexedCommentsFile document;
string filename;
if(index.TryGetValue(key, out filename))
{
if(!cache.TryGetValue(filename, out document))
{
document = new IndexedCommentsFile(filename);
if(cache.Count >= cacheSize)
{
cache.Remove(lruList[0]);
lruList.RemoveAt(0);
}
cache.Add(filename, document);
lruList.Add(filename);
}
else
{
// Since it got used, move it to the end of the list
// so that it stays around longer. This is a really
// basic Least Recently Used list.
lruList.Remove(filename);
lruList.Add(filename);
}
return document;
}
return null;
}
/// <summary>
/// Return all keys in this index
/// </summary>
/// <returns>A string array containing the keys</returns>
public string[] GetKeys()
{
string[] keys = new string[index.Count];
index.Keys.CopyTo(keys, 0);
return keys;
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//#define COMPUTECALLSCLOSURE_FORCE_SINGLE_THREADED
namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
public interface ICallClosureComputationTarget
{
void ExpandClosure( ComputeCallsClosure.Context host );
}
public sealed class ComputeCallsClosure
{
public delegate void Notification( Context host, Operator op );
public class Context
{
//
// State
//
private readonly ComputeCallsClosure m_owner;
private readonly TypeSystem.Reachability m_reachabilitySet;
//
// Constructor Methods
//
internal Context( ComputeCallsClosure owner ,
TypeSystem.Reachability reachabilitySet )
{
m_owner = owner;
m_reachabilitySet = reachabilitySet;
}
//
// Helper Methods
//
internal void ProcessMethod( MethodRepresentation md )
{
CoverObject( md );
ControlFlowGraphStateForCodeTransformation cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md );
if(cfg != null)
{
Transformations.ScanCodeWithCallback.Execute( m_owner.m_typeSystem, this, cfg, delegate( Operator op, object target )
{
if(target != null)
{
MethodRepresentation mdTarget = target as MethodRepresentation;
if(mdTarget != null)
{
m_owner.QueueMethodForProcessing( mdTarget );
}
CoverObject( target );
if(target is Operator)
{
Operator opTarget = (Operator)target;
Type type = opTarget.GetType();
while(type != null)
{
List< Notification > lst;
if(m_owner.m_delegation.TryGetValue( type, out lst ))
{
foreach(Notification dlg in lst)
{
dlg( this, opTarget );
}
}
type = type.BaseType;
}
CallOperator call = opTarget as CallOperator;
if(call != null)
{
m_owner.m_callsDatabase.RegisterCallSite( call );
}
var tdCodePointer = m_owner.m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_CodePointer;
foreach(var ex in opTarget.Arguments)
{
var exConst = ex as ConstantExpression;
if(exConst != null && exConst.Type == tdCodePointer)
{
var od = (DataManager.ObjectDescriptor)exConst.Value;
if(od != null)
{
var cp = (CodePointer)od.Source;
var mdDelegate = m_owner.m_typeSystem.DataManagerInstance.GetCodePointerFromUniqueID( cp.Target );
CoverObject( mdDelegate );
}
}
}
}
}
return Transformations.ScanCodeWithCallback.CallbackResult.Proceed;
} );
}
}
public void CoverObject( object obj )
{
if(obj == null) return;
if(obj is MethodRepresentation)
{
CoverMethod( (MethodRepresentation)obj );
}
else if(obj is FieldRepresentation)
{
CoverField( (FieldRepresentation)obj );
}
else if(obj is TypeRepresentation)
{
CoverType( (TypeRepresentation)obj );
}
else if(obj is AssemblyRepresentation)
{
CoverAssembly( (AssemblyRepresentation)obj );
}
else if(obj is CustomAttributeRepresentation)
{
CoverCustomAttribute( (CustomAttributeRepresentation)obj );
}
else if(obj is CustomAttributeAssociationRepresentation)
{
CoverCustomAttributeAssociation( (CustomAttributeAssociationRepresentation)obj );
}
else if(obj is ICallClosureComputationTarget)
{
ICallClosureComputationTarget itf = (ICallClosureComputationTarget)obj;
itf.ExpandClosure( this );
}
else
{
m_reachabilitySet.ExpandPending( obj );
}
}
private void CoverReflectionType( object obj )
{
TypeRepresentation td = m_owner.m_typeSystem.TryGetTypeRepresentationFromType( obj.GetType() );
if(td != null)
{
CoverType( td );
}
}
private void CoverAssembly( AssemblyRepresentation asml )
{
m_reachabilitySet.ExpandPending( asml );
}
private void CoverType( TypeRepresentation td )
{
while(td != null)
{
if(m_reachabilitySet.ExpandPending( td ))
{
break;
}
CoverReflectionType( td );
CoverAssembly( td.Owner );
CoverType( td.Extends );
CoverType( td.EnclosingClass );
//
// If a generic type, include the context.
//
TypeRepresentation.GenericContext gc = td.Generic;
if(gc != null)
{
CoverType( gc.Template );
foreach(TypeRepresentation td2 in gc.Parameters)
{
CoverType( td2 );
}
GenericParameterDefinition[] parametersDefinition = gc.ParametersDefinition;
if(parametersDefinition != null)
{
for(int i = 0; i < parametersDefinition.Length; i++)
{
foreach(TypeRepresentation constraint in parametersDefinition[i].Constraints)
{
CoverType( constraint );
}
}
}
}
//
// These are weird objects, because they actually contain a use of themselves in their definition.
// We want to keep the fields alive, so that the size computation doesn't generate the wrong values.
//
if(td is ScalarTypeRepresentation)
{
foreach(FieldRepresentation fd in td.Fields)
{
if(fd is InstanceFieldRepresentation)
{
CoverField( fd );
}
}
}
if(td is ArrayReferenceTypeRepresentation)
{
//
// Keep alive also the managed pointer to the elements of the array, it will be used later.
//
CoverType( m_owner.m_typeSystem.GetManagedPointerToType( td.ContainedType ) );
}
//
// For a non-pointer type, keep alive any associated pointer type.
//
if(!(td is PointerTypeRepresentation))
{
foreach(TypeRepresentation td2 in m_owner.m_typeSystem.Types)
{
PointerTypeRepresentation ptr = td2 as PointerTypeRepresentation;
if(ptr != null && ptr.ContainedType == td)
{
CoverType( ptr );
}
}
}
//
// Look for all the fields, if they have an "AssumeReferenced" attribute, force them to be included.
//
{
TypeRepresentation tdAttrib = m_owner.m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_AssumeReferencedAttribute;
foreach(FieldRepresentation fd in td.Fields)
{
if(fd.HasCustomAttribute( tdAttrib ))
{
CoverField( fd );
}
}
}
//
// Look for all the methods that are marked as exception handlers and include them.
//
{
var heh = m_owner.m_typeSystem.HardwareExceptionHandlers;
foreach(MethodRepresentation md in td.Methods)
{
CustomAttributeRepresentation ca;
if(heh.TryGetValue( md, out ca ))
{
CoverMethod ( md );
CoverCustomAttribute( ca );
}
}
}
//
// Look for all the methods that are marked as debugger handlers and include them.
//
{
var dhh = m_owner.m_typeSystem.DebuggerHookHandlers;
foreach(MethodRepresentation md in td.Methods)
{
CustomAttributeRepresentation ca;
if(dhh.TryGetValue( md, out ca ))
{
CoverMethod ( md );
CoverCustomAttribute( ca );
}
}
}
td = td.ContainedType;
}
}
private void CoverField( FieldRepresentation fd )
{
if(fd == null) return;
if(m_reachabilitySet.ExpandPending( fd ))
{
return;
}
CoverReflectionType( fd );
CoverType( fd.OwnerType );
CoverType( fd.FieldType );
if(fd is StaticFieldRepresentation)
{
StaticFieldRepresentation fdS = (StaticFieldRepresentation)fd;
CoverField( fdS.ImplementedBy );
CoverStaticConstructor( fdS );
}
if(fd is InstanceFieldRepresentation)
{
InstanceFieldRepresentation fdI = (InstanceFieldRepresentation)fd;
CoverField( fdI.ImplementationOf );
CoverStaticConstructor( fdI.ImplementationOf );
}
}
private void CoverStaticConstructor( StaticFieldRepresentation fd )
{
if(fd == null) return;
StaticConstructorMethodRepresentation md = fd.OwnerType.FindDefaultStaticConstructor();
if(md != null)
{
CoverMethod( md );
CoverMethod( m_owner.m_typeSystem.WellKnownMethods.TypeSystemManager_InvokeStaticConstructors );
}
}
private void CoverMethod( MethodRepresentation md )
{
if(md == null) return;
if(m_reachabilitySet.ExpandPending( md ))
{
return;
}
CoverReflectionType( md );
m_owner.QueueMethodForProcessing( md );
//
// If a generic method, include the context.
//
MethodRepresentation.GenericContext gc = md.Generic;
if(gc != null)
{
CoverMethod( gc.Template );
foreach(TypeRepresentation td in gc.Parameters)
{
CoverType( td );
}
GenericParameterDefinition[] parametersDefinition = gc.ParametersDefinition;
if(parametersDefinition != null)
{
for(int i = 0; i < parametersDefinition.Length; i++)
{
foreach(TypeRepresentation constraint in parametersDefinition[i].Constraints)
{
CoverType( constraint );
}
}
}
}
CoverType( md.OwnerType );
CoverType( md.ReturnType );
foreach(TypeRepresentation td in md.ThisPlusArguments)
{
CoverType( td );
}
///
/// For imported methods we need to make sure that any passed structures are preserved.
/// The type system reduction phase will attempt to remove member fields if they are
/// not used or covered here which will leave them with a different signature/size than
/// the native imported method is expecting.
///
if(0 != ( md.BuildTimeFlags & MethodRepresentation.BuildTimeAttributes.Imported ))
{
foreach(CustomAttributeAssociationRepresentation caa in md.CustomAttributes)
{
CoverCustomAttributeAssociation( caa );
}
HashSet<TypeRepresentation> importTypes = new HashSet<TypeRepresentation>();
foreach(TypeRepresentation tr in md.ThisPlusArguments)
{
// Make imported structures do not lose members during type system reduction
if(
tr.BuiltInType == TypeRepresentation.BuiltInTypes.BYREF &&
tr.UnderlyingType.BuiltInType == TypeRepresentation.BuiltInTypes.VALUETYPE )
{
CoverImportedDataType( tr.UnderlyingType, importTypes );
}
// also check for arrays of structs
else if(
tr.BuiltInType == TypeRepresentation.BuiltInTypes.ARRAY &&
tr.ContainedType.BuiltInType == TypeRepresentation.BuiltInTypes.VALUETYPE )
{
CoverImportedDataType( tr.ContainedType, importTypes );
}
}
}
}
/// <summary>
/// Cover all fields from an imported structure so that its size/signature remains consistent.
/// </summary>
/// <param name="tr"></param>
/// <param name="coveredTypes"></param>
private void CoverImportedDataType( TypeRepresentation tr, HashSet<TypeRepresentation> coveredTypes )
{
if(coveredTypes.Contains( tr )) return;
coveredTypes.Add( tr );
CoverType( tr );
foreach(FieldRepresentation fr in tr.Fields)
{
CoverField( fr );
CoverImportedDataType( fr.FieldType, coveredTypes );
}
}
private void CoverCustomAttribute( CustomAttributeRepresentation ca )
{
if(ca == null) return;
if(m_reachabilitySet.ExpandPending( ca ))
{
return;
}
CoverReflectionType( ca );
CoverMethod( ca.Constructor );
}
private void CoverCustomAttributeAssociation( CustomAttributeAssociationRepresentation caa )
{
if(caa == null) return;
if(m_reachabilitySet.ExpandPending( caa ))
{
return;
}
CoverReflectionType( caa );
CoverObject( caa.Target );
CoverObject( caa.CustomAttribute );
}
//--//
internal void IncludeGeneric( object obj )
{
CHECKS.ASSERT( m_owner.m_typeSystem.IsUseProhibited( obj ) == false, "Found use of '{0}' after the entity was marked illegal to use", obj );
if(obj is TypeRepresentation)
{
Include( (TypeRepresentation)obj );
}
else if(obj is TypeRepresentation.GenericContext)
{
Include( (TypeRepresentation.GenericContext)obj );
}
else if(obj is FieldRepresentation)
{
Include( (FieldRepresentation)obj );
}
else if(obj is MethodRepresentation)
{
Include( (MethodRepresentation)obj );
}
else if(obj is MethodRepresentation.GenericContext)
{
Include( (MethodRepresentation.GenericContext)obj );
}
else if(obj is CustomAttributeRepresentation)
{
Include( (CustomAttributeRepresentation)obj );
}
else if(obj is VTable)
{
Include( (VTable)obj );
}
else if(obj is DataManager.DataDescriptor)
{
Include( (DataManager.DataDescriptor)obj );
}
}
private void Include( TypeRepresentation td )
{
CHECKS.ASSERT( m_owner.m_typeSystem.IsUseProhibited( td ) == false, "Found use of '{0}' after the entity was marked illegal to use", td );
CoverType( td );
//--//
TypeRepresentation tdSystem_Attribute = m_owner.m_typeSystem.WellKnownTypes.System_Attribute;
if(tdSystem_Attribute != null && tdSystem_Attribute.IsSuperClassOf( td, null ))
{
//
// If we touch an attribute, make sure all the constructor methods used by actual instances are touched.
//
m_owner.m_typeSystem.EnumerateCustomAttributes( delegate( CustomAttributeAssociationRepresentation caa )
{
CustomAttributeRepresentation ca = caa.CustomAttribute;
MethodRepresentation mdCa = ca .Constructor;
if(mdCa.OwnerType == td)
{
//
// BUGBUG: The named arguments are not included!
//
if(m_reachabilitySet.Contains( mdCa ) == false)
{
CoverMethod( mdCa );
}
}
} );
}
//--//
//
// Include all the concrete subclasses, because we need at least one implementation.
//
if(td.HasBuildTimeFlag( TypeRepresentation.BuildTimeAttributes.ForceDevirtualization ))
{
foreach(TypeRepresentation td2 in m_owner.m_typeSystem.Types)
{
if(td2.IsAbstract == false)
{
for(TypeRepresentation td3 = td2; td3 != null; td3 = td3.Extends)
{
if(td3 == td)
{
CoverType( td2 );
break;
}
}
}
}
}
//--//
//
// Since call closure has reached a new type, make sure that all the overrides to already touched virtual methods are included.
//
foreach(MethodRepresentation md in td.Methods)
{
if(md is VirtualMethodRepresentation && md.IsOpenMethod == false && td.IsOpenType == false && m_reachabilitySet.Contains( md ) == false)
{
int index = md.FindVirtualTableIndex();
if(index == -1)
{
continue;
}
MethodRepresentation mdRoot = md;
TypeRepresentation tdRoot = td;
while((mdRoot.Flags & MethodRepresentation.Attributes.NewSlot) == 0)
{
tdRoot = tdRoot.Extends; if(tdRoot == null) break;
mdRoot = tdRoot.MethodTable[index];
if(m_reachabilitySet.Contains( mdRoot ))
{
CoverMethod( md );
break;
}
}
}
}
//
// Also, include the methods associated with already touched interfaces.
//
foreach(TypeRepresentation.InterfaceMap map in td.InterfaceMaps)
{
if(m_reachabilitySet.Contains( map.Interface ))
{
MethodRepresentation[] mdOverride = map.Methods;
MethodRepresentation[] mdDeclaration = map.Interface.FindInterfaceTable( map.Interface );
for(int i = 0; i < mdDeclaration.Length; i++)
{
if(m_reachabilitySet.Contains( mdDeclaration[i] ))
{
if(m_reachabilitySet.Contains( mdOverride[i] ) == false)
{
CoverMethod( mdOverride[i] );
}
}
}
}
}
}
private void Include( TypeRepresentation.GenericContext ctx )
{
if(ctx.Template != null)
{
Include( ctx.Template );
}
foreach(TypeRepresentation td in ctx.Parameters)
{
Include( td );
}
if(ctx.ParametersDefinition != null)
{
foreach(GenericParameterDefinition def in ctx.ParametersDefinition)
{
foreach(TypeRepresentation td in def.Constraints)
{
Include( td );
}
}
}
}
private void Include( FieldRepresentation fd )
{
CHECKS.ASSERT( m_reachabilitySet.Contains( fd.OwnerType ), "ComputeCallsClosure.GlobalReachabilitySet does not contain '{0}', although it should", fd.OwnerType );
CoverField( fd );
}
private void Include( MethodRepresentation md )
{
CHECKS.ASSERT( m_owner.m_typeSystem.IsUseProhibited( md ) == false, "Found use of '{0}' after the entity was marked illegal to use", md );
CHECKS.ASSERT( m_owner.m_pendingHistory.Contains( md ), "ComputeCallsClosure.EntitiesReferencedByMethod does not contain '{0}', although it should", md );
CHECKS.ASSERT( m_reachabilitySet.Contains( md.OwnerType ), "ComputeCallsClosure.GlobalReachabilitySet does not contain '{0}', although it should", md.OwnerType );
CoverMethod( md );
if(md is VirtualMethodRepresentation && !(md is FinalMethodRepresentation))
{
//
// Include all the overrides for this method in all the subclasses already reached by the closure computation.
//
int index = md.FindVirtualTableIndex();
TypeRepresentation td = md.OwnerType;
List< TypeRepresentation > lst;
if(m_owner.m_typeSystem.DirectDescendant.TryGetValue( td, out lst ))
{
foreach(TypeRepresentation td2 in lst)
{
MethodRepresentation md2 = td2.MethodTable[index];
if(m_reachabilitySet.Contains( md2.OwnerType ))
{
CoverMethod( md2 );
}
}
}
//
// A virtual method defines a slot when it's first introduced.
// Make sure all the methods from this one up to the root of the override tree are included.
//
MethodRepresentation mdRoot = md;
while((mdRoot.Flags & MethodRepresentation.Attributes.NewSlot) == 0)
{
td = td.Extends; if(td == null) break;
mdRoot = td.MethodTable[index];
if(m_reachabilitySet.Contains( mdRoot ) == false)
{
CoverMethod( mdRoot );
}
}
//--//
//
// The method belongs to an interface, we have to include all the implementations in all the touched types.
//
if(td is InterfaceTypeRepresentation)
{
InterfaceTypeRepresentation itf = (InterfaceTypeRepresentation)td;
int itfIndex = md.FindInterfaceTableIndex();
foreach(TypeRepresentation td2 in m_owner.m_typeSystem.InterfaceImplementors[itf])
{
if(m_reachabilitySet.Contains( td2 ))
{
MethodRepresentation mdOverride = td2.FindInterfaceTable( itf )[itfIndex];
if(m_reachabilitySet.Contains( mdOverride ) == false)
{
CoverMethod( mdOverride );
}
}
}
}
}
}
private void Include( MethodRepresentation.GenericContext ctx )
{
Include( ctx.Template );
foreach(TypeRepresentation td in ctx.Parameters)
{
Include( td );
}
if(ctx.ParametersDefinition != null)
{
foreach(GenericParameterDefinition def in ctx.ParametersDefinition)
{
foreach(TypeRepresentation td in def.Constraints)
{
Include( td );
}
}
}
}
private void Include( CustomAttributeRepresentation ca )
{
CHECKS.ASSERT( m_owner.m_typeSystem.IsUseProhibited( ca ) == false, "Found use of '{0}' after the entity was marked illegal to use", ca );
CoverCustomAttribute( ca );
}
private void Include( VTable vTable )
{
Include( vTable.TypeInfo );
}
private void Include( DataManager.DataDescriptor dd )
{
lock(m_owner.m_delayedExpansion)
{
m_owner.m_delayedExpansion.Insert( dd );
}
}
internal bool Contains( object obj )
{
return m_reachabilitySet.Contains( obj );
}
//--//
//
// Access Methods
//
public TypeSystemForCodeTransformation TypeSystem
{
get
{
return m_owner.m_typeSystem;
}
}
internal TypeSystem.Reachability ReachabilitySet
{
get
{
return m_reachabilitySet;
}
}
}
//
// State
//
private readonly TypeSystemForCodeTransformation m_typeSystem;
private readonly CallsDataBase m_callsDatabase;
private readonly PhaseDriver m_phase;
private readonly GrowOnlyHashTable< Type, List< Notification > > m_delegation;
private readonly GrowOnlySet < DataManager.DataDescriptor > m_delayedExpansion;
private readonly GrowOnlySet < MethodRepresentation > m_pendingHistory;
private readonly Queue < MethodRepresentation > m_pending;
private readonly Context m_globalContext;
private readonly GrowOnlyHashTable< MethodRepresentation, GrowOnlySet< object > > m_entitiesReferencedByMethods;
//
// Constructor Methods
//
public ComputeCallsClosure( TypeSystemForCodeTransformation typeSystem ,
DelegationCache cache ,
CallsDataBase callsDatabase ,
PhaseDriver phase ,
bool fCollectPerMethodInfo )
{
m_typeSystem = typeSystem;
m_callsDatabase = callsDatabase;
m_phase = phase;
m_delegation = HashTableFactory.New < Type, List< Notification > >();
m_delayedExpansion = SetFactory .NewWithReferenceEquality< DataManager.DataDescriptor >();
m_pendingHistory = SetFactory .NewWithReferenceEquality< MethodRepresentation >();
m_pending = new Queue < MethodRepresentation >();
m_globalContext = new Context( this, typeSystem.ReachabilitySet );
if(fCollectPerMethodInfo)
{
m_entitiesReferencedByMethods = HashTableFactory.NewWithReferenceEquality< MethodRepresentation, GrowOnlySet< object > >();
}
typeSystem.ReachabilitySet.RestartComputation();
cache.HookNotifications( typeSystem, this, phase );
}
//
// Helper Methods
//
public void Execute( MethodRepresentation mdStart )
{
if(m_globalContext.Contains( mdStart ) == false)
{
QueueMethodForProcessing( mdStart );
ProcessInner();
}
}
public void Expand( object val )
{
m_globalContext.CoverObject( val );
ProcessInner();
}
public void ExpandContents< TKey, TValue >( GrowOnlyHashTable< TKey, TValue > ht )
{
foreach(TKey key in ht.Keys)
{
Expand( key );
Expand( ht[key] );
}
}
public void ExpandValueIfKeyIsReachable< TKey, TValue >( GrowOnlyHashTable< TKey, TValue > ht )
{
foreach(TKey key in ht.Keys)
{
if(m_globalContext.Contains( key ))
{
Expand( ht[key] );
}
}
}
//--//
private void QueueMethodForProcessing( MethodRepresentation md )
{
lock(m_pendingHistory)
{
if(m_pendingHistory.Insert( md ) == true)
{
return;
}
}
lock(m_pending)
{
m_pending.Enqueue( md );
}
}
private void ProcessInner()
{
while(IsThereWorkToDo())
{
ProcessMethods();
ProcessDataDescriptors();
}
}
private bool IsThereWorkToDo()
{
if(m_pending.Count > 0)
{
return true;
}
if(m_globalContext.ReachabilitySet.HasPendingItems())
{
return true;
}
return false;
}
private void Analyze( MethodRepresentation md )
{
m_globalContext.ProcessMethod( md );
if(m_entitiesReferencedByMethods != null)
{
GrowOnlySet< object > entitiesReferencedByMethod;
lock(m_entitiesReferencedByMethods)
{
if(m_entitiesReferencedByMethods.ContainsKey( md )) return;
entitiesReferencedByMethod = SetFactory.NewWithWeakEquality< object >();
m_entitiesReferencedByMethods[md] = entitiesReferencedByMethod;
}
var currentMethodReachabilitySet = TypeSystemForCodeTransformation.Reachability.CreateForUpdate( entitiesReferencedByMethod );
Context ctx = new Context( this, currentMethodReachabilitySet );
ctx.ProcessMethod( md );
}
}
private void ProcessMethods()
{
using(ParallelTransformationsHandler handler = new ParallelTransformationsHandler( Analyze ))
{
while(true)
{
DrainIncrementalSet();
if(m_pending.Count == 0)
{
break;
}
var methods = m_pending.ToArray();
m_pending.Clear();
#if COMPUTECALLSCLOSURE_FORCE_SINGLE_THREADED
foreach(var md in methods)
{
Analyze( md );
}
#else
foreach(var md in methods)
{
handler.Queue( md );
}
handler.Synchronize();
#endif
}
}
}
private void DrainIncrementalSet()
{
while(true)
{
object[] set = m_globalContext.ReachabilitySet.ApplyPendingSet( true );
if(set == null)
{
break;
}
foreach(object obj in set)
{
m_globalContext.IncludeGeneric( obj );
}
}
}
private void ProcessDataDescriptors()
{
TypeSystem.Reachability reachability = m_globalContext.ReachabilitySet.CloneForIncrementalUpdate();
foreach(DataManager.DataDescriptor dd in m_delayedExpansion)
{
if(reachability.Contains( dd ))
{
dd.IncludeExtraTypes( reachability, m_phase );
}
}
object[] set = reachability.ApplyPendingSet( false );
if(set != null)
{
foreach(object obj in set)
{
m_globalContext.CoverObject( obj );
}
}
}
//--//
public void RegisterForNotification( Type type ,
Notification notification )
{
HashTableWithListFactory.AddUnique( m_delegation, type, notification );
}
//--//
//
// Access Methods
//
public TypeSystemForCodeTransformation TypeSystem
{
get
{
return m_typeSystem;
}
}
public GrowOnlyHashTable< MethodRepresentation, GrowOnlySet< object > > EntitiesReferencedByMethods
{
get
{
return m_entitiesReferencedByMethods;
}
}
}
}
| |
using YAF.Lucene.Net.Support;
using YAF.Lucene.Net.Support.Threading;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using JCG = J2N.Collections.Generic;
namespace YAF.Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Utility class to safely share instances of a certain type across multiple
/// threads, while periodically refreshing them. This class ensures each
/// reference is closed only once all threads have finished using it. It is
/// recommended to consult the documentation of <see cref="ReferenceManager{G}"/>
/// implementations for their <see cref="MaybeRefresh()"/> semantics.
/// <para/>
/// @lucene.experimental
/// </summary>
/// <typeparam name="G">The concrete type that will be <see cref="Acquire()"/>d and
/// <see cref="Release(G)"/>d.</typeparam>
public abstract class ReferenceManager<G> : IDisposable
where G : class //Make G nullable
{
private const string REFERENCE_MANAGER_IS_CLOSED_MSG = "this ReferenceManager is closed";
// LUCENENET NOTE: changed this to be a private volatile field
// with a property to set/get it, since protected volatile
// fields are not CLS compliant
private volatile G current;
/// <summary>
/// The current reference
/// </summary>
protected G Current
{
get { return current; }
set { current = value; }
}
private readonly ReentrantLock refreshLock = new ReentrantLock();
private readonly ISet<ReferenceManager.IRefreshListener> refreshListeners = new ConcurrentHashSet<ReferenceManager.IRefreshListener>();
private void EnsureOpen()
{
if (current == null)
{
throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, REFERENCE_MANAGER_IS_CLOSED_MSG);
}
}
private void SwapReference(G newReference)
{
lock (this)
{
EnsureOpen();
G oldReference = current;
current = newReference;
Release(oldReference);
}
}
/// <summary>
/// Decrement reference counting on the given reference. </summary>
/// <exception cref="System.IO.IOException"> If reference decrement on the given resource failed.</exception>
protected abstract void DecRef(G reference);
/// <summary>
/// Refresh the given reference if needed. Returns <c>null</c> if no refresh
/// was needed, otherwise a new refreshed reference. </summary>
/// <exception cref="ObjectDisposedException"> If the reference manager has been <see cref="Dispose()"/>d. </exception>
/// <exception cref="System.IO.IOException"> If the refresh operation failed </exception>
protected abstract G RefreshIfNeeded(G referenceToRefresh);
/// <summary>
/// Try to increment reference counting on the given reference. Returns <c>true</c> if
/// the operation was successful. </summary>
/// <exception cref="ObjectDisposedException"> if the reference manager has been <see cref="Dispose()"/>d. </exception>
protected abstract bool TryIncRef(G reference);
/// <summary>
/// Obtain the current reference. You must match every call to acquire with one
/// call to <see cref="Release(G)"/>; it's best to do so in a finally clause, and set
/// the reference to <c>null</c> to prevent accidental usage after it has been
/// released. </summary>
/// <exception cref="ObjectDisposedException"> If the reference manager has been <see cref="Dispose()"/>d. </exception>
public G Acquire()
{
G @ref;
do
{
if ((@ref = current) == null)
{
throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, REFERENCE_MANAGER_IS_CLOSED_MSG);
}
if (TryIncRef(@ref))
{
return @ref;
}
if (GetRefCount(@ref) == 0 && (object)current == (object)@ref)
{
Debug.Assert(@ref != null);
/* if we can't increment the reader but we are
still the current reference the RM is in a
illegal states since we can't make any progress
anymore. The reference is closed but the RM still
holds on to it as the actual instance.
this can only happen if somebody outside of the RM
decrements the refcount without a corresponding increment
since the RM assigns the new reference before counting down
the reference. */
throw new InvalidOperationException("The managed reference has already closed - this is likely a bug when the reference count is modified outside of the ReferenceManager");
}
} while (true);
}
/// <summary>
/// <para>
/// Closes this ReferenceManager to prevent future <see cref="Acquire()"/>ing. A
/// reference manager should be disposed if the reference to the managed resource
/// should be disposed or the application using the <see cref="ReferenceManager{G}"/>
/// is shutting down. The managed resource might not be released immediately,
/// if the <see cref="ReferenceManager{G}"/> user is holding on to a previously
/// <see cref="Acquire()"/>d reference. The resource will be released once
/// when the last reference is <see cref="Release(G)"/>d. Those
/// references can still be used as if the manager was still active.
/// </para>
/// <para>
/// Applications should not <see cref="Acquire()"/> new references from this
/// manager once this method has been called. <see cref="Acquire()"/>ing a
/// resource on a disposed <see cref="ReferenceManager{G}"/> will throw an
/// <seealso cref="ObjectDisposedException"/>.
/// </para>
/// </summary>
/// <exception cref="System.IO.IOException">
/// If the underlying reader of the current reference could not be disposed </exception>
public void Dispose()
{
lock (this)
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
/// <summary>
/// Returns the current reference count of the given reference.
/// </summary>
protected abstract int GetRefCount(G reference);
/// <summary>
/// Called after <see cref="Dispose()"/>, so subclass can free any resources. </summary>
/// <exception cref="System.IO.IOException"> if the after dispose operation in a sub-class throws an <see cref="System.IO.IOException"/>
/// </exception>
protected virtual void Dispose(bool disposing)
{
if (disposing && current != null)
{
// make sure we can call this more than once
// closeable javadoc says:
// if this is already closed then invoking this method has no effect.
SwapReference(null);
}
}
private void DoMaybeRefresh()
{
// it's ok to call lock() here (blocking) because we're supposed to get here
// from either maybeRefreh() or maybeRefreshBlocking(), after the lock has
// already been obtained. Doing that protects us from an accidental bug
// where this method will be called outside the scope of refreshLock.
// Per ReentrantLock's javadoc, calling lock() by the same thread more than
// once is ok, as long as unlock() is called a matching number of times.
refreshLock.Lock();
bool refreshed = false;
try
{
G reference = Acquire();
try
{
NotifyRefreshListenersBefore();
G newReference = RefreshIfNeeded(reference);
if (newReference != null)
{
Debug.Assert((object)newReference != (object)reference, "refreshIfNeeded should return null if refresh wasn't needed");
try
{
SwapReference(newReference);
refreshed = true;
}
finally
{
if (!refreshed)
{
Release(newReference);
}
}
}
}
finally
{
Release(reference);
NotifyRefreshListenersRefreshed(refreshed);
}
AfterMaybeRefresh();
}
finally
{
refreshLock.Unlock();
}
}
/// <summary>
/// You must call this (or <see cref="MaybeRefreshBlocking()"/>), periodically, if
/// you want that <see cref="Acquire()"/> will return refreshed instances.
///
/// <para>
/// <b>Threads</b>: it's fine for more than one thread to call this at once.
/// Only the first thread will attempt the refresh; subsequent threads will see
/// that another thread is already handling refresh and will return
/// immediately. Note that this means if another thread is already refreshing
/// then subsequent threads will return right away without waiting for the
/// refresh to complete.
/// </para>
/// <para>
/// If this method returns <c>true</c> it means the calling thread either refreshed or
/// that there were no changes to refresh. If it returns <c>false</c> it means another
/// thread is currently refreshing.
/// </para> </summary>
/// <exception cref="System.IO.IOException"> If refreshing the resource causes an <see cref="System.IO.IOException"/> </exception>
/// <exception cref="ObjectDisposedException"> If the reference manager has been <see cref="Dispose()"/>d. </exception>
public bool MaybeRefresh()
{
EnsureOpen();
// Ensure only 1 thread does refresh at once; other threads just return immediately:
bool doTryRefresh = refreshLock.TryLock();
if (doTryRefresh)
{
try
{
DoMaybeRefresh();
}
finally
{
refreshLock.Unlock();
}
}
return doTryRefresh;
}
/// <summary>
/// You must call this (or <see cref="MaybeRefresh()"/>), periodically, if you want
/// that <see cref="Acquire()"/> will return refreshed instances.
///
/// <para/>
/// <b>Threads</b>: unlike <see cref="MaybeRefresh()"/>, if another thread is
/// currently refreshing, this method blocks until that thread completes. It is
/// useful if you want to guarantee that the next call to <see cref="Acquire()"/>
/// will return a refreshed instance. Otherwise, consider using the
/// non-blocking <see cref="MaybeRefresh()"/>. </summary>
/// <exception cref="System.IO.IOException"> If refreshing the resource causes an <see cref="System.IO.IOException"/> </exception>
/// <exception cref="ObjectDisposedException"> If the reference manager has been <see cref="Dispose()"/>d. </exception>
public void MaybeRefreshBlocking()
{
EnsureOpen();
// Ensure only 1 thread does refresh at once
refreshLock.Lock();
try
{
DoMaybeRefresh();
}
finally
{
refreshLock.Unlock();
}
}
/// <summary>
/// Called after a refresh was attempted, regardless of
/// whether a new reference was in fact created. </summary>
/// <exception cref="System.IO.IOException"> if a low level I/O exception occurs</exception>
protected virtual void AfterMaybeRefresh()
{
}
/// <summary>
/// Release the reference previously obtained via <see cref="Acquire()"/>.
/// <para/>
/// <b>NOTE:</b> it's safe to call this after <see cref="Dispose()"/>. </summary>
/// <exception cref="System.IO.IOException"> If the release operation on the given resource throws an <see cref="System.IO.IOException"/> </exception>
public void Release(G reference)
{
Debug.Assert(reference != null);
DecRef(reference);
}
private void NotifyRefreshListenersBefore()
{
foreach (ReferenceManager.IRefreshListener refreshListener in refreshListeners)
{
refreshListener.BeforeRefresh();
}
}
private void NotifyRefreshListenersRefreshed(bool didRefresh)
{
foreach (ReferenceManager.IRefreshListener refreshListener in refreshListeners)
{
refreshListener.AfterRefresh(didRefresh);
}
}
/// <summary>
/// Adds a listener, to be notified when a reference is refreshed/swapped.
/// </summary>
public virtual void AddListener(ReferenceManager.IRefreshListener listener)
{
if (listener == null)
{
throw new ArgumentNullException("Listener cannot be null");
}
refreshListeners.Add(listener);
}
/// <summary>
/// Remove a listener added with <see cref="AddListener(ReferenceManager.IRefreshListener)"/>.
/// </summary>
public virtual void RemoveListener(ReferenceManager.IRefreshListener listener)
{
if (listener == null)
{
throw new ArgumentNullException("Listener cannot be null");
}
refreshListeners.Remove(listener);
}
}
/// <summary>
/// LUCENENET specific class used to provide static access to <see cref="ReferenceManager.IRefreshListener"/>
/// without having to specifiy the generic closing type of <see cref="ReferenceManager{G}"/>.
/// </summary>
public static class ReferenceManager
{
/// <summary>
/// Use to receive notification when a refresh has
/// finished. See <see cref="ReferenceManager{G}.AddListener(IRefreshListener)"/>.
/// </summary>
public interface IRefreshListener
{
/// <summary>
/// Called right before a refresh attempt starts. </summary>
void BeforeRefresh();
/// <summary>
/// Called after the attempted refresh; if the refresh
/// did open a new reference then didRefresh will be <c>true</c>
/// and <see cref="ReferenceManager{G}.Acquire()"/> is guaranteed to return the new
/// reference.
/// </summary>
void AfterRefresh(bool didRefresh);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Entitas {
/// <summary>
/// The Entity class serves as the lifecycle manager for the <see cref="IComponent"/>, managing creation, caching and event handling.
/// </summary>
public partial class Entity {
/// <summary>
/// Called whenever a Component is attached to an entity that did not have a Component of that type attached to it.
/// </summary>
public event EntityChanged OnComponentAdded;
/// <summary>
/// Called whenever a Component is removed from an Entity.
/// </summary>
public event EntityChanged OnComponentRemoved;
/// <summary>
/// Called whenever a Component is replaced with a Component of the same type.
/// </summary>
public event ComponentReplaced OnComponentReplaced;
public delegate void EntityChanged(Entity entity, int index, IComponent component);
public delegate void ComponentReplaced(Entity entity, int index, IComponent previousComponent, IComponent newComponent);
public int creationIndex { get { return _creationIndex; } }
internal int _creationIndex;
internal bool _isEnabled = true;
readonly IComponent[] _components;
IComponent[] _componentsCache;
int[] _componentIndicesCache;
string _toStringCache;
public Entity(int totalComponents) {
_components = new IComponent[totalComponents];
}
/// <summary>
/// Adds the given Component to the Entity, ensuring <see cref="OnComponentAdded"/> is called.
/// Preferred usage is to use the generated syntax for the specific Components. (See: AddXXXX )
///
/// Throws: <para/>
/// - <see cref="EntityIsNotEnabledException"/> if the Entity is not enabled. <para/>
/// - <see cref="EntityAlreadyHasComponentException"/> if the Entity already has the Component. Use <see cref="ReplaceComponent"/> instead.<para/>
/// </summary>
/// <param name="index">The index of the Component to add. See generated *ComponentsIds of the Pool that instantiated this Entity.</param>
/// <param name="component">The component to add.</param>
public Entity AddComponent(int index, IComponent component) {
if (!_isEnabled) {
throw new EntityIsNotEnabledException("Cannot add component!");
}
if (HasComponent(index)) {
var errorMsg = "Cannot add component at index " + index + " to " + this;
throw new EntityAlreadyHasComponentException(errorMsg, index);
}
_components[index] = component;
_componentsCache = null;
_componentIndicesCache = null;
_toStringCache = null;
if (OnComponentAdded != null) {
OnComponentAdded(this, index, component);
}
return this;
}
/// <summary>
/// Removes the specified Component from the Entity, ensuring <see cref="OnComponentRemoved"/> is called.
/// Preferred usage is to use the generated syntax for the specific Components. (See: RemoveXXXX )
///
/// <para/>
/// Throws: <para/>
/// - <see cref="EntityIsNotEnabledException"/> if the Entity is not enabled. <para/>
/// - <see cref="EntityDoesNotHaveComponentException"/> if the Entity does not have the Component.<para/>
/// </summary>
/// <param name="index">The index of the Component to remove. See generated *ComponentsIds of the Pool that instantiated this Entity.</param>
/// <param name="component">The component to remove.</param>
public Entity RemoveComponent(int index) {
if (!_isEnabled) {
throw new EntityIsNotEnabledException("Cannot remove component!");
}
if (!HasComponent(index)) {
var errorMsg = "Cannot remove component at index " + index + " from " + this;
throw new EntityDoesNotHaveComponentException(errorMsg, index);
}
replaceComponent(index, null);
return this;
}
/// <summary>
/// Replaces the specified Component from the Entity, ensuring the following lifecycle: <para/>
/// - If the entity does not have the Component, calls <see cref="OnComponentAdded"/>. <para/>
/// - Otherwise if the given component is null, calls <see cref="OnComponentRemoved"/>. <para/>
/// - Else calls <see cref="OnComponentReplaced"/>. <para/>
///
/// Preferred usage is to use the generated syntax for the specific Components, which handles caching of the previously used Component. (See: ReplaceXXXX )
///
/// <para/>
/// Throws: <para/>
/// - <see cref="EntityIsNotEnabledException"/> if the Entity is not enabled. <para/>
/// </summary>
/// <param name="index">The index of the Component to add. See generated *ComponentsIds of the Pool that instantiated this Entity.</param>
/// <param name="component">The component to replace.</param>
public Entity ReplaceComponent(int index, IComponent component) {
if (!_isEnabled) {
throw new EntityIsNotEnabledException("Cannot replace component!");
}
if (HasComponent(index)) {
replaceComponent(index, component);
} else if (component != null) {
AddComponent(index, component);
}
return this;
}
void replaceComponent(int index, IComponent replacement) {
var previousComponent = _components[index];
if (previousComponent == replacement) {
if (OnComponentReplaced != null) {
OnComponentReplaced(this, index, previousComponent, replacement);
}
} else {
_components[index] = replacement;
_componentsCache = null;
if (replacement == null) {
_componentIndicesCache = null;
_toStringCache = null;
if (OnComponentRemoved != null) {
OnComponentRemoved(this, index, previousComponent);
}
} else {
if (OnComponentReplaced != null) {
OnComponentReplaced(this, index, previousComponent, replacement);
}
}
}
}
public IComponent GetComponent(int index) {
if (!HasComponent(index)) {
var errorMsg = "Cannot get component at index " + index + " from " + this;
throw new EntityDoesNotHaveComponentException(errorMsg, index);
}
return _components[index];
}
public IComponent[] GetComponents() {
if (_componentsCache == null) {
var components = new List<IComponent>(16);
for (int i = 0, componentsLength = _components.Length; i < componentsLength; i++) {
var component = _components[i];
if (component != null) {
components.Add(component);
}
}
_componentsCache = components.ToArray();
}
return _componentsCache;
}
public int[] GetComponentIndices() {
if (_componentIndicesCache == null) {
var indices = new List<int>(16);
for (int i = 0, componentsLength = _components.Length; i < componentsLength; i++) {
if (_components[i] != null) {
indices.Add(i);
}
}
_componentIndicesCache = indices.ToArray();
}
return _componentIndicesCache;
}
public bool HasComponent(int index) {
return _components[index] != null;
}
public bool HasComponents(int[] indices) {
for (int i = 0, indicesLength = indices.Length; i < indicesLength; i++) {
if (_components[indices[i]] == null) {
return false;
}
}
return true;
}
public bool HasAnyComponent(int[] indices) {
for (int i = 0, indicesLength = indices.Length; i < indicesLength; i++) {
if (_components[indices[i]] != null) {
return true;
}
}
return false;
}
public void RemoveAllComponents() {
_toStringCache = null;
for (int i = 0, componentsLength = _components.Length; i < componentsLength; i++) {
if (_components[i] != null) {
replaceComponent(i, null);
}
}
}
/// <summary>
/// Used internally by the Pool to destroy an entity.
/// To destroy an entity, use <see cref="Pool.DestroyEntity"/> on the source Pool of this Entity.
/// </summary>
internal void destroy() {
RemoveAllComponents();
OnComponentAdded = null;
OnComponentReplaced = null;
OnComponentRemoved = null;
_isEnabled = false;
}
public override string ToString() {
if (_toStringCache == null) {
var sb = new StringBuilder()
.Append("Entity_")
.Append(_creationIndex)
.Append("(");
const string seperator = ", ";
var components = GetComponents();
var lastSeperator = components.Length - 1 ;
for (int i = 0, componentsLength = components.Length; i < componentsLength; i++) {
sb.Append(components[i].GetType());
if (i < lastSeperator) {
sb.Append(seperator);
}
}
sb.Append(")");
_toStringCache = sb.ToString();
}
return _toStringCache;
}
}
public class EntityAlreadyHasComponentException : Exception {
public EntityAlreadyHasComponentException(string message, int index) :
base(message + "\nEntity already has a component at index " + index) {
}
}
public class EntityDoesNotHaveComponentException : Exception {
public EntityDoesNotHaveComponentException(string message, int index) :
base(message + "\nEntity does not have a component at index " + index) {
}
}
public class EntityIsNotEnabledException : Exception {
public EntityIsNotEnabledException(string message) :
base(message + "\nEntity is not enabled!") {
}
}
public class EntityEqualityComparer : IEqualityComparer<Entity> {
public static readonly EntityEqualityComparer comparer = new EntityEqualityComparer();
public bool Equals(Entity x, Entity y) {
return x == y;
}
public int GetHashCode(Entity obj) {
return obj._creationIndex;
}
}
public partial class Entity {
public event EntityReleased OnEntityReleased;
public delegate void EntityReleased(Entity entity);
internal int _refCount;
/// <summary>
/// Increases the reference count on this Entity. Used by the Entity Reference Counting.
/// </summary>
public Entity Retain() {
_refCount += 1;
return this;
}
/// <summary>
/// Decreases the reference count on this Entity and ensures callbacks are made when nothing references this Entity.
/// See <see cref="Pool.DestroyEntity"/> to directly destroy an entity.
/// </summary>
public void Release() {
_refCount -= 1;
if (_refCount == 0) {
if (OnEntityReleased != null) {
OnEntityReleased(this);
}
} else if (_refCount < 0) {
throw new EntityIsAlreadyReleasedException();
}
}
}
public class EntityIsAlreadyReleasedException : Exception {
public EntityIsAlreadyReleasedException() :
base("Entity is already released!") {
}
}
}
| |
// 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.Linq;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public abstract class SslStreamStreamToStreamTest
{
private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");
protected abstract Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream);
[Fact]
public async Task SslStream_StreamToStream_Authentication_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var server = new SslStream(serverStream))
using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
{
await DoHandshake(client, server);
Assert.True(client.IsAuthenticated);
Assert.True(server.IsAuthenticated);
}
}
[Fact]
public async Task SslStream_StreamToStream_Authentication_IncorrectServerName_Fail()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new SslStream(clientStream))
using (var server = new SslStream(serverStream))
using (var certificate = Configuration.Certificates.GetServerCertificate())
{
Task t1 = client.AuthenticateAsClientAsync("incorrectServer");
Task t2 = server.AuthenticateAsServerAsync(certificate);
await Assert.ThrowsAsync<AuthenticationException>(() => t1);
await t2;
}
}
[Fact]
public async Task SslStream_StreamToStream_Successive_ClientWrite_Sync_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
await DoHandshake(clientSslStream, serverSslStream);
clientSslStream.Write(_sampleMsg);
int bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");
clientSslStream.Write(_sampleMsg);
bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
}
}
[Fact]
public async Task SslStream_StreamToStream_Successive_ClientWrite_WithZeroBytes_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
await DoHandshake(clientSslStream, serverSslStream);
clientSslStream.Write(Array.Empty<byte>());
await clientSslStream.WriteAsync(Array.Empty<byte>(), 0, 0);
clientSslStream.Write(_sampleMsg);
int bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");
clientSslStream.Write(_sampleMsg);
await clientSslStream.WriteAsync(Array.Empty<byte>(), 0, 0);
clientSslStream.Write(Array.Empty<byte>());
bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task SslStream_StreamToStream_LargeWrites_Sync_Success(bool randomizedData)
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
await DoHandshake(clientSslStream, serverSslStream);
byte[] largeMsg = new byte[4096 * 5]; // length longer than max read chunk size (16K + headers)
if (randomizedData)
{
new Random().NextBytes(largeMsg); // not very compressible
}
else
{
for (int i = 0; i < largeMsg.Length; i++)
{
largeMsg[i] = unchecked((byte)i); // very compressible
}
}
byte[] receivedLargeMsg = new byte[largeMsg.Length];
// First do a large write and read blocks at a time
clientSslStream.Write(largeMsg);
int bytesRead = 0, totalRead = 0;
while (totalRead < largeMsg.Length &&
(bytesRead = serverSslStream.Read(receivedLargeMsg, totalRead, receivedLargeMsg.Length - totalRead)) != 0)
{
totalRead += bytesRead;
}
Assert.Equal(receivedLargeMsg.Length, totalRead);
Assert.Equal(largeMsg, receivedLargeMsg);
// Then write again and read bytes at a time
clientSslStream.Write(largeMsg);
foreach (byte b in largeMsg)
{
Assert.Equal(b, serverSslStream.ReadByte());
}
}
}
[Fact]
public async Task SslStream_StreamToStream_Successive_ClientWrite_Async_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
await DoHandshake(clientSslStream, serverSslStream);
await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length)
.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
int bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += await serverSslStream.ReadAsync(recvBuf, bytesRead, _sampleMsg.Length - bytesRead)
.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");
await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length)
.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += await serverSslStream.ReadAsync(recvBuf, bytesRead, _sampleMsg.Length - bytesRead)
.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
}
}
[Fact]
public async Task SslStream_StreamToStream_Write_ReadByte_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
await DoHandshake(clientSslStream, serverSslStream);
for (int i = 0; i < 3; i++)
{
clientSslStream.Write(_sampleMsg);
foreach (byte b in _sampleMsg)
{
Assert.Equal(b, serverSslStream.ReadByte());
}
}
}
}
[Fact]
public async Task SslStream_StreamToStream_WriteAsync_ReadByte_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
await DoHandshake(clientSslStream, serverSslStream);
for (int i = 0; i < 3; i++)
{
await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length).ConfigureAwait(false);
foreach (byte b in _sampleMsg)
{
Assert.Equal(b, serverSslStream.ReadByte());
}
}
}
}
[Fact]
public async Task SslStream_StreamToStream_WriteAsync_ReadAsync_Pending_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new NotifyReadVirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
await DoHandshake(clientSslStream, serverSslStream);
var serverBuffer = new byte[1];
var tcs = new TaskCompletionSource<object>();
serverStream.OnRead += (buffer, offset, count) =>
{
tcs.TrySetResult(null);
};
Task readTask = serverSslStream.ReadAsync(serverBuffer, 0, serverBuffer.Length);
// Since the sequence of calls that ends in serverStream.Read() is sync, by now
// the read task will have acquired the semaphore shared by Stream.BeginReadInternal()
// and Stream.BeginWriteInternal().
// But to be sure, we wait until we know we're inside Read().
await tcs.Task.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
// Should not hang
await serverSslStream.WriteAsync(new byte[] { 1 }, 0, 1)
.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
// Read in client
var clientBuffer = new byte[1];
await clientSslStream.ReadAsync(clientBuffer, 0, clientBuffer.Length);
Assert.Equal(1, clientBuffer[0]);
// Complete server read task
await clientSslStream.WriteAsync(new byte[] { 2 }, 0, 1);
await readTask;
Assert.Equal(2, serverBuffer[0]);
}
}
[Fact]
public void SslStream_StreamToStream_Flush_Propagated()
{
VirtualNetwork network = new VirtualNetwork();
using (var stream = new VirtualNetworkStream(network, isServer: false))
using (var sslStream = new SslStream(stream, false, AllowAnyServerCertificate))
{
Assert.False(stream.HasBeenSyncFlushed);
sslStream.Flush();
Assert.True(stream.HasBeenSyncFlushed);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Relies on FlushAsync override not available in desktop")]
public void SslStream_StreamToStream_FlushAsync_Propagated()
{
VirtualNetwork network = new VirtualNetwork();
using (var stream = new VirtualNetworkStream(network, isServer: false))
using (var sslStream = new SslStream(stream, false, AllowAnyServerCertificate))
{
Task task = sslStream.FlushAsync();
Assert.False(task.IsCompleted);
stream.CompleteAsyncFlush();
Assert.True(task.IsCompleted);
}
}
private bool VerifyOutput(byte[] actualBuffer, byte[] expectedBuffer)
{
return expectedBuffer.SequenceEqual(actualBuffer);
}
protected bool AllowAnyServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None;
if (!Capability.IsTrustedRootCertificateInstalled())
{
expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors;
}
Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors);
if (sslPolicyErrors == expectedSslPolicyErrors)
{
return true;
}
else
{
return false;
}
}
}
public sealed class SslStreamStreamToStreamTest_Async : SslStreamStreamToStreamTest
{
protected override async Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
{
using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
{
Task t1 = clientSslStream.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));
Task t2 = serverSslStream.AuthenticateAsServerAsync(certificate);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
}
}
}
public sealed class SslStreamStreamToStreamTest_BeginEnd : SslStreamStreamToStreamTest
{
protected override async Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
{
using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
{
Task t1 = Task.Factory.FromAsync(clientSslStream.BeginAuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false), null, null), clientSslStream.EndAuthenticateAsClient);
Task t2 = Task.Factory.FromAsync(serverSslStream.BeginAuthenticateAsServer(certificate, null, null), serverSslStream.EndAuthenticateAsServer);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
}
}
}
public sealed class SslStreamStreamToStreamTest_Sync : SslStreamStreamToStreamTest
{
protected override async Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
{
using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
{
Task t1 = Task.Run(() => clientSslStream.AuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false)));
Task t2 = Task.Run(() => serverSslStream.AuthenticateAsServer(certificate));
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
}
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin.Helpers;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security.Infrastructure;
using Newtonsoft.Json.Linq;
namespace Microsoft.Owin.Security.Facebook
{
internal class FacebookAuthenticationHandler : AuthenticationHandler<FacebookAuthenticationOptions>
{
private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
private const string TokenEndpoint = "https://graph.facebook.com/oauth/access_token";
private const string GraphApiEndpoint = "https://graph.facebook.com/me";
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
public FacebookAuthenticationHandler(HttpClient httpClient, ILogger logger)
{
_httpClient = httpClient;
_logger = logger;
}
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
AuthenticationProperties properties = null;
try
{
string code = null;
string state = null;
IReadableStringCollection query = Request.Query;
IList<string> values = query.GetValues("error");
if (values != null && values.Count >= 1)
{
_logger.WriteVerbose("Remote server returned an error: " + Request.QueryString);
}
values = query.GetValues("code");
if (values != null && values.Count == 1)
{
code = values[0];
}
values = query.GetValues("state");
if (values != null && values.Count == 1)
{
state = values[0];
}
properties = Options.StateDataFormat.Unprotect(state);
if (properties == null)
{
return null;
}
// OAuth2 10.12 CSRF
if (!ValidateCorrelationId(properties, _logger))
{
return new AuthenticationTicket(null, properties);
}
if (code == null)
{
// Null if the remote server returns an error.
return new AuthenticationTicket(null, properties);
}
string requestPrefix = Request.Scheme + "://" + Request.Host;
string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath;
string tokenRequest = "grant_type=authorization_code" +
"&code=" + Uri.EscapeDataString(code) +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
"&client_id=" + Uri.EscapeDataString(Options.AppId) +
"&client_secret=" + Uri.EscapeDataString(Options.AppSecret);
HttpResponseMessage tokenResponse = await _httpClient.GetAsync(TokenEndpoint + "?" + tokenRequest, Request.CallCancelled);
tokenResponse.EnsureSuccessStatusCode();
string text = await tokenResponse.Content.ReadAsStringAsync();
IFormCollection form = WebHelpers.ParseForm(text);
string accessToken = form["access_token"];
string expires = form["expires"];
string graphAddress = GraphApiEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken);
if (Options.SendAppSecretProof)
{
graphAddress += "&appsecret_proof=" + GenerateAppSecretProof(accessToken);
}
HttpResponseMessage graphResponse = await _httpClient.GetAsync(graphAddress, Request.CallCancelled);
graphResponse.EnsureSuccessStatusCode();
text = await graphResponse.Content.ReadAsStringAsync();
JObject user = JObject.Parse(text);
var context = new FacebookAuthenticatedContext(Context, user, accessToken, expires);
context.Identity = new ClaimsIdentity(
Options.AuthenticationType,
ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
if (!string.IsNullOrEmpty(context.Id))
{
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.UserName))
{
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.Email))
{
context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.Name))
{
context.Identity.AddClaim(new Claim("urn:facebook:name", context.Name, XmlSchemaString, Options.AuthenticationType));
// Many Facebook accounts do not set the UserName field. Fall back to the Name field instead.
if (string.IsNullOrEmpty(context.UserName))
{
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType));
}
}
if (!string.IsNullOrEmpty(context.Link))
{
context.Identity.AddClaim(new Claim("urn:facebook:link", context.Link, XmlSchemaString, Options.AuthenticationType));
}
context.Properties = properties;
await Options.Provider.Authenticated(context);
return new AuthenticationTicket(context.Identity, context.Properties);
}
catch (Exception ex)
{
_logger.WriteError("Authentication failed", ex);
return new AuthenticationTicket(null, properties);
}
}
protected override Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode != 401)
{
return Task.FromResult<object>(null);
}
AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge != null)
{
string baseUri =
Request.Scheme +
Uri.SchemeDelimiter +
Request.Host +
Request.PathBase;
string currentUri =
baseUri +
Request.Path +
Request.QueryString;
string redirectUri =
baseUri +
Options.CallbackPath;
AuthenticationProperties properties = challenge.Properties;
if (string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = currentUri;
}
// OAuth2 10.12 CSRF
GenerateCorrelationId(properties);
// comma separated
string scope = string.Join(",", Options.Scope);
string state = Options.StateDataFormat.Protect(properties);
string authorizationEndpoint =
"https://www.facebook.com/dialog/oauth" +
"?response_type=code" +
"&client_id=" + Uri.EscapeDataString(Options.AppId) +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
"&scope=" + Uri.EscapeDataString(scope) +
"&state=" + Uri.EscapeDataString(state);
var redirectContext = new FacebookApplyRedirectContext(
Context, Options,
properties, authorizationEndpoint);
Options.Provider.ApplyRedirect(redirectContext);
}
return Task.FromResult<object>(null);
}
public override async Task<bool> InvokeAsync()
{
return await InvokeReplyPathAsync();
}
private async Task<bool> InvokeReplyPathAsync()
{
if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path)
{
// TODO: error responses
AuthenticationTicket ticket = await AuthenticateAsync();
if (ticket == null)
{
_logger.WriteWarning("Invalid return state, unable to redirect.");
Response.StatusCode = 500;
return true;
}
var context = new FacebookReturnEndpointContext(Context, ticket);
context.SignInAsAuthenticationType = Options.SignInAsAuthenticationType;
context.RedirectUri = ticket.Properties.RedirectUri;
await Options.Provider.ReturnEndpoint(context);
if (context.SignInAsAuthenticationType != null &&
context.Identity != null)
{
ClaimsIdentity grantIdentity = context.Identity;
if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal))
{
grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType);
}
Context.Authentication.SignIn(context.Properties, grantIdentity);
}
if (!context.IsRequestCompleted && context.RedirectUri != null)
{
string redirectUri = context.RedirectUri;
if (context.Identity == null)
{
// add a redirect hint that sign-in failed in some way
redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied");
}
Response.Redirect(redirectUri);
context.RequestCompleted();
}
return context.IsRequestCompleted;
}
return false;
}
private string GenerateAppSecretProof(string accessToken)
{
using (HMACSHA256 algorithm = new HMACSHA256(Encoding.ASCII.GetBytes(Options.AppSecret)))
{
byte[] hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(accessToken));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
builder.Append(hash[i].ToString("x2", CultureInfo.InvariantCulture));
}
return builder.ToString();
}
}
}
}
| |
// 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.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Tagging
{
/// <summary>
/// Base type of all asynchronous tagger providers (<see cref="ITaggerProvider"/> and <see cref="IViewTaggerProvider"/>).
/// </summary>
internal abstract partial class AbstractAsynchronousTaggerProvider<TTag> : ForegroundThreadAffinitizedObject where TTag : ITag
{
private readonly object _uniqueKey = new object();
private readonly IAsynchronousOperationListener _asyncListener;
private readonly IForegroundNotificationService _notificationService;
/// <summary>
/// The behavior the tagger engine will have when text changes happen to the subject buffer
/// it is attached to. Most taggers can simply use <see cref="TaggerTextChangeBehavior.None"/>.
/// However, advanced taggers that want to perform specialized behavior depending on what has
/// actually changed in the file can specify <see cref="TaggerTextChangeBehavior.TrackTextChanges"/>.
///
/// If this is specified the tagger engine will track text changes and pass them along as
/// <see cref="TaggerContext{TTag}.TextChangeRange"/> when calling
/// <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>.
/// </summary>
protected virtual TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.None;
/// <summary>
/// The behavior the tagger will have when changes happen to the caret.
/// </summary>
protected virtual TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.None;
/// <summary>
/// The behavior of tags that are created by the async tagger. This will matter for tags
/// created for a previous version of a document that are mapped forward by the async
/// tagging architecture. This value cannot be <see cref="SpanTrackingMode.Custom"/>.
/// </summary>
protected virtual SpanTrackingMode SpanTrackingMode => SpanTrackingMode.EdgeExclusive;
/// <summary>
/// Comparer used to determine if two <see cref="ITag"/>s are the same. This is used by
/// the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> to determine if a previous set of
/// computed tags and a current set of computed tags should be considered the same or not.
/// If they are the same, then the UI will not be updated. If they are different then
/// the UI will be updated for sets of tags that have been removed or added.
/// </summary>
protected virtual IEqualityComparer<TTag> TagComparer => EqualityComparer<TTag>.Default;
/// <summary>
/// Options controlling this tagger. The tagger infrastructure will check this option
/// against the buffer it is associated with to see if it should tag or not.
///
/// An empty enumerable, or null, can be returned to indicate that this tagger should
/// run unconditionally.
/// </summary>
protected virtual IEnumerable<Option<bool>> Options => SpecializedCollections.EmptyEnumerable<Option<bool>>();
protected virtual IEnumerable<PerLanguageOption<bool>> PerLanguageOptions => SpecializedCollections.EmptyEnumerable<PerLanguageOption<bool>>();
#if DEBUG
public readonly string StackTrace;
#endif
protected AbstractAsynchronousTaggerProvider(
IAsynchronousOperationListener asyncListener,
IForegroundNotificationService notificationService)
{
_asyncListener = asyncListener;
_notificationService = notificationService;
#if DEBUG
StackTrace = new StackTrace().ToString();
#endif
}
private TagSource CreateTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
return new TagSource(textViewOpt, subjectBuffer, this, _asyncListener, _notificationService);
}
internal IAccurateTagger<T> GetOrCreateTagger<T>(ITextView textViewOpt, ITextBuffer subjectBuffer) where T : ITag
{
if (!subjectBuffer.GetOption(EditorComponentOnOffOptions.Tagger))
{
return null;
}
var tagSource = GetOrCreateTagSource(textViewOpt, subjectBuffer);
return tagSource == null
? null
: new Tagger(_asyncListener, _notificationService, tagSource, subjectBuffer) as IAccurateTagger<T>;
}
private TagSource GetOrCreateTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
TagSource tagSource;
if (!this.TryRetrieveTagSource(textViewOpt, subjectBuffer, out tagSource))
{
tagSource = this.CreateTagSource(textViewOpt, subjectBuffer);
if (tagSource == null)
{
return null;
}
this.StoreTagSource(textViewOpt, subjectBuffer, tagSource);
tagSource.Disposed += (s, e) => this.RemoveTagSource(textViewOpt, subjectBuffer);
}
return tagSource;
}
private bool TryRetrieveTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer, out TagSource tagSource)
{
return textViewOpt != null
? textViewOpt.TryGetPerSubjectBufferProperty(subjectBuffer, _uniqueKey, out tagSource)
: subjectBuffer.Properties.TryGetProperty(_uniqueKey, out tagSource);
}
private void RemoveTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
if (textViewOpt != null)
{
textViewOpt.RemovePerSubjectBufferProperty<TagSource, ITextView>(subjectBuffer, _uniqueKey);
}
else
{
subjectBuffer.Properties.RemoveProperty(_uniqueKey);
}
}
private void StoreTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer, TagSource tagSource)
{
if (textViewOpt != null)
{
textViewOpt.AddPerSubjectBufferProperty(subjectBuffer, _uniqueKey, tagSource);
}
else
{
subjectBuffer.Properties.AddProperty(_uniqueKey, tagSource);
}
}
/// <summary>
/// Called by the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> infrastructure to
/// determine the caret position. This value will be passed in as the value to
/// <see cref="TaggerContext{TTag}.CaretPosition"/> in the call to
/// <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>.
/// </summary>
protected virtual SnapshotPoint? GetCaretPoint(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
return textViewOpt?.GetCaretPoint(subjectBuffer);
}
/// <summary>
/// Called by the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> infrastructure to determine
/// the set of spans that it should asynchronously tag. This will be called in response to
/// notifications from the <see cref="ITaggerEventSource"/> that something has changed, and
/// will only be called from the UI thread. The tagger infrastructure will then determine
/// the <see cref="DocumentSnapshotSpan"/>s associated with these <see cref="SnapshotSpan"/>s
/// and will asynchronously call into <see cref="ProduceTagsAsync(TaggerContext{TTag})"/> at some point in
/// the future to produce tags for these spans.
/// </summary>
protected virtual IEnumerable<SnapshotSpan> GetSpansToTag(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
// For a standard tagger, the spans to tag is the span of the entire snapshot.
return new[] { subjectBuffer.CurrentSnapshot.GetFullSpan() };
}
/// <summary>
/// Creates the <see cref="ITaggerEventSource"/> that notifies the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/>
/// that it should recompute tags for the text buffer after an appropriate <see cref="TaggerDelay"/>.
/// </summary>
protected abstract ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer);
internal Task ProduceTagsAsync_ForTestingPurposesOnly(TaggerContext<TTag> context)
{
return ProduceTagsAsync(context);
}
/// <summary>
/// Produce tags for the given context.
/// </summary>
protected virtual async Task ProduceTagsAsync(TaggerContext<TTag> context)
{
foreach (var spanToTag in context.SpansToTag)
{
context.CancellationToken.ThrowIfCancellationRequested();
await ProduceTagsAsync(context, spanToTag, GetCaretPosition(context.CaretPosition, spanToTag.SnapshotSpan)).ConfigureAwait(false);
}
}
private static int? GetCaretPosition(SnapshotPoint? caretPosition, SnapshotSpan snapshotSpan)
{
return caretPosition.HasValue && caretPosition.Value.Snapshot == snapshotSpan.Snapshot
? caretPosition.Value.Position : (int?)null;
}
protected virtual Task ProduceTagsAsync(TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition)
{
return SpecializedTasks.EmptyTask;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.