context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Globalization;
using Common.Logging;
namespace Spring.Context.Support
{
/// <summary>
/// Abstract implementation of the <see cref="Spring.Context.IHierarchicalMessageSource"/> interface,
/// implementing common handling of message variants, making it easy
/// to implement a specific strategy for a concrete <see cref="Spring.Context.IMessageSource"/>.
/// </summary>
/// <remarks>
/// <p>Subclasses must implement the abstract <code>ResolveObject</code>
/// method.</p>
/// <p><b>Note:</b> By default, message texts are only parsed through
/// String.Format if arguments have been passed in for the message. In case
/// of no arguments, message texts will be returned as-is. As a consequence,
/// you should only use String.Format escaping for messages with actual
/// arguments, and keep all other messages unescaped.
/// </p>
/// <p>Supports not only IMessageSourceResolvables as primary messages
/// but also resolution of message arguments that are in turn
/// IMessageSourceResolvables themselves.
/// </p>
/// <p>This class does not implement caching of messages per code, thus
/// subclasses can dynamically change messages over time. Subclasses are
/// encouraged to cache their messages in a modification-aware fashion,
/// allowing for hot deployment of updated messages.
/// </p>
/// </remarks>
/// <author>Rod Johnson</author>
/// <author>Juergen Hoeller</author>
/// <author>Griffin Caprio (.NET)</author>
/// <author>Harald Radi (.NET)</author>
/// <seealso cref="Spring.Context.IMessageSourceResolvable"/>
/// <seealso cref="Spring.Context.IMessageSource"/>
/// <seealso cref="Spring.Context.IHierarchicalMessageSource"/>
public abstract class AbstractMessageSource : IHierarchicalMessageSource
{
#region Fields
/// <summary>
/// holds the logger instance shared with subclasses.
/// </summary>
protected readonly ILog log;
private IMessageSource parentMessageSource;
private bool useCodeAsDefaultMessage = false;
#endregion
#region Constructor
/// <summary>
/// Initializes this instance.
/// </summary>
protected AbstractMessageSource()
{
log = LogManager.GetLogger(GetType());
}
#endregion
#region Properties
/// <summary>Gets or Sets a value indicating whether to use the message code as
/// default message instead of throwing a NoSuchMessageException.
/// Useful for development and debugging. Default is "false".
/// </summary>
/// <remarks>
/// <p>Note: In case of a IMessageSourceResolvable with multiple codes
/// (like a FieldError) and a MessageSource that has a parent MessageSource,
/// do <i>not</i> activate "UseCodeAsDefaultMessage" in the <i>parent</i>:
/// Else, you'll get the first code returned as message by the parent,
/// without attempts to check further codes.</p>
/// <p>To be able to work with "UseCodeAsDefaultMessage" turned on in the parent,
/// AbstractMessageSource contains special checks
/// to delegate to the internal <code>GetMessageInternal</code> method if available.
/// In general, it is recommended to just use "UseCodeAsDefaultMessage" during
/// development and not rely on it in production in the first place, though.</p>
/// <p>Alternatively, consider overriding the <code>GetDefaultMessage</code>
/// method to return a custom fallback message for an unresolvable code.</p>
/// </remarks>
/// <value>
/// <c>true</c> if use the message code as default message instead of
/// throwing a NoSuchMessageException; otherwise, <c>false</c>.
/// </value>
public bool UseCodeAsDefaultMessage
{
get { return useCodeAsDefaultMessage; }
set { useCodeAsDefaultMessage = value; }
}
#endregion
#region IHierarchicalMessageSource Members
/// <summary>
/// The parent message source used to try and resolve messages that
/// this object can't resolve.
/// </summary>
/// <value></value>
/// <remarks>
/// <p>
/// If the value of this property is <see langword="null"/> then no
/// further resolution is possible.
/// </p>
/// </remarks>
public IMessageSource ParentMessageSource
{
get { return parentMessageSource; }
set { parentMessageSource = value; }
}
/// <summary>
/// Resolve the message identified by the supplied
/// <paramref name="name"/>.
/// </summary>
/// <param name="name">The name of the message to resolve.</param>
/// <returns>
/// The resolved message if the lookup was successful (see above for
/// the return value in the case of an unsuccessful lookup).
/// </returns>
/// <remarks>
/// If the lookup is not successful throw NoSuchMessageException
/// </remarks>
public string GetMessage(string name)
{
return GetMessage(name, CultureInfo.CurrentUICulture, null);
}
/// <summary>
/// Resolve the message identified by the supplied
/// <paramref name="name"/>.
/// </summary>
/// <param name="name">The name of the message to resolve.</param>
/// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> that represents
/// the culture for which the resource is localized.</param>
/// <returns>
/// The resolved message if the lookup was successful (see above for
/// the return value in the case of an unsuccessful lookup).
/// </returns>
/// <remarks>
/// Note that the fallback behavior based on CultureInfo seem to
/// have a bug that is fixed by installed .NET 1.1 Service Pack 1.
/// <p>
/// If the lookup is not successful, implementations are permitted to
/// take one of two actions.
/// </p>
/// If the lookup is not successful throw NoSuchMessageException
/// </remarks>
public string GetMessage(string name, CultureInfo culture)
{
return GetMessage(name, culture, null);
}
/// <summary>
/// Resolve the message identified by the supplied
/// <paramref name="name"/>.
/// </summary>
/// <param name="name">The name of the message to resolve.</param>
/// <param name="arguments">The array of arguments that will be filled in for parameters within
/// the message, or <see langword="null"/> if there are no parameters
/// within the message. Parameters within a message should be
/// referenced using the same syntax as the format string for the
/// <see cref="System.String.Format(string,object[])"/> method.</param>
/// <returns>
/// The resolved message if the lookup was successful (see above for
/// the return value in the case of an unsuccessful lookup).
/// </returns>
/// <remarks>
/// If the lookup is not successful throw NoSuchMessageException
/// </remarks>
public string GetMessage(string name, params object[] arguments)
{
return GetMessage(name, CultureInfo.CurrentUICulture, arguments);
}
/// <summary>
/// Resolve the message identified by the supplied
/// <paramref name="name"/>.
/// </summary>
/// <param name="name">The name of the message to resolve.</param>
/// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> that represents
/// the culture for which the resource is localized.</param>
/// <param name="arguments">The array of arguments that will be filled in for parameters within
/// the message, or <see langword="null"/> if there are no parameters
/// within the message. Parameters within a message should be
/// referenced using the same syntax as the format string for the
/// <see cref="System.String.Format(string,object[])"/> method.</param>
/// <returns>
/// The resolved message if the lookup was successful (see above for
/// the return value in the case of an unsuccessful lookup).
/// </returns>
/// <remarks>
/// Note that the fallback behavior based on CultureInfo seem to
/// have a bug that is fixed by installed .NET 1.1 Service Pack 1.
/// <p>
/// If the lookup is not successful throw NoSuchMessageException.
/// </p>
/// </remarks>
public string GetMessage(string name, CultureInfo culture, params object[] arguments)
{
string msg = GetMessageInternal(name, arguments, culture);
if (msg != null) return msg;
string fallback = GetDefaultMessage(name);
if (fallback != null) return fallback;
throw new NoSuchMessageException(name, culture);
}
/// <summary>
/// Resolve the message identified by the supplied
/// <paramref name="name"/>.
/// </summary>
/// <param name="name">The name of the message to resolve.</param>
/// <param name="defaultMessage">The default message if name is not found.</param>
/// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> that represents
/// the culture for which the resource is localized.</param>
/// <param name="arguments">The array of arguments that will be filled in for parameters within
/// the message, or <see langword="null"/> if there are no parameters
/// within the message. Parameters within a message should be
/// referenced using the same syntax as the format string for the
/// <see cref="System.String.Format(string,object[])"/> method.</param>
/// <returns>
/// The resolved message if the lookup was successful (see above for
/// the return value in the case of an unsuccessful lookup).
/// </returns>
/// <remarks>
/// Note that the fallback behavior based on CultureInfo seem to
/// have a bug that is fixed by installed .NET 1.1 Service Pack 1.
/// <p>
/// If the lookup is not successful throw NoSuchMessageException
/// </p>
/// </remarks>
public string GetMessage(string name, string defaultMessage, CultureInfo culture, params object[] arguments)
{
string msg = GetMessageInternal(name, arguments, culture);
if (msg != null) return msg;
if (defaultMessage == null)
{
string fallback = GetDefaultMessage(name);
if (fallback != null) return fallback;
}
return RenderDefaultMessage(defaultMessage, arguments, culture);
}
/// <summary>
/// Resolve the message using all of the attributes contained within
/// the supplied <see cref="Spring.Context.IMessageSourceResolvable"/>
/// argument.
/// </summary>
/// <param name="resolvable">The value object storing those attributes that are required to
/// properly resolve a message.</param>
/// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> that represents
/// the culture for which the resource is localized.</param>
/// <returns>
/// The resolved message if the lookup was successful.
/// </returns>
/// <exception cref="Spring.Context.NoSuchMessageException">
/// If the message could not be resolved.
/// </exception>
public string GetMessage(IMessageSourceResolvable resolvable, CultureInfo culture)
{
string[] codes = resolvable.GetCodes();
if (codes == null) codes = new string[0];
for (int i = 0; i < codes.Length; i++)
{
string msg = GetMessageInternal(codes[i], resolvable.GetArguments(), culture);
if (msg != null) return msg;
}
if (resolvable.DefaultMessage != null)
return RenderDefaultMessage(resolvable.DefaultMessage, resolvable.GetArguments(), culture);
if (codes.Length > 0)
{
string fallback = GetDefaultMessage(codes[0]);
if (fallback != null) return fallback;
}
throw new NoSuchMessageException(codes.Length > 0 ? codes[codes.Length - 1] : null, culture);
}
/// <summary>
/// Gets a localized resource object identified by the supplied
/// <paramref name="name"/>.
/// </summary>
/// <param name="name">
/// The name of the resource object to resolve.
/// </param>
/// <returns>
/// The resolved object, or <see langword="null"/> if not found.
/// </returns>
/// <seealso cref="Spring.Context.IMessageSource.GetResourceObject(string)"/>
public object GetResourceObject(string name)
{
object resource = GetResourceInternal(name, CultureInfo.CurrentUICulture);
if (resource != null) return resource;
if (ParentMessageSource != null)
return ParentMessageSource.GetResourceObject(name, CultureInfo.CurrentUICulture);
return null;
}
/// <summary>
/// Gets a localized resource object identified by the supplied
/// <paramref name="name"/>.
/// </summary>
/// <remarks>
/// Note that the fallback behavior based on CultureInfo seem to
/// have a bug that is fixed by installed .NET 1.1 Service Pack 1.
/// </remarks>
/// <param name="name">
/// The name of the resource object to resolve.
/// </param>
/// <param name="culture">
/// The <see cref="System.Globalization.CultureInfo"/> with which the
/// resource is associated.
/// </param>
/// <returns>
/// The resolved object, or <see langword="null"/> if not found. If
/// the resource name resolves to null, then in .NET 1.1 the return
/// value will be String.Empty whereas in .NET 2.0 it will return
/// null.
/// </returns>
/// <seealso cref="Spring.Context.IMessageSource.GetResourceObject(string, CultureInfo)"/>
public object GetResourceObject(string name, CultureInfo culture)
{
object resource = GetResourceInternal(name, culture);
if (resource != null) return resource;
if (ParentMessageSource != null) return ParentMessageSource.GetResourceObject(name, culture);
return null;
}
/// <summary>
/// Applies resources to object properties.
/// </summary>
/// <param name="value">
/// An object that contains the property values to be applied.
/// </param>
/// <param name="objectName">
/// The base name of the object to use for key lookup.
/// </param>
/// <param name="culture">
/// The <see cref="System.Globalization.CultureInfo"/> with which the
/// resource is associated.
/// </param>
/// <seealso cref="Spring.Context.IMessageSource.ApplyResources(object, string, CultureInfo)"/>
public void ApplyResources(
object value, string objectName, CultureInfo culture)
{
ApplyResourcesInternal(value, objectName, culture);
if (ParentMessageSource != null) ParentMessageSource.ApplyResources(value, objectName, culture);
}
#endregion
#region Protected Methods
/// <summary>Resolve the given code and arguments as message in the given culture,
/// returning null if not found. Does <i>not</i> fall back to the code
/// as default message. Invoked by GetMessage methods.
/// </summary>
/// <param name="code">The code to lookup up, such as 'calculator.noRateSet'.</param>
/// <param name="args"> array of arguments that will be filled in for params
/// within the message.</param>
/// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> with which the
/// resource is associated.</param>
/// <returns>
/// The resolved message if the lookup was successful.
/// </returns>
protected string GetMessageInternal(string code, object[] args, CultureInfo culture)
{
if (code == null) return null;
if (culture == null) culture = CultureInfo.CurrentUICulture;
if ((args != null && args.Length > 0))
{
// Resolve arguments eagerly, for the case where the message
// is defined in a parent MessageSource but resolvable arguments
// are defined in the child MessageSource.
args = ResolveArguments(args, culture);
}
string message = ResolveMessage(code, culture);
if (message != null) return FormatMessage(message, args, culture);
// Not found -> check parent, if any.
return GetMessageFromParent(code, args, culture);
}
/// <summary>
/// Try to retrieve the given message from the parent MessageSource, if any.
/// </summary>
/// <param name="code">The code to lookup up, such as 'calculator.noRateSet'.</param>
/// <param name="args"> array of arguments that will be filled in for params
/// within the message.</param>
/// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> with which the
/// resource is associated.</param>
/// <returns>
/// The resolved message if the lookup was successful.
/// </returns>
protected string GetMessageFromParent(string code, object[] args, CultureInfo culture)
{
if (ParentMessageSource != null)
{
AbstractMessageSource parent = ParentMessageSource as AbstractMessageSource;
if (parent != null)
{
// Call internal method to avoid getting the default code back
// in case of "useCodeAsDefaultMessage" being activated.
return parent.GetMessageInternal(code, args, culture);
}
else
{
// Check parent MessageSource, returning null if not found there.
return ParentMessageSource.GetMessage(code, null, culture, args);
}
}
// Not found in parent either.
return null;
}
/// <summary>
/// Return a fallback default message for the given code, if any.
/// </summary>
/// <remarks>
/// Default is to return the code itself if "UseCodeAsDefaultMessage"
/// is activated, or return no fallback else. In case of no fallback,
/// the caller will usually receive a NoSuchMessageException from GetMessage
/// </remarks>
/// <param name="code">The code to lookup up, such as 'calculator.noRateSet'.</param>
/// <returns>The default message to use, or null if none.</returns>
protected virtual string GetDefaultMessage(string code)
{
if (UseCodeAsDefaultMessage) return code;
return null;
}
/// <summary>
/// Renders the default message string. The default message is passed in as specified by the
/// caller and can be rendered into a fully formatted default message shown to the user.
/// </summary>
/// <remarks>Default implementation passed he String for String.Format resolving any
/// argument placeholders found in them. Subclasses may override this method to plug
/// in custom processing of default messages.
/// </remarks>
/// <param name="defaultMessage">The default message.</param>
/// <param name="args">The array of agruments that will be filled in for parameter
/// placeholders within the message, or null if none.</param>
/// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> with which the
/// resource is associated.</param>
/// <returns>The rendered default message (with resolved arguments)</returns>
protected virtual string RenderDefaultMessage(string defaultMessage, object[] args, CultureInfo culture)
{
return FormatMessage(defaultMessage, args, culture);
}
/// <summary>
/// Format the given default message String resolving any
/// agrument placeholders found in them.
/// </summary>
/// <param name="msg">The message to format.</param>
/// <param name="args">The array of agruments that will be filled in for parameter
/// placeholders within the message, or null if none.</param>
/// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> with which the
/// resource is associated.</param>
/// <returns>The formatted message (with resolved arguments)</returns>
protected virtual string FormatMessage(string msg, object[] args, CultureInfo culture)
{
if (msg == null || ((args == null || args.Length == 0))) return msg;
return String.Format(culture, msg, args);
}
/// <summary>
/// Search through the given array of objects, find any
/// MessageSourceResolvable objects and resolve them.
/// </summary>
/// <remarks>
/// Allows for messages to have MessageSourceResolvables as arguments.
/// </remarks>
///
/// <param name="args">The array of arguments for a message.</param>
/// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> with which the
/// resource is associated.</param>
/// <returns>An array of arguments with any IMessageSourceResolvables resolved</returns>
protected virtual object[] ResolveArguments(object[] args, CultureInfo culture)
{
if (args == null) return new object[0];
object[] resolvedArgs = new object[args.Length];
for (int i = 0; i < args.Length; i++)
{
IMessageSourceResolvable resolvable = args[i] as IMessageSourceResolvable;
if (resolvable != null) resolvedArgs[i] = GetMessage(resolvable, culture);
else resolvedArgs[i] = args[i];
}
return resolvedArgs;
}
/// <summary>
/// Gets the specified resource (e.g. Icon or Bitmap).
/// </summary>
/// <param name="name">The name of the resource to resolve.</param>
/// <param name="cultureInfo">
/// The <see cref="System.Globalization.CultureInfo"/> to resolve the
/// code for.
/// </param>
/// <returns>The resource if found. <see langword="null"/> otherwise.</returns>
protected object GetResourceInternal(string name, CultureInfo cultureInfo)
{
if (cultureInfo == null) cultureInfo = CultureInfo.CurrentUICulture;
if (name == null) return null;
return ResolveObject(name, cultureInfo);
}
/// <summary>
/// Applies resources from the given name on the specified object.
/// </summary>
/// <param name="value">
/// An object that contains the property values to be applied.
/// </param>
/// <param name="objectName">
/// The base name of the object to use for key lookup.
/// </param>
/// <param name="cultureInfo">
/// The <see cref="System.Globalization.CultureInfo"/> with which the
/// resource is associated.
/// </param>
protected void ApplyResourcesInternal(object value, string objectName, CultureInfo cultureInfo)
{
if (cultureInfo == null) cultureInfo = CultureInfo.CurrentUICulture;
ApplyResourcesToObject(value, objectName, cultureInfo);
}
#endregion
#region Protected Abstract Methods
/// <summary>
/// Subclasses must implement this method to resolve a message.
/// </summary>
/// <param name="code">The code to lookup up, such as 'calculator.noRateSet'.</param>
/// <param name="cultureInfo">The <see cref="System.Globalization.CultureInfo"/> with which the
/// resource is associated.</param>
/// <returns>The resolved message from the backing store of message data.</returns>
protected abstract string ResolveMessage(string code, CultureInfo cultureInfo);
/// <summary>
/// Resolves an object (typically an icon or bitmap).
/// </summary>
/// <remarks>
/// <p>
/// Subclasses must implement this method to resolve an object.
/// </p>
/// </remarks>
/// <param name="code">The code of the object to resolve.</param>
/// <param name="cultureInfo">
/// The <see cref="System.Globalization.CultureInfo"/> to resolve the
/// code for.
/// </param>
/// <returns>
/// The resolved object or <see langword="null"/> if not found.
/// </returns>
protected abstract object ResolveObject(string code, CultureInfo cultureInfo);
/// <summary>
/// Applies resources to object properties.
/// </summary>
/// <remarks>
/// <p>
/// Subclasses must implement this method to apply resources
/// to an arbitrary object.
/// </p>
/// </remarks>
/// <param name="value">
/// An object that contains the property values to be applied.
/// </param>
/// <param name="objectName">
/// The base name of the object to use for key lookup.
/// </param>
/// <param name="cultureInfo">
/// The <see cref="System.Globalization.CultureInfo"/> with which the
/// resource is associated.
/// </param>
protected abstract void ApplyResourcesToObject(object value, string objectName, CultureInfo cultureInfo);
#endregion
}
}
| |
using System;
using System.Windows.Forms;
using System.Drawing;
namespace WeifenLuo.WinFormsUI.Docking
{
partial class DockPanel
{
internal class DefaultAutoHideWindowControl : AutoHideWindowControl
{
public DefaultAutoHideWindowControl(DockPanel dockPanel) : base(dockPanel)
{
m_splitter = new SplitterControl(this);
Controls.Add(m_splitter);
}
protected override void OnLayout(LayoutEventArgs levent)
{
DockPadding.All = 0;
if (DockState == DockState.DockLeftAutoHide)
{
DockPadding.Right = 2;
m_splitter.Dock = DockStyle.Right;
}
else if (DockState == DockState.DockRightAutoHide)
{
DockPadding.Left = 2;
m_splitter.Dock = DockStyle.Left;
}
else if (DockState == DockState.DockTopAutoHide)
{
DockPadding.Bottom = 2;
m_splitter.Dock = DockStyle.Bottom;
}
else if (DockState == DockState.DockBottomAutoHide)
{
DockPadding.Top = 2;
m_splitter.Dock = DockStyle.Top;
}
Rectangle rectDisplaying = DisplayingRectangle;
Rectangle rectHidden = new Rectangle(-rectDisplaying.Width, rectDisplaying.Y, rectDisplaying.Width, rectDisplaying.Height);
foreach (Control c in Controls)
{
DockPane pane = c as DockPane;
if (pane == null)
continue;
if (pane == ActivePane)
pane.Bounds = rectDisplaying;
else
pane.Bounds = rectHidden;
}
base.OnLayout(levent);
}
protected override void OnPaint(PaintEventArgs e)
{
// Draw the border
Graphics g = e.Graphics;
if (DockState == DockState.DockBottomAutoHide)
g.DrawLine(SystemPens.ControlLightLight, 0, 1, ClientRectangle.Right, 1);
else if (DockState == DockState.DockRightAutoHide)
g.DrawLine(SystemPens.ControlLightLight, 1, 0, 1, ClientRectangle.Bottom);
else if (DockState == DockState.DockTopAutoHide)
{
g.DrawLine(SystemPens.ControlDark, 0, ClientRectangle.Height - 2, ClientRectangle.Right, ClientRectangle.Height - 2);
g.DrawLine(SystemPens.ControlDarkDark, 0, ClientRectangle.Height - 1, ClientRectangle.Right, ClientRectangle.Height - 1);
}
else if (DockState == DockState.DockLeftAutoHide)
{
g.DrawLine(SystemPens.ControlDark, ClientRectangle.Width - 2, 0, ClientRectangle.Width - 2, ClientRectangle.Bottom);
g.DrawLine(SystemPens.ControlDarkDark, ClientRectangle.Width - 1, 0, ClientRectangle.Width - 1, ClientRectangle.Bottom);
}
base.OnPaint(e);
}
}
public class AutoHideWindowControl : Panel, ISplitterDragSource
{
protected class SplitterControl : SplitterBase
{
public SplitterControl(AutoHideWindowControl autoHideWindow)
{
m_autoHideWindow = autoHideWindow;
}
private AutoHideWindowControl m_autoHideWindow;
private AutoHideWindowControl AutoHideWindow
{
get { return m_autoHideWindow; }
}
protected override int SplitterSize
{
get { return Measures.SplitterSize; }
}
protected override void StartDrag()
{
if ( !m_autoHideWindow.m_dockPanel.AllowChangeLayout )
return;
AutoHideWindow.DockPanel.BeginDrag(AutoHideWindow, AutoHideWindow.RectangleToScreen(Bounds));
}
}
#region consts
private const int ANIMATE_TIME = 100; // in mini-seconds
#endregion
private Timer m_timerMouseTrack;
protected SplitterBase m_splitter;
public AutoHideWindowControl(DockPanel dockPanel)
{
m_dockPanel = dockPanel;
m_timerMouseTrack = new Timer();
m_timerMouseTrack.Tick += new EventHandler(TimerMouseTrack_Tick);
Visible = false;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
m_timerMouseTrack.Dispose();
}
base.Dispose(disposing);
}
private DockPanel m_dockPanel = null;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
private DockPane m_activePane = null;
public DockPane ActivePane
{
get { return m_activePane; }
}
private void SetActivePane()
{
DockPane value = (ActiveContent == null ? null : ActiveContent.DockHandler.Pane);
if (value == m_activePane)
return;
m_activePane = value;
}
private static readonly object ActiveContentChangedEvent = new object();
public event EventHandler ActiveContentChanged
{
add { Events.AddHandler(ActiveContentChangedEvent, value); }
remove { Events.RemoveHandler(ActiveContentChangedEvent, value); }
}
protected virtual void OnActiveContentChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActiveContentChangedEvent];
if (handler != null)
handler(this, e);
}
private IDockContent m_activeContent = null;
public IDockContent ActiveContent
{
get { return m_activeContent; }
set
{
if (value == m_activeContent)
return;
if (value != null)
{
if (!DockHelper.IsDockStateAutoHide(value.DockHandler.DockState) || value.DockHandler.DockPanel != DockPanel)
throw (new InvalidOperationException(Strings.DockPanel_ActiveAutoHideContent_InvalidValue));
}
DockPanel.SuspendLayout();
if (m_activeContent != null)
{
if (m_activeContent.DockHandler.Form.ContainsFocus)
{
if (!Win32Helper.IsRunningOnMono)
{
DockPanel.ContentFocusManager.GiveUpFocus(m_activeContent);
}
}
AnimateWindow(false);
}
m_activeContent = value;
SetActivePane();
if (ActivePane != null)
ActivePane.ActiveContent = m_activeContent;
if (m_activeContent != null)
AnimateWindow(true);
DockPanel.ResumeLayout();
DockPanel.RefreshAutoHideStrip();
SetTimerMouseTrack();
OnActiveContentChanged(EventArgs.Empty);
}
}
public DockState DockState
{
get { return ActiveContent == null ? DockState.Unknown : ActiveContent.DockHandler.DockState; }
}
private bool m_flagAnimate = true;
private bool FlagAnimate
{
get { return m_flagAnimate; }
set { m_flagAnimate = value; }
}
private bool m_flagDragging = false;
internal bool FlagDragging
{
get { return m_flagDragging; }
set
{
if (m_flagDragging == value)
return;
m_flagDragging = value;
SetTimerMouseTrack();
}
}
private void AnimateWindow(bool show)
{
if (!FlagAnimate && Visible != show)
{
Visible = show;
return;
}
Parent.SuspendLayout();
Rectangle rectSource = GetRectangle(!show);
Rectangle rectTarget = GetRectangle(show);
int dxLoc, dyLoc;
int dWidth, dHeight;
dxLoc = dyLoc = dWidth = dHeight = 0;
if (DockState == DockState.DockTopAutoHide)
dHeight = show ? 1 : -1;
else if (DockState == DockState.DockLeftAutoHide)
dWidth = show ? 1 : -1;
else if (DockState == DockState.DockRightAutoHide)
{
dxLoc = show ? -1 : 1;
dWidth = show ? 1 : -1;
}
else if (DockState == DockState.DockBottomAutoHide)
{
dyLoc = (show ? -1 : 1);
dHeight = (show ? 1 : -1);
}
if (show)
{
Bounds = DockPanel.GetAutoHideWindowBounds(new Rectangle(-rectTarget.Width, -rectTarget.Height, rectTarget.Width, rectTarget.Height));
if (Visible == false)
Visible = true;
PerformLayout();
}
SuspendLayout();
LayoutAnimateWindow(rectSource);
if (Visible == false)
Visible = true;
int speedFactor = 1;
int totalPixels = (rectSource.Width != rectTarget.Width) ?
Math.Abs(rectSource.Width - rectTarget.Width) :
Math.Abs(rectSource.Height - rectTarget.Height);
int remainPixels = totalPixels;
DateTime startingTime = DateTime.Now;
while (rectSource != rectTarget)
{
DateTime startPerMove = DateTime.Now;
rectSource.X += dxLoc * speedFactor;
rectSource.Y += dyLoc * speedFactor;
rectSource.Width += dWidth * speedFactor;
rectSource.Height += dHeight * speedFactor;
if (Math.Sign(rectTarget.X - rectSource.X) != Math.Sign(dxLoc))
rectSource.X = rectTarget.X;
if (Math.Sign(rectTarget.Y - rectSource.Y) != Math.Sign(dyLoc))
rectSource.Y = rectTarget.Y;
if (Math.Sign(rectTarget.Width - rectSource.Width) != Math.Sign(dWidth))
rectSource.Width = rectTarget.Width;
if (Math.Sign(rectTarget.Height - rectSource.Height) != Math.Sign(dHeight))
rectSource.Height = rectTarget.Height;
LayoutAnimateWindow(rectSource);
if (Parent != null)
Parent.Update();
remainPixels -= speedFactor;
while (true)
{
TimeSpan time = new TimeSpan(0, 0, 0, 0, ANIMATE_TIME);
TimeSpan elapsedPerMove = DateTime.Now - startPerMove;
TimeSpan elapsedTime = DateTime.Now - startingTime;
if (((int)((time - elapsedTime).TotalMilliseconds)) <= 0)
{
speedFactor = remainPixels;
break;
}
else
speedFactor = remainPixels * (int)elapsedPerMove.TotalMilliseconds / (int)((time - elapsedTime).TotalMilliseconds);
if (speedFactor >= 1)
break;
}
}
ResumeLayout();
Parent.ResumeLayout();
}
private void LayoutAnimateWindow(Rectangle rect)
{
Bounds = DockPanel.GetAutoHideWindowBounds(rect);
Rectangle rectClient = ClientRectangle;
if (DockState == DockState.DockLeftAutoHide)
ActivePane.Location = new Point(rectClient.Right - 2 - Measures.SplitterSize - ActivePane.Width, ActivePane.Location.Y);
else if (DockState == DockState.DockTopAutoHide)
ActivePane.Location = new Point(ActivePane.Location.X, rectClient.Bottom - 2 - Measures.SplitterSize - ActivePane.Height);
}
private Rectangle GetRectangle(bool show)
{
if (DockState == DockState.Unknown)
return Rectangle.Empty;
Rectangle rect = DockPanel.AutoHideWindowRectangle;
if (show)
return rect;
if (DockState == DockState.DockLeftAutoHide)
rect.Width = 0;
else if (DockState == DockState.DockRightAutoHide)
{
rect.X += rect.Width;
rect.Width = 0;
}
else if (DockState == DockState.DockTopAutoHide)
rect.Height = 0;
else
{
rect.Y += rect.Height;
rect.Height = 0;
}
return rect;
}
private void SetTimerMouseTrack()
{
if (ActivePane == null || ActivePane.IsActivated || FlagDragging)
{
m_timerMouseTrack.Enabled = false;
return;
}
// start the timer
int hovertime = SystemInformation.MouseHoverTime ;
// assign a default value 400 in case of setting Timer.Interval invalid value exception
if (hovertime <= 0)
hovertime = 400;
m_timerMouseTrack.Interval = 2 * (int)hovertime;
m_timerMouseTrack.Enabled = true;
}
protected virtual Rectangle DisplayingRectangle
{
get
{
Rectangle rect = ClientRectangle;
// exclude the border and the splitter
if (DockState == DockState.DockBottomAutoHide)
{
rect.Y += 2 + Measures.SplitterSize;
rect.Height -= 2 + Measures.SplitterSize;
}
else if (DockState == DockState.DockRightAutoHide)
{
rect.X += 2 + Measures.SplitterSize;
rect.Width -= 2 + Measures.SplitterSize;
}
else if (DockState == DockState.DockTopAutoHide)
rect.Height -= 2 + Measures.SplitterSize;
else if (DockState == DockState.DockLeftAutoHide)
rect.Width -= 2 + Measures.SplitterSize;
return rect;
}
}
public void RefreshActiveContent()
{
if (ActiveContent == null)
return;
if (!DockHelper.IsDockStateAutoHide(ActiveContent.DockHandler.DockState))
{
FlagAnimate = false;
ActiveContent = null;
FlagAnimate = true;
}
}
public void RefreshActivePane()
{
SetTimerMouseTrack();
}
private void TimerMouseTrack_Tick(object sender, EventArgs e)
{
if (IsDisposed)
return;
if (ActivePane == null || ActivePane.IsActivated)
{
m_timerMouseTrack.Enabled = false;
return;
}
DockPane pane = ActivePane;
Point ptMouseInAutoHideWindow = PointToClient(Control.MousePosition);
Point ptMouseInDockPanel = DockPanel.PointToClient(Control.MousePosition);
Rectangle rectTabStrip = DockPanel.GetTabStripRectangle(pane.DockState);
if (!ClientRectangle.Contains(ptMouseInAutoHideWindow) && !rectTabStrip.Contains(ptMouseInDockPanel))
{
ActiveContent = null;
m_timerMouseTrack.Enabled = false;
}
}
#region ISplitterDragSource Members
void ISplitterDragSource.BeginDrag(Rectangle rectSplitter)
{
FlagDragging = true;
}
void ISplitterDragSource.EndDrag()
{
FlagDragging = false;
}
bool ISplitterDragSource.IsVertical
{
get { return (DockState == DockState.DockLeftAutoHide || DockState == DockState.DockRightAutoHide); }
}
Rectangle ISplitterDragSource.DragLimitBounds
{
get
{
Rectangle rectLimit = DockPanel.DockArea;
if ((this as ISplitterDragSource).IsVertical)
{
rectLimit.X += MeasurePane.MinSize;
rectLimit.Width -= 2 * MeasurePane.MinSize;
}
else
{
rectLimit.Y += MeasurePane.MinSize;
rectLimit.Height -= 2 * MeasurePane.MinSize;
}
return DockPanel.RectangleToScreen(rectLimit);
}
}
void ISplitterDragSource.MoveSplitter(int offset)
{
Rectangle rectDockArea = DockPanel.DockArea;
IDockContent content = ActiveContent;
if (DockState == DockState.DockLeftAutoHide && rectDockArea.Width > 0)
{
if (content.DockHandler.AutoHidePortion < 1)
content.DockHandler.AutoHidePortion += ((double)offset) / (double)rectDockArea.Width;
else
content.DockHandler.AutoHidePortion = Width + offset;
}
else if (DockState == DockState.DockRightAutoHide && rectDockArea.Width > 0)
{
if (content.DockHandler.AutoHidePortion < 1)
content.DockHandler.AutoHidePortion -= ((double)offset) / (double)rectDockArea.Width;
else
content.DockHandler.AutoHidePortion = Width - offset;
}
else if (DockState == DockState.DockBottomAutoHide && rectDockArea.Height > 0)
{
if (content.DockHandler.AutoHidePortion < 1)
content.DockHandler.AutoHidePortion -= ((double)offset) / (double)rectDockArea.Height;
else
content.DockHandler.AutoHidePortion = Height - offset;
}
else if (DockState == DockState.DockTopAutoHide && rectDockArea.Height > 0)
{
if (content.DockHandler.AutoHidePortion < 1)
content.DockHandler.AutoHidePortion += ((double)offset) / (double)rectDockArea.Height;
else
content.DockHandler.AutoHidePortion = Height + offset;
}
}
#region IDragSource Members
Control IDragSource.DragControl
{
get { return this; }
}
#endregion
#endregion
}
private AutoHideWindowControl AutoHideWindow
{
get { return m_autoHideWindow; }
}
internal Control AutoHideControl
{
get { return m_autoHideWindow; }
}
internal void RefreshActiveAutoHideContent()
{
AutoHideWindow.RefreshActiveContent();
}
internal Rectangle AutoHideWindowRectangle
{
get
{
DockState state = AutoHideWindow.DockState;
Rectangle rectDockArea = DockArea;
if (ActiveAutoHideContent == null)
return Rectangle.Empty;
if (Parent == null)
return Rectangle.Empty;
Rectangle rect = Rectangle.Empty;
double autoHideSize = ActiveAutoHideContent.DockHandler.AutoHidePortion;
if (state == DockState.DockLeftAutoHide)
{
if (autoHideSize < 1)
autoHideSize = rectDockArea.Width * autoHideSize;
if (autoHideSize > rectDockArea.Width - MeasurePane.MinSize)
autoHideSize = rectDockArea.Width - MeasurePane.MinSize;
rect.X = rectDockArea.X;
rect.Y = rectDockArea.Y;
rect.Width = (int)autoHideSize;
rect.Height = rectDockArea.Height;
}
else if (state == DockState.DockRightAutoHide)
{
if (autoHideSize < 1)
autoHideSize = rectDockArea.Width * autoHideSize;
if (autoHideSize > rectDockArea.Width - MeasurePane.MinSize)
autoHideSize = rectDockArea.Width - MeasurePane.MinSize;
rect.X = rectDockArea.X + rectDockArea.Width - (int)autoHideSize;
rect.Y = rectDockArea.Y;
rect.Width = (int)autoHideSize;
rect.Height = rectDockArea.Height;
}
else if (state == DockState.DockTopAutoHide)
{
if (autoHideSize < 1)
autoHideSize = rectDockArea.Height * autoHideSize;
if (autoHideSize > rectDockArea.Height - MeasurePane.MinSize)
autoHideSize = rectDockArea.Height - MeasurePane.MinSize;
rect.X = rectDockArea.X;
rect.Y = rectDockArea.Y;
rect.Width = rectDockArea.Width;
rect.Height = (int)autoHideSize;
}
else if (state == DockState.DockBottomAutoHide)
{
if (autoHideSize < 1)
autoHideSize = rectDockArea.Height * autoHideSize;
if (autoHideSize > rectDockArea.Height - MeasurePane.MinSize)
autoHideSize = rectDockArea.Height - MeasurePane.MinSize;
rect.X = rectDockArea.X;
rect.Y = rectDockArea.Y + rectDockArea.Height - (int)autoHideSize;
rect.Width = rectDockArea.Width;
rect.Height = (int)autoHideSize;
}
return rect;
}
}
internal Rectangle GetAutoHideWindowBounds(Rectangle rectAutoHideWindow)
{
if (DocumentStyle == DocumentStyle.SystemMdi ||
DocumentStyle == DocumentStyle.DockingMdi)
return (Parent == null) ? Rectangle.Empty : Parent.RectangleToClient(RectangleToScreen(rectAutoHideWindow));
else
return rectAutoHideWindow;
}
internal void RefreshAutoHideStrip()
{
AutoHideStripControl.RefreshChanges();
}
}
}
| |
// 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.Diagnostics;
using Internal.TypeSystem;
using ILCompiler;
using ILCompiler.DependencyAnalysis.ARM;
namespace ILCompiler.DependencyAnalysis
{
/// <summary>
/// ARM specific portions of ReadyToRunHelperNode
/// </summary>
partial class ReadyToRunHelperNode
{
protected override void EmitCode(NodeFactory factory, ref ARMEmitter encoder, bool relocsOnly)
{
switch (Id)
{
case ReadyToRunHelperId.VirtualCall:
{
MethodDesc targetMethod = (MethodDesc)Target;
Debug.Assert(!targetMethod.OwningType.IsInterface);
Debug.Assert(!targetMethod.CanMethodBeInSealedVTable());
int pointerSize = factory.Target.PointerSize;
int slot = 0;
if (!relocsOnly)
{
slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod, targetMethod.OwningType);
Debug.Assert(slot != -1);
}
encoder.EmitLDR(encoder.TargetRegister.InterproceduralScratch, encoder.TargetRegister.Arg0, 0);
encoder.EmitLDR(encoder.TargetRegister.InterproceduralScratch, encoder.TargetRegister.InterproceduralScratch,
EETypeNode.GetVTableOffset(pointerSize) + (slot * pointerSize));
encoder.EmitJMP(encoder.TargetRegister.InterproceduralScratch);
}
break;
case ReadyToRunHelperId.GetNonGCStaticBase:
{
MetadataType target = (MetadataType)Target;
bool hasLazyStaticConstructor = factory.TypeSystemContext.HasLazyStaticConstructor(target);
encoder.EmitMOV(encoder.TargetRegister.Result, factory.TypeNonGCStaticsSymbol(target));
if (!hasLazyStaticConstructor)
{
encoder.EmitRET();
}
else
{
// We need to trigger the cctor before returning the base. It is stored at the beginning of the non-GC statics region.
encoder.EmitMOV(encoder.TargetRegister.Arg2, factory.TypeNonGCStaticsSymbol(target));
encoder.EmitLDR(encoder.TargetRegister.Arg3, encoder.TargetRegister.Arg2,
((short)(factory.Target.PointerSize - NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target))));
encoder.EmitCMP(encoder.TargetRegister.Arg3, 1);
encoder.EmitRETIfEqual();
encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Result);
encoder.EmitMOV(encoder.TargetRegister.Arg0/*Result*/, encoder.TargetRegister.Arg2);
encoder.EmitSUB(encoder.TargetRegister.Arg0, NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target));
encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnNonGCStaticBase));
}
}
break;
case ReadyToRunHelperId.GetThreadStaticBase:
{
MetadataType target = (MetadataType)Target;
encoder.EmitMOV(encoder.TargetRegister.Arg2, factory.TypeThreadStaticIndex(target));
// First arg: address of the TypeManager slot that provides the helper with
// information about module index and the type manager instance (which is used
// for initialization on first access).
encoder.EmitLDR(encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg2);
// Second arg: index of the type in the ThreadStatic section of the modules
encoder.EmitLDR(encoder.TargetRegister.Arg1, encoder.TargetRegister.Arg2, factory.Target.PointerSize);
if (!factory.TypeSystemContext.HasLazyStaticConstructor(target))
{
encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.GetThreadStaticBaseForType));
}
else
{
encoder.EmitMOV(encoder.TargetRegister.Arg2, factory.TypeNonGCStaticsSymbol(target));
encoder.EmitSUB(encoder.TargetRegister.Arg2, NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target));
// TODO: performance optimization - inline the check verifying whether we need to trigger the cctor
encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnThreadStaticBase));
}
}
break;
case ReadyToRunHelperId.GetGCStaticBase:
{
MetadataType target = (MetadataType)Target;
encoder.EmitMOV(encoder.TargetRegister.Result, factory.TypeGCStaticsSymbol(target));
encoder.EmitLDR(encoder.TargetRegister.Result, encoder.TargetRegister.Result);
encoder.EmitLDR(encoder.TargetRegister.Result, encoder.TargetRegister.Result);
if (!factory.TypeSystemContext.HasLazyStaticConstructor(target))
{
encoder.EmitRET();
}
else
{
// We need to trigger the cctor before returning the base. It is stored at the beginning of the non-GC statics region.
encoder.EmitMOV(encoder.TargetRegister.Arg2, factory.TypeNonGCStaticsSymbol(target));
encoder.EmitLDR(encoder.TargetRegister.Arg3, encoder.TargetRegister.Arg2,
((short)(factory.Target.PointerSize - NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target))));
encoder.EmitCMP(encoder.TargetRegister.Arg3, 1);
encoder.EmitRETIfEqual();
encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Result);
encoder.EmitMOV(encoder.TargetRegister.Arg0/*Result*/, encoder.TargetRegister.Arg2);
encoder.EmitSUB(encoder.TargetRegister.Arg0, NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target));
encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnGCStaticBase));
}
}
break;
case ReadyToRunHelperId.DelegateCtor:
{
DelegateCreationInfo target = (DelegateCreationInfo)Target;
if (target.TargetNeedsVTableLookup)
{
Debug.Assert(!target.TargetMethod.CanMethodBeInSealedVTable());
encoder.EmitLDR(encoder.TargetRegister.Arg2, encoder.TargetRegister.Arg1);
int slot = 0;
if (!relocsOnly)
slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, target.TargetMethod, target.TargetMethod.OwningType);
Debug.Assert(slot != -1);
encoder.EmitLDR(encoder.TargetRegister.Arg2, encoder.TargetRegister.Arg2,
EETypeNode.GetVTableOffset(factory.Target.PointerSize) + (slot * factory.Target.PointerSize));
}
else
{
ISymbolNode targetMethodNode = target.GetTargetNode(factory);
encoder.EmitMOV(encoder.TargetRegister.Arg2, target.GetTargetNode(factory));
}
if (target.Thunk != null)
{
Debug.Assert(target.Constructor.Method.Signature.Length == 3);
encoder.EmitMOV(encoder.TargetRegister.Arg3, target.Thunk);
}
else
{
Debug.Assert(target.Constructor.Method.Signature.Length == 2);
}
encoder.EmitJMP(target.Constructor);
}
break;
case ReadyToRunHelperId.ResolveVirtualFunction:
{
ARMDebug.EmitHelperNYIAssert(factory, ref encoder, ReadyToRunHelperId.ResolveVirtualFunction);
/*
***
NOT TESTED!!!
***
MethodDesc targetMethod = (MethodDesc)Target;
if (targetMethod.OwningType.IsInterface)
{
encoder.EmitMOV(encoder.TargetRegister.Arg1, factory.InterfaceDispatchCell(targetMethod));
encoder.EmitJMP(factory.ExternSymbol("RhpResolveInterfaceMethod"));
}
else
{
if (relocsOnly)
break;
encoder.EmitLDR(encoder.TargetRegister.Result, encoder.TargetRegister.Arg0);
Debug.Assert(!targetMethod.CanMethodBeInSealedVTable());
int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod, targetMethod.OwningType);
Debug.Assert(slot != -1);
encoder.EmitLDR(encoder.TargetRegister.Result, encoder.TargetRegister.Result,
((short)(EETypeNode.GetVTableOffset(factory.Target.PointerSize) + (slot * factory.Target.PointerSize))));
encoder.EmitRET();
}
*/
}
break;
default:
throw new NotImplementedException();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested01.nested01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested01.nested01;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i)
{
if (i == 18)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1()
{
order1 = order1 + 1;
return order1;
}
public static int Bar2(int i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(int j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(i: Bar3(Bar2(Bar1())));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested01a.nested01a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested01a.nested01a;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i)
{
if (i == 18)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static dynamic Bar1()
{
order1 = order1 + 1;
return order1;
}
public static int Bar2(dynamic i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(int j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: Bar3(Bar2(Bar1())));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested01b.nested01b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested01b.nested01b;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i)
{
if (i == 18)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static dynamic Bar1()
{
order1 = order1 + 1;
return order1;
}
public static dynamic Bar2(dynamic i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(dynamic j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(i: Bar3(Bar2(Bar1())));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested02.nested02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested02.nested02;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i)
{
if (i == 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1(int k)
{
order1 = order1 + 1;
return order1;
}
public static int Bar2(int i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(int j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(i: Bar3(Bar1(Bar2(0))));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested02a.nested02a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested02a.nested02a;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(dynamic i)
{
if (i == 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1(int k)
{
order1 = order1 + 1;
return order1;
}
public static int Bar2(dynamic i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(dynamic j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: Bar3(Bar1(Bar2(0))));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested02b.nested02b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested02b.nested02b;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(dynamic i)
{
if (i == 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1(dynamic k)
{
order1 = order1 + 1;
return order1;
}
public static dynamic Bar2(dynamic i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(int j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(i: Bar3(Bar1(Bar2(0))));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested03.nested03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested03.nested03;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i)
{
if (i == 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1(int k)
{
order1 = order1 + 1;
return order1;
}
public static int Bar2(int i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(int j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(i: Bar3(j: Bar1(k: Bar2(i: 0))));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested03a.nested03a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested03a.nested03a;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(dynamic i)
{
if (i == 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1(dynamic k)
{
order1 = order1 + 1;
return order1;
}
public static int Bar2(dynamic i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(dynamic j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: Bar3(j: Bar1(k: Bar2(i: 0))));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested03b.nested03b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested03b.nested03b;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(dynamic i)
{
if (i == 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1(dynamic k)
{
order1 = order1 + 1;
return order1;
}
public static int Bar2(dynamic i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(dynamic j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(i: Bar3(j: Bar1(k: Bar2(i: 0))));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested03c.nested03c
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested03c.nested03c;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i)
{
if (i == 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1(int k)
{
order1 = order1 + 1;
return order1;
}
public static int Bar2(dynamic i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(int j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
dynamic i = 0;
return p.Foo(i: Bar3(j: Bar1(k: Bar2(i: i))));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested05.nested05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested05.nested05;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i)
{
if (i == 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1(int k)
{
order1 = order1 + 1;
return order1;
}
public static int Bar2(int i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(int j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(i: Bar3(j: Bar1(Bar2(i: 0))));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested05a.nested05a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested05a.nested05a;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public dynamic Foo(int i)
{
if (i == 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1(dynamic k)
{
order1 = order1 + 1;
return order1;
}
public static int Bar2(int i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(int j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: Bar3(j: Bar1(Bar2(i: 0))));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested05b.nested05b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested05b.nested05b;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public dynamic Foo(int i)
{
if (i == 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1(dynamic k)
{
order1 = order1 + 1;
return order1;
}
public static int Bar2(int i)
{
order1 = order1 * 4;
return order1;
}
public static int Bar3(int j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(i: Bar3(j: Bar1(Bar2(i: 0))));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested05c.nested05c
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.nested05c.nested05c;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic nesting of functions</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public dynamic Foo(dynamic i)
{
if (i == 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static dynamic Bar1(dynamic k)
{
order1 = order1 + 1;
return order1;
}
public static dynamic Bar2(dynamic i)
{
order1 = order1 * 4;
return order1;
}
public static dynamic Bar3(dynamic j)
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
dynamic i = 0;
return p.Foo(i: Bar3(j: Bar1(Bar2(i: i))));
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order01.order01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order01.order01;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i, int j, int k)
{
if (i + j + k == 28)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1()
{
order1 = order1 + 1;
return order1;
}
public static int Bar2()
{
order1 = order1 * 4;
return order1;
}
public static int Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(i: Bar1(), j: Bar2(), k: Bar3());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order01a.order01a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order01a.order01a;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i, int j, int k)
{
if (i + j + k == 28)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static dynamic Bar1()
{
order1 = order1 + 1;
return order1;
}
public static int Bar2()
{
order1 = order1 * 4;
return order1;
}
public static int Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: Bar1(), j: Bar2(), k: Bar3());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order01b.order01b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order01b.order01b;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i, int j, int k)
{
if (i + j + k == 28)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static dynamic Bar1()
{
order1 = order1 + 1;
return order1;
}
public static int Bar2()
{
order1 = order1 * 4;
return order1;
}
public static int Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(i: Bar1(), j: Bar2(), k: Bar3());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order02.order02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order02.order02;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i, int j, int k)
{
if (i + j + k == 33)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1()
{
order1 = order1 + 1;
return order1;
}
public static int Bar2()
{
order1 = order1 * 4;
return order1;
}
public static int Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(j: Bar2(), k: Bar3(), i: Bar1());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order02a.order02a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order02a.order02a;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i, int j, dynamic k)
{
if (i + j + k == 33)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1()
{
order1 = order1 + 1;
return order1;
}
public static dynamic Bar2()
{
order1 = order1 * 4;
return order1;
}
public static int Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(j: Bar2(), k: Bar3(), i: Bar1());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order02b.order02b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order02b.order02b;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i, int j, dynamic k)
{
if (i + j + k == 33)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1()
{
order1 = order1 + 1;
return order1;
}
public static dynamic Bar2()
{
order1 = order1 * 4;
return order1;
}
public static int Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(j: Bar2(), k: Bar3(), i: Bar1());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order03.order03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order03.order03;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i, int j, int k)
{
if (i + j + k == 11 + 12 + 48)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1()
{
order1 = order1 + 1;
return order1;
}
public static int Bar2()
{
order1 = order1 * 4;
return order1;
}
public static int Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(k: Bar3(), i: Bar1(), j: Bar2());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order03a.order03a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order03a.order03a;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(dynamic i, int j, int k)
{
if (i + j + k == 11 + 12 + 48)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1()
{
order1 = order1 + 1;
return order1;
}
public static int Bar2()
{
order1 = order1 * 4;
return order1;
}
public static dynamic Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(k: Bar3(), i: Bar1(), j: Bar2());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order03b.order03b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order03b.order03b;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(dynamic i, int j, int k)
{
if (i + j + k == 11 + 12 + 48)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1()
{
order1 = order1 + 1;
return order1;
}
public static int Bar2()
{
order1 = order1 * 4;
return order1;
}
public static dynamic Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(k: Bar3(), i: Bar1(), j: Bar2());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order04.order04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order04.order04;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i, int j, int k)
{
if (i + j + k == 100)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1()
{
order1 = order1 + 1;
return order1;
}
public static int Bar2()
{
order1 = order1 * 4;
return order1;
}
public static int Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(k: Bar3(), j: Bar2(), i: Bar1());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order04a.order04a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order04a.order04a;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i, dynamic j, int k)
{
if (i + j + k == 100)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static dynamic Bar1()
{
order1 = order1 + 1;
return order1;
}
public static dynamic Bar2()
{
order1 = order1 * 4;
return order1;
}
public static dynamic Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(k: Bar3(), j: Bar2(), i: Bar1());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order04b.order04b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order04b.order04b;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i, dynamic j, int k)
{
if (i + j + k == 100)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static dynamic Bar1()
{
order1 = order1 + 1;
return order1;
}
public static dynamic Bar2()
{
order1 = order1 * 4;
return order1;
}
public static dynamic Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(k: Bar3(), j: Bar2(), i: Bar1());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order05.order05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order05.order05;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(int i, int j, int k)
{
if (i + j + k == 18 + 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static int Bar1()
{
order1 = order1 + 1;
return order1;
}
public static int Bar2()
{
order1 = order1 * 4;
return order1;
}
public static int Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(j: Bar2(), k: Bar3(), i: Bar1());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order05a.order05a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order05a.order05a;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(dynamic i, dynamic j, dynamic k)
{
if (i + j + k == 18 + 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static dynamic Bar1()
{
order1 = order1 + 1;
return order1;
}
public static dynamic Bar2()
{
order1 = order1 * 4;
return order1;
}
public static dynamic Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(j: Bar2(), k: Bar3(), i: Bar1());
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order05b.order05b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.usage.executeOrder.order05b.order05b;
// <Area> of Methods with Optional Parameters and named arguments</Area>
// <Title>Ensuring execution order is correct</Title>
// <Description>Basic Execution order</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public int Foo(dynamic i, dynamic j, dynamic k)
{
if (i + j + k == 18 + 15)
return 0;
return 1;
}
}
public class Test
{
public static int order1 = 1;
public static dynamic Bar1()
{
order1 = order1 + 1;
return order1;
}
public static dynamic Bar2()
{
order1 = order1 * 4;
return order1;
}
public static dynamic Bar3()
{
order1 = order1 + 10;
return order1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(j: Bar2(), k: Bar3(), i: Bar1());
}
}
//</Code>
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.OpenXmlFormats.Spreadsheet;
using System;
using NPOI.XSSF.Model;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using NPOI.SS.UserModel;
using System.Collections.Generic;
using NPOI.Util;
using NPOI.SS;
using System.Collections;
using NPOI.XSSF.UserModel.Helpers;
using NPOI.SS.Formula;
using System.Linq;
namespace NPOI.XSSF.UserModel
{
/**
* High level representation of a row of a spreadsheet.
*/
public class XSSFRow : IRow, IComparable<XSSFRow>
{
private static POILogger _logger = POILogFactory.GetLogger(typeof(XSSFRow));
/**
* the xml bean Containing all cell defInitions for this row
*/
private CT_Row _row;
/**
* Cells of this row keyed by their column indexes.
* The TreeMap ensures that the cells are ordered by columnIndex in the ascending order.
*/
private SortedDictionary<int, ICell> _cells;
/**
* the parent sheet
*/
private XSSFSheet _sheet;
/**
* Construct a XSSFRow.
*
* @param row the xml bean Containing all cell defInitions for this row.
* @param sheet the parent sheet.
*/
public XSSFRow(CT_Row row, XSSFSheet sheet)
{
this._row = row;
this._sheet = sheet;
this._cells = new SortedDictionary<int, ICell>();
if (0 < row.SizeOfCArray())
{
foreach (CT_Cell c in row.c)
{
XSSFCell cell = new XSSFCell(this, c);
_cells.Add(cell.ColumnIndex,cell);
sheet.OnReadCell(cell);
}
}
if (!row.IsSetR())
{
// Certain file format writers skip the row number
// Assume no gaps, and give this the next row number
int nextRowNum = sheet.LastRowNum + 2;
if (nextRowNum == 2 && sheet.PhysicalNumberOfRows == 0)
{
nextRowNum = 1;
}
row.r = (uint)nextRowNum;
}
}
/**
* Returns the XSSFSheet this row belongs to
*
* @return the XSSFSheet that owns this row
*/
public ISheet Sheet
{
get
{
return this._sheet;
}
}
/**
* Cell iterator over the physically defined cells:
* <blockquote><pre>
* for (Iterator<Cell> it = row.cellIterator(); it.HasNext(); ) {
* Cell cell = it.next();
* ...
* }
* </pre></blockquote>
*
* @return an iterator over cells in this row.
*/
public SortedDictionary<int, ICell>.ValueCollection.Enumerator CellIterator()
{
return _cells.Values.GetEnumerator();
}
/**
* Alias for {@link #cellIterator()} to allow foreach loops:
* <blockquote><pre>
* for(Cell cell : row){
* ...
* }
* </pre></blockquote>
*
* @return an iterator over cells in this row.
*/
public IEnumerator<ICell> GetEnumerator()
{
return CellIterator();
}
/**
* Compares two <code>XSSFRow</code> objects. Two rows are equal if they belong to the same worksheet and
* their row indexes are equal.
*
* @param row the <code>XSSFRow</code> to be compared.
* @return <ul>
* <li>
* the value <code>0</code> if the row number of this <code>XSSFRow</code> is
* equal to the row number of the argument <code>XSSFRow</code>
* </li>
* <li>
* a value less than <code>0</code> if the row number of this this <code>XSSFRow</code> is
* numerically less than the row number of the argument <code>XSSFRow</code>
* </li>
* <li>
* a value greater than <code>0</code> if the row number of this this <code>XSSFRow</code> is
* numerically greater than the row number of the argument <code>XSSFRow</code>
* </li>
* </ul>
* @throws IllegalArgumentException if the argument row belongs to a different worksheet
*/
public int CompareTo(XSSFRow other)
{
if (this.Sheet != other.Sheet)
{
throw new ArgumentException("The compared rows must belong to the same sheet");
}
return RowNum.CompareTo(other.RowNum);
}
public override bool Equals(Object obj)
{
if (!(obj is XSSFRow))
{
return false;
}
XSSFRow other = (XSSFRow)obj;
return (this.RowNum == other.RowNum) &&
(this.Sheet == other.Sheet);
}
public override int GetHashCode()
{
return _row.GetHashCode();
}
/**
* Use this to create new cells within the row and return it.
* <p>
* The cell that is returned is a {@link Cell#CELL_TYPE_BLANK}. The type can be Changed
* either through calling <code>SetCellValue</code> or <code>SetCellType</code>.
* </p>
* @param columnIndex - the column number this cell represents
* @return Cell a high level representation of the Created cell.
* @throws ArgumentException if columnIndex < 0 or greater than 16384,
* the maximum number of columns supported by the SpreadsheetML format (.xlsx)
*/
public ICell CreateCell(int columnIndex)
{
return CreateCell(columnIndex, CellType.Blank);
}
/**
* Use this to create new cells within the row and return it.
*
* @param columnIndex - the column number this cell represents
* @param type - the cell's data type
* @return XSSFCell a high level representation of the Created cell.
* @throws ArgumentException if the specified cell type is invalid, columnIndex < 0
* or greater than 16384, the maximum number of columns supported by the SpreadsheetML format (.xlsx)
* @see Cell#CELL_TYPE_BLANK
* @see Cell#CELL_TYPE_BOOLEAN
* @see Cell#CELL_TYPE_ERROR
* @see Cell#CELL_TYPE_FORMULA
* @see Cell#CELL_TYPE_NUMERIC
* @see Cell#CELL_TYPE_STRING
*/
public ICell CreateCell(int columnIndex, CellType type)
{
CT_Cell ctCell;
XSSFCell prev = _cells.ContainsKey(columnIndex) ? (XSSFCell)_cells[columnIndex] : null;
if (prev != null)
{
ctCell = prev.GetCTCell();
ctCell.Set(new CT_Cell());
}
else
{
ctCell = _row.AddNewC();
}
XSSFCell xcell = new XSSFCell(this, ctCell);
xcell.SetCellNum(columnIndex);
if (type != CellType.Blank)
{
xcell.SetCellType(type);
}
_cells[columnIndex] = xcell;
return xcell;
}
/**
* Returns the cell at the given (0 based) index,
* with the {@link NPOI.SS.usermodel.Row.MissingCellPolicy} from the parent Workbook.
*
* @return the cell at the given (0 based) index
*/
public ICell GetCell(int cellnum)
{
return GetCell(cellnum, _sheet.Workbook.MissingCellPolicy);
}
/// <summary>
/// Get the hssfcell representing a given column (logical cell)
/// 0-based. If you ask for a cell that is not defined, then
/// you Get a null.
/// This is the basic call, with no policies applied
/// </summary>
/// <param name="cellnum">0 based column number</param>
/// <returns>Cell representing that column or null if Undefined.</returns>
private ICell RetrieveCell(int cellnum)
{
if (!_cells.ContainsKey(cellnum))
return null;
//if (cellnum < 0 || cellnum >= cells.Count) return null;
return _cells[cellnum];
}
/**
* Returns the cell at the given (0 based) index, with the specified {@link NPOI.SS.usermodel.Row.MissingCellPolicy}
*
* @return the cell at the given (0 based) index
* @throws ArgumentException if cellnum < 0 or the specified MissingCellPolicy is invalid
* @see Row#RETURN_NULL_AND_BLANK
* @see Row#RETURN_BLANK_AS_NULL
* @see Row#CREATE_NULL_AS_BLANK
*/
public ICell GetCell(int cellnum, MissingCellPolicy policy)
{
if (cellnum < 0) throw new ArgumentException("Cell index must be >= 0");
XSSFCell cell = (XSSFCell)RetrieveCell(cellnum);
switch (policy)
{
case MissingCellPolicy.RETURN_NULL_AND_BLANK:
return cell;
case MissingCellPolicy.RETURN_BLANK_AS_NULL:
bool isBlank = (cell != null && cell.CellType == CellType.Blank);
return (isBlank) ? null : cell;
case MissingCellPolicy.CREATE_NULL_AS_BLANK:
return (cell == null) ? CreateCell(cellnum, CellType.Blank) : cell;
default:
throw new ArgumentException("Illegal policy " + policy + " (" + policy + ")");
}
}
int GetFirstKey()
{
return _cells.Keys.Min();
}
int GetLastKey()
{
return _cells.Keys.Max();
}
/**
* Get the number of the first cell Contained in this row.
*
* @return short representing the first logical cell in the row,
* or -1 if the row does not contain any cells.
*/
public short FirstCellNum
{
get
{
return (short)(_cells.Count == 0 ? -1 : GetFirstKey());
}
}
/**
* Gets the index of the last cell Contained in this row <b>PLUS ONE</b>. The result also
* happens to be the 1-based column number of the last cell. This value can be used as a
* standard upper bound when iterating over cells:
* <pre>
* short minColIx = row.GetFirstCellNum();
* short maxColIx = row.GetLastCellNum();
* for(short colIx=minColIx; colIx<maxColIx; colIx++) {
* XSSFCell cell = row.GetCell(colIx);
* if(cell == null) {
* continue;
* }
* //... do something with cell
* }
* </pre>
*
* @return short representing the last logical cell in the row <b>PLUS ONE</b>,
* or -1 if the row does not contain any cells.
*/
public short LastCellNum
{
get
{
return (short)(_cells.Count == 0 ? -1 : (GetLastKey() + 1));
}
}
/**
* Get the row's height measured in twips (1/20th of a point). If the height is not Set, the default worksheet value is returned,
* See {@link NPOI.XSSF.usermodel.XSSFSheet#GetDefaultRowHeightInPoints()}
*
* @return row height measured in twips (1/20th of a point)
*/
public short Height
{
get
{
return (short)(HeightInPoints * 20);
}
set
{
if (value < 0)
{
if (_row.IsSetHt()) _row.UnsetHt();
if (_row.IsSetCustomHeight()) _row.UnsetCustomHeight();
}
else
{
_row.ht = ((double)value / 20);
_row.customHeight = (true);
}
}
}
/**
* Returns row height measured in point size. If the height is not Set, the default worksheet value is returned,
* See {@link NPOI.XSSF.usermodel.XSSFSheet#GetDefaultRowHeightInPoints()}
*
* @return row height measured in point size
* @see NPOI.XSSF.usermodel.XSSFSheet#GetDefaultRowHeightInPoints()
*/
public float HeightInPoints
{
get
{
if (this._row.IsSetHt())
{
return (float)this._row.ht;
}
return _sheet.DefaultRowHeightInPoints;
}
set
{
this.Height = (short)(value == -1 ? -1 : (value * 20));
}
}
/**
* Gets the number of defined cells (NOT number of cells in the actual row!).
* That is to say if only columns 0,4,5 have values then there would be 3.
*
* @return int representing the number of defined cells in the row.
*/
public int PhysicalNumberOfCells
{
get
{
return _cells.Count;
}
}
/**
* Get row number this row represents
*
* @return the row number (0 based)
*/
public int RowNum
{
get
{
return (int)_row.r-1;
}
set
{
int maxrow = SpreadsheetVersion.EXCEL2007.LastRowIndex;
if (value < 0 || value > maxrow)
{
throw new ArgumentException("Invalid row number (" + value
+ ") outside allowable range (0.." + maxrow + ")");
}
_row.r = (uint)(value+1);
}
}
/**
* Get whether or not to display this row with 0 height
*
* @return - height is zero or not.
*/
public bool ZeroHeight
{
get
{
return (bool)this._row.hidden;
}
set
{
this._row.hidden = value;
}
}
/**
* Is this row formatted? Most aren't, but some rows
* do have whole-row styles. For those that do, you
* can get the formatting from {@link #GetRowStyle()}
*/
public bool IsFormatted
{
get
{
return _row.IsSetS();
}
}
/**
* Returns the whole-row cell style. Most rows won't
* have one of these, so will return null. Call
* {@link #isFormatted()} to check first.
*/
public ICellStyle RowStyle
{
get
{
if (!IsFormatted) return null;
StylesTable stylesSource = ((XSSFWorkbook)Sheet.Workbook).GetStylesSource();
if (stylesSource.NumCellStyles > 0)
{
return stylesSource.GetStyleAt((int)_row.s);
}
else
{
return null;
}
}
set
{
if (value == null)
{
if (_row.IsSetS())
{
_row.UnsetS();
_row.UnsetCustomFormat();
}
}
else
{
StylesTable styleSource = ((XSSFWorkbook)Sheet.Workbook).GetStylesSource();
XSSFCellStyle xStyle = (XSSFCellStyle)value;
xStyle.VerifyBelongsToStylesSource(styleSource);
long idx = styleSource.PutStyle(xStyle);
_row.s = (uint)idx;
_row.customFormat = (true);
}
}
}
/**
* Applies a whole-row cell styling to the row.
* If the value is null then the style information is Removed,
* causing the cell to used the default workbook style.
*/
public void SetRowStyle(ICellStyle style)
{
}
/**
* Remove the Cell from this row.
*
* @param cell the cell to remove
*/
public void RemoveCell(ICell cell)
{
if (cell.Row != this)
{
throw new ArgumentException("Specified cell does not belong to this row");
}
XSSFCell xcell = (XSSFCell)cell;
if (xcell.IsPartOfArrayFormulaGroup)
{
xcell.NotifyArrayFormulaChanging();
}
if (cell.CellType == CellType.Formula)
{
((XSSFWorkbook)_sheet.Workbook).OnDeleteFormula(xcell);
}
_cells.Remove(cell.ColumnIndex);
}
/**
* Returns the underlying CT_Row xml bean Containing all cell defInitions in this row
*
* @return the underlying CT_Row xml bean
*/
public CT_Row GetCTRow()
{
return _row;
}
/**
* Fired when the document is written to an output stream.
*
* @see NPOI.XSSF.usermodel.XSSFSheet#Write(java.io.OutputStream) ()
*/
internal void OnDocumentWrite()
{
// check if cells in the CT_Row are ordered
bool isOrdered = true;
if (_row.SizeOfCArray() != _cells.Count) isOrdered = false;
else
{
int i = 0;
foreach (XSSFCell cell in _cells.Values)
{
CT_Cell c1 = cell.GetCTCell();
CT_Cell c2 = _row.GetCArray(i++);
String r1 = c1.r;
String r2 = c2.r;
if (!(r1 == null ? r2 == null : r1.Equals(r2)))
{
isOrdered = false;
break;
}
}
}
if (!isOrdered)
{
CT_Cell[] cArray = new CT_Cell[_cells.Count];
int i = 0;
foreach (XSSFCell c in _cells.Values)
{
cArray[i++] = c.GetCTCell();
}
_row.SetCArray(cArray);
}
}
/**
* @return formatted xml representation of this row
*/
public override String ToString()
{
return _row.ToString();
}
/**
* update cell references when Shifting rows
*
* @param n the number of rows to move
*/
internal void Shift(int n)
{
int rownum = RowNum + n;
CalculationChain calcChain = ((XSSFWorkbook)_sheet.Workbook).GetCalculationChain();
int sheetId = (int)_sheet.sheet.sheetId;
String msg = "Row[rownum=" + RowNum + "] contains cell(s) included in a multi-cell array formula. " +
"You cannot change part of an array.";
foreach (ICell c in this)
{
XSSFCell cell = (XSSFCell)c;
if (cell.IsPartOfArrayFormulaGroup)
{
cell.NotifyArrayFormulaChanging(msg);
}
//remove the reference in the calculation chain
if (calcChain != null)
calcChain.RemoveItem(sheetId, cell.GetReference());
CT_Cell CT_Cell = cell.GetCTCell();
String r = new CellReference(rownum, cell.ColumnIndex).FormatAsString();
CT_Cell.r = r;
}
RowNum = rownum;
}
/**
* Copy the cells from srcRow to this row
* If this row is not a blank row, this will merge the two rows, overwriting
* the cells in this row with the cells in srcRow
* If srcRow is null, overwrite cells in destination row with blank values, styles, etc per cell copy policy
* srcRow may be from a different sheet in the same workbook
* @param srcRow the rows to copy from
* @param policy the policy to determine what gets copied
*/
public void CopyRowFrom(IRow srcRow, CellCopyPolicy policy)
{
if (srcRow == null)
{
// srcRow is blank. Overwrite cells with blank values, blank styles, etc per cell copy policy
foreach (ICell destCell in this)
{
XSSFCell srcCell = null;
// FIXME: remove type casting when copyCellFrom(Cell, CellCopyPolicy) is added to Cell interface
((XSSFCell)destCell).CopyCellFrom(srcCell, policy);
}
if (policy.IsCopyMergedRegions)
{
// Remove MergedRegions in dest row
int destRowNum = RowNum;
int index = 0;
HashSet<int> indices = new HashSet<int>();
foreach (CellRangeAddress destRegion in Sheet.MergedRegions)
{
if (destRowNum == destRegion.FirstRow && destRowNum == destRegion.LastRow)
{
indices.Add(index);
}
index++;
}
(Sheet as XSSFSheet).RemoveMergedRegions(indices.ToList());
}
if (policy.IsCopyRowHeight)
{
// clear row height
Height = ((short)-1);
}
}
else
{
foreach (ICell c in srcRow)
{
XSSFCell srcCell = (XSSFCell)c;
XSSFCell destCell = CreateCell(srcCell.ColumnIndex, srcCell.CellType) as XSSFCell;
destCell.CopyCellFrom(srcCell, policy);
}
XSSFRowShifter rowShifter = new XSSFRowShifter(_sheet);
int sheetIndex = _sheet.Workbook.GetSheetIndex(_sheet);
String sheetName = _sheet.Workbook.GetSheetName(sheetIndex);
int srcRowNum = srcRow.RowNum;
int destRowNum = RowNum;
int rowDifference = destRowNum - srcRowNum;
FormulaShifter shifter = FormulaShifter.CreateForRowCopy(sheetIndex, sheetName, srcRowNum, srcRowNum, rowDifference, SpreadsheetVersion.EXCEL2007);
rowShifter.UpdateRowFormulas(this, shifter);
// Copy merged regions that are fully contained on the row
// FIXME: is this something that rowShifter could be doing?
if (policy.IsCopyMergedRegions)
{
foreach (CellRangeAddress srcRegion in srcRow.Sheet.MergedRegions)
{
if (srcRowNum == srcRegion.FirstRow && srcRowNum == srcRegion.LastRow)
{
CellRangeAddress destRegion = srcRegion.Copy();
destRegion.FirstRow = (destRowNum);
destRegion.LastRow = (destRowNum);
Sheet.AddMergedRegion(destRegion);
}
}
}
if (policy.IsCopyRowHeight)
{
Height = (srcRow.Height);
}
}
}
#region IRow Members
public List<ICell> Cells
{
get {
List<ICell> cells = new List<ICell>();
foreach (ICell cell in _cells.Values)
{
cells.Add(cell);
}
return cells; }
}
public void MoveCell(ICell cell, int newColumn)
{
throw new NotImplementedException();
}
public IRow CopyRowTo(int targetIndex)
{
return this.Sheet.CopyRow(this.RowNum, targetIndex);
}
public ICell CopyCell(int sourceIndex, int targetIndex)
{
return CellUtil.CopyCell(this, sourceIndex, targetIndex);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool HasCustomHeight()
{
throw new NotImplementedException();
}
public int OutlineLevel
{
get
{
return _row.outlineLevel;
}
set
{
_row.outlineLevel = (byte)value;
}
}
public bool? Hidden
{
get
{
return _row.hidden;
}
set
{
_row.hidden = value ?? false;
}
}
public bool? Collapsed
{
get
{
return _row.collapsed;
}
set
{
_row.collapsed = value ?? false;
}
}
#endregion
}
}
| |
using System;
namespace IntuiLab.Kinect.Events
{
#region GestureDetected
public abstract class GestureDetectedEventArgs : EventArgs
{
public GestureDetectedEventArgs()
{
}
}
#region GestureSwipeLeftDetectedEventArgs
public delegate void GestureSwipeLeftDetectedEventHandler(object sender, GestureSwipeLeftDetectedEventArgs e);
public class GestureSwipeLeftDetectedEventArgs : GestureDetectedEventArgs
{
public GestureSwipeLeftDetectedEventArgs()
{
}
}
#endregion
#region GestureSwipeRightDetectedEventArgs
public delegate void GestureSwipeRightDetectedEventHandler(object sender, GestureSwipeRightDetectedEventArgs e);
public class GestureSwipeRightDetectedEventArgs : GestureDetectedEventArgs
{
public GestureSwipeRightDetectedEventArgs()
{
}
}
#endregion
#region GestureWaveDetectedEventArgs
public delegate void GestureWaveDetectedEventHandler(object sender, GestureWaveDetectedEventArgs e);
public class GestureWaveDetectedEventArgs : GestureDetectedEventArgs
{
public GestureWaveDetectedEventArgs()
{
}
}
#endregion
#region GestureGripDetectedEventArgs
public delegate void GestureGripDetectedEventHandler(object sender, GestureGripDetectedEventArgs e);
public class GestureGripDetectedEventArgs : GestureDetectedEventArgs
{
public GestureGripDetectedEventArgs()
{
}
}
#endregion
#region GesturePushDetectedEventArgs
public delegate void GesturePushDetectedEventHandler(object sender, GesturePushDetectedEventArgs e);
public class GesturePushDetectedEventArgs : GestureDetectedEventArgs
{
public GesturePushDetectedEventArgs()
{
}
}
#endregion
#region GestureMaximizeDetectedEventArgs
public delegate void GestureMaximizeDetectedEventHandler(object sender, GestureMaximizeDetectedEventArgs e);
public class GestureMaximizeDetectedEventArgs : GestureDetectedEventArgs
{
public GestureMaximizeDetectedEventArgs()
{
}
}
#endregion
#region GestureMinimizeDetectedEventArgs
public delegate void GestureMinimizeDetectedEventHandler(object sender, GestureMinimizeDetectedEventArgs e);
public class GestureMinimizeDetectedEventArgs : GestureDetectedEventArgs
{
public GestureMinimizeDetectedEventArgs()
{
}
}
#endregion
#region GestureADetectedEventArgs
public delegate void GestureADetectedEventHandler(object sender, GestureADetectedEventArgs e);
public class GestureADetectedEventArgs : GestureDetectedEventArgs
{
public GestureADetectedEventArgs()
{
}
}
#endregion
#region GestureHomeDetectedEventArgs
public delegate void GestureHomeDetectedEventHandler(object sender, GestureHomeDetectedEventArgs e);
public class GestureHomeDetectedEventArgs : GestureDetectedEventArgs
{
public GestureHomeDetectedEventArgs()
{
}
}
#endregion
#region GestureStayDetectedEventArgs
public delegate void GestureStayDetectedEventHandler(object sender, GestureStayDetectedEventArgs e);
public class GestureStayDetectedEventArgs : GestureDetectedEventArgs
{
public GestureStayDetectedEventArgs()
{
}
}
#endregion
#region GestureTDetectedEventArgs
public delegate void GestureTDetectedEventHandler(object sender, GestureTDetectedEventArgs e);
public class GestureTDetectedEventArgs : GestureDetectedEventArgs
{
public GestureTDetectedEventArgs()
{
}
}
#endregion
#region GestureUDetectedEventArgs
public delegate void GestureUDetectedEventHandler(object sender, GestureUDetectedEventArgs e);
public class GestureUDetectedEventArgs : GestureDetectedEventArgs
{
public GestureUDetectedEventArgs()
{
}
}
#endregion
#region GestureVDetectedEventArgs
public delegate void GestureVDetectedEventHandler(object sender, GestureVDetectedEventArgs e);
public class GestureVDetectedEventArgs : GestureDetectedEventArgs
{
public GestureVDetectedEventArgs()
{
}
}
#endregion
#region GestureWaitDetectedEventArgs
public delegate void GestureWaitDetectedEventHandler(object sender, GestureWaitDetectedEventArgs e);
public class GestureWaitDetectedEventArgs : GestureDetectedEventArgs
{
public GestureWaitDetectedEventArgs()
{
}
}
#endregion
#endregion
#region GestureProgress
public abstract class GestureProgressEventArgs : EventArgs
{
private float m_refPercent;
public float Percent
{
get
{
return m_refPercent;
}
}
public GestureProgressEventArgs(float percent)
{
m_refPercent = percent;
}
}
#region GestureAProgressEventArgs
public delegate void GestureAProgressEventHandler(object sender, GestureAProgressEventArgs e);
public class GestureAProgressEventArgs : GestureProgressEventArgs
{
public GestureAProgressEventArgs(float percent)
: base (percent)
{
}
}
#endregion
#region GestureHomeProgressEventArgs
public delegate void GestureHomeProgressEventHandler(object sender, GestureHomeProgressEventArgs e);
public class GestureHomeProgressEventArgs : GestureProgressEventArgs
{
public GestureHomeProgressEventArgs(float percent)
: base(percent)
{
}
}
#endregion
#region GestureStayProgressEventArgs
public delegate void GestureStayProgressEventHandler(object sender, GestureStayProgressEventArgs e);
public class GestureStayProgressEventArgs : GestureProgressEventArgs
{
public GestureStayProgressEventArgs(float percent)
: base(percent)
{
}
}
#endregion
#region GestureTProgressEventArgs
public delegate void GestureTProgressEventHandler(object sender, GestureTProgressEventArgs e);
public class GestureTProgressEventArgs : GestureProgressEventArgs
{
public GestureTProgressEventArgs(float percent)
: base(percent)
{
}
}
#endregion
#region GestureUProgressEventArgs
public delegate void GestureUProgressEventHandler(object sender, GestureUProgressEventArgs e);
public class GestureUProgressEventArgs : GestureProgressEventArgs
{
public GestureUProgressEventArgs(float percent)
: base(percent)
{
}
}
#endregion
#region GestureVProgressEventArgs
public delegate void GestureVProgressEventHandler(object sender, GestureVProgressEventArgs e);
public class GestureVProgressEventArgs : GestureProgressEventArgs
{
public GestureVProgressEventArgs(float percent)
: base(percent)
{
}
}
#endregion
#region GestureWaitProgressEventArgs
public delegate void GestureWaitProgressEventHandler(object sender, GestureWaitProgressEventArgs e);
public class GestureWaitProgressEventArgs : GestureProgressEventArgs
{
public GestureWaitProgressEventArgs(float percent)
: base(percent)
{
}
}
#endregion
#endregion
#region GestureLost
public abstract class GestureLostEventArgs : EventArgs
{
public GestureLostEventArgs()
{
}
}
#region GestureALostEventArgs
public delegate void GestureALostEventHandler(object sender, GestureALostEventArgs e);
public class GestureALostEventArgs : GestureLostEventArgs
{
public GestureALostEventArgs()
{
}
}
#endregion
#region GestureHomeLostEventArgs
public delegate void GestureHomeLostEventHandler(object sender, GestureHomeLostEventArgs e);
public class GestureHomeLostEventArgs : GestureLostEventArgs
{
public GestureHomeLostEventArgs()
{
}
}
#endregion
#region GestureStayLostEventArgs
public delegate void GestureStayLostEventHandler(object sender, GestureStayLostEventArgs e);
public class GestureStayLostEventArgs : GestureLostEventArgs
{
public GestureStayLostEventArgs()
{
}
}
#endregion
#region GestureTLostEventArgs
public delegate void GestureTLostEventHandler(object sender, GestureTLostEventArgs e);
public class GestureTLostEventArgs : GestureLostEventArgs
{
public GestureTLostEventArgs()
{
}
}
#endregion
#region GestureULostEventArgs
public delegate void GestureULostEventHandler(object sender, GestureULostEventArgs e);
public class GestureULostEventArgs : GestureLostEventArgs
{
public GestureULostEventArgs()
{
}
}
#endregion
#region GestureVLostEventArgs
public delegate void GestureVLostEventHandler(object sender, GestureVLostEventArgs e);
public class GestureVLostEventArgs : GestureLostEventArgs
{
public GestureVLostEventArgs()
{
}
}
#endregion
#region GestureWaitLostEventArgs
public delegate void GestureWaitLostEventHandler(object sender, GestureWaitLostEventArgs e);
public class GestureWaitLostEventArgs : GestureLostEventArgs
{
public GestureWaitLostEventArgs()
{
}
}
#endregion
#endregion
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Linq;
using FluentMigrator.Exceptions;
using FluentMigrator.Runner.Generators.Oracle;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.OracleWithQuotedIdentifier
{
[TestFixture]
public class OracleColumnTests : BaseColumnTests
{
protected OracleGenerator Generator;
[SetUp]
public void Setup()
{
Generator = new OracleGenerator(new OracleQuoterQuotedIdentifier());
}
[Test]
public override void CanCreateNullableColumnWithCustomDomainTypeAndCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpressionWithNullableCustomType();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ADD \"TestColumn1\" MyDomainType");
}
[Test]
public override void CanCreateNullableColumnWithCustomDomainTypeAndDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpressionWithNullableCustomType();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD \"TestColumn1\" MyDomainType");
}
[Test]
public override void CanAlterColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" MODIFY \"TestColumn1\" NVARCHAR2(20) NOT NULL");
}
[Test]
public override void CanAlterColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" MODIFY \"TestColumn1\" NVARCHAR2(20) NOT NULL");
}
[Test]
public override void CanCreateAutoIncrementColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnAddAutoIncrementExpression();
expression.SchemaName = "TestSchema";
Assert.Throws<DatabaseOperationNotSupportedException>(() => Generator.Generate(expression));
}
[Test]
public override void CanCreateAutoIncrementColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnAddAutoIncrementExpression();
Assert.Throws<DatabaseOperationNotSupportedException>(() => Generator.Generate(expression));
}
[Test]
public override void CanCreateColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ADD \"TestColumn1\" NVARCHAR2(5) NOT NULL");
}
[Test]
public override void CanCreateColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD \"TestColumn1\" NVARCHAR2(5) NOT NULL");
}
[Test]
public override void CanCreateColumnWithSystemMethodAndCustomSchema()
{
var expressions = GeneratorTestHelper.GetCreateColumnWithSystemMethodExpression("TestSchema");
var result = string.Join(Environment.NewLine, expressions.Select(x => (string)Generator.Generate((dynamic)x)));
result.ShouldBe(
@"ALTER TABLE ""TestSchema"".""TestTable1"" ADD ""TestColumn1"" TIMESTAMP(4)" + Environment.NewLine +
@"UPDATE ""TestSchema"".""TestTable1"" SET ""TestColumn1"" = LOCALTIMESTAMP WHERE 1 = 1");
}
[Test]
public override void CanCreateColumnWithSystemMethodAndDefaultSchema()
{
var expressions = GeneratorTestHelper.GetCreateColumnWithSystemMethodExpression();
var result = string.Join(Environment.NewLine, expressions.Select(x => (string)Generator.Generate((dynamic)x)));
result.ShouldBe(
@"ALTER TABLE ""TestTable1"" ADD ""TestColumn1"" TIMESTAMP(4)" + Environment.NewLine +
@"UPDATE ""TestTable1"" SET ""TestColumn1"" = LOCALTIMESTAMP WHERE 1 = 1");
}
[Test]
public override void CanCreateDecimalColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateDecimalColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ADD \"TestColumn1\" NUMBER(19,2) NOT NULL");
}
[Test]
public override void CanCreateDecimalColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateDecimalColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD \"TestColumn1\" NUMBER(19,2) NOT NULL");
}
[Test]
public override void CanDropColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" DROP COLUMN \"TestColumn1\"");
}
[Test]
public override void CanDropColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" DROP COLUMN \"TestColumn1\"");
}
[Test]
public override void CanDropMultipleColumnsWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteColumnExpression(new[] { "\"TestColumn1\"", "\"TestColumn2\"" });
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe(
"ALTER TABLE \"TestSchema\".\"TestTable1\" DROP COLUMN \"TestColumn1\"" + Environment.NewLine +
";" + Environment.NewLine +
"ALTER TABLE \"TestSchema\".\"TestTable1\" DROP COLUMN \"TestColumn2\"");
}
[Test]
public override void CanDropMultipleColumnsWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteColumnExpression(new[] { "\"TestColumn1\"", "\"TestColumn2\"" });
var result = Generator.Generate(expression);
result.ShouldBe(
"ALTER TABLE \"TestTable1\" DROP COLUMN \"TestColumn1\"" + Environment.NewLine +
";" + Environment.NewLine +
"ALTER TABLE \"TestTable1\" DROP COLUMN \"TestColumn2\"");
}
[Test]
public override void CanRenameColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetRenameColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" RENAME COLUMN \"TestColumn1\" TO \"TestColumn2\"");
}
[Test]
public override void CanRenameColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetRenameColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" RENAME COLUMN \"TestColumn1\" TO \"TestColumn2\"");
}
[Test]
public void CanCreateColumnWithDefaultValue()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
expression.Column.DefaultValue = 1;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD \"TestColumn1\" NVARCHAR2(5) DEFAULT 1 NOT NULL");
}
[Test]
public void CanCreateColumnWithDefaultStringValue()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
expression.Column.DefaultValue = "1";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD \"TestColumn1\" NVARCHAR2(5) DEFAULT '1' NOT NULL");
}
[Test]
public void CanCreateColumnWithDefaultSystemMethodNewGuid()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
expression.Column.DefaultValue = SystemMethods.NewGuid;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD \"TestColumn1\" NVARCHAR2(5) DEFAULT sys_guid() NOT NULL");
}
[Test]
public void CanCreateColumnWithDefaultSystemMethodCurrentDateTime()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
expression.Column.DefaultValue = SystemMethods.CurrentDateTime;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD \"TestColumn1\" NVARCHAR2(5) DEFAULT LOCALTIMESTAMP NOT NULL");
}
[Test]
public void CanCreateColumnWithDefaultSystemMethodCurrentUser()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
expression.Column.DefaultValue = SystemMethods.CurrentUser;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD \"TestColumn1\" NVARCHAR2(5) DEFAULT USER NOT 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.
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Activator is an object that contains the Activation (CreateInstance/New)
// methods for late bound support.
//
//
//
//
namespace System
{
using System;
using System.Reflection;
using System.Runtime.Remoting;
using System.Security;
using CultureInfo = System.Globalization.CultureInfo;
using Evidence = System.Security.Policy.Evidence;
using StackCrawlMark = System.Threading.StackCrawlMark;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
// Only statics, does not need to be marked with the serializable attribute
public sealed class Activator
{
internal const int LookupMask = 0x000000FF;
internal const BindingFlags ConLookup = (BindingFlags)(BindingFlags.Instance | BindingFlags.Public);
internal const BindingFlags ConstructorDefault = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
// This class only contains statics, so hide the worthless constructor
private Activator()
{
}
// CreateInstance
// The following methods will create a new instance of an Object
// Full Binding Support
// For all of these methods we need to get the underlying RuntimeType and
// call the Impl version.
static public Object CreateInstance(Type type,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture)
{
return CreateInstance(type, bindingAttr, binder, args, culture, null);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public Object CreateInstance(Type type,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes)
{
if ((object)type == null)
throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
if (type is System.Reflection.Emit.TypeBuilder)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_CreateInstanceWithTypeBuilder"));
// If they didn't specify a lookup, then we will provide the default lookup.
if ((bindingAttr & (BindingFlags)LookupMask) == 0)
bindingAttr |= Activator.ConstructorDefault;
if (activationAttributes != null && activationAttributes.Length > 0)
{
throw new PlatformNotSupportedException(Environment.GetResourceString("NotSupported_ActivAttr"));
}
RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
if (rt == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(type));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return rt.CreateInstanceImpl(bindingAttr, binder, args, culture, activationAttributes, ref stackMark);
}
static public Object CreateInstance(Type type, params Object[] args)
{
return CreateInstance(type,
Activator.ConstructorDefault,
null,
args,
null,
null);
}
static public Object CreateInstance(Type type,
Object[] args,
Object[] activationAttributes)
{
return CreateInstance(type,
Activator.ConstructorDefault,
null,
args,
null,
activationAttributes);
}
static public Object CreateInstance(Type type)
{
return Activator.CreateInstance(type, false);
}
/*
* Create an instance using the name of type and the assembly where it exists. This allows
* types to be created remotely without having to load the type locally.
*/
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public ObjectHandle CreateInstance(String assemblyName,
String typeName)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
typeName,
false,
Activator.ConstructorDefault,
null,
null,
null,
null,
null,
ref stackMark);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public ObjectHandle CreateInstance(String assemblyName,
String typeName,
Object[] activationAttributes)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
typeName,
false,
Activator.ConstructorDefault,
null,
null,
null,
activationAttributes,
null,
ref stackMark);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public Object CreateInstance(Type type, bool nonPublic)
{
if ((object)type == null)
throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
if (rt == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(type));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return rt.CreateInstanceDefaultCtor(!nonPublic, false, true, ref stackMark);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public T CreateInstance<T>()
{
RuntimeType rt = typeof(T) as RuntimeType;
// This is a workaround to maintain compatibility with V2. Without this we would throw a NotSupportedException for void[].
// Array, Ref, and Pointer types don't have default constructors.
if (rt.HasElementType)
throw new MissingMethodException(Environment.GetResourceString("Arg_NoDefCTor"));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// Skip the CreateInstanceCheckThis call to avoid perf cost and to maintain compatibility with V2 (throwing the same exceptions).
return (T)rt.CreateInstanceDefaultCtor(true /*publicOnly*/, true /*skipCheckThis*/, true /*fillCache*/, ref stackMark);
}
static public ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName)
{
return CreateInstanceFrom(assemblyFile, typeName, null);
}
static public ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName,
Object[] activationAttributes)
{
return CreateInstanceFrom(assemblyFile,
typeName,
false,
Activator.ConstructorDefault,
null,
null,
null,
activationAttributes);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static ObjectHandle CreateInstance(string assemblyName,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
object[] args,
CultureInfo culture,
object[] activationAttributes)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
typeName,
ignoreCase,
bindingAttr,
binder,
args,
culture,
activationAttributes,
null,
ref stackMark);
}
static internal ObjectHandle CreateInstance(String assemblyString,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityInfo,
ref StackCrawlMark stackMark)
{
Type type = null;
Assembly assembly = null;
if (assemblyString == null)
{
assembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
}
else
{
RuntimeAssembly assemblyFromResolveEvent;
AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(assemblyString, false /*forIntrospection*/, out assemblyFromResolveEvent);
if (assemblyFromResolveEvent != null)
{
// Assembly was resolved via AssemblyResolve event
assembly = assemblyFromResolveEvent;
}
else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime)
{
// WinRT type - we have to use Type.GetType
type = Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, ignoreCase);
}
else
{
// Classic managed type
assembly = RuntimeAssembly.InternalLoadAssemblyName(
assemblyName, securityInfo, null, ref stackMark,
true /*thrownOnFileNotFound*/, false /*forIntrospection*/);
}
}
if (type == null)
{
// It's classic managed type (not WinRT type)
Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyString);
if (assembly == null) return null;
type = assembly.GetType(typeName, true /*throwOnError*/, ignoreCase);
}
Object o = Activator.CreateInstance(type,
bindingAttr,
binder,
args,
culture,
activationAttributes);
Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
if (o == null)
return null;
else
{
ObjectHandle Handle = new ObjectHandle(o);
return Handle;
}
}
public static ObjectHandle CreateInstanceFrom(string assemblyFile,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
object[] args,
CultureInfo culture,
object[] activationAttributes)
{
return CreateInstanceFromInternal(assemblyFile,
typeName,
ignoreCase,
bindingAttr,
binder,
args,
culture,
activationAttributes,
null);
}
private static ObjectHandle CreateInstanceFromInternal(String assemblyFile,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityInfo)
{
#pragma warning disable 618
Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo);
#pragma warning restore 618
Type t = assembly.GetType(typeName, true, ignoreCase);
Object o = Activator.CreateInstance(t,
bindingAttr,
binder,
args,
culture,
activationAttributes);
Log(o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
if (o == null)
return null;
else
{
ObjectHandle Handle = new ObjectHandle(o);
return Handle;
}
}
public static ObjectHandle CreateComInstanceFrom(String assemblyName,
String typeName)
{
return CreateComInstanceFrom(assemblyName,
typeName,
null,
AssemblyHashAlgorithm.None);
}
public static ObjectHandle CreateComInstanceFrom(String assemblyName,
String typeName,
byte[] hashValue,
AssemblyHashAlgorithm hashAlgorithm)
{
Assembly assembly = Assembly.LoadFrom(assemblyName, hashValue, hashAlgorithm);
Type t = assembly.GetType(typeName, true, false);
Object[] Attr = t.GetCustomAttributes(typeof(ComVisibleAttribute), false);
if (Attr.Length > 0)
{
if (((ComVisibleAttribute)Attr[0]).Value == false)
throw new TypeLoadException(Environment.GetResourceString("Argument_TypeMustBeVisibleFromCom"));
}
Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyName);
if (assembly == null) return null;
Object o = Activator.CreateInstance(t,
Activator.ConstructorDefault,
null,
null,
null,
null);
Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
if (o == null)
return null;
else
{
ObjectHandle Handle = new ObjectHandle(o);
return Handle;
}
}
[System.Diagnostics.Conditional("_DEBUG")]
private static void Log(bool test, string title, string success, string failure)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit01.explicit01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit01.explicit01;
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(10,39\).*CS1066</Expects>
public class Derived
{
static public explicit operator int (Derived d = null)
{
if (d != null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic tf = new Derived();
int result = (int)tf;
return result;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit02.explicit02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit02.explicit02;
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(12,41\).*CS1066</Expects>
public class Derived
{
static public explicit operator int (Derived d = default(Derived))
{
if (d == null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = null;
dynamic tf = p;
try
{
int result = (int)tf;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.ValueCantBeNull, e.Message, "int");
if (ret)
return 0;
}
return 1;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit04.explicit04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit04.explicit04;
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(11,39\).*CS1066</Expects>
public class Derived
{
private const Derived x = null;
static public explicit operator int (Derived d = x)
{
if (d != null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic tf = new Derived();
int result = (int)tf;
return result;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit05.explicit05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit05.explicit05;
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(11,39\).*CS1066</Expects>
public class Derived
{
private const Derived x = null;
static public explicit operator int (Derived d = true ? x : x)
{
if (d != null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic tf = new Derived();
int result = (int)tf;
return result;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit01.implicit01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit01.implicit01;
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(10,39\).*CS1066</Expects>
public class Derived
{
static public implicit operator int (Derived d = null)
{
if (d != null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic tf = new Derived();
int result = tf;
return result;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit02.implicit02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit02.implicit02;
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(11,39\).*CS1066</Expects>
public class Derived
{
static public implicit operator int (Derived d = default(Derived))
{
if (d == null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = null;
dynamic tf = p;
try
{
int result = tf;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.ValueCantBeNull, e.Message, "int");
if (ret)
return 0;
}
return 1;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit04.implicit04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit04.implicit04;
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(11,39\).*CS1066</Expects>
public class Derived
{
private const Derived x = null;
static public implicit operator int (Derived d = x)
{
if (d != null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic tf = new Derived();
int result = tf;
return result;
}
}
//</code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit05.implicit05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit05.implicit05;
// <Area>Declaration of Optional Params</Area>
// <Title> Explicit User defined conversions</Title>
// <Description>User-defined conversions with defaults</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(11,39\).*CS1066</Expects>
public class Derived
{
private const Derived x = null;
static public implicit operator int (Derived d = true ? x : x)
{
if (d != null)
return 0;
return 1;
}
}
public class TestFunction
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic tf = new Derived();
int result = tf;
return result;
}
}
//</code>
}
| |
// (c) Copyright Esri, 2010 - 2013
// This source is subject to the Apache 2.0 License.
// Please see http://www.apache.org/licenses/LICENSE-2.0.html for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Resources;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Display;
using System.Xml;
using ESRI.ArcGIS.OSM.OSMClassExtension;
using System.Globalization;
using ESRI.ArcGIS.DataSourcesFile;
namespace ESRI.ArcGIS.OSM.GeoProcessing
{
[Guid("3379c124-ea23-49f7-905a-03c3694a6fdb")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPExport2OSM")]
public class OSMGPExport2OSM : ESRI.ArcGIS.Geoprocessing.IGPFunction2
{
string m_DisplayName = String.Empty;
int in_featureDatasetParameterNumber, out_osmFileLocationParameterNumber;
ResourceManager resourceManager = null;
OSMGPFactory osmGPFactory = null;
OSMUtility _osmUtility = null;
ISpatialReference m_wgs84 = null;
public OSMGPExport2OSM()
{
resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);
osmGPFactory = new OSMGPFactory();
_osmUtility = new OSMUtility();
ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory;
m_wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference;
}
#region "IGPFunction2 Implementations"
public ESRI.ArcGIS.esriSystem.UID DialogCLSID
{
get
{
return null;
}
}
public string DisplayName
{
get
{
if (String.IsNullOrEmpty(m_DisplayName))
{
m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_Export2OSMName).DisplayName;
}
return m_DisplayName;
}
}
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
{
try
{
IGPUtilities3 execute_Utilities = new GPUtilitiesClass();
if (TrackCancel == null)
{
TrackCancel = new CancelTrackerClass();
}
IGPParameter inputFeatureDatasetParameter = paramvalues.get_Element(in_featureDatasetParameterNumber) as IGPParameter;
IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(inputFeatureDatasetParameter);
IGPValue outputOSMFileGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(out_osmFileLocationParameterNumber));
// get the name of the feature dataset
int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\");
string nameOfFeatureDataset = inputFeatureDatasetGPValue.GetAsText().Substring(fdDemlimiterPosition + 1);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
System.Xml.XmlWriter xmlWriter = null;
try
{
xmlWriter = XmlWriter.Create(outputOSMFileGPValue.GetAsText(), settings);
}
catch (Exception ex)
{
message.AddError(120021, ex.Message);
return;
}
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("osm"); // start the osm root node
xmlWriter.WriteAttributeString("version", "0.6"); // add the version attribute
xmlWriter.WriteAttributeString("generator", "ArcGIS Editor for OpenStreetMap"); // add the generator attribute
// write all the nodes
// use a feature search cursor to loop through all the known points and write them out as osm node
IFeatureClassContainer osmFeatureClasses = execute_Utilities.OpenDataset(inputFeatureDatasetGPValue) as IFeatureClassContainer;
if (osmFeatureClasses == null)
{
message.AddError(120022, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), inputFeatureDatasetParameter.Name));
return;
}
IFeatureClass osmPointFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_pt");
if (osmPointFeatureClass == null)
{
message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_pointfeatureclass"), nameOfFeatureDataset + "_osm_pt"));
return;
}
// check the extension of the point feature class to determine its version
int internalOSMExtensionVersion = osmPointFeatureClass.OSMExtensionVersion();
IFeatureCursor searchCursor = null;
System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces();
xmlnsEmpty.Add("", "");
message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_pts_msg"));
int pointCounter = 0;
string nodesExportedMessage = String.Empty;
// collect the indices for the point feature class once
int pointOSMIDFieldIndex = osmPointFeatureClass.Fields.FindField("OSMID");
int pointChangesetFieldIndex = osmPointFeatureClass.Fields.FindField("osmchangeset");
int pointVersionFieldIndex = osmPointFeatureClass.Fields.FindField("osmversion");
int pointUIDFieldIndex = osmPointFeatureClass.Fields.FindField("osmuid");
int pointUserFieldIndex = osmPointFeatureClass.Fields.FindField("osmuser");
int pointTimeStampFieldIndex = osmPointFeatureClass.Fields.FindField("osmtimestamp");
int pointVisibleFieldIndex = osmPointFeatureClass.Fields.FindField("osmvisible");
int pointTagsFieldIndex = osmPointFeatureClass.Fields.FindField("osmTags");
using (ComReleaser comReleaser = new ComReleaser())
{
searchCursor = osmPointFeatureClass.Search(null, false);
comReleaser.ManageLifetime(searchCursor);
System.Xml.Serialization.XmlSerializer pointSerializer = new System.Xml.Serialization.XmlSerializer(typeof(node));
IFeature currentFeature = searchCursor.NextFeature();
IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace;
while (currentFeature != null)
{
if (TrackCancel.Continue() == true)
{
// convert the found point feature into a osm node representation to store into the OSM XML file
node osmNode = ConvertPointFeatureToOSMNode(currentFeature, pointWorkspace, pointTagsFieldIndex, pointOSMIDFieldIndex, pointChangesetFieldIndex, pointVersionFieldIndex, pointUIDFieldIndex, pointUserFieldIndex, pointTimeStampFieldIndex, pointVisibleFieldIndex, internalOSMExtensionVersion);
pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty);
// increase the point counter to later status report
pointCounter++;
currentFeature = searchCursor.NextFeature();
}
else
{
// properly close the document
xmlWriter.WriteEndElement(); // closing the osm root element
xmlWriter.WriteEndDocument(); // finishing the document
xmlWriter.Close(); // closing the document
// report the number of elements loader so far
nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter);
message.AddMessage(nodesExportedMessage);
return;
}
}
}
nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter);
message.AddMessage(nodesExportedMessage);
// next loop through the line and polygon feature classes to export those features as ways
// in case we encounter a multi-part geometry, store it in a relation collection that will be serialized when exporting the relations table
IFeatureClass osmLineFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ln");
if (osmLineFeatureClass == null)
{
message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_linefeatureclass"), nameOfFeatureDataset + "_osm_ln"));
return;
}
message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_ways_msg"));
// as we are looping through the line and polygon feature classes let's collect the multi-part features separately
// as they are considered relations in the OSM world
List<relation> multiPartElements = new List<relation>();
System.Xml.Serialization.XmlSerializer waySerializer = new System.Xml.Serialization.XmlSerializer(typeof(way));
int lineCounter = 0;
int relationCounter = 0;
string waysExportedMessage = String.Empty;
using (ComReleaser comReleaser = new ComReleaser())
{
searchCursor = osmLineFeatureClass.Search(null, false);
comReleaser.ManageLifetime(searchCursor);
IFeature currentFeature = searchCursor.NextFeature();
// collect the indices for the point feature class once
int lineOSMIDFieldIndex = osmLineFeatureClass.Fields.FindField("OSMID");
int lineChangesetFieldIndex = osmLineFeatureClass.Fields.FindField("osmchangeset");
int lineVersionFieldIndex = osmLineFeatureClass.Fields.FindField("osmversion");
int lineUIDFieldIndex = osmLineFeatureClass.Fields.FindField("osmuid");
int lineUserFieldIndex = osmLineFeatureClass.Fields.FindField("osmuser");
int lineTimeStampFieldIndex = osmLineFeatureClass.Fields.FindField("osmtimestamp");
int lineVisibleFieldIndex = osmLineFeatureClass.Fields.FindField("osmvisible");
int lineTagsFieldIndex = osmLineFeatureClass.Fields.FindField("osmTags");
int lineMembersFieldIndex = osmLineFeatureClass.Fields.FindField("osmMembers");
IWorkspace lineWorkspace = ((IDataset)osmLineFeatureClass).Workspace;
while (currentFeature != null)
{
if (TrackCancel.Continue() == false)
{
// properly close the document
xmlWriter.WriteEndElement(); // closing the osm root element
xmlWriter.WriteEndDocument(); // finishing the document
xmlWriter.Close(); // closing the document
// report the number of elements loaded so far
waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
message.AddMessage(waysExportedMessage);
return;
}
//test if the feature geometry has multiple parts
IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection;
if (geometryCollection != null)
{
if (geometryCollection.GeometryCount == 1)
{
// convert the found polyline feature into a osm way representation to store into the OSM XML file
way osmWay = ConvertFeatureToOSMWay(currentFeature, lineWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, internalOSMExtensionVersion);
waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty);
// increase the line counter for later status report
lineCounter++;
}
else
{
relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, lineWorkspace, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, lineMembersFieldIndex, internalOSMExtensionVersion);
multiPartElements.Add(osmRelation);
// increase the line counter for later status report
relationCounter++;
}
}
currentFeature = searchCursor.NextFeature();
}
}
IFeatureClass osmPolygonFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ply");
IFeatureWorkspace commonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace as IFeatureWorkspace;
if (osmPolygonFeatureClass == null)
{
message.AddError(120024, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_polygonfeatureclass"), nameOfFeatureDataset + "_osm_ply"));
return;
}
using (ComReleaser comReleaser = new ComReleaser())
{
searchCursor = osmPolygonFeatureClass.Search(null, false);
comReleaser.ManageLifetime(searchCursor);
IFeature currentFeature = searchCursor.NextFeature();
// collect the indices for the point feature class once
int polygonOSMIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("OSMID");
int polygonChangesetFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmchangeset");
int polygonVersionFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmversion");
int polygonUIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuid");
int polygonUserFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuser");
int polygonTimeStampFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmtimestamp");
int polygonVisibleFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmvisible");
int polygonTagsFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmTags");
int polygonMembersFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmMembers");
IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace;
while (currentFeature != null)
{
if (TrackCancel.Continue() == false)
{
// properly close the document
xmlWriter.WriteEndElement(); // closing the osm root element
xmlWriter.WriteEndDocument(); // finishing the document
xmlWriter.Close(); // closing the document
// report the number of elements loaded so far
waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
message.AddMessage(waysExportedMessage);
message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
return;
}
//test if the feature geometry has multiple parts
IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection;
if (geometryCollection != null)
{
if (geometryCollection.GeometryCount == 1)
{
// convert the found polyline feature into a osm way representation to store into the OSM XML file
way osmWay = ConvertFeatureToOSMWay(currentFeature, polygonWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, internalOSMExtensionVersion);
waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty);
// increase the line counter for later status report
lineCounter++;
}
else
{
relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, polygonWorkspace, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, polygonMembersFieldIndex, internalOSMExtensionVersion);
multiPartElements.Add(osmRelation);
// increase the line counter for later status report
relationCounter++;
}
}
currentFeature = searchCursor.NextFeature();
}
}
waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
message.AddMessage(waysExportedMessage);
// now let's go through the relation table
message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_relations_msg"));
ITable relationTable = commonWorkspace.OpenTable(nameOfFeatureDataset + "_osm_relation");
if (relationTable == null)
{
message.AddError(120025, String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_relationTable"), nameOfFeatureDataset + "_osm_relation"));
return;
}
System.Xml.Serialization.XmlSerializer relationSerializer = new System.Xml.Serialization.XmlSerializer(typeof(relation));
string relationsExportedMessage = String.Empty;
using (ComReleaser comReleaser = new ComReleaser())
{
ICursor rowCursor = relationTable.Search(null, false);
comReleaser.ManageLifetime(rowCursor);
IRow currentRow = rowCursor.NextRow();
// collect the indices for the relation table once
int relationOSMIDFieldIndex = relationTable.Fields.FindField("OSMID");
int relationChangesetFieldIndex = relationTable.Fields.FindField("osmchangeset");
int relationVersionFieldIndex = relationTable.Fields.FindField("osmversion");
int relationUIDFieldIndex = relationTable.Fields.FindField("osmuid");
int relationUserFieldIndex = relationTable.Fields.FindField("osmuser");
int relationTimeStampFieldIndex = relationTable.Fields.FindField("osmtimestamp");
int relationVisibleFieldIndex = relationTable.Fields.FindField("osmvisible");
int relationTagsFieldIndex = relationTable.Fields.FindField("osmTags");
int relationMembersFieldIndex = relationTable.Fields.FindField("osmMembers");
IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace;
while (currentRow != null)
{
if (TrackCancel.Continue() == false)
{
// properly close the document
xmlWriter.WriteEndElement(); // closing the osm root element
xmlWriter.WriteEndDocument(); // finishing the document
xmlWriter.Close(); // closing the document
// report the number of elements loaded so far
relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
message.AddMessage(relationsExportedMessage);
message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
return;
}
relation osmRelation = ConvertRowToOSMRelation(currentRow, (IWorkspace)commonWorkspace, relationTagsFieldIndex, relationOSMIDFieldIndex, relationChangesetFieldIndex, relationVersionFieldIndex, relationUIDFieldIndex, relationUserFieldIndex, relationTimeStampFieldIndex, relationVisibleFieldIndex, relationMembersFieldIndex, internalOSMExtensionVersion);
relationSerializer.Serialize(xmlWriter, osmRelation, xmlnsEmpty);
// increase the line counter for later status report
relationCounter++;
currentRow = rowCursor.NextRow();
}
}
// lastly let's serialize the collected multipart-geometries back into relation elements
foreach (relation currentRelation in multiPartElements)
{
if (TrackCancel.Continue() == false)
{
// properly close the document
xmlWriter.WriteEndElement(); // closing the osm root element
xmlWriter.WriteEndDocument(); // finishing the document
xmlWriter.Close(); // closing the document
// report the number of elements loaded so far
relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
message.AddMessage(relationsExportedMessage);
return;
}
relationSerializer.Serialize(xmlWriter, currentRelation, xmlnsEmpty);
relationCounter++;
}
relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
message.AddMessage(relationsExportedMessage);
xmlWriter.WriteEndElement(); // closing the osm root element
xmlWriter.WriteEndDocument(); // finishing the document
xmlWriter.Close(); // closing the document
}
catch (Exception ex)
{
message.AddError(120026, ex.Message);
}
}
public ESRI.ArcGIS.esriSystem.IName FullName
{
get
{
IName fullName = null;
if (osmGPFactory != null)
{
fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_Export2OSMName) as IName;
}
return fullName;
}
}
public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam)
{
return null;
}
public int HelpContext
{
get
{
return 0;
}
}
public string HelpFile
{
get
{
return String.Empty;
}
}
public bool IsLicensed()
{
return true;
}
public string MetadataFile
{
get
{
string metadafile = "osmgpexport2osm.xml";
try
{
string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray());
string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation();
string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpfileloader_" + languageid[0] + ".xml";
string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpfileloader_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml";
if (System.IO.File.Exists(localizedMetaDataFileShort))
{
metadafile = localizedMetaDataFileShort;
}
else if (System.IO.File.Exists(localizedMetaDataFileLong))
{
metadafile = localizedMetaDataFileLong;
}
}
catch { }
return metadafile;
}
}
public string Name
{
get
{
return OSMGPFactory.m_Export2OSMName;
}
}
public ESRI.ArcGIS.esriSystem.IArray ParameterInfo
{
get
{
//
IArray parameterArray = new ArrayClass();
// input feature dataset (required)
IGPParameterEdit3 inputOSMDataset = new GPParameterClass() as IGPParameterEdit3;
inputOSMDataset.DataType = new DEFeatureDatasetTypeClass();
inputOSMDataset.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
inputOSMDataset.DisplayName = resourceManager.GetString("GPTools_OSMGPExport2OSM_desc_inputDataset_desc");
inputOSMDataset.Name = "in_osmFeatureDataset";
inputOSMDataset.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
in_featureDatasetParameterNumber = 0;
parameterArray.Add(inputOSMDataset);
// output osm XML file
IGPParameterEdit3 outputOSMFile = new GPParameterClass() as IGPParameterEdit3;
outputOSMFile.DataType = new DEFileTypeClass();
outputOSMFile.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
outputOSMFile.DisplayName = resourceManager.GetString("GPTools_OSMGPExport2OSM_desc_outputXMLFile_desc");
outputOSMFile.Name = "out_osmXMLFile";
outputOSMFile.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
IGPFileDomain osmFileDomainFilter = new GPFileDomainClass();
osmFileDomainFilter.AddType("osm");
outputOSMFile.Domain = osmFileDomainFilter as IGPDomain;
out_osmFileLocationParameterNumber = 1;
parameterArray.Add(outputOSMFile);
return parameterArray;
}
}
public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
{
IGPUtilities3 execute_Utilities = new GPUtilitiesClass();
IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(in_featureDatasetParameterNumber));
// get the name of the feature dataset
int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\");
if (fdDemlimiterPosition == -1)
{
Messages.ReplaceError(in_featureDatasetParameterNumber, -33, resourceManager.GetString("GPTools_OSMGPExport2OSM_invalid_featuredataset"));
}
}
public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
{
}
public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr)
{
return default(ESRI.ArcGIS.Geodatabase.IGPMessages);
}
#endregion
private node ConvertPointFeatureToOSMNode(IFeature currentFeature, IWorkspace featureWorkspace, int tagsFieldIndex, int osmIDFieldIndex, int changesetIDFieldIndex, int osmVersionFieldIndex, int userIDFieldIndex, int userNameFieldIndex, int timeStampFieldIndex, int visibleFieldIndex, int extensionVersion)
{
if (currentFeature == null)
throw new ArgumentNullException("currentFeature");
node osmNode = new node();
object featureValue = DBNull.Value;
if (currentFeature.Shape.IsEmpty == false)
{
IPoint wgs84Point = currentFeature.Shape as IPoint;
wgs84Point.Project(m_wgs84);
CultureInfo exportCultureInfo = new CultureInfo("en-US");
exportCultureInfo.NumberFormat.NumberDecimalDigits = 6;
osmNode.lat = Convert.ToString(wgs84Point.Y, exportCultureInfo);
osmNode.lon = Convert.ToString(wgs84Point.X, exportCultureInfo);
Marshal.ReleaseComObject(wgs84Point);
}
if (osmIDFieldIndex != -1)
{
osmNode.id = Convert.ToString(currentFeature.get_Value(osmIDFieldIndex));
}
if (changesetIDFieldIndex != -1)
{
featureValue = currentFeature.get_Value(changesetIDFieldIndex);
if (featureValue != DBNull.Value)
{
osmNode.changeset = Convert.ToString(currentFeature.get_Value(changesetIDFieldIndex));
}
}
if (osmVersionFieldIndex != -1)
{
featureValue = currentFeature.get_Value(osmVersionFieldIndex);
if (featureValue != DBNull.Value)
{
osmNode.version = Convert.ToString(featureValue);
}
}
if (userIDFieldIndex != -1)
{
featureValue = currentFeature.get_Value(userIDFieldIndex);
if (featureValue != DBNull.Value)
{
osmNode.uid = Convert.ToString(featureValue);
}
}
if (userNameFieldIndex != -1)
{
featureValue = currentFeature.get_Value(userNameFieldIndex);
if (featureValue != DBNull.Value)
{
osmNode.user = Convert.ToString(featureValue);
}
}
if (timeStampFieldIndex != -1)
{
featureValue = currentFeature.get_Value(timeStampFieldIndex);
if (featureValue != DBNull.Value)
{
osmNode.timestamp = Convert.ToDateTime(featureValue).ToUniversalTime().ToString("u");
}
}
if (visibleFieldIndex != -1)
{
featureValue = currentFeature.get_Value(visibleFieldIndex);
if (featureValue != DBNull.Value)
{
try
{
osmNode.visible = (nodeVisible)Enum.Parse(typeof(nodeVisible), Convert.ToString(featureValue));
}
catch
{
osmNode.visible = nodeVisible.@true;
}
}
}
if (tagsFieldIndex > -1)
{
tag[] tags = null;
tags = _osmUtility.retrieveOSMTags((IRow)currentFeature, tagsFieldIndex, featureWorkspace);
if (tags.Length != 0)
{
osmNode.tag = tags;
}
}
return osmNode;
}
private way ConvertFeatureToOSMWay(IFeature currentFeature, IWorkspace featureWorkspace, IFeatureClass pointFeatureClass, int osmIDPointFieldIndex, int tagsFieldIndex, int osmIDFieldIndex, int changesetIDFieldIndex, int osmVersionFieldIndex, int userIDFieldIndex, int userNameFieldIndex, int timeStampFieldIndex, int visibleFieldIndex, int extensionVersion)
{
if (currentFeature == null)
throw new ArgumentNullException("currentFeature");
way osmWay = new way();
object featureValue = DBNull.Value;
List<nd> vertexIDs = new List<nd>();
if (currentFeature.Shape.IsEmpty == false)
{
IPointCollection pointCollection = currentFeature.Shape as IPointCollection;
if (currentFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
{
for (int pointIndex = 0; pointIndex < pointCollection.PointCount - 1; pointIndex++)
{
nd vertex = new nd();
vertex.@ref = OSMToolHelper.retrieveNodeID(pointFeatureClass, osmIDPointFieldIndex, extensionVersion, pointCollection.get_Point(pointIndex));
vertexIDs.Add(vertex);
}
// the last node is the first one again even though it doesn't have an internal ID
nd lastVertex = new nd();
lastVertex.@ref = OSMToolHelper.retrieveNodeID(pointFeatureClass, osmIDPointFieldIndex, extensionVersion, pointCollection.get_Point(0));
vertexIDs.Add(lastVertex);
}
else
{
for (int pointIndex = 0; pointIndex < pointCollection.PointCount; pointIndex++)
{
nd vertex = new nd();
vertex.@ref = OSMToolHelper.retrieveNodeID(pointFeatureClass, osmIDPointFieldIndex, extensionVersion, pointCollection.get_Point(pointIndex));
vertexIDs.Add(vertex);
}
}
osmWay.nd = vertexIDs.ToArray();
}
if (osmIDFieldIndex != -1)
{
osmWay.id = Convert.ToString(currentFeature.get_Value(osmIDFieldIndex));
}
if (changesetIDFieldIndex != -1)
{
featureValue = currentFeature.get_Value(changesetIDFieldIndex);
if (featureValue != DBNull.Value)
{
osmWay.changeset = Convert.ToString(currentFeature.get_Value(changesetIDFieldIndex));
}
}
if (osmVersionFieldIndex != -1)
{
featureValue = currentFeature.get_Value(osmVersionFieldIndex);
if (featureValue != DBNull.Value)
{
osmWay.version = Convert.ToString(featureValue);
}
}
if (userIDFieldIndex != -1)
{
featureValue = currentFeature.get_Value(userIDFieldIndex);
if (featureValue != DBNull.Value)
{
osmWay.uid = Convert.ToString(featureValue);
}
}
if (userNameFieldIndex != -1)
{
featureValue = currentFeature.get_Value(userNameFieldIndex);
if (featureValue != DBNull.Value)
{
osmWay.user = Convert.ToString(featureValue);
}
}
if (timeStampFieldIndex != -1)
{
featureValue = currentFeature.get_Value(timeStampFieldIndex);
if (featureValue != DBNull.Value)
{
osmWay.timestamp = Convert.ToDateTime(featureValue).ToUniversalTime().ToString("u");
}
}
if (visibleFieldIndex != -1)
{
featureValue = currentFeature.get_Value(visibleFieldIndex);
if (featureValue != DBNull.Value)
{
try
{
osmWay.visible = (wayVisible)Enum.Parse(typeof(wayVisible), Convert.ToString(featureValue));
}
catch
{
osmWay.visible = wayVisible.@true;
}
}
}
if (tagsFieldIndex > -1)
{
tag[] tags = null;
tags = _osmUtility.retrieveOSMTags((IRow)currentFeature, tagsFieldIndex, featureWorkspace);
if (tags.Length != 0)
{
osmWay.tag = tags;
}
}
return osmWay;
}
private relation ConvertRowToOSMRelation(IRow currentRow, IWorkspace featureWorkspace, int tagsFieldIndex, int osmIDFieldIndex, int changesetIDFieldIndex, int osmVersionFieldIndex, int userIDFieldIndex, int userNameFieldIndex, int timeStampFieldIndex, int visibleFieldIndex, int membersFieldIndex, int extensionVersion)
{
if (currentRow == null)
throw new ArgumentNullException("currentRow");
relation osmRelation = new relation();
object featureValue = DBNull.Value;
List<object> relationItems = new List<object>();
if (membersFieldIndex != -1)
{
member[] members = _osmUtility.retrieveMembers(currentRow, membersFieldIndex);
relationItems.AddRange(members);
}
if (osmIDFieldIndex != -1)
{
osmRelation.id = Convert.ToString(currentRow.get_Value(osmIDFieldIndex));
}
if (changesetIDFieldIndex != -1)
{
featureValue = currentRow.get_Value(changesetIDFieldIndex);
if (featureValue != DBNull.Value)
{
osmRelation.changeset = Convert.ToString(currentRow.get_Value(changesetIDFieldIndex));
}
}
if (osmVersionFieldIndex != -1)
{
featureValue = currentRow.get_Value(osmVersionFieldIndex);
if (featureValue != DBNull.Value)
{
osmRelation.version = Convert.ToString(featureValue);
}
}
if (userIDFieldIndex != -1)
{
featureValue = currentRow.get_Value(userIDFieldIndex);
if (featureValue != DBNull.Value)
{
osmRelation.uid = Convert.ToString(featureValue);
}
}
if (userNameFieldIndex != -1)
{
featureValue = currentRow.get_Value(userNameFieldIndex);
if (featureValue != DBNull.Value)
{
osmRelation.user = Convert.ToString(featureValue);
}
}
if (timeStampFieldIndex != -1)
{
featureValue = currentRow.get_Value(timeStampFieldIndex);
if (featureValue != DBNull.Value)
{
osmRelation.timestamp = Convert.ToDateTime(featureValue).ToUniversalTime().ToString("u");
}
}
if (visibleFieldIndex != -1)
{
featureValue = currentRow.get_Value(visibleFieldIndex);
if (featureValue != DBNull.Value)
{
osmRelation.visible = Convert.ToString(featureValue);
}
}
if (tagsFieldIndex > -1)
{
tag[] tags = null;
tags = _osmUtility.retrieveOSMTags((IRow)currentRow, tagsFieldIndex, featureWorkspace);
// if the row is of type IFeature and a polygon then add the type=multipolygon tag
if (currentRow is IFeature)
{
IFeature currentFeature = currentRow as IFeature;
if (currentFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
{
tag mpTag = new tag();
mpTag.k = "type";
mpTag.v = "multipolygon";
relationItems.Add(mpTag);
}
}
if (tags.Length != 0)
{
relationItems.AddRange(tags);
}
}
// add all items (member and tags) to the relation element
osmRelation.Items = relationItems.ToArray();
return osmRelation;
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2007 Novell Inc., www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
// Authors:
// Thomas Wiest (twiest@novell.com)
// Rusty Howell (rhowell@novell.com)
//
// (C) Novell Inc.
using System;
using System.Collections;
using System.Text;
using System.Management.Internal.BaseDataTypes;
namespace System.Management.Internal
{
/// <summary>
/// Holds an collection of CimParameter objects
/// </summary>
internal class CimParameterValueList : BaseDataTypeList<CimParameterValue>
{
#region Constructors
/// <summary>
/// Creates a new CimParameterValueList with the given parameters
/// </summary>
/// <param name="items"></param>
public CimParameterValueList(params CimParameterValue[] items)
: base(items)
{
}
#endregion
#region Properties
/// <summary>
/// Gets a CimParameter based on the name
/// </summary>
/// <param name="name">Name of the CimParameter</param>
/// <returns>CimParameter or null if not found</returns>
public CimParameterValue this[CimName name]
{
get { return FindItem(name); }
}
#endregion
#region Methods
/// <summary>
/// Removes a CimParameter from the collection, based the the name
/// </summary>
/// <param name="name">Name of the parameter to remove</param>
public bool Remove(CimName name)
{
CimParameterValue param = FindItem(name);
if (param != null)
{
items.Remove(param);
return true;
}
return false;
}
private CimParameterValue FindItem(CimName name)
{
//use predicates to optimize?
foreach (CimParameterValue curParam in items)
{
if (curParam.Name == name)
return curParam;
}
return null;
}
#region Equals, operator== , operator!=
public override bool Equals(object obj)
{
if ((obj == null) || !(obj is CimParameterValueList))
{
return false;
}
return (this == (CimParameterValueList)obj);
}
/// <summary>
/// Shallow compare two CimPropertyLists
/// </summary>
/// <param name="list1"></param>
/// <param name="list2"></param>
/// <returns>Returns true if both lists have the same elements with the same names</returns>
public static bool operator ==(CimParameterValueList list1, CimParameterValueList list2)
{
if (((object)list1 == null) || ((object)list2 == null))
{
if (((object)list1 == null) && ((object)list2 == null))
{
return true;
}
return false;
}
if (list1.Count != list2.Count)
return false;
//check that all A's exist are in B
//Changed for MONO
for (int i = 0; i < list1.Count; ++i)
{
if (list2.FindItem(list1[i].Name) == null)
return false;
}
//check that all B's exist in A
for (int i = 0; i < list2.Count; ++i)
{
if (list1.FindItem(list2[i].Name) == null)
return false;
}
return true;
}
/// <summary>
/// Shallow compare of two CimPropertyLists
/// </summary>
/// <param name="list1"></param>
/// <param name="list2"></param>
/// <returns>Returns true if the lists do not have the same elements</returns>
public static bool operator !=(CimParameterValueList list1, CimParameterValueList list2)
{
return !(list1 == list2);
}
#endregion
#region Operator <,>,<=,>=
/* I don't think <,> are necessary...
/// <summary>
/// Determines whether a list is a subset of another list (shallow compare)
/// </summary>
/// <param name="list1">Subset list</param>
/// <param name="list2">Superset list</param>
/// <returns>Returns true if list1 is a subset of list2</returns>
public static bool operator <(CimParameterList list1, CimParameterList list2)
{
if (!(list1 <= list2))
return false;
//list1 is a subset of list2
return !(list1 == list2);//return true if the two lists are not equal
}
/// <summary>
/// Determines whether a list is a superset of another list (shallow compare)
/// </summary>
/// <param name="list1">Superset list</param>
/// <param name="list2">subset list</param>
/// <returns>Returns true if list1 is a superset of list2</returns>
public static bool operator >(CimParameterList list1, CimParameterList list2)
{
return (list2 < list1);
}
* */
/// <summary>
/// Determines whether a list is a subset of another list (shallow compare)
/// </summary>
/// <param name="list1">Superset list</param>
/// <param name="list2">subset list</param>
/// <returns>Returns true if list1 is a superset of list2</returns>
public static bool operator <=(CimParameterValueList list1, CimParameterValueList list2)
{
//return ((list1 < list2) || (list1 == list2));
if (((object)list1 == null) || ((object)list2 == null))
{
if (((object)list1 == null) && ((object)list2 == null))
{
return true;
}
return false;
}
if (list1.Count > list2.Count)
return false;
//Changed for MONO
for(int i = 0; i < list1.Count; ++i)
{
if (list2.FindItem(list1[i].Name) == null)
return false;
}
return true;
}
/// <summary>
/// Determines whether a list is a superset of another list (shallow compare)
/// </summary>
/// <param name="list1">Superset list</param>
/// <param name="list2">subset list</param>
/// <returns>Returns true if list1 is a superset of list2</returns>
public static bool operator >=(CimParameterValueList list1, CimParameterValueList list2)
{
return (list2 <= list1);
}
#endregion
/// <summary>
/// Performes a deep compare of two CimPropertyLists
/// </summary>
/// <param name="list">CimPropertyList to compare</param>
/// <returns>Returns true if the lists have the same properties and values</returns>
public bool IsEqualTo(CimParameterValueList list)
{
if (this != list)//do shallow compare first
return false;
//Changed for MONO
for (int i = 0; i < this.Count; i++)
{
CimParameterValue p = list.FindItem(this[i].Name);
if ((p == null) || (p != this[i]))
return false;
}
return true;
}
#endregion
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using System.Threading;
using MindTouch.Dream;
using MindTouch.Dream.Test;
using MindTouch.Extensions.Time;
using MindTouch.Tasking;
using MindTouch.Xml;
using NUnit.Framework;
namespace MindTouch.Deki.Tests.ChangeSubscriptionTests {
[TestFixture]
public class DekiChangeSubscriptionExtTests {
private static readonly log4net.ILog _log = LogUtils.CreateLog();
private Plug _pageSub;
private Plug _adminPlug;
private Plug _pageSubscriberPlug;
private string _userId;
[TestFixtureSetUp]
public void GlobalInit() {
_adminPlug = Utils.BuildPlugForAdmin();
_log.DebugFormat("admin plug: {0}", _adminPlug.Uri.ToString());
_userId = null;
string subscriber = null;
UserUtils.CreateRandomContributor(_adminPlug, out _userId, out subscriber);
_log.DebugFormat("created contributor {0} ({1})", subscriber, _userId);
_pageSubscriberPlug = Utils.BuildPlugForUser(subscriber);
_log.DebugFormat("subscriber plug: {0}", _pageSubscriberPlug.Uri.ToString());
_pageSub = _pageSubscriberPlug.At("pagesubservice");
DreamMessage response = PageUtils.CreateRandomPage(_adminPlug);
Assert.IsTrue(response.IsSuccessful);
}
[TearDown]
public void PerTestTearDown() {
MockPlug.DeregisterAll();
}
[Test]
public void Create_view_remove_subscription() {
string id;
string path;
DreamMessage response = PageUtils.CreateRandomPage(_adminPlug, out id, out path);
Assert.IsTrue(response.IsSuccessful);
// let the page create event bubble through
Thread.Sleep(1000);
_log.DebugFormat("post single page subscription: {0}", id);
response = _pageSub.At("pages", id).WithHeader("X-Deki-Site", "id=default").PostAsync().Wait();
Assert.IsTrue(response.IsSuccessful);
_log.Debug("get subscription");
response = _pageSub.At("subscriptions").With("pages", id).WithHeader("X-Deki-Site", "id=default").GetAsync().Wait();
Assert.IsTrue(response.IsSuccessful);
XDoc subscription = response.ToDocument()["subscription.page"];
Assert.AreEqual(1, subscription.ListLength);
Assert.AreEqual("0", subscription["@depth"].AsText);
_log.Debug("post page tree subscription");
response = _pageSub.At("pages", id).With("depth", "infinity").WithHeader("X-Deki-Site", "id=default").PostAsync().Wait();
Assert.IsTrue(response.IsSuccessful);
_log.Debug("get subscription");
response = _pageSub.At("subscriptions").With("pages", id).WithHeader("X-Deki-Site", "id=default").GetAsync().Wait();
Assert.IsTrue(response.IsSuccessful);
subscription = response.ToDocument()["subscription.page"];
Assert.AreEqual(1, subscription.ListLength);
Assert.AreEqual("infinity", subscription["@depth"].AsText);
_log.Debug("remove subscription");
response = _pageSub.At("pages", id).WithHeader("X-Deki-Site", "id=default").DeleteAsync().Wait();
Assert.IsTrue(response.IsSuccessful);
_log.Debug("get subscription");
response = _pageSub.At("subscriptions").With("pages", id).WithHeader("X-Deki-Site", "id=default").GetAsync().Wait();
Assert.IsTrue(response.IsSuccessful);
Assert.IsTrue(response.ToDocument()["subscription.page"].IsEmpty, response.AsText());
}
[Test]
public void Subscribe_and_see_page_change_dispatched() {
XDoc set = null, sub = null;
_log.Debug("start: Subscribe_and_see_page_change_dispatched");
var emailResetEvent = new ManualResetEvent(false);
// subscribe to dekipubsub, so we can verify page creation event has passed
XUri coreSubscriber = new XUri("http://mock/dekisubscriber");
var createdPages = new HashSet<string>();
var modifiedPages = new HashSet<string>();
MockPlug.Register(coreSubscriber, delegate(Plug p, string v, XUri u, DreamMessage r, Result<DreamMessage> r2) {
var doc = r.ToDocument();
var channel = doc["channel"].AsUri;
var pId = doc["pageid"].AsText;
_log.DebugFormat("dekisubscriber called called with channel '{0}' for page {1}", channel, pId);
if(channel.LastSegment == "create") {
lock(createdPages) {
createdPages.Add(pId);
}
} else if(channel.LastSegment == "update") {
lock(modifiedPages) {
modifiedPages.Add(pId);
}
} else {
_log.Info("wrong channel!");
}
r2.Return(DreamMessage.Ok());
});
XDoc subscriptionSet = new XDoc("subscription-set")
.Elem("uri.owner", coreSubscriber)
.Start("subscription")
.Elem("channel", "event://*/deki/pages/*")
.Start("recipient")
.Attr("authtoken", Utils.Settings.HostInfo.ApiKey)
.Elem("uri", coreSubscriber)
.End()
.End();
var subscriptionResult = Utils.Settings.HostInfo.LocalHost.At("deki", "pubsub", "subscribers").With("apikey", Utils.Settings.HostInfo.ApiKey).PostAsync(subscriptionSet).Wait();
Assert.IsTrue(subscriptionResult.IsSuccessful);
_log.DebugFormat("check for subscription in combined set");
Assert.IsTrue(Wait.For(() => {
set = Utils.Settings.HostInfo.LocalHost.At("deki", "pubsub", "subscribers").With("apikey", Utils.Settings.HostInfo.ApiKey).Get(new Result<XDoc>()).Wait();
sub = set["subscription[channel='event://*/deki/pages/*']"];
return sub["recipient/uri"].Contents == coreSubscriber.ToString();
}, 10.Seconds()));
int emailerCalled = 0;
XDoc emailDoc = null;
DreamMessage response;
string pageId;
string pagePath;
// create a page
_log.DebugFormat("creating page");
response = PageUtils.CreateRandomPage(_adminPlug, out pageId, out pagePath);
Assert.IsTrue(response.IsSuccessful);
//give the page creation event a chance to bubble through
_log.DebugFormat("checking for page {0} creation event", pageId);
Assert.IsTrue(Wait.For(() => {
Thread.Sleep(100);
lock(createdPages) {
return createdPages.Contains(pageId);
}
}, 10.Seconds()));
_log.DebugFormat("got create event");
_log.DebugFormat("post page subscription for page {0}", pageId);
response = _pageSub.At("pages", pageId).With("depth", "0").WithHeader("X-Deki-Site", "id=default").PostAsFormAsync().Wait();
Assert.IsTrue(response.IsSuccessful);
//give the sub a chance to propagate
Assert.IsTrue(Wait.For(() => {
set = Utils.Settings.HostInfo.LocalHost.At("deki", "pubsub", "subscribers").With("apikey", Utils.Settings.HostInfo.ApiKey).Get(new Result<XDoc>()).Wait();
sub = set[string.Format("subscription[channel='event://default/deki/pages/update' and recipient/@userid='{0}' and uri.resource='deki://default/pages/{1}#depth%3d0']", _userId, pageId)];
return sub.ListLength > 0;
}, 10.Seconds()), set.ToPrettyString());
XUri emailerEndpoint = Utils.Settings.HostInfo.Host.LocalMachineUri.At("deki", "mailer");
MockPlug.Register(emailerEndpoint, delegate(Plug p, string v, XUri u, DreamMessage r, Result<DreamMessage> r2) {
_log.Debug("emailer called");
emailerCalled++;
emailDoc = r.ToDocument();
emailResetEvent.Set();
r2.Return(DreamMessage.Ok());
});
_log.Debug("mod page");
modifiedPages.Clear();
response = PageUtils.SavePage(Utils.BuildPlugForAdmin(), pagePath, "foo");
Assert.IsTrue(response.IsSuccessful);
_log.DebugFormat("checking for page {0} update event", pageId);
Assert.IsTrue(Wait.For(() => {
Thread.Sleep(100);
lock(modifiedPages) {
return modifiedPages.Contains(pageId);
}
}, 10.Seconds()));
_log.DebugFormat("got update event");
_log.Debug("making sure change sub service is still subscribed");
set = Utils.Settings.HostInfo.LocalHost.At("deki", "pubsub", "subscribers").With("apikey", Utils.Settings.HostInfo.ApiKey).Get(new Result<XDoc>()).Wait();
sub = set[string.Format("subscription[channel='event://default/deki/pages/update' and recipient/@userid='{0}' and uri.resource='deki://default/pages/{1}#depth%3d0']", _userId, pageId)];
Assert.IsTrue(sub.ListLength > 0, set.ToPrettyString());
_log.Debug("waiting on email post");
Assert.IsTrue(Wait.For(() => emailResetEvent.WaitOne(100, true), 10.Seconds()));
_log.Debug("email fired");
Assert.IsFalse(emailDoc.IsEmpty);
Assert.AreEqual(pageId, emailDoc["pages/pageid"].AsText);
Thread.Sleep(200);
Assert.AreEqual(1, emailerCalled);
}
}
}
| |
using Lucene.Net.Support;
using Lucene.Net.Util;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IBits = Lucene.Net.Util.IBits;
using Codec = Lucene.Net.Codecs.Codec;
using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory;
using Directory = Lucene.Net.Store.Directory;
using DocValuesFormat = Lucene.Net.Codecs.DocValuesFormat;
using DocValuesProducer = Lucene.Net.Codecs.DocValuesProducer;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using StoredFieldsReader = Lucene.Net.Codecs.StoredFieldsReader;
using TermVectorsReader = Lucene.Net.Codecs.TermVectorsReader;
/// <summary>
/// <see cref="IndexReader"/> implementation over a single segment.
/// <para/>
/// Instances pointing to the same segment (but with different deletes, etc)
/// may share the same core data.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class SegmentReader : AtomicReader
{
private readonly SegmentCommitInfo si;
private readonly IBits liveDocs;
// Normally set to si.docCount - si.delDocCount, unless we
// were created as an NRT reader from IW, in which case IW
// tells us the docCount:
private readonly int numDocs;
internal readonly SegmentCoreReaders core;
internal readonly SegmentDocValues segDocValues;
internal readonly DisposableThreadLocal<IDictionary<string, object>> docValuesLocal = new DisposableThreadLocalAnonymousInnerClassHelper();
private class DisposableThreadLocalAnonymousInnerClassHelper : DisposableThreadLocal<IDictionary<string, object>>
{
public DisposableThreadLocalAnonymousInnerClassHelper()
{
}
protected internal override IDictionary<string, object> InitialValue()
{
return new Dictionary<string, object>();
}
}
internal readonly DisposableThreadLocal<IDictionary<string, IBits>> docsWithFieldLocal = new DisposableThreadLocalAnonymousInnerClassHelper2();
private class DisposableThreadLocalAnonymousInnerClassHelper2 : DisposableThreadLocal<IDictionary<string, IBits>>
{
public DisposableThreadLocalAnonymousInnerClassHelper2()
{
}
protected internal override IDictionary<string, IBits> InitialValue()
{
return new Dictionary<string, IBits>();
}
}
internal readonly IDictionary<string, DocValuesProducer> dvProducersByField = new Dictionary<string, DocValuesProducer>();
internal readonly ISet<DocValuesProducer> dvProducers = new IdentityHashSet<DocValuesProducer>();
private readonly FieldInfos fieldInfos; // LUCENENET specific - since it is readonly, made all internal classes use property
private readonly IList<long?> dvGens = new List<long?>();
/// <summary>
/// Constructs a new <see cref="SegmentReader"/> with a new core. </summary>
/// <exception cref="CorruptIndexException"> if the index is corrupt </exception>
/// <exception cref="System.IO.IOException"> if there is a low-level IO error </exception>
// TODO: why is this public?
public SegmentReader(SegmentCommitInfo si, int termInfosIndexDivisor, IOContext context)
{
this.si = si;
// TODO if the segment uses CFS, we may open the CFS file twice: once for
// reading the FieldInfos (if they are not gen'd) and second time by
// SegmentCoreReaders. We can open the CFS here and pass to SCR, but then it
// results in less readable code (resource not closed where it was opened).
// Best if we could somehow read FieldInfos in SCR but not keep it there, but
// constructors don't allow returning two things...
fieldInfos = ReadFieldInfos(si);
core = new SegmentCoreReaders(this, si.Info.Dir, si, context, termInfosIndexDivisor);
segDocValues = new SegmentDocValues();
bool success = false;
Codec codec = si.Info.Codec;
try
{
if (si.HasDeletions)
{
// NOTE: the bitvector is stored using the regular directory, not cfs
liveDocs = codec.LiveDocsFormat.ReadLiveDocs(Directory, si, IOContext.READ_ONCE);
}
else
{
Debug.Assert(si.DelCount == 0);
liveDocs = null;
}
numDocs = si.Info.DocCount - si.DelCount;
if (FieldInfos.HasDocValues)
{
InitDocValuesProducers(codec);
}
success = true;
}
finally
{
// With lock-less commits, it's entirely possible (and
// fine) to hit a FileNotFound exception above. In
// this case, we want to explicitly close any subset
// of things that were opened so that we don't have to
// wait for a GC to do so.
if (!success)
{
DoClose();
}
}
}
/// <summary>
/// Create new <see cref="SegmentReader"/> sharing core from a previous
/// <see cref="SegmentReader"/> and loading new live docs from a new
/// deletes file. Used by <see cref="DirectoryReader.OpenIfChanged(DirectoryReader)"/>.
/// </summary>
internal SegmentReader(SegmentCommitInfo si, SegmentReader sr)
: this(si, sr, si.Info.Codec.LiveDocsFormat.ReadLiveDocs(si.Info.Dir, si, IOContext.READ_ONCE), si.Info.DocCount - si.DelCount)
{
}
/// <summary>
/// Create new <see cref="SegmentReader"/> sharing core from a previous
/// <see cref="SegmentReader"/> and using the provided in-memory
/// liveDocs. Used by <see cref="IndexWriter"/> to provide a new NRT
/// reader
/// </summary>
internal SegmentReader(SegmentCommitInfo si, SegmentReader sr, IBits liveDocs, int numDocs)
{
this.si = si;
this.liveDocs = liveDocs;
this.numDocs = numDocs;
this.core = sr.core;
core.IncRef();
this.segDocValues = sr.segDocValues;
// System.out.println("[" + Thread.currentThread().getName() + "] SR.init: sharing reader: " + sr + " for gens=" + sr.genDVProducers.keySet());
// increment refCount of DocValuesProducers that are used by this reader
bool success = false;
try
{
Codec codec = si.Info.Codec;
if (si.FieldInfosGen == -1)
{
fieldInfos = sr.FieldInfos;
}
else
{
fieldInfos = ReadFieldInfos(si);
}
if (FieldInfos.HasDocValues)
{
InitDocValuesProducers(codec);
}
success = true;
}
finally
{
if (!success)
{
DoClose();
}
}
}
// initialize the per-field DocValuesProducer
private void InitDocValuesProducers(Codec codec)
{
Directory dir = core.cfsReader != null ? core.cfsReader : si.Info.Dir;
DocValuesFormat dvFormat = codec.DocValuesFormat;
IDictionary<long?, IList<FieldInfo>> genInfos = GetGenInfos();
// System.out.println("[" + Thread.currentThread().getName() + "] SR.initDocValuesProducers: segInfo=" + si + "; gens=" + genInfos.keySet());
// TODO: can we avoid iterating over fieldinfos several times and creating maps of all this stuff if dv updates do not exist?
foreach (KeyValuePair<long?, IList<FieldInfo>> e in genInfos)
{
long? gen = e.Key;
IList<FieldInfo> infos = e.Value;
DocValuesProducer dvp = segDocValues.GetDocValuesProducer(gen, si, IOContext.READ, dir, dvFormat, infos, TermInfosIndexDivisor);
foreach (FieldInfo fi in infos)
{
dvProducersByField[fi.Name] = dvp;
dvProducers.Add(dvp);
}
}
dvGens.AddRange(genInfos.Keys);
}
/// <summary>
/// Reads the most recent <see cref="Index.FieldInfos"/> of the given segment info.
/// <para/>
/// @lucene.internal
/// </summary>
internal static FieldInfos ReadFieldInfos(SegmentCommitInfo info)
{
Directory dir;
bool closeDir;
if (info.FieldInfosGen == -1 && info.Info.UseCompoundFile)
{
// no fieldInfos gen and segment uses a compound file
dir = new CompoundFileDirectory(info.Info.Dir, IndexFileNames.SegmentFileName(info.Info.Name, "", IndexFileNames.COMPOUND_FILE_EXTENSION), IOContext.READ_ONCE, false);
closeDir = true;
}
else
{
// gen'd FIS are read outside CFS, or the segment doesn't use a compound file
dir = info.Info.Dir;
closeDir = false;
}
try
{
string segmentSuffix = info.FieldInfosGen == -1 ? "" : info.FieldInfosGen.ToString(CultureInfo.InvariantCulture);//Convert.ToString(info.FieldInfosGen, Character.MAX_RADIX));
return info.Info.Codec.FieldInfosFormat.FieldInfosReader.Read(dir, info.Info.Name, segmentSuffix, IOContext.READ_ONCE);
}
finally
{
if (closeDir)
{
dir.Dispose();
}
}
}
// returns a gen->List<FieldInfo> mapping. Fields without DV updates have gen=-1
private IDictionary<long?, IList<FieldInfo>> GetGenInfos()
{
IDictionary<long?, IList<FieldInfo>> genInfos = new Dictionary<long?, IList<FieldInfo>>();
foreach (FieldInfo fi in FieldInfos)
{
if (fi.DocValuesType == DocValuesType.NONE)
{
continue;
}
long gen = fi.DocValuesGen;
IList<FieldInfo> infos;
genInfos.TryGetValue(gen, out infos);
if (infos == null)
{
infos = new List<FieldInfo>();
genInfos[gen] = infos;
}
infos.Add(fi);
}
return genInfos;
}
public override IBits LiveDocs
{
get
{
EnsureOpen();
return liveDocs;
}
}
protected internal override void DoClose()
{
//System.out.println("SR.close seg=" + si);
try
{
core.DecRef();
}
finally
{
dvProducersByField.Clear();
try
{
IOUtils.Dispose(docValuesLocal, docsWithFieldLocal);
}
finally
{
segDocValues.DecRef(dvGens);
}
}
}
public override FieldInfos FieldInfos
{
get
{
EnsureOpen();
return fieldInfos;
}
}
/// <summary>
/// Expert: retrieve thread-private
/// <see cref="StoredFieldsReader"/>
/// <para/>
/// @lucene.internal
/// </summary>
public StoredFieldsReader FieldsReader
{
get
{
EnsureOpen();
return core.fieldsReaderLocal.Get();
}
}
public override void Document(int docID, StoredFieldVisitor visitor)
{
CheckBounds(docID);
FieldsReader.VisitDocument(docID, visitor);
}
public override Fields Fields
{
get
{
EnsureOpen();
return core.fields;
}
}
public override int NumDocs
{
get
{
// Don't call ensureOpen() here (it could affect performance)
return numDocs;
}
}
public override int MaxDoc
{
get
{
// Don't call ensureOpen() here (it could affect performance)
return si.Info.DocCount;
}
}
/// <summary>
/// Expert: retrieve thread-private
/// <see cref="Codecs.TermVectorsReader"/>
/// <para/>
/// @lucene.internal
/// </summary>
public TermVectorsReader TermVectorsReader
{
get
{
EnsureOpen();
return core.termVectorsLocal.Get();
}
}
public override Fields GetTermVectors(int docID)
{
TermVectorsReader termVectorsReader = TermVectorsReader;
if (termVectorsReader == null)
{
return null;
}
CheckBounds(docID);
return termVectorsReader.Get(docID);
}
private void CheckBounds(int docID)
{
if (docID < 0 || docID >= MaxDoc)
{
throw new System.IndexOutOfRangeException("docID must be >= 0 and < maxDoc=" + MaxDoc + " (got docID=" + docID + ")");
}
}
public override string ToString()
{
// SegmentInfo.toString takes dir and number of
// *pending* deletions; so we reverse compute that here:
return si.ToString(si.Info.Dir, si.Info.DocCount - numDocs - si.DelCount);
}
/// <summary>
/// Return the name of the segment this reader is reading.
/// </summary>
public string SegmentName
{
get
{
return si.Info.Name;
}
}
/// <summary>
/// Return the <see cref="SegmentCommitInfo"/> of the segment this reader is reading.
/// </summary>
public SegmentCommitInfo SegmentInfo
{
get
{
return si;
}
}
/// <summary>
/// Returns the directory this index resides in. </summary>
public Directory Directory
{
get
{
// Don't ensureOpen here -- in certain cases, when a
// cloned/reopened reader needs to commit, it may call
// this method on the closed original reader
return si.Info.Dir;
}
}
// this is necessary so that cloned SegmentReaders (which
// share the underlying postings data) will map to the
// same entry in the FieldCache. See LUCENE-1579.
public override object CoreCacheKey
{
get
{
// NOTE: if this ever changes, be sure to fix
// SegmentCoreReader.notifyCoreClosedListeners to match!
// Today it passes "this" as its coreCacheKey:
return core;
}
}
public override object CombinedCoreAndDeletesKey
{
get
{
return this;
}
}
/// <summary>
/// Returns term infos index divisor originally passed to
/// <see cref="SegmentReader(SegmentCommitInfo, int, IOContext)"/>.
/// </summary>
public int TermInfosIndexDivisor
{
get
{
return core.termsIndexDivisor;
}
}
// returns the FieldInfo that corresponds to the given field and type, or
// null if the field does not exist, or not indexed as the requested
// DovDocValuesType.
private FieldInfo GetDVField(string field, DocValuesType type)
{
FieldInfo fi = FieldInfos.FieldInfo(field);
if (fi == null)
{
// Field does not exist
return null;
}
if (fi.DocValuesType == DocValuesType.NONE)
{
// Field was not indexed with doc values
return null;
}
if (fi.DocValuesType != type)
{
// Field DocValues are different than requested type
return null;
}
return fi;
}
public override NumericDocValues GetNumericDocValues(string field)
{
EnsureOpen();
FieldInfo fi = GetDVField(field, DocValuesType.NUMERIC);
if (fi == null)
{
return null;
}
IDictionary<string, object> dvFields = docValuesLocal.Get();
NumericDocValues dvs;
object dvsDummy;
dvFields.TryGetValue(field, out dvsDummy);
dvs = (NumericDocValues)dvsDummy;
if (dvs == null)
{
DocValuesProducer dvProducer;
dvProducersByField.TryGetValue(field, out dvProducer);
Debug.Assert(dvProducer != null);
dvs = dvProducer.GetNumeric(fi);
dvFields[field] = dvs;
}
return dvs;
}
public override IBits GetDocsWithField(string field)
{
EnsureOpen();
FieldInfo fi = FieldInfos.FieldInfo(field);
if (fi == null)
{
// Field does not exist
return null;
}
if (fi.DocValuesType == DocValuesType.NONE)
{
// Field was not indexed with doc values
return null;
}
IDictionary<string, IBits> dvFields = docsWithFieldLocal.Get();
IBits dvs;
dvFields.TryGetValue(field, out dvs);
if (dvs == null)
{
DocValuesProducer dvProducer;
dvProducersByField.TryGetValue(field, out dvProducer);
Debug.Assert(dvProducer != null);
dvs = dvProducer.GetDocsWithField(fi);
dvFields[field] = dvs;
}
return dvs;
}
public override BinaryDocValues GetBinaryDocValues(string field)
{
EnsureOpen();
FieldInfo fi = GetDVField(field, DocValuesType.BINARY);
if (fi == null)
{
return null;
}
IDictionary<string, object> dvFields = docValuesLocal.Get();
object ret;
BinaryDocValues dvs;
dvFields.TryGetValue(field, out ret);
dvs = (BinaryDocValues)ret;
if (dvs == null)
{
DocValuesProducer dvProducer;
dvProducersByField.TryGetValue(field, out dvProducer);
Debug.Assert(dvProducer != null);
dvs = dvProducer.GetBinary(fi);
dvFields[field] = dvs;
}
return dvs;
}
public override SortedDocValues GetSortedDocValues(string field)
{
EnsureOpen();
FieldInfo fi = GetDVField(field, DocValuesType.SORTED);
if (fi == null)
{
return null;
}
IDictionary<string, object> dvFields = docValuesLocal.Get();
SortedDocValues dvs;
object ret;
dvFields.TryGetValue(field, out ret);
dvs = (SortedDocValues)ret;
if (dvs == null)
{
DocValuesProducer dvProducer;
dvProducersByField.TryGetValue(field, out dvProducer);
Debug.Assert(dvProducer != null);
dvs = dvProducer.GetSorted(fi);
dvFields[field] = dvs;
}
return dvs;
}
public override SortedSetDocValues GetSortedSetDocValues(string field)
{
EnsureOpen();
FieldInfo fi = GetDVField(field, DocValuesType.SORTED_SET);
if (fi == null)
{
return null;
}
IDictionary<string, object> dvFields = docValuesLocal.Get();
object ret;
SortedSetDocValues dvs;
dvFields.TryGetValue(field, out ret);
dvs = (SortedSetDocValues)ret;
if (dvs == null)
{
DocValuesProducer dvProducer;
dvProducersByField.TryGetValue(field, out dvProducer);
Debug.Assert(dvProducer != null);
dvs = dvProducer.GetSortedSet(fi);
dvFields[field] = dvs;
}
return dvs;
}
public override NumericDocValues GetNormValues(string field)
{
EnsureOpen();
FieldInfo fi = FieldInfos.FieldInfo(field);
if (fi == null || !fi.HasNorms)
{
// Field does not exist or does not index norms
return null;
}
return core.GetNormValues(fi);
}
/// <summary>
/// Called when the shared core for this <see cref="SegmentReader"/>
/// is disposed.
/// <para/>
/// This listener is called only once all <see cref="SegmentReader"/>s
/// sharing the same core are disposed. At this point it
/// is safe for apps to evict this reader from any caches
/// keyed on <see cref="CoreCacheKey"/>. This is the same
/// interface that <see cref="Search.IFieldCache"/> uses, internally,
/// to evict entries.
/// <para/>
/// NOTE: This was CoreClosedListener in Lucene.
/// <para/>
/// @lucene.experimental
/// </summary>
public interface ICoreDisposedListener
{
/// <summary>
/// Invoked when the shared core of the original
/// <see cref="SegmentReader"/> has disposed.
/// </summary>
void OnDispose(object ownerCoreCacheKey);
}
/// <summary>
/// Expert: adds a <see cref="ICoreDisposedListener"/> to this reader's shared core </summary>
public void AddCoreDisposedListener(ICoreDisposedListener listener)
{
EnsureOpen();
core.AddCoreDisposedListener(listener);
}
/// <summary>
/// Expert: removes a <see cref="ICoreDisposedListener"/> from this reader's shared core </summary>
public void RemoveCoreDisposedListener(ICoreDisposedListener listener)
{
EnsureOpen();
core.RemoveCoreDisposedListener(listener);
}
/// <summary>
/// Returns approximate RAM Bytes used </summary>
public long RamBytesUsed()
{
EnsureOpen();
long ramBytesUsed = 0;
if (dvProducers != null)
{
foreach (DocValuesProducer producer in dvProducers)
{
ramBytesUsed += producer.RamBytesUsed();
}
}
if (core != null)
{
ramBytesUsed += core.RamBytesUsed();
}
return ramBytesUsed;
}
public override void CheckIntegrity()
{
EnsureOpen();
// stored fields
FieldsReader.CheckIntegrity();
// term vectors
TermVectorsReader termVectorsReader = TermVectorsReader;
if (termVectorsReader != null)
{
termVectorsReader.CheckIntegrity();
}
// terms/postings
if (core.fields != null)
{
core.fields.CheckIntegrity();
}
// norms
if (core.normsProducer != null)
{
core.normsProducer.CheckIntegrity();
}
// docvalues
if (dvProducers != null)
{
foreach (DocValuesProducer producer in dvProducers)
{
producer.CheckIntegrity();
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
public static class PathTests
{
[Theory]
[InlineData(null, null, null)]
[InlineData(null, null, "exe")]
[InlineData("", "", "")]
[InlineData("file", "file.exe", null)]
[InlineData("file.", "file.exe", "")]
[InlineData("file.exe", "file", "exe")]
[InlineData("file.exe", "file", ".exe")]
[InlineData("file.exe", "file.txt", "exe")]
[InlineData("file.exe", "file.txt", ".exe")]
[InlineData("file.txt.exe", "file.txt.bin", "exe")]
[InlineData("dir/file.exe", "dir/file.t", "exe")]
[InlineData("dir/file.t", "dir/file.exe", "t")]
[InlineData("dir/file.exe", "dir/file", "exe")]
public static void ChangeExtension(string expected, string path, string newExtension)
{
if (expected != null)
expected = expected.Replace('/', Path.DirectorySeparatorChar);
if (path != null)
path = path.Replace('/', Path.DirectorySeparatorChar);
Assert.Equal(expected, Path.ChangeExtension(path, newExtension));
}
[Theory,
InlineData(null, null),
InlineData(@"", null),
InlineData(@".", @""),
InlineData(@"..", @""),
InlineData(@"baz", @"")
]
public static void GetDirectoryName(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Theory,
InlineData(@"dir/baz", @"dir"),
InlineData(@"dir\baz", @"dir"),
InlineData(@"dir\baz\bar", @"dir\baz"),
InlineData(@"dir\\baz", @"dir"),
InlineData(@" dir\baz", @" dir"),
InlineData(@" C:\dir\baz", @"C:\dir"),
InlineData(@"..\..\files.txt", @"..\..")
]
[PlatformSpecific(PlatformID.Windows)]
public static void GetDirectoryName_Windows(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Theory,
InlineData(@"dir/baz", @"dir"),
InlineData(@"dir//baz", @"dir"),
InlineData(@"dir\baz", @""),
InlineData(@"dir/baz/bar", @"dir/baz"),
InlineData(@"../../files.txt", @"../..")
]
[PlatformSpecific(PlatformID.AnyUnix)]
public static void GetDirectoryName_Unix(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Fact]
public static void GetDirectoryName_CurrentDirectory()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal(curDir, Path.GetDirectoryName(Path.Combine(curDir, "baz")));
Assert.Equal(null, Path.GetDirectoryName(Path.GetPathRoot(curDir)));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetDirectoryName_ControlCharacters_Unix()
{
Assert.Equal(new string('\t', 1), Path.GetDirectoryName(Path.Combine(new string('\t', 1), "file")));
Assert.Equal(new string('\b', 2), Path.GetDirectoryName(Path.Combine(new string('\b', 2), "fi le")));
Assert.Equal(new string('\v', 3), Path.GetDirectoryName(Path.Combine(new string('\v', 3), "fi\nle")));
Assert.Equal(new string('\n', 4), Path.GetDirectoryName(Path.Combine(new string('\n', 4), "fi\rle")));
}
[Theory]
[InlineData(".exe", "file.exe")]
[InlineData("", "file")]
[InlineData(null, null)]
[InlineData("", "file.")]
[InlineData(".s", "file.s")]
[InlineData("", "test/file")]
[InlineData(".extension", "test/file.extension")]
public static void GetExtension(string expected, string path)
{
if (path != null)
{
path = path.Replace('/', Path.DirectorySeparatorChar);
}
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData(".e xe", "file.e xe")]
[InlineData(". ", "file. ")]
[InlineData(". ", " file. ")]
[InlineData(".extension", " file.extension")]
[InlineData(".exten\tsion", "file.exten\tsion")]
public static void GetExtension_Unix(string expected, string path)
{
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
[Fact]
public static void GetFileName()
{
Assert.Equal(null, Path.GetFileName(null));
Assert.Equal(string.Empty, Path.GetFileName(string.Empty));
Assert.Equal(".", Path.GetFileName("."));
Assert.Equal("..", Path.GetFileName(".."));
Assert.Equal("file", Path.GetFileName("file"));
Assert.Equal("file.", Path.GetFileName("file."));
Assert.Equal("file.exe", Path.GetFileName("file.exe"));
Assert.Equal("file.exe", Path.GetFileName(Path.Combine("baz", "file.exe")));
Assert.Equal("file.exe", Path.GetFileName(Path.Combine("bar", "baz", "file.exe")));
Assert.Equal(string.Empty, Path.GetFileName(Path.Combine("bar", "baz") + Path.DirectorySeparatorChar));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetFileName_Unix()
{
Assert.Equal(" . ", Path.GetFileName(" . "));
Assert.Equal(" .. ", Path.GetFileName(" .. "));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName(Path.Combine("b \r\n ar", "fi le")));
}
[Fact]
public static void GetFileNameWithoutExtension()
{
Assert.Equal(null, Path.GetFileNameWithoutExtension(null));
Assert.Equal(string.Empty, Path.GetFileNameWithoutExtension(string.Empty));
Assert.Equal("file", Path.GetFileNameWithoutExtension("file"));
Assert.Equal("file", Path.GetFileNameWithoutExtension("file.exe"));
Assert.Equal("file", Path.GetFileNameWithoutExtension(Path.Combine("bar", "baz", "file.exe")));
Assert.Equal(string.Empty, Path.GetFileNameWithoutExtension(Path.Combine("bar", "baz") + Path.DirectorySeparatorChar));
}
[Fact]
public static void GetPathRoot()
{
Assert.Null(Path.GetPathRoot(null));
Assert.Equal(string.Empty, Path.GetPathRoot(string.Empty));
string cwd = Directory.GetCurrentDirectory();
Assert.Equal(cwd.Substring(0, cwd.IndexOf(Path.DirectorySeparatorChar) + 1), Path.GetPathRoot(cwd));
Assert.True(Path.IsPathRooted(cwd));
Assert.Equal(string.Empty, Path.GetPathRoot(@"file.exe"));
Assert.False(Path.IsPathRooted("file.exe"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\test\unc\path\to\something", @"\\test\unc")]
[InlineData(@"\\a\b\c\d\e", @"\\a\b")]
[InlineData(@"\\a\b\", @"\\a\b")]
[InlineData(@"\\a\b", @"\\a\b")]
[InlineData(@"\\test\unc", @"\\test\unc")]
[InlineData(@"\\?\UNC\test\unc\path\to\something", @"\\?\UNC\test\unc")]
[InlineData(@"\\?\UNC\test\unc", @"\\?\UNC\test\unc")]
[InlineData(@"\\?\UNC\a\b", @"\\?\UNC\a\b")]
[InlineData(@"\\?\UNC\a\b\", @"\\?\UNC\a\b")]
[InlineData(@"\\?\C:\foo\bar.txt", @"\\?\C:\")]
public static void GetPathRoot_Windows_UncAndExtended(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:", @"C:")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\\", @"C:\")]
[InlineData(@"C://", @"C:\")]
[InlineData(@"C:\foo", @"C:\")]
[InlineData(@"C:\\foo", @"C:\")]
[InlineData(@"C://foo", @"C:\")]
public static void GetPathRoot_Windows(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetPathRoot_Unix()
{
// slashes are normal filename characters
string uncPath = @"\\test\unc\path\to\something";
Assert.False(Path.IsPathRooted(uncPath));
Assert.Equal(string.Empty, Path.GetPathRoot(uncPath));
}
[Fact]
public static void GetRandomFileName()
{
char[] invalidChars = Path.GetInvalidFileNameChars();
var fileNames = new HashSet<string>();
for (int i = 0; i < 100; i++)
{
string s = Path.GetRandomFileName();
Assert.Equal(s.Length, 8 + 1 + 3);
Assert.Equal(s[8], '.');
Assert.Equal(-1, s.IndexOfAny(invalidChars));
Assert.True(fileNames.Add(s));
}
}
[Fact]
public static void GetInvalidPathChars()
{
Assert.NotNull(Path.GetInvalidPathChars());
Assert.NotSame(Path.GetInvalidPathChars(), Path.GetInvalidPathChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidPathChars(), (IEnumerable<char>)Path.GetInvalidPathChars());
Assert.True(Path.GetInvalidPathChars().Length > 0);
Assert.All(Path.GetInvalidPathChars(), c =>
{
string bad = c.ToString();
Assert.Throws<ArgumentException>(() => Path.ChangeExtension(bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine(bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine("ok", "ok", bad));
Assert.Throws<ArgumentException>(() => Path.Combine("ok", "ok", bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine(bad, bad, bad, bad, bad));
Assert.Throws<ArgumentException>(() => Path.GetDirectoryName(bad));
Assert.Throws<ArgumentException>(() => Path.GetExtension(bad));
Assert.Throws<ArgumentException>(() => Path.GetFileName(bad));
Assert.Throws<ArgumentException>(() => Path.GetFileNameWithoutExtension(bad));
Assert.Throws<ArgumentException>(() => Path.GetFullPath(bad));
Assert.Throws<ArgumentException>(() => Path.GetPathRoot(bad));
Assert.Throws<ArgumentException>(() => Path.IsPathRooted(bad));
});
}
[Fact]
public static void GetInvalidFileNameChars()
{
Assert.NotNull(Path.GetInvalidFileNameChars());
Assert.NotSame(Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.True(Path.GetInvalidFileNameChars().Length > 0);
}
[Fact]
[OuterLoop]
public static void GetInvalidFileNameChars_OtherCharsValid()
{
string curDir = Directory.GetCurrentDirectory();
var invalidChars = new HashSet<char>(Path.GetInvalidFileNameChars());
for (int i = 0; i < char.MaxValue; i++)
{
char c = (char)i;
if (!invalidChars.Contains(c))
{
string name = "file" + c + ".txt";
Assert.Equal(Path.Combine(curDir, name), Path.GetFullPath(name));
}
}
}
[Fact]
public static void GetTempPath_Default()
{
string tmpPath = Path.GetTempPath();
Assert.False(string.IsNullOrEmpty(tmpPath));
Assert.Equal(tmpPath, Path.GetTempPath());
Assert.Equal(Path.DirectorySeparatorChar, tmpPath[tmpPath.Length - 1]);
Assert.True(Directory.Exists(tmpPath));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp")]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp\")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\tmp\", @"C:\tmp")]
[InlineData(@"C:\tmp\", @"C:\tmp\")]
public static void GetTempPath_SetEnvVar_Windows(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMP", expected, newTempPath);
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData("/tmp/", "/tmp")]
[InlineData("/tmp/", "/tmp/")]
[InlineData("/", "/")]
[InlineData("/var/tmp/", "/var/tmp")]
[InlineData("/var/tmp/", "/var/tmp/")]
[InlineData("~/", "~")]
[InlineData("~/", "~/")]
[InlineData(".tmp/", ".tmp")]
[InlineData("./tmp/", "./tmp")]
[InlineData("/home/someuser/sometempdir/", "/home/someuser/sometempdir/")]
[InlineData("/home/someuser/some tempdir/", "/home/someuser/some tempdir/")]
[InlineData("/tmp/", null)]
public static void GetTempPath_SetEnvVar_Unix(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMPDIR", expected, newTempPath);
}
private static void GetTempPath_SetEnvVar(string envVar, string expected, string newTempPath)
{
string original = Path.GetTempPath();
Assert.NotNull(original);
try
{
Environment.SetEnvironmentVariable(envVar, newTempPath);
Assert.Equal(
Path.GetFullPath(expected),
Path.GetFullPath(Path.GetTempPath()));
}
finally
{
Environment.SetEnvironmentVariable(envVar, original);
Assert.Equal(original, Path.GetTempPath());
}
}
[Fact]
public static void GetTempFileName()
{
string tmpFile = Path.GetTempFileName();
try
{
Assert.True(File.Exists(tmpFile));
Assert.Equal(".tmp", Path.GetExtension(tmpFile), ignoreCase: true, ignoreLineEndingDifferences: false, ignoreWhiteSpaceDifferences: false);
Assert.Equal(-1, tmpFile.IndexOfAny(Path.GetInvalidPathChars()));
using (FileStream fs = File.OpenRead(tmpFile))
{
Assert.Equal(0, fs.Length);
}
Assert.Equal(Path.Combine(Path.GetTempPath(), Path.GetFileName(tmpFile)), tmpFile);
}
finally
{
File.Delete(tmpFile);
}
}
[Fact]
public static void GetFullPath_InvalidArgs()
{
Assert.Throws<ArgumentNullException>(() => Path.GetFullPath(null));
Assert.Throws<ArgumentException>(() => Path.GetFullPath(string.Empty));
}
[Fact]
public static void GetFullPath_BasicExpansions()
{
string curDir = Directory.GetCurrentDirectory();
// Current directory => current directory
Assert.Equal(curDir, Path.GetFullPath(curDir));
// "." => current directory
Assert.Equal(curDir, Path.GetFullPath("."));
// ".." => up a directory
Assert.Equal(Path.GetDirectoryName(curDir), Path.GetFullPath(".."));
// "dir/./././." => "dir"
Assert.Equal(curDir, Path.GetFullPath(Path.Combine(curDir, ".", ".", ".", ".", ".")));
// "dir///." => "dir"
Assert.Equal(curDir, Path.GetFullPath(curDir + new string(Path.DirectorySeparatorChar, 3) + "."));
// "dir/../dir/./../dir" => "dir"
Assert.Equal(curDir, Path.GetFullPath(Path.Combine(curDir, "..", Path.GetFileName(curDir), ".", "..", Path.GetFileName(curDir))));
// "C:\somedir\.." => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.Combine(Path.GetPathRoot(curDir), "somedir", "..")));
// "C:\." => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.Combine(Path.GetPathRoot(curDir), ".")));
// "C:\..\..\..\.." => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.Combine(Path.GetPathRoot(curDir), "..", "..", "..", "..")));
// "C:\\\" => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.GetPathRoot(curDir) + new string(Path.DirectorySeparatorChar, 3)));
// Path longer than MaxPath that normalizes down to less than MaxPath
const int Iters = 10000;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 2));
for (int i = 0; i < 10000; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('.');
}
Assert.Equal(curDir, Path.GetFullPath(longPath.ToString()));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetFullPath_Unix_Whitespace()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal("/ / ", Path.GetFullPath("/ // "));
Assert.Equal(Path.Combine(curDir, " "), Path.GetFullPath(" "));
Assert.Equal(Path.Combine(curDir, "\r\n"), Path.GetFullPath("\r\n"));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData("http://www.microsoft.com")]
[InlineData("file://somefile")]
public static void GetFullPath_Unix_URIsAsFileNames(string uriAsFileName)
{
// URIs are valid filenames, though the multiple slashes will be consolidated in GetFullPath
Assert.Equal(
Path.Combine(Directory.GetCurrentDirectory(), uriAsFileName.Replace("//", "/")),
Path.GetFullPath(uriAsFileName));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_NormalizedLongPathTooLong()
{
// Try out a long path that normalizes down to more than MaxPath
string curDir = Directory.GetCurrentDirectory();
const int Iters = 260;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 4));
for (int i = 0; i < Iters; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('a').Append(Path.DirectorySeparatorChar).Append('.');
}
// Now no longer throws unless over ~32K
Assert.NotNull(Path.GetFullPath(longPath.ToString()));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_AlternateDataStreamsNotSupported()
{
// Throws via our invalid colon filtering
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"bad:path"));
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"C:\some\bad:path"));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_URIFormatNotSupported()
{
// Throws via our invalid colon filtering
Assert.Throws<NotSupportedException>(() => Path.GetFullPath("http://www.microsoft.com"));
Assert.Throws<NotSupportedException>(() => Path.GetFullPath("file://www.microsoft.com"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\?\GLOBALROOT\")]
[InlineData(@"\\?\")]
[InlineData(@"\\?\.")]
[InlineData(@"\\?\..")]
[InlineData(@"\\?\\")]
[InlineData(@"\\?\C:\\")]
[InlineData(@"\\?\C:\|")]
[InlineData(@"\\?\C:\.")]
[InlineData(@"\\?\C:\..")]
[InlineData(@"\\?\C:\Foo\.")]
[InlineData(@"\\?\C:\Foo\..")]
public static void GetFullPath_Windows_ArgumentExceptionPaths(string path)
{
Assert.Throws<ArgumentException>(() => Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"bad::$DATA")]
[InlineData(@"C :")]
[InlineData(@"C :\somedir")]
public static void GetFullPath_Windows_NotSupportedExceptionPaths(string path)
{
// Many of these used to throw ArgumentException despite being documented as NotSupportedException
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:...")]
[InlineData(@"C:...\somedir")]
[InlineData(@"\.. .\")]
[InlineData(@"\. .\")]
[InlineData(@"\ .\")]
public static void GetFullPath_Windows_LegacyArgumentExceptionPaths(string path)
{
// These paths are legitimate Windows paths that can be created without extended syntax.
// We now allow them through.
Path.GetFullPath(path);
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_MaxPathNotTooLong()
{
// Shouldn't throw anymore
Path.GetFullPath(@"C:\" + new string('a', 255) + @"\");
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_PathTooLong()
{
Assert.Throws<PathTooLongException>(() => Path.GetFullPath(@"C:\" + new string('a', short.MaxValue) + @"\"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\.", @"C:\")]
[InlineData(@"C:\..", @"C:\")]
[InlineData(@"C:\..\..", @"C:\")]
[InlineData(@"C:\A\..", @"C:\")]
[InlineData(@"C:\..\..\A\..", @"C:\")]
public static void GetFullPath_Windows_RelativeRoot(string path, string expected)
{
Assert.Equal(Path.GetFullPath(path), expected);
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_StrangeButLegalPaths()
{
// These are legal and creatable without using extended syntax if you use a trailing slash
// (such as "md ...\"). We used to filter these out, but now allow them to prevent apps from
// being blocked when they hit these paths.
string curDir = Directory.GetCurrentDirectory();
Assert.NotEqual(
Path.GetFullPath(curDir + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar));
Assert.NotEqual(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar));
Assert.NotEqual(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\?\C:\ ")]
[InlineData(@"\\?\C:\ \ ")]
[InlineData(@"\\?\C:\ .")]
[InlineData(@"\\?\C:\ ..")]
[InlineData(@"\\?\C:\...")]
public static void GetFullPath_Windows_ValidExtendedPaths(string path)
{
Assert.Equal(path, Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\server\share", @"\\server\share")]
[InlineData(@"\\server\share", @" \\server\share")]
[InlineData(@"\\server\share\dir", @"\\server\share\dir")]
[InlineData(@"\\server\share", @"\\server\share\.")]
[InlineData(@"\\server\share", @"\\server\share\..")]
[InlineData(@"\\server\share\", @"\\server\share\ ")]
[InlineData(@"\\server\ share\", @"\\server\ share\")]
[InlineData(@"\\?\UNC\server\share", @"\\?\UNC\server\share")]
[InlineData(@"\\?\UNC\server\share\dir", @"\\?\UNC\server\share\dir")]
[InlineData(@"\\?\UNC\server\share\. ", @"\\?\UNC\server\share\. ")]
[InlineData(@"\\?\UNC\server\share\.. ", @"\\?\UNC\server\share\.. ")]
[InlineData(@"\\?\UNC\server\share\ ", @"\\?\UNC\server\share\ ")]
[InlineData(@"\\?\UNC\server\ share\", @"\\?\UNC\server\ share\")]
public static void GetFullPath_Windows_UNC_Valid(string expected, string input)
{
Assert.Equal(expected, Path.GetFullPath(input));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\")]
[InlineData(@"\\server")]
[InlineData(@"\\server\")]
[InlineData(@"\\server\\")]
[InlineData(@"\\server\..")]
[InlineData(@"\\?\UNC\")]
[InlineData(@"\\?\UNC\server")]
[InlineData(@"\\?\UNC\server\")]
[InlineData(@"\\?\UNC\server\\")]
[InlineData(@"\\?\UNC\server\..")]
[InlineData(@"\\?\UNC\server\share\.")]
[InlineData(@"\\?\UNC\server\share\..")]
[InlineData(@"\\?\UNC\a\b\\")]
public static void GetFullPath_Windows_UNC_Invalid(string invalidPath)
{
Assert.Throws<ArgumentException>(() => Path.GetFullPath(invalidPath));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_83Paths()
{
// Create a temporary file name with a name longer than 8.3 such that it'll need to be shortened.
string tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".txt");
File.Create(tempFilePath).Dispose();
try
{
// Get its short name
var sb = new StringBuilder(260);
if (GetShortPathName(tempFilePath, sb, sb.Capacity) > 0) // only proceed if we could successfully create the short name
{
// Make sure the shortened name expands back to the original one
Assert.Equal(tempFilePath, Path.GetFullPath(sb.ToString()));
// Validate case where short name doesn't expand to a real file
string invalidShortName = @"S:\DOESNT~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp";
Assert.Equal(invalidShortName, Path.GetFullPath(invalidShortName));
// Same thing, but with a long path that normalizes down to a short enough one
const int Iters = 1000;
var shortLongName = new StringBuilder(invalidShortName, invalidShortName.Length + (Iters * 2));
for (int i = 0; i < Iters; i++)
{
shortLongName.Append(Path.DirectorySeparatorChar).Append('.');
}
Assert.Equal(invalidShortName, Path.GetFullPath(shortLongName.ToString()));
}
}
finally
{
File.Delete(tempFilePath);
}
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData('*')]
[InlineData('?')]
public static void GetFullPath_Windows_Wildcards(char wildcard)
{
Assert.Throws<ArgumentException>("path", () => Path.GetFullPath("test" + wildcard + "ing"));
}
// Windows-only P/Invoke to create 8.3 short names from long names
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpedyc;
namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpei
{
/// <summary>
/// The server implementation of MS-RDPEI server.
/// </summary>
public class RdpeiServer
{
#region Private Variables
RdpedycServer rdpedycServer;
DynamicVirtualChannel rdpeiDVC;
List<RDPINPUT_PDU> receivedList;
const string rdpeiChannelName = "Microsoft::Windows::RDS::Input";
const int PacketsInterval = 100; // The interval in milliseconds between sending/receiving two packets.
uint rdpeiChannelId;
#endregion
#region Constructor
/// <summary>
/// Constructor of RdpeiServer
/// </summary>
public RdpeiServer(RdpedycServer edycServer)
{
receivedList = new List<RDPINPUT_PDU>();
rdpedycServer = edycServer;
}
#endregion
/// <summary>
/// Reset the RdpeiServer instance.
/// </summary>
public void Reset()
{
rdpedycServer = null;
rdpeiDVC = null;
receivedList.Clear();
}
#region Properties
/// <summary>
/// The dynamic virtual channel created for remote touch.
/// </summary>
public DynamicVirtualChannel RdpeiDVChannel
{
get
{
return rdpeiDVC;
}
}
#endregion
#region Public Methods
/// <summary>
/// Create dynamic virtual channel.
/// </summary>
/// <param name="transportType">selected transport type for created channels</param>
/// <param name="timeout">Timeout</param>
/// <returns>true if client supports this protocol; otherwise, return false.</returns>
public bool CreateRdpeiDvc(TimeSpan timeout, DynamicVC_TransportType transportType = DynamicVC_TransportType.RDP_TCP)
{
const ushort priority = 0;
try
{
rdpeiDVC = rdpedycServer.CreateChannel(timeout, priority, rdpeiChannelName, transportType, OnDataReceived);
rdpeiChannelId = rdpeiDVC.ChannelId;
}
catch
{
}
if (rdpeiDVC != null)
{
return true;
}
return false;
}
#endregion
#region Create Methods
/// <summary>
/// Method to create a RDPINPUT_SC_READY_PDU.
/// </summary>
/// <param name="eventId">A 16-bit unsigned integer that identifies the type of the input event PDU.</param>
/// <param name="pduLength">A 32-bit unsigned integer that specifies the length of the input event PDU in bytes.</param>
/// <param name="protocolVersion">A 32-bit unsigned integer that specifies the input protocol version.</param>
/// <returns>The created RDPINPUT_SC_READY_PDU.</returns>
public RDPINPUT_SC_READY_PDU CreateRdpInputScReadyPdu(EventId_Values eventId = EventId_Values.EVENTID_SC_READY, uint pduLength = 10, RDPINPUT_SC_READY_ProtocolVersion protocolVersion = RDPINPUT_SC_READY_ProtocolVersion.RDPINPUT_PROTOCOL_V100)
{
RDPINPUT_SC_READY_PDU pdu = new RDPINPUT_SC_READY_PDU();
pdu.header.eventId = eventId;
pdu.header.pduLength = pduLength;
pdu.protocolVersion = protocolVersion;
return pdu;
}
/// <summary>
/// Method to create a RDPINPUT_SUSPEND_TOUCH_PDU.
/// </summary>
/// <returns>The created RDPINPUT_SUSPEND_TOUCH_PDU.</returns>
public RDPINPUT_SUSPEND_TOUCH_PDU CreateRdpInputSuspendTouchPdu()
{
RDPINPUT_SUSPEND_TOUCH_PDU pdu = new RDPINPUT_SUSPEND_TOUCH_PDU();
pdu.header.eventId = EventId_Values.EVENTID_SUSPEND_TOUCH;
pdu.header.pduLength = pdu.Length();
return pdu;
}
/// <summary>
/// Method to create a RDPINPUT_RESUME_TOUCH_PDU.
/// </summary>
/// <returns>RDPINPUT_RESUME_TOUCH_PDU</returns>
public RDPINPUT_RESUME_TOUCH_PDU CreateRdpInputResumeTouchPdu()
{
RDPINPUT_RESUME_TOUCH_PDU pdu = new RDPINPUT_RESUME_TOUCH_PDU();
pdu.header.eventId = EventId_Values.EVENTID_RESUME_TOUCH;
pdu.header.pduLength = pdu.Length();
return pdu;
}
#endregion
#region Send Methods
/// <summary>
/// Method to send a RDPINPUT_SC_READY_PDU to client.
/// </summary>
/// <param name="pdu">A RDPINPUT_SC_READY_PDU structure.</param>
public void SendRdpInputScReadyPdu(RDPINPUT_SC_READY_PDU pdu)
{
byte[] data = PduMarshaler.Marshal(pdu);
// Sleep some time to avoid this packet to be merged with other packets in TCP level.
System.Threading.Thread.Sleep(PacketsInterval);
if (rdpeiDVC == null)
{
throw new InvalidOperationException("DVC instance of RDPEI is null, Dynamic virtual channel must be created before sending data.");
}
rdpeiDVC.Send(data);
}
/// <summary>
/// Method to send a RDPINPUT_SUSPEND_TOUCH_PDU to client.
/// </summary>
/// <param name="pdu">A RDPINPUT_SUSPEND_TOUCH_PDU structure.</param>
public void SendRdpInputSuspendTouchPdu(RDPINPUT_SUSPEND_TOUCH_PDU pdu)
{
byte[] data = PduMarshaler.Marshal(pdu);
// Sleep some time to avoid this packet to be merged with other packets in TCP level.
System.Threading.Thread.Sleep(PacketsInterval);
if (rdpeiDVC == null)
{
throw new InvalidOperationException("DVC instance of RDPEI is null, Dynamic virtual channel must be created before sending data.");
}
rdpeiDVC.Send(data);
}
/// <summary>
/// Method to send a RDPINPUT_RESUME_TOUCH_PDU to client.
/// </summary>
/// <param name="pdu">A RDPINPUT_RESUME_TOUCH_PDU structure.</param>
public void SendRdpInputResumeTouchPdu(RDPINPUT_RESUME_TOUCH_PDU pdu)
{
byte[] data = PduMarshaler.Marshal(pdu);
// Sleep some time to avoid this packet to be merged with other packets in TCP level.
System.Threading.Thread.Sleep(PacketsInterval);
if (rdpeiDVC == null)
{
throw new InvalidOperationException("DVC instance of RDPEI is null, Dynamic virtual channel must be created before sending data.");
}
rdpeiDVC.Send(data);
}
#endregion
#region Receive Methods
/// <summary>
/// Expect a RDPINPUT_CS_READY_PDU.
/// </summary>
/// <param name="timeout">TimeOut</param>
/// <returns>A RDPINPUT_CS_READY_PDU instance.</returns>
public RDPINPUT_CS_READY_PDU ExpectRdpInputCsReadyPdu(TimeSpan timeout)
{
RDPINPUT_CS_READY_PDU pdu = ExpectRdpeiPdu<RDPINPUT_CS_READY_PDU>(timeout);
return pdu;
}
/// <summary>
/// Expect a RDPINPUT_TOUCH_EVENT_PDU.
/// </summary>
/// <param name="timeout">TimeOut</param>
/// <returns>A RDPINPUT_TOUCH_EVENT_PDU instance.</returns>
public RDPINPUT_TOUCH_EVENT_PDU ExpectRdpInputTouchEventPdu(TimeSpan timeout)
{
RDPINPUT_TOUCH_EVENT_PDU pdu = ExpectRdpeiPdu<RDPINPUT_TOUCH_EVENT_PDU>(timeout);
return pdu;
}
/// <summary>
/// Expect a RDPINPUT_DISMISS_HOVERING_CONTACT_PDU.
/// </summary>
/// <param name="timeout">TimeOut</param>
/// <returns>A RDPINPUT_DISMISS_HOVERING_CONTACT_PDU instance.</returns>
public RDPINPUT_DISMISS_HOVERING_CONTACT_PDU ExpectRdpInputDismissHoveringContactPdu(TimeSpan timeout)
{
RDPINPUT_DISMISS_HOVERING_CONTACT_PDU pdu = ExpectRdpeiPdu<RDPINPUT_DISMISS_HOVERING_CONTACT_PDU>(timeout);
return pdu;
}
/// <summary>
/// Expect a RDPINPUT_TOUCH_EVENT_PDU or a RDPINPUT_DISMISS_HOVERING_CONTACT_PDU or a RDPINPUT_CS_READY_PDU.
/// </summary>
/// <param name="timeout">TimeOut</param>
/// <returns>A RDPINPUT_TOUCH_EVENT_PDU or a RDPINPUT_DISMISS_HOVERING_CONTACT_PDU or a RDPINPUT_CS_READY_PDU instance.</returns>
public RDPINPUT_PDU ExpectRdpInputPdu(TimeSpan timeout)
{
RDPINPUT_PDU pdu = ExpectRdpeiPdu<RDPINPUT_PDU>(timeout);
return pdu;
}
#endregion
#region Private methods
/// <summary>
/// Method to expect a specified type of Rdpei Pdu.
/// </summary>
/// <typeparam name="T">The specified type.</typeparam>
/// <param name="timeout">Timeout</param>
/// <returns>Return the specified type of Pdu otherwise, return null.</returns>
private T ExpectRdpeiPdu<T>(TimeSpan timeout) where T : RDPINPUT_PDU
{
DateTime endTime = DateTime.Now + timeout;
while (endTime > DateTime.Now)
{
if (receivedList.Count > 0)
{
lock (receivedList)
{
foreach (RDPINPUT_PDU pdu in receivedList)
{
T response = pdu as T;
if (response != null)
{
receivedList.Remove(pdu);
return response;
}
}
}
}
System.Threading.Thread.Sleep(PacketsInterval);
}
return null;
}
/// <summary>
/// The callback method to receive data from transport layer.
/// </summary>
private void OnDataReceived(byte[] data, uint channelId)
{
lock (receivedList)
{
RDPINPUT_PDU pdu = new RDPINPUT_PDU();
bool fResult = PduMarshaler.Unmarshal(data, pdu);
if (fResult)
{
byte[] pduData = new byte[pdu.header.pduLength];
Array.Copy(data, pduData, pduData.Length);
RDPINPUT_PDU msg = pdu;
if (pdu.header.eventId == EventId_Values.EVENTID_CS_READY)
{
RDPINPUT_CS_READY_PDU request = new RDPINPUT_CS_READY_PDU();
if (PduMarshaler.Unmarshal(pduData, request))
{
msg = request;
}
}
else if (pdu.header.eventId == EventId_Values.EVENTID_DISMISS_HOVERING_CONTACT)
{
RDPINPUT_DISMISS_HOVERING_CONTACT_PDU request = new RDPINPUT_DISMISS_HOVERING_CONTACT_PDU();
if (PduMarshaler.Unmarshal(pduData, request))
{
msg = request;
}
}
else if (pdu.header.eventId == EventId_Values.EVENTID_TOUCH)
{
RDPINPUT_TOUCH_EVENT_PDU request = new RDPINPUT_TOUCH_EVENT_PDU();
if (PduMarshaler.Unmarshal(pduData, request))
{
msg = request;
}
}
receivedList.Add(msg);
}
}
}
#endregion Private Methods
}
}
| |
// ***********************************************************************
// Copyright (c) 2012-2014 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
namespace NUnit.Framework.Api
{
/// <summary>
/// DefaultTestAssemblyBuilder loads a single assembly and builds a TestSuite
/// containing test fixtures present in the assembly.
/// </summary>
public class DefaultTestAssemblyBuilder : ITestAssemblyBuilder
{
static Logger log = InternalTrace.GetLogger(typeof(DefaultTestAssemblyBuilder));
#region Instance Fields
/// <summary>
/// The default suite builder used by the test assembly builder.
/// </summary>
ISuiteBuilder _defaultSuiteBuilder;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DefaultTestAssemblyBuilder"/> class.
/// </summary>
public DefaultTestAssemblyBuilder()
{
_defaultSuiteBuilder = new DefaultSuiteBuilder();
}
#endregion
#region Build Methods
/// <summary>
/// Build a suite of tests from a provided assembly
/// </summary>
/// <param name="assembly">The assembly from which tests are to be built</param>
/// <param name="options">A dictionary of options to use in building the suite</param>
/// <returns>
/// A TestSuite containing the tests found in the assembly
/// </returns>
public ITest Build(Assembly assembly, IDictionary<string, object> options)
{
#if NETSTANDARD1_3 || NETSTANDARD1_6
log.Debug("Loading {0}", assembly.FullName);
#else
log.Debug("Loading {0} in AppDomain {1}", assembly.FullName, AppDomain.CurrentDomain.FriendlyName);
#endif
string assemblyPath = AssemblyHelper.GetAssemblyPath(assembly);
return Build(assembly, assemblyPath, options);
}
/// <summary>
/// Build a suite of tests given the filename of an assembly
/// </summary>
/// <param name="assemblyName">The filename of the assembly from which tests are to be built</param>
/// <param name="options">A dictionary of options to use in building the suite</param>
/// <returns>
/// A TestSuite containing the tests found in the assembly
/// </returns>
public ITest Build(string assemblyName, IDictionary<string, object> options)
{
#if NETSTANDARD1_3 || NETSTANDARD1_6
log.Debug("Loading {0}", assemblyName);
#else
log.Debug("Loading {0} in AppDomain {1}", assemblyName, AppDomain.CurrentDomain.FriendlyName);
#endif
TestSuite testAssembly = null;
try
{
var assembly = AssemblyHelper.Load(assemblyName);
testAssembly = Build(assembly, assemblyName, options);
}
catch (Exception ex)
{
testAssembly = new TestAssembly(assemblyName);
testAssembly.MakeInvalid(ExceptionHelper.BuildMessage(ex, true));
}
return testAssembly;
}
private TestSuite Build(Assembly assembly, string assemblyPath, IDictionary<string, object> options)
{
TestSuite testAssembly = null;
try
{
if (options.ContainsKey(FrameworkPackageSettings.DefaultTestNamePattern))
TestNameGenerator.DefaultTestNamePattern = options[FrameworkPackageSettings.DefaultTestNamePattern] as string;
if (options.ContainsKey(FrameworkPackageSettings.WorkDirectory))
TestContext.DefaultWorkDirectory = options[FrameworkPackageSettings.WorkDirectory] as string;
else
TestContext.DefaultWorkDirectory = Directory.GetCurrentDirectory();
if (options.ContainsKey(FrameworkPackageSettings.TestParametersDictionary))
{
var testParametersDictionary = options[FrameworkPackageSettings.TestParametersDictionary] as IDictionary<string, string>;
if (testParametersDictionary != null)
{
foreach (var parameter in testParametersDictionary)
TestContext.Parameters.Add(parameter.Key, parameter.Value);
}
}
else
{
// This cannot be changed without breaking backwards compatibility with old runners.
// Deserializes the way old runners understand.
if (options.ContainsKey(FrameworkPackageSettings.TestParameters))
{
string parameters = options[FrameworkPackageSettings.TestParameters] as string;
if (!string.IsNullOrEmpty(parameters))
foreach (string param in parameters.Split(new[] { ';' }))
{
int eq = param.IndexOf("=");
if (eq > 0 && eq < param.Length - 1)
{
var name = param.Substring(0, eq);
var val = param.Substring(eq + 1);
TestContext.Parameters.Add(name, val);
}
}
}
}
IList fixtureNames = null;
if (options.ContainsKey(FrameworkPackageSettings.LOAD))
fixtureNames = options[FrameworkPackageSettings.LOAD] as IList;
var fixtures = GetFixtures(assembly, fixtureNames);
testAssembly = BuildTestAssembly(assembly, assemblyPath, fixtures);
}
catch (Exception ex)
{
testAssembly = new TestAssembly(assemblyPath);
testAssembly.MakeInvalid(ExceptionHelper.BuildMessage(ex, true));
}
return testAssembly;
}
#endregion
#region Helper Methods
private IList<Test> GetFixtures(Assembly assembly, IList names)
{
var fixtures = new List<Test>();
log.Debug("Examining assembly for test fixtures");
var testTypes = GetCandidateFixtureTypes(assembly, names);
log.Debug("Found {0} classes to examine", testTypes.Count);
#if LOAD_TIMING
System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
timer.Start();
#endif
int testcases = 0;
foreach (Type testType in testTypes)
{
var typeInfo = new TypeWrapper(testType);
try
{
if (_defaultSuiteBuilder.CanBuildFrom(typeInfo))
{
Test fixture = _defaultSuiteBuilder.BuildFrom(typeInfo);
fixtures.Add(fixture);
testcases += fixture.TestCaseCount;
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
#if LOAD_TIMING
log.Debug("Found {0} fixtures with {1} test cases in {2} seconds", fixtures.Count, testcases, timer.Elapsed);
#else
log.Debug("Found {0} fixtures with {1} test cases", fixtures.Count, testcases);
#endif
return fixtures;
}
private IList<Type> GetCandidateFixtureTypes(Assembly assembly, IList names)
{
var types = assembly.GetTypes();
if (names == null || names.Count == 0)
return types;
var result = new List<Type>();
foreach (string name in names)
{
Type fixtureType = assembly.GetType(name);
if (fixtureType != null)
result.Add(fixtureType);
else
{
string prefix = name + ".";
foreach (Type type in types)
if (type.FullName.StartsWith(prefix))
result.Add(type);
}
}
return result;
}
// This method invokes members on the 'System.Diagnostics.Process' class and must satisfy the link demand of
// the full-trust 'PermissionSetAttribute' on this class. Callers of this method have no influence on how the
// Process class is used, so we can safely satisfy the link demand with a 'SecuritySafeCriticalAttribute' rather
// than a 'SecurityCriticalAttribute' and allow use by security transparent callers.
[SecuritySafeCritical]
private TestSuite BuildTestAssembly(Assembly assembly, string assemblyName, IList<Test> fixtures)
{
TestSuite testAssembly = new TestAssembly(assembly, assemblyName);
if (fixtures.Count == 0)
{
testAssembly.MakeInvalid("Has no TestFixtures");
}
else
{
NamespaceTreeBuilder treeBuilder =
new NamespaceTreeBuilder(testAssembly);
treeBuilder.Add(fixtures);
testAssembly = treeBuilder.RootSuite;
}
testAssembly.ApplyAttributesToTest(assembly);
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
testAssembly.Properties.Set(PropertyNames.ProcessID, System.Diagnostics.Process.GetCurrentProcess().Id);
testAssembly.Properties.Set(PropertyNames.AppDomain, AppDomain.CurrentDomain.FriendlyName);
#endif
// TODO: Make this an option? Add Option to sort assemblies as well?
testAssembly.Sort();
return testAssembly;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Journalist.EventStore.Events;
using Journalist.EventStore.Streams;
using Journalist.EventStore.UnitTests.Infrastructure.Stubs;
using Journalist.EventStore.UnitTests.Infrastructure.TestData;
using Moq;
using Ploeh.AutoFixture.Xunit2;
using Xunit;
namespace Journalist.EventStore.UnitTests.Streams
{
public class EventStreamConsumerTests
{
[Theory]
[EventStreamReaderCustomization(hasEvents: false)]
public async Task ReceiveAsync_WhenReaderIsEmpty_ReturnsEmptyStreamCode(
EventStreamConsumer consumer)
{
Assert.Equal(ReceivingResultCode.EmptyStream, await consumer.ReceiveEventsAsync());
}
[Theory]
[EventStreamReaderCustomization(hasEvents: false)]
public async Task ReceiveAsync_WhenReaderIsEmpty_FreesSession(
[Frozen] Mock<IEventStreamConsumingSession> sessionMock,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
sessionMock.Verify(self => self.FreeAsync(), Times.Once());
}
[Theory]
[EventStreamReaderCustomization]
public async Task ReceiveAsync_WhenReaderIsNotEmpty_ReturnsEventsReceivedCode(
EventStreamConsumer consumer)
{
Assert.Equal(ReceivingResultCode.EventsReceived, await consumer.ReceiveEventsAsync());
}
[Theory]
[EventStreamReaderCustomization(leaderPromotion: false)]
public async Task ReceiveAsync_WhenReaderWasNotBeenPromotedToLeader_ReturnsPromotionFailedCode(
EventStreamConsumer consumer)
{
Assert.Equal(ReceivingResultCode.PromotionFailed, await consumer.ReceiveEventsAsync());
}
[Theory]
[EventStreamReaderCustomization]
public async Task ReceiveAsync_WhenReaderIsNotEmpty_ReadEventsFromReader(
[Frozen] Mock<IEventStreamReader> readerMock,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
readerMock.Verify(self => self.ReadEventsAsync(), Times.Once());
}
[Theory]
[EventStreamReaderCustomization]
public async Task EnumerateEvents_WhenReceiveMethodWasCalled_ReturnsEventsFromReader(
[Frozen] IReadOnlyList<JournaledEvent> events,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
var receivedEvents = consumer.EnumerateEvents();
Assert.Equal(events, receivedEvents);
}
[Theory]
[EventStreamReaderCustomization]
public void EnumerateEvents_WhenReceiveMethodWasNotCalled_Throws(
EventStreamConsumer consumer)
{
Assert.Throws<InvalidOperationException>(() => consumer.EnumerateEvents().ToList());
}
[Theory]
[EventStreamReaderCustomization]
public async Task ReceiveEventsAsync_WhenReceivingWasStarted_CommitsReaderVersion(
[Frozen] StreamVersion streamVersion,
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
[Frozen] IEventStreamReader reader,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync(); // starts receiving
await consumer.ReceiveEventsAsync(); // continues receiving and commits previous events
Assert.Equal(1, commitStreamVersionMock.CallsCount);
Assert.Equal(streamVersion.Increment(reader.Events.Count), commitStreamVersionMock.CommitedVersion);
}
[Theory]
[EventStreamReaderCustomization(disableAutoCommit: true)]
public async Task ReceiveEventsAsync_WhenReceivingWasStartedAndAutoCommitDisabled_DoesNotCommitReaderVersion(
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
[Frozen] IEventStreamReader reader,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
await consumer.ReceiveEventsAsync();
Assert.Equal(0, commitStreamVersionMock.CallsCount);
Assert.Equal(StreamVersion.Unknown, commitStreamVersionMock.CommitedVersion);
}
[Theory]
[EventStreamReaderCustomization(disableAutoCommit: true)]
public async Task CommitProcessedStreamVersionAsync_WhenReceivingWasStartedAndAutoCommitDisabled_DoesNotCommitReaderVersion(
[Frozen] StreamVersion streamVersion,
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
[Frozen] IEventStreamReader reader,
EventStreamConsumer consumer)
{
var expectedVersion = reader.StreamVersion.Increment(reader.Events.Count * 2);
await consumer.ReceiveEventsAsync();
await consumer.ReceiveEventsAsync();
await consumer.CommitProcessedStreamVersionAsync(false);
Assert.Equal(1, commitStreamVersionMock.CallsCount);
Assert.Equal(expectedVersion, commitStreamVersionMock.CommitedVersion);
}
[Theory]
[EventStreamReaderCustomization]
public async Task ReceiveEventsAsync_WhenReceivingWasNotStartedBefore_CommitsReaderVersion(
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
[Frozen] IEventStreamReader reader,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
Assert.Equal(0, commitStreamVersionMock.CallsCount);
Assert.Equal(StreamVersion.Unknown, commitStreamVersionMock.CommitedVersion);
}
[Theory]
[EventStreamReaderCustomization]
public async Task CloseAsync_WhenReaderHasUnprocessedEventsAndNoMessagesWereConsumed_DoesNotThrow(
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
await consumer.CloseAsync();
Assert.Equal(1, commitStreamVersionMock.CallsCount);
}
[Theory]
[EventStreamReaderCustomization]
public async Task CloseAsync_FreesConsumingSessions(
[Frozen] Mock<IEventStreamConsumingSession> sessionMock,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
await consumer.CloseAsync();
sessionMock.Verify(self => self.FreeAsync(), Times.Once());
}
[Theory]
[EventStreamReaderCustomization]
public async Task CloseAsync_WhenReaderHasUnprocessedEventsAndOnMessagesWasConsumed_CommitsConsumedVersion(
[Frozen] StreamVersion version,
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
var handledEventCount = 0;
foreach (var e in consumer.EnumerateEvents())
{
if (handledEventCount >= 1)
{
break;
}
handledEventCount++;
}
await consumer.CloseAsync();
Assert.Equal(1, commitStreamVersionMock.CallsCount);
Assert.Equal(version.Increment(), commitStreamVersionMock.CommitedVersion);
}
[Theory]
[EventStreamReaderCustomization]
public async Task CloseAsync_WhenReaderHasUnprocessedEventsAndCurrentEventHasBeenCommited_SkipCommit(
[Frozen] StreamVersion version,
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
foreach (var e in consumer.EnumerateEvents())
{
await consumer.CommitProcessedStreamVersionAsync();
break;
}
await consumer.CloseAsync();
Assert.Equal(1, commitStreamVersionMock.CallsCount);
Assert.Equal(version.Increment(), commitStreamVersionMock.CommitedVersion);
}
[Theory]
[EventStreamReaderCustomization]
public async Task CloseAsync_WhenReaderHasNoUnprocessedEvents_NotThrows(
EventStreamConsumer consumer)
{
await consumer.CloseAsync();
}
[Theory]
[EventStreamReaderCustomization(completed: true)]
public async Task CloseAsync_WhenReaderInCompletedStateAndHasNoUnprocessedEvents_CommitsConsumedVersion(
[Frozen] StreamVersion version,
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
[Frozen] IEventStreamReader reader,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
consumer.EnumerateEvents().ToList();
await consumer.CloseAsync();
Assert.Equal(1, commitStreamVersionMock.CallsCount);
Assert.Equal(reader.StreamVersion.Increment(reader.Events.Count), commitStreamVersionMock.CommitedVersion);
}
[Theory]
[EventStreamReaderCustomization]
public async Task RememberConsumedStreamVersionAsync_WhenEventWasConsumed_CommitsConsumedVersion(
[Frozen] StreamVersion version,
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
var handledEvents = 0;
foreach (var e in consumer.EnumerateEvents())
{
handledEvents++;
await consumer.CommitProcessedStreamVersionAsync();
break;
}
Assert.Equal(1, commitStreamVersionMock.CallsCount);
Assert.Equal(version.Increment(handledEvents), commitStreamVersionMock.CommitedVersion);
}
[Theory]
[EventStreamReaderCustomization(disableAutoCommit: true)]
public async Task RememberConsumedStreamVersionAsync_WhenEventWasConsumedAndAutoCommitDisabled_CommitsConsumedVersion(
[Frozen] StreamVersion version,
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
var handledEvents = 0;
foreach (var e in consumer.EnumerateEvents())
{
handledEvents++;
await consumer.CommitProcessedStreamVersionAsync();
break;
}
Assert.Equal(1, commitStreamVersionMock.CallsCount);
Assert.Equal(version.Increment(handledEvents), commitStreamVersionMock.CommitedVersion);
}
[Theory]
[EventStreamReaderCustomization]
public async Task RememberConsumedStreamVersionAsync_WhenAllEventsWereConsumed_CommitsReaderVersion(
[Frozen] StreamVersion streamVersion,
[Frozen] IEventStreamReader streamReader,
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
var handledEvents = 0;
foreach (var e in consumer.EnumerateEvents())
{
handledEvents++;
}
await consumer.CommitProcessedStreamVersionAsync(true);
Assert.Equal(1, commitStreamVersionMock.CallsCount);
Assert.Equal(streamReader.StreamVersion.Increment(streamReader.Events.Count), commitStreamVersionMock.CommitedVersion);
}
[Theory]
[EventStreamReaderCustomization]
public async Task RememberConsumedStreamVersionAsync_WhenSkipCurrentFlagIsTrue_CommitsOnlyProcessedEvents(
[Frozen] StreamVersion version,
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
EventStreamConsumer consumer)
{
await consumer.ReceiveEventsAsync();
var handledEvents = 0;
foreach (var e in consumer.EnumerateEvents())
{
handledEvents++;
await consumer.CommitProcessedStreamVersionAsync(skipCurrent: true);
break;
}
Assert.Equal(0, commitStreamVersionMock.CallsCount);
}
[Theory]
[EventStreamReaderCustomization]
public async Task RememberConsumedStreamVersionAsync_WhenSkipCurrentFlagIsTrue_CommitsOnlyProcessedEvents(
[Frozen] StreamVersion version,
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
[Frozen] Mock<IEventStreamReader> readerMock,
[Frozen] JournaledEvent[] events,
EventStreamConsumer consumer)
{
var streamVersion = version.Increment(events.Length);
readerMock
.Setup(self => self.StreamVersion)
.Returns(streamVersion);
await consumer.ReceiveEventsAsync();
var handledEvents = 0;
foreach (var e in consumer.EnumerateEvents())
{
handledEvents++;
await consumer.CommitProcessedStreamVersionAsync(skipCurrent: true);
}
Assert.Equal(handledEvents - 1, commitStreamVersionMock.CallsCount);
Assert.Equal(streamVersion.Decrement(), commitStreamVersionMock.CommitedVersion);
}
[Theory]
[EventStreamReaderCustomization]
public async Task RememberConsumedStreamVersionAsync_WhenLatestManuallyCommitedVersionEqualsToStreamCurrent_SkipCommitOnReceiveAsync(
[Frozen] StreamVersion version,
[Frozen] CommitStreamVersionFMock commitStreamVersionMock,
[Frozen] Mock<IEventStreamReader> readerMock,
[Frozen] JournaledEvent[] events,
EventStreamConsumer consumer)
{
var streamVersion = version.Increment(events.Length);
readerMock
.Setup(self => self.StreamVersion)
.Returns(streamVersion);
await consumer.ReceiveEventsAsync();
var handledEvents = 0;
foreach (var e in consumer.EnumerateEvents())
{
handledEvents++;
await consumer.CommitProcessedStreamVersionAsync();
}
await consumer.ReceiveEventsAsync();
Assert.Equal(handledEvents, commitStreamVersionMock.CallsCount);
Assert.Equal(streamVersion, commitStreamVersionMock.CommitedVersion);
}
}
}
| |
// 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.
#if XMLCHARTYPE_GEN_RESOURCE
#undef XMLCHARTYPE_USE_RESOURCE
#endif
//------------------------------------------------------------------------------
// </copyright>
//------------------------------------------------------------------------------
//#define XMLCHARTYPE_USE_RESOURCE // load the character properties from resources (XmlCharType.bin must be linked to System.Xml.dll)
//#define XMLCHARTYPE_GEN_RESOURCE // generate the character properties into XmlCharType.bin
#if XMLCHARTYPE_GEN_RESOURCE || XMLCHARTYPE_USE_RESOURCE
using System.IO;
using System.Reflection;
#endif
using System.Threading;
using System.Diagnostics;
namespace System.Xml
{
/// <include file='doc\XmlCharType.uex' path='docs/doc[@for="XmlCharType"]/*' />
/// <internalonly/>
/// <devdoc>
/// The XmlCharType class is used for quick character type recognition
/// which is optimized for the first 127 ascii characters.
/// </devdoc>
#if XMLCHARTYPE_USE_RESOURCE
unsafe internal struct XmlCharType {
#else
internal struct XmlCharType
{
#endif
// Whitespace chars -- Section 2.3 [3]
// Letters -- Appendix B [84]
// Starting NCName characters -- Section 2.3 [5] (Starting Name characters without ':')
// NCName characters -- Section 2.3 [4] (Name characters without ':')
// Character data characters -- Section 2.2 [2]
// PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec
internal const int fWhitespace = 1;
internal const int fLetter = 2;
internal const int fNCStartName = 4;
internal const int fNCName = 8;
internal const int fCharData = 16;
internal const int fPublicId = 32;
internal const int fText = 64;
internal const int fAttrValue = 128;
private const uint CharPropertiesSize = (uint)char.MaxValue + 1;
#if !XMLCHARTYPE_USE_RESOURCE || XMLCHARTYPE_GEN_RESOURCE
internal const string s_Whitespace =
"\u0009\u000a\u000d\u000d\u0020\u0020";
private const string s_Letter =
"\u0041\u005a\u0061\u007a\u00c0\u00d6\u00d8\u00f6" +
"\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" +
"\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" +
"\u0250\u02a8\u02bb\u02c1\u0386\u0386\u0388\u038a" +
"\u038c\u038c\u038e\u03a1\u03a3\u03ce\u03d0\u03d6" +
"\u03da\u03da\u03dc\u03dc\u03de\u03de\u03e0\u03e0" +
"\u03e2\u03f3\u0401\u040c\u040e\u044f\u0451\u045c" +
"\u045e\u0481\u0490\u04c4\u04c7\u04c8\u04cb\u04cc" +
"\u04d0\u04eb\u04ee\u04f5\u04f8\u04f9\u0531\u0556" +
"\u0559\u0559\u0561\u0586\u05d0\u05ea\u05f0\u05f2" +
"\u0621\u063a\u0641\u064a\u0671\u06b7\u06ba\u06be" +
"\u06c0\u06ce\u06d0\u06d3\u06d5\u06d5\u06e5\u06e6" +
"\u0905\u0939\u093d\u093d\u0958\u0961\u0985\u098c" +
"\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b2\u09b2" +
"\u09b6\u09b9\u09dc\u09dd\u09df\u09e1\u09f0\u09f1" +
"\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28\u0a2a\u0a30" +
"\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59\u0a5c" +
"\u0a5e\u0a5e\u0a72\u0a74\u0a85\u0a8b\u0a8d\u0a8d" +
"\u0a8f\u0a91\u0a93\u0aa8\u0aaa\u0ab0\u0ab2\u0ab3" +
"\u0ab5\u0ab9\u0abd\u0abd\u0ae0\u0ae0\u0b05\u0b0c" +
"\u0b0f\u0b10\u0b13\u0b28\u0b2a\u0b30\u0b32\u0b33" +
"\u0b36\u0b39\u0b3d\u0b3d\u0b5c\u0b5d\u0b5f\u0b61" +
"\u0b85\u0b8a\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a" +
"\u0b9c\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa" +
"\u0bae\u0bb5\u0bb7\u0bb9\u0c05\u0c0c\u0c0e\u0c10" +
"\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39\u0c60\u0c61" +
"\u0c85\u0c8c\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3" +
"\u0cb5\u0cb9\u0cde\u0cde\u0ce0\u0ce1\u0d05\u0d0c" +
"\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39\u0d60\u0d61" +
"\u0e01\u0e2e\u0e30\u0e30\u0e32\u0e33\u0e40\u0e45" +
"\u0e81\u0e82\u0e84\u0e84\u0e87\u0e88\u0e8a\u0e8a" +
"\u0e8d\u0e8d\u0e94\u0e97\u0e99\u0e9f\u0ea1\u0ea3" +
"\u0ea5\u0ea5\u0ea7\u0ea7\u0eaa\u0eab\u0ead\u0eae" +
"\u0eb0\u0eb0\u0eb2\u0eb3\u0ebd\u0ebd\u0ec0\u0ec4" +
"\u0f40\u0f47\u0f49\u0f69\u10a0\u10c5\u10d0\u10f6" +
"\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" +
"\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" +
"\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" +
"\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" +
"\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" +
"\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" +
"\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" +
"\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" +
"\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" +
"\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" +
"\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" +
"\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" +
"\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" +
"\u1ff6\u1ffc\u2126\u2126\u212a\u212b\u212e\u212e" +
"\u2180\u2182\u3007\u3007\u3021\u3029\u3041\u3094" +
"\u30a1\u30fa\u3105\u312c\u4e00\u9fa5\uac00\ud7a3";
private const string s_NCStartName =
"\u0041\u005a\u005f\u005f\u0061\u007a" +
"\u00c0\u00d6\u00d8\u00f6\u00f8\u0131\u0134\u013e" +
"\u0141\u0148\u014a\u017e\u0180\u01c3\u01cd\u01f0" +
"\u01f4\u01f5\u01fa\u0217\u0250\u02a8\u02bb\u02c1" +
"\u0386\u0386\u0388\u038a\u038c\u038c\u038e\u03a1" +
"\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" +
"\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" +
"\u040e\u044f\u0451\u045c\u045e\u0481\u0490\u04c4" +
"\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb\u04ee\u04f5" +
"\u04f8\u04f9\u0531\u0556\u0559\u0559\u0561\u0586" +
"\u05d0\u05ea\u05f0\u05f2\u0621\u063a\u0641\u064a" +
"\u0671\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" +
"\u06d5\u06d5\u06e5\u06e6\u0905\u0939\u093d\u093d" +
"\u0958\u0961\u0985\u098c\u098f\u0990\u0993\u09a8" +
"\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9\u09dc\u09dd" +
"\u09df\u09e1\u09f0\u09f1\u0a05\u0a0a\u0a0f\u0a10" +
"\u0a13\u0a28\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36" +
"\u0a38\u0a39\u0a59\u0a5c\u0a5e\u0a5e\u0a72\u0a74" +
"\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" +
"\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abd\u0abd" +
"\u0ae0\u0ae0\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" +
"\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3d\u0b3d" +
"\u0b5c\u0b5d\u0b5f\u0b61\u0b85\u0b8a\u0b8e\u0b90" +
"\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f" +
"\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5\u0bb7\u0bb9" +
"\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33" +
"\u0c35\u0c39\u0c60\u0c61\u0c85\u0c8c\u0c8e\u0c90" +
"\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9\u0cde\u0cde" +
"\u0ce0\u0ce1\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28" +
"\u0d2a\u0d39\u0d60\u0d61\u0e01\u0e2e\u0e30\u0e30" +
"\u0e32\u0e33\u0e40\u0e45\u0e81\u0e82\u0e84\u0e84" +
"\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" +
"\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" +
"\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb0\u0eb2\u0eb3" +
"\u0ebd\u0ebd\u0ec0\u0ec4\u0f40\u0f47\u0f49\u0f69" +
"\u10a0\u10c5\u10d0\u10f6\u1100\u1100\u1102\u1103" +
"\u1105\u1107\u1109\u1109\u110b\u110c\u110e\u1112" +
"\u113c\u113c\u113e\u113e\u1140\u1140\u114c\u114c" +
"\u114e\u114e\u1150\u1150\u1154\u1155\u1159\u1159" +
"\u115f\u1161\u1163\u1163\u1165\u1165\u1167\u1167" +
"\u1169\u1169\u116d\u116e\u1172\u1173\u1175\u1175" +
"\u119e\u119e\u11a8\u11a8\u11ab\u11ab\u11ae\u11af" +
"\u11b7\u11b8\u11ba\u11ba\u11bc\u11c2\u11eb\u11eb" +
"\u11f0\u11f0\u11f9\u11f9\u1e00\u1e9b\u1ea0\u1ef9" +
"\u1f00\u1f15\u1f18\u1f1d\u1f20\u1f45\u1f48\u1f4d" +
"\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b\u1f5d\u1f5d" +
"\u1f5f\u1f7d\u1f80\u1fb4\u1fb6\u1fbc\u1fbe\u1fbe" +
"\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3\u1fd6\u1fdb" +
"\u1fe0\u1fec\u1ff2\u1ff4\u1ff6\u1ffc\u2126\u2126" +
"\u212a\u212b\u212e\u212e\u2180\u2182\u3007\u3007" +
"\u3021\u3029\u3041\u3094\u30a1\u30fa\u3105\u312c" +
"\u4e00\u9fa5\uac00\ud7a3";
private const string s_NCName =
"\u002d\u002e\u0030\u0039\u0041\u005a\u005f\u005f" +
"\u0061\u007a\u00b7\u00b7\u00c0\u00d6\u00d8\u00f6" +
"\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" +
"\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" +
"\u0250\u02a8\u02bb\u02c1\u02d0\u02d1\u0300\u0345" +
"\u0360\u0361\u0386\u038a\u038c\u038c\u038e\u03a1" +
"\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" +
"\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" +
"\u040e\u044f\u0451\u045c\u045e\u0481\u0483\u0486" +
"\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb" +
"\u04ee\u04f5\u04f8\u04f9\u0531\u0556\u0559\u0559" +
"\u0561\u0586\u0591\u05a1\u05a3\u05b9\u05bb\u05bd" +
"\u05bf\u05bf\u05c1\u05c2\u05c4\u05c4\u05d0\u05ea" +
"\u05f0\u05f2\u0621\u063a\u0640\u0652\u0660\u0669" +
"\u0670\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" +
"\u06d5\u06e8\u06ea\u06ed\u06f0\u06f9\u0901\u0903" +
"\u0905\u0939\u093c\u094d\u0951\u0954\u0958\u0963" +
"\u0966\u096f\u0981\u0983\u0985\u098c\u098f\u0990" +
"\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9" +
"\u09bc\u09bc\u09be\u09c4\u09c7\u09c8\u09cb\u09cd" +
"\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09f1" +
"\u0a02\u0a02\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28" +
"\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39" +
"\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d" +
"\u0a59\u0a5c\u0a5e\u0a5e\u0a66\u0a74\u0a81\u0a83" +
"\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" +
"\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5" +
"\u0ac7\u0ac9\u0acb\u0acd\u0ae0\u0ae0\u0ae6\u0aef" +
"\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" +
"\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3c\u0b43" +
"\u0b47\u0b48\u0b4b\u0b4d\u0b56\u0b57\u0b5c\u0b5d" +
"\u0b5f\u0b61\u0b66\u0b6f\u0b82\u0b83\u0b85\u0b8a" +
"\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c" +
"\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5" +
"\u0bb7\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd" +
"\u0bd7\u0bd7\u0be7\u0bef\u0c01\u0c03\u0c05\u0c0c" +
"\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39" +
"\u0c3e\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56" +
"\u0c60\u0c61\u0c66\u0c6f\u0c82\u0c83\u0c85\u0c8c" +
"\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9" +
"\u0cbe\u0cc4\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6" +
"\u0cde\u0cde\u0ce0\u0ce1\u0ce6\u0cef\u0d02\u0d03" +
"\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39" +
"\u0d3e\u0d43\u0d46\u0d48\u0d4a\u0d4d\u0d57\u0d57" +
"\u0d60\u0d61\u0d66\u0d6f\u0e01\u0e2e\u0e30\u0e3a" +
"\u0e40\u0e4e\u0e50\u0e59\u0e81\u0e82\u0e84\u0e84" +
"\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" +
"\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" +
"\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb9\u0ebb\u0ebd" +
"\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9" +
"\u0f18\u0f19\u0f20\u0f29\u0f35\u0f35\u0f37\u0f37" +
"\u0f39\u0f39\u0f3e\u0f47\u0f49\u0f69\u0f71\u0f84" +
"\u0f86\u0f8b\u0f90\u0f95\u0f97\u0f97\u0f99\u0fad" +
"\u0fb1\u0fb7\u0fb9\u0fb9\u10a0\u10c5\u10d0\u10f6" +
"\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" +
"\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" +
"\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" +
"\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" +
"\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" +
"\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" +
"\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" +
"\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" +
"\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" +
"\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" +
"\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" +
"\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" +
"\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" +
"\u1ff6\u1ffc\u20d0\u20dc\u20e1\u20e1\u2126\u2126" +
"\u212a\u212b\u212e\u212e\u2180\u2182\u3005\u3005" +
"\u3007\u3007\u3021\u302f\u3031\u3035\u3041\u3094" +
"\u3099\u309a\u309d\u309e\u30a1\u30fa\u30fc\u30fe" +
"\u3105\u312c\u4e00\u9fa5\uac00\ud7a3";
private const string s_CharData =
"\u0009\u000a\u000d\u000d\u0020\ud7ff\ue000\ufffd";
private const string s_PublicID =
"\u000a\u000a\u000d\u000d\u0020\u0021\u0023\u0025" +
"\u0027\u003b\u003d\u003d\u003f\u005a\u005f\u005f" +
"\u0061\u007a";
private const string s_Text = // TextChar = CharData - { 0xA | 0xD | '<' | '&' | 0x9 | ']' | 0xDC00 - 0xDFFF }
"\u0020\u0025\u0027\u003b\u003d\u005c\u005e\ud7ff\ue000\ufffd";
private const string s_AttrValue = // AttrValueChar = CharData - { 0xA | 0xD | 0x9 | '<' | '>' | '&' | '\'' | '"' | 0xDC00 - 0xDFFF }
"\u0020\u0021\u0023\u0025\u0028\u003b\u003d\u003d\u003f\ud7ff\ue000\ufffd";
#endif
// static lock for XmlCharType class
private static object s_Lock;
private static object StaticLock
{
get
{
if (s_Lock == null)
{
object o = new object();
Interlocked.CompareExchange(ref s_Lock, o, null);
}
return s_Lock;
}
}
#if XMLCHARTYPE_USE_RESOURCE
private static byte* s_CharProperties;
internal byte* charProperties;
static void InitInstance() {
lock ( StaticLock ) {
if ( s_CharProperties != null ) {
return;
}
UnmanagedMemoryStream memStream = (UnmanagedMemoryStream)Assembly.GetExecutingAssembly().GetManifestResourceStream( "XmlCharType.bin" );
Debug.Assert( memStream.Length == CharPropertiesSize );
byte* chProps = memStream.PositionPointer;
Interlocked.MemoryBarrier(); // For weak memory models (IA64)
s_CharProperties = chProps;
}
}
#else // !XMLCHARTYPE_USE_RESOURCE
private static byte[] s_CharProperties;
internal byte[] charProperties;
private static void InitInstance()
{
lock (StaticLock)
{
if (s_CharProperties != null)
{
return;
}
byte[] chProps = new byte[CharPropertiesSize];
Interlocked.MemoryBarrier(); // For weak memory models (IA64)
SetProperties(chProps, s_Whitespace, fWhitespace);
SetProperties(chProps, s_Letter, fLetter);
SetProperties(chProps, s_NCStartName, fNCStartName);
SetProperties(chProps, s_NCName, fNCName);
SetProperties(chProps, s_CharData, fCharData);
SetProperties(chProps, s_PublicID, fPublicId);
SetProperties(chProps, s_Text, fText);
SetProperties(chProps, s_AttrValue, fAttrValue);
s_CharProperties = chProps;
}
}
private static void SetProperties(byte[] chProps, string ranges, byte value)
{
for (int p = 0; p < ranges.Length; p += 2)
{
for (int i = ranges[p], last = ranges[p + 1]; i <= last; i++)
{
chProps[i] |= value;
}
}
}
#endif
#if XMLCHARTYPE_USE_RESOURCE
private XmlCharType( byte* charProperties ) {
#else
private XmlCharType(byte[] charProperties)
{
#endif
Debug.Assert(s_CharProperties != null);
this.charProperties = charProperties;
}
internal static XmlCharType Instance
{
get
{
if (s_CharProperties == null)
{
InitInstance();
}
return new XmlCharType(s_CharProperties);
}
}
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsWhiteSpace(char ch)
{
return (charProperties[ch] & fWhitespace) != 0;
}
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsLetter(char ch)
{
return (charProperties[ch] & fLetter) != 0;
}
public bool IsExtender(char ch)
{
return (ch == 0xb7);
}
/// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsNCNameChar(char ch)
{
return (charProperties[ch] & fNCName) != 0;
}
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsStartNCNameChar(char ch)
{
return (charProperties[ch] & fNCStartName) != 0;
}
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsCharData(char ch)
{
return (charProperties[ch] & fCharData) != 0;
}
// [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsPubidChar(char ch)
{
return (charProperties[ch] & fPublicId) != 0;
}
// TextChar = CharData - { 0xA, 0xD, '<', '&', ']' }
// NOTE: This method will not be inlined (because it uses byte* charProperties)
internal bool IsTextChar(char ch)
{
return (charProperties[ch] & fText) != 0;
}
// AttrValueChar = CharData - { 0xA, 0xD, 0x9, '<', '>', '&', '\'', '"' }
// NOTE: This method will not be inlined (because it uses byte* charProperties)
internal bool IsAttributeValueChar(char ch)
{
return (charProperties[ch] & fAttrValue) != 0;
}
public bool IsNameChar(char ch)
{
return IsNCNameChar(ch) || ch == ':';
}
public bool IsStartNameChar(char ch)
{
return IsStartNCNameChar(ch) || ch == ':';
}
public bool IsDigit(char ch)
{
return (ch >= 0x30 && ch <= 0x39);
}
public bool IsHexDigit(char ch)
{
return (ch >= 0x30 && ch <= 0x39) || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F');
}
internal bool IsOnlyWhitespace(string str)
{
return IsOnlyWhitespaceWithPos(str) == -1;
}
internal int IsOnlyWhitespaceWithPos(string str)
{
if (str != null)
{
for (int i = 0; i < str.Length; i++)
{
if ((charProperties[str[i]] & fWhitespace) == 0)
{
return i;
}
}
}
return -1;
}
internal bool IsName(string str)
{
if (str.Length == 0 || !IsStartNameChar(str[0]))
{
return false;
}
for (int i = 1; i < str.Length; i++)
{
if (!IsNameChar(str[i]))
{
return false;
}
}
return true;
}
internal bool IsNmToken(string str)
{
if (str.Length == 0)
{
return false;
}
for (int i = 0; i < str.Length; i++)
{
if ((charProperties[str[i]] & fNCName) == 0 && str[i] != ':')
{
return false;
}
}
return true;
}
internal int IsOnlyCharData(string str)
{
if (str != null)
{
for (int i = 0; i < str.Length; i++)
{
if ((charProperties[str[i]] & fCharData) == 0)
{
return i;
}
}
}
return -1;
}
internal int IsPublicId(string str)
{
if (str != null)
{
for (int i = 0; i < str.Length; i++)
{
if ((charProperties[str[i]] & fPublicId) == 0)
{
return i;
}
}
}
return -1;
}
#if XMLCHARTYPE_GEN_RESOURCE
public static void Main( string[] args ) {
try {
InitInstance();
string fileName = ( args.Length == 0 ) ? "XmlCharType.bin" : args[0];
Console.Write( "Writing XmlCharType character properties to {0}...", fileName );
FileStream fs = new FileStream( fileName, FileMode.Create );
for ( int i = 0; i < CharPropertiesSize; i += 4096 ) {
fs.Write( s_CharProperties, i, 4096 );
}
fs.Close();
Console.WriteLine( "done." );
}
catch ( Exception e ) {
Console.WriteLine();
Console.WriteLine( "Exception: {0}", e.Message );
}
}
#endif
}
}
| |
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using System.Collections.Generic;
using System.Text;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
/// <summary>
/// Utility methods for inventory archiving
/// </summary>
public static class InventoryArchiveUtils
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Character used for escaping the path delimter ("\/") and itself ("\\") in human escaped strings
public static readonly char ESCAPE_CHARACTER = '\\';
// The character used to separate inventory path components (different folders and items)
public static readonly char PATH_DELIMITER = '/';
/// <summary>
/// Escape an archive path.
/// </summary>
/// This has to be done differently from human paths because we can't leave in any "/" characters (due to
/// problems if the archive is built from or extracted to a filesystem
/// <param name="path"></param>
/// <returns></returns>
public static string EscapeArchivePath(string path)
{
// Only encode ampersands (for escaping anything) and / (since this is used as general dir separator).
return path.Replace("&", "&").Replace("/", "/");
}
/// <summary>
/// Find a folder given a PATH_DELIMITER delimited path starting from a user's root folder
/// </summary>
/// <remarks>
/// This method does not handle paths that contain multiple delimitors
///
/// FIXME: We have no way of distinguishing folders with the same path
///
/// FIXME: Delimitors which occur in names themselves are not currently escapable.
/// </remarks>
/// <param name="inventoryService">
/// Inventory service to query
/// </param>
/// <param name="userId">
/// User id to search
/// </param>
/// <param name="path">
/// The path to the required folder.
/// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned.
/// </param>
/// <returns>The folder found. Please note that if there are multiple folders with the same name then an
/// unspecified one will be returned. If no such folder eixsts then null is returned</returns>
public static InventoryFolderBase FindFolderByPath(
IInventoryService inventoryService, UUID userId, string path)
{
List<InventoryFolderBase> folders = FindFoldersByPath(inventoryService, userId, path);
if (folders.Count == 0)
return null;
else
return folders[0];
}
/// <summary>
/// Find a folder given a PATH_DELIMITER delimited path starting from a given folder
/// </summary>
/// <remarks>
/// This method does not handle paths that contain multiple delimitors
///
/// FIXME: We have no way of distinguishing folders with the same path
///
/// FIXME: Delimitors which occur in names themselves are not currently escapable.
/// </remarks>
/// <param name="inventoryService">
/// Inventory service to query
/// </param>
/// <param name="startFolder">
/// The folder from which the path starts
/// </param>
/// <param name="path">
/// The path to the required folder.
/// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned.
/// </param>
/// <returns>The folder found. Please note that if there are multiple folders with the same name then an
/// unspecified one will be returned. If no such folder eixsts then null is returned</returns>
public static InventoryFolderBase FindFolderByPath(
IInventoryService inventoryService, InventoryFolderBase startFolder, string path)
{
if (null == startFolder)
return null;
List<InventoryFolderBase> folders = FindFoldersByPath(inventoryService, startFolder, path);
if (folders.Count == 0)
return null;
else
return folders[0];
}
/// <summary>
/// Find a set of folders given a PATH_DELIMITER delimited path starting from a user's root folder
/// </summary>
/// <remarks>
/// This method does not handle paths that contain multiple delimitors
///
/// FIXME: We have no way of distinguishing folders with the same path
///
/// FIXME: Delimitors which occur in names themselves are not currently escapable.
/// </remarks>
/// <param name="inventoryService">
/// Inventory service to query
/// </param>
/// <param name="userId">
/// User id to search
/// </param>
/// <param name="path">
/// The path to the required folder.
/// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned.
/// </param>
/// <returns>An empty list if the folder is not found, otherwise a list of all folders that match the name</returns>
public static List<InventoryFolderBase> FindFoldersByPath(
IInventoryService inventoryService, UUID userId, string path)
{
InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId);
if (null == rootFolder)
return new List<InventoryFolderBase>();
return FindFoldersByPath(inventoryService, rootFolder, path);
}
/// <summary>
/// Find a set of folders given a PATH_DELIMITER delimited path starting from this folder
/// </summary>
/// <remarks>
/// This method does not handle paths that contain multiple delimitors
///
/// FIXME: We have no way of distinguishing folders with the same path.
///
/// FIXME: Delimitors which occur in names themselves are not currently escapable.
/// </remarks>
/// <param name="inventoryService">
/// Inventory service to query
/// </param>
/// <param name="startFolder">
/// The folder from which the path starts
/// </param>
/// <param name="path">
/// The path to the required folder.
/// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned.
/// </param>
/// <returns>An empty list if the folder is not found, otherwise a list of all folders that match the name</returns>
public static List<InventoryFolderBase> FindFoldersByPath(
IInventoryService inventoryService, InventoryFolderBase startFolder, string path)
{
List<InventoryFolderBase> foundFolders = new List<InventoryFolderBase>();
if (path == string.Empty)
{
foundFolders.Add(startFolder);
return foundFolders;
}
path = path.Trim();
if (path == PATH_DELIMITER.ToString())
{
foundFolders.Add(startFolder);
return foundFolders;
}
// If the path isn't just / then trim any starting extraneous slashes
path = path.TrimStart(new char[] { PATH_DELIMITER });
// m_log.DebugFormat("[INVENTORY ARCHIVE UTILS]: Adjusted path in FindFolderByPath() is [{0}]", path);
string[] components = SplitEscapedPath(path);
components[0] = UnescapePath(components[0]);
//string[] components = path.Split(new string[] { PATH_DELIMITER.ToString() }, 2, StringSplitOptions.None);
InventoryCollection contents = inventoryService.GetFolderContent(startFolder.Owner, startFolder.ID);
// m_log.DebugFormat(
// "Found {0} folders in {1} for {2}", contents.Folders.Count, startFolder.Name, startFolder.Owner);
foreach (InventoryFolderBase folder in contents.Folders)
{
if (folder.Name == components[0])
{
if (components.Length > 1)
foundFolders.AddRange(FindFoldersByPath(inventoryService, folder, components[1]));
else
foundFolders.Add(folder);
}
}
return foundFolders;
}
/// <summary>
/// Find an item given a PATH_DELIMITOR delimited path starting from the user's root folder.
/// </summary>
/// <remarks>
/// This method does not handle paths that contain multiple delimitors
///
/// FIXME: We do not yet handle situations where folders or items have the same name. We could handle this by some
/// XPath like expression
///
/// FIXME: Delimitors which occur in names themselves are not currently escapable.
/// </remarks>
///
/// <param name="inventoryService">
/// Inventory service to query
/// </param>
/// <param name="userId">
/// The user to search
/// </param>
/// <param name="path">
/// The path to the required item.
/// </param>
/// <returns>null if the item is not found</returns>
public static InventoryItemBase FindItemByPath(
IInventoryService inventoryService, UUID userId, string path)
{
InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId);
if (null == rootFolder)
return null;
return FindItemByPath(inventoryService, rootFolder, path);
}
/// <summary>
/// Find an item given a PATH_DELIMITOR delimited path starting from this folder.
/// </summary>
/// <remarks>
/// This method does not handle paths that contain multiple delimiters
///
/// FIXME: We do not yet handle situations where folders or items have the same name. We could handle this by some
/// XPath like expression
///
/// FIXME: Delimitors which occur in names themselves are not currently escapable.
/// </remarks>
///
/// <param name="inventoryService">Inventory service to query</param>
/// <param name="startFolder">The folder from which the path starts</param>
/// <param name="path">The path to the required item.</param>
/// <returns>null if the item is not found</returns>
public static InventoryItemBase FindItemByPath(
IInventoryService inventoryService, InventoryFolderBase startFolder, string path)
{
List<InventoryItemBase> foundItems = FindItemsByPath(inventoryService, startFolder, path);
if (foundItems.Count != 0)
return foundItems[0];
else
return null;
}
public static List<InventoryItemBase> FindItemsByPath(
IInventoryService inventoryService, UUID userId, string path)
{
InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId);
if (null == rootFolder)
return new List<InventoryItemBase>();
return FindItemsByPath(inventoryService, rootFolder, path);
}
/// <summary>
/// Find items that match a given PATH_DELIMITOR delimited path starting from this folder.
/// </summary>
/// <remarks>
/// This method does not handle paths that contain multiple delimiters
///
/// FIXME: We do not yet handle situations where folders or items have the same name. We could handle this by some
/// XPath like expression
///
/// FIXME: Delimitors which occur in names themselves are not currently escapable.
/// </remarks>
///
/// <param name="inventoryService">Inventory service to query</param>
/// <param name="startFolder">The folder from which the path starts</param>
/// <param name="path">The path to the required item.</param>
/// <returns>The items that were found with this path. An empty list if no items were found.</returns>
public static List<InventoryItemBase> FindItemsByPath(
IInventoryService inventoryService, InventoryFolderBase startFolder, string path)
{
List<InventoryItemBase> foundItems = new List<InventoryItemBase>();
// If the path isn't just / then trim any starting extraneous slashes
path = path.TrimStart(new char[] { PATH_DELIMITER });
string[] components = SplitEscapedPath(path);
components[0] = UnescapePath(components[0]);
//string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None);
if (components.Length == 1)
{
// m_log.DebugFormat(
// "FOUND SINGLE COMPONENT [{0}]. Looking for this in [{1}] {2}",
// components[0], startFolder.Name, startFolder.ID);
List<InventoryItemBase> items = inventoryService.GetFolderItems(startFolder.Owner, startFolder.ID);
// m_log.DebugFormat("[INVENTORY ARCHIVE UTILS]: Found {0} items in FindItemByPath()", items.Count);
foreach (InventoryItemBase item in items)
{
// m_log.DebugFormat("[INVENTORY ARCHIVE UTILS]: Inspecting item {0} {1}", item.Name, item.ID);
if (item.Name == components[0])
foundItems.Add(item);
}
}
else
{
// m_log.DebugFormat("FOUND COMPONENTS [{0}] and [{1}]", components[0], components[1]);
InventoryCollection contents = inventoryService.GetFolderContent(startFolder.Owner, startFolder.ID);
foreach (InventoryFolderBase folder in contents.Folders)
{
if (folder.Name == components[0])
foundItems.AddRange(FindItemsByPath(inventoryService, folder, components[1]));
}
}
return foundItems;
}
/// <summary>
/// Split a human escaped path into two components if it contains an unescaped path delimiter, or one component
/// if no delimiter is present
/// </summary>
/// <param name="path"></param>
/// <returns>
/// The split path. We leave the components in their originally unescaped state (though we remove the delimiter
/// which originally split them if applicable).
/// </returns>
public static string[] SplitEscapedPath(string path)
{
// m_log.DebugFormat("SPLITTING PATH {0}", path);
bool singleEscapeChar = false;
for (int i = 0; i < path.Length; i++)
{
if (path[i] == ESCAPE_CHARACTER && !singleEscapeChar)
{
singleEscapeChar = true;
}
else
{
if (PATH_DELIMITER == path[i] && !singleEscapeChar)
return new string[2] { path.Remove(i), path.Substring(i + 1) };
else
singleEscapeChar = false;
}
}
// We didn't find a delimiter
return new string[1] { path };
}
/// <summary>
/// Unescape an archive path.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string UnescapeArchivePath(string path)
{
return path.Replace("/", "/").Replace("&", "&");
}
/// <summary>
/// Unescapes a human escaped path. This means that "\\" goes to "\", and "\/" goes to "/"
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string UnescapePath(string path)
{
// m_log.DebugFormat("ESCAPING PATH {0}", path);
StringBuilder sb = new StringBuilder();
bool singleEscapeChar = false;
for (int i = 0; i < path.Length; i++)
{
if (path[i] == ESCAPE_CHARACTER && !singleEscapeChar)
singleEscapeChar = true;
else
singleEscapeChar = false;
if (singleEscapeChar)
{
if (PATH_DELIMITER == path[i])
sb.Append(PATH_DELIMITER);
}
else
{
sb.Append(path[i]);
}
}
// m_log.DebugFormat("ESCAPED PATH TO {0}", sb);
return sb.ToString();
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
namespace YAF.Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using UnicodeUtil = YAF.Lucene.Net.Util.UnicodeUtil;
/// <summary>
/// Abstract base class for performing write operations of Lucene's low-level
/// data types.
///
/// <para/><see cref="DataOutput"/> may only be used from one thread, because it is not
/// thread safe (it keeps internal state like file position).
/// </summary>
public abstract class DataOutput
{
/// <summary>
/// Writes a single byte.
/// <para/>
/// The most primitive data type is an eight-bit byte. Files are
/// accessed as sequences of bytes. All other data types are defined
/// as sequences of bytes, so file formats are byte-order independent.
/// </summary>
/// <seealso cref="DataInput.ReadByte()"/>
public abstract void WriteByte(byte b);
/// <summary>
/// Writes an array of bytes.
/// </summary>
/// <param name="b">the bytes to write</param>
/// <param name="length">the number of bytes to write</param>
/// <seealso cref="DataInput.ReadBytes(byte[], int, int)"/>
public virtual void WriteBytes(byte[] b, int length)
{
WriteBytes(b, 0, length);
}
/// <summary>
/// Writes an array of bytes. </summary>
/// <param name="b"> the bytes to write </param>
/// <param name="offset"> the offset in the byte array </param>
/// <param name="length"> the number of bytes to write </param>
/// <seealso cref="DataInput.ReadBytes(byte[], int, int)"/>
public abstract void WriteBytes(byte[] b, int offset, int length);
/// <summary>
/// Writes an <see cref="int"/> as four bytes.
/// <para/>
/// 32-bit unsigned integer written as four bytes, high-order bytes first.
/// <para/>
/// NOTE: this was writeInt() in Lucene
/// </summary>
/// <seealso cref="DataInput.ReadInt32()"/>
public virtual void WriteInt32(int i)
{
WriteByte((byte)(sbyte)(i >> 24));
WriteByte((byte)(sbyte)(i >> 16));
WriteByte((byte)(sbyte)(i >> 8));
WriteByte((byte)(sbyte)i);
}
/// <summary>
/// Writes a short as two bytes.
/// <para/>
/// NOTE: this was writeShort() in Lucene
/// </summary>
/// <seealso cref="DataInput.ReadInt16()"/>
public virtual void WriteInt16(short i)
{
WriteByte((byte)(sbyte)((ushort)i >> 8));
WriteByte((byte)(sbyte)(ushort)i);
}
/// <summary>
/// Writes an <see cref="int"/> in a variable-length format. Writes between one and
/// five bytes. Smaller values take fewer bytes. Negative numbers are
/// supported, but should be avoided.
/// <para>VByte is a variable-length format for positive integers is defined where the
/// high-order bit of each byte indicates whether more bytes remain to be read. The
/// low-order seven bits are appended as increasingly more significant bits in the
/// resulting integer value. Thus values from zero to 127 may be stored in a single
/// byte, values from 128 to 16,383 may be stored in two bytes, and so on.</para>
/// <para>VByte Encoding Example</para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Byte 1</term>
/// <term>Byte 2</term>
/// <term>Byte 3</term>
/// </listheader>
/// <item>
/// <term>0</term>
/// <term>00000000</term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term>1</term>
/// <term>00000001</term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term>2</term>
/// <term>00000010</term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term>...</term>
/// <term></term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term>127</term>
/// <term>01111111</term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term>128</term>
/// <term>10000000</term>
/// <term>00000001</term>
/// <term></term>
/// </item>
/// <item>
/// <term>129</term>
/// <term>10000001</term>
/// <term>00000001</term>
/// <term></term>
/// </item>
/// <item>
/// <term>130</term>
/// <term>10000010</term>
/// <term>00000001</term>
/// <term></term>
/// </item>
/// <item>
/// <term>...</term>
/// <term></term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term>16,383</term>
/// <term>11111111</term>
/// <term>01111111</term>
/// <term></term>
/// </item>
/// <item>
/// <term>16,384</term>
/// <term>10000000</term>
/// <term>10000000</term>
/// <term>00000001</term>
/// </item>
/// <item>
/// <term>16,385</term>
/// <term>10000001</term>
/// <term>10000000</term>
/// <term>00000001</term>
/// </item>
/// <item>
/// <term>...</term>
/// <term></term>
/// <term></term>
/// <term></term>
/// </item>
/// </list>
///
/// <para>this provides compression while still being efficient to decode.</para>
/// <para/>
/// NOTE: this was writeVInt() in Lucene
/// </summary>
/// <param name="i"> Smaller values take fewer bytes. Negative numbers are
/// supported, but should be avoided. </param>
/// <exception cref="System.IO.IOException"> If there is an I/O error writing to the underlying medium. </exception>
/// <seealso cref="DataInput.ReadVInt32()"/>
public void WriteVInt32(int i)
{
while ((i & ~0x7F) != 0)
{
WriteByte((byte)unchecked((sbyte)((i & 0x7F) | 0x80)));
i = (int)((uint)i >> 7);
}
WriteByte((byte)(sbyte)i);
}
/// <summary>
/// Writes a <see cref="long"/> as eight bytes.
/// <para/>
/// 64-bit unsigned integer written as eight bytes, high-order bytes first.
/// <para/>
/// NOTE: this was writeLong() in Lucene
/// </summary>
/// <seealso cref="DataInput.ReadInt64()"/>
public virtual void WriteInt64(long i)
{
WriteInt32((int)(i >> 32));
WriteInt32((int)i);
}
/// <summary>
/// Writes an <see cref="long"/> in a variable-length format. Writes between one and nine
/// bytes. Smaller values take fewer bytes. Negative numbers are not
/// supported.
/// <para/>
/// The format is described further in <see cref="DataOutput.WriteVInt32(int)"/>.
/// <para/>
/// NOTE: this was writeVLong() in Lucene
/// </summary>
/// <seealso cref="DataInput.ReadVInt64()"/>
public void WriteVInt64(long i)
{
Debug.Assert(i >= 0L);
while ((i & ~0x7FL) != 0L)
{
WriteByte((byte)unchecked((sbyte)((i & 0x7FL) | 0x80L)));
i = (long)((ulong)i >> 7);
}
WriteByte((byte)(sbyte)i);
}
/// <summary>
/// Writes a string.
/// <para/>
/// Writes strings as UTF-8 encoded bytes. First the length, in bytes, is
/// written as a <see cref="WriteVInt32"/>, followed by the bytes.
/// </summary>
/// <seealso cref="DataInput.ReadString()"/>
public virtual void WriteString(string s)
{
var utf8Result = new BytesRef(10);
UnicodeUtil.UTF16toUTF8(s, 0, s.Length, utf8Result);
WriteVInt32(utf8Result.Length);
WriteBytes(utf8Result.Bytes, 0, utf8Result.Length);
}
private const int COPY_BUFFER_SIZE = 16384;
private byte[] copyBuffer;
/// <summary>
/// Copy numBytes bytes from input to ourself. </summary>
public virtual void CopyBytes(DataInput input, long numBytes)
{
Debug.Assert(numBytes >= 0, "numBytes=" + numBytes);
long left = numBytes;
if (copyBuffer == null)
{
copyBuffer = new byte[COPY_BUFFER_SIZE];
}
while (left > 0)
{
int toCopy;
if (left > COPY_BUFFER_SIZE)
{
toCopy = COPY_BUFFER_SIZE;
}
else
{
toCopy = (int)left;
}
input.ReadBytes(copyBuffer, 0, toCopy);
WriteBytes(copyBuffer, 0, toCopy);
left -= toCopy;
}
}
/// <summary>
/// Writes a <see cref="T:IDictionary{string, string}"/>.
/// <para/>
/// First the size is written as an <see cref="WriteInt32(int)"/>,
/// followed by each key-value pair written as two consecutive
/// <see cref="WriteString(string)"/>s.
/// </summary>
/// <param name="map"> Input <see cref="T:IDictionary{string, string}"/>. May be <c>null</c> (equivalent to an empty dictionary) </param>
public virtual void WriteStringStringMap(IDictionary<string, string> map)
{
if (map == null)
{
WriteInt32(0);
}
else
{
WriteInt32(map.Count);
foreach (KeyValuePair<string, string> entry in map)
{
WriteString(entry.Key);
WriteString(entry.Value);
}
}
}
/// <summary>
/// Writes a <see cref="string"/> set.
/// <para/>
/// First the size is written as an <see cref="WriteInt32(int)"/>,
/// followed by each value written as a
/// <see cref="WriteString(string)"/>.
/// </summary>
/// <param name="set"> Input <see cref="T:ISet{string}"/>. May be <c>null</c> (equivalent to an empty set) </param>
public virtual void WriteStringSet(ISet<string> set)
{
if (set == null)
{
WriteInt32(0);
}
else
{
WriteInt32(set.Count);
foreach (string value in set)
{
WriteString(value);
}
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Collections.Generic;
namespace UMA.Editors
{
[CustomEditor(typeof(OverlayLibrary))]
[CanEditMultipleObjects]
public class OverlayLibraryEditor : Editor
{
private SerializedObject m_Object;
private OverlayLibrary overlayLibrary;
private SerializedProperty m_OverlayDataCount;
private const string kArraySizePath = "overlayElementList.Array.size";
private const string kArrayData = "overlayElementList.Array.data[{0}]";
private bool canUpdate;
private bool isDirty;
public SerializedProperty scaleAdjust;
public SerializedProperty readWrite;
public SerializedProperty compress;
public void OnEnable(){
m_Object = new SerializedObject(target);
overlayLibrary = m_Object.targetObject as OverlayLibrary;
m_OverlayDataCount = m_Object.FindProperty(kArraySizePath);
scaleAdjust = serializedObject.FindProperty ("scaleAdjust");
readWrite = serializedObject.FindProperty ("readWrite");
compress = serializedObject.FindProperty ("compress");
}
private OverlayDataAsset[] GetOverlayDataArray()
{
int arrayCount = m_OverlayDataCount.intValue;
OverlayDataAsset[] OverlayDataArray = new OverlayDataAsset[arrayCount];
for(int i = 0; i < arrayCount; i++){
OverlayDataArray[i] = m_Object.FindProperty(string.Format(kArrayData,i)).objectReferenceValue as OverlayDataAsset;
}
return OverlayDataArray;
}
private void SetOverlayData(int index, OverlayDataAsset overlayElement)
{
m_Object.FindProperty(string.Format(kArrayData,index)).objectReferenceValue = overlayElement;
isDirty = true;
}
private OverlayDataAsset GetOverlayDataAtIndex(int index)
{
return m_Object.FindProperty(string.Format(kArrayData, index)).objectReferenceValue as OverlayDataAsset;
}
private void AddOverlayData(OverlayDataAsset overlayElement)
{
m_OverlayDataCount.intValue ++;
SetOverlayData(m_OverlayDataCount.intValue - 1, overlayElement);
}
private void RemoveOverlayDataAtIndex(int index){
for(int i = index; i < m_OverlayDataCount.intValue - 1; i++){
SetOverlayData(i, GetOverlayDataAtIndex(i + 1));
}
m_OverlayDataCount.intValue --;
}
private void ScaleDownTextures(){
OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
string path;
for(int i = 0; i < overlayElementList.Length; i++){
if(overlayElementList[i] != null){
Rect tempRect = overlayElementList[i].rect;
overlayElementList[i].rect = new Rect(tempRect.x*0.5f,tempRect.y*0.5f,tempRect.width*0.5f,tempRect.height*0.5f);
EditorUtility.SetDirty(overlayElementList[i]);
for(int textureID = 0; textureID < overlayElementList[i].textureList.Length; textureID++){
if(overlayElementList[i].textureList[textureID]){
path = AssetDatabase.GetAssetPath(overlayElementList[i].textureList[textureID]);
TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
textureImporter.maxTextureSize = (int)(textureImporter.maxTextureSize*0.5f);
AssetDatabase.WriteImportSettingsIfDirty (path);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
}
}
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
private void ScaleUpTextures(){
OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
string path;
for(int i = 0; i < overlayElementList.Length; i++){
if(overlayElementList[i] != null){
Rect tempRect = overlayElementList[i].rect;
overlayElementList[i].rect = new Rect(tempRect.x*2,tempRect.y*2,tempRect.width*2,tempRect.height*2);
EditorUtility.SetDirty(overlayElementList[i]);
for(int textureID = 0; textureID < overlayElementList[i].textureList.Length; textureID++){
if(overlayElementList[i].textureList[textureID]){
path = AssetDatabase.GetAssetPath(overlayElementList[i].textureList[textureID]);
TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
textureImporter.maxTextureSize = (int)(textureImporter.maxTextureSize*2);
AssetDatabase.WriteImportSettingsIfDirty (path);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
}
}
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
private void ConfigureTextures(){
OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
string path;
for(int i = 0; i < overlayElementList.Length; i++){
if(overlayElementList[i] != null){
for(int textureID = 0; textureID < overlayElementList[i].textureList.Length; textureID++){
if(overlayElementList[i].textureList[textureID]){
path = AssetDatabase.GetAssetPath(overlayElementList[i].textureList[textureID]);
TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
textureImporter.isReadable = readWrite.boolValue;
if(compress.boolValue){
#if UNITY_5_5_OR_NEWER
textureImporter.textureCompression = TextureImporterCompression.CompressedHQ;
textureImporter.compressionQuality = (int)TextureCompressionQuality.Best;
#else
textureImporter.textureFormat = TextureImporterFormat.AutomaticCompressed;
textureImporter.compressionQuality = (int)TextureCompressionQuality.Best;
#endif
}else{
#if UNITY_5_5_OR_NEWER
textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
#else
textureImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor;
textureImporter.compressionQuality = (int)TextureCompressionQuality.Best;
#endif
}
AssetDatabase.WriteImportSettingsIfDirty (path);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
Debug.Log(overlayElementList[i].textureList[textureID].name + " isReadable set to " + readWrite.boolValue + " and compression set to " + compress.boolValue);
}
}
}
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
private void DropAreaGUI(Rect dropArea){
var evt = Event.current;
if(evt.type == EventType.DragUpdated){
if(dropArea.Contains(evt.mousePosition)){
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
if(evt.type == EventType.DragPerform){
if(dropArea.Contains(evt.mousePosition)){
DragAndDrop.AcceptDrag();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences;
for(int i = 0; i < draggedObjects.Length; i++){
if (draggedObjects[i])
{
OverlayDataAsset tempOverlayData = draggedObjects[i] as OverlayDataAsset;
if (tempOverlayData)
{
AddOverlayData(tempOverlayData);
continue;
}
var path = AssetDatabase.GetAssetPath(draggedObjects[i]);
if (System.IO.Directory.Exists(path))
{
RecursiveScanFoldersForAssets(path);
}
}
}
}
}
}
private void RecursiveScanFoldersForAssets(string path)
{
var assetFiles = System.IO.Directory.GetFiles(path, "*.asset");
foreach (var assetFile in assetFiles)
{
var tempOverlayData = AssetDatabase.LoadAssetAtPath(assetFile, typeof(OverlayDataAsset)) as OverlayDataAsset;
if (tempOverlayData)
{
AddOverlayData(tempOverlayData);
}
}
foreach (var subFolder in System.IO.Directory.GetDirectories(path))
{
RecursiveScanFoldersForAssets(subFolder.Replace('\\', '/'));
}
}
public override void OnInspectorGUI(){
m_Object.Update();
serializedObject.Update();
GUILayout.Label ("overlayList", EditorStyles.boldLabel);
OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
GUILayout.Space(30);
GUILayout.Label ("Overlays reduced " + scaleAdjust.intValue +" time(s)");
GUILayout.BeginHorizontal();
if(scaleAdjust.intValue > 0){
if(GUILayout.Button("Resolution +")){
ScaleUpTextures();
isDirty = true;
canUpdate = false;
scaleAdjust.intValue --;
}
}
if(GUILayout.Button("Resolution -")){
ScaleDownTextures();
isDirty = true;
canUpdate = false;
scaleAdjust.intValue ++;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.BeginHorizontal();
compress.boolValue = GUILayout.Toggle (compress.boolValue ? true : false," Compress Textures");
readWrite.boolValue = GUILayout.Toggle (readWrite.boolValue ? true : false," Read/Write");
if(GUILayout.Button(" Apply")){
ConfigureTextures();
isDirty = true;
canUpdate = false;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.BeginHorizontal();
if(GUILayout.Button("Order by Name")){
canUpdate = false;
List<OverlayDataAsset> OverlayDataTemp = overlayElementList.ToList();
//Make sure there's no invalid data
for(int i = 0; i < OverlayDataTemp.Count; i++){
if(OverlayDataTemp[i] == null){
OverlayDataTemp.RemoveAt(i);
i--;
}
}
OverlayDataTemp.Sort((x,y) => x.name.CompareTo(y.name));
for(int i = 0; i < OverlayDataTemp.Count; i++){
SetOverlayData(i,OverlayDataTemp[i]);
}
}
if(GUILayout.Button("Update List")){
isDirty = true;
canUpdate = false;
}
if (GUILayout.Button("Remove Duplicates"))
{
HashSet<OverlayDataAsset> Overlays = new HashSet<OverlayDataAsset>();
foreach(OverlayDataAsset oda in overlayElementList)
{
Overlays.Add(oda);
}
m_OverlayDataCount.intValue = Overlays.Count;
for(int i=0;i<Overlays.Count;i++)
{
SetOverlayData(i,Overlays.ElementAt(i));
}
isDirty = true;
canUpdate = false;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
Rect dropArea = GUILayoutUtility.GetRect(0.0f,50.0f, GUILayout.ExpandWidth(true));
GUI.Box(dropArea,"Drag Overlays here");
GUILayout.Space(20);
for(int i = 0; i < m_OverlayDataCount.intValue; i ++){
GUILayout.BeginHorizontal();
var result = EditorGUILayout.ObjectField(overlayElementList[i], typeof(OverlayDataAsset), true) as OverlayDataAsset;
if(GUI.changed && canUpdate){
SetOverlayData(i,result);
}
if(GUILayout.Button("-", GUILayout.Width(20.0f))){
canUpdate = false;
RemoveOverlayDataAtIndex(i);
}
GUILayout.EndHorizontal();
if(i == m_OverlayDataCount.intValue -1){
canUpdate = true;
if(isDirty){
overlayLibrary.UpdateDictionary();
isDirty = false;
}
}
}
DropAreaGUI(dropArea);
if(GUILayout.Button("Add OverlayData")){
AddOverlayData(null);
}
if(GUILayout.Button("Clear List")){
m_OverlayDataCount.intValue = 0;
}
m_Object.ApplyModifiedProperties();
serializedObject.ApplyModifiedProperties();
}
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
using System;
using Generator.Enums;
using Generator.Enums.InstructionInfo;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
namespace Generator.Tables {
sealed class ImpliedAccessesDef {
public readonly ImpliedAccesses ImpliedAccesses;
public readonly EnumValue EnumValue;
public ImpliedAccessesDef(ImpliedAccesses impliedAccesses, EnumValue enumValue) {
ImpliedAccesses = impliedAccesses;
EnumValue = enumValue;
}
}
sealed class ImpliedAccesses : IEquatable<ImpliedAccesses?> {
public readonly List<ImplAccCondition> Conditions;
public ImpliedAccesses() => Conditions = new List<ImplAccCondition>();
public ImpliedAccesses(List<ImplAccCondition> conditions) => Conditions = conditions;
public override bool Equals(object? obj) => Equals(obj as ImpliedAccesses);
public bool Equals(ImpliedAccesses? other) {
if (other is null)
return false;
if (Conditions.Count != other.Conditions.Count)
return false;
for (int i = 0; i < Conditions.Count; i++) {
if (!Conditions[i].Equals(other.Conditions[i]))
return false;
}
return true;
}
public override int GetHashCode() {
int hc = 0;
foreach (var cond in Conditions)
hc = HashCode.Combine(hc, cond);
return hc;
}
}
enum ImplAccConditionKind {
// No condition
None,
// 64-bit code only
Bit64,
// Not 64-bit code (16 or 32-bit code only)
NotBit64,
}
sealed class ImplAccCondition : IEquatable<ImplAccCondition?> {
public readonly ImplAccConditionKind Kind;
public readonly List<ImplAccStatement> TrueStatements = new List<ImplAccStatement>();
public readonly List<ImplAccStatement> FalseStatements = new List<ImplAccStatement>();
public ImplAccCondition(ImplAccConditionKind kind) => Kind = kind;
public override bool Equals(object? obj) => Equals(obj as ImplAccCondition);
public bool Equals(ImplAccCondition? other) =>
other is not null && Kind == other.Kind && Equals(TrueStatements, other.TrueStatements) && Equals(FalseStatements, other.FalseStatements);
static bool Equals(List<ImplAccStatement> a, List<ImplAccStatement> b) {
if (a.Count != b.Count)
return false;
for (int i = 0; i < a.Count; i++) {
if (!a[i].Equals(b[i]))
return false;
}
return true;
}
public override int GetHashCode() {
int hc = HashCode.Combine(Kind);
foreach (var stmt in TrueStatements)
hc = HashCode.Combine(hc, stmt);
foreach (var stmt in FalseStatements)
hc = HashCode.Combine(hc, stmt);
return hc;
}
}
enum ImplAccRegisterKind {
/// <summary>A Register enum value</summary>
Register,
/// <summary>Use segment prefix, or DS if no segment prefix</summary>
SegmentDefaultDS,
/// <summary>DI, EDI, or RDI depending on address size</summary>
a_rDI,
/// <summary>Use op #0's register prop</summary>
Op0,
/// <summary>Use op #1's register prop</summary>
Op1,
/// <summary>Use op #2's register prop</summary>
Op2,
/// <summary>Use op #3's register prop</summary>
Op3,
/// <summary>Use op #4's register prop</summary>
Op4,
}
readonly struct ImplAccRegister : IEquatable<ImplAccRegister>, IComparable<ImplAccRegister> {
public readonly ImplAccRegisterKind Kind;
public readonly EnumValue? Register;
public ImplAccRegister(EnumValue register) {
Kind = ImplAccRegisterKind.Register;
Register = register;
}
public ImplAccRegister(ImplAccRegisterKind kind) {
if (kind == ImplAccRegisterKind.Register)
throw new ArgumentOutOfRangeException(nameof(kind));
Kind = kind;
Register = null;
}
public static bool operator ==(ImplAccRegister left, ImplAccRegister right) => left.Equals(right);
public static bool operator !=(ImplAccRegister left, ImplAccRegister right) => !left.Equals(right);
public bool Equals(ImplAccRegister other) => Kind == other.Kind && Register == other.Register;
public override bool Equals(object? obj) => obj is ImplAccRegister other && Equals(other);
public override int GetHashCode() => HashCode.Combine(Kind, Register);
public int CompareTo(ImplAccRegister other) {
int c;
c = Kind.CompareTo(other.Kind);
if (c != 0) return c;
if (Kind == ImplAccRegisterKind.Register) {
if (Register is EnumValue r1 && other.Register is EnumValue r2)
return r1.Value.CompareTo(r2.Value);
throw new InvalidOperationException();
}
else {
if (Register is not null || other.Register is not null)
throw new InvalidOperationException();
return 0;
}
}
}
enum ImplAccMemorySizeKind {
/// <summary>A MemorySize enum value</summary>
MemorySize,
/// <summary>Use the instruction's memory size property</summary>
Default,
}
readonly struct ImplAccMemorySize : IEquatable<ImplAccMemorySize>, IComparable<ImplAccMemorySize> {
public readonly ImplAccMemorySizeKind Kind;
public readonly EnumValue? MemorySize;
public ImplAccMemorySize(EnumValue memorySize) {
Kind = ImplAccMemorySizeKind.MemorySize;
MemorySize = memorySize;
}
public ImplAccMemorySize(ImplAccMemorySizeKind kind) {
if (kind == ImplAccMemorySizeKind.MemorySize)
throw new ArgumentOutOfRangeException(nameof(kind));
Kind = kind;
MemorySize = null;
}
public static bool operator ==(ImplAccMemorySize left, ImplAccMemorySize right) => left.Equals(right);
public static bool operator !=(ImplAccMemorySize left, ImplAccMemorySize right) => !left.Equals(right);
public bool Equals(ImplAccMemorySize other) => Kind == other.Kind && MemorySize == other.MemorySize;
public override bool Equals(object? obj) => obj is ImplAccMemorySize size && Equals(size);
public override int GetHashCode() => HashCode.Combine(Kind, MemorySize);
public int CompareTo(ImplAccMemorySize other) {
if (Kind != other.Kind)
return Kind.CompareTo(other.Kind);
if (Kind == ImplAccMemorySizeKind.MemorySize) {
if (MemorySize is EnumValue m1 && other.MemorySize is EnumValue m2)
return m1.Value.CompareTo(m2.Value);
throw new InvalidOperationException();
}
else {
if (MemorySize is not null && other.MemorySize is not null)
throw new InvalidOperationException();
return 0;
}
}
}
enum ImplAccStatementKind {
// These check an internal array and won't work if other statements add more registers. Put them first so they're sorted first.
Arpl,
LastGpr8,
LastGpr16,
LastGpr32,
MemoryAccess,
RegisterAccess,
RegisterRangeAccess,
ShiftMask,
ShiftMask1FMod,
ZeroRegRflags,
ZeroRegRegmem,
ZeroRegRegRegmem,
EmmiReg,
Enter,
Leave,
Push,
Pop,
PopRm,
Pusha,
Popa,
lea,
Cmps,
Ins,
Lods,
Movs,
Outs,
Scas,
Stos,
Xstore,
}
abstract class ImplAccStatement : IEquatable<ImplAccStatement> {
public abstract ImplAccStatementKind Kind { get; }
public abstract bool Equals([AllowNull] ImplAccStatement other);
public sealed override bool Equals(object? obj) => obj is ImplAccStatement other && Equals(other);
public abstract override int GetHashCode();
}
sealed class NoArgImplAccStatement : ImplAccStatement {
public override ImplAccStatementKind Kind { get; }
public NoArgImplAccStatement(ImplAccStatementKind kind) => Kind = kind;
public override bool Equals([AllowNull] ImplAccStatement obj) => obj is NoArgImplAccStatement other && Kind == other.Kind;
public override int GetHashCode() => HashCode.Combine(Kind);
}
enum EmmiAccess {
Read,
Write,
ReadWrite,
}
sealed class EmmiImplAccStatement : ImplAccStatement, IComparable<EmmiImplAccStatement> {
public override ImplAccStatementKind Kind => ImplAccStatementKind.EmmiReg;
public readonly EmmiAccess Access;
public EmmiImplAccStatement(EmmiAccess access) => Access = access;
public override bool Equals([AllowNull] ImplAccStatement obj) => obj is EmmiImplAccStatement other && Access == other.Access;
public override int GetHashCode() => HashCode.Combine(Access);
public int CompareTo([AllowNull] EmmiImplAccStatement other) {
if (other is null)
return 1;
return Access.CompareTo(other.Access);
}
}
sealed class IntArgImplAccStatement : ImplAccStatement, IComparable<IntArgImplAccStatement> {
public override ImplAccStatementKind Kind { get; }
public readonly uint Arg;
public IntArgImplAccStatement(ImplAccStatementKind kind, uint arg) {
Kind = kind;
Arg = arg;
}
public override bool Equals([AllowNull] ImplAccStatement obj) => obj is IntArgImplAccStatement other && Kind == other.Kind && Arg == other.Arg;
public override int GetHashCode() => HashCode.Combine(Kind, Arg);
public int CompareTo([AllowNull] IntArgImplAccStatement other) {
if (other is null)
return 1;
return Arg.CompareTo(other.Arg);
}
}
sealed class IntX2ArgImplAccStatement : ImplAccStatement, IComparable<IntX2ArgImplAccStatement> {
public override ImplAccStatementKind Kind { get; }
public readonly uint Arg1;
public readonly uint Arg2;
public IntX2ArgImplAccStatement(ImplAccStatementKind kind, uint arg1, uint arg2) {
Kind = kind;
Arg1 = arg1;
Arg2 = arg2;
}
public override bool Equals([AllowNull] ImplAccStatement obj) => obj is IntX2ArgImplAccStatement other && Kind == other.Kind && Arg1 == other.Arg1 && Arg2 == other.Arg2;
public override int GetHashCode() => HashCode.Combine(Kind, Arg1, Arg2);
public int CompareTo([AllowNull] IntX2ArgImplAccStatement other) {
if (other is null)
return 1;
int c;
c = Kind.CompareTo(other.Kind);
if (c != 0) return c;
c = Arg1.CompareTo(other.Arg1);
if (c != 0) return c;
return Arg2.CompareTo(other.Arg2);
}
}
sealed class RegisterRangeImplAccStatement : ImplAccStatement, IComparable<RegisterRangeImplAccStatement> {
public override ImplAccStatementKind Kind => ImplAccStatementKind.RegisterRangeAccess;
public readonly OpAccess Access;
public readonly EnumValue RegisterFirst;
public readonly EnumValue RegisterLast;
public RegisterRangeImplAccStatement(OpAccess access, EnumValue registerFirst, EnumValue registerLast) {
Access = access;
RegisterFirst = registerFirst;
RegisterLast = registerLast;
}
public override bool Equals([AllowNull] ImplAccStatement obj) =>
obj is RegisterRangeImplAccStatement other && Access == other.Access && RegisterFirst == other.RegisterFirst && RegisterLast == other.RegisterLast;
public override int GetHashCode() => HashCode.Combine(Access, RegisterFirst, RegisterLast);
public int CompareTo([AllowNull] RegisterRangeImplAccStatement other) {
if (other is null)
return 1;
int c;
c = Access.CompareTo(other.Access);
if (c != 0) return c;
c = RegisterFirst.Value.CompareTo(other.RegisterFirst.Value);
if (c != 0) return c;
return RegisterLast.Value.CompareTo(other.RegisterLast.Value);
}
}
sealed class RegisterImplAccStatement : ImplAccStatement, IComparable<RegisterImplAccStatement> {
public override ImplAccStatementKind Kind => ImplAccStatementKind.RegisterAccess;
public readonly OpAccess Access;
public readonly ImplAccRegister Register;
public readonly bool IsMemOpSegRead;
public RegisterImplAccStatement(OpAccess access, ImplAccRegister register, bool isMemOpSegRead) {
IsMemOpSegRead = register.Kind == ImplAccRegisterKind.SegmentDefaultDS;
if (isMemOpSegRead) {
if (register.Kind == ImplAccRegisterKind.Register) {
switch ((Register)register.Register!.Value) {
case Enums.Register.ES:
case Enums.Register.CS:
case Enums.Register.SS:
case Enums.Register.DS:
IsMemOpSegRead = true;
break;
}
}
}
Access = access;
Register = register;
}
public override bool Equals([AllowNull] ImplAccStatement obj) =>
obj is RegisterImplAccStatement other && Access == other.Access && Register == other.Register && IsMemOpSegRead == other.IsMemOpSegRead;
public override int GetHashCode() => HashCode.Combine(Access, Register, IsMemOpSegRead);
public int CompareTo([AllowNull] RegisterImplAccStatement other) {
if (other is null)
return 1;
int c;
c = Access.CompareTo(other.Access);
if (c != 0) return c;
c = IsMemOpSegRead.CompareTo(other.IsMemOpSegRead);
if (c != 0) return c;
return Register.CompareTo(other.Register);
}
}
sealed class MemoryImplAccStatement : ImplAccStatement, IComparable<MemoryImplAccStatement> {
public override ImplAccStatementKind Kind => ImplAccStatementKind.MemoryAccess;
public readonly OpAccess Access;
public readonly ImplAccRegister? Segment;
public readonly ImplAccRegister? Base;
public readonly ImplAccRegister? Index;
public readonly int Scale;
public ulong Displacement => 0;
public readonly ImplAccMemorySize MemorySize;
public readonly CodeSize AddressSize;
public readonly uint VsibSize;
public MemoryImplAccStatement(OpAccess access, ImplAccRegister? segment, ImplAccRegister? @base, ImplAccRegister? index, int scale, ImplAccMemorySize memorySize, CodeSize addressSize, uint vsibSize) {
if (vsibSize != 0 && vsibSize != 4 && vsibSize != 8)
throw new ArgumentOutOfRangeException(nameof(vsibSize));
Access = access;
Segment = segment;
Base = @base;
Index = index;
Scale = scale;
MemorySize = memorySize;
AddressSize = addressSize;
VsibSize = vsibSize;
}
public override bool Equals([AllowNull] ImplAccStatement obj) =>
obj is MemoryImplAccStatement other &&
Access == other.Access && Segment == other.Segment &&
Base == other.Base && Index == other.Index && Scale == other.Scale &&
MemorySize == other.MemorySize &&
AddressSize == other.AddressSize &&
VsibSize == other.VsibSize;
public override int GetHashCode() => HashCode.Combine(Access, Segment, Base, Index, Scale, MemorySize, AddressSize, VsibSize);
public int CompareTo([AllowNull] MemoryImplAccStatement other) {
if (other is null)
return 1;
int c;
c = Access.CompareTo(other.Access);
if (c != 0) return c;
c = CompareTo(Segment, other.Segment);
if (c != 0) return c;
c = CompareTo(Base, other.Base);
if (c != 0) return c;
c = CompareTo(Index, other.Index);
if (c != 0) return c;
c = Scale.CompareTo(other.Scale);
if (c != 0) return c;
c = MemorySize.CompareTo(other.MemorySize);
if (c != 0) return c;
c = AddressSize.CompareTo(other.AddressSize);
if (c != 0) return c;
return VsibSize.CompareTo(other.VsibSize);
}
static int CompareTo(ImplAccRegister? a, ImplAccRegister? b) {
if (a == b)
return 0;
if (a is null)
return -1;
if (b is null)
return 1;
return a.GetValueOrDefault().CompareTo(b.GetValueOrDefault());
}
}
sealed class ImpliedAccessEnumFactory {
readonly Dictionary<ImpliedAccesses, ImpliedAccessesDef> toDef;
readonly List<ImpliedAccessesDef> hardCodedDefs;
readonly List<ImpliedAccessesDef> otherDefs;
readonly ImpliedAccessesDef noneDef;
readonly HashSet<string> usedEnumNames;
readonly StringBuilder sb;
public ImpliedAccessEnumFactory() {
toDef = new Dictionary<ImpliedAccesses, ImpliedAccessesDef>();
hardCodedDefs = new List<ImpliedAccessesDef>();
otherDefs = new List<ImpliedAccessesDef>();
usedEnumNames = new HashSet<string>(StringComparer.Ordinal);
sb = new StringBuilder();
noneDef = AddHardCodedValue("None", new ImpliedAccesses());
// The order is important. The code assumes this order, see Instruction.Info.cs
AddHardCodedValue("Shift_Ib_MASK1FMOD9", new IntArgImplAccStatement(ImplAccStatementKind.ShiftMask1FMod, 9));
AddHardCodedValue("Shift_Ib_MASK1FMOD11", new IntArgImplAccStatement(ImplAccStatementKind.ShiftMask1FMod, 17));
AddHardCodedValue("Shift_Ib_MASK1F", new IntArgImplAccStatement(ImplAccStatementKind.ShiftMask, 0x1F));
AddHardCodedValue("Shift_Ib_MASK3F", new IntArgImplAccStatement(ImplAccStatementKind.ShiftMask, 0x3F));
AddHardCodedValue("Clear_rflags", new NoArgImplAccStatement(ImplAccStatementKind.ZeroRegRflags));
}
void AddHardCodedValue(string enumValueName, ImplAccStatement impAcc) {
var cond = new ImplAccCondition(ImplAccConditionKind.None);
cond.TrueStatements.Add(impAcc);
var accesses = new ImpliedAccesses(new List<ImplAccCondition> { cond });
AddHardCodedValue(enumValueName, accesses);
}
ImpliedAccessesDef AddHardCodedValue(string enumValueName, ImpliedAccesses accesses) {
usedEnumNames.Add(enumValueName);
var enumValue = new EnumValue(0, enumValueName, null);
var def = new ImpliedAccessesDef(accesses, enumValue);
hardCodedDefs.Add(def);
toDef.Add(accesses, def);
return def;
}
public ImpliedAccessesDef Add(ImpliedAccesses? accesses) {
if (accesses is null)
return noneDef;
if (toDef.TryGetValue(accesses, out var def))
return def;
var name = GetEnumName(accesses);
var enumValue = new EnumValue(0, name, null);
def = new ImpliedAccessesDef(accesses, enumValue);
toDef.Add(accesses, def);
otherDefs.Add(def);
return def;
}
string GetEnumName(ImpliedAccesses accesses) {
var name = CreateName(sb, accesses);
if (name.Length == 0)
throw new InvalidOperationException();
const int MaxNameLength = 100;
if (name.Length > MaxNameLength)
name = name[0..MaxNameLength] + "_etc";
for (int i = 0; ; i++) {
var newName = i == 0 ? name : name + "_" + i.ToString();
if (usedEnumNames.Add(newName))
return newName;
}
throw new InvalidOperationException();
}
static string CreateName(StringBuilder sb, ImpliedAccesses accesses) {
sb.Clear();
foreach (var cond in accesses.Conditions) {
if (sb.Length > 0)
sb.Append('_');
switch (cond.Kind) {
case ImplAccConditionKind.None: break;
case ImplAccConditionKind.Bit64: sb.Append("b64"); break;
case ImplAccConditionKind.NotBit64: sb.Append("n64"); break;
default: throw new InvalidOperationException();
}
CreateName(sb, "t", cond.TrueStatements);
CreateName(sb, "f", cond.FalseStatements);
}
return sb.ToString();
}
static void CreateName(StringBuilder sb, string name, List<ImplAccStatement> stmts) {
if (stmts.Count == 0)
return;
if (sb.Length > 0)
sb.Append('_');
sb.Append(name);
foreach (var stmt in stmts) {
sb.Append('_');
IntArgImplAccStatement arg1;
IntX2ArgImplAccStatement arg2;
switch (stmt.Kind) {
case ImplAccStatementKind.MemoryAccess:
var mem = (MemoryImplAccStatement)stmt;
sb.Append(GetAccess(mem.Access));
sb.Append("mem");
break;
case ImplAccStatementKind.RegisterAccess:
var reg = (RegisterImplAccStatement)stmt;
sb.Append(GetAccess(reg.Access));
sb.Append(GetRegister(reg.Register));
break;
case ImplAccStatementKind.RegisterRangeAccess:
var rreg = (RegisterRangeImplAccStatement)stmt;
sb.Append(GetAccess(rreg.Access));
sb.Append(rreg.RegisterFirst.RawName.ToLowerInvariant());
sb.Append("TO");
sb.Append(rreg.RegisterLast.RawName.ToLowerInvariant());
break;
case ImplAccStatementKind.ShiftMask:
arg1 = (IntArgImplAccStatement)stmt;
sb.Append($"sm{arg1.Arg:X}");
break;
case ImplAccStatementKind.ZeroRegRflags:
sb.Append("zrfl");
break;
case ImplAccStatementKind.ZeroRegRegmem:
sb.Append("zrrm");
break;
case ImplAccStatementKind.ZeroRegRegRegmem:
sb.Append("zrrrm");
break;
case ImplAccStatementKind.Arpl:
sb.Append("arpl");
break;
case ImplAccStatementKind.LastGpr8:
sb.Append("gpr8");
break;
case ImplAccStatementKind.LastGpr16:
sb.Append("gpr16");
break;
case ImplAccStatementKind.LastGpr32:
sb.Append("gpr32");
break;
case ImplAccStatementKind.lea:
sb.Append("lea");
break;
case ImplAccStatementKind.Cmps:
sb.Append("cmps");
break;
case ImplAccStatementKind.Ins:
sb.Append("ins");
break;
case ImplAccStatementKind.Lods:
sb.Append("lods");
break;
case ImplAccStatementKind.Movs:
sb.Append("movs");
break;
case ImplAccStatementKind.Outs:
sb.Append("outs");
break;
case ImplAccStatementKind.Scas:
sb.Append("scas");
break;
case ImplAccStatementKind.Stos:
sb.Append("stos");
break;
case ImplAccStatementKind.Xstore:
arg1 = (IntArgImplAccStatement)stmt;
sb.Append($"xstore{arg1.Arg}");
break;
case ImplAccStatementKind.ShiftMask1FMod:
arg1 = (IntArgImplAccStatement)stmt;
sb.Append($"sm1Fm{arg1.Arg}");
break;
case ImplAccStatementKind.Enter:
arg1 = (IntArgImplAccStatement)stmt;
sb.Append($"enter{arg1.Arg}");
break;
case ImplAccStatementKind.Leave:
arg1 = (IntArgImplAccStatement)stmt;
sb.Append($"leave{arg1.Arg}");
break;
case ImplAccStatementKind.PopRm:
arg1 = (IntArgImplAccStatement)stmt;
sb.Append($"poprm{arg1.Arg}");
break;
case ImplAccStatementKind.Pusha:
arg1 = (IntArgImplAccStatement)stmt;
sb.Append($"pusha{arg1.Arg}");
break;
case ImplAccStatementKind.Popa:
arg1 = (IntArgImplAccStatement)stmt;
sb.Append($"popa{arg1.Arg}");
break;
case ImplAccStatementKind.Push:
arg2 = (IntX2ArgImplAccStatement)stmt;
sb.Append($"push{arg2.Arg1}x{arg2.Arg2}");
break;
case ImplAccStatementKind.Pop:
arg2 = (IntX2ArgImplAccStatement)stmt;
sb.Append($"pop{arg2.Arg1}x{arg2.Arg2}");
break;
case ImplAccStatementKind.EmmiReg:
var emmi = (EmmiImplAccStatement)stmt;
sb.Append("emmi");
switch (emmi.Access) {
case EmmiAccess.Read: sb.Append('R'); break;
case EmmiAccess.Write: sb.Append('W'); break;
case EmmiAccess.ReadWrite: sb.Append("RW"); break;
default: throw new InvalidOperationException();
}
break;
default:
throw new InvalidOperationException();
}
}
}
static string GetRegister(ImplAccRegister register) =>
register.Kind switch {
ImplAccRegisterKind.Register => register.Register!.RawName.ToLowerInvariant(),
ImplAccRegisterKind.SegmentDefaultDS => "seg",
ImplAccRegisterKind.a_rDI => "arDI",
ImplAccRegisterKind.Op0 => "op0reg",
ImplAccRegisterKind.Op1 => "op1reg",
ImplAccRegisterKind.Op2 => "op2reg",
ImplAccRegisterKind.Op3 => "op3reg",
ImplAccRegisterKind.Op4 => "op4reg",
_ => throw new InvalidOperationException(),
};
static string GetAccess(OpAccess access) =>
access switch {
OpAccess.None => string.Empty,
OpAccess.Read => "R",
OpAccess.CondRead => "CR",
OpAccess.Write => "W",
OpAccess.CondWrite => "CW",
OpAccess.ReadWrite => "RW",
OpAccess.ReadCondWrite => "RCW",
OpAccess.NoMemAccess => "NMA",
_ => throw new InvalidOperationException(),
};
public (EnumType type, ImpliedAccessesDef[] defs) CreateEnum() {
var values = new List<ImpliedAccessesDef>(hardCodedDefs.Count + otherDefs.Count);
values.AddRange(hardCodedDefs);
values.AddRange(otherDefs);
return (new EnumType(TypeIds.ImpliedAccess, null, values.Select(a => a.EnumValue).ToArray(), EnumTypeFlags.None), values.ToArray());
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Agent.Sdk.Knob;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.WebApi;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
using System.Linq;
using Microsoft.VisualStudio.Services.Common;
using System.Diagnostics;
namespace Microsoft.VisualStudio.Services.Agent.Listener
{
[ServiceLocator(Default = typeof(JobDispatcher))]
public interface IJobDispatcher : IAgentService
{
TaskCompletionSource<bool> RunOnceJobCompleted { get; }
void Run(Pipelines.AgentJobRequestMessage message, bool runOnce = false);
bool Cancel(JobCancelMessage message);
void MetadataUpdate(JobMetadataMessage message);
Task WaitAsync(CancellationToken token);
Task ShutdownAsync();
}
// This implementation of IJobDispatcher is not thread safe.
// It is base on the fact that the current design of agent is dequeue
// and process one message from message queue everytime.
// In addition, it only execute one job every time,
// and server will not send another job while this one is still running.
public sealed class JobDispatcher : AgentService, IJobDispatcher
{
private int _poolId;
AgentSettings _agentSetting;
private static readonly string _workerProcessName = $"Agent.Worker{IOUtil.ExeExtension}";
// this is not thread-safe
private readonly Queue<Guid> _jobDispatchedQueue = new Queue<Guid>();
private readonly ConcurrentDictionary<Guid, WorkerDispatcher> _jobInfos = new ConcurrentDictionary<Guid, WorkerDispatcher>();
//allow up to 30sec for any data to be transmitted over the process channel
//timeout limit can be overwrite by environment VSTS_AGENT_CHANNEL_TIMEOUT
private TimeSpan _channelTimeout;
private TaskCompletionSource<bool> _runOnceJobCompleted = new TaskCompletionSource<bool>();
public override void Initialize(IHostContext hostContext)
{
ArgUtil.NotNull(hostContext, nameof(hostContext));
base.Initialize(hostContext);
// get pool id from config
var configurationStore = hostContext.GetService<IConfigurationStore>();
_agentSetting = configurationStore.GetSettings();
_poolId = _agentSetting.PoolId;
int channelTimeoutSeconds = AgentKnobs.AgentChannelTimeout.GetValue(UtilKnobValueContext.Instance()).AsInt();
// _channelTimeout should in range [30, 300] seconds
_channelTimeout = TimeSpan.FromSeconds(Math.Min(Math.Max(channelTimeoutSeconds, 30), 300));
Trace.Info($"Set agent/worker IPC timeout to {_channelTimeout.TotalSeconds} seconds.");
}
public TaskCompletionSource<bool> RunOnceJobCompleted => _runOnceJobCompleted;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "WorkerDispatcher")]
public void Run(Pipelines.AgentJobRequestMessage jobRequestMessage, bool runOnce = false)
{
ArgUtil.NotNull(jobRequestMessage, nameof(jobRequestMessage));
Trace.Info($"Job request {jobRequestMessage.RequestId} for plan {jobRequestMessage.Plan.PlanId} job {jobRequestMessage.JobId} received.");
WorkerDispatcher currentDispatch = null;
if (_jobDispatchedQueue.Count > 0)
{
Guid dispatchedJobId = _jobDispatchedQueue.Dequeue();
if (_jobInfos.TryGetValue(dispatchedJobId, out currentDispatch))
{
Trace.Verbose($"Retrieve previous WorkerDispather for job {currentDispatch.JobId}.");
}
}
WorkerDispatcher newDispatch = new WorkerDispatcher(jobRequestMessage.JobId, jobRequestMessage.RequestId);
if (runOnce)
{
Trace.Info("Start dispatcher for one time used agent.");
jobRequestMessage.Variables[Constants.Variables.Agent.RunMode] = new VariableValue(Constants.Agent.CommandLine.Flags.Once);
newDispatch.WorkerDispatch = RunOnceAsync(jobRequestMessage, currentDispatch, newDispatch);
}
else
{
newDispatch.WorkerDispatch = RunAsync(jobRequestMessage, currentDispatch, newDispatch);
}
_jobInfos.TryAdd(newDispatch.JobId, newDispatch);
_jobDispatchedQueue.Enqueue(newDispatch.JobId);
}
public void MetadataUpdate(JobMetadataMessage jobMetadataMessage)
{
ArgUtil.NotNull(jobMetadataMessage, nameof(jobMetadataMessage));
Trace.Info($"Job metadata update received");
WorkerDispatcher workerDispatcher;
if (!_jobInfos.TryGetValue(jobMetadataMessage.JobId, out workerDispatcher))
{
Trace.Verbose($"Job request {jobMetadataMessage.JobId} is not a current running job, ignore metadata update.");
}
else
{
workerDispatcher.UpdateMetadata(jobMetadataMessage);
Trace.Verbose($"Fired metadata update for job request {workerDispatcher.JobId}.");
}
}
public bool Cancel(JobCancelMessage jobCancelMessage)
{
ArgUtil.NotNull(jobCancelMessage, nameof(jobCancelMessage));
Trace.Info($"Job cancellation request {jobCancelMessage.JobId} received, cancellation timeout {jobCancelMessage.Timeout.TotalMinutes} minutes.");
WorkerDispatcher workerDispatcher;
if (!_jobInfos.TryGetValue(jobCancelMessage.JobId, out workerDispatcher))
{
Trace.Verbose($"Job request {jobCancelMessage.JobId} is not a current running job, ignore cancllation request.");
return false;
}
else
{
if (workerDispatcher.Cancel(jobCancelMessage.Timeout))
{
Trace.Verbose($"Fired cancellation token for job request {workerDispatcher.JobId}.");
}
return true;
}
}
public async Task WaitAsync(CancellationToken token)
{
WorkerDispatcher currentDispatch = null;
Guid dispatchedJobId;
if (_jobDispatchedQueue.Count > 0)
{
dispatchedJobId = _jobDispatchedQueue.Dequeue();
if (_jobInfos.TryGetValue(dispatchedJobId, out currentDispatch))
{
Trace.Verbose($"Retrive previous WorkerDispather for job {currentDispatch.JobId}.");
}
}
else
{
Trace.Verbose($"There is no running WorkerDispather needs to await.");
}
if (currentDispatch != null)
{
using (var registration = token.Register(() => { if (currentDispatch.Cancel(TimeSpan.FromSeconds(60))) { Trace.Verbose($"Fired cancellation token for job request {currentDispatch.JobId}."); } }))
{
try
{
Trace.Info($"Waiting WorkerDispather for job {currentDispatch.JobId} run to finish.");
await currentDispatch.WorkerDispatch;
Trace.Info($"Job request {currentDispatch.JobId} processed successfully.");
}
catch (Exception ex)
{
Trace.Error($"Worker Dispatch failed with an exception for job request {currentDispatch.JobId}.");
Trace.Error(ex);
}
finally
{
WorkerDispatcher workerDispatcher;
if (_jobInfos.TryRemove(currentDispatch.JobId, out workerDispatcher))
{
Trace.Verbose($"Remove WorkerDispather from {nameof(_jobInfos)} dictionary for job {currentDispatch.JobId}.");
workerDispatcher.Dispose();
}
}
}
}
}
public async Task ShutdownAsync()
{
Trace.Info($"Shutting down JobDispatcher. Make sure all WorkerDispatcher has finished.");
WorkerDispatcher currentDispatch = null;
if (_jobDispatchedQueue.Count > 0)
{
Guid dispatchedJobId = _jobDispatchedQueue.Dequeue();
if (_jobInfos.TryGetValue(dispatchedJobId, out currentDispatch))
{
try
{
Trace.Info($"Ensure WorkerDispather for job {currentDispatch.JobId} run to finish, cancel any running job.");
await EnsureDispatchFinished(currentDispatch, cancelRunningJob: true);
}
catch (Exception ex)
{
Trace.Error($"Catching worker dispatch exception for job request {currentDispatch.JobId} durning job dispatcher shut down.");
Trace.Error(ex);
}
finally
{
WorkerDispatcher workerDispatcher;
if (_jobInfos.TryRemove(currentDispatch.JobId, out workerDispatcher))
{
Trace.Verbose($"Remove WorkerDispather from {nameof(_jobInfos)} dictionary for job {currentDispatch.JobId}.");
workerDispatcher.Dispose();
}
}
}
}
}
private async Task EnsureDispatchFinished(WorkerDispatcher jobDispatch, bool cancelRunningJob = false)
{
if (!jobDispatch.WorkerDispatch.IsCompleted)
{
if (cancelRunningJob)
{
// cancel running job when shutting down the agent.
// this will happen when agent get Ctrl+C or message queue loop crashed.
jobDispatch.WorkerCancellationTokenSource.Cancel();
// wait for worker process exit then return.
await jobDispatch.WorkerDispatch;
return;
}
// base on the current design, server will only send one job for a given agent everytime.
// if the agent received a new job request while a previous job request is still running, this typically indicate two situations
// 1. an agent bug cause server and agent mismatch on the state of the job request, ex. agent not renew jobrequest properly but think it still own the job reqest, however server already abandon the jobrequest.
// 2. a server bug or design change that allow server send more than one job request to an given agent that haven't finish previous job request.
var agentServer = HostContext.GetService<IAgentServer>();
TaskAgentJobRequest request = null;
try
{
request = await agentServer.GetAgentRequestAsync(_poolId, jobDispatch.RequestId, CancellationToken.None);
}
catch (Exception ex)
{
// we can't even query for the jobrequest from server, something totally busted, stop agent/worker.
Trace.Error($"Catch exception while checking jobrequest {jobDispatch.JobId} status. Cancel running worker right away.");
Trace.Error(ex);
jobDispatch.WorkerCancellationTokenSource.Cancel();
// make sure worker process exit before we rethrow, otherwise we might leave orphan worker process behind.
await jobDispatch.WorkerDispatch;
// rethrow original exception
throw;
}
if (request.Result != null)
{
// job request has been finished, the server already has result.
// this means agent is busted since it still running that request.
// cancel the zombie worker, run next job request.
Trace.Error($"Received job request while previous job {jobDispatch.JobId} still running on worker. Cancel the previous job since the job request have been finished on server side with result: {request.Result.Value}.");
jobDispatch.WorkerCancellationTokenSource.Cancel();
// wait 45 sec for worker to finish.
Task completedTask = await Task.WhenAny(jobDispatch.WorkerDispatch, Task.Delay(TimeSpan.FromSeconds(45)));
if (completedTask != jobDispatch.WorkerDispatch)
{
// at this point, the job exectuion might encounter some dead lock and even not able to be canclled.
// no need to localize the exception string should never happen.
throw new InvalidOperationException($"Job dispatch process for {jobDispatch.JobId} has encountered unexpected error, the dispatch task is not able to be canceled within 45 seconds.");
}
}
else
{
// something seriously wrong on server side. stop agent from continue running.
// no need to localize the exception string should never happen.
throw new InvalidOperationException($"Server send a new job request while the previous job request {jobDispatch.JobId} haven't finished.");
}
}
try
{
await jobDispatch.WorkerDispatch;
Trace.Info($"Job request {jobDispatch.JobId} processed succeed.");
}
catch (Exception ex)
{
Trace.Error($"Worker Dispatch failed witn an exception for job request {jobDispatch.JobId}.");
Trace.Error(ex);
}
finally
{
WorkerDispatcher workerDispatcher;
if (_jobInfos.TryRemove(jobDispatch.JobId, out workerDispatcher))
{
Trace.Verbose($"Remove WorkerDispather from {nameof(_jobInfos)} dictionary for job {jobDispatch.JobId}.");
workerDispatcher.Dispose();
}
}
}
private async Task RunOnceAsync(Pipelines.AgentJobRequestMessage message, WorkerDispatcher previousJobDispatch, WorkerDispatcher currentJobDispatch)
{
try
{
await RunAsync(message, previousJobDispatch, currentJobDispatch);
}
finally
{
Trace.Info("Fire signal for one time used agent.");
_runOnceJobCompleted.TrySetResult(true);
}
}
private async Task RunAsync(Pipelines.AgentJobRequestMessage message, WorkerDispatcher previousJobDispatch, WorkerDispatcher newJobDispatch)
{
if (previousJobDispatch != null)
{
Trace.Verbose($"Make sure the previous job request {previousJobDispatch.JobId} has successfully finished on worker.");
await EnsureDispatchFinished(previousJobDispatch);
}
else
{
Trace.Verbose($"This is the first job request.");
}
var jobRequestCancellationToken = newJobDispatch.WorkerCancellationTokenSource.Token;
var workerCancelTimeoutKillToken = newJobDispatch.WorkerCancelTimeoutKillTokenSource.Token;
var term = HostContext.GetService<ITerminal>();
term.WriteLine(StringUtil.Loc("RunningJob", DateTime.UtcNow, message.JobDisplayName));
// first job request renew succeed.
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
var notification = HostContext.GetService<IJobNotification>();
// lock renew cancellation token.
using (var lockRenewalTokenSource = new CancellationTokenSource())
using (var workerProcessCancelTokenSource = new CancellationTokenSource())
{
long requestId = message.RequestId;
Guid lockToken = Guid.Empty; // lockToken has never been used, keep this here of compat
// Because an agent can be idle for a long time between jobs, it is possible that in that time
// a firewall has closed the connection. For that reason, forcibly reestablish this connection at the
// start of a new job
var agentServer = HostContext.GetService<IAgentServer>();
await agentServer.RefreshConnectionAsync(AgentConnectionType.JobRequest, TimeSpan.FromSeconds(30));
// start renew job request
Trace.Info($"Start renew job request {requestId} for job {message.JobId}.");
Task renewJobRequest = RenewJobRequestAsync(_poolId, requestId, lockToken, firstJobRequestRenewed, lockRenewalTokenSource.Token);
// wait till first renew succeed or job request is canceled
// not even start worker if the first renew fail
await Task.WhenAny(firstJobRequestRenewed.Task, renewJobRequest, Task.Delay(-1, jobRequestCancellationToken));
if (renewJobRequest.IsCompleted)
{
// renew job request task complete means we run out of retry for the first job request renew.
Trace.Info($"Unable to renew job request for job {message.JobId} for the first time, stop dispatching job to worker.");
return;
}
if (jobRequestCancellationToken.IsCancellationRequested)
{
Trace.Info($"Stop renew job request for job {message.JobId}.");
// stop renew lock
lockRenewalTokenSource.Cancel();
// renew job request should never blows up.
await renewJobRequest;
// complete job request with result Cancelled
await CompleteJobRequestAsync(_poolId, message, lockToken, TaskResult.Canceled);
return;
}
HostContext.WritePerfCounter($"JobRequestRenewed_{requestId.ToString()}");
Task<int> workerProcessTask = null;
object _outputLock = new object();
List<string> workerOutput = new List<string>();
using (var processChannel = HostContext.CreateService<IProcessChannel>())
using (var processInvoker = HostContext.CreateService<IProcessInvoker>())
{
// Start the process channel.
// It's OK if StartServer bubbles an execption after the worker process has already started.
// The worker will shutdown after 30 seconds if it hasn't received the job message.
processChannel.StartServer(
// Delegate to start the child process.
startProcess: (string pipeHandleOut, string pipeHandleIn) =>
{
// Validate args.
ArgUtil.NotNullOrEmpty(pipeHandleOut, nameof(pipeHandleOut));
ArgUtil.NotNullOrEmpty(pipeHandleIn, nameof(pipeHandleIn));
// Save STDOUT from worker, worker will use STDOUT report unhandle exception.
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stdout)
{
if (!string.IsNullOrEmpty(stdout.Data))
{
lock (_outputLock)
{
workerOutput.Add(stdout.Data);
}
}
};
// Save STDERR from worker, worker will use STDERR on crash.
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stderr)
{
if (!string.IsNullOrEmpty(stderr.Data))
{
lock (_outputLock)
{
workerOutput.Add(stderr.Data);
}
}
};
// Start the child process.
HostContext.WritePerfCounter("StartingWorkerProcess");
var assemblyDirectory = HostContext.GetDirectory(WellKnownDirectory.Bin);
string workerFileName = Path.Combine(assemblyDirectory, _workerProcessName);
workerProcessTask = processInvoker.ExecuteAsync(
workingDirectory: assemblyDirectory,
fileName: workerFileName,
arguments: "spawnclient " + pipeHandleOut + " " + pipeHandleIn,
environment: null,
requireExitCodeZero: false,
outputEncoding: null,
killProcessOnCancel: true,
redirectStandardIn: null,
inheritConsoleHandler: false,
keepStandardInOpen: false,
highPriorityProcess: true,
cancellationToken: workerProcessCancelTokenSource.Token);
}
);
// Send the job request message.
// Kill the worker process if sending the job message times out. The worker
// process may have successfully received the job message.
try
{
var body = JsonUtility.ToString(message);
var numBytes = System.Text.ASCIIEncoding.Unicode.GetByteCount(body) / 1024;
string numBytesString = numBytes > 0 ? $"{numBytes} KB" : " < 1 KB";
Trace.Info($"Send job request message to worker for job {message.JobId} ({numBytesString}).");
HostContext.WritePerfCounter($"AgentSendingJobToWorker_{message.JobId}");
var stopWatch = Stopwatch.StartNew();
using (var csSendJobRequest = new CancellationTokenSource(_channelTimeout))
{
await processChannel.SendAsync(
messageType: MessageType.NewJobRequest,
body: body,
cancellationToken: csSendJobRequest.Token);
}
stopWatch.Stop();
Trace.Info($"Took {stopWatch.ElapsedMilliseconds} ms to send job message to worker");
}
catch (OperationCanceledException)
{
// message send been cancelled.
// timeout 30 sec. kill worker.
Trace.Info($"Job request message sending for job {message.JobId} been cancelled after waiting for {_channelTimeout.TotalSeconds} seconds, kill running worker.");
workerProcessCancelTokenSource.Cancel();
try
{
await workerProcessTask;
}
catch (OperationCanceledException)
{
Trace.Info("worker process has been killed.");
}
Trace.Info($"Stop renew job request for job {message.JobId}.");
// stop renew lock
lockRenewalTokenSource.Cancel();
// renew job request should never blows up.
await renewJobRequest;
// not finish the job request since the job haven't run on worker at all, we will not going to set a result to server.
return;
}
// we get first jobrequest renew succeed and start the worker process with the job message.
// send notification to machine provisioner.
var systemConnection = message.Resources.Endpoints.SingleOrDefault(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));
var accessToken = systemConnection?.Authorization?.Parameters["AccessToken"];
VariableValue identifier = null;
VariableValue definitionId = null;
if (message.Plan.PlanType == "Build")
{
message.Variables.TryGetValue("build.buildId", out identifier);
message.Variables.TryGetValue("system.definitionId", out definitionId);
}
else if (message.Plan.PlanType == "Release")
{
message.Variables.TryGetValue("release.deploymentId", out identifier);
message.Variables.TryGetValue("release.definitionId", out definitionId);
}
await notification.JobStarted(message.JobId, accessToken, systemConnection.Url, message.Plan.PlanId, (identifier?.Value ?? "0"), (definitionId?.Value ?? "0"), message.Plan.PlanType);
HostContext.WritePerfCounter($"SentJobToWorker_{requestId.ToString()}");
try
{
TaskResult resultOnAbandonOrCancel = TaskResult.Succeeded;
// wait for renewlock, worker process or cancellation token been fired.
// keep listening iff we receive a metadata update
bool keepListening = true;
while (keepListening)
{
var metadataUpdateTask = newJobDispatch.MetadataSource.Task;
var completedTask = await Task.WhenAny(renewJobRequest, workerProcessTask, Task.Delay(-1, jobRequestCancellationToken), metadataUpdateTask);
if (completedTask == workerProcessTask)
{
keepListening = false;
// worker finished successfully, complete job request with result, attach unhandled exception reported by worker, stop renew lock, job has finished.
int returnCode = await workerProcessTask;
Trace.Info($"Worker finished for job {message.JobId}. Code: " + returnCode);
string detailInfo = null;
if (!TaskResultUtil.IsValidReturnCode(returnCode))
{
detailInfo = string.Join(Environment.NewLine, workerOutput);
Trace.Info($"Return code {returnCode} indicate worker encounter an unhandled exception or app crash, attach worker stdout/stderr to JobRequest result.");
await LogWorkerProcessUnhandledException(message, detailInfo);
}
TaskResult result = TaskResultUtil.TranslateFromReturnCode(returnCode);
Trace.Info($"finish job request for job {message.JobId} with result: {result}");
term.WriteLine(StringUtil.Loc("JobCompleted", DateTime.UtcNow, message.JobDisplayName, result));
Trace.Info($"Stop renew job request for job {message.JobId}.");
// stop renew lock
lockRenewalTokenSource.Cancel();
// renew job request should never blows up.
await renewJobRequest;
// complete job request
await CompleteJobRequestAsync(_poolId, message, lockToken, result, detailInfo);
// print out unhandled exception happened in worker after we complete job request.
// when we run out of disk space, report back to server has higher priority.
if (!string.IsNullOrEmpty(detailInfo))
{
Trace.Error("Unhandled exception happened in worker:");
Trace.Error(detailInfo);
}
return;
}
else if (completedTask == renewJobRequest)
{
keepListening = false;
resultOnAbandonOrCancel = TaskResult.Abandoned;
}
else if (completedTask == metadataUpdateTask)
{
Trace.Info($"Send job metadata update message to worker for job {message.JobId}.");
using (var csSendCancel = new CancellationTokenSource(_channelTimeout))
{
var body = JsonUtility.ToString(metadataUpdateTask.Result);
await processChannel.SendAsync(
messageType: MessageType.JobMetadataUpdate,
body: body,
cancellationToken: csSendCancel.Token);
}
newJobDispatch.ResetMetadataSource();
}
else
{
keepListening = false;
resultOnAbandonOrCancel = TaskResult.Canceled;
}
}
// renew job request completed or job request cancellation token been fired for RunAsync(jobrequestmessage)
// cancel worker gracefully first, then kill it after worker cancel timeout
try
{
Trace.Info($"Send job cancellation message to worker for job {message.JobId}.");
using (var csSendCancel = new CancellationTokenSource(_channelTimeout))
{
var messageType = MessageType.CancelRequest;
if (HostContext.AgentShutdownToken.IsCancellationRequested)
{
switch (HostContext.AgentShutdownReason)
{
case ShutdownReason.UserCancelled:
messageType = MessageType.AgentShutdown;
break;
case ShutdownReason.OperatingSystemShutdown:
messageType = MessageType.OperatingSystemShutdown;
break;
}
}
await processChannel.SendAsync(
messageType: messageType,
body: string.Empty,
cancellationToken: csSendCancel.Token);
}
}
catch (OperationCanceledException)
{
// message send been cancelled.
Trace.Info($"Job cancel message sending for job {message.JobId} been cancelled, kill running worker.");
workerProcessCancelTokenSource.Cancel();
try
{
await workerProcessTask;
}
catch (OperationCanceledException)
{
Trace.Info("worker process has been killed.");
}
}
// wait worker to exit
// if worker doesn't exit within timeout, then kill worker.
var exitTask = await Task.WhenAny(workerProcessTask, Task.Delay(-1, workerCancelTimeoutKillToken));
// worker haven't exit within cancellation timeout.
if (exitTask != workerProcessTask)
{
Trace.Info($"worker process for job {message.JobId} haven't exit within cancellation timout, kill running worker.");
workerProcessCancelTokenSource.Cancel();
try
{
await workerProcessTask;
}
catch (OperationCanceledException)
{
Trace.Info("worker process has been killed.");
}
}
Trace.Info($"finish job request for job {message.JobId} with result: {resultOnAbandonOrCancel}");
term.WriteLine(StringUtil.Loc("JobCompleted", DateTime.UtcNow, message.JobDisplayName, resultOnAbandonOrCancel));
// complete job request with cancel result, stop renew lock, job has finished.
Trace.Info($"Stop renew job request for job {message.JobId}.");
// stop renew lock
lockRenewalTokenSource.Cancel();
// renew job request should never blows up.
await renewJobRequest;
// complete job request
await CompleteJobRequestAsync(_poolId, message, lockToken, resultOnAbandonOrCancel);
}
finally
{
// This should be the last thing to run so we don't notify external parties until actually finished
await notification.JobCompleted(message.JobId);
}
}
}
}
public async Task RenewJobRequestAsync(int poolId, long requestId, Guid lockToken, TaskCompletionSource<int> firstJobRequestRenewed, CancellationToken token)
{
ArgUtil.NotNull(firstJobRequestRenewed, nameof(firstJobRequestRenewed));
var agentServer = HostContext.GetService<IAgentServer>();
TaskAgentJobRequest request = null;
int firstRenewRetryLimit = 5;
int encounteringError = 0;
// renew lock during job running.
// stop renew only if cancellation token for lock renew task been signal or exception still happen after retry.
while (!token.IsCancellationRequested)
{
try
{
request = await agentServer.RenewAgentRequestAsync(poolId, requestId, lockToken, token);
Trace.Info($"Successfully renew job request {requestId}, job is valid till {request.LockedUntil.Value}");
if (!firstJobRequestRenewed.Task.IsCompleted)
{
// fire first renew succeed event.
firstJobRequestRenewed.TrySetResult(0);
}
if (encounteringError > 0)
{
encounteringError = 0;
agentServer.SetConnectionTimeout(AgentConnectionType.JobRequest, TimeSpan.FromSeconds(60));
HostContext.WritePerfCounter("JobRenewRecovered");
}
// renew again after 60 sec delay
await HostContext.Delay(TimeSpan.FromSeconds(60), token);
}
catch (TaskAgentJobNotFoundException)
{
// no need for retry. the job is not valid anymore.
Trace.Info($"TaskAgentJobNotFoundException received when renew job request {requestId}, job is no longer valid, stop renew job request.");
return;
}
catch (TaskAgentJobTokenExpiredException)
{
// no need for retry. the job is not valid anymore.
Trace.Info($"TaskAgentJobTokenExpiredException received renew job request {requestId}, job is no longer valid, stop renew job request.");
return;
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
// OperationCanceledException may caused by http timeout or _lockRenewalTokenSource.Cance();
// Stop renew only on cancellation token fired.
Trace.Info($"job renew has been canceled, stop renew job request {requestId}.");
return;
}
catch (Exception ex)
{
Trace.Error($"Catch exception during renew agent jobrequest {requestId}.");
Trace.Error(ex);
encounteringError++;
// retry
TimeSpan remainingTime = TimeSpan.Zero;
if (!firstJobRequestRenewed.Task.IsCompleted)
{
// retry 5 times every 10 sec for the first renew
if (firstRenewRetryLimit-- > 0)
{
remainingTime = TimeSpan.FromSeconds(10);
}
}
else
{
// retry till reach lockeduntil + 5 mins extra buffer.
remainingTime = request.LockedUntil.Value + TimeSpan.FromMinutes(5) - DateTime.UtcNow;
}
if (remainingTime > TimeSpan.Zero)
{
TimeSpan delayTime;
if (!firstJobRequestRenewed.Task.IsCompleted)
{
Trace.Info($"Retrying lock renewal for jobrequest {requestId}. The first job renew request has failed.");
delayTime = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10));
}
else
{
Trace.Info($"Retrying lock renewal for jobrequest {requestId}. Job is valid until {request.LockedUntil.Value}.");
if (encounteringError > 5)
{
delayTime = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30));
}
else
{
delayTime = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15));
}
}
// Re-establish connection to server in order to avoid affinity with server.
// Reduce connection timeout to 30 seconds (from 60s)
HostContext.WritePerfCounter("ResetJobRenewConnection");
await agentServer.RefreshConnectionAsync(AgentConnectionType.JobRequest, TimeSpan.FromSeconds(30));
try
{
// back-off before next retry.
await HostContext.Delay(delayTime, token);
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
Trace.Info($"job renew has been canceled, stop renew job request {requestId}.");
}
}
else
{
Trace.Info($"Lock renewal has run out of retry, stop renew lock for jobrequest {requestId}.");
HostContext.WritePerfCounter("JobRenewReachLimit");
return;
}
}
}
}
// TODO: We need send detailInfo back to DT in order to add an issue for the job
private async Task CompleteJobRequestAsync(int poolId, Pipelines.AgentJobRequestMessage message, Guid lockToken, TaskResult result, string detailInfo = null)
{
Trace.Entering();
if (PlanUtil.GetFeatures(message.Plan).HasFlag(PlanFeatures.JobCompletedPlanEvent))
{
Trace.Verbose($"Skip FinishAgentRequest call from Listener because Plan version is {message.Plan.Version}");
return;
}
var agentServer = HostContext.GetService<IAgentServer>();
int completeJobRequestRetryLimit = 5;
List<Exception> exceptions = new List<Exception>();
while (completeJobRequestRetryLimit-- > 0)
{
try
{
await agentServer.FinishAgentRequestAsync(poolId, message.RequestId, lockToken, DateTime.UtcNow, result, CancellationToken.None);
return;
}
catch (TaskAgentJobNotFoundException)
{
Trace.Info($"TaskAgentJobNotFoundException received, job {message.JobId} is no longer valid.");
return;
}
catch (TaskAgentJobTokenExpiredException)
{
Trace.Info($"TaskAgentJobTokenExpiredException received, job {message.JobId} is no longer valid.");
return;
}
catch (Exception ex)
{
Trace.Error($"Caught exception during complete agent jobrequest {message.RequestId}.");
Trace.Error(ex);
exceptions.Add(ex);
}
// delay 5 seconds before next retry.
await Task.Delay(TimeSpan.FromSeconds(5));
}
// rethrow all catched exceptions during retry.
throw new AggregateException(exceptions);
}
// log an error issue to job level timeline record
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "jobServer")]
private async Task LogWorkerProcessUnhandledException(Pipelines.AgentJobRequestMessage message, string errorMessage)
{
try
{
var systemConnection = message.Resources.Endpoints.SingleOrDefault(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection));
ArgUtil.NotNull(systemConnection, nameof(systemConnection));
var jobServer = HostContext.GetService<IJobServer>();
VssCredentials jobServerCredential = VssUtil.GetVssCredential(systemConnection);
Uri jobServerUrl = systemConnection.Url;
// Make sure SystemConnection Url match Config Url base for OnPremises server
if (!message.Variables.ContainsKey(Constants.Variables.System.ServerType) ||
string.Equals(message.Variables[Constants.Variables.System.ServerType]?.Value, "OnPremises", StringComparison.OrdinalIgnoreCase))
{
try
{
Uri result = null;
Uri configUri = new Uri(_agentSetting.ServerUrl);
if (Uri.TryCreate(new Uri(configUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)), jobServerUrl.PathAndQuery, out result))
{
//replace the schema and host portion of messageUri with the host from the
//server URI (which was set at config time)
jobServerUrl = result;
}
}
catch (InvalidOperationException ex)
{
//cannot parse the Uri - not a fatal error
Trace.Error(ex);
}
catch (UriFormatException ex)
{
//cannot parse the Uri - not a fatal error
Trace.Error(ex);
}
}
var jobConnection = VssUtil.CreateConnection(jobServerUrl, jobServerCredential);
await jobServer.ConnectAsync(jobConnection);
var timeline = await jobServer.GetTimelineAsync(message.Plan.ScopeIdentifier, message.Plan.PlanType, message.Plan.PlanId, message.Timeline.Id, CancellationToken.None);
ArgUtil.NotNull(timeline, nameof(timeline));
TimelineRecord jobRecord = timeline.Records.FirstOrDefault(x => x.Id == message.JobId && x.RecordType == "Job");
ArgUtil.NotNull(jobRecord, nameof(jobRecord));
jobRecord.ErrorCount++;
jobRecord.Issues.Add(new Issue() { Type = IssueType.Error, Message = errorMessage });
await jobServer.UpdateTimelineRecordsAsync(message.Plan.ScopeIdentifier, message.Plan.PlanType, message.Plan.PlanId, message.Timeline.Id, new TimelineRecord[] { jobRecord }, CancellationToken.None);
}
catch (Exception ex)
{
Trace.Error("Fail to report unhandled exception from Agent.Worker process");
Trace.Error(ex);
}
}
private class WorkerDispatcher : IDisposable
{
public long RequestId { get; }
public Guid JobId { get; }
public Task WorkerDispatch { get; set; }
public TaskCompletionSource<JobMetadataMessage> MetadataSource { get; set; }
public CancellationTokenSource WorkerCancellationTokenSource { get; private set; }
public CancellationTokenSource WorkerCancelTimeoutKillTokenSource { get; private set; }
private readonly object _lock = new object();
const int maxValueInMinutes = 35790; // 35790 * 60 * 1000 = 2147400000
// The "CancelAfter" method converts minutes to milliseconds
// It throws an exception if the value is greater than 2147483647 (Int32.MaxValue)
public WorkerDispatcher(Guid jobId, long requestId)
{
JobId = jobId;
RequestId = requestId;
WorkerCancelTimeoutKillTokenSource = new CancellationTokenSource();
WorkerCancellationTokenSource = new CancellationTokenSource();
MetadataSource = new TaskCompletionSource<JobMetadataMessage>();
}
public bool Cancel(TimeSpan timeout)
{
if (WorkerCancellationTokenSource != null && WorkerCancelTimeoutKillTokenSource != null)
{
lock (_lock)
{
if (WorkerCancellationTokenSource != null && WorkerCancelTimeoutKillTokenSource != null)
{
WorkerCancellationTokenSource.Cancel();
// make sure we have at least 60 seconds for cancellation.
if (timeout.TotalSeconds < 60)
{
timeout = TimeSpan.FromSeconds(60);
}
// make sure we have less than 2147400000 milliseconds
if (timeout.TotalMinutes > maxValueInMinutes)
{
timeout = TimeSpan.FromMinutes(maxValueInMinutes);
}
WorkerCancelTimeoutKillTokenSource.CancelAfter(timeout.Subtract(TimeSpan.FromSeconds(15)));
return true;
}
}
}
return false;
}
public void UpdateMetadata(JobMetadataMessage message)
{
lock (_lock)
{
MetadataSource.TrySetResult(message);
}
}
public void ResetMetadataSource()
{
MetadataSource = new TaskCompletionSource<JobMetadataMessage>();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (WorkerCancellationTokenSource != null || WorkerCancelTimeoutKillTokenSource != null)
{
lock (_lock)
{
if (WorkerCancellationTokenSource != null)
{
WorkerCancellationTokenSource.Dispose();
WorkerCancellationTokenSource = null;
}
if (WorkerCancelTimeoutKillTokenSource != null)
{
WorkerCancelTimeoutKillTokenSource.Dispose();
WorkerCancelTimeoutKillTokenSource = null;
}
}
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
namespace Microsoft.VisualStudio.FSharp.ProjectSystem {
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Security.Permissions;
using System.Collections;
using System.IO;
using System.Text;
using RECT = Microsoft.VisualStudio.OLE.Interop.RECT;
using POINT = Microsoft.VisualStudio.OLE.Interop.POINT;
using Microsoft.Win32.SafeHandles;
internal static class NativeMethods
{
internal static IntPtr InvalidIntPtr = ((IntPtr)((int)(-1)));
// IIDS
public static readonly Guid IID_IServiceProvider = typeof(Microsoft.VisualStudio.OLE.Interop.IServiceProvider).GUID;
public static readonly Guid IID_IObjectWithSite = typeof(IObjectWithSite).GUID;
public static readonly Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}");
public static readonly Guid GUID_PropertyBrowserToolWindow = new Guid(unchecked((int)0xeefa5220), unchecked((short)0xe298), (short)0x11d0, new byte[]{ 0x8f, 0x78, 0x0, 0xa0, 0xc9, 0x11, 0x0, 0x57 });
[ComImport,System.Runtime.InteropServices.Guid("5EFC7974-14BC-11CF-9B2B-00AA00573819")]
public class OleComponentUIManager {
}
// packing
public static int SignedHIWORD(int n) {
return (int)(short)((n >> 16) & 0xffff);
}
public static int SignedLOWORD(int n) {
return (int)(short)(n & 0xFFFF);
}
public const int
CLSCTX_INPROC_SERVER = 0x1;
public const int
S_FALSE = 0x00000001,
S_OK = 0x00000000,
IDOK = 1,
IDCANCEL = 2,
IDABORT = 3,
IDRETRY = 4,
IDIGNORE = 5,
IDYES = 6,
IDNO = 7,
IDCLOSE = 8,
IDHELP = 9,
IDTRYAGAIN = 10,
IDCONTINUE = 11,
OLECMDERR_E_NOTSUPPORTED = unchecked((int)0x80040100),
OLECMDERR_E_UNKNOWNGROUP = unchecked((int)0x80040104),
UNDO_E_CLIENTABORT = unchecked((int)0x80044001),
E_OUTOFMEMORY = unchecked((int)0x8007000E),
E_INVALIDARG = unchecked((int)0x80070057),
E_FAIL = unchecked((int)0x80004005),
E_NOINTERFACE = unchecked((int)0x80004002),
E_POINTER = unchecked((int)0x80004003),
E_NOTIMPL = unchecked((int)0x80004001),
E_UNEXPECTED = unchecked((int)0x8000FFFF),
E_HANDLE = unchecked((int)0x80070006),
E_ABORT = unchecked((int)0x80004004),
E_ACCESSDENIED = unchecked((int)0x80070005),
E_PENDING = unchecked((int)0x8000000A);
public const int
STG_E_FILENOTFOUND = unchecked((int)0x80030002);
public const int
OLECLOSE_SAVEIFDIRTY = 0,
OLECLOSE_NOSAVE = 1,
OLECLOSE_PROMPTSAVE = 2;
public const int
OLEIVERB_PRIMARY = 0,
OLEIVERB_SHOW = -1,
OLEIVERB_OPEN = -2,
OLEIVERB_HIDE = -3,
OLEIVERB_UIACTIVATE = -4,
OLEIVERB_INPLACEACTIVATE = -5,
OLEIVERB_DISCARDUNDOSTATE = -6,
OLEIVERB_PROPERTIES = -7;
public const int
OFN_READONLY = unchecked((int)0x00000001),
OFN_OVERWRITEPROMPT = unchecked((int)0x00000002),
OFN_HIDEREADONLY = unchecked((int)0x00000004),
OFN_NOCHANGEDIR = unchecked((int)0x00000008),
OFN_SHOWHELP = unchecked((int)0x00000010),
OFN_ENABLEHOOK = unchecked((int)0x00000020),
OFN_ENABLETEMPLATE = unchecked((int)0x00000040),
OFN_ENABLETEMPLATEHANDLE = unchecked((int)0x00000080),
OFN_NOVALIDATE = unchecked((int)0x00000100),
OFN_ALLOWMULTISELECT = unchecked((int)0x00000200),
OFN_EXTENSIONDIFFERENT = unchecked((int)0x00000400),
OFN_PATHMUSTEXIST = unchecked((int)0x00000800),
OFN_FILEMUSTEXIST = unchecked((int)0x00001000),
OFN_CREATEPROMPT = unchecked((int)0x00002000),
OFN_SHAREAWARE = unchecked((int)0x00004000),
OFN_NOREADONLYRETURN = unchecked((int)0x00008000),
OFN_NOTESTFILECREATE = unchecked((int)0x00010000),
OFN_NONETWORKBUTTON = unchecked((int)0x00020000),
OFN_NOLONGNAMES = unchecked((int)0x00040000),
OFN_EXPLORER = unchecked((int)0x00080000),
OFN_NODEREFERENCELINKS = unchecked((int)0x00100000),
OFN_LONGNAMES = unchecked((int)0x00200000),
OFN_ENABLEINCLUDENOTIFY = unchecked((int)0x00400000),
OFN_ENABLESIZING = unchecked((int)0x00800000),
OFN_USESHELLITEM = unchecked((int)0x01000000),
OFN_DONTADDTORECENT = unchecked((int)0x02000000),
OFN_FORCESHOWHIDDEN = unchecked((int)0x10000000);
// for READONLYSTATUS
public const int
ROSTATUS_NotReadOnly = 0x0,
ROSTATUS_ReadOnly = 0x1,
ROSTATUS_Unknown = unchecked((int)0xFFFFFFFF);
public const int
IEI_DoNotLoadDocData = 0x10000000;
public const int
CB_SETDROPPEDWIDTH = 0x0160,
GWL_STYLE = (-16),
GWL_EXSTYLE = (-20),
DWL_MSGRESULT = 0,
SW_SHOWNORMAL = 1,
HTMENU = 5,
WS_POPUP = unchecked((int)0x80000000),
WS_CHILD = 0x40000000,
WS_MINIMIZE = 0x20000000,
WS_VISIBLE = 0x10000000,
WS_DISABLED = 0x08000000,
WS_CLIPSIBLINGS = 0x04000000,
WS_CLIPCHILDREN = 0x02000000,
WS_MAXIMIZE = 0x01000000,
WS_CAPTION = 0x00C00000,
WS_BORDER = 0x00800000,
WS_DLGFRAME = 0x00400000,
WS_VSCROLL = 0x00200000,
WS_HSCROLL = 0x00100000,
WS_SYSMENU = 0x00080000,
WS_THICKFRAME = 0x00040000,
WS_TABSTOP = 0x00010000,
WS_MINIMIZEBOX = 0x00020000,
WS_MAXIMIZEBOX = 0x00010000,
WS_EX_DLGMODALFRAME = 0x00000001,
WS_EX_MDICHILD = 0x00000040,
WS_EX_TOOLWINDOW = 0x00000080,
WS_EX_CLIENTEDGE = 0x00000200,
WS_EX_CONTEXTHELP = 0x00000400,
WS_EX_RIGHT = 0x00001000,
WS_EX_LEFT = 0x00000000,
WS_EX_RTLREADING = 0x00002000,
WS_EX_LEFTSCROLLBAR = 0x00004000,
WS_EX_CONTROLPARENT = 0x00010000,
WS_EX_STATICEDGE = 0x00020000,
WS_EX_APPWINDOW = 0x00040000,
WS_EX_LAYERED = 0x00080000,
WS_EX_TOPMOST = 0x00000008,
WS_EX_NOPARENTNOTIFY = 0x00000004,
LVM_SETEXTENDEDLISTVIEWSTYLE = (0x1000 + 54),
LVS_EX_LABELTIP = 0x00004000,
// winuser.h
WH_JOURNALPLAYBACK = 1,
WH_GETMESSAGE = 3,
WH_MOUSE = 7,
WSF_VISIBLE = 0x0001,
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DELETEITEM = 0x002D,
WM_DESTROY = 0x0002,
WM_MOVE = 0x0003,
WM_SIZE = 0x0005,
WM_ACTIVATE = 0x0006,
WA_INACTIVE = 0,
WA_ACTIVE = 1,
WA_CLICKACTIVE = 2,
WM_SETFOCUS = 0x0007,
WM_KILLFOCUS = 0x0008,
WM_ENABLE = 0x000A,
WM_SETREDRAW = 0x000B,
WM_SETTEXT = 0x000C,
WM_GETTEXT = 0x000D,
WM_GETTEXTLENGTH = 0x000E,
WM_PAINT = 0x000F,
WM_CLOSE = 0x0010,
WM_QUERYENDSESSION = 0x0011,
WM_QUIT = 0x0012,
WM_QUERYOPEN = 0x0013,
WM_ERASEBKGND = 0x0014,
WM_SYSCOLORCHANGE = 0x0015,
WM_ENDSESSION = 0x0016,
WM_SHOWWINDOW = 0x0018,
WM_WININICHANGE = 0x001A,
WM_SETTINGCHANGE = 0x001A,
WM_DEVMODECHANGE = 0x001B,
WM_ACTIVATEAPP = 0x001C,
WM_FONTCHANGE = 0x001D,
WM_TIMECHANGE = 0x001E,
WM_CANCELMODE = 0x001F,
WM_SETCURSOR = 0x0020,
WM_MOUSEACTIVATE = 0x0021,
WM_CHILDACTIVATE = 0x0022,
WM_QUEUESYNC = 0x0023,
WM_GETMINMAXINFO = 0x0024,
WM_PAINTICON = 0x0026,
WM_ICONERASEBKGND = 0x0027,
WM_NEXTDLGCTL = 0x0028,
WM_SPOOLERSTATUS = 0x002A,
WM_DRAWITEM = 0x002B,
WM_MEASUREITEM = 0x002C,
WM_VKEYTOITEM = 0x002E,
WM_CHARTOITEM = 0x002F,
WM_SETFONT = 0x0030,
WM_GETFONT = 0x0031,
WM_SETHOTKEY = 0x0032,
WM_GETHOTKEY = 0x0033,
WM_QUERYDRAGICON = 0x0037,
WM_COMPAREITEM = 0x0039,
WM_GETOBJECT = 0x003D,
WM_COMPACTING = 0x0041,
WM_COMMNOTIFY = 0x0044,
WM_WINDOWPOSCHANGING = 0x0046,
WM_WINDOWPOSCHANGED = 0x0047,
WM_POWER = 0x0048,
WM_COPYDATA = 0x004A,
WM_CANCELJOURNAL = 0x004B,
WM_NOTIFY = 0x004E,
WM_INPUTLANGCHANGEREQUEST = 0x0050,
WM_INPUTLANGCHANGE = 0x0051,
WM_TCARD = 0x0052,
WM_HELP = 0x0053,
WM_USERCHANGED = 0x0054,
WM_NOTIFYFORMAT = 0x0055,
WM_CONTEXTMENU = 0x007B,
WM_STYLECHANGING = 0x007C,
WM_STYLECHANGED = 0x007D,
WM_DISPLAYCHANGE = 0x007E,
WM_GETICON = 0x007F,
WM_SETICON = 0x0080,
WM_NCCREATE = 0x0081,
WM_NCDESTROY = 0x0082,
WM_NCCALCSIZE = 0x0083,
WM_NCHITTEST = 0x0084,
WM_NCPAINT = 0x0085,
WM_NCACTIVATE = 0x0086,
WM_GETDLGCODE = 0x0087,
WM_NCMOUSEMOVE = 0x00A0,
WM_NCLBUTTONDOWN = 0x00A1,
WM_NCLBUTTONUP = 0x00A2,
WM_NCLBUTTONDBLCLK = 0x00A3,
WM_NCRBUTTONDOWN = 0x00A4,
WM_NCRBUTTONUP = 0x00A5,
WM_NCRBUTTONDBLCLK = 0x00A6,
WM_NCMBUTTONDOWN = 0x00A7,
WM_NCMBUTTONUP = 0x00A8,
WM_NCMBUTTONDBLCLK = 0x00A9,
WM_NCXBUTTONDOWN = 0x00AB,
WM_NCXBUTTONUP = 0x00AC,
WM_NCXBUTTONDBLCLK = 0x00AD,
WM_KEYFIRST = 0x0100,
WM_KEYDOWN = 0x0100,
WM_KEYUP = 0x0101,
WM_CHAR = 0x0102,
WM_DEADCHAR = 0x0103,
WM_CTLCOLOR = 0x0019,
WM_SYSKEYDOWN = 0x0104,
WM_SYSKEYUP = 0x0105,
WM_SYSCHAR = 0x0106,
WM_SYSDEADCHAR = 0x0107,
WM_KEYLAST = 0x0108,
WM_IME_STARTCOMPOSITION = 0x010D,
WM_IME_ENDCOMPOSITION = 0x010E,
WM_IME_COMPOSITION = 0x010F,
WM_IME_KEYLAST = 0x010F,
WM_INITDIALOG = 0x0110,
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
WM_TIMER = 0x0113,
WM_HSCROLL = 0x0114,
WM_VSCROLL = 0x0115,
WM_INITMENU = 0x0116,
WM_INITMENUPOPUP = 0x0117,
WM_MENUSELECT = 0x011F,
WM_MENUCHAR = 0x0120,
WM_ENTERIDLE = 0x0121,
WM_CHANGEUISTATE = 0x0127,
WM_UPDATEUISTATE = 0x0128,
WM_QUERYUISTATE = 0x0129,
WM_CTLCOLORMSGBOX = 0x0132,
WM_CTLCOLOREDIT = 0x0133,
WM_CTLCOLORLISTBOX = 0x0134,
WM_CTLCOLORBTN = 0x0135,
WM_CTLCOLORDLG = 0x0136,
WM_CTLCOLORSCROLLBAR = 0x0137,
WM_CTLCOLORSTATIC = 0x0138,
WM_MOUSEFIRST = 0x0200,
WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_LBUTTONDBLCLK = 0x0203,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205,
WM_RBUTTONDBLCLK = 0x0206,
WM_MBUTTONDOWN = 0x0207,
WM_MBUTTONUP = 0x0208,
WM_MBUTTONDBLCLK = 0x0209,
WM_XBUTTONDOWN = 0x020B,
WM_XBUTTONUP = 0x020C,
WM_XBUTTONDBLCLK = 0x020D,
WM_MOUSEWHEEL = 0x020A,
WM_MOUSELAST = 0x020A,
WM_PARENTNOTIFY = 0x0210,
WM_ENTERMENULOOP = 0x0211,
WM_EXITMENULOOP = 0x0212,
WM_NEXTMENU = 0x0213,
WM_SIZING = 0x0214,
WM_CAPTURECHANGED = 0x0215,
WM_MOVING = 0x0216,
WM_POWERBROADCAST = 0x0218,
WM_DEVICECHANGE = 0x0219,
WM_IME_SETCONTEXT = 0x0281,
WM_IME_NOTIFY = 0x0282,
WM_IME_CONTROL = 0x0283,
WM_IME_COMPOSITIONFULL = 0x0284,
WM_IME_SELECT = 0x0285,
WM_IME_CHAR = 0x0286,
WM_IME_KEYDOWN = 0x0290,
WM_IME_KEYUP = 0x0291,
WM_MDICREATE = 0x0220,
WM_MDIDESTROY = 0x0221,
WM_MDIACTIVATE = 0x0222,
WM_MDIRESTORE = 0x0223,
WM_MDINEXT = 0x0224,
WM_MDIMAXIMIZE = 0x0225,
WM_MDITILE = 0x0226,
WM_MDICASCADE = 0x0227,
WM_MDIICONARRANGE = 0x0228,
WM_MDIGETACTIVE = 0x0229,
WM_MDISETMENU = 0x0230,
WM_ENTERSIZEMOVE = 0x0231,
WM_EXITSIZEMOVE = 0x0232,
WM_DROPFILES = 0x0233,
WM_MDIREFRESHMENU = 0x0234,
WM_MOUSEHOVER = 0x02A1,
WM_MOUSELEAVE = 0x02A3,
WM_CUT = 0x0300,
WM_COPY = 0x0301,
WM_PASTE = 0x0302,
WM_CLEAR = 0x0303,
WM_UNDO = 0x0304,
WM_RENDERFORMAT = 0x0305,
WM_RENDERALLFORMATS = 0x0306,
WM_DESTROYCLIPBOARD = 0x0307,
WM_DRAWCLIPBOARD = 0x0308,
WM_PAINTCLIPBOARD = 0x0309,
WM_VSCROLLCLIPBOARD = 0x030A,
WM_SIZECLIPBOARD = 0x030B,
WM_ASKCBFORMATNAME = 0x030C,
WM_CHANGECBCHAIN = 0x030D,
WM_HSCROLLCLIPBOARD = 0x030E,
WM_QUERYNEWPALETTE = 0x030F,
WM_PALETTEISCHANGING = 0x0310,
WM_PALETTECHANGED = 0x0311,
WM_HOTKEY = 0x0312,
WM_PRINT = 0x0317,
WM_PRINTCLIENT = 0x0318,
WM_HANDHELDFIRST = 0x0358,
WM_HANDHELDLAST = 0x035F,
WM_AFXFIRST = 0x0360,
WM_AFXLAST = 0x037F,
WM_PENWINFIRST = 0x0380,
WM_PENWINLAST = 0x038F,
WM_APP = unchecked((int)0x8000),
WM_USER = 0x0400,
WM_REFLECT =
WM_USER + 0x1C00,
WS_OVERLAPPED = 0x00000000,
WPF_SETMINPOSITION = 0x0001,
WM_CHOOSEFONT_GETLOGFONT = (0x0400 + 1),
WHEEL_DELTA = 120,
DWLP_MSGRESULT = 0,
PSNRET_NOERROR = 0,
PSNRET_INVALID = 1,
PSNRET_INVALID_NOCHANGEPAGE = 2;
public const int
PSN_APPLY = ((0-200)-2),
PSN_KILLACTIVE = ((0-200)-1),
PSN_RESET = ((0-200)-3),
PSN_SETACTIVE = ((0-200)-0);
public const int
GMEM_MOVEABLE = 0x0002,
GMEM_ZEROINIT = 0x0040,
GMEM_DDESHARE = 0x2000;
public const int
SWP_NOACTIVATE = 0x0010,
SWP_NOZORDER = 0x0004,
SWP_NOSIZE = 0x0001,
SWP_NOMOVE = 0x0002,
SWP_FRAMECHANGED = 0x0020;
public const int
TVM_SETINSERTMARK = (0x1100 + 26),
TVM_GETEDITCONTROL = (0x1100 + 15);
public const int
FILE_ATTRIBUTE_READONLY = 0x00000001;
public const int
PSP_DEFAULT = 0x00000000,
PSP_DLGINDIRECT = 0x00000001,
PSP_USEHICON = 0x00000002,
PSP_USEICONID = 0x00000004,
PSP_USETITLE = 0x00000008,
PSP_RTLREADING = 0x00000010,
PSP_HASHELP = 0x00000020,
PSP_USEREFPARENT = 0x00000040,
PSP_USECALLBACK = 0x00000080,
PSP_PREMATURE = 0x00000400,
PSP_HIDEHEADER = 0x00000800,
PSP_USEHEADERTITLE = 0x00001000,
PSP_USEHEADERSUBTITLE = 0x00002000;
public const int
PSH_DEFAULT = 0x00000000,
PSH_PROPTITLE = 0x00000001,
PSH_USEHICON = 0x00000002,
PSH_USEICONID = 0x00000004,
PSH_PROPSHEETPAGE = 0x00000008,
PSH_WIZARDHASFINISH = 0x00000010,
PSH_WIZARD = 0x00000020,
PSH_USEPSTARTPAGE = 0x00000040,
PSH_NOAPPLYNOW = 0x00000080,
PSH_USECALLBACK = 0x00000100,
PSH_HASHELP = 0x00000200,
PSH_MODELESS = 0x00000400,
PSH_RTLREADING = 0x00000800,
PSH_WIZARDCONTEXTHELP = 0x00001000,
PSH_WATERMARK = 0x00008000,
PSH_USEHBMWATERMARK = 0x00010000, // user pass in a hbmWatermark instead of pszbmWatermark
PSH_USEHPLWATERMARK = 0x00020000, //
PSH_STRETCHWATERMARK = 0x00040000, // stretchwatermark also applies for the header
PSH_HEADER = 0x00080000,
PSH_USEHBMHEADER = 0x00100000,
PSH_USEPAGELANG = 0x00200000, // use frame dialog template matched to page
PSH_WIZARD_LITE = 0x00400000,
PSH_NOCONTEXTHELP = 0x02000000;
public const int
PSBTN_BACK = 0,
PSBTN_NEXT = 1,
PSBTN_FINISH = 2,
PSBTN_OK = 3,
PSBTN_APPLYNOW = 4,
PSBTN_CANCEL = 5,
PSBTN_HELP = 6,
PSBTN_MAX = 6;
public const int
TRANSPARENT = 1,
OPAQUE = 2,
FW_BOLD = 700;
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public class LOGFONT {
public int lfHeight = 0;
public int lfWidth = 0;
public int lfEscapement = 0;
public int lfOrientation = 0;
public int lfWeight = 0;
public byte lfItalic = 0;
public byte lfUnderline = 0;
public byte lfStrikeOut = 0;
public byte lfCharSet = 0;
public byte lfOutPrecision = 0;
public byte lfClipPrecision = 0;
public byte lfQuality = 0;
public byte lfPitchAndFamily = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]
public string lfFaceName = null;
}
// possibly dead code?
[StructLayout(LayoutKind.Sequential)]
internal struct NMHDR
{
internal IntPtr hwndFrom;
internal int idFrom;
internal int code;
}
/// <devdoc>
/// Helper class for setting the text parameters to OLECMDTEXT structures.
/// </devdoc>
public static class OLECMDTEXT
{
/// <summary>
/// Flags for the OLE command text
/// </summary>
public enum OLECMDTEXTF
{
/// <summary>No flag</summary>
OLECMDTEXTF_NONE = 0,
/// <summary>The name of the command is required.</summary>
OLECMDTEXTF_NAME = 1,
/// <summary>A description of the status is required.</summary>
OLECMDTEXTF_STATUS = 2
}
/// <summary>
/// Gets the flags of the OLECMDTEXT structure
/// </summary>
/// <param name="pCmdTextInt">The structure to read.</param>
/// <returns>The value of the flags.</returns>
public static OLECMDTEXTF GetFlags(IntPtr pCmdTextInt)
{
Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT pCmdText = (Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT)Marshal.PtrToStructure(pCmdTextInt, typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT));
if ( (pCmdText.cmdtextf & (int)OLECMDTEXTF.OLECMDTEXTF_NAME) != 0 )
return OLECMDTEXTF.OLECMDTEXTF_NAME;
if ( (pCmdText.cmdtextf & (int)OLECMDTEXTF.OLECMDTEXTF_STATUS) != 0 )
return OLECMDTEXTF.OLECMDTEXTF_STATUS;
return OLECMDTEXTF.OLECMDTEXTF_NONE;
}
/// <devdoc>
/// Accessing the text of this structure is very cumbersome. Instead, you may
/// use this method to access an integer pointer of the structure.
/// Passing integer versions of this structure is needed because there is no
/// way to tell the common language runtime that there is extra data at the end of the structure.
/// </devdoc>
public static string GetText(IntPtr pCmdTextInt) {
Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT pCmdText = (Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT)Marshal.PtrToStructure(pCmdTextInt, typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT));
// Get the offset to the rgsz param.
//
IntPtr offset = Marshal.OffsetOf(typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT), "rgwz");
// Punt early if there is no text in the structure.
//
if (pCmdText.cwActual == 0) {
return String.Empty;
}
char[] text = new char[pCmdText.cwActual - 1];
Marshal.Copy((IntPtr)((long)pCmdTextInt + (long)offset), text, 0, text.Length);
StringBuilder s = new StringBuilder(text.Length);
s.Append(text);
return s.ToString();
}
/// <devdoc>
/// Accessing the text of this structure is very cumbersome. Instead, you may
/// use this method to access an integer pointer of the structure.
/// Passing integer versions of this structure is needed because there is no
/// way to tell the common language runtime that there is extra data at the end of the structure.
/// </devdoc>
/// <summary>
/// Sets the text inside the structure starting from an integer pointer.
/// </summary>
/// <param name="pCmdTextInt">The integer pointer to the position where to set the text.</param>
/// <param name="text">The text to set.</param>
public static void SetText(IntPtr pCmdTextInt, string text) {
Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT pCmdText = (Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT) Marshal.PtrToStructure(pCmdTextInt, typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT));
char[] menuText = text.ToCharArray();
// Get the offset to the rgsz param. This is where we will stuff our text
//
IntPtr offset = Marshal.OffsetOf(typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT), "rgwz");
IntPtr offsetToCwActual = Marshal.OffsetOf(typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT), "cwActual");
// The max chars we copy is our string, or one less than the buffer size,
// since we need a null at the end.
//
int maxChars = Math.Min((int)pCmdText.cwBuf - 1, menuText.Length);
Marshal.Copy(menuText, 0, (IntPtr)((long)pCmdTextInt + (long)offset), maxChars);
// append a null character
Marshal.WriteInt16((IntPtr)((long)pCmdTextInt + (long)offset + maxChars * 2), 0);
// write out the length
// +1 for the null char
Marshal.WriteInt32((IntPtr)((long)pCmdTextInt + (long)offsetToCwActual), maxChars + 1);
}
}
/// <devdoc>
/// OLECMDF enums for IOleCommandTarget
/// </devdoc>
public enum tagOLECMDF {
OLECMDF_SUPPORTED = 1,
OLECMDF_ENABLED = 2,
OLECMDF_LATCHED = 4,
OLECMDF_NINCHED = 8,
OLECMDF_INVISIBLE = 16
}
/// <devdoc>
/// Constants for stream usage.
/// </devdoc>
public sealed class StreamConsts {
public const int LOCK_WRITE = 0x1;
public const int LOCK_EXCLUSIVE = 0x2;
public const int LOCK_ONLYONCE = 0x4;
public const int STATFLAG_DEFAULT = 0x0;
public const int STATFLAG_NONAME = 0x1;
public const int STATFLAG_NOOPEN = 0x2;
public const int STGC_DEFAULT = 0x0;
public const int STGC_OVERWRITE = 0x1;
public const int STGC_ONLYIFCURRENT = 0x2;
public const int STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE = 0x4;
public const int STREAM_SEEK_SET = 0x0;
public const int STREAM_SEEK_CUR = 0x1;
public const int STREAM_SEEK_END = 0x2;
}
/// <devdoc>
/// This method takes a file URL and converts it to an absolute path. The trick here is that
/// if there is a '#' in the path, everything after this is treated as a fragment. So
/// we need to append the fragment to the end of the path.
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static string GetAbsolutePath(string fileName) {
System.Diagnostics.Debug.Assert(fileName != null && fileName.Length > 0, "Cannot get absolute path, fileName is not valid");
Uri uri = new Uri(fileName);
return uri.LocalPath + uri.Fragment;
}
/// <devdoc>
/// This method takes a file URL and converts it to a local path. The trick here is that
/// if there is a '#' in the path, everything after this is treated as a fragment. So
/// we need to append the fragment to the end of the path.
/// </devdoc>
public static string GetLocalPath(string fileName) {
System.Diagnostics.Debug.Assert(fileName != null && fileName.Length > 0, "Cannot get local path, fileName is not valid");
Uri uri = new Uri(fileName);
return uri.LocalPath + uri.Fragment;
}
/// <devdoc>
/// Please use this "approved" method to compare file names.
/// </devdoc>
public static bool IsSamePath(string file1, string file2)
{
if (file1 == null || file1.Length == 0)
{
return (file2 == null || file2.Length == 0);
}
Uri uri1 = null;
Uri uri2 = null;
try
{
if (!Uri.TryCreate(file1, UriKind.Absolute, out uri1) || !Uri.TryCreate(file2, UriKind.Absolute, out uri2))
{
return false;
}
if (uri1 != null && uri1.IsFile && uri2 != null && uri2.IsFile)
{
return 0 == String.Compare(uri1.LocalPath, uri2.LocalPath, StringComparison.OrdinalIgnoreCase);
}
return file1 == file2;
}
catch (UriFormatException e)
{
Trace.WriteLine("Exception " + e.Message);
}
return false;
}
[ComImport(),Guid("9BDA66AE-CA28-4e22-AA27-8A7218A0E3FA"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IEventHandler {
// converts the underlying codefunction into an event handler for the given event
// if the given event is NULL, then the function will handle no events
[PreserveSig]
int AddHandler(string bstrEventName);
[PreserveSig]
int RemoveHandler(string bstrEventName);
IVsEnumBSTR GetHandledEvents();
bool HandlesEvent(string bstrEventName);
}
[ComImport(),Guid("A55CCBCC-7031-432d-B30A-A68DE7BDAD75"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IParameterKind {
void SetParameterPassingMode(PARAMETER_PASSING_MODE ParamPassingMode);
void SetParameterArrayDimensions(int uDimensions);
int GetParameterArrayCount();
int GetParameterArrayDimensions(int uIndex);
int GetParameterPassingMode();
}
public enum PARAMETER_PASSING_MODE
{
cmParameterTypeIn = 1,
cmParameterTypeOut = 2,
cmParameterTypeInOut = 3
}
[
ComImport, Guid("3E596484-D2E4-461a-A876-254C4F097EBB"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)
]
public interface IMethodXML
{
// Generate XML describing the contents of this function's body.
void GetXML (ref string pbstrXML);
// Parse the incoming XML with respect to the CodeModel XML schema and
// use the result to regenerate the body of the function.
[PreserveSig]
int SetXML (string pszXML);
// This is really a textpoint
[PreserveSig]
int GetBodyPoint([MarshalAs(UnmanagedType.Interface)]out object bodyPoint);
}
[ComImport(),Guid("EA1A87AD-7BC5-4349-B3BE-CADC301F17A3"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVBFileCodeModelEvents {
[PreserveSig]
int StartEdit();
[PreserveSig]
int EndEdit();
}
///--------------------------------------------------------------------------
/// ICodeClassBase:
///--------------------------------------------------------------------------
[GuidAttribute("23BBD58A-7C59-449b-A93C-43E59EFC080C")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport()]
public interface ICodeClassBase {
[PreserveSig()]
int GetBaseName(out string pBaseName);
}
public const ushort CF_HDROP = 15; // winuser.h
public const uint MK_CONTROL = 0x0008; //winuser.h
public const uint MK_SHIFT = 0x0004;
public const int MAX_PATH = 260; // windef.h
/// <summary>
/// Specifies options for a bitmap image associated with a task item.
/// </summary>
public enum VSTASKBITMAP
{
BMP_COMPILE = -1,
BMP_SQUIGGLE = -2,
BMP_COMMENT = -3,
BMP_SHORTCUT = -4,
BMP_USER = -5
};
public const int ILD_NORMAL = 0x0000,
ILD_TRANSPARENT = 0x0001,
ILD_MASK = 0x0010,
ILD_ROP = 0x0040;
/// <summary>
/// Defines the values that are not supported by the System.Environment.SpecialFolder enumeration
/// </summary>
public enum ExtendedSpecialFolder
{
/// <summary>
/// Identical to CSIDL_COMMON_STARTUP
/// </summary>
CommonStartup = 0x0018,
/// <summary>
/// Identical to CSIDL_WINDOWS
/// </summary>
Windows = 0x0024,
}
// APIS
/// <summary>
/// Changes the parent window of the specified child window.
/// </summary>
/// <param name="hWnd">Handle to the child window.</param>
/// <param name="hWndParent">Handle to the new parent window. If this parameter is NULL, the desktop window becomes the new parent window.</param>
/// <returns>A handle to the previous parent window indicates success. NULL indicates failure.</returns>
[DllImport("User32", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern bool DestroyIcon(IntPtr handle);
[DllImport("user32.dll", EntryPoint = "IsDialogMessageA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool IsDialogMessageA(IntPtr hDlg, ref MSG msg);
/// <summary>
/// Indicates whether the file type is binary or not
/// </summary>
/// <param name="lpApplicationName">Full path to the file to check</param>
/// <param name="lpBinaryType">If file isbianry the bitness of the app is indicated by lpBinaryType value.</param>
/// <returns>True if the file is binary false otherwise</returns>
[DllImport("kernel32.dll")]
public static extern bool GetBinaryType([MarshalAs(UnmanagedType.LPWStr)]string lpApplicationName, out uint lpBinaryType);
public const uint INFINITE = 0xFFFFFFFF;
public const uint WAIT_ABANDONED_0 = 0x00000080;
public const uint WAIT_OBJECT_0 = 0x00000000;
public const uint WAIT_TIMEOUT = 0x00000102;
[DllImport("kernel32.dll", SetLastError=true, ExactSpelling=true)]
public static extern Int32 WaitForSingleObject(SafeWaitHandle handle, uint timeout);
}
}
| |
//
// File.cs: Provides tagging for GIF files
//
// Author:
// Mike Gemuende (mike@gemuende.be)
//
// Copyright (C) 2010 Mike Gemuende
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
using System;
using System.IO;
using TagLib;
using TagLib.Image;
using TagLib.Xmp;
namespace TagLib.Gif
{
/// <summary>
/// This class extends <see cref="TagLib.Image.ImageBlockFile" /> to provide tagging
/// and property support for Gif files.
/// </summary>
[SupportedMimeType("taglib/gif", "gif")]
[SupportedMimeType("image/gif")]
public class File : TagLib.Image.ImageBlockFile
{
#region GIF specific constants
/// <summary>
/// Gif file signature which occurs at the begin of the file
/// </summary>
protected static readonly string SIGNATURE = "GIF";
/// <summary>
/// String which is used to indicate version the gif file format version 87a
/// </summary>
protected static readonly string VERSION_87A = "87a";
/// <summary>
/// String which is used to indicate version the gif file format version 89a
/// </summary>
protected static readonly string VERSION_89A = "89a";
/// <summary>
/// Application Extension Identifier for an XMP Block
/// </summary>
private static readonly string XMP_IDENTIFIER = "XMP Data";
/// <summary>
/// Application Authentication Extension Code for an XMP Block
/// </summary>
private static readonly string XMP_AUTH_CODE = "XMP";
/// <summary>
/// The Magic Trailer for XMP Data
/// </summary>
/// <remarks>
/// The storage of XMP data in GIF does not follow the GIF specification. According to the
/// specification, extension data is stored in so-called sub-blocks, which start with a length
/// byte which specifies the number of data bytes contained in the sub block. So a block can at
/// most contain 256 data bytes. After a sub-block, the next sub-block begins. The sequence ends,
/// when a sub-block starts with 0. So readers, which are not aware of the XMP data not following
/// this scheme, will get confused by the XMP data. To fix this, this trailer is added to the end.
/// It has a length of 258 bytes, so that it is ensured that a reader which tries to skip the
/// XMP data reads one of this bytes as length of a sub-block. But, each byte points with its length
/// to the last one. Therefoe, independent of the byte, the reader reads as sub-block length, it is
/// redirected to the last byte of the trailer and therfore to the end of the XMP data.
/// </remarks>
private static readonly byte [] XMP_MAGIC_TRAILER = new byte [] {
0x01, 0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0xF1,
0xF0, 0xEF, 0xEE, 0xED, 0xEC, 0xEB, 0xEA, 0xE9, 0xE8, 0xE7, 0xE6, 0xE5, 0xE4, 0xE3, 0xE2, 0xE1,
0xE0, 0xDF, 0xDE, 0xDD, 0xDC, 0xDB, 0xDA, 0xD9, 0xD8, 0xD7, 0xD6, 0xD5, 0xD4, 0xD3, 0xD2, 0xD1,
0xD0, 0xCF, 0xCE, 0xCD, 0xCC, 0xCB, 0xCA, 0xC9, 0xC8, 0xC7, 0xC6, 0xC5, 0xC4, 0xC3, 0xC2, 0xC1,
0xC0, 0xBF, 0xBE, 0xBD, 0xBC, 0xBB, 0xBA, 0xB9, 0xB8, 0xB7, 0xB6, 0xB5, 0xB4, 0xB3, 0xB2, 0xB1,
0xB0, 0xAF, 0xAE, 0xAD, 0xAC, 0xAB, 0xAA, 0xA9, 0xA8, 0xA7, 0xA6, 0xA5, 0xA4, 0xA3, 0xA2, 0xA1,
0xA0, 0x9F, 0x9E, 0x9D, 0x9C, 0x9B, 0x9A, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91,
0x90, 0x8F, 0x8E, 0x8D, 0x8C, 0x8B, 0x8A, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81,
0x80, 0x7F, 0x7E, 0x7D, 0x7C, 0x7B, 0x7A, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71,
0x70, 0x6F, 0x6E, 0x6D, 0x6C, 0x6B, 0x6A, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61,
0x60, 0x5F, 0x5E, 0x5D, 0x5C, 0x5B, 0x5A, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51,
0x50, 0x4F, 0x4E, 0x4D, 0x4C, 0x4B, 0x4A, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41,
0x40, 0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31,
0x30, 0x2F, 0x2E, 0x2D, 0x2C, 0x2B, 0x2A, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21,
0x20, 0x1F, 0x1E, 0x1D, 0x1C, 0x1B, 0x1A, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11,
0x10, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01,
0x00, 0x00
};
#endregion
#region private fields
/// <summary>
/// The width of the image
/// </summary>
private int width;
/// <summary>
/// The height of the image
/// </summary>
private int height;
/// <summary>
/// The Properties of the image
/// </summary>
private Properties properties;
/// <summary>
/// The version of the file format
/// </summary>
private string version;
/// <summary>
/// The start of the first block in file after the header.
/// </summary>
private long start_of_blocks = -1;
#endregion
#region public Properties
/// <summary>
/// Gets the media properties of the file represented by the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="TagLib.Properties" /> object containing the
/// media properties of the file represented by the current
/// instance.
/// </value>
public override TagLib.Properties Properties {
get { return properties; }
}
#endregion
#region constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified path in the local file
/// system and specified read style.
/// </summary>
/// <param name="path">
/// A <see cref="string" /> object containing the path of the
/// file to use in the new instance.
/// </param>
/// <param name="propertiesStyle">
/// A <see cref="ReadStyle" /> value specifying at what level
/// of accuracy to read the media properties, or <see
/// cref="ReadStyle.None" /> to ignore the properties.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" />.
/// </exception>
public File (string path, ReadStyle propertiesStyle)
: this (new File.LocalFileAbstraction (path),
propertiesStyle)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified path in the local file
/// system.
/// </summary>
/// <param name="path">
/// A <see cref="string" /> object containing the path of the
/// file to use in the new instance.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" />.
/// </exception>
public File (string path) : this (path, ReadStyle.Average)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified file abstraction and
/// specified read style.
/// </summary>
/// <param name="abstraction">
/// A <see cref="IFileAbstraction" /> object to use when
/// reading from and writing to the file.
/// </param>
/// <param name="propertiesStyle">
/// A <see cref="ReadStyle" /> value specifying at what level
/// of accuracy to read the media properties, or <see
/// cref="ReadStyle.None" /> to ignore the properties.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="abstraction" /> is <see langword="null"
/// />.
/// </exception>
public File (File.IFileAbstraction abstraction,
ReadStyle propertiesStyle) : base (abstraction)
{
Read (propertiesStyle);
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified file abstraction.
/// </summary>
/// <param name="abstraction">
/// A <see cref="IFileAbstraction" /> object to use when
/// reading from and writing to the file.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="abstraction" /> is <see langword="null"
/// />.
/// </exception>
protected File (IFileAbstraction abstraction)
: this (abstraction, ReadStyle.Average)
{
}
#endregion
#region Public Methods
/// <summary>
/// Saves the changes made in the current instance to the
/// file it represents.
/// </summary>
public override void Save ()
{
Mode = AccessMode.Write;
try {
SaveMetadata ();
TagTypesOnDisk = TagTypes;
} finally {
Mode = AccessMode.Closed;
}
}
#endregion
#region Private Methods
/// <summary>
/// Reads the information from file with a specified read style.
/// </summary>
/// <param name="propertiesStyle">
/// A <see cref="ReadStyle" /> value specifying at what level
/// of accuracy to read the media properties, or <see
/// cref="ReadStyle.None" /> to ignore the properties.
/// </param>
private void Read (ReadStyle propertiesStyle)
{
Mode = AccessMode.Read;
try {
ImageTag = new CombinedImageTag (TagTypes.XMP | TagTypes.GifComment);
ReadHeader ();
ReadMetadata ();
TagTypesOnDisk = TagTypes;
if (propertiesStyle != ReadStyle.None)
properties = ExtractProperties ();
} finally {
Mode = AccessMode.Closed;
}
}
/// <summary>
/// Reads a single byte form file. This is needed often for Gif files.
/// </summary>
/// <returns>
/// A <see cref="System.Byte"/> with the read data.
/// </returns>
private byte ReadByte ()
{
ByteVector data = ReadBlock (1);
if (data.Count != 1)
throw new CorruptFileException ("Unexpected end of file");
return data[0];
}
/// <summary>
/// Reads the Header and the Logical Screen Descriptor of the GIF file and,
/// if there is one, skips the global color table. It also extracts the
/// image width and height from it.
/// </summary>
private void ReadHeader ()
{
// The header consists of:
//
// 3 Bytes Signature
// 3 Bytes Version
//
// The Logical Screen Descriptor of:
//
// 2 Bytes Width (little endian)
// 2 Bytes Height (little endian)
// 1 Byte Screen and Color Map (packed field)
// 1 Byte Background Color
// 1 Byte Aspect Ratio
//
// Whereas the bits of the packed field contains some special information.
ByteVector data = ReadBlock (13);
if (data.Count != 13)
throw new CorruptFileException ("Unexpected end of Header");
if (data.Mid (0, 3).ToString () != SIGNATURE)
throw new CorruptFileException (String.Format ("Expected a GIF signature at start of file, but found: {0}", data.Mid (0, 3).ToString ()));
// We do not care about the version here, because we can read both versions in the same way.
// We just care when writing metadata, that, if necessary, the version is increased to 89a.
var read_version = data.Mid (3, 3).ToString ();
if (read_version == VERSION_87A || read_version == VERSION_89A)
version = read_version;
else
throw new UnsupportedFormatException (
String.Format ("Only GIF versions 87a and 89a are currently supported, but not: {0}", read_version));
// Read Image Size (little endian)
width = data.Mid (6, 2).ToUShort (false);
height = data.Mid (8, 2).ToUShort (false);
// Skip optional global color table
SkipColorTable (data [10]);
}
/// <summary>
/// Reads the metadata from file. The current position must point to the
/// start of the first block after the Header and Logical Screen
/// Descriptor (and, if there is one, the Global Color Table)
/// </summary>
private void ReadMetadata ()
{
start_of_blocks = Tell;
// Read Blocks until end of file is reached.
while (true) {
byte identifier = ReadByte ();
switch (identifier) {
case 0x2c:
SkipImage ();
break;
case 0x21:
ReadExtensionBlock ();
break;
case 0x3B:
return;
default:
throw new CorruptFileException (
String.Format ("Do not know what to do with byte 0x{0:X2} at the beginning of a block ({1}).", identifier, Tell - 1));
}
}
}
/// <summary>
/// Reads an Extension Block at the current position. The current position must
/// point to the 2nd byte of the comment block. (The other byte is usually
/// read before to identify the comment block)
/// </summary>
private void ReadExtensionBlock ()
{
// Extension Block
//
// 1 Byte Extension Introducer (0x21)
// 1 Byte Extension Identifier
// ....
//
// Note, the Extension Introducer was read before to
// identify the Extension Block. Therefore, it has not
// to be handled here.
byte identifier = ReadByte ();
switch (identifier) {
case 0xFE:
ReadCommentBlock ();
break;
case 0xFF:
ReadApplicationExtensionBlock ();
break;
// Control Extension Block, ...
case 0xF9:
// ... Plain Text Extension ...
case 0x01:
// ... and all other unknown blocks can be skipped by just
// reading sub-blocks.
default:
SkipSubBlocks ();
break;
}
}
/// <summary>
/// Reads an Application Extension Block at the current position. The current
/// position must point to the 3rd byte of the comment block. (The other 2 bytes
/// are usually read before to identify the comment block)
/// </summary>
private void ReadApplicationExtensionBlock ()
{
// Application Extension Block
//
// 1 Byte Extension Introducer (0x21)
// 1 Byte Application Extension Label (0xFF)
// 1 Byte Block Size (0x0B - 11)
// 8 Bytes Application Identifier
// 3 Bytes Application Auth. Code
// N Bytes Application Data (sub blocks)
// 1 Byte Block Terminator (0x00)
//
// Note, the first 2 bytes are still read to identify the Comment Block.
// Therefore, we only need to read the sub blocks and extract the data.
long position = Tell;
ByteVector data = ReadBlock (12);
if (data.Count != 12)
throw new CorruptFileException ("");
// Contains XMP data
if (data.Mid (1, 8) == XMP_IDENTIFIER &&
data.Mid (9, 3) == XMP_AUTH_CODE) {
// XMP Data is not organized in sub-blocks
// start of xmp data
long data_start = Tell;
// start of trailer start
// FIXME: Since File.Find is still buggy, the following call does not work to find the end of the
// XMP data. Therfore, we use here a different way for now.
//long xmp_trailer_start = Find (new ByteVector (0x00), data_start);
// Since searching just one byte is save, we search for the end of the xmp trailer which
// consists of two 0x00 bytes and compute the expected start.
long xmp_trailer_start = Find (new byte [] {0x00}, data_start) - XMP_MAGIC_TRAILER.Length + 2;
Seek (data_start, SeekOrigin.Begin);
if (xmp_trailer_start <= data_start)
throw new CorruptFileException ("No End of XMP data found");
// length of xmp data
int data_length = (int) (xmp_trailer_start - data_start);
ByteVector xmp_data = ReadBlock (data_length);
ImageTag.AddTag (new XmpTag (xmp_data.ToString (StringType.UTF8), this));
// 2 bytes where read before
AddMetadataBlock (position - 2, 14 + data_length + XMP_MAGIC_TRAILER.Length);
// set position behind the XMP block
Seek (xmp_trailer_start + XMP_MAGIC_TRAILER.Length, SeekOrigin.Begin);
} else {
SkipSubBlocks ();
}
}
/// <summary>
/// Reads a Comment Block at the current position. The current position must
/// point to the 3rd byte of the comment block. (The other 2 bytes are usually
/// read before to identify the comment block)
/// </summary>
private void ReadCommentBlock ()
{
long position = Tell;
// Comment Extension
//
// 1 Byte Extension Introducer (0x21)
// 1 Byte Comment Label (0xFE)
// N Bytes Comment Data (Sub Blocks)
// 1 Byte Block Terminator (0x00)
//
// Note, the first 2 bytes are still read to identify the Comment Block.
// Therefore, we only need to read the sub blocks and extract the data.
string comment = ReadSubBlocks ();
// Only add the tag, if no one is still contained.
if ((TagTypes & TagTypes.GifComment) == 0x00) {
ImageTag.AddTag (new GifCommentTag (comment));
// 2 bytes where read before
AddMetadataBlock (position - 2, Tell - position + 2);
}
}
/// <summary>
/// Skips the color table if there is one
/// </summary>
/// <param name="packed_data">
/// A <see cref="System.Byte"/> with the packed data which is
/// contained Logical Screen Descriptor or in the Image Descriptor.
/// </param>
/// <remarks>
/// The data contained in the packed data is different for the Logical
/// Screen Descriptor and for the Image Descriptor. But fortunately,
/// the bits which are used do identifying the exitstance and the size
/// of the color table are at the same position.
/// </remarks>
private void SkipColorTable (byte packed_data)
{
// Packed Field (Information with Bit 0 is LSB)
//
// Bit 0-2 Size of Color Table
// Bit 3-6 Other stuff
// Bit 7 (Local|Global) Color Table Flag
//
// We are interested in Bit 7 which indicates if a global color table is
// present or not and the Bits 0-2 which indicate the size of the color
// table.
if ((packed_data & 0x80) == 0x80) {
// 2^(size + 1) for each color.
int table_size = 3 * (1 << ((packed_data & 0x07) + 1));
// and simply skip the color table
ByteVector color_table = ReadBlock (table_size);
if (color_table.Count != table_size)
throw new CorruptFileException ("Unexpected end of Color Table");
}
}
/// <summary>
/// Skip over the image data at the current position. The current position must
/// point to 2nd byte of the Image Descriptor. (First byte is usually read before
/// to identify the image descriptor.)
/// </summary>
private void SkipImage ()
{
// Image Descriptor
//
// 1 Byte Separator (0x2C)
// 2 Bytes Image Left Position (little endian)
// 2 Bytes Image Right Position (little endian)
// 2 Bytes Image Witdh (little endian)
// 2 Bytes Image Height (little endian)
// 1 Byte Packed Data
//
// Note, the Separator was read before to identify the Image Block
// Therefore, we only need to read 9 bytes here.
ByteVector data = ReadBlock (9);
if (data.Count != 9)
throw new CorruptFileException ("Unexpected end of Image Descriptor");
// Skip an optional local color table
SkipColorTable (data [8]);
// Image Data
//
// 1 Byte LZW Minimum Code Size
// N Bytes Image Data (Sub-Blocks)
//
// Before the image data, one byte for LZW encoding information is used.
// This byte is read first, then the sub-blocks are skipped.
ReadBlock (1);
SkipSubBlocks ();
}
/// <summary>
/// Reads a sequence of sub-blocks from the current position and concatenates the data
/// from the sub-blocks to a string. The current position must point to the size-byte
/// of the first subblock to skip.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> with the data contained in the sub-blocks.
/// </returns>
private string ReadSubBlocks ()
{
// Sub Block
// Starts with one byte with the number of data bytes
// following. The last sub block is terminated by length 0
System.Text.StringBuilder builder = new System.Text.StringBuilder ();
byte length = 0;
do {
if (length >= 0)
builder.Append (ReadBlock (length).ToString ());
// read new length byte
length = ReadByte ();
// The sub-blocks are terminated with 0
} while (length != 0);
return builder.ToString ();
}
/// <summary>
/// Skips over a sequence of sub-blocks from the current position in the file.
/// The current position must point to the size-byte of the first subblock to skip.
/// </summary>
private void SkipSubBlocks ()
{
// Sub Block
// Starts with one byte with the number of data bytes
// following. The last sub block is terminated by length 0
byte length = 0;
do {
if (Tell + length >= Length)
throw new CorruptFileException ("Unexpected end of Sub-Block");
// Seek to end of sub-block and update the position
Seek (Tell + length, SeekOrigin.Begin);
// read new length byte
length = ReadByte ();
// The sub-blocks are terminated with 0
} while (length != 0);
}
/// <summary>
/// Save the metadata to file.
/// </summary>
private void SaveMetadata ()
{
ByteVector comment_block = RenderGifCommentBlock ();
ByteVector xmp_block = RenderXMPBlock ();
// If we write metadata and the version is not 89a, bump the format version
// because application extension blocks and comment extension blocks are
// specified in 89a.
// If we do not write metadata or if metadata is deleted, we do not care
// about the version, because it may be wrong before.
if (comment_block != null && xmp_block != null && version != VERSION_89A) {
Insert (VERSION_89A, 3, VERSION_89A.Length);
}
// now, only metadata is stored at the beginning of the file, and we can overwrite it.
ByteVector metadata_blocks = new ByteVector ();
metadata_blocks.Add (comment_block);
metadata_blocks.Add (xmp_block);
SaveMetadata (metadata_blocks, start_of_blocks);
}
/// <summary>
/// Renders the XMP data to a Application Extension Block which can be
/// embedded in a Gif file.
/// </summary>
/// <returns>
/// A <see cref="ByteVector"/> with the Application Extension Block for the
/// XMP data, or <see langword="null" /> if the file does not have XMP data.
/// </returns>
private ByteVector RenderXMPBlock ()
{
// Check, if XmpTag is contained
XmpTag xmp = ImageTag.Xmp;
if (xmp == null)
return null;
ByteVector xmp_data = new ByteVector ();
// Add Extension Introducer (0x21), Application Extension Label (0xFF) and
// the Block Size (0x0B
xmp_data.Add (new byte [] {0x21, 0xFF, 0x0B});
// Application Identifier and Appl. Auth. Code
xmp_data.Add (XMP_IDENTIFIER);
xmp_data.Add (XMP_AUTH_CODE);
// Add XMP data and Magic Trailer
// For XMP, we do not need to store the data in sub-blocks, therfore we
// can just add the whole rendered data. (The trailer fixes this)
xmp_data.Add (xmp.Render ());
xmp_data.Add (XMP_MAGIC_TRAILER);
return xmp_data;
}
/// <summary>
/// Renders the Gif Comment to a Comment Extension Block which can be
/// embedded in a Gif file.
/// </summary>
/// <returns>
/// A <see cref="ByteVector"/> with the Comment Extension Block for the
/// Gif Comment, or <see langword="null" /> if the file does not have
/// a Gif Comment.
/// </returns>
private ByteVector RenderGifCommentBlock ()
{
// Check, if GifCommentTag is contained
GifCommentTag comment_tag = GetTag (TagTypes.GifComment) as GifCommentTag;
if (comment_tag == null)
return null;
string comment = comment_tag.Comment;
if (comment == null)
return null;
ByteVector comment_data = new ByteVector ();
// Add Extension Introducer (0x21) and Comment Label (0xFE)
comment_data.Add (new byte [] {0x21, 0xFE});
// Add data of comment in sub-blocks of max length 256.
ByteVector comment_bytes = new ByteVector (comment);
byte block_max = 255;
for (int start = 0; start < comment_bytes.Count; start += block_max) {
byte block_length = (byte) Math.Min (comment_bytes.Count - start, block_max);
comment_data.Add (block_length);
comment_data.Add (comment_bytes.Mid (start, block_length));
}
comment_data.Add (new byte [] {0x00});
return comment_data;
}
/// <summary>
/// Attempts to extract the media properties of the main
/// photo.
/// </summary>
/// <returns>
/// A <see cref="Properties" /> object with a best effort guess
/// at the right values. When no guess at all can be made,
/// <see langword="null" /> is returned.
/// </returns>
private Properties ExtractProperties ()
{
if (width > 0 && height > 0)
return new Properties (TimeSpan.Zero, new Codec (width, height));
return null;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Composition.Hosting.Util;
using System.Diagnostics;
using System.Threading;
namespace System.Composition.Hosting.Core
{
/// <summary>
/// Represents a node in the lifetime tree. A <see cref="LifetimeContext"/> is the unit of
/// sharing for shared parts, controls the disposal of bound parts, and can be used to retrieve
/// instances either as part of an existing <see cref="CompositionOperation"/> or as the basis of a new
/// composition operation. An individual lifetime context can be marked to contain parts that are
/// constrained by particular sharing boundaries.
/// </summary>
/// <remarks>
/// Contains two pieces of _independently protected_ shared state. Shared part instances is
/// lock-free-readable and does not result in issues if added to during disposal. It is protected
/// by being locked itself. Activation logic is unavoidably called under this lock.
/// Bound part instances is always protected, by locking [this], and should never be written to
/// after disposal and so is set to null under a lock in Dispose(). If it were allowed it would result in
/// disposable parts not being released. Dispose methods on parts are called outside the lock.
/// </remarks>
/// <seealso cref="Export{T}"/>
public sealed class LifetimeContext : CompositionContext, IDisposable
{
private readonly LifetimeContext _root;
private readonly LifetimeContext _parent;
// Protects the two members holding shared instances
private readonly object _sharingLock = new object();
private SmallSparseInitonlyArray _sharedPartInstances, _instancesUndergoingInitialization;
// Protects the member holding bound instances.
private readonly object _boundPartLock = new object();
private List<IDisposable> _boundPartInstances = new List<IDisposable>(0);
private readonly string[] _sharingBoundaries;
private readonly ExportDescriptorRegistry _partRegistry;
private static int s_nextSharingId = -1;
/// <summary>
/// Generates an identifier that can be used to locate shared part instances.
/// </summary>
/// <returns>A new unique identifier.</returns>
public static int AllocateSharingId()
{
return Interlocked.Increment(ref s_nextSharingId);
}
internal LifetimeContext(ExportDescriptorRegistry partRegistry, string[] sharingBoundaries)
{
_root = this;
_sharingBoundaries = sharingBoundaries;
_partRegistry = partRegistry;
}
internal LifetimeContext(LifetimeContext parent, string[] sharingBoundaries)
{
_parent = parent;
_root = parent._root;
_sharingBoundaries = sharingBoundaries;
_partRegistry = parent._partRegistry;
}
/// <summary>
/// Find the broadest lifetime context within all of the specified sharing boundaries.
/// </summary>
/// <param name="sharingBoundary">The sharing boundary to find a lifetime context within.</param>
/// <returns>The broadest lifetime context within all of the specified sharing boundaries.</returns>
/// <remarks>Currently, the root cannot be a boundary.</remarks>
public LifetimeContext FindContextWithin(string sharingBoundary)
{
if (sharingBoundary == null)
return _root;
var toCheck = this;
while (toCheck != null)
{
foreach (var implemented in toCheck._sharingBoundaries)
{
if (implemented == sharingBoundary)
return toCheck;
}
toCheck = toCheck._parent;
}
// To generate acceptable error messages here we're going to need to pass in a description
// of the component, or otherwise find a way to get one.
string message = SR.Format(SR.Component_NotCreatableOutsideSharingBoundary, sharingBoundary);
var ex = new CompositionFailedException(message);
Debug.WriteLine(SR.Diagnostic_ThrowingException, ex.ToString());
throw ex;
}
/// <summary>
/// Release the lifetime context and any disposable part instances
/// that are bound to it.
/// </summary>
public void Dispose()
{
IEnumerable<IDisposable> toDispose = null;
lock (_boundPartLock)
{
if (_boundPartInstances != null)
{
toDispose = _boundPartInstances;
_boundPartInstances = null;
}
}
if (toDispose != null)
{
foreach (var instance in toDispose)
instance.Dispose();
}
}
/// <summary>
/// Bind the lifetime of a disposable part to the current
/// lifetime context.
/// </summary>
/// <param name="instance">The disposable part to bind.</param>
public void AddBoundInstance(IDisposable instance)
{
lock (_boundPartLock)
{
if (_boundPartInstances == null)
throw new ObjectDisposedException(ToString());
_boundPartInstances.Add(instance);
}
}
/// <summary>
/// Either retrieve an existing part instance with the specified sharing id, or
/// create and share a new part instance using <paramref name="creator"/> within
/// <paramref name="operation"/>.
/// </summary>
/// <param name="sharingId">Sharing id for the part in question.</param>
/// <param name="operation">Operation in which to activate a new part instance if necessary.</param>
/// <param name="creator">Activator that can activate a new part instance if necessary.</param>
/// <returns>The part instance corresponding to <paramref name="sharingId"/> within this lifetime context.</returns>
/// <remarks>This method is lock-free if the part instance already exists. If the part instance must be created,
/// a lock will be taken that will serialize other writes via this method (concurrent reads will continue to
/// be safe and lock-free). It is important that the composition, and thus lock acquisition, is strictly
/// leaf-to-root in the lifetime tree.</remarks>
public object GetOrCreate(int sharingId, CompositionOperation operation, CompositeActivator creator)
{
object result;
if (_sharedPartInstances != null && _sharedPartInstances.TryGetValue(sharingId, out result))
return result;
// Remains locked for the rest of the operation.
operation.EnterSharingLock(_sharingLock);
if (_sharedPartInstances == null)
{
_sharedPartInstances = new SmallSparseInitonlyArray();
_instancesUndergoingInitialization = new SmallSparseInitonlyArray();
}
else if (_sharedPartInstances.TryGetValue(sharingId, out result))
{
return result;
}
// Already being initialized _on the same thread_.
if (_instancesUndergoingInitialization.TryGetValue(sharingId, out result))
return result;
result = creator(this, operation);
_instancesUndergoingInitialization.Add(sharingId, result);
operation.AddPostCompositionAction(() =>
{
_sharedPartInstances.Add(sharingId, result);
});
return result;
}
/// <summary>
/// Retrieve the single <paramref name="contract"/> instance from the
/// <see cref="CompositionContext"/>.
/// </summary>
/// <param name="contract">The contract to retrieve.</param>
/// <returns>An instance of the export.</returns>
/// <param name="export">The export if available, otherwise, null.</param>
/// <exception cref="CompositionFailedException" />
public override bool TryGetExport(CompositionContract contract, out object export)
{
ExportDescriptor defaultForExport;
if (!_partRegistry.TryGetSingleForExport(contract, out defaultForExport))
{
export = null;
return false;
}
export = CompositionOperation.Run(this, defaultForExport.Activator);
return true;
}
/// <summary>
/// Describes this lifetime context.
/// </summary>
/// <returns>A string description.</returns>
public override string ToString()
{
if (_parent == null)
return "Root Lifetime Context";
if (_sharingBoundaries.Length == 0)
return "Non-sharing Lifetime Context";
return "Boundary for " + string.Join(", ", _sharingBoundaries);
}
}
}
| |
using PatchKit.Api.Models.Main;
using System.Collections.Generic;
using System.Threading;
using CancellationToken = PatchKit.Unity.Patcher.Cancellation.CancellationToken;
namespace PatchKit.Api
{
public partial class MainApiConnection
{
/// <param name="apiKey">Application owner API key.</param>
public App[] ListsUserApplications(string apiKey, CancellationToken cancellationToken)
{
string path = "/1/apps";
List<string> queryList = new List<string>();
queryList.Add("api_key="+apiKey);
string query = string.Join("&", queryList.ToArray());
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<App[]>(response);
}
/// <summary>
/// Gets detailes app info
/// </summary>
/// <param name="appSecret">Secret of an application.</param>
public App GetApplicationInfo(string appSecret, CancellationToken cancellationToken)
{
string path = "/1/apps/{app_secret}";
path = path.Replace("{app_secret}", appSecret.ToString());
string query = string.Empty;
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<App>(response);
}
/// <summary>
/// Gets a complete changelog of an application.
/// </summary>
/// <param name="appSecret">Secret of an application.</param>
public Changelog GetAppChangelog(string appSecret, CancellationToken cancellationToken)
{
string path = "/1/apps/{app_secret}/changelog";
path = path.Replace("{app_secret}", appSecret.ToString());
string query = string.Empty;
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<Changelog>(response);
}
/// <summary>
/// Gets the basic information for all published versions. When API Key is provided, draft version information is included if draft version exists.
/// </summary>
/// <param name="appSecret">Secret of an application.</param>
/// <param name="apiKey">Application owner API key.</param>
public AppVersion[] GetAppVersionList(string appSecret, string apiKey, CancellationToken cancellationToken)
{
string path = "/1/apps/{app_secret}/versions";
List<string> queryList = new List<string>();
path = path.Replace("{app_secret}", appSecret.ToString());
if (apiKey != null)
{
queryList.Add("api_key="+apiKey);
}
string query = string.Join("&", queryList.ToArray());
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<AppVersion[]>(response);
}
/// <summary>
/// Gets latest application version object.
/// </summary>
/// <param name="appSecret">Secret of an application.</param>
public AppVersion GetAppLatestAppVersion(string appSecret, CancellationToken cancellationToken)
{
string path = "/1/apps/{app_secret}/versions/latest";
path = path.Replace("{app_secret}", appSecret.ToString());
string query = string.Empty;
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<AppVersion>(response);
}
/// <summary>
/// Gets latest application version id. Please use /apps/{app_secret} instead to get the latest version.
/// </summary>
/// <param name="appSecret">Secret of an application.</param>
[System.Obsolete]
public AppVersionId GetAppLatestAppVersionId(string appSecret, CancellationToken cancellationToken)
{
string path = "/1/apps/{app_secret}/versions/latest/id";
path = path.Replace("{app_secret}", appSecret.ToString());
string query = string.Empty;
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<AppVersionId>(response);
}
/// <summary>
/// Gets selected version object. If API key is provided, can get the information about draft version.
/// </summary>
/// <param name="appSecret">Secret of an application.</param>
/// <param name="versionId">Version id.</param>
/// <param name="apiKey">Application owner API key.</param>
public AppVersion GetAppVersion(string appSecret, int versionId, string apiKey, CancellationToken cancellationToken)
{
string path = "/1/apps/{app_secret}/versions/{version_id}";
List<string> queryList = new List<string>();
path = path.Replace("{app_secret}", appSecret.ToString());
path = path.Replace("{version_id}", versionId.ToString());
if (apiKey != null)
{
queryList.Add("api_key="+apiKey);
}
string query = string.Join("&", queryList.ToArray());
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<AppVersion>(response);
}
/// <summary>
/// Gets selected version content summary.
/// </summary>
/// <param name="appSecret">Secret of an application.</param>
/// <param name="versionId">Version id.</param>
public AppContentSummary GetAppVersionContentSummary(string appSecret, int versionId, CancellationToken cancellationToken)
{
string path = "/1/apps/{app_secret}/versions/{version_id}/content_summary";
path = path.Replace("{app_secret}", appSecret.ToString());
path = path.Replace("{version_id}", versionId.ToString());
string query = string.Empty;
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<AppContentSummary>(response);
}
/// <summary>
/// Gets selected version diff summary.
/// </summary>
/// <param name="appSecret">Secret of an application.</param>
/// <param name="versionId">Version id.</param>
public AppDiffSummary GetAppVersionDiffSummary(string appSecret, int versionId, CancellationToken cancellationToken)
{
string path = "/1/apps/{app_secret}/versions/{version_id}/diff_summary";
path = path.Replace("{app_secret}", appSecret.ToString());
path = path.Replace("{version_id}", versionId.ToString());
string query = string.Empty;
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<AppDiffSummary>(response);
}
/// <summary>
/// Gets selected application version content torrent url.
/// </summary>
/// <param name="appSecret">Secret of an application.</param>
/// <param name="versionId">Version id.</param>
/// <param name="keySecret">Key secret provided by key server. This value is optional and is needed only if application is secured by license keys.</param>
public AppContentTorrentUrl GetAppVersionContentTorrentUrl(string appSecret, int versionId, string keySecret, CancellationToken cancellationToken)
{
string path = "/1/apps/{app_secret}/versions/{version_id}/content_torrent_url";
List<string> queryList = new List<string>();
path = path.Replace("{app_secret}", appSecret.ToString());
path = path.Replace("{version_id}", versionId.ToString());
if (keySecret != null)
{
queryList.Add("key_secret="+keySecret);
}
string query = string.Join("&", queryList.ToArray());
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<AppContentTorrentUrl>(response);
}
/// <summary>
/// Gets selected application version diff torrent url.
/// </summary>
/// <param name="appSecret">Secret of an application.</param>
/// <param name="versionId">Version id.</param>
/// <param name="keySecret">Key secret provided by key server. This value is optional and is needed only if application is secured by license keys.</param>
public AppDiffTorrentUrl GetAppVersionDiffTorrentUrl(string appSecret, int versionId, string keySecret, CancellationToken cancellationToken)
{
string path = "/1/apps/{app_secret}/versions/{version_id}/diff_torrent_url";
List<string> queryList = new List<string>();
path = path.Replace("{app_secret}", appSecret.ToString());
path = path.Replace("{version_id}", versionId.ToString());
if (keySecret != null)
{
queryList.Add("key_secret="+keySecret);
}
string query = string.Join("&", queryList.ToArray());
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<AppDiffTorrentUrl>(response);
}
/// <summary>
/// Gets selected application version content urls.
/// </summary>
/// <param name="appSecret">Secret of an application.</param>
/// <param name="versionId">Version id.</param>
/// <param name="country">Country iso code</param>
/// <param name="keySecret">Key secret provided by key server. This value is optional and is needed only if application is secured by license keys.</param>
public ResourceUrl[] GetAppVersionContentUrls(string appSecret, int versionId, string country, string keySecret, CancellationToken cancellationToken)
{
string path = "/1/apps/{app_secret}/versions/{version_id}/content_urls";
List<string> queryList = new List<string>();
path = path.Replace("{app_secret}", appSecret.ToString());
path = path.Replace("{version_id}", versionId.ToString());
if (country != null)
{
queryList.Add("country="+country);
}
if (keySecret != null)
{
queryList.Add("key_secret="+keySecret);
}
string query = string.Join("&", queryList.ToArray());
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<ResourceUrl[]>(response);
}
/// <summary>
/// Gets selected application version diff urls.
/// </summary>
/// <param name="appSecret">Secret of an application.</param>
/// <param name="versionId">Version id.</param>
/// <param name="country">Country iso code</param>
/// <param name="keySecret">Key secret provided by key server. This value is optional and is needed only if application is secured by license keys.</param>
public ResourceUrl[] GetAppVersionDiffUrls(string appSecret, int versionId, string country, string keySecret, CancellationToken cancellationToken)
{
string path = "/1/apps/{app_secret}/versions/{version_id}/diff_urls";
List<string> queryList = new List<string>();
path = path.Replace("{app_secret}", appSecret.ToString());
path = path.Replace("{version_id}", versionId.ToString());
if (country != null)
{
queryList.Add("country="+country);
}
if (keySecret != null)
{
queryList.Add("key_secret="+keySecret);
}
string query = string.Join("&", queryList.ToArray());
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<ResourceUrl[]>(response);
}
/// <param name="apiKey">Application owner API key. Required when not using a session.</param>
public Plan GetPlanInfo(string apiKey, CancellationToken cancellationToken)
{
string path = "/1/me/plan";
List<string> queryList = new List<string>();
queryList.Add("api_key="+apiKey);
string query = string.Join("&", queryList.ToArray());
var response = GetResponse(path, query, cancellationToken);
return ParseResponse<Plan>(response);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.EntityFrameworkCore.Spanner.Extensions;
using Google.Cloud.EntityFrameworkCore.Spanner.Extensions.Internal;
using Google.Cloud.EntityFrameworkCore.Spanner.Infrastructure;
using Google.Cloud.EntityFrameworkCore.Spanner.IntegrationTests.Model;
using Google.Cloud.EntityFrameworkCore.Spanner.Storage;
using Google.Cloud.Spanner.Data;
using Google.Cloud.Spanner.V1;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
using V1 = Google.Cloud.Spanner.V1;
#pragma warning disable EF1001
namespace Google.Cloud.EntityFrameworkCore.Spanner.Tests
{
internal class MockServerSampleDbContextUsingMutations : SpannerSampleDbContext
{
private readonly string _connectionString;
internal MockServerSampleDbContextUsingMutations(string connectionString) : base()
{
_connectionString = connectionString;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder
.UseSpanner(_connectionString, _ => SpannerModelValidationConnectionProvider.Instance.EnableDatabaseModelValidation(false), ChannelCredentials.Insecure)
.UseMutations(MutationUsage.Always)
.UseLazyLoadingProxies();
}
}
}
internal class MockServerVersionDbContextUsingMutations : SpannerVersionDbContext
{
private readonly string _connectionString;
internal MockServerVersionDbContextUsingMutations(string connectionString) : base()
{
_connectionString = connectionString;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder
.UseSpanner(_connectionString, _ => SpannerModelValidationConnectionProvider.Instance.EnableDatabaseModelValidation(false), ChannelCredentials.Insecure)
.UseMutations(MutationUsage.Always)
.UseLazyLoadingProxies();
}
}
}
/// <summary>
/// Tests CRUD operations using mutations on an in-mem Spanner mock server.
/// </summary>
public class EntityFrameworkMockUsingMutationsServerTests : IClassFixture<SpannerMockServerFixture>
{
private readonly SpannerMockServerFixture _fixture;
public EntityFrameworkMockUsingMutationsServerTests(SpannerMockServerFixture service)
{
_fixture = service;
service.SpannerMock.Reset();
}
private string ConnectionString => $"Data Source=projects/p1/instances/i1/databases/d1;Host={_fixture.Host};Port={_fixture.Port}";
[Fact]
public async Task InsertAlbum()
{
using var db = new MockServerSampleDbContextUsingMutations(ConnectionString);
db.Albums.Add(new Albums
{
AlbumId = 1L,
Title = "Some title",
SingerId = 1L,
ReleaseDate = new SpannerDate(2000, 1, 1),
});
var updateCount = await db.SaveChangesAsync();
Assert.Equal(1L, updateCount);
Assert.Collection(
_fixture.SpannerMock.Requests.Where(request => request is CommitRequest).Select(request => (CommitRequest)request),
request => {
Assert.Single(request.Mutations);
var mutation = request.Mutations[0];
Assert.Equal(Mutation.OperationOneofCase.Insert, mutation.OperationCase);
Assert.Equal("Albums", mutation.Insert.Table);
var row = mutation.Insert.Values[0];
var cols = mutation.Insert.Columns;
Assert.Equal("1", row.Values[cols.IndexOf("AlbumId")].StringValue);
Assert.Equal("Some title", row.Values[cols.IndexOf("Title")].StringValue);
Assert.Equal("1", row.Values[cols.IndexOf("SingerId")].StringValue);
Assert.Equal("2000-01-01", row.Values[cols.IndexOf("ReleaseDate")].StringValue);
}
);
}
[Fact]
public async Task InsertSinger()
{
var selectFullNameSql = AddSelectSingerFullNameResult("Alice Morrison", 0);
using var db = new MockServerSampleDbContextUsingMutations(ConnectionString);
db.Singers.Add(new Singers
{
SingerId = 1L,
FirstName = "Alice",
LastName = "Morrison",
});
var updateCount = await db.SaveChangesAsync();
Assert.Equal(1L, updateCount);
Assert.Collection(
_fixture.SpannerMock.Requests.Where(request => request is CommitRequest).Select(request => (CommitRequest)request),
request => {
Assert.Single(request.Mutations);
var mutation = request.Mutations[0];
Assert.Equal(Mutation.OperationOneofCase.Insert, mutation.OperationCase);
Assert.Equal("Singers", mutation.Insert.Table);
var row = mutation.Insert.Values[0];
var cols = mutation.Insert.Columns;
Assert.Equal("1", row.Values[cols.IndexOf("SingerId")].StringValue);
Assert.Equal("Alice", row.Values[cols.IndexOf("FirstName")].StringValue);
Assert.Equal("Morrison", row.Values[cols.IndexOf("LastName")].StringValue);
Assert.Equal(-1, cols.IndexOf("FullName"));
}
);
// Verify that the SELECT for the FullName is done after the commit.
Assert.Collection(_fixture.SpannerMock.Requests
.Where(request => request is CommitRequest || request is ExecuteSqlRequest)
.Select(request => request.GetType()),
request => Assert.Equal(typeof(CommitRequest), request),
request => Assert.Equal(typeof(ExecuteSqlRequest), request));
Assert.Single(_fixture.SpannerMock.Requests
.Where(request => request is ExecuteSqlRequest sqlRequest && sqlRequest.Sql.Trim() == selectFullNameSql.Trim()));
}
[Fact]
public async Task InsertSingerInTransaction()
{
using var db = new MockServerSampleDbContextUsingMutations(ConnectionString);
using var transaction = await db.Database.BeginTransactionAsync();
db.Singers.Add(new Singers
{
SingerId = 1L,
FirstName = "Alice",
LastName = "Morrison",
});
var updateCount = await db.SaveChangesAsync();
await transaction.CommitAsync();
Assert.Equal(1L, updateCount);
Assert.Collection(
_fixture.SpannerMock.Requests.Where(request => request is CommitRequest).Select(request => (CommitRequest)request),
request => {
Assert.Single(request.Mutations);
var mutation = request.Mutations[0];
Assert.Equal(Mutation.OperationOneofCase.Insert, mutation.OperationCase);
Assert.Equal("Singers", mutation.Insert.Table);
var row = mutation.Insert.Values[0];
var cols = mutation.Insert.Columns;
Assert.Equal("1", row.Values[cols.IndexOf("SingerId")].StringValue);
Assert.Equal("Alice", row.Values[cols.IndexOf("FirstName")].StringValue);
Assert.Equal("Morrison", row.Values[cols.IndexOf("LastName")].StringValue);
Assert.Equal(-1, cols.IndexOf("FullName"));
}
);
// Verify that EF Core does NOT try to fetch the name of the Singer, even though it is a computed
// column that should normally be propagated. The fetch is skipped because the update uses mutations
// in combination with manual transactions. Trying to fetch the name of the singer is therefore not
// possible during the transaction.
Assert.Collection(_fixture.SpannerMock.Requests
.Where(request => request is CommitRequest || request is ExecuteSqlRequest)
.Select(request => request.GetType()),
request => Assert.Equal(typeof(CommitRequest), request));
}
[Fact]
public async Task UpdateSinger_SelectsFullName()
{
// Setup results.
var selectSingerSql = AddFindSingerResult($"SELECT `s`.`SingerId`, `s`.`BirthDate`, `s`.`FirstName`, " +
$"`s`.`FullName`, `s`.`LastName`, `s`.`Picture`{Environment.NewLine}FROM `Singers` AS `s`{Environment.NewLine}" +
$"WHERE `s`.`SingerId` = @__p_0{Environment.NewLine}LIMIT 1");
var selectFullNameSql = AddSelectSingerFullNameResult("Alice Pieterson-Morrison", 0);
using var db = new MockServerSampleDbContextUsingMutations(ConnectionString);
var singer = await db.Singers.FindAsync(1L);
singer.LastName = "Pieterson-Morrison";
var updateCount = await db.SaveChangesAsync();
Assert.Equal(1L, updateCount);
Assert.Collection(
_fixture.SpannerMock.Requests
.Where(request => !new[] { typeof(BeginTransactionRequest), typeof(BatchCreateSessionsRequest) }.Contains(request.GetType()))
.Select(request => request.GetType()),
request => Assert.Equal(typeof(ExecuteSqlRequest), request),
request => Assert.Equal(typeof(CommitRequest), request),
request => Assert.Equal(typeof(ExecuteSqlRequest), request)
);
Assert.Collection(
_fixture.SpannerMock.Requests.Where(request => request is ExecuteSqlRequest).Select(request => (ExecuteSqlRequest)request),
request =>
{
Assert.Equal(selectSingerSql.Trim(), request.Sql.Trim());
Assert.Null(request.Transaction?.Id);
},
request =>
{
Assert.Equal(selectFullNameSql.Trim(), request.Sql.Trim());
Assert.Null(request.Transaction?.Id);
}
);
Assert.Collection(
_fixture.SpannerMock.Requests.Where(request => request is CommitRequest).Select(request => request as CommitRequest),
request =>
{
Assert.Collection(
request.Mutations,
mutation =>
{
Assert.Equal(Mutation.OperationOneofCase.Update, mutation.OperationCase);
Assert.Equal("Singers", mutation.Update.Table);
Assert.Collection(
mutation.Update.Columns,
column => Assert.Equal("SingerId", column),
column => Assert.Equal("LastName", column)
);
Assert.Collection(
mutation.Update.Values,
row =>
{
Assert.Collection(
row.Values,
value => Assert.Equal("1", value.StringValue),
value => Assert.Equal("Pieterson-Morrison", value.StringValue)
);
}
);
}
);
}
);
}
[Fact]
public async Task DeleteSinger_DoesNotSelectFullName()
{
using var db = new MockServerSampleDbContextUsingMutations(ConnectionString);
db.Singers.Remove(new Singers { SingerId = 1L });
var updateCount = await db.SaveChangesAsync();
Assert.Equal(1L, updateCount);
Assert.Collection(
_fixture.SpannerMock.Requests.Where(request => request is CommitRequest).Select(request => (CommitRequest)request),
request =>
{
Assert.Single(request.Mutations);
var mutation = request.Mutations[0];
Assert.Equal(Mutation.OperationOneofCase.Delete, mutation.OperationCase);
Assert.Equal("Singers", mutation.Delete.Table);
var keySet = mutation.Delete.KeySet;
Assert.False(keySet.All);
Assert.Empty(keySet.Ranges);
Assert.Single(keySet.Keys);
Assert.Single(keySet.Keys[0].Values);
Assert.Equal("1", keySet.Keys[0].Values[0].StringValue);
}
);
Assert.Empty(_fixture.SpannerMock.Requests.Where(request => request is ExecuteBatchDmlRequest));
Assert.Empty(_fixture.SpannerMock.Requests.Where(request => request is ExecuteSqlRequest));
Assert.Single(_fixture.SpannerMock.Requests.Where(request => request is CommitRequest));
}
[Fact]
public async Task VersionNumberIsAutomaticallyGeneratedOnInsertAndUpdate()
{
using var db = new MockServerVersionDbContextUsingMutations(ConnectionString);
var singer = new SingersWithVersion { SingerId = 1L, FirstName = "Pete", LastName = "Allison" };
db.Singers.Add(singer);
await db.SaveChangesAsync();
Assert.Empty(_fixture.SpannerMock.Requests.Where(r => r is ExecuteBatchDmlRequest));
Assert.Collection(
_fixture.SpannerMock.Requests.Where(r => r is CommitRequest).Select(r => r as CommitRequest),
r =>
{
Assert.Collection(
r.Mutations,
mutation =>
{
Assert.Equal(Mutation.OperationOneofCase.Insert, mutation.OperationCase);
Assert.Equal("SingersWithVersion", mutation.Insert.Table);
Assert.Collection(
mutation.Insert.Columns,
column => Assert.Equal("SingerId", column),
column => Assert.Equal("FirstName", column),
column => Assert.Equal("LastName", column),
column => Assert.Equal("Version", column)
);
Assert.Collection(
mutation.Insert.Values,
row => Assert.Collection(
row.Values,
value => Assert.Equal("1", value.StringValue),
value => Assert.Equal("Pete", value.StringValue),
value => Assert.Equal("Allison", value.StringValue),
value => Assert.Equal("1", value.StringValue)
)
);
}
);
}
);
_fixture.SpannerMock.Reset();
// Update the singer and verify that the version number is first checked using a SELECT statement and then is updated in a mutation.
var concurrencySql = $"SELECT 1 FROM `SingersWithVersion` {Environment.NewLine}WHERE `SingerId` = @p0 AND `Version` = @p1";
_fixture.SpannerMock.AddOrUpdateStatementResult(concurrencySql, StatementResult.CreateSelect1ResultSet());
singer.LastName = "Peterson - Allison";
await db.SaveChangesAsync();
Assert.Empty(_fixture.SpannerMock.Requests.Where(r => r is ExecuteBatchDmlRequest));
Assert.Collection(
_fixture.SpannerMock.Requests.Where(r => r is ExecuteSqlRequest).Select(r => r as ExecuteSqlRequest),
r =>
{
Assert.Equal("1", r.Params.Fields["p0"].StringValue); // SingerId
Assert.Equal("1", r.Params.Fields["p1"].StringValue); // Version
}
);
Assert.Collection(
_fixture.SpannerMock.Requests.Where(r => r is CommitRequest).Select(r => r as CommitRequest),
r =>
{
Assert.Collection(
r.Mutations,
mutation =>
{
Assert.Equal(Mutation.OperationOneofCase.Update, mutation.OperationCase);
Assert.Equal("SingersWithVersion", mutation.Update.Table);
Assert.Collection(
mutation.Update.Columns,
column => Assert.Equal("SingerId", column),
column => Assert.Equal("LastName", column),
column => Assert.Equal("Version", column)
);
Assert.Collection(
mutation.Update.Values,
row => Assert.Collection(
row.Values,
value => Assert.Equal("1", value.StringValue),
value => Assert.Equal("Peterson - Allison", value.StringValue),
value => Assert.Equal("2", value.StringValue)
)
);
}
);
}
);
}
[Fact]
public async Task UpdateFailsIfVersionNumberChanged()
{
using var db = new MockServerVersionDbContextUsingMutations(ConnectionString);
// Set the result of the concurrency check to an empty result set to simulate a version number that has changed.
var concurrencySql = $"SELECT 1 FROM `SingersWithVersion` {Environment.NewLine}WHERE `SingerId` = @p0 AND `Version` = @p1";
_fixture.SpannerMock.AddOrUpdateStatementResult(concurrencySql, StatementResult.CreateSingleColumnResultSet(new V1.Type { Code = V1.TypeCode.Int64 }, "COL1"));
// Attach a singer to the context and try to update it.
var singer = new SingersWithVersion { SingerId = 1L, FirstName = "Pete", LastName = "Allison", Version = 1L };
db.Attach(singer);
singer.LastName = "Allison - Peterson";
await Assert.ThrowsAsync<DbUpdateConcurrencyException>(() => db.SaveChangesAsync());
// Update the concurrency check result to 1 to simulate a resolved version conflict.
_fixture.SpannerMock.AddOrUpdateStatementResult(concurrencySql, StatementResult.CreateSelect1ResultSet());
Assert.Equal(1L, await db.SaveChangesAsync());
}
[Theory]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public async Task ExplicitAndImplicitTransactionIsRetried(bool disableInternalRetries, bool useExplicitTransaction)
{
using var db = new MockServerSampleDbContextUsingMutations(ConnectionString);
IDbContextTransaction transaction = null;
if (useExplicitTransaction)
{
// Note that using explicit transactions in combination with mutations has a couple of side-effects:
// 1. Read-your-writes does not work.
// 2. Computed columns are not propagated to the current context.
transaction = await db.Database.BeginTransactionAsync();
if (disableInternalRetries)
{
transaction.DisableInternalRetries();
}
}
db.Venues.Add(new Venues
{
Code = "C1",
Name = "Concert Hall",
});
// Abort the next statement that is executed on the mock server.
_fixture.SpannerMock.AbortNextStatement();
// We can only disable internal retries when using explicit transactions. Otherwise internal retries
// are always used.
if (disableInternalRetries && useExplicitTransaction)
{
await db.SaveChangesAsync();
var e = await Assert.ThrowsAsync<SpannerException>(() => transaction.CommitAsync());
Assert.Equal(ErrorCode.Aborted, e.ErrorCode);
}
else
{
var updateCount = await db.SaveChangesAsync();
Assert.Equal(1L, updateCount);
if (useExplicitTransaction)
{
await transaction.CommitAsync();
}
Assert.Empty(_fixture.SpannerMock.Requests.Where(request => request is ExecuteBatchDmlRequest));
Assert.Collection(
_fixture.SpannerMock.Requests.Where(request => request is CommitRequest).Select(request => (CommitRequest)request),
// The commit request is sent twice to the server, as the statement is aborted during the first attempt.
request =>
{
Assert.Single(request.Mutations);
Assert.Equal("Venues", request.Mutations.First().Insert.Table);
Assert.NotNull(request.TransactionId);
},
request =>
{
Assert.Single(request.Mutations);
Assert.Equal("Venues", request.Mutations.First().Insert.Table);
Assert.NotNull(request.TransactionId);
}
);
}
}
[Fact]
public async Task CanInsertCommitTimestamp()
{
using var db = new MockServerSampleDbContextUsingMutations(ConnectionString);
_fixture.SpannerMock.AddOrUpdateStatementResult($"{Environment.NewLine}SELECT `ColComputed`" +
$"{Environment.NewLine}FROM `TableWithAllColumnTypes`{Environment.NewLine}WHERE TRUE AND `ColInt64` = @p0", StatementResult.CreateSingleColumnResultSet(new V1.Type { Code = V1.TypeCode.String }, "FOO"));
db.TableWithAllColumnTypes.Add(new TableWithAllColumnTypes { ColInt64 = 1L });
await db.SaveChangesAsync();
Assert.Collection(
_fixture.SpannerMock.Requests.Where(request => request is CommitRequest).Select(request => (CommitRequest)request),
request =>
{
Assert.Single(request.Mutations);
var mutation = request.Mutations[0];
Assert.Equal(Mutation.OperationOneofCase.Insert, mutation.OperationCase);
Assert.Single(mutation.Insert.Values);
var row = mutation.Insert.Values[0];
var cols = mutation.Insert.Columns;
Assert.Equal("spanner.commit_timestamp()", row.Values[cols.IndexOf("ColCommitTS")].StringValue);
}
);
}
[Fact]
public async Task CanUpdateCommitTimestamp()
{
using var db = new MockServerSampleDbContextUsingMutations(ConnectionString);
_fixture.SpannerMock.AddOrUpdateStatementResult($"{Environment.NewLine}SELECT `ColComputed`{Environment.NewLine}FROM `TableWithAllColumnTypes`{Environment.NewLine}WHERE TRUE AND `ColInt64` = @p0", StatementResult.CreateSingleColumnResultSet(new V1.Type { Code = V1.TypeCode.String }, "FOO"));
var row = new TableWithAllColumnTypes { ColInt64 = 1L };
db.TableWithAllColumnTypes.Attach(row);
row.ColBool = true;
await db.SaveChangesAsync();
Assert.Collection(
_fixture.SpannerMock.Requests.Where(request => request is CommitRequest).Select(request => (CommitRequest)request),
request =>
{
Assert.Single(request.Mutations);
var mutation = request.Mutations[0];
Assert.Equal(Mutation.OperationOneofCase.Update, mutation.OperationCase);
Assert.Single(mutation.Update.Values);
var row = mutation.Update.Values[0];
var cols = mutation.Update.Columns;
Assert.Equal("spanner.commit_timestamp()", row.Values[cols.IndexOf("ColCommitTS")].StringValue);
}
);
}
[Fact]
public async Task CanInsertRowWithCommitTimestampAndComputedColumn()
{
using var db = new MockServerSampleDbContextUsingMutations(ConnectionString);
var selectSql = $"{Environment.NewLine}SELECT `ColComputed`{Environment.NewLine}FROM `TableWithAllColumnTypes`{Environment.NewLine}WHERE TRUE AND `ColInt64` = @p0";
_fixture.SpannerMock.AddOrUpdateStatementResult(selectSql, StatementResult.CreateSingleColumnResultSet(new V1.Type { Code = V1.TypeCode.String }, "FOO"));
db.TableWithAllColumnTypes.Add(
new TableWithAllColumnTypes { ColInt64 = 1L }
);
await db.SaveChangesAsync();
Assert.Empty(_fixture.SpannerMock.Requests.Where(request => request is ExecuteBatchDmlRequest));
Assert.Collection(
_fixture.SpannerMock.Requests.Where(request => request is ExecuteSqlRequest).Select(request => (ExecuteSqlRequest)request),
request => Assert.Equal(selectSql.Trim(), request.Sql.Trim())
);
Assert.Single(_fixture.SpannerMock.Requests.Where(request => request is CommitRequest));
// Verify the order of the requests (that is, the Select statement should be outside the implicit transaction).
Assert.Collection(
_fixture.SpannerMock.Requests.Where(request => request is CommitRequest || request is ExecuteSqlRequest).Select(request => request.GetType()),
requestType => Assert.Equal(typeof(CommitRequest), requestType),
requestType => Assert.Equal(typeof(ExecuteSqlRequest), requestType)
);
Assert.Collection(
_fixture.SpannerMock.Requests.Where(request => request is CommitRequest).Select(request => (CommitRequest)request),
request =>
{
Assert.Single(request.Mutations);
var mutation = request.Mutations[0];
Assert.Equal(Mutation.OperationOneofCase.Insert, mutation.OperationCase);
Assert.Single(mutation.Insert.Values);
var row = mutation.Insert.Values[0];
var cols = mutation.Insert.Columns;
Assert.Equal("spanner.commit_timestamp()", row.Values[cols.IndexOf("ColCommitTS")].StringValue);
}
);
}
[Fact]
public async Task CanInsertAllTypes()
{
using var db = new MockServerSampleDbContextUsingMutations(ConnectionString);
_fixture.SpannerMock.AddOrUpdateStatementResult($"{Environment.NewLine}SELECT `ColComputed`" +
$"{Environment.NewLine}FROM `TableWithAllColumnTypes`{Environment.NewLine}WHERE TRUE AND `ColInt64` = @p0", StatementResult.CreateSingleColumnResultSet(new V1.Type { Code = V1.TypeCode.String }, "FOO"));
db.TableWithAllColumnTypes.Add(new TableWithAllColumnTypes
{
ColInt64 = 1L,
ColBool = true,
ColBytes = new byte[] {1,2,3},
ColDate = new SpannerDate(2000, 1, 1),
ColFloat64 = 3.14,
ColJson = JsonDocument.Parse("{\"key\": \"value\"}"),
ColNumeric = SpannerNumeric.Parse("6.626"),
ColString = "test",
ColTimestamp = new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc),
ColBoolArray = new List<bool?>{true, null, false},
ColBytesArray = new List<byte[]>{new byte[]{1,2,3}, null, new byte[]{3,2,1}},
ColBytesMax = new byte[] {},
ColDateArray = new List<SpannerDate?>{new SpannerDate(2021, 8, 26), null, new SpannerDate(2000, 1, 1)},
ColFloat64Array = new List<double?>{3.14, null, 6.626},
ColInt64Array = new List<long?>{1,null,2},
ColJsonArray = new List<JsonDocument>{JsonDocument.Parse("{\"key1\": \"value1\"}"), null, JsonDocument.Parse("{\"key2\": \"value2\"}")},
ColNumericArray = new List<SpannerNumeric?>{SpannerNumeric.Parse("3.14"), null, SpannerNumeric.Parse("6.626")},
ColStringArray = new List<string>{"test1", null, "test2"},
ColStringMax = "",
ColTimestampArray = new List<DateTime?>{new DateTime(2000, 1, 1, 0, 0, 0, 1, DateTimeKind.Utc), null, new DateTime(2000, 1, 1, 0, 0, 0, 2, DateTimeKind.Utc)},
ColBytesMaxArray = new List<byte[]>(),
ColStringMaxArray = new List<string>(),
});
await db.SaveChangesAsync();
// Verify the value types.
Assert.Collection(
_fixture.SpannerMock.Requests.OfType<CommitRequest>(),
request =>
{
var values = request.Mutations[0].Insert.Values[0].Values;
var columns = request.Mutations[0].Insert.Columns;
var index = 0;
Assert.Equal("ColCommitTS", columns[index]);
Assert.Equal(Value.KindOneofCase.StringValue, values[index].KindCase);
Assert.Equal("spanner.commit_timestamp()", values[index++].StringValue);
Assert.Equal("ColInt64", columns[index]);
Assert.Equal(Value.KindOneofCase.StringValue, values[index].KindCase);
Assert.Equal("1", values[index++].StringValue);
Assert.Equal("ASC", columns[index]);
Assert.Equal(Value.KindOneofCase.NullValue, values[index++].KindCase);
Assert.Equal("ColBool", columns[index]);
Assert.Equal(Value.KindOneofCase.BoolValue, values[index].KindCase);
Assert.True(values[index++].BoolValue);
Assert.Equal("ColBoolArray", columns[index]);
Assert.Equal(Value.KindOneofCase.ListValue, values[index].KindCase);
Assert.Collection(values[index++].ListValue.Values,
v => Assert.True(v.BoolValue),
v => Assert.Equal(Value.KindOneofCase.NullValue, v.KindCase),
v => Assert.False(v.BoolValue)
);
Assert.Equal("ColBytes", columns[index]);
Assert.Equal(Value.KindOneofCase.StringValue, values[index].KindCase);
Assert.Equal(Convert.ToBase64String(new byte[]{1,2,3}), values[index++].StringValue);
Assert.Equal("ColBytesArray", columns[index]);
Assert.Equal(Value.KindOneofCase.ListValue, values[index].KindCase);
Assert.Collection(values[index++].ListValue.Values,
v => Assert.Equal(Convert.ToBase64String(new byte[]{1,2,3}), v.StringValue),
v => Assert.Equal(Value.KindOneofCase.NullValue, v.KindCase),
v => Assert.Equal(Convert.ToBase64String(new byte[]{3,2,1}), v.StringValue)
);
Assert.Equal("ColBytesMax", columns[index]);
Assert.Equal(Value.KindOneofCase.StringValue, values[index].KindCase);
Assert.Equal("", values[index++].StringValue);
Assert.Equal("ColBytesMaxArray", columns[index]);
Assert.Equal(Value.KindOneofCase.ListValue, values[index].KindCase);
Assert.Empty(values[index++].ListValue.Values);
Assert.Equal("ColDate", columns[index]);
Assert.Equal(Value.KindOneofCase.StringValue, values[index].KindCase);
Assert.Equal("2000-01-01", values[index++].StringValue);
Assert.Equal("ColDateArray", columns[index]);
Assert.Equal(Value.KindOneofCase.ListValue, values[index].KindCase);
Assert.Collection(values[index++].ListValue.Values,
v => Assert.Equal("2021-08-26", v.StringValue),
v => Assert.Equal(Value.KindOneofCase.NullValue, v.KindCase),
v => Assert.Equal("2000-01-01", v.StringValue)
);
Assert.Equal("ColFloat64", columns[index]);
Assert.Equal(Value.KindOneofCase.NumberValue, values[index].KindCase);
Assert.Equal(3.14d, values[index++].NumberValue);
Assert.Equal("ColFloat64Array", columns[index]);
Assert.Equal(Value.KindOneofCase.ListValue, values[index].KindCase);
Assert.Collection(values[index++].ListValue.Values,
v => Assert.Equal(3.14d, v.NumberValue),
v => Assert.Equal(Value.KindOneofCase.NullValue, v.KindCase),
v => Assert.Equal(6.626d, v.NumberValue)
);
Assert.Equal(Value.KindOneofCase.ListValue, values[index].KindCase);
Assert.Collection(values[index++].ListValue.Values,
v => Assert.Equal("1", v.StringValue),
v => Assert.Equal(Value.KindOneofCase.NullValue, v.KindCase),
v => Assert.Equal("2", v.StringValue)
);
Assert.Equal("ColJson", columns[index]);
Assert.Equal(Value.KindOneofCase.StringValue, values[index].KindCase);
Assert.Equal("{\"key\": \"value\"}", values[index++].StringValue);
Assert.Equal("ColJsonArray", columns[index]);
Assert.Equal(Value.KindOneofCase.ListValue, values[index].KindCase);
Assert.Collection(values[index++].ListValue.Values,
v => Assert.Equal("{\"key1\": \"value1\"}", v.StringValue),
v => Assert.Equal(Value.KindOneofCase.NullValue, v.KindCase),
v => Assert.Equal("{\"key2\": \"value2\"}", v.StringValue)
);
Assert.Equal("ColNumeric", columns[index]);
Assert.Equal(Value.KindOneofCase.StringValue, values[index].KindCase);
Assert.Equal("6.626", values[index++].StringValue);
Assert.Equal("ColNumericArray", columns[index]);
Assert.Equal(Value.KindOneofCase.ListValue, values[index].KindCase);
Assert.Collection(values[index++].ListValue.Values,
v => Assert.Equal("3.14", v.StringValue),
v => Assert.Equal(Value.KindOneofCase.NullValue, v.KindCase),
v => Assert.Equal("6.626", v.StringValue)
);
Assert.Equal("ColString", columns[index]);
Assert.Equal(Value.KindOneofCase.StringValue, values[index].KindCase);
Assert.Equal("test", values[index++].StringValue);
Assert.Equal("ColStringArray", columns[index]);
Assert.Equal(Value.KindOneofCase.ListValue, values[index].KindCase);
Assert.Collection(values[index++].ListValue.Values,
v => Assert.Equal("test1", v.StringValue),
v => Assert.Equal(Value.KindOneofCase.NullValue, v.KindCase),
v => Assert.Equal("test2", v.StringValue)
);
Assert.Equal("ColStringMax", columns[index]);
Assert.Equal(Value.KindOneofCase.StringValue, values[index].KindCase);
Assert.Equal("", values[index++].StringValue);
Assert.Equal("ColStringMaxArray", columns[index]);
Assert.Equal(Value.KindOneofCase.ListValue, values[index].KindCase);
Assert.Empty(values[index++].ListValue.Values);
Assert.Equal("ColTimestamp", columns[index]);
Assert.Equal(Value.KindOneofCase.StringValue, values[index].KindCase);
Assert.Equal("2000-01-01T00:00:00Z", values[index++].StringValue);
Assert.Equal("ColTimestampArray", columns[index]);
Assert.Equal(Value.KindOneofCase.ListValue, values[index].KindCase);
Assert.Collection(values[index++].ListValue.Values,
v => Assert.Equal("2000-01-01T00:00:00.001Z", v.StringValue),
v => Assert.Equal(Value.KindOneofCase.NullValue, v.KindCase),
v => Assert.Equal("2000-01-01T00:00:00.002Z", v.StringValue)
);
}
);
}
private string AddFindSingerResult(string sql)
{
_fixture.SpannerMock.AddOrUpdateStatementResult(sql, StatementResult.CreateResultSet(
new List<Tuple<V1.TypeCode, string>>
{
Tuple.Create(V1.TypeCode.Int64, "SingerId"),
Tuple.Create(V1.TypeCode.Date, "BirthDate"),
Tuple.Create(V1.TypeCode.String, "FirstName"),
Tuple.Create(V1.TypeCode.String, "FullName"),
Tuple.Create(V1.TypeCode.String, "LastName"),
Tuple.Create(V1.TypeCode.Bytes, "Picture"),
},
new List<object[]>
{
new object[] { 1L, null, "Alice", "Alice Morrison", "Morrison", null },
}
));
return sql;
}
private string AddSelectSingerFullNameResult(string fullName, int paramIndex)
{
var selectFullNameSql = $"{Environment.NewLine}SELECT `FullName`{Environment.NewLine}FROM `Singers`" +
$"{Environment.NewLine}WHERE TRUE AND `SingerId` = @p{paramIndex}";
_fixture.SpannerMock.AddOrUpdateStatementResult(selectFullNameSql, StatementResult.CreateResultSet(
new List<Tuple<V1.TypeCode, string>>
{
Tuple.Create(V1.TypeCode.Int64, "SingerId"),
Tuple.Create(V1.TypeCode.String, "FullName"),
},
new List<object[]>
{
new object[] { 1L, fullName },
}
));
return selectFullNameSql;
}
}
}
#pragma warning restore EF1001
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Axiom.MathLib;
using Axiom.Core;
using Axiom.Input;
using Multiverse.Gui;
/// This file is for the gui widgets that are in the 3d world.
/// Some examples are the bubble text and the names of characters.
namespace Multiverse.BetaWorld.Gui
{
#if NOT_ME
public class ZOrderedStatic : Window
{
protected float zValue;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="name">Name of this widget.</param>
public ZOrderedStatic(string name)
: base(name)
{
}
protected override void DrawSelf(float z)
{
base.DrawSelf(zValue);
}
public float ZValue
{
get
{
return zValue;
}
set
{
zValue = value;
}
}
}
public class ZOrderedStaticText : ZOrderedStatic
{
HorizontalTextFormat horzFormatting;
ColorRect textColors = new ColorRect();
protected Font font;
protected string text;
public ZOrderedStaticText(string name)
: base(name)
{
}
protected void UpdateText() {
}
public string Text {
get {
return text;
}
set {
text = value;
UpdateText();
}
}
/// <summary>
/// Perform the actual rendering for this Window.
/// </summary>
/// <param name="z">float value specifying the base Z co-ordinate that should be used when rendering.</param>
protected override void DrawSelf(float z)
{
// Don't do anything if we don't have any text
if (this.Text == string.Empty)
return;
// render what base class needs to render first
base.DrawSelf(z);
// render text
Font textFont = this.Font;
Size max = this.MaximumSize;
Rect maxRect = new Rect(0, max.width, 0, max.height);
string message = this.Text;
// get total pixel height of the text based on its format
float textHeight =
textFont.GetFormattedLineCount(message, maxRect, horzFormatting) * textFont.LineSpacing;
float textWidth =
textFont.GetFormattedTextExtent(message, maxRect, horzFormatting);
float height = Math.Min(textHeight, max.height);
float width = textWidth;
Rect absRect = this.UnclippedPixelRect;
int newTop = (int)(absRect.Bottom - height);
int newLeft = (int)(absRect.Left + (absRect.Width - width) / 2);
int newBottom = newTop + (int)height;
int newRight = newLeft + (int)width;
Rect newAbsRect = new Rect(newLeft, newRight, newTop, newBottom);
SetAreaRect(newAbsRect);
Rect clipper = newAbsRect.GetIntersection(this.PixelRect);
textColors.SetAlpha(EffectiveAlpha);
// The z value for this will be slightly less, so that the text
// is in front of the background
textFont.DrawText(
message,
this.UnclippedInnerRect,
this.ZValue - Renderer.GuiZLayerStep,
clipper,
horzFormatting,
textColors);
}
public void SetTextColor(ColorEx color)
{
textColors = new ColorRect(color);
}
public HorizontalTextFormat HorizontalFormat
{
get
{
return horzFormatting;
}
set
{
horzFormatting = value;
}
}
public Font Font {
get { return font; }
}
}
#endif
/// <summary>
/// Summary description for WLNameText.
/// </summary>
public class WLNameText : Window
{
LayeredStaticText textWidget;
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
/// <param name="name">Name of this widget.</param>
public WLNameText(string name)
: base(name)
{
textWidget = new LayeredStaticText(name, this);
// textWidget.Visible = true;
AddChild(textWidget);
}
#endregion Constructor
/// <summary>
/// Init this widget.
/// </summary>
public override void Initialize()
{
base.Initialize();
colors = new ColorRect(ColorEx.Red);
textWidget.SetTextColor(ColorEx.Cyan);
textWidget.HorizontalFormat = HorizontalTextFormat.Centered;
}
public void SetText(string str) {
textWidget.SetText(str);
float height = textWidget.GetTextHeight(false);
float width = textWidget.GetTextWidth();
Rect newArea = new Rect(0, width, 0, height);
textWidget.SetAreaRect(newArea);
textWidget.SetVScrollPosition(0);
this.SetAreaRect(newArea);
}
public void SetFont(Font font) {
textWidget.Font = font;
textWidget.UpdateText();
float height = textWidget.GetTextHeight(false);
float width = textWidget.GetTextWidth();
Rect newArea = new Rect(0, width, 0, height);
textWidget.SetAreaRect(newArea);
textWidget.SetVScrollPosition(0);
this.SetAreaRect(newArea);
}
}
public class FrameWindow : Window
{
public FrameWindow()
{
}
public FrameWindow(string name)
: base(name)
{
}
protected TextureInfo top;
protected TextureInfo bottom;
protected TextureInfo left;
protected TextureInfo right;
protected TextureInfo topLeft;
protected TextureInfo topRight;
protected TextureInfo bottomLeft;
protected TextureInfo bottomRight;
protected TextureInfo background;
protected ColorRect backgroundColors;
public ColorRect BackgroundColors
{
get
{
return backgroundColors;
}
set
{
backgroundColors = value;
}
}
}
/// <summary>
/// Variant of the RenderableFrame that also has a bottom center image
/// (for the bubble tail).
/// </summary>
public class ComplexFrameWindow : FrameWindow {
protected TextureInfo bottomCenter;
public ComplexFrameWindow(string name)
: base(name) {
}
protected override void DrawSelf(float z) {
float maxOffset = (int)FrameStrata.Maximum * LayeredStaticText.GuiZFrameStrataStep;
Point pos = this.DerivedPosition;
DrawSelf(new Vector3(pos.x, pos.y, z + maxOffset), null);
}
/// <summary>
///
/// </summary>
/// <param name="position"></param>
/// <param name="clipRect"></param>
protected override void DrawSelf(Vector3 position, Rect clipRect) {
Vector3 finalPos = position;
float origWidth = area.Width;
float origHeight = area.Height;
Size finalSize = new Size();
// Pass our alpha settings to the textures we draw
colors.SetAlpha(this.EffectiveAlpha);
// calculate 'adjustments' required to accommodate corner pieces.
float coordAdj = 0, sizeAdj = 0;
// draw top-edge, if required
if (top != null) {
// calculate adjustments required if top-left corner will be rendered.
if (topLeft != null) {
sizeAdj = topLeft.Width;
coordAdj = topLeft.Width;
}
else {
coordAdj = 0;
sizeAdj = 0;
}
// calculate adjustments required if top-right corner will be rendered.
if (topRight != null) {
sizeAdj += topRight.Width;
}
finalSize.width = origWidth - sizeAdj;
finalSize.height = top.Height;
finalPos.x = position.x + coordAdj;
top.Draw(finalPos, finalSize, clipRect, colors);
}
// draw bottom-edge, if required
if (bottom != null) {
// calculate adjustments required if bottom-left corner will be rendered.
if (bottomLeft != null) {
sizeAdj = bottomLeft.Width;
coordAdj = bottomLeft.Width;
}
else {
coordAdj = 0;
sizeAdj = 0;
}
// calculate adjustments required if bottom-right corner will be rendered.
if (bottomRight != null) {
sizeAdj += bottomRight.Width;
}
if (bottomCenter != null) {
float leftPortion = (float)Math.Floor((origWidth - sizeAdj) / 2);
float rightPortion = origWidth - sizeAdj - bottomCenter.Width - leftPortion;
// Draw the left portion of the bottom edge
finalSize.width = leftPortion;
finalSize.height = bottom.Height;
finalPos.x = position.x + coordAdj;
finalPos.y = position.y + origHeight - finalSize.height;
bottom.Draw(finalPos, finalSize, clipRect, colors);
finalSize.width = bottomCenter.Width;
finalSize.height = bottomCenter.Height;
finalPos.x = position.x + coordAdj + leftPortion;
finalPos.y = position.y + origHeight - finalSize.height;
bottomCenter.Draw(finalPos, finalSize, clipRect, colors);
finalSize.width = rightPortion;
finalSize.height = bottom.Height;
finalPos.x = position.x + coordAdj + leftPortion + bottomCenter.Width;
finalPos.y = position.y + origHeight - finalSize.height;
bottom.Draw(finalPos, finalSize, clipRect, colors);
} else {
finalSize.width = origWidth - sizeAdj;
finalSize.height = bottom.Height;
finalPos.x = position.x + coordAdj;
finalPos.y = position.y + origHeight - finalSize.height;
bottom.Draw(finalPos, finalSize, clipRect, colors);
}
}
// reset x co-ordinate to input value
finalPos.x = position.x;
// draw left-edge, if required
if (left != null) {
// calculate adjustments required if top-left corner will be rendered.
if (topLeft != null) {
sizeAdj = topLeft.Height;
coordAdj = topLeft.Height;
}
else {
coordAdj = 0;
sizeAdj = 0;
}
// calculate adjustments required if bottom-left corner will be rendered.
if (bottomLeft != null) {
sizeAdj += bottomLeft.Height;
}
finalSize.height = origHeight - sizeAdj;
finalSize.width = left.Width;
finalPos.y = position.y + coordAdj;
left.Draw(finalPos, finalSize, clipRect, colors);
}
// draw right-edge, if required
if (right != null) {
// calculate adjustments required if top-left corner will be rendered.
if (topRight != null) {
sizeAdj = topRight.Height;
coordAdj = topRight.Height;
}
else {
coordAdj = 0;
sizeAdj = 0;
}
// calculate adjustments required if bottom-right corner will be rendered.
if (bottomRight != null) {
sizeAdj += bottomRight.Height;
}
finalSize.height = origHeight - sizeAdj;
finalSize.width = left.Width;
finalPos.y = position.y + coordAdj;
finalPos.x = position.x + origWidth - finalSize.width;
right.Draw(finalPos, finalSize, clipRect, colors);
}
// draw required corner pieces...
if (topLeft != null) {
topLeft.Draw(position, clipRect, colors);
}
if (topRight != null) {
finalPos.x = position.x + origWidth - topRight.Width;
finalPos.y = position.y;
topRight.Draw(finalPos, clipRect, colors);
}
if (bottomLeft != null) {
finalPos.x = position.x;
finalPos.y = position.y + origHeight - bottomLeft.Height;
bottomLeft.Draw(finalPos, clipRect, colors);
}
if (bottomRight != null) {
finalPos.x = position.x + origWidth - bottomRight.Width;
finalPos.y = position.y + origHeight - bottomRight.Height;
bottomRight.Draw(finalPos, clipRect, colors);
}
if (background != null) {
float sizeAdjX = 0;
float coordAdjX = 0;
float sizeAdjY = 0;
float coordAdjY = 0;
if (top != null) {
sizeAdjY += top.Height;
coordAdjY += top.Height;
}
if (bottom != null) {
sizeAdjY += bottom.Height;
}
if (left != null) {
sizeAdjX += left.Width;
coordAdjX += left.Width;
}
if (right != null) {
sizeAdjX += right.Width;
}
finalSize.height = origHeight - sizeAdjY;
finalSize.width = origWidth - sizeAdjX;
finalPos.y = position.y + coordAdjY;
finalPos.x = position.x + coordAdjX;
background.Draw(finalPos, finalSize, clipRect, colors);
}
}
public TextureInfo BottomCenter {
get {
return bottomCenter;
}
set {
bottomCenter = value;
}
}
}
/// <summary>
/// Summary description for WLBubbleText.
/// </summary>
public class WLBubbleText : ComplexFrameWindow
{
protected const string ImagesetName = "WindowsLook";
protected const string BackgroundImageName = "Background";
protected const string TopLeftBubbleImageName = "TopLeftBubble";
protected const string TopRightBubbleImageName = "TopRightBubble";
protected const string BottomLeftBubbleImageName = "BottomLeftBubble";
protected const string BottomRightBubbleImageName = "BottomRightBubble";
protected const string LeftBubbleImageName = "LeftBubble";
protected const string RightBubbleImageName = "RightBubble";
protected const string TopBubbleImageName = "TopBubble";
protected const string BottomBubbleImageName = "BottomBubble";
protected const string TailBubbleImageName = "TailBubble";
LayeredStaticText textWidget;
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
/// <param name="name">Name of this widget.</param>
public WLBubbleText(string name)
: base(name)
{
textWidget = new LayeredStaticText(name, this);
textWidget.Visible = true;
AddChild(textWidget);
}
#endregion Constructor
/// <summary>
/// Init this widget.
/// </summary>
public override void Initialize()
{
base.Initialize();
colors = new ColorRect(ColorEx.WhiteSmoke);
TextureAtlas atlas = AtlasManager.Instance.GetTextureAtlas(ImagesetName);
topLeft = atlas.GetTextureInfo(TopLeftBubbleImageName);
topRight = atlas.GetTextureInfo(TopRightBubbleImageName);
bottomLeft = atlas.GetTextureInfo(BottomLeftBubbleImageName);
bottomRight = atlas.GetTextureInfo(BottomRightBubbleImageName);
left = atlas.GetTextureInfo(LeftBubbleImageName);
right = atlas.GetTextureInfo(RightBubbleImageName);
top = atlas.GetTextureInfo(TopBubbleImageName);
bottom = atlas.GetTextureInfo(BottomBubbleImageName);
background = atlas.GetTextureInfo(BackgroundImageName);
bottomCenter = atlas.GetTextureInfo(TailBubbleImageName);
textWidget.HorizontalFormat = HorizontalTextFormat.WordWrapCentered;
textWidget.VerticalFormat = VerticalTextFormat.Bottom;
textWidget.NormalTextStyle = new TextStyle();
textWidget.NormalTextStyle.textColor = ColorEx.Black;
}
public void SetText(string str) {
// Maximum dimensions
Rect newArea = new Rect(0, 200, 0, 200);
// Initial size to see how we wrap
textWidget.SetAreaRect(newArea);
textWidget.SetText(str);
float textHeight = textWidget.GetTextHeight(false);
float textWidth = textWidget.GetTextWidth();
// smallest size that will still fit all the text
textWidget.SetAreaRect(new Rect(left.Width, left.Width + textWidth, top.Height, top.Height + textHeight));
newArea.Height = textHeight + top.Height + Math.Max(bottom.Height, bottomCenter.Height);
newArea.Width = textWidth + left.Width + right.Width;
// textWidget.SetVScrollPosition(0);
this.SetAreaRect(newArea);
}
public void SetFont(Font font) {
textWidget.Font = font;
// Maximum dimensions
Rect newArea = new Rect(0, 200, 0, 200);
textWidget.SetAreaRect(newArea);
textWidget.UpdateText();
// textWidget.SetVScrollPosition(0);
float textHeight = textWidget.GetTextHeight(false);
float textWidth = textWidget.GetTextWidth();
// smallest size that will still fit all the text
textWidget.SetAreaRect(new Rect(left.Width, left.Width + textWidth, top.Height, top.Height + textHeight));
newArea.Height = textHeight + top.Height + Math.Max(bottom.Height, bottomCenter.Height);
newArea.Width = textWidth + left.Width + right.Width;
this.SetAreaRect(newArea);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System.Xml;
namespace XmlDocumentTests.XmlNodeTests
{
public static class PreviousSiblingTests
{
[Fact]
public static void OnElementNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><elem1/><elem2/><elem3/></root>");
var elem1 = xmlDocument.DocumentElement.ChildNodes[0];
var elem2 = xmlDocument.DocumentElement.ChildNodes[1];
var elem3 = xmlDocument.DocumentElement.ChildNodes[2];
Assert.Null(elem1.PreviousSibling);
Assert.Same(elem1, elem2.PreviousSibling);
Assert.Same(elem2, elem3.PreviousSibling);
}
[Fact]
public static void OnTextNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/>some text</root>");
Assert.Equal(XmlNodeType.Text, xmlDocument.DocumentElement.ChildNodes[1].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[1].PreviousSibling, xmlDocument.DocumentElement.ChildNodes[0]);
}
[Fact]
public static void OnTextNodeSplit()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text</root>");
var textNode = (XmlText)xmlDocument.DocumentElement.FirstChild;
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Null(textNode.PreviousSibling);
var split = textNode.SplitText(4);
Assert.Equal(2, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(textNode, split.PreviousSibling);
Assert.Null(textNode.PreviousSibling);
}
[Fact]
public static void OnCommentNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><!--some text--></root>");
Assert.Equal(XmlNodeType.Comment, xmlDocument.DocumentElement.ChildNodes[1].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0], xmlDocument.DocumentElement.ChildNodes[1].PreviousSibling);
}
[Fact]
public static void SiblingOfLastChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text<child1/><child2/></root>");
Assert.Same(xmlDocument.DocumentElement.ChildNodes[1], xmlDocument.DocumentElement.LastChild.PreviousSibling);
}
[Fact]
public static void OnCDataNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><![CDATA[ <opentag> without an </endtag> and & <! are all ok here ]]></root>");
Assert.Equal(XmlNodeType.CDATA, xmlDocument.DocumentElement.ChildNodes[1].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0], xmlDocument.DocumentElement.ChildNodes[1].PreviousSibling);
}
[Fact]
public static void OnDocumentFragment()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/>some text<child2/><child3/></root>");
var documentFragment = xmlDocument.CreateDocumentFragment();
documentFragment.AppendChild(xmlDocument.DocumentElement);
Assert.Null(documentFragment.PreviousSibling);
}
[Fact]
public static void OnDocumentElement()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<?PI pi info?><root/>");
var piInfo = xmlDocument.ChildNodes[0];
Assert.Equal(XmlNodeType.ProcessingInstruction, piInfo.NodeType);
Assert.Equal(piInfo, xmlDocument.DocumentElement.PreviousSibling);
}
[Fact]
public static void OnAttributeNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr1='test' attr2='test2' />");
var attr1 = xmlDocument.DocumentElement.Attributes[0];
var attr2 = xmlDocument.DocumentElement.Attributes[1];
Assert.Equal("attr1", attr1.Name);
Assert.Equal("attr2", attr2.Name);
Assert.Null(attr1.PreviousSibling);
Assert.Null(attr2.PreviousSibling);
}
[Fact]
public static void OnAttributeNodeWithChildren()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr1='test' attr2='test2'><child1/><child2/><child3/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
var child3 = xmlDocument.DocumentElement.ChildNodes[2];
Assert.Null(child1.PreviousSibling);
Assert.Same(child1, child2.PreviousSibling);
Assert.Same(child2, child3.PreviousSibling);
}
[Fact]
public static void ElementOneChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child/></root>");
Assert.Null(xmlDocument.DocumentElement.ChildNodes[0].PreviousSibling);
}
[Fact]
public static void OnAllSiblings()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3 attr='1'/>Some Text<child4/><!-- comment --><?PI processing info?></root>");
var count = xmlDocument.DocumentElement.ChildNodes.Count;
var nextNode = xmlDocument.DocumentElement.ChildNodes[count - 1];
for (var idx = count - 2; idx >= 0; idx--)
{
var currentNode = xmlDocument.DocumentElement.ChildNodes[idx];
Assert.Equal(currentNode, nextNode.PreviousSibling);
nextNode = currentNode;
}
Assert.Null(nextNode.PreviousSibling);
}
[Fact]
public static void RemoveChildCheckSibling()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
Assert.Equal("child1", child1.Name);
Assert.Equal("child2", child2.Name);
Assert.Equal(child1, child2.PreviousSibling);
Assert.Null(child1.PreviousSibling);
xmlDocument.DocumentElement.RemoveChild(child2);
Assert.Null(child2.PreviousSibling);
Assert.Null(child1.PreviousSibling);
}
[Fact]
public static void ReplaceChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
var child3 = xmlDocument.DocumentElement.ChildNodes[2];
Assert.Null(child1.PreviousSibling);
Assert.Same(child1, child2.PreviousSibling);
Assert.Same(child2, child3.PreviousSibling);
var newNode = xmlDocument.CreateElement("child4");
xmlDocument.DocumentElement.ReplaceChild(newNode, child2);
Assert.Null(child1.PreviousSibling);
Assert.Same(child1, newNode.PreviousSibling);
Assert.Same(newNode, child3.PreviousSibling);
Assert.Null(child2.PreviousSibling);
}
[Fact]
public static void InsertChildAfter()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var newNode = xmlDocument.CreateElement("child2");
Assert.Null(child1.PreviousSibling);
xmlDocument.DocumentElement.InsertAfter(newNode, child1);
Assert.Null(child1.PreviousSibling);
Assert.Same(child1, newNode.PreviousSibling);
}
[Fact]
public static void InsertChildBefore()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var newNode = xmlDocument.CreateElement("child2");
Assert.Null(child1.PreviousSibling);
xmlDocument.DocumentElement.InsertBefore(newNode, child1);
Assert.Same(newNode, child1.PreviousSibling);
Assert.Null(newNode.PreviousSibling);
}
[Fact]
public static void AppendChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var newNode = xmlDocument.CreateElement("child2");
Assert.Null(child1.PreviousSibling);
xmlDocument.DocumentElement.AppendChild(newNode);
Assert.Same(child1, newNode.PreviousSibling);
Assert.Null(child1.PreviousSibling);
}
[Fact]
public static void NewlyCreatedElement()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateElement("element");
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void NewlyCreatedAttribute()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateAttribute("attribute");
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void NewlyCreatedTextNode()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateTextNode("textnode");
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void NewlyCreatedCDataNode()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateCDataSection("cdata section");
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void NewlyCreatedProcessingInstruction()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateProcessingInstruction("PI", "data");
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void NewlyCreatedComment()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateComment("comment");
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void NewlyCreatedDocumentFragment()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateDocumentFragment();
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void FirstChildNextSibling()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
Assert.Null(xmlDocument.DocumentElement.FirstChild.PreviousSibling);
}
}
}
| |
// 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.Diagnostics;
namespace System.Security.Cryptography
{
/// <summary>
/// Utility class to strongly type algorithms used with CNG. Since all CNG APIs which require an
/// algorithm name take the name as a string, we use this string wrapper class to specifically mark
/// which parameters are expected to be algorithms. We also provide a list of well known algorithm
/// names, which helps Intellisense users find a set of good algorithm names to use.
/// </summary>
public sealed class CngAlgorithm : IEquatable<CngAlgorithm>
{
public CngAlgorithm(string algorithm)
{
if (algorithm == null)
throw new ArgumentNullException(nameof(algorithm));
if (algorithm.Length == 0)
throw new ArgumentException(SR.Format(SR.Cryptography_InvalidAlgorithmName, algorithm), nameof(algorithm));
_algorithm = algorithm;
}
/// <summary>
/// Name of the algorithm
/// </summary>
public string Algorithm
{
get
{
return _algorithm;
}
}
public static bool operator ==(CngAlgorithm left, CngAlgorithm right)
{
if (object.ReferenceEquals(left, null))
{
return object.ReferenceEquals(right, null);
}
return left.Equals(right);
}
public static bool operator !=(CngAlgorithm left, CngAlgorithm right)
{
if (object.ReferenceEquals(left, null))
{
return !object.ReferenceEquals(right, null);
}
return !left.Equals(right);
}
public override bool Equals(object obj)
{
Debug.Assert(_algorithm != null);
return Equals(obj as CngAlgorithm);
}
public bool Equals(CngAlgorithm other)
{
if (object.ReferenceEquals(other, null))
{
return false;
}
return _algorithm.Equals(other.Algorithm);
}
public override int GetHashCode()
{
Debug.Assert(_algorithm != null);
return _algorithm.GetHashCode();
}
public override string ToString()
{
Debug.Assert(_algorithm != null);
return _algorithm;
}
//
// Well known algorithms
//
public static CngAlgorithm Rsa
{
get
{
return s_rsa ?? (s_rsa = new CngAlgorithm("RSA")); // BCRYPT_RSA_ALGORITHM
}
}
public static CngAlgorithm ECDiffieHellmanP256
{
get
{
return s_ecdhp256 ?? (s_ecdhp256 = new CngAlgorithm("ECDH_P256")); // BCRYPT_ECDH_P256_ALGORITHM
}
}
public static CngAlgorithm ECDiffieHellmanP384
{
get
{
return s_ecdhp384 ?? (s_ecdhp384 = new CngAlgorithm("ECDH_P384")); // BCRYPT_ECDH_P384_ALGORITHM
}
}
public static CngAlgorithm ECDiffieHellmanP521
{
get
{
return s_ecdhp521 ?? (s_ecdhp521 = new CngAlgorithm("ECDH_P521")); // BCRYPT_ECDH_P521_ALGORITHM
}
}
public static CngAlgorithm ECDsaP256
{
get
{
return s_ecdsap256 ?? (s_ecdsap256 = new CngAlgorithm("ECDSA_P256")); // BCRYPT_ECDSA_P256_ALGORITHM
}
}
public static CngAlgorithm ECDsaP384
{
get
{
return s_ecdsap384 ?? (s_ecdsap384 = new CngAlgorithm("ECDSA_P384")); // BCRYPT_ECDSA_P384_ALGORITHM
}
}
public static CngAlgorithm ECDsaP521
{
get
{
return s_ecdsap521 ?? (s_ecdsap521 = new CngAlgorithm("ECDSA_P521")); // BCRYPT_ECDSA_P521_ALGORITHM
}
}
public static CngAlgorithm MD5
{
get
{
return s_md5 ?? (s_md5 = new CngAlgorithm("MD5")); // BCRYPT_MD5_ALGORITHM
}
}
public static CngAlgorithm Sha1
{
get
{
return s_sha1 ?? (s_sha1 = new CngAlgorithm("SHA1")); // BCRYPT_SHA1_ALGORITHM
}
}
public static CngAlgorithm Sha256
{
get
{
return s_sha256 ?? (s_sha256 = new CngAlgorithm("SHA256")); // BCRYPT_SHA256_ALGORITHM
}
}
public static CngAlgorithm Sha384
{
get
{
return s_sha384 ?? (s_sha384 = new CngAlgorithm("SHA384")); // BCRYPT_SHA384_ALGORITHM
}
}
public static CngAlgorithm Sha512
{
get
{
return s_sha512 ?? (s_sha512 = new CngAlgorithm("SHA512")); // BCRYPT_SHA512_ALGORITHM
}
}
private static CngAlgorithm s_ecdhp256;
private static CngAlgorithm s_ecdhp384;
private static CngAlgorithm s_ecdhp521;
private static CngAlgorithm s_ecdsap256;
private static CngAlgorithm s_ecdsap384;
private static CngAlgorithm s_ecdsap521;
private static CngAlgorithm s_md5;
private static CngAlgorithm s_sha1;
private static CngAlgorithm s_sha256;
private static CngAlgorithm s_sha384;
private static CngAlgorithm s_sha512;
private static CngAlgorithm s_rsa;
private readonly string _algorithm;
}
}
| |
/// Copyright (C) 2012-2014 Soomla 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 UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;
using Soomla;
using Soomla.Profile;
using Soomla.Example;
/// <summary>
/// This class contains functions that initialize the game and that display the different screens of the game.
/// </summary>
public class ExampleWindow : MonoBehaviour {
private static ExampleWindow instance = null;
public string fontSuffix = "";
private static bool isVisible = false;
private bool isInit = false;
private Provider targetProvider = Provider.FACEBOOK;
private Reward exampleReward = new BadgeReward("example_reward", "Example Social Reward");
/// <summary>
/// Initializes the game state before the game starts.
/// </summary>
void Awake(){
if(instance == null){ //making sure we only initialize one instance.
instance = this;
GameObject.DontDestroyOnLoad(this.gameObject);
} else { //Destroying unused instances.
GameObject.Destroy(this);
}
//FONT
//using max to be certain we have the longest side of the screen, even if we are in portrait.
if(Mathf.Max(Screen.width, Screen.height) > 640){
fontSuffix = "_2X"; //a nice suffix to show the fonts are twice as big as the original
}
}
private Texture2D tBackground;
private Texture2D tShed;
private Texture2D tBGBar;
private Texture2D tShareDisable;
private Texture2D tShare;
private Texture2D tSharePress;
private Texture2D tShareStoryDisable;
private Texture2D tShareStory;
private Texture2D tShareStoryPress;
private Texture2D tUploadDisable;
private Texture2D tUpload;
private Texture2D tUploadPress;
private Texture2D tConnect;
private Texture2D tConnectPress;
private Texture2D tLogout;
private Texture2D tLogoutPress;
private Font fgoodDog;
// private bool bScreenshot = false;
/// <summary>
/// Starts this instance.
/// Use this for initialization.
/// </summary>
void Start () {
fgoodDog = (Font)Resources.Load("Fonts/GoodDog" + fontSuffix);
tBackground = (Texture2D)Resources.Load("Profile/BG");
tShed = (Texture2D)Resources.Load("Profile/Headline");
tBGBar = (Texture2D)Resources.Load("Profile/BG-Bar");
tShareDisable = (Texture2D)Resources.Load("Profile/BTN-Share-Disable");
tShare = (Texture2D)Resources.Load("Profile/BTN-Share-Normal");
tSharePress = (Texture2D)Resources.Load("Profile/BTN-Share-Press");
tShareStoryDisable = (Texture2D)Resources.Load("Profile/BTN-ShareStory-Disable");
tShareStory = (Texture2D)Resources.Load("Profile/BTN-ShareStory-Normal");
tShareStoryPress = (Texture2D)Resources.Load("Profile/BTN-ShareStory-Press");
tUploadDisable = (Texture2D)Resources.Load("Profile/BTN-Upload-Disable");
tUpload = (Texture2D)Resources.Load("Profile/BTN-Upload-Normal");
tUploadPress = (Texture2D)Resources.Load("Profile/BTN-Upload-Press");
tConnect = (Texture2D)Resources.Load("Profile/BTN-Connect");
tConnectPress = (Texture2D)Resources.Load("Profile/BTN-Connect-Press");
tLogout = (Texture2D)Resources.Load("Profile/BTN-LogOut");
tLogoutPress = (Texture2D)Resources.Load("Profile/BTN-LogOut-Press");
// examples of catching fired events
ProfileEvents.OnSoomlaProfileInitialized += () => {
Soomla.SoomlaUtils.LogDebug("ExampleWindow", "SoomlaProfile Initialized !");
isInit = true;
};
ProfileEvents.OnUserRatingEvent += () => {
Soomla.SoomlaUtils.LogDebug("ExampleWindow", "User opened rating page");
};
ProfileEvents.OnLoginFinished += (UserProfile UserProfile, bool autoLogin, string payload) => {
Soomla.SoomlaUtils.LogDebug("ExampleWindow", "login finished for: " + UserProfile.toJSONObject().print());
SoomlaProfile.GetContacts(targetProvider);
};
ProfileEvents.OnGetContactsFinished += (Provider provider, SocialPageData<UserProfile> contactsData, string payload) => {
Soomla.SoomlaUtils.LogDebug("ExampleWindow", "get contacts for: " + contactsData.PageData.Count + " page: " + contactsData.PageNumber + " More? " + contactsData.HasMore);
foreach (var profile in contactsData.PageData) {
Soomla.SoomlaUtils.LogDebug("ExampleWindow", "Contact: " + profile.toJSONObject().print());
}
if (contactsData.HasMore) {
SoomlaProfile.GetContacts(targetProvider);
}
};
SoomlaProfile.Initialize();
// SoomlaProfile.OpenAppRatingPage();
#if UNITY_IPHONE
Handheld.SetActivityIndicatorStyle(iOSActivityIndicatorStyle.Gray);
#elif UNITY_ANDROID
Handheld.SetActivityIndicatorStyle(AndroidActivityIndicatorStyle.Small);
#endif
}
/// <summary>
/// Sets the window to open, and sets the GUI state to welcome.
/// </summary>
public static void OpenWindow(){
isVisible = true;
}
/// <summary>
/// Sets the window to closed.
/// </summary>
public static void CloseWindow(){
isVisible = false;
}
/// <summary>
/// Implements the game behavior of MuffinRush.
/// Overrides the superclass function in order to provide functionality for our game.
/// </summary>
void Update () {
if (Application.platform == RuntimePlatform.Android) {
if (Input.GetKeyUp(KeyCode.Escape)) {
//quit application on back button
Application.Quit();
return;
}
}
}
/// <summary>
/// Calls the relevant function to display the correct screen of the game.
/// </summary>
void OnGUI(){
if(!isVisible){
return;
}
GUI.skin.horizontalScrollbar = GUIStyle.none;
GUI.skin.verticalScrollbar = GUIStyle.none;
welcomeScreen();
}
/// <summary>
/// Displays the welcome screen of the game.
/// </summary>
void welcomeScreen()
{
Color backupColor = GUI.color;
float vertGap = 80f;
//drawing background, just using a white pixel here
GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),tBackground);
GUI.DrawTexture(new Rect(0,0,Screen.width,timesH(240f)), tShed, ScaleMode.StretchToFill, true);
float rowsTop = 300.0f;
float rowsHeight = 120.0f;
GUI.DrawTexture(new Rect(timesW(65.0f),timesH(rowsTop+10f),timesW(516.0f),timesH(102.0f)), tBGBar, ScaleMode.StretchToFill, true);
if (SoomlaProfile.IsLoggedIn(targetProvider)) {
GUI.skin.button.normal.background = tShare;
GUI.skin.button.hover.background = tShare;
GUI.skin.button.active.background = tSharePress;
if(GUI.Button(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), "")){
SoomlaProfile.UpdateStatus(targetProvider, "I LOVE SOOMLA ! http://www.soom.la", null, exampleReward);
}
} else {
GUI.DrawTexture(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), tShareDisable,
ScaleMode.StretchToFill, true);
}
GUI.color = Color.black;
GUI.skin.label.font = fgoodDog;
GUI.skin.label.fontSize = 30;
GUI.skin.label.alignment = TextAnchor.MiddleCenter;
GUI.Label(new Rect(timesW(270.0f),timesH(rowsTop),timesW(516.0f-212.0f),timesH(120.0f)),"I Love SOOMLA!");
GUI.color = backupColor;
rowsTop += vertGap + rowsHeight;
GUI.DrawTexture(new Rect(timesW(65.0f),timesH(rowsTop+10f),timesW(516.0f),timesH(102.0f)), tBGBar, ScaleMode.StretchToFill, true);
if (SoomlaProfile.IsLoggedIn(targetProvider)) {
GUI.skin.button.normal.background = tShareStory;
GUI.skin.button.hover.background = tShareStory;
GUI.skin.button.active.background = tShareStoryPress;
if(GUI.Button(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), "")){
SoomlaProfile.UpdateStory(targetProvider,
"The story of SOOMBOT (Profile Test App)",
"The story of SOOMBOT (Profile Test App)",
"SOOMBOT Story",
"DESCRIPTION",
"http://about.soom.la/soombots",
"http://about.soom.la/wp-content/uploads/2014/05/330x268-spockbot.png",
null,
exampleReward);
}
} else {
GUI.DrawTexture(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), tShareStoryDisable,
ScaleMode.StretchToFill, true);
}
GUI.color = Color.black;
GUI.skin.label.font = fgoodDog;
GUI.skin.label.fontSize = 25;
GUI.skin.label.alignment = TextAnchor.MiddleCenter;
GUI.Label(new Rect(timesW(270.0f),timesH(rowsTop),timesW(516.0f-212.0f),timesH(120.0f)),"Full story of The SOOMBOT!");
GUI.color = backupColor;
rowsTop += vertGap + rowsHeight;
GUI.DrawTexture(new Rect(timesW(65.0f),timesH(rowsTop+10f),timesW(516.0f),timesH(102.0f)), tBGBar, ScaleMode.StretchToFill, true);
if (SoomlaProfile.IsLoggedIn(targetProvider)) {
GUI.skin.button.normal.background = tUpload;
GUI.skin.button.hover.background = tUpload;
GUI.skin.button.active.background = tUploadPress;
if(GUI.Button(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), "")){
// string fileName = "soom.jpg";
// string path = "";
//
// #if UNITY_IOS
// path = Application.dataPath + "/Raw/" + fileName;
// #elif UNITY_ANDROID
// path = "jar:file://" + Application.dataPath + "!/assets/" + fileName;
// #endif
//
// byte[] bytes = File.ReadAllBytes(path);
// SoomlaProfile.UploadImage(targetProvider, "Awesome Test App of SOOMLA Profile!", fileName, bytes, 10, null, exampleReward);
SoomlaProfile.UploadCurrentScreenShot(this, targetProvider, "Awesome Test App of SOOMLA Profile!", "This a screenshot of the current state of SOOMLA's test app on my computer.", null);
}
} else {
GUI.DrawTexture(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), tUploadDisable,
ScaleMode.StretchToFill, true);
}
GUI.color = Color.black;
GUI.skin.label.font = fgoodDog;
GUI.skin.label.fontSize = 28;
GUI.skin.label.alignment = TextAnchor.MiddleCenter;
GUI.Label(new Rect(timesW(270.0f),timesH(rowsTop),timesW(516.0f-212.0f),timesH(120.0f)),"Current Screenshot");
GUI.color = backupColor;
if (SoomlaProfile.IsLoggedIn(targetProvider)) {
GUI.skin.button.normal.background = tLogout;
GUI.skin.button.hover.background = tLogout;
GUI.skin.button.active.background = tLogoutPress;
if(GUI.Button(new Rect(timesW(20.0f),timesH(950f),timesW(598.0f),timesH(141.0f)), "")){
SoomlaProfile.Logout(targetProvider);
}
} else if (isInit) {
GUI.skin.button.normal.background = tConnect;
GUI.skin.button.hover.background = tConnect;
GUI.skin.button.active.background = tConnectPress;
if(GUI.Button(new Rect(timesW(20.0f),timesH(950f),timesW(598.0f),timesH(141.0f)), "")){
SoomlaProfile.Login(targetProvider, null, exampleReward);
}
}
}
private static string ScreenShotName(int width, int height) {
return string.Format("{0}/screen_{1}x{2}_{3}.png",
Application.persistentDataPath,
width, height,
System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
}
private float timesW(float f) {
return (float)(f/640.0)*Screen.width;
}
private float timesH(float f) {
return (float)(f/1136.0)*Screen.height;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Reflection;
using System.Resources;
using System.Management.Automation;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
internal sealed class DisplayResourceManagerCache
{
internal enum LoadingResult { NoError, AssemblyNotFound, ResourceNotFound, StringNotFound }
internal enum AssemblyBindingStatus { NotFound, FoundInGac, FoundInPath };
internal string GetTextTokenString(TextToken tt)
{
if (tt.resource != null)
{
string resString = this.GetString(tt.resource);
if (resString != null)
return resString;
}
return tt.text;
}
internal void VerifyResource(StringResourceReference resourceReference, out LoadingResult result, out AssemblyBindingStatus bindingStatus)
{
GetStringHelper(resourceReference, out result, out bindingStatus);
}
private string GetString(StringResourceReference resourceReference)
{
LoadingResult result;
AssemblyBindingStatus bindingStatus;
return GetStringHelper(resourceReference, out result, out bindingStatus);
}
private string GetStringHelper(StringResourceReference resourceReference, out LoadingResult result, out AssemblyBindingStatus bindingStatus)
{
result = LoadingResult.AssemblyNotFound;
bindingStatus = AssemblyBindingStatus.NotFound;
AssemblyLoadResult loadResult = null;
// try first to see if we have an assembly reference in the cache
if (_resourceReferenceToAssemblyCache.Contains(resourceReference))
{
loadResult = _resourceReferenceToAssemblyCache[resourceReference] as AssemblyLoadResult;
bindingStatus = loadResult.status;
}
else
{
loadResult = new AssemblyLoadResult();
// we do not have an assembly, we try to load it
bool foundInGac;
loadResult.a = LoadAssemblyFromResourceReference(resourceReference, out foundInGac);
if (loadResult.a == null)
{
loadResult.status = AssemblyBindingStatus.NotFound;
}
else
{
loadResult.status = foundInGac ? AssemblyBindingStatus.FoundInGac : AssemblyBindingStatus.FoundInPath;
}
// add to the cache even if null
_resourceReferenceToAssemblyCache.Add(resourceReference, loadResult);
}
bindingStatus = loadResult.status;
if (loadResult.a == null)
{
// we failed the assembly loading
result = LoadingResult.AssemblyNotFound;
return null;
}
else
{
resourceReference.assemblyLocation = loadResult.a.Location;
};
// load now the resource from the resource manager cache
try
{
string val = ResourceManagerCache.GetResourceString(loadResult.a, resourceReference.baseName, resourceReference.resourceId);
if (val == null)
{
result = LoadingResult.StringNotFound;
return null;
}
else
{
result = LoadingResult.NoError;
return val;
}
}
catch (InvalidOperationException)
{
result = LoadingResult.ResourceNotFound;
}
catch (MissingManifestResourceException)
{
result = LoadingResult.ResourceNotFound;
}
catch (Exception e) // will rethrow
{
Diagnostics.Assert(false, "ResourceManagerCache.GetResourceString unexpected exception " + e.GetType().FullName);
throw;
}
return null;
}
/// <summary>
/// Get a reference to an assembly object by looking up the currently loaded assemblies.
/// </summary>
/// <param name="resourceReference">the string resource reference object containing
/// the name of the assembly to load</param>
/// <param name="foundInGac"> true if assembly was found in the GAC. NOTE: the current
/// implementation always return FALSE</param>
/// <returns></returns>
private Assembly LoadAssemblyFromResourceReference(StringResourceReference resourceReference, out bool foundInGac)
{
// NOTE: we keep the function signature as and the calling code is able do deal
// with dynamically loaded assemblies. If this functionality is implemented, this
// method will have to be changed accordingly
foundInGac = false; // it always be false, since we return already loaded assemblies
return _assemblyNameResolver.ResolveAssemblyName(resourceReference.assemblyName);
}
private sealed class AssemblyLoadResult
{
internal Assembly a;
internal AssemblyBindingStatus status;
}
/// <summary>
/// Helper class to resolve an assembly name to an assembly reference
/// The class caches previous results for faster lookup.
/// </summary>
private class AssemblyNameResolver
{
/// <summary>
/// Resolve the assembly name against the set of loaded assemblies.
/// </summary>
/// <param name="assemblyName"></param>
/// <returns></returns>
internal Assembly ResolveAssemblyName(string assemblyName)
{
if (string.IsNullOrEmpty(assemblyName))
{
return null;
}
// look up the cache first
if (_assemblyReferences.Contains(assemblyName))
{
return (Assembly)_assemblyReferences[assemblyName];
}
// not found, scan the loaded assemblies
// first look for the full name
Assembly retVal = ResolveAssemblyNameInLoadedAssemblies(assemblyName, true) ??
ResolveAssemblyNameInLoadedAssemblies(assemblyName, false);
// NOTE: we cache the result (both for success and failure)
// Porting note: this won't be hit in normal usage, but can be hit with bad build setup
Diagnostics.Assert(retVal != null, "AssemblyName resolution failed, a resource file might be broken");
_assemblyReferences.Add(assemblyName, retVal);
return retVal;
}
private Assembly ResolveAssemblyNameInLoadedAssemblies(string assemblyName, bool fullName)
{
Assembly result = null;
#if false
// This should be re-enabled once the default assembly list contains the
// assemblies referenced by the S.M.A.dll.
// First we need to get the execution context from thread-local storage.
ExecutionContext context = System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS();
if (context != null)
{
context.AssemblyCache.GetAtKey(assemblyName, out result);
}
#else
foreach (Assembly a in ClrFacade.GetAssemblies())
{
AssemblyName aName = null;
try
{
aName = a.GetName();
}
catch (System.Security.SecurityException)
{
continue;
}
string nameToCompare = fullName ? aName.FullName : aName.Name;
if (string.Equals(nameToCompare, assemblyName, StringComparison.Ordinal))
{
return a;
}
}
#endif
return result;
}
private Hashtable _assemblyReferences = new Hashtable(StringComparer.OrdinalIgnoreCase);
}
private AssemblyNameResolver _assemblyNameResolver = new AssemblyNameResolver();
private Hashtable _resourceReferenceToAssemblyCache = new Hashtable();
}
}
| |
#region License
/*
* HttpListenerRequest.cs
*
* This code is derived from HttpListenerRequest.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides the access to a request to the <see cref="HttpListener"/>.
/// </summary>
/// <remarks>
/// The HttpListenerRequest class cannot be inherited.
/// </remarks>
public sealed class HttpListenerRequest
{
#region Private Fields
private static readonly byte[] _100continue;
private string[] _acceptTypes;
private bool _chunked;
private Encoding _contentEncoding;
private long _contentLength;
private bool _contentLengthWasSet;
private HttpListenerContext _context;
private CookieCollection _cookies;
private WebHeaderCollection _headers;
private Guid _identifier;
private Stream _inputStream;
private bool _keepAlive;
private bool _keepAliveWasSet;
private string _method;
private NameValueCollection _queryString;
private Uri _referer;
private string _uri;
private Uri _url;
private string[] _userLanguages;
private Version _version;
private bool _websocketRequest;
private bool _websocketRequestWasSet;
#endregion
#region Static Constructor
static HttpListenerRequest ()
{
_100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
}
#endregion
#region Internal Constructors
internal HttpListenerRequest (HttpListenerContext context)
{
_context = context;
_contentLength = -1;
_headers = new WebHeaderCollection ();
_identifier = Guid.NewGuid ();
}
#endregion
#region Public Properties
/// <summary>
/// Gets the media types which are acceptable for the response.
/// </summary>
/// <value>
/// An array of <see cref="string"/> that contains the media type names in the Accept
/// request-header, or <see langword="null"/> if the request didn't include an Accept header.
/// </value>
public string[] AcceptTypes {
get {
return _acceptTypes;
}
}
/// <summary>
/// Gets an error code that identifies a problem with the client's certificate.
/// </summary>
/// <value>
/// Always returns <c>0</c>.
/// </value>
public int ClientCertificateError {
get {
return 0; // TODO: Always returns 0.
}
}
/// <summary>
/// Gets the encoding for the entity body data included in the request.
/// </summary>
/// <value>
/// A <see cref="Encoding"/> that represents the encoding for the entity body data,
/// or <see cref="Encoding.Default"/> if the request didn't include the information
/// about the encoding.
/// </value>
public Encoding ContentEncoding {
get {
return _contentEncoding ?? (_contentEncoding = Encoding.Default);
}
}
/// <summary>
/// Gets the size of the entity body data included in the request.
/// </summary>
/// <value>
/// A <see cref="long"/> that represents the value of the Content-Length entity-header. The
/// value is a number of bytes in the entity body data. <c>-1</c> if the size isn't known.
/// </value>
public long ContentLength64 {
get {
return _contentLength;
}
}
/// <summary>
/// Gets the media type of the entity body included in the request.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the Content-Type entity-header.
/// </value>
public string ContentType {
get {
return _headers["Content-Type"];
}
}
/// <summary>
/// Gets the cookies included in the request.
/// </summary>
/// <value>
/// A <see cref="CookieCollection"/> that contains the cookies included in the request.
/// </value>
public CookieCollection Cookies {
get {
return _cookies ?? (_cookies = _headers.GetCookies (false));
}
}
/// <summary>
/// Gets a value indicating whether the request has the entity body.
/// </summary>
/// <value>
/// <c>true</c> if the request has the entity body; otherwise, <c>false</c>.
/// </value>
public bool HasEntityBody {
get {
return _contentLength > 0 || _chunked;
}
}
/// <summary>
/// Gets the HTTP headers used in the request.
/// </summary>
/// <value>
/// A <see cref="NameValueCollection"/> that contains the HTTP headers used in the request.
/// </value>
public NameValueCollection Headers {
get {
return _headers;
}
}
/// <summary>
/// Gets the HTTP method used in the request.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the HTTP method used in the request.
/// </value>
public string HttpMethod {
get {
return _method;
}
}
/// <summary>
/// Gets a <see cref="Stream"/> that contains the entity body data included in the request.
/// </summary>
/// <value>
/// A <see cref="Stream"/> that contains the entity body data included in the request.
/// </value>
public Stream InputStream {
get {
return _inputStream ??
(_inputStream = HasEntityBody
? _context.Connection.GetRequestStream (_contentLength, _chunked)
: Stream.Null);
}
}
/// <summary>
/// Gets a value indicating whether the client that sent the request is authenticated.
/// </summary>
/// <value>
/// <c>true</c> if the client is authenticated; otherwise, <c>false</c>.
/// </value>
public bool IsAuthenticated {
get {
return _context.User != null;
}
}
/// <summary>
/// Gets a value indicating whether the request is sent from the local computer.
/// </summary>
/// <value>
/// <c>true</c> if the request is sent from the local computer; otherwise, <c>false</c>.
/// </value>
public bool IsLocal {
get {
return RemoteEndPoint.Address.IsLocal ();
}
}
/// <summary>
/// Gets a value indicating whether the HTTP connection is secured using the SSL protocol.
/// </summary>
/// <value>
/// <c>true</c> if the HTTP connection is secured; otherwise, <c>false</c>.
/// </value>
public bool IsSecureConnection {
get {
return _context.Connection.IsSecure;
}
}
/// <summary>
/// Gets a value indicating whether the request is a WebSocket connection request.
/// </summary>
/// <value>
/// <c>true</c> if the request is a WebSocket connection request; otherwise, <c>false</c>.
/// </value>
public bool IsWebSocketRequest {
get {
if (!_websocketRequestWasSet) {
_websocketRequest = _method == "GET" &&
_version > HttpVersion.Version10 &&
_headers.Contains ("Upgrade", "websocket") &&
_headers.Contains ("Connection", "Upgrade");
_websocketRequestWasSet = true;
}
return _websocketRequest;
}
}
/// <summary>
/// Gets a value indicating whether the client requests a persistent connection.
/// </summary>
/// <value>
/// <c>true</c> if the client requests a persistent connection; otherwise, <c>false</c>.
/// </value>
public bool KeepAlive {
get {
if (!_keepAliveWasSet) {
string keepAlive;
_keepAlive = _version > HttpVersion.Version10 ||
_headers.Contains ("Connection", "keep-alive") ||
((keepAlive = _headers["Keep-Alive"]) != null && keepAlive != "closed");
_keepAliveWasSet = true;
}
return _keepAlive;
}
}
/// <summary>
/// Gets the server endpoint as an IP address and a port number.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the server endpoint.
/// </value>
public System.Net.IPEndPoint LocalEndPoint {
get {
return _context.Connection.LocalEndPoint;
}
}
/// <summary>
/// Gets the HTTP version used in the request.
/// </summary>
/// <value>
/// A <see cref="Version"/> that represents the HTTP version used in the request.
/// </value>
public Version ProtocolVersion {
get {
return _version;
}
}
/// <summary>
/// Gets the query string included in the request.
/// </summary>
/// <value>
/// A <see cref="NameValueCollection"/> that contains the query string parameters.
/// </value>
public NameValueCollection QueryString {
get {
return _queryString ??
(_queryString = HttpUtility.InternalParseQueryString (_url.Query, Encoding.UTF8));
}
}
/// <summary>
/// Gets the raw URL (without the scheme, host, and port) requested by the client.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the raw URL requested by the client.
/// </value>
public string RawUrl {
get {
return _url.PathAndQuery; // TODO: Should decode?
}
}
/// <summary>
/// Gets the client endpoint as an IP address and a port number.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the client endpoint.
/// </value>
public System.Net.IPEndPoint RemoteEndPoint {
get {
return _context.Connection.RemoteEndPoint;
}
}
/// <summary>
/// Gets the request identifier of a incoming HTTP request.
/// </summary>
/// <value>
/// A <see cref="Guid"/> that represents the identifier of a request.
/// </value>
public Guid RequestTraceIdentifier {
get {
return _identifier;
}
}
/// <summary>
/// Gets the URL requested by the client.
/// </summary>
/// <value>
/// A <see cref="Uri"/> that represents the URL requested by the client.
/// </value>
public Uri Url {
get {
return _url;
}
}
/// <summary>
/// Gets the URL of the resource from which the requested URL was obtained.
/// </summary>
/// <value>
/// A <see cref="Uri"/> that represents the value of the Referer request-header,
/// or <see langword="null"/> if the request didn't include an Referer header.
/// </value>
public Uri UrlReferrer {
get {
return _referer;
}
}
/// <summary>
/// Gets the information about the user agent originating the request.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the User-Agent request-header.
/// </value>
public string UserAgent {
get {
return _headers["User-Agent"];
}
}
/// <summary>
/// Gets the server endpoint as an IP address and a port number.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the server endpoint.
/// </value>
public string UserHostAddress {
get {
return LocalEndPoint.ToString ();
}
}
/// <summary>
/// Gets the internet host name and port number (if present) specified by the client.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the Host request-header.
/// </value>
public string UserHostName {
get {
return _headers["Host"];
}
}
/// <summary>
/// Gets the natural languages which are preferred for the response.
/// </summary>
/// <value>
/// An array of <see cref="string"/> that contains the natural language names in
/// the Accept-Language request-header, or <see langword="null"/> if the request
/// didn't include an Accept-Language header.
/// </value>
public string[] UserLanguages {
get {
return _userLanguages;
}
}
#endregion
#region Private Methods
private static bool tryCreateVersion (string version, out Version result)
{
try {
result = new Version (version);
return true;
}
catch {
result = null;
return false;
}
}
#endregion
#region Internal Methods
internal void AddHeader (string header)
{
var colon = header.IndexOf (':');
if (colon == -1) {
_context.ErrorMessage = "Invalid header";
return;
}
var name = header.Substring (0, colon).Trim ();
var val = header.Substring (colon + 1).Trim ();
_headers.InternalSet (name, val, false);
var lower = name.ToLower (CultureInfo.InvariantCulture);
if (lower == "accept") {
_acceptTypes = new List<string> (val.SplitHeaderValue (',')).ToArray ();
return;
}
if (lower == "accept-language") {
_userLanguages = val.Split (',');
return;
}
if (lower == "content-length") {
long len;
if (Int64.TryParse (val, out len) && len >= 0) {
_contentLength = len;
_contentLengthWasSet = true;
}
else {
_context.ErrorMessage = "Invalid Content-Length header";
}
return;
}
if (lower == "content-type") {
try {
_contentEncoding = HttpUtility.GetEncoding (val);
}
catch {
_context.ErrorMessage = "Invalid Content-Type header";
}
return;
}
if (lower == "referer")
_referer = val.ToUri ();
}
internal void FinishInitialization ()
{
var host = _headers["Host"];
var nohost = host == null || host.Length == 0;
if (_version > HttpVersion.Version10 && nohost) {
_context.ErrorMessage = "Invalid Host header";
return;
}
if (nohost)
host = UserHostAddress;
_url = HttpUtility.CreateRequestUrl (_uri, host, IsWebSocketRequest, IsSecureConnection);
if (_url == null) {
_context.ErrorMessage = "Invalid request url";
return;
}
var enc = Headers["Transfer-Encoding"];
if (_version > HttpVersion.Version10 && enc != null && enc.Length > 0) {
_chunked = enc.ToLower () == "chunked";
if (!_chunked) {
_context.ErrorMessage = String.Empty;
_context.ErrorStatus = 501;
return;
}
}
if (!_chunked && !_contentLengthWasSet) {
var method = _method.ToLower ();
if (method == "post" || method == "put") {
_context.ErrorMessage = String.Empty;
_context.ErrorStatus = 411;
return;
}
}
var expect = Headers["Expect"];
if (expect != null && expect.Length > 0 && expect.ToLower () == "100-continue") {
var output = _context.Connection.GetResponseStream ();
output.InternalWrite (_100continue, 0, _100continue.Length);
}
}
// Returns true is the stream could be reused.
internal bool FlushInput ()
{
if (!HasEntityBody)
return true;
var len = 2048;
if (_contentLength > 0)
len = (int) Math.Min (_contentLength, (long) len);
var buff = new byte[len];
while (true) {
// TODO: Test if MS has a timeout when doing this.
try {
var ares = InputStream.BeginRead (buff, 0, len, null, null);
if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (100))
return false;
if (InputStream.EndRead (ares) <= 0)
return true;
}
catch {
return false;
}
}
}
internal void SetRequestLine (string requestLine)
{
var parts = requestLine.Split (new[] { ' ' }, 3);
if (parts.Length != 3) {
_context.ErrorMessage = "Invalid request line (parts)";
return;
}
_method = parts[0];
if (!_method.IsToken ()) {
_context.ErrorMessage = "Invalid request line (method)";
return;
}
_uri = parts[1];
var ver = parts[2];
if (ver.Length != 8 ||
!ver.StartsWith ("HTTP/") ||
!tryCreateVersion (ver.Substring (5), out _version) ||
_version.Major < 1)
_context.ErrorMessage = "Invalid request line (version)";
}
#endregion
#region Public Methods
/// <summary>
/// Begins getting the client's X.509 v.3 certificate asynchronously.
/// </summary>
/// <remarks>
/// This asynchronous operation must be completed by calling the
/// <see cref="EndGetClientCertificate"/> method. Typically, that method is invoked by the
/// <paramref name="requestCallback"/> delegate.
/// </remarks>
/// <returns>
/// An <see cref="IAsyncResult"/> that contains the status of the asynchronous operation.
/// </returns>
/// <param name="requestCallback">
/// An <see cref="AsyncCallback"/> delegate that references the method(s) called when the
/// asynchronous operation completes.
/// </param>
/// <param name="state">
/// An <see cref="object"/> that contains a user defined object to pass to the
/// <paramref name="requestCallback"/> delegate.
/// </param>
/// <exception cref="NotImplementedException">
/// This method isn't implemented.
/// </exception>
public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
{
// TODO: Not Implemented.
throw new NotImplementedException ();
}
/// <summary>
/// Ends an asynchronous operation to get the client's X.509 v.3 certificate.
/// </summary>
/// <remarks>
/// This method completes an asynchronous operation started by calling the
/// <see cref="BeginGetClientCertificate"/> method.
/// </remarks>
/// <returns>
/// A <see cref="X509Certificate2"/> that contains the client's X.509 v.3 certificate.
/// </returns>
/// <param name="asyncResult">
/// An <see cref="IAsyncResult"/> obtained by calling the
/// <see cref="BeginGetClientCertificate"/> method.
/// </param>
/// <exception cref="NotImplementedException">
/// This method isn't implemented.
/// </exception>
public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
{
// TODO: Not Implemented.
throw new NotImplementedException ();
}
/// <summary>
/// Gets the client's X.509 v.3 certificate.
/// </summary>
/// <returns>
/// A <see cref="X509Certificate2"/> that contains the client's X.509 v.3 certificate.
/// </returns>
/// <exception cref="NotImplementedException">
/// This method isn't implemented.
/// </exception>
public X509Certificate2 GetClientCertificate ()
{
// TODO: Not Implemented.
throw new NotImplementedException ();
}
/// <summary>
/// Returns a <see cref="string"/> that represents the current
/// <see cref="HttpListenerRequest"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the current <see cref="HttpListenerRequest"/>.
/// </returns>
public override string ToString ()
{
var output = new StringBuilder (64);
output.AppendFormat ("{0} {1} HTTP/{2}\r\n", _method, _uri, _version);
output.Append (_headers.ToString ());
return output.ToString ();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace MS.Internal.Xml.XPath
{
internal sealed class StringFunctions : ValueQuery
{
Function.FunctionType funcType;
private IList<Query> argList;
public StringFunctions(Function.FunctionType funcType, IList<Query> argList)
{
Debug.Assert(argList != null, "Use 'new Query[]{}' instead.");
this.funcType = funcType;
this.argList = argList;
}
private StringFunctions(StringFunctions other) : base(other)
{
this.funcType = other.funcType;
Query[] tmp = new Query[other.argList.Count];
{
for (int i = 0; i < tmp.Length; i++)
{
tmp[i] = Clone(other.argList[i]);
}
}
this.argList = tmp;
}
public override void SetXsltContext(XsltContext context)
{
for (int i = 0; i < argList.Count; i++)
{
argList[i].SetXsltContext(context);
}
}
public override object Evaluate(XPathNodeIterator nodeIterator)
{
switch (funcType)
{
case Function.FunctionType.FuncString: return toString(nodeIterator);
case Function.FunctionType.FuncConcat: return Concat(nodeIterator);
case Function.FunctionType.FuncStartsWith: return StartsWith(nodeIterator);
case Function.FunctionType.FuncContains: return Contains(nodeIterator);
case Function.FunctionType.FuncSubstringBefore: return SubstringBefore(nodeIterator);
case Function.FunctionType.FuncSubstringAfter: return SubstringAfter(nodeIterator);
case Function.FunctionType.FuncSubstring: return Substring(nodeIterator);
case Function.FunctionType.FuncStringLength: return StringLength(nodeIterator);
case Function.FunctionType.FuncNormalize: return Normalize(nodeIterator);
case Function.FunctionType.FuncTranslate: return Translate(nodeIterator);
}
return string.Empty;
}
internal static string toString(double num)
{
return num.ToString("R", NumberFormatInfo.InvariantInfo);
}
internal static string toString(bool b)
{
return b ? "true" : "false";
}
private string toString(XPathNodeIterator nodeIterator)
{
if (argList.Count > 0)
{
object argVal = argList[0].Evaluate(nodeIterator);
switch (GetXPathType(argVal))
{
case XPathResultType.NodeSet:
XPathNavigator value = argList[0].Advance();
return value != null ? value.Value : string.Empty;
case XPathResultType.String:
return (string)argVal;
case XPathResultType.Boolean:
return ((bool)argVal) ? "true" : "false";
case XPathResultType_Navigator:
return ((XPathNavigator)argVal).Value;
default:
Debug.Assert(GetXPathType(argVal) == XPathResultType.Number);
return toString((double)argVal);
}
}
return nodeIterator.Current.Value;
}
public override XPathResultType StaticType
{
get
{
if (funcType == Function.FunctionType.FuncStringLength)
{
return XPathResultType.Number;
}
if (
funcType == Function.FunctionType.FuncStartsWith ||
funcType == Function.FunctionType.FuncContains
)
{
return XPathResultType.Boolean;
}
return XPathResultType.String;
}
}
private string Concat(XPathNodeIterator nodeIterator)
{
int count = 0;
StringBuilder s = new StringBuilder();
while (count < argList.Count)
{
s.Append(argList[count++].Evaluate(nodeIterator).ToString());
}
return s.ToString();
}
private bool StartsWith(XPathNodeIterator nodeIterator)
{
string s1 = argList[0].Evaluate(nodeIterator).ToString();
string s2 = argList[1].Evaluate(nodeIterator).ToString();
return s1.Length >= s2.Length && string.CompareOrdinal(s1, 0, s2, 0, s2.Length) == 0;
}
private static readonly CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo;
private bool Contains(XPathNodeIterator nodeIterator)
{
string s1 = argList[0].Evaluate(nodeIterator).ToString();
string s2 = argList[1].Evaluate(nodeIterator).ToString();
return compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal) >= 0;
}
private string SubstringBefore(XPathNodeIterator nodeIterator)
{
string s1 = argList[0].Evaluate(nodeIterator).ToString();
string s2 = argList[1].Evaluate(nodeIterator).ToString();
if (s2.Length == 0) { return s2; }
int idx = compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal);
return (idx < 1) ? string.Empty : s1.Substring(0, idx);
}
private string SubstringAfter(XPathNodeIterator nodeIterator)
{
string s1 = argList[0].Evaluate(nodeIterator).ToString();
string s2 = argList[1].Evaluate(nodeIterator).ToString();
if (s2.Length == 0) { return s1; }
int idx = compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal);
return (idx < 0) ? string.Empty : s1.Substring(idx + s2.Length);
}
private string Substring(XPathNodeIterator nodeIterator)
{
string str1 = argList[0].Evaluate(nodeIterator).ToString();
double num = XmlConvertEx.XPathRound(XmlConvertEx.ToXPathDouble(argList[1].Evaluate(nodeIterator))) - 1;
if (Double.IsNaN(num) || str1.Length <= num)
{
return string.Empty;
}
if (argList.Count == 3)
{
double num1 = XmlConvertEx.XPathRound(XmlConvertEx.ToXPathDouble(argList[2].Evaluate(nodeIterator)));
if (Double.IsNaN(num1))
{
return string.Empty;
}
if (num < 0 || num1 < 0)
{
num1 = num + num1;
// NOTE: condition is true for NaN
if (!(num1 > 0))
{
return string.Empty;
}
num = 0;
}
double maxlength = str1.Length - num;
if (num1 > maxlength)
{
num1 = maxlength;
}
return str1.Substring((int)num, (int)num1);
}
if (num < 0)
{
num = 0;
}
return str1.Substring((int)num);
}
private Double StringLength(XPathNodeIterator nodeIterator)
{
if (argList.Count > 0)
{
return argList[0].Evaluate(nodeIterator).ToString().Length;
}
return nodeIterator.Current.Value.Length;
}
private string Normalize(XPathNodeIterator nodeIterator)
{
string str1;
if (argList.Count > 0)
{
str1 = argList[0].Evaluate(nodeIterator).ToString();
}
else
{
str1 = nodeIterator.Current.Value;
}
str1 = XmlConvertEx.TrimString(str1);
int count = 0;
StringBuilder str2 = new StringBuilder();
bool FirstSpace = true;
XmlCharType xmlCharType = XmlCharType.Instance;
while (count < str1.Length)
{
if (!xmlCharType.IsWhiteSpace(str1[count]))
{
FirstSpace = true;
str2.Append(str1[count]);
}
else if (FirstSpace)
{
FirstSpace = false;
str2.Append(' ');
}
count++;
}
return str2.ToString();
}
private string Translate(XPathNodeIterator nodeIterator)
{
string str1 = argList[0].Evaluate(nodeIterator).ToString();
string str2 = argList[1].Evaluate(nodeIterator).ToString();
string str3 = argList[2].Evaluate(nodeIterator).ToString();
int count = 0, index;
StringBuilder str = new StringBuilder();
while (count < str1.Length)
{
index = str2.IndexOf(str1[count]);
if (index != -1)
{
if (index < str3.Length)
{
str.Append(str3[index]);
}
}
else
{
str.Append(str1[count]);
}
count++;
}
return str.ToString();
}
public override XPathNodeIterator Clone() { return new StringFunctions(this); }
public override void PrintQuery(XmlWriter w)
{
w.WriteStartElement(this.GetType().Name);
w.WriteAttributeString("name", funcType.ToString());
foreach (Query arg in this.argList)
{
arg.PrintQuery(w);
}
w.WriteEndElement();
}
}
}
| |
// ============================================================================
// FileName: SIPAssetPersistor.cs
//
// Description:
// Base class for retrieving and persisting SIP asset objects from a persistent
// data store such as a relational database or XML file.
//
// Author(s):
// Aaron Clauson
//
// History:
// 01 Oct 2008 Aaron Clauson Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2008 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 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 SIP Sorcery PTY LTD.
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// ============================================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using SIPSorcery.SIP.App;
using SIPSorcery.Sys;
using log4net;
#if !SILVERLIGHT
using System.Data;
using System.Data.Common;
using System.Data.Linq;
using System.Data.Linq.Mapping;
#endif
namespace SIPSorcery.Persistence
{
#if !SILVERLIGHT
public delegate T SIPAssetGetFromDirectQueryDelegate<T>(string sqlQuery, params IDbDataParameter[] sqlParameters);
#endif
public class SIPAssetPersistor<T>
{
protected static ILog logger = AppState.logger;
#if !SILVERLIGHT
protected DbProviderFactory m_dbProviderFactory;
protected string m_dbConnectionStr;
protected ObjectMapper<T> m_objectMapper;
#endif
public virtual event SIPAssetDelegate<T> Added;
public virtual event SIPAssetDelegate<T> Updated;
public virtual event SIPAssetDelegate<T> Deleted;
public virtual event SIPAssetsModifiedDelegate Modified;
public virtual T Add(T asset)
{
throw new NotImplementedException("Method " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() + " not implemented.");
}
public virtual T Update(T asset)
{
throw new NotImplementedException("Method " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() + " not implemented.");
}
public virtual void UpdateProperty(Guid id, string propertyName, object value)
{
throw new NotImplementedException("Method " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() + " not implemented.");
}
public virtual void IncrementProperty(Guid id, string propertyName)
{
throw new NotImplementedException("Method " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() + " not implemented.");
}
public virtual void DecrementProperty(Guid id, string propertyName)
{
throw new NotImplementedException("Method " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() + " not implemented.");
}
public virtual void Delete(T asset)
{
throw new NotImplementedException("Method " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() + " not implemented.");
}
public virtual void Delete(Expression<Func<T, bool>> where)
{
throw new NotImplementedException("Method " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() + " not implemented.");
}
public virtual T Get(Guid id)
{
throw new NotImplementedException("Method " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() + " not implemented.");
}
public virtual object GetProperty(Guid id, string propertyName)
{
throw new NotImplementedException("Method " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() + " not implemented.");
}
public virtual int Count(Expression<Func<T, bool>> where)
{
throw new NotImplementedException("Method " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() + " not implemented.");
}
public virtual T Get(Expression<Func<T, bool>> where)
{
throw new NotImplementedException("Method " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() + " not implemented.");
}
public virtual List<T> Get(Expression<Func<T, bool>> where, string orderByField, int offset, int count)
{
throw new NotImplementedException("Method " + System.Reflection.MethodBase.GetCurrentMethod().Name + " in " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() + " not implemented.");
}
#if !SILVERLIGHT
protected DbParameter GetParameter(DbProviderFactory dbProviderFactory, MetaDataMember member, object parameterValue, string parameterName)
{
DbParameter dbParameter = dbProviderFactory.CreateParameter();
dbParameter.ParameterName = parameterName;
dbParameter.DbType = EntityTypeConversionTable.LookupDbType(member.DbType);
if (parameterValue == null)
{
dbParameter.Value = null;
}
else if (member.Type == typeof(DateTimeOffset) || member.Type == typeof(Nullable<DateTimeOffset>))
{
dbParameter.Value = ((DateTimeOffset)parameterValue).ToString("o");
}
else
{
dbParameter.Value = parameterValue;
}
return dbParameter;
}
protected void Increment(Guid id, string propertyName)
{
try
{
MetaDataMember member = m_objectMapper.GetMember(propertyName);
string commandText = "update " + m_objectMapper.TableName + " set " + propertyName + " = " + propertyName + " + 1 where id = '" + id + "'";
ExecuteCommand(commandText);
}
catch (Exception excp)
{
logger.Error("Exception SIPAssetPersistor IncrementProperty (for " + typeof(T).Name + "). " + excp.Message);
throw;
}
}
protected void Decrement(Guid id, string propertyName)
{
try
{
MetaDataMember member = m_objectMapper.GetMember(propertyName);
string commandText = "update " + m_objectMapper.TableName + " set " + propertyName + " = " + propertyName + "- 1 where id = '" + id + "'";
ExecuteCommand(commandText);
}
catch (Exception excp)
{
logger.Error("Exception SIPAssetPersistor DecrementProperty (for " + typeof(T).Name + "). " + excp.Message);
throw;
}
}
private void ExecuteCommand(string commandText)
{
try
{
using (IDbConnection connection = m_dbProviderFactory.CreateConnection())
{
connection.ConnectionString = m_dbConnectionStr;
connection.Open();
IDbCommand command = connection.CreateCommand();
command.CommandText = commandText;
command.ExecuteNonQuery();
}
}
catch (Exception excp)
{
logger.Error("Exception SIPAssetPersistor ExecuteCommand (for " + typeof(T).Name + "). " + excp.Message);
throw;
}
}
#endif
}
}
| |
#include "RenderSystems/Volumes/VolumesCommon.h"
#define DENSITY_MULT (1.0/(float(THREAD_DIM) + 3.0))
cbuffer BlockStateCbuffer
{
float4 gWorldOffset;
float4 gWorldScale;
};
Texture3D<float> densityTexture;
Texture3D<uint> meshCounts;
Texture3D<uint> meshSparse8;
Texture3D<uint> meshSparse4;
RWBuffer<uint> outIndexBuffer : u0;
RWByteAddressBuffer outVertexBuffer : u1;
RWByteAddressBuffer outNormalBuffer : u2;
RWByteAddressBuffer outIndirectBuffer : u3;
SamplerState densitySampler : s0;
groupshared uint gsmSparse4;
uint getGridVertexOffset(uint3 gridCoord)
{
return dot(uint3(3,3*(THREAD_DIM+1),3*(THREAD_DIM+1)*(THREAD_DIM+1)), gridCoord);
}
float3 ComputeVertexNorm(int3 voxelPos)
{
//gradient samples
float2 xSamples = float2(densityTexture[voxelPos + int3(1,0,0)], densityTexture[voxelPos - int3(1,0,0)]);
float2 ySamples = float2(densityTexture[voxelPos - int3(0,1,0)], densityTexture[voxelPos + int3(0,1,0)]);
float2 zSamples = float2(densityTexture[voxelPos + int3(0,0,1)], densityTexture[voxelPos - int3(0,0,1)]);
return normalize(-float3(xSamples.x - xSamples.y,ySamples.x - ySamples.y,zSamples.x - xSamples.y));
return float3(1.0,0.0,0.0);
}
float3 ComputeVertexNormBilinear(float3 voxelPos)
{
float3 voxelUv = ((voxelPos + float3(1.5,1.5,1.5))*DENSITY_MULT);
float delta = DENSITY_MULT * 1;
float2 xSamples = float2(densityTexture.SampleLevel(densitySampler,voxelUv - delta*float3(1,0,0), 0).x, densityTexture.SampleLevel(densitySampler,float3(voxelUv + delta*float3(1,0,0)), 0).x);
float2 ySamples = float2(densityTexture.SampleLevel(densitySampler,voxelUv + delta*float3(0,1,0), 0).x, densityTexture.SampleLevel(densitySampler,float3(voxelUv - delta*float3(0,1,0)), 0).x);
float2 zSamples = float2(densityTexture.SampleLevel(densitySampler,voxelUv + delta*float3(0,0,1), 0).x, densityTexture.SampleLevel(densitySampler,float3(voxelUv - delta*float3(0,0,1)), 0).x);
return normalize(-float3(xSamples.x - xSamples.y,ySamples.x - ySamples.y,zSamples.x - zSamples.y));
}
float3 ComputeVertexPos(uint edgeIndex, uint3 voxelPos)
{
const int3 cubePos[8] = {
int3(0, 0, 0), //0
int3(1, 0, 0), //1
int3(1, 1, 0), //2
int3(0, 1, 0), //3
int3(0, 0, 1), //4
int3(1, 0, 1), //5
int3(1, 1, 1), //6
int3(0, 1, 1), //7
};
// 8e------ _~ 4----4e---5
// 0----0e----1 /| ------9e
// | | | 5e
// 3e 7e 1e |
// | | | |
// |_~ 7---6e-|--6
// 11e----- 3----2e----2/ -------10e
//
//indices to vertexOffsets
const uint2 edgeConnections[12] = {
uint2(0, 1),
uint2(1, 2),
uint2(2, 3),
uint2(3, 0),
uint2(4, 5),
uint2(5, 6),
uint2(6, 7),
uint2(7, 4),
uint2(4, 0),
uint2(5, 1),
uint2(6, 2),
uint2(7 ,3)
};
uint2 edgeConnection = edgeConnections[edgeIndex];
int3 sampleOffsetA = cubePos[edgeConnection.x];
int3 sampleOffsetB = cubePos[edgeConnection.y];
int3 sampleCoordA = sampleOffsetA + voxelPos;
int3 sampleCoordB = sampleOffsetB + voxelPos;
float2 densitySamples = float2(densityTexture[sampleCoordA + uint3(1,1,1)], densityTexture[sampleCoordB + uint3(1,1,1)]);
float3 fCoordA = (float3(sampleOffsetA));
float3 fCoordB = (float3(sampleOffsetB));
float midPoint = (MID_POINT - densitySamples.x) / (densitySamples.y - densitySamples.x);
float3 coord = lerp(fCoordA,fCoordB, midPoint*float3(1,1,1));
return coord + float3(voxelPos);
}
void WriteIndices(uint3 gridCoord, uint2 geoInfo, uint caseId)
{
//remappings. Dependant on the fact of the ownership of each voxel on edges 0, 3 and 8
const uint4 remapMask[12] = {
uint4(0,0,0,0),//0
uint4(1,0,0,1),//1
uint4(0,1,0,0),//2
uint4(0,0,0,1),//3
uint4(0,0,1,0),//4
uint4(1,0,1,1),//5
uint4(0,1,1,0),//6
uint4(0,0,1,1),//7
uint4(0,0,0,2),//8
uint4(1,0,0,2),//9
uint4(1,1,0,2),//10
uint4(0,1,0,2) //11
};
[loop]
for (uint idxIt = 0; idxIt < geoInfo.y; ++idxIt)
{
uint caseIndex = GetIndex(caseId, idxIt);
uint4 remapMsk = remapMask[caseIndex];
outIndexBuffer[geoInfo.x + idxIt] = getGridVertexOffset(gridCoord + remapMsk.xyz) + remapMsk.w ;
}
}
void BuildIndices(uint3 gi, uint3 gti, uint3 dti)
{
uint3 gridCoord = gi * 8 + gti;
uint countsInfo = meshCounts[gridCoord];
uint2 indexCount_caseId = uint2(countsInfo >> 8, countsInfo & 0xff);
uint caseId = indexCount_caseId.y;
uint indexOffset = meshSparse8[gridCoord] - indexCount_caseId.x + gsmSparse4;
uint2 geoInfo = uint2(indexOffset,indexCount_caseId.x);
WriteIndices(gridCoord, geoInfo, caseId);
}
void WriteVertexes(uint voffset, uint3 voxelPos, uint3 gti, uint countInfo, uint caseId)
{
uint byteOffset = voffset * 12; //three 32 bit components. Which is 12 bites. geoInfo.x contains offset in vertex buffer
uint edgeOrder[] = {0, 3, 8};
int edgeId = 0;
[loop]
for (edgeId = 0; edgeId < 3; ++edgeId)
{
uint edgeIndex = edgeOrder[edgeId];
if (GetEdgeBit(countInfo, edgeIndex))
{
float3 vertexPos = ComputeVertexPos(edgeIndex, voxelPos)*gWorldScale.x + gWorldOffset.xyz;
StoreFloat3Vertex(outVertexBuffer, byteOffset + 12*edgeId, vertexPos);
}
}
}
void WriteNormals(uint voffset, uint3 voxelPos, uint3 gti, uint countInfo, uint caseId)
{
uint byteOffset = voffset * 12; //three 32 bit components. Which is 12 bites. geoInfo.x contains offset in vertex buffer
uint edgeOrder[] = {0, 3, 8};
int edgeId = 0;
[loop]
for (edgeId = 0; edgeId < 3; ++edgeId)
{
uint edgeIndex = edgeOrder[edgeId];
if (GetEdgeBit(countInfo, edgeIndex))
{
float3 vertexPos = ComputeVertexPos(edgeIndex, voxelPos);
float3 outNormal = ComputeVertexNormBilinear(vertexPos);
StoreFloat3Vertex(outNormalBuffer, byteOffset + 12*edgeId,outNormal);
}
}
}
void BuildVertexes(uint3 dti, uint3 gti)
{
uint vOffset = getGridVertexOffset(dti);
uint countsInfo = meshCounts[dti];
uint2 indexCount_caseId = uint2(countsInfo >> 8, countsInfo & 0xff);
uint caseId = indexCount_caseId.y;
uint edgeCountInfo = GetCountInfo(caseId);
WriteVertexes(vOffset, dti, gti, edgeCountInfo, caseId);
}
void BuildNormals(uint3 dti, uint3 gti)
{
uint vOffset = getGridVertexOffset(dti);
uint countsInfo = meshCounts[dti];
uint2 indexCount_caseId = uint2(countsInfo >> 8, countsInfo & 0xff);
uint caseId = indexCount_caseId.y;
uint edgeCountInfo = GetCountInfo(caseId);
WriteNormals(vOffset, dti, gti, edgeCountInfo, caseId);
}
[numthreads(BLOCK_DIM+1,BLOCK_DIM+1,BLOCK_DIM+1)]
void main(uint3 dti : SV_DispatchThreadId, uint3 gti : SV_GroupThreadId, uint3 gi : SV_GroupId)
{
if (all(gti == 0))
{
gsmSparse4 = meshSparse4[gi];
}
GroupMemoryBarrierWithGroupSync();
if (all(gti < BLOCK_DIM))
{
BuildIndices(gi, gti, dti);
}
if (all(dti < (THREAD_DIM+1)))
{
BuildVertexes(dti, gti);
}
GroupMemoryBarrierWithGroupSync();
if (all(dti < (THREAD_DIM+1)))
{
BuildNormals(dti, gti);
}
if (all(gi == 0) && all(gti == 0))
{
uint totalCountIndices = meshSparse8[uint3(THREAD_DIM-1,THREAD_DIM-1,THREAD_DIM-1)] + meshSparse4[uint3(1,1,1)];
//[in] UINT IndexCountPerInstance
outIndirectBuffer.Store(0, totalCountIndices);
//[in] UINT InstanceCount
outIndirectBuffer.Store(4, 1);
//[in] UINT StartIndexLocation,
outIndirectBuffer.Store(8, 0);
//[in] INT BaseVertexLocation,
outIndirectBuffer.Store(12, 0);
//[in] UINT StartInstanceLocation
outIndirectBuffer.Store(16, 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.
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
namespace System.Dynamic.Utils
{
internal static partial class TypeUtils
{
public static Type GetNonNullableType(this Type type)
{
if (IsNullableType(type))
{
return type.GetGenericArguments()[0];
}
return type;
}
public static Type GetNullableType(this Type type)
{
Debug.Assert(type != null, "type cannot be null");
if (type.IsValueType && !IsNullableType(type))
{
return typeof(Nullable<>).MakeGenericType(type);
}
return type;
}
public static bool IsNullableType(this Type type)
{
return type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
public static bool IsNullableOrReferenceType(this Type type)
{
return !type.IsValueType || IsNullableType(type);
}
public static bool IsBool(this Type type)
{
return GetNonNullableType(type) == typeof(bool);
}
public static bool IsNumeric(this Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
}
}
return false;
}
public static bool IsInteger(this Type type)
{
type = GetNonNullableType(type);
if (type.IsEnum)
{
return false;
}
switch (type.GetTypeCode())
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
public static bool IsInteger64(this Type type)
{
type = GetNonNullableType(type);
if (type.IsEnum)
{
return false;
}
switch (type.GetTypeCode())
{
case TypeCode.Int64:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
public static bool IsArithmetic(this Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
}
}
return false;
}
public static bool IsUnsignedInt(this Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
}
}
return false;
}
public static bool IsIntegerOrBool(this Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.Int64:
case TypeCode.Int32:
case TypeCode.Int16:
case TypeCode.UInt64:
case TypeCode.UInt32:
case TypeCode.UInt16:
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Byte:
return true;
}
}
return false;
}
public static bool IsNumericOrBool(this Type type)
{
return IsNumeric(type) || IsBool(type);
}
// Checks if the type is a valid target for an instance call
public static bool IsValidInstanceType(MemberInfo member, Type instanceType)
{
Type targetType = member.DeclaringType;
if (AreReferenceAssignable(targetType, instanceType))
{
return true;
}
if (targetType == null)
{
return false;
}
if (instanceType.IsValueType)
{
if (AreReferenceAssignable(targetType, typeof(object)))
{
return true;
}
if (AreReferenceAssignable(targetType, typeof(ValueType)))
{
return true;
}
if (instanceType.IsEnum && AreReferenceAssignable(targetType, typeof(Enum)))
{
return true;
}
// A call to an interface implemented by a struct is legal whether the struct has
// been boxed or not.
if (targetType.IsInterface)
{
foreach (Type interfaceType in instanceType.GetTypeInfo().ImplementedInterfaces)
{
if (AreReferenceAssignable(targetType, interfaceType))
{
return true;
}
}
}
}
return false;
}
public static bool HasIdentityPrimitiveOrNullableConversionTo(this Type source, Type dest)
{
Debug.Assert(source != null && dest != null);
// Identity conversion
if (AreEquivalent(source, dest))
{
return true;
}
// Nullable conversions
if (IsNullableType(source) && AreEquivalent(dest, GetNonNullableType(source)))
{
return true;
}
if (IsNullableType(dest) && AreEquivalent(source, GetNonNullableType(dest)))
{
return true;
}
// Primitive runtime conversions
// All conversions amongst enum, bool, char, integer and float types
// (and their corresponding nullable types) are legal except for
// nonbool==>bool and nonbool==>bool? which are only legal from
// bool-backed enums.
if (IsConvertible(source) && IsConvertible(dest))
{
return GetNonNullableType(dest) != typeof(bool)
|| source.IsEnum && source.GetEnumUnderlyingType() == typeof(bool);
}
return false;
}
public static bool HasReferenceConversionTo(this Type source, Type dest)
{
Debug.Assert(source != null && dest != null);
// void -> void conversion is handled elsewhere
// (it's an identity conversion)
// All other void conversions are disallowed.
if (source == typeof(void) || dest == typeof(void))
{
return false;
}
Type nnSourceType = GetNonNullableType(source);
Type nnDestType = GetNonNullableType(dest);
// Down conversion
if (nnSourceType.IsAssignableFrom(nnDestType))
{
return true;
}
// Up conversion
if (nnDestType.IsAssignableFrom(nnSourceType))
{
return true;
}
// Interface conversion
if (source.IsInterface || dest.IsInterface)
{
return true;
}
// Variant delegate conversion
if (IsLegalExplicitVariantDelegateConversion(source, dest))
return true;
// Object conversion
if (source == typeof(object) || dest == typeof(object))
{
return true;
}
return false;
}
private static bool IsCovariant(Type t)
{
Debug.Assert(t != null);
return 0 != (t.GenericParameterAttributes & GenericParameterAttributes.Covariant);
}
private static bool IsContravariant(Type t)
{
Debug.Assert(t != null);
return 0 != (t.GenericParameterAttributes & GenericParameterAttributes.Contravariant);
}
private static bool IsInvariant(Type t)
{
Debug.Assert(t != null);
return 0 == (t.GenericParameterAttributes & GenericParameterAttributes.VarianceMask);
}
private static bool IsDelegate(Type t)
{
Debug.Assert(t != null);
return t.IsSubclassOf(typeof(MulticastDelegate));
}
public static bool IsLegalExplicitVariantDelegateConversion(Type source, Type dest)
{
Debug.Assert(source != null && dest != null);
// There *might* be a legal conversion from a generic delegate type S to generic delegate type T,
// provided all of the follow are true:
// o Both types are constructed generic types of the same generic delegate type, D<X1,... Xk>.
// That is, S = D<S1...>, T = D<T1...>.
// o If type parameter Xi is declared to be invariant then Si must be identical to Ti.
// o If type parameter Xi is declared to be covariant ("out") then Si must be convertible
// to Ti via an identify conversion, implicit reference conversion, or explicit reference conversion.
// o If type parameter Xi is declared to be contravariant ("in") then either Si must be identical to Ti,
// or Si and Ti must both be reference types.
if (!IsDelegate(source) || !IsDelegate(dest) || !source.IsGenericType || !dest.IsGenericType)
return false;
Type genericDelegate = source.GetGenericTypeDefinition();
if (dest.GetGenericTypeDefinition() != genericDelegate)
return false;
Type[] genericParameters = genericDelegate.GetGenericArguments();
Type[] sourceArguments = source.GetGenericArguments();
Type[] destArguments = dest.GetGenericArguments();
Debug.Assert(genericParameters != null);
Debug.Assert(sourceArguments != null);
Debug.Assert(destArguments != null);
Debug.Assert(genericParameters.Length == sourceArguments.Length);
Debug.Assert(genericParameters.Length == destArguments.Length);
for (int iParam = 0; iParam < genericParameters.Length; ++iParam)
{
Type sourceArgument = sourceArguments[iParam];
Type destArgument = destArguments[iParam];
Debug.Assert(sourceArgument != null && destArgument != null);
// If the arguments are identical then this one is automatically good, so skip it.
if (AreEquivalent(sourceArgument, destArgument))
{
continue;
}
Type genericParameter = genericParameters[iParam];
Debug.Assert(genericParameter != null);
if (IsInvariant(genericParameter))
{
return false;
}
if (IsCovariant(genericParameter))
{
if (!sourceArgument.HasReferenceConversionTo(destArgument))
{
return false;
}
}
else if (IsContravariant(genericParameter))
{
if (sourceArgument.IsValueType || destArgument.IsValueType)
{
return false;
}
}
}
return true;
}
public static bool IsConvertible(this Type type)
{
type = GetNonNullableType(type);
if (type.IsEnum)
{
return true;
}
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Char:
return true;
default:
return false;
}
}
public static bool HasReferenceEquality(Type left, Type right)
{
if (left.IsValueType || right.IsValueType)
{
return false;
}
// If we have an interface and a reference type then we can do
// reference equality.
// If we have two reference types and one is assignable to the
// other then we can do reference equality.
return left.IsInterface || right.IsInterface ||
AreReferenceAssignable(left, right) ||
AreReferenceAssignable(right, left);
}
public static bool HasBuiltInEqualityOperator(Type left, Type right)
{
// If we have an interface and a reference type then we can do
// reference equality.
if (left.IsInterface && !right.IsValueType)
{
return true;
}
if (right.IsInterface && !left.IsValueType)
{
return true;
}
// If we have two reference types and one is assignable to the
// other then we can do reference equality.
if (!left.IsValueType && !right.IsValueType)
{
if (AreReferenceAssignable(left, right) || AreReferenceAssignable(right, left))
{
return true;
}
}
// Otherwise, if the types are not the same then we definitely
// do not have a built-in equality operator.
if (!AreEquivalent(left, right))
{
return false;
}
// We have two identical value types, modulo nullability. (If they were both the
// same reference type then we would have returned true earlier.)
Debug.Assert(left.IsValueType);
// Equality between struct types is only defined for numerics, bools, enums,
// and their nullable equivalents.
Type nnType = GetNonNullableType(left);
if (nnType == typeof(bool) || IsNumeric(nnType) || nnType.IsEnum)
{
return true;
}
return false;
}
public static bool IsImplicitlyConvertibleTo(this Type source, Type destination)
{
return AreEquivalent(source, destination) || // identity conversion
IsImplicitNumericConversion(source, destination) ||
IsImplicitReferenceConversion(source, destination) ||
IsImplicitBoxingConversion(source, destination) ||
IsImplicitNullableConversion(source, destination);
}
public static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type convertToType)
{
Type nnExprType = GetNonNullableType(convertFrom);
Type nnConvType = GetNonNullableType(convertToType);
// try exact match on types
MethodInfo[] eMethods = nnExprType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
MethodInfo method = FindConversionOperator(eMethods, convertFrom, convertToType);
if (method != null)
{
return method;
}
MethodInfo[] cMethods = nnConvType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
method = FindConversionOperator(cMethods, convertFrom, convertToType);
if (method != null)
{
return method;
}
if (AreEquivalent(nnExprType, convertFrom) && AreEquivalent(nnConvType, convertToType))
{
return null;
}
// try lifted conversion
return FindConversionOperator(eMethods, nnExprType, nnConvType)
?? FindConversionOperator(cMethods, nnExprType, nnConvType)
?? FindConversionOperator(eMethods, nnExprType, convertToType)
?? FindConversionOperator(cMethods, nnExprType, convertToType);
}
private static MethodInfo FindConversionOperator(MethodInfo[] methods, Type typeFrom, Type typeTo)
{
foreach (MethodInfo mi in methods)
{
if (
(mi.Name == "op_Implicit" || mi.Name == "op_Explicit")
&& AreEquivalent(mi.ReturnType, typeTo)
)
{
ParameterInfo[] pis = mi.GetParametersCached();
if (pis.Length == 1 && AreEquivalent(pis[0].ParameterType, typeFrom))
{
return mi;
}
}
}
return null;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static bool IsImplicitNumericConversion(Type source, Type destination)
{
TypeCode tcSource = source.GetTypeCode();
TypeCode tcDest = destination.GetTypeCode();
switch (tcSource)
{
case TypeCode.SByte:
switch (tcDest)
{
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.Byte:
switch (tcDest)
{
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.Int16:
switch (tcDest)
{
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.UInt16:
switch (tcDest)
{
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.Int32:
switch (tcDest)
{
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.UInt32:
switch (tcDest)
{
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.Int64:
case TypeCode.UInt64:
switch (tcDest)
{
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.Char:
switch (tcDest)
{
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.Single:
return (tcDest == TypeCode.Double);
}
return false;
}
private static bool IsImplicitReferenceConversion(Type source, Type destination)
{
return destination.IsAssignableFrom(source);
}
private static bool IsImplicitBoxingConversion(Type source, Type destination)
{
if (source.IsValueType && (destination == typeof(object) || destination == typeof(ValueType)))
return true;
if (source.IsEnum && destination == typeof(Enum))
return true;
return false;
}
private static bool IsImplicitNullableConversion(Type source, Type destination)
{
if (IsNullableType(destination))
return IsImplicitlyConvertibleTo(GetNonNullableType(source), GetNonNullableType(destination));
return false;
}
public static Type FindGenericType(Type definition, Type type)
{
while (type != null && type != typeof(object))
{
if (type.IsConstructedGenericType && AreEquivalent(type.GetGenericTypeDefinition(), definition))
{
return type;
}
if (definition.IsInterface)
{
foreach (Type itype in type.GetTypeInfo().ImplementedInterfaces)
{
Type found = FindGenericType(definition, itype);
if (found != null)
return found;
}
}
type = type.BaseType;
}
return null;
}
/// <summary>
/// Searches for an operator method on the type. The method must have
/// the specified signature, no generic arguments, and have the
/// SpecialName bit set. Also searches inherited operator methods.
///
/// NOTE: This was designed to satisfy the needs of op_True and
/// op_False, because we have to do runtime lookup for those. It may
/// not work right for unary operators in general.
/// </summary>
public static MethodInfo GetBooleanOperator(Type type, string name)
{
do
{
MethodInfo result = type.GetAnyStaticMethodValidated(name, new Type[] { type });
if (result != null && result.IsSpecialName && !result.ContainsGenericParameters)
{
return result;
}
type = type.BaseType;
} while (type != null);
return null;
}
public static Type GetNonRefType(this Type type)
{
return type.IsByRef ? type.GetElementType() : type;
}
#if FEATURE_COMPILE
internal static bool IsUnsigned(this Type type) => IsUnsigned(GetNonNullableType(type).GetTypeCode());
internal static bool IsUnsigned(this TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.Char:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
internal static bool IsFloatingPoint(this Type type) => IsFloatingPoint(GetNonNullableType(type).GetTypeCode());
internal static bool IsFloatingPoint(this TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Single:
case TypeCode.Double:
return true;
default:
return false;
}
}
#endif
public static bool IsVector(this Type type)
{
// Unfortunately, the IsSzArray property of System.Type is inaccessible to us,
// so we use a little equality comparison trick instead. This omission is being
// tracked at https://github.com/dotnet/coreclr/issues/1877.
return type == type.GetElementType().MakeArrayType();
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcgv = Google.Cloud.Gaming.V1;
using sys = System;
namespace Google.Cloud.Gaming.V1
{
/// <summary>Resource name for the <c>GameServerDeployment</c> resource.</summary>
public sealed partial class GameServerDeploymentName : gax::IResourceName, sys::IEquatable<GameServerDeploymentName>
{
/// <summary>The possible contents of <see cref="GameServerDeploymentName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>.
/// </summary>
ProjectLocationDeployment = 1,
}
private static gax::PathTemplate s_projectLocationDeployment = new gax::PathTemplate("projects/{project}/locations/{location}/gameServerDeployments/{deployment}");
/// <summary>Creates a <see cref="GameServerDeploymentName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="GameServerDeploymentName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static GameServerDeploymentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new GameServerDeploymentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="GameServerDeploymentName"/> with the pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="GameServerDeploymentName"/> constructed from the provided ids.
/// </returns>
public static GameServerDeploymentName FromProjectLocationDeployment(string projectId, string locationId, string deploymentId) =>
new GameServerDeploymentName(ResourceNameType.ProjectLocationDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GameServerDeploymentName"/> with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GameServerDeploymentName"/> with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string deploymentId) =>
FormatProjectLocationDeployment(projectId, locationId, deploymentId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GameServerDeploymentName"/> with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GameServerDeploymentName"/> with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>.
/// </returns>
public static string FormatProjectLocationDeployment(string projectId, string locationId, string deploymentId) =>
s_projectLocationDeployment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="GameServerDeploymentName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="gameServerDeploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="GameServerDeploymentName"/> if successful.</returns>
public static GameServerDeploymentName Parse(string gameServerDeploymentName) =>
Parse(gameServerDeploymentName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="GameServerDeploymentName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="gameServerDeploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="GameServerDeploymentName"/> if successful.</returns>
public static GameServerDeploymentName Parse(string gameServerDeploymentName, bool allowUnparsed) =>
TryParse(gameServerDeploymentName, allowUnparsed, out GameServerDeploymentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GameServerDeploymentName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="gameServerDeploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GameServerDeploymentName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string gameServerDeploymentName, out GameServerDeploymentName result) =>
TryParse(gameServerDeploymentName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GameServerDeploymentName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="gameServerDeploymentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GameServerDeploymentName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string gameServerDeploymentName, bool allowUnparsed, out GameServerDeploymentName result)
{
gax::GaxPreconditions.CheckNotNull(gameServerDeploymentName, nameof(gameServerDeploymentName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationDeployment.TryParseName(gameServerDeploymentName, out resourceName))
{
result = FromProjectLocationDeployment(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(gameServerDeploymentName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private GameServerDeploymentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string deploymentId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
DeploymentId = deploymentId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="GameServerDeploymentName"/> class from the component parts of
/// pattern <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
public GameServerDeploymentName(string projectId, string locationId, string deploymentId) : this(ResourceNameType.ProjectLocationDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Deployment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DeploymentId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationDeployment: return s_projectLocationDeployment.Expand(ProjectId, LocationId, DeploymentId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as GameServerDeploymentName);
/// <inheritdoc/>
public bool Equals(GameServerDeploymentName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(GameServerDeploymentName a, GameServerDeploymentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(GameServerDeploymentName a, GameServerDeploymentName b) => !(a == b);
}
/// <summary>Resource name for the <c>GameServerDeploymentRollout</c> resource.</summary>
public sealed partial class GameServerDeploymentRolloutName : gax::IResourceName, sys::IEquatable<GameServerDeploymentRolloutName>
{
/// <summary>The possible contents of <see cref="GameServerDeploymentRolloutName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>.
/// </summary>
ProjectLocationDeployment = 1,
}
private static gax::PathTemplate s_projectLocationDeployment = new gax::PathTemplate("projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout");
/// <summary>
/// Creates a <see cref="GameServerDeploymentRolloutName"/> containing an unparsed resource name.
/// </summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="GameServerDeploymentRolloutName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static GameServerDeploymentRolloutName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new GameServerDeploymentRolloutName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="GameServerDeploymentRolloutName"/> with the pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="GameServerDeploymentRolloutName"/> constructed from the provided ids.
/// </returns>
public static GameServerDeploymentRolloutName FromProjectLocationDeployment(string projectId, string locationId, string deploymentId) =>
new GameServerDeploymentRolloutName(ResourceNameType.ProjectLocationDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GameServerDeploymentRolloutName"/> with
/// pattern <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GameServerDeploymentRolloutName"/> with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>.
/// </returns>
public static string Format(string projectId, string locationId, string deploymentId) =>
FormatProjectLocationDeployment(projectId, locationId, deploymentId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GameServerDeploymentRolloutName"/> with
/// pattern <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="GameServerDeploymentRolloutName"/> with pattern
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>.
/// </returns>
public static string FormatProjectLocationDeployment(string projectId, string locationId, string deploymentId) =>
s_projectLocationDeployment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="GameServerDeploymentRolloutName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="gameServerDeploymentRolloutName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="GameServerDeploymentRolloutName"/> if successful.</returns>
public static GameServerDeploymentRolloutName Parse(string gameServerDeploymentRolloutName) =>
Parse(gameServerDeploymentRolloutName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="GameServerDeploymentRolloutName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="gameServerDeploymentRolloutName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="GameServerDeploymentRolloutName"/> if successful.</returns>
public static GameServerDeploymentRolloutName Parse(string gameServerDeploymentRolloutName, bool allowUnparsed) =>
TryParse(gameServerDeploymentRolloutName, allowUnparsed, out GameServerDeploymentRolloutName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GameServerDeploymentRolloutName"/>
/// instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="gameServerDeploymentRolloutName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GameServerDeploymentRolloutName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string gameServerDeploymentRolloutName, out GameServerDeploymentRolloutName result) =>
TryParse(gameServerDeploymentRolloutName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GameServerDeploymentRolloutName"/>
/// instance; optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="gameServerDeploymentRolloutName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GameServerDeploymentRolloutName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string gameServerDeploymentRolloutName, bool allowUnparsed, out GameServerDeploymentRolloutName result)
{
gax::GaxPreconditions.CheckNotNull(gameServerDeploymentRolloutName, nameof(gameServerDeploymentRolloutName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationDeployment.TryParseName(gameServerDeploymentRolloutName, out resourceName))
{
result = FromProjectLocationDeployment(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(gameServerDeploymentRolloutName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private GameServerDeploymentRolloutName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string deploymentId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
DeploymentId = deploymentId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="GameServerDeploymentRolloutName"/> class from the component parts
/// of pattern <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param>
public GameServerDeploymentRolloutName(string projectId, string locationId, string deploymentId) : this(ResourceNameType.ProjectLocationDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Deployment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DeploymentId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationDeployment: return s_projectLocationDeployment.Expand(ProjectId, LocationId, DeploymentId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as GameServerDeploymentRolloutName);
/// <inheritdoc/>
public bool Equals(GameServerDeploymentRolloutName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(GameServerDeploymentRolloutName a, GameServerDeploymentRolloutName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(GameServerDeploymentRolloutName a, GameServerDeploymentRolloutName b) => !(a == b);
}
public partial class ListGameServerDeploymentsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetGameServerDeploymentRequest
{
/// <summary>
/// <see cref="gcgv::GameServerDeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::GameServerDeploymentName GameServerDeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetGameServerDeploymentRolloutRequest
{
/// <summary>
/// <see cref="gcgv::GameServerDeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::GameServerDeploymentName GameServerDeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateGameServerDeploymentRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteGameServerDeploymentRequest
{
/// <summary>
/// <see cref="gcgv::GameServerDeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::GameServerDeploymentName GameServerDeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GameServerDeployment
{
/// <summary>
/// <see cref="gcgv::GameServerDeploymentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::GameServerDeploymentName GameServerDeploymentName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GameServerDeploymentRollout
{
/// <summary>
/// <see cref="gcgv::GameServerDeploymentRolloutName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
public gcgv::GameServerDeploymentRolloutName GameServerDeploymentRolloutName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentRolloutName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/*
* Copyright (c) 2009 Jim Radford http://www.jimradford.com
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Microsoft.Win32;
using WeifenLuo.WinFormsUI.Docking;
using log4net;
using System.Xml.Serialization;
using System.IO;
using System.Collections;
using System.Reflection;
namespace SuperPutty.Data
{
public enum ConnectionProtocol
{
SSH,
SSH2,
Telnet,
Rlogin,
Raw,
Serial,
Cygterm,
Mintty,
Auto
}
public class SessionData : IComparable, ICloneable
{
private static readonly ILog Log = LogManager.GetLogger(typeof(SessionData));
/// <summary>
/// Full session id (includes path for session tree)
/// </summary>
private string _SessionId;
[XmlAttribute]
public string SessionId
{
get { return this._SessionId; }
set
{
this.OldSessionId = SessionId;
this._SessionId = value;
}
}
internal string OldSessionId { get; set; }
private string _OldName;
[XmlIgnore]
public string OldName
{
get { return _OldName; }
set { _OldName = value; }
}
private string _SessionName;
[XmlAttribute]
public string SessionName
{
get { return _SessionName; }
set { OldName = _SessionName;
_SessionName = value;
if (SessionId == null)
{
SessionId = value;
}
}
}
private string _ImageKey;
[XmlAttribute]
public string ImageKey
{
get { return _ImageKey; }
set { _ImageKey = value; }
}
private string _Host;
[XmlAttribute]
public string Host
{
get { return _Host; }
set { _Host = value; }
}
private int _Port;
[XmlAttribute]
public int Port
{
get { return _Port; }
set { _Port = value; }
}
private ConnectionProtocol _Proto;
[XmlAttribute]
public ConnectionProtocol Proto
{
get { return _Proto; }
set { _Proto = value; }
}
private string _PuttySession;
[XmlAttribute]
public string PuttySession
{
get { return _PuttySession; }
set { _PuttySession = value; }
}
private string _Username;
[XmlAttribute]
public string Username
{
get { return _Username; }
set { _Username = value; }
}
private string _Password;
[XmlIgnore]
public string Password
{
get { return _Password; }
set { _Password = value; }
}
private string _ExtraArgs;
[XmlAttribute]
public string ExtraArgs
{
get { return _ExtraArgs; }
set { _ExtraArgs = value; }
}
/* Unused...ignore for now
private string _LastPath = ".";
public string LastPath
{
get { return _LastPath; }
set { _LastPath = value; }
}*/
private DockState m_LastDockstate = DockState.Document;
[XmlIgnore]
public DockState LastDockstate
{
get { return m_LastDockstate; }
set { m_LastDockstate = value; }
}
private bool m_AutoStartSession = false;
[XmlIgnore]
public bool AutoStartSession
{
get { return m_AutoStartSession; }
set { m_AutoStartSession = value; }
}
public SessionData(string sessionName, string hostName, int port, ConnectionProtocol protocol, string sessionConfig)
{
SessionName = sessionName;
Host = hostName;
Port = port;
Proto = protocol;
PuttySession = sessionConfig;
}
public SessionData()
{
Proto = ConnectionProtocol.Auto;
}
internal void SaveToRegistry()
{
if (!String.IsNullOrEmpty(this.SessionName)
&& !String.IsNullOrEmpty(this.Host)
&& this.Port >= 0)
{
// detect if session was renamed
if (!String.IsNullOrEmpty(this.OldName) && this.OldName != this.SessionName)
{
RegistryRemove(this.OldName);
}
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Jim Radford\SuperPuTTY\Sessions\" + this.SessionName, true);
if (key == null)
{
key = Registry.CurrentUser.CreateSubKey(@"Software\Jim Radford\SuperPuTTY\Sessions\" + this.SessionName);
}
if (key != null)
{
key.SetValue("Host", this.Host);
key.SetValue("Port", this.Port);
key.SetValue("Proto", this.Proto);
key.SetValue("PuttySession", this.PuttySession);
if(!String.IsNullOrEmpty(this.Username))
key.SetValue("Login", this.Username);
//key.SetValue("Last Path", this.LastPath);
if(this.LastDockstate != DockState.Hidden && this.LastDockstate != DockState.Unknown)
key.SetValue("Last Dock", (int)this.LastDockstate);
key.SetValue("Auto Start", this.AutoStartSession);
if (this.SessionId != null)
{
key.SetValue("SessionId", this.SessionId);
}
key.Close();
}
else
{
Logger.Log("Unable to create registry key for " + this.SessionName);
}
}
}
void RegistryRemove(string sessionName)
{
if (!String.IsNullOrEmpty(sessionName))
{
Log.DebugFormat("Removing session, name={0}", sessionName);
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Jim Radford\SuperPuTTY\Sessions", true);
try
{
if (key.OpenSubKey(sessionName) != null)
{
key.DeleteSubKeyTree(sessionName);
key.Close();
}
}
catch (UnauthorizedAccessException e)
{
Logger.Log(e);
}
}
}
/// <summary>
/// Read any existing saved sessions from the registry, decode and populate a list containing the data
/// </summary>
/// <returns>A list containing the entries retrieved from the registry</returns>
public static List<SessionData> LoadSessionsFromRegistry()
{
Log.Info("LoadSessionsFromRegistry...");
List<SessionData> sessionList = new List<SessionData>();
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Jim Radford\SuperPuTTY\Sessions");
if (key != null)
{
string[] sessionKeys = key.GetSubKeyNames();
foreach (string session in sessionKeys)
{
SessionData sessionData = new SessionData();
RegistryKey itemKey = key.OpenSubKey(session);
if (itemKey != null)
{
sessionData.Host = (string)itemKey.GetValue("Host", "");
sessionData.Port = (int)itemKey.GetValue("Port", 22);
sessionData.Proto = (ConnectionProtocol)Enum.Parse(typeof(ConnectionProtocol), (string)itemKey.GetValue("Proto", "SSH"));
sessionData.PuttySession = (string)itemKey.GetValue("PuttySession", "Default Session");
sessionData.SessionName = session;
sessionData.SessionId = (string)itemKey.GetValue("SessionId", session);
sessionData.Username = (string)itemKey.GetValue("Login", "");
sessionData.LastDockstate = (DockState)itemKey.GetValue("Last Dock", DockState.Document);
sessionData.AutoStartSession = bool.Parse((string)itemKey.GetValue("Auto Start", "False"));
sessionList.Add(sessionData);
}
}
}
return sessionList;
}
public static List<SessionData> LoadSessionsFromFile(string fileName)
{
List<SessionData> sessions = new List<SessionData>();
if (File.Exists(fileName))
{
WorkaroundCygwinBug();
XmlSerializer s = new XmlSerializer(sessions.GetType());
using (TextReader r = new StreamReader(fileName))
{
sessions = (List<SessionData>)s.Deserialize(r);
}
Log.InfoFormat("Loaded {0} sessions from {1}", sessions.Count, fileName);
}
else
{
Log.WarnFormat("Could not load sessions, file doesn't exist. file={0}", fileName);
}
return sessions;
}
static void WorkaroundCygwinBug()
{
try
{
// work around known bug with cygwin
Dictionary<string, string> envVars = new Dictionary<string, string>();
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
{
string envVar = (string) de.Key;
if (envVars.ContainsKey(envVar.ToUpper()))
{
// duplicate found... (e.g. TMP and tmp)
Log.DebugFormat("Clearing duplicate envVariable, {0}", envVar);
Environment.SetEnvironmentVariable(envVar, null);
continue;
}
envVars.Add(envVar.ToUpper(), envVar);
}
}
catch (Exception ex)
{
Log.WarnFormat("Error working around cygwin issue: {0}", ex.Message);
}
}
public static void SaveSessionsToFile(List<SessionData> sessions, string fileName)
{
Log.InfoFormat("Saving {0} sessions to {1}", sessions.Count, fileName);
BackUpFiles(fileName, 20);
// sort and save file
sessions.Sort();
XmlSerializer s = new XmlSerializer(sessions.GetType());
using (TextWriter w = new StreamWriter(fileName))
{
s.Serialize(w, sessions);
}
}
private static void BackUpFiles(string fileName, int count)
{
if (File.Exists(fileName) && count > 0)
{
try
{
// backup
string fileBaseName = Path.GetFileNameWithoutExtension(fileName);
string dirName = Path.GetDirectoryName(fileName);
string backupName = Path.Combine(dirName, string.Format("{0}.{1:yyyyMMdd_hhmmss}.XML", fileBaseName, DateTime.Now));
File.Copy(fileName, backupName, true);
// limit last count saves
List<string> oldFiles = new List<string>(Directory.GetFiles(dirName, fileBaseName + ".*.XML"));
oldFiles.Sort();
oldFiles.Reverse();
if (oldFiles.Count > count)
{
for (int i = 20; i < oldFiles.Count; i++)
{
Log.InfoFormat("Cleaning up old file, {0}", oldFiles[i]);
File.Delete(oldFiles[i]);
}
}
}
catch (Exception ex)
{
Log.Error("Error backing up files", ex);
}
}
}
public int CompareTo(object obj)
{
SessionData s = obj as SessionData;
return s == null ? 1 : this.SessionId.CompareTo(s.SessionId);
}
public static string CombineSessionIds(string parent, string child)
{
if (parent == null && child == null)
{
return null;
}
else if (child == null)
{
return parent;
}
else if (parent == null)
{
return child;
}
else
{
return parent + "/" + child;
}
}
public static string GetSessionNameFromId(string sessionId)
{
string[] parts = GetSessionNameParts(sessionId);
return parts.Length > 0 ? parts[parts.Length - 1] : sessionId;
}
public static string[] GetSessionNameParts(string sessionId)
{
return sessionId.Split('/');
}
public static string GetSessionParentId(string sessionId)
{
string parentPath = null;
if (sessionId != null)
{
int idx = sessionId.LastIndexOf('/');
if (idx != -1)
{
parentPath = sessionId.Substring(0, idx);
}
}
return parentPath;
}
public object Clone()
{
SessionData session = new SessionData();
foreach (PropertyInfo pi in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (pi.CanWrite)
{
pi.SetValue(session, pi.GetValue(this, null), null);
}
}
return session;
}
public override string ToString()
{
if (this.Proto == ConnectionProtocol.Cygterm || this.Proto == ConnectionProtocol.Mintty)
{
return string.Format("{0}://{1}", this.Proto.ToString().ToLower(), this.Host);
}
else
{
return string.Format("{0}://{1}:{2}", this.Proto.ToString().ToLower(), this.Host, this.Port);
}
}
}
}
| |
using Lucene.Net.Codecs.Memory;
using Lucene.Net.Documents;
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Store;
using Lucene.Net.Support;
using Lucene.Net.Support.Threading;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Index
{
//using MemoryPostingsFormat = Lucene.Net.Codecs.memory.MemoryPostingsFormat;
using Codec = Lucene.Net.Codecs.Codec;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using TermQuery = Lucene.Net.Search.TermQuery;
using TopDocs = Lucene.Net.Search.TopDocs;
[TestFixture]
public class TestRollingUpdates : LuceneTestCase
{
// Just updates the same set of N docs over and over, to
// stress out deletions
[Test]
public virtual void TestRollingUpdates_Mem()
{
Random random = new Random(Random().Next());
BaseDirectoryWrapper dir = NewDirectory();
LineFileDocs docs = new LineFileDocs(random, DefaultCodecSupportsDocValues());
//provider.register(new MemoryCodec());
if ((!"Lucene3x".Equals(Codec.Default.Name)) && Random().NextBoolean())
{
Codec.Default =
TestUtil.AlwaysPostingsFormat(new MemoryPostingsFormat(Random().nextBoolean(), random.NextFloat()));
}
MockAnalyzer analyzer = new MockAnalyzer(Random());
analyzer.MaxTokenLength = TestUtil.NextInt(Random(), 1, IndexWriter.MAX_TERM_LENGTH);
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
int SIZE = AtLeast(20);
int id = 0;
IndexReader r = null;
IndexSearcher s = null;
int numUpdates = (int)(SIZE * (2 + (TEST_NIGHTLY ? 200 * Random().NextDouble() : 5 * Random().NextDouble())));
if (VERBOSE)
{
Console.WriteLine("TEST: numUpdates=" + numUpdates);
}
int updateCount = 0;
// TODO: sometimes update ids not in order...
for (int docIter = 0; docIter < numUpdates; docIter++)
{
Documents.Document doc = docs.NextDoc();
string myID = "" + id;
if (id == SIZE - 1)
{
id = 0;
}
else
{
id++;
}
if (VERBOSE)
{
Console.WriteLine(" docIter=" + docIter + " id=" + id);
}
((Field)doc.GetField("docid")).SetStringValue(myID);
Term idTerm = new Term("docid", myID);
bool doUpdate;
if (s != null && updateCount < SIZE)
{
TopDocs hits = s.Search(new TermQuery(idTerm), 1);
Assert.AreEqual(1, hits.TotalHits);
doUpdate = !w.TryDeleteDocument(r, hits.ScoreDocs[0].Doc);
if (VERBOSE)
{
if (doUpdate)
{
Console.WriteLine(" tryDeleteDocument failed");
}
else
{
Console.WriteLine(" tryDeleteDocument succeeded");
}
}
}
else
{
doUpdate = true;
if (VERBOSE)
{
Console.WriteLine(" no searcher: doUpdate=true");
}
}
updateCount++;
if (doUpdate)
{
w.UpdateDocument(idTerm, doc);
}
else
{
w.AddDocument(doc);
}
if (docIter >= SIZE && Random().Next(50) == 17)
{
if (r != null)
{
r.Dispose();
}
bool applyDeletions = Random().NextBoolean();
if (VERBOSE)
{
Console.WriteLine("TEST: reopen applyDeletions=" + applyDeletions);
}
r = w.GetReader(applyDeletions);
if (applyDeletions)
{
s = NewSearcher(r);
}
else
{
s = null;
}
Assert.IsTrue(!applyDeletions || r.NumDocs == SIZE, "applyDeletions=" + applyDeletions + " r.NumDocs=" + r.NumDocs + " vs SIZE=" + SIZE);
updateCount = 0;
}
}
if (r != null)
{
r.Dispose();
}
w.Commit();
Assert.AreEqual(SIZE, w.NumDocs);
w.Dispose();
TestIndexWriter.AssertNoUnreferencedFiles(dir, "leftover files after rolling updates");
docs.Dispose();
// LUCENE-4455:
SegmentInfos infos = new SegmentInfos();
infos.Read(dir);
long totalBytes = 0;
foreach (SegmentCommitInfo sipc in infos.Segments)
{
totalBytes += sipc.GetSizeInBytes();
}
long totalBytes2 = 0;
foreach (string fileName in dir.ListAll())
{
if (!fileName.StartsWith(IndexFileNames.SEGMENTS, StringComparison.Ordinal))
{
totalBytes2 += dir.FileLength(fileName);
}
}
Assert.AreEqual(totalBytes2, totalBytes);
dir.Dispose();
}
[Test]
public virtual void TestUpdateSameDoc()
{
Directory dir = NewDirectory();
LineFileDocs docs = new LineFileDocs(Random());
for (int r = 0; r < 3; r++)
{
IndexWriter w = new IndexWriter(dir, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2));
int numUpdates = AtLeast(20);
int numThreads = TestUtil.NextInt(Random(), 2, 6);
IndexingThread[] threads = new IndexingThread[numThreads];
for (int i = 0; i < numThreads; i++)
{
threads[i] = new IndexingThread(docs, w, numUpdates, NewStringField);
threads[i].Start();
}
for (int i = 0; i < numThreads; i++)
{
threads[i].Join();
}
w.Dispose();
}
IndexReader open = DirectoryReader.Open(dir);
Assert.AreEqual(1, open.NumDocs);
open.Dispose();
docs.Dispose();
dir.Dispose();
}
internal class IndexingThread : ThreadClass
{
internal readonly LineFileDocs Docs;
internal readonly IndexWriter Writer;
internal readonly int Num;
private readonly Func<string, string, Field.Store, Field> NewStringField;
/// <param name="newStringField">
/// LUCENENET specific
/// Passed in because <see cref="LuceneTestCase.NewStringField(string, string, Field.Store)"/>
/// is no longer static.
/// </param>
public IndexingThread(LineFileDocs docs, IndexWriter writer, int num, Func<string, string, Field.Store, Field> newStringField)
: base()
{
this.Docs = docs;
this.Writer = writer;
this.Num = num;
NewStringField = newStringField;
}
public override void Run()
{
try
{
DirectoryReader open = null;
for (int i = 0; i < Num; i++)
{
Documents.Document doc = new Documents.Document(); // docs.NextDoc();
doc.Add(NewStringField("id", "test", Field.Store.NO));
Writer.UpdateDocument(new Term("id", "test"), doc);
if (Random().Next(3) == 0)
{
if (open == null)
{
open = DirectoryReader.Open(Writer, true);
}
DirectoryReader reader = DirectoryReader.OpenIfChanged(open);
if (reader != null)
{
open.Dispose();
open = reader;
}
Assert.AreEqual(1, open.NumDocs, "iter: " + i + " numDocs: " + open.NumDocs + " del: " + open.NumDeletedDocs + " max: " + open.MaxDoc);
}
}
if (open != null)
{
open.Dispose();
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
/// <summary>
/// Char.System.IConvertible.ToType(Type, IFormatProvider)
/// Converts the value of the current Char object to an object of the specified type using
/// the specified IFormatProvider object.
/// </summary>
public class CharIConvertibleToType
{
public static int Main()
{
CharIConvertibleToType testObj = new CharIConvertibleToType();
TestLibrary.TestFramework.BeginTestCase("for method: Char.System.IConvertible.ToType(Type, IFormatProvider)");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
retVal = NegTest8() && retVal;
retVal = NegTest9() && retVal;
retVal = NegTest10() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_ID = "P001";
const string c_TEST_DESC = "PosTest1: Conversion to byte";
string errorDesc;
byte b;
object expectedObj;
object actualObj;
char ch;
b = TestLibrary.Generator.GetByte(-55);
ch = (char)b;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
NumberFormatInfo numberFormat = new NumberFormatInfo();
IFormatProvider provider = numberFormat;
IConvertible converter = ch;
expectedObj = b;
actualObj = converter.ToType(typeof(byte), numberFormat);
if (((byte)expectedObj != (byte)actualObj) || !(actualObj is byte))
{
errorDesc = string.Format("Byte value of character \\u{0:x} is not ", (int)ch);
errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")";
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_ID = "P002";
const string c_TEST_DESC = "PosTest2: Conversion to sbyte";
string errorDesc;
sbyte sb;
object expectedObj;
object actualObj;
char ch;
sb = (sbyte)(TestLibrary.Generator.GetByte(-55) % (sbyte.MaxValue + 1));
ch = (char)sb;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
NumberFormatInfo numberFormat = new NumberFormatInfo();
IFormatProvider provider = numberFormat;
IConvertible converter = ch;
expectedObj = sb;
actualObj = converter.ToType(typeof(sbyte), numberFormat);
if (((sbyte)expectedObj != (sbyte)actualObj) || !(actualObj is sbyte))
{
errorDesc = string.Format("SByte value of character \\u{0:x} is not ", (int)ch);
errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")";
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_ID = "P003";
const string c_TEST_DESC = "PosTest3: Conversion to Int16";
string errorDesc;
Int16 i;
object expectedObj;
object actualObj;
char ch;
i = (Int16)(TestLibrary.Generator.GetInt32(-55) % (Int16.MaxValue + 1));
ch = (char)i;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
NumberFormatInfo numberFormat = new NumberFormatInfo();
IFormatProvider provider = numberFormat;
IConvertible converter = ch;
expectedObj = i;
actualObj = converter.ToType(typeof(Int16), numberFormat);
if (((Int16)expectedObj != (Int16)actualObj) || !(actualObj is Int16))
{
errorDesc = string.Format("Int16 value of character \\u{0:x} is not ", (int)ch);
errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")";
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_ID = "P004";
const string c_TEST_DESC = "PosTest4: Conversion to UInt16";
string errorDesc;
UInt16 i;
object expectedObj;
object actualObj;
char ch;
i = (UInt16)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1));
ch = (char)i;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
NumberFormatInfo numberFormat = new NumberFormatInfo();
IFormatProvider provider = numberFormat;
IConvertible converter = ch;
expectedObj = i;
actualObj = converter.ToType(typeof(UInt16), numberFormat);
if (((UInt16)expectedObj != (UInt16)actualObj) || !(actualObj is UInt16))
{
errorDesc = string.Format("UInt16 value of character \\u{0:x} is not ", (int)ch);
errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
const string c_TEST_ID = "P005";
const string c_TEST_DESC = "PosTest5: Conversion to Int32";
string errorDesc;
int i;
object expectedObj;
object actualObj;
char ch;
i = TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1);
ch = (char)i;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
NumberFormatInfo numberFormat = new NumberFormatInfo();
IFormatProvider provider = numberFormat;
IConvertible converter = ch;
expectedObj = i;
actualObj = converter.ToType(typeof(int), numberFormat);
if (((int)expectedObj != (int)actualObj) || !(actualObj is int))
{
errorDesc = string.Format("Int32 value of character \\u{0:x} is not ", (int)ch);
errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")";
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
const string c_TEST_ID = "P006";
const string c_TEST_DESC = "PosTest6: Conversion to UInt32";
string errorDesc;
UInt32 i;
object expectedObj;
object actualObj;
char ch;
i = (UInt32)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1));
ch = (char)i;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
NumberFormatInfo numberFormat = new NumberFormatInfo();
IFormatProvider provider = numberFormat;
IConvertible converter = ch;
expectedObj = i;
actualObj = converter.ToType(typeof(UInt32), numberFormat);
if (((UInt32)expectedObj != (UInt32)actualObj) || !(actualObj is UInt32))
{
errorDesc = string.Format("UInt32 value of character \\u{0:x} is not ", (int)ch);
errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")";
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
const string c_TEST_ID = "P007";
const string c_TEST_DESC = "PosTest7: Conversion to Int64";
string errorDesc;
Int64 i;
object expectedObj;
object actualObj;
char ch;
i = TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1);
ch = (char)i;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
NumberFormatInfo numberFormat = new NumberFormatInfo();
IFormatProvider provider = numberFormat;
IConvertible converter = ch;
expectedObj = i;
actualObj = converter.ToType(typeof(Int64), numberFormat);
if (((Int64)expectedObj != (Int64)actualObj) || !(actualObj is Int64))
{
errorDesc = string.Format("Int64 value of character \\u{0:x} is not ", (int)ch);
errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")";
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
const string c_TEST_ID = "P008";
const string c_TEST_DESC = "PosTest8: Conversion to UInt64";
string errorDesc;
UInt64 i;
object expectedObj;
object actualObj;
char ch;
i = (UInt64)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1));
ch = (char)i;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
NumberFormatInfo numberFormat = new NumberFormatInfo();
IFormatProvider provider = numberFormat;
IConvertible converter = ch;
expectedObj = i;
actualObj = converter.ToType(typeof(UInt64), numberFormat);
if (((UInt64)expectedObj != (UInt64)actualObj) || !(actualObj is UInt64))
{
errorDesc = string.Format("UInt64 value of character \\u{0:x} is not ", (int)ch);
errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")";
TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
const string c_TEST_ID = "P009";
const string c_TEST_DESC = "PosTest9: Conversion to char";
string errorDesc;
object expectedObj;
object actualObj;
char ch;
ch = TestLibrary.Generator.GetChar(-55);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
IConvertible converter = ch;
expectedObj = ch;
actualObj = converter.ToType(typeof(char), null);
if (((char)expectedObj != (char)actualObj) || !(actualObj is char))
{
errorDesc = string.Format("char value of character \\u{0:x} is not ", (int)ch);
errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")";
TestLibrary.TestFramework.LogError("017" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("018" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest10()
{
bool retVal = true;
const string c_TEST_ID = "P010";
const string c_TEST_DESC = "PosTest10: Conversion to string";
string errorDesc;
object expectedObj;
object actualObj;
char ch;
ch = TestLibrary.Generator.GetChar(-55);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
IConvertible converter = ch;
expectedObj = new string(ch, 1);
actualObj = converter.ToType(typeof(string), null);
if (((string)expectedObj != (string)actualObj) || !(actualObj is string))
{
errorDesc = string.Format("string value of character \\u{0:x} is not ", (int)ch);
errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")";
TestLibrary.TestFramework.LogError("019" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("020" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//ArgumentNullException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: type is a null reference (Nothing in Visual Basic).";
string errorDesc;
char ch = TestLibrary.Generator.GetChar(-55);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
IConvertible converter = ch;
converter.ToType(null, null);
errorDesc = "ArgumentNullException is not thrown as expected.";
errorDesc += string.Format("\nThe character is \\u{0:x}", (int)ch);
TestLibrary.TestFramework.LogError("021" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentNullException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe character is \\u{0:x}", (int)ch);
TestLibrary.TestFramework.LogError("022" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//InvalidCastException
public bool NegTest2()
{
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: type is boolean";
return this.DoInvalidCastTest(c_TEST_ID, c_TEST_DESC, "023", "024", typeof(bool));
}
public bool NegTest3()
{
const string c_TEST_ID = "N003";
const string c_TEST_DESC = "NegTest3: type is double";
return this.DoInvalidCastTest(c_TEST_ID, c_TEST_DESC, "025", "026", typeof(double));
}
public bool NegTest4()
{
const string c_TEST_ID = "N004";
const string c_TEST_DESC = "NegTest4: type is single";
return this.DoInvalidCastTest(c_TEST_ID, c_TEST_DESC, "027", "028", typeof(Single));
}
public bool NegTest5()
{
const string c_TEST_ID = "N005";
const string c_TEST_DESC = "NegTest5: type is DateTime";
return this.DoInvalidCastTest(c_TEST_ID, c_TEST_DESC, "029", "030", typeof(DateTime));
}
public bool NegTest6()
{
const string c_TEST_ID = "N006";
const string c_TEST_DESC = "NegTest6: type is Decimal";
return this.DoInvalidCastTest(c_TEST_ID, c_TEST_DESC, "031", "032", typeof(Decimal));
}
public bool NegTest7()
{
const string c_TEST_ID = "N007";
const string c_TEST_DESC = "NegTest7: type is Decimal";
return this.DoInvalidCastTest(c_TEST_ID, c_TEST_DESC, "033", "034", typeof(Decimal));
}
//bug
//OverflowException
public bool NegTest8()
{
const string c_TEST_ID = "N008";
const string c_TEST_DESC = "NegTest8: Value is too large for destination type";
return this.DoOverflowTest(c_TEST_ID, c_TEST_DESC, "035", typeof(Int16), Int16.MaxValue);
}
public bool NegTest9()
{
const string c_TEST_ID = "N009";
const string c_TEST_DESC = "NegTest9: Value is too large for destination type";
return this.DoOverflowTest(c_TEST_ID, c_TEST_DESC, "036", typeof(byte), byte.MaxValue);
}
public bool NegTest10()
{
const string c_TEST_ID = "N010";
const string c_TEST_DESC = "NegTest10: Value is too large for destination type";
return this.DoOverflowTest(c_TEST_ID, c_TEST_DESC, "037", typeof(sbyte), sbyte.MaxValue);
}
#endregion
#region Helper methods for negative tests
private bool DoInvalidCastTest(string testId,
string testDesc,
string errorNum1,
string errorNum2,
Type destType)
{
bool retVal = true;
string errorDesc;
char ch = TestLibrary.Generator.GetChar(-55);
TestLibrary.TestFramework.BeginScenario(testDesc);
try
{
IConvertible converter = ch;
converter.ToType(destType, null);
errorDesc = "InvalidCastException is not thrown as expected.";
errorDesc += string.Format("\nThe character is \\u{0:x}", (int)ch);
TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc);
retVal = false;
}
catch (InvalidCastException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe character is \\u{0:x}", (int)ch);
TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc);
retVal = false;
}
return retVal;
}
private bool DoOverflowTest(string testId,
string testDesc,
string errorNum,
Type destType,
int destTypeMaxValue)
{
bool retVal = true;
string errorDesc;
int i;
char ch;
i = destTypeMaxValue + 1 +
TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue - destTypeMaxValue);
ch = (char)i;
TestLibrary.TestFramework.BeginScenario(testDesc);
try
{
IConvertible converter = ch;
converter.ToType(destType, null);
TestLibrary.TestFramework.LogError(errorNum + "TestId-" +testId,
"No OverflowException thrown when expected");
retVal = false;
}
catch (OverflowException)
{
TestLibrary.TestFramework.LogInformation("Caught expected overflow.");
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe character is \\u{0:x}", (int)ch);
TestLibrary.TestFramework.LogError(errorNum + " TestId-" + testId, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
[ToolboxItem(false)]
public partial class DockPane : UserControl, IDockDragSource
{
public enum AppearanceStyle
{
ToolWindow,
Document
}
private enum HitTestArea
{
Caption,
TabStrip,
Content,
None
}
private struct HitTestResult
{
public HitTestArea HitArea;
public int Index;
public HitTestResult(HitTestArea hitTestArea, int index)
{
HitArea = hitTestArea;
Index = index;
}
}
private DockPaneCaptionBase m_captionControl;
private DockPaneCaptionBase CaptionControl
{
get { return m_captionControl; }
}
private DockPaneStripBase m_tabStripControl;
internal DockPaneStripBase TabStripControl
{
get { return m_tabStripControl; }
}
internal protected DockPane(IDockContent content, DockState visibleState, bool show)
{
InternalConstruct(content, visibleState, false, Rectangle.Empty, null, DockAlignment.Right, 0.5, show);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
internal protected DockPane(IDockContent content, FloatWindow floatWindow, bool show)
{
if (floatWindow == null)
throw new ArgumentNullException("floatWindow");
InternalConstruct(content, DockState.Float, false, Rectangle.Empty, floatWindow.NestedPanes.GetDefaultPreviousPane(this), DockAlignment.Right, 0.5, show);
}
internal protected DockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, double proportion, bool show)
{
if (previousPane == null)
throw (new ArgumentNullException("previousPane"));
InternalConstruct(content, previousPane.DockState, false, Rectangle.Empty, previousPane, alignment, proportion, show);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
internal protected DockPane(IDockContent content, Rectangle floatWindowBounds, bool show)
{
InternalConstruct(content, DockState.Float, true, floatWindowBounds, null, DockAlignment.Right, 0.5, show);
}
private void InternalConstruct(IDockContent content, DockState dockState, bool flagBounds, Rectangle floatWindowBounds, DockPane prevPane, DockAlignment alignment, double proportion, bool show)
{
if (dockState == DockState.Hidden || dockState == DockState.Unknown)
throw new ArgumentException(Strings.DockPane_SetDockState_InvalidState);
if (content == null)
throw new ArgumentNullException(Strings.DockPane_Constructor_NullContent);
if (content.DockHandler.DockPanel == null)
throw new ArgumentException(Strings.DockPane_Constructor_NullDockPanel);
SuspendLayout();
SetStyle(ControlStyles.Selectable, false);
m_isFloat = (dockState == DockState.Float);
m_contents = new DockContentCollection();
m_displayingContents = new DockContentCollection(this);
m_dockPanel = content.DockHandler.DockPanel;
m_dockPanel.AddPane(this);
m_splitter = new SplitterControl(this);
m_nestedDockingStatus = new NestedDockingStatus(this);
m_captionControl = DockPanel.DockPaneCaptionFactory.CreateDockPaneCaption(this);
m_tabStripControl = DockPanel.DockPaneStripFactory.CreateDockPaneStrip(this);
Controls.AddRange(new Control[] { m_captionControl, m_tabStripControl });
DockPanel.SuspendLayout(true);
if (flagBounds)
FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds);
else if (prevPane != null)
DockTo(prevPane.NestedPanesContainer, prevPane, alignment, proportion);
SetDockState(dockState);
if (show)
content.DockHandler.Pane = this;
else if (this.IsFloat)
content.DockHandler.FloatPane = this;
else
content.DockHandler.PanelPane = this;
ResumeLayout();
DockPanel.ResumeLayout(true, true);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
m_dockState = DockState.Unknown;
if (NestedPanesContainer != null)
NestedPanesContainer.NestedPanes.Remove(this);
if (DockPanel != null)
{
DockPanel.RemovePane(this);
m_dockPanel = null;
}
Splitter.Dispose();
if (m_autoHidePane != null)
m_autoHidePane.Dispose();
}
base.Dispose(disposing);
}
private IDockContent m_activeContent = null;
public virtual IDockContent ActiveContent
{
get { return m_activeContent; }
set
{
if (ActiveContent == value)
return;
if (value != null)
{
if (!DisplayingContents.Contains(value))
throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue));
}
else
{
if (DisplayingContents.Count != 0)
throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue));
}
IDockContent oldValue = m_activeContent;
if (DockPanel.ActiveAutoHideContent == oldValue)
DockPanel.ActiveAutoHideContent = null;
m_activeContent = value;
if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document)
{
if (m_activeContent != null)
m_activeContent.DockHandler.Form.BringToFront();
}
else
{
if (m_activeContent != null)
m_activeContent.DockHandler.SetVisible();
if (oldValue != null && DisplayingContents.Contains(oldValue))
oldValue.DockHandler.SetVisible();
if (IsActivated && m_activeContent != null)
m_activeContent.DockHandler.Activate();
}
if (FloatWindow != null)
FloatWindow.SetText();
if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi &&
DockState == DockState.Document)
RefreshChanges(false); // delayed layout to reduce screen flicker
else
RefreshChanges();
if (m_activeContent != null)
TabStripControl.EnsureTabVisible(m_activeContent);
}
}
private bool m_allowDockDragAndDrop = true;
public virtual bool AllowDockDragAndDrop
{
get { return m_allowDockDragAndDrop; }
set { m_allowDockDragAndDrop = value; }
}
private IDisposable m_autoHidePane = null;
internal IDisposable AutoHidePane
{
get { return m_autoHidePane; }
set { m_autoHidePane = value; }
}
private object m_autoHideTabs = null;
internal object AutoHideTabs
{
get { return m_autoHideTabs; }
set { m_autoHideTabs = value; }
}
private object TabPageContextMenu
{
get
{
IDockContent content = ActiveContent;
if (content == null)
return null;
if (content.DockHandler.TabPageContextMenuStrip != null)
return content.DockHandler.TabPageContextMenuStrip;
else if (content.DockHandler.TabPageContextMenu != null)
return content.DockHandler.TabPageContextMenu;
else
return null;
}
}
internal bool HasTabPageContextMenu
{
get { return TabPageContextMenu != null; }
}
internal void ShowTabPageContextMenu(Control control, Point position)
{
object menu = TabPageContextMenu;
if (menu == null)
return;
ContextMenuStrip contextMenuStrip = menu as ContextMenuStrip;
if (contextMenuStrip != null)
{
contextMenuStrip.Show(control, position);
return;
}
ContextMenu contextMenu = menu as ContextMenu;
if (contextMenu != null)
contextMenu.Show(this, position);
}
private Rectangle CaptionRectangle
{
get
{
if (!HasCaption)
return Rectangle.Empty;
Rectangle rectWindow = DisplayingRectangle;
int x, y, width;
x = rectWindow.X;
y = rectWindow.Y;
width = rectWindow.Width;
int height = CaptionControl.MeasureHeight();
return new Rectangle(x, y, width, height);
}
}
internal Rectangle ContentRectangle
{
get
{
Rectangle rectWindow = DisplayingRectangle;
Rectangle rectCaption = CaptionRectangle;
Rectangle rectTabStrip = TabStripRectangle;
int x = rectWindow.X;
int y = rectWindow.Y + (rectCaption.IsEmpty ? 0 : rectCaption.Height);
if (DockState == DockState.Document && DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Top)
y += rectTabStrip.Height;
int width = rectWindow.Width;
int height = rectWindow.Height - rectCaption.Height - rectTabStrip.Height;
return new Rectangle(x, y, width, height);
}
}
internal Rectangle TabStripRectangle
{
get
{
if (Appearance == AppearanceStyle.ToolWindow)
return TabStripRectangle_ToolWindow;
else
return TabStripRectangle_Document;
}
}
private Rectangle TabStripRectangle_ToolWindow
{
get
{
if (DisplayingContents.Count <= 1 || IsAutoHide)
return Rectangle.Empty;
Rectangle rectWindow = DisplayingRectangle;
int width = rectWindow.Width;
int height = TabStripControl.MeasureHeight();
int x = rectWindow.X;
int y = rectWindow.Bottom - height;
Rectangle rectCaption = CaptionRectangle;
if (rectCaption.Contains(x, y))
y = rectCaption.Y + rectCaption.Height;
return new Rectangle(x, y, width, height);
}
}
private Rectangle TabStripRectangle_Document
{
get
{
if (DisplayingContents.Count == 0)
return Rectangle.Empty;
if (DisplayingContents.Count == 1 && DockPanel.DocumentStyle == DocumentStyle.DockingSdi)
return Rectangle.Empty;
Rectangle rectWindow = DisplayingRectangle;
int x = rectWindow.X;
int width = rectWindow.Width;
int height = TabStripControl.MeasureHeight();
int y = 0;
if (DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
y = rectWindow.Height - height;
else
y = rectWindow.Y;
return new Rectangle(x, y, width, height);
}
}
public virtual string CaptionText
{
get { return ActiveContent == null ? string.Empty : ActiveContent.DockHandler.TabText; }
}
private DockContentCollection m_contents;
public DockContentCollection Contents
{
get { return m_contents; }
}
private DockContentCollection m_displayingContents;
public DockContentCollection DisplayingContents
{
get { return m_displayingContents; }
}
private DockPanel m_dockPanel;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
private bool HasCaption
{
get
{
if (DockState == DockState.Document ||
DockState == DockState.Hidden ||
DockState == DockState.Unknown ||
(DockState == DockState.Float && FloatWindow.VisibleNestedPanes.Count <= 1))
return false;
else
return true;
}
}
private bool m_isActivated = false;
public bool IsActivated
{
get { return m_isActivated; }
}
internal void SetIsActivated(bool value)
{
if (m_isActivated == value)
return;
m_isActivated = value;
if (DockState != DockState.Document)
RefreshChanges(false);
OnIsActivatedChanged(EventArgs.Empty);
}
private bool m_isActiveDocumentPane = false;
public bool IsActiveDocumentPane
{
get { return m_isActiveDocumentPane; }
}
internal void SetIsActiveDocumentPane(bool value)
{
if (m_isActiveDocumentPane == value)
return;
m_isActiveDocumentPane = value;
if (DockState == DockState.Document)
RefreshChanges();
OnIsActiveDocumentPaneChanged(EventArgs.Empty);
}
public bool IsDockStateValid(DockState dockState)
{
foreach (IDockContent content in Contents)
if (!content.DockHandler.IsDockStateValid(dockState))
return false;
return true;
}
public bool IsAutoHide
{
get { return DockHelper.IsDockStateAutoHide(DockState); }
}
public AppearanceStyle Appearance
{
get { return (DockState == DockState.Document) ? AppearanceStyle.Document : AppearanceStyle.ToolWindow; }
}
internal Rectangle DisplayingRectangle
{
get { return ClientRectangle; }
}
public void Activate()
{
if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel.ActiveAutoHideContent != ActiveContent)
DockPanel.ActiveAutoHideContent = ActiveContent;
else if (!IsActivated && ActiveContent != null)
ActiveContent.DockHandler.Activate();
}
internal void AddContent(IDockContent content)
{
if (Contents.Contains(content))
return;
Contents.Add(content);
}
internal void Close()
{
Dispose();
}
public void CloseActiveContent()
{
CloseContent(ActiveContent);
}
internal void CloseContent(IDockContent content)
{
DockPanel dockPanel = DockPanel;
if (content == null)
return;
if (!content.DockHandler.CloseButton)
return;
dockPanel.SuspendLayout(true);
try
{
if (content.DockHandler.HideOnClose)
{
content.DockHandler.Hide();
NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this);
}
else
content.DockHandler.Close();
}
finally
{
dockPanel.ResumeLayout(true, true);
}
}
private HitTestResult GetHitTest(Point ptMouse)
{
Point ptMouseClient = PointToClient(ptMouse);
Rectangle rectCaption = CaptionRectangle;
if (rectCaption.Contains(ptMouseClient))
return new HitTestResult(HitTestArea.Caption, -1);
Rectangle rectContent = ContentRectangle;
if (rectContent.Contains(ptMouseClient))
return new HitTestResult(HitTestArea.Content, -1);
Rectangle rectTabStrip = TabStripRectangle;
if (rectTabStrip.Contains(ptMouseClient))
return new HitTestResult(HitTestArea.TabStrip, TabStripControl.HitTest(TabStripControl.PointToClient(ptMouse)));
return new HitTestResult(HitTestArea.None, -1);
}
private bool m_isHidden = true;
public bool IsHidden
{
get { return m_isHidden; }
}
private void SetIsHidden(bool value)
{
if (m_isHidden == value)
return;
m_isHidden = value;
if (DockHelper.IsDockStateAutoHide(DockState))
{
DockPanel.RefreshAutoHideStrip();
DockPanel.PerformLayout();
}
else if (NestedPanesContainer != null)
((Control)NestedPanesContainer).PerformLayout();
}
protected override void OnLayout(LayoutEventArgs levent)
{
SetIsHidden(DisplayingContents.Count == 0);
if (!IsHidden)
{
CaptionControl.Bounds = CaptionRectangle;
TabStripControl.Bounds = TabStripRectangle;
SetContentBounds();
foreach (IDockContent content in Contents)
{
if (DisplayingContents.Contains(content))
if (content.DockHandler.FlagClipWindow && content.DockHandler.Form.Visible)
content.DockHandler.FlagClipWindow = false;
}
}
base.OnLayout(levent);
}
internal void SetContentBounds()
{
Rectangle rectContent = ContentRectangle;
if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi)
rectContent = DockPanel.RectangleToMdiClient(RectangleToScreen(rectContent));
Rectangle rectInactive = new Rectangle(-rectContent.Width, rectContent.Y, rectContent.Width, rectContent.Height);
foreach (IDockContent content in Contents)
if (content.DockHandler.Pane == this)
{
if (content == ActiveContent)
content.DockHandler.Form.Bounds = rectContent;
else
content.DockHandler.Form.Bounds = rectInactive;
}
}
internal void RefreshChanges()
{
RefreshChanges(true);
}
private void RefreshChanges(bool performLayout)
{
if (IsDisposed)
return;
CaptionControl.RefreshChanges();
TabStripControl.RefreshChanges();
if (DockState == DockState.Float && FloatWindow != null)
FloatWindow.RefreshChanges();
if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel != null)
{
DockPanel.RefreshAutoHideStrip();
DockPanel.PerformLayout();
}
if (performLayout)
PerformLayout();
}
internal void RemoveContent(IDockContent content)
{
if (!Contents.Contains(content))
return;
Contents.Remove(content);
}
public void SetContentIndex(IDockContent content, int index)
{
int oldIndex = Contents.IndexOf(content);
if (oldIndex == -1)
throw (new ArgumentException(Strings.DockPane_SetContentIndex_InvalidContent));
if (index < 0 || index > Contents.Count - 1)
if (index != -1)
throw (new ArgumentOutOfRangeException(Strings.DockPane_SetContentIndex_InvalidIndex));
if (oldIndex == index)
return;
if (oldIndex == Contents.Count - 1 && index == -1)
return;
Contents.Remove(content);
if (index == -1)
Contents.Add(content);
else if (oldIndex < index)
Contents.AddAt(content, index - 1);
else
Contents.AddAt(content, index);
RefreshChanges();
}
private void SetParent()
{
if (DockState == DockState.Unknown || DockState == DockState.Hidden)
{
SetParent(null);
Splitter.Parent = null;
}
else if (DockState == DockState.Float)
{
SetParent(FloatWindow);
Splitter.Parent = FloatWindow;
}
else if (DockHelper.IsDockStateAutoHide(DockState))
{
SetParent(DockPanel.AutoHideControl);
Splitter.Parent = null;
}
else
{
SetParent(DockPanel.DockWindows[DockState]);
Splitter.Parent = Parent;
}
}
private void SetParent(Control value)
{
if (Parent == value)
return;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Workaround of .Net Framework bug:
// Change the parent of a control with focus may result in the first
// MDI child form get activated.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
IDockContent contentFocused = GetFocusedContent();
if (contentFocused != null)
DockPanel.SaveFocus();
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Parent = value;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Workaround of .Net Framework bug:
// Change the parent of a control with focus may result in the first
// MDI child form get activated.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (contentFocused != null)
contentFocused.DockHandler.Activate();
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
public new void Show()
{
Activate();
}
internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline)
{
if (!dragSource.CanDockTo(this))
return;
Point ptMouse = Control.MousePosition;
HitTestResult hitTestResult = GetHitTest(ptMouse);
if (hitTestResult.HitArea == HitTestArea.Caption)
dockOutline.Show(this, -1);
else if (hitTestResult.HitArea == HitTestArea.TabStrip && hitTestResult.Index != -1)
dockOutline.Show(this, hitTestResult.Index);
}
internal void ValidateActiveContent()
{
if (ActiveContent == null)
{
if (DisplayingContents.Count != 0)
ActiveContent = DisplayingContents[0];
return;
}
if (DisplayingContents.IndexOf(ActiveContent) >= 0)
return;
IDockContent prevVisible = null;
for (int i = Contents.IndexOf(ActiveContent) - 1; i >= 0; i--)
if (Contents[i].DockHandler.DockState == DockState)
{
prevVisible = Contents[i];
break;
}
IDockContent nextVisible = null;
for (int i = Contents.IndexOf(ActiveContent) + 1; i < Contents.Count; i++)
if (Contents[i].DockHandler.DockState == DockState)
{
nextVisible = Contents[i];
break;
}
if (prevVisible != null)
ActiveContent = prevVisible;
else if (nextVisible != null)
ActiveContent = nextVisible;
else
ActiveContent = null;
}
private static readonly object DockStateChangedEvent = new object();
public event EventHandler DockStateChanged
{
add { Events.AddHandler(DockStateChangedEvent, value); }
remove { Events.RemoveHandler(DockStateChangedEvent, value); }
}
protected virtual void OnDockStateChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[DockStateChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object IsActivatedChangedEvent = new object();
public event EventHandler IsActivatedChanged
{
add { Events.AddHandler(IsActivatedChangedEvent, value); }
remove { Events.RemoveHandler(IsActivatedChangedEvent, value); }
}
protected virtual void OnIsActivatedChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[IsActivatedChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object IsActiveDocumentPaneChangedEvent = new object();
public event EventHandler IsActiveDocumentPaneChanged
{
add { Events.AddHandler(IsActiveDocumentPaneChangedEvent, value); }
remove { Events.RemoveHandler(IsActiveDocumentPaneChangedEvent, value); }
}
protected virtual void OnIsActiveDocumentPaneChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[IsActiveDocumentPaneChangedEvent];
if (handler != null)
handler(this, e);
}
public DockWindow DockWindow
{
get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as DockWindow; }
set
{
DockWindow oldValue = DockWindow;
if (oldValue == value)
return;
DockTo(value);
}
}
public FloatWindow FloatWindow
{
get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as FloatWindow; }
set
{
FloatWindow oldValue = FloatWindow;
if (oldValue == value)
return;
DockTo(value);
}
}
private NestedDockingStatus m_nestedDockingStatus;
public NestedDockingStatus NestedDockingStatus
{
get { return m_nestedDockingStatus; }
}
private bool m_isFloat;
public bool IsFloat
{
get { return m_isFloat; }
}
public INestedPanesContainer NestedPanesContainer
{
get
{
if (NestedDockingStatus.NestedPanes == null)
return null;
else
return NestedDockingStatus.NestedPanes.Container;
}
}
private DockState m_dockState = DockState.Unknown;
public DockState DockState
{
get { return m_dockState; }
set
{
SetDockState(value);
}
}
public DockPane SetDockState(DockState value)
{
if (value == DockState.Unknown || value == DockState.Hidden)
throw new InvalidOperationException(Strings.DockPane_SetDockState_InvalidState);
if ((value == DockState.Float) == this.IsFloat)
{
InternalSetDockState(value);
return this;
}
if (DisplayingContents.Count == 0)
return null;
IDockContent firstContent = null;
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(value))
{
firstContent = content;
break;
}
}
if (firstContent == null)
return null;
firstContent.DockHandler.DockState = value;
DockPane pane = firstContent.DockHandler.Pane;
DockPanel.SuspendLayout(true);
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(value))
content.DockHandler.Pane = pane;
}
DockPanel.ResumeLayout(true, true);
return pane;
}
private void InternalSetDockState(DockState value)
{
if (m_dockState == value)
return;
DockState oldDockState = m_dockState;
INestedPanesContainer oldContainer = NestedPanesContainer;
m_dockState = value;
SuspendRefreshStateChange();
IDockContent contentFocused = GetFocusedContent();
if (contentFocused != null)
DockPanel.SaveFocus();
if (!IsFloat)
DockWindow = DockPanel.DockWindows[DockState];
else if (FloatWindow == null)
FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this);
if (contentFocused != null)
DockPanel.ContentFocusManager.Activate(contentFocused);
ResumeRefreshStateChange(oldContainer, oldDockState);
DockPanel.InvokeDockStateChanged(); //2015 - haha01haha01
}
private int m_countRefreshStateChange = 0;
private void SuspendRefreshStateChange()
{
m_countRefreshStateChange++;
DockPanel.SuspendLayout(true);
}
private void ResumeRefreshStateChange()
{
m_countRefreshStateChange--;
System.Diagnostics.Debug.Assert(m_countRefreshStateChange >= 0);
DockPanel.ResumeLayout(true, true);
}
private bool IsRefreshStateChangeSuspended
{
get { return m_countRefreshStateChange != 0; }
}
private void ResumeRefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState)
{
ResumeRefreshStateChange();
RefreshStateChange(oldContainer, oldDockState);
}
private void RefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState)
{
lock (this)
{
if (IsRefreshStateChangeSuspended)
return;
SuspendRefreshStateChange();
}
DockPanel.SuspendLayout(true);
IDockContent contentFocused = GetFocusedContent();
if (contentFocused != null)
DockPanel.SaveFocus();
SetParent();
if (ActiveContent != null)
ActiveContent.DockHandler.SetDockState(ActiveContent.DockHandler.IsHidden, DockState, ActiveContent.DockHandler.Pane);
foreach (IDockContent content in Contents)
{
if (content.DockHandler.Pane == this)
content.DockHandler.SetDockState(content.DockHandler.IsHidden, DockState, content.DockHandler.Pane);
}
if (oldContainer != null)
{
Control oldContainerControl = (Control)oldContainer;
if (oldContainer.DockState == oldDockState && !oldContainerControl.IsDisposed)
oldContainerControl.PerformLayout();
}
if (DockHelper.IsDockStateAutoHide(oldDockState))
DockPanel.RefreshActiveAutoHideContent();
if (NestedPanesContainer.DockState == DockState)
((Control)NestedPanesContainer).PerformLayout();
if (DockHelper.IsDockStateAutoHide(DockState))
DockPanel.RefreshActiveAutoHideContent();
if (DockHelper.IsDockStateAutoHide(oldDockState) ||
DockHelper.IsDockStateAutoHide(DockState))
{
DockPanel.RefreshAutoHideStrip();
DockPanel.PerformLayout();
}
ResumeRefreshStateChange();
if (contentFocused != null)
contentFocused.DockHandler.Activate();
DockPanel.ResumeLayout(true, true);
if (oldDockState != DockState)
OnDockStateChanged(EventArgs.Empty);
}
private IDockContent GetFocusedContent()
{
IDockContent contentFocused = null;
foreach (IDockContent content in Contents)
{
if (content.DockHandler.Form.ContainsFocus)
{
contentFocused = content;
break;
}
}
return contentFocused;
}
public DockPane DockTo(INestedPanesContainer container)
{
if (container == null)
throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer);
DockAlignment alignment;
if (container.DockState == DockState.DockLeft || container.DockState == DockState.DockRight)
alignment = DockAlignment.Bottom;
else
alignment = DockAlignment.Right;
return DockTo(container, container.NestedPanes.GetDefaultPreviousPane(this), alignment, 0.5);
}
public DockPane DockTo(INestedPanesContainer container, DockPane previousPane, DockAlignment alignment, double proportion)
{
if (container == null)
throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer);
if (container.IsFloat == this.IsFloat)
{
InternalAddToDockList(container, previousPane, alignment, proportion);
return this;
}
IDockContent firstContent = GetFirstContent(container.DockState);
if (firstContent == null)
return null;
DockPane pane;
DockPanel.DummyContent.DockPanel = DockPanel;
if (container.IsFloat)
pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, (FloatWindow)container, true);
else
pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, container.DockState, true);
pane.DockTo(container, previousPane, alignment, proportion);
SetVisibleContentsToPane(pane);
DockPanel.DummyContent.DockPanel = null;
return pane;
}
private void SetVisibleContentsToPane(DockPane pane)
{
SetVisibleContentsToPane(pane, ActiveContent);
}
private void SetVisibleContentsToPane(DockPane pane, IDockContent activeContent)
{
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(pane.DockState))
{
content.DockHandler.Pane = pane;
i--;
}
}
if (activeContent.DockHandler.Pane == pane)
pane.ActiveContent = activeContent;
}
private void InternalAddToDockList(INestedPanesContainer container, DockPane prevPane, DockAlignment alignment, double proportion)
{
if ((container.DockState == DockState.Float) != IsFloat)
throw new InvalidOperationException(Strings.DockPane_DockTo_InvalidContainer);
int count = container.NestedPanes.Count;
if (container.NestedPanes.Contains(this))
count--;
if (prevPane == null && count > 0)
throw new InvalidOperationException(Strings.DockPane_DockTo_NullPrevPane);
if (prevPane != null && !container.NestedPanes.Contains(prevPane))
throw new InvalidOperationException(Strings.DockPane_DockTo_NoPrevPane);
if (prevPane == this)
throw new InvalidOperationException(Strings.DockPane_DockTo_SelfPrevPane);
INestedPanesContainer oldContainer = NestedPanesContainer;
DockState oldDockState = DockState;
container.NestedPanes.Add(this);
NestedDockingStatus.SetStatus(container.NestedPanes, prevPane, alignment, proportion);
if (DockHelper.IsDockWindowState(DockState))
m_dockState = container.DockState;
RefreshStateChange(oldContainer, oldDockState);
}
public void SetNestedDockingProportion(double proportion)
{
NestedDockingStatus.SetStatus(NestedDockingStatus.NestedPanes, NestedDockingStatus.PreviousPane, NestedDockingStatus.Alignment, proportion);
if (NestedPanesContainer != null)
((Control)NestedPanesContainer).PerformLayout();
}
public DockPane Float()
{
DockPanel.SuspendLayout(true);
IDockContent activeContent = ActiveContent;
DockPane floatPane = GetFloatPaneFromContents();
if (floatPane == null)
{
IDockContent firstContent = GetFirstContent(DockState.Float);
if (firstContent == null)
{
DockPanel.ResumeLayout(true, true);
return null;
}
floatPane = DockPanel.DockPaneFactory.CreateDockPane(firstContent, DockState.Float, true);
}
SetVisibleContentsToPane(floatPane, activeContent);
DockPanel.ResumeLayout(true, true);
return floatPane;
}
private DockPane GetFloatPaneFromContents()
{
DockPane floatPane = null;
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (!content.DockHandler.IsDockStateValid(DockState.Float))
continue;
if (floatPane != null && content.DockHandler.FloatPane != floatPane)
return null;
else
floatPane = content.DockHandler.FloatPane;
}
return floatPane;
}
private IDockContent GetFirstContent(DockState dockState)
{
for (int i = 0; i < DisplayingContents.Count; i++)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(dockState))
return content;
}
return null;
}
public void RestoreToPanel()
{
DockPanel.SuspendLayout(true);
IDockContent activeContent = DockPanel.ActiveContent;
for (int i = DisplayingContents.Count - 1; i >= 0; i--)
{
IDockContent content = DisplayingContents[i];
if (content.DockHandler.CheckDockState(false) != DockState.Unknown)
content.DockHandler.IsFloat = false;
}
DockPanel.ResumeLayout(true, true);
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)Win32.Msgs.WM_MOUSEACTIVATE)
Activate();
base.WndProc(ref m);
}
#region IDockDragSource Members
#region IDragSource Members
Control IDragSource.DragControl
{
get { return this; }
}
#endregion
bool IDockDragSource.IsDockStateValid(DockState dockState)
{
return IsDockStateValid(dockState);
}
bool IDockDragSource.CanDockTo(DockPane pane)
{
if (!IsDockStateValid(pane.DockState))
return false;
if (pane == this)
return false;
return true;
}
Rectangle IDockDragSource.BeginDrag(Point ptMouse)
{
Point location = PointToScreen(new Point(0, 0));
Size size;
DockPane floatPane = ActiveContent.DockHandler.FloatPane;
if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1)
size = DockPanel.DefaultFloatWindowSize;
else
size = floatPane.FloatWindow.Size;
if (ptMouse.X > location.X + size.Width)
location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize;
return new Rectangle(location, size);
}
public void FloatAt(Rectangle floatWindowBounds)
{
if (FloatWindow == null || FloatWindow.NestedPanes.Count != 1)
FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds);
else
FloatWindow.Bounds = floatWindowBounds;
DockState = DockState.Float;
NestedDockingStatus.NestedPanes.Remove(this);
}
public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex)
{
if (dockStyle == DockStyle.Fill)
{
IDockContent activeContent = ActiveContent;
for (int i = Contents.Count - 1; i >= 0; i--)
{
IDockContent c = Contents[i];
if (c.DockHandler.DockState == DockState)
{
c.DockHandler.Pane = pane;
if (contentIndex != -1)
pane.SetContentIndex(c, contentIndex);
}
}
pane.ActiveContent = activeContent;
}
else
{
if (dockStyle == DockStyle.Left)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Left, 0.5);
else if (dockStyle == DockStyle.Right)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Right, 0.5);
else if (dockStyle == DockStyle.Top)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Top, 0.5);
else if (dockStyle == DockStyle.Bottom)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Bottom, 0.5);
DockState = pane.DockState;
}
}
public void DockTo(DockPanel panel, DockStyle dockStyle)
{
if (panel != DockPanel)
throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel");
if (dockStyle == DockStyle.Top)
DockState = DockState.DockTop;
else if (dockStyle == DockStyle.Bottom)
DockState = DockState.DockBottom;
else if (dockStyle == DockStyle.Left)
DockState = DockState.DockLeft;
else if (dockStyle == DockStyle.Right)
DockState = DockState.DockRight;
else if (dockStyle == DockStyle.Fill)
DockState = DockState.Document;
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
namespace imageviewer
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
private string [] folderFile = null;
private int selected = 0;
private int begin = 0;
private int end = 0;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Button button4;
private System.ComponentModel.IContainer components;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.panel1 = new System.Windows.Forms.Panel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.button4 = new System.Windows.Forms.Button();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel1.AutoScroll = true;
this.panel1.BackColor = System.Drawing.Color.Black;
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.panel1.Controls.Add(this.pictureBox1);
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(424, 248);
this.panel1.TabIndex = 0;
//
// pictureBox1
//
this.pictureBox1.Location = new System.Drawing.Point(8, 8);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// button1
//
this.button1.Location = new System.Drawing.Point(8, 256);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(128, 23);
this.button1.TabIndex = 1;
this.button1.Text = "<< Previous";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(152, 256);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(128, 23);
this.button2.TabIndex = 2;
this.button2.Text = "Open Folder";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(288, 256);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(128, 23);
this.button3.TabIndex = 3;
this.button3.Text = "Next >>";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// folderBrowserDialog1
//
this.folderBrowserDialog1.ShowNewFolderButton = false;
//
// timer1
//
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// button4
//
this.button4.Location = new System.Drawing.Point(8, 288);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(408, 23);
this.button4.TabIndex = 4;
this.button4.Text = "<< START Slide Show >>";
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(424, 317);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.panel1);
this.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Vision";
this.Load += new System.EventHandler(this.Form1_Load);
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button2_Click(object sender, System.EventArgs e)
{
if(folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
string [] part1=null, part2=null, part3=null;
part1 = Directory.GetFiles(folderBrowserDialog1.SelectedPath,"*.jpg");
part2 = Directory.GetFiles(folderBrowserDialog1.SelectedPath,"*.jpeg");
part3 = Directory.GetFiles(folderBrowserDialog1.SelectedPath,"*.bmp");
folderFile = new string[part1.Length + part2.Length + part3.Length];
Array.Copy(part1,0,folderFile,0,part1.Length);
Array.Copy(part2,0,folderFile,part1.Length,part2.Length);
Array.Copy(part3,0,folderFile,part1.Length + part2.Length,part3.Length);
selected = 0;
begin = 0;
end = folderFile.Length;
showImage(folderFile[selected]);
button1.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
}
}
private void showImage(string path)
{
Image imgtemp = Image.FromFile(path);
pictureBox1.Width = imgtemp.Width / 2;
pictureBox1.Height = imgtemp.Height / 2;
pictureBox1.Image = imgtemp;
}
private void prevImage()
{
if(selected == 0)
{
selected = folderFile.Length - 1;
showImage(folderFile[selected]);
}
else
{
selected = selected - 1;
showImage(folderFile[selected]);
}
}
private void nextImage()
{
if(selected == folderFile.Length - 1)
{
selected = 0;
showImage(folderFile[selected]);
}
else
{
selected = selected + 1;
showImage(folderFile[selected]);
}
}
private void button1_Click(object sender, System.EventArgs e)
{
prevImage();
}
private void button3_Click(object sender, System.EventArgs e)
{
nextImage();
}
private void timer1_Tick(object sender, System.EventArgs e)
{
nextImage();
}
private void button4_Click(object sender, System.EventArgs e)
{
if(timer1.Enabled == true)
{
timer1.Enabled = false;
button4.Text = "<< START Slide Show >>";
}
else
{
timer1.Enabled = true;
button4.Text = "<< STOP Slide Show >>";
}
}
private void Form1_Load(object sender, System.EventArgs e)
{
button1.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Internal.IL;
using Internal.JitInterface;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysisFramework;
namespace ILCompiler
{
public class CompilationOptions
{
public IReadOnlyDictionary<string, string> InputFilePaths;
public IReadOnlyDictionary<string, string> ReferenceFilePaths;
public string OutputFilePath;
public string SystemModuleName;
public TargetOS TargetOS;
public TargetArchitecture TargetArchitecture;
public bool MultiFile;
public bool IsCppCodeGen;
public bool NoLineNumbers;
public string DgmlLog;
public bool FullLog;
public bool Verbose;
}
public partial class Compilation : ICompilationRootProvider
{
private readonly CompilerTypeSystemContext _typeSystemContext;
private readonly CompilationOptions _options;
private readonly TypeInitialization _typeInitManager;
private NodeFactory _nodeFactory;
private DependencyAnalyzerBase<NodeFactory> _dependencyGraph;
private NameMangler _nameMangler = null;
private ILCompiler.CppCodeGen.CppWriter _cppWriter = null;
private CompilationModuleGroup _compilationModuleGroup;
public Compilation(CompilationOptions options)
{
_options = options;
_typeSystemContext = new CompilerTypeSystemContext(new TargetDetails(options.TargetArchitecture, options.TargetOS));
_typeSystemContext.InputFilePaths = options.InputFilePaths;
_typeSystemContext.ReferenceFilePaths = options.ReferenceFilePaths;
_typeSystemContext.SetSystemModule(_typeSystemContext.GetModuleForSimpleName(options.SystemModuleName));
_nameMangler = new NameMangler(this);
_typeInitManager = new TypeInitialization();
if (options.MultiFile)
{
_compilationModuleGroup = new MultiFileCompilationModuleGroup(_typeSystemContext, this);
}
else
{
_compilationModuleGroup = new SingleFileCompilationModuleGroup(_typeSystemContext, this);
}
}
public CompilerTypeSystemContext TypeSystemContext
{
get
{
return _typeSystemContext;
}
}
public NameMangler NameMangler
{
get
{
return _nameMangler;
}
}
public NodeFactory NodeFactory
{
get
{
return _nodeFactory;
}
}
public TextWriter Log
{
get;
set;
}
internal bool IsCppCodeGen
{
get
{
return _options.IsCppCodeGen;
}
}
internal CompilationOptions Options
{
get
{
return _options;
}
}
private ILProvider _methodILCache = new ILProvider();
public MethodIL GetMethodIL(MethodDesc method)
{
// Flush the cache when it grows too big
if (_methodILCache.Count > 1000)
_methodILCache= new ILProvider();
return _methodILCache.GetMethodIL(method);
}
private CorInfoImpl _corInfo;
public void CompileSingleFile()
{
NodeFactory.NameMangler = NameMangler;
_nodeFactory = new NodeFactory(_typeSystemContext, _typeInitManager, _compilationModuleGroup, _options.IsCppCodeGen);
// Choose which dependency graph implementation to use based on the amount of logging requested.
if (_options.DgmlLog == null)
{
// No log uses the NoLogStrategy
_dependencyGraph = new DependencyAnalyzer<NoLogStrategy<NodeFactory>, NodeFactory>(_nodeFactory, null);
}
else
{
if (_options.FullLog)
{
// Full log uses the full log strategy
_dependencyGraph = new DependencyAnalyzer<FullGraphLogStrategy<NodeFactory>, NodeFactory>(_nodeFactory, null);
}
else
{
// Otherwise, use the first mark strategy
_dependencyGraph = new DependencyAnalyzer<FirstMarkLogStrategy<NodeFactory>, NodeFactory>(_nodeFactory, null);
}
}
_nodeFactory.AttachToDependencyGraph(_dependencyGraph);
_compilationModuleGroup.AddWellKnownTypes();
_compilationModuleGroup.AddCompilationRoots();
if (_options.IsCppCodeGen)
{
_cppWriter = new CppCodeGen.CppWriter(this);
_dependencyGraph.ComputeDependencyRoutine += CppCodeGenComputeDependencyNodeDependencies;
var nodes = _dependencyGraph.MarkedNodeList;
_cppWriter.OutputCode(nodes, _compilationModuleGroup.StartupCodeMain);
}
else
{
_corInfo = new CorInfoImpl(this);
_dependencyGraph.ComputeDependencyRoutine += ComputeDependencyNodeDependencies;
var nodes = _dependencyGraph.MarkedNodeList;
ObjectWriter.EmitObject(_options.OutputFilePath, nodes, _nodeFactory);
}
if (_options.DgmlLog != null)
{
using (FileStream dgmlOutput = new FileStream(_options.DgmlLog, FileMode.Create))
{
DgmlWriter.WriteDependencyGraphToStream(dgmlOutput, _dependencyGraph);
dgmlOutput.Flush();
}
}
}
#region ICompilationRootProvider implementation
public void AddCompilationRoot(MethodDesc method, string reason, string exportName = null)
{
var methodEntryPoint = _nodeFactory.MethodEntrypoint(method);
_dependencyGraph.AddRoot(methodEntryPoint, reason);
if (exportName != null)
_nodeFactory.NodeAliases.Add(methodEntryPoint, exportName);
}
public void AddCompilationRoot(TypeDesc type, string reason)
{
_dependencyGraph.AddRoot(_nodeFactory.ConstructedTypeSymbol(type), reason);
}
#endregion
private void ComputeDependencyNodeDependencies(List<DependencyNodeCore<NodeFactory>> obj)
{
foreach (MethodCodeNode methodCodeNodeNeedingCode in obj)
{
MethodDesc method = methodCodeNodeNeedingCode.Method;
string methodName = method.ToString();
Log.WriteLine("Compiling " + methodName);
var methodIL = GetMethodIL(method);
if (methodIL == null)
return;
try
{
_corInfo.CompileMethod(methodCodeNodeNeedingCode);
}
catch (Exception e)
{
Log.WriteLine("*** " + method + ": " + e.Message);
// Call the __not_yet_implemented method
DependencyAnalysis.X64.X64Emitter emit = new DependencyAnalysis.X64.X64Emitter(_nodeFactory);
emit.Builder.RequireAlignment(_nodeFactory.Target.MinimumFunctionAlignment);
emit.Builder.DefinedSymbols.Add(methodCodeNodeNeedingCode);
emit.EmitLEAQ(emit.TargetRegister.Arg0, _nodeFactory.StringIndirection(method.ToString()));
DependencyAnalysis.X64.AddrMode loadFromArg0 =
new DependencyAnalysis.X64.AddrMode(emit.TargetRegister.Arg0, null, 0, 0, DependencyAnalysis.X64.AddrModeSize.Int64);
emit.EmitMOV(emit.TargetRegister.Arg0, ref loadFromArg0);
emit.EmitMOV(emit.TargetRegister.Arg0, ref loadFromArg0);
emit.EmitLEAQ(emit.TargetRegister.Arg1, _nodeFactory.StringIndirection(e.Message));
DependencyAnalysis.X64.AddrMode loadFromArg1 =
new DependencyAnalysis.X64.AddrMode(emit.TargetRegister.Arg1, null, 0, 0, DependencyAnalysis.X64.AddrModeSize.Int64);
emit.EmitMOV(emit.TargetRegister.Arg1, ref loadFromArg1);
emit.EmitMOV(emit.TargetRegister.Arg1, ref loadFromArg1);
emit.EmitJMP(_nodeFactory.ExternSymbol("__not_yet_implemented"));
methodCodeNodeNeedingCode.SetCode(emit.Builder.ToObjectData());
continue;
}
}
}
private void CppCodeGenComputeDependencyNodeDependencies(List<DependencyNodeCore<NodeFactory>> obj)
{
foreach (CppMethodCodeNode methodCodeNodeNeedingCode in obj)
{
_cppWriter.CompileMethod(methodCodeNodeNeedingCode);
}
}
private Dictionary<MethodDesc, DelegateInfo> _delegateInfos = new Dictionary<MethodDesc, DelegateInfo>();
public DelegateInfo GetDelegateCtor(MethodDesc target)
{
DelegateInfo info;
if (!_delegateInfos.TryGetValue(target, out info))
{
_delegateInfos.Add(target, info = new DelegateInfo(this, target));
}
return info;
}
/// <summary>
/// Gets an object representing the static data for RVA mapped fields from the PE image.
/// </summary>
public object GetFieldRvaData(FieldDesc field)
{
return _nodeFactory.ReadOnlyDataBlob(NameMangler.GetMangledFieldName(field),
((EcmaField)field).GetFieldRvaData(), _typeSystemContext.Target.PointerSize);
}
public bool HasLazyStaticConstructor(TypeDesc type)
{
return _typeInitManager.HasLazyStaticConstructor(type);
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentMigrator.Expressions;
using FluentMigrator.Runner.Extensions;
using FluentMigrator.Runner.Generators.Generic;
namespace FluentMigrator.Runner.Generators.SqlServer
{
public class SqlServer2000Generator : GenericGenerator
{
public SqlServer2000Generator()
: base(new SqlServerColumn(new SqlServer2000TypeMap()), new SqlServerQuoter())
{
}
protected SqlServer2000Generator(IColumn column)
: base(column, new SqlServerQuoter())
{
}
public override string RenameTable { get { return "sp_rename '{0}', '{1}'"; } }
public override string RenameColumn { get { return "sp_rename '{0}.{1}', '{2}'"; } }
public override string DropIndex { get { return "DROP INDEX {1}.{0}"; } }
public override string AddColumn { get { return "ALTER TABLE {0} ADD {1}"; } }
public virtual string IdentityInsert { get { return "SET IDENTITY_INSERT {0} {1}"; } }
public override string CreateConstraint { get { return "ALTER TABLE {0} ADD CONSTRAINT {1} {2}{3} ({4})"; } }
//Not need for the nonclusted keyword as it is the default mode
public override string GetClusterTypeString(CreateIndexExpression column)
{
return column.Index.IsClustered ? "CLUSTERED " : string.Empty;
}
protected string GetConstraintClusteringString(CreateConstraintExpression constraint)
{
object indexType;
if (!constraint.Constraint.AdditionalFeatures.TryGetValue(
SqlServerExtensions.ConstraintType, out indexType)) return string.Empty;
return (indexType.Equals(SqlServerConstraintType.Clustered)) ? " CLUSTERED" : " NONCLUSTERED";
}
public override string Generate(CreateConstraintExpression expression)
{
var constraintType = (expression.Constraint.IsPrimaryKeyConstraint) ? "PRIMARY KEY" : "UNIQUE";
var constraintClustering = GetConstraintClusteringString(expression);
string columns = String.Join(", ", expression.Constraint.Columns.Select(x => Quoter.QuoteColumnName(x)).ToArray());
return string.Format(CreateConstraint, Quoter.QuoteTableName(expression.Constraint.TableName),
Quoter.Quote(expression.Constraint.ConstraintName),
constraintType,
constraintClustering,
columns);
}
public override string Generate(RenameTableExpression expression)
{
return String.Format(RenameTable, Quoter.QuoteTableName(Quoter.QuoteCommand(expression.OldName)), Quoter.QuoteCommand(expression.NewName));
}
public override string Generate(RenameColumnExpression expression)
{
return String.Format(RenameColumn, Quoter.QuoteTableName(expression.TableName), Quoter.QuoteColumnName(Quoter.QuoteCommand(expression.OldName)), Quoter.QuoteCommand(expression.NewName));
}
public override string Generate(DeleteColumnExpression expression)
{
// before we drop a column, we have to drop any default value constraints in SQL Server
var builder = new StringBuilder();
foreach (string column in expression.ColumnNames)
{
if (expression.ColumnNames.First() != column) builder.AppendLine("GO");
BuildDelete(expression, column, builder);
}
return builder.ToString();
}
protected virtual void BuildDelete(DeleteColumnExpression expression, string columnName, StringBuilder builder)
{
builder.AppendLine(Generate(new DeleteDefaultConstraintExpression {
ColumnName = columnName,
SchemaName = expression.SchemaName,
TableName = expression.TableName
}));
builder.AppendLine();
builder.AppendLine(String.Format("-- now we can finally drop column" + Environment.NewLine + "ALTER TABLE {0} DROP COLUMN {1};",
Quoter.QuoteTableName(expression.TableName),
Quoter.QuoteColumnName(columnName)));
}
public override string Generate(AlterDefaultConstraintExpression expression)
{
// before we alter a default constraint on a column, we have to drop any default value constraints in SQL Server
var builder = new StringBuilder();
builder.AppendLine(Generate(new DeleteDefaultConstraintExpression
{
ColumnName = expression.ColumnName,
SchemaName = expression.SchemaName,
TableName = expression.TableName
}));
builder.AppendLine();
builder.Append(String.Format("-- create alter table command to create new default constraint as string and run it" + Environment.NewLine +"ALTER TABLE {0} WITH NOCHECK ADD CONSTRAINT {3} DEFAULT({2}) FOR {1};",
Quoter.QuoteTableName(expression.TableName),
Quoter.QuoteColumnName(expression.ColumnName),
Quoter.QuoteValue(expression.DefaultValue),
Quoter.QuoteConstraintName(SqlServerColumn.GetDefaultConstraintName(expression.TableName, expression.ColumnName))));
return builder.ToString();
}
public override string Generate(InsertDataExpression expression)
{
if (IsUsingIdentityInsert(expression))
{
return string.Format("{0}; {1}; {2}",
string.Format(IdentityInsert, Quoter.QuoteTableName(expression.TableName), "ON"),
base.Generate(expression),
string.Format(IdentityInsert, Quoter.QuoteTableName(expression.TableName), "OFF"));
}
return base.Generate(expression);
}
protected static bool IsUsingIdentityInsert(InsertDataExpression expression)
{
if (expression.AdditionalFeatures.ContainsKey(SqlServerExtensions.IdentityInsert))
{
return (bool)expression.AdditionalFeatures[SqlServerExtensions.IdentityInsert];
}
return false;
}
public override string Generate(CreateSequenceExpression expression)
{
return compatabilityMode.HandleCompatabilty("Sequences are not supported in SqlServer2000");
}
public override string Generate(DeleteSequenceExpression expression)
{
return compatabilityMode.HandleCompatabilty("Sequences are not supported in SqlServer2000");
}
public override string Generate(DeleteDefaultConstraintExpression expression)
{
string sql =
"DECLARE @default sysname, @sql nvarchar(4000);" + Environment.NewLine + Environment.NewLine +
"-- get name of default constraint" + Environment.NewLine +
"SELECT @default = name" + Environment.NewLine +
"FROM sys.default_constraints" + Environment.NewLine +
"WHERE parent_object_id = object_id('{0}')" + Environment.NewLine +
"AND type = 'D'" + Environment.NewLine +
"AND parent_column_id = (" + Environment.NewLine +
"SELECT column_id" + Environment.NewLine +
"FROM sys.columns" + Environment.NewLine +
"WHERE object_id = object_id('{0}')" + Environment.NewLine +
"AND name = '{1}'" + Environment.NewLine +
");" + Environment.NewLine + Environment.NewLine +
"-- create alter table command to drop constraint as string and run it" + Environment.NewLine +
"SET @sql = N'ALTER TABLE {0} DROP CONSTRAINT ' + @default;" + Environment.NewLine +
"EXEC sp_executesql @sql;";
return String.Format(sql, Quoter.QuoteTableName(expression.TableName), expression.ColumnName);
}
public override bool IsAdditionalFeatureSupported(string feature)
{
return _supportedAdditionalFeatures.Any(x => x == feature);
}
private readonly IEnumerable<string> _supportedAdditionalFeatures = new List<string>
{
SqlServerExtensions.IdentityInsert,
SqlServerExtensions.IdentitySeed,
SqlServerExtensions.IdentityIncrement,
SqlServerExtensions.ConstraintType
};
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExpressRouteCircuitPeeringsOperations operations.
/// </summary>
internal partial class ExpressRouteCircuitPeeringsOperations : IServiceOperations<NetworkClient>, IExpressRouteCircuitPeeringsOperations
{
/// <summary>
/// Initializes a new instance of the ExpressRouteCircuitPeeringsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ExpressRouteCircuitPeeringsOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified peering from the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (peeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "peeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("peeringName", peeringName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{peeringName}", System.Uri.EscapeDataString(peeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitPeering>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a peering in the specified express route circuits.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ExpressRouteCircuitPeering> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, peeringParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified peering from the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (peeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "peeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("peeringName", peeringName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{peeringName}", System.Uri.EscapeDataString(peeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a peering in the specified express route circuits.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (peeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "peeringName");
}
if (peeringParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "peeringParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("peeringName", peeringName);
tracingParameters.Add("peeringParameters", peeringParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{peeringName}", System.Uri.EscapeDataString(peeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(peeringParameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(peeringParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitPeering>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using CoreFoundation;
using ExternalAccessory;
using Foundation;
using HomeKit;
using UIKit;
namespace HomeKitCatalog
{
public enum AccessoryType
{
// A HomeKit object
HomeKit,
// An external, `EAWiFiUnconfiguredAccessory` object
External
}
// Represents an accessory type and encapsulated accessory.
public class Accessory : IEquatable<Accessory>
{
Func<string> nameGetter;
public string Name {
get {
return nameGetter ();
}
}
public AccessoryType Type { get; set; }
public NSObject AccessoryObject { get; private set; }
public HMAccessory HomeKitAccessoryObject { get; private set; }
public EAWiFiUnconfiguredAccessory ExternalAccessoryObject { get; private set; }
public static bool operator == (Accessory lhs, Accessory rhs)
{
return lhs.Name == rhs.Name;
}
public static bool operator != (Accessory lhs, Accessory rhs)
{
return lhs.Name != rhs.Name;
}
public bool Equals (Accessory other)
{
return Name == other.Name;
}
public override bool Equals (object obj)
{
if (obj == null || obj.GetType () != typeof(Accessory))
return false;
var other = (Accessory)obj;
return Name == other.Name;
}
public override int GetHashCode ()
{
return Name.GetHashCode ();
}
public static Accessory CreateHomeKitObject (HMAccessory accessory)
{
return new Accessory {
Type = AccessoryType.HomeKit,
AccessoryObject = accessory,
HomeKitAccessoryObject = accessory,
nameGetter = () => accessory.Name
};
}
public static Accessory CreateExternalObject (EAWiFiUnconfiguredAccessory accessory)
{
return new Accessory {
Type = AccessoryType.External,
AccessoryObject = accessory,
ExternalAccessoryObject = accessory,
nameGetter = () => accessory.Name
};
}
}
public partial class AccessoryBrowserViewController : HMCatalogViewController, IModifyAccessoryDelegate, IEAWiFiUnconfiguredAccessoryBrowserDelegate, IHMAccessoryBrowserDelegate
{
static readonly NSString AccessoryCell = (NSString)"AccessoryCell";
static readonly NSString AddedAccessoryCell = (NSString)"AddedAccessoryCell";
const string AddAccessorySegue = "Add Accessory";
readonly List<HMAccessory> addedAccessories = new List<HMAccessory> ();
readonly List<Accessory> displayedAccessories = new List<Accessory> ();
readonly HMAccessoryBrowser accessoryBrowser = new HMAccessoryBrowser ();
EAWiFiUnconfiguredAccessoryBrowser externalAccessoryBrowser;
#region ctors
public AccessoryBrowserViewController (IntPtr handle)
: base (handle)
{
}
[Export ("initWithCoder:")]
public AccessoryBrowserViewController (NSCoder coder)
: base (coder)
{
}
#endregion
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
TableView.EstimatedRowHeight = 44;
TableView.RowHeight = UITableView.AutomaticDimension;
accessoryBrowser.Delegate = this;
// We can't use the ExternalAccessory framework on the iPhone simulator.
if (!UIDevice.CurrentDevice.Model.Contains ("Simulator"))
externalAccessoryBrowser = new EAWiFiUnconfiguredAccessoryBrowser (this, DispatchQueue.MainQueue);
StartBrowsing ();
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
ReloadTable ();
}
// Stops browsing and dismisses the view controller.
[Export ("dismiss:")]
void Dismiss (NSString sender)
{
StopBrowsing ();
DismissViewController (true, null);
}
// Sets the accessory, home, and delegate of a ModifyAccessoryViewController.
public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
{
base.PrepareForSegue (segue, sender);
var accessorySender = sender as HMAccessory;
if (accessorySender != null && segue.Identifier == AddAccessorySegue) {
var modifyViewController = (ModifyAccessoryViewController)segue.IntendedDestinationViewController ();
modifyViewController.Accessory = accessorySender;
modifyViewController.Delegate = this;
}
}
#region Table View Methods
// Generates the number of rows based on the number of displayed accessories.
// This method will also display a table view background message, if required.
// returns: The number of rows based on the number of displayed accessories.
public override nint RowsInSection (UITableView tableView, nint section)
{
var rows = displayedAccessories.Count;
var message = rows == 0 ? "No Discovered Accessories" : null;
TableView.SetBackgroundMessage (message);
return rows;
}
// returns: Creates a cell that lists an accessory, and if it hasn't been added to the home,
// shows a disclosure indicator instead of a checkmark.
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
Accessory accessory = displayedAccessories [indexPath.Row];
var reuseIdentifier = AccessoryCell;
if (accessory.Type == AccessoryType.HomeKit && addedAccessories.Contains (accessory.HomeKitAccessoryObject))
reuseIdentifier = AddedAccessoryCell;
var cell = tableView.DequeueReusableCell (reuseIdentifier, indexPath);
cell.TextLabel.Text = accessory.Name;
var hkAccessory = accessory.HomeKitAccessoryObject;
var detailTextLabel = cell.DetailTextLabel;
if (detailTextLabel != null) {
detailTextLabel.Text = (hkAccessory != null)
? hkAccessory.Category.LocalizedDescription
: "External Accessory";
}
return cell;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
var accessory = displayedAccessories [indexPath.Row];
switch (accessory.Type) {
case AccessoryType.HomeKit:
ConfigureAccessory (accessory.HomeKitAccessoryObject);
break;
case AccessoryType.External:
if (externalAccessoryBrowser != null)
externalAccessoryBrowser.ConfigureAccessory (accessory.ExternalAccessoryObject, this);
break;
}
}
#endregion
#region Helper Methods
// Starts browsing on both HomeKit and External accessory browsers.
void StartBrowsing ()
{
accessoryBrowser.StartSearchingForNewAccessories ();
if (externalAccessoryBrowser != null)
externalAccessoryBrowser.StartSearchingForUnconfiguredAccessories (null);
}
// Stops browsing on both HomeKit and External accessory browsers.
void StopBrowsing ()
{
accessoryBrowser.StopSearchingForNewAccessories ();
if (externalAccessoryBrowser != null)
externalAccessoryBrowser.StopSearchingForUnconfiguredAccessories ();
}
// Concatenates and sorts the discovered and added accessories.
// TODO: can we use IEnumerable<Accessory> ???
List<Accessory> AllAccessories ()
{
var hashSet = new HashSet<Accessory> ();
var discovered = accessoryBrowser.DiscoveredAccessories.Select (Accessory.CreateHomeKitObject);
hashSet.UnionWith (discovered);
var added = addedAccessories.Select (Accessory.CreateHomeKitObject);
hashSet.UnionWith (added);
if (externalAccessoryBrowser != null) {
NSSet external = externalAccessoryBrowser.UnconfiguredAccessories;
if (external != null) {
var unconfiguredAccessories = external.Cast<EAWiFiUnconfiguredAccessory> ().Select (Accessory.CreateExternalObject);
hashSet.UnionWith (unconfiguredAccessories);
}
}
var result = hashSet.ToList ();
result.SortByLocalizedName (a => a.Name);
return result;
}
/// Updates the displayed accesories array and reloads the table view.
void ReloadTable ()
{
displayedAccessories.Clear ();
displayedAccessories.AddRange (AllAccessories ());
TableView.ReloadData ();
}
/// Sends the accessory to the next view.
void ConfigureAccessory (HMAccessory accessory)
{
if (displayedAccessories.Contains (Accessory.CreateHomeKitObject (accessory)))
PerformSegue (AddAccessorySegue, accessory);
}
// Finds an unconfigured accessory with a specified name.
HMAccessory UnconfiguredHomeKitAccessory (string name)
{
return displayedAccessories.Where (a => a.Type == AccessoryType.HomeKit)
.Select (a => a.HomeKitAccessoryObject)
.FirstOrDefault (a => a.Name == name);
}
#endregion
#region IModifyAccessoryDelegate Methods
public void AccessoryViewControllerDidSaveAccessory (ModifyAccessoryViewController accessoryViewController, HMAccessory accessory)
{
addedAccessories.Add (accessory);
ReloadTable ();
}
#endregion
#region EAWiFiUnconfiguredAccessoryBrowserDelegate Methods
// Any updates to the external accessory browser causes a reload in the table view.
public void DidUpdateState (EAWiFiUnconfiguredAccessoryBrowser browser, EAWiFiUnconfiguredAccessoryBrowserState state)
{
ReloadTable ();
}
public void DidFindUnconfiguredAccessories (EAWiFiUnconfiguredAccessoryBrowser browser, NSSet accessories)
{
ReloadTable ();
}
public void DidRemoveUnconfiguredAccessories (EAWiFiUnconfiguredAccessoryBrowser browser, NSSet accessories)
{
ReloadTable ();
}
// If the configuration was successful, presents the 'Add Accessory' view.
public void DidFinishConfiguringAccessory (EAWiFiUnconfiguredAccessoryBrowser browser, EAWiFiUnconfiguredAccessory accessory, EAWiFiUnconfiguredAccessoryConfigurationStatus status)
{
if (status != EAWiFiUnconfiguredAccessoryConfigurationStatus.Success)
return;
var foundAccessory = UnconfiguredHomeKitAccessory (accessory.Name);
if (foundAccessory != null)
ConfigureAccessory (foundAccessory);
}
#endregion
#region HMAccessoryBrowserDelegate Methods
// Inserts the accessory into the internal array and inserts the row into the table view.
[Export ("accessoryBrowser:didFindNewAccessory:")]
public void DidFindNewAccessory (HMAccessoryBrowser browser, HMAccessory accessory)
{
var newAccessory = Accessory.CreateHomeKitObject (accessory);
if (displayedAccessories.Contains (newAccessory))
return;
displayedAccessories.Add (newAccessory);
displayedAccessories.SortByLocalizedName (a => a.Name);
var newIndex = displayedAccessories.IndexOf (newAccessory);
if (newIndex >= 0) {
var newIndexPath = NSIndexPath.FromRowSection (newIndex, 0);
TableView.InsertRows (new []{ newIndexPath }, UITableViewRowAnimation.Automatic);
}
}
// Removes the accessory from the internal array and deletes the row from the table view.
[Export ("accessoryBrowser:didRemoveNewAccessory:")]
public void DidRemoveNewAccessory (HMAccessoryBrowser browser, HMAccessory accessory)
{
var removedAccessory = Accessory.CreateHomeKitObject (accessory);
var removedIndex = displayedAccessories.IndexOf (removedAccessory);
if (removedIndex < 0)
return;
var removedIndexPath = NSIndexPath.FromRowSection (removedIndex, 0);
displayedAccessories.RemoveAt (removedIndex);
TableView.DeleteRows (new []{ removedIndexPath }, UITableViewRowAnimation.Automatic);
}
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.Analysis.Browser {
public partial class MainWindow : Window {
public static readonly ICommand CloseDatabaseCommand = new RoutedCommand();
public static readonly ICommand OpenDatabaseCommand = new RoutedCommand();
public static readonly ICommand BrowseSaveCommand = new RoutedCommand();
public static readonly ICommand BrowseFolderCommand = new RoutedCommand();
public static readonly ICommand GoToItemCommand = new RoutedCommand();
public static readonly IEnumerable<Version> SupportedVersions = new[] {
new Version(2, 5),
new Version(2, 6),
new Version(2, 7),
new Version(3, 0),
new Version(3, 1),
new Version(3, 2),
new Version(3, 3),
new Version(3, 4),
};
public MainWindow() {
InitializeComponent();
DatabaseDirectory.Text = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Python Tools"
);
if (Directory.Exists(App.InitialPath)) {
Hide();
ProcessArguments().DoNotWait();
}
}
private async Task ProcessArguments() {
try {
Version version;
if (Version.TryParse(App.InitialVersion, out version)) {
Version = version;
}
if (!(App.ExportTree || App.ExportDiffable)) {
Show();
}
await Load(App.InitialPath);
if ((App.ExportTree || App.ExportDiffable) && !string.IsNullOrEmpty(App.ExportPath)) {
if (!App.ExportPerPackage) {
await (App.ExportDiffable ?
Analysis.ExportDiffable(App.ExportPath, App.ExportFilter) :
Analysis.ExportTree(App.ExportPath, App.ExportFilter));
} else {
Directory.CreateDirectory(App.ExportPath);
foreach (var package in Analysis.Modules.OfType<ModuleView>().Select(m => m.Name).Where(n => !n.Contains("."))) {
var path = Path.Combine(App.ExportPath, package + ".txt");
var filter = "^" + package + ".*";
await (App.ExportDiffable ?
Analysis.ExportDiffable(path, filter) :
Analysis.ExportTree(path, filter));
}
}
Close();
}
} catch (Exception ex) when (!ex.IsCriticalException()) {
MessageBox.Show(string.Format("Error occurred:{0}{0}{1}", Environment.NewLine, ex));
}
}
internal AnalysisView Analysis {
get { return (AnalysisView)GetValue(AnalysisProperty); }
private set { SetValue(AnalysisPropertyKey, value); }
}
private static readonly DependencyPropertyKey AnalysisPropertyKey = DependencyProperty.RegisterReadOnly("Analysis", typeof(AnalysisView), typeof(MainWindow), new PropertyMetadata());
public static readonly DependencyProperty AnalysisProperty = AnalysisPropertyKey.DependencyProperty;
public bool HasAnalysis {
get { return (bool)GetValue(HasAnalysisProperty); }
private set { SetValue(HasAnalysisPropertyKey, value); }
}
private static readonly DependencyPropertyKey HasAnalysisPropertyKey = DependencyProperty.RegisterReadOnly("HasAnalysis", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
public static readonly DependencyProperty HasAnalysisProperty = HasAnalysisPropertyKey.DependencyProperty;
public bool Loading {
get { return (bool)GetValue(LoadingProperty); }
private set { SetValue(LoadingPropertyKey, value); }
}
private static readonly DependencyPropertyKey LoadingPropertyKey = DependencyProperty.RegisterReadOnly("Loading", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
public static readonly DependencyProperty LoadingProperty = LoadingPropertyKey.DependencyProperty;
public Version Version {
get { return (Version)GetValue(VersionProperty); }
set { SetValue(VersionProperty, value); }
}
public static readonly DependencyProperty VersionProperty = DependencyProperty.Register("Version", typeof(Version), typeof(MainWindow), new PropertyMetadata(new Version(2, 7)));
public bool LoadWithContention {
get { return (bool)GetValue(LoadWithContentionProperty); }
set { SetValue(LoadWithContentionProperty, value); }
}
public static readonly DependencyProperty LoadWithContentionProperty = DependencyProperty.Register("LoadWithContention", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
public bool LoadWithLowMemory {
get { return (bool)GetValue(LoadWithLowMemoryProperty); }
set { SetValue(LoadWithLowMemoryProperty, value); }
}
public static readonly DependencyProperty LoadWithLowMemoryProperty = DependencyProperty.Register("LoadWithLowMemory", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
public bool LoadRecursive {
get { return (bool)GetValue(LoadRecursiveProperty); }
set { SetValue(LoadRecursiveProperty, value); }
}
public static readonly DependencyProperty LoadRecursiveProperty = DependencyProperty.Register("LoadRecursive", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
private void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = !Loading;
}
private void Open_Executed(object sender, ExecutedRoutedEventArgs e) {
string path;
var tb = e.Source as TextBox;
if (tb == null || !Directory.Exists(path = tb.Text)) {
using (var bfd = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog()) {
bfd.IsFolderPicker = true;
bfd.RestoreDirectory = true;
if (HasAnalysis) {
path = Analysis.Path;
} else {
path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Python Tools"
);
}
while (path.Length >= 4 && !Directory.Exists(path)) {
path = Path.GetDirectoryName(path);
}
if (path.Length <= 3) {
path = null;
}
bfd.InitialDirectory = path;
if (bfd.ShowDialog() == WindowsAPICodePack.Dialogs.CommonFileDialogResult.Cancel) {
return;
}
path = bfd.FileName;
}
}
Load(path).DoNotWait();
}
private async Task Load(string path) {
HasAnalysis = false;
Loading = true;
Analysis = null;
Cursor = Cursors.Wait;
var version = Version;
var withContention = LoadWithContention;
var withLowMemory = LoadWithLowMemory;
var withRecursion = LoadRecursive;
var tcs = new TaskCompletionSource<object>();
tcs.SetResult(null);
Task startTask = tcs.Task;
if (withLowMemory) {
startTask = Task.Factory.StartNew(() => {
var bigBlocks = new LinkedList<byte[]>();
var rnd = new Random();
try {
while (true) {
var block = new byte[10 * 1024 * 1024];
rnd.NextBytes(block);
bigBlocks.AddLast(block);
}
} catch (OutOfMemoryException) {
// Leave 200MB of memory available
for (int i = 0; i < 20 && bigBlocks.Any(); ++i) {
bigBlocks.RemoveFirst();
}
}
return bigBlocks;
}).ContinueWith(t => {
Tag = t.Result;
}, TaskScheduler.FromCurrentSynchronizationContext());
}
var loadTask = startTask.ContinueWith<AnalysisView>(t => {
return new AnalysisView(path, version, withContention, withRecursion);
}, TaskContinuationOptions.LongRunning);
await loadTask.ContinueWith(
t => {
Tag = null;
try {
Analysis = t.Result;
HasAnalysis = true;
} catch (Exception ex) {
HasAnalysis = false;
MessageBox.Show(string.Format("Error occurred:{0}{0}{1}", Environment.NewLine, ex));
}
Loading = false;
Cursor = Cursors.Arrow;
},
TaskScheduler.FromCurrentSynchronizationContext()
);
}
private void Export_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = HasAnalysis && !string.IsNullOrEmpty(ExportFilename.Text);
}
private void Export_Executed(object sender, ExecutedRoutedEventArgs e) {
e.Handled = true;
var path = ExportFilename.Text;
var filter = ExportFilter.Text;
Cursor = Cursors.AppStarting;
Task t = null;
if (e.Command == AnalysisView.ExportTreeCommand) {
t = Analysis.ExportTree(path, filter);
} else if (e.Command == AnalysisView.ExportDiffableCommand) {
t = Analysis.ExportDiffable(path, filter);
}
if (t != null) {
t.ContinueWith(t2 => {
Process.Start("explorer.exe", "/select,\"" + path + "\"");
}, TaskContinuationOptions.OnlyOnRanToCompletion);
t.ContinueWith(t2 => {
Cursor = Cursors.Arrow;
if (t2.Exception != null) {
MessageBox.Show(string.Format("An error occurred while exporting:{0}{0}{1}",
Environment.NewLine,
t2.Exception));
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
private void BrowseSave_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = e.Source is TextBox && e.Parameter is string;
}
private void BrowseSave_Executed(object sender, ExecutedRoutedEventArgs e) {
using (var dialog = new System.Windows.Forms.SaveFileDialog()) {
dialog.Filter = (string)e.Parameter;
dialog.AutoUpgradeEnabled = true;
var path = ((TextBox)e.Source).Text;
try {
dialog.FileName = path;
dialog.InitialDirectory = Path.GetDirectoryName(path);
} catch (ArgumentException) {
dialog.FileName = string.Empty;
dialog.InitialDirectory = Analysis.Path;
}
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) {
return;
}
((TextBox)e.Source).SetCurrentValue(TextBox.TextProperty, dialog.FileName);
}
}
private void BrowseFolder_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = e.Source is TextBox;
}
private void BrowseFolder_Executed(object sender, ExecutedRoutedEventArgs e) {
using (var bfd = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog()) {
bfd.IsFolderPicker = true;
bfd.RestoreDirectory = true;
var path = ((TextBox)e.Source).Text;
while (path.Length >= 4 && !Directory.Exists(path)) {
path = Path.GetDirectoryName(path);
}
if (path.Length <= 3) {
path = null;
}
bfd.InitialDirectory = path;
if (bfd.ShowDialog() == WindowsAPICodePack.Dialogs.CommonFileDialogResult.Cancel) {
return;
}
((TextBox)e.Source).SetCurrentValue(TextBox.TextProperty, bfd.FileName);
}
}
private void GoToItem_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = e.Parameter is IAnalysisItemView;
}
private static Stack<TreeViewItem> SelectChild(TreeViewItem root, object value) {
if (root == null) {
return null;
}
if (root.DataContext == value) {
var lst = new Stack<TreeViewItem>();
lst.Push(root);
return lst;
}
foreach (var child in root.Items
.OfType<object>()
.Select(i => (TreeViewItem)root.ItemContainerGenerator.ContainerFromItem(i))) {
var lst = SelectChild(child, value);
if (lst != null) {
lst.Push(root);
return lst;
}
}
return null;
}
private static void SelectChild(TreeView tree, object value) {
Stack<TreeViewItem> result = null;
foreach (var item in tree.Items
.OfType<object>()
.Select(i => (TreeViewItem)tree.ItemContainerGenerator.ContainerFromItem(i))) {
if ((result = SelectChild(item, value)) != null) {
break;
}
}
if (result != null) {
while (result.Any()) {
var item = result.Pop();
item.IsExpanded = true;
item.Focus();
}
}
}
private void GoToItem_Executed(object sender, ExecutedRoutedEventArgs e) {
Cursor = Cursors.Wait;
try {
SelectChild(DatabaseTreeView, e.Parameter);
} finally {
Cursor = Cursors.Arrow;
}
}
private void Close_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = true;
}
private void Close_Executed(object sender, ExecutedRoutedEventArgs e) {
Close();
}
private void CloseDatabase_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = HasAnalysis;
}
private void CloseDatabase_Executed(object sender, ExecutedRoutedEventArgs e) {
Analysis = null;
Loading = false;
HasAnalysis = false;
DatabaseDirectory.SelectAll();
}
private void DatabaseDirectory_TextChanged(object sender, TextChangedEventArgs e) {
var dir = DatabaseDirectory.Text;
if (!Directory.Exists(dir)) {
return;
}
int bestIndex = -1;
Version bestVersion = null;
foreach (var ver in SupportedVersions.Reverse()) {
int index = dir.IndexOf("\\" + ver.ToString());
if (index > bestIndex) {
bestVersion = ver;
bestIndex = index;
}
}
if (bestIndex >= 0) {
Version = bestVersion;
}
}
private void NavigateTo_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = Directory.Exists(e.Parameter as string);
e.Handled = true;
}
private void NavigateTo_Executed(object sender, ExecutedRoutedEventArgs e) {
DatabaseDirectory.SetCurrentValue(TextBox.TextProperty, e.Parameter);
DatabaseDirectory.Focus();
DatabaseDirectory.SelectAll();
e.Handled = true;
}
private void DatabaseDirectory_SubDirs_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
DatabaseDirectory.Focus();
e.Handled = true;
}
}
class PropertyItemTemplateSelector : DataTemplateSelector {
public DataTemplate Text { get; set; }
public DataTemplate AnalysisItem { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container) {
if (item is string) {
return Text;
} else if (item is IAnalysisItemView) {
return AnalysisItem;
}
return null;
}
}
[ValueConversion(typeof(string), typeof(IEnumerable<string>))]
class DirectoryList : IValueConverter {
public bool IncludeParentDirectory { get; set; }
public bool IncludeDirectories { get; set; }
public bool IncludeFiles { get; set; }
public bool NamesOnly { get; set; }
private IEnumerable<string> GetParentDirectory(string dir) {
if (!IncludeParentDirectory || !PathUtils.IsValidPath(dir)) {
yield break;
}
var parentDir = Path.GetDirectoryName(dir);
if (!string.IsNullOrEmpty(parentDir)) {
yield return parentDir;
}
}
private IEnumerable<string> GetFiles(string dir) {
if (!IncludeFiles) {
return Enumerable.Empty<string>();
}
var files = Directory.EnumerateFiles(dir);
if (NamesOnly) {
files = files.Select(f => Path.GetFileName(f));
}
return files.OrderBy(f => f);
}
private IEnumerable<string> GetDirectories(string dir) {
if (!IncludeDirectories) {
return Enumerable.Empty<string>();
}
var dirs = Directory.EnumerateDirectories(dir);
if (NamesOnly) {
dirs = dirs.Select(d => Path.GetFileName(d));
}
return dirs.OrderBy(d => d);
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
var dir = value as string;
if (!Directory.Exists(dir)) {
return Enumerable.Empty<string>();
}
return GetParentDirectory(dir).Concat(GetDirectories(dir)).Concat(GetFiles(dir));
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
}
| |
using iSukces.Code.Ammy;
using Xunit;
namespace iSukces.Code.Tests.Ui
{
public partial class CompatTelerikGridAmmyMixinsGeneratorTests
{
[Fact]
public void T01_Should_create()
{
AmmyHelper.ConvertToIAmmyCodePiece += (a, b) =>
{
if (b.SourceValue is SampleStaticTextSource s)
{
var value = new SimpleAmmyCodePiece(s.Value.CsEncode());
b.Handle(value);
}
else if (b.SourceValue is SampleTranslatedTextSource s2)
{
var value = new SimpleAmmyCodePiece("SomeFakeClass.SomeFakeProperty");
b.Handle(value);
}
};
var g = new SampleGridViewAmmyMixinsGenerator(new FakeAssemblyBaseDirectoryProvider());
var ctx = new TestContext();
var type = typeof(GridDefinition1);
g.AssemblyStart(type.Assembly, ctx);
g.Generate(type, ctx);
var code = g.GetFullCode();
var exp = @"using Telerik.Windows.Controls
mixin GridDefinition1() for RadGridView
{
Resources: ResourceDictionary
{
combine MergedDictionaries: [ ResourceDictionary {Source: ""pack://application:,,,/MyApplication;component/resources/gridviewstyles.g.xaml""} ]
}
IsLocalizationLanguageRespected: false
#MyGridProperties
combine Columns: [
GridViewDataColumn { DataMemberBinding: bind ""Number"", Header: ""Number"", IsReadOnly: true, Width: 160, TextAlignment: Right }
GridViewDataColumn { DataMemberBinding: bind ""Name"", Header: ""*Name"", IsReadOnly: true, Width: 160 }
GridViewDataColumn { DataMemberBinding: bind ""Date"", Header: SomeFakeClass.SomeFakeProperty, IsReadOnly: true, Width: 120 }
]
}
";
Assert.Equal(exp.Trim(), code.Trim());
const string exp2 = @"// ReSharper disable All
namespace iSukces.Code.Tests.Ui
{
partial class CompatTelerikGridAmmyMixinsGeneratorTests
{
partial class GridDefinition1
{
private static string GetHeader(string name)
{
switch(name)
{
case ""Date"": return Translations.GetCurrentTranslation(""translations.common.date"");
case ""Name"": return ""*Name"";
}
return name;
}
}
}
}
";
Assert.Equal(exp2.Trim(), ctx.Code.Trim());
}
[Fact]
public void T02_Should_create_bool_with_data_template()
{
AmmyHelper.ConvertToIAmmyCodePiece += (a, b) =>
{
if (b.SourceValue is SampleStaticTextSource s)
{
var value = new SimpleAmmyCodePiece(s.Value.CsEncode());
b.Handle(value);
}
else if (b.SourceValue is SampleTranslatedTextSource s2)
{
var value = new SimpleAmmyCodePiece("SomeFakeClass.SomeFakeProperty");
b.Handle(value);
}
};
var g = new SampleGridViewAmmyMixinsGenerator(new FakeAssemblyBaseDirectoryProvider());
var ctx = new TestContext();
var type = typeof(GridDefinition2);
g.AssemblyStart(type.Assembly, ctx);
g.Generate(type, ctx);
var code = g.GetFullCode();
var exp = @"
using Telerik.Windows.Controls
mixin GridDefinition2() for RadGridView
{
Resources: ResourceDictionary
{
combine MergedDictionaries: [ ResourceDictionary {Source: ""pack://application:,,,/MyApplication;component/resources/gridviewstyles.g.xaml""} ]
}
IsLocalizationLanguageRespected: false
#MyGridProperties
combine Columns: [
GridViewDataColumn { DataMemberBinding: bind ""Flag"", Header: ""Flag1"", Width: 160
CellTemplate: System.Windows.DataTemplate {
iSukces.Code.Tests.Ammy.CheckBox {
IsChecked: bind ""Flag"" set [Mode: TwoWay, UpdateSourceTrigger: PropertyChanged]
}
}
CellEditTemplate: System.Windows.DataTemplate {
iSukces.Code.Tests.Ammy.CheckBox {
IsChecked: bind ""Flag"" set [Mode: TwoWay, UpdateSourceTrigger: PropertyChanged]
}
}
EditTriggers: CellClick
}
]
}
";
Assert.Equal(exp.Trim(), code.Trim());
const string exp2 = @"// ReSharper disable All
namespace iSukces.Code.Tests.Ui
{
partial class CompatTelerikGridAmmyMixinsGeneratorTests
{
partial class GridDefinition2
{
private static string GetHeader(string name)
{
switch(name)
{
case ""Flag"": return ""Flag1"";
}
return name;
}
}
}
}
";
Assert.Equal(exp2.Trim(), ctx.Code.Trim());
}
[Fact]
public void T03_Should_create_bool_with_nested_values()
{
AmmyHelper.ConvertToIAmmyCodePiece += (a, b) =>
{
if (b.SourceValue is SampleStaticTextSource s)
{
var value = new SimpleAmmyCodePiece(s.Value.CsEncode());
b.Handle(value);
}
else if (b.SourceValue is SampleTranslatedTextSource s2)
{
var value = new SimpleAmmyCodePiece("SomeFakeClass.SomeFakeProperty");
b.Handle(value);
}
};
var g = new SampleGridViewAmmyMixinsGenerator(new FakeAssemblyBaseDirectoryProvider());
var ctx = new TestContext();
var type = typeof(GridDefinition3);
g.AssemblyStart(type.Assembly, ctx);
g.Generate(type, ctx);
var code = g.GetFullCode();
var exp = @"
using Telerik.Windows.Controls
mixin GridDefinition3() for RadGridView
{
Resources: ResourceDictionary
{
combine MergedDictionaries: [ ResourceDictionary {Source: ""pack://application:,,,/MyApplication;component/resources/gridviewstyles.g.xaml""} ]
}
IsLocalizationLanguageRespected: false
#MyGridProperties
combine Columns: [
GridViewDataColumn { DataMemberBinding: bind ""Obj.Name"", Header: ""Name"", Width: 160 }
GridViewDataColumn { DataMemberBinding: bind ""Obj.Number"", Header: ""Number"", Width: 130 }
GridViewDataColumn { DataMemberBinding: bind, Header: ""Whole"", Width: 120 }
]
}
";
Assert.Equal(exp.Trim(), code.Trim());
const string exp2 = @"
// ReSharper disable All
namespace iSukces.Code.Tests.Ui
{
partial class CompatTelerikGridAmmyMixinsGeneratorTests
{
partial class GridDefinition3
{
private static string GetHeader(string name)
{
switch(name)
{
case """": return ""Whole"";
}
return name;
}
}
}
}
";
Assert.Equal(exp2.Trim(), ctx.Code.Trim());
}
}
}
| |
// 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 Test.Cryptography;
namespace System.Security.Cryptography.Pkcs.Tests
{
internal static class Certificates
{
public static readonly CertLoader RSAKeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer1Cer, RawData.s_RSAKeyTransfer1Pfx, "1111");
public static readonly CertLoader RSAKeyTransfer2 = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer2Cer, RawData.s_RSAKeyTransfer2Pfx, "1111");
public static readonly CertLoader RSAKeyTransfer3 = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer3Cer, RawData.s_RSAKeyTransfer3Pfx, "1111");
public static readonly CertLoader RSAKeyTransfer_ExplicitSki = new CertLoaderFromRawData(RawData.s_RSAKeyTransferCer_ExplicitSki, RawData.s_RSAKeyTransferPfx_ExplicitSki, "1111");
public static readonly CertLoader RSAKeyTransferCapi1 = new CertLoaderFromRawData(RawData.s_RSAKeyTransferCapi1Cer, RawData.s_RSAKeyTransferCapi1Pfx, "1111");
public static readonly CertLoader RSASha256KeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSASha256KeyTransfer1Cer, RawData.s_RSASha256KeyTransfer1Pfx, "1111");
public static readonly CertLoader RSASha384KeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSASha384KeyTransfer1Cer, RawData.s_RSASha384KeyTransfer1Pfx, "1111");
public static readonly CertLoader RSASha512KeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSASha512KeyTransfer1Cer, RawData.s_RSASha512KeyTransfer1Pfx, "1111");
public static readonly CertLoader RSA2048Sha256KeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSA2048Sha256KeyTransfer1Cer, RawData.s_RSA2048Sha256KeyTransfer1Pfx, "1111");
public static readonly CertLoader DHKeyAgree1 = new CertLoaderFromRawData(RawData.s_DHKeyAgree1Cer);
public static readonly CertLoader RSA2048SignatureOnly = new CertLoaderFromRawData(RawData.s_Rsa2048SignatureOnlyCer, RawData.s_Rsa2048SignatureOnlyPfx, "12345");
public static readonly CertLoader Dsa1024 = new CertLoaderFromRawData(RawData.s_dsa1024Cert, RawData.s_dsa1024Pfx, "1234");
public static readonly CertLoader ECDsaP256Win = new CertLoaderFromRawData(RawData.ECDsaP256_DigitalSignature_Cert, RawData.ECDsaP256_DigitalSignature_Pfx_Windows, "Test");
public static readonly CertLoader ECDsaP521Win = new CertLoaderFromRawData(RawData.ECDsaP521_DigitalSignature_Cert, RawData.ECDsaP521_DigitalSignature_Pfx_Windows, "Test");
public static readonly CertLoader ValidLookingTsaCert = new CertLoaderFromRawData(RawData.ValidLookingTsaCert_Cer, RawData.ValidLookingTsaCert_Pfx, "export");
public static readonly CertLoader TwoEkuTsaCert = new CertLoaderFromRawData(RawData.TwoEkuTsaCert, RawData.TwoEkuTsaPfx, "export");
public static readonly CertLoader NonCriticalTsaEku = new CertLoaderFromRawData(RawData.NonCriticalTsaEkuCert, RawData.NonCriticalTsaEkuPfx, "export");
public static readonly CertLoader TlsClientServerCert = new CertLoaderFromRawData(RawData.TlsClientServerEkuCert, RawData.TlsClientServerEkuPfx, "export");
public static readonly CertLoader RSAKeyTransfer4_ExplicitSki = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer4_ExplicitSkiCer, RawData.s_RSAKeyTransfer4_ExplicitSkiPfx, "1111");
public static readonly CertLoader RSAKeyTransfer5_ExplicitSkiOfRSAKeyTransfer4 = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer5_ExplicitSkiOfRSAKeyTransfer4Cer, RawData.s_RSAKeyTransfer5_ExplicitSkiOfRSAKeyTransfer4Pfx, "1111");
public static readonly CertLoader NegativeSerialNumber = new CertLoaderFromRawData(RawData.NegativeSerialNumberCert, RawData.NegativeSerialNumberPfx, "1234");
public static readonly CertLoader RsaOaep2048_NullParameters = new CertLoaderFromRawData(RawData.RsaOaep2048_NullParametersCert, RawData.RsaOaep2048_NullParametersPfx, "1111");
public static readonly CertLoader RsaOaep2048_Sha1Parameters = new CertLoaderFromRawData(RawData.RsaOaep2048_Sha1ParametersCert, RawData.RsaOaep2048_Sha1ParametersPfx, "1111");
public static readonly CertLoader RsaOaep2048_Sha256Parameters = new CertLoaderFromRawData(RawData.RsaOaep2048_Sha256ParametersCert, RawData.RsaOaep2048_Sha256ParametersPfx, "1111");
public static readonly CertLoader RsaOaep2048_NoParameters = new CertLoaderFromRawData(RawData.RsaOaep2048_NoParametersCert, RawData.RsaOaep2048_NoParametersPfx, "1111");
// Note: the raw data is its own (nested) class to avoid problems with static field initialization ordering.
private static class RawData
{
public static byte[] s_RSAKeyTransfer1Cer =
("308201c830820131a003020102021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d0101050500301a3118"
+ "30160603550403130f5253414b65795472616e7366657231301e170d3136303431323136323534375a170d31373034313232"
+ "32323534375a301a311830160603550403130f5253414b65795472616e736665723130819f300d06092a864886f70d010101"
+ "050003818d00308189028181009eaab63f5629db5ac0bd74300b43ba61f49189ccc30c001fa96bd3b139f45732cd3c37e422"
+ "ccbb2c598a4c6b3977a516a36ff850a5e914331f7445e86973f5a6cbb590105e933306e240eab6db72d08430cd7316e99481"
+ "a272adef0f2479d0b7c58e89e072364d660fdad1b51a603ff4549a82e8dc914df82bcc6c6c232985450203010001a30f300d"
+ "300b0603551d0f040403020520300d06092a864886f70d01010505000381810048c83e6f45d73a111c67e8f9f9c2d646292b"
+ "75cec52ef0f9ae3e1639504aa1759512c46527fcf5476897d3fb6fc515ff1646f8f8bc09f84ea6e2ad04242d3fb9b190b816"
+ "86b73d334e8b3afa7fb8eb31483efc0c7ccb0f8c1ca94d8be4f0daade4498501d02e6f92dd7b2f4401550896eb511ef14417"
+ "cbb5a1b360d67998d334").HexToByteArray();
// password = "1111"
public static byte[] s_RSAKeyTransfer1Pfx =
("308205d20201033082058e06092a864886f70d010701a082057f0482057b308205773082034806092a864886f70d010701a0"
+ "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103"
+ "300e040818fdedadbb31b101020207d0048202806aa390fa9a4cb071a0daf25765ed69efe039896036c0f0edfc03ebe35d2a"
+ "f2f6a5bc9efd907f3b64ae15ac7f61d830e48810aa096ee37fe442b7bfbceeb92e22c25bd5484baf91460be29e06648485db"
+ "7b10ea92d17983c4d22067396c12e4598541ab989d7beb38bf8a0213fd7c9d49ecd46d319bbb58b1423504cd4145e1b33978"
+ "41306c5ace9eab42d408e05101911adc684e63a8c8c9579ce929e48ce2393af1a63c3180c52bd87475e3edb9763dff731ede"
+ "38fc8043dee375001a59e7d6eec5d686d509efee38ef0e7bddcd7ba0477f6f38ff7172ceaeef94ff56ad4b9533241f404d58"
+ "c2b5d54f1ab8250c56b1a70f57b7fffc640b7037408b8f830263befc031ffe7dbc6bef23f02c1e6e2b541be12009bfb11297"
+ "02fc0559e54d264df9b0d046c73ad1b25056231e5d3c4015bdc4f0a9af70ac28b7241233ecc845ce14484779102a45da2560"
+ "c354ec3e01f26d0e0b9a8b650f811d2ffeba95ec1e5cf6be2d060788c1b18ea4ec8f41e46da734c1216044a10a3e171620ed"
+ "79f7e9dd36972c89d91111c68fd60a94d2aa2a3dbbde0383c7c367f77b70a218ddf9fb4ed7abf94c233ffb2797d9ca3802ed"
+ "77868d3ab5651abb90e4de9ea74854b13603859b308689d770a62b5821e5a5650ecb23ca2894ad7901c7e1d2f22ef97e9092"
+ "f0791e886487a59d380d98c0368d3f2f261e0139714b02010e61aa073ee782b1fe5b6f79d070ef1412a13270138330a2e308"
+ "599e1e7829be9f983202ac0dc1c38d38587defe2741903af35227e4f979a68adef86a8459be4a2d74e5de7f94e114a8ea7e4"
+ "0ea2af6b8a93a747377bdd8ddd83c086bb20ca49854efb931ee689b319f984e5377f5a0f20d0a613326d749af00675c6bc06"
+ "0be528ef90ec6a9b2f9b3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e"
+ "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074"
+ "006f0072006100670065002000500072006f007600690064006500723082022706092a864886f70d010701a0820218048202"
+ "14308202103082020c060b2a864886f70d010c0a0103a08201e4308201e0060a2a864886f70d01091601a08201d0048201cc"
+ "308201c830820131a003020102021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d0101050500301a3118"
+ "30160603550403130f5253414b65795472616e7366657231301e170d3136303431323136323534375a170d31373034313232"
+ "32323534375a301a311830160603550403130f5253414b65795472616e736665723130819f300d06092a864886f70d010101"
+ "050003818d00308189028181009eaab63f5629db5ac0bd74300b43ba61f49189ccc30c001fa96bd3b139f45732cd3c37e422"
+ "ccbb2c598a4c6b3977a516a36ff850a5e914331f7445e86973f5a6cbb590105e933306e240eab6db72d08430cd7316e99481"
+ "a272adef0f2479d0b7c58e89e072364d660fdad1b51a603ff4549a82e8dc914df82bcc6c6c232985450203010001a30f300d"
+ "300b0603551d0f040403020520300d06092a864886f70d01010505000381810048c83e6f45d73a111c67e8f9f9c2d646292b"
+ "75cec52ef0f9ae3e1639504aa1759512c46527fcf5476897d3fb6fc515ff1646f8f8bc09f84ea6e2ad04242d3fb9b190b816"
+ "86b73d334e8b3afa7fb8eb31483efc0c7ccb0f8c1ca94d8be4f0daade4498501d02e6f92dd7b2f4401550896eb511ef14417"
+ "cbb5a1b360d67998d3343115301306092a864886f70d0109153106040401000000303b301f300706052b0e03021a0414c4c0"
+ "4e0c0b0a20e50d58cb5ce565ba7c192d5d3f041479b53fc5f1f1f493a02cf113d563a247462e8726020207d0").HexToByteArray();
public static byte[] s_RSAKeyTransfer2Cer =
("308201c830820131a00302010202102bce9f9ece39f98044f0cd2faa9a14e7300d06092a864886f70d0101050500301a3118"
+ "30160603550403130f5253414b65795472616e7366657232301e170d3136303332353231323334325a170d31373033323630"
+ "33323334325a301a311830160603550403130f5253414b65795472616e736665723230819f300d06092a864886f70d010101"
+ "050003818d0030818902818100ea5a3834bfb863ae481b696ea7010ba4492557a160a102b3b4d11c120a7128f20b656ebbd2"
+ "4b426f1a6d40be0a55ca1b53ebdca202d258eebb20d5c662819182e64539360461dd3b5dda4085f10250fc5249cf023976b8"
+ "db2bc5f5e628fdb0f26e1b11e83202cbcfc9750efd6bb4511e6211372b60a97adb984779fdae21ce070203010001a30f300d"
+ "300b0603551d0f040403020520300d06092a864886f70d0101050500038181004dc6f9fd6054ae0361d28d2d781be590fa8f"
+ "5685fedfc947e315db12a4c47e220601e8c810e84a39b05b7a89f87425a06c0202ad48b3f2713109f5815e6b5d61732dac45"
+ "41da152963e700a6f37faf7678f084a9fb4fe88f7b2cbc6cdeb0b9fdcc6a8a16843e7bc281a71dc6eb8bbc4092d299bf7599"
+ "a3492c99c9a3acf41b29").HexToByteArray();
// password = "1111"
public static byte[] s_RSAKeyTransfer2Pfx =
("308205d20201033082058e06092a864886f70d010701a082057f0482057b308205773082034806092a864886f70d010701a0"
+ "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103"
+ "300e04080338620310d29656020207d0048202804a94d3b1a1bf43efe3726aa9f0abc90c44585d2f0aee0864b4d574cd2cc1"
+ "dca4a353b102779e072ed6072d3c083b83974e74069b353ba8ac8be113228e0225993f5ecb7293ab1a6941bef75f7bcb0e3b"
+ "e6902832be46b976e94c6a0bc6865822ff07371551d206e300558da67cf972d89c3d181beb86d02f5523baa8351b88992654"
+ "a4c507e136dd32120530585a25424fe40f9962b910e08fb55f582c3764946ba7f6d92520decfc9faa2d5e180f9824e5ed4c8"
+ "c57e549a27950e7a875f2ed450035a69de6d95ec7bd9e30b65b8563fdd52809a4a1fc960f75c817c72f98afb000e8a8a33be"
+ "f62e458c2db97b464121489bf3c54de45e05f9c3e06c21892735e3f2d9353a71febcd6a73a0af3c3fc0922ea71bdc483ed7e"
+ "5653740c107cfd5e101e1609c20061f864671ccb45c8b5b5b7b48436797afe19de99b5027faf4cead0fd69d1987bbda5a0a4"
+ "0141495998d368d3a4747fc370205eed9fc28e530d2975ca4084c297a544441cf46c39fb1f0f42c65b99a6c9c970746012ad"
+ "c2be15fbbc803d5243f73fdec50bdee0b74297bd30ca3ea3a1dc623db6a199e93e02053bd1a6ca1a00a5c6090de1fa10cdd5"
+ "b5541bd5f5f92ff60a139c50deff8768e7b242018611efd2cce0d9441f3c8b207906345a985617ba5e98e7883c9b925ba17d"
+ "c4fadddbbe025cecd24bb9b95cae573a8a24ceb635eb9f663e74b0084a88f4e8e0d2baf767be3abe5b873695989a0edac7bd"
+ "092de79c3b6427dcbedee0512918fc3f7a45cd6898701673c9ed9f2f873abb8aa64cec7b8d350e8c780c645e50ce607a1afd"
+ "bcefba6cf5cebbc766d1e61d78fbef7680b38dd0f32133ceb39c6c9cabd0b33af9f7ef73c94854b57cf68e61997b61393a0b"
+ "6fc37f8834157e0c9fba3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e"
+ "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074"
+ "006f0072006100670065002000500072006f007600690064006500723082022706092a864886f70d010701a0820218048202"
+ "14308202103082020c060b2a864886f70d010c0a0103a08201e4308201e0060a2a864886f70d01091601a08201d0048201cc"
+ "308201c830820131a00302010202102bce9f9ece39f98044f0cd2faa9a14e7300d06092a864886f70d0101050500301a3118"
+ "30160603550403130f5253414b65795472616e7366657232301e170d3136303332353231323334325a170d31373033323630"
+ "33323334325a301a311830160603550403130f5253414b65795472616e736665723230819f300d06092a864886f70d010101"
+ "050003818d0030818902818100ea5a3834bfb863ae481b696ea7010ba4492557a160a102b3b4d11c120a7128f20b656ebbd2"
+ "4b426f1a6d40be0a55ca1b53ebdca202d258eebb20d5c662819182e64539360461dd3b5dda4085f10250fc5249cf023976b8"
+ "db2bc5f5e628fdb0f26e1b11e83202cbcfc9750efd6bb4511e6211372b60a97adb984779fdae21ce070203010001a30f300d"
+ "300b0603551d0f040403020520300d06092a864886f70d0101050500038181004dc6f9fd6054ae0361d28d2d781be590fa8f"
+ "5685fedfc947e315db12a4c47e220601e8c810e84a39b05b7a89f87425a06c0202ad48b3f2713109f5815e6b5d61732dac45"
+ "41da152963e700a6f37faf7678f084a9fb4fe88f7b2cbc6cdeb0b9fdcc6a8a16843e7bc281a71dc6eb8bbc4092d299bf7599"
+ "a3492c99c9a3acf41b293115301306092a864886f70d0109153106040401000000303b301f300706052b0e03021a04143cdb"
+ "6a36dfd2288ba4e3771766d7a5289c04419704146c84193dc4f3778f21197d11ff994d8bf4822049020207d0").HexToByteArray();
public static byte[] s_RSAKeyTransfer3Cer =
("308201c830820131a00302010202104497d870785a23aa4432ed0106ef72a6300d06092a864886f70d0101050500301a3118"
+ "30160603550403130f5253414b65795472616e7366657233301e170d3136303332353231323335355a170d31373033323630"
+ "33323335355a301a311830160603550403130f5253414b65795472616e736665723330819f300d06092a864886f70d010101"
+ "050003818d0030818902818100bbc6fe8702a4e92eadb9b0f41577c0fffc731411c6f87c27c9ef7c2e2113d4269574f44f2e"
+ "90382bd193eb2f57564cf00092172d91a003e7252a544958b30aab6402e6fba7e442e973d1902e383f6bc4a4d8a00e60b3f3"
+ "3a032bdf6bedb56acb0d08669b71dd7b35f5d39d9914f5e111e1cd1559eb741a3075d673c39e7850a50203010001a30f300d"
+ "300b0603551d0f040403020520300d06092a864886f70d01010505000381810058abccbf69346360351d55817a61a6091b0b"
+ "022607caeb44edb6f05a91f169903608d7391b245ac0dcbe052e16a91ac1f8d9533f19f6793f15cb6681b2cbaa0d8e83d77b"
+ "5207e7c70d843deda8754af8ef1029e0b68c35d88c30d7da2f85d1a20dd4099facf373341b50a8a213f735421062e1477459"
+ "6e27a32e23b3f3fcfec3").HexToByteArray();
// password = "1111"
public static byte[] s_RSAKeyTransfer3Pfx =
("308205d20201033082058e06092a864886f70d010701a082057f0482057b308205773082034806092a864886f70d010701a0"
+ "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103"
+ "300e0408a9197ad512c316b5020207d004820280b1c213fa87f3906cde3502249830a01d1d636d0058bd8d6172222544c35a"
+ "9676f390a5ef1d52f13fae2f04fe2ca1bcb9914296f97fdf729a52e0c3472c9f7ae72bd746f0a66b0c9363fae0328ad063fa"
+ "45d35cc2679c85e970c7420ad036012ce553ef47ed8fe594917739aab1123be435a0ca88ac4b85cf3d341d4aeb2c6816d8fc"
+ "a2e9611224b42f0ca00bde4f25db460200f25fe99ed4fd0236e4d00c48085aec4734f0bce7e6c8fea08b11a2a7214f4a18c0"
+ "fa4b732c8dae5c5857f2edec27fa94eb17ac05d1d05b321b01c1368231ff89c46c6378abf67cb751156370bbcc35591e0028"
+ "d4ace5158048d9d25b00e028b7766f1c74ade9603a211aad241fc3b7599a2b15f86846dfdc106f49cf56491b3f6ff451d641"
+ "400f38fabcdb74a4423828b041901fa5d8c528ebf1cc6169b08eb14b2d457acb6970a11ccaa8fbc3b37b6454803b07b1916e"
+ "2ad3533f2b72721625c11f39a457033744fde3745c3d107a3f1e14118e04db41ca8970a383e8706bcf8ba5439a4cb360b250"
+ "4fcae3dbfb54af0154f9b813ad552f2bdbc2a9eb61d38ae5e6917990cbeb1c5292845637c5fed477dabbed4198a2978640ba"
+ "7db22c85322115fa9027ad418a61e2e31263da3776398faaaab818aae6423c873bd393f558fa2fc05115b4983d35ecfeae13"
+ "601519a53c7a77b5688aeddc6f210a65303eeb0dbd7e3a5ec94d7552cf4cbe7acebf5e4e10abaccd2e990f1cf217b98ad9b5"
+ "06820f7769a7c5e61d95462918681c2b111faf29f13e3615c4c5e75426dbcd903c483590434e8ab1965dc620e7d8bebea36f"
+ "53f1bc0807933b0ef9d8cc1b36b96aff8288e9a8d1bba24af562dfeb497b9a58083b71d76dacd6f2ce67cb2593c6f06472ef"
+ "e508012c34f40d87e0be3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e"
+ "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074"
+ "006f0072006100670065002000500072006f007600690064006500723082022706092a864886f70d010701a0820218048202"
+ "14308202103082020c060b2a864886f70d010c0a0103a08201e4308201e0060a2a864886f70d01091601a08201d0048201cc"
+ "308201c830820131a00302010202104497d870785a23aa4432ed0106ef72a6300d06092a864886f70d0101050500301a3118"
+ "30160603550403130f5253414b65795472616e7366657233301e170d3136303332353231323335355a170d31373033323630"
+ "33323335355a301a311830160603550403130f5253414b65795472616e736665723330819f300d06092a864886f70d010101"
+ "050003818d0030818902818100bbc6fe8702a4e92eadb9b0f41577c0fffc731411c6f87c27c9ef7c2e2113d4269574f44f2e"
+ "90382bd193eb2f57564cf00092172d91a003e7252a544958b30aab6402e6fba7e442e973d1902e383f6bc4a4d8a00e60b3f3"
+ "3a032bdf6bedb56acb0d08669b71dd7b35f5d39d9914f5e111e1cd1559eb741a3075d673c39e7850a50203010001a30f300d"
+ "300b0603551d0f040403020520300d06092a864886f70d01010505000381810058abccbf69346360351d55817a61a6091b0b"
+ "022607caeb44edb6f05a91f169903608d7391b245ac0dcbe052e16a91ac1f8d9533f19f6793f15cb6681b2cbaa0d8e83d77b"
+ "5207e7c70d843deda8754af8ef1029e0b68c35d88c30d7da2f85d1a20dd4099facf373341b50a8a213f735421062e1477459"
+ "6e27a32e23b3f3fcfec33115301306092a864886f70d0109153106040401000000303b301f300706052b0e03021a0414cd11"
+ "0833d653f2e18d2afb2de74689ff0446ec7d0414f2ca1c390db19317697044b9012ef6864e0f05cc020207d0").HexToByteArray();
public static byte[] s_RSAKeyTransferCapi1Cer =
("3082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e03021d0500301e311c301a0603"
+ "55040313135253414b65795472616e736665724361706931301e170d3135303431353037303030305a170d32353034313530"
+ "37303030305a301e311c301a060355040313135253414b65795472616e73666572436170693130819f300d06092a864886f7"
+ "0d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03e301c37d9bff6d75b6eb6671ba"
+ "9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6c9d2b4e283ea3535923f398a31"
+ "2a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4111299f99424408d0203010001"
+ "a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e311c301a060355040313135253"
+ "414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca300906052b0e03021d050003818100"
+ "81e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c5931662d9ecd8b1e7b81749e48468167"
+ "e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957d653b5c78e5291e4401045576f"
+ "6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a429646").HexToByteArray();
// Password = "1111"
//
// Built by:
//
// makecert -r -len 1024 -n "CN=RSAKeyTransferCapi1" -b 04/15/2015 -e 04/15/2025 RSAKeyTransferCapi1.cer -sv RSAKeyTransferCapi1.pvk -sky exchange
// pvk2pfx.exe -pvk RSAKeyTransferCapi1.pvk -spc RSAKeyTransferCapi1.cer -pfx RSAKeyTransferCapi1.pfx -po 1111
//
public static byte[] s_RSAKeyTransferCapi1Pfx =
("30820626020103308205e206092a864886f70d010701a08205d3048205cf308205cb3082035806092a864886f70d010701a0"
+ "82034904820345308203413082033d060b2a864886f70d010c0a0102a08202b6308202b2301c060a2a864886f70d010c0103"
+ "300e0408dbd82a9abd7c1a2b020207d004820290768873985e74c2ece506531d348d8b43f2ae8524a2bcc737eeb778fac1ee"
+ "b21f82deb7cf1ba54bc9a865be8294de23e6648ffb881ae2f0132265c6dacd60ae55df1497abc3eb9181f47cb126261ea66f"
+ "d22107bbcdb8825251c60c5179ef873cb7e047782a4a255e3e9d2e0dd33f04cde92f9d268e8e4daf8ba74e54d8b279a0e811"
+ "9a3d0152608c51331bbdd23ff65da492f85809e1d7f37af9ae00dca796030a19e517e7fe2572d4502d4738fd5394ee369216"
+ "fb64cf84beab33860855e23204156dcf774fac18588f1c1ca1a576f276e9bfbf249449842f193020940a35f163378a2ce7da"
+ "37352d5b0c7c3ac5eb5f21ed1921a0076523b2e66a101655bb78d4ecc22472ac0151b7e8051633747d50377258ab19dcb22e"
+ "e09820876607d3291b55bba73d713d6689486b310507316b4f227383e4869628ad31f0b431145d45f4f38f325772c866a20e"
+ "0b442088cbf663e92e8ee82dd495fba8d40345474a384bb3b80b49ca1d66eef5321235135dcc0a5425e4bf3b8ce5c2469e2a"
+ "c0f8d53aab276361d9a2ff5c974c6e6b66126158676331fe7f74643fd1e215b22d7799846651350ed0f1f21a67ac6b3bfd62"
+ "7defb235ef8732d772d1c4bea2ae80c165f0182f547ea7a3f3366288f74c030689988a9838c27b10a48737a620d8220f68b4"
+ "ea8d8eb26298d5359d54a59c6be6716cefc12c929e17bb71c57c560659a7757ba8ac08ae90794474e50f0e87a22e2b7c3ebd"
+ "061390928bf48c6c6200c225f7025eab20f5f6fee5dc41682b2d4a607c8c81964b7d52651e5a62a41f4e8ea3982c294a4aee"
+ "8a67dc36a8b34b29509a4868c259dc205d1e8a3b6259a76a147f002f3bfbc8378e8edd230a34f9cd5f13ce6651b10394709d"
+ "5092bb6a70d8c2816f1c0e44cd45dfa7c2d94aa32112d79cb44a3174301306092a864886f70d010915310604040100000030"
+ "5d06092b060104018237110131501e4e004d006900630072006f0073006f006600740020005300740072006f006e00670020"
+ "00430072007900700074006f0067007200610070006800690063002000500072006f007600690064006500723082026b0609"
+ "2a864886f70d010701a082025c048202583082025430820250060b2a864886f70d010c0a0103a082022830820224060a2a86"
+ "4886f70d01091601a0820214048202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906"
+ "052b0e03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135"
+ "3037303030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243"
+ "6170693130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2b"
+ "c27b03e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec8"
+ "6aa8f6c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a3"
+ "36baa4111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa1"
+ "20301e311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4c"
+ "ca300906052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c"
+ "5931662d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075"
+ "d11957d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a429646311530130609"
+ "2a864886f70d0109153106040401000000303b301f300706052b0e03021a041463c18f4fec17cf06262e8acd744e18b8ab7b"
+ "8f280414134ec4a25653b142c3d3f9999830f2ac66ef513b020207d0").HexToByteArray();
public static byte[] s_RSASha256KeyTransfer1Cer =
("308201d43082013da003020102021072c6c7734916468c4d608253da017676300d06092a864886f70d01010b05003020311e"
+ "301c060355040313155253415368613235364b65795472616e7366657231301e170d3136303431383130353934365a170d31"
+ "37303431383136353934365a3020311e301c060355040313155253415368613235364b65795472616e736665723130819f30"
+ "0d06092a864886f70d010101050003818d0030818902818100cad046de3a7f6dc78fc5a4e01d1f7d90db596f586334d5708a"
+ "ecb8e52d6bb912c0b5ec9633a82b4abac4c2860c766f2fdf1c905c4a72a54adfd041adabe5f2afd1e2ad88615970e818dc3d"
+ "4d00bb6c4ce94c5eb4e3efedd80d14c3d295ea471ae430cbb20b071582f1396369fbe90c14aa5f85b8e3b14011d81fbd41ec"
+ "b1495d0203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010b050003818100baed2a5ae2d1"
+ "1ee4209c0694c790e72e3e8ad310b2506b277d7c001b09f660d48dba846ac5bbef97653613adf53d7624fc9b2b337f25cb33"
+ "74227900cfefbe2fdac92b4f769cf2bf3befb485f282a85bfb09454b797ce5286de560c219fb0dd6fce0442adbfef4f767e9"
+ "ac81cf3e9701baf81efc73a0ed88576adff12413b827").HexToByteArray();
// password = "1111"
public static byte[] s_RSASha256KeyTransfer1Pfx =
("308205de0201033082059a06092a864886f70d010701a082058b04820587308205833082034806092a864886f70d010701a0"
+ "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103"
+ "300e040829e4911057aa5fb6020207d00482028052e016e1e339ca6a648ab1e152813899bd2ec0de1e34804c33e109cf2136"
+ "d42edc0d5ff8a005939ec38d4284aa0cfda295e801b701855c3c129e9311dc80b3538ba76d3164d48d83a73949d695f42294"
+ "75469f262c807767bc5c12bb83b2c4857fa9f8c7c519143136ba93ab93e17ad4b0b63cf6449708e6128425b00eaeae6bc5b6"
+ "7ff092673c9aabbbb63e90424295f0ae828bcd00f5ad85fe8384711ca5fffd4cbfe57ddbc3e5bb1df19e6fd7640fbd8d4516"
+ "f8d2d5ec84baca72ac42b50e77be0055dfdbbbe9c6de42c06fc86de8fbfc6231db89b30065d534e76aa851833b6c9c651288"
+ "c12f87ba12ae429e9bec0b22297c666046355ebd5a54dc7f13a55e0ebd53c768f69eee57d6041263f5bdf1c4c5b2b55dfb9b"
+ "38171aaed0d21fd5a41e0ef760db42f373c9007e1df47fd79ba9b41528c9c02dffdd04472265763ae94f4e05b86976a2c459"
+ "093d8e6bb0d0c5da5994fe3edbdf843b67e8e4c4daf59351788bf8b96da116aecbb95d52bf727ff10ca41340112f0bcb41e0"
+ "b8373a6e55727c745b77cf1944b74fa447ed0a6d93b8e43fd6e4b4b3e0d49d03ee2ee12d15519406c49a4c1be70de5171c93"
+ "d056e9f47b8a96d50f01873be4c596590f1247a2f2822dea9339fa87dd49545b559e0225ab738ecc0b054155749670d412be"
+ "472d13dfb0a8c8f56b3c0be1aa0d9195ba937b0c2119c702a0be1f83e1b4a77375ed1654e3dcf6b8ce119db3ac7cd440369a"
+ "b0b964e0b526b865680015cc3046a20badeaca4543ce65042ff5eb691e93232754a7b34fd8b6833c2625fdfdc59d80b3dcb4"
+ "ce70d1833ecf6344bb7331e46b71bb1592b6d814370548ee2b2f4df207696be87d2e1e0c5dc0ca528e5a231802cbb7853968"
+ "beb6ceb1b3a2998ecd313174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e"
+ "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074"
+ "006f0072006100670065002000500072006f007600690064006500723082023306092a864886f70d010701a0820224048202"
+ "203082021c30820218060b2a864886f70d010c0a0103a08201f0308201ec060a2a864886f70d01091601a08201dc048201d8"
+ "308201d43082013da003020102021072c6c7734916468c4d608253da017676300d06092a864886f70d01010b05003020311e"
+ "301c060355040313155253415368613235364b65795472616e7366657231301e170d3136303431383130353934365a170d31"
+ "37303431383136353934365a3020311e301c060355040313155253415368613235364b65795472616e736665723130819f30"
+ "0d06092a864886f70d010101050003818d0030818902818100cad046de3a7f6dc78fc5a4e01d1f7d90db596f586334d5708a"
+ "ecb8e52d6bb912c0b5ec9633a82b4abac4c2860c766f2fdf1c905c4a72a54adfd041adabe5f2afd1e2ad88615970e818dc3d"
+ "4d00bb6c4ce94c5eb4e3efedd80d14c3d295ea471ae430cbb20b071582f1396369fbe90c14aa5f85b8e3b14011d81fbd41ec"
+ "b1495d0203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010b050003818100baed2a5ae2d1"
+ "1ee4209c0694c790e72e3e8ad310b2506b277d7c001b09f660d48dba846ac5bbef97653613adf53d7624fc9b2b337f25cb33"
+ "74227900cfefbe2fdac92b4f769cf2bf3befb485f282a85bfb09454b797ce5286de560c219fb0dd6fce0442adbfef4f767e9"
+ "ac81cf3e9701baf81efc73a0ed88576adff12413b8273115301306092a864886f70d0109153106040401000000303b301f30"
+ "0706052b0e03021a0414282ee1780ac2a08b2783b1f8f7c855fb1a53ce9e04143fad59471323dc979f3bf29b927e54eca677"
+ "7576020207d0").HexToByteArray();
public static byte[] s_RSASha384KeyTransfer1Cer =
("308201d43082013da00302010202103c724fb7a0159a9345caac9e3df5f136300d06092a864886f70d01010c05003020311e"
+ "301c060355040313155253415368613338344b65795472616e7366657231301e170d3136303431383131303530365a170d31"
+ "37303431383137303530365a3020311e301c060355040313155253415368613338344b65795472616e736665723130819f30"
+ "0d06092a864886f70d010101050003818d0030818902818100e6b46b0e6f4f6df724081e11f201b9fbb07f2b6db2b868f607"
+ "68e2b5b843f690ca5e8d48f439d8b181ace2fb27dfa07eff0324642d6c9129e2d95e136702f6c31fe3ccf3aa87ba9f1b6f7b"
+ "acd07156ff3dd2a7f4c70356fb94b0adbde6819383c19bbefb4a6d1d6491a770d5f9feb11bcb3e5ac99cb153984dee0910e4"
+ "b57f8f0203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010c0500038181003842cc95a680"
+ "c8a31534a461d061a4706a0aba52b7a1c709c2f1e3b94acf6dc0930b74e63e3babf3c5b11c8f8a888722d9f23c7e0a8c9b09"
+ "90ebcdbce563b8d4209efc1b04750f46c8c6117ccb96b26b5f02b0b5f961ab01b0c3b4cdb2530cbc5dcf37786712a3476ce7"
+ "32c5c544c328db5ebc3a338b18fe32aedaffedd973ef").HexToByteArray();
// password = "1111"
public static byte[] s_RSASha384KeyTransfer1Pfx =
("308205de0201033082059a06092a864886f70d010701a082058b04820587308205833082034806092a864886f70d010701a0"
+ "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103"
+ "300e040856d7d59810ce8b17020207d00482028082012797edb5f74429bb6b91dd1e24aa32a19b89d92fd486e826773a7a11"
+ "03a9b49d98c6b7e97d411d19b44cd79559964f31cb6f0443c70d687c390d31c656ee3887391ae1735c142d891ec8337c5dc4"
+ "d6b5a4f09400a4cc35dd8dbde831f7625b7afedf4990294988b0b32b2889c97cd85c2568ffef332be83232449dd4083a43d4"
+ "89e654520eb922239379b5e9f5dfc1e64972339dee27dfdd874e2ee2b85f941f3b313ab881571c3a5a9b292d8c82d79d74a0"
+ "2d78dd5cfce366b3a914b61b861b35948757d137e5d53589a0fa2f1b4d06ee6b4aa4b8d3f526b059637b236ceb2de128d7bd"
+ "f91c12612d09e1cb4bed1b5e336fb56424b68dcc6d6cd5d90f666047c8b181526a60622027d322db0172046c23e84a3c725e"
+ "45ce774df037cafb74b359c3ec6874dce98673d9f7581f54dcb6e3c40583de2de6aaf6739bba878362e9bfab331cab2eb22d"
+ "3b130dec4eedf55a7ed8d5960e9f037209f9c1ef584c6dd5de17245d0da62c54420dc862b6648418d2aa9797f86a2cd0ecf6"
+ "abcbeb16907d8f44021690682a4e1286cd3f9aea4866108b3c968cf4b80a39c60436079617346861662e01a5419d8cebe2c6"
+ "e186141e42baf7cfc596270dbab8db03da9bd501daa426e24aa2d8ccf4d4512a8dce3ae8954be69b5c3a70fac587ac91ad97"
+ "fb427c8118659b710b57183c4fd16ffd276834e2fe45d74e175f3f5077783cdd7668b4e87217512ceb7f3e64715ba22bbab7"
+ "0d1b3485820c16304758cf1dd0b806d801f1185bb14d12f2c147ec65b95088077dec23498ebe40a952727c559c7af5cf20f1"
+ "f491f4123db093dc1a67014c3db46c11c7d5833b15167c91138eba6b4badf869aefba5fbea523a5ad02bb676db6039e7aabd"
+ "44f0702d59cf3d1ad9bb3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e"
+ "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074"
+ "006f0072006100670065002000500072006f007600690064006500723082023306092a864886f70d010701a0820224048202"
+ "203082021c30820218060b2a864886f70d010c0a0103a08201f0308201ec060a2a864886f70d01091601a08201dc048201d8"
+ "308201d43082013da00302010202103c724fb7a0159a9345caac9e3df5f136300d06092a864886f70d01010c05003020311e"
+ "301c060355040313155253415368613338344b65795472616e7366657231301e170d3136303431383131303530365a170d31"
+ "37303431383137303530365a3020311e301c060355040313155253415368613338344b65795472616e736665723130819f30"
+ "0d06092a864886f70d010101050003818d0030818902818100e6b46b0e6f4f6df724081e11f201b9fbb07f2b6db2b868f607"
+ "68e2b5b843f690ca5e8d48f439d8b181ace2fb27dfa07eff0324642d6c9129e2d95e136702f6c31fe3ccf3aa87ba9f1b6f7b"
+ "acd07156ff3dd2a7f4c70356fb94b0adbde6819383c19bbefb4a6d1d6491a770d5f9feb11bcb3e5ac99cb153984dee0910e4"
+ "b57f8f0203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010c0500038181003842cc95a680"
+ "c8a31534a461d061a4706a0aba52b7a1c709c2f1e3b94acf6dc0930b74e63e3babf3c5b11c8f8a888722d9f23c7e0a8c9b09"
+ "90ebcdbce563b8d4209efc1b04750f46c8c6117ccb96b26b5f02b0b5f961ab01b0c3b4cdb2530cbc5dcf37786712a3476ce7"
+ "32c5c544c328db5ebc3a338b18fe32aedaffedd973ef3115301306092a864886f70d0109153106040401000000303b301f30"
+ "0706052b0e03021a041429bd86de50f91b8f804b2097b1d9167ca56577f40414b8714b8172fa1baa384bed57e3ddb6d1851a"
+ "f5e9020207d0").HexToByteArray();
public static byte[] s_RSASha512KeyTransfer1Cer =
("308201d43082013da00302010202102f5d9d58a5f41b844650aa233e68f105300d06092a864886f70d01010d05003020311e"
+ "301c060355040313155253415368613531324b65795472616e7366657231301e170d3136303431383131303532355a170d31"
+ "37303431383137303532355a3020311e301c060355040313155253415368613531324b65795472616e736665723130819f30"
+ "0d06092a864886f70d010101050003818d0030818902818100b2eca20240da8486b1a933ade62ad8781ef30d4434ebbc9b3f"
+ "c9c550d0f9a75f4345b5520f3d0bafa63b8037785d1e8cbd3efe9a22513dc8b82bcd1d44bf26bd2c292205ca3e793ff1cb09"
+ "e0df4afefb542362bc148ea2b76053d06754b4a37a535afe63b048282f8fb6bd8cf5dc5b47b7502760587f84d9995acbf1f3"
+ "4a3ca10203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010d050003818100493d857684d2"
+ "7468dd09926d20933254c7c79645f7b466e7b4a90a583cedba1c3b3dbf4ccf1c2506eb392dcf15f53f964f3c3b519132a38e"
+ "b966d3ea397fe25457b8a703fb43ddab1c52272d6a12476df1df1826c90fb679cebc4c04efc764fd8ce3277305c3bcdf1637"
+ "91784d778663194097180584e5e8ab69039908bf6f86").HexToByteArray();
// password = "1111"
public static byte[] s_RSASha512KeyTransfer1Pfx =
("308205de0201033082059a06092a864886f70d010701a082058b04820587308205833082034806092a864886f70d010701a0"
+ "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103"
+ "300e04083a0e344b65dd4e27020207d00482028014464df9f07d2cb37a28607570130de5877e829e759040976866afc831db"
+ "4d2741734ae53ea5eb80c1080dae7b0a2acddabd3d47b1ed5f3051455429308f3b7b0b48c5a4dbc5d718534472c746ce62f1"
+ "bbb8c5d178c1d3e91efdbd4f56569517bcadf3c81dbe4c34746194e47bcf46b74cd1880d7bd12d9b819b462fbcf6f51f3972"
+ "2858c9b9af8975bfefd7f007928b39e11d50b612761d03e566b992f92e9c9873d138c937fc43fe971db4c8e57b51aeef4ed0"
+ "022ec76c3bb4bd9f2395b99585449303a6d68183edf6e5dda1885531bee10b7cf6509390f4ee6a37ed2931d658548bd6390f"
+ "a7094fdf017166309074c00581d2b7dcaaee657f9c48e08edf636004dc5e60486dd022c45058700fe682472b371380948792"
+ "74c2a20dd9e07e149e7ab52157db748160ad81f91019297baa58ce68656b0b2f7c9ac88b3da6920c2a5eab7bcc2629974f8a"
+ "6c8bf33629af05e4e34d5d24393448e9751b7708f5915b0fd97a5af4dd5a37d71b18b6526316cbc65b1c6af8a6779acbc470"
+ "2381f027bdb118cb84e9005b02a8bd2d02365d280cffb04831f877de7bd3d3287f11beed8978a5389e2b28317eb90569781f"
+ "94f66f672736a09b4a7caeaaefd1909f2d20255df51512dbd08ec6125455d932b626bdfd3c4f669148fa783671f90b59ceff"
+ "560c338f92cbe8bf7fbab4db3e9b943effac747eb34f06bd72aee961ed31742caa2a9934a5fe4685677ecbca6fb1b1c0b642"
+ "b4f71d55d0e2cb1dc10ce845514090cc117a875c4d10c0ce367e31091144eacd7e600792d61d036bde020e3bb9a004a7dd1a"
+ "cf03541b6fff3bcef4c30df05d98b75688320685261b2b34813407b20a7c92a04eeb46cb7e618a6ee32154728ba6735668f4"
+ "11abece4ba07426a394b3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e"
+ "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074"
+ "006f0072006100670065002000500072006f007600690064006500723082023306092a864886f70d010701a0820224048202"
+ "203082021c30820218060b2a864886f70d010c0a0103a08201f0308201ec060a2a864886f70d01091601a08201dc048201d8"
+ "308201d43082013da00302010202102f5d9d58a5f41b844650aa233e68f105300d06092a864886f70d01010d05003020311e"
+ "301c060355040313155253415368613531324b65795472616e7366657231301e170d3136303431383131303532355a170d31"
+ "37303431383137303532355a3020311e301c060355040313155253415368613531324b65795472616e736665723130819f30"
+ "0d06092a864886f70d010101050003818d0030818902818100b2eca20240da8486b1a933ade62ad8781ef30d4434ebbc9b3f"
+ "c9c550d0f9a75f4345b5520f3d0bafa63b8037785d1e8cbd3efe9a22513dc8b82bcd1d44bf26bd2c292205ca3e793ff1cb09"
+ "e0df4afefb542362bc148ea2b76053d06754b4a37a535afe63b048282f8fb6bd8cf5dc5b47b7502760587f84d9995acbf1f3"
+ "4a3ca10203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010d050003818100493d857684d2"
+ "7468dd09926d20933254c7c79645f7b466e7b4a90a583cedba1c3b3dbf4ccf1c2506eb392dcf15f53f964f3c3b519132a38e"
+ "b966d3ea397fe25457b8a703fb43ddab1c52272d6a12476df1df1826c90fb679cebc4c04efc764fd8ce3277305c3bcdf1637"
+ "91784d778663194097180584e5e8ab69039908bf6f863115301306092a864886f70d0109153106040401000000303b301f30"
+ "0706052b0e03021a041401844058f6e177051a87eedcc55cc4fa8d567ff10414669cb82c9cc3ceb4d3ca9f65bd57ba829616"
+ "60d9020207d0").HexToByteArray();
public static byte[] s_RSA2048Sha256KeyTransfer1Cer =
("3082031e30820206a003020102020900dce4d72a7f3ca58e300d06092a86"
+ "4886f70d01010b050030243122302006035504030c195253413230343853"
+ "68613235364b65795472616e7366657231301e170d313930313033323034"
+ "3133345a170d3238313233313230343133345a3024312230200603550403"
+ "0c19525341323034385368613235364b65795472616e7366657231308201"
+ "22300d06092a864886f70d01010105000382010f003082010a0282010100"
+ "bf8495ef84c91eb42ae9196c52aa2c6e22a258c4d76e09e93980d81fafe6"
+ "977fe1a3c8b4e9ca414405a1a4db6d549a4849189d568aa639f10fa556f5"
+ "5377c8fde8ec33ccdc833c4c5b8b36275e8f1899443871b7363f204a2826"
+ "8bd9e890fdd488b17bc49890f78fab5d8a5927b69655760d400a30e0ee87"
+ "dd38b4168df6814596e0efaafb2f9cc134664bb8629e65aa107847b4416b"
+ "d57f0b701c30e9a160aa589646e981815d9823201ae0ee601208c51c08d3"
+ "e50b1fab1560802916e678310c03e3cff3bcc039f98d5b254e2baf027ae9"
+ "f78faef72c2d93075eca64b5ad3e92348068c4dcb8cad0bad954a7d04fce"
+ "3aff94ef8cf282095db75a25a4114f8f0203010001a3533051301d060355"
+ "1d0e04160414fedfd2558b95e705584a50008ed0d1683aee840e301f0603"
+ "551d23041830168014fedfd2558b95e705584a50008ed0d1683aee840e30"
+ "0f0603551d130101ff040530030101ff300d06092a864886f70d01010b05"
+ "00038201010031c46689db724a1a8d268eaa7139efcf8a31496f15f325a1"
+ "9349547114d7992ead5fa0bd6ffd5539b1639f0cf8f975c5e9ebed8a0482"
+ "89c782ec7e0342f339f53e811cc6a6864173502388875964f0c50d84aba9"
+ "228dd2e3ddd3339374b76a6826f4f848a403adda2e095974232b084c8672"
+ "b12c18d675d81ed8fa4b15a1c7abc73f9ccb5bc25716eeb9d2c97f8ebcb9"
+ "d4824fb23c7fbc78e1d3b9b1b3749f6c0981b2b6cc81dc723aa5cc589346"
+ "dceca222c78f68fe80563e12282f7df936a161163f86a9eadba2e180a906"
+ "de73aebeea0775f6ab9ae97c71f26e187e3d8cb50c8137663c99d440877d"
+ "5a5e17df9785976e9031dd96134a07899281b6b64e3f").HexToByteArray();
public static byte[] s_RSA2048Sha256KeyTransfer1Pfx =
("308209710201033082093706092a864886f70d010701a08209280482092430820920308203c706092a864886f70d010706a0"
+ "8203b8308203b4020100308203ad06092a864886f70d010701301c060a2a864886f70d010c0106300e04081681e2854fdf32"
+ "7702020800808203807561ee3de7d54036ba61f41f76155bd406cd909358a12db40e07698863cc1143c77becf6dcb87a4a8a"
+ "701c8ff59021431a98ff6193c6d36e3bd7d11806c788042bc6f5dbceede60a1d6a314300ceca09b571e1a7842db92e19185b"
+ "e2408db8458d3e9127096b1f8a8c493aebc22bdfeb48bcd6d592b9db1d075fc7468cae8bf5bc01a0fa93bb2047981c5a4e23"
+ "f8c8e7795b1f94f5fbe2dbd03578ae2cdf13560bb73c219d258919f002217cb15a8b6e037da01c1de49b4c699c74c5396cf8"
+ "67bb308026c3a6b85da079de0aedecea0770a6b76128d185fc94a955789f3f26ffb99689b7311c7619ad24a33c6be16e022b"
+ "7216de49e1f11c9b4ded79aa438f535dbdb8bcc9f58ed2b3cd62515c5742f5e2ae0e9f791b83d4ebba5b3766e10194ae27f0"
+ "68960d039777c5ce71b11da9a4c791f612e06cddd2e474cfb8bda95faf88f6a854c26f6c787d20db07aa777f6ec2c208760c"
+ "67cb51cc5c79e13ba2760013d4ff54ab33a0aff355fea7aabd607a4fd8449d16173249be6785be5fa2e415932b6be65b483c"
+ "718e151e820bb4930f7df183cfa8c4a88b989a133ddb1717ea5b73f0950bf485de09d335347a16b96f02a4417e3671856c19"
+ "8b45462a21ce0df8f8e4c5178aae1999dc936aff91512ef9b7667de37e924118a6e958b111bf33088938987136143fa28ec7"
+ "216f77f4fecf87cfe3cd6af4d73a2e544d2f24a915de8d619faf0a4b891f09a9365bdd6dc48bc1eed864354e84c1bf0bc9dd"
+ "99a9e1280f6c81501424700960209ce0da9fd9e1b462d06673bb041439c8726f2b8890b90e859f717478637594675299c29c"
+ "da3f2dc6b6b9f1b72befc542407f180c89204774965c277fec78905b14b0ba54d19a9e8c3eb9c6ec6d056773a248908a6483"
+ "de20539b75de610c4ebdc77dc3a903a7e00fb1f6f46bfc97fe08a75b9d82bc4c536e4c71cf7c88d2eb57c50a97278ea5a254"
+ "1c5ee418f2aeccf800dd1dee31aacb4e6c679c58400757817a08ad7ec12e128f2e177bf2870d68c6d9fb4b2987abee13bfc1"
+ "7b529dd00edc8eea55fc8268e02dcbd84e7cb2cfe1ae8d4c1fb0a486871e18ddde79759ad0127e5dac938a105aaee9368901"
+ "186c149424ec992b57fe927b1f6c35142229e3d427a0d86d454d302c3cf4fa4f1b75c42813e8029a1428570aa1903acde079"
+ "6d0d2259780bf4752a70788fc642c372009f57cd430ee2edc01954e5a615744e7cd3bd8784e3c3b80b0b63847464207f92ec"
+ "821dd564f43082055106092a864886f70d010701a08205420482053e3082053a30820536060b2a864886f70d010c0a0102a0"
+ "8204fe308204fa301c060a2a864886f70d010c0103300e04084dcda62e7b3f05f602020800048204d87345553aefe9a5c6d8"
+ "488c069190343bd43adcb7a3058066b12b01f58d238b517627b440b704a1944955c4f97b59eb0bafb4d6ea35f6d931773013"
+ "e0202a1229659ab32469edd459a7712757457a5a967af3a4328d772a87ca46076c76dcbcb3671be555969826e1f94d2879be"
+ "9f464bca6d970cc31ac485ff50d2f055a1cf1cfe1aa0a14e166a85bf27c9d5f8d2ba876e54d737936a6f5f61d6e2dd7cf4e1"
+ "3bd34e397809cf62de6d793944d37c82b180bf98d1ffd7b345174883864fd31b80fb598ba4eb63c1f7ca9c676ec0c38f2306"
+ "7329f63b28ca0dd17f0f78caa00d1953d818bf198f769095ed84a8fa50888ee3327ffcd2eb508545dc961435ced61d5af9d9"
+ "7cdae7fa44ab658ecbf7bc4656deb32cdb8fbf45538c21d653f89cdeed08f84a732cd1a9f3f5d27231daf06fb80e8521dec5"
+ "51331466c851d133648e9ed978aca042d66a8dd224b6bd3ebd861302c1c096247a193beb6fc37a50c6b79e3751bf68b4bf45"
+ "2ff71bfa07ae20d22d3003c92bd1f7907850c0a689ed2ed15466f23e164d5356cf8c0fdf22c109e2de5178a3e58216402f6a"
+ "ffffd911924dfebe0d771b4056399753972ed7006f0e89ca0a6e256c8d439c0199bc2407e2ddadf820edb464cee1cf059d9a"
+ "eae490493dcbc3c59c1bdcc70059a636a6d6092fe554efb616bcf653b4d673e025569fc95218ce99aa48bd01832f76739f30"
+ "05ddb6616e0f42cf236f30aacd261afd567765b5b2e8363d94e871f32755b8b2a9170d40ecfe497f88c4287550df80a9b802"
+ "2560d6137f6f4641c8479535e4f2c2f66f60843623f30a8201422c797b7ba8df24440249571203eacc6d362c2c87c417f854"
+ "dc64194e8e8566a414bb32d2eb8a316296286ed36767bdc34c97ee9d891c6d28453b1e83a525b8dcddcb20510c913acea8e3"
+ "3053784a36097f8cd2984c8ee6623c1e0875046769cda607cba996417ee97b788819e476425a9b5369bd8affcc867c5974ba"
+ "639a5c2d1ad33d63776a06b040e364233e9407f7004200fe1716a55ca6871f5e68033a8c0b5d1392df55f39ee2c751bcacc5"
+ "3c8347870e453c2fa4e0abbf3ed9a668bdb2839ca9529292a9545db18af6d0213d67fca687d164a7fce7a7c1482f3788bf8e"
+ "77e5d820f75a975e3b4b00a4ee9d2a21cb4eb81c5e31a48d82f7c09b92eff40a83dc0e5528c2f90442ef85e47e3af680ac74"
+ "4117add8582e293b78d078f0f07307453be0e7a64ff9cae27eb51fb14eb5b8760643ad1204b352a9a9772f419f92a37a0ce9"
+ "2f002b5a34b97bbd9df209a090df38fe67244fd01e19b92fa881d00b70c6083480c12483a2fe1103c1c12f3148819728ce30"
+ "11678d6711452bda6163911d2c29168f3e915f3b7e9afc6fa8b7d1e21c32db0252f784f33341b87107af7c783a05270ef2de"
+ "48175e147683e515fa97f4d3fe8dd77b1d4e24e6049fbf1ed9d08d0dc6b2be65554ba116b25e3cb1462f3aaf1fbd60624909"
+ "a579a726f6176552000e84ab323a88f23a630985685e3aeb0b08c9f027f717257c595d053f257d6e5f2ecfd30903bdc35868"
+ "f4b20f86938102d22c782713e3ea01d67bfa0ecea9668b6b15de3198adb4e87e438634cb3fa3ea7e2c195d9616dd2b42e107"
+ "3e29e94dc9067f2794f25f8a78108db5c99a51298353cb7c1c0352d76f19ea6222e03836cc7bcf9f8873b07d4e0ba845b3f2"
+ "f19eb36e9cc8215f28f2b911f772d4330340fbb6f8cc1840241720074c0c743125302306092a864886f70d01091531160414"
+ "c6fe1078ea0dbc7c8d7f96ad3b7157625c8aab8c30313021300906052b0e03021a05000414bd17b7ccb644846ca45544381e"
+ "b780abf0ccc2650408e4b108ac25f3820e02020800").HexToByteArray();
public static byte[] s_DHKeyAgree1Cer =
("3082041930820305a00302010202100ae59b0cb8119f8942eda74163413a02300906052b0e03021d0500304f314d304b0603"
+ "5504031e44004d0061006e006100670065006400200050004b00430053002300370020005400650073007400200052006f00"
+ "6f007400200041007500740068006f0072006900740079301e170d3136303431333132313630315a170d3339313233313233"
+ "353935395a301f311d301b06035504031314446648656c6c654b657941677265656d656e7431308201b63082012b06072a86"
+ "48ce3e02013082011e02818100b2f221e2b4649401f817557771e4f2ca1c1309caab3fa4d85b03dc1ea13c8395665eb4d05a"
+ "212b33e1d727403fec46d30ef3c3fd58cd5b621d7d30912f2360676f16b206aa419dba39b95267b42f14f6500b1729de2d94"
+ "ef182ed0f3042fd3850a7398808c48f3501fca0e929cec7a9594e98bccb093c21ca9b7dbdfcdd733110281805e0bed02dd17"
+ "342f9f96d186d2cc9e6ff57f5345b44bfeeb0da936b37bca62e2e508d9635a216616abe777c3fa64021728e7aa42cfdae521"
+ "01c6a390c3eb618226d8060ceacdbc59fa43330ad41e34a604b1c740959b534f00bd6cf0f35b62d1f8de68d8f37389cd435d"
+ "764b4abec5fc39a1e936cdf52a8b73e0f4f37dda536902150093ced62909a4ac3aeca9982f68d1eed34bf055b30381840002"
+ "81804f7e72a0e0ed4aae8e498131b0f23425537b9a28b15810a3c1ff6f1439647f4e55dcf73e72a7573ce609a5fb5c5dc3dc"
+ "daa883b334780c232ea12b3af2f88226775db48f4b800c9ab1b54e7a26c4c0697bbd5e09355e3b4ac8005a89c65027e1d0d7"
+ "091b6aec8ede5dc72e9bb0d3597915d50da58221673ad8a74e76b2a79f25a38194308191300c0603551d130101ff04023000"
+ "3081800603551d010479307780109713ac709a6e2cc6aa54b098e5557cd8a151304f314d304b06035504031e44004d006100"
+ "6e006100670065006400200050004b00430053002300370020005400650073007400200052006f006f007400200041007500"
+ "740068006f00720069007400798210d581eafe596cd7a34d453011f4a4b6f0300906052b0e03021d05000382010100357fbe"
+ "079401e111bf80db152752766983c756eca044610f8baab67427dc9b5f37df736da806e91a562939cf876a0998c1232f31b9"
+ "9cf38f0e34d39c7e8a2cc04ed897bfdc91f7f292426063ec3ec5490e35c52a7f98ba86a4114976c45881373dacc95ad3e684"
+ "7e1e28bb58e4f7cfc7138a56ce75f01a8050194159e1878bd90f9f580f63c6dd41e2d15cd80dc0a8db61101df9009d891ec2"
+ "28f70f3a0a37358e7917fc94dfeb6e7cb176e8f5dbfa1ace2af6c0a4306e22eb3051e7705306152ce87328b24f7f153d565b"
+ "73aef677d25ae8657f81ca1cd5dd50404b70b9373eadcd2d276e263105c00607a86f0c10ab26d1aafd986313a36c70389a4d"
+ "1a8e88").HexToByteArray();
public static byte[] s_RSAKeyTransferCer_ExplicitSki =
("3082033E30820226A003020102020900B5EFA7E1E80518B4300D06092A864886F70D01010B0500304D310B3009060355"
+ "04061302515A310D300B060355040813044C616E643111300F060355040713084D7974686963616C311C301A06035504"
+ "03131353656C662D5369676E6564204578616D706C65301E170D3136303632383030323034355A170D31363037323830"
+ "30323034355A304D310B300906035504061302515A310D300B060355040813044C616E643111300F060355040713084D"
+ "7974686963616C311C301A0603550403131353656C662D5369676E6564204578616D706C6530820122300D06092A8648"
+ "86F70D01010105000382010F003082010A0282010100D95D63618741AD85354BA58242835CD69D7BC2A41173221E899E"
+ "109F1354A87F5DC99EF898881293880D55F86E779E353C226CEA0D1FFCC2EE7227216DDC9116B7DF290A81EC9434CDA4"
+ "408B7C06517B3AFF2C9D0FD458F9FCCDE414849C421402B39D97E197CA0C4F874D65A86EAD20E3041A0701F6ABA063AC"
+ "B418186F9BF657C604776A6358C0F031608673278EFD702A07EE50B6DC1E090EEE5BB873284E6547F612017A26DEC5C2"
+ "7533558F10C1894E899E9F8676D8C0E547B6B5C6EEEF23D06AA4A1532144CF104EB199C324F8E7998DB63B251C7E35A0"
+ "4B7B5AFFD652F5AD228B099863C668772BEEEFF4F60EA753C8F5D0780AAED4CFA7860F1D3D490203010001A321301F30"
+ "1D0603551D0E0416041401952851C55DB594B0C6167F5863C5B6B67AEFE6300D06092A864886F70D01010B0500038201"
+ "0100BB7DDDC4EEC4E31163B84C5C3F4EA1B9314B75D4CCCA8F5339503DC6318E279E73826AD77AC6EA4344F2905D8792"
+ "83D867A66319E1EA383B70CE997A98D545FE258E38C577554E3BBDF42349B98BED9C94B7CE55D51F740EF60ACC75D017"
+ "F3D0D1438F8F86B2453F2308279521EE4AC09046498F60ECEC8867E7BF011C882A514BF85F6C915A70E0383AB5320034"
+ "19A107A9FFEDBF34681AEEE57DF6A3DB3759D605A9269FB694D8EA56A90740529159D725BFD70C9141A38B98D4E88CDC"
+ "31124ABBB4C3D3D49C220CCB6F2F94176B8225A0E2ADDB0F4A72E6B021601CD297AC45A0CAB95EBAC4001C8167899868"
+ "3188DB9364AAD52D4E28169CC898B621FF84").HexToByteArray();
// password = "1111"
public static byte[] s_RSAKeyTransferPfx_ExplicitSki =
("308209810201033082094706092A864886F70D010701A08209380482093430820930308203E706092A864886F70D0107"
+ "06A08203D8308203D4020100308203CD06092A864886F70D010701301C060A2A864886F70D010C0106300E0408101C5A"
+ "3E2DBE2A9102020800808203A0F58476F5E4741F8834F50ED49D1A3A5B2FC8C345B54255C30556B1426C1BA1D9EE4440"
+ "CD63CD48557B7BDC55D877D656183E2815DEDE92236E036E0D7FD93022174EFA179A85EF76DEE10950EE3BEB004FB118"
+ "C58D4372A319575DB129F5912B385E63E1E83DC420A8FC8C23A283977480281EDDD745D97EC768328875D19FE414D7D9"
+ "9D3B0AAA2FBA77346F82E4E1357C54E142B2F5E929CBD6057801F49ED08A8BD2456918CCEDAD6DAD9A7281C4EFD2FCF5"
+ "6F04EDC5E62E79741024AF8BE401141AA9A9CE08F5D51D4636D8B25F9B3C59B4BC2DD7E60FBABA0A7E8FE15EAECB7221"
+ "3BC22D8CE56987427B41A79333FB4B9BC5DB6E79C2AE4E954F975C343D155C5587BD7206414B9C0529D00C6DB1470C33"
+ "A51D2A9BBDE5CC2352C61B0FB9945487FDB0E26981426BE7CCF44CF494E695D4760060468B7D23BA3C6F9B1762AC4B3A"
+ "428B23A36F275F3FDFD7BAB236197C7C7FB6466A11B05DB39F947FB19EFE9BFED2B18308E2BBD0AB00AA399508194CB2"
+ "1073B1B278BE389A8AA843B610B439AFA056A0EC81EBDF4061D2AB87C9CB840C3E6B92BB2FC30815D5744593862CC34A"
+ "EF1C4B7BBCF640CBA2D1E15E13D3B571FD3C403BC927812B291E53EAE6721C994E343148C10A16053AE560A55DFA5695"
+ "33CA35D83D81643CC7788E7F94C6592F99C09AFB770E9FE1380A1212A646A936BE531BF85F89D19EF57C180E8E3F1F4F"
+ "BD266032095862E3A0F8394E93CEFF2B8ADAD374DFCB8A041DB498618D1D71765EFD1CD5B024AC13B9FF0F96F975B443"
+ "08C14AC60965082CC409AE43D033512CF1B83458D475D2E06A49131894F1D4BFAF5FC4CBADA8566B6312E8DA31D8A397"
+ "273BE77B8395F4CAB4428B22DFE18FD4365C134B7724220D2DCE31938EFCF8E4DFC321E02CF15476BF5EB675F2055205"
+ "9662166A4549904BC6A5E4B8353C43DAC225317F4B4FA963C900F0B0D0E7FC854BE91A1CFF330FE77B03776EABD0326B"
+ "0FB37AC5176CF82530960F423B13299E037285C9324E0A872414ECF35735F58463506EBFB2CC91D790FC0D67E2714287"
+ "960C68FB43A7EE42A14F5397F07E055E75EE4F7D047634907702EEC8ABB08D82C82CEBE2B042B1F20367DFDB839B82AF"
+ "88F72272AE91DA94CD9B334343196889381FE307A76BE0B627EE32D827582A7CD68BF467D954805030753FA8DABFCC21"
+ "E68A77E2A76F9E95E61A2FBCA1C8FFC2CE272E9D125E5C65759529BF3FDD2E28722EC9B7B57BD9819BAAC01556002D88"
+ "3B8BD842C3EB3BCC4A54B4D0B1DB32ECEBA8DD668D67C859A6EB0BAE293082054106092A864886F70D010701A0820532"
+ "0482052E3082052A30820526060B2A864886F70D010C0A0102A08204EE308204EA301C060A2A864886F70D010C010330"
+ "0E0408482E476C7712FD7202020800048204C8AF5357D64578320D963917F44B2B7714334AAE6571554F03A599913275"
+ "4BA03892316159385225C4EEA7C958091BC8A32A9433AECA3A07F791ACE431217F0DFBD53DC15D257069B99DA04EF719"
+ "892004FD307E151EBB359C1D69AE8FF78A1CC1654470B0862CDAC1AED521608C29AA8D30E81A4015D54F75421B9BDB29"
+ "5036D79E4535F28D4A2ABF4F203BC67065A709AEF6EAF4D6A3DC7387CB3459D82399F4797CE53FD2BD0A19B1A9566F74"
+ "246D6B6C50BD2777B6F6DE1A8C469F69D7EBF230018D56DF4C1764862CD982E81F56A543DA4ADB63EF8612A1BB561471"
+ "56035541B0B41F06BBE2CD47DC402A75023558205870060438CF99D8BFC7CAADDE0583311FE4B854051C83638420BC5E"
+ "93F999E67EDBBC266F519609E2BE9FC1BC3C7FEE54DBAB04DAC8A94BB347F3DC28DDAB7D28DD3BBFFB44C84E6F23A8E0"
+ "1CAB36382723DB94CD8973A303D8D4C7A22B9F811C07ED9A78E06135E0426FC93BB408F1DC915DF4ADBF048D22C201D8"
+ "0FDC0EF942D1E2AC0F39F8A95BA849C07BB0DA165B3F0317478870F704B8A34B7D5816BC4F8CA0C6BDB5346F2211416C"
+ "79D7117AD1B86E44E0BC0C3793F9895638E5B7A2A5B957E0E691819AC7FA1F05E8D05ED99E4E286C96E3E31DF99633E8"
+ "CB73CA135109AE727CB047641726A1599492B6F3E8E62195A79239279B2A9FBF47B31FEFF3C20DEC2DFBDB0CE98B183D"
+ "BA773561DEE404BA1A5BEF5AB9729DBE22FB1C17EFD4D3AC81F04F49F9855CEACECB202090A1290C10E9D676F0658F3D"
+ "E4C43DCD5A17B88881893DA87060C5F56D5CC9A92E6B1A47A6D16FB32C09925606F6D5C7CAFBC7A82D8E441A05DFBEE0"
+ "BEC92D89264B62D5DECC342D29D9A7727BBDE4E63EEB7CAED7C76953F6AC8CB570619C7607B753FD46889C76D29C9AC6"
+ "6F56CB3848323FA9CD16578EA5C6D876AE63D95F65E2CDEF68A1CF3D2FC3DF91D0055B0CDBD1510E291C0E7AC6EAA0D2"
+ "AB5E8FAD44108C94A592251447926DB7139BC2A433D61711C6DA5EF82A8E18CEBF99AF753E33FFF65126B7D3D3D09FF0"
+ "C50EFF7822FA8797BAC52383B94E8FE602E62577994ACA6A2150F60A31CA0E79FE6DF3405D6918EADC2231558FB29045"
+ "034EB9DA9FB87BD71996C6AB6EA71A70EBFBC99BC292338A363176516C14EC92E174C59C6BE82F5BC0296525109C9A7F"
+ "C9D9E654955992A5C9EDFD39ED9889BEAF105B2EF62B041789F20A6AB26563FCFA1A1482EE2A20E8C1A2F0931ACBA7F8"
+ "756EE4C9119D29817ACA7D2B81FE736FD7A33D20EC333AC5123D29345647B734DB24B5C56B4576ABBF9B02F782DDE0B4"
+ "BA277080F28F3D86DEC35F0F19B2B5DB0BD7A59B7C4B2BAE08E8584449BD3685F371F6A24F5F91EA6843DC6ABA89976E"
+ "589511EB23A733D23F6CE076C952E9E7190ED78D5A34387F93418A87CB02270941F19DD35E1DB5836E67296A7F28A5EB"
+ "8F32DA73EA7A47D5CEB292E767468CDF938A44B3CEEE6276A34705606A8F7496D7310DA1A0468A604B8A9E7AB50450A6"
+ "DFE0C4540CEA058CD7919E823D8A32FB811C6BF8754C65D7A9723018ADE95AED5C30978A8DBA185CF0BA36346456CD3E"
+ "15C511FAD71B445DDFA7C5455A3597FE536E3BB87518C0725D6BE673D05DC5E74B4FF442711D242A37D0CCB88E6D19BD"
+ "6B7299207D7036EB87D5E86189768CB14AE4F8886BB5AB7864BDA9757D0C26BFFF3FAA4001258557D394313125302306"
+ "092A864886F70D01091531160414080FB9AAB81BD67FD85C2186B359054CEB13D2D730313021300906052B0E03021A05"
+ "0004142C205F0B1E9B99B0ED14E83F13D84BC683F66D3B04080D22E45D6A657CC602020800").HexToByteArray();
public static byte[] s_Rsa2048SignatureOnlyCer = (
"3082032C30820214A003020102020900E0D8AB6819D7306E300D06092A864886" +
"F70D01010B05003038313630340603550403132D54776F2074686F7573616E64" +
"20666F7274792065696768742062697473206F662052534120676F6F646E6573" +
"73301E170D3137313130333233353131355A170D313831313033323335313135" +
"5A3038313630340603550403132D54776F2074686F7573616E6420666F727479" +
"2065696768742062697473206F662052534120676F6F646E6573733082012230" +
"0D06092A864886F70D01010105000382010F003082010A028201010096C114A5" +
"898D09133EF859F89C1D848BA8CB5258793E05B92D499C55EEFACE274BBBC268" +
"03FB813B9C11C6898153CC1745DED2C4D2672F807F0B2D957BC4B65EBC9DDE26" +
"E2EA7B2A6FE9A7C4D8BD1EF6032B8F0BB6AA33C8B57248B3D5E3901D8A38A283" +
"D7E25FF8E6F522381EE5484234CFF7B30C174635418FA89E14C468AD89DCFCBB" +
"B535E5AF53510F9EA7F9DA8C1B53375B6DAB95A291439A5648726EE1012E4138" +
"8E100691642CF6917F5569D8351F2782F435A579014E8448EEA0C4AECAFF2F47" +
"6799D88457E2C8BCB56E5E128782B4FE26AFF0720D91D52CCAFE344255808F52" +
"71D09F784F787E8323182080915BE0AE15A71D66476D0F264DD084F302030100" +
"01A3393037301D0603551D0E04160414745B5F12EF962E84B897E246D399A2BA" +
"DEA9C5AC30090603551D1304023000300B0603551D0F040403020780300D0609" +
"2A864886F70D01010B0500038201010087A15DF37FBD6E9DED7A8FFF25E60B73" +
"1F635469BA01DD14BC03B2A24D99EFD8B894E9493D63EC88C496CB04B33DF252" +
"22544F23D43F4023612C4D97B719C1F9431E4DB7A580CDF66A3E5F0DAF89A267" +
"DD187ABFFB08361B1F79232376AA5FC5AD384CC2F98FE36C1CEA0B943E1E3961" +
"190648889C8ABE8397A5A338843CBFB1D8B212BE46685ACE7B80475CC7C97FC0" +
"377936ABD5F664E9C09C463897726650711A1110FA9866BC1C278D95E5636AB9" +
"6FAE95CCD67FD572A8C727E2C03E7B242457318BEC1BE52CA5BD9454A0A41140" +
"AE96ED1C56D220D1FD5DD3B1B4FB2AA0E04FC94F7E3C7D476F29896224556395" +
"3AD7225EDCEAC8B8509E49292E62D8BF").HexToByteArray();
public static byte[] s_Rsa2048SignatureOnlyPfx = (
"308209E3020103308209A306092A864886F70D010701A0820994048209903082" +
"098C308205BD06092A864886F70D010701A08205AE048205AA308205A6308205" +
"A2060B2A864886F70D010C0A0102A08204FE308204FA301C060A2A864886F70D" +
"010C0103300E04083EF905F0EA26FBF7020207D0048204D82297B5546DA6CC49" +
"BD8C1444E3FE1845A2C9E9BDB8B83E78235DF4ADF7A97496A62D31D4EEEB76B0" +
"71C0B183ACC3663272F88CF4F31E2E00D76357C0A051B8D6E0BB0BCF4CCDD064" +
"CCBAF546EABA80DA56CD11FE952C61154792559D65F26B0476CF7A5FDB8CC794" +
"B89F6ACD50003459054FE82C48D8791B226A0EEEC01F048AC3CE716C9F3BB313" +
"D64BEBBF0037D83133DD9C15D04F15BB11652D793B613A68AFE580245724E5D1" +
"110040B332B5C39BE04086BA4DFC58E905BC2FE8B3C696181E2879AF197EE24D" +
"91D8AD67013F14C4864C8D0FB19C134B766CF3E48B8C9E363A11EB19F1E82E74" +
"D25EDD96517D64A94314B40C11651030D561E742E63856E8D1A3EE9FDFD6CF64" +
"7140CFC354AE7EA1D14C157C2985F82D54296F7D3DE456AF7513F5F30A0421E4" +
"3A9DAD6DF8A2BF69005B35CA8066F80755D848DA73EF03BC0CC129C5799911D9" +
"3A1ED43F8E76732AF56FD62DC6D0B0DBA6AAC6DCDE77D0E8AC9F6A5EB5A02B61" +
"BC477706D4F1873240AB45E0291EF21E6034D48F1AE8EB139DE7ACD8B8A821E6" +
"70B395C3EC4B0E75C34BF0067F052FCED835CAC1F17C3FBEA2FC9FD281FCDE21" +
"D5B27CF31A07E90164A979ACEF0E1C67DBA6C33082E9B189D4BDA2D2D504776F" +
"455843437BDF10D4AF48639EC03344BCC36EFEA7CDE08D7F94DDEAF98BCB5D65" +
"207AE0C349EECE3032DE19F3B337F29A3457AA0AAF4306FA8301619AB01B7235" +
"BE16CB93728E142DAA6C1CBBCC5BD82D913596994DA40FB916CF2DB5FBCC20CF" +
"E893DC62BBC5FC59E00BC0A704A9DB25BBF9291971F2377FC1A20F2C954869DB" +
"6FFCC90C625AABE97ED4CF7C0209D39AD780003C437152D636ACB3B484C46885" +
"DC1584733D2153A3F9B968F12CDD5937CDF9DD2581D72EE67C83AE2530197AA7" +
"C6110613BEFF0B75E586C28394EA8EBCF7F9DB133295B33DC86C8DBA92BF8BD1" +
"ADCAF8D2CD2E018B08D59FF1C30A13484AB11468F7DCEB1FE53A6DAF309B0510" +
"7772CB735314A5B2F053E60A653F0496BCB9CADF5E50339A4D2EF2382056B768" +
"558EB9230D996C636E6D29664F92F70A088DE3EE4EC4BBD8A9C4C98C7892D122" +
"28806622B87E581A321AD835B8F4B964A17B5BE6D9DA50133D494732A41884E2" +
"9E891FE2D40ACCFD585C8BF626C1E8A412D2EE7CDE060E2CCDA826BF79D80F1B" +
"F6B8400473BCE0C19D03ACF55D1FAA994C04A8CD11D49743B1F45F48DFFDD701" +
"18B5FA82ECDF67714F5DE5D3D3DDDCB76ED0EA6A6E151665A4AA351DB1A99F8C" +
"7502D3795C2C358CCA589C390C1F4810615130B91BA42A85E77FA37197E1B083" +
"FE1246B067C6444D49B369D45B130A6D7B463C3F0459EB41D68009CABD2F5C60" +
"49DB706FA742C9773FB5791AF123FBE485E05F87759ADD25281BE337B6095EC3" +
"4EFF9FC692798FB4217EF4B2B59902D930F28181933FAA278C041123CAE3CA63" +
"6DFD3AD4E04EB751A30D50C26288EA4D01C7B323E4FD6387F88E020BC433BF60" +
"C4406398C44EA5C7A6EB24134B0811E4F94DFAF5553172306FA5543C254E7E04" +
"DEEC84DBF9FAF7BFEA8D61E094CBB18DD45C5BAB9199DD719F9A305E205605CC" +
"671DCD566FEBA2C8F4C1A445625C4F42D1CFE32087F095591798D1D48DA46DE9" +
"230F5102B56A1EF879D48936D5331D6B3D9F1B564CF08FD3C641CFF3B02CB4FC" +
"8995E5EC5DD1D183704940C02DEA7430FD594E54800DCC74B7732731C63FBBA2" +
"A2F6DC031174390A74781D352B09FB4F318190301306092A864886F70D010915" +
"3106040401000000307906092B0601040182371101316C1E6A004D0069006300" +
"72006F0073006F0066007400200045006E00680061006E006300650064002000" +
"520053004100200061006E006400200041004500530020004300720079007000" +
"74006F0067007200610070006800690063002000500072006F00760069006400" +
"650072308203C706092A864886F70D010706A08203B8308203B4020100308203" +
"AD06092A864886F70D010701301C060A2A864886F70D010C0106300E04087CB7" +
"E0256AD1AD80020207D0808203800C21CEBEF9F3765F11A188B56702050E3DCA" +
"78AA27123654D066399DD56E62187C89A30940B5B63493950EEFA06C04B5CAF0" +
"329143AF30EE0B47406E49D4E6241817986F864780B743B58F03DF13523F5C01" +
"C889046356623AFA816B163E57A36672FAC9CA72294B2A17F75F5ADB1A4CBDB7" +
"B3F5C33C643DA0CC00CB79E54FAB25D1881B81C03BA5762BAA551A7E8BA38144" +
"353B07285B288BC2747F75B7AF249040C338CFC585D0B1CECFED46BCAE7FAF09" +
"60BB3EE996E30E626CB544A38393BC7DFDB7A27A21A6CF09332B544F448DF5B3" +
"31E000F7CCD5CE5C8E8765A2339919C713352FCD30FA52B994C25EA95E548C4B" +
"5EC23B3BDEC7342D0676B9227D3405758DBA5BD09F9253791FAA03F158F04848" +
"D5073DD240F466F57770353528B3AE83A626F33D05BD1BBB4E28CB067FFAA97D" +
"B4C79EEAAFB4B30BE738C1AA5DB1830B3968CDF6BAF778494AE40EF003DCDA54" +
"486E9952EB44628385E149C348E0E431928B85608622B994CF43433DA9C19482" +
"360121560E53E85FE7CBB7C31E27AD335BC247F284EAC3CA94C30DBB4DF2AB02" +
"DF1154626838240213D910D5B7476A025CA7565CECBA0051320FC7EECD6C74FF" +
"505566F75804D1E2BD2B0181B235CE911EAD9260C0799C817F956AE290E00EF0" +
"997F7B6BD059B315915D580CF0C019A23A6D4993F6E8B8106A1AB6CE1991B609" +
"1B42B6D33EE01EC96CB475430365E9C710C5EB4C6010260D12108022449F7E6D" +
"1A2F28838304DB2A60B9FF714FC887579A4CDC139DAF30A18D3910D82313CCB1" +
"FA43A8930E0F10DE24652AC1E5B797084BEBDB8AB5FA6DCE03E44ABF35EDEB1A" +
"FFEAD3F7C9CB342CCA2882D945EB52C20DC595FA10161866EB9426281CF13341" +
"311B59FDE8E69F9B853117740D92F4AC1B2E4597D41B8A097E1DAA688FFF1C5C" +
"846DF96CA75224EC26F4FF328164F5D1EC06B697211BDB42E6C97EB294A5798C" +
"0FCE6104C950A5207F74EC0DED8AEE10463EF2D9ACD7473D2BE48EBBF0A550B9" +
"AA19A465147B378B078229E8804918136633D7FCE5340AC61A1418D7D9BB18D1" +
"98B7B7866C4D7DC562B1F93F3F322484BDDCEB23680B8EB9904EC783D5CD7177" +
"CFE9CA9D1893104E97760E871DE0907D4BDF6263E7BB0F47414AF31E377C7447" +
"B881E68AE3E80D06597F12D5EF5ED861D055D494D89F04A70800DA3FD4E53877" +
"87FBEED7B772E3A24E7F4832A956FEC0C81847C68373ED4760ABF542F77DC794" +
"249519BDDF5F846EB8C5078BCC053037301F300706052B0E03021A0414461F5B" +
"19C6933240012EFEB95F734C648CCD13460414FA1743400686D25BA1CB28D736" +
"F2B1ED97699EA4").HexToByteArray();
public static byte[] s_dsa1024Pfx = (
"308206EE020103308206B406092A864886F70D010701A08206A5048206A13082" +
"069D3082043706092A864886F70D010706A0820428308204240201003082041D" +
"06092A864886F70D010701301C060A2A864886F70D010C0106300E04084AF212" +
"89D5D7E2E702020800808203F0DECCF218AC91F26BAB026998AB77C7629D20DB" +
"E2FB7022A3C4A1CECD743C0F932E944AE229DAFB61AD76C4DEB6995DF4F4BA01" +
"2DBAD5C63A4C846E0807FCA0BC4A162CDFBAB4B3C4D304F473B3ACC1D268436E" +
"F537DAE97ECC3C634C8DF2A294CC23E904A169F369021A0C024A03DE98A65B0F" +
"3F14D6910525D76AD98B91E67BB7398E245CF48A4D2A5603CFCCF4E547D7EDAB" +
"669D9A8597C6839119EB9FD932D1E4BA8B45D3317186CDA2EFF247BCFD64A5CA" +
"ED604BF7033E423CC21CEC6454FE3B74E03A26C51A1C3519CE339FBE9F10B81D" +
"DF6A0AAB4F8166D90B6F52B3439AB4B5273D0A506E3E01869F8FEBD1521EF8E5" +
"BFB357FA630E3C988926EF3ACC0A0F4176FE8A93337C1A5C6DEAB5758EC2F07C" +
"11E8B2495ECDE58D12312CCCA2E8B2EE8564B533D18C7A26A9290394C2A9942C" +
"295EBB0317F5695103627519567960908323FFE6560AD054C97800218A52F37A" +
"DDE4E7F18EF3BF3718A9D7BF57B700DBEB5AB86598C9604A4546995E34DBABBB" +
"6A9FB483A3C2DFE6046DFD54F2D7AC61C062AF04B7FBAC395C5DD19408D6926A" +
"93B896BFB92DA6F7F5A4E54EDBE2CFBB56576878150676ADB0D37E0177B91E0D" +
"F09D7B37769E66842DD40C7B1422127F152A165BC9669168885BA0243C9641B4" +
"48F68575AA6AB9247A49A61AC3C683EE057B7676B9610CF9100096FC46BDC8B9" +
"BAA03535815D5E98BA3ABC1E18E39B50A8AF8D81E30F2DFD6AF5D0F9FC3636AB" +
"69E128C793571723A79E42FC7C1BD7F39BD45FBE9C39EEB010005435BEC19844" +
"2058033D2601B83124BD369DADB831317E0B2C28CE7535A2E89D8A0E5E34E252" +
"3B0FCEC34FF26A2B80566F4D86F958F70106BF3322FA70A3312E48EAA130246A" +
"07412E93FDE91F633F758BC49311F6CBBAEC5D2F22AFCD696F72BC22E7DE6C00" +
"3275DFEC47E3848226FE9DBA184EA711E051B267C584749F897EFE7EAFD02F1D" +
"BF3FD8E882474CA1F45509EF2E7B82F35B677CB88ED42AF729848EE2B424B0CE" +
"2E9AAC945BABA550C20D5B25075A30FE70D8CAA5A527A35F1DF17BCCB91930C1" +
"7120C625667120E0806C2B51EDFF540F928BD555FB48DBCB83CCCE0C385E78C8" +
"65BE715AE6F8BE472E5FC187EBE3FEFD8D7FE62D4DB2EE61F42D24D81FAA9179" +
"0FB17E8EBC8E219B6F9E039F5AB3BC4870821D474B36C8F8D0583D9DC06E4383" +
"D03424420B8C8B26276877166A0F51E22F0D8FA60A070CFBD47EAFBC717C879C" +
"B5A1EA69C4C2A38F26A1EEF96A0C32BFCECCE4EA97E90A425066B1DD0891353F" +
"766EB9F2BFA2563A815DAF3639EBB147E1E8757A6BFAB902C4A8F037AD47E03F" +
"AF2E019FCF6CA7430BDFEA4B45B28ED746BB90E09BEF7B370A75E7924BBA0920" +
"25FE654A9A197A5B8BBBE43DC7C892FF14E75A37EB97FC489AB121A43E308202" +
"5E06092A864886F70D010701A082024F0482024B3082024730820243060B2A86" +
"4886F70D010C0A0102A082017630820172301C060A2A864886F70D010C010330" +
"0E0408ECB4D1550DA52C6302020800048201509322DC0193DD9E79ADAFD38827" +
"AD6DE9299327DDDF6E9DF4FB70D53A64951E4B814E90D2A19B3F4B8E39A2F851" +
"A3E5E9B9EB947DD248A3E5F5EB458F3323D4656709E97C6BD59238C4D1F26AB6" +
"7D73235FAE7780D98705957B6650AC0DE3E2D46E22455D0A105D138F16A84839" +
"14EDDF5C518B748558704ED3AE4A8C4914F667BBDE07978E4A4FC66194F6B86B" +
"AB9F558EDE890C25DFB97C59653906CC573B5DEB62165CFF8A5F4F8059A478EB" +
"F6FED75F1DACDC612C2E271E25A7083E15D33697270FD442D79FFCB25DB135F9" +
"8E580DC9CE14F73C3B847931AF821C77718455F595CA15B86386F3FCC5962262" +
"5FC916DDB4A08479DCB49FF7444333FA99FBB22F1AEC1876CF1E099F7A4ECA85" +
"A325A8623E071EEA9359194EEE712F73076C5EB72AA243D0C0978B934BC8596F" +
"8353FD3CA859EEA457C6175E82AE5854CC7B6598A1E980332F56AB1EE1208277" +
"4A91A63181B9302306092A864886F70D01091531160414E6335FA7097AB6DE4A" +
"1CDB0C678D7A929883FB6430819106092B06010401823711013181831E818000" +
"4D006900630072006F0073006F0066007400200045006E00680061006E006300" +
"650064002000440053005300200061006E006400200044006900660066006900" +
"65002D00480065006C006C006D0061006E002000430072007900700074006F00" +
"67007200610070006800690063002000500072006F0076006900640065007230" +
"313021300906052B0E03021A0500041466FD3518CEBBD69877BA663C9E8D7092" +
"8E8A98F30408DFB5AE610308BCF802020800").HexToByteArray();
public static byte[] s_dsa1024Cert = (
"3082038D3082034AA003020102020900AB740A714AA83C92300B060960864801" +
"650304030230818D310B3009060355040613025553311330110603550408130A" +
"57617368696E67746F6E3110300E060355040713075265646D6F6E64311E301C" +
"060355040A13154D6963726F736F667420436F72706F726174696F6E3120301E" +
"060355040B13172E4E4554204672616D65776F726B2028436F72654658293115" +
"30130603550403130C313032342D62697420445341301E170D31353131323531" +
"34343030335A170D3135313232353134343030335A30818D310B300906035504" +
"0613025553311330110603550408130A57617368696E67746F6E3110300E0603" +
"55040713075265646D6F6E64311E301C060355040A13154D6963726F736F6674" +
"20436F72706F726174696F6E3120301E060355040B13172E4E4554204672616D" +
"65776F726B2028436F7265465829311530130603550403130C313032342D6269" +
"7420445341308201B73082012C06072A8648CE3804013082011F02818100AEE3" +
"309FC7C9DB750D4C3797D333B3B9B234B462868DB6FFBDED790B7FC8DDD574C2" +
"BD6F5E749622507AB2C09DF5EAAD84859FC0706A70BB8C9C8BE22B4890EF2325" +
"280E3A7F9A3CE341DBABEF6058D063EA6783478FF8B3B7A45E0CA3F7BAC9995D" +
"CFDDD56DF168E91349130F719A4E717351FAAD1A77EAC043611DC5CC5A7F0215" +
"00D23428A76743EA3B49C62EF0AA17314A85415F0902818100853F830BDAA738" +
"465300CFEE02418E6B07965658EAFDA7E338A2EB1531C0E0CA5EF1A12D9DDC7B" +
"550A5A205D1FF87F69500A4E4AF5759F3F6E7F0C48C55396B738164D9E35FB50" +
"6BD50E090F6A497C70E7E868C61BD4477C1D62922B3DBB40B688DE7C175447E2" +
"E826901A109FAD624F1481B276BF63A665D99C87CEE9FD063303818400028180" +
"25B8E7078E149BAC352667623620029F5E4A5D4126E336D56F1189F9FF71EA67" +
"1B844EBD351514F27B69685DDF716B32F102D60EA520D56F544D19B2F08F5D9B" +
"DDA3CBA3A73287E21E559E6A07586194AFAC4F6E721EDCE49DE0029627626D7B" +
"D30EEB337311DB4FF62D7608997B6CC32E9C42859820CA7EF399590D5A388C48" +
"A330302E302C0603551D110425302387047F0000018710000000000000000000" +
"0000000000000182096C6F63616C686F7374300B060960864801650304030203" +
"3000302D021500B9316CC7E05C9F79197E0B41F6FD4E3FCEB72A8A0214075505" +
"CCAECB18B7EF4C00F9C069FA3BC78014DE").HexToByteArray();
// Password: "Test"
internal static readonly byte[] ECDsaP256_DigitalSignature_Pfx_Windows = (
"308204470201033082040306092A864886F70D010701A08203F4048203F03082" +
"03EC3082016D06092A864886F70D010701A082015E0482015A30820156308201" +
"52060B2A864886F70D010C0A0102A081CC3081C9301C060A2A864886F70D010C" +
"0103300E0408EC154269C5878209020207D00481A80BAA4AF8660E6FAB7B050B" +
"8EF604CFC378652B54FE005DC3C7E2F12E5EFC7FE2BB0E1B3828CAFE752FD64C" +
"7CA04AF9FBC5A1F36E30D7D299C52BF6AE65B54B9240CC37C04E7E06330C24E9" +
"6D19A67B7015A6BF52C172FFEA719B930DBE310EEBC756BDFF2DF2846EE973A6" +
"6C63F4E9130083D64487B35C1941E98B02B6D5A92972293742383C62CCAFB996" +
"EAD71A1DF5D0380EFFF25BA60B233A39210FD7D55A9B95CD8A440DF666317430" +
"1306092A864886F70D0109153106040401000000305D06092B06010401823711" +
"0131501E4E004D006900630072006F0073006F0066007400200053006F006600" +
"7400770061007200650020004B00650079002000530074006F00720061006700" +
"65002000500072006F007600690064006500723082027706092A864886F70D01" +
"0706A0820268308202640201003082025D06092A864886F70D010701301C060A" +
"2A864886F70D010C0106300E0408175CCB1790C48584020207D080820230E956" +
"E38768A035D8EA911283A63F2E5B6E5B73231CFC4FFD386481DE24B7BB1B0995" +
"D614A0D1BD086215CE0054E01EF9CF91B7D80A4ACB6B596F1DFD6CBCA71476F6" +
"10C0D6DD24A301E4B79BA6993F15D34A8ADB7115A8605E797A2C6826A4379B65" +
"90B56CA29F7C36997119257A827C3CA0EC7F8F819536208C650E324C8F884794" +
"78705F833155463A4EFC02B5D5E2608B83F3CAF6C9BB97C1BBBFC6C5584BDCD3" +
"9C46A3944915B3845C41429C7792EB4FA3A7EDECCD801F31A4B6EF57D808AEEA" +
"AF3D1F55F378EF8EF9632CED16EDA3EFBE4A9D5C5F608CA90A9AC8D3F86462AC" +
"219BFFD0B8A87DDD22CF029230369B33FC2B488B5F82702EFC3F270F912EAD2E" +
"2402D99F8324164C5CD5959F22DEC0D1D212345B4B3F62848E7D9CFCE2224B61" +
"976C107E1B218B4B7614FF65BCCA388F85D6920270D4C588DEED323C416D014F" +
"5F648CC2EE941855EB3C889DCB9A345ED11CAE94041A86ED23E5789137A3DE22" +
"5F4023D260BB686901F2149B5D7E37102FFF5282995892BDC2EAB48BD5DA155F" +
"72B1BD05EE3EDD32160AC852E5B47CA9AEACE24946062E9D7DCDA642F945C9E7" +
"C98640DFAC7A2B88E76A560A0B4156611F9BE8B3613C71870F035062BD4E3D9F" +
"D896CF373CBFBFD31410972CDE50739FFB8EC9180A52D7F5415EBC997E5A4221" +
"349B4BB7D53614630EEEA729A74E0C0D20726FDE5814321D6C265A7DC6BA24CA" +
"F2FCE8C8C162733D58E02E08921E70EF838B95C96A5818489782563AE8A2A85F" +
"64A95EB350FF8EF6D625AD031BCD303B301F300706052B0E03021A0414C8D96C" +
"ED140F5CA3CB92BEFCA32C690804576ABF0414B59D4FECA9944D40EEFDE7FB96" +
"196D167B0FA511020207D0").HexToByteArray();
internal static readonly byte[] ECDsaP256_DigitalSignature_Cert = (
"308201583081FFA003020102021035428F3B3C5107AD49E776D6E74C4DC8300A" +
"06082A8648CE3D04030230153113301106035504030C0A454344534120546573" +
"74301E170D3135303530313030333730335A170D313630353031303035373033" +
"5A30153113301106035504030C0A454344534120546573743059301306072A86" +
"48CE3D020106082A8648CE3D030107034200047590F69CA114E92927E034C997" +
"B7C882A8C992AC00CEFB4EB831901536F291E1B515263BCD20E1EA32496FDAC8" +
"4E2D8D1B703266A9088F6EAF652549D9BB63D5A331302F300E0603551D0F0101" +
"FF040403020388301D0603551D0E0416041411218A92C5EB12273B3C5CCFB822" +
"0CCCFDF387DB300A06082A8648CE3D040302034800304502201AFE595E19F1AE" +
"4B6A4B231E8851926438C55B5DDE632E6ADF13C1023A65898E022100CBDF434F" +
"DD197D8B594E8026E44263BADE773C2BEBD060CC4109484A498E7C7E").HexToByteArray();
internal static readonly byte[] ECDsaP521_DigitalSignature_Pfx_Windows = (
"308205C10201033082057D06092A864886F70D010701A082056E0482056A3082" +
"05663082024706092A864886F70D010701A08202380482023430820230308202" +
"2C060B2A864886F70D010C0A0102A082013630820132301C060A2A864886F70D" +
"010C0103300E04089C795C574944FD6F020207D004820110C7F41C3C3314CCFC" +
"8A0CF90698179B7B6F1618C7BE905B09718023C302A98AFCD92C74CEFDBE9568" +
"6031510BEB8765918E07007F3C882B49BFBBDEFA4B9414B4A76E011A793DA489" +
"F5B21F9129CB81A4718A2690BE65BCBE3714DE62DEF4C792FFA52CCDE59FC48E" +
"5ABE03B9A34D342CE5B148FBA66CE699B9F2DDCF0475E31A1EE71543922EF65A" +
"3EACB69553ABE4316590D640F6DB58D7B8BF33B57EF2A35445CA6A553BF59B48" +
"F4D9A5B7E37AF448DCBFED3A2BD258A4BA3180A66D7508CA2037061517675135" +
"DB609B7DF7CB5F39874E66512C57F65DA93E3A43A12929B63FCACC82C5B8D638" +
"00713A83B04A6CEB47A3C79D9852AFF5DB58180B6CF8193E7194CF7F0B6EED2E" +
"A6697C42AC556C8C3181E2300D06092B06010401823711023100301306092A86" +
"4886F70D0109153106040401000000305D06092A864886F70D01091431501E4E" +
"00740065002D00650037003900350037003300640030002D0037003000390036" +
"002D0034006200300035002D0062003400330038002D00640036003000650032" +
"0030006600360030003100300034305D06092B060104018237110131501E4E00" +
"4D006900630072006F0073006F0066007400200053006F006600740077006100" +
"7200650020004B00650079002000530074006F00720061006700650020005000" +
"72006F007600690064006500723082031706092A864886F70D010706A0820308" +
"30820304020100308202FD06092A864886F70D010701301C060A2A864886F70D" +
"010C0103300E0408812C7B1E5FBB35DF020207D0808202D00AFB0F5D92F40AD4" +
"CCABAA4805775198F5988210F0601C39EA4A5B025A0FADB6A95C3ED3CB86E65C" +
"B13BA11216244BE2773705202CF5895D9E31E5FC208A9DD2D90B47495475A078" +
"B1B531AE496E4E534E4A23D828D2DC3488D982CB05FF9A32E7C60FCADEFA8EAB" +
"F01F1D29E0650DAC688F434C4D5D8A26C4D7AD339FD0A2C4E22785E07DEC2FB6" +
"7D041FA03BAE4BD6F3175EBB65EE79B276FECE8A8155A925792DA2F8AF2FAAF8" +
"75AC2207078643C6E3C3AFEF37FED0AA60BDB06C8C1908ACF8FA2BCD28BCC8D4" +
"47D998449108BA7A03E7AE6A439D7310E1A1A7296DBDFF48F7401E259ACE7B0A" +
"D7B77B06001B0D526278B109217A7FF14CBA143DBCA99604EB2067D1DE3FA94D" +
"D306D0937D9EF825E3B5B425F1F01A2153ECE2DFFF81779B7678626965F586DB" +
"B519633EE3CEBD9FB14F5CF88DF6E907176D79CC6A7B9754C5EA02AFB549C65B" +
"612866D48D294E44EC8A74CB36592F1C40C4B53640F5AE13F0A7A7AE731942CC" +
"5091C57EA07743373404698E347A10BF0433F495B69FE8077EC8971B8B322DA0" +
"82746883DE62FF08D3BE6D0575BCDAC392E79CC9B286953AE3B17D27C477B040" +
"63AC2BEA6AA74BE63456DA2DE4685E8195EF620F19FDA8943515A4BC2ECBAA2D" +
"16DF0237A9C272D6418F948715238EC5CA386E74E4AA67248A56A285F1FD2E17" +
"A5F0F09DD3448BA570A056DDC7FA275A42CC0D524911BFA8DB42BFA04588AE5B" +
"5044CABD353B9090F9F8CF02514C9AC0F347A9BE2A03EC351BAE2D1AC42CAC2B" +
"89C9ABF3600F41EDD4447CDD14192F85094FEFB95DBF260A6739276A279FD104" +
"E346A3FD238F7497474B1B4F8B7C02E4EECA34284C19D0AA169C178207BB1F19" +
"62CD5E0C8A2C7C55249628F0BFC575DF2ECB25D36E1B29631A612945B9A99070" +
"5FF55769B50D0B77725F61FE55284301A604C63BC7FC58F79CDF89F7E57ED060" +
"CDD855DF59E9A8C9A06EA0DFECA32DF2A5263D0BF72B9D485519AB87EA963D01" +
"9BF9F6B1D77ED4AA303B301F300706052B0E03021A0414AF6FEF9E53E1144A81" +
"53A9459AADF886BA2979990414AC82239C24D3BB89B37A6A6109D7B43ABC433D" +
"12020207D0").HexToByteArray();
internal static readonly byte[] ECDsaP521_DigitalSignature_Cert = (
"3082024D308201AEA00302010202101549950E8AA087A34C179BE49774C8AF30" +
"0A06082A8648CE3D040302301A3118301606035504030C0F4543445341205035" +
"32312054657374301E170D3138303930353130333230395A170D313930393035" +
"3130353230395A301A3118301606035504030C0F454344534120503532312054" +
"65737430819B301006072A8648CE3D020106052B810400230381860004019D99" +
"4545E2E70D4CD0901FFBADC7B6CCEED2DC4EE69624B7F0B5C3E81F7A8DEEAFFF" +
"BC317A3768D03F1582877D1D84FC69554B76DFFAA439929D94B6BE5CBA8CBA01" +
"ECB0CDCD730492414D10A00DCA812CEC46D6D92B9142297500C543652FE54A81" +
"427E18EC155EB05D3426A28F24819F5293F3FBC95A9CD7646D5D4D046753ECE0" +
"B9A3819230818F300E0603551D0F0101FF040403020388301D0603551D0E0416" +
"0414FFA852184A01C69680A052AF5BE279E949718DF6302E060A2B0601040182" +
"370A0B0B04204500430044005300410020005000350032003100200054006500" +
"730074000000302E060A2B0601040182370A0B0D042045004300440053004100" +
"20005000350032003100200054006500730074000000300A06082A8648CE3D04" +
"030203818C00308188024201D8EB229D9D73C8C6634E305836E938349672D12D" +
"73BFC5A87E2CD2985FF64EE44BB2800214E4839A2DBCEAA3F2342C269D74126A" +
"FE248C0C0F7C700B4680CA8F36024200F6625A58C219C389F2B4127BFDC228D8" +
"2765E2F9399DB66ED71EDF4D64F85998DE15ED82A75F363E42432BCE108CE55A" +
"41A9899160F95848826A9CE39498AEC2EF").HexToByteArray();
internal static readonly byte[] ValidLookingTsaCert_Cer = (
"308204243082020CA003020102020401020304300D06092A864886F70D01010B" +
"05003029312730250603550403131E4578706572696D656E74616C2049737375" +
"696E6720417574686F72697479301E170D3138303130393137313532355A170D" +
"3138303431303137313532355A302C312A30280603550403132156616C69642D" +
"4C6F6F6B696E672054696D657374616D7020417574686F726974793082012230" +
"0D06092A864886F70D01010105000382010F003082010A0282010100D32985C3" +
"0E46ADE50E0D7D984CC072291E723DC4AA12DF9F0212414C5A6E56CBB9F8F977" +
"73E50C2F578F432EDADFCA3A6E5D6A0A3ECFE129F98EAA9A25D1AB6895B90475" +
"AD569BF8355A1C4E668A48D7EAD73206CCA97D762EB46DA75CF189E2EC97A8DE" +
"BA8A4AF9CFAB6D3FD37B6EB8BBED5ADA192655831CFDAA8C72778A314992AB29" +
"65F3860B74D96DEB2E425216D927FCF556B241D43AAF5FA47E2BE68592D2F964" +
"F5E0DE784D0FAD663C3E61BD4A4CF55B690291B052EC79CEA9B7F128E6B8B40C" +
"5BADCDB8E8A2B3A15C7F0BD982A1F0C1A59C8E1A9C6FC91EE9B82794BA9E79A8" +
"C89C88BF8261822813E7465B68FFE3008524707FEA6760AD52339FFF02030100" +
"01A351304F30090603551D1304023000300B0603551D0F0404030206C0301606" +
"03551D250101FF040C300A06082B06010505070308301D0603551D0E04160414" +
"EEA15BD77DF9B404445716D15929ACA4C796D104300D06092A864886F70D0101" +
"0B0500038202010046AC07652C232ED9DB6704C0DD318D873043771CD34CA966" +
"91C04E5B7A311805E965957E721358B2ABA55A0445864251263E09BFE2EAEB64" +
"43EA9B20F05502873B50528E48FF5FD26731BEA1B13CA3E3A3E3654E6A829675" +
"B9D7944D734C48D36E19B88B77320A5096BF7462E1B4D69F1DC05F76A9417376" +
"D5127027B1BA02380684DCEB75A4B14FA36B2606DDBA53697CE7C997C2FF13E4" +
"66234CBE07901DF33A037F323FEF8C4229F2B7D030BAC88B4C3D84601576B0DE" +
"32F3116C6DF7E9AA29028289E0CCA89F8B809310C37E9BD514536131D9E66AF0" +
"6B1F36BAD55C9F9D6D1393CF724D75D3441AD67491AA76C8C31AADE22209831F" +
"C079B49408ACC2C0D975EF8BEE3E0F6A01DA4DFC6045433BA6B1C17BB0E3E181" +
"22770667CBD6197413569470BF0983BF358C6E09EC926631B0A2385D3BF9D9F3" +
"0B5314170865D705CA773652BD66E1B3C112D7DA97CDFB9447FBFCD4DF674AB8" +
"A6F430760276B7D8439BE40961D0B7F9F2B7AC1D291C0E67C1789FE038B6652D" +
"24FCAF0A49CDB1E61FBA146AEFA3D934BF3B6AE8A5703CCA80AA500B56DF93FA" +
"931E2D71E292042342CFB073431AF0AA1ACC0B5F53EBF66CFECD52EB08B11628" +
"000F5EA01AB1D8E89F219178DB67B2CD68AFC2C0C248D8A65FD9AE1A0DBFF84F" +
"3BBF2077EBFB373F6ED8D6C7CEA7BFDF0425494078F293949496B0BEAF63CAB5" +
"62C297590A737174").HexToByteArray();
internal static readonly byte[] ValidLookingTsaCert_Pfx = (
"30820AAE02010330820A6E06092A864886F70D010701A0820A5F04820A5B3082" +
"0A573082059006092A864886F70D010701A08205810482057D30820579308205" +
"75060B2A864886F70D010C0A0102A08204EE308204EA301C060A2A864886F70D" +
"010C0103300E040809F1CB8B4255EADD020207D0048204C83EF1251C78FF3815" +
"CDB0648F20FF20FA0437E5AAC5CB91C0D547755113724A913C02427A12A878E3" +
"B161F388F4DA9AEFBBA5FEB274CEF3A35CC2EC4BFE32442E5B6624888D41FC3B" +
"EA02BBEDA034BB196A3FA41E23DCEB6F6E906FD86FED066D547518FD628C66F0" +
"1AA4B38F3DDD94D63A5B336B587BAC4D2B739EF096A902ECC4216EC284099F10" +
"C93785AFC3939A44C22FD027E4E643B03641FB3B76B21DB632D8522A365A495D" +
"5AC74CF7765E294CEC55C73F6A4BB45ABD214D7AECBC3735DA41D8FC66CD5C34" +
"54F354E16084D0E1984B20423219C29CAE0FDCD16A16C5BF17DB23DD8F2B1C1B" +
"DFC9008B647D2FD84E4EC7952BFDF4EA0F0A13D57CD530109BFBA96DD3F37F01" +
"7F7BA246C35A9D5C0A2294A2EEFE35B29542A094F373B6FFECE108D70CEDB99C" +
"A7172B17C6C647CD6614D3FAE0C02B3D54062FD8392F152AB1B46D1C270A9F19" +
"A48A393CCF22EC3DA958C35A8A6A3E7CFFDC2C54090F844B3B73C3CE7F7EF26C" +
"982567ED621FDB93E402FC145E6D7E8D7F2F9C56F870823C98B81586F34C7C96" +
"CBAA5A67544964FA1BD70B9C5E8284ACF22FFC69BF62E389C5678E44CB10D6C3" +
"D3F73DA7BF12B44D74C0233C140ECC93C5F0118C8F0D9B6FFDFB23966ADC070C" +
"8DBFAFE78AE1E05F8FA7C75A22FBF7A8458B9C61B1F2BF2AD2F0A6C6D15AAD55" +
"D960F173AC3D9890CAF50228796FAD6C7EAB1C8A3C8E9E42E4A4DA99C4A67FB3" +
"E2AC958AD989508538C96697A0CFBEEB38E9CF27DAE3AB9492729A205CB25340" +
"85CA0D580DCD49E88DA7950F99CD05523885B5257BD302E1B449F03941BD0DA1" +
"ECCAE6A22BC9F7E446F7F6FD4EE850CA3BDD7338F705D93C2F196712250BCB1D" +
"A18C9661E195486768515BC2761A66F61770589A62D172DF8EC288549E86E518" +
"7B04E1550154FF45060945BDA07014F14EB554A5A324F9B79DA192F79AB0745D" +
"F30355DF580778773F2FFC76FB7B367EDBE173AC7F70698766DE6BB384A5C88B" +
"66B163E8ABBF0AA44C4ED0D3D51D167E8BEFB2E71D36043ADB098BF2DADD409C" +
"1F53F5546D1C8A1DC5E7BE566D14C494460161BFA7CB7E936790A81A45763004" +
"689FA9BC33F31B4E86A152700D35B20380F87F4304D7850CA7BF583724328E0A" +
"0D9B611B919975DF118B334D9DD96A46A21B00FC3B7FCCAFEA968FF030EA5D8F" +
"9AD8624F668B2A7E433E54547EB89FB876A7E1AD2E9DAA38F30E938D8BCFB431" +
"6E12FB8BEBF57FD0BF542E55386A6DEE074CFC6A33A55A57503CAB7F115DB875" +
"C8EBF787670BE98DC03C65F2502D6F8D001ECC819BBB9C60BFC3A88DB8A117D9" +
"9E09C13AC23324E15E5EE3C22B084D428FF2DFB37F917F7629F8A15093BB7777" +
"B1AD8CACB4A5C6271E8B21A18DB95D6196E9EBD870521CA16930F2D1D43962AB" +
"B8413016DA0117E10AB2622FC601DD08826429D8B8AE9BC6F15AE78392C36BC3" +
"06FC19C90AD43BADD9AACDFA8CC16075529BFC8C34766C12783BF2F2E0B393CD" +
"4F8F05D588B99218806D57CD5935E25DB2AE20DC4CDFD7F5111AF9A9EFE45349" +
"42CAAA72F1F95636085FEC84BB98D209FD4222BC5F84DE5926A28FF7A5B7548A" +
"B4FC3331431964454A0C532C205CF8D3872C561E83D805F7BD7DC811A0A90C9A" +
"CB308E8F06AB739DCE97A840B4AFC0E884982CFC9B37897CF272ED1F46027101" +
"BC97B11F04D64B07556DCFD5F609C5C9FB4B3F2AB345CAB46211EF0BE5ADD6BD" +
"3174301306092A864886F70D0109153106040401000000305D06092B06010401" +
"8237110131501E4E004D006900630072006F0073006F0066007400200053006F" +
"0066007400770061007200650020004B00650079002000530074006F00720061" +
"00670065002000500072006F00760069006400650072308204BF06092A864886" +
"F70D010706A08204B0308204AC020100308204A506092A864886F70D01070130" +
"1C060A2A864886F70D010C0106300E0408C10D9837801E56F8020207D0808204" +
"78827979D15533A4A7210A435D0189C133B65B00407E85BC44368D066C65007C" +
"256EE51A55E35BF8EE7C6FAC3D67FF7CF2031FECDCC356A51396B2977E044A79" +
"E6C6CB8859E4AD49765468A4A467071292EFE47AEB39856FF8F00B5C6C6190EA" +
"B20CC9A7C630C09E3F351ECB20CEC1BFE7BEB5A3FD534BAF8CDB658318A37279" +
"269A11E8A87074FF0B111E2CFC493BD08D7887A7A222743B0C50E47F676F9B47" +
"449F8FCBC6AE5F5A3456AE6BC3CB8A3CF28C59D0A16FE4336E0BFCA0AD74F95E" +
"0F1010C3F698E16418E46B0059AB8F3DFD31FDB99132665CEC4CDAE8B6C1D0EA" +
"9DADB8E591769261C27188CD5FF8D5C56E6866D85E1502254823940EC77096F0" +
"6D3A261F49495AA60114BDDCA27C603F78314678CB08738FA2974DE03BE315F9" +
"1FCA511446C68127211CF575948550DE4F7FDBF4AC31E395E12EBFD4BB99F470" +
"498846940A92B6F85CF5D745B5230EAF994DD368FF55809F299213749CBABE54" +
"C54D39B2165370DA43468409E73C55EF784D17496AAF8B6B5CC0F9FF234D7CF5" +
"C84C248E91F8B08F74A8A953F60407940A2EB9576655CD9946D468DD6B3DB634" +
"A30D4FE8E09C51AAB99C3DB5CC834A447EFBFDACEC9A49AFD675BCB247575B27" +
"ADEEA9C5A6F2FCFF71A57EA99B467029C3E40D94D2849527FB90B9BF39294CC1" +
"AD1F4CC18F75302FF241E05896A357BAAB88BDA8F7EB22B9AEFC5D7600154631" +
"3C2E87452F99997CF4747CA936BD9199C61CEE5E61BBDB80C17978938F241D53" +
"AAC97758FD1A77F3C7C28F88F1BDC7E74176CA41B73B7042A6C3C7AE918635E1" +
"1EF4F2607588B0FF7C656541C32A1450AC71AEA42C14E94F0408A09902C30D10" +
"ABE8396EDF5760991C2E02949EED06D091A2AB64827A53F29FA8B8B79036DA26" +
"210A7C34EBE73590DAE990666E0F0F011EE8E41D08E16B28D49F30D8539EF18B" +
"61860EE73D9AF98E4D3F17A50D06FC0592C218F38C33E0B526761D030E037B27" +
"348CFDBB72C6B635BAEA497BA12618BFA47A9E358EE834FBA8A5FA9D30A66CFE" +
"BFAF1E25FAA361F94433B40628E7423491BBA29116EA6ADDC6DFEFFA3AC2AD83" +
"83C3EA05DE72B7CE357612A9C60CADCD42DECCD40438A9FC8E5D9413825178A1" +
"9D67E7B13449F118A6B56A4F8A5DCC0AA05D0AB40B8FE0820A2399307331524D" +
"B3389C97181EDC2ED2C5B72C1318B406CF99120CD784B85238488D1DA062478D" +
"1EE6380F9954BE5442C1C00ABF8D284AF95937E2D515E2E8858F3C50516CA00F" +
"E3F632BB05EE4AD63A6F2D72C7F2B06DC993866F6A740C1EF5159117437F646C" +
"A47AA4BE5936C2F6BEF4C628A744FA2A2E2068752FF43BB9CB29C986D3A466FB" +
"F3A107E8D610B8236E4E074CD6B32B50BF1C389CBDC2A92FDD19047450E04B4F" +
"B963CA94860C1DF05D9FE1D202227E351BC2226572D6950D7E5242BE17DCC992" +
"A989B7D13BAB9C8EC76FF5B8DED7696BBDAC058F6183F6F799365EA1DCC4F1B2" +
"43A35027BA2F02E19DFCABEB564536EDA7B073519C60294C4AC25956D9F9DA60" +
"3C5E4F335D7570299993460BDC5F20776F22D745A6B3F7E80EC69DA881AC72A4" +
"D6B7AADF7EF19C77A2555C1CF8CE1CEB030EBF1C365D40C9C33037301F300706" +
"052B0E03021A0414AACBB391FF9626295715807ED7DDEE57F716A5710414658C" +
"344F4B20292DD9282953DAA4CB587AD48714").HexToByteArray();
internal static readonly byte[] TwoEkuTsaCert = (
"3082044030820228A003020102020401020304300D06092A864886F70D01010B" +
"05003029312730250603550403131E4578706572696D656E74616C2049737375" +
"696E6720417574686F72697479301E170D3138303131303137313931325A170D" +
"3138303431313137313931325A3026312430220603550403131B54776F20454B" +
"552054696D657374616D7020417574686F7269747930820122300D06092A8648" +
"86F70D01010105000382010F003082010A0282010100C456AE596BB94EA55CE7" +
"D51785F44223F940237C1F0A279533875427547BDC3944B73E8E6F4463800571" +
"226147CEA3649972F96F128B673BCA6BBFD70B5178FE93D4DD7BE9E4D450AA0B" +
"4D177F24DBCB2A7A13D7F10BABCE0E9AD3B853F01872196F6905F523E260555C" +
"AFC5B158A82ED52D62BDA32142982EE8BB4E011E44622B59387B8A287F4DD7A1" +
"5C783EAB5D4736CAB0E06A78EE50A7BA59DFE2C35DAEA0637FD581DB485ACA9A" +
"57B94585A9E7D7BFAEE31F92F96DB5F95DDCE52B839BC06C30191014FE6804F0" +
"CF4CA29412EB34D87303CE5FB49EC3E4B1A7CB001B6F117E1D5846A605ECF5D6" +
"8FDC32EA972CC8521B823708518BBE59D15D10DB79990203010001A373307130" +
"090603551D1304023000300B0603551D0F0404030206C030160603551D250101" +
"FF040C300A06082B0601050507030830200603551D250101FF0416301406082B" +
"0601050507030106082B06010505070302301D0603551D0E04160414B163E5F7" +
"BBB872522615BB55850DF3D636E8EA6A300D06092A864886F70D01010B050003" +
"820201008E5927A04E7D6361819B565EC9C3BFB59F1BBB57007B4534FC5B2F53" +
"6A02BAFB2EC19DD8EE65DC77F34E2E7A4A2EA1597EE2019CFEBE8BA45BD35A53" +
"D201465818F1B6E0E891FB380813E27FC1F6D9F3D5DC4C23267FB4326960E7C4" +
"D69CF837904E694F4DBBD1AA346FC058B158AAC7EDD7F947F67DD09D9183B84E" +
"B91CDE170895B830F4DE87850BC79C3E27534298BD8C7E7DAF3CC1242777435B" +
"2A80CBD57C015B1B52A5B46D85187E5FF20EE68A96FB705FAFF4E335EF4FDBFF" +
"CC5D981943127CE41EFA8C1D7E2E05D03D772E0C02F4443AB3420B6E3D1607BD" +
"B2416268AB7D9D2B5824AD82B06ECB58B41C0AE092D704F77023F6CC8918F7D4" +
"3128357B7504276C805E6C27A0A5872C89375F69FF14E91B4A11922DFE7B8142" +
"8B103B55973214426A063DE2955AAB165CDF105E574F23C00E50FF5B8AB86222" +
"460734EF5003A0D780DA6FEE9B8CEF0AF45C0BB1D0D142C4A2FDB2BD9776B049" +
"B70FB4B52D2EF2141E3C3EC8F4BD914209C2F2EB31FAB2311F906EB48D4396D8" +
"5C5D9B54FDCF52C00FEDB9F399607C1D95BEC1D81BBF8B9E35C36BC72FD90834" +
"AE8D4A02DFF4FD65DB9748DB626FD4D387A4E0E5ECB73168AF3BB3C788DFAD4D" +
"CECCE43F9513EA99F1AFFB2B900F5AC55DE8D7AF96B243BA663500A63E4A35D4" +
"7257229376EE8C0179396C355DFEEEC03F8773BA1DD5B0807E44EA1E11257751" +
"67020DF9").HexToByteArray();
internal static readonly byte[] TwoEkuTsaPfx = (
"30820AC602010330820A8606092A864886F70D010701A0820A7704820A733082" +
"0A6F3082059006092A864886F70D010701A08205810482057D30820579308205" +
"75060B2A864886F70D010C0A0102A08204EE308204EA301C060A2A864886F70D" +
"010C0103300E0408C4A9C5FF5EE508D5020207D0048204C8344C1DBD71C360A0" +
"B4ECAD9F7F43F25272B5C99F1D54A7A0926401082B4E1512610D52B15CBD8203" +
"36AB72F4E57D083B49BBD606F5C1A268B66E7931E0980A06D8EDF5B5C0BCDA51" +
"908E21890B24054867912D65125BA0F75B561175A053D2F875C1C846CDC6AFD1" +
"7599AE877B8CF18585BC405B1E356FD49AAB207BC7C2BBCEF1B0E9FA2EBE205F" +
"E5F98F825BD9564FA45A7FF011EA41A247AAFA06391C62BAC548A004A139F9C8" +
"8039B1837066BBF5DD7E8DCEDA3B13ACA5214A53C8D6D748B4DA885CA59741B2" +
"5799051D59AECE8F06EE0C637406A91070C7DE72B2FAF982BB0A9D937C517D5D" +
"B0F4D0EB69FDB597F8695A9BC42DD5F87F56119AB5F3E051B0E03E4A069FBF39" +
"3C5592E1BC28264BDED3ACD7D0CBB5DEE9B426101C6CC5752A5068DF4520C71C" +
"F10875F1F23BF84D4B6D3A2E133E059A8B1F02B47258F36F84AF4EAC85045489" +
"971E63970A614CB05C3FA28A711F8DA220C23E463E50B17408E05316F1CB32CA" +
"37A0C4262081E9C60D897559FF167F2F9B58162399368DD5B85309E9B941FE32" +
"356258D2EBBBBAB957F496742DB2CF7D8233EBF879887B3F07156BFF9D2CF87B" +
"D495C684CDF46E451715D4CA1DA21F960868BA70CE88D4D8904EDB97EF69435B" +
"DC89648A1C330757D51B9D94AF48814109B13EC4AAE6EA99B2ECE5DFDD384F71" +
"E3A4D39328F5FC55344E2B6EC68D164F57B92AC17D6BF52AF153D431E06770DF" +
"53A8F14AC579E5E130FC5C3A665E5BEE8CCACC5188191B00EFD13A3A0DD1CBA2" +
"FAB565CCE5459DCE7CBF8332A3FA1A6E943AB05A2BD28A35025A19DDE18A63E9" +
"123BBA96B0147221E7CD90CA3A8DFAD634CF8A24EC1AF619CA7B43D844B078CA" +
"AC708A4D1775AE368B583785307CA3F73C370740DAE2163AADC966BED8EF2648" +
"28557C1F10BFFED48ACA7ACBB60CA16724F0FD9A2C79B4556A71C7BEAE5549B2" +
"BDF5B165760DF0C7A0977D923952C9DDC95D89D379E0DF0E292D1534753938DC" +
"8764451A231F132FE3F40C472CDFED28564002A39ACD4B7059CC284E72D27ED6" +
"4204DCE2CF30FFF82EE788950CF24358214406CABAB32332CCD7D14A141162BF" +
"832B1091EEA2C845DE9338D96917065E0CBEFFD292232B20956DFE8116C724F8" +
"EDB03BED1474460B0C3C45A894C7CEAEA083C2FD5162C926F5DD945BA3BF3A53" +
"45E82A93F8BCF462AF4C51F4784F8618FC2DB64B4E4A497F0654F573A2F83426" +
"DFF119440981C9ECBDBA7BDD2AB18F2D62B5EDEA6E2396537EEF3A4264EEC3DA" +
"4843FF0CD344204C8FDF9C92AF1278937694B30EBE6238AC70D19719D43D77C7" +
"6B117C4048A7698B822BF371EEC55C1A4C51A13E4A84822F5370616A67B25723" +
"0BB9B14443A8FAA13414244CFA353E414C9E652C447BE58AEEF982FE4A12FB64" +
"5FCE47038C15499277FD0EA308036497437DDDF39F596D48FAAC1177112E0929" +
"234E3F5389DDC21CE14362729AF3EDCD7F2641A8633C13C1E10FBB808E5881D9" +
"A19778C52E8A8D9DD97766B18EAA9F147AB7B184D7DA131148A70FA0D2FB079F" +
"E4E4062211D0EF4C3E40D49025BC84C68FC2CAD10F2F5AF80D8174B2A05301D7" +
"35F3688D854D5D9A2A4646D7F4FD49A16F9432197EB581FB71906AF7D2A0115F" +
"418AA18C1F14285C7197F3508D374947A8769A91711B0D159A71CA3258529DA0" +
"C918D8E53E0ADA32E8F32AF11552ED557DC1D8F0F1D027669221C00529B44031" +
"3174301306092A864886F70D0109153106040401000000305D06092B06010401" +
"8237110131501E4E004D006900630072006F0073006F0066007400200053006F" +
"0066007400770061007200650020004B00650079002000530074006F00720061" +
"00670065002000500072006F00760069006400650072308204D706092A864886" +
"F70D010706A08204C8308204C4020100308204BD06092A864886F70D01070130" +
"1C060A2A864886F70D010C0106300E0408E42BF45F0D448170020207D0808204" +
"90BE13F1716CAB0C61D6269860EF56B1C6695C35AA4B8333CB772579033EC447" +
"9B83662C6EF04487BD6BD3EFC7BEE8C17F5EAD6E73389A9EFD73FEE959F4FF68" +
"D31616FA6D24D918F0377555CD68AFFF60F7E7AAF1619C2E1F4B057F5D2CC20E" +
"DEA3A8683DF2DF5E6D3C062065B38FFC4C16E7AD27BD31742C8732D09114B768" +
"FFAE7BEFD13303C64E8CA18F2571BBB1FFCC3A28BDBDE510D841FF781D7C615B" +
"178252E13D24B89D0DE8E47D9160CAE6BDF5E3959BA35218EDC43708F68CB2E6" +
"B37BFE52D05141B5BBD351C570B18848C68AC15E109467E373904F3AFDA06905" +
"0C1596D2ACED9D2733EB1FA0CD503B06828944463C579986BBC24B443261F1C2" +
"2C170F13F3EEAA0FF2EF63200612723AB4A0C768B03C6AC3C6B8D967DA306018" +
"2D2E3B412EE8E6E0639C282ADEC3899F36D740CF1CEA888824FBCCE2A7A22AF2" +
"06681597D80B907F50F7044B928BFAFC10F2580B5F7380E2C43BD6F273CD7EC6" +
"36F3F4F3AD5F2DF9F48CF4B0A4EBB8CB3BA1DDE3448C5ADE45C75CB80CCD61A6" +
"AFB2E29BA3833A6465C34ACEB7E47CAEDFC1A6B5DB7E3DE594026B648082732C" +
"1A3804E882DECC2018BCC27A29AAB4B98873099025449B9709EB9C0B5F84EA34" +
"4A7CE3D0829DE1ED1C89B165A1130DDC8333E54486A94E35A8C017B21DC38D74" +
"C6C0A685D68103743DD7DFEBBDF0D9BC55DE11DB3F38F762415BA58B2E52CCBC" +
"72B76D70EA1BA331B24F3817DC635FF59A1247A8F6EB1AAAA257388709BE7E44" +
"E8A3716A4A2FA0D57E07853EBE9BCE05FDDD23215531BFBAE5E304A9DE44DA93" +
"6AFF963085CE099665B03357C295D33A338EDFE664EEF200A957484D51736FBA" +
"73924014152949BDF128248ACEF561F51F08456E03E3533354283A74D0BDA10F" +
"53BEBD5710C0735C2960188781EBE4B9AC0E658723CBD09C8898FFAE79E5D066" +
"EBE4586777E1039D38EFF6C74ACB80365341A868C610377C03DE1B691300FC4B" +
"76A7192FD2D37864CFB336852EE9C2FA8AB96F196A0EDD84876B3278C4200143" +
"11C933D8C759945E3565C80CE8E7782C4BEC074FA87EF25D951D846FC160A0E8" +
"ADE67650FAC6B2A7C8F9798CBF8DAD6B23CE7A429995051CFE6941EF7258A10E" +
"2BD776B6C7DD59823A50BB767E38D6CA099553AD0E3982296DBA8AE6D72CC473" +
"9F4A9476B113FB06DE80B32F65FEFE0545CB44A3F5940C6776806168C534BC18" +
"4E73AB8F7B0E855849ABBAFA9D832246329794682331A05DA97848262E9FBCD3" +
"0A4894B6EEDF42150B23EADB3362C54CEC2CDFA9F36F67AD22389B3487CEDB98" +
"174644FC2A7C5FEA11488F031AAA30A9F7FE15662C86A0AC5EBAF2FB47CF555D" +
"B8D1C85410107C2CF40099DA3B281F0DF391E5602B64DA73B585895DCC465338" +
"29BC0E72F178F41179238049BED59D0602BCAD8AC9E9BC140306D8BDD4150C6C" +
"4DFD8EA353271B928EA23482E719A58D02515EA83DB54252CB8D466EAC9FD1EE" +
"71D00DC6D39362883364E31CBC963CD295CDB490074F5C43759D7DD655AA8A46" +
"EE5FE06E186AB3025E71AAABA9DFD8A105ED86B85FF7C772F596BEEE31CA5BF2" +
"26BAC1F59123893945BB052A48E9BE2254FF1512B1C2E46D34111F7BA35EA906" +
"74FBC63FC70A18F095C2AA6CD060A7B52A3037301F300706052B0E03021A0414" +
"A519F103F114AFAD5EB7F368DB4D0748559CDD190414584DD2F41EC2DBDAEA69" +
"FB2FF401BD9FC3B57572").HexToByteArray();
internal static readonly byte[] NonCriticalTsaEkuCert = (
"308204243082020CA003020102020401020304300D06092A864886F70D01010B" +
"05003029312730250603550403131E4578706572696D656E74616C2049737375" +
"696E6720417574686F72697479301E170D3138303131303137323532335A170D" +
"3138303431313137323532335A302F312D302B060355040313244E6F6E2D4372" +
"69746963616C20454B552054696D657374616D7020417574686F726974793082" +
"0122300D06092A864886F70D01010105000382010F003082010A0282010100B1" +
"74BCC25C16B5B726821C2AD59F0EDB594832A15FE186A087FF40A8BC9396C55B" +
"C0DB2B3CE3EC5EF26A11AA87073348435417982D29C439FA3EC94A62B4BCC9EB" +
"CE0236B7E5306B3144E71373B05C24D3C1EE7A4D263BF11FC54D09E4B674F593" +
"389AAD503930EB7CEFECCA3A64FCCCC15E32E4B304BDAA36267E6BF2DA9584A7" +
"66E1862758D04E7FF9CC5C46CB074DFBCFAFDC355BF848337CD38331FE8556B9" +
"F350C6780C7260F73FBCA77FC454247B018E937D2002C9590E07804233EBC28E" +
"7BC712ACCF6A125EA60B86A87217B23A91866BEAAAE842D0D0D02E87F5F123AB" +
"811EDCAD7A6819E88B0F0D0932D0748EE02726D7138B1ACEB7A6D4090245DD02" +
"03010001A34E304C30090603551D1304023000300B0603551D0F0404030206C0" +
"30130603551D25040C300A06082B06010505070308301D0603551D0E04160414" +
"610479D21BFEAEC87835A7D03714613D566F25D3300D06092A864886F70D0101" +
"0B050003820201006511E16CB557E9936363DF92EA22776DD9AD1ED6ECBFE1A6" +
"B9B718BAF9828AD2B8CE5450F56E1371B54577DE1146FE82089A4331D063DA8B" +
"3CE786945ABBE4D11F4465068B1C3E4CF987C2C014BAD8BCECCC946EF3C5C56B" +
"0DDECFB11967A10949A6D111DC96C627D2F1D7969CA6BA7AB131367E89D950C5" +
"0B756E516CD4CC6BE679BB53684517236846DCE33BB49235CB1601A6657CC154" +
"8C2D57E5554B2755FD047922B0FAC86437758AB72C1A6EC458DB08D93CFB31D4" +
"8C723494978D7F32B940E5519852F9B6EA4F0363B59FCA7F8A6CCDE595896B91" +
"869C1D90FF2CA0CD29F9AA5FF452470B752052BFFBE2CBBE00C68F2DDCBE8C68" +
"53136118CFD1916D711BF90021C04FB5879BE0974228F79C71532FB2B5DDA1E1" +
"E89BD5EC9015F2207F7C55D72E976A87479AB62A46465E8D75466492F82CA574" +
"D788B27A5CA251C9BE3A4EB90F6E7F238CE8AAF46E598DDD70094E148DAE4DAA" +
"21275F79095ABCE8A47CC362386FDE498D102CCD42B2313AC88FC11E21DF8283" +
"631329E61F35E8DB12EA8D33DD02B8987C7FC38242412EC97CD52A7A913C6992" +
"D87E71A75F9654F7F9EDEB80B0BBEA25C5A22CCAF388D109DB0EA7C79247CE4D" +
"C89F390EB8C6CCC19FA9EB5DFC5BFA4457DB30B27CA73EE1C19934C8BED63E58" +
"F227222B86010D9521324BDDE04F47BF5190778C6B812ED78AC7DD8C82FBD0C4" +
"0DA1EE040184500D").HexToByteArray();
internal static readonly byte[] NonCriticalTsaEkuPfx = (
"30820AAE02010330820A6E06092A864886F70D010701A0820A5F04820A5B3082" +
"0A573082059006092A864886F70D010701A08205810482057D30820579308205" +
"75060B2A864886F70D010C0A0102A08204EE308204EA301C060A2A864886F70D" +
"010C0103300E040830D97AD5E5020804020207D0048204C857D388EF52DCE112" +
"B6D73E8611F6971BA662ECBA8F80435F83126D213190D6F77369E8D1213CF1C1" +
"7791AC985C7A0125D1D4728B841FE7BE3E9C44469CBE672377CD97821B49BBA2" +
"75789D64B648F4F243136E9448166EA366EBBB973041C437E1BA70B609761F03" +
"03A5ED03C041732D34F070555B006FACA2B8639A0B609D1A7F8A88ABD260CB69" +
"3365D9181A638A6ADF69385C96BC094E6EEA507160F18A22E0552183C586A45E" +
"C680CE10B56E1D3956F704C89A0981429C470DB378DE1CF21BD67E9EEB43B37F" +
"E00117CD3CDB02398FD0D7FD4B48EA38CBF6B19254E957AD2D8A0A4C3AE72355" +
"590407AC9FE2622C8AF04BF17E62CBB213F9D29999BF184532BC64E2ED1A5323" +
"1501741A1352F492AFE713503A950DF12E9BB505EBE9C80DF4DB6CC9E1EE0CF0" +
"02C9CB145E265F7D84A448B9C7462CE25EEBDC9AB3A6E1C996FC535FF7627163" +
"1CA7E36C1614A9113C96EDD951F2B3B7508DEC6A2BE6889436A741CD170B6201" +
"D546430CC38CE1E874D78A9D6E4D9665CE8261368FBA08C7456E5B01723D3465" +
"7AD715328341B4BAD14825D1DB1B0030819B61607E2F4FE76D0EF1616E2C1F96" +
"4395FFAAA4A9F7E833A1527B630D862DFF5C8DD6EE6557F55B429C9088020D10" +
"309070D8BD46B1512C0D6B68C8C00EBF215C5DC3DE0BD8B4A92E4C3115687194" +
"D7DEF524FEA4B02389388C7021BD85EDF13BE19086D08AC682EB8B37F1AC6445" +
"67CF6213363D889536CD8A4287A9DC16DD5497A8D06A489D6AB12E4943784EDB" +
"559FC02C7DC1E190A9FBCB8EF7D83AEDB31AE1BA8F356742E539E4A7B9D0A516" +
"90FCF505BFD5DA6AC8DD67439C2CE9E8D3DFB78A88581BDF0EBB89B810FA7894" +
"78D5A5BA44BF287BC8D98DF1B286F2B9109430524DFD5739405E46C755F9C943" +
"03C95FF6E89400D1E1D1E814D795FF0B77ECC84AABFF6A8D3C665770778CE9C9" +
"A9189DA1E257988AF6588A596F5534D91FA4505581DBB0F8588F97CC3177788D" +
"131A2F03972DA2753DCEE18965E032A5326CF50378D7D98233A913387315C71E" +
"3FB2D81A78B537BBBD4408C2E8DA4EFE975EFAA785BDEBA40C5CFF9E25CA07A0" +
"77DFD9744FE20F783A38A274CDB85A374D1E7723473106DEA578B14C766FEEE8" +
"6446C61AAFCED190892AE44C8BDC72D5178C3AB1BE9600CA15F5D3383A6219D0" +
"675F2DBA9AED44BF8702777EA6902344AA572535217EF44BEE37C6E507FEB4FA" +
"62EF557119608466CD1339C242AFB4F8E0E9EB403E41872B3C5A34B94EF2EBC7" +
"91111687C764E4E20A25EF07DAE9E402FB08B79EDB4F5B5C3ADAB14E3CA9004E" +
"FEDECD8DA9D4791BA96F6D6493B301698F2202DB9834B423ACFE71324716FDEF" +
"6D70FEBC98503E914593A1F511BCD0C39425DAA9981B6BEFA122F8812564D14F" +
"B6383F3CB8C2C41449E9B58B3D4EE27651C5B20CEBE786312878E641C20531B2" +
"909BE5727E4C4C01FDEFBC635292A663B53A8EAB29A1FA4CEFF11A02AD511AA7" +
"F2FD338A86E1876B568074F50B33835186C71C3854945AF082B4DBBD6865581A" +
"139B3973A3FD5E62AD88C51D636D616AB18EA808BE982C7C51B20FA239D07014" +
"CEE766F9CDF5D592B1D31881AA5939C670A7CCB48D234268D61031A27D99728A" +
"4701EF7A241C45A26799C45A8A0A02EA054215973B6F156520544DBE0C3A89DF" +
"7BBEEB7AB754495781A4A37F4CDD64B1A3A535826B00E1A710AD4D4A56C17662" +
"3174301306092A864886F70D0109153106040401000000305D06092B06010401" +
"8237110131501E4E004D006900630072006F0073006F0066007400200053006F" +
"0066007400770061007200650020004B00650079002000530074006F00720061" +
"00670065002000500072006F00760069006400650072308204BF06092A864886" +
"F70D010706A08204B0308204AC020100308204A506092A864886F70D01070130" +
"1C060A2A864886F70D010C0106300E0408DBF6A30F31A06E2B020207D0808204" +
"783C0D88298EEF3EDDB8C04416DD28F2DA6654714BD9092529FE1181153A60FC" +
"552B4D62B0C1F53C6F6337A7C774DBE4396690431E55A963AA509A2351104B91" +
"E74B9250AA58812954181B1ED602D9699105960C7B82E91362946292E65C99D5" +
"80DCD3B00FCC0FF4B25095AAF4B5E67886B817556D8B69B3016DE071E31F2B86" +
"3612A6050FB7D97C5454CE63B842B02FBA72D102DFAFEB01192CCF33BDDEAFB3" +
"950C53E1452B449950CA860BEF314B32AFABF6B9F2BB1CAFD064960C073239A3" +
"EEC38BA9B30BDF0A9DBA3FCA6F22F47DC8F593BB7102FE0D8039AE5B2317C9E0" +
"2DB059C99F06708809362C1676D14D7E5F3DB30E0090697366DDC9900A218E7F" +
"99851838A111B9C9C9DD9A696DD096DDAA23175164034407463AFA4664BD5E70" +
"3B6AFD659D6C7CD266ABE731F51F96A2D148B919B83888E4416759169C304A15" +
"57251FCAE553B5A177DBB5366B031B59149CCE263601A0231544CFD7107BDDFC" +
"4037AC0AD99F93D001C4CBC4DBCEDE235875C20789BBE8BEDFDE63D1959C25AA" +
"1E410AB081F03CF5562D814C54A9B66A27E74DC261D4E41513927BADA1E993D5" +
"20EA81D592B1D4ACEA2577929229B60A8B0AA7499037F3F7F24C1E8E980A06BB" +
"6B953090844FE068B611DC4C880A4B2FE21F82002C4305A9AE27C1B17607D59C" +
"89589F122721FFB6DC2D95EFB7D96625EE3C6C252E0E3FF25D4407549358F995" +
"D9911E9021303FB711B71D7D5F61D6BA845A456B9A832926A098E0EDCA081E53" +
"9FABBE54C09DF90D37D349FAA3A9259432491307C216E8D3C160E1D5E994161F" +
"BB29C9BBD789CCEB23591B983D35CE3001D7D4A313A9D66356D5B3BC0BB061D6" +
"49DFC15CAF2B8B70D3FCF40B1D412E60FFAD5FB4A0F2944F019CD2CD26108345" +
"20771F437BF27A586AB0866BF1F5920C488648D463A2C430E217CFB080E91930" +
"05589A9670FA9C75050E45100A553E9A21FE300DE621B12CCA03FE189CE65367" +
"B1CC452426AD21C67925894905CD594E85C354F85748994C34AAE7E281DC3C71" +
"81BEE53119708F6C2D29B2CA987F5620650BE2EA087FAF976BB58349E8B67F67" +
"FAAE11559752C31EB34A72FD4BB23B363255530F92E8C0C82FB7ACD6FF4DD7CB" +
"AFB831E624522FBDD47A8191957BAF0E9998AB61C5F839B6DFF3A568132A1A21" +
"643A576D3562EF72294B13E6662ECF9CBFEC602C7AAC5E01D43759917D95BF3D" +
"D572A45B2CAA118965764470C163FACA61D06693273D869214816431963087DE" +
"B10FE0316352440E87189532D950E0A9AE5ABE9926907E52F1E4F135B467F4E2" +
"8BA57B9F371FC934409526E261926E484B465ED10CFDB25A2F3E6838F41C37F7" +
"DF6A88E7063EBAEB6C426B0A4C7842C58CA49581F14337FDF43FC22DAF79900D" +
"306E34ED9DACBD6072DF4F34588F28F0F4AE13B431D9F47ACCD6EFB1C4EBBDED" +
"D507512B820FB02713948D45F3C595330B271308F0E6DAB862BB917EE9E2B1F4" +
"17CE21A26CC17358C11E2BCC514EB241D0767B4971E9B89F94731843B508C20A" +
"54345F58E99D430065326FFEA3E1FAC40E24BFB17A51A884CA022944A27436DF" +
"8F2C4E296A728496C38076FD3F14B007FEFF015EB42329F7453037301F300706" +
"052B0E03021A0414A0E907FF695A237FAB54BBB94CBCE689EE0B4552041426E2" +
"132250203B3235FD5023D999B747478D8873").HexToByteArray();
internal static readonly byte[] TlsClientServerEkuCert = (
"3082043130820219A003020102020401020304300D06092A864886F70D01010B" +
"05003029312730250603550403131E4578706572696D656E74616C2049737375" +
"696E6720417574686F72697479301E170D3138303131303137333331375A170D" +
"3138303431313137333331375A302F312D302B060355040313244E6F6E2D4372" +
"69746963616C20454B552054696D657374616D7020417574686F726974793082" +
"0122300D06092A864886F70D01010105000382010F003082010A0282010100B3" +
"CBCBEA8EFAAAEDF982CD046188D2F57FE9FE4F4FEA94ADFB7DE47AE731636624" +
"3C4E5F8C2821BF0B01A32048E8A275FD9B3073E0DA2E8870FD9671BFA600A47C" +
"8588AAE88150448E6B4C594C5EA288119BE9A3EA369F66EED7C499738B8EAF84" +
"5E6B36BCEDF7887D061BC86F12D40982199C1C41CCF5440AEF592A482931B541" +
"1B0E0400FB24AF838BA89A3E1393C24B80B4C67AB923DE68B0B8A2218DA93C2C" +
"A4908E3B906BF3431839CA6D3FC2A4FC33C4CB58BDEF8982A39DD186D0BB88E8" +
"E68819C4A7DA4D29F48F1C1F00098DF41C140FA649204564A3AAB9D0E7486252" +
"77F40B9739ED07D385BF9C0F78528CC5DED08A84B6D392874B2A4EB98B3A5102" +
"03010001A35B305930090603551D1304023000300B0603551D0F0404030206C0" +
"30200603551D250101FF0416301406082B0601050507030106082B0601050507" +
"0302301D0603551D0E04160414743B8DC143DEC364FA69992CB3306A9EDEACEA" +
"1C300D06092A864886F70D01010B050003820201003A48278ED517B381CA420A" +
"E3C12C31C22F49D1DC35EA60B018BCB88C6C3E0FF1E7A301E525B5592649B496" +
"7BA62D89AC748DB026CBD73C9333AAE89C5F5D76FC77E970F214F1508CBFBD9B" +
"09CD50EF93D61559004027E80BCE6809F196633C22A13CA2CD7596ADE5B4A23E" +
"BB4E03367892433357636316F0D235D3DACFEB99631CB437DEB04E4A074B1CBA" +
"6C6D722210B058285A3E124EC8148E31B3DE37DCBAECF560076FC0E50965D482" +
"DCBF529127CBE2440BA746DC71765516D480E68805C7668A0B538BC489DA2FE5" +
"E158BB6786A626BF0AAB74AF042347785B54323CC019CA84347BFF57C025791D" +
"69C558A605D46C50297DE1E9576972053A3DDFE5EC8FD2DE0D48B80252C39EE5" +
"4410AD46D8128A453758DA442CC2879290A50232B13920D9C6800D8773C2FD82" +
"D11755C336CD6416FFE26F97599A29E5D18227949DD4385C74D29547D6C70ECB" +
"CBE006AE2D18BCB8708C50E7C46D442A8DEDECEEDCDEAEC47042957B1D18D410" +
"96350438DCD8223B17E5FDC3C9C0D9BD47D191E6142A601930817E30F8E0509F" +
"D5F5FE269683494F08C55B9ECE6E3D503C81A81F40CC959B858E52BA086D95B5" +
"8DC13492C128B64F862E7800384C98A1303EA570D328C003E2B944A804B9794F" +
"A5C6040881E61510E90C20F21DEA0A73E0DA5C1A2D178A48D76CC8FAA2ADA660" +
"2A98B50AC197B40348A012E83A98EFF2B8D64900DE").HexToByteArray();
internal static readonly byte[] TlsClientServerEkuPfx = (
"30820AB602010330820A7606092A864886F70D010701A0820A6704820A633082" +
"0A5F3082059006092A864886F70D010701A08205810482057D30820579308205" +
"75060B2A864886F70D010C0A0102A08204EE308204EA301C060A2A864886F70D" +
"010C0103300E04084BEC68D6BA25EEEE020207D0048204C8E534D459438245AC" +
"EAC40458DAE1FDC42FB28605913F53F859CA1B7D62E385E48352F956A1B4D904" +
"B796CE577F18A5E334990367542F7EB0806EDE06892812F914D62BC029E6637D" +
"60BB10F125350DFC7F7702D68984F79C9192ECC07178330141B2CD8D88974F30" +
"DD2CDF6F82F668AA5BF9F3201F1A8ED58B2546A2683260751F8254C3AC574ED2" +
"8FBEF421A4C8B1C2CFB4691875314C06148A801036E39827BF3AA57F9FC32DB0" +
"00C0BB9CCEB0E828651AD82E903B710DE378B00533994AEA596AD4FFD5B075E3" +
"4BA54099F8FEA4AFCC469D071C48A0EF8BB58B46D3666A251188209AB7FE80F2" +
"238EC6977280497ED7833283D3C49DD9546190404E1018C1179DDABBAF18D9B9" +
"FE18D71FA4A87976F95A533FAE01E96057CDB05FF19DD14673AABB7FB5C3B01A" +
"44F7D8265B320E846244E7C3EE65D01F4B468084F3890D92A065D745F41275D2" +
"9650B00BF3CB7B4DB64D14A78591147F9FEA71DE4469DE58D1E90A40B5ABB151" +
"B4F24BCA90E1966C9588D96627FE1F69ED8BC7A52F03BEED75CA8E90EBB811B1" +
"37BABB34129C5E7AE44E1B6FE3A3DE8EC923F05E4A471BA0D27B134E5880CC4B" +
"20CE7404CE9EB2C114C7018E811786A7FFF5FE6A2C7FAC4C4B2FA0CA6223E9D4" +
"0A9D6567FB659857A83703D9E995CA2E1BC96FD6EAC678204661CD866530E61B" +
"40533A011A250B6632760FD942A8A5741410C1BF0212D66085BB623F5C53A186" +
"6699CE7CAD843C9325D54D260D254B3273717DEBE43F4F7FEDFC984546434CEC" +
"46D70E3B888A85A11252DC12E7D50A32CAD5D4544C161F81BBCEF0D0DE893F25" +
"C762FDCCDE1DF91262C815C925BFC6BA133E5CD42D32E7D2A6FB0BF22AE8482C" +
"CEAE15070F1692D5BF3C2E2CCC02D77DF879C4D4F188B80870A234714B92197C" +
"7A27F39A7E5366D7A2E99BCBF8BC5576DD627754EC4AEE2DE118EEDF7686D109" +
"0B3A59E97051624D56224423BC9B4A2D7A85549596D4F981E29BF4C7F6CA8F38" +
"2E4138BF515BB72CF4CF5D44F49274843BCCED64A9CA5A514E29C2DFE75CA4B2" +
"FABACCA238DBA202AC6A996BDE4F79C9A568450C849BF12063C0CCEFF4B81057" +
"A386697D217F4AD02ADCA127271CC5A3E5E9E3F6722D4173B83B39CEF5DF0BF8" +
"F9630D575F3A99BF83BDA8A5A1A8CA5AF876F14BA5360DC6CBA5D1EC2F46C3E2" +
"F14F87A03052C3EE4994C6B661248401F40EA0843F011E5186EF09B8917B4218" +
"DF0352289252463E2DE1FFED603F330D80D6349C36FA9CF9B721069BDD833491" +
"52FB1BA9F994507BB22CA076AE781FCDC5B1A487C9EE8BC2C83476260F61D866" +
"0981A7BA1F5471F56C067BC6A3C1C6F4F76C72497DDD8AB961DB8FF673B00EB8" +
"7C498624B2C46A184B6D4F248AC9307DF046DCFC70811402AF06468E7E07D6FC" +
"353830F4F06B5902FD823A4A94099AAD9CEEC531CC544F74BCE62777F188CAC1" +
"B819F6F0F449372E1B3ADC45514C8598A18427D2957511938CAC5439768A97C4" +
"8D05A62660628DC2C16D1CFE73920C00B6DBEB4D66D1572F60817FBCCC3DDEB4" +
"C5DCBB69799E4D3BC155FCF564B6AEBF25C7AC3A0F0CE7F4F2761738A7485236" +
"8B4D950EA6672BA4615A9A040FA5166FF520948CA1D3649D9AD2317B8380FE90" +
"4644F2C06F6173C8FB52A572FC50D69C273DBB63EBACA717441C2530CDEDAC0B" +
"3796FAA4F9BAEC808A01F70E5B48E42B2AA49AFB65054EEFCB0F10072A38DA5E" +
"3174301306092A864886F70D0109153106040401000000305D06092B06010401" +
"8237110131501E4E004D006900630072006F0073006F0066007400200053006F" +
"0066007400770061007200650020004B00650079002000530074006F00720061" +
"00670065002000500072006F00760069006400650072308204C706092A864886" +
"F70D010706A08204B8308204B4020100308204AD06092A864886F70D01070130" +
"1C060A2A864886F70D010C0106300E0408FDE1F090274C2210020207D0808204" +
"8071C27010C2CFFD78D49D28DBB5AEF4269926F1055E9DF0471FFD7077366628" +
"DB87AC150E12BD5C636BE9A9CCAB194C87F32749D9544873A0C2360453A5293D" +
"E03D5DCC1E3F12FDD89CF5BC37099A08DD9700CC0B6D1E351D5451386513E774" +
"C3FAAB375F7A6731C8923C7979F8B283D33C09CF1DFAEFA9EC014845CD779C24" +
"A1B085C2F9A8B3AF35197ECAD885B926463D785E9C192326FC6B956695970920" +
"8B571E383D1083AD446DFEFADA128E247BC038DC74C43E9B5832922814DCEAED" +
"F97E989BDB105642466FE2B2E2FEC3A19F556766DBBD0BCF9C5627876B1D2A19" +
"42B3EC2DFA957DE74E669AC767811C6CE6133ED50F97D29FA002FAA0A72980A5" +
"CC66C5FB86B1F657BE940489087D473AE6A5475A952B24A585254FC27AD50D80" +
"0C3A77B13AC17401453645C03FFC66984FEA1ECC385852EFD7EB008971E31652" +
"43A3F672FFB8590F756B4481EB5FFBBF5935C8062741D7AB38A4BE28D141FF16" +
"6773ADE4EC3C021DDB5FCC43E2D03CDA4AD6BAC0EE63CA816089B8C971A3244C" +
"6186BBEE09C09A31BC29DC8EAC665E7D9C6CC148C3FAD9028FF2E0A9F727DE1B" +
"08AD8561D918677FB026A8EBD9BCFB0E106C058C6EFFD53FE13996B9C40F12B3" +
"90DDD3CC63107CCA59F1CF861692629F4AFD7D3257218D9F888DF2E7A67BD601" +
"2EEF48B82D09F01D1D1EDCEBEE878A771399D58EEA1D50C8F8ADCA3432696F2D" +
"49D7253F064F4EC28C335853CD4EF9E72094517EFE61EB3E0A7F50451C1F9CA6" +
"B95FCF62F36E6D79B16D99119C9E0D4AFFB36972E68A1FA2E2A099596176EA5D" +
"C09756632BB4FC82136BB554FB32A2997DD982BDBD058F9990403FF786342C91" +
"F117A98F0076CAB6AAF35F8FD5A5E795F9F3368049849D582E9950B42924BBC6" +
"5EA3A0FB8FE87FD0B74C1621B52B673E92FD6475DCCB138425740AD1C006ECE5" +
"3633C9AA2B02404384A31F7FE7DC9F41F2CDB4584283B48E6C5D1EE659316F2C" +
"FAB3E6D5AEE5F0F986D223E7077C417BD890035E373BAC6B90E62451B14BB701" +
"30C263872865F8975165452074A53FD036FC3930FF2F781D2805999DA7955BB6" +
"4D4A98D0E67E4C18F73126177D047E89B24A409DEEA7B7B8CAABD0DD39DF3818" +
"59E973360EFEE67D8FF9E24275E9F47D5A67E812DD68F8325603F3040180D85E" +
"2EF61BD821CA666550E55F8A8C172D93315C6D7E14567BD9DE84A0C298A6A586" +
"A63611495C66DD7D9AF83E20CEF31F3A3D3CC25553F2045FBB547C97C1AE43E1" +
"F0147C116C82AB442562534E0898023CFB459DB66B7320DECA41E26477D76D5A" +
"562BAC06023B778271311E3BC8E2D5ABD90515650A994CDAA99D38F6169D480A" +
"122AD01731819FEEB8FE3111C1CF06FB9B5882EB74232B0CDA7DCAD2988FA9F1" +
"8F4DCDC7DDC45983128E07F6687AD6C1FB219B3295AA74592B3D8B05C7D9851D" +
"140A71CAD10D18EBCCDEB9C9243B39772E29D923D9D5014EA4CED9FE5C7859BD" +
"6AAE8902726D5ECBB6C0D028728F316034F991CEA8F435FFDF35B26583C1CC44" +
"959BAE4514EB478327BA76E6F9B759E176FDD8BFEDA8BDE6E7BF5E2F9C76CAB8" +
"055DBE8A531FA77690A620BC5463431899B7577E3AEF0D382F31955AB5FCC951" +
"973037301F300706052B0E03021A0414F2009473DB4B8B63778E28E68613246F" +
"D53995810414A911A22D051F1BF45E7FF974C4285F6B4D880B08").HexToByteArray();
internal static readonly byte[] s_RSAKeyTransfer4_ExplicitSkiCer = Convert.FromBase64String(
"LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURhakNDQWxLZ0F3SUJBZ0lKQUppdWpocnpi" +
"Sk9XTUEwR0NTcUdTSWIzRFFFQkN3VUFNR014Q3pBSkJnTlYKQkFZVEFsVlRNUk13RVFZRFZRUUlE" +
"QXBYWVhOb2FXNW5kRzl1TVJBd0RnWURWUVFIREFkU1pXUnRiMjVrTVJJdwpFQVlEVlFRS0RBbE5h" +
"V055YjNOdlpuUXhHVEFYQmdOVkJBTU1FR052Y21WbWVDMTBaWE4wTFdObGNuUXdIaGNOCk1UZ3dO" +
"VEF6TVRjd05UVTFXaGNOTWpnd05ETXdNVGN3TlRVMVdqQmpNUXN3Q1FZRFZRUUdFd0pWVXpFVE1C" +
"RUcKQTFVRUNBd0tWMkZ6YUdsdVozUnZiakVRTUE0R0ExVUVCd3dIVW1Wa2JXOXVaREVTTUJBR0Ex" +
"VUVDZ3dKVFdsagpjbTl6YjJaME1Sa3dGd1lEVlFRRERCQmpiM0psWm5ndGRHVnpkQzFqWlhKME1J" +
"SUJJakFOQmdrcWhraUc5dzBCCkFRRUZBQU9DQVE4QU1JSUJDZ0tDQVFFQTN3Y01hNS9YTm14UEc2" +
"NWwrZmtjV1RUcExzdURXTjIzZXVsMGI3OGUKK1RNNXpHbEUrakU0SHdJdXF0TTlXVytiRG5Ody9W" +
"Ri82ME1STk9HWW5wWG55ZzZ3cEtKQXRxcm41aUpYY1RKeAowRUNUUHZBVWhLYWdzaHJMdVFCS1JH" +
"U2pCdjVRQUg2cWMyZUZkdEJZS1dxVnBPSTBvUm5nREdkMTJOQVRiVVJECnEwUTJabHJEeVVJWnFw" +
"VEZzaHlhdU00Nm84NmttZkI3Ty9TN0ZwbHE5S3lrZkxXTGhpTWVGVWZ2a0tSYnJpeVIKNnVneDRp" +
"b09NWUpsR0Zzd2x5NXRyYm9HaGdtNTFKVEdDaXM1R29GcjlvZEJiWDFiSkFDai9peXM5bmYzaEpy" +
"NApsRmZGVUJHc0hkeXpVRUYzZVZGSFo4U1lKdHRIdnlHdmJWWUxBcXpwTE15UEhRSURBUUFCb3lF" +
"d0h6QWRCZ05WCkhRNEVGZ1FVdEd0aGs0LzVoa3ZZU1VzNU45b1p5ZkJ2cU5Nd0RRWUpLb1pJaHZj" +
"TkFRRUxCUUFEZ2dFQkFIYnIKYzZFRUxpYmdsc09ReU9HYVlxUFZNa3JyWThhb3FveXVQUks1dzVP" +
"dmlHVnVOb0R0dG1vbmRVek9pV1kybFlmUQpPak9UV29hb29qM0pQV1lrOEYrT1VrL05NRVB1NEFN" +
"Nmx1dm9oNDRCNThBTXNYS0JaUjFXdFpncTRKVmQwb01lCm5ockY2Tkkzc3puaEFkZDdZQnozNzUy" +
"bTV5bzFqQStKc0plVTdQRjlZL2F3bDFBWlp5VlZKYVBDdFpMY21KTFAKcVlWVHNlZ2NxVFlsK254" +
"MDdHVitja1QxaGp0bjIvcFc5VkZMaXFHWUt4RkI0WXVOTnAvRWtUeFY5QTdJeGpDRgorQ1ZyVy9H" +
"Z0NhbC9DVTE0b2tSaG5zVUxsQWw0RzBFeWorQy8zZE90alZQMjhWWFdacEJ2WXB6SWkrUHNxK1RH" +
"ClEveU9MN2psMGFnT1dTcngwWnM9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K");
internal static readonly byte[] s_RSAKeyTransfer4_ExplicitSkiPfx = Convert.FromBase64String(
"MIIJqQIBAzCCCW8GCSqGSIb3DQEHAaCCCWAEgglcMIIJWDCCBA8GCSqGSIb3DQEHBqCCBAAwggP8" +
"AgEAMIID9QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQI2rQEBhq4HAUCAggAgIIDyEn+zCF3" +
"wteqkmcbOFO7Aa2HbI8d1Dbp8M2QESYZhIZr/nX69etCuh4UewErHwwxfJYVQjhKO9NhWO4wB3UP" +
"defCCrbrCmU2CIiTsgydNw8Qfyrdp4nMUNJ8AGCK9+atNX5MmLnLoFFT182SCZiJFVspDAlI/aEr" +
"YNF3hvtYIJPce3om82XFHPotezxpFIma1MBuhQXEjcA12tfMAjPGdA1snqjMPPUOWK1f2Zpq7gCi" +
"Q0E9fR3O2g4ut2FDpMAPIsG1HE4TlnShJ7qMT1wj70BcXstTVNFALw9emw4guIbbeqJmPrFKuqpY" +
"7qi+Pk5AuBRMiR/g/A5ltJuP2ZemdlF79nI+Xz+uJPXzEHk4g4wueWCaR+lCeDhxGXqWrht4gVDV" +
"sCp156WiDdfaUD5wkWPKihXlI42S65dvltHEG/NiD3zY324rAM+A8fAp4S1aILrqXjENehtncgCQ" +
"6OX1RDvW2HD96pRwmdz0g+qGkQzQzzEXx2qdjqIO4nNWyedw/CrfEvC7mGCqoQ3x0mbHPtJNoRMS" +
"AyNzkk2jQ7d8EpQJhbhgqsox0kDwBLXF4DlX9IhotCZBGI3em47PV9jFD7DRbU8G0nVjqb2Jo12d" +
"5nkyvGPF+VIOxvqLO7yyMgptpEut2x6AhRsnCP+uPdzSCckPTJBlmGiHWIhRwWbLk77OLXOmF13v" +
"TpE98cZojKH026CfmEtFrNVaMkC74YBBbHQR97Q6aTUjb0KIMpfJ6zeWFs88/E8h9B0K0B3RNg5d" +
"qKjQhjix+j6KWAyhnP6iBSsFHtT30t1izEMPOK3Rn3lcB4NHOp3iRixAlb+abFPiCmA7Vo5ox7Fk" +
"ns4+n/CeVCZaMie0+F9JFE9c9wxi7wYp9YGR28cAB7jNsVgQ5NJypNI1m7S74D7ivsN1D/4H7w6s" +
"7+2NJyChQ6d1tKriDrpaFXBtuytieRGbmoI9hEqTvVRNGKHR/g1CJk705o+Iz25Trkhb8I7HOJmS" +
"U6TS4Nm5eZxaqcnLiwwq2bkm0O4yeo92gX8aynMAKVqp4Zdf3nunGer+HIbp7vOA3i+3CscqgIY7" +
"fFIQip75V3sr2acpQrSttY1sZiGQ7r7064g9WWgWmOloT8JaCPLzbqstA0q2+3nNsqOJItij8ig5" +
"e04ZJdkHNQSVQ560A3Y0+6+w0AOWJJ5U3fDzG+E06jdO8+2Y0lzlBmDEnlUx34OD5RBg/tgAjC7+" +
"SR9flnMTMwdyhfoKWMUYhtQsKk8vORGLjaJxyfZG33Ndt78nYazRPKW8G4sYdqi0bh4GMIIFQQYJ" +
"KoZIhvcNAQcBoIIFMgSCBS4wggUqMIIFJgYLKoZIhvcNAQwKAQKgggTuMIIE6jAcBgoqhkiG9w0B" +
"DAEDMA4ECFwry53rQT+rAgIIAASCBMgEOQRCGM/ukQAEA4qrBattYzlC3tiHD0gqEh6SAxvPabaD" +
"ISMLLoG0aZ0yjo+wDN7apOb9ohRIxoVyadJ9d9N4/nPIn1TnzHc7yQDTa1cktMSEszJgK8nWso+A" +
"fQeljqqMmlTkryMiUdp+ekRu4TiDzq+zezQp20Lw5sfTVgGuMYfTUAYkB6LNzjbUw4S7/mEEcpN7" +
"bKFKfcf3xi19yRwIO0ThLA9nF78Pq1QaORRpUuDi2zxSacHxN0wvM5HEIVEqL6+U7BgVAZF8r51x" +
"1/+0do4O1XZpDcDQC1/yjW39dSFzWbNMOCm3aj87Tc5wurIFW1JqPmHc01k/Ks83dqSqscEBte/q" +
"ez0XKtFGizUaxieo0ZQRHkLWE1wS7vmHIzhmYbRpSr3/WZO8u5Q5da3c1Gt5Jo6MAk3qp3gbowgp" +
"I9vPFW4NIhq+XIx9rn8BdwKIpRwXGB5vK4aWh9GK4KBMk3mFVxWYa0ICf962R9VMzSvSLSSIJyuW" +
"3UpbzXxQUjOVs99oKyfuDLyLQPeOVgBAVl5orSE2hcKAN2EZpHOF45TZsY9Z+HJaSwpaUDEPcvT/" +
"9JD4uLhAcH7nQ5HX/Usp9nO8N5zC+ozBT1Hp8o0+g5pb8FBxh5NF0Guj3TlQ6VDXFX41lArdJy04" +
"rZfWkGU9QE4VbMrBve/vyAiqdMIJ4nUCG0ghMr7VjFLPD4Gz7+9EZS2tft3tpu4VihM/TxSGgsWj" +
"Fiyy5YZRU72KLZ+ztZvdLqYOc52/Xwxcgzdb2owMkpr3LAJONm8yXI+PFkOAVF+vkBdf4zNIzmja" +
"ScsvnIhK7TwvlfAHEJBu8Q8pkO6sp7190WA6wOWhb7RovDMFMCJFaH7AVG8X7iu0fDxN/EqXwKH/" +
"XTz/+FRGDIRmmS/VtavQEWkUsfSKKxfKT+glZ/sHyo5T6Cml3HaUkZ/aW8sQ7klIW1/uDepYE4ma" +
"tA8znoDPT7fS5RM9cFfvn3Uh3KqfLB8SCBAiFkDQslf/vsVvFHxxIClA4++0oWwJ2rBibW3RdQPJ" +
"acgd8BHuTy65TMZgbkthVBFa4p3Ne2c7Zbxhazw0Pt5Fqw/+kOp+o9chMxJsu75VMjzvVpMgRott" +
"vn3c0jPj8olsiPn6mEWoYhdQQupTc3qmmhSHRILHc5FBY9UKoVRdg3fWeB8vf3OnQRqK1kvmc/yz" +
"3+CUX9Kl998lYlp/YrFpqIv9A1LkyF8l43hXU56yuQTgaoYiMVTBEbdQ6/Luwg+ZAhLfl41G8MCS" +
"Yn46mQgko9BYr9uIFpR78yzWbLnjm40vQ9mP2BE+5LxCg+QE0Frw7tpLHYrs1zIAhFw9nkZTDeTl" +
"6VvOSmQegbw5uP3VV/SkkX2fO8DzU9M5nDDmK/CCklaGy2nzFAKrHIhsHhML4FWjiLxA0PGh6aBE" +
"/2p+n9W45rLNqCOTejsbE5LVz/lUcDXbaCSKU28AdOUSSmv6f2hYV7idMmCORvpgKZmtjrjwVfGp" +
"Rph7S0574FrS744psLILb+aSGaiNBPOFiBRRcUhPyVNL+Y4cOj/NMpgW6EsUpWpTJAr/1dnjFMbz" +
"lz1b4B8KZkeQl3smXJaJz/7oU1jJ96QRYnGRyx6NYXOvu+v3b56g3Lo8MvBF59duDNcxJTAjBgkq" +
"hkiG9w0BCRUxFgQUsdOM787p6dBPlEljE4Lazjja1NswMTAhMAkGBSsOAwIaBQAEFHcLzfQtoDAa" +
"sbfisMs0Ll8CgjH2BAhMwg4eZANcOgICCAA=");
internal static readonly byte[] s_RSAKeyTransfer5_ExplicitSkiOfRSAKeyTransfer4Cer = Convert.FromBase64String(
"LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURhakNDQWxLZ0F3SUJBZ0lKQUs0cjJQai96" +
"ZnF2TUEwR0NTcUdTSWIzRFFFQkN3VUFNR014Q3pBSkJnTlYKQkFZVEFsVlRNUk13RVFZRFZRUUlE" +
"QXBYWVhOb2FXNW5kRzl1TVJBd0RnWURWUVFIREFkU1pXUnRiMjVrTVJJdwpFQVlEVlFRS0RBbE5h" +
"V055YjNOdlpuUXhHVEFYQmdOVkJBTU1FR052Y21WbWVDMTBaWE4wTFdObGNuUXdIaGNOCk1UZ3dO" +
"VEF6TVRjd05UVTJXaGNOTWpnd05ETXdNVGN3TlRVMldqQmpNUXN3Q1FZRFZRUUdFd0pWVXpFVE1C" +
"RUcKQTFVRUNBd0tWMkZ6YUdsdVozUnZiakVRTUE0R0ExVUVCd3dIVW1Wa2JXOXVaREVTTUJBR0Ex" +
"VUVDZ3dKVFdsagpjbTl6YjJaME1Sa3dGd1lEVlFRRERCQmpiM0psWm5ndGRHVnpkQzFqWlhKME1J" +
"SUJJakFOQmdrcWhraUc5dzBCCkFRRUZBQU9DQVE4QU1JSUJDZ0tDQVFFQTRJVUVaTmpMU1pja1Fi" +
"WWJIUk1rek9lOW1lNzBWQVFHUjF0QWRLeTgKbHB2bkFxWkw1VGxPWHd5di94MktXbG9kVXlsOGpZ" +
"dEhRc3lpb3BQRHF3QVBVUk5tdEZtQnVsTi95QW5Bc3JTZApqdWVHMWJCUjFZYVZzSFhpeDR0Mldy" +
"SjFJcWtUbzIrTjIzb3ppa0w3ZWJzM0RtdDE4NlNLckJGVkdyODAvU3hYCndlMThiUWJQZ0RHYStS" +
"MUczalFZakpPVGRFSk1rQzkzMUY0ZEFBYXZVcjgxWEJKNTg2T2dUZnY3SHhTMi9TMVAKS2cyNk4x" +
"M1dWZEZRMmxieDVYYkZRZVpoVlovZ09uL2xDckVwM2NFcGdlSDdVSUt4ZmFrRGFQNHF5WDNhMXhx" +
"YQpKU3hsa3liTWFwaWpiWVBiSmRzd3RKWkhIQTJxblhhTktwVDI4NldLRG5lWnlRSURBUUFCb3lF" +
"d0h6QWRCZ05WCkhRNEVGZ1FVdEd0aGs0LzVoa3ZZU1VzNU45b1p5ZkJ2cU5Nd0RRWUpLb1pJaHZj" +
"TkFRRUxCUUFEZ2dFQkFObFUKbW1EU0FrSk9rZkxtNlpZbFY3VTBtUEY1OXlJQjZReGJrSjlHUVVB" +
"VjZrSnMwSG1lcUJRSncrQWRHRFBYaEV0dwo4ZDlGR0crZUtGeUdjWEY3Q1V4TU45ZGNjaThHYzFQ" +
"WnA1UEZmbk04UVhZVTdLSFhRQWVlNm9yWW5FelBPZzMwCnljTklLbkF1L09Ram1ZcjRrci9zRnpk" +
"Q2I1MDZRWkRxMnF0ai8wZThDYUY4T2RXdHNTWGIvcGtQM3liRzZqNHUKZzF2L0JtU1VYaUdWWFZx" +
"M0JDUGZoeEowWGhyMnBBOS84b0VENjFBMG1aaGVmOUp5RTFhZFd5Q3RTaWMrelplYwpBcStDTnFs" +
"R2o2cUpuRWhTaDBXVkdwMlRmMFhRaXBTTDk2REVCNlF2NlF4T3hpb0xNNG9zY2tKUEdhTGl5cmNj" +
"CkZDUFYveUJyVm5Md0ZHR3NheFk9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K");
internal static readonly byte[] s_RSAKeyTransfer5_ExplicitSkiOfRSAKeyTransfer4Pfx = Convert.FromBase64String(
"MIIJqQIBAzCCCW8GCSqGSIb3DQEHAaCCCWAEgglcMIIJWDCCBA8GCSqGSIb3DQEHBqCCBAAwggP8" +
"AgEAMIID9QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQITLms5nr095wCAggAgIIDyPyxib5c" +
"oCEPC3OpfmCzzieARKf56sQZU31qlDJNDet7v1R68T7X9vu236kHOphKvqedPVNXKEPpaQXIxkSY" +
"Hus2Xg7Zv7jwW99/A/coitXNEyOnqdv3vYRu2f69iwZJQmiPsQKC8uVbDBgPBZPPe+tgkY5e7dqZ" +
"mwob4oJ3bjKR4cYPk8QkSOxgBXHLNZ0Cv3fjiAVKHnPGSo5pyvwwUtSp0bBXniyq9wnzYheiLBSg" +
"S99M1HVvnbbFuhZYeyTP6gqRSda9bgVa0NNGhFYKjnw0H2K2KRtIskL/P4vcxZWTSdLNxZKQDfgx" +
"R0Om+f8qFiDzaW5jo3ljJ9pZKrHWo0tDAhSBicOvFsNTX3zu9ldRJLyHO7SZObvHr3BCa6LoXRNA" +
"BEhYmihmKwCv0dXfUgEZ6BSwSeHdNEWSVQhLLHI5oL2eRjHOCa8q3Md9GDn1hdnwUQftmvn9w2Dg" +
"EhJxJe+DjhLquh+fB+JXFnrNg5s0birl1RPL7wsdadGBav9UhpRcIgxux4eaOkkGE8mySOxBY66s" +
"BV6upSxJf+KAQXBQOqMYoC5wK6hXzllAWLDjpEHuU2q40bTWoUZk2lw8rSzxW/mhLoVl21Ix3x6h" +
"Hm8VUaGkOsQbpMhI68B47yNgnkUyX5FciFtxnV7cxAqxjtaq5yO7gjzUSs7uyV3pYhdL95f1tlrD" +
"goBz/OKSFZYnII8UnTQniFdqZc6rhKnJpTvuVJy6I3Os9DrJpZ34MagAkb6lwIy/BqV4hPDx2AaQ" +
"j3P/Qk4xPq0EcbUSuDZHAe4nLygpnMtDynM5UDcUjLLEtGIX9MpUtAPUtZEH/ZRtWF0wIkvFCUDc" +
"Gh6v8bZtRYvCd4Vbnf99ueRKjyA2PREcriO+gsdEUd+rmkBwCMPPRmIjX8tr9yuqM9kRlmvzYbBB" +
"3RcUsfyl9I39S1kJQkrr5mOH2hVMTl6UQ70jM+RBet4FJN3TUWaoBNm5m2+9FLpL8GcFPH//WPnw" +
"S2AqXl+iTysAUxqjtZ8jWkyl6DmybKHxPbR6Vy/6w/2WOUQOOsnFADm9NJPV8TE1Z6qnhlh4f7fz" +
"zAue+vnkZE7920JN/ThEkreIJ1vvyfPQsfo5XSoK7SA7OlP0JX4bKEyWsahFzmFOaGNJUCKTR/gh" +
"JVB6CcgrvyAE4BFsZeq79teOCKVZiseKwtmarTCMGQOdo+h5ceWXnII0gjndwcZbzURh3sj86AS+" +
"GXk69sNKC6HvbineMu/oL8ZgsifD/OTTRC5ewXENyoF57vMCkFV19K95PNTN6icGEcYeMIIFQQYJ" +
"KoZIhvcNAQcBoIIFMgSCBS4wggUqMIIFJgYLKoZIhvcNAQwKAQKgggTuMIIE6jAcBgoqhkiG9w0B" +
"DAEDMA4ECITzIA3DVAowAgIIAASCBMhUF7mWIkOeh/4zd9n71iNtHgyZIm90cF31YRHS3syGcsAI" +
"B4LH0wnHthG1u5GaEhTjMzBTr96hFkOFwmCW+8Kbg25oIcy12aren2Rn2LPkoHmmV/aA5ot7bbsK" +
"2vTgbae4GbMwXb0oBMKLU3wzKcYyluhVGVket2+szUHUsMKZxhFUThkvZqnNC1BYKDidiCP0npEb" +
"bgX4ARBEB++bL01YFvQbX/72JSPKTtvTs3aoYTlfoklwUrxSw60/wYn+3y8KVyBIkdZKDVKS0AbF" +
"uNEQZYmyf4AiSv7q4h6WKfwI9ojl7wv9k0/h/a+x+8rAITHdX/ZaSNcmoWa/zCKWNO+YntvrRxLZ" +
"xGE4t3S/4h32bbo+dDD5iLucuUGVMFt6b9CBph8+QYIbte3zjQPjPWY1YexRI4LqiK5/3ZFCRPJK" +
"Eq4bYmhur34RmQ9vZy7NfANgW+lJVit1vfOMHjQj62svkbabMjVrWVhnpAJ7jhBoNRzbggY/Ehhq" +
"G5BXY6fEjwPWFivHM0gmmBX5VlCTmhJck2sCJ4rKSpc9ZB4J6ucPH3wHEyO1HIDgB8yI47v4CZeB" +
"XyfIrozivPn7OCmItD4tUdH7w4/BJxNOMZ+Gpoz5tGWoeMcPWzb3JoUBJgpZ7YnqFbG8I1lTlG6P" +
"EbhNuyXtB83R65CAASteHww7PMfZDmUQO/KJwNvmZFPNox4IocTKLf7cOMXt6NR5hPQpc/tecDdu" +
"QzQG1nEITq0MP8Ex3YQgu37gfpYNiRAki7yKrwzYpwVrUSwap0RPIn4+UxwoINXngwZTmNkhXEr+" +
"sfW8uiB8P5ZrhqF+9dCGBHKAAy35NMEGXXHK79YOrnP2qNf8IbfnopwnZNYSniKFF7XvPmjiVANa" +
"ARQ8wWIUbhsweZIz9dz0GH7mdk877o0k1xrqpXagAeaF7wwAz/HLFbIG4+XXD5fFjkqaFpuTYjOt" +
"FgneN9wXDwgvQWyqPbjx/kJBD5k+UAW1r1z+LDwD/VdPMJ5bdfWa5QFCIxWw137VsieGXNZvB57Y" +
"hdI2D3LKk+0DhGJjGTxy6g/ZTwvGUlPPe20+Ip2+zSoKhE2YVBAbsy36+cr77buOPg8L5aNqUg5l" +
"rIYe5eLADLg8Unavy54ySIy2pZ0gX2G2eGQebwAIQEqDYBIRUyiEhbjGKprTTRQj6Ho3M/mmHOKM" +
"fHZeWT+BGOAa0+eCz436QS7YsXl2AOwFBqDI6ZONYTBRu2WLvuK3nbwb+h1Rv6/pd7NGI6AXJBKJ" +
"1+iBLGl5HBoOIYmpG+yGgajXGXDVqkRGESUnrJQGlXbwq00MFvtKbGI9+iQBgw4pbrUzc5xId0OZ" +
"1ynSTYrKzaGfi1KqMj2dQbQ+b0SshD/BVrBtYYVEnY9LaPokHna0cYcUGXxnycesk2Av0kQziEmH" +
"vltVZDj1LyMBJzF/auHY+Pbx4NIN33fOdKXByQSE4ulZqgsftn77B25yxwjO2Sks+ess7+pGBbO1" +
"ikOqm6zol92lwRibj8bbbva86Sd3yd846Yxc4QRcSldTPMOQsBrfs8ZetusRCiONXb+gKDne/Z/N" +
"u94mkxMkJvLRJHPesvNkxiXYhC0mSFl9RDSkIgrRJ2uRSxv0V5OdcAiCi3d98OlrIYkxJTAjBgkq" +
"hkiG9w0BCRUxFgQU++MZ+0nVwxEM/9SdcPKsQcAk4ycwMTAhMAkGBSsOAwIaBQAEFFNlHKZQXjbm" +
"f0PE6idyhcH963CyBAiMLpuBSuzCdgICCAA=");
internal static readonly byte[] NegativeSerialNumberCert = (
"308202C2308201AAA0030201020210FD319CB1514B06AF49E00522277E43C830" +
"0D06092A864886F70D01010B05003014311230100603550403130953656C6620" +
"54657374301E170D3138303531343231303434385A170D313830363133323130" +
"3434395A3014311230100603550403130953656C66205465737430820122300D" +
"06092A864886F70D01010105000382010F003082010A0282010100E2D9B5C874" +
"F206A73C1FC3741C4C3669953929305CF057FF980DE2BAAEBA5CF76D34DE5BF8" +
"ED865B087BF935E31816B8B0DEDB61ABEF78D5CBC5C3389DBD815ECF7BDDC042" +
"BD21F68D9A7315671686613260B5D3505BC7C241C37C6E42C581228965B5D052" +
"B8ED3756966C6B678CDF647E5B659E5059915B16EF192BD313F6423FD487BBB4" +
"06BA70A7EDA7DBC55E15F1D93017BC92238D22DD9A15176A21F1BF7CF7AD280F" +
"7C32D76C8B136F0FBD0A89A373CF194CB5A0CF7AC1FA8098458290FD66311BB8" +
"DB17E9CB70D6668A8926F26198586C796C61EEDBFD376525130BAD2C452B6A66" +
"97AF7FE8F91408785C20DE79F4AD702197734328B4642FB898FF730203010001" +
"A310300E300C0603551D130101FF04023000300D06092A864886F70D01010B05" +
"00038201010057E4CE63680B165CD3DDAF5CC84F31CBC6C2CCDCBE33893A3FA7" +
"01781BBB9F003C0E301216F37D4E9C735F138920121983728EA88324DBEC66C7" +
"824BB25EC534C3AA5999C8A6D9393F9B04B599A94B415D0C0392E0FBE875221D" +
"A4348FE76ACBE5D845292AC475A9104052CCEF89390118E8EA8051519F423276" +
"164D8BDD5F46A8888C540DF5DD45A021593A0174BB5331223931F7756C5906A1" +
"94E7FF2EFB91D4CBFA4D1D762AE0769A07F2CC424692DB37131B2BEBDB3EE4BE" +
"07F9B1B12B5D368EC9317237CAB04D5B059F9226C972BADBB23CA747A46581D4" +
"9240E6FC0F2C8933F1844AD5F54E504DDAA3E87AE843C298DED1761035D2DFBF" +
"61E1B8F20930").HexToByteArray();
internal static readonly byte[] NegativeSerialNumberPfx = (
"308209C40201033082098406092A864886F70D010701A0820975048209713082" +
"096D3082060E06092A864886F70D010701A08205FF048205FB308205F7308205" +
"F3060B2A864886F70D010C0A0102A08204FE308204FA301C060A2A864886F70D" +
"010C0103300E0408F693A2B96616B043020207D0048204D8BEC6839AED85FA03" +
"2EAF9DED74CE6456E4DB561D9A30B8C343AF36CEA3C7F2FA55B1B7C30DBF4209" +
"58FEB61153386DCE8B81DCC756E06EC872E8B63FD6D8341123FDAE522E955357" +
"76B5A09941595C79404E68729389819D05459515314167A9E2585F3B2C8F9F24" +
"860BA42612DC492137051063A8EC8CBBC3D0ED59B92D10E6612C0C9AD5AE74DD" +
"999007CFEDA7A1AD2A2D5C25E41201F5A810D2654A3DA1648AF5D9EBBCFDFEEB" +
"FF8BC78A7BCE26EF0ECB1B0F07B33FB777160ACDF3DE00267398D771A35740AF" +
"661B189CB7394C02599417AF601231F3B6F40869E2DA8909D8A6D9565CFA389C" +
"5A002193B3CC374D973F0A587697CE6812126E3BC390093E56B671E8FA77E1C1" +
"E56AE194AD7695BED88A1139AA149F4E0875121995661B4133E9242FCAAF8A1F" +
"5721A055FC523EFEA4EEA98B6FB48EF07891B2E80D6EAC824FE9BBFBCB6A72A9" +
"52F12C3E3DE63F33F9A126BAC8FB0C7F2BF98A781598E6FE5A86409F4F22249F" +
"4A38B4670A2BF0EF93B0990AF33672CCAEFF15BB5813ECEDFDA38CA2BEEDAAA5" +
"2B880609057B3FC728F6D1964B7185A933B1526666FBC42C1B5D9A6FF3E2B3BD" +
"1BB8893BB6B9170BD4D7C6EB47C573FA90E19971017A6FAAD2B36CC746EBB238" +
"2211248404A09E2ABBC546D85B212286334E164FE24E03BAE053C3C12FA21F29" +
"FAC8A69F0EEBC688FB50834B5D7F2CB7CECC9BD5D6C06200AAC11B33AF2B6E11" +
"1F3853AEFBC086881561860093AE6C66A488BECE95CC80ECCABCFE91BDD302EC" +
"B86DF4B99530ECD707943E76ECA51E07DC109B9B788D1C0664C560352B251FCF" +
"D9F57C6C18DEDFB9B848A2A57A96B0BEB6C20FEFADAAE468D96B48AB061F6BE6" +
"194865E676009BD48E5951C534C05A4C4186DF7CF85B596E2F4FA2495440071B" +
"C13ECE7AF0E58FA13B53DF115BBAF846A5E2AF1F71B3F8AE895C62ABD90FBEBB" +
"815993D122B4B6816DF95C8097E9A1FC66F0181441B3BC3320BBABEE02004138" +
"93BBFEB480123A28B14AD4D4B8C918B851DA11C4347C8D1E46B2F211F0E6F049" +
"0674C2B1C2F6AC020D79E50A45363AD54D5CD2D6668DE917111111E380ACC015" +
"3CF5A0E3B25A4DF35305308FA2A5C0FFFFA31F6699D5F0699DD82AA5502EA6C3" +
"B6B782FDEDF5515DBA4D1FDB295A77119D49BC098D35A45E8DB2C88B7C97DD1A" +
"BB54B0D2EA27AD7B7A79D3C707C482376F8F612129C48024F4A1065BFCFAC2FE" +
"A176AAA2E0064BE2E77D9E3BCEA0AA732B59DB213A9A0EC972E376D8ACDE5BB6" +
"4C668B0E24BFE9479BE7574B07D4BEADF821769720A0B7557411826C97206B3D" +
"176262F4BBF64631ECBD31418487588773E39D46784A4361E31742333BE1DE2A" +
"BB0331011CA400795E306EDA88F82C78B6906B22E5D0CF68F9F349B9725178BA" +
"6B03D972E27C8EB376BE51206DE070FA45EE430D6CE17FD2744A7830E7A8E2C4" +
"C5033D39BFB14D74214ADE082371C49246540B0593487B0DC95BC9B887FA2222" +
"250D59EB2BB04983AD59004E3921ADCADB30E5C713B9B5FC31A6FD97D6694483" +
"2E29DAD105CF81265F8149B5EB32192CD0FA45F53621AE7A4D372ECCEC013D08" +
"B7D1BE73E5D3331236E90DE00A3AC3044F1A5462C9E84CB621A9C68C8B954824" +
"B684ED3DFC2D2839B19AF443F54ECBF3EC580BADC3CBECFDFE05BDCBA201C984" +
"C7DDE01EF79E57C5E8EAF9C1E4C8D48DCDA8C6A51F8C0DECABFC4BA6B776C4C8" +
"BA0110C6D5CEEBC7476E86D4710F5E773181E1301306092A864886F70D010915" +
"3106040401000000304F06092A864886F70D01091431421E4000380038003100" +
"3800350063003300300061006100660038003400370036003500610037003700" +
"32006600610036003400350035003900630062003400320064307906092B0601" +
"040182371101316C1E6A004D006900630072006F0073006F0066007400200045" +
"006E00680061006E006300650064002000520053004100200061006E00640020" +
"004100450053002000430072007900700074006F006700720061007000680069" +
"0063002000500072006F007600690064006500723082035706092A864886F70D" +
"010706A0820348308203440201003082033D06092A864886F70D010701301C06" +
"0A2A864886F70D010C0106300E0408EBDF03E906A5A3C1020207D08082031043" +
"B764B7A7FA6203394F0625BB0D59B39D3F28197972CBEC961476D76BE560A312" +
"1ED025A9455F39C33B2ABC1FA897EC29FAF01970321069F8CA20EE4DF6F9E98B" +
"0DCB3A290DFF4B9B1D151E4AE3AFD7D7383B40B292B0F369A47823A7C175F6CE" +
"A327283B8B33712B88F06ADDA6CD626036765E9E102E110C8E44EA75E53C5FEB" +
"661B08D7A9C06B59A35E76F293E8EFA64AF425B877D0321C13BA0079DA14D3A9" +
"A76EB69CF22E4D427A35C7391B650B822FA91FF0D3DFD1E037C34E2F1110C1A7" +
"F88A35E560422AE31203ED22BA74D1A6F8FB2AB5DA6E5E66633B7081E6F5681E" +
"DE01BD28E6DA6B6E0C1444A010DE229D6AD6E44E99400EC22EF1DD6E7E805503" +
"4B1A29ACD78F6D561E2DA35B84DA1F08BCDD0A74AF49E509744A91F4304F7EEB" +
"6231C18EC9159D31114183C0B9621AA227663AC67A5DB4B0982B539578DF0ED7" +
"6B577FD370FA4330E2DFAA015E1E6E2E4C6B71967071390D4B1CD061F567D072" +
"2BBBE027C1350B1679D1AE7DE7522AF62960403C15F1B75DC2AA0A1339051FA9" +
"E16692773046ABE0EEC29C1E6FE0ADEA33F7F878B004BC161D362ABDCD2F9992" +
"82D967B9FA46BCBF0D12CB6659FB2BABA258DE158F51F961CAD7AB5D68D6DFE8" +
"5E0DC6F043C4AB203E2F549EE0A3C2E25E13CD1462CD03AA3DB4689BA1DD0D8E" +
"D8293DA3D195901405154E98999E60BBA39A543E64963BE607BD48275508946B" +
"D27DA136C9F53C692DDC81FD3F6AD56419589716EF6F3A66A35049B29D438D5C" +
"F778961F74E954CBE1395D8A98971C30C3941CFCF2D3B8851C819D79D164FC71" +
"CA414798F4FFF3A6362A59AA17F543B5B4B2F2B7E14ED48B8ABEEB68469161B0" +
"6D2233257291C6F1B67D0BDC2422F3E04213CA29EB648219A6C3E339C1352E55" +
"F6D8749592723934693DD54F1D098DACFE9D308556B060CCC75D2F7AA8DDEC3C" +
"B1B127DE82AC8489FEFA4A9F09D49C919F703236036853D5E802975D4B3DA619" +
"EF90CF53AA38D0D646B69E75751DA833C619337722CA785477343614ACB67AF4" +
"427E3EAFAC5900F0A573512BD81F1A86A848321309156093665E39193B0867A0" +
"5C86500AF2760F8A87DB8E6E5FA2753037301F300706052B0E03021A0414AA38" +
"B6B4257EBA3E399CA9EDD87BDC1F82FBF7D70414B796F49E612D1A2B5A0DEC11" +
"608A153B5BCD4FE9").HexToByteArray();
internal static byte[] RsaOaep2048_NullParametersCert = (
"3082032830820210A003020102021000B2DB376E004B56F8089A1034C37D7330" +
"0D06092A864886F70D01010B050030173115301306035504030C0C436F6E746F" +
"736F20526F6F74301E170D3139303432313231323134335A170D323930343232" +
"3231323134335A30173115301306035504030C0C436F6E746F736F204C656166" +
"30820122300D06092A864886F70D01010705000382010F003082010A02820101" +
"0091A009FE3025D0366735DB93BFCD714979B4982B54374E60C4220A2C0F7E74" +
"A9BF62EDA8D87BE09956A73F4C527FEF7A53C2DA2BFBFAF28FD49C786E09963A" +
"948A10D65DB8AEC829EF88DD5FB7386211AC8828124CBC24582450FA11337B4A" +
"72FE8FFC9C95C30F4C7B0019FF591D0C92F88B7A21D25C8CE47D52E55E4823F9" +
"CB06B7F62E10586E2DBAE84D48654F1D7A8EB5D160F6B076A82A3806864B09A7" +
"58E9121AE8EF50D76CFFCFF81FE4193E5D0BD3E0CC4E58FDBC3CC973A2907C88" +
"EA3E7BD2689384341ABDCDA2525C275EAFA4884F548F4FF20A869E9F598F48C1" +
"571D42DE9E8B4C4CDD6B47865F9BA0A7BB342B29CDCE00D6711B79C2C8D50405" +
"330203010001A370306E300C0603551D130101FF04023000300E0603551D0F01" +
"01FF040403020430304E0603551D23044730458014A791F70FC3C8B363A49AEE" +
"505055EAD33659711CA11BA41930173115301306035504030C0C436F6E746F73" +
"6F20526F6F7482100099356AD75D355A305839B87F087B5F300D06092A864886" +
"F70D01010B050003820101006F0FA161D224E2E27F35CEB37B92A8090568C9AE" +
"F29F659A1DF3484770369751359849721A544759230AC79E8487D38CFDEAA31A" +
"492E286B10E24B6B2FACF0E6F103B1D4CD6FD2B8784F536C1397B6E791499DCC" +
"5B82C006458793815B2FA016A9C2DB1A690A8005803B60FD1876C11D290F77ED" +
"5E41F63E907F21E645CECD96F063EB3E22BCDA5D80EEEE8BC23379BFD6B37184" +
"82ADFBB84C6E28F86A8367F28A1777E61A1E0EA50E50993957E9715D95707A22" +
"5C7B4071D980FDC13E0D72DEDC6205884B14E523941CC0F1ADFC64109E85ED67" +
"83039EF14C45C5CE54151D679E8D38FB90F5F64F96C8FE23CBBA362C1A17A922" +
"32DB27C43535DD8ABB9C054B").HexToByteArray();
internal static byte[] RsaOaep2048_NullParametersPfx = (
"308209BE0201033082097806092A864886F70D010701A0820969048209653082" +
"09613082056606092A864886F70D010701A0820557048205533082054F308205" +
"4B060B2A864886F70D010C0A0102A08204FA308204F63028060A2A864886F70D" +
"010C0103301A0414CDCA906D503CB0FD77952B3E473FCDA78409868302020400" +
"048204C8580404D87213470B672926374C32E46601DF1B0CF28A28C89E91B402" +
"BBA6F12557D46C36D7C50447651BB14AB488671879C278BF4ED7B3FD1C2C387C" +
"B5491192C552F2617683DB4B8D752CDCC29FD16E711B3D715BAFA893A606F767" +
"8D464A12AD34D74EAFA7872CFD90413407723C3A2344B37BBC801BA5A2FC50F7" +
"F23ECEC60FFF517B942EFB269F7291A568E6CE294A89231D309639228FA3559D" +
"D72A9D51A33A6B112422F63E55C65E8C5B7AC69D04FDB785D9DAF53FAFEAAD02" +
"CCE7A10690EFEED1CB61335B663E8AB05D43148EFADD170205CFD9C0BAE14703" +
"40B2B10BDD0F6607ADF176026183DD62D2E0E52E77AD6945B616F979956ABE3A" +
"E1C193A8BC7AD57DF90F02D52B88761FA85656039035B15D326C7C400D0C1BCA" +
"CE265C8B1B3F48DE1297852055C37C89718383F7AFFEA171795570A2A13EDBB1" +
"22B257A47752A67AC0AA922C69C50939A225B6725FE826A2ADFDF6672196547A" +
"71C25A1FFAE1BCFBC06A20D25F1A0A1C35678E1DD9ECAF3BD1DA1F8B803CB3BC" +
"FE39EA2BF26D4B74F44B6F8BCC43B39B1D51F8B935BFA55DFCFA504B5EA8792C" +
"35D30E40F908C4B9D200C65F89492559265DF46B7659C2F3934EC1F4590F6294" +
"319E03E88105CDE763347B77C30FE66F538DDB7C353563238224F523EC0D7469" +
"1DB8C4D4FD5B99CAF8576A5508A0D537E33864749D790864D78886C47362EEF0" +
"22E5E32B1A8DDA19949317196D641D5B08473A234817E10B2BED5DD9E680B30D" +
"E5E545A1B93819200435D73CE39E083E9F1D19B55E8B0A0BC9144A5072908127" +
"DD9031F5FAF0111FA7D1511ECB5809E49E29DA27954C78CFBE384D2944CDEEB8" +
"3AF2B4C861AD92005ACD0A6374544DC8C89C28BC3FD7A9287BDA231902D8C6DC" +
"3417423BFC82075BB29009C7CEEC69043AB209BE934C6A08A11362E79083C25A" +
"716267098C9B8C054FCD55B8310D559E612273E84DABA24CAFB3FCBFC2068591" +
"0762FFF325599FF882AB2C013BBFED97D21520DBCBEC0EBC03170591A4A98229" +
"0FE8ACD561CE5DECD3C4DFB8C32BB6AB1B8799A8D6515569F37977CE60603D43" +
"87A5D2BF4D62FF0C971B9EE6AE735FC4C047376DEA0EE16A12CDE810A5AF738E" +
"4B454B2CE484D608A07FA18CE4868B6047F1BD377F7A8F16A983E19D9693D677" +
"7F734F7417221B7D2ABC0E74CF9C039FBE16DD34106F88AF25ACCE8F407A5179" +
"EC3BF209E35F5F315F0F0CE064627EFD830DF50CDCF8D21403D533924711B442" +
"3E6DFB65B5AA000EF6DB8D90F57BCC592FE9C6F1A30A7B7FD4D651F4B3E37F70" +
"C6CE0267370B5960C74EE23EE476AF8290114E41A2535FF3DE6A629EA2C87A71" +
"7B3C164E6103222F9010ED4426A2B766DFF4271C1C6A2CF704F1DB1B8A27215D" +
"91115FA4E873A00487DF7EC18E07013D47F59A5014AEE87FD1F94BBFFE72D8E6" +
"CD0BFE40ACD32DC3F8AF7E8E288ADC9ABC75E5FEE7E56C676D25D94F1AFBADCA" +
"7ADB09ED186751211D5A07CE4735508489178B1958FAE7E96A5AF25ED52FDEFC" +
"D72E351096336D4C65836BA62693D6DB3111EB61679EC9AF0D837C1B1C1E08FD" +
"E4413EF1CCA6B61E029195E477DCA8F92DC503A3F90A917730A0B4134F5543A0" +
"877E7A125E7B2B87BF21CE84A811E2D8063C3506DF6ED4BD3E5AD0EB1119876E" +
"C51172FC664C4D2771501D9B977B0579059932DC6F4B6811593CA1B063316150" +
"A4385EF3EE87C2D4A64A2BD2313E301706092A864886F70D010914310A1E0800" +
"74006500730074302306092A864886F70D01091531160414989A932D9FF76F8C" +
"FCAA6B7420276D27B96236F9308203F306092A864886F70D010706A08203E430" +
"8203E0020100308203D906092A864886F70D0107013028060A2A864886F70D01" +
"0C0106301A0414692101FB773A3B21A23929C1ABEFC05DA7FB2C970202040080" +
"8203A021B1E0409E6D0C4D02435D73CEF56BA485245E75AFF29214F9889B3AFB" +
"80529C789BB4F0F366A850F89B35175554DF88A0CD453FB4FCA331ECC5069B11" +
"03B670B745EC8F612896FE1451857232E5444FBA5A52ED963984ED79906D815D" +
"B3F59FB19DAE35D8EC29E71016581AD3BEEF9992A76B776E221C73C47930D7E8" +
"FD378FF254EF23CA3B34B6E75F1F7FDF58688129E4973A18BCDBBD9C5469D6D5" +
"7B08E5377C2C416BC55642EB8C27545BF641500916EAE7A37B7D3346B9EEDF32" +
"3DEB35D07D1E28420950BA40FCD45F2CFB7BADFDFF30D04454AE32A7583A79BE" +
"002B34DFEA8259FC93BBFC67F6FDB428F4E73BB5228FDCFA1B5E4BAB67AF73C8" +
"B53683CCE9A3A255CF66AE2DA79BE727F378E74FA9CFBBD6F30AC1C33D25501C" +
"DFC61E5FD79BC13AD0091FDCEB00BA11A26DA4E8FC08DED37C8E4176C7D9A4D2" +
"A6C91F847AEE5EB07EF37FB45411CC21CA230957F4D9BCDE96CFE8C5E476B5E5" +
"7CC87ECAE0197C77C7977DA5D5E5002D5F51DBA06359B9F5E99448D700ED65FE" +
"1618B347E2D1C9B4425F664DF796DF08110BB72E55D4CA34A9C19D4A00DC7161" +
"8A5C047DDF25AA1BEDB4649ED421F51316B4EAEA1D6B264E86743BB92BFA172C" +
"EF5CE50715D1226505F780D3BB9ED84E30719B88B776A44278360B052A6BCD98" +
"17F0129FAFD37EB2566802B54533D345974E55D3C6EA59A224EE38203B32595E" +
"5FFF6BBD41DADC4220D1202C8C71633A026901F08F2FFF54D4661EB7E4E658BB" +
"8F059DA7F300405E17007694BA1939E473610802F427848B0C7A9C5AAAAD1F24" +
"0CEFB2BDCF0F4F8200B1EAE67430C47FC460B57E65D973FD9852B20B9F7C8009" +
"B9B99A52513264081BE6AC7C4ECEA3E8F702D32C82DB7221F5FD8116971D2473" +
"811BB2C13ED6349F907BD1819B04DF7DB213FB0AEF0EEEAC47D9DD74FB387448" +
"519E03F43803CE1A0CE168C225B8EC2FF5A4F7B7F2E985458DF078C1152C8D8E" +
"0835A762A307AC352A3B6D37CF84B934F857DDC70306D0953CB7797356F374E2" +
"6DD3B96C32BCA6DB98DFC8413B87171955B6758F382C2EC43DE012D9F02E5335" +
"1F8E063C1E0B1896334672D621AF38E153EBCAB7D5CCF61087916CD6107416E9" +
"11069B57359839F7D64FEC244CC8AB35F65C3F84DB80D1657016F69111DA7B63" +
"052205786981FA3E3047FA4BB4876F315235F96FB83F02282ADD202168123C73" +
"A2A8698209BEF3D3FFCE19EACD67708D97194BC77D94784CE85C33ED1BCB82D5" +
"4256318773B4E6A58D1518CACEB03CA74999BF7A898A6BB543413803F77D925A" +
"6D9A23303D3021300906052B0E03021A05000414A0CE79F0E969E2A8F6959B58" +
"6B99CD091DE4E4FA04143FFA346F6E7F8ABDE22A51853C06F365CE21D7D70202" +
"0400").HexToByteArray();
internal static byte[] RsaOaep2048_Sha1ParametersCert = (
"3082032830820210A003020102021000CD1B955EB1EFB9F3BAE8C64D49C16F30" +
"0D06092A864886F70D01010B050030173115301306035504030C0C436F6E746F" +
"736F20526F6F74301E170D3139303432313232313734315A170D323930343232" +
"3232313734315A30173115301306035504030C0C436F6E746F736F204C656166" +
"30820122300D06092A864886F70D01010730000382010F003082010A02820101" +
"00DD16801AF1ABCA05C53DA0863C7719C9719DFB363784F5ADBC0367BB98E873" +
"FD46B06CCE3640BC3BAB450756E8CA7FB336D5EF1FA15BE76C60F06E71F3843B" +
"9155D6DCEA8A3C9D361068FE4AB95064AABB997731E47FDD00AED791A377774D" +
"36A204C851E521325F2BA01616CB5684C8CA628D7A42C8CD02CF423FF9C6EB80" +
"74F5D61E8226A39DAC0E4B051701FB7301C4F85DD4D2DE0FD1D5CC143B18FDE8" +
"007ADC853C08003B86F5D4B97E87124906CF4D3C746CDBDE3B3B8431FB1601D6" +
"4EC6E9EC99C6A5288023F8C15803DD8E85A6621C0714C60FA8062D5E6208FC5B" +
"F1C32B7DE521C0AB1A7E60E444A1230E6BAF605BA35FC1111CDEF6B6E188DF84" +
"8D0203010001A370306E300C0603551D130101FF04023000300E0603551D0F01" +
"01FF040403020430304E0603551D2304473045801419AA399804F91ED61132EC" +
"CBAAF578543F46972DA11BA41930173115301306035504030C0C436F6E746F73" +
"6F20526F6F74821000BEBBAC206CB54DF85376C2D4E0F19F300D06092A864886" +
"F70D01010B050003820101000B8F34A7BBD7E2DEAD1E1025B505DB439A7CC9B2" +
"6D9BD4EC8E0D5A5B3222E0926F5B2F97B888AD2AB8632CE2EEF9878FEED75A23" +
"019B4FFC6583B95FE8E033A75D2293E6A37084E811275E9819311A9E9A5AC9AA" +
"F27031E814CDC7A7DEB99B42D8D24334BD00C4B8066EEDEDA9A19F5AD4720A87" +
"E0EC4299A8F527929ADA9AE72A6D28E5E8EBBC7AE565D645065E0D64FD57F87D" +
"8A3D542EBDF21F3464FC3B3AB33A74A46DCC2658E73690B7BB800B20E30AB038" +
"6CF44C4211FA82A49F2E52BD168590955159B2D82A37421E0A72A11E6AB2117D" +
"F9AB0E0165F0E4C5D4075FE9E21C8B6E783C3EAC67027B4F9FBCA3855FA361C3" +
"C322E14CE938B2FE3A5AF38A").HexToByteArray();
internal static byte[] RsaOaep2048_Sha1ParametersPfx = (
"308209BE0201033082097806092A864886F70D010701A0820969048209653082" +
"09613082056606092A864886F70D010701A0820557048205533082054F308205" +
"4B060B2A864886F70D010C0A0102A08204FA308204F63028060A2A864886F70D" +
"010C0103301A0414F4D52466643FE5A7B6C45AD1800F828B2FED17DF02020400" +
"048204C8C5779FCEF0DE7E5D03ACCF6BCE8126CEE1F35DE299F7CE2ECF36F54E" +
"A95DDFE98D164F8A5BC7A9F6CF39C8B90FCD40323D0C885E6AA5C54D810CD706" +
"A42909972CAA471BF8A6AE1E51D646D95E29507CC018ACFB060B36268BFABC8B" +
"82D01A31B1D492AC016D06BE487A5557793DE1DD1197C9D723C1AF3E9AE2DBC0" +
"640FA18D3998356C2FD6D2A06DFD259E34083543AFEC7F72B85CCE6BE565C430" +
"6EE7B19A039D1F22BF4F3AA3EA272C21AC4DEE6155041CCC0EC2DB68CAED1609" +
"3F328689478A7A25B36A47A6655691F10163220ADA2F436943A68A6AB24D76A7" +
"D12D400EFAE7C6D85FDAF8434CC8C524CB4B3759893536957F06BDB03711DB60" +
"315EB84799C29C00186D4640278640815928679266CD6D767E83EF10B2CCB277" +
"4D1A90D8F64A23CBB3A823A6A7D0BC1BD8B5D2E56E91F3F117D5D88EB88489CB" +
"5CF4522D47DF401D1C8525A89A79D04E7A6A17CC04F4F2D7FF355F91FB0EEE57" +
"C8B8B8CEF5AC41704A303013FE95DDBE70646D9A34A77A4CA283018213E2BDD0" +
"92F3F45A8070E1472A3A1D6D8AD46190620CBD84FC5183F3A03921D9C815C1FA" +
"D1140B6BB1008301B60E58239BDE8AAD68340AC3BAF2FDC00240DB5965C6BCC0" +
"5F58C2B63F36A25656F645425B019D9EC57893245C48C0709827B208FA705716" +
"3CA6DA5441C46B1A76187B7B6D2A286EEA26035ADED73B3B2B3229EC53F04608" +
"60FDA1413CF2B5D16DB55806D90F09CE9D4FC41CB9FDE51869E2650270B042B4" +
"063572217AFF48B3D6B5EFF29575DE8178B2D3397DB909A1F6ED2BC4623D4AAC" +
"F2E56B20DCC6064BD5673F9AFB317372BAC63B9B12CC18E3A8C3EAAF63B2A96D" +
"D04EF4A6580F98C353570ED1F268C4CAB268F6409F972AFE37D42FEC5896AD95" +
"F576F745BA5092D7D0591A894B3C2B922AB76A8BA5523DB6EBB7CA3C63A39436" +
"31CFB8958DC8C327296C2892FBFFD40A66F34195C5D9C8CECEB0596BD09406F5" +
"CE417BAFDF31D0438409D12A8A657B093BF48FBEFE532E6A54EFBA99439CB96C" +
"971BA7CD42CEFA3F5CE46A1290AB16DD451CB5228D6C6B611F1DC3A3856D2689" +
"495949D68921C7AAF01E96F5BDFD365C1D09776EFA1367C8C1613B3EE01FE02B" +
"338600062391E21341C2B2EF0E918FBB30E382DE3011374E852C8AC37EC74220" +
"C1172AFDF61229F02D7774D5FDB33E5B5B44A961CDCF386D3DBB73946E20ADF4" +
"D3F52F21A433AB71217E6AD17CFE85224D4E6326F6BC6FA0DE4B76B433C24767" +
"7D7DCB754C2C5F30F6C50817A7AA7AC0520DAD79BDC5273ACFFF2E08A38349E6" +
"6BE4027344D0BB590C8F9080CBD0D9C0C0DFF360CB53E74ED5922C75CB87703C" +
"3601A7FE69BEFDE8618CC23D05855A7ADB58F18C68A970E6B9B9D16C0147B2E4" +
"279460B856DEDAB4855C529CFE3BC76D2AEC253911DA6A2CB3BC965FB9B43A85" +
"B3EA673724C310698F16E24F9DEAA547095C70736AA559447DE34EE8A80FF9AA" +
"EF79929BF7BDB474A41E7F4D7B509FD195CB8C6B260D92D76AC50B3650CCBA7D" +
"FF11C04C1DC8F5CB1E99CD651234882269212BE7957732C3EF74731D2D349B60" +
"8AB1DB1DF628C1D50842E481ABD7BD15A95196416ECA8870A2AE9EE6B1724933" +
"44DD0B843AE53362CDF4C23BAD8E96BF205B783CC0B810B56E7AFC50F1F91B19" +
"C6776F01D452B29A87326D262F1742902072B4143647E28D821AFC27BDDF4F36" +
"CF6A6857159C43582396C7A2313E301706092A864886F70D010914310A1E0800" +
"74006500730074302306092A864886F70D0109153116041481AC4AB421E0EE3E" +
"783F04B1FD5314632A7CA500308203F306092A864886F70D010706A08203E430" +
"8203E0020100308203D906092A864886F70D0107013028060A2A864886F70D01" +
"0C0106301A04140003F5A90C3AFBADC5D4B269C00550E8291F952E0202040080" +
"8203A085E9E37AC65A1539B96463E46790E461AC4FE12D09E72B584C47332342" +
"1446095C926D54A8154CC5237E41F3DB93D5AC96600A3FFA115BBA90942D35D3" +
"4C540FA5FE7C06BE6EBF432AE0674D0BBF51F5AF54A00FE6B0779F6D24133632" +
"EFCB75AE44022F8DAFA05D82BE8704E4A2F331CF4DED131C9DE7C2BFF7871539" +
"724AC6425922C9D8C4DD45ECB1957FE3A97A0CCF8AC38FF6B8969C310ADA5AE9" +
"DB43DF7556AD724702D82B334738543B8B85723F1DE520EFCF3F15BA72BDFBD4" +
"CE9A3B858D812317341605346DD17569FED134D7FD68F628CA4C888883FF8BE1" +
"9AA25E24AD46AC4FB9672B5FFDA7FDA340C611E4D7E8761EAC8A3D9246E4DC1E" +
"D1A92263E8ECFC9A9BB676CEF3E413D159F475EEBD7707889E71E6F799740B3C" +
"E56A1EE57752C7A979DBD90EFFE1E2AD2B17685BCD9AF73F59532225C648E2EB" +
"7BEA8CB81CE5705F922657F8E5EF4F32C8F4426F2E5C9664EAF7AFF9C7FA0975" +
"E1A3AA5509E0931AB471B7B9C64A08E9A103F47C4C4430D7D9EE848094B6268A" +
"9C7CD811763CB0344B6AA1CB3C3A9964628BA348A93C75C2755F7E11315609A2" +
"27BF54010948206501C92D3551B106DBC15EB596E1141A0CA48B7D655A13D0D0" +
"E35473701AC38936102905C4723CC84F01C74DE854DB3AE352E0514F4AFF54CD" +
"BF4146A03ADB72909AB999CD21733B9C5065FA5165E27A6ABD89AF8754D9C010" +
"0C76A2976CDF958FBB0B83C15E2CA8C80397B74E43ED388C80FF4A05BA13928A" +
"61077A56BC6064098D4EDE315A6E96B2C30D3B48102896BD1B9E1D0774F1CAE8" +
"9AE21A0A0162CA05336E82351DA659F3E8231467C40B28774D639848FC435B12" +
"4D5BEABC70765F021E9B04823E33D0A62C00CC3206DBDC5A65E3A6404241E715" +
"2B3C942592A0B1655E9C1BFBF87E5643CC227258B64F3BE8266A91F2D4DCFB48" +
"036E6AF7B81069EB66AEEB50C8BFD9129C51B518E15B4BE8BBA60989DF77852D" +
"C3B394BC2A17BCE4A9C935DD1E51F8F672B5DFE18EB1A414791651B4875C1F45" +
"7BE8EE0D3D1DBA0869513879E8D9338F993D4E57267DE23B7015D744572BDBDD" +
"135E07793F3E24E04638772645DCE8325D7DDB9803E2CF7BBCA9792F0EEEE001" +
"5D9621D316D83CD90E7F5451F2A8F9264A5F6FF6AE85325985F31854421D82B4" +
"60F4420B9F3F08608CDC79F15F1D0096A8580225AE9BB81EFB85E56C80A08AA7" +
"D70C42B1CF6DADE96D635574847F84AB9DD15FE1E393DEAF368FACB2F03D45CC" +
"52C4F6A3BE155B7D32D46738200062BB36B53D7CE3FAF2DE04A83B42544AE212" +
"728658303D3021300906052B0E03021A050004144200D15CFF93500F241D12EA" +
"D690D3DB9CDE40A90414E9656D02B74AD5F7C1C9ECBEECDAA9F91B3B3E3A0202" +
"0400").HexToByteArray();
internal static byte[] RsaOaep2048_Sha256ParametersCert = (
"308203573082023FA003020102021000E632D0CD2B7885DEC18B874E9DEB2930" +
"0D06092A864886F70D01010B050030173115301306035504030C0C436F6E746F" +
"736F20526F6F74301E170D3139303432313232313734325A170D323930343232" +
"3232313734325A30173115301306035504030C0C436F6E746F736F204C656166" +
"30820151303C06092A864886F70D010107302FA00F300D060960864801650304" +
"02010500A11C301A06092A864886F70D010108300D0609608648016503040201" +
"05000382010F003082010A02820101009773FC00EF371FCEBE2145563A29A08C" +
"608EC3F24FB1976594876E3D168BD744BC665C061B75F0B0ADFBFE90967ECFAE" +
"522A30A38457656F0D620C8CF4632D9B879F80240A0F6304CE276F5641C3B756" +
"995202CFA14E6BC777235D942B517CA963A5AFED7B595569877E3EA645A6D887" +
"10975FD8BB213D58F50DBEE58A3716D7EFD2171734CD17E099513F3225366C6E" +
"B91B0946FDC8F6745A15FF15EB71E7C2C6537C9E3CB95F38E9A571496247C9BF" +
"118B2A361AD47B6122D4E098095105F8BE7C031C7CAD1044F44849B794379235" +
"27AED01CC9E8605BA7431956E7ECF4B4A829A36C77FB8353AA8966EAE05219DC" +
"0BA45F0E41F5B6B91D954148455055450203010001A370306E300C0603551D13" +
"0101FF04023000300E0603551D0F0101FF040403020430304E0603551D230447" +
"3045801419AA399804F91ED61132ECCBAAF578543F46972DA11BA41930173115" +
"301306035504030C0C436F6E746F736F20526F6F74821000BEBBAC206CB54DF8" +
"5376C2D4E0F19F300D06092A864886F70D01010B050003820101004629B34FF2" +
"9208886EBFFDB0C54F935394F33FDC2F4B82C7EA1A18E0630905906D8DFF23F8" +
"0D79848584453DA67D65FB8E4C8C5D53EBF864B1414B43AEB89276C6BF0C0870" +
"6545E90C14F033ED8F47B6020E6FB87AFE0C41B3A5DCB5ECA881D519759D7EC1" +
"093A21C38CAE7202EBFA99FE94121EF89944EA68BF92C8EF605D6C9EFCA0D849" +
"D4E775AE0EABADAFB83019A323A0CE3544B9F877546C5B0043730E8F1342F332" +
"5AF4683C73BADDFEF3518B0A4E015A10BC6178C10E3AF6A11430A9F102E59B5C" +
"C44593D76E1A80D29932CF3A4F170F4516AD3666108BE1CE17FD74E266DE6B7E" +
"2F7DB1215D41CE515B615167083E8EF4A3A54607EC7D14A0839A58").HexToByteArray();
internal static byte[] RsaOaep2048_Sha256ParametersPfx = (
"308209EE020103308209A806092A864886F70D010701A0820999048209953082" +
"09913082056606092A864886F70D010701A0820557048205533082054F308205" +
"4B060B2A864886F70D010C0A0102A08204FA308204F63028060A2A864886F70D" +
"010C0103301A0414E5DDB04EF6C37EC860C8F2CD89330E233C6732A402020400" +
"048204C8500596DD0681F7DAD596776609BB7B87D9D4163DB7FDDD4814771FC9" +
"F022BF51CAEDF359C2FE122ACE3409EEAFD0231AB4F935FFCE3ED94FAB187A72" +
"332AB58C59515412F10184AB793AD31A483BEB0D4D51757E9C069BFDF3803801" +
"95DCC13ECA7DC5F8F89E25DF0AE364A88B6621707352AF566C8E3342ACD4AB0D" +
"DF49651B755EF8837AE1690EF1FEB85AB3550EB618CE9FE74213F85806CF8A1A" +
"3575F994F4F6CBFAA81DBAFE07ADEBDBDD526054749219B1745C246E66CCBEA0" +
"2B8B00A68AF82BB2EBA9F57C58B0BD10D0CC646735928AE4AD5229192416658D" +
"BEA6B46E7C161E1ADC228478BE8DAB604988A41408D95D352B7270B837102784" +
"2C9FC6763770702AB4FA0F408CE67AA65650C8E399F311E32D7EA162304460AF" +
"5719B36D2064A6A00B41B264B26939158C261FED9E176E9BF7C29E66C54B9614" +
"0957315A65F04EE868B0A18018A763073C320E322C1AA9E767AA788B7B045626" +
"D1C51DE5BA8C74A82D4FB7892AA6E628BA874A79BBF17E6764BE4D600DE83673" +
"86A8D182E44E67EB74806606429420AD3A102821323A58718FA5CF45711AAE82" +
"072DEDE5122CA829D9B29DE4B6AECE54D5C1C3E6732A943926A658E8BBAEF062" +
"8128DDB63000F7958894F38167F80F1F7CB204C4EB7A7F34329E4D0D9DC5F75B" +
"7619AA40A7D7FFAEDA481BB0720E9705F1FEAA93B2A30DF3A1E5BA5BED5F15C6" +
"CD2B4E58EADF9C533F03FCEC1ACB4FEF64A11A190AAD270B33CB6E088AD6EF61" +
"C16757FE5B5907D7C7AD7B0306521703B2363D3CB8EB4C2D53FB6941DA9A05DE" +
"41854F18F8F7DADE6D615DEF8F8ADB3C94722B68EC811F4C26A59210005C89A1" +
"5D3B8D440BD859919E3D83427A7A758CD3F01E5050275F3131A25624AF2ABA7B" +
"98F38A0D5867EEC386F69A6B4A02FCD906D5DF1A70FADC0DEFF1421530395894" +
"84C99689821BF286FC9074C5C42AA31790947B0B5D86BC775F764EFF6E42A514" +
"603624FD8AF0DE2C1A76D9AE94807A69449B569979B1AA3FB5C9C33E12C9A6CC" +
"4B4E02C4FBCC8DEF3D3A176ADA3BC21615E01596AD45E2479929570BE4752C38" +
"CCEEBB5C1DAEDBB85E9529E5ED6A5D427B4ADF572C8F5BA75E538BEB3A8CE059" +
"3FA05AB3779912CA314CD2DC4B801D5FFAE7F0FDDACD71EE4483FDC32F0CBB62" +
"AE18D4DE521AD50EFD4E8D34586CE208D6CD74800A3FB0E869746D9D9F64129E" +
"9308C0AD94B4A788C9B0F9E689F9B7B132368C701D79308D716347BAB6F66219" +
"94B00B06A260B3F71B3477BFE363C4D2CFB26ECBD54B0D83F7F399A1A60ECE5F" +
"7DEA546ACD40F94F01DFBA2814F760BD9FFC36F7C04104D1897B6928745DFB53" +
"5F9B297EE6E0F1301402CE8413D2B4AF18024D356EFEA7444FA4ABA371F49706" +
"FE050E2697F8A57D917A18BA1049BC6CB4CD5BB0E60313C06259A792B18E086C" +
"47B7052D47BA524391F4B03BC33B175176E9E223C0ED55CCBAFB4C228BCFA862" +
"BD1A28D38AEF249B7CD6A5D54B27A31CBD48081D26DD4F8ACEB54519969E98F0" +
"E550B14F9BD123D0BC687B12FB5D4703AE971C6528435DEE49C8C919DF9FF27A" +
"B1C28944694890C3CAF085ED60CEB25B2F77B71EFDB0E4462C42A2D4ECB9BB80" +
"ED7E63724548295851BEC017A2FF662EED7DE5496C3A03B2E66722AB61437EFB" +
"D1FD01A1D38FCF8D7088E44FCDDB46B04C3ED8B1A5957B414952EDA21F134BAF" +
"B63DAFB9EA61D1E6C1B7FF07313E301706092A864886F70D010914310A1E0800" +
"74006500730074302306092A864886F70D01091531160414A818F5D36906905E" +
"2F6FA5BFF7829502427B9A573082042306092A864886F70D010706A082041430" +
"8204100201003082040906092A864886F70D0107013028060A2A864886F70D01" +
"0C0106301A04145D4F6CE75AFE72F271F5ABF7D4222AEC5F689C1E0202040080" +
"8203D086644BB639A1348939D6F67CA12354E69D27B92D36C6DBF62D6565B58A" +
"920992B8E5EB63078E73F4CA3FC66EAF9772FB35A7A6C514A9EEA4C84CDED3D5" +
"0D7CE9B5105D5D43273995E83BFDC2E30769007712FBF949B4B9DB584508AC25" +
"78ED447FB17B6D289601F1ACDDB5D5C9D511366F48E0B1A1D1F80F81957B0C71" +
"1BCD3DE8D2B7C166DEEE93994B9845D6719376F0DE335F8130B8AA0478837809" +
"D71BFC6430BCC4939C5E6329694E6E80097888007C80DD6733633470D5234728" +
"4C17257AD610BE367A7383C1AD98F4499C0ED644EC840FF119EEA82F9B910E2B" +
"53BC6C430D629696DA5AC7C24099E334A4DF8FB28B5A21CA05A72D3590307B5D" +
"D0B68C6F76BAD7EC14D4732F0BEAE723D111A2DC31AFA06E55E6837FB8706289" +
"45EBCF4B4AA6A6998E973BBA5EB853B3BEC95C81736149A8173ADCF319DB9CFB" +
"C10BFF450B9C026ABB4A5887DFDD6F5B8F19D6D59ED2CBD3113F867414E21647" +
"1E963878D7292B2749FABCC7982AB187A79BF74BD591D8523B4E2587C4714E94" +
"FFE21193A28DD72C4C947889674A7EE0305433FDE0572D8B69881491EF03D963" +
"9A0A9D8E65F234DF51428C662DAFDB68C7665DD917EBD1338AF36CA418B67632" +
"B4C057D96E400E571C31F7FF75291013E8D092648109E1366F378F86C4311678" +
"67932071DBEB100DF01F95E7B9262F06DC6393ADA419AB583AF78F94E7FB72D7" +
"C4AB90F52D94E309152F07C349625AD67D7B922990E82CF79436AFB5DA314DE5" +
"AF55FEF6E70442334E8574A7FAFBC5DA56A72E87ED56ABC84D6389BCBF0C54F0" +
"8AFC841522F41A90CA11B5597E0F822B20177FCD15B74AAF975601DCCD628C0F" +
"B33F5BA273D33CD8647CC681EA44F7DC452F2DC6750CA88E0D8FF1C2A9132D53" +
"62F1A57F87E778969B88ADA6D9F8AF1C404D4AB9730E44BFAAF7080481C8B066" +
"D4FC8B0C47AF90926D7A91C95C6FC5CAD275DBD65BD0835BE93DC30AD0ACC2A1" +
"942F29A8D28C20D0F1220C9AD981896BA50E99718CAC9D48963DEF98BEFDDDE0" +
"32FFD89374716F1946E922AF828533BCDBA7865DD50F190F526763D008B8F44F" +
"EEC22E7C90F86E24EEABAC404FE49AF49787A31FB7FC2AEAA04C114F64A4DC68" +
"ACEE48F7AF3939CED423A9664D25B906EDA43AC2EAE0E571B857199C9AAF4858" +
"F4DFE1F83BBB15D2889FA7B1EE3CE768445007F5949C2F353C3A405EE7842E4B" +
"6FC77F1A26042DD5D182C44A21AC6ACF1A43FC9498664A7A722E90AC297078E0" +
"633BFB83D85DAB26CD9462364FF161BF9CF194103F6D91A6D28B7284293FB55B" +
"3909151C85CFAEB5F5633E82D5364725EFA4CCFB7F62454399BEEDF1FDCD64A7" +
"788822C1BE1A53B5B4FBF60039AF86B12E1B1E303D3021300906052B0E03021A" +
"050004144E291DFD7C40F48494D521D4939815FF16938E220414732425C273E6" +
"923C8F31AED55ED4BA1110E70AEA02020400").HexToByteArray();
internal static byte[] RsaOaep2048_NoParametersCert = (
"308203263082020EA003020102021000D90B171E0AE0BB7FC73832CF72AB8530" +
"0D06092A864886F70D01010B050030173115301306035504030C0C436F6E746F" +
"736F20526F6F74301E170D3139303432313232313734315A170D323930343232" +
"3232313734315A30173115301306035504030C0C436F6E746F736F204C656166" +
"30820120300B06092A864886F70D0101070382010F003082010A0282010100D2" +
"12A4429CE6557322B0558BACB0DE8CABEC6FCA8E57C58125AFE1B91F9A79FA0E" +
"59CD6D580F139A80378DF000AC6837E303B0C873A31ECE01C604CED463160DDC" +
"8842447FB36C4013D3DF4039BF0C24DF522914AB6FE836E465114A80EF5C46D4" +
"6ED19222A7C92294BE39966D814A24A996E9618A055A24C7A5E4271BC6BBB7AF" +
"E29667CABDD4216CB286E8D95DEECA2AAC0D6E5D15B7BC6CA40BE80C0FED9830" +
"C8D933F871244BB69A61F8CC10BA1D6BB3402B8542D79BFCE2E9BD7D91D4E118" +
"F7E0181148EE8F6A665492B00E28F2A4F2481343A1BD063B86E11C67C74B0D49" +
"8DB0AD1B84A013D6E89184BEFDF87CA9DA2DE2C62FCCF056B48953C696AB4502" +
"03010001A370306E300C0603551D130101FF04023000300E0603551D0F0101FF" +
"040403020430304E0603551D2304473045801419AA399804F91ED61132ECCBAA" +
"F578543F46972DA11BA41930173115301306035504030C0C436F6E746F736F20" +
"526F6F74821000BEBBAC206CB54DF85376C2D4E0F19F300D06092A864886F70D" +
"01010B050003820101007522F8814F534DB7EA5D2A1DC9D0344D4C4877F291FB" +
"7C4DB42D172C431A9C81267F114D8E4197AD90854522E4D55D4B211C7367A5FE" +
"45478971642AC940A6D66FB6384AC437628B8679C2495FA35B3998B852DDF59B" +
"3944FB15577B3FBD9F104A823A92E09AD7CFACD886B363EADF2478056D5CCB97" +
"B233762DE31525E4FC6733E2CBDEBFC282E3F6B467BBD5932C89B92D0EA7A8DD" +
"5C44AFCAD2980C6A24B8DF83E743CDC2DA3BB9188D01C8C8F596BBA5ACFE2E7A" +
"21FE0F3D753D409AE08E34208C1AD07F70B73B97ED62DA6B8959232585BA5AAD" +
"6AFFDD7D7298CD80D42B50AA7DC6A317BB7B2FE9EE95AB1FC8E3C1B2392D5750" +
"45DC4D41362F8C83ABED").HexToByteArray();
internal static byte[] RsaOaep2048_NoParametersPfx = (
"308209BE0201033082097806092A864886F70D010701A0820969048209653082" +
"09613082056606092A864886F70D010701A0820557048205533082054F308205" +
"4B060B2A864886F70D010C0A0102A08204FA308204F63028060A2A864886F70D" +
"010C0103301A0414993C8510854D2E0B2E6A93146230548B5EA6290602020400" +
"048204C8BF5DCE211704D21DAA9C8F855657C889DB6F5B29ADA8F9DF721A159A" +
"A3CB9899904C80B382EEC08767A6C7AA2B3FFFA13F41BF5FC8205DC70EE9F4B0" +
"49D270D48EBD290157267DA0393F2746032B9D6F6C7594FD3495DFA6FE4D0D84" +
"DF9E8091620DA4219BA65031CFCFF3F0024DEF64E47681806FEC30B625DBA88B" +
"823B7120835E8DAAAA8A8E110B9DBA537426C50099B7824AF3451EFC406AAB22" +
"C5B3698CE2A73C222392960699BA3F3AEE9F089C299DF80D720489424596D1B1" +
"8538AC963F9C0E545ED6DDAD79DA3D401CAD32D5F88A1025E8491D76AB3ADD3B" +
"36500B8DC4D3FE6F5E5A1819AA767C5BE7344C985821D88CAFE9914F6388C0E1" +
"E715F4A1B7BA67A4687697FF8632756101C70CFE6ECD4711F1DF8694D1A7DAB1" +
"6998C6D96BEF5DEAD2FB97E36B39ECF794DCD057544878FA55135F71ADAFE8BB" +
"A0249C3208E6B56E310767984F9E405389F54732CD6FCF9B2650E1ADA2B2AB1E" +
"298C549D09050A2C004F1D4F491070FC9B115B06EE2AE30939A836E38CF1FA3C" +
"6B39373E61AA64F030E772F78A49C6CE6762A2B3F1D771B1FE17669906E26042" +
"54158DB5D4B5E8965D267B99008FCB36A9B2A3EA83E534DC255BF1B0C79EDBA9" +
"86623FDC395A59A2D95EB0A7E1D67899ED84F7F832B2775E4DA9ECBA63253E65" +
"7E509442E4A794E93E2A24D1672939D69EDCA784684781A5B40A98F5E6E61F0B" +
"72918E04847070C5C1E46E9156A3E25849B2F701E8B11FAE6A9C949DFD70F106" +
"9751D120A93B6BBF8C14A7419E470479C32FCC3824CB3F56A1F93F0EEAC3A402" +
"26CDBA64FACCCBA3E09888B920ABCB9E18D8F1E673C3D3B6475C1E406221571E" +
"C92FFBCCB2FE9F110410196FEBC905C6926D25E717ACA85EC10B456F02B11561" +
"467B152A74BD263F26C636FEF093D03AA8FD880E68692B3808C6BA7152A16A50" +
"E82000A04760C86756FF0EA382EDA8571AD0181F98EC110B278493512F052B2B" +
"95E0CF3798A9A54C688661746DAE65603BD43F990CEB0D0CB53DA780494E59F1" +
"608E5B0C150C044CDE74870225A2F932D69D27ECDDC5EC3818D043ED363F27E8" +
"F55D9B9396E439B8A3154B4E7F2BE160615220FA327253EFDEC5F19B6D51E0B9" +
"1E513D17A6277066C866E59123019025994ECA8BAE4CDDD4021E2497A8C62DBF" +
"A22711832CCFE68824D0D410933DCEB1A15AE4ABEA523D18E8417A161A508796" +
"CDB9B746A97EF90A1E0597C82B148DDE0572A1AFE212670509FB4CC3FB6ED3D4" +
"A85372B85EAD17EBE704D97B976D4D157F58DD5D6E3EA8C307CEC87B936E4950" +
"BB136131001E937184B5973D4038DCE98C15E68C0951286AA8D676913A67F3EB" +
"1291F96326EC0B8A0B4DB8DBD9E11390B0AF1772B247A3ABE572367B8A4B6FC0" +
"36AF30130DA7D148540BD294438509CD879AAC3F62357C52914F58AD2B1BCF3F" +
"0DF373314423F64B3687D692BDFE595F478BC6D879F4DBA572063B8648EB59D6" +
"DF4B1BB6BD01B1B077195CAA63DD2C927850A0AF54A8711A929EA899716B8928" +
"CB9E559AA4C89B06D3C8A9FB2C64F9A61763A532FBA9CD03F6A750560893B3D0" +
"F32605C0C9D260FA5DF10EA9498A19FD1BA8C35FF988959CB76CB178DB3AE544" +
"2AA3DFCAAF79595A85D8EA3BDC860A06A1176D95EF72E66898E06D3357CC434C" +
"A2F46E9B57C5FDEBDD23B23186D9DF280FC05B326013FD96F44BD56E54B90A59" +
"AA21865A576FE43C14DCD8DB313E301706092A864886F70D010914310A1E0800" +
"74006500730074302306092A864886F70D01091531160414C8FCFD94B774494D" +
"0B5A9187550D9562468B86C8308203F306092A864886F70D010706A08203E430" +
"8203E0020100308203D906092A864886F70D0107013028060A2A864886F70D01" +
"0C0106301A041495480C3C3F897F0F2763D2A8A89AF4F546485E800202040080" +
"8203A0C9D6ACAC66EEE46EA9B5A3188623408790361FFEE1BBD67D1CEC14A22E" +
"9F90D6F65CEADE7B1A25313ADAB523FFFC47FB41A953C8E4414E834FB51CEB1C" +
"853F6FEC9FDCA5CED07BB8DD695D728DE4CC2B2EE40F243D4CDB6A20E7EDDC2B" +
"32B1A570A9EC50360D5864774F0C04501FCEB9BFBAA3B76CD3855DAE042D3FDC" +
"884F6673F77AFBFC9FD1344854E3E26996E6493C8C39C86077FD998B066E56B7" +
"3F3CE9175CA6369780D92EA4F8DE7BE7918670B6BA044DCF5C39BAF85FC305B8" +
"16541B335A6D528945DE6047ED8A30AC1B1292CD3E2050F5665E9DBA4816E053" +
"6E45EB3C2D271C1D4FE4C44502E298B9958351EC282DD218701A7B06E85FC7FC" +
"58EA1C69FC89326D1936A5E485DEF9DB036C76CA1BFB1E9C2EF926E0076BADC6" +
"6164905F62CAD6AD8042C269F91AFF5508E3DB16CFDD966D8A88A03F446AEBBC" +
"A56A17E525770A51D2595E7605DB4864FEE301B0376C91B416327C635FBEE114" +
"3F0D686FBF77758831F4FC1984E9274D2D4C463A4EDE3864DB1825DAF10C3FAB" +
"BDAAC3A0127226356DF027C91D01210F9D1E2449A25C73A882BDAC43936EC224" +
"4CA0CF84097BE8381014564B64F012739F97B91AAD04AFEA1C7BFCCAD998A693" +
"8204DA560F510B1EA3E4B99908F25058DCFB0032C51E6DDD7D6BB4A459833B5A" +
"5295F727B7A306A9DD43A537242F527BCEDC633BE50A5699F4AC39E1DBE54867" +
"654BC85E5FD43594FE00F1F86651E43C4D9BE7F86ADFD862BAD7801D68D124DB" +
"4A90CB71DF4AF601A05E65D5F4D48B21F1E5151AAAFE899434E5DE503D217867" +
"73F7DC27AC46B35E02AF1102BD39285E8DBA07E425947D2100DAA3A6CB263F18" +
"32AFE5BC659A28C67DF8572BE6360825BBC837BEDA8B87EE10A38C3682FC1C2C" +
"2ABFDD0AA11C4DA433B9AB1927F9B1955814EE044BCC095BDE4BAB05C245E211" +
"7FCD5FB503CBC918B48E6D7F2E4D12693B01D8969956E92AC49E54A63879F113" +
"52D8EFA103CE559D071F430067B05FBF68B5DC54FD25BE68CA054170E777B575" +
"E4355674DB504F9480AA7ADDAEB2295C964689561ED6A909F5C279E6F1EF1CAE" +
"94202A9073B1CDC5746E7EC47D60B927C661E39E305051CC77CE54EDF4F199DF" +
"7C67596A9264F6AA7D6AFE955116BC100117E41F361A2C9F1DA8073B8D184037" +
"EC9E23DF5F346E16D2B7F713FCE053CD815E783D13EA8CDEF7ACD014BB4B1D3E" +
"EC46C75DD09C005ADA5F8DBEAC2B47D5B77F31A967B419FA57A61C661CD10903" +
"D8CEBD9820ABEA3089F4387471FBEC87596FD036CC448F37B775538AE72C5AF1" +
"9502F3303D3021300906052B0E03021A0500041484BFCFD2BED79AAAAD26AFCC" +
"CC8F76FB6FD9D40804143A666EE41B085688C62A85EC7964C0FACF0512DF0202" +
"0400").HexToByteArray();
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Kudan.AR
{
[DisallowMultipleComponent]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Kudan AR/Kudan Tracker")]
public class KudanTracker : MonoBehaviour
{
static KudanTracker kudanTracker;
/// <summary>
/// The default width of the camera.
/// </summary>
private const int DefaultCameraWidth = 640;
/// <summary>
/// The default height of the camera.
/// </summary>
private const int DefaultCameraHeight = 480;
[Tooltip("The Editor API Key Issued by Kudan")]
/// <summary>
/// The editor API key.
/// </summary>
public string _EditorAPIKey = string.Empty;
/// <summary>
/// Reference to the tracker plugin.
/// </summary>
protected TrackerBase _trackerPlugin;
/// <summary>
/// Array of detected trackables.
/// </summary>
protected Trackable[] _lastDetectedTrackables;
[Tooltip("The API License key issued by Kudan")]
/// <summary>
/// The API License key.
/// </summary>
public string _APIKey = string.Empty;
/// <summary>
/// The default tracking method used by the tracker on startup.
/// </summary>
public TrackingMethodBase _defaultTrackingMethod;
/// <summary>
/// Array of all tracking methods that can be used by the tracker.
/// </summary>
public TrackingMethodBase[] _trackingMethods;
/// <summary>
/// Sets the Marker Recovery Mode.
/// Enabling this will help with recovering a lost marker, however this comes at the cost of slightly more CPU usage.
/// </summary>
public bool _markerRecoveryMode;
[Tooltip("Don't destroy between level loads")]
/// <summary>
/// Whether or not to make this tracker persist between scenes.
/// </summary>
public bool _makePersistent = true;
/// <summary>
/// Whether or not to start initialise this tracker when it is loaded.
/// </summary>
public bool _startOnEnable = true;
/// <summary>
/// Whether or not to apply the projection matrix.
/// </summary>
public bool _applyProjection = true;
[Tooltip("The camera to apply the projection matrix to. If left blank this will use the main camera.")]
/// <summary>
/// The camera to apply the projection matrix to.
/// </summary>
public Camera _renderingCamera;
[Tooltip("The renderer to draw the tracking texture to.")]
/// <summary>
/// The renderer to draw the tracking texture to.
/// </summary>
public Renderer _background;
/// <summary>
/// Whether or not to display the debug GUI.
/// </summary>
public bool _displayDebugGUI = true;
[Range(1, 4)]
/// <summary>
/// The size of the debug GUI.
/// </summary>
public int _debugGUIScale = 1;
[HideInInspector]
/// <summary>
/// The debug shader.
/// </summary>
public Shader _debugFlatShader;
/// <summary>
/// ArbiTracker floor height
/// </summary>
protected float _floorHeight = 200.0f;
/// <summary>
/// Gets the interface exposing the Kudan API for those that need scripting control.
/// </summary>
public TrackerBase Interface
{
get { return _trackerPlugin; }
}
/// <summary>
/// The current tracking method.
/// </summary>
private TrackingMethodBase _currentTrackingMethod;
/// <summary>
/// Gets the current tracking method.
/// </summary>
public TrackingMethodBase CurrentTrackingMethod
{
get { return _currentTrackingMethod; }
}
#if UNITY_EDITOR
/// <summary>
/// The index of the toolbar.
/// </summary>
private int _toolbarIndex;
/// <summary>
/// If you have more than one webcam you can change your prefered webcam ID here.
/// ID is of the webcam used in Play Mode.
/// </summary>
[Range(0, 10)]
[Tooltip ("If you have more than one webcam you can change your prefered webcam ID here.")]
public int _playModeWebcamID;
/// <summary>
/// Checks the validity of the license key.
/// </summary>
private void checkLicenseKeyValidity()
{
bool result = NativeInterface.CheckAPIKeyIsValid(_APIKey.Trim(), PlayerSettings.bundleIdentifier);
if (result)
{
Debug.Log ("[KudanAR] Your Bundle License Key Is Valid");
}
else
{
Debug.LogError ("[KudanAR] License Key is INVALID for Bundle: "+ PlayerSettings.bundleIdentifier);
}
}
/// <summary>
/// Checks the editor license key.
/// </summary>
private void checkEditorLicenseKey()
{
bool result = NativeInterface.SetUnityEditorApiKey (_EditorAPIKey.Trim());
if (result)
{
Debug.Log ("[KudanAR] Editor Play Mode Key is Valid");
}
else
{
Debug.LogError ("[KudanAR] Editor Play Mode Key is NOT Valid");
}
}
#endif
/// <summary>
/// Gets the appropriate tracker Plugin for the platform being used
/// </summary>
void GetPlugin ()
{
#if UNITY_EDITOR_OSX
_trackerPlugin = new TrackerOSX();
checkEditorLicenseKey();
checkLicenseKeyValidity();
#elif UNITY_EDITOR_WIN
_trackerPlugin = new TrackerWindows();
checkEditorLicenseKey();
checkLicenseKeyValidity();
#elif UNITY_IOS
_trackerPlugin = new TrackeriOS(_background);
#elif UNITY_ANDROID
_trackerPlugin = new TrackerAndroid(_background);
#endif
}
/// <summary>
/// Start this instance.
/// </summary>
void Start()
{
// Check there is only a single instance of this component
if (FindObjectsOfType<KudanTracker>().Length > 1)
{
Debug.LogError("[KudanAR] There should only be one instance of KudanTracker active at a time");
return;
}
CreateDebugLineMaterial();
// Create the platform specific plugin interface
GetPlugin();
if (_trackerPlugin == null)
{
Debug.LogError("[KudanAR] Failed to initialise");
this.enabled = false;
return;
}
// Initialise plugin
if (!_trackerPlugin.InitPlugin())
{
Debug.LogError("[KudanAR] Error initialising plugin");
this.enabled = false;
}
else
{
// Set the API key
if (!string.IsNullOrEmpty(_APIKey))
{
_trackerPlugin.SetApiKey (_APIKey, Application.bundleIdentifier);
}
// Print plugin version
string version = _trackerPlugin.GetPluginVersion();
float nativeVersion = _trackerPlugin.GetNativePluginVersion();
Debug.Log(string.Format("[KudanAR] Initialising v{0} (native v{1})", version, nativeVersion));
// Don't destroy this component between level loads
if (_makePersistent)
{
GameObject.DontDestroyOnLoad(this.gameObject);
}
foreach (TrackingMethodBase method in _trackingMethods)
{
method.Init();
}
_trackerPlugin.SetMarkerRecoveryStatus(_markerRecoveryMode);
ChangeTrackingMethod(_defaultTrackingMethod);
// Start the camera
#if UNITY_EDITOR
if (_trackerPlugin.StartInputFromCamera(_playModeWebcamID, DefaultCameraWidth, DefaultCameraHeight))
#else
if (_trackerPlugin.StartInputFromCamera(0, DefaultCameraWidth, DefaultCameraHeight))
#endif
{
// Start tracking
if (_startOnEnable)
{
_trackerPlugin.StartTracking();
}
}
else
{
Debug.LogError("[KudanAR] Failed to start camera, is it already in use?");
}
}
}
void Awake()
{
// If there is no KudanTracker currently in the scene when it loads, make sure that this persists between scenes, then set the static reference of KudanTracker to this object.
if (kudanTracker == null)
{
if (_makePersistent)
{
DontDestroyOnLoad(gameObject);
kudanTracker = this;
}
}
// If KudanTracker already exists in the scene, but this is not it, destroy this gameobject, because there should only be one KudanTracker in a scene at any one time.
else if (kudanTracker != this)
{
Destroy(gameObject);
}
}
/// <summary>
/// Raises the enable event.
/// </summary>
void OnEnable()
{
if (_startOnEnable)
{
StartTracking();
}
}
/// <summary>
/// Raises the disable event.
/// </summary>
void OnDisable()
{
StopTracking();
}
/// <summary>
/// Raises the application focus event.
/// </summary>
/// <param name="focusStatus">If set to <c>true</c> focus status.</param>
void OnApplicationFocus(bool focusStatus)
{
if (_trackerPlugin != null)
{
_trackerPlugin.OnApplicationFocus(focusStatus);
}
}
/// <summary>
/// Raises the application pause event.
/// </summary>
/// <param name="pauseStatus">If set to <c>true</c> pause status.</param>
void OnApplicationPause(bool pauseStatus)
{
if (_trackerPlugin != null)
{
_trackerPlugin.OnApplicationPause(pauseStatus);
}
}
/// <summary>
/// Starts the tracking.
/// </summary>
public void StartTracking()
{
if (_trackerPlugin != null)
{
_trackerPlugin.StartTracking();
}
}
/// <summary>
/// Stops the tracking.
/// </summary>
public void StopTracking()
{
if (_trackerPlugin != null)
{
_trackerPlugin.StopTracking();
}
// Restore projection matrix
Camera camera = _renderingCamera;
if (camera == null)
{
camera = Camera.main;
}
if (camera != null)
{
camera.ResetProjectionMatrix();
}
}
/// <summary>
/// Changes the tracking method.
/// </summary>
/// <param name="newTrackingMethod">New tracking method.</param>
public void ChangeTrackingMethod(TrackingMethodBase newTrackingMethod)
{
if (newTrackingMethod != null && _currentTrackingMethod != newTrackingMethod)
{
if (_currentTrackingMethod != null)
{
_currentTrackingMethod.StopTracking();
}
_currentTrackingMethod = newTrackingMethod;
_currentTrackingMethod.StartTracking();
}
}
/// <summary>
/// Starts Arbitrary Tracking.
/// </summary>
/// <param name="position">Position.</param>
/// <param name="orientation">Orientation.</param>
public void ArbiTrackStart(Vector3 position, Quaternion orientation)
{
_trackerPlugin.ArbiTrackStart(position, orientation);
}
/// <summary>
/// Checks if Arbitrary Tracking is running.
/// </summary>
/// <returns><c>true</c>, if Arbitrary Tracking is running, <c>false</c> otherwise.</returns>
public bool ArbiTrackIsTracking()
{
return _trackerPlugin.ArbiTrackIsTracking();
}
/// <summary>
/// Gets the current position and orientation of the floor, relative to the device.
/// </summary>
/// <param name="position">Position.</param>
/// <param name="orientation">Orientation.</param>
public void FloorPlaceGetPose(out Vector3 position, out Quaternion orientation)
{
_trackerPlugin.FloorPlaceGetPose(out position, out orientation);
}
/// <summary>
/// Gets the current position and orientation of the markerless driver being tracked.
/// </summary>
/// <param name="position">Position.</param>
/// <param name="orientation">Orientation.</param>
public void ArbiTrackGetPose(out Vector3 position, out Quaternion orientation)
{
_trackerPlugin.ArbiTrackGetPose(out position, out orientation);
}
/// <summary>
/// Raises the destroy event.
/// </summary>
void OnDestroy()
{
if (_trackerPlugin != null)
{
StopTracking();
_trackerPlugin.StopInput();
_trackerPlugin.DeinitPlugin();
_trackerPlugin = null;
}
if (_lineMaterial != null)
{
Material.Destroy(_lineMaterial);
_lineMaterial = null;
}
}
/// <summary>
/// Raises the pre render event.
/// </summary>
void OnPreRender()
{
_trackerPlugin.updateCam ();
}
/// <summary>
/// Update this instance.
/// </summary>
void Update()
{
if (_trackerPlugin != null)
{
Camera renderingCamera = _renderingCamera;
if (renderingCamera == null)
{
renderingCamera = Camera.main;
}
_trackerPlugin.SetupRenderingCamera(renderingCamera.nearClipPlane, renderingCamera.farClipPlane);
// Update tracking
_trackerPlugin.UpdateTracking();
// Apply projection matrix
if (_applyProjection)
{
renderingCamera.projectionMatrix = _trackerPlugin.GetProjectionMatrix();
}
else
{
renderingCamera.ResetProjectionMatrix();
}
// Take a copy of the detected trackables
ProcessNewTrackables();
_currentTrackingMethod.ProcessFrame();
// Apply texture to background renderer
Texture texture = _trackerPlugin.GetTrackingTexture();
if (_background != null && texture != null)
{
_background.material.mainTexture = texture;
}
}
}
#if UNITY_ANDROID
/// <summary>
/// Raises the post render event.
/// </summary>
void OnPostRender()
{
if (_trackerPlugin != null)
{
_trackerPlugin.PostRender();
}
if (_displayDebugGUI)
{
RenderAxes();
}
}
#else
/// <summary>
/// Raises the post render event.
/// </summary>
void OnPostRender()
{
if (_displayDebugGUI)
{
RenderAxes();
}
}
#endif
/// <summary>
/// Processes new trackables.
/// </summary>
private void ProcessNewTrackables()
{
_lastDetectedTrackables = _trackerPlugin.GetDetectedTrackablesAsArray();
}
/// <summary>
/// Determines whether this instance has active tracking data.
/// </summary>
/// <returns><c>true</c> if this instance has active tracking data; otherwise, <c>false</c>.</returns>
public bool HasActiveTrackingData()
{
return (_trackerPlugin != null && _trackerPlugin.IsTrackingRunning() && _lastDetectedTrackables != null && _lastDetectedTrackables.Length > 0);
}
public void SetArbiTrackFloorHeight(float floorHeight)
{
_trackerPlugin.SetArbiTrackFloorHeight (floorHeight);
}
/// <summary>
/// Raises the draw gizmos event.
/// </summary>
void OnDrawGizmos()
{
// Draw useful debug rendering in Editor
if (HasActiveTrackingData())
{
foreach (Trackable t in _lastDetectedTrackables)
{
// Draw circle
Gizmos.color = Color.cyan;
Gizmos.DrawSphere(t.position, 10f);
// Draw line from origin to point (useful if object is offscreen)
Gizmos.color = Color.cyan;
Gizmos.DrawLine(Vector3.zero, t.position);
// Draw axes
Matrix4x4 xform = Matrix4x4.TRS(t.position, t.orientation, Vector3.one * 250f);
Gizmos.matrix = xform;
Gizmos.color = Color.red;
Gizmos.DrawLine(Vector3.zero, Vector3.right);
Gizmos.color = Color.green;
Gizmos.DrawLine(Vector3.zero, Vector3.up);
Gizmos.color = Color.blue;
Gizmos.DrawLine(Vector3.zero, Vector3.forward);
}
}
}
/// <summary>
/// Starts line rendering.
/// </summary>
/// <returns><c>true</c>, if line rendering was started, <c>false</c> otherwise.</returns>
public bool StartLineRendering()
{
bool result = false;
if (_lineMaterial != null)
{
_lineMaterial.SetPass(0);
result = true;
}
return result;
}
/// <summary>
/// Renders axes for debugging.
/// </summary>
private void RenderAxes()
{
if (HasActiveTrackingData() && StartLineRendering())
{
foreach (Trackable t in _lastDetectedTrackables)
{
Matrix4x4 xform = Matrix4x4.TRS(t.position, t.orientation, Vector3.one * 250f);
GL.PushMatrix();
Matrix4x4 m = GL.GetGPUProjectionMatrix(_trackerPlugin.GetProjectionMatrix(), false);
m = _trackerPlugin.GetProjectionMatrix();
GL.LoadProjectionMatrix(m);
// Draw line from origin to point (useful if object is offscreen)
GL.Color(Color.cyan);
GL.Vertex(Vector3.zero);
GL.Vertex(t.position);
GL.Begin(GL.LINES);
GL.MultMatrix(xform);
GL.Color(Color.red);
GL.Vertex(Vector3.zero);
GL.Vertex(Vector3.right);
GL.Color(Color.green);
GL.Vertex(Vector3.zero);
GL.Vertex(Vector3.up);
GL.Color(Color.blue);
GL.Vertex(Vector3.zero);
GL.Vertex(Vector3.forward);
GL.End();
GL.PopMatrix();
}
}
}
/// <summary>
/// Raises the GUI event.
/// </summary>
void OnGUI()
{
// Display debug GUI with tracking information
if (_displayDebugGUI)
{
GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(_debugGUIScale, _debugGUIScale, 1f));
GUILayout.BeginVertical("box");
#if UNITY_EDITOR
GUILayout.Label("KUDAN AR", UnityEditor.EditorStyles.boldLabel);
#else
GUILayout.Label("KUDAN AR");
#endif
// Tracking status
if (_trackerPlugin != null && _trackerPlugin.IsTrackingRunning())
{
GUI.color = Color.green;
GUILayout.Label("Tracker is running");
}
else
{
GUI.color = Color.red;
GUILayout.Label("Tracker NOT running");
}
GUI.color = Color.white;
// Screen resolution
GUILayout.Label("Screen: " + Screen.width + "x" + Screen.height);
// Frame rates
if (_trackerPlugin != null)
{
GUILayout.Label("Camera rate: " + _trackerPlugin.CameraFrameRate.ToString("F2") + "hz");
GUILayout.Label("Tracker rate: " + _trackerPlugin.TrackerFrameRate.ToString("F2") + "hz");
GUILayout.Label("App rate: " + _trackerPlugin.AppFrameRate.ToString("F2") + "hz");
}
if (_trackerPlugin != null && _trackerPlugin.IsTrackingRunning())
{
// Texture image and resolution
if (_currentTrackingMethod != null)
{
GUILayout.Label("Method: " + _currentTrackingMethod.Name);
_currentTrackingMethod.DebugGUI(_debugGUIScale);
}
}
}
}
/// <summary>
/// The line material.
/// </summary>
private Material _lineMaterial;
/// <summary>
/// Creates the debug line material.
/// </summary>
private void CreateDebugLineMaterial()
{
if (!_lineMaterial && _debugFlatShader != null)
{
_lineMaterial = new Material(_debugFlatShader);
_lineMaterial.hideFlags = HideFlags.HideAndDontSave;
}
}
}
};
| |
using System;
using System.Linq.Expressions;
using NRules.Rete;
using Tuple = NRules.Rete.Tuple;
namespace NRules.Diagnostics
{
/// <summary>
/// Provider of rules session events.
/// </summary>
public interface IEventProvider
{
/// <summary>
/// Raised when a new rule activation is created.
/// A new activation is created when a new set of facts (tuple) matches a rule.
/// The activation is placed on the agenda and becomes a candidate for firing.
/// </summary>
event EventHandler<AgendaEventArgs> ActivationCreatedEvent;
/// <summary>
/// Raised when an existing activation is deleted.
/// An activation is deleted when a previously matching set of facts (tuple) no longer
/// matches the rule due to updated or retracted facts.
/// The activation is removed from the agenda and is no longer a candidate for firing.
/// </summary>
event EventHandler<AgendaEventArgs> ActivationDeletedEvent;
/// <summary>
/// Raised before a rule is about to fire.
/// </summary>
event EventHandler<AgendaEventArgs> RuleFiringEvent;
/// <summary>
/// Raised after a rule has fired and all its actions executed.
/// </summary>
event EventHandler<AgendaEventArgs> RuleFiredEvent;
/// <summary>
/// Raised before a new fact is inserted into working memory.
/// </summary>
event EventHandler<WorkingMemoryEventArgs> FactInsertingEvent;
/// <summary>
/// Raised after a new fact is inserted into working memory.
/// </summary>
event EventHandler<WorkingMemoryEventArgs> FactInsertedEvent;
/// <summary>
/// Raised before an existing fact is updated in the working memory.
/// </summary>
event EventHandler<WorkingMemoryEventArgs> FactUpdatingEvent;
/// <summary>
/// Raised after an existing fact is updated in the working memory.
/// </summary>
event EventHandler<WorkingMemoryEventArgs> FactUpdatedEvent;
/// <summary>
/// Raised before an existing fact is retracted from the working memory.
/// </summary>
event EventHandler<WorkingMemoryEventArgs> FactRetractingEvent;
/// <summary>
/// Raised after an existing fact is retracted from the working memory.
/// </summary>
event EventHandler<WorkingMemoryEventArgs> FactRetractedEvent;
/// <summary>
/// Raised when action execution threw an exception.
/// Gives observer of the event control over handling of the exception.
/// </summary>
event EventHandler<ActionErrorEventArgs> ActionFailedEvent;
/// <summary>
/// Raised when condition evaluation threw an exception.
/// </summary>
event EventHandler<ConditionErrorEventArgs> ConditionFailedEvent;
}
internal interface IEventAggregator : IEventProvider
{
void RaiseActivationCreated(ISession session, Activation activation);
void RaiseActivationDeleted(ISession session, Activation activation);
void RaiseRuleFiring(ISession session, Activation activation);
void RaiseRuleFired(ISession session, Activation activation);
void RaiseFactInserting(ISession session, Fact fact);
void RaiseFactInserted(ISession session, Fact fact);
void RaiseFactUpdating(ISession session, Fact fact);
void RaiseFactUpdated(ISession session, Fact fact);
void RaiseFactRetracting(ISession session, Fact fact);
void RaiseFactRetracted(ISession session, Fact fact);
void RaiseActionFailed(ISession session, Exception exception, Expression expression, Tuple tuple, out bool isHandled);
void RaiseConditionFailed(ISession session, Exception exception, Expression expression, Tuple tuple, Fact fact);
}
internal class EventAggregator : IEventAggregator
{
private readonly IEventAggregator _parent;
public event EventHandler<AgendaEventArgs> ActivationCreatedEvent;
public event EventHandler<AgendaEventArgs> ActivationDeletedEvent;
public event EventHandler<AgendaEventArgs> RuleFiringEvent;
public event EventHandler<AgendaEventArgs> RuleFiredEvent;
public event EventHandler<WorkingMemoryEventArgs> FactInsertingEvent;
public event EventHandler<WorkingMemoryEventArgs> FactInsertedEvent;
public event EventHandler<WorkingMemoryEventArgs> FactUpdatingEvent;
public event EventHandler<WorkingMemoryEventArgs> FactUpdatedEvent;
public event EventHandler<WorkingMemoryEventArgs> FactRetractingEvent;
public event EventHandler<WorkingMemoryEventArgs> FactRetractedEvent;
public event EventHandler<ActionErrorEventArgs> ActionFailedEvent;
public event EventHandler<ConditionErrorEventArgs> ConditionFailedEvent;
public EventAggregator()
{
}
public EventAggregator(IEventAggregator eventAggregator)
{
_parent = eventAggregator;
}
public void RaiseActivationCreated(ISession session, Activation activation)
{
var handler = ActivationCreatedEvent;
if (handler != null)
{
var @event = new AgendaEventArgs(activation.Rule, activation.Tuple);
handler(session, @event);
}
if (_parent != null)
{
_parent.RaiseActivationCreated(session, activation);
}
}
public void RaiseActivationDeleted(ISession session, Activation activation)
{
var handler = ActivationDeletedEvent;
if (handler != null)
{
var @event = new AgendaEventArgs(activation.Rule, activation.Tuple);
handler(session, @event);
}
if (_parent != null)
{
_parent.RaiseActivationDeleted(session, activation);
}
}
public void RaiseRuleFiring(ISession session, Activation activation)
{
var handler = RuleFiringEvent;
if (handler != null)
{
var @event = new AgendaEventArgs(activation.Rule, activation.Tuple);
handler(session, @event);
}
if (_parent != null)
{
_parent.RaiseRuleFiring(session, activation);
}
}
public void RaiseRuleFired(ISession session, Activation activation)
{
var handler = RuleFiredEvent;
if (handler != null)
{
var @event = new AgendaEventArgs(activation.Rule, activation.Tuple);
handler(session, @event);
}
if (_parent != null)
{
_parent.RaiseRuleFired(session, activation);
}
}
public void RaiseFactInserting(ISession session, Fact fact)
{
var handler = FactInsertingEvent;
if (handler != null)
{
var @event = new WorkingMemoryEventArgs(fact);
handler(session, @event);
}
if (_parent != null)
{
_parent.RaiseFactInserting(session, fact);
}
}
public void RaiseFactInserted(ISession session, Fact fact)
{
var handler = FactInsertedEvent;
if (handler != null)
{
var @event = new WorkingMemoryEventArgs(fact);
handler(session, @event);
}
if (_parent != null)
{
_parent.RaiseFactInserted(session, fact);
}
}
public void RaiseFactUpdating(ISession session, Fact fact)
{
var handler = FactUpdatingEvent;
if (handler != null)
{
var @event = new WorkingMemoryEventArgs(fact);
handler(session, @event);
}
if (_parent != null)
{
_parent.RaiseFactUpdating(session, fact);
}
}
public void RaiseFactUpdated(ISession session, Fact fact)
{
var handler = FactUpdatedEvent;
if (handler != null)
{
var @event = new WorkingMemoryEventArgs(fact);
handler(session, @event);
}
if (_parent != null)
{
_parent.RaiseFactUpdated(session, fact);
}
}
public void RaiseFactRetracting(ISession session, Fact fact)
{
var handler = FactRetractingEvent;
if (handler != null)
{
var @event = new WorkingMemoryEventArgs(fact);
handler(session, @event);
}
if (_parent != null)
{
_parent.RaiseFactRetracting(session, fact);
}
}
public void RaiseFactRetracted(ISession session, Fact fact)
{
var handler = FactRetractedEvent;
if (handler != null)
{
var @event = new WorkingMemoryEventArgs(fact);
handler(session, @event);
}
if (_parent != null)
{
_parent.RaiseFactRetracted(session, fact);
}
}
public void RaiseActionFailed(ISession session, Exception exception, Expression expression, Tuple tuple, out bool isHandled)
{
isHandled = false;
var handler = ActionFailedEvent;
if (handler != null)
{
var @event = new ActionErrorEventArgs(exception, expression, tuple);
handler(session, @event);
isHandled = @event.IsHandled;
}
if (_parent != null && !isHandled)
{
_parent.RaiseActionFailed(session, exception, expression, tuple, out isHandled);
}
}
public void RaiseConditionFailed(ISession session, Exception exception, Expression expression, Tuple tuple, Fact fact)
{
var hanlder = ConditionFailedEvent;
if (hanlder != null)
{
var @event = new ConditionErrorEventArgs(exception, expression, tuple, fact);
hanlder(session, @event);
}
if (_parent != null)
{
_parent.RaiseConditionFailed(session, exception, expression, tuple, fact);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Tests
{
public class File_Move_Tests : FileSystemWatcherTest
{
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void Windows_File_Move_To_Same_Directory()
{
FileMove_SameDirectory(WatcherChangeTypes.Renamed);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Unix_File_Move_To_Same_Directory()
{
FileMove_SameDirectory(WatcherChangeTypes.Created | WatcherChangeTypes.Deleted);
}
[Fact]
public void File_Move_From_Watched_To_Unwatched()
{
FileMove_FromWatchedToUnwatched(WatcherChangeTypes.Deleted);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void Windows_File_Move_To_Different_Watched_Directory()
{
FileMove_DifferentWatchedDirectory(WatcherChangeTypes.Changed);
}
[Fact]
[PlatformSpecific(PlatformID.OSX)]
public void OSX_File_Move_To_Different_Watched_Directory()
{
FileMove_DifferentWatchedDirectory(WatcherChangeTypes.Changed);
}
[Fact]
[PlatformSpecific(PlatformID.Linux)]
public void Linux_File_Move_To_Different_Watched_Directory()
{
FileMove_DifferentWatchedDirectory(0);
}
[Fact]
public void File_Move_From_Unwatched_To_Watched()
{
FileMove_FromUnwatchedToWatched(WatcherChangeTypes.Created);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
[PlatformSpecific(PlatformID.Windows)]
public void Windows_File_Move_In_Nested_Directory(bool includeSubdirectories)
{
FileMove_NestedDirectory(includeSubdirectories ? WatcherChangeTypes.Renamed : 0, includeSubdirectories);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Unix_File_Move_In_Nested_Directory(bool includeSubdirectories)
{
FileMove_NestedDirectory(includeSubdirectories ? WatcherChangeTypes.Created | WatcherChangeTypes.Deleted : 0, includeSubdirectories);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void Windows_File_Move_With_Set_NotifyFilter()
{
FileMove_WithNotifyFilter(WatcherChangeTypes.Renamed);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Unix_File_Move_With_Set_NotifyFilter()
{
FileMove_WithNotifyFilter(WatcherChangeTypes.Deleted);
}
#region Test Helpers
private void FileMove_SameDirectory(WatcherChangeTypes eventType)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
using (var testFile = new TempFile(Path.Combine(dir.Path, "file")))
using (var watcher = new FileSystemWatcher(dir.Path, "*"))
{
string sourcePath = testFile.Path;
string targetPath = testFile.Path + "_" + eventType.ToString();
// Move the testFile to a different name in the same directory
Action action = () => File.Move(sourcePath, targetPath);
Action cleanup = () => File.Move(targetPath, sourcePath);
if ((eventType & WatcherChangeTypes.Deleted) > 0)
ExpectEvent(watcher, eventType, action, cleanup, new string[] { sourcePath, targetPath });
else
ExpectEvent(watcher, eventType, action, cleanup, targetPath);
}
}
private void FileMove_DifferentWatchedDirectory(WatcherChangeTypes eventType)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
using (var dir_adjacent = new TempDirectory(Path.Combine(testDirectory.Path, "dir_adj")))
using (var testFile = new TempFile(Path.Combine(dir.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, "*"))
{
string sourcePath = testFile.Path;
string targetPath = Path.Combine(dir_adjacent.Path, Path.GetFileName(testFile.Path) + "_" + eventType.ToString());
// Move the testFile to a different directory under the Watcher
Action action = () => File.Move(sourcePath, targetPath);
Action cleanup = () => File.Move(targetPath, sourcePath);
ExpectEvent(watcher, eventType, action, cleanup, new string[] { dir.Path, dir_adjacent.Path });
}
}
private void FileMove_FromWatchedToUnwatched(WatcherChangeTypes eventType)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir_watched = new TempDirectory(Path.Combine(testDirectory.Path, "dir_watched")))
using (var dir_unwatched = new TempDirectory(Path.Combine(testDirectory.Path, "dir_unwatched")))
using (var testFile = new TempFile(Path.Combine(dir_watched.Path, "file")))
using (var watcher = new FileSystemWatcher(dir_watched.Path, "*"))
{
string sourcePath = testFile.Path; // watched
string targetPath = Path.Combine(dir_unwatched.Path, "file");
Action action = () => File.Move(sourcePath, targetPath);
Action cleanup = () => File.Move(targetPath, sourcePath);
ExpectEvent(watcher, eventType, action, cleanup, sourcePath);
}
}
private void FileMove_FromUnwatchedToWatched(WatcherChangeTypes eventType)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir_watched = new TempDirectory(Path.Combine(testDirectory.Path, "dir_watched")))
using (var dir_unwatched = new TempDirectory(Path.Combine(testDirectory.Path, "dir_unwatched")))
using (var testFile = new TempFile(Path.Combine(dir_unwatched.Path, "file")))
using (var watcher = new FileSystemWatcher(dir_watched.Path, "*"))
{
string sourcePath = testFile.Path; // unwatched
string targetPath = Path.Combine(dir_watched.Path, "file");
Action action = () => File.Move(sourcePath, targetPath);
Action cleanup = () => File.Move(targetPath, sourcePath);
ExpectEvent(watcher, eventType, action, cleanup, targetPath);
}
}
private void FileMove_NestedDirectory(WatcherChangeTypes eventType, bool includeSubdirectories)
{
using (var dir = new TempDirectory(GetTestFilePath()))
using (var firstDir = new TempDirectory(Path.Combine(dir.Path, "dir1")))
using (var nestedDir = new TempDirectory(Path.Combine(firstDir.Path, "nested")))
using (var nestedFile = new TempFile(Path.Combine(nestedDir.Path, "nestedFile" + eventType.ToString())))
using (var watcher = new FileSystemWatcher(dir.Path, "*"))
{
watcher.NotifyFilter = NotifyFilters.FileName;
watcher.IncludeSubdirectories = includeSubdirectories;
string sourcePath = nestedFile.Path;
string targetPath = nestedFile.Path + "_2";
// Move the testFile to a different name within the same nested directory
Action action = () => File.Move(sourcePath, targetPath);
Action cleanup = () => File.Move(targetPath, sourcePath);
if ((eventType & WatcherChangeTypes.Deleted) > 0)
ExpectEvent(watcher, eventType, action, cleanup, new string[] { targetPath, sourcePath });
else
ExpectEvent(watcher, eventType, action, cleanup, targetPath);
}
}
private void FileMove_WithNotifyFilter(WatcherChangeTypes eventType)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
watcher.NotifyFilter = NotifyFilters.FileName;
string sourcePath = file.Path;
string targetPath = Path.Combine(testDirectory.Path, "target");
// Move the testFile to a different name under the same directory with active notifyfilters
Action action = () => File.Move(sourcePath, targetPath);
Action cleanup = () => File.Move(targetPath, sourcePath);
if ((eventType & WatcherChangeTypes.Deleted) > 0)
ExpectEvent(watcher, eventType, action, cleanup, sourcePath);
else
ExpectEvent(watcher, eventType, action, cleanup, targetPath);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Zero.Api.Areas.HelpPage.ModelDescriptions;
using Zero.Api.Areas.HelpPage.Models;
namespace Zero.Api.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
/// <summary>Items from the SHCore.dll</summary>
public static partial class SHCore
{
private const string Lib_SHCore = "shcore.dll";
/// <summary>
/// <para>Indicates whether the device is a primary or immersive type of display.</para>
/// <para><c>Note</c> The functions that use these enumeration values are no longer supported as of Windows 8.1.</para>
/// </summary>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/ne-shellscalingapi-display_device_type typedef enum {
// DEVICE_PRIMARY, DEVICE_IMMERSIVE } DISPLAY_DEVICE_TYPE;
[PInvokeData("shellscalingapi.h", MSDNShortId = "NE:shellscalingapi.__unnamed_enum_0")]
public enum DISPLAY_DEVICE_TYPE
{
/// <summary>The device is a primary display device.</summary>
DEVICE_PRIMARY = 0,
/// <summary>The device is an immersive display device.</summary>
DEVICE_IMMERSIVE,
}
/// <summary>Identifies the dots per inch (dpi) setting for a monitor.</summary>
/// <remarks>All of these settings are affected by the PROCESS_DPI_AWARENESS of your application</remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/ne-shellscalingapi-monitor_dpi_type typedef enum
// MONITOR_DPI_TYPE { MDT_EFFECTIVE_DPI, MDT_ANGULAR_DPI, MDT_RAW_DPI, MDT_DEFAULT } ;
[PInvokeData("shellscalingapi.h", MSDNShortId = "NE:shellscalingapi.MONITOR_DPI_TYPE")]
public enum MONITOR_DPI_TYPE
{
/// <summary>
/// The effective DPI. This value should be used when determining the correct scale factor for scaling UI elements. This
/// incorporates the scale factor set by the user for this specific display.
/// </summary>
MDT_EFFECTIVE_DPI = 0,
/// <summary>
/// The angular DPI. This DPI ensures rendering at a compliant angular resolution on the screen. This does not include the scale
/// factor set by the user for this specific display.
/// </summary>
MDT_ANGULAR_DPI,
/// <summary>
/// The raw DPI. This value is the linear DPI of the screen as measured on the screen itself. Use this value when you want to
/// read the pixel density and not the recommended scaling setting. This does not include the scale factor set by the user for
/// this specific display and is not guaranteed to be a supported DPI value.
/// </summary>
MDT_RAW_DPI,
/// <summary>The default DPI setting for a monitor is MDT_EFFECTIVE_DPI.</summary>
MDT_DEFAULT = MDT_EFFECTIVE_DPI,
}
/// <summary>
/// <para>
/// Identifies dots per inch (dpi) awareness values. DPI awareness indicates how much scaling work an application performs for DPI
/// versus how much is done by the system.
/// </para>
/// <para>
/// Users have the ability to set the DPI scale factor on their displays independent of each other. Some legacy applications are not
/// able to adjust their scaling for multiple DPI settings. In order for users to use these applications without content appearing
/// too large or small on displays, Windows can apply DPI virtualization to an application, causing it to be automatically be scaled
/// by the system to match the DPI of the current display. The <c>PROCESS_DPI_AWARENESS</c> value indicates what level of scaling
/// your application handles on its own and how much is provided by Windows. Keep in mind that applications scaled by the system may
/// appear blurry and will read virtualized data about the monitor to maintain compatibility.
/// </para>
/// </summary>
/// <remarks>
/// <para><c>Important</c>
/// <para></para>
/// Previous versions of Windows required you to set the DPI awareness for the entire application. Now the DPI awareness is tied to
/// individual threads, processes, or windows. This means that the DPI awareness can change while the app is running and that
/// multiple windows can have their own independent DPI awareness values. See DPI_AWARENESS for more information about how DPI
/// awareness currently works. The recommendations below about setting the DPI awareness in the application manifest are still
/// supported, but the current recommendation is to use the <c>DPI_AWARENESS_CONTEXT</c>.
/// </para>
/// <para>
/// The DPI awareness for an application should be set through the application manifest so that it is determined before any actions
/// are taken which depend on the DPI of the system. Alternatively, you can set the DPI awareness using SetProcessDpiAwareness, but
/// if you do so, you need to make sure to set it before taking any actions dependent on the system DPI. Once you set the DPI
/// awareness for a process, it cannot be changed.
/// </para>
/// <para><c>Tip</c>
/// <para></para>
/// If your app is <c>PROCESS_DPI_UNAWARE</c>, there is no need to set any value in the application manifest.
/// <c>PROCESS_DPI_UNAWARE</c> is the default value for apps unless another value is specified.
/// </para>
/// <para>
/// <c>PROCESS_DPI_UNAWARE</c> and <c>PROCESS_SYSTEM_DPI_AWARE</c> apps do not need to respond to WM_DPICHANGED and are not expected
/// to handle changes in DPI. The system will automatically scale these types of apps up or down as necessary when the DPI changes.
/// <c>PROCESS_PER_MONITOR_DPI_AWARE</c> apps are responsible for recognizing and responding to changes in DPI, signaled by
/// <c>WM_DPICHANGED</c>. These will not be scaled by the system. If an app of this type does not resize the window and its content,
/// it will appear to grow or shrink by the relative DPI changes as the window is moved from one display to the another with a
/// different DPI setting.
/// </para>
/// <para><c>Tip</c>
/// <para></para>
/// In previous versions of Windows, there was no setting for <c>PROCESS_PER_MONITOR_DPI_AWARE</c>. Apps were either DPI unaware or
/// DPI aware. Legacy applications that were classified as DPI aware before Windows 8.1 are considered to have a
/// <c>PROCESS_DPI_AWARENESS</c> setting of <c>PROCESS_SYSTEM_DPI_AWARE</c> in current versions of Windows.
/// </para>
/// <para>
/// To understand the importance and impact of the different DPI awareness values, consider a user who has three displays: A, B, and
/// C. Display A is set to 100% scaling factor (96 DPI), display B is set to 200% scaling factor (192 DPI), and display C is set to
/// 300% scaling factor (288 DPI). The system DPI is set to 200%.
/// </para>
/// <para>
/// An application that is <c>PROCESS_DPI_UNAWARE</c> will always use a scaling factor of 100% (96 DPI). In this scenario, a
/// <c>PROCESS_DPI_UNAWARE</c> window is created with a size of 500 by 500. On display A, it will render natively with no scaling.
/// On displays B and C, it will be scaled up by the system automatically by a factor of 2 and 3 respectively. This is because a
/// <c>PROCESS_DPI_UNAWARE</c> always assumes a DPI of 96, and the system accounts for that. If the app queries for window size, it
/// will always get a value of 500 by 500 regardless of what display it is in. If this app were to ask for the DPI of any of the
/// three monitors, it will receive 96.
/// </para>
/// <para>
/// Now consider an application that is <c>PROCESS_SYSTEM_DPI_AWARE</c>. Remember that in the sample, the system DPI is 200% or 192
/// DPI. This means that any windows created by this app will render natively on display B. It the window moves to display A, it
/// will automatically be scaled down by a factor of 2. This is because a <c>PROCESS_SYSTEM_DPI_AWARE</c> app in this scenario
/// assumes that the DPI will always be 192. It queries for the DPI on startup, and then never changes it. The system accommodates
/// this by automatically scaling down when moving to display A. Likewise, if the window moves to display C, the system will
/// automatically scale up by a factor of 1.5. If the app queries for window size, it will always get the same value, similar to
/// <c>PROCESS_DPI_UNAWARE</c>. If it asks for the DPI of any of the three monitors, it will receive 192.
/// </para>
/// <para>
/// Unlike the other awareness values, <c>PROCESS_PER_MONITOR_DPI_AWARE</c> should adapt to the display that it is on. This means
/// that it is always rendered natively and is never scaled by the system. The responsibility is on the app to adjust the scale
/// factor when receiving the WM_DPICHANGED message. Part of this message includes a suggested rect for the window. This suggestion
/// is the current window scaled from the old DPI value to the new DPI value. For example, a window that is 500 by 500 on display A
/// and moved to display B will receive a suggested window rect that is 1000 by 1000. If that same window is moved to display C, the
/// suggested window rect attached to <c>WM_DPICHANGED</c> will be 1500 by 1500. Furthermore, when this app queries for the window
/// size, it will always get the actual native value. Likewise, if it asks for the DPI of any of the three monitors, it will receive
/// 96, 192, and 288 respectively.
/// </para>
/// <para>
/// Because of DPI virtualization, if one application queries another with a different awareness level for DPI-dependent
/// information, the system will automatically scale values to match the awareness level of the caller. One example of this is if
/// you call GetWindowRect and pass in a window created by another application. Using the situation described above, assume that a
/// <c>PROCESS_DPI_UNAWARE</c> app created a 500 by 500 window on display C. If you query for the window rect from a different
/// application, the size of the rect will vary based upon the DPI awareness of your app.
/// </para>
/// <list type="table">
/// <listheader>
/// <term>PROCESS_DPI_UNAWARE</term>
/// <term>
/// You will get a 500 by 500 rect because the system will assume a DPI of 96 and automatically scale the actual rect down by a
/// factor of 3.
/// </term>
/// </listheader>
/// <item>
/// <term>PROCESS_SYSTEM_DPI_AWARE</term>
/// <term>
/// You will get a 1000 by 1000 rect because the system will assume a DPI of 192 and automatically scale the actual rect down by a
/// factor of 3/2.
/// </term>
/// </item>
/// <item>
/// <term>PROCESS_PER_MONITOR_DPI_AWARE</term>
/// <term>
/// You will get a 1500 by 1500 rect because the system will use the actual DPI of the display and not do any scaling behind the scenes.
/// </term>
/// </item>
/// </list>
/// <para>Examples</para>
/// <para>This snippet demonstrates how to set a value of <c>PROCESS_SYSTEM_DPI_AWARE</c> in your application manifest.</para>
/// <para>
/// <code><dpiAware>true</dpiAware></code>
/// </para>
/// <para>This snippet demonstrates how to set a value of <c>PROCESS_PER_MONITOR_DPI_AWARE</c> in your application manifest.</para>
/// <para>
/// <code><dpiAware>true/PM</dpiAware></code>
/// </para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/ne-shellscalingapi-process_dpi_awareness typedef enum
// PROCESS_DPI_AWARENESS { PROCESS_DPI_UNAWARE, PROCESS_SYSTEM_DPI_AWARE, PROCESS_PER_MONITOR_DPI_AWARE } ;
[PInvokeData("shellscalingapi.h", MSDNShortId = "NE:shellscalingapi.PROCESS_DPI_AWARENESS")]
public enum PROCESS_DPI_AWARENESS
{
/// <summary>
/// DPI unaware. This app does not scale for DPI changes and is always assumed to have a scale factor of 100% (96 DPI). It will
/// be automatically scaled by the system on any other DPI setting.
/// </summary>
PROCESS_DPI_UNAWARE = 0,
/// <summary>
/// System DPI aware. This app does not scale for DPI changes. It will query for the DPI once and use that value for the
/// lifetime of the app. If the DPI changes, the app will not adjust to the new DPI value. It will be automatically scaled up or
/// down by the system when the DPI changes from the system value.
/// </summary>
PROCESS_SYSTEM_DPI_AWARE,
/// <summary>
/// Per monitor DPI aware. This app checks for the DPI when it is created and adjusts the scale factor whenever the DPI changes.
/// These applications are not automatically scaled by the system.
/// </summary>
PROCESS_PER_MONITOR_DPI_AWARE,
}
/// <summary>Flags that are used to indicate the scaling change that occurred.</summary>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/ne-shellscalingapi-scale_change_flags typedef enum {
// SCF_VALUE_NONE, SCF_SCALE, SCF_PHYSICAL } SCALE_CHANGE_FLAGS;
[PInvokeData("shellscalingapi.h", MSDNShortId = "NE:shellscalingapi.__unnamed_enum_1")]
[Flags]
public enum SCALE_CHANGE_FLAGS
{
/// <summary>No change.</summary>
SCF_VALUE_NONE = 0x00,
/// <summary>The scale factor has changed.</summary>
SCF_SCALE = 0x01,
/// <summary>
/// The physical dpi of the device has changed. A change in the physical dpi is generally caused either by switching display
/// devices or switching display resolutions.
/// </summary>
SCF_PHYSICAL = 0x02,
}
/// <summary>
/// <para>
/// [Some information relates to pre-released product which may be substantially modified before it's commercially released.
/// Microsoft makes no warranties, express or implied, with respect to the information provided here.]
/// </para>
/// <para>Identifies the type of UI component that is needed in the shell.</para>
/// </summary>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/ne-shellscalingapi-shell_ui_component typedef enum {
// SHELL_UI_COMPONENT_TASKBARS, SHELL_UI_COMPONENT_NOTIFICATIONAREA, SHELL_UI_COMPONENT_DESKBAND } SHELL_UI_COMPONENT;
[PInvokeData("shellscalingapi.h", MSDNShortId = "NE:shellscalingapi.__unnamed_enum_2")]
public enum SHELL_UI_COMPONENT
{
/// <summary>This UI component is a taskbar icon.</summary>
SHELL_UI_COMPONENT_TASKBARS = 0,
/// <summary>This UI component is an icon in the notification area.</summary>
SHELL_UI_COMPONENT_NOTIFICATIONAREA,
/// <summary>This UI component is a deskband icon.</summary>
SHELL_UI_COMPONENT_DESKBAND,
}
/// <summary>Queries the dots per inch (dpi) of a display.</summary>
/// <param name="hmonitor">Handle of the monitor being queried.</param>
/// <param name="dpiType">The type of DPI being queried. Possible values are from the MONITOR_DPI_TYPE enumeration.</param>
/// <param name="dpiX">
/// The value of the DPI along the X axis. This value always refers to the horizontal edge, even when the screen is rotated.
/// </param>
/// <param name="dpiY">
/// The value of the DPI along the Y axis. This value always refers to the vertical edge, even when the screen is rotated.
/// </param>
/// <returns>
/// <para>This function returns one of the following values.</para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>S_OK</term>
/// <term>The function successfully returns the X and Y DPI values for the specified monitor.</term>
/// </item>
/// <item>
/// <term>E_INVALIDARG</term>
/// <term>The handle, DPI type, or pointers passed in are not valid.</term>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>
/// This API is not DPI aware and should not be used if the calling thread is per-monitor DPI aware. For the DPI-aware version of
/// this API, see GetDpiForWindow.
/// </para>
/// <para>
/// When you call <c>GetDpiForMonitor</c>, you will receive different DPI values depending on the DPI awareness of the calling
/// application. DPI awareness is an application-level property usually defined in the application manifest. For more information
/// about DPI awareness values, see PROCESS_DPI_AWARENESS. The following table indicates how the results will differ based on the
/// <c>PROCESS_DPI_AWARENESS</c> value of your application.
/// </para>
/// <list type="table">
/// <listheader>
/// <term>PROCESS_DPI_UNAWARE</term>
/// <term>96 because the app is unaware of any other scale factors.</term>
/// </listheader>
/// <item>
/// <term>PROCESS_SYSTEM_DPI_AWARE</term>
/// <term>A value set to the system DPI because the app assumes all applications use the system DPI.</term>
/// </item>
/// <item>
/// <term>PROCESS_PER_MONITOR_DPI_AWARE</term>
/// <term>The actual DPI value set by the user for that display.</term>
/// </item>
/// </list>
/// <para>
/// The values of *dpiX and *dpiY are identical. You only need to record one of the values to determine the DPI and respond appropriately.
/// </para>
/// <para>
/// When MONITOR_DPI_TYPE is <c>MDT_ANGULAR_DPI</c> or <c>MDT_RAW_DPI</c>, the returned DPI value does not include any changes that
/// the user made to the DPI by using the desktop scaling override slider control in Control Panel.
/// </para>
/// <para>
/// For more information about DPI settings in Control Panel, see the Writing DPI-Aware Desktop Applications in Windows 8.1 Preview
/// white paper.
/// </para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/nf-shellscalingapi-getdpiformonitor HRESULT GetDpiForMonitor(
// HMONITOR hmonitor, MONITOR_DPI_TYPE dpiType, UINT *dpiX, UINT *dpiY );
[DllImport(Lib_SHCore, SetLastError = false, ExactSpelling = true)]
[PInvokeData("shellscalingapi.h", MSDNShortId = "NF:shellscalingapi.GetDpiForMonitor")]
public static extern HRESULT GetDpiForMonitor(HMONITOR hmonitor, MONITOR_DPI_TYPE dpiType, out uint dpiX, out uint dpiY);
/// <summary>Retrieves the dots per inch (dpi) occupied by a SHELL_UI_COMPONENT based on the current scale factor and PROCESS_DPI_AWARENESS.</summary>
/// <param name="Arg1">The type of shell component.</param>
/// <returns>The DPI required for an icon of this type.</returns>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/nf-shellscalingapi-getdpiforshelluicomponent UINT
// GetDpiForShellUIComponent( SHELL_UI_COMPONENT Arg1 );
[DllImport(Lib_SHCore, SetLastError = false, ExactSpelling = true)]
[PInvokeData("shellscalingapi.h", MSDNShortId = "NF:shellscalingapi.GetDpiForShellUIComponent")]
public static extern uint GetDpiForShellUIComponent(SHELL_UI_COMPONENT Arg1);
/// <summary>Retrieves the dots per inch (dpi) awareness of the specified process.</summary>
/// <param name="hprocess">Handle of the process that is being queried. If this parameter is NULL, the current process is queried.</param>
/// <param name="value">The DPI awareness of the specified process. Possible values are from the PROCESS_DPI_AWARENESS enumeration.</param>
/// <returns>
/// <para>This function returns one of the following values.</para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>S_OK</term>
/// <term>The function successfully retrieved the DPI awareness of the specified process.</term>
/// </item>
/// <item>
/// <term>E_INVALIDARG</term>
/// <term>The handle or pointer passed in is not valid.</term>
/// </item>
/// <item>
/// <term>E_ACCESSDENIED</term>
/// <term>The application does not have sufficient privileges.</term>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>This function is identical to the following code:</para>
/// <para>
/// <code>GetAwarenessFromDpiAwarenessContext(GetThreadDpiAwarenessContext());</code>
/// </para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/nf-shellscalingapi-getprocessdpiawareness HRESULT
// GetProcessDpiAwareness( HANDLE hprocess, PROCESS_DPI_AWARENESS *value );
[DllImport(Lib_SHCore, SetLastError = false, ExactSpelling = true)]
[PInvokeData("shellscalingapi.h", MSDNShortId = "NF:shellscalingapi.GetProcessDpiAwareness")]
public static extern HRESULT GetProcessDpiAwareness([In, Optional] HPROCESS hprocess, out PROCESS_DPI_AWARENESS value);
/// <summary>
/// <para>Gets the preferred scale factor for a display device.</para>
/// <para><c>Note</c> This function is not supported as of Windows 8.1. Use GetScaleFactorForMonitor instead.</para>
/// </summary>
/// <param name="deviceType">
/// <para>Type: <c>DISPLAY_DEVICE_TYPE</c></para>
/// <para>The value that indicates the type of the display device.</para>
/// </param>
/// <returns>
/// <para>Type: <c>DEVICE_SCALE_FACTOR</c></para>
/// <para>A value that indicates the scale factor that should be used with the specified DISPLAY_DEVICE_TYPE.</para>
/// <list type="table">
/// <listheader>
/// <term>Return code/value</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>SCALE_100_PERCENT 100</term>
/// <term>Use a scale factor of 1x.</term>
/// </item>
/// <item>
/// <term>SCALE_140_PERCENT 140</term>
/// <term>Use a scale factor of 1.4x.</term>
/// </item>
/// <item>
/// <term>SCALE_180_PERCENT 180</term>
/// <term>Use a scale factor of 1.8x.</term>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>The default DEVICE_SCALE_FACTOR is SCALE_100_PERCENT.</para>
/// <para>Use the scale factor that is returned to scale point values for fonts and pixel values.</para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/nf-shellscalingapi-getscalefactorfordevice DEVICE_SCALE_FACTOR
// GetScaleFactorForDevice( DISPLAY_DEVICE_TYPE deviceType );
[DllImport(Lib_SHCore, SetLastError = false, ExactSpelling = true)]
[PInvokeData("shellscalingapi.h", MSDNShortId = "NF:shellscalingapi.GetScaleFactorForDevice")]
public static extern DEVICE_SCALE_FACTOR GetScaleFactorForDevice(DISPLAY_DEVICE_TYPE deviceType);
/// <summary>Gets the scale factor of a specific monitor. This function replaces GetScaleFactorForDevice.</summary>
/// <param name="hMon">The monitor's handle.</param>
/// <param name="pScale">
/// <para>
/// When this function returns successfully, this value points to one of the DEVICE_SCALE_FACTOR values that specify the scale
/// factor of the specified monitor.
/// </para>
/// <para>
/// If the function call fails, this value points to a valid scale factor so that apps can opt to continue on with incorrectly sized resources.
/// </para>
/// </param>
/// <returns>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</returns>
/// <remarks>
/// Your code needs to handle the WM_WINDOWPOSCHANGED message in addition to the scale change event registered through
/// RegisterScaleChangeEvent, because the app window can be moved between monitors. In response to the <c>WM_WINDOWPOSCHANGED</c>
/// message, call MonitorFromWindow, followed by <c>GetScaleFactorForMonitor</c> to get the scale factor of the monitor which the
/// app window is on. Your code can then react to any dots per inch (dpi) change by reloading assets and changing layout.
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/nf-shellscalingapi-getscalefactorformonitor HRESULT
// GetScaleFactorForMonitor( HMONITOR hMon, DEVICE_SCALE_FACTOR *pScale );
[DllImport(Lib_SHCore, SetLastError = false, ExactSpelling = true)]
[PInvokeData("shellscalingapi.h", MSDNShortId = "NF:shellscalingapi.GetScaleFactorForMonitor")]
public static extern HRESULT GetScaleFactorForMonitor(HMONITOR hMon, out DEVICE_SCALE_FACTOR pScale);
/// <summary>Registers for an event that is triggered when the scale has possibly changed. This function replaces RegisterScaleChangeNotifications.</summary>
/// <param name="hEvent">Handle of the event to register for scale change notifications.</param>
/// <param name="pdwCookie">
/// When this function returns successfully, this value receives the address of a pointer to a cookie that can be used later to
/// unregister for the scale change notifications through UnregisterScaleChangeEvent.
/// </param>
/// <returns>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</returns>
/// <remarks>
/// The event is raised whenever something that can affect scale changes, but just because the scale can be affected doesn't mean
/// that it has been. Callers can cache the scale factor to verify that the monitor's scale actually has changed. The event handle
/// will be duplicated, so callers can close their handle at any time.
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/nf-shellscalingapi-registerscalechangeevent HRESULT
// RegisterScaleChangeEvent( HANDLE hEvent, DWORD_PTR *pdwCookie );
[DllImport(Lib_SHCore, SetLastError = false, ExactSpelling = true)]
[PInvokeData("shellscalingapi.h", MSDNShortId = "NF:shellscalingapi.RegisterScaleChangeEvent")]
public static extern HRESULT RegisterScaleChangeEvent(HEVENT hEvent, out IntPtr pdwCookie);
/// <summary>
/// <para>Registers a window to receive callbacks when scaling information changes.</para>
/// <para><c>Note</c> This function is not supported as of Windows 8.1. Use RegisterScaleChangeEvent instead.</para>
/// </summary>
/// <param name="displayDevice">
/// <para>Type: <c>DISPLAY_DEVICE_TYPE</c></para>
/// <para>The enum value that indicates which display device to receive notifications about.</para>
/// </param>
/// <param name="hwndNotify">
/// <para>Type: <c>HWND</c></para>
/// <para>The handle of the window that will receive the notifications.</para>
/// </param>
/// <param name="uMsgNotify">
/// <para>Type: <c>UINT</c></para>
/// <para>
/// An application-defined message that is passed to the window specified by hwndNotify when scaling information changes. Typically,
/// this should be set to WM_APP+x, where x is an integer value.
/// </para>
/// </param>
/// <param name="pdwCookie">
/// <para>Type: <c>DWORD*</c></para>
/// <para>
/// Pointer to a value that, when this function returns successfully, receives a registration token. This token is used to revoke
/// notifications by calling RevokeScaleChangeNotifications.
/// </para>
/// </param>
/// <returns>
/// <para>Type: <c>STDAPI</c></para>
/// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para>
/// </returns>
/// <remarks>
/// This message specified by uMsgNotify is posted to the registered window through PostMessage. The wParam of the message can
/// contain a combination of SCALE_CHANGE_FLAGS that describe the change that occurred.
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/nf-shellscalingapi-registerscalechangenotifications HRESULT
// RegisterScaleChangeNotifications( DISPLAY_DEVICE_TYPE displayDevice, HWND hwndNotify, UINT uMsgNotify, DWORD *pdwCookie );
[DllImport(Lib_SHCore, SetLastError = false, ExactSpelling = true)]
[PInvokeData("shellscalingapi.h", MSDNShortId = "NF:shellscalingapi.RegisterScaleChangeNotifications")]
public static extern HRESULT RegisterScaleChangeNotifications(DISPLAY_DEVICE_TYPE displayDevice, HWND hwndNotify, uint uMsgNotify, out uint pdwCookie);
/// <summary>
/// <para>Revokes the registration of a window, preventing it from receiving callbacks when scaling information changes.</para>
/// <para><c>Note</c> This function is not supported as of Windows 8.1. Use UnregisterScaleChangeEvent instead.</para>
/// </summary>
/// <param name="displayDevice">
/// <para>Type: <c>DISPLAY_DEVICE_TYPE</c></para>
/// <para>The enum value that indicates which display device to receive notifications about.</para>
/// </param>
/// <param name="dwCookie">
/// <para>Type: <c>DWORD</c></para>
/// <para>The registration token returned by a previous call to RegisterScaleChangeNotifications.</para>
/// </param>
/// <returns>
/// <para>Type: <c>STDAPI</c></para>
/// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para>
/// </returns>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/nf-shellscalingapi-revokescalechangenotifications HRESULT
// RevokeScaleChangeNotifications( DISPLAY_DEVICE_TYPE displayDevice, DWORD dwCookie );
[DllImport(Lib_SHCore, SetLastError = false, ExactSpelling = true)]
[PInvokeData("shellscalingapi.h", MSDNShortId = "NF:shellscalingapi.RevokeScaleChangeNotifications")]
public static extern HRESULT RevokeScaleChangeNotifications(DISPLAY_DEVICE_TYPE displayDevice, uint dwCookie);
/// <summary>
/// <para>
/// It is recommended that you set the process-default DPI awareness via application manifest. See Setting the default DPI awareness
/// for a process for more information. Setting the process-default DPI awareness via API call can lead to unexpected application behavior.
/// </para>
/// <para>
/// Sets the process-default DPI awareness level. This is equivalent to calling SetProcessDpiAwarenessContext with the corresponding
/// DPI_AWARENESS_CONTEXT value.
/// </para>
/// </summary>
/// <param name="value">The DPI awareness value to set. Possible values are from the PROCESS_DPI_AWARENESSenumeration.</param>
/// <returns>
/// <para>This function returns one of the following values.</para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>S_OK</term>
/// <term>The DPI awareness for the app was set successfully.</term>
/// </item>
/// <item>
/// <term>E_INVALIDARG</term>
/// <term>The value passed in is not valid.</term>
/// </item>
/// <item>
/// <term>E_ACCESSDENIED</term>
/// <term>The DPI awareness is already set, either by calling this API previously or through the application (.exe) manifest.</term>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>
/// It is recommended that you set the process-default DPI awareness via application manifest. See Setting the default DPI awareness
/// for a process for more information. Setting the process-default DPI awareness via API call can lead to unexpected application behavior.
/// </para>
/// <para>
/// Previous versions of Windows only had one DPI awareness value for the entire application. For those applications, the
/// recommendation was to set the DPI awareness value in the manifest as described in PROCESS_DPI_AWARENESS. Under that
/// recommendation, you were not supposed to use <c>SetProcessDpiAwareness</c> to update the DPI awareness. In fact, future calls to
/// this API would fail after the DPI awareness was set once. Now that DPI awareness is tied to a thread rather than an application,
/// you can use this method to update the DPI awareness. However, consider using SetThreadDpiAwarenessContext instead.
/// </para>
/// <para><c>Important</c>
/// <para></para>
/// For older applications, it is strongly recommended to not use <c>SetProcessDpiAwareness</c> to set the DPI awareness for your
/// application. Instead, you should declare the DPI awareness for your application in the application manifest. See
/// PROCESS_DPI_AWARENESS for more information about the DPI awareness values and how to set them in the manifest.
/// </para>
/// <para>
/// You must call this API before you call any APIs that depend on the dpi awareness. This is part of the reason why it is
/// recommended to use the application manifest rather than the <c>SetProcessDpiAwareness</c> API. Once API awareness is set for an
/// app, any future calls to this API will fail. This is true regardless of whether you set the DPI awareness in the manifest or by
/// using this API.
/// </para>
/// <para>If the DPI awareness level is not set, the default value is <c>PROCESS_DPI_UNAWARE</c>.</para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/nf-shellscalingapi-setprocessdpiawareness HRESULT
// SetProcessDpiAwareness( PROCESS_DPI_AWARENESS value );
[DllImport(Lib_SHCore, SetLastError = false, ExactSpelling = true)]
[PInvokeData("shellscalingapi.h", MSDNShortId = "NF:shellscalingapi.SetProcessDpiAwareness")]
public static extern HRESULT SetProcessDpiAwareness(PROCESS_DPI_AWARENESS value);
/// <summary>Unregisters for the scale change event registered through RegisterScaleChangeEvent. This function replaces RevokeScaleChangeNotifications.</summary>
/// <param name="dwCookie">A pointer to the cookie retrieved in the call to RegisterScaleChangeEvent.</param>
/// <returns>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</returns>
// https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/nf-shellscalingapi-unregisterscalechangeevent HRESULT
// UnregisterScaleChangeEvent( DWORD_PTR dwCookie );
[DllImport(Lib_SHCore, SetLastError = false, ExactSpelling = true)]
[PInvokeData("shellscalingapi.h", MSDNShortId = "NF:shellscalingapi.UnregisterScaleChangeEvent")]
public static extern HRESULT UnregisterScaleChangeEvent(IntPtr dwCookie);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.AspNetCore.Authentication
{
public class AzureADAuthenticationBuilderExtensionsTests
{
[Fact]
public void AddAzureAD_AddsAllAuthenticationHandlers()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureAD(o => { });
var provider = services.BuildServiceProvider();
// Assert
Assert.NotNull(provider.GetService<OpenIdConnectHandler>());
Assert.NotNull(provider.GetService<CookieAuthenticationHandler>());
Assert.NotNull(provider.GetService<PolicySchemeHandler>());
}
[Fact]
public void AddAzureAD_ConfiguresAllOptions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureAD(o =>
{
o.Instance = "https://login.microsoftonline.com";
o.ClientId = "ClientId";
o.ClientSecret = "ClientSecret";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.TenantId = "Common";
});
var provider = services.BuildServiceProvider();
// Assert
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
Assert.NotNull(azureADOptionsMonitor);
var azureADOptions = azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme);
Assert.Equal(AzureADDefaults.OpenIdScheme, azureADOptions.OpenIdConnectSchemeName);
Assert.Equal(AzureADDefaults.CookieScheme, azureADOptions.CookieSchemeName);
Assert.Equal("https://login.microsoftonline.com", azureADOptions.Instance);
Assert.Equal("ClientId", azureADOptions.ClientId);
Assert.Equal("ClientSecret", azureADOptions.ClientSecret);
Assert.Equal("/signin-oidc", azureADOptions.CallbackPath);
Assert.Equal("domain.onmicrosoft.com", azureADOptions.Domain);
var openIdOptionsMonitor = provider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
Assert.NotNull(openIdOptionsMonitor);
var openIdOptions = openIdOptionsMonitor.Get(AzureADDefaults.OpenIdScheme);
Assert.Equal("ClientId", openIdOptions.ClientId);
Assert.Equal($"https://login.microsoftonline.com/Common", openIdOptions.Authority);
Assert.True(openIdOptions.UseTokenLifetime);
Assert.Equal("/signin-oidc", openIdOptions.CallbackPath);
Assert.Equal(AzureADDefaults.CookieScheme, openIdOptions.SignInScheme);
var cookieAuthenticationOptionsMonitor = provider.GetService<IOptionsMonitor<CookieAuthenticationOptions>>();
Assert.NotNull(cookieAuthenticationOptionsMonitor);
var cookieAuthenticationOptions = cookieAuthenticationOptionsMonitor.Get(AzureADDefaults.CookieScheme);
Assert.Equal("/AzureAD/Account/SignIn/AzureAD", cookieAuthenticationOptions.LoginPath);
Assert.Equal("/AzureAD/Account/SignOut/AzureAD", cookieAuthenticationOptions.LogoutPath);
Assert.Equal("/AzureAD/Account/AccessDenied", cookieAuthenticationOptions.AccessDeniedPath);
Assert.Equal(SameSiteMode.None, cookieAuthenticationOptions.Cookie.SameSite);
}
[Fact]
public void AddAzureAD_AllowsOverridingCookiesAndOpenIdConnectSettings()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureAD(o =>
{
o.Instance = "https://login.microsoftonline.com";
o.ClientId = "ClientId";
o.ClientSecret = "ClientSecret";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.TenantId = "Common";
});
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, o =>
{
o.Authority = "https://overriden.com";
});
services.Configure<CookieAuthenticationOptions>(AzureADDefaults.CookieScheme, o =>
{
o.AccessDeniedPath = "/Overriden";
});
var provider = services.BuildServiceProvider();
// Assert
var openIdOptionsMonitor = provider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
Assert.NotNull(openIdOptionsMonitor);
var openIdOptions = openIdOptionsMonitor.Get(AzureADDefaults.OpenIdScheme);
Assert.Equal("ClientId", openIdOptions.ClientId);
Assert.Equal($"https://overriden.com", openIdOptions.Authority);
var cookieAuthenticationOptionsMonitor = provider.GetService<IOptionsMonitor<CookieAuthenticationOptions>>();
Assert.NotNull(cookieAuthenticationOptionsMonitor);
var cookieAuthenticationOptions = cookieAuthenticationOptionsMonitor.Get(AzureADDefaults.CookieScheme);
Assert.Equal("/AzureAD/Account/SignIn/AzureAD", cookieAuthenticationOptions.LoginPath);
Assert.Equal("/Overriden", cookieAuthenticationOptions.AccessDeniedPath);
}
[Fact]
public void AddAzureAD_RegisteringAddCookiesAndAddOpenIdConnectHasNoImpactOnAzureAAExtensions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddOpenIdConnect()
.AddCookie()
.AddAzureAD(o =>
{
o.Instance = "https://login.microsoftonline.com";
o.ClientId = "ClientId";
o.ClientSecret = "ClientSecret";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.TenantId = "Common";
});
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, o =>
{
o.Authority = "https://overriden.com";
});
services.Configure<CookieAuthenticationOptions>(AzureADDefaults.CookieScheme, o =>
{
o.AccessDeniedPath = "/Overriden";
});
var provider = services.BuildServiceProvider();
// Assert
var openIdOptionsMonitor = provider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
Assert.NotNull(openIdOptionsMonitor);
var openIdOptions = openIdOptionsMonitor.Get(AzureADDefaults.OpenIdScheme);
Assert.Equal("ClientId", openIdOptions.ClientId);
Assert.Equal($"https://overriden.com", openIdOptions.Authority);
var cookieAuthenticationOptionsMonitor = provider.GetService<IOptionsMonitor<CookieAuthenticationOptions>>();
Assert.NotNull(cookieAuthenticationOptionsMonitor);
var cookieAuthenticationOptions = cookieAuthenticationOptionsMonitor.Get(AzureADDefaults.CookieScheme);
Assert.Equal("/AzureAD/Account/SignIn/AzureAD", cookieAuthenticationOptions.LoginPath);
Assert.Equal("/Overriden", cookieAuthenticationOptions.AccessDeniedPath);
}
[Fact]
public void AddAzureAD_ThrowsForDuplicatedSchemes()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureAD(o => { })
.AddAzureAD(o => { });
var provider = services.BuildServiceProvider();
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));
Assert.Equal("A scheme with the name 'AzureAD' was already added.", exception.Message);
}
[Fact]
public void AddAzureAD_ThrowsWhenOpenIdSchemeIsAlreadyInUse()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureAD(o => { })
.AddAzureAD("Custom", AzureADDefaults.OpenIdScheme, "Cookie", null, o => { });
var provider = services.BuildServiceProvider();
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
var expectedMessage = $"The Open ID Connect scheme 'AzureADOpenID' can't be associated with the Azure Active Directory scheme 'Custom'. " +
"The Open ID Connect scheme 'AzureADOpenID' is already mapped to the Azure Active Directory scheme 'AzureAD'";
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void AddAzureAD_ThrowsWhenCookieSchemeIsAlreadyInUse()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureAD(o => { })
.AddAzureAD("Custom", "OpenID", AzureADDefaults.CookieScheme, null, o => { });
var provider = services.BuildServiceProvider();
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
var expectedMessage = $"The cookie scheme 'AzureADCookie' can't be associated with the Azure Active Directory scheme 'Custom'. " +
"The cookie scheme 'AzureADCookie' is already mapped to the Azure Active Directory scheme 'AzureAD'";
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void AddAzureAD_ThrowsWhenInstanceIsNotSet()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureAD(o => { });
var provider = services.BuildServiceProvider();
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
var expectedMessage = "The 'Instance' option must be provided.";
// Act & Assert
var exception = Assert.Throws<OptionsValidationException>(
() => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));
Assert.Contains(expectedMessage, exception.Failures);
}
[Fact]
public void AddAzureAD_SkipsOptionsValidationForNonAzureCookies()
{
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureAD(o => { })
.AddCookie("other");
var provider = services.BuildServiceProvider();
var cookieAuthOptions = provider.GetService<IOptionsMonitor<CookieAuthenticationOptions>>();
Assert.NotNull(cookieAuthOptions.Get("other"));
}
[Fact]
public void AddAzureADBearer_AddsAllAuthenticationHandlers()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADBearer(o => { });
var provider = services.BuildServiceProvider();
// Assert
Assert.NotNull(provider.GetService<JwtBearerHandler>());
Assert.NotNull(provider.GetService<PolicySchemeHandler>());
}
[Fact]
public void AddAzureADBearer_ConfiguresAllOptions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADBearer(o =>
{
o.Instance = "https://login.microsoftonline.com/";
o.ClientId = "ClientId";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.TenantId = "TenantId";
});
var provider = services.BuildServiceProvider();
// Assert
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
Assert.NotNull(azureADOptionsMonitor);
var options = azureADOptionsMonitor.Get(AzureADDefaults.BearerAuthenticationScheme);
Assert.Equal(AzureADDefaults.JwtBearerAuthenticationScheme, options.JwtBearerSchemeName);
Assert.Equal("https://login.microsoftonline.com/", options.Instance);
Assert.Equal("ClientId", options.ClientId);
Assert.Equal("domain.onmicrosoft.com", options.Domain);
var bearerOptionsMonitor = provider.GetService<IOptionsMonitor<JwtBearerOptions>>();
Assert.NotNull(bearerOptionsMonitor);
var bearerOptions = bearerOptionsMonitor.Get(AzureADDefaults.JwtBearerAuthenticationScheme);
Assert.Equal("ClientId", bearerOptions.Audience);
Assert.Equal($"https://login.microsoftonline.com/TenantId", bearerOptions.Authority);
}
[Fact]
public void AddAzureADBearer_CanOverrideJwtBearerOptionsConfiguration()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADBearer(o =>
{
o.Instance = "https://login.microsoftonline.com/";
o.ClientId = "ClientId";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.TenantId = "TenantId";
});
services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, o =>
{
o.Audience = "http://overriden.com";
});
var provider = services.BuildServiceProvider();
// Assert
var bearerOptionsMonitor = provider.GetService<IOptionsMonitor<JwtBearerOptions>>();
Assert.NotNull(bearerOptionsMonitor);
var bearerOptions = bearerOptionsMonitor.Get(AzureADDefaults.JwtBearerAuthenticationScheme);
Assert.Equal("http://overriden.com", bearerOptions.Audience);
Assert.Equal($"https://login.microsoftonline.com/TenantId", bearerOptions.Authority);
}
[Fact]
public void AddAzureADBearer_RegisteringJwtBearerHasNoImpactOnAzureAAExtensions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddJwtBearer()
.AddAzureADBearer(o =>
{
o.Instance = "https://login.microsoftonline.com/";
o.ClientId = "ClientId";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.TenantId = "TenantId";
});
services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, o =>
{
o.Audience = "http://overriden.com";
});
var provider = services.BuildServiceProvider();
// Assert
var bearerOptionsMonitor = provider.GetService<IOptionsMonitor<JwtBearerOptions>>();
Assert.NotNull(bearerOptionsMonitor);
var bearerOptions = bearerOptionsMonitor.Get(AzureADDefaults.JwtBearerAuthenticationScheme);
Assert.Equal("http://overriden.com", bearerOptions.Audience);
Assert.Equal($"https://login.microsoftonline.com/TenantId", bearerOptions.Authority);
}
[Fact]
public void AddAzureADBearer_ThrowsForDuplicatedSchemes()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADBearer(o => { })
.AddAzureADBearer(o => { });
var provider = services.BuildServiceProvider();
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));
Assert.Equal("A scheme with the name 'AzureADBearer' was already added.", exception.Message);
}
[Fact]
public void AddAzureADBearer_ThrowsWhenBearerSchemeIsAlreadyInUse()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADBearer(o => { })
.AddAzureADBearer("Custom", AzureADDefaults.JwtBearerAuthenticationScheme, o => { });
var provider = services.BuildServiceProvider();
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
var expectedMessage = $"The JSON Web Token Bearer scheme 'AzureADJwtBearer' can't be associated with the Azure Active Directory scheme 'Custom'. " +
"The JSON Web Token Bearer scheme 'AzureADJwtBearer' is already mapped to the Azure Active Directory scheme 'AzureADBearer'";
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void AddAzureADBearer_ThrowsWhenInstanceIsNotSet()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADBearer(o => { });
var provider = services.BuildServiceProvider();
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
var expectedMessage = "The 'Instance' option must be provided.";
// Act & Assert
var exception = Assert.Throws<OptionsValidationException>(
() => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));
Assert.Contains(expectedMessage, exception.Failures);
}
[Fact]
public void AddAzureADBearer_SkipsOptionsValidationForNonAzureCookies()
{
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADBearer(o => { })
.AddJwtBearer("other", o => { });
var provider = services.BuildServiceProvider();
var jwtOptions = provider.GetService<IOptionsMonitor<JwtBearerOptions>>();
Assert.NotNull(jwtOptions.Get("other"));
}
[Fact]
public void AddAzureAD_SkipsOptionsValidationForNonAzureOpenIdConnect()
{
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureAD(o => { })
.AddOpenIdConnect("other", null, o =>
{
o.ClientId = "ClientId";
o.Authority = "https://authority.com";
});
var provider = services.BuildServiceProvider();
var openIdConnectOptions = provider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
Assert.NotNull(openIdConnectOptions.Get("other"));
}
}
}
| |
//
// 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.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.StorSimple;
using Microsoft.WindowsAzure.Management.StorSimple.Models;
namespace Microsoft.WindowsAzure.Management.StorSimple
{
/// <summary>
/// All Operations related to Devices
/// </summary>
internal partial class DeviceOperations : IServiceOperations<StorSimpleManagementClient>, IDeviceOperations
{
/// <summary>
/// Initializes a new instance of the DeviceOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DeviceOperations(StorSimpleManagementClient client)
{
this._client = client;
}
private StorSimpleManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.StorSimpleManagementClient.
/// </summary>
public StorSimpleManagementClient Client
{
get { return this._client; }
}
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list of devices.
/// </returns>
public async Task<DeviceListResponse> ListAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (customRequestHeaders == null)
{
throw new ArgumentNullException("customRequestHeaders");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/~/";
url = url + "CisVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/api/devices";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-01-01.1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2014-01-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
DeviceListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DeviceListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement arrayOfDeviceInfoSequenceElement = responseDoc.Element(XName.Get("ArrayOfDeviceInfo", "http://windowscloudbackup.com/CiS/V2013_03"));
if (arrayOfDeviceInfoSequenceElement != null)
{
foreach (XElement arrayOfDeviceInfoElement in arrayOfDeviceInfoSequenceElement.Elements(XName.Get("DeviceInfo", "http://windowscloudbackup.com/CiS/V2013_03")))
{
DeviceInfo deviceInfoInstance = new DeviceInfo();
result.Devices.Add(deviceInfoInstance);
XElement aCRCountElement = arrayOfDeviceInfoElement.Element(XName.Get("ACRCount", "http://windowscloudbackup.com/CiS/V2013_03"));
if (aCRCountElement != null)
{
int aCRCountInstance = int.Parse(aCRCountElement.Value, CultureInfo.InvariantCulture);
deviceInfoInstance.ACRCount = aCRCountInstance;
}
XElement activationTimeElement = arrayOfDeviceInfoElement.Element(XName.Get("ActivationTime", "http://windowscloudbackup.com/CiS/V2013_03"));
if (activationTimeElement != null)
{
string activationTimeInstance = activationTimeElement.Value;
deviceInfoInstance.ActivationTime = activationTimeInstance;
}
XElement activeControllerElement = arrayOfDeviceInfoElement.Element(XName.Get("ActiveController", "http://windowscloudbackup.com/CiS/V2013_03"));
if (activeControllerElement != null)
{
ControllerId activeControllerInstance = ((ControllerId)Enum.Parse(typeof(ControllerId), activeControllerElement.Value, true));
deviceInfoInstance.ActiveController = activeControllerInstance;
}
XElement availableStorageInBytesElement = arrayOfDeviceInfoElement.Element(XName.Get("AvailableStorageInBytes", "http://windowscloudbackup.com/CiS/V2013_03"));
if (availableStorageInBytesElement != null)
{
long availableStorageInBytesInstance = long.Parse(availableStorageInBytesElement.Value, CultureInfo.InvariantCulture);
deviceInfoInstance.AvailableStorageInBytes = availableStorageInBytesInstance;
}
XElement cloudCredCountElement = arrayOfDeviceInfoElement.Element(XName.Get("CloudCredCount", "http://windowscloudbackup.com/CiS/V2013_03"));
if (cloudCredCountElement != null)
{
int cloudCredCountInstance = int.Parse(cloudCredCountElement.Value, CultureInfo.InvariantCulture);
deviceInfoInstance.CloudCredCount = cloudCredCountInstance;
}
XElement cultureElement = arrayOfDeviceInfoElement.Element(XName.Get("Culture", "http://windowscloudbackup.com/CiS/V2013_03"));
if (cultureElement != null)
{
string cultureInstance = cultureElement.Value;
deviceInfoInstance.Culture = cultureInstance;
}
XElement currentControllerElement = arrayOfDeviceInfoElement.Element(XName.Get("CurrentController", "http://windowscloudbackup.com/CiS/V2013_03"));
if (currentControllerElement != null)
{
ControllerId currentControllerInstance = ((ControllerId)Enum.Parse(typeof(ControllerId), currentControllerElement.Value, true));
deviceInfoInstance.CurrentController = currentControllerInstance;
}
XElement dataContainerCountElement = arrayOfDeviceInfoElement.Element(XName.Get("DataContainerCount", "http://windowscloudbackup.com/CiS/V2013_03"));
if (dataContainerCountElement != null)
{
int dataContainerCountInstance = int.Parse(dataContainerCountElement.Value, CultureInfo.InvariantCulture);
deviceInfoInstance.DataContainerCount = dataContainerCountInstance;
}
XElement descriptionElement = arrayOfDeviceInfoElement.Element(XName.Get("Description", "http://windowscloudbackup.com/CiS/V2013_03"));
if (descriptionElement != null)
{
string descriptionInstance = descriptionElement.Value;
deviceInfoInstance.Description = descriptionInstance;
}
XElement deviceIdElement = arrayOfDeviceInfoElement.Element(XName.Get("DeviceId", "http://windowscloudbackup.com/CiS/V2013_03"));
if (deviceIdElement != null)
{
string deviceIdInstance = deviceIdElement.Value;
deviceInfoInstance.DeviceId = deviceIdInstance;
}
XElement deviceSoftwareVersionElement = arrayOfDeviceInfoElement.Element(XName.Get("DeviceSoftwareVersion", "http://windowscloudbackup.com/CiS/V2013_03"));
if (deviceSoftwareVersionElement != null)
{
string deviceSoftwareVersionInstance = deviceSoftwareVersionElement.Value;
deviceInfoInstance.DeviceSoftwareVersion = deviceSoftwareVersionInstance;
}
XElement friendlyNameElement = arrayOfDeviceInfoElement.Element(XName.Get("FriendlyName", "http://windowscloudbackup.com/CiS/V2013_03"));
if (friendlyNameElement != null)
{
string friendlyNameInstance = friendlyNameElement.Value;
deviceInfoInstance.FriendlyName = friendlyNameInstance;
}
XElement isConfigUpdatedElement = arrayOfDeviceInfoElement.Element(XName.Get("IsConfigUpdated", "http://windowscloudbackup.com/CiS/V2013_03"));
if (isConfigUpdatedElement != null)
{
bool isConfigUpdatedInstance = bool.Parse(isConfigUpdatedElement.Value);
deviceInfoInstance.IsConfigUpdated = isConfigUpdatedInstance;
}
XElement isVirtualApplianceInterimEntryElement = arrayOfDeviceInfoElement.Element(XName.Get("IsVirtualApplianceInterimEntry", "http://windowscloudbackup.com/CiS/V2013_03"));
if (isVirtualApplianceInterimEntryElement != null)
{
bool isVirtualApplianceInterimEntryInstance = bool.Parse(isVirtualApplianceInterimEntryElement.Value);
deviceInfoInstance.IsVirtualApplianceInterimEntry = isVirtualApplianceInterimEntryInstance;
}
XElement locationElement = arrayOfDeviceInfoElement.Element(XName.Get("Location", "http://windowscloudbackup.com/CiS/V2013_03"));
if (locationElement != null)
{
string locationInstance = locationElement.Value;
deviceInfoInstance.Location = locationInstance;
}
XElement modelDescriptionElement = arrayOfDeviceInfoElement.Element(XName.Get("ModelDescription", "http://windowscloudbackup.com/CiS/V2013_03"));
if (modelDescriptionElement != null)
{
string modelDescriptionInstance = modelDescriptionElement.Value;
deviceInfoInstance.ModelDescription = modelDescriptionInstance;
}
XElement nNicCardsElement = arrayOfDeviceInfoElement.Element(XName.Get("NNicCards", "http://windowscloudbackup.com/CiS/V2013_03"));
if (nNicCardsElement != null)
{
int nNicCardsInstance = int.Parse(nNicCardsElement.Value, CultureInfo.InvariantCulture);
deviceInfoInstance.NNicCards = nNicCardsInstance;
}
XElement provisionedStorageInBytesElement = arrayOfDeviceInfoElement.Element(XName.Get("ProvisionedStorageInBytes", "http://windowscloudbackup.com/CiS/V2013_03"));
if (provisionedStorageInBytesElement != null)
{
long provisionedStorageInBytesInstance = long.Parse(provisionedStorageInBytesElement.Value, CultureInfo.InvariantCulture);
deviceInfoInstance.ProvisionedStorageInBytes = provisionedStorageInBytesInstance;
}
XElement serialNumberElement = arrayOfDeviceInfoElement.Element(XName.Get("SerialNumber", "http://windowscloudbackup.com/CiS/V2013_03"));
if (serialNumberElement != null)
{
string serialNumberInstance = serialNumberElement.Value;
deviceInfoInstance.SerialNumber = serialNumberInstance;
}
XElement statusElement = arrayOfDeviceInfoElement.Element(XName.Get("Status", "http://windowscloudbackup.com/CiS/V2013_03"));
if (statusElement != null)
{
DeviceStatus statusInstance = ((DeviceStatus)Enum.Parse(typeof(DeviceStatus), statusElement.Value, true));
deviceInfoInstance.Status = statusInstance;
}
XElement targetIQNElement = arrayOfDeviceInfoElement.Element(XName.Get("TargetIQN", "http://windowscloudbackup.com/CiS/V2013_03"));
if (targetIQNElement != null)
{
string targetIQNInstance = targetIQNElement.Value;
deviceInfoInstance.TargetIQN = targetIQNInstance;
}
XElement timeZoneElement = arrayOfDeviceInfoElement.Element(XName.Get("TimeZone", "http://windowscloudbackup.com/CiS/V2013_03"));
if (timeZoneElement != null)
{
string timeZoneInstance = timeZoneElement.Value;
deviceInfoInstance.TimeZone = timeZoneInstance;
}
XElement totalStorageInBytesElement = arrayOfDeviceInfoElement.Element(XName.Get("TotalStorageInBytes", "http://windowscloudbackup.com/CiS/V2013_03"));
if (totalStorageInBytesElement != null)
{
long totalStorageInBytesInstance = long.Parse(totalStorageInBytesElement.Value, CultureInfo.InvariantCulture);
deviceInfoInstance.TotalStorageInBytes = totalStorageInBytesInstance;
}
XElement typeElement = arrayOfDeviceInfoElement.Element(XName.Get("Type", "http://windowscloudbackup.com/CiS/V2013_03"));
if (typeElement != null)
{
DeviceType typeInstance = ((DeviceType)Enum.Parse(typeof(DeviceType), typeElement.Value, true));
deviceInfoInstance.Type = typeInstance;
}
XElement usingStorageInBytesElement = arrayOfDeviceInfoElement.Element(XName.Get("UsingStorageInBytes", "http://windowscloudbackup.com/CiS/V2013_03"));
if (usingStorageInBytesElement != null)
{
long usingStorageInBytesInstance = long.Parse(usingStorageInBytesElement.Value, CultureInfo.InvariantCulture);
deviceInfoInstance.UsingStorageInBytes = usingStorageInBytesInstance;
}
XElement volumeCountElement = arrayOfDeviceInfoElement.Element(XName.Get("VolumeCount", "http://windowscloudbackup.com/CiS/V2013_03"));
if (volumeCountElement != null)
{
int volumeCountInstance = int.Parse(volumeCountElement.Value, CultureInfo.InvariantCulture);
deviceInfoInstance.VolumeCount = volumeCountInstance;
}
}
}
}
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();
}
}
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Utilities
// File : ConceptualContent.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 06/13/2010
// Note : Copyright 2008-2010, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains the class used to hold the conceptual content for a
// project during a build and for editing.
//
// 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.7 04/24/2008 EFW Created the code
// 1.9.0.0 06/06/2010 EFW Added support for multi-format build output
//=============================================================================
using System.Collections.ObjectModel;
using System.IO;
using System.Xml;
using SandcastleBuilder.Utils.BuildEngine;
namespace SandcastleBuilder.Utils.ConceptualContent
{
/// <summary>
/// This class is used to hold the conceptual content settings for a
/// project during a build and for editing.
/// </summary>
public class ConceptualContentSettings
{
#region Private data members
//=====================================================================
private ImageReferenceCollection imageFiles;
private FileItemCollection codeSnippetFiles, tokenFiles,
contentLayoutFiles;
private Collection<TopicCollection> topics;
#endregion
#region Properties
//=====================================================================
/// <summary>
/// This is used to get the conceptual content image files
/// </summary>
public ImageReferenceCollection ImageFiles
{
get { return imageFiles; }
}
/// <summary>
/// This is used to get the conceptual content code snippet files
/// </summary>
public FileItemCollection CodeSnippetFiles
{
get { return codeSnippetFiles; }
}
/// <summary>
/// This is used to get the conceptual content token files
/// </summary>
public FileItemCollection TokenFiles
{
get { return tokenFiles; }
}
/// <summary>
/// This is used to get the conceptual content layout files
/// </summary>
public FileItemCollection ContentLayoutFiles
{
get { return contentLayoutFiles; }
}
/// <summary>
/// This is used to get a collection of the conceptual content topics
/// </summary>
/// <remarks>Each item in the collection represents one content layout
/// file from the project.</remarks>
public Collection<TopicCollection> Topics
{
get { return topics; }
}
#endregion
#region Constructor
//=====================================================================
/// <summary>
/// Constructor
/// </summary>
/// <param name="project">The project from which to load the settings</param>
public ConceptualContentSettings(SandcastleProject project)
{
imageFiles = new ImageReferenceCollection(project);
codeSnippetFiles = new FileItemCollection(project, BuildAction.CodeSnippets);
tokenFiles = new FileItemCollection(project, BuildAction.Tokens);
contentLayoutFiles = new FileItemCollection(project, BuildAction.ContentLayout);
topics = new Collection<TopicCollection>();
foreach(FileItem file in contentLayoutFiles)
topics.Add(new TopicCollection(file));
}
#endregion
#region Build process methods
//=====================================================================
/// <summary>
/// This is used to copy the additional content token, image, and
/// topic files to the build folder.
/// </summary>
/// <param name="builder">The build process</param>
/// <remarks>This will copy the code snippet file if specified, save
/// token information to a shared content file called <b>_Tokens_.xml</b>
/// in the build process's working folder, copy the image files to the
/// <b>.\media</b> folder in the build process's working folder, save
/// the media map to a file called <b>_MediaContent_.xml</b> in the
/// build process's working folder, and save the topic files to the
/// <b>.\ddueXml</b> folder in the build process's working folder.
/// The topic files will have their content wrapped in a
/// <c><topic></c> tag if needed and will be named using their
/// <see cref="Topic.Id" /> value.</remarks>
public void CopyContentFiles(BuildProcess builder)
{
string folder;
bool missingFile = false;
builder.ReportProgress("Copying standard token shared content file...");
builder.TransformTemplate("HelpFileBuilderTokens.tokens",
builder.TemplateFolder, builder.WorkingFolder);
builder.ReportProgress("Checking for other token files...");
foreach(FileItem tokenFile in this.tokenFiles)
if(!File.Exists(tokenFile.FullPath))
{
missingFile = true;
builder.ReportProgress(" Missing token file: {0}", tokenFile.FullPath);
}
else
{
builder.ReportProgress(" {0} -> {1}", tokenFile.FullPath,
Path.Combine(builder.WorkingFolder, Path.GetFileName(tokenFile.FullPath)));
builder.TransformTemplate(Path.GetFileName(tokenFile.FullPath),
Path.GetDirectoryName(tokenFile.FullPath), builder.WorkingFolder);
}
if(missingFile)
throw new BuilderException("BE0052", "One or more token files could not be found");
builder.ReportProgress("Checking for code snippets files...");
foreach(FileItem snippetsFile in this.codeSnippetFiles)
if(!File.Exists(snippetsFile.FullPath))
{
missingFile = true;
builder.ReportProgress(" Missing code snippets file: {0}", snippetsFile.FullPath);
}
else
builder.ReportProgress(" Found {0}", snippetsFile.FullPath);
if(missingFile)
throw new BuilderException("BE0053", "One or more code snippets files could not be found");
// Save the image info to a shared content file and copy the
// image files to the working folder.
folder = builder.WorkingFolder + "Media";
if(!Directory.Exists(folder))
Directory.CreateDirectory(folder);
// Create the build process's help format output folders too if needed
builder.EnsureOutputFoldersExist("media");
builder.ReportProgress("Copying images and creating the media map file...");
// Copy all image project items and create the content file
imageFiles.SaveAsSharedContent(builder.WorkingFolder + "_MediaContent_.xml", folder, builder);
// Copy the topic files
folder = builder.WorkingFolder + "ddueXml";
if(!Directory.Exists(folder))
Directory.CreateDirectory(folder);
builder.ReportProgress("Generating conceptual topic files");
// Create topic files
foreach(TopicCollection tc in topics)
{
tc.Load();
tc.GenerateConceptualTopics(folder, builder);
}
}
/// <summary>
/// This is used to create the conceptual content build configuration
/// files.
/// </summary>
/// <param name="builder">The build process</param>
/// <remarks>This will create the companion files used to resolve
/// conceptual links and the <b>_ContentMetadata_.xml</b> and
/// <b>ConceptualManifest.xml</b> configuration files.</remarks>
public void CreateConfigurationFiles(BuildProcess builder)
{
this.CreateCompanionFiles(builder);
this.CreateContentMetadata(builder);
this.CreateConceptualManifest(builder);
}
/// <summary>
/// This is used to create the companion files used to resolve
/// conceptual links.
/// </summary>
/// <param name="builder">The build process</param>
private void CreateCompanionFiles(BuildProcess builder)
{
string destFolder = builder.WorkingFolder + "xmlComp\\";
builder.ReportProgress(" Companion files");
if(!Directory.Exists(destFolder))
Directory.CreateDirectory(destFolder);
foreach(TopicCollection tc in topics)
foreach(Topic t in tc)
t.WriteCompanionFile(destFolder, builder);
}
/// <summary>
/// Create the content metadata file
/// </summary>
/// <param name="builder">The build process</param>
/// <remarks>The content metadata file contains metadata information
/// for each topic such as its title, table of contents title, help
/// attributes, and index keywords. Help attributes are a combination
/// of the project-level help attributes and any parsed from the topic
/// file. Any replacement tags in the token values will be replaced
/// with the appropriate project values.
/// <p/>A true MAML version of this file contains several extra
/// attributes. Since Sandcastle doesn't use them, I'm not going to
/// waste time adding them. The only stuff written is what is required
/// by Sandcastle. In addition, I'm putting the <c>title</c> and
/// <c>PBM_FileVersion</c> item elements in here rather than use the
/// separate companion files. They all end up in the metadata section
/// of the topic being built so this saves having two extra components
/// in the configuration that do the same thing with different files.
/// </remarks>
private void CreateContentMetadata(BuildProcess builder)
{
XmlWriterSettings settings = new XmlWriterSettings();
XmlWriter writer = null;
builder.ReportProgress(" _ContentMetadata_.xml");
try
{
settings.Indent = true;
settings.CloseOutput = true;
writer = XmlWriter.Create(builder.WorkingFolder + "_ContentMetadata_.xml", settings);
writer.WriteStartDocument();
writer.WriteStartElement("metadata");
// Write out each topic and all of its sub-topics
foreach(TopicCollection tc in topics)
foreach(Topic t in tc)
t.WriteMetadata(writer, builder);
writer.WriteEndElement(); // </metadata>
writer.WriteEndDocument();
}
finally
{
if(writer != null)
writer.Close();
}
}
/// <summary>
/// Create the content metadata file
/// </summary>
/// <param name="builder">The build process</param>
/// <remarks>The content metadata file contains metadata information
/// for each topic such as its title, table of contents title, help
/// attributes, and index keywords. Help attributes are a combination
/// of the project-level help attributes and any parsed from the topic
/// file. Any replacement tags in the token values will be replaced
/// with the appropriate project values.</remarks>
private void CreateConceptualManifest(BuildProcess builder)
{
XmlWriterSettings settings = new XmlWriterSettings();
XmlWriter writer = null;
builder.ReportProgress(" ConceptualManifest.xml");
try
{
settings.Indent = true;
settings.CloseOutput = true;
writer = XmlWriter.Create(builder.WorkingFolder + "ConceptualManifest.xml", settings);
writer.WriteStartDocument();
writer.WriteStartElement("topics");
foreach(TopicCollection tc in topics)
foreach(Topic t in tc)
t.WriteManifest(writer, builder);
writer.WriteEndElement(); // </topics>
writer.WriteEndDocument();
}
finally
{
if(writer != null)
writer.Close();
}
}
#endregion
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel.Background;
using Windows.Devices.Bluetooth.Rfcomm;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario3_BgChatServer : Page
{
// The background task registration for the background advertisement watcher
private IBackgroundTaskRegistration taskRegistration;
// The watcher trigger used to configure the background task registration
private RfcommConnectionTrigger trigger;
// A name is given to the task in order for it to be identifiable across context.
private string taskName = "Scenario3_BackgroundTask";
// Entry point for the background task.
private string taskEntryPoint = "BackgroundTasks.RfcommServerTask";
// Define the raw bytes that are converted into SDP record
private byte[] sdpRecordBlob = new byte[]
{
0x35, 0x4a, // DES len = 74 bytes
// Vol 3 Part B 5.1.15 ServiceName
// 34 bytes
0x09, 0x01, 0x00, // UINT16 (0x09) value = 0x0100 [ServiceName]
0x25, 0x1d, // TextString (0x25) len = 29 bytes
0x42, 0x6c, 0x75, 0x65, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x20, // Bluetooth <sp>
0x52, 0x66, 0x63, 0x6f, 0x6d, 0x6d, 0x20, // Rfcomm <sp>
0x43, 0x68, 0x61, 0x74, 0x20, // Chat <sp>
0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, // Service
// Vol 3 Part B 5.1.15 ServiceDescription
// 40 bytes
0x09, 0x01, 0x01, // UINT16 (0x09) value = 0x0101 [ServiceDescription]
0x25, 0x23, // TextString (0x25) = 35 bytes,
0x42, 0x6c, 0x75, 0x65, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x20, // Bluetooth <sp>
0x52, 0x66, 0x63, 0x6f, 0x6d, 0x6d, 0x20, // Rfcomm <sp>
0x43, 0x68, 0x61, 0x74, 0x20, // Chat <sp>
0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20, // Service <sp>
0x69, 0x6e, 0x20, 0x43, 0x23 // in C#
};
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
MainPage rootPage = MainPage.Current;
public Scenario3_BgChatServer()
{
this.InitializeComponent();
trigger = new RfcommConnectionTrigger();
// Local service Id is the only mandatory field that should be used to filter a known service UUID.
trigger.InboundConnection.LocalServiceId = RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid);
// The SDP record is nice in order to populate optional name and description fields
trigger.InboundConnection.SdpRecord = sdpRecordBlob.AsBuffer();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == taskName)
{
AttachProgressAndCompletedHandlers(task.Value);
}
}
}
private async void ListenButton_Click(object sender, RoutedEventArgs e)
{
ListenButton.IsEnabled = false;
DisconnectButton.IsEnabled = true;
// Registering a background trigger if it is not already registered. Rfcomm Chat Service will now be advertised in the SDP record
// First get the existing tasks to see if we already registered for it
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == taskName)
{
taskRegistration = task.Value;
break;
}
}
if (taskRegistration != null)
{
rootPage.NotifyUser("Background watcher already registered.", NotifyType.StatusMessage);
return;
}
else
{
// Applications registering for background trigger must request for permission.
BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
var builder = new BackgroundTaskBuilder();
builder.TaskEntryPoint = taskEntryPoint;
builder.SetTrigger(trigger);
builder.Name = taskName;
try
{
taskRegistration = builder.Register();
AttachProgressAndCompletedHandlers(taskRegistration);
// Even though the trigger is registered successfully, it might be blocked. Notify the user if that is the case.
if ((backgroundAccessStatus == BackgroundAccessStatus.AlwaysAllowed) || (backgroundAccessStatus == BackgroundAccessStatus.AllowedSubjectToSystemPolicy))
{
rootPage.NotifyUser("Background watcher registered.", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Background tasks may be disabled for this app", NotifyType.ErrorMessage);
}
}
catch (Exception)
{
rootPage.NotifyUser("Background task not registered",
NotifyType.ErrorMessage);
}
}
}
private void SendButton_Click(object sender, RoutedEventArgs e)
{
SendMessage();
}
public void KeyboardKey_Pressed(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{
SendMessage();
}
}
/// <summary>
/// Sends the current message in MessageTextBox. Also makes sure the text is not empty and updates the conversation list.
/// </summary>
private void SendMessage()
{
var message = MessageTextBox.Text;
var previousMessage = (string)ApplicationData.Current.LocalSettings.Values["SendMessage"];
// Make sure previous message has been sent
if ( previousMessage == null || previousMessage == "")
{
// Save the current message to local settings so the background task can pick it up.
ApplicationData.Current.LocalSettings.Values["SendMessage"] = message;
// Clear the messageTextBox for a new message
MessageTextBox.Text = "";
ConversationListBox.Items.Add("Sent: " + message);
}
else
{
// Do nothing until previous message has been sent.
}
}
private void DisconnectButton_Click(object sender, RoutedEventArgs e)
{
Disconnect();
}
/// <summary>
/// Called when background task defferal is completed. This can happen for a number of reasons (both expected and unexpected).
/// IF this is expected, we'll notify the user. If it's not, we'll show that this is an error. Finally, clean up the connection by calling Disconnect().
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private async void OnCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
var settings = ApplicationData.Current.LocalSettings;
if (settings.Values.ContainsKey("TaskCancelationReason"))
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Task cancelled unexpectedly - reason: " + settings.Values["TaskCancelationReason"].ToString(), NotifyType.ErrorMessage);
});
}
else
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Background task completed", NotifyType.StatusMessage);
});
}
try
{
args.CheckResult();
}
catch (Exception ex)
{
rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
}
Disconnect();
}
/// <summary>
/// Handles UX changes and task registration changes when socket is disconnected
/// </summary>
private async void Disconnect()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
ListenButton.IsEnabled = true;
DisconnectButton.IsEnabled = false;
ConversationListBox.Items.Clear();
// Unregistering the background task will remove the Rfcomm Chat Service from the SDP record and stop listening for incoming connections
// First get the existing tasks to see if we already registered for it
if (taskRegistration != null)
{
taskRegistration.Unregister(true);
taskRegistration = null;
rootPage.NotifyUser("Background watcher unregistered.", NotifyType.StatusMessage);
}
else
{
// At this point we assume we haven't found any existing tasks matching the one we want to unregister
rootPage.NotifyUser("No registered background watcher found.", NotifyType.StatusMessage);
}
});
}
/// <summary>
/// The background task updates the progress counter. When that happens, this event handler gets invoked
/// When the handler is invoked, we will display the value stored in local settings to the user.
/// </summary>
/// <param name="task"></param>
/// <param name="args"></param>
private async void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
{
if (ApplicationData.Current.LocalSettings.Values.Keys.Contains("ReceivedMessage"))
{
string backgroundMessage = (string)ApplicationData.Current.LocalSettings.Values["ReceivedMessage"];
string remoteDeviceName = (string)ApplicationData.Current.LocalSettings.Values["RemoteDeviceName"];
if(!backgroundMessage.Equals(""))
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Client Connected: " + remoteDeviceName, NotifyType.StatusMessage);
ConversationListBox.Items.Add("Received: " + backgroundMessage);
});
}
}
}
private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
{
task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
}
}
}
| |
/*
Copyright 2012 Michael Edwards
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//-CRE-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Glass.Mapper.Sc.DataMappers;
using Glass.Mapper.Sc.Fields;
using Glass.Mapper.Sc.IoC;
using NUnit.Framework;
namespace Glass.Mapper.Sc.Integration.DataMappers
{
[TestFixture]
public class SitecoreFieldImageMapperFixture : AbstractMapperFixture
{
#region Method - GetField
[Test]
public void GetField_ImageInField_ReturnsImageObject()
{
//Assign
var fieldValue =
"<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" mediapath=\"/Files/20121222_001405\" src=\"~/media/D897833C1F534FAEB54BBB5B11B8F851.ashx\" hspace=\"15\" vspace=\"20\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Image;
//Assert
Assert.AreEqual("test alt", result.Alt);
// Assert.Equals(null, result.Border);
Assert.AreEqual(string.Empty, result.Class);
Assert.AreEqual(15, result.HSpace);
Assert.AreEqual(480, result.Height);
Assert.AreEqual(new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"), result.MediaId);
Assert.IsTrue(result.Src.EndsWith("/~/media/D897833C1F534FAEB54BBB5B11B8F851.ashx"));
Assert.AreEqual(20, result.VSpace);
Assert.AreEqual(640, result.Width);
}
[Test]
public void GetField_ImageFieldEmpty_ReturnsNull()
{
//Assign
var fieldValue = string.Empty;
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
var field = item.Fields[FieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
var context = Context.Create(new DependencyResolver(new Config()));
var service = new SitecoreService(Database, context);
//Act
var result =
service.GetItem<StubImage>("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
//Assert
Assert.IsNull(result.Field);
}
[Test]
public void GetField_FieldIsEmpty_ReturnsNullImageObject()
{
//Assign
var fieldValue = string.Empty;
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Image;
//Assert
Assert.IsNull(result);
}
[Test]
public void GetField_FieldIsNull_ReturnsNullImageObject()
{
//Assign
string fieldValue = null;
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Image;
//Assert
Assert.IsNull(result);
}
#endregion
#region Method - SetField
[Test]
public void SetField_ImagePassed_ReturnsPopulatedField()
{
//Assign
var expected =
"<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" width=\"640\" vspace=\"50\" height=\"480\" hspace=\"30\" alt=\"test alt\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
var image = new Image()
{
Alt = "test alt",
HSpace = 30,
Height = 480,
MediaId = new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"),
VSpace = 50,
Width = 640,
Border = String.Empty,
Class = String.Empty
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, image, null, null);
}
//Assert
Assert.AreEqual(expected, field.Value);
}
[Test]
public void SetField_JustImageId_ReturnsPopulatedField()
{
//Assign
var expected =
"<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" alt=\"\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
var image = new Image()
{
MediaId = new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"),
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, image, null, null);
}
//Assert
Assert.AreEqual(expected, field.Value);
}
#endregion
#region Stubs
public class StubImage
{
public virtual Image Field { get; set; }
}
#endregion
}
}
| |
using Microsoft.Owin;
using Microsoft.Owin.Helpers;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Kingdango.Owin.Security.ExtensibleMiddleware.Facebook
{
public 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"];
HttpResponseMessage graphResponse = await _httpClient.GetAsync(
GraphApiEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken), 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;
}
}
}
| |
// Generated by TinyPG v1.3 available at www.codeproject.com
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
namespace TinyPG
{
#region Scanner
public partial class Scanner
{
public string Input;
public int StartPos = 0;
public int EndPos = 0;
public int CurrentLine;
public int CurrentColumn;
public int CurrentPosition;
public List<Token> Skipped; // tokens that were skipped
public Dictionary<TokenType, Regex> Patterns;
private Token LookAheadToken;
private List<TokenType> Tokens;
private List<TokenType> SkipList; // tokens to be skipped
public Scanner()
{
Regex regex;
Patterns = new Dictionary<TokenType, Regex>();
Tokens = new List<TokenType>();
LookAheadToken = null;
Skipped = new List<Token>();
SkipList = new List<TokenType>();
SkipList.Add(TokenType.WHITESPACE);
regex = new Regex(@"\(", RegexOptions.Compiled);
Patterns.Add(TokenType.BROPEN, regex);
Tokens.Add(TokenType.BROPEN);
regex = new Regex(@"\)", RegexOptions.Compiled);
Patterns.Add(TokenType.BRCLOSE, regex);
Tokens.Add(TokenType.BRCLOSE);
regex = new Regex(@"^$", RegexOptions.Compiled);
Patterns.Add(TokenType.EOF, regex);
Tokens.Add(TokenType.EOF);
regex = new Regex("==", RegexOptions.Compiled);
Patterns.Add(TokenType.EQ, regex);
Tokens.Add(TokenType.EQ);
regex = new Regex("!=", RegexOptions.Compiled);
Patterns.Add(TokenType.NEQ, regex);
Tokens.Add(TokenType.NEQ);
regex = new Regex(">", RegexOptions.Compiled);
Patterns.Add(TokenType.GT, regex);
Tokens.Add(TokenType.GT);
regex = new Regex("<", RegexOptions.Compiled);
Patterns.Add(TokenType.LT, regex);
Tokens.Add(TokenType.LT);
regex = new Regex(">=", RegexOptions.Compiled);
Patterns.Add(TokenType.GTE, regex);
Tokens.Add(TokenType.GTE);
regex = new Regex("<=", RegexOptions.Compiled);
Patterns.Add(TokenType.LTE, regex);
Tokens.Add(TokenType.LTE);
regex = new Regex("contains", RegexOptions.Compiled);
Patterns.Add(TokenType.CONTAINS, regex);
Tokens.Add(TokenType.CONTAINS);
regex = new Regex("&&", RegexOptions.Compiled);
Patterns.Add(TokenType.AND, regex);
Tokens.Add(TokenType.AND);
regex = new Regex("\\|\\|", RegexOptions.Compiled);
Patterns.Add(TokenType.OR, regex);
Tokens.Add(TokenType.OR);
regex = new Regex(@"\w+", RegexOptions.Compiled);
Patterns.Add(TokenType.NAME, regex);
Tokens.Add(TokenType.NAME);
regex = new Regex(@"""[^""]*""", RegexOptions.Compiled);
Patterns.Add(TokenType.VALUE, regex);
Tokens.Add(TokenType.VALUE);
regex = new Regex(";", RegexOptions.Compiled);
Patterns.Add(TokenType.SEP, regex);
Tokens.Add(TokenType.SEP);
regex = new Regex("Was", RegexOptions.Compiled);
Patterns.Add(TokenType.WAS, regex);
Tokens.Add(TokenType.WAS);
regex = new Regex("Obsolete", RegexOptions.Compiled);
Patterns.Add(TokenType.OBSOLETE, regex);
Tokens.Add(TokenType.OBSOLETE);
regex = new Regex("Delete", RegexOptions.Compiled);
Patterns.Add(TokenType.DELETE, regex);
Tokens.Add(TokenType.DELETE);
regex = new Regex(@"\s+", RegexOptions.Compiled);
Patterns.Add(TokenType.WHITESPACE, regex);
Tokens.Add(TokenType.WHITESPACE);
}
public void Init(string input)
{
this.Input = input;
StartPos = 0;
EndPos = 0;
CurrentLine = 0;
CurrentColumn = 0;
CurrentPosition = 0;
LookAheadToken = null;
}
public Token GetToken(TokenType type)
{
Token t = new Token(this.StartPos, this.EndPos);
t.Type = type;
return t;
}
/// <summary>
/// executes a lookahead of the next token
/// and will advance the scan on the input string
/// </summary>
/// <returns></returns>
public Token Scan(params TokenType[] expectedtokens)
{
Token tok = LookAhead(expectedtokens); // temporarely retrieve the lookahead
LookAheadToken = null; // reset lookahead token, so scanning will continue
StartPos = tok.EndPos;
EndPos = tok.EndPos; // set the tokenizer to the new scan position
return tok;
}
/// <summary>
/// returns token with longest best match
/// </summary>
/// <returns></returns>
public Token LookAhead(params TokenType[] expectedtokens)
{
int i;
int startpos = StartPos;
Token tok = null;
List<TokenType> scantokens;
// this prevents double scanning and matching
// increased performance
if (LookAheadToken != null
&& LookAheadToken.Type != TokenType._UNDETERMINED_
&& LookAheadToken.Type != TokenType._NONE_) return LookAheadToken;
// if no scantokens specified, then scan for all of them (= backward compatible)
if (expectedtokens.Length == 0)
scantokens = Tokens;
else
{
scantokens = new List<TokenType>(expectedtokens);
scantokens.AddRange(SkipList);
}
do
{
int len = -1;
TokenType index = (TokenType)int.MaxValue;
string input = Input.Substring(startpos);
tok = new Token(startpos, EndPos);
for (i = 0; i < scantokens.Count; i++)
{
Regex r = Patterns[scantokens[i]];
Match m = r.Match(input);
if (m.Success && m.Index == 0 && ((m.Length > len) || (scantokens[i] < index && m.Length == len )))
{
len = m.Length;
index = scantokens[i];
}
}
if (index >= 0 && len >= 0)
{
tok.EndPos = startpos + len;
tok.Text = Input.Substring(tok.StartPos, len);
tok.Type = index;
}
else if (tok.StartPos < tok.EndPos - 1)
{
tok.Text = Input.Substring(tok.StartPos, 1);
}
if (SkipList.Contains(tok.Type))
{
startpos = tok.EndPos;
Skipped.Add(tok);
}
else
{
// only assign to non-skipped tokens
tok.Skipped = Skipped; // assign prior skips to this token
Skipped = new List<Token>(); //reset skips
}
}
while (SkipList.Contains(tok.Type));
LookAheadToken = tok;
return tok;
}
}
#endregion
#region Token
public enum TokenType
{
//Non terminal tokens:
_NONE_ = 0,
_UNDETERMINED_= 1,
//Non terminal tokens:
Start = 2,
RenameStatement= 3,
DeleteStatement= 4,
ObsoleteStatement= 5,
RulesStatement= 6,
MatchOperator= 7,
CombineOperator= 8,
SimpleRule= 9,
CompositeRule= 10,
Rule = 11,
//Terminal tokens:
BROPEN = 12,
BRCLOSE = 13,
EOF = 14,
EQ = 15,
NEQ = 16,
GT = 17,
LT = 18,
GTE = 19,
LTE = 20,
CONTAINS= 21,
AND = 22,
OR = 23,
NAME = 24,
VALUE = 25,
SEP = 26,
WAS = 27,
OBSOLETE= 28,
DELETE = 29,
WHITESPACE= 30
}
public class Token
{
private int startpos;
private int endpos;
private string text;
private object value;
// contains all prior skipped symbols
private List<Token> skipped;
public int StartPos {
get { return startpos;}
set { startpos = value; }
}
public int Length {
get { return endpos - startpos;}
}
public int EndPos {
get { return endpos;}
set { endpos = value; }
}
public string Text {
get { return text;}
set { text = value; }
}
public List<Token> Skipped {
get { return skipped;}
set { skipped = value; }
}
public object Value {
get { return value;}
set { this.value = value; }
}
[XmlAttribute]
public TokenType Type;
public Token()
: this(0, 0)
{
}
public Token(int start, int end)
{
Type = TokenType._UNDETERMINED_;
startpos = start;
endpos = end;
Text = ""; // must initialize with empty string, may cause null reference exceptions otherwise
Value = null;
}
public void UpdateRange(Token token)
{
if (token.StartPos < startpos) startpos = token.StartPos;
if (token.EndPos > endpos) endpos = token.EndPos;
}
public override string ToString()
{
if (Text != null)
return Type.ToString() + " '" + Text + "'";
else
return Type.ToString();
}
}
#endregion
}
| |
//------------------------------------------------------------------------------
// <copyright file="QilXmlWriter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Xml;
namespace System.Xml.Xsl.Qil {
/// <summary>
/// If an annotation implements this interface, then QilXmlWriter will call ToString() on the annotation
/// and serialize the result (if non-empty).
/// </summary>
interface IQilAnnotation {
string Name { get; }
};
/// <summary>
/// An example of QilVisitor. Prints the QilExpression tree as XML.
/// </summary>
/// <remarks>
/// <para>The QilXmlWriter Visits every node in the tree, printing out an XML representation of
/// each node. Several formatting options are available, including whether or not to include annotations
/// and type information. When full information is printed out, the graph can be reloaded from
/// its serialized form using QilXmlReader.</para>
/// <para>The XML format essentially uses one XML element for each node in the QIL graph.
/// Node properties such as type information are serialized as XML attributes.
/// Annotations are serialized as processing-instructions in front of a node.</para>
/// <para>Feel free to subclass this visitor to customize its behavior.</para>
/// </remarks>
internal class QilXmlWriter : QilScopedVisitor {
protected XmlWriter writer;
protected Options options;
private NameGenerator ngen;
[Flags]
public enum Options {
None = 0, // No options selected
Annotations = 1, // Print annotations
TypeInfo = 2, // Print type information using "G" option
RoundTripTypeInfo = 4, // Print type information using "S" option
LineInfo = 8, // Print source line information
NodeIdentity = 16, // Print node identity (only works if QIL_TRACE_NODE_CREATION is defined)
NodeLocation = 32, // Print node creation location (only works if QIL_TRACE_NODE_CREATION is defined)
};
/// <summary>
/// Construct a QilXmlWriter.
/// </summary>
public QilXmlWriter(XmlWriter writer) : this(writer, Options.Annotations | Options.TypeInfo | Options.LineInfo | Options.NodeIdentity | Options.NodeLocation) {
}
/// <summary>
/// Construct a QilXmlWriter.
/// </summary>
public QilXmlWriter(XmlWriter writer, Options options) {
this.writer = writer;
this.ngen = new NameGenerator();
this.options = options;
}
/// <summary>
/// Serialize a QilExpression graph as XML.
/// </summary>
/// <param name="q">the QilExpression graph</param>
public void ToXml(QilNode node) {
VisitAssumeReference(node);
}
//-----------------------------------------------
// QilXmlWrite methods
//-----------------------------------------------
/// <summary>
/// Write all annotations as comments:
/// 1. string -- <!-- (string) ann -->
/// 2. IQilAnnotation -- <!-- ann.Name = ann.ToString() -->
/// 3. IList<object> -- recursively call WriteAnnotations for each object in list
/// 4. otherwise, do not write the annotation
/// </summary>
protected virtual void WriteAnnotations(object ann) {
string s = null, name = null;
if (ann == null) {
return;
}
else if (ann is string) {
s = ann as string;
}
else if (ann is IQilAnnotation) {
// Get annotation's name and string value
IQilAnnotation qilann = ann as IQilAnnotation;
name = qilann.Name;
s = ann.ToString();
}
else if (ann is IList<object>) {
IList<object> list = (IList<object>) ann;
foreach (object annItem in list)
WriteAnnotations(annItem);
return;
}
if (s != null && s.Length != 0)
this.writer.WriteComment(name != null && name.Length != 0 ? name + ": " + s : s);
}
/// <summary>
/// Called in order to write out source line information.
/// </summary>
protected virtual void WriteLineInfo(QilNode node) {
this.writer.WriteAttributeString("lineInfo", string.Format(CultureInfo.InvariantCulture, "[{0},{1} -- {2},{3}]",
node.SourceLine.Start.Line, node.SourceLine.Start.Pos,
node.SourceLine.End.Line , node.SourceLine.End.Pos
));
}
/// <summary>
/// Called in order to write out the xml type of a node.
/// </summary>
protected virtual void WriteXmlType(QilNode node) {
this.writer.WriteAttributeString("xmlType", node.XmlType.ToString((this.options & Options.RoundTripTypeInfo) != 0 ? "S" : "G"));
}
//-----------------------------------------------
// QilVisitor overrides
//-----------------------------------------------
/// <summary>
/// Override certain node types in order to add additional attributes, suppress children, etc.
/// </summary>
protected override QilNode VisitChildren(QilNode node) {
if (node is QilLiteral) {
// If literal is not handled elsewhere, print its string value
this.writer.WriteValue(Convert.ToString(((QilLiteral) node).Value, CultureInfo.InvariantCulture));
return node;
}
else if (node is QilReference) {
QilReference reference = (QilReference) node;
// Write the generated identifier for this iterator
this.writer.WriteAttributeString("id", this.ngen.NameOf(node));
// Write the debug name of this reference (if it's defined) as a "name" attribute
if (reference.DebugName != null)
this.writer.WriteAttributeString("name", reference.DebugName.ToString());
if (node.NodeType == QilNodeType.Parameter) {
// Don't visit parameter's name, or its default value if it is null
QilParameter param = (QilParameter) node;
if (param.DefaultValue != null)
VisitAssumeReference(param.DefaultValue);
return node;
}
}
return base.VisitChildren(node);
}
/// <summary>
/// Write references to functions or iterators like this: <RefTo id="$a"/>.
/// </summary>
protected override QilNode VisitReference(QilNode node) {
QilReference reference = (QilReference) node;
string name = ngen.NameOf(node);
if (name == null)
name = "OUT-OF-SCOPE REFERENCE";
this.writer.WriteStartElement("RefTo");
this.writer.WriteAttributeString("id", name);
if (reference.DebugName != null)
this.writer.WriteAttributeString("name", reference.DebugName.ToString());
this.writer.WriteEndElement();
return node;
}
/// <summary>
/// Scan through the external parameters, global variables, and function list for forward references.
/// </summary>
protected override QilNode VisitQilExpression(QilExpression qil) {
IList<QilNode> fdecls = new ForwardRefFinder().Find(qil);
if (fdecls != null && fdecls.Count > 0) {
this.writer.WriteStartElement("ForwardDecls");
foreach (QilNode n in fdecls) {
// i.e. <Function id="$a"/>
this.writer.WriteStartElement(Enum.GetName(typeof(QilNodeType), n.NodeType));
this.writer.WriteAttributeString("id", this.ngen.NameOf(n));
WriteXmlType(n);
if (n.NodeType == QilNodeType.Function) {
// Visit Arguments and SideEffects operands
Visit(n[0]);
Visit(n[2]);
}
this.writer.WriteEndElement();
}
this.writer.WriteEndElement();
}
return VisitChildren(qil);
}
/// <summary>
/// Serialize literal types using either "S" or "G" formatting, depending on the option which has been set.
/// </summary>
protected override QilNode VisitLiteralType(QilLiteral value) {
this.writer.WriteString(((XmlQueryType) value).ToString((this.options & Options.TypeInfo) != 0 ? "G" : "S"));
return value;
}
/// <summary>
/// Serialize literal QName as three separate attributes.
/// </summary>
protected override QilNode VisitLiteralQName(QilName value) {
this.writer.WriteAttributeString("name", value.ToString());
return value;
}
//-----------------------------------------------
// QilScopedVisitor overrides
//-----------------------------------------------
/// <summary>
/// Annotate this iterator or function with a generated name.
/// </summary>
protected override void BeginScope(QilNode node) {
this.ngen.NameOf(node);
}
/// <summary>
/// Clear the name annotation on this iterator or function.
/// </summary>
protected override void EndScope(QilNode node) {
this.ngen.ClearName(node);
}
/// <summary>
/// By default, call WriteStartElement for every node type.
/// </summary>
protected override void BeforeVisit(QilNode node) {
base.BeforeVisit(node);
// Write the annotations in front of the element, to avoid issues with attributes
// and make it easier to round-trip
if ((this.options & Options.Annotations) != 0)
WriteAnnotations(node.Annotation);
// Call WriteStartElement
this.writer.WriteStartElement("", Enum.GetName(typeof(QilNodeType), node.NodeType), "");
// Write common attributes
#if QIL_TRACE_NODE_CREATION
if ((this.options & Options.NodeIdentity) != 0)
this.writer.WriteAttributeString("nodeId", node.NodeId.ToString(CultureInfo.InvariantCulture));
if ((this.options & Options.NodeLocation) != 0)
this.writer.WriteAttributeString("nodeLoc", node.NodeLocation);
#endif
if ((this.options & (Options.TypeInfo | Options.RoundTripTypeInfo)) != 0)
WriteXmlType(node);
if ((this.options & Options.LineInfo) != 0 && node.SourceLine != null)
WriteLineInfo(node);
}
/// <summary>
/// By default, call WriteEndElement for every node type.
/// </summary>
protected override void AfterVisit(QilNode node) {
this.writer.WriteEndElement();
base.AfterVisit(node);
}
//-----------------------------------------------
// Helper methods
//-----------------------------------------------
/// <summary>
/// Find list of all iterators and functions which are referenced before they have been declared.
/// </summary>
internal class ForwardRefFinder : QilVisitor {
private List<QilNode> fwdrefs = new List<QilNode>();
private List<QilNode> backrefs = new List<QilNode>();
public IList<QilNode> Find(QilExpression qil) {
Visit(qil);
return this.fwdrefs;
}
/// <summary>
/// Add iterators and functions to backrefs list as they are visited.
/// </summary>
protected override QilNode Visit(QilNode node) {
if (node is QilIterator || node is QilFunction)
this.backrefs.Add(node);
return base.Visit(node);
}
/// <summary>
/// If reference is not in scope, then it must be a forward reference.
/// </summary>
protected override QilNode VisitReference(QilNode node) {
if (!this.backrefs.Contains(node) && !this.fwdrefs.Contains(node))
this.fwdrefs.Add(node);
return node;
}
}
//=================================== Helper class: NameGenerator =========================================
private sealed class NameGenerator {
StringBuilder name;
int len;
int zero;
char start;
char end;
/// <summary>
/// Construct a new name generator with prefix "$" and alphabetical mode.
/// </summary>
public NameGenerator()
{
string prefix = "$";
len = zero = prefix.Length;
start = 'a';
end = 'z';
name = new StringBuilder(prefix, len + 2);
name.Append(start);
}
/// <summary>
/// Skolem function for names.
/// </summary>
/// <returns>a unique name beginning with the prefix</returns>
public string NextName()
{
string result = name.ToString();
char c = name[len];
if (c == end)
{
name[len] = start;
int i = len;
for ( ; i-- > zero && name[i]==end; )
name[i] = start;
if (i < zero)
{
len++;
name.Append(start);
}
else
name[i]++;
}
else
name[len] = ++c;
return result;
}
/// <summary>
/// Lookup or generate a name for a node. Uses annotations to store the name on the node.
/// </summary>
/// <param name="i">the node</param>
/// <returns>the node name (unique across nodes)</returns>
public string NameOf(QilNode n)
{
string name = null;
object old = n.Annotation;
NameAnnotation a = old as NameAnnotation;
if (a == null)
{
name = NextName();
n.Annotation = new NameAnnotation(name, old);
}
else
{
name = a.Name;
}
return name;
}
/// <summary>
/// Clear name annotation from a node.
/// </summary>
/// <param name="n">the node</param>
public void ClearName(QilNode n)
{
if (n.Annotation is NameAnnotation)
n.Annotation = ((NameAnnotation)n.Annotation).PriorAnnotation;
}
/// <summary>
/// Class used to hold our annotations on the graph
/// </summary>
private class NameAnnotation : ListBase<object>
{
public string Name;
public object PriorAnnotation;
public NameAnnotation(string s, object a)
{
Name = s;
PriorAnnotation = a;
}
public override int Count {
get { return 1; }
}
public override object this[int index] {
get {
if (index == 0)
return PriorAnnotation;
throw new IndexOutOfRangeException();
}
set { throw new NotSupportedException(); }
}
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Media;
using System.Windows.Controls.Primitives; // IItemContainerGenerator
namespace System.Windows.Controls
{
/// <summary>
/// A base class that provides access to information that is useful for panels that with to implement virtualization.
/// </summary>
public abstract class VirtualizingPanel : Panel
{
/// <summary>
/// The default constructor.
/// </summary>
protected VirtualizingPanel() : base()
{
}
public bool CanHierarchicallyScrollAndVirtualize
{
get { return CanHierarchicallyScrollAndVirtualizeCore; }
}
protected virtual bool CanHierarchicallyScrollAndVirtualizeCore
{
get { return false; }
}
public double GetItemOffset(UIElement child)
{
return GetItemOffsetCore(child);
}
/// <summary>
/// Fetch the logical/item offset for this child with respect to the top of the
/// panel. This is similar to a TransformToAncestor operation. Just works
/// in logical units.
/// </summary>
protected virtual double GetItemOffsetCore(UIElement child)
{
return 0;
}
/// <summary>
/// Attached property for use on the ItemsControl that is the host for the items being
/// presented by this panel. Use this property to turn virtualization on/off.
/// </summary>
public static readonly DependencyProperty IsVirtualizingProperty =
DependencyProperty.RegisterAttached("IsVirtualizing", typeof(bool), typeof(VirtualizingPanel),
new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnVirtualizationPropertyChanged)));
/// <summary>
/// Retrieves the value for <see cref="IsVirtualizingProperty" />.
/// </summary>
/// <param name="element">The element on which to query the value.</param>
/// <returns>True if virtualizing, false otherwise.</returns>
public static bool GetIsVirtualizing(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (bool)element.GetValue(IsVirtualizingProperty);
}
/// <summary>
/// Sets the value for <see cref="IsVirtualizingProperty" />.
/// </summary>
/// <param name="element">The element on which to set the value.</param>
/// <param name="value">True if virtualizing, false otherwise.</param>
public static void SetIsVirtualizing(DependencyObject element, bool value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsVirtualizingProperty, value);
}
/// <summary>
/// Attached property for use on the ItemsControl that is the host for the items being
/// presented by this panel. Use this property to modify the virtualization mode.
///
/// Note that this property can only be set before the panel has been initialized
/// </summary>
public static readonly DependencyProperty VirtualizationModeProperty =
DependencyProperty.RegisterAttached("VirtualizationMode", typeof(VirtualizationMode), typeof(VirtualizingPanel),
new FrameworkPropertyMetadata(VirtualizationMode.Standard, FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnVirtualizationPropertyChanged)));
/// <summary>
/// Retrieves the value for <see cref="VirtualizationModeProperty" />.
/// </summary>
/// <param name="o">The object on which to query the value.</param>
/// <returns>The current virtualization mode.</returns>
public static VirtualizationMode GetVirtualizationMode(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (VirtualizationMode)element.GetValue(VirtualizationModeProperty);
}
/// <summary>
/// Sets the value for <see cref="VirtualizationModeProperty" />.
/// </summary>
/// <param name="element">The element on which to set the value.</param>
/// <param name="value">The desired virtualization mode.</param>
public static void SetVirtualizationMode(DependencyObject element, VirtualizationMode value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(VirtualizationModeProperty, value);
}
/// <summary>
/// Attached property for use on the ItemsControl that is the host for the items being
/// presented by this panel. Use this property to turn virtualization on/off when grouping.
/// </summary>
public static readonly DependencyProperty IsVirtualizingWhenGroupingProperty =
DependencyProperty.RegisterAttached("IsVirtualizingWhenGrouping", typeof(bool), typeof(VirtualizingPanel),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnVirtualizationPropertyChanged), new CoerceValueCallback(CoerceIsVirtualizingWhenGrouping)));
/// <summary>
/// Retrieves the value for <see cref="IsVirtualizingWhenGroupingProperty" />.
/// </summary>
/// <param name="element">The object on which to query the value.</param>
/// <returns>True if virtualizing, false otherwise.</returns>
public static bool GetIsVirtualizingWhenGrouping(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (bool)element.GetValue(IsVirtualizingWhenGroupingProperty);
}
/// <summary>
/// Sets the value for <see cref="IsVirtualizingWhenGroupingProperty" />.
/// </summary>
/// <param name="element">The element on which to set the value.</param>
/// <param name="value">True if virtualizing, false otherwise.</param>
public static void SetIsVirtualizingWhenGrouping(DependencyObject element, bool value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsVirtualizingWhenGroupingProperty, value);
}
/// <summary>
/// Attached property for use on the ItemsControl that is the host for the items being
/// presented by this panel. Use this property to switch between pixel and item scrolling.
/// </summary>
public static readonly DependencyProperty ScrollUnitProperty =
DependencyProperty.RegisterAttached("ScrollUnit", typeof(ScrollUnit), typeof(VirtualizingPanel),
new FrameworkPropertyMetadata(ScrollUnit.Item, FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnVirtualizationPropertyChanged)));
/// <summary>
/// Retrieves the value for <see cref="ScrollUnitProperty" />.
/// </summary>
/// <param name="element">The object on which to query the value.</param>
public static ScrollUnit GetScrollUnit(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (ScrollUnit)element.GetValue(ScrollUnitProperty);
}
/// <summary>
/// Sets the value for <see cref="ScrollUnitProperty" />.
/// </summary>
/// <param name="element">The element on which to set the value.</param>
public static void SetScrollUnit(DependencyObject element, ScrollUnit value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(ScrollUnitProperty, value);
}
/// <summary>
/// Attached property for use on the ItemsControl that is the host for the items being
/// presented by this panel. Use this property to configure the dimensions of the cache
/// before and after the viewport when virtualizing. Please note that the unit of these dimensions
/// is determined by the value of the <see cref="CacheLengthUnitProperty"/>.
/// </summary>
public static readonly DependencyProperty CacheLengthProperty =
DependencyProperty.RegisterAttached("CacheLength", typeof(VirtualizationCacheLength), typeof(VirtualizingPanel),
new FrameworkPropertyMetadata(new VirtualizationCacheLength(1.0), FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnVirtualizationPropertyChanged)), new ValidateValueCallback(ValidateCacheSizeBeforeOrAfterViewport));
/// <summary>
/// Retrieves the value for <see cref="CacheLengthProperty" />.
/// </summary>
/// <param name="element">The object on which to query the value.</param>
/// <returns>VirtualCacheLength representing the dimensions of the cache before and after the
/// viewport.</returns>
public static VirtualizationCacheLength GetCacheLength(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (VirtualizationCacheLength)element.GetValue(CacheLengthProperty);
}
/// <summary>
/// Sets the value for <see cref="CacheLengthProperty" />.
/// </summary>
/// <param name="element">The element on which to set the value.</param>
/// <param name="value">VirtualCacheLength representing the dimensions of the cache before and after the
/// viewport.</param>
public static void SetCacheLength(DependencyObject element, VirtualizationCacheLength value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(CacheLengthProperty, value);
}
/// <summary>
/// Attached property for use on the ItemsControl that is the host for the items being
/// presented by this panel. Use this property to configure the unit portion of the before
/// and after cache sizes.
/// </summary>
public static readonly DependencyProperty CacheLengthUnitProperty =
DependencyProperty.RegisterAttached("CacheLengthUnit", typeof(VirtualizationCacheLengthUnit), typeof(VirtualizingPanel),
new FrameworkPropertyMetadata(VirtualizationCacheLengthUnit.Page, FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnVirtualizationPropertyChanged)));
/// <summary>
/// Retrieves the value for <see cref="CacheLengthUnitProperty" />.
/// </summary>
/// <param name="element">The object on which to query the value.</param>
/// <returns>The CacheLenghtUnit for the matching CacheLength property.</returns>
public static VirtualizationCacheLengthUnit GetCacheLengthUnit(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (VirtualizationCacheLengthUnit)element.GetValue(CacheLengthUnitProperty);
}
/// <summary>
/// Sets the value for <see cref="CacheLengthUnitProperty" />.
/// </summary>
/// <param name="element">The element on which to set the value.</param>
/// <param name="value">The CacheLenghtUnit for the matching CacheLength property.</param>
public static void SetCacheLengthUnit(DependencyObject element, VirtualizationCacheLengthUnit value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(CacheLengthUnitProperty, value);
}
/// <summary>
/// Attached property for use on a container being presented by this panel. The parent panel
/// is expected to honor this property and not virtualize containers that are designated non-virtualizable.
/// </summary>
public static readonly DependencyProperty IsContainerVirtualizableProperty =
DependencyProperty.RegisterAttached("IsContainerVirtualizable", typeof(bool), typeof(VirtualizingPanel),
new FrameworkPropertyMetadata(true));
/// <summary>
/// Retrieves the value for <see cref="IsContainerVirtualizableProperty" />.
/// </summary>
/// <param name="element">The object on which to query the value.</param>
/// <returns>True if the container is virtualizable, false otherwise.</returns>
public static bool GetIsContainerVirtualizable(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (bool)element.GetValue(IsContainerVirtualizableProperty);
}
/// <summary>
/// Sets the value for <see cref="IsContainerVirtualizableProperty" />.
/// </summary>
/// <param name="element">The element on which to set the value.</param>
/// <param name="value">True if container is virtualizable, false otherwise.</param>
public static void SetIsContainerVirtualizable(DependencyObject element, bool value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsContainerVirtualizableProperty, value);
}
/// <summary>
/// Attached property for use on a container being presented by this panel. The parent panel
/// is expected to honor this property and not cache container sizes that are designated such.
/// </summary>
internal static readonly DependencyProperty ShouldCacheContainerSizeProperty =
DependencyProperty.RegisterAttached("ShouldCacheContainerSize", typeof(bool), typeof(VirtualizingPanel),
new FrameworkPropertyMetadata(true));
/// <summary>
/// Retrieves the value for <see cref="ShouldCacheContainerSizeProperty" />.
/// </summary>
/// <param name="element">The object on which to query the value.</param>
/// <returns>True if the container size should be cached, false otherwise.</returns>
internal static bool GetShouldCacheContainerSize(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
if (VirtualizingStackPanel.IsVSP45Compat)
{
return (bool)element.GetValue(ShouldCacheContainerSizeProperty);
}
else
{
// this property can cause infinite loops. Suppose element X sets this
// to false, so that we don't cache the size of X. When X leaves
// the viewport, we will estimate its size using the average container
// size (that average doesn't include X). When it returns, we will
// use the actual size. This difference can cause infinite re-measure
// or bad scroll result (scroll to the wrong offset) when X is near
// the edge of the viewport.
//
// The property is only set on the DataGridRow that hosts the
// NewItemPlaceholder. The intent was to avoid treating a
// DataGrid as having non-uniform containers only on account of the
// NewItem row. While this helps a common case (a non-grouped
// DataGrid whose containers are all the same, except the placeholder
// which is different), it doesn't justify breaking other cases.
//
// Ignore the value (always return true). This fixes the loops and
// bad scrolls, and only increases perf in the case mentioned above,
// and even then only memory consumption (hashtable lookup is O(1)),
// and only proportional to the number of items the user actually
// scrolls into view.
return true;
}
}
private static bool ValidateCacheSizeBeforeOrAfterViewport(object value)
{
VirtualizationCacheLength cacheLength = (VirtualizationCacheLength)value;
return DoubleUtil.GreaterThanOrClose(cacheLength.CacheBeforeViewport, 0.0) &&
DoubleUtil.GreaterThanOrClose(cacheLength.CacheAfterViewport, 0.0);
}
private static object CoerceIsVirtualizingWhenGrouping(DependencyObject d, object baseValue)
{
bool isVirtualizing = GetIsVirtualizing(d);
return isVirtualizing && (bool)baseValue;
}
internal static void OnVirtualizationPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ItemsControl ic = d as ItemsControl;
if (ic != null)
{
Panel p = ic.ItemsHost;
if (p != null)
{
p.InvalidateMeasure();
ItemsPresenter itemsPresenter = VisualTreeHelper.GetParent(p) as ItemsPresenter;
if (itemsPresenter != null)
{
itemsPresenter.InvalidateMeasure();
}
if (d is TreeView)
{
DependencyProperty dp = e.Property;
if (dp == VirtualizingStackPanel.IsVirtualizingProperty ||
dp == VirtualizingPanel.IsVirtualizingWhenGroupingProperty ||
dp == VirtualizingStackPanel.VirtualizationModeProperty ||
dp == VirtualizingPanel.ScrollUnitProperty)
{
VirtualizationPropertyChangePropagationRecursive(ic, p);
}
}
}
}
}
private static void VirtualizationPropertyChangePropagationRecursive(DependencyObject parent, Panel itemsHost)
{
UIElementCollection children = itemsHost.InternalChildren;
int childrenCount = children.Count;
for (int i=0; i<childrenCount; i++)
{
IHierarchicalVirtualizationAndScrollInfo virtualizingChild = children[i] as IHierarchicalVirtualizationAndScrollInfo;
if (virtualizingChild != null)
{
TreeViewItem.IsVirtualizingPropagationHelper(parent, (DependencyObject)virtualizingChild);
Panel childItemsHost = virtualizingChild.ItemsHost;
if (childItemsHost != null)
{
VirtualizationPropertyChangePropagationRecursive((DependencyObject)virtualizingChild, childItemsHost);
}
}
}
}
/// <summary>
/// The generator associated with this panel.
/// </summary>
public IItemContainerGenerator ItemContainerGenerator
{
get
{
return Generator;
}
}
internal override void GenerateChildren()
{
// Do nothing. Subclasses will use the exposed generator to generate children.
}
/// <summary>
/// Adds a child to the InternalChildren collection.
/// This method is meant to be used when a virtualizing panel
/// generates a new child. This method circumvents some validation
/// that occurs in UIElementCollection.Add.
/// </summary>
/// <param name="child">Child to add.</param>
protected void AddInternalChild(UIElement child)
{
AddInternalChild(InternalChildren, child);
}
/// <summary>
/// Inserts a child into the InternalChildren collection.
/// This method is meant to be used when a virtualizing panel
/// generates a new child. This method circumvents some validation
/// that occurs in UIElementCollection.Insert.
/// </summary>
/// <param name="index">The index at which to insert the child.</param>
/// <param name="child">Child to insert.</param>
protected void InsertInternalChild(int index, UIElement child)
{
InsertInternalChild(InternalChildren, index, child);
}
/// <summary>
/// Removes a child from the InternalChildren collection.
/// This method is meant to be used when a virtualizing panel
/// re-virtualizes a new child. This method circumvents some validation
/// that occurs in UIElementCollection.RemoveRange.
/// </summary>
/// <param name="index"></param>
/// <param name="range"></param>
protected void RemoveInternalChildRange(int index, int range)
{
RemoveInternalChildRange(InternalChildren, index, range);
}
// This is internal as an optimization for VirtualizingStackPanel (so it doesn't need to re-query InternalChildren repeatedly)
internal static void AddInternalChild(UIElementCollection children, UIElement child)
{
children.AddInternal(child);
}
// This is internal as an optimization for VirtualizingStackPanel (so it doesn't need to re-query InternalChildren repeatedly)
internal static void InsertInternalChild(UIElementCollection children, int index, UIElement child)
{
children.InsertInternal(index, child);
}
// This is internal as an optimization for VirtualizingStackPanel (so it doesn't need to re-query InternalChildren repeatedly)
internal static void RemoveInternalChildRange(UIElementCollection children, int index, int range)
{
children.RemoveRangeInternal(index, range);
}
/// <summary>
/// Called when the Items collection associated with the containing ItemsControl changes.
/// </summary>
/// <param name="sender">sender</param>
/// <param name="args">Event arguments</param>
protected virtual void OnItemsChanged(object sender, ItemsChangedEventArgs args)
{
}
public bool ShouldItemsChangeAffectLayout(bool areItemChangesLocal, ItemsChangedEventArgs args)
{
return ShouldItemsChangeAffectLayoutCore(areItemChangesLocal, args);
}
/// <summary>
/// Returns whether an Items collection change affects layout for this panel.
/// </summary>
/// <param name="args">Event arguments</param>
/// <param name="areItemChangesLocal">Says if this notification represents a direct change to this Panel's collection</param>
protected virtual bool ShouldItemsChangeAffectLayoutCore(bool areItemChangesLocal, ItemsChangedEventArgs args)
{
return true;
}
/// <summary>
/// Called when the UI collection of children is cleared by the base Panel class.
/// </summary>
protected virtual void OnClearChildren()
{
}
/// <summary>
/// This is the public accessor for protected method BringIndexIntoView.
/// </summary>
public void BringIndexIntoViewPublic(int index)
{
BringIndexIntoView(index);
}
/// <summary>
/// Generates the item at the specified index and calls BringIntoView on it.
/// </summary>
/// <param name="index">Specify the item index that should become visible</param>
protected internal virtual void BringIndexIntoView(int index)
{
}
// This method returns a bool to indicate if or not the panel layout is affected by this collection change
internal override bool OnItemsChangedInternal(object sender, ItemsChangedEventArgs args)
{
switch (args.Action)
{
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Remove:
case NotifyCollectionChangedAction.Replace:
case NotifyCollectionChangedAction.Move:
// Don't allow Panel's code to run for add/remove/replace/move
break;
default:
base.OnItemsChangedInternal(sender, args);
break;
}
OnItemsChanged(sender, args);
return ShouldItemsChangeAffectLayout(true /*areItemChangesLocal*/, args);
}
internal override void OnClearChildrenInternal()
{
OnClearChildren();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Dfm
{
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.MarkdownLite;
public class DfmRenderer : HtmlRenderer, IDisposable
{
private readonly DocfxFlavoredIncHelper _inlineInclusionHelper = new DocfxFlavoredIncHelper();
private readonly DocfxFlavoredIncHelper _blockInclusionHelper = new DocfxFlavoredIncHelper();
private readonly DfmCodeExtractor _dfmCodeExtractor = new DfmCodeExtractor();
public ImmutableDictionary<string, string> Tokens { get; set; }
public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmXrefInlineToken token, MarkdownInlineContext context)
{
StringBuffer result = "<xref";
result = AppendAttribute(result, "href", token.Href);
result = AppendAttribute(result, "title", token.Title);
result = AppendAttribute(result, "data-throw-if-not-resolved", token.ThrowIfNotResolved.ToString());
result = AppendAttribute(result, "data-raw-source", token.SourceInfo.Markdown);
result = AppendSourceInfo(result, renderer, token);
result += ">";
foreach (var item in token.Content)
{
result += renderer.Render(item);
}
result += "</xref>";
return result;
}
public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmIncludeBlockToken token, MarkdownBlockContext context)
{
lock (_blockInclusionHelper)
{
return _blockInclusionHelper.Load(renderer, token.Src, token.Raw, token.SourceInfo, context, (DfmEngine)renderer.Engine);
}
}
public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmIncludeInlineToken token, MarkdownInlineContext context)
{
lock (_inlineInclusionHelper)
{
return _inlineInclusionHelper.Load(renderer, token.Src, token.Raw, token.SourceInfo, context, (DfmEngine)renderer.Engine);
}
}
public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmYamlHeaderBlockToken token, MarkdownBlockContext context)
{
if (string.IsNullOrEmpty(token.Content))
{
return StringBuffer.Empty;
}
var startLine = token.SourceInfo.LineNumber;
var endLine = startLine + token.Content.Count(ch => ch == '\n') + 2;
var sourceFile = token.SourceInfo.File;
StringBuffer result = $"<yamlheader start=\"{startLine}\" end=\"{endLine}\"";
if (!string.IsNullOrEmpty(sourceFile))
{
sourceFile = StringHelper.HtmlEncode(sourceFile);
result += $" sourceFile=\"{sourceFile}\"";
}
result += ">";
result += StringHelper.HtmlEncode(token.Content);
return result + "</yamlheader>";
}
public override StringBuffer Render(IMarkdownRenderer renderer, MarkdownBlockquoteBlockToken token, MarkdownBlockContext context)
{
StringBuffer content = string.Empty;
var splitTokens = DfmBlockquoteHelper.SplitBlockquoteTokens(token.Tokens);
foreach (var splitToken in splitTokens)
{
if (splitToken.Token is DfmSectionBlockToken)
{
if (!splitToken.Token.SourceInfo.Markdown.EndsWith("\n"))
{
Logger.LogWarning("The content part of [!div] syntax is suggested to start in a new line.", file: splitToken.Token.SourceInfo.File, line: splitToken.Token.SourceInfo.LineNumber.ToString());
}
content += "<div";
content += ((DfmSectionBlockToken)splitToken.Token).Attributes;
content = AppendSourceInfo(content, renderer, splitToken.Token);
content += ">";
foreach (var item in splitToken.InnerTokens)
{
content += renderer.Render(item);
}
content += "</div>\n";
}
else if (splitToken.Token is DfmNoteBlockToken)
{
if (!splitToken.Token.SourceInfo.Markdown.EndsWith("\n"))
{
Logger.LogWarning("The content part of NOTE/WARNING/CAUTION/IMPORTANT syntax is suggested to start in a new line.", file: splitToken.Token.SourceInfo.File, line: splitToken.Token.SourceInfo.LineNumber.ToString());
}
var noteToken = (DfmNoteBlockToken)splitToken.Token;
content += "<div class=\"";
content += noteToken.NoteType.ToUpper();
content += "\"";
content = AppendSourceInfo(content, renderer, splitToken.Token);
content += ">";
string heading;
if (Tokens != null && Tokens.TryGetValue(noteToken.NoteType.ToLower(), out heading))
{
content += heading;
}
else
{
content += "<h5>";
content += noteToken.NoteType.ToUpper();
content += "</h5>";
}
foreach (var item in splitToken.InnerTokens)
{
content += renderer.Render(item);
}
content += "</div>\n";
}
else if (splitToken.Token is DfmVideoBlockToken)
{
var videoToken = splitToken.Token as DfmVideoBlockToken;
content += "<div class=\"embeddedvideo\"><iframe src=\"";
content += videoToken.Link;
content += "\" frameborder=\"0\" allowfullscreen=\"true\"";
content = AppendSourceInfo(content, renderer, splitToken.Token);
content += "></iframe></div>\n";
continue;
}
else
{
content += "<blockquote";
content = AppendSourceInfo(content, renderer, splitToken.Token);
content += ">";
foreach (var item in splitToken.InnerTokens)
{
content += renderer.Render(item);
}
content += "</blockquote>\n";
}
}
return content;
}
public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmFencesToken token, IMarkdownContext context)
{
if (!PathUtility.IsRelativePath(token.Path))
{
string errorMessage = $"Code absolute path: {token.Path} is not supported in file {context.GetFilePathStack().Peek()}";
Logger.LogError(errorMessage);
return DfmFencesBlockHelper.GetRenderedFencesBlockString(token, renderer.Options, errorMessage);
}
try
{
// Always report original dependency
context.ReportDependency(token.Path);
var filePathWithStatus = DfmFallbackHelper.GetFilePathWithFallback(token.Path, context);
var extractResult = _dfmCodeExtractor.ExtractFencesCode(token, filePathWithStatus.Item1);
var result = DfmFencesBlockHelper.GetRenderedFencesBlockString(token, renderer.Options, extractResult.ErrorMessage, extractResult.FencesCodeLines);
return result;
}
catch (DirectoryNotFoundException)
{
return DfmFencesBlockHelper.GenerateReferenceNotFoundErrorMessage(renderer, token);
}
catch (FileNotFoundException)
{
return DfmFencesBlockHelper.GenerateReferenceNotFoundErrorMessage(renderer, token);
}
}
public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmFencesBlockToken token, MarkdownBlockContext context)
{
return Render(renderer, token, (IMarkdownContext)context);
}
public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmNoteBlockToken token, MarkdownBlockContext context)
{
return token.Content;
}
public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmVideoBlockToken token, MarkdownBlockContext context)
{
return token.SourceInfo.Markdown;
}
public void Dispose()
{
_inlineInclusionHelper.Dispose();
_blockInclusionHelper.Dispose();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The design of this map service is based on SimianGrid's PHP-based
* map service. See this URL for the original PHP version:
* https://github.com/openmetaversefoundation/simiangrid/
*/
using log4net;
using Nini.Config;
using OpenSim.Services.Interfaces;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
namespace OpenSim.Services.MapImageService
{
public class MapImageService : IMapImageService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private const int ZOOM_LEVELS = 8;
private const int IMAGE_WIDTH = 256;
private const int HALF_WIDTH = 128;
private const int JPEG_QUALITY = 80;
private static string m_TilesStoragePath = "maptiles";
private static object m_Sync = new object();
private static bool m_Initialized = false;
private static string m_WaterTileFile = string.Empty;
private static Color m_Watercolor = Color.FromArgb(29, 71, 95);
public MapImageService(IConfigSource config)
{
if (!m_Initialized)
{
m_Initialized = true;
m_log.Debug("[MAP IMAGE SERVICE]: Starting MapImage service");
IConfig serviceConfig = config.Configs["MapImageService"];
if (serviceConfig != null)
{
m_TilesStoragePath = serviceConfig.GetString("TilesStoragePath", m_TilesStoragePath);
if (!Directory.Exists(m_TilesStoragePath))
Directory.CreateDirectory(m_TilesStoragePath);
m_WaterTileFile = Path.Combine(m_TilesStoragePath, "water.jpg");
if (!File.Exists(m_WaterTileFile))
{
Bitmap waterTile = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH);
FillImage(waterTile, m_Watercolor);
waterTile.Save(m_WaterTileFile, ImageFormat.Jpeg);
}
}
}
}
#region IMapImageService
public bool AddMapTile(int x, int y, byte[] imageData, out string reason)
{
reason = string.Empty;
string fileName = GetFileName(1, x, y);
lock (m_Sync)
{
try
{
using (FileStream f = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write))
f.Write(imageData, 0, imageData.Length);
}
catch (Exception e)
{
m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to save image file {0}: {1}", fileName, e);
reason = e.Message;
return false;
}
}
return UpdateMultiResolutionFiles(x, y, out reason);
}
public bool RemoveMapTile(int x, int y, out string reason)
{
reason = String.Empty;
string fileName = GetFileName(1, x, y);
lock (m_Sync)
{
try
{
File.Delete(fileName);
}
catch (Exception e)
{
m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to save delete file {0}: {1}", fileName, e);
reason = e.Message;
return false;
}
}
return UpdateMultiResolutionFiles(x, y, out reason);
}
private bool UpdateMultiResolutionFiles(int x, int y, out string reason)
{
reason = String.Empty;
lock (m_Sync)
{
// Stitch seven more aggregate tiles together
for (uint zoomLevel = 2; zoomLevel <= ZOOM_LEVELS; zoomLevel++)
{
// Calculate the width (in full resolution tiles) and bottom-left
// corner of the current zoom level
int width = (int)Math.Pow(2, (double)(zoomLevel - 1));
int x1 = x - (x % width);
int y1 = y - (y % width);
if (!CreateTile(zoomLevel, x1, y1))
{
m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to create tile for {0},{1} at zoom level {1}", x, y, zoomLevel);
reason = string.Format("Map tile at zoom level {0} failed", zoomLevel);
return false;
}
}
}
return true;
}
public byte[] GetMapTile(string fileName, out string format)
{
// m_log.DebugFormat("[MAP IMAGE SERVICE]: Getting map tile {0}", fileName);
format = ".jpg";
string fullName = Path.Combine(m_TilesStoragePath, fileName);
if (File.Exists(fullName))
{
format = Path.GetExtension(fileName).ToLower();
//m_log.DebugFormat("[MAP IMAGE SERVICE]: Found file {0}, extension {1}", fileName, format);
return File.ReadAllBytes(fullName);
}
else if (File.Exists(m_WaterTileFile))
{
return File.ReadAllBytes(m_WaterTileFile);
}
else
{
m_log.DebugFormat("[MAP IMAGE SERVICE]: unable to get file {0}", fileName);
return new byte[0];
}
}
#endregion
private string GetFileName(uint zoomLevel, int x, int y)
{
string extension = "jpg";
return Path.Combine(m_TilesStoragePath, string.Format("map-{0}-{1}-{2}-objects.{3}", zoomLevel, x, y, extension));
}
private Bitmap GetInputTileImage(string fileName)
{
try
{
if (File.Exists(fileName))
return new Bitmap(fileName);
}
catch (Exception e)
{
m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
}
return null;
}
private Bitmap GetOutputTileImage(string fileName)
{
try
{
if (File.Exists(fileName))
return new Bitmap(fileName);
else
{
// Create a new output tile with a transparent background
Bitmap bm = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH, PixelFormat.Format24bppRgb);
bm.MakeTransparent();
return bm;
}
}
catch (Exception e)
{
m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
}
return null;
}
private bool CreateTile(uint zoomLevel, int x, int y)
{
// m_log.DebugFormat("[MAP IMAGE SERVICE]: Create tile for {0} {1}, zoom {2}", x, y, zoomLevel);
int prevWidth = (int)Math.Pow(2, (double)zoomLevel - 2);
int thisWidth = (int)Math.Pow(2, (double)zoomLevel - 1);
// Convert x and y to the bottom left tile for this zoom level
int xIn = x - (x % prevWidth);
int yIn = y - (y % prevWidth);
// Convert x and y to the bottom left tile for the next zoom level
int xOut = x - (x % thisWidth);
int yOut = y - (y % thisWidth);
// Try to open the four input tiles from the previous zoom level
Bitmap inputBL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn));
Bitmap inputBR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn));
Bitmap inputTL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn + prevWidth));
Bitmap inputTR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn + prevWidth));
// Open the output tile (current zoom level)
string outputFile = GetFileName(zoomLevel, xOut, yOut);
Bitmap output = GetOutputTileImage(outputFile);
if (output == null)
return false;
FillImage(output, m_Watercolor);
if (inputBL != null)
{
ImageCopyResampled(output, inputBL, 0, HALF_WIDTH, 0, 0);
inputBL.Dispose();
}
if (inputBR != null)
{
ImageCopyResampled(output, inputBR, HALF_WIDTH, HALF_WIDTH, 0, 0);
inputBR.Dispose();
}
if (inputTL != null)
{
ImageCopyResampled(output, inputTL, 0, 0, 0, 0);
inputTL.Dispose();
}
if (inputTR != null)
{
ImageCopyResampled(output, inputTR, HALF_WIDTH, 0, 0, 0);
inputTR.Dispose();
}
// Write the modified output
try
{
using (Bitmap final = new Bitmap(output))
{
output.Dispose();
final.Save(outputFile, ImageFormat.Jpeg);
}
}
catch (Exception e)
{
m_log.WarnFormat("[MAP IMAGE SERVICE]: Oops on saving {0} {1}", outputFile, e);
}
// Save also as png?
return true;
}
#region Image utilities
private void FillImage(Bitmap bm, Color c)
{
for (int x = 0; x < bm.Width; x++)
for (int y = 0; y < bm.Height; y++)
bm.SetPixel(x, y, c);
}
private void ImageCopyResampled(Bitmap output, Bitmap input, int destX, int destY, int srcX, int srcY)
{
int resamplingRateX = 2; // (input.Width - srcX) / (output.Width - destX);
int resamplingRateY = 2; // (input.Height - srcY) / (output.Height - destY);
for (int x = destX; x < destX + HALF_WIDTH; x++)
for (int y = destY; y < destY + HALF_WIDTH; y++)
{
Color p = input.GetPixel(srcX + (x - destX) * resamplingRateX, srcY + (y - destY) * resamplingRateY);
output.SetPixel(x, y, p);
}
}
#endregion
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class ListRecordingSubscriptionsRequestDecoder
{
public const ushort BLOCK_LENGTH = 32;
public const ushort TEMPLATE_ID = 17;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private ListRecordingSubscriptionsRequestDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public ListRecordingSubscriptionsRequestDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public ListRecordingSubscriptionsRequestDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdId()
{
return 1;
}
public static int ControlSessionIdSinceVersion()
{
return 0;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public long ControlSessionId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int PseudoIndexId()
{
return 3;
}
public static int PseudoIndexSinceVersion()
{
return 0;
}
public static int PseudoIndexEncodingOffset()
{
return 16;
}
public static int PseudoIndexEncodingLength()
{
return 4;
}
public static string PseudoIndexMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int PseudoIndexNullValue()
{
return -2147483648;
}
public static int PseudoIndexMinValue()
{
return -2147483647;
}
public static int PseudoIndexMaxValue()
{
return 2147483647;
}
public int PseudoIndex()
{
return _buffer.GetInt(_offset + 16, ByteOrder.LittleEndian);
}
public static int SubscriptionCountId()
{
return 4;
}
public static int SubscriptionCountSinceVersion()
{
return 0;
}
public static int SubscriptionCountEncodingOffset()
{
return 20;
}
public static int SubscriptionCountEncodingLength()
{
return 4;
}
public static string SubscriptionCountMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int SubscriptionCountNullValue()
{
return -2147483648;
}
public static int SubscriptionCountMinValue()
{
return -2147483647;
}
public static int SubscriptionCountMaxValue()
{
return 2147483647;
}
public int SubscriptionCount()
{
return _buffer.GetInt(_offset + 20, ByteOrder.LittleEndian);
}
public static int ApplyStreamIdId()
{
return 5;
}
public static int ApplyStreamIdSinceVersion()
{
return 0;
}
public static int ApplyStreamIdEncodingOffset()
{
return 24;
}
public static int ApplyStreamIdEncodingLength()
{
return 4;
}
public static string ApplyStreamIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public BooleanType ApplyStreamId()
{
return (BooleanType)_buffer.GetInt(_offset + 24, ByteOrder.LittleEndian);
}
public static int StreamIdId()
{
return 6;
}
public static int StreamIdSinceVersion()
{
return 0;
}
public static int StreamIdEncodingOffset()
{
return 28;
}
public static int StreamIdEncodingLength()
{
return 4;
}
public static string StreamIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int StreamIdNullValue()
{
return -2147483648;
}
public static int StreamIdMinValue()
{
return -2147483647;
}
public static int StreamIdMaxValue()
{
return 2147483647;
}
public int StreamId()
{
return _buffer.GetInt(_offset + 28, ByteOrder.LittleEndian);
}
public static int ChannelId()
{
return 7;
}
public static int ChannelSinceVersion()
{
return 0;
}
public static string ChannelCharacterEncoding()
{
return "US-ASCII";
}
public static string ChannelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ChannelHeaderLength()
{
return 4;
}
public int ChannelLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetChannel(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetChannel(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string Channel()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[ListRecordingSubscriptionsRequest](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ControlSessionId=");
builder.Append(ControlSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='pseudoIndex', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("PseudoIndex=");
builder.Append(PseudoIndex());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='subscriptionCount', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=20, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=20, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("SubscriptionCount=");
builder.Append(SubscriptionCount());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='applyStreamId', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=BEGIN_ENUM, name='BooleanType', referencedName='null', description='Language independent boolean type.', id=-1, version=0, deprecated=0, encodedLength=4, offset=24, componentTokenCount=4, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}}
builder.Append("ApplyStreamId=");
builder.Append(ApplyStreamId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='streamId', referencedName='null', description='null', id=6, version=0, deprecated=0, encodedLength=0, offset=28, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=28, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("StreamId=");
builder.Append(StreamId());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='channel', referencedName='null', description='null', id=7, version=0, deprecated=0, encodedLength=0, offset=32, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Channel=");
builder.Append(Channel());
Limit(originalLimit);
return builder;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using QiHe.CodeLib;
namespace ExcelLibrary.CompoundDocumentFormat
{
public partial class CompoundDocument
{
private void WriteHeader()
{
this.FileStorage.Position = 0;
WriteHeader(this.Writer, this.Header);
}
private static void WriteHeader(BinaryWriter writer, FileHeader header)
{
// header size is 512 bytes
writer.Write(header.FileTypeIdentifier);
writer.Write(header.FileIdentifier.ToByteArray());
writer.Write(header.RevisionNumber);
writer.Write(header.VersionNumber);
writer.Write(header.ByteOrderMark);
writer.Write(header.SectorSizeInPot);
writer.Write(header.ShortSectorSizeInPot);
writer.Write(header.UnUsed10);
writer.Write(header.NumberOfSATSectors);
writer.Write(header.FirstSectorIDofDirectoryStream);
writer.Write(header.UnUsed4);
writer.Write(header.MinimumStreamSize);
writer.Write(header.FirstSectorIDofShortSectorAllocationTable);
writer.Write(header.NumberOfShortSectors);
writer.Write(header.FirstSectorIDofMasterSectorAllocationTable);
writer.Write(header.NumberOfMasterSectors);
WriteArrayOfInt32(writer, header.MasterSectorAllocationTable);
}
private static void WriteDirectoryEntry(BinaryWriter writer, DirectoryEntry entry)
{
writer.Write(entry.NameBuffer);
writer.Write(entry.NameDataSize);
writer.Write(entry.EntryType);
writer.Write(entry.NodeColor);
writer.Write(entry.LeftChildDID);
writer.Write(entry.RightChildDID);
writer.Write(entry.MembersTreeNodeDID);
writer.Write(entry.UniqueIdentifier.ToByteArray());
writer.Write(entry.UserFlags);
writer.Write(entry.CreationTime.ToFileTime());
writer.Write(entry.LastModificationTime.ToFileTime());
writer.Write(entry.FirstSectorID);
writer.Write(entry.StreamLength);
writer.Write(entry.UnUsed);
}
//void WriteMasterSectorAllocationTable(BinaryWriter writer)
//{
// int extraIDcount = MasterSectorAllocationTable.Count - Header.MasterSectorAllocationTable.Length;
// if (extraIDcount <= 0)
// {
// Header.FirstSectorIDofMasterSectorAllocationTable = SID.EOC;
// for (int i = 0; i < MasterSectorAllocationTable.Count; i++)
// {
// Header.MasterSectorAllocationTable[i] = MasterSectorAllocationTable[i];
// }
// }
// else
// {
// Header.FirstSectorIDofMasterSectorAllocationTable = 0;
// for (int i = 0; i < Header.MasterSectorAllocationTable.Length; i++)
// {
// Header.MasterSectorAllocationTable[i] = MasterSectorAllocationTable[i];
// }
// int sectorIDcount = SectorSize / 4 - 1;
// int sectorIndex = Header.MasterSectorAllocationTable.Length;
// int nextSectID = 1;
// while (extraIDcount > sectorIDcount)
// {
// for (int i = 0; i < sectorIDcount; i++)
// {
// writer.Write(MasterSectorAllocationTable[sectorIndex]);
// sectorIndex++;
// }
// writer.Write(nextSectID);
// nextSectID++;
// extraIDcount -= sectorIDcount;
// }
// for (int i = 0; i < extraIDcount; i++)
// {
// writer.Write(MasterSectorAllocationTable[sectorIndex]);
// sectorIndex++;
// }
// for (int i = 0; i < sectorIDcount - extraIDcount; i++)
// {
// writer.Write(-1);
// }
// writer.Write(SID.EOC);
// }
//}
public void WriteStreamData(string[] streamPath, byte[] data)
{
DirectoryEntry entry = GetOrCreateDirectoryEntry(streamPath);
entry.EntryType = EntryType.Stream;
entry.StreamLength = data.Length;
if (entry.StreamLength < Header.MinimumStreamSize)
{
if (entry.FirstSectorID == SID.EOC)
{
entry.FirstSectorID = AllocateShortSector();
}
WriteShortStreamData(entry.FirstSectorID, data);
}
else
{
if (entry.FirstSectorID == SID.EOC)
{
entry.FirstSectorID = AllocateDataSector();
}
WriteStreamData(entry.FirstSectorID, data);
}
}
internal void WriteStreamData(int startSID, byte[] data)
{
int prev_sid = SID.EOC;
int sid = startSID;
int index = 0;
while (index < data.Length)
{
if (sid == SID.EOC)
{
if (prev_sid == SID.EOC)
{
sid = this.AllocateDataSector();
}
else
{
sid = this.AllocateDataSectorAfter(prev_sid);
}
}
int offset = GetSectorOffset(sid);
Writer.BaseStream.Position = offset;
if (index + SectorSize < data.Length)
{
Writer.Write(data, index, SectorSize);
}
else
{
Writer.Write(data, index, data.Length - index);
}
index += SectorSize;
prev_sid = sid;
sid = this.SectorAllocation.GetNextSectorID(prev_sid);
}
if (sid != SID.EOC && prev_sid != SID.EOC)
{
SectorAllocation.LinkSectorID(prev_sid, SID.EOC);
while (sid != SID.EOC)
{
int next_sid = SectorAllocation.GetNextSectorID(sid);
SectorAllocation.LinkSectorID(sid, SID.Free);
sid = next_sid;
}
}
}
private void AppendStreamData(int startSID, int streamLength, byte[] data)
{
int sid = startSID;
int next_sid = SectorAllocation.GetNextSectorID(sid);
int index = 0;
while (next_sid != SID.EOC)
{
sid = next_sid;
next_sid = SectorAllocation.GetNextSectorID(sid);
index += SectorSize;
}
if (index < streamLength)
{
int position = streamLength - index;
int length = SectorSize - position;
if (data.Length <= length)
{
WriteInSector(sid, position, data, 0, data.Length);
}
else
{
WriteInSector(sid, position, data, 0, length);
next_sid = AllocateDataSectorAfter(sid);
byte[] remained_data = new byte[data.Length - length];
Array.Copy(data, length, remained_data, 0, remained_data.Length);
WriteStreamData(next_sid, remained_data);
}
}
else
{
next_sid = AllocateDataSectorAfter(sid);
WriteStreamData(next_sid, data);
}
}
internal void WriteShortStreamData(int startSID, byte[] data)
{
int prev_sid = SID.EOC;
int sid = startSID;
int index = 0;
while (index < data.Length)
{
if (sid == SID.EOC)
{
if (prev_sid == SID.EOC)
{
sid = this.ShortSectorAllocation.AllocateSector();
}
else
{
sid = this.ShortSectorAllocation.AllocateSectorAfter(prev_sid);
}
}
int offset = GetShortSectorOffset(sid);
ShortStreamContainer.Position = offset;
if (index + ShortSectorSize < data.Length)
{
ShortStreamContainer.Write(data, index, ShortSectorSize);
}
else
{
ShortStreamContainer.Write(data, index, data.Length - index);
}
index += ShortSectorSize;
prev_sid = sid;
sid = this.ShortSectorAllocation.GetNextSectorID(prev_sid);
}
if (sid != SID.EOC && prev_sid != SID.EOC)
{
ShortSectorAllocation.LinkSectorID(prev_sid, SID.EOC);
while (sid != SID.EOC)
{
int next_sid = ShortSectorAllocation.GetNextSectorID(sid);
ShortSectorAllocation.LinkSectorID(sid, SID.Free);
sid = next_sid;
}
}
}
private DirectoryEntry GetOrCreateDirectoryEntry(string[] streamPath)
{
DirectoryEntry entry = this.RootStorage;
foreach (string entryName in streamPath)
{
if (!entry.Members.ContainsKey(entryName))
{
DirectoryEntry newEntry = new DirectoryEntry(this, entryName);
newEntry.ID = this.DirectoryEntries.Count;
this.DirectoryEntries.Add(newEntry.ID, newEntry);
entry.AddChild(newEntry);
}
entry = entry.Members[entryName];
}
return entry;
}
public void DeleteDirectoryEntry(string[] streamPath)
{
DirectoryEntry entry = GetOrCreateDirectoryEntry(streamPath);
DeleteDirectoryEntry(entry);
}
public void DeleteDirectoryEntry(DirectoryEntry entry)
{
entry.EntryType = EntryType.Empty;
entry.StreamLength = 0;
entry.Parent.Members.Remove(entry.Name);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Reflection.Metadata.Cil.Decoder;
using System.Reflection.Metadata.Cil.Instructions;
using System.Reflection.Metadata.Cil.Visitor;
using System.Reflection.Metadata.Ecma335;
using System.Text;
namespace System.Reflection.Metadata.Cil
{
/// <summary>
/// Class representing a method definition in a type whithin an assembly.
/// </summary>
public struct CilMethodDefinition : ICilVisitable
{
internal CilReaders _readers;
private MethodDefinition _methodDefinition;
private CilTypeProvider _provider;
private MethodBodyBlock _methodBody;
private CilMethodImport _import;
private string _name;
private int _rva;
private MethodSignature<CilType> _signature;
private BlobReader _ilReader;
private ImmutableArray<CilInstruction> _instructions;
private CilLocal[] _locals;
private CilParameter[] _parameters;
private int _token;
private IEnumerable<CilCustomAttribute> _customAttributes;
private IEnumerable<string> _genericParameters;
private CilTypeDefinition _typeDefinition;
private int _methodDeclarationToken;
private bool _isIlReaderInitialized;
private bool _isSignatureInitialized;
private bool _isImportInitialized;
private IReadOnlyList<CilExceptionRegion> _exceptionRegions;
internal static CilMethodDefinition Create(MethodDefinition methodDefinition, int token, ref CilReaders readers, CilTypeDefinition typeDefinition)
{
CilMethodDefinition method = new CilMethodDefinition();
method._methodDefinition = methodDefinition;
method._token = token;
method._typeDefinition = typeDefinition;
method._readers = readers;
method._provider = readers.Provider;
method._rva = -1;
method._methodDeclarationToken = -1;
method._isIlReaderInitialized = false;
method._isSignatureInitialized = false;
method._isImportInitialized = false;
if(method.RelativeVirtualAddress != 0)
method._methodBody = method._readers.PEReader.GetMethodBody(method.RelativeVirtualAddress);
return method;
}
internal static CilMethodDefinition Create(MethodDefinitionHandle methodHandle, ref CilReaders readers, CilTypeDefinition typeDefinition)
{
MethodDefinition method = readers.MdReader.GetMethodDefinition(methodHandle);
int token = MetadataTokens.GetToken(methodHandle);
return Create(method, token, ref readers, typeDefinition);
}
#region Internal Properties
internal MethodBodyBlock MethodBody
{
get
{
return _methodBody;
}
}
/// <summary>
/// BlobReader that contains the msil instruction bytes.
/// </summary>
internal BlobReader IlReader
{
get
{
if (!_isIlReaderInitialized)
{
_isIlReaderInitialized = true;
_ilReader = MethodBody.GetILReader();
}
return _ilReader;
}
}
/// <summary>
/// Type provider to solve type names and references.
/// </summary>
internal CilTypeProvider Provider
{
get
{
return _provider;
}
}
#endregion
#region Public APIs
/// <summary>
/// Method name
/// </summary>
public string Name
{
get
{
return CilDecoder.GetCachedValue(_methodDefinition.Name, _readers, ref _name);
}
}
public CilTypeDefinition DeclaringType
{
get
{
return _typeDefinition;
}
}
/// <summary>
/// Method Relative Virtual Address, if is equal to 0 it is a virtual method and has no body.
/// </summary>
public int RelativeVirtualAddress
{
get
{
if(_rva == -1)
{
_rva = _methodDefinition.RelativeVirtualAddress;
}
return _rva;
}
}
/// <summary>
/// Method Token.
/// </summary>
internal int Token
{
get
{
return _token;
}
}
/// <summary>
/// Code Size in bytes not including headers.
/// </summary>
public int Size
{
get
{
return IlReader.Length;
}
}
/// <summary>
/// Method max stack capacity
/// </summary>
public int MaxStack
{
get
{
return MethodBody.MaxStack;
}
}
/// <summary>
/// Method Signature containing the return type, parameter count and header information.
/// </summary>
public MethodSignature<CilType> Signature
{
get
{
if(!_isSignatureInitialized)
{
_isSignatureInitialized = true;
_signature = CilDecoder.DecodeMethodSignature(_methodDefinition, _provider);
}
return _signature;
}
}
public bool HasImport
{
get
{
return Attributes.HasFlag(MethodAttributes.PinvokeImpl);
}
}
public CilMethodImport Import
{
get
{
if (!_isImportInitialized)
{
_isImportInitialized = true;
_import = CilMethodImport.Create(_methodDefinition.GetImport(), ref _readers, _methodDefinition);
}
return _import;
}
}
/// <summary>
/// Boolean to know if it overrides a method definition.
/// </summary>
public bool IsImplementation
{
get
{
return MethodDeclarationToken != 0;
}
}
/// <summary>
/// Boolean to know if the local variables should be initialized with the "init" prefix on its signature.
/// </summary>
public bool LocalVariablesInitialized
{
get
{
return MethodBody.LocalVariablesInitialized;
}
}
/// <summary>
/// Boolean to know if the method has a locals declared on its body.
/// </summary>
public bool HasLocals
{
get
{
return !MethodBody.LocalSignature.IsNil;
}
}
/// <summary>
/// Boolean to know if the current method is the entry point of the assembly.
/// </summary>
public bool IsEntryPoint
{
get
{
return _token == _readers.PEReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress;
}
}
/// <summary>
/// Token that represents the token of the method declaration if this method overrides any. 0 if it doesn't override a declaration.
/// </summary>
public int MethodDeclarationToken
{
get
{
if (_methodDeclarationToken == -1)
{
_methodDeclarationToken = _typeDefinition.GetOverridenMethodToken(Token);
}
return _methodDeclarationToken;
}
}
/// <summary>
/// Flags on the method (Calling convention, accesibility flags, etc.
/// </summary>
public MethodAttributes Attributes
{
get
{
return _methodDefinition.Attributes;
}
}
public MethodImplAttributes ImplAttributes
{
get
{
return _methodDefinition.ImplAttributes;
}
}
/// <summary>
/// Custom attributes declared on the method body header.
/// </summary>
public IEnumerable<CilCustomAttribute> CustomAttributes
{
get
{
if(_customAttributes == null)
{
_customAttributes = PopulateCustomAttributes();
}
return _customAttributes;
}
}
/// <summary>
/// Exception regions in the method body.
/// </summary>
public IReadOnlyList<CilExceptionRegion> ExceptionRegions
{
get
{
if(_exceptionRegions == null)
{
_exceptionRegions = CilExceptionRegion.CreateRegions(MethodBody.ExceptionRegions);
}
return _exceptionRegions;
}
}
/// <summary>
/// List of instructions that represent the method body.
/// </summary>
public ImmutableArray<CilInstruction> Instructions
{
get
{
if(_instructions == null)
{
_instructions = CilDecoder.DecodeMethodBody(this).ToImmutableArray();
}
return _instructions;
}
}
/// <summary>
/// Parameters that the method take.
/// </summary>
public CilParameter[] Parameters
{
get
{
if (_parameters == null)
{
_parameters = CilDecoder.DecodeParameters(Signature, _methodDefinition.GetParameters(), ref _readers);
}
return _parameters;
}
}
/// <summary>
/// Locals contained on the method body.
/// </summary>
public CilLocal[] Locals
{
get
{
if (_locals == null)
{
_locals = CilDecoder.DecodeLocalSignature(MethodBody, _readers.MdReader, _provider);
}
return _locals;
}
}
/// <summary>
/// Method generic parameters.
/// </summary>
public IEnumerable<string> GenericParameters
{
get
{
if(_genericParameters == null)
{
_genericParameters = CilDecoder.DecodeGenericParameters(_methodDefinition, this);
}
return _genericParameters;
}
}
/// <summary>
/// Method that given an index returns a local.
///
/// Exception:
/// IndexOutOfBoundsException if the index is greater or equal than the number of locals or less to 0.
/// </summary>
/// <param name="index">Index of the local to get</param>
/// <returns>The local in current index.</returns>
public CilLocal GetLocal(int index)
{
if(index < 0 || index >= Locals.Length)
{
throw new IndexOutOfRangeException("Index out of bounds trying to get local");
}
return Locals[index];
}
/// <summary>
/// Method that given an index returns a parameter.
///
/// Exception:
/// IndexOutOfBoundsException if the index is greater or equal than the number of locals or less to 0.
/// </summary>
/// <param name="index">Index of the parameter to get</param>
/// <returns>The local in current index.</returns>
public CilParameter GetParameter(int index)
{
if(index < 0 || index >= Parameters.Length)
{
throw new IndexOutOfRangeException("Index out of bounds trying to get parameter.");
}
return Parameters[index];
}
/// <summary>
/// Method that decodes the method signature as a string with all it's flags, return type, name and parameters.
/// </summary>
/// <returns>Returns the method signature as a string</returns>
public string GetDecodedSignature()
{
string attributes = GetAttributesForSignature();
StringBuilder signature = new StringBuilder();
if (Signature.Header.IsInstance)
{
signature.Append("instance ");
}
signature.Append(Signature.ReturnType);
return String.Format("{0}{1} {2}{3}{4} {5}", attributes, signature.ToString(), Name, GetGenericParametersString(), GetParameterListString(), GetImplementationFlags());
}
/// <summary>
/// Method that formats the Relative Virtual Address to it's hexadecimal representation.
/// </summary>
/// <returns>String representing the Relative virtual Address in hexadecimal</returns>
public string GetFormattedRva()
{
return string.Format("0x{0:x8}", RelativeVirtualAddress);
}
public void Accept(ICilVisitor visitor)
{
visitor.Visit(this);
}
#endregion
#region Private Methods
internal IEnumerable<CilParameter> GetOptionalParameters()
{
for(int i = 0; i<Parameters.Length; i++)
{
var parameter = Parameters[i];
if (parameter.IsOptional && parameter.HasDefault)
{
yield return parameter;
}
}
}
private string GetGenericParametersString()
{
int i = 0;
StringBuilder genericParameters = new StringBuilder();
foreach (var genericParameter in GenericParameters)
{
if (i == 0)
{
genericParameters.Append("<");
}
genericParameters.Append(genericParameter);
genericParameters.Append(",");
i++;
}
if (i > 0)
{
genericParameters.Length -= 1; //Delete trailing ,
genericParameters.Append(">");
}
return genericParameters.ToString();
}
private string GetParameterListString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
for(int i = 0; i < Parameters.Length; i++)
{
if(i > 0)
{
sb.Append(", ");
}
sb.Append(Parameters[i].GetParameterSignature());
}
sb.Append(")");
return sb.ToString();
}
private IEnumerable<CilCustomAttribute> PopulateCustomAttributes()
{
foreach(var handle in _methodDefinition.GetCustomAttributes())
{
var attribute = _readers.MdReader.GetCustomAttribute(handle);
yield return new CilCustomAttribute(attribute, ref _readers);
}
}
private string GetAttributesForSignature()
{
return string.Format("{0}{1}", GetAccessibilityFlags(), GetContractFlags());
}
private string GetContractFlags()
{
StringBuilder sb = new StringBuilder();
if (Attributes.HasFlag(MethodAttributes.HideBySig))
{
sb.Append("hidebysig ");
}
if (Attributes.HasFlag(MethodAttributes.Static))
{
sb.Append("static ");
}
if(Attributes.HasFlag(MethodAttributes.NewSlot))
{
sb.Append("newslot ");
}
if (Attributes.HasFlag(MethodAttributes.SpecialName))
{
sb.Append("specialname ");
}
if (Attributes.HasFlag(MethodAttributes.RTSpecialName))
{
sb.Append("rtspecialname ");
}
if (Attributes.HasFlag(MethodAttributes.Abstract))
{
sb.Append("abstract ");
}
if (Attributes.HasFlag(MethodAttributes.CheckAccessOnOverride))
{
sb.Append("strict ");
}
if (Attributes.HasFlag(MethodAttributes.Virtual))
{
sb.Append("virtual ");
}
if (Attributes.HasFlag(MethodAttributes.Final))
{
sb.Append("final ");
}
if (Attributes.HasFlag(MethodAttributes.PinvokeImpl))
{
sb.Append("pinvokeimpl(");
sb.Append(Import.GetMethodImportDeclaration());
sb.Append(") ");
}
return sb.ToString();
}
/// <summary>
/// This Method is intended to get the accessibility flags.
/// Since the enum doesn't have flags values, the smallest values (private, famANDAssem) will always return true.
/// To solve this we have to check from the greatest through the smallest and the first flag it finds that way we always find the desired value.
/// </summary>
/// <returns>
/// The accesibility flag as a string.
/// </returns>
private string GetAccessibilityFlags()
{
if (Attributes.HasFlag(MethodAttributes.Public))
{
return "public ";
}
if (Attributes.HasFlag(MethodAttributes.FamORAssem))
{
return "famorassem ";
}
if (Attributes.HasFlag(MethodAttributes.Family))
{
return "family ";
}
if (Attributes.HasFlag(MethodAttributes.Assembly))
{
return "assembly ";
}
if (Attributes.HasFlag(MethodAttributes.FamANDAssem))
{
return "famandassem ";
}
if (Attributes.HasFlag(MethodAttributes.Private))
{
return "private ";
}
return string.Empty;
}
private string GetImplementationFlags()
{
return string.Format("{0} {1}", GetCodeType(), GetCodeManagement());
}
private string GetCodeType()
{
if (ImplAttributes.HasFlag(MethodImplAttributes.Runtime))
{
return "runtime";
}
if (ImplAttributes.HasFlag(MethodImplAttributes.OPTIL))
{
return "optil";
}
if (ImplAttributes.HasFlag(MethodImplAttributes.Native))
{
return "native";
}
if (ImplAttributes.HasFlag(MethodImplAttributes.IL))
{
return "cil";
}
throw new BadImageFormatException("Invalid Code Type flag");
}
private string GetCodeManagement()
{
if (ImplAttributes.HasFlag(MethodImplAttributes.Managed))
{
return "managed";
}
if (ImplAttributes.HasFlag(MethodImplAttributes.Unmanaged))
{
return "unmanaged";
}
throw new BadImageFormatException("Invalid code management flag");
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// Thread tracks managed thread IDs, recycling them when threads die to keep the set of
// live IDs compact.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Diagnostics;
using System.Runtime;
namespace System.Threading
{
internal class ManagedThreadId
{
//
// Binary tree used to keep track of active thread ids. Each node of the tree keeps track of 32 consecutive ids.
// Implemented as immutable collection to avoid locks. Each modification creates a new top level node.
//
class ImmutableIdDispenser
{
private readonly ImmutableIdDispenser _left; // Child nodes
private readonly ImmutableIdDispenser _right;
private readonly int _used; // Number of ids tracked by this node and all its childs
private readonly int _size; // Maximum number of ids that can be tracked by this node and all its childs
private readonly uint _bitmap; // Bitmap of ids tracked by this node
private const int BitsPerNode = 32;
private ImmutableIdDispenser(ImmutableIdDispenser left, ImmutableIdDispenser right, int used, int size, uint bitmap)
{
_left = left;
_right = right;
_used = used;
_size = size;
_bitmap = bitmap;
CheckInvariants();
}
[Conditional("DEBUG")]
private void CheckInvariants()
{
int actualUsed = 0;
uint countBits = _bitmap;
while (countBits != 0)
{
actualUsed += (int)(countBits & 1);
countBits >>= 1;
}
if (_left != null)
{
Debug.Assert(_left._size == ChildSize);
actualUsed += _left._used;
}
if (_right != null)
{
Debug.Assert(_right._size == ChildSize);
actualUsed += _right._used;
}
Debug.Assert(actualUsed == _used);
Debug.Assert(_used <= _size);
}
private int ChildSize
{
get
{
Debug.Assert((_size / 2) >= (BitsPerNode / 2));
return (_size / 2) - (BitsPerNode / 2);
}
}
public static ImmutableIdDispenser Empty
{
get
{
// The empty dispenser has the id=0 allocated, so it is not really empty.
// It saves us from dealing with the corner case of true empty dispenser,
// and it ensures that ManagedThreadIdNone will not be ever given out.
return new ImmutableIdDispenser(null, null, 1, BitsPerNode, 1);
}
}
public ImmutableIdDispenser AllocateId(out int id)
{
if (_used == _size)
{
id = _size;
return new ImmutableIdDispenser(this, null, _size + 1, checked(2 * _size + BitsPerNode), 1);
}
var bitmap = _bitmap;
var left = _left;
var right = _right;
// Any free bits in current node?
if (bitmap != UInt32.MaxValue)
{
int bit = 0;
while ((bitmap & (uint)(1 << bit)) != 0)
bit++;
bitmap |= (uint)(1 << bit);
id = ChildSize + bit;
}
else
{
Debug.Assert(ChildSize > 0);
if (left == null)
{
left = new ImmutableIdDispenser(null, null, 1, ChildSize, 1);
id = left.ChildSize;
}
else
if (right == null)
{
right = new ImmutableIdDispenser(null, null, 1, ChildSize, 1);
id = ChildSize + BitsPerNode + right.ChildSize;
}
else
{
if (left._used < right._used)
{
Debug.Assert(left._used < left._size);
left = left.AllocateId(out id);
}
else
{
Debug.Assert(right._used < right._size);
right = right.AllocateId(out id);
id += (ChildSize + BitsPerNode);
}
}
}
return new ImmutableIdDispenser(left, right, _used + 1, _size, bitmap);
}
public ImmutableIdDispenser RecycleId(int id)
{
Debug.Assert(id < _size);
if (_used == 1)
return null;
var bitmap = _bitmap;
var left = _left;
var right = _right;
int childSize = ChildSize;
if (id < childSize)
{
left = left.RecycleId(id);
}
else
{
id -= childSize;
if (id < BitsPerNode)
{
Debug.Assert((bitmap & (uint)(1 << id)) != 0);
bitmap &= ~(uint)(1 << id);
}
else
{
right = right.RecycleId(id - BitsPerNode);
}
}
return new ImmutableIdDispenser(left, right, _used - 1, _size, bitmap);
}
}
[ThreadStatic]
private static ManagedThreadId t_currentThreadId;
[ThreadStatic]
private static int t_currentManagedThreadId;
// We have to avoid the static constructors on the ManagedThreadId class, otherwise we can run into stack overflow as first time Current property get called,
// the runtime will ensure running the static constructor and this process will call the Current property again (when taking any lock)
// System::Environment.get_CurrentManagedThreadId
// System::Threading::Lock.Acquire
// System::Runtime::CompilerServices::ClassConstructorRunner::Cctor.GetCctor
// System::Runtime::CompilerServices::ClassConstructorRunner.EnsureClassConstructorRun
// System::Threading::ManagedThreadId.get_Current
// System::Environment.get_CurrentManagedThreadId
private static ImmutableIdDispenser s_idDispenser;
private int _managedThreadId;
internal const int ManagedThreadIdNone = 0;
public static int Current
{
get
{
int currentManagedThreadId = t_currentManagedThreadId;
if (currentManagedThreadId == ManagedThreadIdNone)
return MakeForCurrentThread();
else
return currentManagedThreadId;
}
}
private static int MakeForCurrentThread()
{
if (s_idDispenser == null)
Interlocked.CompareExchange(ref s_idDispenser, ImmutableIdDispenser.Empty, null);
int id;
var priorIdDispenser = Volatile.Read(ref s_idDispenser);
for (;;)
{
var updatedIdDispenser = priorIdDispenser.AllocateId(out id);
var interlockedResult = Interlocked.CompareExchange(ref s_idDispenser, updatedIdDispenser, priorIdDispenser);
if (Object.ReferenceEquals(priorIdDispenser, interlockedResult))
break;
priorIdDispenser = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
Debug.Assert(id != ManagedThreadIdNone);
t_currentThreadId = new ManagedThreadId(id);
t_currentManagedThreadId = id;
return id;
}
private ManagedThreadId(int managedThreadId)
{
_managedThreadId = managedThreadId;
}
~ManagedThreadId()
{
if (RuntimeImports.RhHasShutdownStarted())
{
return;
}
if (_managedThreadId == ManagedThreadIdNone)
{
return;
}
try
{
var priorIdDispenser = Volatile.Read(ref s_idDispenser);
for (;;)
{
var updatedIdDispenser = s_idDispenser.RecycleId(_managedThreadId);
var interlockedResult = Interlocked.CompareExchange(ref s_idDispenser, updatedIdDispenser, priorIdDispenser);
if (Object.ReferenceEquals(priorIdDispenser, interlockedResult))
break;
priorIdDispenser = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
}
catch (OutOfMemoryException)
{
// Try to recycle the id next time
RuntimeImports.RhReRegisterForFinalize(this);
}
}
}
}
| |
/*
//
// INTEL CORPORATION PROPRIETARY INFORMATION
// This software is supplied under the terms of a license agreement or
// nondisclosure agreement with Intel Corporation and may not be copied
// or disclosed except in accordance with the terms of that agreement.
// Copyright(c) 2003-2012 Intel Corporation. All Rights Reserved.
//
// Intel(R) Integrated Performance Primitives Using Intel(R) IPP
// in Microsoft* C# .NET for Windows* Sample
//
// By downloading and installing this sample, you hereby agree that the
// accompanying Materials are being provided to you under the terms and
// conditions of the End User License Agreement for the Intel(R) Integrated
// Performance Primitives product previously accepted by you. Please refer
// to the file ippEULA.rtf located in the root directory of your Intel(R) IPP
// product installation for more information.
//
*/
// generated automatically on Wed Mar 31 16:13:13 2010
using System;
using System.Security;
using System.Runtime.InteropServices;
namespace ipp {
//
// enums
//
public enum IppLZ77HuffMode {
IppLZ77UseFixed = 0,
IppLZ77UseDynamic = 1,
IppLZ77UseStored = 2,
};
public enum IppLZ77Flush {
IppLZ77NoFlush = 0,
IppLZ77SyncFlush = 1,
IppLZ77FullFlush = 2,
IppLZ77FinishFlush = 3,
};
public enum IppLZ77InflateStatus {
IppLZ77InflateStatusInit = 0,
IppLZ77InflateStatusHuffProcess = 1,
IppLZ77InflateStatusLZ77Process = 2,
IppLZ77InflateStatusFinal = 3,
};
public enum IppLZOMethod {
IppLZO1XST = 0,
IppLZO1XMT = 1,
};
public enum IppBWTSortAlgorithmHint {
ippBWTItohTanakaLimSort = 0,
ippBWTItohTanakaUnlimSort = 1,
ippBWTSuffixSort = 2,
ippBWTAutoSort = 3,
};
public enum IppGITStrategyHint {
ippGITNoStrategy = 0,
ippGITLeftReorder = 1,
ippGITRightReorder = 2,
ippGITFixedOrder = 3,
};
public enum IppLZ77Chcksm {
IppLZ77NoChcksm = 0,
IppLZ77Adler32 = 1,
IppLZ77CRC32 = 2,
};
public enum IppLZ77DeflateStatus {
IppLZ77StatusInit = 0,
IppLZ77StatusLZ77Process = 1,
IppLZ77StatusHuffProcess = 2,
IppLZ77StatusFinal = 3,
};
public enum IppInflateMode {
ippTYPE = 0,
ippLEN = 1,
ippLENEXT = 2,
};
public enum IppLZ77ComprLevel {
IppLZ77FastCompr = 0,
IppLZ77AverageCompr = 1,
IppLZ77BestCompr = 2,
};
//
// hidden or own structures
//
[StructLayout(LayoutKind.Sequential)] public struct IppDecodeHuffState_BZ2 {};
[StructLayout(LayoutKind.Sequential)] public struct IppEncodeHuffState_BZ2 {};
[StructLayout(LayoutKind.Sequential)] public struct IppGITState_8u {};
[StructLayout(LayoutKind.Sequential)] public struct IppHuffState_8u {};
[StructLayout(LayoutKind.Sequential)] public struct IppLZ77State_8u {};
[StructLayout(LayoutKind.Sequential)] public struct IppLZOState_8u {};
[StructLayout(LayoutKind.Sequential)] public struct IppLZSSState_8u {};
[StructLayout(LayoutKind.Sequential)] public struct IppMTFState_8u {};
[StructLayout(LayoutKind.Sequential)] public struct IppRLEState_BZ2 {};
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)] public struct IppDeflateHuffCode {
public ushort code;
public ushort len;
public IppDeflateHuffCode ( ushort code, ushort len ) {
this.code = code;
this.len = len;
}};
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)] public struct IppsVLCTable_32s {
public int value;
public int code;
public int length;
public IppsVLCTable_32s ( int value, int code, int length ) {
this.value = value;
this.code = code;
this.length = length;
}};
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)] public struct IppLZ77Pair {
public ushort length;
public ushort offset;
public IppLZ77Pair ( ushort length, ushort offset ) {
this.length = length;
this.offset = offset;
}};
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)] unsafe public struct IppInflateState {
public byte* pWindow;
public uint winSize;
public uint tableType;
public uint tableBufferSize;
public IppInflateState ( byte* pWindow, uint winSize, uint tableType, uint tableBufferSize ) {
this.pWindow = pWindow;
this.winSize = winSize;
this.tableType = tableType;
this.tableBufferSize = tableBufferSize;
}};
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)] public struct IppDeflateFreqTable {
public ushort freq;
public ushort code;
public IppDeflateFreqTable ( ushort freq, ushort code ) {
this.freq = freq;
this.code = code;
}};
unsafe public class dc {
internal const string libname = "ippdc.dll";
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname,EntryPoint="ippdcGetLibVersion")] public static extern
int* xippdcGetLibVersion ( );
public static IppLibraryVersion ippdcGetLibVersion() {
return new IppLibraryVersion( xippdcGetLibVersion() );
}
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsAdler32_8u ( byte *pSrc, int srcLen, uint *pAdler32 );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsBWTFwdGetBufSize_SelectSort_8u ( uint wndSize, uint *pBWTFwdBufSize, IppBWTSortAlgorithmHint sortAlgorithmHint );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsBWTFwdGetSize_8u ( int wndSize, int *pBWTFwdBuffSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsBWTFwd_8u ( byte *pSrc, byte *pDst, int len, int *index, byte *pBWTFwdBuff );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsBWTFwd_SelectSort_8u ( byte *pSrc, byte *pDst, uint len, uint *index, byte *pBWTFwdBuf, IppBWTSortAlgorithmHint sortAlgorithmHint );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsBWTFwd_SmallBlock_8u ( byte *pSrc, byte *pDst, int len, int *index, byte *pBWTBuff );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsBWTGetSize_SmallBlock_8u ( int wndSize, int *pBuffSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsBWTInvGetSize_8u ( int wndSize, int *pBWTInvBuffSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsBWTInv_8u ( byte *pSrc, byte *pDst, int len, int index, byte *pBWTInvBuff );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsBWTInv_SmallBlock_8u ( byte *pSrc, byte *pDst, int len, int index, byte *pBWTBuff );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsCRC32C_8u ( byte *pSrc, uint srcLen, uint *pCRC32C );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsCRC32_8u ( byte *pSrc, int srcLen, uint *pCRC32 );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsCRC32_BZ2_8u ( byte *pSrc, int srcLen, uint *pCRC32 );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeBlockGetSize_BZ2_8u ( int blockSize, int *pBuffSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeBlock_BZ2_16u8u ( ushort *pSrc, int srcLen, byte *pDst, int *pDstLen, int index, int dictSize, byte *inUse, byte *pBuff );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeGITGetSize_8u ( int maxSrcLen, int *pGITStateSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeGITInitAlloc_8u ( int maxSrcLen, int maxDstLen, IppGITState_8u **ppGITState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeGITInit_8u ( int maxDstLen, IppGITState_8u *pGITState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeGIT_8u ( byte *pSrc, int srcLen, byte *pDst, int *pDstLen, IppGITStrategyHint strategyHint, IppGITState_8u *pGITState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
void ippsDecodeHuffFree_BZ2_8u16u ( IppDecodeHuffState_BZ2 *pDecodeHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeHuffGetSize_BZ2_8u16u ( int wndSize, int *pDecodeHuffStateSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeHuffInitAlloc_8u ( int *codeLenTable, IppHuffState_8u **ppHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeHuffInitAlloc_BZ2_8u16u ( int wndSize, int sizeDictionary, IppDecodeHuffState_BZ2 **ppDecodeHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeHuffInit_8u ( int *codeLenTable, IppHuffState_8u *pHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeHuffInit_BZ2_8u16u ( int sizeDictionary, IppDecodeHuffState_BZ2 *pDecodeHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeHuffOne_8u ( byte *pSrc, int srcOffsetBits, byte *pDst, IppHuffState_8u *pHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeHuff_8u ( byte *pSrc, int srcLen, byte *pDst, int *pDstLen, IppHuffState_8u *pHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeHuff_BZ2_8u16u ( uint *pCode, int *pCodeLenBits, byte **ppSrc, int *pSrcLen, ushort *pDst, int *pDstLen, IppDecodeHuffState_BZ2 *pDecodeHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77CopyState_8u ( IppLZ77State_8u *pLZ77StateSrc, IppLZ77State_8u *pLZ77StateDst );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77DynamicHuffFull_8u ( byte **ppSrc, int *pSrcLen, byte **ppDst, int *pDstLen, IppLZ77Flush flush, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77DynamicHuff_8u ( byte **ppSrc, int *pSrcLen, IppLZ77Pair **ppDst, int *pDstLen, IppLZ77Flush flush, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77FixedHuffFull_8u ( byte **ppSrc, int *pSrcLen, byte **ppDst, int *pDstLen, IppLZ77Flush flush, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77FixedHuff_8u ( byte **ppSrc, int *pSrcLen, IppLZ77Pair **ppDst, int *pDstLen, IppLZ77Flush flush, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77GetBlockType_8u ( byte **ppSrc, int *pSrcLen, IppLZ77HuffMode *pHuffMode, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77GetPairs_8u ( IppLZ77Pair **ppPairs, int *pPairsInd, int *pPairsLen, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77GetSize_8u ( int *pLZ77StateSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77GetStatus_8u ( IppLZ77InflateStatus *pInflateStatus, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77InitAlloc_8u ( IppLZ77Chcksm checksum, IppLZ77State_8u **ppLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77Init_8u ( IppLZ77Chcksm checksum, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77Reset_8u ( IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77SetDictionary_8u ( byte *pDictionary, int dictLen, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77SetPairs_8u ( IppLZ77Pair *pPairs, int pairsInd, int pairsLen, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77SetStatus_8u ( IppLZ77InflateStatus inflateStatus, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77StoredBlock_8u ( byte **ppSrc, int *pSrcLen, byte **ppDst, int *pDstLen, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77StoredHuff_8u ( byte **ppSrc, int *pSrcLen, IppLZ77Pair **ppDst, int *pDstLen, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZ77_8u ( IppLZ77Pair **ppSrc, int *pSrcLen, byte **ppDst, int *pDstLen, IppLZ77Flush flush, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZOSafe_8u ( byte *pSrc, uint srcLen, byte *pDst, uint *pDstLen );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZO_8u ( byte *pSrc, uint srcLen, byte *pDst, uint *pDstLen );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZSSInitAlloc_8u ( IppLZSSState_8u **ppLZSSState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZSSInit_8u ( IppLZSSState_8u *pLZSSState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeLZSS_8u ( byte **ppSrc, int *pSrcLen, byte **ppDst, int *pDstLen, IppLZSSState_8u *pLZSSState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeRLEStateFlush_BZ2_8u ( IppRLEState_BZ2 *pRLEState, byte **ppDst, uint *pDstLen );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeRLEStateInit_BZ2_8u ( IppRLEState_BZ2 *pRLEState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeRLEState_BZ2_8u ( byte **ppSrc, uint *pSrcLen, byte **ppDst, uint *pDstLen, IppRLEState_BZ2 *pRLEState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeRLE_8u ( byte **ppSrc, int *pSrcLen, byte *pDst, int *pDstLen );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeRLE_BZ2_8u ( byte **ppSrc, int *pSrcLen, byte *pDst, int *pDstLen );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDecodeZ1Z2_BZ2_16u8u ( ushort **ppSrc, int *pSrcLen, byte *pDst, int *pDstLen );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDeflateDictionarySet_8u ( byte *pDictSrc, uint dictLen, int *pHashHeadDst, uint hashSize, int *pHashPrevDst, byte *pWindowDst, uint winSize, int comprLevel );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDeflateHuff_8u ( byte *pLitSrc, ushort *pDistSrc, uint srcLen, ushort *pCode, uint *pCodeLenBits, IppDeflateHuffCode *pLitHuffCodes, IppDeflateHuffCode *pDistHuffCodes, byte *pDst, uint *pDstIdx );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDeflateLZ77_8u ( byte **ppSrc, uint *pSrcLen, uint *pSrcIdx, byte *pWindow, uint winSize, int *pHashHead, int *pHashPrev, uint hashSize, IppDeflateFreqTable *pLitFreqTable, IppDeflateFreqTable *pDistFreqTable, byte *pLitDst, ushort *pDistDst, uint *pDstLen, int comprLevel, IppLZ77Flush flush );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsDeflateUpdateHash_8u ( byte *pSrc, uint srcIdx, uint srcLen, int *pHashHeadDst, uint hashSize, int *pHashPrevDst, uint winSize, int comprLevel );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeGITGetSize_8u ( int maxSrcLen, int maxDstLen, int *pGITStateSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeGITInitAlloc_8u ( int maxSrcLen, int maxDstLen, IppGITState_8u **ppGITState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeGITInit_8u ( int maxSrcLen, int maxDstLen, IppGITState_8u *ppGITState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeGIT_8u ( byte *pSrc, int srcLen, byte *pDst, int *pDstLen, IppGITStrategyHint strategyHint, IppGITState_8u *pGITState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeHuffFinal_8u ( byte *pDst, int *pDstLen, IppHuffState_8u *pHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
void ippsEncodeHuffFree_BZ2_16u8u ( IppEncodeHuffState_BZ2 *pEncodeHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeHuffGetSize_BZ2_16u8u ( int wndSize, int *pEncodeHuffStateSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeHuffInitAlloc_8u ( int *freqTable, IppHuffState_8u **ppHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeHuffInitAlloc_BZ2_16u8u ( int wndSize, int sizeDictionary, int *freqTable, ushort *pSrc, int srcLen, IppEncodeHuffState_BZ2 **ppEncodeHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeHuffInit_8u ( int *freqTable, IppHuffState_8u *pHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeHuffInit_BZ2_16u8u ( int sizeDictionary, int *freqTable, ushort *pSrc, int srcLen, IppEncodeHuffState_BZ2 *pEncodeHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeHuffOne_8u ( byte src, byte *pDst, int dstOffsetBits, IppHuffState_8u *pHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeHuff_8u ( byte *pSrc, int srcLen, byte *pDst, int *pDstLen, IppHuffState_8u *pHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeHuff_BZ2_16u8u ( uint *pCode, int *pCodeLenBits, ushort **ppSrc, int *pSrcLen, byte *pDst, int *pDstLen, IppEncodeHuffState_BZ2 *pEncodeHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77DynamicHuff_8u ( IppLZ77Pair **ppSrc, int *pSrcLen, byte **ppDst, int *pDstLen, IppLZ77Flush flush, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77FixedHuff_8u ( IppLZ77Pair **ppSrc, int *pSrcLen, byte **ppDst, int *pDstLen, IppLZ77Flush flush, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77Flush_8u ( byte **ppDst, int *pDstLen, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77GetPairs_8u ( IppLZ77Pair **ppPairs, int *pPairsInd, int *pPairsLen, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77GetSize_8u ( int *pLZ77StateSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77GetStatus_8u ( IppLZ77DeflateStatus *pDeflateStatus, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77InitAlloc_8u ( IppLZ77ComprLevel comprLevel, IppLZ77Chcksm checksum, IppLZ77State_8u **ppLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77Init_8u ( IppLZ77ComprLevel comprLevel, IppLZ77Chcksm checksum, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77Reset_8u ( IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77SelectHuffMode_8u ( IppLZ77Pair *pSrc, int srcLen, IppLZ77HuffMode *pHuffMode, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77SetDictionary_8u ( byte *pDictionary, int dictLen, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77SetPairs_8u ( IppLZ77Pair *pPairs, int pairsInd, int pairsLen, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77SetStatus_8u ( IppLZ77DeflateStatus deflateStatus, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77StoredBlock_8u ( byte **ppSrc, int *pSrcLen, byte **ppDst, int *pDstLen, IppLZ77Flush flush, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZ77_8u ( byte **ppSrc, int *pSrcLen, IppLZ77Pair **ppDst, int *pDstLen, IppLZ77Flush flush, IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZOGetSize ( IppLZOMethod method, uint maxInputLen, uint *pSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZOInit_8u ( IppLZOMethod method, uint maxInputLen, IppLZOState_8u *pLZOState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZO_8u ( byte *pSrc, uint srcLen, byte *pDst, uint *pDstLen, IppLZOState_8u *pLZOState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZSSFlush_8u ( byte **ppDst, int *pDstLen, IppLZSSState_8u *pLZSSState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZSSInitAlloc_8u ( IppLZSSState_8u **ppLZSSState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZSSInit_8u ( IppLZSSState_8u *pLZSSState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeLZSS_8u ( byte **ppSrc, int *pSrcLen, byte **ppDst, int *pDstLen, IppLZSSState_8u *pLZSSState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeRLEFlush_BZ2_8u ( byte *pDst, int *pDstLen, IppRLEState_BZ2 *pRLEState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeRLEInitAlloc_BZ2_8u ( IppRLEState_BZ2 **ppRLEState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeRLEInit_BZ2_8u ( IppRLEState_BZ2 *pRLEState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeRLE_8u ( byte **ppSrc, int *pSrcLen, byte *pDst, int *pDstLen );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeRLE_BZ2_8u ( byte **ppSrc, int *pSrcLen, byte *pDst, int *pDstLen, IppRLEState_BZ2 *pRLEState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsEncodeZ1Z2_BZ2_8u16u ( byte **ppSrc, int *pSrcLen, ushort *pDst, int *pDstLen, int *freqTable );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsExpandDictionary_8u_I ( byte *inUse, byte *pSrcDst, int srcDstLen, int sizeDictionary );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
void ippsGITFree_8u ( IppGITState_8u *pGITState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
void ippsHuffFree_8u ( IppHuffState_8u *pHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsHuffGetDstBuffSize_8u ( int *codeLenTable, int srcLen, int *pEncDstBuffSize, int *pDecDstBuffSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsHuffGetLenCodeTable_8u ( int *codeLenTable, IppHuffState_8u *pHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsHuffGetSize_8u ( int *pHuffStateSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsHuffLenCodeTablePack_8u ( int *codeLenTable, byte *pDst, int *pDstLen );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsHuffLenCodeTableUnpack_8u ( byte *pSrc, int *pSrcLen, int *codeLenTable );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsInflateBuildHuffTable ( ushort *pCodeLens, uint nLitCodeLens, uint nDistCodeLens, IppInflateState *pIppInflateState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsInflate_8u ( byte **ppSrc, uint *pSrcLen, uint *pCode, uint *pCodeLenBits, uint winIdx, byte **ppDst, uint *pDstLen, uint dstIdx, IppInflateMode *pMode, IppInflateState *pIppInflateState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
void ippsLZ77Free_8u ( IppLZ77State_8u *pLZ77State );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
void ippsLZSSFree_8u ( IppLZSSState_8u *pLZSSState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsLZSSGetSize_8u ( int *pLZSSStateSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
void ippsMTFFree_8u ( IppMTFState_8u *pMTFState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsMTFFwd_8u ( byte *pSrc, byte *pDst, int len, IppMTFState_8u *pMTFState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsMTFGetSize_8u ( int *pMTFStateSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsMTFInitAlloc_8u ( IppMTFState_8u **ppMTFState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsMTFInit_8u ( IppMTFState_8u *pMTFState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsMTFInv_8u ( byte *pSrc, byte *pDst, int len, IppMTFState_8u *pMTFState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsPackHuffContext_BZ2_16u8u ( uint *pCode, int *pCodeLenBits, byte *pDst, int *pDstLen, IppEncodeHuffState_BZ2 *pEncodeHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
void ippsRLEFree_BZ2_8u ( IppRLEState_BZ2 *pRLEState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsRLEGetInUseTable_8u ( byte *inUse, IppRLEState_BZ2 *pRLEState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsRLEGetSize_BZ2_8u ( int *pRLEStateSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsReduceDictionary_8u_I ( byte *inUse, byte *pSrcDst, int srcDstLen, int *pSizeDictionary );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsUnpackHuffContext_BZ2_8u16u ( uint *pCode, int *pCodeLenBits, byte **ppSrc, int *pSrcLen, IppDecodeHuffState_BZ2 *pDecodeHuffState );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCCountBits_16s32s ( short *pSrc, int srcLen, int *pCountBits, IppsVLCEncodeSpec_32s *pVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCDecodeBlock_1u16s ( byte **ppSrc, int *pSrcBitsOffset, short *pDst, int dstLen, IppsVLCDecodeSpec_32s *pVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
void ippsVLCDecodeFree_32s ( IppsVLCDecodeSpec_32s *pVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCDecodeGetSize_32s ( IppsVLCTable_32s *pInputTable, int inputTableSize, int *pSubTablesSizes, int numSubTables, int *pSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCDecodeInitAlloc_32s ( IppsVLCTable_32s *pInputTable, int inputTableSize, int *pSubTablesSizes, int numSubTables, IppsVLCDecodeSpec_32s **ppVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCDecodeInit_32s ( IppsVLCTable_32s *pInputTable, int inputTableSize, int *pSubTablesSizes, int numSubTables, IppsVLCDecodeSpec_32s *pVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCDecodeOne_1u16s ( byte **ppSrc, int *pSrcBitsOffset, short *pDst, IppsVLCDecodeSpec_32s *pVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCDecodeUTupleBlock_1u16s ( byte **ppSrc, int *pSrcBitsOffset, short *pDst, int dstLen, IppsVLCDecodeUTupleSpec_32s *pVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
void ippsVLCDecodeUTupleFree_32s ( IppsVLCDecodeUTupleSpec_32s *pVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCDecodeUTupleGetSize_32s ( IppsVLCTable_32s *pInputTable, int inputTableSize, int *pSubTablesSizes, int numSubTables, int numElements, int numValueBit, int *pSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCDecodeUTupleInitAlloc_32s ( IppsVLCTable_32s *pInputTable, int inputTableSize, int *pSubTablesSizes, int numSubTables, int numElements, int numValueBit, IppsVLCDecodeUTupleSpec_32s **ppVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCDecodeUTupleInit_32s ( IppsVLCTable_32s *pInputTable, int inputTableSize, int *pSubTablesSizes, int numSubTables, int numElements, int numValueBit, IppsVLCDecodeUTupleSpec_32s *pVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCDecodeUTupleOne_1u16s ( byte **ppSrc, int *pSrcBitsOffset, short *pDst, IppsVLCDecodeUTupleSpec_32s *pVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCEncodeBlock_16s1u ( short *pSrc, int srcLen, byte **ppDst, int *pDstBitsOffset, IppsVLCEncodeSpec_32s *pVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
void ippsVLCEncodeFree_32s ( IppsVLCEncodeSpec_32s *pVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCEncodeGetSize_32s ( IppsVLCTable_32s *pInputTable, int inputTableSize, int *pSize );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCEncodeInitAlloc_32s ( IppsVLCTable_32s *pInputTable, int inputTableSize, IppsVLCEncodeSpec_32s **ppVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCEncodeInit_32s ( IppsVLCTable_32s *pInputTable, int inputTableSize, IppsVLCEncodeSpec_32s *pVLCSpec );
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(ipp.dc.libname)] public static extern
IppStatus ippsVLCEncodeOne_16s1u ( short src, byte **pDst, int *pDstBitsOffset, IppsVLCEncodeSpec_32s *pVLCSpec );
};
};
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.Framework.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OmniSharp.Models;
using OmniSharp.Options;
using OmniSharp.Services;
namespace OmniSharp.Dnx
{
public class DnxPaths
{
private readonly IOmnisharpEnvironment _env;
private readonly OmniSharpOptions _options;
private readonly ILogger _logger;
public DnxRuntimePathResult RuntimePath { get; private set; }
public string Dnx { get; private set; }
public string Dnu { get; private set; }
public string Klr { get; private set; }
public string Kpm { get; private set; }
public string K { get; private set; }
public DnxPaths(IOmnisharpEnvironment env,
OmniSharpOptions options,
ILoggerFactory loggerFactory)
{
_env = env;
_options = options;
_logger = loggerFactory.CreateLogger<DnxPaths>();
RuntimePath = GetRuntimePath();
Dnx = FirstPath(RuntimePath.Value, "dnx", "dnx.exe");
Dnu = FirstPath(RuntimePath.Value, "dnu", "dnu.cmd");
Klr = FirstPath(RuntimePath.Value, "klr", "klr.exe");
Kpm = FirstPath(RuntimePath.Value, "kpm", "kpm.cmd");
K = FirstPath(RuntimePath.Value, "k", "k.cmd");
}
private DnxRuntimePathResult GetRuntimePath()
{
var root = ResolveRootDirectory(_env.Path);
var globalJson = Path.Combine(root, "global.json");
var versionOrAliasToken = GetRuntimeVersionOrAlias(globalJson);
var versionOrAlias = versionOrAliasToken?.Value<string>() ?? _options.Dnx.Alias ?? "default";
var seachedLocations = new List<string>();
foreach (var location in GetRuntimeLocations())
{
// Need to expand variables, because DNX_HOME variable might include %USERPROFILE%.
var paths = GetRuntimePathsFromVersionOrAlias(versionOrAlias, Environment.ExpandEnvironmentVariables(location));
foreach (var path in paths)
{
if (string.IsNullOrEmpty(path))
{
continue;
}
if (Directory.Exists(path))
{
_logger.LogInformation(string.Format("Using runtime '{0}'.", path));
return new DnxRuntimePathResult()
{
Value = path
};
}
seachedLocations.Add(path);
}
}
var message = new ErrorMessage()
{
Text = string.Format("The specified runtime path '{0}' does not exist. Searched locations {1}.\nVisit https://github.com/aspnet/Home/tree/glennc/readmelove for an installation guide.", versionOrAlias, string.Join("\n", seachedLocations))
};
if (versionOrAliasToken != null)
{
message.FileName = globalJson;
message.Line = ((IJsonLineInfo)versionOrAliasToken).LineNumber;
message.Column = ((IJsonLineInfo)versionOrAliasToken).LinePosition;
}
_logger.LogError(message.Text);
return new DnxRuntimePathResult()
{
Error = message
};
}
private JToken GetRuntimeVersionOrAlias(string globalJson)
{
if (File.Exists(globalJson))
{
_logger.LogInformation("Looking for sdk version in '{0}'.", globalJson);
using (var stream = File.OpenRead(globalJson))
{
var obj = JObject.Load(new JsonTextReader(new StreamReader(stream)));
return obj["sdk"]?["version"];
}
}
return null;
}
private static string ResolveRootDirectory(string projectPath)
{
var di = new DirectoryInfo(projectPath);
while (di.Parent != null)
{
if (di.EnumerateFiles("global.json").Any())
{
return di.FullName;
}
di = di.Parent;
}
// If we don't find any files then make the project folder the root
return projectPath;
}
private IEnumerable<string> GetRuntimeLocations()
{
yield return Environment.GetEnvironmentVariable("DNX_HOME") ?? string.Empty;
yield return Environment.GetEnvironmentVariable("KRE_HOME") ?? string.Empty;
// %HOME% and %USERPROFILE% might point to different places.
foreach (var home in new string[] { Environment.GetEnvironmentVariable("HOME"), Environment.GetEnvironmentVariable("USERPROFILE") }.Where(s => !string.IsNullOrEmpty(s)))
{
// Newer path
yield return Path.Combine(home, ".dnx");
// New path
yield return Path.Combine(home, ".k");
// Old path
yield return Path.Combine(home, ".kre");
}
}
private IEnumerable<string> GetRuntimePathsFromVersionOrAlias(string versionOrAlias, string runtimePath)
{
// Newer format
yield return GetRuntimePathFromVersionOrAlias(versionOrAlias, runtimePath, ".dnx", "dnx-mono.{0}", "dnx-clr-win-x86.{0}", "runtimes");
// New format
yield return GetRuntimePathFromVersionOrAlias(versionOrAlias, runtimePath, ".k", "kre-mono.{0}", "kre-clr-win-x86.{0}", "runtimes");
// Old format
yield return GetRuntimePathFromVersionOrAlias(versionOrAlias, runtimePath, ".kre", "KRE-Mono.{0}", "KRE-CLR-x86.{0}", "packages");
}
private string GetRuntimePathFromVersionOrAlias(string versionOrAlias,
string runtimeHome,
string sdkFolder,
string monoFormat,
string windowsFormat,
string runtimeFolder)
{
if (string.IsNullOrEmpty(runtimeHome))
{
return null;
}
var aliasDirectory = Path.Combine(runtimeHome, "alias");
var aliasFiles = new[] { "{0}.alias", "{0}.txt" };
// Check alias first
foreach (var shortAliasFile in aliasFiles)
{
var aliasFile = Path.Combine(aliasDirectory, string.Format(shortAliasFile, versionOrAlias));
if (File.Exists(aliasFile))
{
var fullName = File.ReadAllText(aliasFile).Trim();
return Path.Combine(runtimeHome, runtimeFolder, fullName);
}
}
// There was no alias, look for the input as a version
var version = versionOrAlias;
if (PlatformHelper.IsMono)
{
return Path.Combine(runtimeHome, runtimeFolder, string.Format(monoFormat, versionOrAlias));
}
else
{
return Path.Combine(runtimeHome, runtimeFolder, string.Format(windowsFormat, versionOrAlias));
}
}
private static string FirstPath(string runtimePath, params string[] candidates)
{
if (runtimePath == null)
{
return null;
}
return candidates
.Select(candidate => Path.Combine(runtimePath, "bin", candidate))
.FirstOrDefault(File.Exists);
}
}
}
| |
// Ami Bar
// amibar@gmail.com
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace Amib.Threading.Internal
{
#region WorkItem Delegate
/// <summary>
/// An internal delegate to call when the WorkItem starts or completes
/// </summary>
internal delegate void WorkItemStateCallback(WorkItem workItem);
#endregion
#region IInternalWorkItemResult interface
public class CanceledWorkItemsGroup
{
public static readonly CanceledWorkItemsGroup NotCanceledWorkItemsGroup = new CanceledWorkItemsGroup();
public bool IsCanceled { get; set; }
}
internal interface IInternalWorkItemResult
{
event WorkItemStateCallback OnWorkItemStarted;
event WorkItemStateCallback OnWorkItemCompleted;
}
#endregion
#region IWorkItem interface
public interface IWorkItem
{
}
#endregion
#region WorkItem class
/// <summary>
/// Holds a callback delegate and the state for that delegate.
/// </summary>
public class WorkItem : IHasWorkItemPriority, IWorkItem
{
#region WorkItemState enum
/// <summary>
/// Indicates the state of the work item in the thread pool
/// </summary>
private enum WorkItemState
{
InQueue,
InProgress,
Completed,
Canceled,
}
#endregion
#region Member Variables
public Thread currentThread;
/// <summary>
/// Callback delegate for the callback.
/// </summary>
private readonly WorkItemCallback _callback;
/// <summary>
/// State with which to call the callback delegate.
/// </summary>
private object _state;
/// <summary>
/// Stores the caller's context
/// </summary>
private readonly CallerThreadContext _callerContext;
/// <summary>
/// Holds the result of the mehtod
/// </summary>
private object _result;
/// <summary>
/// Hold the exception if the method threw it
/// </summary>
private Exception _exception;
/// <summary>
/// Hold the state of the work item
/// </summary>
private WorkItemState _workItemState;
/// <summary>
/// A ManualResetEvent to indicate that the result is ready
/// </summary>
private ManualResetEvent _workItemCompleted;
/// <summary>
/// A reference count to the _workItemCompleted.
/// When it reaches to zero _workItemCompleted is Closed
/// </summary>
private int _workItemCompletedRefCount;
/// <summary>
/// Represents the result state of the work item
/// </summary>
private readonly WorkItemResult _workItemResult;
/// <summary>
/// Work item info
/// </summary>
private readonly WorkItemInfo _workItemInfo;
#pragma warning disable 67
/// <summary>
/// Called when the WorkItem starts
/// </summary>
private event WorkItemStateCallback _workItemStartedEvent;
/// <summary>
/// Called when the WorkItem completes
/// </summary>
private event WorkItemStateCallback _workItemCompletedEvent;
#pragma warning restore 67
/// <summary>
/// A reference to an object that indicates whatever the
/// WorkItemsGroup has been canceled
/// </summary>
private CanceledWorkItemsGroup _canceledWorkItemsGroup = CanceledWorkItemsGroup.NotCanceledWorkItemsGroup;
/// <summary>
/// The work item group this work item belong to.
/// </summary>
private readonly IWorkItemsGroup _workItemsGroup;
#region Performance Counter fields
/// <summary>
/// The time when the work items is queued.
/// Used with the performance counter.
/// </summary>
private DateTime _queuedTime;
/// <summary>
/// The time when the work items starts its execution.
/// Used with the performance counter.
/// </summary>
private DateTime _beginProcessTime;
/// <summary>
/// The time when the work items ends its execution.
/// Used with the performance counter.
/// </summary>
private DateTime _endProcessTime;
#endregion
#endregion
#region Properties
public TimeSpan WaitingTime
{
get { return (_beginProcessTime - _queuedTime); }
}
public TimeSpan ProcessTime
{
get { return (_endProcessTime - _beginProcessTime); }
}
#endregion
#region Construction
/// <summary>
/// Initialize the callback holding object.
/// </summary>
/// <param name = "callback">Callback delegate for the callback.</param>
/// <param name = "state">State with which to call the callback delegate.</param>
/// We assume that the WorkItem object is created within the thread
/// that meant to run the callback
public WorkItem(
IWorkItemsGroup workItemsGroup,
WorkItemInfo workItemInfo,
WorkItemCallback callback,
object state)
{
_workItemsGroup = workItemsGroup;
_workItemInfo = workItemInfo;
if (_workItemInfo.UseCallerCallContext || _workItemInfo.UseCallerHttpContext)
{
_callerContext = CallerThreadContext.Capture(_workItemInfo.UseCallerCallContext,
_workItemInfo.UseCallerHttpContext);
}
_callback = callback;
_state = state;
_workItemResult = new WorkItemResult(this);
Initialize();
}
internal void Initialize()
{
_workItemState = WorkItemState.InQueue;
_workItemCompleted = null;
_workItemCompletedRefCount = 0;
}
internal bool WasQueuedBy(IWorkItemsGroup workItemsGroup)
{
return (workItemsGroup == _workItemsGroup);
}
#endregion
#region Methods
public CanceledWorkItemsGroup CanceledWorkItemsGroup
{
get { return _canceledWorkItemsGroup; }
set { _canceledWorkItemsGroup = value; }
}
/// <summary>
/// Change the state of the work item to in progress if it wasn't canceled.
/// </summary>
/// <returns>
/// Return true on success or false in case the work item was canceled.
/// If the work item needs to run a post execute then the method will return true.
/// </returns>
public bool StartingWorkItem()
{
_beginProcessTime = DateTime.Now;
lock (this)
{
if (IsCanceled)
{
bool result = false;
if ((_workItemInfo.PostExecuteWorkItemCallback != null) &&
((_workItemInfo.CallToPostExecute & CallToPostExecute.WhenWorkItemCanceled) ==
CallToPostExecute.WhenWorkItemCanceled))
{
result = true;
}
return result;
}
Debug.Assert(WorkItemState.InQueue == GetWorkItemState());
SetWorkItemState(WorkItemState.InProgress);
}
return true;
}
/// <summary>
/// Execute the work item and the post execute
/// </summary>
public void Execute()
{
CallToPostExecute currentCallToPostExecute = 0;
// Execute the work item if we are in the correct state
switch (GetWorkItemState())
{
case WorkItemState.InProgress:
currentCallToPostExecute |= CallToPostExecute.WhenWorkItemNotCanceled;
ExecuteWorkItem();
break;
case WorkItemState.Canceled:
currentCallToPostExecute |= CallToPostExecute.WhenWorkItemCanceled;
break;
default:
Debug.Assert(false);
throw new NotSupportedException();
}
// Run the post execute as needed
if ((currentCallToPostExecute & _workItemInfo.CallToPostExecute) != 0)
{
PostExecute();
}
_endProcessTime = DateTime.Now;
}
internal void FireWorkItemCompleted()
{
try
{
if (null != _workItemCompletedEvent)
{
_workItemCompletedEvent(this);
}
}
catch // Ignore exceptions
{
}
}
/// <summary>
/// Execute the work item
/// </summary>
private void ExecuteWorkItem()
{
CallerThreadContext ctc = null;
if (null != _callerContext)
{
ctc = CallerThreadContext.Capture(_callerContext.CapturedCallContext, _callerContext.CapturedHttpContext);
CallerThreadContext.Apply(_callerContext);
}
Exception exception = null;
object result = null;
try
{
result = _callback(_state);
}
catch (Exception e)
{
// Save the exception so we can rethrow it later
exception = e;
}
if (null != _callerContext)
{
CallerThreadContext.Apply(ctc);
}
SetResult(result, exception);
}
/// <summary>
/// Runs the post execute callback
/// </summary>
private void PostExecute()
{
if (null != _workItemInfo.PostExecuteWorkItemCallback)
{
try
{
_workItemInfo.PostExecuteWorkItemCallback(this._workItemResult);
}
catch (Exception e)
{
Debug.Assert(null != e);
}
}
}
/// <summary>
/// Set the result of the work item to return
/// </summary>
/// <param name = "result">The result of the work item</param>
internal void SetResult(object result, Exception exception)
{
_result = result;
_exception = exception;
SignalComplete(false);
}
/// <summary>
/// Returns the work item result
/// </summary>
/// <returns>The work item result</returns>
internal IWorkItemResult GetWorkItemResult()
{
return _workItemResult;
}
/// <summary>
/// Wait for all work items to complete
/// </summary>
/// <param name = "workItemResults">Array of work item result objects</param>
/// <param name = "millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
/// <param name = "exitContext">
/// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
/// </param>
/// <param name = "cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
/// <returns>
/// true when every work item in workItemResults has completed; otherwise false.
/// </returns>
internal static bool WaitAll(
IWorkItemResult[] workItemResults,
int millisecondsTimeout,
bool exitContext,
WaitHandle cancelWaitHandle)
{
if (0 == workItemResults.Length)
{
return true;
}
bool success;
WaitHandle[] waitHandles = new WaitHandle[workItemResults.Length];
;
GetWaitHandles(workItemResults, waitHandles);
if ((null == cancelWaitHandle) && (waitHandles.Length <= 64))
{
success = WaitHandle.WaitAll(waitHandles, millisecondsTimeout, exitContext);
}
else
{
success = true;
int millisecondsLeft = millisecondsTimeout;
DateTime start = DateTime.Now;
WaitHandle[] whs;
whs = null != cancelWaitHandle ? new[] {null, cancelWaitHandle} : new WaitHandle[] {null};
bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout);
// Iterate over the wait handles and wait for each one to complete.
// We cannot use WaitHandle.WaitAll directly, because the cancelWaitHandle
// won't affect it.
// Each iteration we update the time left for the timeout.
for (int i = 0; i < workItemResults.Length; ++i)
{
// WaitAny don't work with negative numbers
if (!waitInfinitely && (millisecondsLeft < 0))
{
success = false;
break;
}
whs[0] = waitHandles[i];
int result = WaitHandle.WaitAny(whs, millisecondsLeft, exitContext);
if ((result > 0) || (WaitHandle.WaitTimeout == result))
{
success = false;
break;
}
if (!waitInfinitely)
{
// Update the time left to wait
TimeSpan ts = DateTime.Now - start;
millisecondsLeft = millisecondsTimeout - (int) ts.TotalMilliseconds;
}
}
}
// Release the wait handles
ReleaseWaitHandles(workItemResults);
return success;
}
/// <summary>
/// Waits for any of the work items in the specified array to complete, cancel, or timeout
/// </summary>
/// <param name = "workItemResults">Array of work item result objects</param>
/// <param name = "millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
/// <param name = "exitContext">
/// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
/// </param>
/// <param name = "cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
/// <returns>
/// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled.
/// </returns>
internal static int WaitAny(
IWorkItemResult[] workItemResults,
int millisecondsTimeout,
bool exitContext,
WaitHandle cancelWaitHandle)
{
WaitHandle[] waitHandles = null;
if (null != cancelWaitHandle)
{
waitHandles = new WaitHandle[workItemResults.Length + 1];
GetWaitHandles(workItemResults, waitHandles);
waitHandles[workItemResults.Length] = cancelWaitHandle;
}
else
{
waitHandles = new WaitHandle[workItemResults.Length];
GetWaitHandles(workItemResults, waitHandles);
}
int result = WaitHandle.WaitAny(waitHandles, millisecondsTimeout, exitContext);
// Treat cancel as timeout
if (null != cancelWaitHandle)
{
if (result == workItemResults.Length)
{
result = WaitHandle.WaitTimeout;
}
}
ReleaseWaitHandles(workItemResults);
return result;
}
/// <summary>
/// Fill an array of wait handles with the work items wait handles.
/// </summary>
/// <param name = "workItemResults">An array of work item results</param>
/// <param name = "waitHandles">An array of wait handles to fill</param>
private static void GetWaitHandles(
IWorkItemResult[] workItemResults,
WaitHandle[] waitHandles)
{
for (int i = 0; i < workItemResults.Length; ++i)
{
WorkItemResult wir = workItemResults[i] as WorkItemResult;
Debug.Assert(null != wir, "All workItemResults must be WorkItemResult objects");
waitHandles[i] = wir.GetWorkItem().GetWaitHandle();
}
}
/// <summary>
/// Release the work items' wait handles
/// </summary>
/// <param name = "workItemResults">An array of work item results</param>
private static void ReleaseWaitHandles(IWorkItemResult[] workItemResults)
{
#if (!ISWIN)
foreach (IWorkItemResult result in workItemResults)
{
WorkItemResult wir = result as WorkItemResult;
if (wir != null)
{
wir.GetWorkItem().ReleaseWaitHandle();
}
}
#else
foreach (WorkItemResult wir in workItemResults.OfType<WorkItemResult>())
{
wir.GetWorkItem().ReleaseWaitHandle();
}
#endif
}
#endregion
#region Private Members
private WorkItemState GetWorkItemState()
{
if (_canceledWorkItemsGroup.IsCanceled)
{
return WorkItemState.Canceled;
}
return _workItemState;
}
/// <summary>
/// Sets the work item's state
/// </summary>
/// <param name = "workItemState">The state to set the work item to</param>
private void SetWorkItemState(WorkItemState workItemState)
{
lock (this)
{
_workItemState = workItemState;
}
}
/// <summary>
/// Signals that work item has been completed or canceled
/// </summary>
/// <param name = "canceled">Indicates that the work item has been canceled</param>
private void SignalComplete(bool canceled)
{
SetWorkItemState(canceled ? WorkItemState.Canceled : WorkItemState.Completed);
lock (this)
{
// If someone is waiting then signal.
if (null != _workItemCompleted)
{
_workItemCompleted.Set();
}
}
}
internal void WorkItemIsQueued()
{
_queuedTime = DateTime.Now;
}
#endregion
#region Members exposed by WorkItemResult
/// <summary>
/// Cancel the work item if it didn't start running yet.
/// </summary>
/// <returns>Returns true on success or false if the work item is in progress or already completed</returns>
private bool Cancel()
{
lock (this)
{
switch (GetWorkItemState())
{
case WorkItemState.Canceled:
//Debug.WriteLine("Work item already canceled");
return true;
case WorkItemState.Completed:
case WorkItemState.InProgress:
//Debug.WriteLine("Work item cannot be canceled");
return false;
case WorkItemState.InQueue:
// Signal to the wait for completion that the work
// item has been completed (canceled). There is no
// reason to wait for it to get out of the queue
SignalComplete(true);
//Debug.WriteLine("Work item canceled");
return true;
}
}
return false;
}
/// <summary>
/// Get the result of the work item.
/// If the work item didn't run yet then the caller waits for the result, timeout, or cancel.
/// In case of error the method throws and exception
/// </summary>
/// <returns>The result of the work item</returns>
private object GetResult(
int millisecondsTimeout,
bool exitContext,
WaitHandle cancelWaitHandle)
{
Exception e = null;
object result = GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e);
if (null != e)
{
throw new WorkItemResultException(
"The work item caused an excpetion, see the inner exception for details", e);
}
return result;
}
/// <summary>
/// Get the result of the work item.
/// If the work item didn't run yet then the caller waits for the result, timeout, or cancel.
/// In case of error the e argument is filled with the exception
/// </summary>
/// <returns>The result of the work item</returns>
private object GetResult(
int millisecondsTimeout,
bool exitContext,
WaitHandle cancelWaitHandle,
out Exception e)
{
e = null;
// Check for cancel
if (WorkItemState.Canceled == GetWorkItemState())
{
throw new WorkItemCancelException("Work item canceled");
}
// Check for completion
if (IsCompleted)
{
e = _exception;
return _result;
}
// If no cancelWaitHandle is provided
if (null == cancelWaitHandle)
{
WaitHandle wh = GetWaitHandle();
bool timeout = !wh.WaitOne(millisecondsTimeout, exitContext);
ReleaseWaitHandle();
if (timeout)
{
throw new WorkItemTimeoutException("Work item timeout");
}
}
else
{
WaitHandle wh = GetWaitHandle();
int result = WaitHandle.WaitAny(new[] {wh, cancelWaitHandle});
ReleaseWaitHandle();
switch (result)
{
case 0:
// The work item signaled
// Note that the signal could be also as a result of canceling the
// work item (not the get result)
break;
case 1:
case WaitHandle.WaitTimeout:
throw new WorkItemTimeoutException("Work item timeout");
default:
Debug.Assert(false);
break;
}
}
// Check for cancel
if (WorkItemState.Canceled == GetWorkItemState())
{
throw new WorkItemCancelException("Work item canceled");
}
Debug.Assert(IsCompleted);
e = _exception;
// Return the result
return _result;
}
/// <summary>
/// A wait handle to wait for completion, cancel, or timeout
/// </summary>
private WaitHandle GetWaitHandle()
{
lock (this)
{
if (null == _workItemCompleted)
{
_workItemCompleted = new ManualResetEvent(IsCompleted);
}
++_workItemCompletedRefCount;
}
return _workItemCompleted;
}
private void ReleaseWaitHandle()
{
lock (this)
{
if (null != _workItemCompleted)
{
--_workItemCompletedRefCount;
if (0 == _workItemCompletedRefCount)
{
_workItemCompleted.Close();
_workItemCompleted = null;
}
}
}
}
/// <summary>
/// Returns true when the work item has completed or canceled
/// </summary>
private bool IsCompleted
{
get
{
lock (this)
{
WorkItemState workItemState = GetWorkItemState();
return ((workItemState == WorkItemState.Completed) ||
(workItemState == WorkItemState.Canceled));
}
}
}
/// <summary>
/// Returns true when the work item has canceled
/// </summary>
public bool IsCanceled
{
get
{
lock (this)
{
return (GetWorkItemState() == WorkItemState.Canceled);
}
}
}
#endregion
#region IHasWorkItemPriority Members
/// <summary>
/// Returns the priority of the work item
/// </summary>
public WorkItemPriority WorkItemPriority
{
get { return _workItemInfo.WorkItemPriority; }
}
#endregion
internal event WorkItemStateCallback OnWorkItemStarted
{
add { _workItemStartedEvent += value; }
remove { _workItemStartedEvent -= value; }
}
internal event WorkItemStateCallback OnWorkItemCompleted
{
add { _workItemCompletedEvent += value; }
remove { _workItemCompletedEvent -= value; }
}
#region WorkItemResult class
private class WorkItemResult : IWorkItemResult, IInternalWorkItemResult
{
/// <summary>
/// A back reference to the work item
/// </summary>
private readonly WorkItem _workItem;
public WorkItemResult(WorkItem workItem)
{
_workItem = workItem;
}
#region IInternalWorkItemResult Members
public event WorkItemStateCallback OnWorkItemStarted
{
add { _workItem.OnWorkItemStarted += value; }
remove { _workItem.OnWorkItemStarted -= value; }
}
public event WorkItemStateCallback OnWorkItemCompleted
{
add { _workItem.OnWorkItemCompleted += value; }
remove { _workItem.OnWorkItemCompleted -= value; }
}
#endregion
#region IWorkItemResult Members
public bool IsCompleted
{
get { return _workItem.IsCompleted; }
}
public void Abort()
{
_workItem.Abort();
}
public bool IsCanceled
{
get { return _workItem.IsCanceled; }
}
public object GetResult()
{
return _workItem.GetResult(Timeout.Infinite, true, null);
}
public object GetResult(int millisecondsTimeout, bool exitContext)
{
return _workItem.GetResult(millisecondsTimeout, exitContext, null);
}
public object GetResult(TimeSpan timeout, bool exitContext)
{
return _workItem.GetResult((int) timeout.TotalMilliseconds, exitContext, null);
}
public object GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle)
{
return _workItem.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle);
}
public object GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle)
{
return _workItem.GetResult((int) timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
}
public object GetResult(out Exception e)
{
return _workItem.GetResult(Timeout.Infinite, true, null, out e);
}
public object GetResult(int millisecondsTimeout, bool exitContext, out Exception e)
{
return _workItem.GetResult(millisecondsTimeout, exitContext, null, out e);
}
public object GetResult(TimeSpan timeout, bool exitContext, out Exception e)
{
return _workItem.GetResult((int) timeout.TotalMilliseconds, exitContext, null, out e);
}
public object GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle,
out Exception e)
{
return _workItem.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e);
}
public object GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e)
{
return _workItem.GetResult((int) timeout.TotalMilliseconds, exitContext, cancelWaitHandle, out e);
}
public bool Cancel()
{
return _workItem.Cancel();
}
public object State
{
get { return _workItem._state; }
}
public WorkItemPriority WorkItemPriority
{
get { return _workItem._workItemInfo.WorkItemPriority; }
}
/// <summary>
/// Return the result, same as GetResult()
/// </summary>
public object Result
{
get { return GetResult(); }
}
/// <summary>
/// Returns the exception if occured otherwise returns null.
/// This value is valid only after the work item completed,
/// before that it is always null.
/// </summary>
public object Exception
{
get { return _workItem._exception; }
}
#endregion
internal WorkItem GetWorkItem()
{
return _workItem;
}
}
#endregion
public void DisposeOfState()
{
if (_workItemInfo.DisposeOfStateObjects)
{
IDisposable disp = _state as IDisposable;
if (null != disp)
{
disp.Dispose();
_state = null;
}
}
}
public void Abort()
{
lock (this)
{
if (currentThread != null)
currentThread.Abort();
}
}
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Data;
using System.Diagnostics;
#pragma warning disable 0618 // ignore obsolete warning about XmlDataDocument
namespace System.Xml
{
//
// Maps XML nodes to schema
//
// With the exception of some functions (the most important is SearchMatchingTableSchema) all functions expect that each region rowElem is already associated
// w/ it's DataRow (basically the test to determine a rowElem is based on a != null associated DataRow). As a result of this, some functions will NOT work properly
// when they are used on a tree for which rowElem's are not associated w/ a DataRow.
//
internal sealed class DataSetMapper
{
private Hashtable _tableSchemaMap; // maps an string (currently this is localName:nsURI) to a DataTable. Used to quickly find if a bound-elem matches any data-table metadata..
private Hashtable _columnSchemaMap; // maps a string (table localName:nsURI) to a Hashtable. The 2nd hastable (the one that is stored as data in columnSchemaMap, maps a string to a DataColumn.
private XmlDataDocument _doc; // The document this mapper is related to
private DataSet _dataSet; // The dataset this mapper is related to
internal const string strReservedXmlns = "http://www.w3.org/2000/xmlns/";
internal DataSetMapper()
{
Debug.Assert(_dataSet == null);
_tableSchemaMap = new Hashtable();
_columnSchemaMap = new Hashtable();
}
internal void SetupMapping(XmlDataDocument xd, DataSet ds)
{
// If are already mapped, forget about our current mapping and re-do it again.
if (IsMapped())
{
_tableSchemaMap = new Hashtable();
_columnSchemaMap = new Hashtable();
}
_doc = xd;
_dataSet = ds;
foreach (DataTable t in _dataSet.Tables)
{
AddTableSchema(t);
foreach (DataColumn c in t.Columns)
{
// don't include auto-generated PK & FK to be part of mapping
if (!IsNotMapped(c))
{
AddColumnSchema(c);
}
}
}
}
internal bool IsMapped() => _dataSet != null;
internal DataTable SearchMatchingTableSchema(string localName, string namespaceURI)
{
object tid = GetIdentity(localName, namespaceURI);
return (DataTable)(_tableSchemaMap[tid]);
}
// SearchMatchingTableSchema function works only when the elem has not been bound to a DataRow. If you want to get the table associated w/ an element after
// it has been associated w/ a DataRow use GetTableSchemaForElement function.
// rowElem is the parent region rowElem or null if there is no parent region (in case elem is a row elem, then rowElem will be the parent region; if elem is not
// mapped to a DataRow, then rowElem is the region elem is part of)
//
// Those are the rules for determing if elem is a row element:
// 1. node is an element (already meet, since elem is of type XmlElement)
// 2. If the node is already associated w/ a DataRow, then the node is a row element - not applicable, b/c this function is intended to be called on a
// to find out if the node s/b associated w/ a DataRow (see XmlDataDocument.LoadRows)
// 3. If the node localName/ns matches a DataTable then
// 3.1 Take the parent region DataTable (in our case rowElem.Row.DataTable)
// 3.2 If no parent region, then the node is associated w/ a DataTable
// 3.3 If there is a parent region
// 3.3.1 If the node has no elem children and no attr other than namespace declaration, and the node can match
// a column from the parent region table, then the node is NOT associated w/ a DataTable (it is a potential DataColumn in the parent region)
// 3.3.2 Else the node is a row-element (and associated w/ a DataTable / DataRow )
//
internal DataTable SearchMatchingTableSchema(XmlBoundElement rowElem, XmlBoundElement elem)
{
Debug.Assert(elem != null);
DataTable t = SearchMatchingTableSchema(elem.LocalName, elem.NamespaceURI);
if (t == null)
{
return null;
}
if (rowElem == null)
{
return t;
}
// Currently we expect we map things from top of the tree to the bottom
Debug.Assert(rowElem.Row != null);
DataColumn col = GetColumnSchemaForNode(rowElem, elem);
if (col == null)
{
return t;
}
foreach (XmlAttribute a in elem.Attributes)
{
#if DEBUG
// Some sanity check to catch errors like namespace attributes have the right localName/namespace value, but a wrong atomized namespace value
if (a.LocalName == "xmlns")
{
Debug.Assert(a.Prefix != null && a.Prefix.Length == 0);
Debug.Assert(a.NamespaceURI == (object)strReservedXmlns);
}
if (a.Prefix == "xmlns")
{
Debug.Assert(a.NamespaceURI == (object)strReservedXmlns);
}
if (a.NamespaceURI == strReservedXmlns)
{
Debug.Assert(a.NamespaceURI == (object)strReservedXmlns);
}
#endif
// No namespace attribute found, so elem cannot be a potential DataColumn, therefore is a row-elem
if (a.NamespaceURI != (object)strReservedXmlns)
{
return t;
}
}
for (XmlNode n = elem.FirstChild; n != null; n = n.NextSibling)
{
if (n.NodeType == XmlNodeType.Element)
{
// elem has an element child, so elem cannot be a potential DataColumn, therefore is a row-elem
return t;
}
}
// Node is a potential DataColumn in rowElem region
return null;
}
internal DataColumn GetColumnSchemaForNode(XmlBoundElement rowElem, XmlNode node)
{
Debug.Assert(rowElem != null);
// The caller must make sure that node is not a row-element
Debug.Assert((node is XmlBoundElement) ? ((XmlBoundElement)node).Row == null : true);
object tid = GetIdentity(rowElem.LocalName, rowElem.NamespaceURI);
object cid = GetIdentity(node.LocalName, node.NamespaceURI);
Hashtable columns = (Hashtable)_columnSchemaMap[tid];
if (columns != null)
{
DataColumn col = (DataColumn)(columns[cid]);
if (col == null)
{
return null;
}
MappingType mt = col.ColumnMapping;
if (node.NodeType == XmlNodeType.Attribute && mt == MappingType.Attribute)
{
return col;
}
if (node.NodeType == XmlNodeType.Element && mt == MappingType.Element)
{
return col;
}
// node's (localName, ns) matches a column, but the MappingType is different (i.e. node is elem, MT is attr)
return null;
}
return null;
}
internal DataTable GetTableSchemaForElement(XmlElement elem)
{
XmlBoundElement be = elem as XmlBoundElement;
if (be == null)
{
return null;
}
return GetTableSchemaForElement(be);
}
internal DataTable GetTableSchemaForElement(XmlBoundElement be) => be.Row?.Table;
internal static bool IsNotMapped(DataColumn c) => c.ColumnMapping == MappingType.Hidden;
// ATTENTION: GetRowFromElement( XmlElement ) and GetRowFromElement( XmlBoundElement ) should have the same functionality and side effects.
// See this code fragment for why:
// XmlBoundElement be = ...;
// XmlElement e = be;
// GetRowFromElement( be ); // Calls GetRowFromElement( XmlBoundElement )
// GetRowFromElement( e ); // Calls GetRowFromElement( XmlElement ), in spite of e beeing an instance of XmlBoundElement
internal DataRow GetRowFromElement(XmlElement e) => (e as XmlBoundElement)?.Row;
internal DataRow GetRowFromElement(XmlBoundElement be) => be.Row;
// Get the row-elem associatd w/ the region node is in.
// If node is in a region not mapped (like document element node) the function returns false and sets elem to null)
// This function does not work if the region is not associated w/ a DataRow (it uses DataRow association to know what is the row element associated w/ the region)
internal bool GetRegion(XmlNode node, out XmlBoundElement rowElem)
{
while (node != null)
{
XmlBoundElement be = node as XmlBoundElement;
// Break if found a region
if (be != null && GetRowFromElement(be) != null)
{
rowElem = be;
return true;
}
if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
}
else
{
node = node.ParentNode;
}
}
rowElem = null;
return false;
}
internal bool IsRegionRadical(XmlBoundElement rowElem)
{
// You must pass a row element (which s/b associated w/ a DataRow)
Debug.Assert(rowElem.Row != null);
if (rowElem.ElementState == ElementState.Defoliated)
{
return true;
}
DataTable table = GetTableSchemaForElement(rowElem);
DataColumnCollection columns = table.Columns;
int iColumn = 0;
// check column attributes...
int cAttrs = rowElem.Attributes.Count;
for (int iAttr = 0; iAttr < cAttrs; iAttr++)
{
XmlAttribute attr = rowElem.Attributes[iAttr];
// only specified attributes are radical
if (!attr.Specified)
{
return false;
}
// only mapped attrs are valid
DataColumn schema = GetColumnSchemaForNode(rowElem, attr);
if (schema == null)
{
return false;
}
// check to see if column is in order
if (!IsNextColumn(columns, ref iColumn, schema))
{
return false;
}
// must have exactly one text node (XmlNodeType.Text) child
XmlNode fc = attr.FirstChild;
if (fc == null || fc.NodeType != XmlNodeType.Text || fc.NextSibling != null)
{
return false;
}
}
// check column elements
iColumn = 0;
XmlNode n = rowElem.FirstChild;
for (; n != null; n = n.NextSibling)
{
// only elements can exist in radically structured data
if (n.NodeType != XmlNodeType.Element)
{
return false;
}
XmlElement e = n as XmlElement;
// only checking for column mappings in this loop
if (GetRowFromElement(e) != null)
{
break;
}
// element's must have schema to be radically structured
DataColumn schema = GetColumnSchemaForNode(rowElem, e);
if (schema == null)
{
return false;
}
// check to see if column is in order
if (!IsNextColumn(columns, ref iColumn, schema))
{
return false;
}
// must have no attributes
if (e.HasAttributes)
{
return false;
}
// must have exactly one text node child
XmlNode fc = e.FirstChild;
if (fc == null || fc.NodeType != XmlNodeType.Text || fc.NextSibling != null)
{
return false;
}
}
// check for remaining sub-regions
for (; n != null; n = n.NextSibling)
{
// only elements can exist in radically structured data
if (n.NodeType != XmlNodeType.Element)
{
return false;
}
// element's must be regions in order to be radially structured
DataRow row = GetRowFromElement((XmlElement)n);
if (row == null)
{
return false;
}
}
return true;
}
private void AddTableSchema(DataTable table)
{
object idTable = GetIdentity(table.EncodedTableName, table.Namespace);
_tableSchemaMap[idTable] = table;
}
private void AddColumnSchema(DataColumn col)
{
DataTable table = col.Table;
object idTable = GetIdentity(table.EncodedTableName, table.Namespace);
object idColumn = GetIdentity(col.EncodedColumnName, col.Namespace);
Hashtable columns = (Hashtable)_columnSchemaMap[idTable];
if (columns == null)
{
columns = new Hashtable();
_columnSchemaMap[idTable] = columns;
}
columns[idColumn] = col;
}
private static object GetIdentity(string localName, string namespaceURI)
{
// we need access to XmlName to make this faster
return localName + ":" + namespaceURI;
}
private bool IsNextColumn(DataColumnCollection columns, ref int iColumn, DataColumn col)
{
for (; iColumn < columns.Count; iColumn++)
{
if (columns[iColumn] == col)
{
iColumn++; // advance before we return...
return true;
}
}
return false;
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// TaxCity
/// </summary>
[DataContract]
public partial class TaxCity : IEquatable<TaxCity>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="TaxCity" /> class.
/// </summary>
/// <param name="accountingCode">Accounting code for programs such as QuickBooks.</param>
/// <param name="city">City.</param>
/// <param name="cityOid">Tax record object identifier used internally by database.</param>
/// <param name="countyOid">Tax record object identifier used internally by database.</param>
/// <param name="dontCollectCity">Flag instructing engine to not collect city tax for this city.</param>
/// <param name="dontCollectPostalCode">Flag instructing engine to not collect postal code tax for this city.</param>
/// <param name="postalCodes">Postal Codes within this city.</param>
/// <param name="taxRate">Tax Rate.</param>
/// <param name="taxRateFormatted">Tax rate formatted.</param>
public TaxCity(string accountingCode = default(string), string city = default(string), int? cityOid = default(int?), int? countyOid = default(int?), bool? dontCollectCity = default(bool?), bool? dontCollectPostalCode = default(bool?), List<TaxPostalCode> postalCodes = default(List<TaxPostalCode>), decimal? taxRate = default(decimal?), string taxRateFormatted = default(string))
{
this.AccountingCode = accountingCode;
this.City = city;
this.CityOid = cityOid;
this.CountyOid = countyOid;
this.DontCollectCity = dontCollectCity;
this.DontCollectPostalCode = dontCollectPostalCode;
this.PostalCodes = postalCodes;
this.TaxRate = taxRate;
this.TaxRateFormatted = taxRateFormatted;
}
/// <summary>
/// Accounting code for programs such as QuickBooks
/// </summary>
/// <value>Accounting code for programs such as QuickBooks</value>
[DataMember(Name="accounting_code", EmitDefaultValue=false)]
public string AccountingCode { get; set; }
/// <summary>
/// City
/// </summary>
/// <value>City</value>
[DataMember(Name="city", EmitDefaultValue=false)]
public string City { get; set; }
/// <summary>
/// Tax record object identifier used internally by database
/// </summary>
/// <value>Tax record object identifier used internally by database</value>
[DataMember(Name="city_oid", EmitDefaultValue=false)]
public int? CityOid { get; set; }
/// <summary>
/// Tax record object identifier used internally by database
/// </summary>
/// <value>Tax record object identifier used internally by database</value>
[DataMember(Name="county_oid", EmitDefaultValue=false)]
public int? CountyOid { get; set; }
/// <summary>
/// Flag instructing engine to not collect city tax for this city
/// </summary>
/// <value>Flag instructing engine to not collect city tax for this city</value>
[DataMember(Name="dont_collect_city", EmitDefaultValue=false)]
public bool? DontCollectCity { get; set; }
/// <summary>
/// Flag instructing engine to not collect postal code tax for this city
/// </summary>
/// <value>Flag instructing engine to not collect postal code tax for this city</value>
[DataMember(Name="dont_collect_postal_code", EmitDefaultValue=false)]
public bool? DontCollectPostalCode { get; set; }
/// <summary>
/// Postal Codes within this city
/// </summary>
/// <value>Postal Codes within this city</value>
[DataMember(Name="postal_codes", EmitDefaultValue=false)]
public List<TaxPostalCode> PostalCodes { get; set; }
/// <summary>
/// Tax Rate
/// </summary>
/// <value>Tax Rate</value>
[DataMember(Name="tax_rate", EmitDefaultValue=false)]
public decimal? TaxRate { get; set; }
/// <summary>
/// Tax rate formatted
/// </summary>
/// <value>Tax rate formatted</value>
[DataMember(Name="tax_rate_formatted", EmitDefaultValue=false)]
public string TaxRateFormatted { 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 TaxCity {\n");
sb.Append(" AccountingCode: ").Append(AccountingCode).Append("\n");
sb.Append(" City: ").Append(City).Append("\n");
sb.Append(" CityOid: ").Append(CityOid).Append("\n");
sb.Append(" CountyOid: ").Append(CountyOid).Append("\n");
sb.Append(" DontCollectCity: ").Append(DontCollectCity).Append("\n");
sb.Append(" DontCollectPostalCode: ").Append(DontCollectPostalCode).Append("\n");
sb.Append(" PostalCodes: ").Append(PostalCodes).Append("\n");
sb.Append(" TaxRate: ").Append(TaxRate).Append("\n");
sb.Append(" TaxRateFormatted: ").Append(TaxRateFormatted).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 virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as TaxCity);
}
/// <summary>
/// Returns true if TaxCity instances are equal
/// </summary>
/// <param name="input">Instance of TaxCity to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TaxCity input)
{
if (input == null)
return false;
return
(
this.AccountingCode == input.AccountingCode ||
(this.AccountingCode != null &&
this.AccountingCode.Equals(input.AccountingCode))
) &&
(
this.City == input.City ||
(this.City != null &&
this.City.Equals(input.City))
) &&
(
this.CityOid == input.CityOid ||
(this.CityOid != null &&
this.CityOid.Equals(input.CityOid))
) &&
(
this.CountyOid == input.CountyOid ||
(this.CountyOid != null &&
this.CountyOid.Equals(input.CountyOid))
) &&
(
this.DontCollectCity == input.DontCollectCity ||
(this.DontCollectCity != null &&
this.DontCollectCity.Equals(input.DontCollectCity))
) &&
(
this.DontCollectPostalCode == input.DontCollectPostalCode ||
(this.DontCollectPostalCode != null &&
this.DontCollectPostalCode.Equals(input.DontCollectPostalCode))
) &&
(
this.PostalCodes == input.PostalCodes ||
this.PostalCodes != null &&
this.PostalCodes.SequenceEqual(input.PostalCodes)
) &&
(
this.TaxRate == input.TaxRate ||
(this.TaxRate != null &&
this.TaxRate.Equals(input.TaxRate))
) &&
(
this.TaxRateFormatted == input.TaxRateFormatted ||
(this.TaxRateFormatted != null &&
this.TaxRateFormatted.Equals(input.TaxRateFormatted))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AccountingCode != null)
hashCode = hashCode * 59 + this.AccountingCode.GetHashCode();
if (this.City != null)
hashCode = hashCode * 59 + this.City.GetHashCode();
if (this.CityOid != null)
hashCode = hashCode * 59 + this.CityOid.GetHashCode();
if (this.CountyOid != null)
hashCode = hashCode * 59 + this.CountyOid.GetHashCode();
if (this.DontCollectCity != null)
hashCode = hashCode * 59 + this.DontCollectCity.GetHashCode();
if (this.DontCollectPostalCode != null)
hashCode = hashCode * 59 + this.DontCollectPostalCode.GetHashCode();
if (this.PostalCodes != null)
hashCode = hashCode * 59 + this.PostalCodes.GetHashCode();
if (this.TaxRate != null)
hashCode = hashCode * 59 + this.TaxRate.GetHashCode();
if (this.TaxRateFormatted != null)
hashCode = hashCode * 59 + this.TaxRateFormatted.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Copyright (c) 2006-2007 Frank Laub
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.Text;
using System.Runtime.InteropServices;
using System.IO;
using OpenSSL.Core;
namespace OpenSSL.Crypto
{
#region Cipher
/// <summary>
/// Wraps the EVP_CIPHER object.
/// </summary>
public class Cipher : Base
{
private EVP_CIPHER raw;
internal Cipher(IntPtr ptr, bool owner) : base(ptr, owner)
{
this.raw = (EVP_CIPHER)Marshal.PtrToStructure(this.ptr, typeof(EVP_CIPHER));
}
/// <summary>
/// Prints the LongName of this cipher.
/// </summary>
/// <param name="bio"></param>
public override void Print(BIO bio)
{
bio.Write(this.LongName);
}
/// <summary>
/// Not implemented, these objects should never be disposed
/// </summary>
protected override void OnDispose() {
throw new NotImplementedException();
}
/// <summary>
/// Returns EVP_get_cipherbyname()
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static Cipher CreateByName(string name)
{
byte[] buf = Encoding.ASCII.GetBytes(name);
IntPtr ptr = Native.EVP_get_cipherbyname(buf);
if(ptr == IntPtr.Zero)
return null;
return new Cipher(ptr, false);
}
/// <summary>
/// Calls OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH)
/// </summary>
public static string[] AllNamesSorted
{
get { return new NameCollector(Native.OBJ_NAME_TYPE_CIPHER_METH, true).Result.ToArray(); }
}
/// <summary>
/// Calls OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH)
/// </summary>
public static string[] AllNames
{
get { return new NameCollector(Native.OBJ_NAME_TYPE_CIPHER_METH, false).Result.ToArray(); }
}
#region EVP_CIPHER
[StructLayout(LayoutKind.Sequential)]
struct EVP_CIPHER
{
public int nid;
public int block_size;
public int key_len;
public int iv_len;
public uint flags;
public IntPtr init;
public IntPtr do_cipher;
public IntPtr cleanup;
public int ctx_size;
public IntPtr set_asn1_parameters;
public IntPtr get_asn1_parameters;
public IntPtr ctrl;
public IntPtr app_data;
}
#endregion
#region Ciphers
/// <summary>
/// EVP_enc_null()
/// </summary>
public static Cipher Null = new Cipher(Native.EVP_enc_null(), false);
/// <summary>
/// EVP_des_ecb()
/// </summary>
public static Cipher DES_ECB = new Cipher(Native.EVP_des_ecb(), false);
/// <summary>
/// EVP_des_ede()
/// </summary>
public static Cipher DES_EDE = new Cipher(Native.EVP_des_ede(), false);
/// <summary>
/// EVP_des_ede3()
/// </summary>
public static Cipher DES_EDE3 = new Cipher(Native.EVP_des_ede3(), false);
/// <summary>
/// EVP_des_ede_ecb()
/// </summary>
public static Cipher DES_EDE_ECB = new Cipher(Native.EVP_des_ede_ecb(), false);
/// <summary>
/// EVP_des_ede3_ecb()
/// </summary>
public static Cipher DES_EDE3_ECB = new Cipher(Native.EVP_des_ede3_ecb(), false);
/// <summary>
/// EVP_des_cfb64()
/// </summary>
public static Cipher DES_CFB64 = new Cipher(Native.EVP_des_cfb64(), false);
/// <summary>
/// EVP_des_cfb1()
/// </summary>
public static Cipher DES_CFB1 = new Cipher(Native.EVP_des_cfb1(), false);
/// <summary>
/// EVP_des_cfb8()
/// </summary>
public static Cipher DES_CFB8 = new Cipher(Native.EVP_des_cfb8(), false);
/// <summary>
/// EVP_des_ede_cfb64()
/// </summary>
public static Cipher DES_EDE_CFB64 = new Cipher(Native.EVP_des_ede_cfb64(), false);
/// <summary>
/// EVP_des_ede3_cfb64()
/// </summary>
public static Cipher DES_EDE3_CFB64 = new Cipher(Native.EVP_des_ede3_cfb64(), false);
/// <summary>
/// EVP_des_ede3_cfb1()
/// </summary>
// public static Cipher DES_EDE3_CFB1 = new Cipher(Native.EVP_des_ede3_cfb1(), false);
/// <summary>
/// EVP_des_ede3_cfb8()
/// </summary>
public static Cipher DES_EDE3_CFB8 = new Cipher(Native.EVP_des_ede3_cfb8(), false);
/// <summary>
/// EVP_des_ofb()
/// </summary>
public static Cipher DES_OFB = new Cipher(Native.EVP_des_ofb(), false);
/// <summary>
/// EVP_ded_ede_ofb()
/// </summary>
public static Cipher DES_EDE_OFB = new Cipher(Native.EVP_des_ede_ofb(), false);
/// <summary>
/// EVP_des_ede3_ofb()
/// </summary>
public static Cipher DES_EDE3_OFB = new Cipher(Native.EVP_des_ede3_ofb(), false);
/// <summary>
/// EVP_des_cbc()
/// </summary>
public static Cipher DES_CBC = new Cipher(Native.EVP_des_cbc(), false);
/// <summary>
/// EVP_des_ede_cbc()
/// </summary>
public static Cipher DES_EDE_CBC = new Cipher(Native.EVP_des_ede_cbc(), false);
/// <summary>
/// EVP_des_ede3_cbc()
/// </summary>
public static Cipher DES_EDE3_CBC = new Cipher(Native.EVP_des_ede3_cbc(), false);
/// <summary>
/// EVP_desx_cbc()
/// </summary>
public static Cipher DESX_CBC = new Cipher(Native.EVP_desx_cbc(), false);
/// <summary>
/// EVP_rc4()
/// </summary>
public static Cipher RC4 = new Cipher(Native.EVP_rc4(), false);
/// <summary>
/// EVP_rc4_40()
/// </summary>
public static Cipher RC4_40 = new Cipher(Native.EVP_rc4_40(), false);
/// <summary>
/// EVP_idea_ecb()
/// </summary>
public static Cipher Idea_ECB = new Cipher(Native.EVP_idea_ecb(), false);
/// <summary>
/// EVP_idea_cfb64()
/// </summary>
public static Cipher Idea_CFB64 = new Cipher(Native.EVP_idea_cfb64(), false);
/// <summary>
/// EVP_idea_ofb()
/// </summary>
public static Cipher Idea_OFB = new Cipher(Native.EVP_idea_ofb(), false);
/// <summary>
/// EVP_idea_cbc()
/// </summary>
public static Cipher Idea_CBC = new Cipher(Native.EVP_idea_cbc(), false);
/// <summary>
/// EVP_rc2_ecb()
/// </summary>
public static Cipher RC2_ECB = new Cipher(Native.EVP_rc2_ecb(), false);
/// <summary>
/// EVP_rc2_cbc()
/// </summary>
public static Cipher RC2_CBC = new Cipher(Native.EVP_rc2_cbc(), false);
/// <summary>
/// EVP_rc2_40_cbc()
/// </summary>
public static Cipher RC2_40_CBC = new Cipher(Native.EVP_rc2_40_cbc(), false);
/// <summary>
/// EVP_rc2_64_cbc()
/// </summary>
public static Cipher RC2_64_CBC = new Cipher(Native.EVP_rc2_64_cbc(), false);
/// <summary>
/// EVP_rc2_cfb64()
/// </summary>
public static Cipher RC2_CFB64 = new Cipher(Native.EVP_rc2_cfb64(), false);
/// <summary>
/// EVP_rc2_ofb()
/// </summary>
public static Cipher RC2_OFB = new Cipher(Native.EVP_rc2_ofb(), false);
/// <summary>
/// EVP_bf_ecb()
/// </summary>
public static Cipher Blowfish_ECB = new Cipher(Native.EVP_bf_ecb(), false);
/// <summary>
/// EVP_bf_cbc()
/// </summary>
public static Cipher Blowfish_CBC = new Cipher(Native.EVP_bf_cbc(), false);
/// <summary>
/// EVP_bf_cfb64()
/// </summary>
public static Cipher Blowfish_CFB64 = new Cipher(Native.EVP_bf_cfb64(), false);
/// <summary>
/// EVP_bf_ofb()
/// </summary>
public static Cipher Blowfish_OFB = new Cipher(Native.EVP_bf_ofb(), false);
/// <summary>
/// EVP_cast5_ecb()
/// </summary>
public static Cipher Cast5_ECB = new Cipher(Native.EVP_cast5_ecb(), false);
/// <summary>
/// EVP_cast5_cbc()
/// </summary>
public static Cipher Cast5_CBC = new Cipher(Native.EVP_cast5_cbc(), false);
/// <summary>
/// EVP_cast5_cfb64()
/// </summary>
public static Cipher Cast5_OFB64 = new Cipher(Native.EVP_cast5_cfb64(), false);
/// <summary>
/// EVP_cast5_ofb()
/// </summary>
public static Cipher Cast5_OFB = new Cipher(Native.EVP_cast5_ofb(), false);
#if OPENSSL_RC5_SUPPORT
public static Cipher RC5_32_12_16_CBC = new Cipher(Native.EVP_rc5_32_12_16_cbc(), false);
public static Cipher RC5_32_12_16_ECB = new Cipher(Native.EVP_rc5_32_12_16_ecb(), false);
public static Cipher RC5_32_12_16_CFB64 = new Cipher(Native.EVP_rc5_32_12_16_cfb64(), false);
public static Cipher RC5_32_12_16_OFB = new Cipher(Native.EVP_rc5_32_12_16_ofb(), false);
#endif
/// <summary>
/// EVP_aes_128_ecb()
/// </summary>
public static Cipher AES_128_ECB = new Cipher(Native.EVP_aes_128_ecb(), false);
/// <summary>
/// EVP_aes_128_cbc()
/// </summary>
public static Cipher AES_128_CBC = new Cipher(Native.EVP_aes_128_cbc(), false);
/// <summary>
/// EVP_aes_128_cfb1()
/// </summary>
public static Cipher AES_128_CFB1 = new Cipher(Native.EVP_aes_128_cfb1(), false);
/// <summary>
/// EVP_aes_128_cfb8()
/// </summary>
public static Cipher AES_128_CFB8 = new Cipher(Native.EVP_aes_128_cfb8(), false);
/// <summary>
/// EVP_aes_128_cfb128()
/// </summary>
public static Cipher AES_128_CFB128 = new Cipher(Native.EVP_aes_128_cfb128(), false);
/// <summary>
/// EVP_aes_128_ofb()
/// </summary>
public static Cipher AES_128_OFB = new Cipher(Native.EVP_aes_128_ofb(), false);
/// <summary>
/// EVP_aes_192_ecb()
/// </summary>
public static Cipher AES_192_ECB = new Cipher(Native.EVP_aes_192_ecb(), false);
/// <summary>
/// EVP_aes_192_cbc()
/// </summary>
public static Cipher AES_192_CBC = new Cipher(Native.EVP_aes_192_cbc(), false);
/// <summary>
/// EVP_aes_192_cfb1()
/// </summary>
public static Cipher AES_192_CFB1 = new Cipher(Native.EVP_aes_192_cfb1(), false);
/// <summary>
/// EVP_aes_192_cfb8()
/// </summary>
public static Cipher AES_192_CFB8 = new Cipher(Native.EVP_aes_192_cfb8(), false);
/// <summary>
/// EVP_aes_192_cfb128()
/// </summary>
public static Cipher AES_192_CFB128 = new Cipher(Native.EVP_aes_192_cfb128(), false);
/// <summary>
/// EVP_aes_192_ofb()
/// </summary>
public static Cipher AES_192_OFB = new Cipher(Native.EVP_aes_192_ofb(), false);
/// <summary>
/// EVP_aes_256_ecb()
/// </summary>
public static Cipher AES_256_ECB = new Cipher(Native.EVP_aes_256_ecb(), false);
/// <summary>
/// EVP_aes_256_cbc()
/// </summary>
public static Cipher AES_256_CBC = new Cipher(Native.EVP_aes_256_cbc(), false);
/// <summary>
/// EVP_aes_256_cfb1()
/// </summary>
public static Cipher AES_256_CFB1 = new Cipher(Native.EVP_aes_256_cfb1(), false);
/// <summary>
/// EVP_aes_256_cfb8()
/// </summary>
public static Cipher AES_256_CFB8 = new Cipher(Native.EVP_aes_256_cfb8(), false);
/// <summary>
/// EVP_aes_256_cfb128()
/// </summary>
public static Cipher AES_256_CFB128 = new Cipher(Native.EVP_aes_256_cfb128(), false);
/// <summary>
/// EVP_aes_256_ofb()
/// </summary>
public static Cipher AES_256_OFB = new Cipher(Native.EVP_aes_256_ofb(), false);
#endregion
#region Properties
/// <summary>
/// Returns the key_len field
/// </summary>
public int KeyLength
{
get { return this.raw.key_len; }
}
/// <summary>
/// Returns the iv_len field
/// </summary>
public int IVLength
{
get { return this.raw.iv_len; }
}
/// <summary>
/// Returns the block_size field
/// </summary>
public int BlockSize
{
get { return this.raw.block_size; }
}
/// <summary>
/// Returns the flags field
/// </summary>
public uint Flags
{
get { return this.raw.flags; }
}
/// <summary>
/// Returns the long name for the nid field using OBJ_nid2ln()
/// </summary>
public string LongName
{
get { return Native.OBJ_nid2ln(this.raw.nid); }
}
/// <summary>
/// Returns the name for the nid field using OBJ_nid2sn()
/// </summary>
public string Name
{
get { return Native.OBJ_nid2sn(this.raw.nid); }
}
/// <summary>
/// Returns EVP_CIPHER_type()
/// </summary>
public int Type
{
get { return Native.EVP_CIPHER_type(this.ptr); }
}
/// <summary>
/// Returns the long name for the type using OBJ_nid2ln()
/// </summary>
public string TypeName
{
get { return Native.OBJ_nid2ln(this.Type); }
}
#endregion
}
#endregion
/// <summary>
/// Simple struct to encapsulate common parameters for crypto functions
/// </summary>
public struct Envelope
{
/// <summary>
/// The key for a crypto operation
/// </summary>
public byte[][] Keys;
/// <summary>
/// The IV (Initialization Vector)
/// </summary>
public byte[] IV;
/// <summary>
/// The payload (contains plaintext or ciphertext)
/// </summary>
public byte[] Data;
}
/// <summary>
/// Wraps the EVP_CIPHER_CTX object.
/// </summary>
public class CipherContext : Base, IDisposable
{
#region EVP_CIPHER_CTX
[StructLayout(LayoutKind.Sequential)]
struct EVP_CIPHER_CTX
{
public IntPtr cipher;
public IntPtr engine; /* functional reference if 'cipher' is ENGINE-provided */
public int encrypt; /* encrypt or decrypt */
public int buf_len; /* number we have left */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Native.EVP_MAX_IV_LENGTH)]
public byte[] oiv; /* original iv */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Native.EVP_MAX_IV_LENGTH)]
public byte[] iv; /* working iv */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Native.EVP_MAX_BLOCK_LENGTH)]
public byte[] buf;/* saved partial block */
public int num; /* used by cfb/ofb mode */
public IntPtr app_data; /* application stuff */
public int key_len; /* May change for variable length cipher */
public uint flags; /* Various flags */
public IntPtr cipher_data; /* per EVP data */
public int final_used;
public int block_mask;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = Native.EVP_MAX_BLOCK_LENGTH)]
public byte[] final;/* possible final block */
}
#endregion
private Cipher cipher;
/// <summary>
/// Calls OPENSSL_malloc() and initializes the buffer using EVP_CIPHER_CTX_init()
/// </summary>
/// <param name="cipher"></param>
public CipherContext(Cipher cipher)
: base(Native.OPENSSL_malloc(Marshal.SizeOf(typeof(EVP_CIPHER_CTX))), true)
{
Native.EVP_CIPHER_CTX_init(this.ptr);
this.cipher = cipher;
}
/// <summary>
/// Returns the cipher's LongName
/// </summary>
/// <param name="bio"></param>
public override void Print(BIO bio)
{
bio.Write("CipherContext: " + this.cipher.LongName);
}
#region Methods
/// <summary>
/// Calls EVP_OpenInit() and EVP_OpenFinal()
/// </summary>
/// <param name="input"></param>
/// <param name="ekey"></param>
/// <param name="iv"></param>
/// <param name="pkey"></param>
/// <returns></returns>
public byte[] Open(byte[] input, byte[] ekey, byte[] iv, CryptoKey pkey)
{
Native.ExpectSuccess(Native.EVP_OpenInit(
this.ptr, this.cipher.Handle, ekey, ekey.Length, iv, pkey.Handle));
MemoryStream memory = new MemoryStream();
byte[] output = new byte[input.Length + this.Cipher.BlockSize];
int len;
Native.ExpectSuccess(Native.EVP_DecryptUpdate(this.ptr, output, out len, input, input.Length));
memory.Write(output, 0, len);
Native.ExpectSuccess(Native.EVP_OpenFinal(this.ptr, output, out len));
memory.Write(output, 0, len);
return memory.ToArray();
}
/// <summary>
/// Calls EVP_SealInit() and EVP_SealFinal()
/// </summary>
/// <param name="pkeys"></param>
/// <param name="input"></param>
/// <returns></returns>
public Envelope Seal(CryptoKey[] pkeys, byte[] input)
{
Envelope env = new Envelope();
var ptrs = new IntPtr[pkeys.Length];
try {
env.Keys = new byte[pkeys.Length][];
IntPtr[] pubkeys = new IntPtr[pkeys.Length];
int[] ekeylens = new int[pkeys.Length];
for (int i = 0; i < pkeys.Length; i++) {
ptrs[i] = Marshal.AllocHGlobal(pkeys[i].Size);
pubkeys[i] = pkeys[i].Handle;
}
if (this.Cipher.IVLength > 0) {
env.IV = new byte[this.Cipher.IVLength];
}
Native.ExpectSuccess(Native.EVP_SealInit(
this.ptr, this.Cipher.Handle, ptrs, ekeylens, env.IV, pubkeys, pubkeys.Length));
for (int i = 0; i < pkeys.Length; i++) {
env.Keys[i] = new byte[ekeylens[i]];
Marshal.Copy(ptrs[i], env.Keys[i], 0, ekeylens[i]);
}
MemoryStream memory = new MemoryStream();
byte[] output = new byte[input.Length + this.Cipher.BlockSize];
int len;
Native.ExpectSuccess(Native.EVP_EncryptUpdate(this.ptr, output, out len, input, input.Length));
memory.Write(output, 0, len);
Native.ExpectSuccess(Native.EVP_SealFinal(this.ptr, output, out len));
memory.Write(output, 0, len);
env.Data = memory.ToArray();
return env;
}
finally {
foreach (var ptr in ptrs) {
Marshal.FreeHGlobal(ptr);
}
}
}
/// <summary>
/// Encrypts or decrypts the specified payload.
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <param name="doEncrypt"></param>
/// <returns></returns>
public byte[] Crypt(byte[] input, byte[] key, byte[] iv, bool doEncrypt)
{
return this.Crypt(input, key, iv, doEncrypt, -1);
}
private byte[] SetupKey(byte[] key)
{
if (key == null) {
key = new byte[this.Cipher.KeyLength];
key.Initialize();
return key;
}
if (this.Cipher.KeyLength == key.Length) {
return key;
}
byte[] real_key = new byte[this.Cipher.KeyLength];
real_key.Initialize();
Buffer.BlockCopy(key, 0, real_key, 0, Math.Min(key.Length, real_key.Length));
return real_key;
}
private byte[] SetupIV(byte[] iv)
{
if (this.cipher.IVLength > iv.Length)
{
byte[] ret = new byte[this.cipher.IVLength];
ret.Initialize();
Buffer.BlockCopy(iv, 0, ret, 0, iv.Length);
return ret;
}
return iv;
}
/// <summary>
/// Calls EVP_CipherInit_ex(), EVP_CipherUpdate(), and EVP_CipherFinal_ex()
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <param name="doEncrypt"></param>
/// <param name="padding"></param>
/// <returns></returns>
public byte[] Crypt(byte[] input, byte[] key, byte[] iv, bool doEncrypt, int padding)
{
int enc = doEncrypt ? 1 : 0;
int total = Math.Max(input.Length, this.cipher.BlockSize);
byte[] real_key = SetupKey(key);
byte[] real_iv = SetupIV(iv);
byte[] buf = new byte[total];
MemoryStream memory = new MemoryStream(total);
Native.ExpectSuccess(Native.EVP_CipherInit_ex(
this.ptr, this.cipher.Handle, IntPtr.Zero, null, null, enc));
Native.ExpectSuccess(Native.EVP_CIPHER_CTX_set_key_length(this.ptr, real_key.Length));
if (padding >= 0)
Native.ExpectSuccess(Native.EVP_CIPHER_CTX_set_padding(this.ptr, padding));
if (this.IsStream)
{
for (int i = 0; i < Math.Min(real_key.Length, iv.Length); i++)
{
real_key[i] ^= iv[i];
}
Native.ExpectSuccess(Native.EVP_CipherInit_ex(
this.ptr, this.cipher.Handle, IntPtr.Zero, real_key, null, enc));
}
else
{
Native.ExpectSuccess(Native.EVP_CipherInit_ex(
this.ptr, this.cipher.Handle, IntPtr.Zero, real_key, real_iv, enc));
}
int len = 0;
Native.ExpectSuccess(Native.EVP_CipherUpdate(this.ptr, buf, out len, input, input.Length));
memory.Write(buf, 0, len);
len = buf.Length;
Native.EVP_CipherFinal_ex(this.ptr, buf, ref len);
memory.Write(buf, 0, len);
return memory.ToArray();
}
/// <summary>
/// Encrypts the specified plaintext
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public byte[] Encrypt(byte[] input, byte[] key, byte[] iv)
{
return this.Crypt(input, key, iv, true);
}
/// <summary>
/// Decrypts the specified ciphertext
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public byte[] Decrypt(byte[] input, byte[] key, byte[] iv)
{
return this.Crypt(input, key, iv, false);
}
/// <summary>
/// Encrypts the specified plaintext
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <param name="padding"></param>
/// <returns></returns>
public byte[] Encrypt(byte[] input, byte[] key, byte[] iv, int padding)
{
return this.Crypt(input, key, iv, true, padding);
}
/// <summary>
/// Decrypts the specified ciphertext
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <param name="padding"></param>
/// <returns></returns>
public byte[] Decrypt(byte[] input, byte[] key, byte[] iv, int padding)
{
return this.Crypt(input, key, iv, false, padding);
}
/// <summary>
/// Calls EVP_BytesToKey
/// </summary>
/// <param name="md"></param>
/// <param name="salt"></param>
/// <param name="data"></param>
/// <param name="count"></param>
/// <param name="iv"></param>
/// <returns></returns>
public byte[] BytesToKey(MessageDigest md, byte[] salt, byte[] data, int count, out byte[] iv)
{
int keylen = this.Cipher.KeyLength;
if (keylen == 0) {
keylen = 8;
}
byte[] key = new byte[keylen];
int ivlen = this.Cipher.IVLength;
if (ivlen == 0) {
ivlen = 8;
}
iv = new byte[ivlen];
Native.ExpectSuccess(Native.EVP_BytesToKey(
this.cipher.Handle,
md.Handle,
salt,
data,
data.Length,
count,
key,
iv));
return key;
}
#endregion
#region Properties
/// <summary>
/// Returns the EVP_CIPHER for this context.
/// </summary>
public Cipher Cipher
{
get { return this.cipher; }
}
public bool IsStream
{
get { return (this.cipher.Flags & Native.EVP_CIPH_MODE) == Native.EVP_CIPH_STREAM_CIPHER; }
}
private EVP_CIPHER_CTX Raw
{
get { return (EVP_CIPHER_CTX)Marshal.PtrToStructure(this.ptr, typeof(EVP_CIPHER_CTX)); }
set { Marshal.StructureToPtr(value, this.ptr, false); }
}
#endregion
#region IDisposable Members
/// <summary>
/// Calls EVP_CIPHER_CTX_clean() and then OPENSSL_free()
/// </summary>
protected override void OnDispose() {
Native.EVP_CIPHER_CTX_cleanup(this.ptr);
Native.OPENSSL_free(this.ptr);
}
#endregion
}
}
| |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using TrackableEntities;
using TrackableEntities.Client;
namespace AIM.Client.Entities.Models
{
[JsonObject(IsReference = true)]
[DataContract(IsReference = true, Namespace = "http://schemas.datacontract.org/2004/07/TrackableEntities.Models")]
public partial class Education : ModelBase<Education>, IEquatable<Education>, ITrackable
{
[DataMember]
public int EducationId
{
get { return _EducationId; }
set
{
if (Equals(value, _EducationId)) return;
_EducationId = value;
NotifyPropertyChanged(m => m.EducationId);
}
}
private int _EducationId;
[DataMember]
public string SchoolName
{
get { return _SchoolName; }
set
{
if (Equals(value, _SchoolName)) return;
_SchoolName = value;
NotifyPropertyChanged(m => m.SchoolName);
}
}
private string _SchoolName;
[DataMember]
public string Degree
{
get { return _Degree; }
set
{
if (Equals(value, _Degree)) return;
_Degree = value;
NotifyPropertyChanged(m => m.Degree);
}
}
private string _Degree;
[DataMember]
public Nullable<System.DateTime> Graduated
{
get { return _Graduated; }
set
{
if (Equals(value, _Graduated)) return;
_Graduated = value;
NotifyPropertyChanged(m => m.Graduated);
}
}
private Nullable<System.DateTime> _Graduated;
[DataMember]
public string YearsAttended
{
get { return _YearsAttended; }
set
{
if (Equals(value, _YearsAttended)) return;
_YearsAttended = value;
NotifyPropertyChanged(m => m.YearsAttended);
}
}
private string _YearsAttended;
[DataMember]
public string Street
{
get { return _Street; }
set
{
if (Equals(value, _Street)) return;
_Street = value;
NotifyPropertyChanged(m => m.Street);
}
}
private string _Street;
[DataMember]
public string Street2
{
get { return _Street2; }
set
{
if (Equals(value, _Street2)) return;
_Street2 = value;
NotifyPropertyChanged(m => m.Street2);
}
}
private string _Street2;
[DataMember]
public string City
{
get { return _City; }
set
{
if (Equals(value, _City)) return;
_City = value;
NotifyPropertyChanged(m => m.City);
}
}
private string _City;
[DataMember]
public StateEnum? State
{
get { return _state; }
set
{
if (Equals(value, _state)) return;
_state = value;
NotifyPropertyChanged(m => m.State);
}
}
private StateEnum? _state;
[DataMember]
public string Zip
{
get { return _Zip; }
set
{
if (Equals(value, _Zip)) return;
_Zip = value;
NotifyPropertyChanged(m => m.Zip);
}
}
private string _Zip;
[DataMember]
public int? ApplicantId
{
get { return _ApplicantId; }
set
{
if (Equals(value, _ApplicantId)) return;
_ApplicantId = value;
NotifyPropertyChanged(m => m.ApplicantId);
}
}
private int? _ApplicantId;
[DataMember]
public Applicant Applicant
{
get { return _Applicant; }
set
{
if (Equals(value, _Applicant)) return;
_Applicant = value;
ApplicantChangeTracker = _Applicant == null ? null
: new ChangeTrackingCollection<Applicant> { _Applicant };
NotifyPropertyChanged(m => m.Applicant);
}
}
private Applicant _Applicant;
private ChangeTrackingCollection<Applicant> ApplicantChangeTracker { get; set; }
#region Change Tracking
[DataMember]
public TrackingState TrackingState { get; set; }
[DataMember]
public ICollection<string> ModifiedProperties { get; set; }
[JsonProperty, DataMember]
private Guid EntityIdentifier { get; set; }
#pragma warning disable 414
[JsonProperty, DataMember]
private Guid _entityIdentity = default(Guid);
#pragma warning restore 414
bool IEquatable<Education>.Equals(Education other)
{
if (EntityIdentifier != default(Guid))
return EntityIdentifier == other.EntityIdentifier;
return false;
}
#endregion Change Tracking
}
}
| |
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// There are 2 #defines that have an impact on performance of this ByteBuffer implementation
//
// UNSAFE_BYTEBUFFER
// This will use unsafe code to manipulate the underlying byte array. This
// can yield a reasonable performance increase.
//
// BYTEBUFFER_NO_BOUNDS_CHECK
// This will disable the bounds check asserts to the byte array. This can
// yield a small performance gain in normal code..
//
// Using UNSAFE_BYTEBUFFER and BYTEBUFFER_NO_BOUNDS_CHECK together can yield a
// performance gain of ~15% for some operations, however doing so is potentially
// dangerous. Do so at your own risk!
//
using System;
using System.IO;
using System.Text;
namespace FlatBuffers
{
/// <summary>
/// Class to mimic Java's ByteBuffer which is used heavily in Flatbuffers.
/// </summary>
public class ByteBuffer
{
protected byte[] _buffer;
private int _pos; // Must track start of the buffer.
public int Length { get { return _buffer.Length; } }
public ByteBuffer(int size) : this(new byte[size]) { }
public ByteBuffer(byte[] buffer) : this(buffer, 0) { }
public ByteBuffer(byte[] buffer, int pos)
{
_buffer = buffer;
_pos = pos;
}
public int Position {
get { return _pos; }
set { _pos = value; }
}
public void Reset()
{
_pos = 0;
}
// Create a new ByteBuffer on the same underlying data.
// The new ByteBuffer's position will be same as this buffer's.
public ByteBuffer Duplicate()
{
return new ByteBuffer(_buffer, Position);
}
// Increases the size of the ByteBuffer, and copies the old data towards
// the end of the new buffer.
public void GrowFront(int newSize)
{
if ((Length & 0xC0000000) != 0)
throw new Exception(
"ByteBuffer: cannot grow buffer beyond 2 gigabytes.");
if (newSize < Length)
throw new Exception("ByteBuffer: cannot truncate buffer.");
byte[] newBuffer = new byte[newSize];
Buffer.BlockCopy(_buffer, 0, newBuffer, newSize - Length,
Length);
_buffer = newBuffer;
}
public byte[] ToArray(int pos, int len)
{
byte[] arr = new byte[len];
Buffer.BlockCopy(_buffer, pos, arr, 0, len);
return arr;
}
public byte[] ToSizedArray()
{
return ToArray(Position, Length - Position);
}
public byte[] ToFullArray()
{
return ToArray(0, Length);
}
public ArraySegment<byte> ToArraySegment(int pos, int len)
{
return new ArraySegment<byte>(_buffer, pos, len);
}
public MemoryStream ToMemoryStream(int pos, int len)
{
return new MemoryStream(_buffer, pos, len);
}
#if !UNSAFE_BYTEBUFFER
// Pre-allocated helper arrays for convertion.
private float[] floathelper = new[] { 0.0f };
private int[] inthelper = new[] { 0 };
private double[] doublehelper = new[] { 0.0 };
private ulong[] ulonghelper = new[] { 0UL };
#endif // !UNSAFE_BYTEBUFFER
// Helper functions for the unsafe version.
static public ushort ReverseBytes(ushort input)
{
return (ushort)(((input & 0x00FFU) << 8) |
((input & 0xFF00U) >> 8));
}
static public uint ReverseBytes(uint input)
{
return ((input & 0x000000FFU) << 24) |
((input & 0x0000FF00U) << 8) |
((input & 0x00FF0000U) >> 8) |
((input & 0xFF000000U) >> 24);
}
static public ulong ReverseBytes(ulong input)
{
return (((input & 0x00000000000000FFUL) << 56) |
((input & 0x000000000000FF00UL) << 40) |
((input & 0x0000000000FF0000UL) << 24) |
((input & 0x00000000FF000000UL) << 8) |
((input & 0x000000FF00000000UL) >> 8) |
((input & 0x0000FF0000000000UL) >> 24) |
((input & 0x00FF000000000000UL) >> 40) |
((input & 0xFF00000000000000UL) >> 56));
}
#if !UNSAFE_BYTEBUFFER
// Helper functions for the safe (but slower) version.
protected void WriteLittleEndian(int offset, int count, ulong data)
{
if (BitConverter.IsLittleEndian)
{
for (int i = 0; i < count; i++)
{
_buffer[offset + i] = (byte)(data >> i * 8);
}
}
else
{
for (int i = 0; i < count; i++)
{
_buffer[offset + count - 1 - i] = (byte)(data >> i * 8);
}
}
}
protected ulong ReadLittleEndian(int offset, int count)
{
AssertOffsetAndLength(offset, count);
ulong r = 0;
if (BitConverter.IsLittleEndian)
{
for (int i = 0; i < count; i++)
{
r |= (ulong)_buffer[offset + i] << i * 8;
}
}
else
{
for (int i = 0; i < count; i++)
{
r |= (ulong)_buffer[offset + count - 1 - i] << i * 8;
}
}
return r;
}
#endif // !UNSAFE_BYTEBUFFER
private void AssertOffsetAndLength(int offset, int length)
{
#if !BYTEBUFFER_NO_BOUNDS_CHECK
if (offset < 0 ||
offset > _buffer.Length - length)
throw new ArgumentOutOfRangeException();
#endif
}
public void PutSbyte(int offset, sbyte value)
{
AssertOffsetAndLength(offset, sizeof(sbyte));
_buffer[offset] = (byte)value;
}
public void PutByte(int offset, byte value)
{
AssertOffsetAndLength(offset, sizeof(byte));
_buffer[offset] = value;
}
public void PutByte(int offset, byte value, int count)
{
AssertOffsetAndLength(offset, sizeof(byte) * count);
for (var i = 0; i < count; ++i)
_buffer[offset + i] = value;
}
// this method exists in order to conform with Java ByteBuffer standards
public void Put(int offset, byte value)
{
PutByte(offset, value);
}
public void PutStringUTF8(int offset, string value)
{
AssertOffsetAndLength(offset, value.Length);
Encoding.UTF8.GetBytes(value, 0, value.Length,
_buffer, offset);
}
#if UNSAFE_BYTEBUFFER
// Unsafe but more efficient versions of Put*.
public void PutShort(int offset, short value)
{
PutUshort(offset, (ushort)value);
}
public unsafe void PutUshort(int offset, ushort value)
{
AssertOffsetAndLength(offset, sizeof(ushort));
fixed (byte* ptr = _buffer)
{
*(ushort*)(ptr + offset) = BitConverter.IsLittleEndian
? value
: ReverseBytes(value);
}
}
public void PutInt(int offset, int value)
{
PutUint(offset, (uint)value);
}
public unsafe void PutUint(int offset, uint value)
{
AssertOffsetAndLength(offset, sizeof(uint));
fixed (byte* ptr = _buffer)
{
*(uint*)(ptr + offset) = BitConverter.IsLittleEndian
? value
: ReverseBytes(value);
}
}
public unsafe void PutLong(int offset, long value)
{
PutUlong(offset, (ulong)value);
}
public unsafe void PutUlong(int offset, ulong value)
{
AssertOffsetAndLength(offset, sizeof(ulong));
fixed (byte* ptr = _buffer)
{
*(ulong*)(ptr + offset) = BitConverter.IsLittleEndian
? value
: ReverseBytes(value);
}
}
public unsafe void PutFloat(int offset, float value)
{
AssertOffsetAndLength(offset, sizeof(float));
fixed (byte* ptr = _buffer)
{
if (BitConverter.IsLittleEndian)
{
*(float*)(ptr + offset) = value;
}
else
{
*(uint*)(ptr + offset) = ReverseBytes(*(uint*)(&value));
}
}
}
public unsafe void PutDouble(int offset, double value)
{
AssertOffsetAndLength(offset, sizeof(double));
fixed (byte* ptr = _buffer)
{
if (BitConverter.IsLittleEndian)
{
*(double*)(ptr + offset) = value;
}
else
{
*(ulong*)(ptr + offset) = ReverseBytes(*(ulong*)(ptr + offset));
}
}
}
#else // !UNSAFE_BYTEBUFFER
// Slower versions of Put* for when unsafe code is not allowed.
public void PutShort(int offset, short value)
{
AssertOffsetAndLength(offset, sizeof(short));
WriteLittleEndian(offset, sizeof(short), (ulong)value);
}
public void PutUshort(int offset, ushort value)
{
AssertOffsetAndLength(offset, sizeof(ushort));
WriteLittleEndian(offset, sizeof(ushort), (ulong)value);
}
public void PutInt(int offset, int value)
{
AssertOffsetAndLength(offset, sizeof(int));
WriteLittleEndian(offset, sizeof(int), (ulong)value);
}
public void PutUint(int offset, uint value)
{
AssertOffsetAndLength(offset, sizeof(uint));
WriteLittleEndian(offset, sizeof(uint), (ulong)value);
}
public void PutLong(int offset, long value)
{
AssertOffsetAndLength(offset, sizeof(long));
WriteLittleEndian(offset, sizeof(long), (ulong)value);
}
public void PutUlong(int offset, ulong value)
{
AssertOffsetAndLength(offset, sizeof(ulong));
WriteLittleEndian(offset, sizeof(ulong), value);
}
public void PutFloat(int offset, float value)
{
AssertOffsetAndLength(offset, sizeof(float));
floathelper[0] = value;
Buffer.BlockCopy(floathelper, 0, inthelper, 0, sizeof(float));
WriteLittleEndian(offset, sizeof(float), (ulong)inthelper[0]);
}
public void PutDouble(int offset, double value)
{
AssertOffsetAndLength(offset, sizeof(double));
doublehelper[0] = value;
Buffer.BlockCopy(doublehelper, 0, ulonghelper, 0, sizeof(double));
WriteLittleEndian(offset, sizeof(double), ulonghelper[0]);
}
#endif // UNSAFE_BYTEBUFFER
public sbyte GetSbyte(int index)
{
AssertOffsetAndLength(index, sizeof(sbyte));
return (sbyte)_buffer[index];
}
public byte Get(int index)
{
AssertOffsetAndLength(index, sizeof(byte));
return _buffer[index];
}
public string GetStringUTF8(int startPos, int len)
{
return Encoding.UTF8.GetString(_buffer, startPos, len);
}
#if UNSAFE_BYTEBUFFER
// Unsafe but more efficient versions of Get*.
public short GetShort(int offset)
{
return (short)GetUshort(offset);
}
public unsafe ushort GetUshort(int offset)
{
AssertOffsetAndLength(offset, sizeof(ushort));
fixed (byte* ptr = _buffer)
{
return BitConverter.IsLittleEndian
? *(ushort*)(ptr + offset)
: ReverseBytes(*(ushort*)(ptr + offset));
}
}
public int GetInt(int offset)
{
return (int)GetUint(offset);
}
public unsafe uint GetUint(int offset)
{
AssertOffsetAndLength(offset, sizeof(uint));
fixed (byte* ptr = _buffer)
{
return BitConverter.IsLittleEndian
? *(uint*)(ptr + offset)
: ReverseBytes(*(uint*)(ptr + offset));
}
}
public long GetLong(int offset)
{
return (long)GetUlong(offset);
}
public unsafe ulong GetUlong(int offset)
{
AssertOffsetAndLength(offset, sizeof(ulong));
fixed (byte* ptr = _buffer)
{
return BitConverter.IsLittleEndian
? *(ulong*)(ptr + offset)
: ReverseBytes(*(ulong*)(ptr + offset));
}
}
public unsafe float GetFloat(int offset)
{
AssertOffsetAndLength(offset, sizeof(float));
fixed (byte* ptr = _buffer)
{
if (BitConverter.IsLittleEndian)
{
return *(float*)(ptr + offset);
}
else
{
uint uvalue = ReverseBytes(*(uint*)(ptr + offset));
return *(float*)(&uvalue);
}
}
}
public unsafe double GetDouble(int offset)
{
AssertOffsetAndLength(offset, sizeof(double));
fixed (byte* ptr = _buffer)
{
if (BitConverter.IsLittleEndian)
{
return *(double*)(ptr + offset);
}
else
{
ulong uvalue = ReverseBytes(*(ulong*)(ptr + offset));
return *(double*)(&uvalue);
}
}
}
#else // !UNSAFE_BYTEBUFFER
// Slower versions of Get* for when unsafe code is not allowed.
public short GetShort(int index)
{
return (short)ReadLittleEndian(index, sizeof(short));
}
public ushort GetUshort(int index)
{
return (ushort)ReadLittleEndian(index, sizeof(ushort));
}
public int GetInt(int index)
{
return (int)ReadLittleEndian(index, sizeof(int));
}
public uint GetUint(int index)
{
return (uint)ReadLittleEndian(index, sizeof(uint));
}
public long GetLong(int index)
{
return (long)ReadLittleEndian(index, sizeof(long));
}
public ulong GetUlong(int index)
{
return ReadLittleEndian(index, sizeof(ulong));
}
public float GetFloat(int index)
{
int i = (int)ReadLittleEndian(index, sizeof(float));
inthelper[0] = i;
Buffer.BlockCopy(inthelper, 0, floathelper, 0, sizeof(float));
return floathelper[0];
}
public double GetDouble(int index)
{
ulong i = ReadLittleEndian(index, sizeof(double));
// There's Int64BitsToDouble but it uses unsafe code internally.
ulonghelper[0] = i;
Buffer.BlockCopy(ulonghelper, 0, doublehelper, 0, sizeof(double));
return doublehelper[0];
}
#endif // UNSAFE_BYTEBUFFER
}
}
| |
/*
* Copyright (c) 2014 All Rights Reserved by the SDL Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.Xml;
using System.Xml.Linq;
using Trisoft.ISHRemote.Objects;
using Trisoft.ISHRemote.Objects.Public;
using Trisoft.ISHRemote.Exceptions;
namespace Trisoft.ISHRemote.Cmdlets.Settings
{
/// <summary>
/// <para type="synopsis">This cmdlet can be used to get a configuration setting from the repository. Depending on the parameters you use, the setting will be returned differently.
/// If you provide:
/// * A requested metadata parameter with the fields to get, the setting will be return as IshFields
/// * A fieldname and no filepath, the setting will be returned as string
/// * A fieldname and a filepath, the setting will be saved to the file.
/// If the file is already present, providing -Force will allow you to overwrite the file</para>
/// <para type="description">This cmdlet can be used to get a configuration setting from the repository. Depending on the parameters you use, the setting will be returned differently.
/// If you provide:
/// * A requested metadata parameter with the fields to get, the setting will be return as IshFields
/// * A fieldname and no filepath, the setting will be returned as string
/// * A fieldname and a filepath, the setting will be saved to the file.
/// If the file is already present, providing -Force will allow you to overwrite the file</para>
/// </summary>
/// <example>
/// <code>
/// New-IshSession -WsBaseUrl "https://example.com/ISHWS/" -PSCredential "Admin"
/// $settingsFolderPath = 'C:\temp'
/// Write-Verbose "Saving in $settingsFolderPath"
/// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLInboxConfiguration.xml"
/// Get-IshSetting -FieldName "FINBOXCONFIGURATION" -FilePath $filePath
/// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLBackgroundTaskConfiguration.xml"
/// Get-IshSetting -FieldName "FISHBACKGROUNDTASKCONFIG" -FilePath $filePath
/// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLChangeTrackerConfig.xml"
/// Get-IshSetting -FieldName "FISHCHANGETRACKERCONFIG" -FilePath $filePath
/// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLExtensionConfiguration.xml"
/// Get-IshSetting -FieldName "FISHEXTENSIONCONFIG" -FilePath $filePath
/// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLPluginConfig.xml"
/// Get-IshSetting -FieldName "FISHPLUGINCONFIGXML" -FilePath $filePath
/// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLStatusConfiguration.xml"
/// Get-IshSetting -FieldName "FSTATECONFIGURATION" -FilePath $filePath
/// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLTranslationConfiguration.xml"
/// Get-IshSetting -FieldName "FTRANSLATIONCONFIGURATION" -FilePath $filePath
/// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLWriteObjPluginConfig.xml"
/// Get-IshSetting -FieldName "FISHWRITEOBJPLUGINCFG" -FilePath $filePath
/// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLPublishPluginConfiguration.xml"
/// Get-IshSetting -FieldName "FISHPUBLISHPLUGINCONFIG" -FilePath $filePath
/// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLCollectiveSpacesConfiguration.xml"
/// Get-IshSetting -FieldName "FISHCOLLECTIVESPACESCFG" -FilePath $filePath
/// Write-Host "Done, see $settingsFolderPath"
/// </code>
/// <para>Retrieve all Settings xml configuration entries and save them in a folder to desk allowing file-to-file comparison with EnterViaUI folder.</para>
/// </example>
[Cmdlet(VerbsCommon.Get, "IshSetting", SupportsShouldProcess = false)]
[OutputType(typeof(IshField),typeof(FileInfo),typeof(string))]
public sealed class GetIshSetting : SettingsCmdlet
{
/// <summary>
/// <para type="description">The IshSession variable holds the authentication and contract information. This object can be initialized using the New-IshSession cmdlet.</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "RequestedMetadataGroup")]
[ValidateNotNullOrEmpty]
public IshSession IshSession { get; set; }
/// <summary>
/// <para type="description">The metadata fields to retrieve</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "RequestedMetadataGroup")]
[ValidateNotNull]
public IshField[] RequestedMetadata { get; set; }
/// <summary>
/// <para type="description">The settings field to retrieve</para>
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")]
[ValidateNotNullOrEmpty]
public string FieldName { get; set; }
/// <summary>
/// <para type="description">The value type</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")]
public Enumerations.ValueType ValueType
{
get { return _valueType; }
set { _valueType = value; }
}
/// <summary>
/// <para type="description">File on the Windows filesystem where to save the retrieved setting</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")]
[ValidateNotNullOrEmpty]
public string FilePath { get; set; }
/// <summary>
/// <para type="description">When set, will override the file when it already exists</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")]
[ValidateNotNullOrEmpty]
public SwitchParameter Force { get; set; }
#region Private fields
/// <summary>
/// Private fields to store the parameters and provide a default for non-mandatory parameters
/// </summary>
private Enumerations.ValueType _valueType = Enumerations.ValueType.Value;
#endregion
protected override void BeginProcessing()
{
if (IshSession == null) { IshSession = (IshSession)SessionState.PSVariable.GetValue(ISHRemoteSessionStateIshSession); }
if (IshSession == null) { throw new ArgumentException(ISHRemoteSessionStateIshSessionException); }
WriteDebug($"Using IshSession[{IshSession.Name}] from SessionState.{ISHRemoteSessionStateIshSession}");
base.BeginProcessing();
}
protected override void ProcessRecord()
{
try
{
// 2. Retrieve the updated material from the database and write it out
WriteDebug("Retrieving");
IshFields requestedMetadata = new IshFields();
if (RequestedMetadata != null)
{
requestedMetadata = new IshFields(RequestedMetadata);
}
else if (FieldName != null)
{
requestedMetadata.AddField(new IshRequestedMetadataField(FieldName, Enumerations.Level.None, ValueType));
}
var metadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, requestedMetadata, Enumerations.ActionMode.Read);
string xmlIshObjects = IshSession.Settings25.GetMetadata(metadata.ToXml());
var ishFields = new IshObjects(xmlIshObjects).Objects[0].IshFields;
if (FieldName == null)
{
// 3. Write it
WriteVerbose("returned object count[1]");
WriteObject(ishFields.Fields(), true);
}
else if (FieldName != null)
{
if (FilePath != null)
{
//Create the file.
Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
var fileMode = (Force.IsPresent) ? FileMode.Create : FileMode.CreateNew;
string value = ishFields.GetFieldValue(FieldName, Enumerations.Level.None, ValueType);
if (!String.IsNullOrEmpty(value))
{
try
{
// Let's try to see if it is xml first
var doc = XDocument.Parse(value);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (var stream = new FileStream(FilePath, fileMode, FileAccess.Write))
{
using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings))
{
doc.Save(xmlWriter);
}
}
}
catch (Exception)
{
// remove potential readonly flag
if (File.Exists(FilePath))
{
File.SetAttributes(FilePath, FileAttributes.Normal);
}
// Write it as a text file
Stream stream = null;
try
{
stream = new FileStream(FilePath, fileMode, FileAccess.ReadWrite);
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
{
stream = null;
writer.Write(value);
}
}
finally
{
if (stream != null)
stream.Dispose();
}
}
}
WriteVerbose("returned object count[1]");
WriteObject(new FileInfo(FilePath));
}
else
{
WriteVerbose("returned object count[1]");
WriteObject(ishFields.GetFieldValue(FieldName, Enumerations.Level.None, ValueType));
}
}
}
catch (TrisoftAutomationException trisoftAutomationException)
{
ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null));
}
catch (Exception exception)
{
ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null));
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using NUnit.Framework;
using NUnit.Framework.Constraints;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Tests.Common;
namespace OpenSim.Data.Tests
{
public static class Constraints
{
//This is here because C# has a gap in the language, you can't infer type from a constructor
public static PropertyCompareConstraint<T> PropertyCompareConstraint<T>(T expected)
{
return new PropertyCompareConstraint<T>(expected);
}
}
public class PropertyCompareConstraint<T> : NUnit.Framework.Constraints.Constraint
{
private readonly object _expected;
//the reason everywhere uses propertyNames.Reverse().ToArray() is because the stack is backwards of the order we want to display the properties in.
private string failingPropertyName = string.Empty;
private object failingExpected;
private object failingActual;
public PropertyCompareConstraint(T expected)
{
_expected = expected;
}
public override bool Matches(object actual)
{
return ObjectCompare(_expected, actual, new Stack<string>());
}
private bool ObjectCompare(object expected, object actual, Stack<string> propertyNames)
{
//If they are both null, they are equal
if (actual == null && expected == null)
return true;
//If only one is null, then they aren't
if (actual == null || expected == null)
{
failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
failingActual = actual;
failingExpected = expected;
return false;
}
//prevent loops...
if (propertyNames.Count > 50)
{
failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
failingActual = actual;
failingExpected = expected;
return false;
}
if (actual.GetType() != expected.GetType())
{
propertyNames.Push("GetType()");
failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
propertyNames.Pop();
failingActual = actual.GetType();
failingExpected = expected.GetType();
return false;
}
if (actual.GetType() == typeof(Color))
{
Color actualColor = (Color) actual;
Color expectedColor = (Color) expected;
if (actualColor.R != expectedColor.R)
{
propertyNames.Push("R");
failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
propertyNames.Pop();
failingActual = actualColor.R;
failingExpected = expectedColor.R;
return false;
}
if (actualColor.G != expectedColor.G)
{
propertyNames.Push("G");
failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
propertyNames.Pop();
failingActual = actualColor.G;
failingExpected = expectedColor.G;
return false;
}
if (actualColor.B != expectedColor.B)
{
propertyNames.Push("B");
failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
propertyNames.Pop();
failingActual = actualColor.B;
failingExpected = expectedColor.B;
return false;
}
if (actualColor.A != expectedColor.A)
{
propertyNames.Push("A");
failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
propertyNames.Pop();
failingActual = actualColor.A;
failingExpected = expectedColor.A;
return false;
}
return true;
}
IComparable comp = actual as IComparable;
if (comp != null)
{
if (comp.CompareTo(expected) != 0)
{
failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
failingActual = actual;
failingExpected = expected;
return false;
}
return true;
}
//Now try the much more annoying IComparable<T>
Type icomparableInterface = actual.GetType().GetInterface("IComparable`1");
if (icomparableInterface != null)
{
int result = (int)icomparableInterface.GetMethod("CompareTo").Invoke(actual, new[] { expected });
if (result != 0)
{
failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
failingActual = actual;
failingExpected = expected;
return false;
}
return true;
}
IEnumerable arr = actual as IEnumerable;
if (arr != null)
{
List<object> actualList = arr.Cast<object>().ToList();
List<object> expectedList = ((IEnumerable)expected).Cast<object>().ToList();
if (actualList.Count != expectedList.Count)
{
propertyNames.Push("Count");
failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray());
failingActual = actualList.Count;
failingExpected = expectedList.Count;
propertyNames.Pop();
return false;
}
//actualList and expectedList should be the same size.
for (int i = 0; i < actualList.Count; i++)
{
propertyNames.Push("[" + i + "]");
if (!ObjectCompare(expectedList[i], actualList[i], propertyNames))
return false;
propertyNames.Pop();
}
//Everything seems okay...
return true;
}
//Skip static properties. I had a nasty problem comparing colors because of all of the public static colors.
PropertyInfo[] properties = expected.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
if (ignores.Contains(property.Name))
continue;
object actualValue = property.GetValue(actual, null);
object expectedValue = property.GetValue(expected, null);
propertyNames.Push(property.Name);
if (!ObjectCompare(expectedValue, actualValue, propertyNames))
return false;
propertyNames.Pop();
}
return true;
}
public override void WriteDescriptionTo(MessageWriter writer)
{
writer.WriteExpectedValue(failingExpected);
}
public override void WriteActualValueTo(MessageWriter writer)
{
writer.WriteActualValue(failingActual);
writer.WriteLine();
writer.Write(" On Property: " + failingPropertyName);
}
//These notes assume the lambda: (x=>x.Parent.Value)
//ignores should really contain like a fully dotted version of the property name, but I'm starting with small steps
readonly List<string> ignores = new List<string>();
public PropertyCompareConstraint<T> IgnoreProperty(Expression<Func<T, object>> func)
{
Expression express = func.Body;
PullApartExpression(express);
return this;
}
private void PullApartExpression(Expression express)
{
//This deals with any casts... like implicit casts to object. Not all UnaryExpression are casts, but this is a first attempt.
if (express is UnaryExpression)
PullApartExpression(((UnaryExpression)express).Operand);
if (express is MemberExpression)
{
//If the inside of the lambda is the access to x, we've hit the end of the chain.
// We should track by the fully scoped parameter name, but this is the first rev of doing this.
ignores.Add(((MemberExpression)express).Member.Name);
}
}
}
[TestFixture]
public class PropertyCompareConstraintTest : OpenSimTestCase
{
public class HasInt
{
public int TheValue { get; set; }
}
[Test]
public void IntShouldMatch()
{
HasInt actual = new HasInt { TheValue = 5 };
HasInt expected = new HasInt { TheValue = 5 };
var constraint = Constraints.PropertyCompareConstraint(expected);
Assert.That(constraint.Matches(actual), Is.True);
}
[Test]
public void IntShouldNotMatch()
{
HasInt actual = new HasInt { TheValue = 5 };
HasInt expected = new HasInt { TheValue = 4 };
var constraint = Constraints.PropertyCompareConstraint(expected);
Assert.That(constraint.Matches(actual), Is.False);
}
[Test]
public void IntShouldIgnore()
{
HasInt actual = new HasInt { TheValue = 5 };
HasInt expected = new HasInt { TheValue = 4 };
var constraint = Constraints.PropertyCompareConstraint(expected).IgnoreProperty(x => x.TheValue);
Assert.That(constraint.Matches(actual), Is.True);
}
[Test]
public void AssetShouldMatch()
{
UUID uuid1 = UUID.Random();
AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString());
AssetBase expected = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString());
var constraint = Constraints.PropertyCompareConstraint(expected);
Assert.That(constraint.Matches(actual), Is.True);
}
[Test]
public void AssetShouldNotMatch()
{
UUID uuid1 = UUID.Random();
AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString());
AssetBase expected = new AssetBase(UUID.Random(), "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString());
var constraint = Constraints.PropertyCompareConstraint(expected);
Assert.That(constraint.Matches(actual), Is.False);
}
[Test]
public void AssetShouldNotMatch2()
{
UUID uuid1 = UUID.Random();
AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString());
AssetBase expected = new AssetBase(uuid1, "asset two", (sbyte)AssetType.Texture, UUID.Zero.ToString());
var constraint = Constraints.PropertyCompareConstraint(expected);
Assert.That(constraint.Matches(actual), Is.False);
}
[Test]
public void UUIDShouldMatch()
{
UUID uuid1 = UUID.Random();
UUID uuid2 = UUID.Parse(uuid1.ToString());
var constraint = Constraints.PropertyCompareConstraint(uuid1);
Assert.That(constraint.Matches(uuid2), Is.True);
}
[Test]
public void UUIDShouldNotMatch()
{
UUID uuid1 = UUID.Random();
UUID uuid2 = UUID.Random();
var constraint = Constraints.PropertyCompareConstraint(uuid1);
Assert.That(constraint.Matches(uuid2), Is.False);
}
[Test]
public void TestColors()
{
Color actual = Color.Red;
Color expected = Color.FromArgb(actual.A, actual.R, actual.G, actual.B);
var constraint = Constraints.PropertyCompareConstraint(expected);
Assert.That(constraint.Matches(actual), Is.True);
}
[Test]
public void ShouldCompareLists()
{
List<int> expected = new List<int> { 1, 2, 3 };
List<int> actual = new List<int> { 1, 2, 3 };
var constraint = Constraints.PropertyCompareConstraint(expected);
Assert.That(constraint.Matches(actual), Is.True);
}
[Test]
public void ShouldFailToCompareListsThatAreDifferent()
{
List<int> expected = new List<int> { 1, 2, 3 };
List<int> actual = new List<int> { 1, 2, 4 };
var constraint = Constraints.PropertyCompareConstraint(expected);
Assert.That(constraint.Matches(actual), Is.False);
}
[Test]
public void ShouldFailToCompareListsThatAreDifferentLengths()
{
List<int> expected = new List<int> { 1, 2, 3 };
List<int> actual = new List<int> { 1, 2 };
var constraint = Constraints.PropertyCompareConstraint(expected);
Assert.That(constraint.Matches(actual), Is.False);
}
public class Recursive
{
public Recursive Other { get; set; }
}
[Test]
public void ErrorsOutOnRecursive()
{
Recursive parent = new Recursive();
Recursive child = new Recursive();
parent.Other = child;
child.Other = parent;
var constraint = Constraints.PropertyCompareConstraint(child);
Assert.That(constraint.Matches(child), Is.False);
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="ObjectDataProvider.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description: Implementation of ObjectDataProvider object.
//
// Specs: http://avalon/connecteddata/Specs/Avalon%20DataProviders.mht
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Windows.Threading;
using System.Threading;
using System.Windows;
using System.Windows.Data;
using MS.Internal;
using MS.Internal.Data; // ParameterCollection
using System.Windows.Markup;
//---------------------------------------------------------------------------
// Design notes:
//
// ObjectDataProvider uses Activator.CreateInstance() to instantiate a new
// ObjectInstance and Type.InvokeMember() to call a member on the object.
//
// Another way to write this class is through using ConstructorInfo and
// MethodInfo, it would allow some nice things like caching the MemberInfo
// and changing it only when the MethodParameters was changed in a
// significant way.
// However, it was discovered that Type.GetConstructorInfo() and
// Type.GetMethodInfo() need to know all the types of the parameters for
// member matching. This means that any null parameter may foil the match.
//
// By using Activator.CreateInstance() and Type.InvokeMember(), we get to
// take advantage of more of the "magic" that finds the best matched
// constructor/method with the given parameters.
//
// Security info:
//
// ObjectDataProvider will fail (as it should) when it does not have
// permissions to perform reflection on the given Type or Member.
//---------------------------------------------------------------------------
namespace System.Windows.Data
{
/// <summary>
/// The ObjectDataProvider class defines an object
/// that instantiates a business object for use as a source for data binding.
/// </summary>
[Localizability(LocalizationCategory.NeverLocalize)] // Not localizable
public class ObjectDataProvider : DataSourceProvider
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Instantiates a new instance of a ObjectDataProvider
/// </summary>
public ObjectDataProvider()
{
_constructorParameters = new ParameterCollection(new ParameterCollectionChanged(OnParametersChanged));
_methodParameters = new ParameterCollection(new ParameterCollectionChanged(OnParametersChanged));
_sourceDataChangedHandler = new EventHandler(OnSourceDataChanged);
}
#endregion Constructors
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// The type to instantiate for use as ObjectInstance.
/// This is null when the ObjectDataProvider is uninitialized or explicitly set to null.
/// If the user makes an assignment to ObjectInstance, ObjectType will return
/// the Type of the object (or null if the object is null).
/// </summary>
/// <remarks>
/// Only one of ObjectType or ObjectInstance can be set by the user to a non-null value.
/// While refresh is deferred, ObjectInstance and Data will not update until Refresh() is called.
/// </remarks>
public Type ObjectType
{
get { return _objectType; }
set
{
// User is only allowed to set one of ObjectType or ObjectInstance.
// To change "mode", the user must null the other property first.
if (_mode == SourceMode.FromInstance)
throw new InvalidOperationException(SR.Get(SRID.ObjectDataProviderCanHaveOnlyOneSource));
_mode = (value == null) ? SourceMode.NoSource : SourceMode.FromType;
_constructorParameters.SetReadOnly(false);
if (_needNewInstance = SetObjectType(value)) // raises property changed event
{
// Note: ObjectInstance and Data are not updated until Refresh() happens!
if (! IsRefreshDeferred)
Refresh();
}
}
}
/// <summary>
/// This method is used by TypeDescriptor to determine if this property should
/// be serialized.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeObjectType()
{
return (_mode == SourceMode.FromType) && (ObjectType != null);
}
/// <summary>
/// When ObjectType is set to a non-null value, this holds the
/// instantiated object of the Type specified in ObjectType.
/// If ObjectInstance is assigned by the user, ObjectType property will reflect the Type
/// of the assigned object.
/// If a DataSourceProvider is assigned to ObjectInstance, ObjectDataProvider will
/// use the Data of the assigned source provider as its effective ObjectInstance.
/// </summary>
/// <returns>
/// The instance of object constructed from ObjectType and ConstructorParameters. -or-
/// The DataSourceProvider whose Data is used as ObjectInstance.
/// </returns>
/// <remarks>
/// Only one of ObjectType or ObjectInstance can be set by the user to a non-null value.
/// This property, like the Data property, honors DeferRefresh: after setting the ObjectType,
/// ObjectInstance will not be filled until Refresh() happens.
/// </remarks>
public object ObjectInstance
{
get
{
return (_instanceProvider != null) ? _instanceProvider : _objectInstance;
}
set
{
// User is only allowed to set one of ObjectType or ObjectInstance.
// To change mode, the user must null the property first.
if (_mode == SourceMode.FromType)
throw new InvalidOperationException(SR.Get(SRID.ObjectDataProviderCanHaveOnlyOneSource));
_mode = (value == null) ? SourceMode.NoSource : SourceMode.FromInstance;
if (ObjectInstance == value) // instance or provider has not changed, do nothing
{
// debug-only sanity check, since GetType() isn't that cheap;
// using _objectInstance because we're not trying to check the type of the provider!
Debug.Assert((_objectInstance == null) ? (_objectType == null) : (_objectType == _objectInstance.GetType()));
return;
}
if (value != null)
{
_constructorParameters.SetReadOnly(true);
_constructorParameters.ClearInternal();
}
else
{
_constructorParameters.SetReadOnly(false);
}
value = TryInstanceProvider(value); // returns the real instance
// this also updates ObjectType if necessary:
if (SetObjectInstance(value)) // raises property changed event
{
// Note: Data is not updated until Refresh() happens!
if (! IsRefreshDeferred)
Refresh();
}
}
}
/// <summary>
/// This method is used by TypeDescriptor to determine if this property should
/// be serialized.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeObjectInstance()
{
return (_mode == SourceMode.FromInstance) && (ObjectInstance != null);
}
/// <summary>
/// The name of the method to call on the specified type.
/// </summary>
[DefaultValue(null)]
public string MethodName
{
get { return _methodName; }
set
{
_methodName = value;
OnPropertyChanged(s_method);
if (!IsRefreshDeferred)
Refresh();
}
}
/// <summary>
/// Parameters to pass to the Constructor
/// </summary>
/// <remarks>
/// Changing this collection will implicitly cause this DataProvider to refresh.
/// When changing multiple refresh-causing properties, the use of
/// <seealso cref="DataSourceProvider.DeferRefresh"/> is recommended.
/// ConstuctorParameters becomes empty and read-only when
/// ObjectInstance is assigned a value by the user.
/// </remarks>
public IList ConstructorParameters
{
get { return _constructorParameters; }
}
/// <summary>
/// This method is used by TypeDescriptor to determine if this property should
/// be serialized.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeConstructorParameters()
{
return (_mode == SourceMode.FromType) && (_constructorParameters.Count > 0);
}
/// <summary>
/// Parameters to pass to the Method
/// </summary>
/// <remarks>
/// Changing this collection will implicitly cause this DataProvider to refresh.
/// When changing multiple refresh-causing properties, the use of
/// <seealso cref="DataSourceProvider.DeferRefresh"/> is recommended.
/// </remarks>
public IList MethodParameters
{
get { return _methodParameters; }
}
/// <summary>
/// This method is used by TypeDescriptor to determine if this property should
/// be serialized.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeMethodParameters()
{
return _methodParameters.Count > 0;
}
/// <summary>
/// If true object creation will be performed in a worker
/// thread, otherwise will be done in active context.
/// </summary>
[DefaultValue(false)]
public bool IsAsynchronous
{
get { return _isAsynchronous; }
set { _isAsynchronous = value; OnPropertyChanged(s_async); }
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Start instantiating the requested object, either immediately
/// or on a background thread, see IsAsynchronous.
/// Called by base class from InitialLoad or Refresh
/// </summary>
protected override void BeginQuery()
{
if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.ProviderQuery))
{
TraceData.Trace(TraceEventType.Warning,
TraceData.BeginQuery(
TraceData.Identify(this),
IsAsynchronous ? "asynchronous" : "synchronous"));
}
if (IsAsynchronous)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(QueryWorker), null);
}
else
{
QueryWorker(null);
}
}
#endregion Protected Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
// if the passed in value was a DataSourceProvider,
// start listening to the (new) provider, and returns the instance value;
// else just return the value.
private object TryInstanceProvider(object value)
{
if (_instanceProvider != null) // was using provider for source
{
// stop listening to old provider
_instanceProvider.DataChanged -= _sourceDataChangedHandler;
}
_instanceProvider = value as DataSourceProvider;
if (_instanceProvider != null)
{
// start listening to new provider
_instanceProvider.DataChanged += _sourceDataChangedHandler;
value = _instanceProvider.Data;
}
return value;
}
// called from ObjectInstance setter or from source provider data change event handler;
// raises property changed event;
// return true iff ObjectInstance is changed
private bool SetObjectInstance(object value)
{
// In FromType mode, _objectInstance is set in CreateObjectInstance()
Debug.Assert(_mode != SourceMode.FromType);
if (_objectInstance == value)
return false;
_objectInstance = value;
// set the objectType by looking at the new value
SetObjectType((value != null) ? value.GetType() : null);
// raise this change event AFTER both oType and oInstance are updated
OnPropertyChanged(s_instance);
return true;
}
// raises property changed event;
// return true iff ObjectType is changed
private bool SetObjectType(Type newType)
{
if (_objectType != newType)
{
_objectType = newType;
OnPropertyChanged(s_type);
return true;
}
return false;
}
void QueryWorker(object obj)
{
object data = null;
Exception e = null; // exception to pass back to main thread
if (_mode == SourceMode.NoSource || _objectType == null)
{
if (TraceData.IsEnabled)
TraceData.Trace(TraceEventType.Error, TraceData.ObjectDataProviderHasNoSource);
e = new InvalidOperationException(SR.Get(SRID.ObjectDataProviderHasNoSource));
}
else
{
Exception exInstantiation = null;
if (_needNewInstance && (_mode == SourceMode.FromType))
{
// check if there are public constructors before trying to instantiate;
// this isn't cheap (and is redundant), but it should be better than throwing an exception.
ConstructorInfo[] ciAry = _objectType.GetConstructors();
if (ciAry.Length != 0)
{
_objectInstance = CreateObjectInstance(out exInstantiation);
}
// don't try to instantiate again until type/parameters change
_needNewInstance = false;
}
// keep going even if there's no ObjectInstance; method might be static.
if (string.IsNullOrEmpty(MethodName))
{
data = _objectInstance;
}
else
{
data = InvokeMethodOnInstance(out e);
if (e != null && exInstantiation != null)
{
// if InvokeMethod failed, we prefer to surface the instantiation error, if any.
// (although this can be confusing if the user wanted to call a static method)
e = exInstantiation;
}
}
}
if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.ProviderQuery))
{
TraceData.Trace(TraceEventType.Warning,
TraceData.QueryFinished(
TraceData.Identify(this),
Dispatcher.CheckAccess() ? "synchronous" : "asynchronous",
TraceData.Identify(data),
TraceData.IdentifyException(e)));
}
OnQueryFinished(data, e, null, null);
}
object CreateObjectInstance(out Exception e)
{
object instance = null;
string error = null; // string that describes known error
e = null;
// PreSharp uses message numbers that the C# compiler doesn't know about.
// Disable the C# complaints, per the PreSharp documentation.
#pragma warning disable 1634, 1691
// PreSharp complains about catching NullReference (and other) exceptions.
// It doesn't recognize that IsCritical[Application]Exception() handles these correctly.
#pragma warning disable 56500
Debug.Assert(_objectType != null);
try
{
object[] parameters = new object[_constructorParameters.Count];
_constructorParameters.CopyTo(parameters, 0);
instance = Activator.CreateInstance(_objectType, 0, null, parameters,
System.Globalization.CultureInfo.InvariantCulture);
OnPropertyChanged(s_instance);
}
catch (ArgumentException ae)
{
// this may fire when trying to create Context Affinity objects
error = "Cannot create Context Affinity object.";
e = ae;
}
catch (System.Runtime.InteropServices.COMException ce)
{
// this may fire due to marshalling issues
error = "Marshaling issue detected.";
e = ce;
}
catch (System.MissingMethodException mme)
{
// this may be due to setting parameters to a non parameter
// only class contructor
error = "Wrong parameters for constructor.";
e = mme;
}
// Catch all exceptions. When there is no app code on the stack,
// the exception isn't actionable by the app.
// Yet we don't want to crash the app.
catch (Exception ex)
{
if (CriticalExceptions.IsCriticalApplicationException(ex))
throw;
error = null; // indicate unknown error
e = ex;
}
catch // non CLS compliant exception
{
error = null; // indicate unknown error
e = new InvalidOperationException(SR.Get(SRID.ObjectDataProviderNonCLSException, _objectType.Name));
}
#pragma warning restore 56500
#pragma warning restore 1634, 1691
if (e != null || error != null)
{
// report known errors through TraceData (instead of throwing exceptions)
if (TraceData.IsEnabled)
TraceData.Trace(TraceEventType.Error, TraceData.ObjDPCreateFailed, _objectType.Name, error, e);
// in async mode we pass all exceptions to main thread;
// in [....] mode we don't handle unknown exceptions.
if (!IsAsynchronous && error == null)
throw e;
}
return instance;
}
object InvokeMethodOnInstance(out Exception e)
{
object data = null;
string error = null; // string that describes known error
e = null;
Debug.Assert(_objectType != null);
object[] parameters = new object[_methodParameters.Count];
_methodParameters.CopyTo(parameters, 0);
// PreSharp uses message numbers that the C# compiler doesn't know about.
// Disable the C# complaints, per the PreSharp documentation.
#pragma warning disable 1634, 1691
// PreSharp complains about catching NullReference (and other) exceptions.
// It doesn't recognize that IsCritical[Application]Exception() handles these correctly.
#pragma warning disable 56500
try
{
data = _objectType.InvokeMember(MethodName,
s_invokeMethodFlags, null, _objectInstance, parameters,
System.Globalization.CultureInfo.InvariantCulture);
}
catch (ArgumentException ae)
{
error = "Parameter array contains a string that is a null reference.";
e = ae;
}
catch (MethodAccessException mae)
{
error = "The specified member is a class initializer.";
e = mae;
}
catch (MissingMethodException mme)
{
error = "No method was found with matching parameter signature.";
e = mme;
}
catch (TargetException te)
{
error = "The specified member cannot be invoked on target.";
e = te;
}
catch (AmbiguousMatchException ame)
{
error = "More than one method matches the binding criteria.";
e = ame;
}
// Catch all exceptions. When there is no app code on the stack,
// the exception isn't actionable by the app.
// Yet we don't want to crash the app.
catch (Exception ex)
{
if (CriticalExceptions.IsCriticalApplicationException(ex))
{
throw;
}
error = null; // indicate unknown error
e = ex;
}
catch //FXCop Fix: CatchNonClsCompliantExceptionsInGeneralHandlers
{
error = null; // indicate unknown error
e = new InvalidOperationException(SR.Get(SRID.ObjectDataProviderNonCLSExceptionInvoke, MethodName, _objectType.Name));
}
#pragma warning restore 56500
#pragma warning restore 1634, 1691
if (e != null || error != null)
{
// report known errors through TraceData (instead of throwing exceptions)
if (TraceData.IsEnabled)
TraceData.Trace(TraceEventType.Error, TraceData.ObjDPInvokeFailed, MethodName, _objectType.Name, error, e);
// in async mode we pass all exceptions to main thread;
// in [....] mode we don't handle unknown exceptions.
if (!IsAsynchronous && error == null)
throw e;
}
return data;
}
// call-back function for the ParameterCollections
private void OnParametersChanged(ParameterCollection sender)
{
// if the ConstructorParameters change, remember to instantiate a new object
if (sender == _constructorParameters)
{
// sanity check: we shouldn't have ctor param changes in FromInstance mode
Invariant.Assert (_mode != SourceMode.FromInstance);
_needNewInstance = true;
}
// Note: ObjectInstance and Data are not updated until Refresh() happens!
if (!IsRefreshDeferred)
Refresh();
}
// handler for DataChanged event of the instance's DataSourceProvider
private void OnSourceDataChanged(object sender, EventArgs args)
{
Invariant.Assert(sender == _instanceProvider);
if (SetObjectInstance(_instanceProvider.Data))
{
// Note: Data is not updated until Refresh() happens!
if (! IsRefreshDeferred)
Refresh();
}
}
/// <summary>
/// Helper to raise a PropertyChanged event />).
/// </summary>
private void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Types
private enum SourceMode
{
NoSource, // can accept assignment to ObjectType or ObjectSource
FromType, // can accept assignment only to ObjectType
FromInstance, // can accept assignment only to ObjectInstance
}
#endregion Private Types
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
Type _objectType;
object _objectInstance;
string _methodName;
DataSourceProvider _instanceProvider;
ParameterCollection _constructorParameters;
ParameterCollection _methodParameters;
bool _isAsynchronous = false;
SourceMode _mode = SourceMode.NoSource;
bool _needNewInstance = true; // set to true when ObjectType or ConstructorParameters change
EventHandler _sourceDataChangedHandler;
const string s_instance = "ObjectInstance";
const string s_type = "ObjectType";
const string s_method = "MethodName";
const string s_async = "IsAsynchronous";
const BindingFlags s_invokeMethodFlags =
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.InvokeMethod |
BindingFlags.FlattenHierarchy |
BindingFlags.OptionalParamBinding;
#endregion Private Fields
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using Thrift.Collections;
using Thrift.Protocol;
using Thrift.Transport;
using Thrift.Test;
namespace Test
{
public class TestClient
{
private static int numIterations = 1;
private static string protocol = "";
public static void Execute(string[] args)
{
try
{
string host = "localhost";
int port = 9090;
string url = null, pipe = null;
int numThreads = 1;
bool buffered = false, framed = false, encrypted = false;
try
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-u")
{
url = args[++i];
}
else if (args[i] == "-n")
{
numIterations = Convert.ToInt32(args[++i]);
}
else if (args[i] == "-pipe") // -pipe <name>
{
pipe = args[++i];
Console.WriteLine("Using named pipes transport");
}
else if (args[i].Contains("--host="))
{
host = args[i].Substring(args[i].IndexOf("=") + 1);
}
else if (args[i].Contains("--port="))
{
port = int.Parse(args[i].Substring(args[i].IndexOf("=")+1));
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
buffered = true;
Console.WriteLine("Using buffered sockets");
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
framed = true;
Console.WriteLine("Using framed transport");
}
else if (args[i] == "-t")
{
numThreads = Convert.ToInt32(args[++i]);
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
protocol = "compact";
Console.WriteLine("Using compact protocol");
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
protocol = "json";
Console.WriteLine("Using JSON protocol");
}
else if (args[i] == "--ssl")
{
encrypted = true;
Console.WriteLine("Using encrypted transport");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
//issue tests on separate threads simultaneously
Thread[] threads = new Thread[numThreads];
DateTime start = DateTime.Now;
for (int test = 0; test < numThreads; test++)
{
Thread t = new Thread(new ParameterizedThreadStart(ClientThread));
threads[test] = t;
if (url == null)
{
// endpoint transport
TTransport trans = null;
if (pipe != null)
trans = new TNamedPipeClientTransport(pipe);
else
{
if (encrypted)
trans = new TTLSSocket(host, port, "../../../../../keys/client.pem");
else
trans = new TSocket(host, port);
}
// layered transport
if (buffered)
trans = new TBufferedTransport(trans as TStreamTransport);
if (framed)
trans = new TFramedTransport(trans);
//ensure proper open/close of transport
trans.Open();
trans.Close();
t.Start(trans);
}
else
{
THttpClient http = new THttpClient(new Uri(url));
t.Start(http);
}
}
for (int test = 0; test < numThreads; test++)
{
threads[test].Join();
}
Console.Write("Total time: " + (DateTime.Now - start));
}
catch (Exception outerEx)
{
Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
}
Console.WriteLine();
Console.WriteLine();
}
public static void ClientThread(object obj)
{
TTransport transport = (TTransport)obj;
for (int i = 0; i < numIterations; i++)
{
ClientTest(transport);
}
transport.Close();
}
public static void ClientTest(TTransport transport)
{
TProtocol proto;
if (protocol == "compact")
proto = new TCompactProtocol(transport);
else if (protocol == "json")
proto = new TJSONProtocol(transport);
else
proto = new TBinaryProtocol(transport);
ThriftTest.Client client = new ThriftTest.Client(proto);
try
{
if (!transport.IsOpen)
{
transport.Open();
}
}
catch (TTransportException ttx)
{
Console.WriteLine("Connect failed: " + ttx.Message);
return;
}
long start = DateTime.Now.ToFileTime();
Console.Write("testVoid()");
client.testVoid();
Console.WriteLine(" = void");
Console.Write("testString(\"Test\")");
string s = client.testString("Test");
Console.WriteLine(" = \"" + s + "\"");
Console.Write("testByte(1)");
sbyte i8 = client.testByte((sbyte)1);
Console.WriteLine(" = " + i8);
Console.Write("testI32(-1)");
int i32 = client.testI32(-1);
Console.WriteLine(" = " + i32);
Console.Write("testI64(-34359738368)");
long i64 = client.testI64(-34359738368);
Console.WriteLine(" = " + i64);
Console.Write("testDouble(5.325098235)");
double dub = client.testDouble(5.325098235);
Console.WriteLine(" = " + dub);
Console.Write("testStruct({\"Zero\", 1, -3, -5})");
Xtruct o = new Xtruct();
o.String_thing = "Zero";
o.Byte_thing = (sbyte)1;
o.I32_thing = -3;
o.I64_thing = -5;
Xtruct i = client.testStruct(o);
Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}");
Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})");
Xtruct2 o2 = new Xtruct2();
o2.Byte_thing = (sbyte)1;
o2.Struct_thing = o;
o2.I32_thing = 5;
Xtruct2 i2 = client.testNest(o2);
i = i2.Struct_thing;
Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}");
Dictionary<int, int> mapout = new Dictionary<int, int>();
for (int j = 0; j < 5; j++)
{
mapout[j] = j - 10;
}
Console.Write("testMap({");
bool first = true;
foreach (int key in mapout.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapout[key]);
}
Console.Write("})");
Dictionary<int, int> mapin = client.testMap(mapout);
Console.Write(" = {");
first = true;
foreach (int key in mapin.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapin[key]);
}
Console.WriteLine("}");
List<int> listout = new List<int>();
for (int j = -2; j < 3; j++)
{
listout.Add(j);
}
Console.Write("testList({");
first = true;
foreach (int j in listout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
List<int> listin = client.testList(listout);
Console.Write(" = {");
first = true;
foreach (int j in listin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
//set
THashSet<int> setout = new THashSet<int>();
for (int j = -2; j < 3; j++)
{
setout.Add(j);
}
Console.Write("testSet({");
first = true;
foreach (int j in setout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
THashSet<int> setin = client.testSet(setout);
Console.Write(" = {");
first = true;
foreach (int j in setin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
Console.Write("testEnum(ONE)");
Numberz ret = client.testEnum(Numberz.ONE);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(TWO)");
ret = client.testEnum(Numberz.TWO);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(THREE)");
ret = client.testEnum(Numberz.THREE);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(FIVE)");
ret = client.testEnum(Numberz.FIVE);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(EIGHT)");
ret = client.testEnum(Numberz.EIGHT);
Console.WriteLine(" = " + ret);
Console.Write("testTypedef(309858235082523)");
long uid = client.testTypedef(309858235082523L);
Console.WriteLine(" = " + uid);
Console.Write("testMapMap(1)");
Dictionary<int, Dictionary<int, int>> mm = client.testMapMap(1);
Console.Write(" = {");
foreach (int key in mm.Keys)
{
Console.Write(key + " => {");
Dictionary<int, int> m2 = mm[key];
foreach (int k2 in m2.Keys)
{
Console.Write(k2 + " => " + m2[k2] + ", ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
Insanity insane = new Insanity();
insane.UserMap = new Dictionary<Numberz, long>();
insane.UserMap[Numberz.FIVE] = 5000L;
Xtruct truck = new Xtruct();
truck.String_thing = "Truck";
truck.Byte_thing = (sbyte)8;
truck.I32_thing = 8;
truck.I64_thing = 8;
insane.Xtructs = new List<Xtruct>();
insane.Xtructs.Add(truck);
Console.Write("testInsanity()");
Dictionary<long, Dictionary<Numberz, Insanity>> whoa = client.testInsanity(insane);
Console.Write(" = {");
foreach (long key in whoa.Keys)
{
Dictionary<Numberz, Insanity> val = whoa[key];
Console.Write(key + " => {");
foreach (Numberz k2 in val.Keys)
{
Insanity v2 = val[k2];
Console.Write(k2 + " => {");
Dictionary<Numberz, long> userMap = v2.UserMap;
Console.Write("{");
if (userMap != null)
{
foreach (Numberz k3 in userMap.Keys)
{
Console.Write(k3 + " => " + userMap[k3] + ", ");
}
}
else
{
Console.Write("null");
}
Console.Write("}, ");
List<Xtruct> xtructs = v2.Xtructs;
Console.Write("{");
if (xtructs != null)
{
foreach (Xtruct x in xtructs)
{
Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, ");
}
}
else
{
Console.Write("null");
}
Console.Write("}");
Console.Write("}, ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
sbyte arg0 = 1;
int arg1 = 2;
long arg2 = long.MaxValue;
Dictionary<short, string> multiDict = new Dictionary<short, string>();
multiDict[1] = "one";
Numberz arg4 = Numberz.FIVE;
long arg5 = 5000000;
Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + "," + multiDict + "," + arg4 + "," + arg5 + ")");
Xtruct multiResponse = client.testMulti(arg0, arg1, arg2, multiDict, arg4, arg5);
Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing
+ ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n");
Console.WriteLine("Test Oneway(1)");
client.testOneway(1);
Console.Write("Test Calltime()");
var startt = DateTime.UtcNow;
for ( int k=0; k<1000; ++k )
client.testVoid();
Console.WriteLine(" = " + (DateTime.UtcNow - startt).TotalSeconds.ToString() + " ms a testVoid() call" );
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Dataflow.V1Beta3
{
/// <summary>Settings for <see cref="SnapshotsV1Beta3Client"/> instances.</summary>
public sealed partial class SnapshotsV1Beta3Settings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="SnapshotsV1Beta3Settings"/>.</summary>
/// <returns>A new instance of the default <see cref="SnapshotsV1Beta3Settings"/>.</returns>
public static SnapshotsV1Beta3Settings GetDefault() => new SnapshotsV1Beta3Settings();
/// <summary>Constructs a new <see cref="SnapshotsV1Beta3Settings"/> object with default settings.</summary>
public SnapshotsV1Beta3Settings()
{
}
private SnapshotsV1Beta3Settings(SnapshotsV1Beta3Settings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetSnapshotSettings = existing.GetSnapshotSettings;
DeleteSnapshotSettings = existing.DeleteSnapshotSettings;
ListSnapshotsSettings = existing.ListSnapshotsSettings;
OnCopy(existing);
}
partial void OnCopy(SnapshotsV1Beta3Settings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SnapshotsV1Beta3Client.GetSnapshot</c> and <c>SnapshotsV1Beta3Client.GetSnapshotAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetSnapshotSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SnapshotsV1Beta3Client.DeleteSnapshot</c> and <c>SnapshotsV1Beta3Client.DeleteSnapshotAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteSnapshotSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SnapshotsV1Beta3Client.ListSnapshots</c> and <c>SnapshotsV1Beta3Client.ListSnapshotsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListSnapshotsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="SnapshotsV1Beta3Settings"/> object.</returns>
public SnapshotsV1Beta3Settings Clone() => new SnapshotsV1Beta3Settings(this);
}
/// <summary>
/// Builder class for <see cref="SnapshotsV1Beta3Client"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class SnapshotsV1Beta3ClientBuilder : gaxgrpc::ClientBuilderBase<SnapshotsV1Beta3Client>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public SnapshotsV1Beta3Settings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public SnapshotsV1Beta3ClientBuilder()
{
UseJwtAccessWithScopes = SnapshotsV1Beta3Client.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref SnapshotsV1Beta3Client client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<SnapshotsV1Beta3Client> task);
/// <summary>Builds the resulting client.</summary>
public override SnapshotsV1Beta3Client Build()
{
SnapshotsV1Beta3Client client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<SnapshotsV1Beta3Client> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<SnapshotsV1Beta3Client> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private SnapshotsV1Beta3Client BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return SnapshotsV1Beta3Client.Create(callInvoker, Settings);
}
private async stt::Task<SnapshotsV1Beta3Client> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return SnapshotsV1Beta3Client.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => SnapshotsV1Beta3Client.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => SnapshotsV1Beta3Client.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => SnapshotsV1Beta3Client.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>SnapshotsV1Beta3 client wrapper, for convenient use.</summary>
/// <remarks>
/// Provides methods to manage snapshots of Google Cloud Dataflow jobs.
/// </remarks>
public abstract partial class SnapshotsV1Beta3Client
{
/// <summary>
/// The default endpoint for the SnapshotsV1Beta3 service, which is a host of "dataflow.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "dataflow.googleapis.com:443";
/// <summary>The default SnapshotsV1Beta3 scopes.</summary>
/// <remarks>
/// The default SnapshotsV1Beta3 scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/compute</description></item>
/// <item><description>https://www.googleapis.com/auth/compute.readonly</description></item>
/// <item><description>https://www.googleapis.com/auth/userinfo.email</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly",
"https://www.googleapis.com/auth/userinfo.email",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="SnapshotsV1Beta3Client"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="SnapshotsV1Beta3ClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="SnapshotsV1Beta3Client"/>.</returns>
public static stt::Task<SnapshotsV1Beta3Client> CreateAsync(st::CancellationToken cancellationToken = default) =>
new SnapshotsV1Beta3ClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="SnapshotsV1Beta3Client"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="SnapshotsV1Beta3ClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="SnapshotsV1Beta3Client"/>.</returns>
public static SnapshotsV1Beta3Client Create() => new SnapshotsV1Beta3ClientBuilder().Build();
/// <summary>
/// Creates a <see cref="SnapshotsV1Beta3Client"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="SnapshotsV1Beta3Settings"/>.</param>
/// <returns>The created <see cref="SnapshotsV1Beta3Client"/>.</returns>
internal static SnapshotsV1Beta3Client Create(grpccore::CallInvoker callInvoker, SnapshotsV1Beta3Settings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
SnapshotsV1Beta3.SnapshotsV1Beta3Client grpcClient = new SnapshotsV1Beta3.SnapshotsV1Beta3Client(callInvoker);
return new SnapshotsV1Beta3ClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC SnapshotsV1Beta3 client</summary>
public virtual SnapshotsV1Beta3.SnapshotsV1Beta3Client GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Gets information about a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Snapshot GetSnapshot(GetSnapshotRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets information about a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Snapshot> GetSnapshotAsync(GetSnapshotRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets information about a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Snapshot> GetSnapshotAsync(GetSnapshotRequest request, st::CancellationToken cancellationToken) =>
GetSnapshotAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual DeleteSnapshotResponse DeleteSnapshot(DeleteSnapshotRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DeleteSnapshotResponse> DeleteSnapshotAsync(DeleteSnapshotRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DeleteSnapshotResponse> DeleteSnapshotAsync(DeleteSnapshotRequest request, st::CancellationToken cancellationToken) =>
DeleteSnapshotAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Lists snapshots.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ListSnapshotsResponse ListSnapshots(ListSnapshotsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists snapshots.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListSnapshotsResponse> ListSnapshotsAsync(ListSnapshotsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists snapshots.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListSnapshotsResponse> ListSnapshotsAsync(ListSnapshotsRequest request, st::CancellationToken cancellationToken) =>
ListSnapshotsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>SnapshotsV1Beta3 client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Provides methods to manage snapshots of Google Cloud Dataflow jobs.
/// </remarks>
public sealed partial class SnapshotsV1Beta3ClientImpl : SnapshotsV1Beta3Client
{
private readonly gaxgrpc::ApiCall<GetSnapshotRequest, Snapshot> _callGetSnapshot;
private readonly gaxgrpc::ApiCall<DeleteSnapshotRequest, DeleteSnapshotResponse> _callDeleteSnapshot;
private readonly gaxgrpc::ApiCall<ListSnapshotsRequest, ListSnapshotsResponse> _callListSnapshots;
/// <summary>
/// Constructs a client wrapper for the SnapshotsV1Beta3 service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="SnapshotsV1Beta3Settings"/> used within this client.</param>
public SnapshotsV1Beta3ClientImpl(SnapshotsV1Beta3.SnapshotsV1Beta3Client grpcClient, SnapshotsV1Beta3Settings settings)
{
GrpcClient = grpcClient;
SnapshotsV1Beta3Settings effectiveSettings = settings ?? SnapshotsV1Beta3Settings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetSnapshot = clientHelper.BuildApiCall<GetSnapshotRequest, Snapshot>(grpcClient.GetSnapshotAsync, grpcClient.GetSnapshot, effectiveSettings.GetSnapshotSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("snapshot_id", request => request.SnapshotId);
Modify_ApiCall(ref _callGetSnapshot);
Modify_GetSnapshotApiCall(ref _callGetSnapshot);
_callDeleteSnapshot = clientHelper.BuildApiCall<DeleteSnapshotRequest, DeleteSnapshotResponse>(grpcClient.DeleteSnapshotAsync, grpcClient.DeleteSnapshot, effectiveSettings.DeleteSnapshotSettings).WithGoogleRequestParam("project_id", request => request.ProjectId);
Modify_ApiCall(ref _callDeleteSnapshot);
Modify_DeleteSnapshotApiCall(ref _callDeleteSnapshot);
_callListSnapshots = clientHelper.BuildApiCall<ListSnapshotsRequest, ListSnapshotsResponse>(grpcClient.ListSnapshotsAsync, grpcClient.ListSnapshots, effectiveSettings.ListSnapshotsSettings).WithGoogleRequestParam("project_id", request => request.ProjectId);
Modify_ApiCall(ref _callListSnapshots);
Modify_ListSnapshotsApiCall(ref _callListSnapshots);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetSnapshotApiCall(ref gaxgrpc::ApiCall<GetSnapshotRequest, Snapshot> call);
partial void Modify_DeleteSnapshotApiCall(ref gaxgrpc::ApiCall<DeleteSnapshotRequest, DeleteSnapshotResponse> call);
partial void Modify_ListSnapshotsApiCall(ref gaxgrpc::ApiCall<ListSnapshotsRequest, ListSnapshotsResponse> call);
partial void OnConstruction(SnapshotsV1Beta3.SnapshotsV1Beta3Client grpcClient, SnapshotsV1Beta3Settings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC SnapshotsV1Beta3 client</summary>
public override SnapshotsV1Beta3.SnapshotsV1Beta3Client GrpcClient { get; }
partial void Modify_GetSnapshotRequest(ref GetSnapshotRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeleteSnapshotRequest(ref DeleteSnapshotRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListSnapshotsRequest(ref ListSnapshotsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Gets information about a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Snapshot GetSnapshot(GetSnapshotRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetSnapshotRequest(ref request, ref callSettings);
return _callGetSnapshot.Sync(request, callSettings);
}
/// <summary>
/// Gets information about a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Snapshot> GetSnapshotAsync(GetSnapshotRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetSnapshotRequest(ref request, ref callSettings);
return _callGetSnapshot.Async(request, callSettings);
}
/// <summary>
/// Deletes a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override DeleteSnapshotResponse DeleteSnapshot(DeleteSnapshotRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteSnapshotRequest(ref request, ref callSettings);
return _callDeleteSnapshot.Sync(request, callSettings);
}
/// <summary>
/// Deletes a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<DeleteSnapshotResponse> DeleteSnapshotAsync(DeleteSnapshotRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteSnapshotRequest(ref request, ref callSettings);
return _callDeleteSnapshot.Async(request, callSettings);
}
/// <summary>
/// Lists snapshots.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ListSnapshotsResponse ListSnapshots(ListSnapshotsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListSnapshotsRequest(ref request, ref callSettings);
return _callListSnapshots.Sync(request, callSettings);
}
/// <summary>
/// Lists snapshots.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ListSnapshotsResponse> ListSnapshotsAsync(ListSnapshotsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListSnapshotsRequest(ref request, ref callSettings);
return _callListSnapshots.Async(request, callSettings);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection.Tests;
using System.Runtime.CompilerServices;
using System.Security;
using Xunit;
[assembly:
Attr(77, name = "AttrSimple"),
Int32Attr(77, name = "Int32AttrSimple"),
Int64Attr(77, name = "Int64AttrSimple"),
StringAttr("hello", name = "StringAttrSimple"),
EnumAttr(PublicEnum.Case1, name = "EnumAttrSimple"),
TypeAttr(typeof(object), name = "TypeAttrSimple")]
[assembly: CompilationRelaxations(8)]
[assembly: Debuggable((DebuggableAttribute.DebuggingModes)263)]
[assembly: CLSCompliant(false)]
namespace System.Reflection.Tests
{
public class AssemblyTests : FileCleanupTestBase
{
private string SourceTestAssemblyPath { get; } = Path.Combine(Environment.CurrentDirectory, "TestAssembly.dll");
private string DestTestAssemblyPath { get; }
private string LoadFromTestPath { get; }
public AssemblyTests()
{
// Assembly.Location does not return the file path for single-file deployment targets.
DestTestAssemblyPath = Path.Combine(base.TestDirectory, "TestAssembly.dll");
LoadFromTestPath = Path.Combine(base.TestDirectory, "System.Reflection.Tests.dll");
File.Copy(SourceTestAssemblyPath, DestTestAssemblyPath);
string currAssemblyPath = Path.Combine(Environment.CurrentDirectory, "System.Reflection.Tests.dll");
File.Copy(currAssemblyPath, LoadFromTestPath, true);
}
[Theory]
[InlineData(typeof(Int32Attr))]
[InlineData(typeof(Int64Attr))]
[InlineData(typeof(StringAttr))]
[InlineData(typeof(EnumAttr))]
[InlineData(typeof(TypeAttr))]
[InlineData(typeof(CompilationRelaxationsAttribute))]
[InlineData(typeof(AssemblyTitleAttribute))]
[InlineData(typeof(AssemblyDescriptionAttribute))]
[InlineData(typeof(AssemblyCompanyAttribute))]
[InlineData(typeof(CLSCompliantAttribute))]
[InlineData(typeof(DebuggableAttribute))]
[InlineData(typeof(Attr))]
public void CustomAttributes(Type type)
{
Assembly assembly = Helpers.ExecutingAssembly;
IEnumerable<Type> attributesData = assembly.CustomAttributes.Select(customAttribute => customAttribute.AttributeType);
Assert.Contains(type, attributesData);
ICustomAttributeProvider attributeProvider = assembly;
Assert.Single(attributeProvider.GetCustomAttributes(type, false));
Assert.True(attributeProvider.IsDefined(type, false));
IEnumerable<Type> customAttributes = attributeProvider.GetCustomAttributes(false).Select(attribute => attribute.GetType());
Assert.Contains(type, customAttributes);
}
[Theory]
[InlineData(typeof(int), false)]
[InlineData(typeof(Attr), true)]
[InlineData(typeof(Int32Attr), true)]
[InlineData(typeof(Int64Attr), true)]
[InlineData(typeof(StringAttr), true)]
[InlineData(typeof(EnumAttr), true)]
[InlineData(typeof(TypeAttr), true)]
[InlineData(typeof(ObjectAttr), true)]
[InlineData(typeof(NullAttr), true)]
public void DefinedTypes(Type type, bool expected)
{
IEnumerable<Type> customAttrs = Helpers.ExecutingAssembly.DefinedTypes.Select(typeInfo => typeInfo.AsType());
Assert.Equal(expected, customAttrs.Contains(type));
}
[Theory]
[InlineData("EmbeddedImage.png", true)]
[InlineData("EmbeddedTextFile.txt", true)]
[InlineData("NoSuchFile", false)]
public void EmbeddedFiles(string resource, bool exists)
{
string[] resources = Helpers.ExecutingAssembly.GetManifestResourceNames();
Stream resourceStream = Helpers.ExecutingAssembly.GetManifestResourceStream(resource);
Assert.Equal(exists, resources.Contains(resource));
Assert.Equal(exists, resourceStream != null);
}
[Theory]
[InlineData("EmbeddedImage1.png", true)]
[InlineData("EmbeddedTextFile1.txt", true)]
[InlineData("NoSuchFile", false)]
public void GetManifestResourceStream(string resource, bool exists)
{
Type assemblyType = typeof(AssemblyTests);
Stream resourceStream = assemblyType.Assembly.GetManifestResourceStream(assemblyType, resource);
Assert.Equal(exists, resourceStream != null);
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), true };
yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), true };
yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Helpers.ExecutingAssembly, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public void Equals(Assembly assembly1, Assembly assembly2, bool expected)
{
Assert.Equal(expected, assembly1.Equals(assembly2));
}
[Theory]
[InlineData(typeof(AssemblyPublicClass), true)]
[InlineData(typeof(AssemblyTests), true)]
[InlineData(typeof(AssemblyPublicClass.PublicNestedClass), true)]
[InlineData(typeof(PublicEnum), true)]
[InlineData(typeof(AssemblyGenericPublicClass<>), true)]
[InlineData(typeof(AssemblyInternalClass), false)]
public void ExportedTypes(Type type, bool expected)
{
Assembly assembly = Helpers.ExecutingAssembly;
Assert.Equal(assembly.GetExportedTypes(), assembly.ExportedTypes);
Assert.Equal(expected, assembly.ExportedTypes.Contains(type));
}
[Fact]
public void GetEntryAssembly()
{
Assert.NotNull(Assembly.GetEntryAssembly());
string assembly = Assembly.GetEntryAssembly().ToString();
bool correct = assembly.IndexOf("xunit.console", StringComparison.OrdinalIgnoreCase) != -1;
Assert.True(correct, $"Unexpected assembly name {assembly}");
}
[Fact]
public void GetFile()
{
Assert.Throws<ArgumentNullException>(() => typeof(AssemblyTests).Assembly.GetFile(null));
AssertExtensions.Throws<ArgumentException>(null, () => typeof(AssemblyTests).Assembly.GetFile(""));
Assert.Null(typeof(AssemblyTests).Assembly.GetFile("NonExistentfile.dll"));
Assert.NotNull(typeof(AssemblyTests).Assembly.GetFile("System.Reflection.Tests.dll"));
Assert.Equal(typeof(AssemblyTests).Assembly.GetFile("System.Reflection.Tests.dll").Name, typeof(AssemblyTests).Assembly.Location);
}
[Fact]
public void GetFiles()
{
Assert.NotNull(typeof(AssemblyTests).Assembly.GetFiles());
Assert.Equal(1, typeof(AssemblyTests).Assembly.GetFiles().Length);
Assert.Equal(typeof(AssemblyTests).Assembly.GetFiles()[0].Name, typeof(AssemblyTests).Assembly.Location);
}
public static IEnumerable<object[]> GetHashCode_TestData()
{
yield return new object[] { LoadSystemRuntimeAssembly() };
yield return new object[] { LoadSystemCollectionsAssembly() };
yield return new object[] { LoadSystemReflectionAssembly() };
yield return new object[] { typeof(AssemblyTests).GetTypeInfo().Assembly };
}
[Theory]
[MemberData(nameof(GetHashCode_TestData))]
public void GetHashCode(Assembly assembly)
{
int hashCode = assembly.GetHashCode();
Assert.NotEqual(-1, hashCode);
Assert.NotEqual(0, hashCode);
}
[Theory]
[InlineData("System.Reflection.Tests.AssemblyPublicClass", true)]
[InlineData("System.Reflection.Tests.AssemblyInternalClass", true)]
[InlineData("System.Reflection.Tests.PublicEnum", true)]
[InlineData("System.Reflection.Tests.PublicStruct", true)]
[InlineData("AssemblyPublicClass", false)]
[InlineData("NoSuchType", false)]
public void GetType(string name, bool exists)
{
Type type = Helpers.ExecutingAssembly.GetType(name);
if (exists)
{
Assert.Equal(name, type.FullName);
}
else
{
Assert.Null(type);
}
}
[Fact]
public void GetType_NoQualifierAllowed()
{
Assembly a = typeof(G<int>).Assembly;
string s = typeof(G<int>).AssemblyQualifiedName;
AssertExtensions.Throws<ArgumentException>(null, () => a.GetType(s, throwOnError: true, ignoreCase: false));
}
[Fact]
public void GetType_DoesntSearchMscorlib()
{
Assembly a = typeof(AssemblyTests).Assembly;
Assert.Throws<TypeLoadException>(() => a.GetType("System.Object", throwOnError: true, ignoreCase: false));
Assert.Throws<TypeLoadException>(() => a.GetType("G`1[[System.Object]]", throwOnError: true, ignoreCase: false));
}
[Fact]
public void GetType_DefaultsToItself()
{
Assembly a = typeof(AssemblyTests).Assembly;
Type t = a.GetType("G`1[[G`1[[System.Int32, mscorlib]]]]", throwOnError: true, ignoreCase: false);
Assert.Equal(typeof(G<G<int>>), t);
}
[Fact]
public void GlobalAssemblyCache()
{
Assert.False(typeof(AssemblyTests).Assembly.GlobalAssemblyCache);
}
[Fact]
public void HostContext()
{
Assert.Equal(0, typeof(AssemblyTests).Assembly.HostContext);
}
public static IEnumerable<object[]> IsDynamic_TestData()
{
yield return new object[] { Helpers.ExecutingAssembly, false };
yield return new object[] { LoadSystemCollectionsAssembly(), false };
}
[Theory]
[MemberData(nameof(IsDynamic_TestData))]
public void IsDynamic(Assembly assembly, bool expected)
{
Assert.Equal(expected, assembly.IsDynamic);
}
public static IEnumerable<object[]> Load_TestData()
{
yield return new object[] { new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName) };
yield return new object[] { new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName) };
yield return new object[] { new AssemblyName(typeof(AssemblyName).GetTypeInfo().Assembly.FullName) };
}
[Fact]
public void IsFullyTrusted()
{
Assert.True(typeof(AssemblyTests).Assembly.IsFullyTrusted);
}
[Fact]
public void SecurityRuleSet_Netcore()
{
Assert.Equal(SecurityRuleSet.None, typeof(AssemblyTests).Assembly.SecurityRuleSet);
}
[Theory]
[MemberData(nameof(Load_TestData))]
public void Load(AssemblyName assemblyRef)
{
Assert.NotNull(Assembly.Load(assemblyRef));
}
[Fact]
public void Load_Invalid()
{
Assert.Throws<ArgumentNullException>(() => Assembly.Load((AssemblyName)null)); // AssemblyRef is null
Assert.Throws<FileNotFoundException>(() => Assembly.Load(new AssemblyName("no such assembly"))); // No such assembly
}
[Fact]
public void LoadFile()
{
Assembly currentAssembly = typeof(AssemblyTests).Assembly;
const string RuntimeTestsDll = "System.Reflection.Tests.dll";
string fullRuntimeTestsPath = Path.GetFullPath(RuntimeTestsDll);
var loadedAssembly1 = Assembly.LoadFile(fullRuntimeTestsPath);
Assert.NotEqual(currentAssembly, loadedAssembly1);
#if NETCOREAPP
System.Runtime.Loader.AssemblyLoadContext alc = System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(loadedAssembly1);
string expectedName = string.Format("Assembly.LoadFile({0})", fullRuntimeTestsPath);
Assert.Equal(expectedName, alc.Name);
Assert.Contains(fullRuntimeTestsPath, alc.Name);
Assert.Contains(expectedName, alc.ToString());
Assert.Contains("System.Runtime.Loader.IndividualAssemblyLoadContext", alc.ToString());
#endif
string dir = Path.GetDirectoryName(fullRuntimeTestsPath);
fullRuntimeTestsPath = Path.Combine(dir, ".", RuntimeTestsDll);
Assembly loadedAssembly2 = Assembly.LoadFile(fullRuntimeTestsPath);
Assert.Equal(loadedAssembly1, loadedAssembly2);
}
[Fact]
public void LoadFile_NullPath_Netcore_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("path", () => Assembly.LoadFile(null));
}
[Fact]
public void LoadFile_NoSuchPath_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("path", null, () => Assembly.LoadFile("System.Runtime.Tests.dll"));
}
[Fact]
public void LoadFromUsingHashValue_Netcore()
{
Assert.Throws<NotSupportedException>(() => Assembly.LoadFrom("abc", null, System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1));
}
[Fact]
public void LoadFrom_SamePath_ReturnsEqualAssemblies()
{
Assembly assembly1 = Assembly.LoadFrom(DestTestAssemblyPath);
Assembly assembly2 = Assembly.LoadFrom(DestTestAssemblyPath);
Assert.Equal(assembly1, assembly2);
}
[Fact]
public void LoadFrom_SameIdentityAsAssemblyWithDifferentPath_ReturnsEqualAssemblies()
{
Assembly assembly1 = Assembly.LoadFrom(typeof(AssemblyTests).Assembly.Location);
Assert.Equal(assembly1, typeof(AssemblyTests).Assembly);
Assembly assembly2 = Assembly.LoadFrom(LoadFromTestPath);
Assert.Equal(assembly1, assembly2);
}
[Fact]
public void LoadFrom_NullAssemblyFile_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => Assembly.LoadFrom(null));
AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => Assembly.UnsafeLoadFrom(null));
}
[Fact]
public void LoadFrom_EmptyAssemblyFile_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("path", null, (() => Assembly.LoadFrom("")));
AssertExtensions.Throws<ArgumentException>("path", null, (() => Assembly.UnsafeLoadFrom("")));
}
[Fact]
public void LoadFrom_NoSuchFile_ThrowsFileNotFoundException()
{
Assert.Throws<FileNotFoundException>(() => Assembly.LoadFrom("NoSuchPath"));
Assert.Throws<FileNotFoundException>(() => Assembly.UnsafeLoadFrom("NoSuchPath"));
}
[Fact]
public void UnsafeLoadFrom_SamePath_ReturnsEqualAssemblies()
{
Assembly assembly1 = Assembly.UnsafeLoadFrom(DestTestAssemblyPath);
Assembly assembly2 = Assembly.UnsafeLoadFrom(DestTestAssemblyPath);
Assert.Equal(assembly1, assembly2);
}
[Fact]
public void LoadFrom_WithHashValue_NetCoreCore_ThrowsNotSupportedException()
{
Assert.Throws<NotSupportedException>(() => Assembly.LoadFrom(DestTestAssemblyPath, new byte[0], Configuration.Assemblies.AssemblyHashAlgorithm.None));
}
[Fact]
public void LoadModule_Netcore()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
Assert.Throws<NotImplementedException>(() => assembly.LoadModule("abc", null));
Assert.Throws<NotImplementedException>(() => assembly.LoadModule("abc", null, null));
}
#pragma warning disable 618
[Fact]
public void LoadWithPartialName()
{
string simpleName = typeof(AssemblyTests).Assembly.GetName().Name;
var assembly = Assembly.LoadWithPartialName(simpleName);
Assert.Equal(typeof(AssemblyTests).Assembly, assembly);
}
[Fact]
public void LoadWithPartialName_Neg()
{
AssertExtensions.Throws<ArgumentNullException>("partialName", () => Assembly.LoadWithPartialName(null));
AssertExtensions.Throws<ArgumentException>("partialName", () => Assembly.LoadWithPartialName(""));
Assert.Null(Assembly.LoadWithPartialName("no such assembly"));
}
#pragma warning restore 618
[Fact]
public void Location_ExecutingAssembly_IsNotNull()
{
// This test applies on all platforms including .NET Native. Location must at least be non-null (it can be empty).
// System.Reflection.CoreCLR.Tests adds tests that expect more than that.
Assert.NotNull(Helpers.ExecutingAssembly.Location);
}
[Fact]
public void CodeBase()
{
Assert.NotEmpty(Helpers.ExecutingAssembly.CodeBase);
}
[Fact]
public void ImageRuntimeVersion()
{
Assert.NotEmpty(Helpers.ExecutingAssembly.ImageRuntimeVersion);
}
public static IEnumerable<object[]> CreateInstance_TestData()
{
yield return new object[] { Helpers.ExecutingAssembly, typeof(AssemblyPublicClass).FullName, typeof(AssemblyPublicClass) };
yield return new object[] { typeof(int).GetTypeInfo().Assembly, typeof(int).FullName, typeof(int) };
yield return new object[] { typeof(int).GetTypeInfo().Assembly, typeof(Dictionary<int, string>).FullName, typeof(Dictionary<int, string>) };
}
[Theory]
[MemberData(nameof(CreateInstance_TestData))]
public void CreateInstance(Assembly assembly, string typeName, Type expectedType)
{
Assert.IsType(expectedType, assembly.CreateInstance(typeName));
Assert.IsType(expectedType, assembly.CreateInstance(typeName, false));
Assert.IsType(expectedType, assembly.CreateInstance(typeName, true));
Assert.IsType(expectedType, assembly.CreateInstance(typeName.ToUpper(), true));
Assert.IsType(expectedType, assembly.CreateInstance(typeName.ToLower(), true));
}
public static IEnumerable<object[]> CreateInstanceWithBindingFlags_TestData()
{
yield return new object[] { typeof(AssemblyTests).Assembly, typeof(AssemblyPublicClass).FullName, BindingFlags.CreateInstance, typeof(AssemblyPublicClass) };
yield return new object[] { typeof(int).Assembly, typeof(int).FullName, BindingFlags.Default, typeof(int) };
yield return new object[] { typeof(int).Assembly, typeof(Dictionary<int, string>).FullName, BindingFlags.Default, typeof(Dictionary<int, string>) };
}
[Theory]
[MemberData(nameof(CreateInstanceWithBindingFlags_TestData))]
public void CreateInstanceWithBindingFlags(Assembly assembly, string typeName, BindingFlags bindingFlags, Type expectedType)
{
Assert.IsType(expectedType, assembly.CreateInstance(typeName, true, bindingFlags, null, null, null, null));
Assert.IsType(expectedType, assembly.CreateInstance(typeName, false, bindingFlags, null, null, null, null));
}
public static IEnumerable<object[]> CreateInstance_Invalid_TestData()
{
yield return new object[] { "", typeof(ArgumentException) };
yield return new object[] { null, typeof(ArgumentNullException) };
yield return new object[] { typeof(AssemblyClassWithPrivateCtor).FullName, typeof(MissingMethodException) };
yield return new object[] { typeof(AssemblyClassWithNoDefaultCtor).FullName, typeof(MissingMethodException) };
}
[Theory]
[MemberData(nameof(CreateInstance_Invalid_TestData))]
public void CreateInstance_Invalid(string typeName, Type exceptionType)
{
Assembly assembly = Helpers.ExecutingAssembly;
Assert.Throws(exceptionType, () => Helpers.ExecutingAssembly.CreateInstance(typeName));
Assert.Throws(exceptionType, () => Helpers.ExecutingAssembly.CreateInstance(typeName, true));
Assert.Throws(exceptionType, () => Helpers.ExecutingAssembly.CreateInstance(typeName, false));
assembly = typeof(AssemblyTests).Assembly;
Assert.Throws(exceptionType, () => assembly.CreateInstance(typeName, true, BindingFlags.Public, null, null, null, null));
Assert.Throws(exceptionType, () => assembly.CreateInstance(typeName, false, BindingFlags.Public, null, null, null, null));
}
[Fact]
public void CreateQualifiedName()
{
string assemblyName = Helpers.ExecutingAssembly.ToString();
Assert.Equal(typeof(AssemblyTests).FullName + ", " + assemblyName, Assembly.CreateQualifiedName(assemblyName, typeof(AssemblyTests).FullName));
}
[Fact]
public void GetReferencedAssemblies()
{
// It is too brittle to depend on the assembly references so we just call the method and check that it does not throw.
AssemblyName[] assemblies = Helpers.ExecutingAssembly.GetReferencedAssemblies();
Assert.NotEmpty(assemblies);
}
public static IEnumerable<object[]> Modules_TestData()
{
yield return new object[] { LoadSystemCollectionsAssembly() };
yield return new object[] { LoadSystemReflectionAssembly() };
}
[Theory]
[MemberData(nameof(Modules_TestData))]
public void Modules(Assembly assembly)
{
Assert.NotEmpty(assembly.Modules);
foreach (Module module in assembly.Modules)
{
Assert.NotNull(module);
}
}
public static IEnumerable<object[]> Equality_TestData()
{
yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), true };
yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), true };
yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), typeof(AssemblyTests).Assembly, false };
}
[Theory]
[MemberData(nameof(Equality_TestData))]
public void Equality(Assembly assembly1, Assembly assembly2, bool expected)
{
Assert.Equal(expected, assembly1 == assembly2);
Assert.NotEqual(expected, assembly1 != assembly2);
}
[Fact]
public void GetAssembly_Nullery()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Assembly.GetAssembly(null));
}
public static IEnumerable<object[]> GetAssembly_TestData()
{
yield return new object[] { Assembly.Load(new AssemblyName(typeof(HashSet<int>).GetTypeInfo().Assembly.FullName)), Assembly.GetAssembly(typeof(HashSet<int>)), true };
yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.GetAssembly(typeof(int)), true };
yield return new object[] { typeof(AssemblyTests).Assembly, Assembly.GetAssembly(typeof(AssemblyTests)), true };
}
[Theory]
[MemberData(nameof(GetAssembly_TestData))]
public void GetAssembly(Assembly assembly1, Assembly assembly2, bool expected)
{
Assert.Equal(expected, assembly1.Equals(assembly2));
}
public static IEnumerable<object[]> GetCallingAssembly_TestData()
{
yield return new object[] { typeof(AssemblyTests).Assembly, GetGetCallingAssembly(), true };
yield return new object[] { Assembly.GetCallingAssembly(), GetGetCallingAssembly(), false };
}
[Theory]
[MemberData(nameof(GetCallingAssembly_TestData))]
public void GetCallingAssembly(Assembly assembly1, Assembly assembly2, bool expected)
{
Assert.Equal(expected, assembly1.Equals(assembly2));
}
[Fact]
public void GetExecutingAssembly()
{
Assert.True(typeof(AssemblyTests).Assembly.Equals(Assembly.GetExecutingAssembly()));
}
[Fact]
public void GetSatelliteAssemblyNeg()
{
Assert.Throws<ArgumentNullException>(() => (typeof(AssemblyTests).Assembly.GetSatelliteAssembly(null)));
Assert.Throws<System.IO.FileNotFoundException>(() => (typeof(AssemblyTests).Assembly.GetSatelliteAssembly(CultureInfo.InvariantCulture)));
}
[Fact]
public void AssemblyLoadFromString()
{
AssemblyName an = typeof(AssemblyTests).Assembly.GetName();
string fullName = an.FullName;
string simpleName = an.Name;
Assembly a1 = Assembly.Load(fullName);
Assert.NotNull(a1);
Assert.Equal(fullName, a1.GetName().FullName);
Assembly a2 = Assembly.Load(simpleName);
Assert.NotNull(a2);
Assert.Equal(fullName, a2.GetName().FullName);
}
[Fact]
public void AssemblyLoadFromStringNeg()
{
Assert.Throws<ArgumentNullException>(() => Assembly.Load((string)null));
AssertExtensions.Throws<ArgumentException>(null, () => Assembly.Load(string.Empty));
string emptyCName = new string('\0', 1);
AssertExtensions.Throws<ArgumentException>(null, () => Assembly.Load(emptyCName));
Assert.Throws<FileNotFoundException>(() => Assembly.Load("no such assembly")); // No such assembly
}
[Fact]
public void AssemblyLoadFromBytes()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location);
Assembly loadedAssembly = Assembly.Load(aBytes);
Assert.NotNull(loadedAssembly);
Assert.Equal(assembly.FullName, loadedAssembly.FullName);
}
[Fact]
public void AssemblyLoadFromBytesNeg()
{
Assert.Throws<ArgumentNullException>(() => Assembly.Load((byte[])null));
Assert.Throws<BadImageFormatException>(() => Assembly.Load(new byte[0]));
}
[Fact]
public void AssemblyLoadFromBytesWithSymbols()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location);
byte[] symbols = System.IO.File.ReadAllBytes((System.IO.Path.ChangeExtension(assembly.Location, ".pdb")));
Assembly loadedAssembly = Assembly.Load(aBytes, symbols);
Assert.NotNull(loadedAssembly);
Assert.Equal(assembly.FullName, loadedAssembly.FullName);
}
[Fact]
public void AssemblyReflectionOnlyLoadFromString()
{
AssemblyName an = typeof(AssemblyTests).Assembly.GetName();
Assert.Throws<PlatformNotSupportedException>(() => Assembly.ReflectionOnlyLoad(an.FullName));
}
[Fact]
public void AssemblyReflectionOnlyLoadFromBytes()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location);
Assert.Throws<PlatformNotSupportedException>(() => Assembly.ReflectionOnlyLoad(aBytes));
}
[Fact]
public void AssemblyReflectionOnlyLoadFromNeg()
{
Assert.Throws<PlatformNotSupportedException>(() => Assembly.ReflectionOnlyLoad((string)null));
Assert.Throws<PlatformNotSupportedException>(() => Assembly.ReflectionOnlyLoad(string.Empty));
Assert.Throws<PlatformNotSupportedException>(() => Assembly.ReflectionOnlyLoad((byte[])null));
}
public static IEnumerable<object[]> GetModules_TestData()
{
yield return new object[] { LoadSystemCollectionsAssembly() };
yield return new object[] { LoadSystemReflectionAssembly() };
}
[Theory]
[MemberData(nameof(GetModules_TestData))]
public void GetModules_GetModule(Assembly assembly)
{
Assert.NotEmpty(assembly.GetModules());
foreach (Module module in assembly.GetModules())
{
Assert.Equal(module, assembly.GetModule(module.ToString()));
}
}
[Fact]
public void GetLoadedModules()
{
Assembly assembly = typeof(AssemblyTests).Assembly;
Assert.NotEmpty(assembly.GetLoadedModules());
foreach (Module module in assembly.GetLoadedModules())
{
Assert.NotNull(module);
Assert.Equal(module, assembly.GetModule(module.ToString()));
}
}
[Theory]
[InlineData(typeof(Int32Attr))]
[InlineData(typeof(Int64Attr))]
[InlineData(typeof(StringAttr))]
[InlineData(typeof(EnumAttr))]
[InlineData(typeof(TypeAttr))]
[InlineData(typeof(CompilationRelaxationsAttribute))]
[InlineData(typeof(AssemblyTitleAttribute))]
[InlineData(typeof(AssemblyDescriptionAttribute))]
[InlineData(typeof(AssemblyCompanyAttribute))]
[InlineData(typeof(CLSCompliantAttribute))]
[InlineData(typeof(DebuggableAttribute))]
[InlineData(typeof(Attr))]
public void GetCustomAttributesData(Type attrType)
{
IEnumerable<CustomAttributeData> customAttributesData = typeof(AssemblyTests).Assembly.GetCustomAttributesData().Where(cad => cad.AttributeType == attrType);
Assert.True(customAttributesData.Count() > 0, $"Did not find custom attribute of type {attrType}");
}
private static Assembly LoadSystemCollectionsAssembly()
{
// Force System.collections to be linked statically
List<int> li = new List<int>();
li.Add(1);
return Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName));
}
private static Assembly LoadSystemReflectionAssembly()
{
// Force System.Reflection to be linked statically
return Assembly.Load(new AssemblyName(typeof(AssemblyName).GetTypeInfo().Assembly.FullName));
}
private static Assembly LoadSystemRuntimeAssembly()
{
// Load System.Runtime
return Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)); ;
}
private static Assembly GetGetCallingAssembly()
{
return Assembly.GetCallingAssembly();
}
}
public struct PublicStruct { }
public class AssemblyPublicClass
{
public class PublicNestedClass { }
}
public class AssemblyGenericPublicClass<T> { }
internal class AssemblyInternalClass { }
public class AssemblyClassWithPrivateCtor
{
private AssemblyClassWithPrivateCtor() { }
}
public class AssemblyClassWithNoDefaultCtor
{
public AssemblyClassWithNoDefaultCtor(int x) { }
}
}
internal class G<T> { }
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Employee Categories Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KPECDataSet : EduHubDataSet<KPEC>
{
/// <inheritdoc />
public override string Name { get { return "KPEC"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KPECDataSet(EduHubContext Context)
: base(Context)
{
Index_KPECKEY = new Lazy<Dictionary<string, KPEC>>(() => this.ToDictionary(i => i.KPECKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KPEC" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KPEC" /> fields for each CSV column header</returns>
internal override Action<KPEC, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KPEC, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "KPECKEY":
mapper[i] = (e, v) => e.KPECKEY = v;
break;
case "DESCRIPTION":
mapper[i] = (e, v) => e.DESCRIPTION = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KPEC" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KPEC" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KPEC" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KPEC}"/> of entities</returns>
internal override IEnumerable<KPEC> ApplyDeltaEntities(IEnumerable<KPEC> Entities, List<KPEC> DeltaEntities)
{
HashSet<string> Index_KPECKEY = new HashSet<string>(DeltaEntities.Select(i => i.KPECKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.KPECKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_KPECKEY.Remove(entity.KPECKEY);
if (entity.KPECKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, KPEC>> Index_KPECKEY;
#endregion
#region Index Methods
/// <summary>
/// Find KPEC by KPECKEY field
/// </summary>
/// <param name="KPECKEY">KPECKEY value used to find KPEC</param>
/// <returns>Related KPEC entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KPEC FindByKPECKEY(string KPECKEY)
{
return Index_KPECKEY.Value[KPECKEY];
}
/// <summary>
/// Attempt to find KPEC by KPECKEY field
/// </summary>
/// <param name="KPECKEY">KPECKEY value used to find KPEC</param>
/// <param name="Value">Related KPEC entity</param>
/// <returns>True if the related KPEC entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByKPECKEY(string KPECKEY, out KPEC Value)
{
return Index_KPECKEY.Value.TryGetValue(KPECKEY, out Value);
}
/// <summary>
/// Attempt to find KPEC by KPECKEY field
/// </summary>
/// <param name="KPECKEY">KPECKEY value used to find KPEC</param>
/// <returns>Related KPEC entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KPEC TryFindByKPECKEY(string KPECKEY)
{
KPEC value;
if (Index_KPECKEY.Value.TryGetValue(KPECKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KPEC table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KPEC]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KPEC](
[KPECKEY] varchar(10) NOT NULL,
[DESCRIPTION] varchar(30) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KPEC_Index_KPECKEY] PRIMARY KEY CLUSTERED (
[KPECKEY] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="KPECDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="KPECDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KPEC"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KPEC"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KPEC> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_KPECKEY = new List<string>();
foreach (var entity in Entities)
{
Index_KPECKEY.Add(entity.KPECKEY);
}
builder.AppendLine("DELETE [dbo].[KPEC] WHERE");
// Index_KPECKEY
builder.Append("[KPECKEY] IN (");
for (int index = 0; index < Index_KPECKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// KPECKEY
var parameterKPECKEY = $"@p{parameterIndex++}";
builder.Append(parameterKPECKEY);
command.Parameters.Add(parameterKPECKEY, SqlDbType.VarChar, 10).Value = Index_KPECKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KPEC data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KPEC data set</returns>
public override EduHubDataSetDataReader<KPEC> GetDataSetDataReader()
{
return new KPECDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KPEC data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KPEC data set</returns>
public override EduHubDataSetDataReader<KPEC> GetDataSetDataReader(List<KPEC> Entities)
{
return new KPECDataReader(new EduHubDataSetLoadedReader<KPEC>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KPECDataReader : EduHubDataSetDataReader<KPEC>
{
public KPECDataReader(IEduHubDataSetReader<KPEC> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 5; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // KPECKEY
return Current.KPECKEY;
case 1: // DESCRIPTION
return Current.DESCRIPTION;
case 2: // LW_DATE
return Current.LW_DATE;
case 3: // LW_TIME
return Current.LW_TIME;
case 4: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // DESCRIPTION
return Current.DESCRIPTION == null;
case 2: // LW_DATE
return Current.LW_DATE == null;
case 3: // LW_TIME
return Current.LW_TIME == null;
case 4: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // KPECKEY
return "KPECKEY";
case 1: // DESCRIPTION
return "DESCRIPTION";
case 2: // LW_DATE
return "LW_DATE";
case 3: // LW_TIME
return "LW_TIME";
case 4: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "KPECKEY":
return 0;
case "DESCRIPTION":
return 1;
case "LW_DATE":
return 2;
case "LW_TIME":
return 3;
case "LW_USER":
return 4;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System.Text.RegularExpressions;
using System.Diagnostics;
using System;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using WeifenLuo.WinFormsUI;
using Microsoft.Win32;
using WeifenLuo;
using System.ComponentModel;
namespace SoftLogik.Win.UI
{
/// <summary>
/// Treeview Control that utilizes a Custom Data Source Manager .
/// </summary>
[ToolboxBitmap(typeof(TreeView), "DataTreeView")]
public partial class DataTreeView
{
protected override void OnPaint(PaintEventArgs pe)
{
// Calling the base class OnPaint
base.OnPaint(pe);
}
private bool m_autoBuild = true;
public bool AutoBuildTree
{
get
{
return this.m_autoBuild;
}
set
{
this.m_autoBuild = value;
}
}
#region Data Binding
private CurrencyManager m_currencyManager = null;
private string m_ValueMember;
private string m_DisplayMember;
private object m_oDataSource;
[Category("Data")]public object DataSource
{
get
{
return m_oDataSource;
}
set
{
if (value == null)
{
this.m_currencyManager = null;
this.Nodes.Clear();
}
else
{
if (!(value is IList|| m_oDataSource is IListSource))
{
throw (new System.Exception("Invalid DataSource"));
}
else
{
if (value is IListSource)
{
IListSource myListSource = (IListSource) value;
if (myListSource.ContainsListCollection == true)
{
throw (new System.Exception("Invalid DataSource"));
}
}
this.m_oDataSource = value;
this.m_currencyManager = (CurrencyManager) (this.BindingContext[value]);
if (this.AutoBuildTree)
{
BuildTree();
}
}
}
}
} // end of DataSource property
[Category("Data")]public string ValueMember
{
get
{
return this.m_ValueMember;
}
set
{
this.m_ValueMember = value;
}
}
[Category("Data")]public string DisplayMember
{
get
{
return this.m_DisplayMember;
}
set
{
this.m_DisplayMember = value;
}
}
public object GetValue(int index)
{
IList innerList = this.m_currencyManager.List;
if (innerList != null)
{
if ((this.ValueMember != "") && (index >= 0 && 0 < innerList.Count))
{
PropertyDescriptor pdValueMember;
pdValueMember = this.m_currencyManager.GetItemProperties()[this.ValueMember];
return pdValueMember.GetValue(innerList[index]);
}
}
return null;
}
public object GetDisplay(int index)
{
IList innerList = this.m_currencyManager.List;
if (innerList != null)
{
if ((this.DisplayMember != "") && (index >= 0 && 0 < innerList.Count))
{
PropertyDescriptor pdDisplayMember;
pdDisplayMember = this.m_currencyManager.GetItemProperties()[this.ValueMember];
return pdDisplayMember.GetValue(innerList[index]);
}
}
return null;
}
#endregion
#region Building the Tree
private ArrayList treeGroups = new ArrayList();
public void BuildTree()
{
this.Nodes.Clear();
if ((this.m_currencyManager != null) && (this.m_currencyManager.List != null))
{
IList innerList = this.m_currencyManager.List;
TreeNodeCollection currNode = this.Nodes;
int currGroupIndex = 0;
int currListIndex = 0;
if (this.treeGroups.Count > currGroupIndex)
{
SPTreeNodeGroup currGroup = (SPTreeNodeGroup) (treeGroups[currGroupIndex]);
SPTreeNode myFirstNode = null;
PropertyDescriptor pdGroupBy;
PropertyDescriptor pdValue;
PropertyDescriptor pdDisplay;
pdGroupBy = this.m_currencyManager.GetItemProperties()[currGroup.GroupBy];
pdValue = this.m_currencyManager.GetItemProperties()[currGroup.ValueMember];
pdDisplay = this.m_currencyManager.GetItemProperties()[currGroup.DisplayMember];
string currGroupBy = null;
if (innerList.Count > currListIndex)
{
object currObject;
while (currListIndex < innerList.Count)
{
currObject = innerList[currListIndex];
if (pdGroupBy.GetValue(currObject).ToString() != currGroupBy)
{
currGroupBy = pdGroupBy.GetValue(currObject).ToString();
myFirstNode = new SPTreeNode(currGroup.Name, pdDisplay.GetValue(currObject).ToString(), currObject, pdValue.GetValue(innerList[currListIndex]), currGroup.ImageIndex, currGroup.SelectedImageIndex, currListIndex);
currNode.Add((TreeNode) myFirstNode);
}
else
{
AddNodes(currGroupIndex, ref currListIndex, myFirstNode.Nodes, currGroup.GroupBy);
}
} // end while
} // end if
}
else
{
while (currListIndex < innerList.Count)
{
AddNodes(currGroupIndex, ref currListIndex, this.Nodes, "");
}
} // end else
if (this.Nodes.Count > 0)
{
this.SelectedNode = this.Nodes[0];
}
} // end if
}
private void AddNodes(int currGroupIndex, ref int currentListIndex, TreeNodeCollection currNodes, string prevGroupByField)
{
IList innerList = this.m_currencyManager.List;
System.ComponentModel.PropertyDescriptor pdPrevGroupBy = null;
string prevGroupByValue = null;
SPTreeNodeGroup currGroup;
if (prevGroupByField != "")
{
pdPrevGroupBy = this.m_currencyManager.GetItemProperties()[prevGroupByField];
}
currGroupIndex++;
if (treeGroups.Count > currGroupIndex)
{
currGroup = (SPTreeNodeGroup) (treeGroups[currGroupIndex]);
PropertyDescriptor pdGroupBy = null;
PropertyDescriptor pdValue = null;
PropertyDescriptor pdDisplay = null;
pdGroupBy = this.m_currencyManager.GetItemProperties()[currGroup.GroupBy];
pdValue = this.m_currencyManager.GetItemProperties()[currGroup.ValueMember];
pdDisplay = this.m_currencyManager.GetItemProperties()[currGroup.DisplayMember];
string currGroupBy = null;
if (innerList.Count > currentListIndex)
{
if (pdPrevGroupBy != null)
{
prevGroupByValue = pdPrevGroupBy.GetValue(innerList[currentListIndex]).ToString();
}
SPTreeNode myFirstNode = null;
object currObject = null;
while ((currentListIndex < innerList.Count) && (pdPrevGroupBy != null) && (pdPrevGroupBy.GetValue(innerList[currentListIndex]).ToString() == prevGroupByValue))
{
currObject = innerList[currentListIndex];
if (pdGroupBy.GetValue(currObject).ToString() != currGroupBy)
{
currGroupBy = pdGroupBy.GetValue(currObject).ToString();
myFirstNode = new SPTreeNode(currGroup.Name, pdDisplay.GetValue(currObject).ToString(), currObject, pdValue.GetValue(innerList[currentListIndex]), currGroup.ImageIndex, currGroup.SelectedImageIndex, currentListIndex);
currNodes.Add((TreeNode) myFirstNode);
}
else
{
AddNodes(currGroupIndex, ref currentListIndex, myFirstNode.Nodes, currGroup.GroupBy);
}
}
}
}
else
{
SPTreeNode myNewLeafNode;
object currObject = this.m_currencyManager.List[currentListIndex];
if ((this.DisplayMember != null) && (this.ValueMember != null) && (this.DisplayMember != "") && (this.ValueMember != ""))
{
PropertyDescriptorCollection pdDisplayColl = this.m_currencyManager.GetItemProperties();
PropertyDescriptor pdDisplayloc = pdDisplayColl[this.DisplayMember.ToLowerInvariant()];
PropertyDescriptor pdValueloc = pdDisplayColl[this.ValueMember.ToLowerInvariant()];
if (this.Tag == null)
{
myNewLeafNode = new SPTreeNode("", pdDisplayloc.GetValue(currObject).ToString(), currObject, pdValueloc.GetValue(currObject), currentListIndex);
}
else
{
myNewLeafNode = new SPTreeNode(this.Tag.ToString(), pdDisplayloc.GetValue(currObject).ToString(), currObject, pdValueloc.GetValue(currObject), currentListIndex);
}
}
else
{
myNewLeafNode = new SPTreeNode("", currentListIndex.ToString(), currObject, currObject, this.ImageIndex, this.SelectedImageIndex, currentListIndex);
}
currNodes.Add((TreeNode) myNewLeafNode);
currentListIndex++;
}
}
#endregion
#region Groups
public void RemoveGroup(SPTreeNodeGroup group)
{
if (treeGroups.Contains(group))
{
treeGroups.Remove(group);
if (this.AutoBuildTree)
{
BuildTree();
}
}
}
public void RemoveGroup(string groupName)
{
foreach (SPTreeNodeGroup group in this.treeGroups)
{
if (group.Name == groupName)
{
RemoveGroup(group);
return;
}
}
}
public void RemoveAllGroups()
{
this.treeGroups.Clear();
if (this.AutoBuildTree)
{
this.BuildTree();
}
}
public void AddGroup(SPTreeNodeGroup group)
{
try
{
treeGroups.Add(group);
if (this.AutoBuildTree)
{
this.BuildTree();
}
}
catch (NotSupportedException e)
{
MessageBox.Show(e.Message);
}
catch (System.Exception e)
{
throw (e);
}
}
public void AddGroup(string name, string groupBy, string displayMember, string valueMember, int imageIndex, int selectedImageIndex)
{
SPTreeNodeGroup myNewGroup = new SPTreeNodeGroup(name, groupBy, displayMember, valueMember, imageIndex, selectedImageIndex);
this.AddGroup(myNewGroup);
}
public SPTreeNodeGroup[] GetGroups()
{
return ((SPTreeNodeGroup[]) (treeGroups.ToArray(Type.GetType("SPTreeNodeGroup"))));
}
#endregion
public void SetLeafData(string name, string displayMember, string valueMember, int imageIndex, int selectedImageIndex)
{
this.Tag = name;
this.DisplayMember = displayMember;
this.ValueMember = valueMember;
this.ImageIndex = imageIndex;
this.SelectedImageIndex = selectedImageIndex;
}
public bool IsLeafNode(TreeNode node)
{
return (node.Nodes.Count == 0);
}
#region Keeping Everything In Sync
public TreeNode FindNodeByValue(object value)
{
return FindNodeByValue(value, this.Nodes);
}
public TreeNode FindNodeByValue(object Value, TreeNodeCollection nodesToSearch)
{
int i = 0;
TreeNode currNode;
SPTreeNode leafNode;
while (i < nodesToSearch.Count)
{
currNode = nodesToSearch[i];
i++;
if (currNode.LastNode == null)
{
leafNode = (SPTreeNode) currNode;
if (leafNode.Value.ToString() == Value.ToString())
{
return currNode;
}
}
else
{
currNode = FindNodeByValue(Value, currNode.Nodes);
if (currNode != null)
{
return currNode;
}
}
}
return null;
}
private TreeNode FindNodeByPosition(int posIndex)
{
return FindNodeByPosition(posIndex, this.Nodes);
}
private TreeNode FindNodeByPosition(int posIndex, TreeNodeCollection nodesToSearch)
{
int i = 0;
TreeNode currNode;
SPTreeNode leafNode;
while (i < nodesToSearch.Count)
{
currNode = nodesToSearch[i];
i++;
if (currNode.Nodes.Count == 0)
{
leafNode = (SPTreeNode) currNode;
if (leafNode.Position == posIndex)
{
return currNode;
}
else
{
currNode = FindNodeByPosition(posIndex, currNode.Nodes);
if (currNode != null)
{
return currNode;
}
}
}
}
return null;
}
protected override void OnAfterSelect(TreeViewEventArgs e)
{
SPTreeNode leafNode = (SPTreeNode) e.Node;
if (leafNode != null)
{
if (this.m_currencyManager.Position != leafNode.Position)
{
this.m_currencyManager.Position = leafNode.Position;
}
}
base.OnAfterSelect(e);
}
#endregion
}
[Description("Specify Grouping for a collection of Tree Nodes in TreeView")]public class SPTreeNodeGroup
{
private string groupName;
private string groupByMember;
private string groupByDisplayMember;
private string groupByValueMember;
private int groupImageIndex;
private int groupSelectedImageIndex;
public SPTreeNodeGroup(string name, string groupBy, string displayMember, string valueMember, int imageIndex, int selectedImageIndex)
{
this.ImageIndex = imageIndex;
this.Name = name;
this.GroupBy = groupBy;
this.DisplayMember = displayMember;
this.ValueMember = valueMember;
this.SelectedImageIndex = selectedImageIndex;
}
public SPTreeNodeGroup(string name, string groupBy, string displayMember, string valueMember, int imageIndex) : this(name, groupBy, displayMember, valueMember, imageIndex, imageIndex)
{
}
public SPTreeNodeGroup(string name, string groupBy) : this(name, groupBy, groupBy, groupBy, - 1, - 1)
{
}
public int SelectedImageIndex
{
get
{
return groupSelectedImageIndex;
}
set
{
groupSelectedImageIndex = value;
}
}
public int ImageIndex
{
get
{
return groupImageIndex;
}
set
{
groupImageIndex = value;
}
}
public string Name
{
get
{
return groupName;
}
set
{
groupName = value;
}
}
public string GroupBy
{
get
{
return groupByMember;
}
set
{
groupByMember = value;
}
}
public string DisplayMember
{
get
{
return groupByDisplayMember;
}
set
{
groupByDisplayMember = value;
}
}
public string ValueMember
{
get
{
return groupByValueMember;
}
set
{
groupByValueMember = value;
}
}
}
[Description("A Node in the TreeView")]public class SPTreeNode : TreeNode
{
private string m_groupName;
private object m_value;
private object m_item;
private int m_position;
public SPTreeNode()
{
}
public SPTreeNode(string GroupName, string text, object item, object value, int imageIndex, int selectedImgIndex, int position)
{
this.GroupName = GroupName;
this.Text = text;
this.Item = item;
this.Value = value;
this.ImageIndex = imageIndex;
this.SelectedImageIndex = selectedImgIndex;
this.m_position = position;
}
public SPTreeNode(string groupName, string text, object item, object value, int position)
{
this.GroupName = groupName;
this.Text = text;
this.Item = item;
this.Value = value;
this.m_position = position;
}
public string GroupName
{
get
{
return m_groupName;
}
set
{
this.m_groupName = value;
}
}
public object Item
{
get
{
return m_item;
}
set
{
m_item = value;
}
}
public object Value
{
get
{
return m_value;
}
set
{
m_value = value;
}
}
public int Position
{
get
{
return m_position;
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcsv = Google.Cloud.Scheduler.V1;
using sys = System;
namespace Google.Cloud.Scheduler.V1
{
/// <summary>Resource name for the <c>Job</c> resource.</summary>
public sealed partial class JobName : gax::IResourceName, sys::IEquatable<JobName>
{
/// <summary>The possible contents of <see cref="JobName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/jobs/{job}</c>.
/// </summary>
ProjectLocationJob = 1,
}
private static gax::PathTemplate s_projectLocationJob = new gax::PathTemplate("projects/{project}/locations/{location}/jobs/{job}");
/// <summary>Creates a <see cref="JobName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="JobName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static JobName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new JobName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="JobName"/> with the pattern <c>projects/{project}/locations/{location}/jobs/{job}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="jobId">The <c>Job</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="JobName"/> constructed from the provided ids.</returns>
public static JobName FromProjectLocationJob(string projectId, string locationId, string jobId) =>
new JobName(ResourceNameType.ProjectLocationJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), jobId: gax::GaxPreconditions.CheckNotNullOrEmpty(jobId, nameof(jobId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="JobName"/> with pattern
/// <c>projects/{project}/locations/{location}/jobs/{job}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="jobId">The <c>Job</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="JobName"/> with pattern
/// <c>projects/{project}/locations/{location}/jobs/{job}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string jobId) =>
FormatProjectLocationJob(projectId, locationId, jobId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="JobName"/> with pattern
/// <c>projects/{project}/locations/{location}/jobs/{job}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="jobId">The <c>Job</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="JobName"/> with pattern
/// <c>projects/{project}/locations/{location}/jobs/{job}</c>.
/// </returns>
public static string FormatProjectLocationJob(string projectId, string locationId, string jobId) =>
s_projectLocationJob.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(jobId, nameof(jobId)));
/// <summary>Parses the given resource name string into a new <see cref="JobName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/jobs/{job}</c></description></item>
/// </list>
/// </remarks>
/// <param name="jobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="JobName"/> if successful.</returns>
public static JobName Parse(string jobName) => Parse(jobName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="JobName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/jobs/{job}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="jobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="JobName"/> if successful.</returns>
public static JobName Parse(string jobName, bool allowUnparsed) =>
TryParse(jobName, allowUnparsed, out JobName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>Tries to parse the given resource name string into a new <see cref="JobName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/jobs/{job}</c></description></item>
/// </list>
/// </remarks>
/// <param name="jobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="JobName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string jobName, out JobName result) => TryParse(jobName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="JobName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/jobs/{job}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="jobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="JobName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string jobName, bool allowUnparsed, out JobName result)
{
gax::GaxPreconditions.CheckNotNull(jobName, nameof(jobName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationJob.TryParseName(jobName, out resourceName))
{
result = FromProjectLocationJob(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(jobName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private JobName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string jobId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
JobId = jobId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="JobName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/jobs/{job}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="jobId">The <c>Job</c> ID. Must not be <c>null</c> or empty.</param>
public JobName(string projectId, string locationId, string jobId) : this(ResourceNameType.ProjectLocationJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), jobId: gax::GaxPreconditions.CheckNotNullOrEmpty(jobId, nameof(jobId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Job</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string JobId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationJob: return s_projectLocationJob.Expand(ProjectId, LocationId, JobId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as JobName);
/// <inheritdoc/>
public bool Equals(JobName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(JobName a, JobName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(JobName a, JobName b) => !(a == b);
}
public partial class Job
{
/// <summary>
/// <see cref="gcsv::JobName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::JobName JobName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::JobName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
#pragma warning disable 169
// ReSharper disable InconsistentNaming
namespace NEventStore.Persistence.AcceptanceTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using NEventStore.Contrib.Persistence.AcceptanceTests;
using NEventStore.Contrib.Persistence.AcceptanceTests.BDD;
using NEventStore.Diagnostics;
using Xunit;
using Xunit.Should;
public class when_a_commit_header_has_a_name_that_contains_a_period : PersistenceEngineConcern
{
private ICommit _persisted;
private string _streamId;
protected override void Context()
{
_streamId = Guid.NewGuid().ToString();
var attempt = new CommitAttempt(_streamId,
2,
Guid.NewGuid(),
1,
DateTime.Now,
new Dictionary<string, object> { { "key.1", "value" } },
new List<EventMessage> { new EventMessage { Body = new ExtensionMethods.SomeDomainEvent { SomeProperty = "Test" } } });
Persistence.Commit(attempt);
}
protected override void Because()
{
_persisted = Persistence.GetFrom(_streamId, 0, int.MaxValue).First();
}
[Fact]
public void should_correctly_deserialize_headers()
{
_persisted.Headers.Keys.ShouldContain("key.1");
}
}
public class when_a_commit_is_successfully_persisted : PersistenceEngineConcern
{
private CommitAttempt _attempt;
private DateTime _now;
private ICommit _persisted;
private string _streamId;
protected override void Context()
{
_now = SystemTime.UtcNow.AddYears(1);
_streamId = Guid.NewGuid().ToString();
_attempt = _streamId.BuildAttempt(_now);
Persistence.Commit(_attempt);
}
protected override void Because()
{
_persisted = Persistence.GetFrom(_streamId, 0, int.MaxValue).First();
}
[Fact]
public void should_correctly_persist_the_stream_identifier()
{
_persisted.StreamId.ShouldBe(_attempt.StreamId);
}
[Fact]
public void should_correctly_persist_the_stream_stream_revision()
{
_persisted.StreamRevision.ShouldBe(_attempt.StreamRevision);
}
[Fact]
public void should_correctly_persist_the_commit_identifier()
{
_persisted.CommitId.ShouldBe(_attempt.CommitId);
}
[Fact]
public void should_correctly_persist_the_commit_sequence()
{
_persisted.CommitSequence.ShouldBe(_attempt.CommitSequence);
}
// persistence engines have varying levels of precision with respect to time.
[Fact]
public void should_correctly_persist_the_commit_stamp()
{
var difference = _persisted.CommitStamp.Subtract(_now);
difference.Days.ShouldBe(0);
difference.Hours.ShouldBe(0);
difference.Minutes.ShouldBe(0);
difference.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(1));
}
[Fact]
public void should_correctly_persist_the_headers()
{
_persisted.Headers.Count.ShouldBe(_attempt.Headers.Count);
}
[Fact]
public void should_correctly_persist_the_events()
{
_persisted.Events.Count.ShouldBe(_attempt.Events.Count);
}
[Fact]
public void should_add_the_commit_to_the_set_of_undispatched_commits()
{
Persistence.GetUndispatchedCommits().FirstOrDefault(x => x.CommitId == _attempt.CommitId).ShouldNotBeNull();
}
[Fact]
public void should_cause_the_stream_to_be_found_in_the_list_of_streams_to_snapshot()
{
Persistence.GetStreamsToSnapshot(1).FirstOrDefault(x => x.StreamId == _streamId).ShouldNotBeNull();
}
}
public class when_reading_from_a_given_revision : PersistenceEngineConcern
{
private const int LoadFromCommitContainingRevision = 3;
private const int UpToCommitWithContainingRevision = 5;
private ICommit[] _committed;
private ICommit _oldest, _oldest2, _oldest3;
private string _streamId;
protected override void Context()
{
_oldest = Persistence.CommitSingle(); // 2 events, revision 1-2
_oldest2 = Persistence.CommitNext(_oldest); // 2 events, revision 3-4
_oldest3 = Persistence.CommitNext(_oldest2); // 2 events, revision 5-6
Persistence.CommitNext(_oldest3); // 2 events, revision 7-8
_streamId = _oldest.StreamId;
}
protected override void Because()
{
_committed = Persistence.GetFrom(_streamId, LoadFromCommitContainingRevision, UpToCommitWithContainingRevision).ToArray();
}
[Fact]
public void should_start_from_the_commit_which_contains_the_min_stream_revision_specified()
{
_committed.First().CommitId.ShouldBe(_oldest2.CommitId); // contains revision 3
}
[Fact]
public void should_read_up_to_the_commit_which_contains_the_max_stream_revision_specified()
{
_committed.Last().CommitId.ShouldBe(_oldest3.CommitId); // contains revision 5
}
}
public class when_reading_from_a_given_revision_to_commit_revision : PersistenceEngineConcern
{
private const int LoadFromCommitContainingRevision = 3;
private const int UpToCommitWithContainingRevision = 6;
private ICommit[] _committed;
private ICommit _oldest, _oldest2, _oldest3;
private string _streamId;
protected override void Context()
{
_oldest = Persistence.CommitSingle(); // 2 events, revision 1-2
_oldest2 = Persistence.CommitNext(_oldest); // 2 events, revision 3-4
_oldest3 = Persistence.CommitNext(_oldest2); // 2 events, revision 5-6
Persistence.CommitNext(_oldest3); // 2 events, revision 7-8
_streamId = _oldest.StreamId;
}
protected override void Because()
{
_committed = Persistence.GetFrom(_streamId, LoadFromCommitContainingRevision, UpToCommitWithContainingRevision).ToArray();
}
[Fact]
public void should_start_from_the_commit_which_contains_the_min_stream_revision_specified()
{
_committed.First().CommitId.ShouldBe(_oldest2.CommitId); // contains revision 3
}
[Fact]
public void should_read_up_to_the_commit_which_contains_the_max_stream_revision_specified()
{
_committed.Last().CommitId.ShouldBe(_oldest3.CommitId); // contains revision 6
}
}
public class when_committing_a_stream_with_the_same_revision : PersistenceEngineConcern
{
private CommitAttempt _attemptWithSameRevision;
private Exception _thrown;
protected override void Context()
{
ICommit commit = Persistence.CommitSingle();
_attemptWithSameRevision = commit.StreamId.BuildAttempt();
}
protected override void Because()
{
_thrown = Catch.Exception(() => Persistence.Commit(_attemptWithSameRevision));
}
[Fact]
public void should_throw_a_ConcurrencyException()
{
_thrown.ShouldBeInstanceOf<ConcurrencyException>();
}
}
// This test ensure the uniqueness of BucketId+StreamId+CommitSequence
// to avoid concurrency issues
public class when_committing_a_stream_with_the_same_sequence : PersistenceEngineConcern
{
private CommitAttempt _attempt1, _attempt2;
private Exception _thrown;
protected override void Context()
{
string streamId = Guid.NewGuid().ToString();
_attempt1 = streamId.BuildAttempt();
_attempt2 = new CommitAttempt(
_attempt1.BucketId, // <--- Same bucket
_attempt1.StreamId, // <--- Same stream it
_attempt1.StreamRevision +10,
Guid.NewGuid(),
_attempt1.CommitSequence, // <--- Same commit seq
DateTime.UtcNow,
_attempt1.Headers,
new[]
{
new EventMessage(){ Body = new NEventStore.Contrib.Persistence.AcceptanceTests.ExtensionMethods.SomeDomainEvent {SomeProperty = "Test 3"}}
}
);
Persistence.Commit(_attempt1);
}
protected override void Because()
{
_thrown = Catch.Exception(() => Persistence.Commit(_attempt2));
}
[Fact]
public void should_throw_a_ConcurrencyException()
{
_thrown.ShouldBeInstanceOf<ConcurrencyException>();
}
}
//TODO:This test looks exactly like the one above. What are we trying to prove?
public class when_attempting_to_overwrite_a_committed_sequence : PersistenceEngineConcern
{
private CommitAttempt _failedAttempt;
private Exception _thrown;
protected override void Context()
{
string streamId = Guid.NewGuid().ToString();
CommitAttempt successfulAttempt = streamId.BuildAttempt();
Persistence.Commit(successfulAttempt);
_failedAttempt = streamId.BuildAttempt();
}
protected override void Because()
{
_thrown = Catch.Exception(() => Persistence.Commit(_failedAttempt));
}
[Fact]
public void should_throw_a_ConcurrencyException()
{
_thrown.ShouldBeInstanceOf<ConcurrencyException>();
}
}
public class when_attempting_to_persist_a_commit_twice : PersistenceEngineConcern
{
private CommitAttempt _attemptTwice;
private Exception _thrown;
protected override void Context()
{
var commit = Persistence.CommitSingle();
_attemptTwice = new CommitAttempt(
commit.BucketId,
commit.StreamId,
commit.StreamRevision,
commit.CommitId,
commit.CommitSequence,
commit.CommitStamp,
commit.Headers,
commit.Events);
}
protected override void Because()
{
_thrown = Catch.Exception(() => Persistence.Commit(_attemptTwice));
}
[Fact]
public void should_throw_a_DuplicateCommitException()
{
_thrown.ShouldBeInstanceOf<DuplicateCommitException>();
}
}
public class when_a_commit_has_been_marked_as_dispatched : PersistenceEngineConcern
{
private ICommit _commit;
protected override void Context()
{
_commit = Persistence.CommitSingle();
}
protected override void Because()
{
Persistence.MarkCommitAsDispatched(_commit);
}
[Fact]
public void should_no_longer_be_found_in_the_set_of_undispatched_commits()
{
Persistence.GetUndispatchedCommits().FirstOrDefault(x => x.CommitId == _commit.CommitId).ShouldBeNull();
}
}
public class when_committing_more_events_than_the_configured_page_size : PersistenceEngineConcern
{
private CommitAttempt[] _committed;
private ICommit[] _loaded;
private string _streamId;
protected override void Context()
{
_streamId = Guid.NewGuid().ToString();
_committed = Persistence.CommitMany(ConfiguredPageSizeForTesting + 2, _streamId).ToArray();
}
protected override void Because()
{
_loaded = Persistence.GetFrom(_streamId, 0, int.MaxValue).ToArray();
}
[Fact]
public void should_load_the_same_number_of_commits_which_have_been_persisted()
{
_loaded.Length.ShouldBe(_committed.Length);
}
[Fact]
public void should_load_the_same_commits_which_have_been_persisted()
{
_committed
.All(commit => _loaded.SingleOrDefault(loaded => loaded.CommitId == commit.CommitId) != null)
.ShouldBeTrue();
}
}
public class when_saving_a_snapshot : PersistenceEngineConcern
{
private bool _added;
private Snapshot _snapshot;
private string _streamId;
protected override void Context()
{
_streamId = Guid.NewGuid().ToString();
_snapshot = new Snapshot(_streamId, 1, "Snapshot");
Persistence.CommitSingle(_streamId);
}
protected override void Because()
{
_added = Persistence.AddSnapshot(_snapshot);
}
[Fact]
public void should_indicate_the_snapshot_was_added()
{
_added.ShouldBeTrue();
}
[Fact]
public void should_be_able_to_retrieve_the_snapshot()
{
Persistence.GetSnapshot(_streamId, _snapshot.StreamRevision).ShouldNotBeNull();
}
}
public class when_retrieving_a_snapshot : PersistenceEngineConcern
{
private ISnapshot _correct;
private ISnapshot _snapshot;
private string _streamId;
private ISnapshot _tooFarForward;
protected override void Context()
{
_streamId = Guid.NewGuid().ToString();
ICommit commit1 = Persistence.CommitSingle(_streamId); // rev 1-2
ICommit commit2 = Persistence.CommitNext(commit1); // rev 3-4
Persistence.CommitNext(commit2); // rev 5-6
Persistence.AddSnapshot(new Snapshot(_streamId, 1, string.Empty)); //Too far back
Persistence.AddSnapshot(_correct = new Snapshot(_streamId, 3, "Snapshot"));
Persistence.AddSnapshot(_tooFarForward = new Snapshot(_streamId, 5, string.Empty));
}
protected override void Because()
{
_snapshot = Persistence.GetSnapshot(_streamId, _tooFarForward.StreamRevision - 1);
}
[Fact]
public void should_load_the_most_recent_prior_snapshot()
{
_snapshot.StreamRevision.ShouldBe(_correct.StreamRevision);
}
[Fact]
public void should_have_the_correct_snapshot_payload()
{
_snapshot.Payload.ShouldBe(_correct.Payload);
}
[Fact]
public void should_have_the_correct_stream_id()
{
_snapshot.StreamId.ShouldBe(_correct.StreamId);
}
}
public class when_a_snapshot_has_been_added_to_the_most_recent_commit_of_a_stream : PersistenceEngineConcern
{
private const string SnapshotData = "snapshot";
private ICommit _newest;
private ICommit _oldest, _oldest2;
private string _streamId;
protected override void Context()
{
_streamId = Guid.NewGuid().ToString();
_oldest = Persistence.CommitSingle(_streamId);
_oldest2 = Persistence.CommitNext(_oldest);
_newest = Persistence.CommitNext(_oldest2);
}
protected override void Because()
{
Persistence.AddSnapshot(new Snapshot(_streamId, _newest.StreamRevision, SnapshotData));
}
[Fact]
public void should_no_longer_find_the_stream_in_the_set_of_streams_to_be_snapshot()
{
Persistence.GetStreamsToSnapshot(1).Any(x => x.StreamId == _streamId).ShouldBeFalse();
}
}
public class when_adding_a_commit_after_a_snapshot : PersistenceEngineConcern
{
private const int WithinThreshold = 2;
private const int OverThreshold = 3;
private const string SnapshotData = "snapshot";
private ICommit _oldest, _oldest2;
private string _streamId;
protected override void Context()
{
_streamId = Guid.NewGuid().ToString();
_oldest = Persistence.CommitSingle(_streamId);
_oldest2 = Persistence.CommitNext(_oldest);
Persistence.AddSnapshot(new Snapshot(_streamId, _oldest2.StreamRevision, SnapshotData));
}
protected override void Because()
{
Persistence.Commit(_oldest2.BuildNextAttempt());
}
// Because Raven and Mongo update the stream head asynchronously, occasionally will fail this test
[Fact]
public void should_find_the_stream_in_the_set_of_streams_to_be_snapshot_when_within_the_threshold()
{
Persistence.GetStreamsToSnapshot(WithinThreshold).FirstOrDefault(x => x.StreamId == _streamId).ShouldNotBeNull();
}
[Fact]
public void should_not_find_the_stream_in_the_set_of_streams_to_be_snapshot_when_over_the_threshold()
{
Persistence.GetStreamsToSnapshot(OverThreshold).Any(x => x.StreamId == _streamId).ShouldBeFalse();
}
}
public class when_reading_all_commits_from_a_particular_point_in_time : PersistenceEngineConcern
{
private ICommit[] _committed;
private CommitAttempt _first;
private DateTime _now;
private ICommit _second;
private string _streamId;
private ICommit _third;
protected override void Context()
{
_streamId = Guid.NewGuid().ToString();
_now = SystemTime.UtcNow.AddYears(1);
_first = _streamId.BuildAttempt(_now.AddSeconds(1));
Persistence.Commit(_first);
_second = Persistence.CommitNext(_first);
_third = Persistence.CommitNext(_second);
Persistence.CommitNext(_third);
}
protected override void Because()
{
_committed = Persistence.GetFrom(_now).ToArray();
}
[Fact]
public void should_return_all_commits_on_or_after_the_point_in_time_specified()
{
_committed.Length.ShouldBe(4);
}
}
public class when_paging_over_all_commits_from_a_particular_point_in_time : PersistenceEngineConcern
{
private CommitAttempt[] _committed;
private ICommit[] _loaded;
private DateTime _start;
private Guid _streamId;
protected override void Context()
{
_start = SystemTime.UtcNow;
// Due to loss in precision in various storage engines, we're rounding down to the
// nearest second to ensure include all commits from the 'start'.
_start = _start.AddSeconds(-1);
_committed = Persistence.CommitMany(ConfiguredPageSizeForTesting + 2).ToArray();
}
protected override void Because()
{
_loaded = Persistence.GetFrom(_start).ToArray();
}
[Fact]
public void should_load_the_same_number_of_commits_which_have_been_persisted()
{
_loaded.Length.ShouldBe(_committed.Length);
}
[Fact]
public void should_load_the_same_commits_which_have_been_persisted()
{
_committed
.All(commit => _loaded.SingleOrDefault(loaded => loaded.CommitId == commit.CommitId) != null)
.ShouldBeTrue();
}
}
public class when_paging_over_all_commits_from_a_particular_checkpoint : PersistenceEngineConcern
{
private List<Guid> _committed;
private ICollection<Guid> _loaded;
private Guid _streamId;
private const int checkPoint = 2;
protected override void Context()
{
_committed = Persistence.CommitMany(ConfiguredPageSizeForTesting + 1).Select(c => c.CommitId).ToList();
}
protected override void Because()
{
_loaded = Persistence.GetFrom(checkPoint.ToString()).Select(c => c.CommitId).ToList();
}
[Fact]
public void should_load_the_same_number_of_commits_which_have_been_persisted_starting_from_the_checkpoint()
{
_loaded.Count.ShouldBe(_committed.Count - checkPoint);
}
[Fact]
public void should_load_only_the_commits_starting_from_the_checkpoint()
{
_committed.Skip(checkPoint).All(x => _loaded.Contains(x)).ShouldBeTrue(); // all commits should be found in loaded collection
}
}
public class when_paging_over_all_commits_of_a_bucket_from_a_particular_checkpoint : PersistenceEngineConcern
{
private List<Guid> _committedOnBucket1;
private List<Guid> _committedOnBucket2;
private ICollection<Guid> _loaded;
private Guid _streamId;
private const int checkPoint = 2;
protected override void Context()
{
_committedOnBucket1 = Persistence.CommitMany(ConfiguredPageSizeForTesting + 1,null, "b1").Select(c => c.CommitId).ToList();
_committedOnBucket2 = Persistence.CommitMany(ConfiguredPageSizeForTesting + 1, null, "b2").Select(c => c.CommitId).ToList();
_committedOnBucket1.AddRange(Persistence.CommitMany(4, null, "b1").Select(c => c.CommitId));
}
protected override void Because()
{
_loaded = Persistence.GetFrom("b1", checkPoint.ToString()).Select(c => c.CommitId).ToList();
}
[Fact]
public void should_load_the_same_number_of_commits_which_have_been_persisted_starting_from_the_checkpoint()
{
_loaded.Count.ShouldBe(_committedOnBucket1.Count - checkPoint);
}
[Fact]
public void should_load_only_the_commits_on_bucket1_starting_from_the_checkpoint()
{
_committedOnBucket1.Skip(checkPoint).All(x => _loaded.Contains(x)).ShouldBeTrue(); // all commits should be found in loaded collection
}
[Fact]
public void should_not_load_the_commits_from_bucket2()
{
_committedOnBucket2.All(x => !_loaded.Contains(x)).ShouldBeTrue();
}
}
public class when_reading_all_commits_from_the_year_1_AD : PersistenceEngineConcern
{
private Exception _thrown;
protected override void Because()
{
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
_thrown = Catch.Exception(() => Persistence.GetFrom(DateTime.MinValue).FirstOrDefault());
}
[Fact]
public void should_NOT_throw_an_exception()
{
_thrown.ShouldBeNull();
}
}
public class when_purging_all_commits : PersistenceEngineConcern
{
protected override void Context()
{
Persistence.CommitSingle();
}
protected override void Because()
{
Persistence.Purge();
}
[Fact]
public void should_not_find_any_commits_stored()
{
Persistence.GetFrom(DateTime.MinValue).Count().ShouldBe(0);
}
[Fact]
public void should_not_find_any_streams_to_snapshot()
{
Persistence.GetStreamsToSnapshot(0).Count().ShouldBe(0);
}
[Fact]
public void should_not_find_any_undispatched_commits()
{
Persistence.GetUndispatchedCommits().Count().ShouldBe(0);
}
}
public class when_invoking_after_disposal : PersistenceEngineConcern
{
private Exception _thrown;
protected override void Context()
{
Persistence.Dispose();
}
protected override void Because()
{
_thrown = Catch.Exception(() => Persistence.CommitSingle());
}
[Fact]
public void should_throw_an_ObjectDisposedException()
{
_thrown.ShouldBeInstanceOf<ObjectDisposedException>();
}
}
public class when_committing_a_stream_with_the_same_id_as_a_stream_same_bucket : PersistenceEngineConcern
{
private string _streamId;
private static Exception _thrown;
private DateTime _attemptACommitStamp;
protected override void Context()
{
_streamId = Guid.NewGuid().ToString();
Persistence.Commit(_streamId.BuildAttempt());
}
protected override void Because()
{
_thrown = Catch.Exception(() => Persistence.Commit(_streamId.BuildAttempt()));
}
[Fact]
public void should_throw()
{
_thrown.ShouldNotBeNull();
}
[Fact]
public void should_be_duplicate_commit_exception()
{
_thrown.ShouldBeInstanceOf<ConcurrencyException>();
}
}
public class when_committing_a_stream_with_the_same_id_as_a_stream_in_another_bucket : PersistenceEngineConcern
{
const string _bucketAId = "a";
const string _bucketBId = "b";
private string _streamId;
private static CommitAttempt _attemptForBucketB;
private static Exception _thrown;
private DateTime _attemptACommitStamp;
protected override void Context()
{
_streamId = Guid.NewGuid().ToString();
DateTime now = SystemTime.UtcNow;
Persistence.Commit(_streamId.BuildAttempt(now, _bucketAId));
_attemptACommitStamp = Persistence.GetFrom(_bucketAId, _streamId, 0, int.MaxValue).First().CommitStamp;
_attemptForBucketB = _streamId.BuildAttempt(now.Subtract(TimeSpan.FromDays(1)), _bucketBId);
}
protected override void Because()
{
_thrown = Catch.Exception(() => Persistence.Commit(_attemptForBucketB));
}
[Fact]
public void should_succeed()
{
_thrown.ShouldBeNull();
}
[Fact]
public void should_persist_to_the_correct_bucket()
{
ICommit[] stream = Persistence.GetFrom(_bucketBId, _streamId, 0, int.MaxValue).ToArray();
stream.ShouldNotBeNull();
stream.Count().ShouldBe(1);
}
[Fact]
public void should_not_affect_the_stream_from_the_other_bucket()
{
ICommit[] stream = Persistence.GetFrom(_bucketAId, _streamId, 0, int.MaxValue).ToArray();
stream.ShouldNotBeNull();
stream.Count().ShouldBe(1);
stream.First().CommitStamp.ShouldBe(_attemptACommitStamp);
}
}
public class when_saving_a_snapshot_for_a_stream_with_the_same_id_as_a_stream_in_another_bucket : PersistenceEngineConcern
{
const string _bucketAId = "a";
const string _bucketBId = "b";
string _streamId;
private static Snapshot _snapshot;
protected override void Context()
{
_streamId = Guid.NewGuid().ToString();
_snapshot = new Snapshot(_bucketBId, _streamId, 1, "Snapshot");
Persistence.Commit(_streamId.BuildAttempt(bucketId: _bucketAId));
Persistence.Commit(_streamId.BuildAttempt(bucketId: _bucketBId));
}
protected override void Because()
{
Persistence.AddSnapshot(_snapshot);
}
[Fact]
public void should_affect_snapshots_from_another_bucket()
{
Persistence.GetSnapshot(_bucketAId, _streamId, _snapshot.StreamRevision).ShouldBeNull();
}
}
public class when_reading_all_commits_from_a_particular_point_in_time_and_there_are_streams_in_multiple_buckets : PersistenceEngineConcern
{
const string _bucketAId = "a";
const string _bucketBId = "b";
private static DateTime _now;
private static ICommit[] _returnedCommits;
private CommitAttempt _commitToBucketB;
protected override void Context()
{
_now = SystemTime.UtcNow.AddYears(1);
var commitToBucketA = Guid.NewGuid().ToString().BuildAttempt(_now.AddSeconds(1), _bucketAId);
Persistence.Commit(commitToBucketA);
Persistence.Commit(commitToBucketA = commitToBucketA.BuildNextAttempt());
Persistence.Commit(commitToBucketA = commitToBucketA.BuildNextAttempt());
Persistence.Commit(commitToBucketA.BuildNextAttempt());
_commitToBucketB = Guid.NewGuid().ToString().BuildAttempt(_now.AddSeconds(1), _bucketBId);
Persistence.Commit(_commitToBucketB);
}
protected override void Because()
{
_returnedCommits = Persistence.GetFrom(_bucketAId, _now).ToArray();
}
[Fact]
public void should_not_return_commits_from_other_buckets()
{
_returnedCommits.Any(c => c.CommitId.Equals(_commitToBucketB.CommitId)).ShouldBeFalse();
}
}
public class when_getting_all_commits_since_checkpoint_and_there_are_streams_in_multiple_buckets : PersistenceEngineConcern
{
private ICommit[] _commits;
protected override void Context()
{
const string bucketAId = "a";
const string bucketBId = "b";
Persistence.Commit(Guid.NewGuid().ToString().BuildAttempt(bucketId: bucketAId));
Persistence.Commit(Guid.NewGuid().ToString().BuildAttempt(bucketId: bucketBId));
Persistence.Commit(Guid.NewGuid().ToString().BuildAttempt(bucketId: bucketAId));
}
protected override void Because()
{
_commits = Persistence.GetFromStart().ToArray();
}
[Fact]
public void should_not_be_empty()
{
_commits.ShouldNotBeEmpty();
}
[Fact]
public void should_be_in_order_by_checkpoint()
{
ICheckpoint checkpoint = Persistence.GetCheckpoint();
foreach (var commit in _commits)
{
ICheckpoint commitCheckpoint = Persistence.GetCheckpoint(commit.CheckpointToken);
commitCheckpoint.ShouldBeGreaterThan(checkpoint);
checkpoint = Persistence.GetCheckpoint(commit.CheckpointToken);
}
}
}
public class when_purging_all_commits_and_there_are_streams_in_multiple_buckets : PersistenceEngineConcern
{
const string _bucketAId = "a";
const string _bucketBId = "b";
string _streamId;
protected override void Context()
{
_streamId = Guid.NewGuid().ToString();
Persistence.Commit(_streamId.BuildAttempt(bucketId: _bucketAId));
Persistence.Commit(_streamId.BuildAttempt(bucketId: _bucketBId));
}
protected override void Because()
{
Persistence.Purge();
}
[Fact]
public void should_purge_all_commits_stored_in_bucket_a()
{
Persistence.GetFrom(_bucketAId, DateTime.MinValue).Count().ShouldBe(0);
}
[Fact]
public void should_purge_all_commits_stored_in_bucket_b()
{
Persistence.GetFrom(_bucketBId, DateTime.MinValue).Count().ShouldBe(0);
}
[Fact]
public void should_purge_all_streams_to_snapshot_in_bucket_a()
{
Persistence.GetStreamsToSnapshot(_bucketAId, 0).Count().ShouldBe(0);
}
[Fact]
public void should_purge_all_streams_to_snapshot_in_bucket_b()
{
Persistence.GetStreamsToSnapshot(_bucketBId, 0).Count().ShouldBe(0);
}
[Fact]
public void should_purge_all_undispatched_commits()
{
Persistence.GetUndispatchedCommits().Count().ShouldBe(0);
}
}
public class when_gettingfromcheckpoint_amount_of_commits_exceeds_pagesize : PersistenceEngineConcern
{
private ICommit[] _commits;
private int _moreThanPageSize;
protected override void Because()
{
_moreThanPageSize = ConfiguredPageSizeForTesting + 1;
var eventStore = new OptimisticEventStore(Persistence, null);
// TODO: Not sure how to set the actual pagesize to the const defined above
for (int i = 0; i < _moreThanPageSize; i++)
{
using (IEventStream stream = eventStore.OpenStream(Guid.NewGuid()))
{
stream.Add(new EventMessage { Body = i });
stream.CommitChanges(Guid.NewGuid());
}
}
ICommit[] commits = Persistence.GetFrom(DateTime.MinValue).ToArray();
_commits = Persistence.GetFrom().ToArray();
}
[Fact]
public void Should_have_expected_number_of_commits()
{
_commits.Length.ShouldBe(_moreThanPageSize);
}
}
/*public class TransactionConcern : PersistenceEngineConcern
{
private ICommit[] _commits;
private const int Loop = 2;
private const int StreamsPerTransaction = 20;
protected override void Because()
{
Parallel.For(0, Loop, i =>
{
var eventStore = new OptimisticEventStore(Persistence, null);
using (var scope = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions {IsolationLevel = IsolationLevel.Serializable}))
{
int j;
for (j = 0; j < StreamsPerTransaction; j++)
{
using (var stream = eventStore.OpenStream(i.ToString() + "-" + j.ToString()))
{
for (int k = 0; k < 10; k++)
{
stream.Add(new EventMessage {Body = "body" + k});
}
stream.CommitChanges(Guid.NewGuid());
}
}
scope.Complete();
}
});
_commits = Persistence.GetFrom().ToArray();
}
[Fact]
public void Should_have_expected_number_of_commits()
{
_commits.Length.ShouldBe(Loop * StreamsPerTransaction);
}
[Fact]
public void ScopeCompleteAndSerializable()
{
Reinitialize();
const int loop = 10;
using (var scope = new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions
{
IsolationLevel = IsolationLevel.Serializable
}))
{
Parallel.For(0, loop, i =>
{
Console.WriteLine("Creating stream {0} on thread {1}", i, Thread.CurrentThread.ManagedThreadId);
var eventStore = new OptimisticEventStore(Persistence, null);
string streamId = i.ToString(CultureInfo.InvariantCulture);
using (var stream = eventStore.OpenStream(streamId))
{
stream.Add(new EventMessage { Body = "body1" });
stream.Add(new EventMessage { Body = "body2" });
stream.CommitChanges(Guid.NewGuid());
}
});
scope.Complete();
}
ICheckpoint checkpoint = Persistence.GetCheckpoint();
ICommit[] commits = Persistence.GetFrom(checkpoint.Value).ToArray();
commits.Length.ShouldBe(loop);
}
[Fact]
public void ScopeNotCompleteAndReadCommitted()
{
Reinitialize();
const int loop = 10;
using(new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions
{
IsolationLevel = IsolationLevel.ReadCommitted
}))
{
Parallel.For(0, loop, i =>
{
Console.WriteLine(@"Creating stream {0} on thread {1}", i, Thread.CurrentThread.ManagedThreadId);
var eventStore = new OptimisticEventStore(Persistence, null);
string streamId = i.ToString(CultureInfo.InvariantCulture);
using (var stream = eventStore.OpenStream(streamId))
{
stream.Add(new EventMessage { Body = "body1" });
stream.Add(new EventMessage { Body = "body2" });
stream.CommitChanges(Guid.NewGuid());
}
});
}
ICheckpoint checkpoint = Persistence.GetCheckpoint();
ICommit[] commits = Persistence.GetFrom(checkpoint.Value).ToArray();
commits.Length.ShouldBe(0);
}
[Fact]
public void ScopeNotCompleteAndSerializable()
{
Reinitialize();
const int loop = 10;
using(new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions
{
IsolationLevel = IsolationLevel.ReadCommitted
}))
{
Parallel.For(0, loop, i =>
{
Console.WriteLine(@"Creating stream {0} on thread {1}", i, Thread.CurrentThread.ManagedThreadId);
var eventStore = new OptimisticEventStore(Persistence, null);
string streamId = i.ToString(CultureInfo.InvariantCulture);
using (var stream = eventStore.OpenStream(streamId))
{
stream.Add(new EventMessage { Body = "body1" });
stream.Add(new EventMessage { Body = "body2" });
stream.CommitChanges(Guid.NewGuid());
}
});
}
ICheckpoint checkpoint = Persistence.GetCheckpoint();
ICommit[] commits = Persistence.GetFrom(checkpoint.Value).ToArray();
commits.Length.ShouldBe(0);
}
}*/
public class when_a_payload_is_large : PersistenceEngineConcern
{
[Fact]
public void can_commit()
{
const int bodyLength = 100000;
var attempt = new CommitAttempt(
Bucket.Default,
Guid.NewGuid().ToString(),
1,
Guid.NewGuid(),
1,
DateTime.UtcNow,
new Dictionary<string, object>(),
new List<EventMessage> { new EventMessage { Body = new string('a', bodyLength) } });
Persistence.Commit(attempt);
ICommit commits = Persistence.GetFrom().Single();
commits.Events.Single().Body.ToString().Length.ShouldBe(bodyLength);
}
}
public class PersistenceEngineConcern : SpecificationBase, IUseFixture<PersistenceEngineFixture>
{
private PersistenceEngineFixture _fixture;
protected IPersistStreams Persistence
{
get { return _fixture.Persistence; ; }
}
protected int ConfiguredPageSizeForTesting
{
get { return 2; }
}
protected void Reinitialize()
{
_fixture.Initialize(ConfiguredPageSizeForTesting);
}
public void SetFixture(PersistenceEngineFixture data)
{
_fixture = data;
_fixture.Initialize(ConfiguredPageSizeForTesting);
}
}
public partial class PersistenceEngineFixture : IDisposable
{
private readonly Func<int, IPersistStreams> _createPersistence;
private IPersistStreams _persistence;
public void Initialize(int pageSize)
{
if (_persistence != null && !_persistence.IsDisposed)
{
_persistence.Drop();
_persistence.Dispose();
}
_persistence = new PerformanceCounterPersistenceEngine(_createPersistence(pageSize), "tests");
_persistence.Initialize();
}
public IPersistStreams Persistence
{
get { return _persistence; }
}
public void Dispose()
{
if (_persistence != null && !_persistence.IsDisposed)
{
_persistence.Drop();
_persistence.Dispose();
}
}
}
public class when_deleting_a_stream : PersistenceEngineConcern
{
private ICommit _commit;
protected override void Context()
{
_commit = Persistence.CommitSingle(Guid.NewGuid().ToString());
Persistence.AddSnapshot(new Snapshot(_commit.BucketId, _commit.StreamId, _commit.StreamRevision, "SnapshotData"));
}
protected override void Because()
{
Persistence.DeleteStream(_commit.BucketId, _commit.StreamId);
}
[Fact]
public void should_not_find_stream()
{
Persistence.GetFrom(_commit.BucketId, _commit.StreamId, 0, int.MaxValue).Count().ShouldBe(0);
}
[Fact]
public void should_not_find_any_snapshot_to_stream()
{
Persistence.GetSnapshot(_commit.BucketId, _commit.StreamId, _commit.StreamRevision).ShouldBeNull();
}
}
// ReSharper restore InconsistentNaming
}
| |
// $Id$
#region The MIT License
/*
Copyright (c) 2009 denis.kiselyov@gmail.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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using OreEfficiencyCalc.Properties;
using System.Globalization;
namespace OreEfficiencyCalc {
public partial class MainForm : Form {
private apiForm apiSettings = new apiForm();
private AboutForm about = new AboutForm();
private ManualPricesForm manualPrices = new ManualPricesForm();
private List<Celestial> asteroids = new List<Celestial>();
private Character character;
public MainForm() {
InitializeComponent();
_initConstansts();
_restoreSettings();
}
private void _restoreSettings() {
if (int.Parse(Settings.Default.tradeHub) > 0) {
tradeHub.SelectedValue = int.Parse(Settings.Default.tradeHub);
} else {
Settings.Default.tradeHub = tradeHub.SelectedValue.ToString();
}
//if (tradeHub.SelectedItem == null) {
// tradeHub.SelectedValue = (int)TradeHub.JITA;
//}
customFit.Checked = Settings.Default.customFit;
checkBox_CheckedChanged(customFit, EventArgs.Empty);
HarvestType harvestType = (HarvestType)
Enum.Parse(typeof(HarvestType), Settings.Default.harvestType);
Utils.setCheckedRadioButton(harvestingTypeGroupBox, ((int)harvestType).ToString());
Options.isStartup = false;
foreach (Control c in minerFitGroupBox.Controls) {
if (c is ComboBox) {
Utils.setComboValue((ComboBox) c, Settings.Default[c.Name].ToString());
}
}
}
private void _initConstansts() {
//CultureInfo.CreateSpecificCulture("en-US").NumberFormat;
Options.numberProvider = new NumberFormatInfo();
Options.numberProvider.NumberDecimalSeparator = ".";
// trade hubs
Utils.fillComboWithEnum(tradeHub, typeof(TradeHub));
// updates char skills if required
character = new Character(Settings.Default.userId,
Settings.Default.apiKey, Settings.Default.charId);
}
private void _initFitCombos(HarvestType type) {
Utils.fillComboWithDataTable(ship, Items.i.getShips(character));
Utils.fillComboWithDataTable(high, Items.i.getHarvesters(character, type));
Utils.fillComboWithDataTable(low1, Items.i.getUpgrades(character, type));
Utils.fillComboWithDataTable(low2, Items.i.getUpgrades(character, type));
if (type == HarvestType.ICE) { // there's no usable rigs and drones for ice
rig1.Enabled = rig2.Enabled = rig3.Enabled =
drone1.Enabled = drone2.Enabled = drone3.Enabled =
drone4.Enabled = drone5.Enabled = false;
} else {
Utils.fillComboWithDataTable(rig1, Items.i.getRigs(character));
Utils.fillComboWithDataTable(rig2, Items.i.getRigs(character));
Utils.fillComboWithDataTable(rig3, Items.i.getRigs(character));
Utils.fillComboWithDataTable(drone1, Items.i.getDrones(character));
Utils.fillComboWithDataTable(drone2, Items.i.getDrones(character));
Utils.fillComboWithDataTable(drone3, Items.i.getDrones(character));
Utils.fillComboWithDataTable(drone4, Items.i.getDrones(character));
Utils.fillComboWithDataTable(drone5, Items.i.getDrones(character));
}
// slot number for implants is stored in Tag
Utils.fillComboWithDataTable(implant7,
Items.i.getImplants(character, type, implant7.Tag.ToString()));
Utils.fillComboWithDataTable(implant10,
Items.i.getImplants(character, type, implant10.Tag.ToString()));
}
private void queryButton_Click(object sender, EventArgs e) {
resultGridView.Rows.Clear();
// load mineral prices from cached file or eve-central
if (!Settings.Default.manualPrices) {
Cursor.Current = Cursors.WaitCursor;
Prices.retrievePrices(
(TradeHub)int.Parse(Settings.Default.tradeHub), pricesProgressBar);
Cursor.Current = Cursors.Default;
}
try {
if (customFit.Checked) {
character.setVessel((VesselType)Enum.Parse(typeof(VesselType),
((DataRowView)ship.SelectedItem)["name"].ToString()));
character.Vessel.mountHarvesters(Items.i.getHarvester(high.SelectedValue.ToString()));
character.Vessel.mountUpgrade(Items.i.getUpgrade(low1.SelectedValue.ToString()));
character.Vessel.mountUpgrade(Items.i.getUpgrade(low2.SelectedValue.ToString()));
character.Vessel.mountRig(Items.i.getRig(rig1.SelectedValue.ToString()));
character.Vessel.mountRig(Items.i.getRig(rig2.SelectedValue.ToString()));
character.Vessel.mountRig(Items.i.getRig(rig3.SelectedValue.ToString()));
character.Vessel.addDrone(Items.i.getDrone(drone1.SelectedValue.ToString()));
character.Vessel.addDrone(Items.i.getDrone(drone2.SelectedValue.ToString()));
character.Vessel.addDrone(Items.i.getDrone(drone3.SelectedValue.ToString()));
character.Vessel.addDrone(Items.i.getDrone(drone4.SelectedValue.ToString()));
character.Vessel.addDrone(Items.i.getDrone(drone5.SelectedValue.ToString()));
character.Implants.Clear();
character.Implants.Add(Items.i.getImplant(implant7.SelectedValue.ToString()));
character.Implants.Add(Items.i.getImplant(implant10.SelectedValue.ToString()));
} else {
character.setVessel((VesselType)
character.getSkillLevel(SkillTypes.MINING_BARGE) +
character.getSkillLevel(SkillTypes.EXHUMERS));
character.Vessel.setDefaultFit(character);
}
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
// calculating absolute values
foreach (ICelestial ast in asteroids) {
ast.calculateEfficiency(character);
}
asteroids.Sort(Celestial.compareByAbsEff);
double minVal = asteroids[0].AbsoluteEfficiency;
asteroids.Sort(Celestial.compareByAsteroId);
foreach (Celestial ast in asteroids) {
resultGridView.Rows[
resultGridView.Rows.Add(ast.AsteroidType.ToString(),
Math.Round(ast.AbsoluteEfficiency, 2),
Math.Round(ast.AbsoluteEfficiency / minVal, 5))
].DefaultCellStyle.BackColor = ast.SecurityColor;
}
}
private void refreshAsteroids(List<Celestial> asteroids, HarvestType harvType) {
asteroids.Clear();
Array vals = Enum.GetValues(typeof(AsteroidType));
foreach (AsteroidType val in vals) {
switch (harvType) {
case HarvestType.ORE:
if (Utils.isOre(val)) {
asteroids.Add(new Asteroid(val));
} break;
case HarvestType.MERCOXIT:
if (Utils.isMercoxit(val)) {
asteroids.Add(new Mercoxit(val));
} break;
case HarvestType.ICE:
if (Utils.isIce(val)) {
asteroids.Add(new Ice(val));
} break;
case HarvestType.GAS:
break;
default:
throw new Exception("internal error: refreshAsteroids");
}
}
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e) {
about.ShowDialog();
}
// saving parameters to file
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) {
Settings.Default.Save();
}
private void comboBox_SelectedIndexChanged(object sender, EventArgs e) {
if (Options.isStartup) { return; }
ComboBox combo = (ComboBox)sender;
Settings.Default[combo.Name] =
(combo.SelectedValue is DataRowView) ?
((DataRowView)combo.SelectedValue).Row["id"].ToString() :
combo.SelectedValue;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
this.Close();
}
private void aPIToolStripMenuItem_Click(object sender, EventArgs e) {
if (apiSettings.ShowDialog() == DialogResult.OK) {
_initConstansts();
}
}
private void charSkillsCheckBox_CheckedChanged(object sender, EventArgs e) {
harvestingTypeGroupBox.Enabled = minerFitGroupBox.Enabled = !((CheckBox)sender).Checked;
Settings.Default.useCharSkills = ((CheckBox)sender).Checked;
}
private void MainForm_Activated(object sender, EventArgs e) {
queryButton.Enabled =
((Settings.Default.apiKey.Length > 0) &&
(Settings.Default.userId != null) &&
(Settings.Default.charId != null));
}
/// <summary>
/// executes once on start and every radiobutton operation
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radioButton_CheckedChanged(object sender, EventArgs e) {
HarvestType harvType = (HarvestType)int.Parse(((RadioButton)sender).Tag.ToString());
// reinit asteroids
refreshAsteroids(asteroids, harvType);
// actualize fit combos
_initFitCombos((HarvestType)harvestingTypeGroupBox.SelectedValue);
Settings.Default["harvestType"] = harvType.ToString();
}
private void checkBox_CheckedChanged(object sender, EventArgs e) {
CheckBox check = (CheckBox)sender;
Settings.Default[check.Name] = check.Checked;
if (check.Name == "customFit") {
minerFitGroupBox.Enabled = check.Checked;
}
}
private void pricesToolStripMenuItem_Click(object sender, EventArgs e) {
manualPrices.ShowDialog();
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 4:16:32 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
#pragma warning disable 1591
namespace DotSpatial.Projections.GeographicCategories
{
/// <summary>
/// SolarSystem
/// </summary>
public class SolarSystem : CoordinateSystemCategory
{
#region Private Variables
public readonly ProjectionInfo Adrastea2000;
public readonly ProjectionInfo Amalthea2000;
public readonly ProjectionInfo Ananke2000;
public readonly ProjectionInfo Ariel2000;
public readonly ProjectionInfo Atlas2000;
public readonly ProjectionInfo Belinda2000;
public readonly ProjectionInfo Bianca2000;
public readonly ProjectionInfo Callisto2000;
public readonly ProjectionInfo Calypso2000;
public readonly ProjectionInfo Carme2000;
public readonly ProjectionInfo Charon2000;
public readonly ProjectionInfo Cordelia2000;
public readonly ProjectionInfo Cressida2000;
public readonly ProjectionInfo Deimos2000;
public readonly ProjectionInfo Desdemona2000;
public readonly ProjectionInfo Despina2000;
public readonly ProjectionInfo Dione2000;
public readonly ProjectionInfo Elara2000;
public readonly ProjectionInfo Enceladus2000;
public readonly ProjectionInfo Epimetheus2000;
public readonly ProjectionInfo Europa2000;
public readonly ProjectionInfo Galatea2000;
public readonly ProjectionInfo Ganymede2000;
public readonly ProjectionInfo Helene2000;
public readonly ProjectionInfo Himalia2000;
public readonly ProjectionInfo Hyperion2000;
public readonly ProjectionInfo Iapetus2000;
public readonly ProjectionInfo Io2000;
public readonly ProjectionInfo Janus2000;
public readonly ProjectionInfo Juliet2000;
public readonly ProjectionInfo Jupiter2000;
public readonly ProjectionInfo Larissa2000;
public readonly ProjectionInfo Leda2000;
public readonly ProjectionInfo Lysithea2000;
public readonly ProjectionInfo Mars1979;
public readonly ProjectionInfo Mars2000;
public readonly ProjectionInfo Mercury2000;
public readonly ProjectionInfo Metis2000;
public readonly ProjectionInfo Mimas2000;
public readonly ProjectionInfo Miranda2000;
public readonly ProjectionInfo Moon2000;
public readonly ProjectionInfo Naiad2000;
public readonly ProjectionInfo Neptune2000;
public readonly ProjectionInfo Nereid2000;
public readonly ProjectionInfo Oberon2000;
public readonly ProjectionInfo Ophelia2000;
public readonly ProjectionInfo Pan2000;
public readonly ProjectionInfo Pandora2000;
public readonly ProjectionInfo Pasiphae2000;
public readonly ProjectionInfo Phobos2000;
public readonly ProjectionInfo Phoebe2000;
public readonly ProjectionInfo Pluto2000;
public readonly ProjectionInfo Portia2000;
public readonly ProjectionInfo Prometheus2000;
public readonly ProjectionInfo Proteus2000;
public readonly ProjectionInfo Puck2000;
public readonly ProjectionInfo Rhea2000;
public readonly ProjectionInfo Rosalind2000;
public readonly ProjectionInfo Saturn2000;
public readonly ProjectionInfo Sinope2000;
public readonly ProjectionInfo Telesto2000;
public readonly ProjectionInfo Tethys2000;
public readonly ProjectionInfo Thalassa2000;
public readonly ProjectionInfo Thebe2000;
public readonly ProjectionInfo Titan2000;
public readonly ProjectionInfo Titania2000;
public readonly ProjectionInfo Triton2000;
public readonly ProjectionInfo Umbriel2000;
public readonly ProjectionInfo Uranus2000;
public readonly ProjectionInfo Venus1985;
public readonly ProjectionInfo Venus2000;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of SolarSystem
/// </summary>
public SolarSystem()
{
Adrastea2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=8200 +b=8200 +no_defs ");
Amalthea2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=83500 +b=83500 +no_defs ");
Ananke2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=10000 +b=10000 +no_defs ");
Ariel2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=578900 +b=578900 +no_defs ");
Atlas2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=16000 +b=16000 +no_defs ");
Belinda2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=33000 +b=33000 +no_defs ");
Bianca2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=21000 +b=21000 +no_defs ");
Callisto2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=2409300 +b=2409300 +no_defs ");
Calypso2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=9500 +b=9500 +no_defs ");
Carme2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=15000 +b=15000 +no_defs ");
Charon2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=593000 +b=593000 +no_defs ");
Cordelia2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=13000 +b=13000 +no_defs ");
Cressida2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=31000 +b=31000 +no_defs ");
Deimos2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=6200 +b=6200 +no_defs ");
Desdemona2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=27000 +b=27000 +no_defs ");
Despina2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=74000 +b=74000 +no_defs ");
Dione2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=560000 +b=560000 +no_defs ");
Elara2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=40000 +b=40000 +no_defs ");
Enceladus2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=249400 +b=249400 +no_defs ");
Epimetheus2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=59500 +b=59500 +no_defs ");
Europa2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=1562090 +b=1562090 +no_defs ");
Galatea2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=79000 +b=79000 +no_defs ");
Ganymede2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=2632345 +b=2632345 +no_defs ");
Helene2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=17500 +b=700.0000000000046 +no_defs ");
Himalia2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=85000 +b=85000 +no_defs ");
Hyperion2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=133000 +b=133000 +no_defs ");
Iapetus2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=718000 +b=718000 +no_defs ");
Io2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=1821460 +b=1821460 +no_defs ");
Janus2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=888000 +b=888000 +no_defs ");
Juliet2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=42000 +b=42000 +no_defs ");
Jupiter2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=71492000 +b=66853999.99999999 +no_defs ");
Larissa2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=104000 +b=89000 +no_defs ");
Leda2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=5000 +b=5000 +no_defs ");
Lysithea2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=12000 +b=12000 +no_defs ");
Mars1979 = ProjectionInfo.FromProj4String("+proj=longlat +a=3393400 +b=3375730 +no_defs ");
Mars2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=3396190 +b=3376200 +no_defs ");
Mercury2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=2439700 +b=2439700 +no_defs ");
Metis2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=30000 +b=20000 +no_defs ");
Mimas2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=1986300 +b=1986300 +no_defs ");
Miranda2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=235800 +b=235800 +no_defs ");
Moon2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=1737400 +b=1737400 +no_defs ");
Naiad2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=29000 +b=29000 +no_defs ");
Neptune2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=24764000 +b=24341000 +no_defs ");
Nereid2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=170000 +b=170000 +no_defs ");
Oberon2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=761400 +b=761400 +no_defs ");
Ophelia2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=15000 +b=15000 +no_defs ");
Pan2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=10000 +b=10000 +no_defs ");
Pandora2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=41900 +b=41900 +no_defs ");
Pasiphae2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=18000 +b=18000 +no_defs ");
Phobos2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=11100 +b=11100 +no_defs ");
Phoebe2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=110000 +b=110000 +no_defs ");
Pluto2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=1195000 +b=1195000 +no_defs ");
Portia2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=54000 +b=54000 +no_defs ");
Prometheus2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=50100 +b=50100 +no_defs ");
Proteus2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=208000 +b=208000 +no_defs ");
Puck2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=77000 +b=77000 +no_defs ");
Rhea2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=764000 +b=764000 +no_defs ");
Rosalind2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=27000 +b=27000 +no_defs ");
Saturn2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=60268000 +b=54364000 +no_defs ");
Sinope2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=14000 +b=14000 +no_defs ");
Telesto2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=11000 +b=11000 +no_defs ");
Tethys2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=529800 +b=529800 +no_defs ");
Thalassa2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=40000 +b=40000 +no_defs ");
Thebe2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=49300 +b=49300 +no_defs ");
Titan2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=2575000 +b=2575000 +no_defs ");
Titania2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=788900 +b=788900 +no_defs ");
Triton2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=1352600 +b=1352600 +no_defs ");
Umbriel2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=584700 +b=584700 +no_defs ");
Uranus2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=25559000 +b=24973000 +no_defs ");
Venus1985 = ProjectionInfo.FromProj4String("+proj=longlat +a=6051000 +b=6051000 +no_defs ");
Venus2000 = ProjectionInfo.FromProj4String("+proj=longlat +a=6051800 +b=6051800 +no_defs ");
Adrastea2000.GeographicInfo.Name = "GCS_Adrastea_2000";
Amalthea2000.GeographicInfo.Name = "GCS_Amalthea_2000";
Ananke2000.GeographicInfo.Name = "GCS_Ananke_2000";
Ariel2000.GeographicInfo.Name = "GCS_Ariel_2000";
Atlas2000.GeographicInfo.Name = "GCS_Atlas_2000";
Belinda2000.GeographicInfo.Name = "GCS_Belinda_2000";
Bianca2000.GeographicInfo.Name = "GCS_Bianca_2000";
Callisto2000.GeographicInfo.Name = "GCS_Callisto_2000";
Calypso2000.GeographicInfo.Name = "GCS_Calypso_2000";
Carme2000.GeographicInfo.Name = "GCS_Carme_2000";
Charon2000.GeographicInfo.Name = "GCS_Charon_2000";
Cordelia2000.GeographicInfo.Name = "GCS_Cordelia_2000";
Cressida2000.GeographicInfo.Name = "GCS_Cressida_2000";
Deimos2000.GeographicInfo.Name = "GCS_Deimos_2000";
Desdemona2000.GeographicInfo.Name = "GCS_Desdemona_2000";
Despina2000.GeographicInfo.Name = "GCS_Despina_2000";
Dione2000.GeographicInfo.Name = "GCS_Dione_2000";
Elara2000.GeographicInfo.Name = "GCS_Elara_2000";
Enceladus2000.GeographicInfo.Name = "GCS_Enceladus_2000";
Epimetheus2000.GeographicInfo.Name = "GCS_Epimetheus_2000";
Europa2000.GeographicInfo.Name = "GCS_Europa_2000";
Galatea2000.GeographicInfo.Name = "GCS_Galatea_2000";
Ganymede2000.GeographicInfo.Name = "GCS_Ganymede_2000";
Helene2000.GeographicInfo.Name = "GCS_Helene_2000";
Himalia2000.GeographicInfo.Name = "GCS_Himalia_2000";
Hyperion2000.GeographicInfo.Name = "GCS_Hyperion_2000";
Iapetus2000.GeographicInfo.Name = "GCS_Iapetus_2000";
Io2000.GeographicInfo.Name = "GCS_Io_2000";
Janus2000.GeographicInfo.Name = "GCS_Janus_2000";
Juliet2000.GeographicInfo.Name = "GCS_Juliet_2000";
Jupiter2000.GeographicInfo.Name = "GCS_Jupiter_2000";
Larissa2000.GeographicInfo.Name = "GCS_Larissa_2000";
Leda2000.GeographicInfo.Name = "GCS_Leda_2000";
Lysithea2000.GeographicInfo.Name = "GCS_Lysithea_2000";
Mars1979.GeographicInfo.Name = "GCS_Mars_1979";
Mars2000.GeographicInfo.Name = "GCS_Mars_2000";
Mercury2000.GeographicInfo.Name = "GCS_Mercury_2000";
Metis2000.GeographicInfo.Name = "GCS_Metis_2000";
Mimas2000.GeographicInfo.Name = "GCS_Mimas_2000";
Miranda2000.GeographicInfo.Name = "GCS_Miranda_2000";
Moon2000.GeographicInfo.Name = "GCS_Moon_2000";
Naiad2000.GeographicInfo.Name = "GCS_Naiad_2000";
Neptune2000.GeographicInfo.Name = "GCS_Neptune_2000";
Nereid2000.GeographicInfo.Name = "GCS_Nereid_2000";
Oberon2000.GeographicInfo.Name = "GCS_Oberon_2000";
Ophelia2000.GeographicInfo.Name = "GCS_Ophelia_2000";
Pan2000.GeographicInfo.Name = "GCS_Pan_2000";
Pandora2000.GeographicInfo.Name = "GCS_Pandora_2000";
Pasiphae2000.GeographicInfo.Name = "GCS_Pasiphae_2000";
Phobos2000.GeographicInfo.Name = "GCS_Phobos_2000";
Phoebe2000.GeographicInfo.Name = "GCS_Phoebe_2000";
Pluto2000.GeographicInfo.Name = "GCS_Pluto_2000";
Portia2000.GeographicInfo.Name = "GCS_Portia_2000";
Prometheus2000.GeographicInfo.Name = "GCS_Prometheus_2000";
Proteus2000.GeographicInfo.Name = "GCS_Proteus_2000";
Puck2000.GeographicInfo.Name = "GCS_Puck_2000";
Rhea2000.GeographicInfo.Name = "GCS_Rhea_2000";
Rosalind2000.GeographicInfo.Name = "GCS_Rosalind_2000";
Saturn2000.GeographicInfo.Name = "GCS_Saturn_2000";
Sinope2000.GeographicInfo.Name = "GCS_Sinope_2000";
Telesto2000.GeographicInfo.Name = "GCS_Telesto_2000";
Tethys2000.GeographicInfo.Name = "GCS_Tethys_2000";
Thalassa2000.GeographicInfo.Name = "GCS_Thalassa_2000";
Thebe2000.GeographicInfo.Name = "GCS_Thebe_2000";
Titan2000.GeographicInfo.Name = "GCS_Titan_2000";
Titania2000.GeographicInfo.Name = "GCS_Titania_2000";
Triton2000.GeographicInfo.Name = "GCS_Triton_2000";
Umbriel2000.GeographicInfo.Name = "GCS_Umbriel_2000";
Uranus2000.GeographicInfo.Name = "GCS_Uranus_2000";
Venus1985.GeographicInfo.Name = "GCS_Venus_1985";
Venus2000.GeographicInfo.Name = "GCS_Venus_2000";
Adrastea2000.GeographicInfo.Datum.Name = "D_Adrastea_2000";
Amalthea2000.GeographicInfo.Datum.Name = "D_Amalthea_2000";
Ananke2000.GeographicInfo.Datum.Name = "D_Ananke_2000";
Ariel2000.GeographicInfo.Datum.Name = "D_Ariel_2000";
Atlas2000.GeographicInfo.Datum.Name = "D_Atlas_2000";
Belinda2000.GeographicInfo.Datum.Name = "D_Belinda_2000";
Bianca2000.GeographicInfo.Datum.Name = "D_Bianca_2000";
Callisto2000.GeographicInfo.Datum.Name = "D_Callisto_2000";
Calypso2000.GeographicInfo.Datum.Name = "D_Calypso_2000";
Carme2000.GeographicInfo.Datum.Name = "D_Carme_2000";
Charon2000.GeographicInfo.Datum.Name = "D_Charon_2000";
Cordelia2000.GeographicInfo.Datum.Name = "D_Cordelia_2000";
Cressida2000.GeographicInfo.Datum.Name = "D_Cressida_2000";
Deimos2000.GeographicInfo.Datum.Name = "D_Deimos_2000";
Desdemona2000.GeographicInfo.Datum.Name = "D_Desdemona_2000";
Despina2000.GeographicInfo.Datum.Name = "D_Despina_2000";
Dione2000.GeographicInfo.Datum.Name = "D_Dione_2000";
Elara2000.GeographicInfo.Datum.Name = "D_Elara_2000";
Enceladus2000.GeographicInfo.Datum.Name = "D_Enceladus_2000";
Epimetheus2000.GeographicInfo.Datum.Name = "D_Epimetheus_2000";
Europa2000.GeographicInfo.Datum.Name = "D_Europa_2000";
Galatea2000.GeographicInfo.Datum.Name = "D_Galatea_2000";
Ganymede2000.GeographicInfo.Datum.Name = "D_Ganymede_2000";
Helene2000.GeographicInfo.Datum.Name = "D_Helene_2000";
Himalia2000.GeographicInfo.Datum.Name = "D_Himalia_2000";
Hyperion2000.GeographicInfo.Datum.Name = "D_Hyperion_2000";
Iapetus2000.GeographicInfo.Datum.Name = "D_Iapetus_2000";
Io2000.GeographicInfo.Datum.Name = "D_Io_2000";
Janus2000.GeographicInfo.Datum.Name = "D_Janus_2000";
Juliet2000.GeographicInfo.Datum.Name = "D_Juliet_2000";
Jupiter2000.GeographicInfo.Datum.Name = "D_Jupiter_2000";
Larissa2000.GeographicInfo.Datum.Name = "D_Larissa_2000";
Leda2000.GeographicInfo.Datum.Name = "D_Leda_2000";
Lysithea2000.GeographicInfo.Datum.Name = "D_Lysithea_2000";
Mars1979.GeographicInfo.Datum.Name = "D_Mars_1979";
Mars2000.GeographicInfo.Datum.Name = "D_Mars_2000";
Mercury2000.GeographicInfo.Datum.Name = "D_Mercury_2000";
Metis2000.GeographicInfo.Datum.Name = "D_Metis_2000";
Mimas2000.GeographicInfo.Datum.Name = "D_Mimas_2000";
Miranda2000.GeographicInfo.Datum.Name = "D_Miranda_2000";
Moon2000.GeographicInfo.Datum.Name = "D_Moon_2000";
Naiad2000.GeographicInfo.Datum.Name = "D_Naiad_2000";
Neptune2000.GeographicInfo.Datum.Name = "D_Neptune_2000";
Nereid2000.GeographicInfo.Datum.Name = "D_Nereid_2000";
Oberon2000.GeographicInfo.Datum.Name = "D_Oberon_2000";
Ophelia2000.GeographicInfo.Datum.Name = "D_Ophelia_2000";
Pan2000.GeographicInfo.Datum.Name = "D_Pan_2000";
Pandora2000.GeographicInfo.Datum.Name = "D_Pandora_2000";
Pasiphae2000.GeographicInfo.Datum.Name = "D_Pasiphae_2000";
Phobos2000.GeographicInfo.Datum.Name = "D_Phobos_2000";
Phoebe2000.GeographicInfo.Datum.Name = "D_Phoebe_2000";
Pluto2000.GeographicInfo.Datum.Name = "D_Pluto_2000";
Portia2000.GeographicInfo.Datum.Name = "D_Portia_2000";
Prometheus2000.GeographicInfo.Datum.Name = "D_Prometheus_2000";
Proteus2000.GeographicInfo.Datum.Name = "D_Proteus_2000";
Puck2000.GeographicInfo.Datum.Name = "D_Puck_2000";
Rhea2000.GeographicInfo.Datum.Name = "D_Rhea_2000";
Rosalind2000.GeographicInfo.Datum.Name = "D_Rosalind_2000";
Saturn2000.GeographicInfo.Datum.Name = "D_Saturn_2000";
Sinope2000.GeographicInfo.Datum.Name = "D_Sinope_2000";
Telesto2000.GeographicInfo.Datum.Name = "D_Telesto_2000";
Tethys2000.GeographicInfo.Datum.Name = "D_Tethys_2000";
Thalassa2000.GeographicInfo.Datum.Name = "D_Thalassa_2000";
Thebe2000.GeographicInfo.Datum.Name = "D_Thebe_2000";
Titan2000.GeographicInfo.Datum.Name = "D_Titan_2000";
Titania2000.GeographicInfo.Datum.Name = "D_Titania_2000";
Triton2000.GeographicInfo.Datum.Name = "D_Triton_2000";
Umbriel2000.GeographicInfo.Datum.Name = "D_Umbriel_2000";
Uranus2000.GeographicInfo.Datum.Name = "D_Uranus_2000";
Venus1985.GeographicInfo.Datum.Name = "D_Venus_1985";
Venus2000.GeographicInfo.Datum.Name = "D_Venus_2000";
}
#endregion
}
}
#pragma warning restore 1591
| |
using System;
using System.Text;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using Hexpoint.Blox.Hosts.World;
using Hexpoint.Blox.GameObjects.Units;
using Hexpoint.Blox.GameActions;
namespace AiKnowledgeEngine
{
public class PathFinder
{
#region Cell scores
class LocationScore
{
public int fScore;
public int gScore;
public bool closedSet;
public Position cameFrom;
}
private int GetFScore (Position loc)
{
if (!scores.ContainsKey (loc))
{
return 0;
}
return scores [loc].fScore;
}
private void SetFScore (Position loc, int score)
{
if (scores.ContainsKey (loc))
{
scores [loc].fScore = score;
}
else
{
scores.Add (loc, new LocationScore () { fScore = score });
}
}
private int GetGScore (Position loc)
{
if (!scores.ContainsKey (loc))
{
return 0;
}
return scores [loc].gScore;
}
private void SetGScore (Position loc, int score)
{
if (scores.ContainsKey (loc))
{
scores [loc].gScore = score;
}
else
{
scores.Add (loc, new LocationScore () { gScore = score });
}
}
private void SetCameFrom (Position loc, Position cameFrom)
{
if (scores.ContainsKey (loc))
{
scores [loc].cameFrom = cameFrom;
}
else
{
scores.Add (loc, new LocationScore () { cameFrom = cameFrom });
}
}
private void AddToClosedSet (Position loc)
{
if (scores.ContainsKey (loc))
{
scores [loc].closedSet = true;
}
else
{
scores.Add (loc, new LocationScore () { closedSet = true });
}
}
private bool IsClosedSet (Position loc)
{
if (!scores.ContainsKey (loc))
{
return false;
}
return scores [loc].closedSet;
}
private Position GetCameFrom (Position loc)
{
if (!scores.ContainsKey (loc))
{
throw new ApplicationException ("Don't know where came from");
}
return scores [loc].cameFrom;
}
private Position GetMinFScore (List<Position> locations)
{
int min = int.MaxValue;
Position minPoint = new Position (0, 0, 0);
foreach (Position i in locations)
{
//Console.WriteLine("{0} = {1}, {2}", i, GetGScore(i), GetFScore(i));
int fscore = GetFScore (i);
if (fscore < min)
{
min = fscore;
minPoint = i;
}
}
return minPoint;
}
#endregion
private int ScrMaxX = 0;
private int ScrMaxY = 0;
private int ScrGridSizeX = 0;
private int ScrGridSizeY = 0;
private Map map;
private Character character;
private int fScore;
private Dictionary<Position, LocationScore> scores;
private int gScore;
private bool openSet;
private int characterCount;
private List<Position> openset;
public PathFinder (Map map)
{
this.map = map;
fScore = 0;
gScore = 0;
scores = new Dictionary<Position, LocationScore> ();
openset = new List<Position> ();
}
private int HeuristicCostEstimate (Position a, Position b)
{
Position diff = a - b;
diff = diff * diff;
double xz = Math.Sqrt(diff.X + diff.Z);
double xzy = Math.Sqrt (xz*xz + diff.Y);
return (int)(xzy * 12);
}
private int DistBetween(Position a, Position b)
{
Position diff = a - b;
diff = diff * diff;
double xz = Math.Sqrt(diff.X + diff.Z);
double xzy = Math.Sqrt (xz*xz + diff.Y);
return (int)(xzy * 10);
}
public List<Position> FindPath (Position start, Position goal)
{
List<Position> route = new List<Position> ();
int maxSearch = 100;
int searched = 0;
Position current = start;
route.Add (goal);
scores.Clear ();
openset.Clear ();
openset.Add (start);
SetGScore (start, 0); // Cost from start along best known path.
SetFScore (start, GetGScore (start) + HeuristicCostEstimate (start, goal));
while (openset.Count != 0 && searched++ < maxSearch) {
current = GetMinFScore (openset);
openset.Remove (current);
AddToClosedSet (current);
if (CloseEnough(current, goal))
{
break;
}
List<Position> neighbours = NeighbourNodes (current);
foreach (Position neighbour in neighbours) {
if (IsClosedSet (neighbour))
continue;
int tentativeGScore = GetGScore (current) + DistBetween (current, neighbour);
if (!openset.Contains (neighbour) || tentativeGScore < GetGScore (neighbour)) {
SetCameFrom (neighbour, current);
SetGScore (neighbour, tentativeGScore);
SetFScore (neighbour, tentativeGScore + HeuristicCostEstimate (neighbour, goal));
if (!openset.Contains (neighbour)) {
openset.Add (neighbour);
}
}
}
}
if (searched >= maxSearch)
{
//Console.WriteLine ("Could not find path from {0} to {1}", start, goal);
return null;
}
else
//if (GetFScore (goal) > 0) // Found path
//if (DistBetween(current, goal) < WithinRangeScore)
{
Console.WriteLine ("Found route from {0} to {1} after checking {2} locations", start, goal, searched);
//Position current = goal;
while (current != start)
{
route.Add (current);
current = GetCameFrom (current);
}
}
return route;
}
public List<Position> FindPaths (Position start, Knowledge knowledge, Block.BlockType stopAtType = Block.BlockType.Air, int maxSearch = 100)
{
int searched = 0;
Position current = start;
scores.Clear ();
openset.Clear ();
openset.Add (start);
SetGScore (start, 0); // Cost from start along best known path.
SetFScore (start, GetGScore (start));
while (openset.Count != 0 && searched++ < maxSearch) {
current = GetMinFScore (openset);
openset.Remove (current);
AddToClosedSet (current);
foreach (Position neighbour in NeighbourBlocks(current))
{
if (neighbour.GetBlock().Type == stopAtType)
{
Console.WriteLine ("Found route from {0} to {1} after checking {2} locations", start, current, searched);
List<Position> route = new List<Position>();
while (current != start)
{
route.Add (current);
current = GetCameFrom (current);
}
return route;
}
knowledge.Add(neighbour, start, GetGScore(current));
}
List<Position> neighbours = NeighbourNodes (current);
foreach (Position neighbour in neighbours) {
if (IsClosedSet (neighbour))
continue;
int tentativeGScore = GetGScore (current) + DistBetween (current, neighbour);
if (!openset.Contains (neighbour) || tentativeGScore < GetGScore (neighbour)) {
SetCameFrom (neighbour, current);
SetGScore (neighbour, tentativeGScore);
SetFScore (neighbour, tentativeGScore + HeuristicCostEstimate (start, neighbour));
if (!openset.Contains (neighbour)) {
openset.Add (neighbour);
}
}
}
}
return null;
}
public List<Position> FindPath (Position start, Position destination, Knowledge knowledge, int maxSearch = 100)
{
int searched = 0;
Position current = start;
scores.Clear ();
openset.Clear ();
openset.Add (start);
SetGScore (start, 0); // Cost from start along best known path.
SetFScore (start, GetGScore (start));
while (openset.Count != 0 && searched++ < maxSearch) {
current = GetMinFScore (openset);
openset.Remove (current);
AddToClosedSet (current);
if (current == destination)
{
Console.WriteLine ("Found route from {0} to {1} after checking {2} locations", start, current, searched);
List<Position> route = new List<Position>();
while (current != start)
{
route.Add (current);
current = GetCameFrom (current);
}
return route;
}
List<Position> neighbours = NeighbourNodes (current);
foreach (Position neighbour in neighbours) {
if (IsClosedSet (neighbour))
continue;
int tentativeGScore = GetGScore (current) + DistBetween (current, neighbour);
if (!openset.Contains (neighbour) || tentativeGScore < GetGScore (neighbour)) {
SetCameFrom (neighbour, current);
SetGScore (neighbour, tentativeGScore);
SetFScore (neighbour, tentativeGScore + HeuristicCostEstimate (start, destination));
if (!openset.Contains (neighbour)) {
openset.Add (neighbour);
}
}
}
}
return null;
}
private bool CloseEnough (Position position, Position target)
{
Position diff = (position - target).Abs();
return (diff.X <= 1 && diff.Z <= 1 && diff.Y<=3);
}
public IEnumerable<Position> FindNearestBlock(Position start, Block.BlockType target)
{
foreach (Position check in ListBlocksByRange(start))
{
if (check.GetBlock().Type == target)
yield return check;
}
}
//IEnumerable<Position>
public IEnumerable<Position> ListVisibleBlocks (Coords location, int depth)
{
//int depth = 100;
int fieldOfView = depth / 2;
Coords focus = location;
focus.Xf += (float)(Math.Cos (location.Direction) * depth);
focus.Zf += (float)(Math.Sin (location.Direction) * depth);
Position tl = new Position(-fieldOfView, 0, fieldOfView);
Position tr = new Position(fieldOfView, 0, fieldOfView);
Position bl = new Position(-fieldOfView, 0, -fieldOfView);
Position br = new Position(fieldOfView, 0, -fieldOfView);
return ListVisibleBlocksRecurse (location, focus, tl, tr, bl, br);
}
public IEnumerable<Position> ListVisibleBlocksRecurse (Coords location, Coords focus,
Position tl, Position tr, Position bl, Position br)
{
Coords tlc, trc, blc, brc;
tlc = GetCoords (focus, tl.X, tl.Z, location.Direction);
trc = GetCoords (focus, tr.X, tr.Z, location.Direction);
blc = GetCoords (focus, bl.X, bl.Z, location.Direction);
brc = GetCoords (focus, br.X, br.Z, location.Direction);
//return ListVisibleBlocksRecursive(location, tl, tr, bl, br);
Position tlb = FindIntersectingBlock(location, tlc);
Position trb = FindIntersectingBlock(location, trc);
Position blb = FindIntersectingBlock(location, blc);
Position brb = FindIntersectingBlock(location, brc);
/*
if (tlb != trb || blb != brb || trb != brb || tlb != blb)
{
Position lc = new Position(tl.X, 0, (tr.Z + bl.Z) / 2);
Position rc = new Position(tr.X, 0, (tr.Z + bl.Z) / 2);
Position tc = new Position((tl.X + tr.X) / 2, 0, tr.Z);
Position bc = new Position((tl.X + tr.X) / 2, 0, br.Z);
Position cc = new Position((tl.X + tr.X) / 2, 0, (tr.Z + bl.Z) / 2);
foreach (Position pos in ListVisibleBlocksRecurse (location, focus, tl, tc, rc, cc))
yield return pos;
foreach (Position pos in ListVisibleBlocksRecurse (location, focus, tc, tr, cc, rc))
yield return pos;
foreach (Position pos in ListVisibleBlocksRecurse (location, focus, lc, cc, bl, bc))
yield return pos;
foreach (Position pos in ListVisibleBlocksRecurse (location, focus, cc, rc, bc, br))
yield return pos;
}
else*/
yield return tlb;
//yield return trb;
//yield return blb;
//yield return brb;
}
private Coords GetCoords(Coords focus, int x, int y, float direction)
{
Coords pt = focus;
pt.Xf -= (float)(Math.Sin(direction) * x);
pt.Zf += (float)(Math.Cos(direction) * x);
pt.Yf += y;
return pt;
}
private IEnumerable<Position> ListVisibleBlocksRecursive(Coords start, Coords tl, Coords tr, Coords bl, Coords br)
{
Position tlb = FindIntersectingBlock(start, tl);
Position trb = FindIntersectingBlock(start, tr);
Position blb = FindIntersectingBlock(start, bl);
Position brb = FindIntersectingBlock(start, br);
yield return tlb;
yield return trb;
yield return blb;
yield return brb;
//float w = fieldOfView;
//
//for(int w = -fieldOfView; w < fieldOfView; w++)
//{
//
// Position block = FindIntersectingBlock(location, focus);
/*
Coords pt2 = pt;
pt2.Yf -= fieldOfView;
for (int h = -fieldOfView; h < fieldOfView; h++)
{
foreach (Position pt3 in GraphicsAlgorithms.FindIntersectingBlocks(location.ToPosition(), pt2.ToPosition()))
{
if (!pt3.IsValidBlockLocation)
{
break;
}
if (pt3.GetBlock().IsSolid)
{
NetworkClient.SendAddOrRemoveBlock(pt3, Block.BlockType.Crate);
break;
}
}
pt2.Yf += 1;
// NetworkClient.SendAddOrRemoveBlock(pt.ToPosition(), block.Type);
}
*/
//}
}
private Position FindIntersectingBlock(Coords start, Coords end)
{
foreach (Position pt in GraphicsAlgorithms.FindIntersectingBlocks(start.ToPosition(), end.ToPosition()))
{
if (!pt.IsValidBlockLocation)
{
return end.ToPosition();
}
if (pt.GetBlock().IsSolid)
{
return pt;
}
}
return end.ToPosition();
}
public IEnumerable<Position> ListBlocksByRange(Position start) // TODO - change to visible blocks
{
Position check;
int x,y,z;
int MaxSearchSize = 20;
for(int i=1; i<MaxSearchSize; i++)
{
x = i;
for(y = -i; y<=i; y++)
for(z = -i; z<=i; z++)
{
check = start + new Position(x,y,z);
yield return check;
}
x = -i;
for(y = -i; y<=i; y++)
for(z = -i; z<=i; z++)
{
check = start + new Position(x,y,z);
yield return check;
}
y = i;
for(x = -i; x<=i; x++)
for(z = -i; z<=i; z++)
{
check = start + new Position(x,y,z);
yield return check;
}
y = -i;
for(x = -i; x<=i; x++)
for(z = -i; z<=i; z++)
{
check = start + new Position(x,y,z);
yield return check;
}
z = i;
for(x = -i; x<=i; x++)
for(y = -i; y<=i; y++)
{
check = start + new Position(x,y,z);
yield return check;
}
z = -i;
for(x = -i; x<=i; x++)
for(y = -i; y<=i; y++)
{
check = start + new Position(x,y,z);
yield return check;
}
}
}
public List<Position> FindPathToNearestBlock(Position start, Block.BlockType target)
{
foreach(Position pos in FindNearestBlock(start, target))
{
//Console.WriteLine ("Block at {0}", pos);
List<Position> route = FindPath (start, pos);
if (route != null)
return route;
}
return null;
}
private bool NextToTarget(Position loc, Block.BlockType target)
{
return
((loc + new Position (-1, 0, -1)).GetBlock().Type == target)
|| ((loc + new Position (-1, 0, 0)).GetBlock().Type == target)
|| ((loc + new Position (-1, 0, 1)).GetBlock().Type == target)
|| ((loc + new Position (0, 0, 1)).GetBlock().Type == target)
|| ((loc + new Position (1, 0, 1)).GetBlock().Type == target)
|| ((loc + new Position (1, 0, 0)).GetBlock().Type == target)
|| ((loc + new Position (1, 0, -1)).GetBlock().Type == target)
|| ((loc + new Position (0, 0, -1)).GetBlock().Type == target);
}
/*
public List<Position> FindPath (Position start, Position end)
{
List<Position> route = new List<Position> ();
route.Add (start);
if (start.GetBlock().IsSolid)
{
return route;
}
scores.Clear ();
SetFScore (start, 0);
openset.Clear ();
openset.Add (start);
Position current = start;
while (openset.Count != 0)
{
current = GetMinFScore (openset);
openset.Remove (current);
AddToClosedSet (current);
if (match (current))
{
break;
}
List<Position> neighbours = NeighbourNodes (current, true, true);
foreach (Position neighbour in neighbours)
{
if (IsClosedSet (neighbour))
continue;
Position temp = neighbour;
int tentativeGScore = GetFScore (current) + current.GetDistanceRough (ref temp);
if (!openset.Contains (neighbour) || tentativeGScore < GetGScore (neighbour))
{
SetFScore (neighbour, tentativeGScore);
SetCameFrom (neighbour, current);
if (!openset.Contains (neighbour))
{
openset.Add (neighbour);
}
}
}
}
if (match (current)) // Found path
{
while (current != start)
{
route.Add (current);
current = GetCameFrom (current);
}
}
return route;
}*/
private Position FindMinNeighbour (Position current)
{
//Location cameFrom = GetCameFrom(current);
//if (!map.GetLocation(cameFrom)->hasCharacter())
//{
// return cameFrom; // Shortcut. Assume this is min
//}
openset = NeighbourNodes (current, false);
return GetMinFScore (openset);
}
public IEnumerable<Position> NeighbourBlocks (Position pt)
{
foreach (Position pos in ListNeighbourBlocks (pt))
yield return pos;
foreach (Position pos in ListNeighbourBlocks (pt + new Position (-1, 0, 0)))
yield return pos;
foreach (Position pos in ListNeighbourBlocks (pt + new Position (0, 0, 1)))
yield return pos;
foreach (Position pos in ListNeighbourBlocks (pt + new Position (1, 0, 0)))
yield return pos;
foreach (Position pos in ListNeighbourBlocks (pt + new Position (0, 0, -1)))
yield return pos;
}
private IEnumerable<Position> ListNeighbourBlocks (Position pos)
{
Position up1 = pos + new Position (0, 1, 0);
Position up2 = pos + new Position (0, 2, 0);
Position up3 = pos + new Position (0, 3, 0);
Position dn1 = pos + new Position (0, -1, 0);
Position dn2 = pos + new Position (0, -2, 0);
Position dn3 = pos + new Position(0,-3,0);
if (up3.GetBlock ().IsSolid)
yield return up3;
if (up2.GetBlock ().IsSolid)
yield return up2;
if (up1.GetBlock ().IsSolid)
yield return up1;
if (pos.GetBlock ().IsSolid)
{
yield return pos;
yield break;
}
if (dn1.GetBlock().IsSolid)
{
yield return dn1;
yield break;
}
if (dn2.GetBlock().IsSolid)
{
yield return dn2;
yield break;
}
if (dn3.GetBlock().IsSolid)
{
yield return dn3;
yield break;
}
}
private List<Position> NeighbourNodes (Position pt, bool inclMovable = true, bool inclUnknown = false)
{
List<Position> neighbours = new List<Position> ();
AddNeighbour (neighbours, pt, true, true); // always include current
//AddNeighbour (neighbours, pt + new Position (-1, 0, -1), inclMovable, inclUnknown);
AddNeighbour (neighbours, pt + new Position (-1, 0, 0), inclMovable, inclUnknown);
//AddNeighbour (neighbours, pt + new Position (-1, 0, 1), inclMovable, inclUnknown);
AddNeighbour (neighbours, pt + new Position (0, 0, 1), inclMovable, inclUnknown);
//AddNeighbour (neighbours, pt + new Position (1, 0, 1), inclMovable, inclUnknown);
AddNeighbour (neighbours, pt + new Position (1, 0, 0), inclMovable, inclUnknown);
//AddNeighbour (neighbours, pt + new Position (1, 0, -1), inclMovable, inclUnknown);
AddNeighbour (neighbours, pt + new Position (0, 0, -1), inclMovable, inclUnknown);
return neighbours;
}
private void AddNeighbour (List<Position> neighbours, Position pos, bool inclMovable, bool inclUnknown)
{
Position up1 = pos + new Position(0,1,0);
Position up2 = pos + new Position(0,2,0);
//Position up3 = pos + new Position(0,3,0);
Position dn1 = pos + new Position(0,-1,0);
Position dn2 = pos + new Position(0,-2,0);
//Position dn3 = pos + new Position(0,-3,0);
if (dn1.GetBlock().IsSolid && pos.GetBlock().IsTransparent && up1.GetBlock().IsTransparent)
{
// Walk straight
neighbours.Add(pos);
return;
}
if (pos.GetBlock().IsSolid && up1.GetBlock().IsTransparent && up2.GetBlock().IsTransparent)
{
// Jump up one
neighbours.Add(up1);
return;
}
if (dn2.GetBlock().IsSolid && dn1.GetBlock().IsTransparent && pos.GetBlock().IsTransparent)
{
// Drop down one
neighbours.Add(dn1);
return;
}
// TODO - drop down 2
// TODO - Jump across gap
// TODO - climb
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Diagnostics;
using CK.CodeGen;
using System.Runtime.CompilerServices;
namespace CK.CodeGen
{
/// <summary>
/// Provides Append fluent extension methods to <see cref="ICodeWriter"/> specializations.
/// </summary>
public static class CodeWriterExtensions
{
static readonly Dictionary<Type, string> _typeAliases;
static CodeWriterExtensions()
{
_typeAliases = new Dictionary<Type, string>();
_typeAliases.Add( typeof( void ), "void" );
_typeAliases.Add( typeof( bool ), "bool" );
_typeAliases.Add( typeof( int ), "int" );
_typeAliases.Add( typeof( long ), "long" );
_typeAliases.Add( typeof( short ), "short" );
_typeAliases.Add( typeof( ushort ), "ushort" );
_typeAliases.Add( typeof( sbyte ), "sbyte" );
_typeAliases.Add( typeof( uint ), "uint" );
_typeAliases.Add( typeof( ulong ), "ulong" );
_typeAliases.Add( typeof( byte ), "byte" );
_typeAliases.Add( typeof( char ), "char" );
_typeAliases.Add( typeof( double ), "double" );
_typeAliases.Add( typeof( float ), "float" );
_typeAliases.Add( typeof( decimal ), "decimal" );
_typeAliases.Add( typeof( string ), "string" );
_typeAliases.Add( typeof( object ), "object" );
}
static internal bool AppendTypeAlias( ICodeWriter w, Type t )
{
if( _typeAliases.TryGetValue( t, out var alias ) )
{
w.Append( alias );
return true;
}
return false;
}
/// <summary>
/// Gets a type alias for basic types or null if no alias exists.
/// </summary>
/// <param name="t">The type.</param>
/// <returns>The alias or null.</returns>
static public string? GetTypeAlias( Type t ) => _typeAliases.GetValueOrDefault( t );
/// <summary>
/// Appends raw C# code only once: the code itself is used as a key in <see cref="INamedScope.Memory"/> to
/// avoid adding it twice.
/// </summary>
/// <typeparam name="T">Must be both a <see cref="ICodeWriter"/> and <see cref="INamedScope"/>.</typeparam>
/// <param name="this">This named scope and code writer.</param>
/// <param name="code">Raw code to append. Must not be null, empty or white space.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T AppendOnce<T>( this T @this, string code ) where T : ICodeWriter, INamedScope
{
if( String.IsNullOrWhiteSpace( code ) ) throw new ArgumentException( "To guaranty AppendOnce semantics, code must not be null or white space.", nameof( code ) );
if( !@this.Memory.ContainsKey( code ) )
{
@this.Append( code );
@this.Memory.Add( code, null );
}
return @this;
}
/// <summary>
/// Appends a variable name that is prefixed with the @ sign if it's a <see cref="ReservedKeyword"/>.
/// </summary>
/// <typeparam name="T">The <see cref="ICodeWriter"/>.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="name">The variable name. Must not be null, empty or white space.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T AppendVariable<T>( this T @this, string name ) where T : ICodeWriter
{
if( String.IsNullOrWhiteSpace( name ) ) throw new ArgumentNullException( nameof( name ) );
if( ReservedKeyword.IsReservedKeyword( name ) )
{
@this.Append( "@" );
}
Append( @this, name );
return @this;
}
/// <summary>
/// Appends raw C# code.
/// This is the most basic Append method to use.
/// Use <see cref="AppendSourceString{T}(T, string)"/> to append the source string representation.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="code">Raw code to append.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, string code ) where T : ICodeWriter
{
@this.DoAdd( code );
return @this;
}
/// <summary>
/// Appends raw character.
/// Use <see cref="AppendSourceChar{T}(T, char)"/> to append the source string representation
/// of the character.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="c">Char to append.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, char c ) where T : ICodeWriter
{
@this.DoAdd( c.ToString() );
return @this;
}
/// <summary>
/// Appends a white space.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Space<T>( this T @this ) where T : ICodeWriter => @this.Append( " " );
/// <summary>
/// Appends a <see cref="Environment.NewLine"/>.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T NewLine<T>( this T @this ) where T : ICodeWriter => @this.Append( Environment.NewLine );
/// <summary>
/// Appends a "{" on a new independent line.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T OpenBlock<T>( this T @this ) where T : ICodeWriter => @this.Append( Environment.NewLine ).Append( '{').NewLine();
/// <summary>
/// Appends a "}" on a new independent line.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T CloseBlock<T>( this T @this ) where T : ICodeWriter => @this.Append( Environment.NewLine ).Append( '}' ).NewLine();
/// <summary>
/// Appends the C# type name. Handles generic definition (either opened or closed).
/// The <paramref name="typeDeclaration"/> parameters applies to open generics:
/// When true (the default), typeof( Dictionary<,>.KeyCollection )
/// will append "System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection".
/// When sets to false, it will append "System.Collections.Generic.Dictionary<,>.KeyCollection".
/// </summary>
/// <remarks>
/// Value tuples are expressed (by default) with the (lovely,brackets) but can use the explicit type: <see cref="ValueTuple{T1, T2}"/>
/// instead. This is mainly because of pattern matching limitations in (at least) C# 8 (i.e. netcoreapp3.1).
/// </remarks>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="t">The type to append.</param>
/// <param name="typeDeclaration">True to include generic parameter names in the output.</param>
/// <param name="useValueTupleParentheses">False to use the (safer) "System.ValueTuple<>" instead of the (tuple, with, parentheses, syntax).</param>
/// <returns>This code writer to enable fluent syntax.</returns>
public static T AppendCSharpName<T>( this T @this, Type? t, bool typeDeclaration = true, bool useValueTupleParentheses = true ) where T : ICodeWriter
{
if( t == null ) return @this.Append( "null" );
if( t.IsGenericParameter ) return typeDeclaration ? @this.Append( t.Name ) : @this;
if( AppendTypeAlias( @this, t ) )
{
return @this;
}
if( t.IsArray )
{
AppendCSharpName( @this, t.GetElementType()!, typeDeclaration, useValueTupleParentheses );
return @this.Append( "[" ).Append( new string( ',', t.GetArrayRank() - 1 ) ).Append( "]" );
}
var pathTypes = new Stack<Type>();
pathTypes.Push( t );
Type? decl = t.DeclaringType;
while( decl != null )
{
pathTypes.Push( decl );
decl = decl.DeclaringType;
}
var allGenArgs = new Queue<Type>( t.GetGenericArguments() );
for( int iType = 0; pathTypes.Count > 0; iType++ )
{
Type theT = pathTypes.Pop();
string n;
if( iType == 0 ) n = theT.FullName;
else
{
n = theT.Name;
@this.Append( "." );
}
int idxTick = n.IndexOf( '`', StringComparison.Ordinal ) + 1;
if( idxTick > 0 )
{
int endNbParam = idxTick;
while( endNbParam < n.Length && Char.IsDigit( n, endNbParam ) ) endNbParam++;
int nbParams = int.Parse( n.AsSpan( idxTick, endNbParam - idxTick ), NumberStyles.Integer, NumberFormatInfo.InvariantInfo );
Debug.Assert( nbParams > 0 );
var tName = n.Substring( 0, idxTick - 1 );
bool isValueTuple = tName == "System.ValueTuple";
Type subType = allGenArgs.Dequeue();
bool isNullableValue = !isValueTuple && tName == "System.Nullable" && !subType.IsGenericTypeParameter;
if( isValueTuple && useValueTupleParentheses )
{
@this.Append( "(" );
}
else if( !isNullableValue )
{
@this.Append( tName );
@this.Append( "<" );
}
--nbParams;
int iGen = 0;
for(; ; )
{
if( iGen > 0 ) @this.Append( "," );
AppendCSharpName( @this, subType, typeDeclaration, useValueTupleParentheses );
if( iGen++ == nbParams ) break;
subType = allGenArgs.Dequeue();
// Long Value Tuple handling here only if useValueTupleParentheses is true.
// This lift the rest content, skipping the rest 8th slot itself.
if( iGen == 7 && isValueTuple && useValueTupleParentheses )
{
Debug.Assert( subType.Name.StartsWith( "ValueTuple", StringComparison.Ordinal ) );
Debug.Assert( allGenArgs.Count == 0 );
var rest = subType.GetGenericArguments();
subType = rest[0];
nbParams = rest.Length - 1;
for( int i = 1; i < rest.Length; ++i ) allGenArgs.Enqueue( rest[i] );
iGen = 0;
@this.Append( "," );
}
}
@this.Append( isNullableValue ? "?" : (isValueTuple && useValueTupleParentheses ? ")" : ">") );
}
else @this.Append( n );
}
return @this;
}
/// <summary>
/// Appends "typeof(<see cref="AppendCSharpName"/>)" with the type name in is non declaration form:
/// for the open generic dictionary this is "typeof(System.Collections.Generic.Dictionary<,>)".
/// When <paramref name="t"/> is null, null is appended.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="t">The type to append with typeof operator. When null, "null" will be appended.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
public static T AppendTypeOf<T>( this T @this, Type t ) where T : ICodeWriter
{
// typeof handles the (tuple, with, parentheses, syntax).
return t == null
? @this.Append( "null" )
: @this.Append( "typeof(" ).AppendCSharpName( t, false, useValueTupleParentheses: true ).Append( ")" );
}
/// <summary>
/// Appends a call to <see cref="Assembly.Load(string)"/> with the <see cref="Assembly.FullName"/>.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="a">The assembly.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, Assembly? a ) where T : ICodeWriter
{
return a == null
? @this.Append( "null" )
: @this.Append( "System.Reflection.Assembly.Load(" ).AppendSourceString( a.FullName ).Append( ")" );
}
/// <summary>
/// Appends what is needed to recover a <see cref="MemberInfo"/>: this applies to
/// <see cref="Type"/>, <see cref="MethodInfo"/>, <see cref="PropertyInfo"/>, <see cref="FieldInfo"/>, <see cref="EventInfo"/>
/// and <see cref="ConstructorInfo"/>.
/// Current implementation rely on <see cref="AppendTypeOf{T}(T, Type)"/> on the type (either the <paramref name="m"/> parameter
/// or the <see cref="MemberInfo.DeclaringType"/>): the type must be accessible from where it is used.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="m">The member.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, MemberInfo? m ) where T : ICodeWriter
{
switch( m )
{
case null: @this.Append( "null" ); return @this;
case Type t: @this.AppendTypeOf( t ); return @this;
case MethodInfo method: @this.Append( "(System.Reflection.MethodInfo)" ); break;
case PropertyInfo prop: @this.Append( "(System.Reflection.PropertyInfo)" ); break;
case FieldInfo field: @this.Append( "(System.Reflection.FieldInfo)" ); break;
case EventInfo ev: @this.Append( "(System.Reflection.EventInfo)" ); break;
case ConstructorInfo c: @this.Append( "(System.Reflection.ConstructorInfo)" ); break;
}
return @this.AppendTypeOf( m.DeclaringType )
.Append( ".GetMembers( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.DeclaredOnly )[" )
.Append( Array.IndexOf( m.DeclaringType.GetMembers( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly ), m ) )
.Append( "]" );
}
/// <summary>
/// Appends either "true" or "false".
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="b">The boolean value.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, bool b ) where T : ICodeWriter => @this.Append( b ? "true" : "false" );
/// <summary>
/// Appends the source representation of an integer value.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="i">The integer.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, int i ) where T : ICodeWriter
{
return @this.Append( i.ToString( CultureInfo.InvariantCulture ) );
}
/// <summary>
/// Appends the source representation of a long value (0 is appended as "0L").
/// </summary>
/// <param name="this">This code writer.</param>
/// <param name="i">The long.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, long i ) where T : ICodeWriter
{
return @this.Append( i.ToString( CultureInfo.InvariantCulture ) ).Append( "L" );
}
/// <summary>
/// Appends the source representation of a <see cref="UInt64"/> value (0 is appended as "(ulong)0").
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="i">The unsigned long.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, ulong i ) where T : ICodeWriter
{
return @this.Append( "(ulong)" ).Append( i.ToString( CultureInfo.InvariantCulture ) );
}
/// <summary>
/// Appends the source representation of a <see cref="Int16"/> value (0 is appended as "(short)0").
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="i">The short integer..</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, short i ) where T : ICodeWriter
{
return @this.Append( "(short)" ).Append( i.ToString( CultureInfo.InvariantCulture ) );
}
/// <summary>
/// Appends the source representation of a <see cref="UInt16"/> value (0 is appended as "(ushort)0").
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="i">The unsigned short integer..</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, ushort i ) where T : ICodeWriter
{
return @this.Append( "(ushort)" ).Append( i.ToString( CultureInfo.InvariantCulture ) );
}
/// <summary>
/// Appends the source representation of a <see cref="SByte"/> value (0 is appended as "(sbyte)0").
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="i">The signed byte.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, sbyte i ) where T : ICodeWriter
{
return @this.Append( "(sbyte)" ).Append( i.ToString( CultureInfo.InvariantCulture ) );
}
/// <summary>
/// Appends the source representation of a <see cref="Byte"/> value (0 is appended as "(byte)0").
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="i">The byte.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, byte i ) where T : ICodeWriter
{
return @this.Append( "(byte)" ).Append( i.ToString( CultureInfo.InvariantCulture ) );
}
/// <summary>
/// Appends the source representation of a <see cref="UInt32"/> value (0 is appended as "(uint)0").
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="i">The unsigned integer.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, uint i ) where T : ICodeWriter
{
return @this.Append( "(uint)" ).Append( i.ToString( CultureInfo.InvariantCulture ) );
}
/// <summary>
/// Appends the source representation of a <see cref="Guid"/> value: "new Guid(...)".
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="g">The Guid.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, Guid g ) where T : ICodeWriter
{
return @this.Append( "new Guid(\"" ).Append( g.ToString() ).Append( "\")" );
}
/// <summary>
/// Appends the source representation of a <see cref="Double"/> value.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="d">The double.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, double d ) where T : ICodeWriter
{
return @this.Append( d.ToString( CultureInfo.InvariantCulture ) );
}
/// <summary>
/// Appends the source representation of a <see cref="Single"/> value.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="f">The float.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, float f ) where T : ICodeWriter
{
return @this.Append( f.ToString( CultureInfo.InvariantCulture ) ).Append( "f" );
}
/// <summary>
/// Appends the source representation of a <see cref="Decimal"/> value (0 is appended as "0m").
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="d">The decimal.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, decimal d ) where T : ICodeWriter
{
return @this.Append( d.ToString( CultureInfo.InvariantCulture ) ).Append( "m" );
}
/// <summary>
/// Appends the source representation of a <see cref="DateTime"/> value: "new DateTime( ... )".
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="d">The datetime.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, DateTime d ) where T : ICodeWriter
{
return @this.Append( "new DateTime(" ).Append( d.Ticks ).Append( ", DateTimeKind." ).Append( d.Kind.ToString() ).Append( ")" );
}
/// <summary>
/// Appends the source representation of a <see cref="TimeSpan"/> value: "new TimeSpan( ... )".
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="ts">The time span.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, TimeSpan ts ) where T : ICodeWriter
{
return @this.Append( "new TimeSpan(" ).Append( ts.Ticks.ToString( CultureInfo.InvariantCulture ) ).Append( ")" );
}
/// <summary>
/// Appends the source representation of a <see cref="DateTimeOffset"/> value: "new DateTimeOffset( ... )".
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="to">The date time with offset.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, DateTimeOffset to ) where T : ICodeWriter
{
return @this.Append( "new DateTimeOffset(" )
.Append( to.Ticks )
.Append( ", new TimeSpan(" )
.Append( to.Offset.Ticks )
.Append( "))" );
}
/// <summary>
/// Appends the source representation of a character: "'c'".
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="c">The character.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T AppendSourceChar<T>( this T @this, char c ) where T : ICodeWriter
{
switch( c )
{
case '\\': return @this.Append( @"'\\'" );
case '\r': return @this.Append( @"'\r'" );
case '\n': return @this.Append( @"'\n'" );
case '\t': return @this.Append( @"'\t'" );
case '\0': return @this.Append( @"'\0'" );
case '\b': return @this.Append( @"'\b'" );
case '\v': return @this.Append( @"'\v'" );
case '\a': return @this.Append( @"'\a'" );
case '\f': return @this.Append( @"'\f'" );
}
int vC = c;
if( vC < 32
|| (vC >= 127 && vC <= 160)
|| vC >= 888 )
{
return @this.Append( "'\\u" ).Append( vC.ToString( "X4", NumberFormatInfo.InvariantInfo ) ).Append( "'" );
}
return @this.Append( "'" ).Append( c.ToString() ).Append( "'" );
}
/// <summary>
/// Appends the source representation of the string.
/// See <see cref="ExternalTypeExtensions.ToSourceString(string)"/>.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="s">The string. Can be null.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T AppendSourceString<T>( this T @this, string? s ) where T : ICodeWriter
{
return @this.Append( s.ToSourceString() );
}
/// <summary>
/// Appends multiple string (raw C# code) at once, separated with a comma by default.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="strings">The string. Can be null or empty.</param>
/// <param name="separator">Separator between the strings.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, IEnumerable<string> strings, string? separator = ", " ) where T : ICodeWriter
{
if( strings != null )
{
if( String.IsNullOrEmpty( separator ) ) separator = null;
bool already = false;
foreach( var s in strings )
{
if( already )
{
if( separator != null ) @this.Append( separator );
}
else already = true;
Append( @this, s );
}
}
return @this;
}
/// <summary>
/// Appends the code of a collection of objects of a given type <typeparamref name="T"/>.
/// The code is either "null", <see cref="Array.Empty{T}()"/> or an actual new array
/// with the items appended with <see cref="Append{T}(T, object?, bool)"/>: only
/// basic types are supported.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <typeparam name="TItem">The items type.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="e">Set of items for which code must be generated. Can be null.</param>
/// <param name="useValueTupleParentheses">False to use the (safer) "System.ValueTuple<>" instead of the (tuple, with, parentheses, syntax).</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T AppendArray<T,TItem>( this T @this, IEnumerable<TItem>? e, bool useValueTupleParentheses = true ) where T : ICodeWriter
{
if( e == null ) return @this.Append( "null" );
if( !e.Any() ) return @this.Append( "Array.Empty<" ).AppendCSharpName( typeof( TItem ), false, useValueTupleParentheses ).Append( ">()" );
@this.Append( "new " ).AppendCSharpName( typeof( TItem ), false, useValueTupleParentheses ).Append( "[]{" );
bool already = false;
foreach( TItem x in e )
{
if( already ) @this.Append( "," );
else already = true;
Append( @this, x );
}
return @this.Append( "}" );
}
/// <summary>
/// Appends the code of a collection of objects.
/// If the actual set is a <see cref="IEnumerable{T}"/>, the actual type is extracted
/// otherwise the type of the items is considered as being object.
/// The code is either "null", <see cref="Array.Empty{T}()"/> or an actual new array
/// with the items appended with <see cref="Append{T}(T, object?, bool)"/>: only
/// basic types are supported.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="e">Set of items for which code must be generated. Can be null.</param>
/// <param name="useValueTupleParentheses">False to use the (safer) "System.ValueTuple<>" instead of the (tuple, with, parentheses, syntax).</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T AppendArray<T>( this T @this, IEnumerable? e, bool useValueTupleParentheses = true ) where T : ICodeWriter
{
if( e == null ) return @this.Append( "null" );
Type type = typeof( object );
var eI = e.GetType()
.GetInterfaces()
.FirstOrDefault( iT => iT.IsGenericType && iT.GetGenericTypeDefinition() == typeof( IEnumerable<> ) );
if( eI != null )
{
type = eI.GetGenericArguments()[0];
}
var i = e.GetEnumerator();
bool any = i.MoveNext();
(i as IDisposable)?.Dispose();
if( any )
{
@this.Append( "new " ).AppendCSharpName( type, false, useValueTupleParentheses ).Append( "[]{" );
bool existing = false;
foreach( var x in e )
{
if( existing ) @this.Append( "," );
else existing = true;
Append( @this, x );
}
return @this.Append( "}" );
}
return @this.Append( "Array.Empty<" ).AppendCSharpName( type, false, useValueTupleParentheses ).Append( ">()" );
}
/// <summary>
/// Appends the code source of an enumeration value.
/// The value is written as its integral type value casted into the enum type.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <typeparam name="E">Type of the <see cref="Enum"/>.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="o">The enum value.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T, E>( this T @this, E o ) where T : ICodeWriter where E : Enum => AppendEnumValue( @this, typeof( E ), o );
static T AppendEnumValue<T>( T @this, Type t, object o ) where T : ICodeWriter
{
@this.Append( "((" ).Append( t.FullName ).Append( ')' );
char tU = Enum.GetUnderlyingType( t ).Name[0];
if( tU == 'U' || tU == 'B' )
{
// An enum based on byte (enum EByte : byte) or any other unsigned integral type shorter than a ulong
// cannot be cast into a ulong... We must use Convert that handles this correctly.
@this.Append( Convert.ToUInt64( o, NumberFormatInfo.InvariantInfo ) );
}
else
{
// Parentheses are required around negative values.
long v = Convert.ToInt64( o, NumberFormatInfo.InvariantInfo );
if( v >= 0 ) @this.Append( v );
else @this.Append( '(' ).Append( v ).Append( ')' );
}
return @this.Append( ')' );
}
/// <summary>
/// Appends the code source for an untyped object.
/// Only types that are implemented through one of the existing Append, AppendArray (all IEnumerable are
/// handled) and enum values.
/// extension methods are supported: an <see cref="ArgumentException"/> is thrown for unsupported type.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="o">The object. Can be null.</param>
/// <param name="useValueTupleParentheses">False to use the (safer) "System.ValueTuple<>" instead of the (tuple, with, parentheses, syntax).</param>
/// <returns>This code writer to enable fluent syntax.</returns>
static public T Append<T>( this T @this, object? o, bool useValueTupleParentheses = true ) where T : ICodeWriter
{
if( o == Type.Missing ) return @this.Append( "System.Type.Missing" );
if( o == DBNull.Value ) return @this.Append( "System.DBNull.Value" );
switch( o )
{
case null: return @this.Append( "null" );
case Type x: return @this.Append( "typeof(" ).AppendCSharpName( x, false, true ).Append( ")" );
case MemberInfo m: return @this.Append( "typeof(" ).AppendCSharpName( m.DeclaringType, false, true ).Append( ")" );
case string x: return Append( @this, x.ToSourceString() );
case bool x: return Append( @this, x );
case int x: return Append( @this, x );
case long x: return Append( @this, x );
case short x: return Append( @this, x );
case ushort x: return Append( @this, x );
case sbyte x: return Append( @this, x );
case uint x: return Append( @this, x );
case ulong x: return Append( @this, x );
case byte x: return Append( @this, x );
case Guid x: return Append( @this, x );
case char x: return AppendSourceChar( @this, x );
case double x: return Append( @this, x );
case float x: return Append( @this, x );
case decimal x: return Append( @this, x );
case DateTime x: return Append( @this, x );
case TimeSpan x: return Append( @this, x );
case DateTimeOffset x: return Append( @this, x );
case IEnumerable<Type> x: return AppendArray( @this, x, useValueTupleParentheses );
case IEnumerable x: return AppendArray( @this, x, useValueTupleParentheses );
}
Type t = o.GetType();
if( t.IsEnum ) return AppendEnumValue( @this, t, o );
throw new ArgumentException( "Unknown type: " + o.GetType().AssemblyQualifiedName );
}
/// <summary>
/// Creates a segment of code inside this function.
/// This signature allows a fluent code to "emit" one or more insertion points.
/// </summary>
/// <typeparam name="T">The function scope type.</typeparam>
/// <param name="this">This function scope.</param>
/// <param name="part">The function part to use to inject code at this location (or at the top).</param>
/// <param name="top">Optionally creates the new part at the start of the code instead of at the current writing position in the code.</param>
/// <returns>This function scope writer to enable fluent syntax.</returns>
public static T CreatePart<T>( this T @this, out IFunctionScopePart part, bool top = false ) where T : IFunctionScope
{
part = @this.CreatePart( top );
return @this;
}
/// <summary>
/// Creates a segment of code inside this namespace.
/// This signature allows a fluent code to "emit" one or more insertion points.
/// </summary>
/// <typeparam name="T">The namespace scope type.</typeparam>
/// <param name="this">This namespace scope.</param>
/// <param name="part">The namespace part to use to inject code at this location (or at the top).</param>
/// <param name="top">Optionally creates the new part at the start of the code instead of at the current writing position in the code.</param>
/// <returns>This namespace scope writer to enable fluent syntax.</returns>
public static T CreatePart<T>( this T @this, out INamespaceScopePart part, bool top = false ) where T : INamespaceScope
{
part = @this.CreatePart( top );
return @this;
}
/// <summary>
/// Creates a segment of code inside this type.
/// This signature allows a fluent code to "emit" one or more insertion points.
/// </summary>
/// <typeparam name="T">The type scope type.</typeparam>
/// <param name="this">This type scope.</param>
/// <param name="part">The type part to use to inject code at this location (or at the top).</param>
/// <param name="top">Optionally creates the new part at the start of the code instead of at the current writing position in the code.</param>
/// <returns>This type scope writer to enable fluent syntax.</returns>
public static T CreatePart<T>( this T @this, out ITypeScopePart part, bool top = false ) where T : ITypeScope
{
part = @this.CreatePart( top );
return @this;
}
/// <summary>
/// Fluent function application: this enables a procedural fragment to be inlined in a fluent code.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="f">Fluent function to apply.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
public static T Append<T>( this T @this, Func<T, T> f ) where T : ICodeWriter => f( @this );
/// <summary>
/// Fluent action application: this enables a procedural fragment to be inlined in a fluent code.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="f">Action to apply to this code writer.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
public static T Append<T>( this T @this, Action<T> f ) where T : ICodeWriter
{
f( @this );
return @this;
}
/// <summary>
/// Appends an array with the given types.
/// When <paramref name="types"/> is null, "null" is written, when the enumerable
/// is empty, "<see cref="Type.EmptyTypes"/>" is written.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="types">Types to <see cref="AppendTypeOf"/> in an array.</param>
/// <returns>This code writer to enable fluent syntax.</returns>
public static T AppendArray<T>( this T @this, IEnumerable<Type>? types ) where T : ICodeWriter
{
if( types == null ) return @this.Append( "null" );
bool atLeastOne = false;
foreach( var t in types )
{
if( atLeastOne ) @this.Append( ", " );
else
{
@this.Append( "new[]{" );
atLeastOne = true;
}
@this.AppendTypeOf( t );
}
if( atLeastOne ) @this.Append( "}" );
else @this.Append( "Type.EmptyTypes" );
return @this;
}
/// <summary>
/// Appends a star comment with the current source origin and method name.
/// </summary>
/// <typeparam name="T">Actual type of the code writer.</typeparam>
/// <param name="this">This code writer.</param>
/// <param name="format">Full comment format.</param>
/// <param name="source">Generator file name (should not be set explicitly).</param>
/// <param name="lineNumber">Line number in the generator file (should not be set explicitly).</param>
/// <param name="methodName">The name of the caller (should not be set explicitly).</param>
/// <returns>This code writer to enable fluent syntax.</returns>
public static T GeneratedByComment<T>( this T @this, string format = "/* Generated by {0}, line: {1} (method {2}). */", [CallerFilePath]string? source = null, [CallerLineNumber] int lineNumber = 0, [CallerMemberName] string? methodName = null ) where T : ICodeWriter
{
return @this.Append( String.Format( CultureInfo.InvariantCulture, format, source, lineNumber, methodName ) );
}
class Combiner : ICodeWriter
{
readonly ICodeWriter _w1;
readonly ICodeWriter _w2;
public Combiner( ICodeWriter w1, ICodeWriter w2 )
{
_w1 = w1;
_w2 = w2;
}
public void DoAdd( string? code )
{
_w1.DoAdd( code );
_w2.DoAdd( code );
}
}
/// <summary>
/// Combines 2 writers into one: the same code will be added to both of them.
/// </summary>
/// <param name="this">This code writer.</param>
/// <param name="other">The other code writer.</param>
/// <returns>A writer for this and the other writer.</returns>
public static ICodeWriter And( this ICodeWriter @this, ICodeWriter other ) => new Combiner( @this, other );
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using MindTouch.Xml;
namespace MindTouch.Dream {
internal class DreamFeatureDirectory {
//--- Fields ---
internal Dictionary<string, DreamFeatureDirectory> Subfeatures = new Dictionary<string, DreamFeatureDirectory>(StringComparer.Ordinal);
internal List<DreamFeature> SignatureMap = new List<DreamFeature>();
//--- Methods ---
internal void Add(string[] path, int level, DreamFeature feature) {
// check if we reached the last part of the feature path
if(level == path.Length) {
// add feature to signature map
SignatureMap.Add(feature);
} else {
string key = path[level];
DreamFeatureDirectory entry = null;
// check if sub-feature already exists
if(Subfeatures.TryGetValue(key, out entry)) {
entry.Add(path, level + 1, feature);
} else {
DreamFeatureDirectory tree = new DreamFeatureDirectory();
tree.Add(path, level + 1, feature);
Subfeatures.Add(key, tree);
}
}
}
internal void Add(string[] path, int level, DreamFeatureDirectory features) {
// check if we reached the last part of the feature path
if(level == path.Length) {
throw new ArgumentException(string.Format("feature path is already in use ({0})", string.Join("/", path)));
} else {
string key = path[level];
DreamFeatureDirectory entry = null;
Subfeatures.TryGetValue(key, out entry);
// check if added feature directory is a leaf node
if(level == (path.Length - 1)) {
// check if there was an existing sub-feature
if(entry != null) {
features.CopyAndMergeFrom(entry);
Subfeatures[key] = features;
} else {
Subfeatures.Add(key, features);
}
} else {
// check if a sub-feature needs to be created
if(entry == null) {
entry = new DreamFeatureDirectory();
Subfeatures.Add(key, entry);
}
entry.Add(path, level + 1, features);
}
}
}
internal void CopyAndMergeFrom(DreamFeatureDirectory features) {
SignatureMap.AddRange(features.SignatureMap);
foreach(KeyValuePair<string, DreamFeatureDirectory> pair in features.Subfeatures) {
DreamFeatureDirectory entry;
if(Subfeatures.TryGetValue(pair.Key, out entry)) {
entry.CopyAndMergeFrom(pair.Value);
} else {
Subfeatures.Add(pair.Key, pair.Value);
}
}
}
internal void Remove(XUri uri) {
Remove(uri.GetSegments(UriPathFormat.Normalized), 0);
}
internal void Remove(string[] path, int level) {
string key = path[level];
DreamFeatureDirectory entry;
if(Subfeatures.TryGetValue(key, out entry)) {
if(level == (path.Length - 1)) {
Subfeatures.Remove(key);
} else {
entry.Remove(path, level + 1);
}
}
}
internal List<DreamFeature> Find(XUri uri) {
return Find(uri.GetSegments(UriPathFormat.Normalized), 0);
}
internal List<DreamFeature> Find(string[] path, int level) {
// check if we reached the last part of the path
if(level == path.Length) {
return FindMatchingSignature(0);
}
// search for path in sub-features
List<DreamFeature> result = null;
DreamFeatureDirectory entry;
string key = path[level];
// find sub-feature by name
if(Subfeatures.TryGetValue(key, out entry)) {
result = entry.Find(path, level + 1);
if(result != null) {
return result;
}
}
// find sub-feature by wildcard
if(Subfeatures.TryGetValue("*", out entry)) {
result = entry.Find(path, level + 1);
if(result != null) {
return result;
}
}
return FindMatchingSignature(path.Length - level);
}
internal List<DreamFeature> FindMatchingSignature(int argCount) {
List<DreamFeature> result = null;
foreach(DreamFeature entry in SignatureMap) {
if(entry.OptionalSegments >= argCount) {
if(result == null) {
result = new List<DreamFeature>();
}
result.Add(entry);
}
}
return result;
}
internal XDoc ListAll() {
XDoc result = new XDoc("features");
int count = 0;
int hits = 0;
RecurseListAll(string.Empty, result, ref count, ref hits);
result.Attr("count", count);
result.Attr("hits", hits);
return result;
}
private void RecurseListAll(string prefix, XDoc doc, ref int count, ref int hits) {
foreach(DreamFeature feature in SignatureMap) {
if(feature.OptionalSegments != int.MaxValue) {
string optional = string.Empty;
for(int i = 0; i < feature.OptionalSegments; ++i) {
optional += "?/";
}
doc.Start("feature");
doc.Attr("path", feature.Verb + ":" + prefix + "/" + optional);
doc.Attr("hits", feature.HitCounter);
doc.End();
++count;
hits += feature.HitCounter;
} else {
doc.Start("feature");
doc.Attr("path", feature.Verb + ":" + prefix + "//*");
doc.Attr("hits", feature.HitCounter);
doc.End();
++count;
hits += feature.HitCounter;
}
}
foreach(KeyValuePair<string,DreamFeatureDirectory> subdir in Subfeatures) {
subdir.Value.RecurseListAll(prefix + "/" + subdir.Key, doc, ref count, ref hits);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using Xunit;
using static Microsoft.AspNetCore.Routing.Matching.HttpMethodMatcherPolicy;
namespace Microsoft.AspNetCore.Routing.Matching
{
// End-to-end tests for the HTTP method matching functionality
public abstract class HttpMethodMatcherPolicyIntegrationTestBase
{
protected abstract bool HasDynamicMetadata { get; }
[Fact]
public async Task Match_HttpMethod()
{
// Arrange
var endpoint = CreateEndpoint("/hello", httpMethods: new string[] { "GET", });
var matcher = CreateMatcher(endpoint);
var httpContext = CreateContext("/hello", "GET");
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertMatch(httpContext, endpoint);
}
[Fact]
public async Task Match_HttpMethod_CORS()
{
// Arrange
var endpoint = CreateEndpoint("/hello", httpMethods: new string[] { "GET", }, acceptCorsPreflight: true);
var matcher = CreateMatcher(endpoint);
var httpContext = CreateContext("/hello", "GET");
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertMatch(httpContext, endpoint);
}
[Fact]
public async Task Match_HttpMethod_CORS_Preflight()
{
// Arrange
var endpoint = CreateEndpoint("/hello", httpMethods: new string[] { "GET", }, acceptCorsPreflight: true);
var matcher = CreateMatcher(endpoint);
var httpContext = CreateContext("/hello", "GET", corsPreflight: true);
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertMatch(httpContext, endpoint);
}
[Fact] // Nothing here supports OPTIONS, so it goes to a 405.
public async Task NotMatch_HttpMethod_CORS_Preflight()
{
// Arrange
var endpoint = CreateEndpoint("/hello", httpMethods: new string[] { "GET", }, acceptCorsPreflight: false);
var matcher = CreateMatcher(endpoint);
var httpContext = CreateContext("/hello", "GET", corsPreflight: true);
// Act
await matcher.MatchAsync(httpContext);
// Assert
Assert.NotSame(endpoint, httpContext.GetEndpoint());
Assert.Same(HttpMethodMatcherPolicy.Http405EndpointDisplayName, httpContext.GetEndpoint().DisplayName);
}
[Theory]
[InlineData("GeT", "GET")]
[InlineData("unKNOWN", "UNKNOWN")]
public async Task Match_HttpMethod_CaseInsensitive(string endpointMethod, string requestMethod)
{
// Arrange
var endpoint = CreateEndpoint("/hello", httpMethods: new string[] { endpointMethod, });
var matcher = CreateMatcher(endpoint);
var httpContext = CreateContext("/hello", requestMethod);
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertMatch(httpContext, endpoint);
}
[Theory]
[InlineData("GeT", "GET")]
[InlineData("unKNOWN", "UNKNOWN")]
public async Task Match_HttpMethod_CaseInsensitive_CORS_Preflight(string endpointMethod, string requestMethod)
{
// Arrange
var endpoint = CreateEndpoint("/hello", httpMethods: new string[] { endpointMethod, }, acceptCorsPreflight: true);
var matcher = CreateMatcher(endpoint);
var httpContext = CreateContext("/hello", requestMethod, corsPreflight: true);
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertMatch(httpContext, endpoint);
}
[Fact]
public async Task Match_NoMetadata_MatchesAnyHttpMethod()
{
// Arrange
var endpoint = CreateEndpoint("/hello");
var matcher = CreateMatcher(endpoint);
var httpContext = CreateContext("/hello", "GET");
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertMatch(httpContext, endpoint);
}
[Fact]
public async Task Match_NoMetadata_MatchesAnyHttpMethod_CORS_Preflight()
{
// Arrange
var endpoint = CreateEndpoint("/hello", acceptCorsPreflight: true);
var matcher = CreateMatcher(endpoint);
var httpContext = CreateContext("/hello", "GET", corsPreflight: true);
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertMatch(httpContext, endpoint);
}
[Fact] // This matches because the endpoint accepts OPTIONS
public async Task Match_NoMetadata_MatchesAnyHttpMethod_CORS_Preflight_DoesNotSupportPreflight()
{
// Arrange
var endpoint = CreateEndpoint("/hello", acceptCorsPreflight: false);
var matcher = CreateMatcher(endpoint);
var httpContext = CreateContext("/hello", "GET", corsPreflight: true);
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertMatch(httpContext, endpoint);
}
[Fact]
public async Task Match_EmptyMethodList_MatchesAnyHttpMethod()
{
// Arrange
var endpoint = CreateEndpoint("/hello", httpMethods: new string[] { });
var matcher = CreateMatcher(endpoint);
var httpContext = CreateContext("/hello", "GET");
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertMatch(httpContext, endpoint);
}
[Fact] // When all of the candidates handles specific verbs, use a 405 endpoint
public async Task NotMatch_HttpMethod_Returns405Endpoint()
{
// Arrange
var endpoint1 = CreateEndpoint("/hello", httpMethods: new string[] { "GET", "PUT" });
var endpoint2 = CreateEndpoint("/hello", httpMethods: new string[] { "DELETE" });
var matcher = CreateMatcher(endpoint1, endpoint2);
var httpContext = CreateContext("/hello", "POST");
// Act
await matcher.MatchAsync(httpContext);
// Assert
Assert.NotSame(endpoint1, httpContext.GetEndpoint());
Assert.NotSame(endpoint2, httpContext.GetEndpoint());
Assert.Same(HttpMethodMatcherPolicy.Http405EndpointDisplayName, httpContext.GetEndpoint().DisplayName);
// Invoke the endpoint
await httpContext.GetEndpoint().RequestDelegate(httpContext);
Assert.Equal(405, httpContext.Response.StatusCode);
Assert.Equal("DELETE, GET, PUT", httpContext.Response.Headers["Allow"]);
}
[Fact]
public async Task NotMatch_HttpMethod_CORS_DoesNotReturn405()
{
// Arrange
var endpoint1 = CreateEndpoint("/hello", httpMethods: new string[] { "GET", "PUT" }, acceptCorsPreflight: true);
var endpoint2 = CreateEndpoint("/hello", httpMethods: new string[] { "DELETE" });
var matcher = CreateMatcher(endpoint1, endpoint2);
var httpContext = CreateContext("/hello", "POST", corsPreflight: true);
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertNotMatch(httpContext);
}
[Fact] // When one of the candidates handles all verbs, dont use a 405 endpoint
public async Task NotMatch_HttpMethod_WithAllMethodEndpoint_DoesNotReturn405()
{
// Arrange
var endpoint1 = CreateEndpoint("/{x:int}", httpMethods: new string[] { });
var endpoint2 = CreateEndpoint("/{hello:regex(hello)}", httpMethods: new string[] { "DELETE" });
var matcher = CreateMatcher(endpoint1, endpoint2);
var httpContext = CreateContext("/hello", "POST");
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertNotMatch(httpContext);
}
[Fact]
public async Task Match_EndpointWithHttpMethodPreferred()
{
// Arrange
var endpoint1 = CreateEndpoint("/hello", httpMethods: new string[] { "GET", });
var endpoint2 = CreateEndpoint("/bar");
var matcher = CreateMatcher(endpoint1, endpoint2);
var httpContext = CreateContext("/hello", "GET");
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertMatch(httpContext, endpoint1);
}
[Fact]
public async Task Match_EndpointWithHttpMethodPreferred_EmptyList()
{
// Arrange
var endpoint1 = CreateEndpoint("/hello", httpMethods: new string[] { "GET", });
var endpoint2 = CreateEndpoint("/bar", httpMethods: new string[] { });
var matcher = CreateMatcher(endpoint1, endpoint2);
var httpContext = CreateContext("/hello", "GET");
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertMatch(httpContext, endpoint1);
}
[Fact] // The non-http-method-specific endpoint is part of the same candidate set
public async Task Match_EndpointWithHttpMethodPreferred_FallsBackToNonSpecific()
{
// Arrange
var endpoint1 = CreateEndpoint("/{x}", httpMethods: new string[] { "GET", });
var endpoint2 = CreateEndpoint("/{x}", httpMethods: new string[] { });
var matcher = CreateMatcher(endpoint1, endpoint2);
var httpContext = CreateContext("/hello", "POST");
// Act
await matcher.MatchAsync(httpContext);
// Assert
MatcherAssert.AssertMatch(httpContext, endpoint2, ignoreValues: true);
}
[Fact] // See https://github.com/dotnet/aspnetcore/issues/6415
public async Task NotMatch_HttpMethod_Returns405Endpoint_ReExecute()
{
// Arrange
var endpoint1 = CreateEndpoint("/hello", httpMethods: new string[] { "GET", "PUT" });
var endpoint2 = CreateEndpoint("/hello", httpMethods: new string[] { "DELETE" });
var matcher = CreateMatcher(endpoint1, endpoint2);
var httpContext = CreateContext("/hello", "POST");
// Act
await matcher.MatchAsync(httpContext);
// Assert
Assert.NotSame(endpoint1, httpContext.GetEndpoint());
Assert.NotSame(endpoint2, httpContext.GetEndpoint());
Assert.Same(HttpMethodMatcherPolicy.Http405EndpointDisplayName, httpContext.GetEndpoint().DisplayName);
// Invoke the endpoint
await httpContext.GetEndpoint().RequestDelegate(httpContext);
Assert.Equal(405, httpContext.Response.StatusCode);
Assert.Equal("DELETE, GET, PUT", httpContext.Response.Headers["Allow"]);
// Invoke the endpoint again to verify headers not duplicated
await httpContext.GetEndpoint().RequestDelegate(httpContext);
Assert.Equal(405, httpContext.Response.StatusCode);
Assert.Equal("DELETE, GET, PUT", httpContext.Response.Headers["Allow"]);
}
private static Matcher CreateMatcher(params RouteEndpoint[] endpoints)
{
var services = new ServiceCollection()
.AddOptions()
.AddLogging()
.AddRouting()
.BuildServiceProvider();
var builder = services.GetRequiredService<DfaMatcherBuilder>();
for (var i = 0; i < endpoints.Length; i++)
{
builder.AddEndpoint(endpoints[i]);
}
return builder.Build();
}
internal static HttpContext CreateContext(
string path,
string httpMethod,
bool corsPreflight = false)
{
var httpContext = new DefaultHttpContext();
httpContext.Request.Method = corsPreflight ? PreflightHttpMethod : httpMethod;
httpContext.Request.Path = path;
if (corsPreflight)
{
httpContext.Request.Headers[HeaderNames.Origin] = "example.com";
httpContext.Request.Headers[HeaderNames.AccessControlRequestMethod] = httpMethod;
}
return httpContext;
}
internal RouteEndpoint CreateEndpoint(
string template,
object defaults = null,
object constraints = null,
int order = 0,
string[] httpMethods = null,
bool acceptCorsPreflight = false)
{
var metadata = new List<object>();
if (httpMethods != null)
{
metadata.Add(new HttpMethodMetadata(httpMethods ?? Array.Empty<string>(), acceptCorsPreflight));
}
if (HasDynamicMetadata)
{
metadata.Add(new DynamicEndpointMetadata());
}
var displayName = "endpoint: " + template + " " + string.Join(", ", httpMethods ?? new[] { "(any)" });
return new RouteEndpoint(
TestConstants.EmptyRequestDelegate,
RoutePatternFactory.Parse(template, defaults, constraints),
order,
new EndpointMetadataCollection(metadata),
displayName);
}
internal (Matcher matcher, RouteEndpoint endpoint) CreateMatcher(string template)
{
var endpoint = CreateEndpoint(template);
return (CreateMatcher(endpoint), endpoint);
}
private class DynamicEndpointMetadata : IDynamicEndpointMetadata
{
public bool IsDynamic => true;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
private ThreadPoolBoundHandle _threadPoolBinding;
internal static string GetPipePath(string serverName, string pipeName)
{
string normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName);
if (String.Equals(normalizedPipePath, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentOutOfRangeException("pipeName", SR.ArgumentOutOfRange_AnonymousReserved);
}
return normalizedPipePath;
}
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal static void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
// Check that this handle is infact a handle to a pipe.
if (Interop.mincore.GetFileType(safePipeHandle) != Interop.mincore.FileTypes.FILE_TYPE_PIPE)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// If the handle is of async type, bind the handle to the ThreadPool so that we can use
// the async operations (it's needed so that our native callbacks get called).
_threadPoolBinding = ThreadPoolBoundHandle.BindHandle(handle);
}
private void UninitializeAsyncHandle()
{
if (_threadPoolBinding != null)
_threadPoolBinding.Dispose();
}
[SecurityCritical]
private unsafe int ReadCore(byte[] buffer, int offset, int count)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanRead, "can't read");
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
if (_isAsync)
{
IAsyncResult result = BeginReadCore(buffer, offset, count, null, null);
return EndRead(result);
}
int errorCode = 0;
int r = ReadFileNative(_handle, buffer, offset, count, null, out errorCode);
if (r == -1)
{
// If the other side has broken the connection, set state to Broken and return 0
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED)
{
State = PipeState.Broken;
r = 0;
}
else
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode, String.Empty);
}
}
_isMessageComplete = (errorCode != Interop.mincore.Errors.ERROR_MORE_DATA);
Debug.Assert(r >= 0, "PipeStream's ReadCore is likely broken.");
return r;
}
[SecurityCritical]
private unsafe void WriteCore(byte[] buffer, int offset, int count)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanWrite, "can't write");
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
if (_isAsync)
{
IAsyncResult result = BeginWriteCore(buffer, offset, count, null, null);
EndWrite(result);
return;
}
int errorCode = 0;
int r = WriteFileNative(_handle, buffer, offset, count, null, out errorCode);
if (r == -1)
{
WinIOError(errorCode);
}
Debug.Assert(r >= 0, "PipeStream's WriteCore is likely broken.");
return;
}
// Blocks until the other end of the pipe has read in all written buffer.
[SecurityCritical]
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
// Block until other end of the pipe has read everything.
if (!Interop.mincore.FlushFileBuffers(_handle))
{
WinIOError(Marshal.GetLastWin32Error());
}
}
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public virtual PipeTransmissionMode TransmissionMode
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (_isFromExistingHandle)
{
int pipeFlags;
if (!Interop.mincore.GetNamedPipeInfo(_handle, out pipeFlags, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero))
{
WinIOError(Marshal.GetLastWin32Error());
}
if ((pipeFlags & Interop.mincore.PipeOptions.PIPE_TYPE_MESSAGE) != 0)
{
return PipeTransmissionMode.Message;
}
else
{
return PipeTransmissionMode.Byte;
}
}
else
{
return _transmissionMode;
}
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public virtual int InBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
int inBufferSize;
if (!Interop.mincore.GetNamedPipeInfo(_handle, IntPtr.Zero, IntPtr.Zero, out inBufferSize, IntPtr.Zero))
{
WinIOError(Marshal.GetLastWin32Error());
}
return inBufferSize;
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public virtual int OutBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
int outBufferSize;
// Use cached value if direction is out; otherwise get fresh version
if (_pipeDirection == PipeDirection.Out)
{
outBufferSize = _outBufferSize;
}
else if (!Interop.mincore.GetNamedPipeInfo(_handle, IntPtr.Zero, out outBufferSize,
IntPtr.Zero, IntPtr.Zero))
{
WinIOError(Marshal.GetLastWin32Error());
}
return outBufferSize;
}
}
public virtual PipeTransmissionMode ReadMode
{
[SecurityCritical]
get
{
CheckPipePropertyOperations();
// get fresh value if it could be stale
if (_isFromExistingHandle || IsHandleExposed)
{
UpdateReadMode();
}
return _readMode;
}
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
// Nothing fancy here. This is just a wrapper around the Win32 API. Note, that NamedPipeServerStream
// and the AnonymousPipeStreams override this.
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
unsafe
{
int pipeReadType = (int)value << 1;
if (!Interop.mincore.SetNamedPipeHandleState(_handle, &pipeReadType, IntPtr.Zero, IntPtr.Zero))
{
WinIOError(Marshal.GetLastWin32Error());
}
else
{
_readMode = value;
}
}
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private class ReadWriteAsyncParams
{
public ReadWriteAsyncParams() { }
public ReadWriteAsyncParams(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
this.Buffer = buffer;
this.Offset = offset;
this.Count = count;
this.CancellationHelper = cancellationToken.CanBeCanceled ? new IOCancellationHelper(cancellationToken) : null;
}
public Byte[] Buffer { get; set; }
public int Offset { get; set; }
public int Count { get; set; }
public IOCancellationHelper CancellationHelper { get; private set; }
}
[SecurityCritical]
private unsafe static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(PipeStream.AsyncPSCallback);
[SecurityCritical]
private IAsyncResult BeginWrite(AsyncCallback callback, Object state)
{
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
Debug.Assert(readWriteParams != null);
byte[] buffer = readWriteParams.Buffer;
int offset = readWriteParams.Offset;
int count = readWriteParams.Count;
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
CheckWriteOperations();
if (!_isAsync)
{
return _streamAsyncHelper.BeginWrite(buffer, offset, count, callback, state);
}
else
{
return BeginWriteCore(buffer, offset, count, callback, state);
}
}
[SecurityCritical]
unsafe private PipeStreamAsyncResult BeginWriteCore(byte[] buffer, int offset, int count,
AsyncCallback callback, Object state)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanWrite, "can't write");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert(_isAsync, "BeginWriteCore doesn't work on synchronous file streams!");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
// Create and store async stream class library specific data in the async result
PipeStreamAsyncResult asyncResult = new PipeStreamAsyncResult();
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
asyncResult._isWrite = true;
asyncResult._handle = _handle;
// fixed doesn't work well with zero length arrays. Set the zero-byte flag in case
// caller needs to do any cleanup
if (buffer.Length == 0)
{
//intOverlapped->InternalLow = IntPtr.Zero;
// EndRead will free the Overlapped struct
asyncResult.CallUserCallback();
}
else
{
// For Synchronous IO, I could go with either a userCallback and using the managed
// Monitor class, or I could create a handle and wait on it.
ManualResetEvent waitHandle = new ManualResetEvent(false);
asyncResult._waitHandle = waitHandle;
NativeOverlapped* intOverlapped = _threadPoolBinding.AllocateNativeOverlapped(s_IOCallback, asyncResult, buffer);
asyncResult._overlapped = intOverlapped;
int errorCode = 0;
// Queue an async WriteFile operation and pass in a packed overlapped
int r = WriteFileNative(_handle, buffer, offset, count, intOverlapped, out errorCode);
// WriteFile, the OS version, will return 0 on failure, but this WriteFileNative
// wrapper returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer written back from this
// call when using overlapped structures! You must not pass in a non-null
// lpNumBytesWritten to WriteFile when using overlapped structures! This is by design
// NT behavior.
if (r == -1 && errorCode != Interop.mincore.Errors.ERROR_IO_PENDING)
{
// Clean up
if (intOverlapped != null) _threadPoolBinding.FreeNativeOverlapped(intOverlapped);
WinIOError(errorCode);
}
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
if (readWriteParams != null)
{
if (readWriteParams.CancellationHelper != null)
{
readWriteParams.CancellationHelper.AllowCancellation(_handle, intOverlapped);
}
}
}
return asyncResult;
}
[SecurityCritical]
private unsafe void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
if (!_isAsync)
{
_streamAsyncHelper.EndWrite(asyncResult);
return;
}
PipeStreamAsyncResult afsar = asyncResult as PipeStreamAsyncResult;
if (afsar == null || !afsar._isWrite)
{
throw __Error.GetWrongAsyncResult();
}
// Ensure we can't get into any races by doing an interlocked
// CompareExchange here. Avoids corrupting memory via freeing the
// NativeOverlapped class or GCHandle twice. --
if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
{
throw __Error.GetEndWriteCalledTwice();
}
ReadWriteAsyncParams readWriteParams = afsar.AsyncState as ReadWriteAsyncParams;
IOCancellationHelper cancellationHelper = null;
if (readWriteParams != null)
{
cancellationHelper = readWriteParams.CancellationHelper;
if (cancellationHelper != null)
{
cancellationHelper.SetOperationCompleted();
}
}
// Obtain the WaitHandle, but don't use public property in case we
// delay initialize the manual reset event in the future.
WaitHandle wh = afsar._waitHandle;
if (wh != null)
{
// We must block to ensure that AsyncPSCallback has completed,
// and we should close the WaitHandle in here. AsyncPSCallback
// and the hand-ported imitation version in COMThreadPool.cpp
// are the only places that set this event.
using (wh)
{
wh.WaitOne();
Debug.Assert(afsar._isComplete == true, "PipeStream::EndWrite - AsyncPSCallback didn't set _isComplete to true!");
}
}
// Free memory & GC handles.
NativeOverlapped* overlappedPtr = afsar._overlapped;
if (overlappedPtr != null)
{
_threadPoolBinding.FreeNativeOverlapped(overlappedPtr);
}
// Now check for any error during the write.
if (afsar._errorCode != 0)
{
if (afsar._errorCode == Interop.mincore.Errors.ERROR_OPERATION_ABORTED)
{
if (cancellationHelper != null)
{
cancellationHelper.ThrowIOOperationAborted();
}
}
WinIOError(afsar._errorCode);
}
// Number of buffer written is afsar._numBytes.
return;
}
[SecuritySafeCritical]
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckReadOperations();
if (!_isAsync)
{
return base.ReadAsync(buffer, offset, count, cancellationToken);
}
ReadWriteAsyncParams state = new ReadWriteAsyncParams(buffer, offset, count, cancellationToken);
return Task.Factory.FromAsync<int>(BeginRead, EndRead, state);
}
[SecuritySafeCritical]
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckWriteOperations();
if (!_isAsync)
{
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
ReadWriteAsyncParams state = new ReadWriteAsyncParams(buffer, offset, count, cancellationToken);
return Task.Factory.FromAsync(BeginWrite, EndWrite, state);
}
[SecurityCritical]
private unsafe int ReadFileNative(SafePipeHandle handle, byte[] buffer, int offset, int count,
NativeOverlapped* overlapped, out int errorCode)
{
Debug.Assert(handle != null, "handle is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to ReadFileNative.");
Debug.Assert(buffer.Length - offset >= count, "offset + count >= buffer length");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int r = 0;
int numBytesRead = 0;
fixed (byte* p = buffer)
{
if (_isAsync)
{
r = Interop.mincore.ReadFile(handle, p + offset, count, IntPtr.Zero, overlapped);
}
else
{
r = Interop.mincore.ReadFile(handle, p + offset, count, out numBytesRead, IntPtr.Zero);
}
}
if (r == 0)
{
// We should never silently swallow an error here without some
// extra work. We must make sure that BeginReadCore won't return an
// IAsyncResult that will cause EndRead to block, since the OS won't
// call AsyncPSCallback for us.
errorCode = Marshal.GetLastWin32Error();
// In message mode, the ReadFile can inform us that there is more data to come.
if (errorCode == Interop.mincore.Errors.ERROR_MORE_DATA)
{
return numBytesRead;
}
return -1;
}
else
{
errorCode = 0;
}
return numBytesRead;
}
[SecurityCritical]
private unsafe int WriteFileNative(SafePipeHandle handle, byte[] buffer, int offset, int count,
NativeOverlapped* overlapped, out int errorCode)
{
Debug.Assert(handle != null, "handle is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to WriteFileNative.");
Debug.Assert(buffer.Length - offset >= count, "offset + count >= buffer length");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int numBytesWritten = 0;
int r = 0;
fixed (byte* p = buffer)
{
if (_isAsync)
{
r = Interop.mincore.WriteFile(handle, p + offset, count, IntPtr.Zero, overlapped);
}
else
{
r = Interop.mincore.WriteFile(handle, p + offset, count, out numBytesWritten, IntPtr.Zero);
}
}
if (r == 0)
{
// We should never silently swallow an error here without some
// extra work. We must make sure that BeginWriteCore won't return an
// IAsyncResult that will cause EndWrite to block, since the OS won't
// call AsyncPSCallback for us.
errorCode = Marshal.GetLastWin32Error();
return -1;
}
else
{
errorCode = 0;
}
return numBytesWritten;
}
[SecurityCritical]
private IAsyncResult BeginRead(AsyncCallback callback, Object state)
{
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
Debug.Assert(readWriteParams != null);
byte[] buffer = readWriteParams.Buffer;
int offset = readWriteParams.Offset;
int count = readWriteParams.Count;
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!CanRead)
{
throw __Error.GetReadNotSupported();
}
CheckReadOperations();
if (!_isAsync)
{
// special case when this is called for sync broken pipes because otherwise Stream's
// Begin/EndRead hang. Reads return 0 bytes in this case so we can call the user's
// callback immediately
if (_state == PipeState.Broken)
{
PipeStreamAsyncResult asyncResult = new PipeStreamAsyncResult();
asyncResult._handle = _handle;
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
asyncResult._isWrite = false;
asyncResult.CallUserCallback();
return asyncResult;
}
else
{
return _streamAsyncHelper.BeginRead(buffer, offset, count, callback, state);
}
}
else
{
return BeginReadCore(buffer, offset, count, callback, state);
}
}
[SecurityCritical]
unsafe private PipeStreamAsyncResult BeginReadCore(byte[] buffer, int offset, int count,
AsyncCallback callback, Object state)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanRead, "can't read");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert(_isAsync, "BeginReadCore doesn't work on synchronous file streams!");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
// Create and store async stream class library specific data in the async result
PipeStreamAsyncResult asyncResult = new PipeStreamAsyncResult();
asyncResult._handle = _handle;
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
asyncResult._isWrite = false;
// handle zero-length buffers separately; fixed keyword ReadFileNative doesn't like
// 0-length buffers. Call user callback and we're done
if (buffer.Length == 0)
{
asyncResult.CallUserCallback();
}
else
{
// For Synchronous IO, I could go with either a userCallback and using
// the managed Monitor class, or I could create a handle and wait on it.
ManualResetEvent waitHandle = new ManualResetEvent(false);
asyncResult._waitHandle = waitHandle;
NativeOverlapped* intOverlapped = _threadPoolBinding.AllocateNativeOverlapped(s_IOCallback, asyncResult, buffer);
asyncResult._overlapped = intOverlapped;
// Queue an async ReadFile operation and pass in a packed overlapped
int errorCode = 0;
int r = ReadFileNative(_handle, buffer, offset, count, intOverlapped, out errorCode);
// ReadFile, the OS version, will return 0 on failure, but this ReadFileNative wrapper
// returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer read back from this call
// when using overlapped structures! You must not pass in a non-null lpNumBytesRead to
// ReadFile when using overlapped structures! This is by design NT behavior.
if (r == -1)
{
// One side has closed its handle or server disconnected. Set the state to Broken
// and do some cleanup work
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED)
{
State = PipeState.Broken;
// Clear the overlapped status bit for this special case. Failure to do so looks
// like we are freeing a pending overlapped.
intOverlapped->InternalLow = IntPtr.Zero;
// EndRead will free the Overlapped struct
asyncResult.CallUserCallback();
}
else if (errorCode != Interop.mincore.Errors.ERROR_IO_PENDING)
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
if (readWriteParams != null)
{
if (readWriteParams.CancellationHelper != null)
{
readWriteParams.CancellationHelper.AllowCancellation(_handle, intOverlapped);
}
}
}
return asyncResult;
}
[SecurityCritical]
private unsafe int EndRead(IAsyncResult asyncResult)
{
// There are 3 significantly different IAsyncResults we'll accept
// here. One is from Stream::BeginRead. The other two are variations
// on our PipeStreamAsyncResult. One is from BeginReadCore,
// while the other is from the BeginRead buffering wrapper.
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
if (!_isAsync)
{
return _streamAsyncHelper.EndRead(asyncResult);
}
PipeStreamAsyncResult afsar = asyncResult as PipeStreamAsyncResult;
if (afsar == null || afsar._isWrite)
{
throw __Error.GetWrongAsyncResult();
}
// Ensure we can't get into any races by doing an interlocked
// CompareExchange here. Avoids corrupting memory via freeing the
// NativeOverlapped class or GCHandle twice.
if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
{
throw __Error.GetEndReadCalledTwice();
}
ReadWriteAsyncParams readWriteParams = asyncResult.AsyncState as ReadWriteAsyncParams;
IOCancellationHelper cancellationHelper = null;
if (readWriteParams != null)
{
cancellationHelper = readWriteParams.CancellationHelper;
if (cancellationHelper != null)
{
readWriteParams.CancellationHelper.SetOperationCompleted();
}
}
// Obtain the WaitHandle, but don't use public property in case we
// delay initialize the manual reset event in the future.
WaitHandle wh = afsar._waitHandle;
if (wh != null)
{
// We must block to ensure that AsyncPSCallback has completed,
// and we should close the WaitHandle in here. AsyncPSCallback
// and the hand-ported imitation version in COMThreadPool.cpp
// are the only places that set this event.
using (wh)
{
wh.WaitOne();
Debug.Assert(afsar._isComplete == true,
"FileStream::EndRead - AsyncPSCallback didn't set _isComplete to true!");
}
}
// Free memory & GC handles.
NativeOverlapped* overlappedPtr = afsar._overlapped;
if (overlappedPtr != null)
{
_threadPoolBinding.FreeNativeOverlapped(overlappedPtr);
}
// Now check for any error during the read.
if (afsar._errorCode != 0)
{
if (afsar._errorCode == Interop.mincore.Errors.ERROR_OPERATION_ABORTED)
{
if (cancellationHelper != null)
{
cancellationHelper.ThrowIOOperationAborted();
}
}
WinIOError(afsar._errorCode);
}
// set message complete to true if the pipe is broken as well; need this to signal to readers
// to stop reading
_isMessageComplete = _state == PipeState.Broken ||
afsar._isMessageComplete;
return afsar._numBytes;
}
[SecurityCritical]
internal static Interop.mincore.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability)
{
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES);
if ((inheritability & HandleInheritability.Inheritable) != 0)
{
secAttrs = new Interop.mincore.SECURITY_ATTRIBUTES();
secAttrs.nLength = (uint)Marshal.SizeOf(secAttrs);
secAttrs.bInheritHandle = true;
}
return secAttrs;
}
// When doing IO asynchronously (i.e., _isAsync==true), this callback is
// called by a free thread in the threadpool when the IO operation
// completes.
[SecurityCritical]
unsafe private static void AsyncPSCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
{
// Extract async result from overlapped
PipeStreamAsyncResult asyncResult = (PipeStreamAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped);
asyncResult._numBytes = (int)numBytes;
// Allow async read to finish
if (!asyncResult._isWrite)
{
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED ||
errorCode == Interop.mincore.Errors.ERROR_NO_DATA)
{
errorCode = 0;
numBytes = 0;
}
}
// For message type buffer.
if (errorCode == Interop.mincore.Errors.ERROR_MORE_DATA)
{
errorCode = 0;
asyncResult._isMessageComplete = false;
}
else
{
asyncResult._isMessageComplete = true;
}
asyncResult._errorCode = (int)errorCode;
// Call the user-provided callback. It can and often should
// call EndRead or EndWrite. There's no reason to use an async
// delegate here - we're already on a threadpool thread.
// IAsyncResult's completedSynchronously property must return
// false here, saying the user callback was called on another thread.
asyncResult._completedSynchronously = false;
asyncResult._isComplete = true;
// The OS does not signal this event. We must do it ourselves.
ManualResetEvent wh = asyncResult._waitHandle;
if (wh != null)
{
Debug.Assert(!wh.GetSafeWaitHandle().IsClosed, "ManualResetEvent already closed!");
bool r = wh.Set();
Debug.Assert(r, "ManualResetEvent::Set failed!");
if (!r)
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
AsyncCallback callback = asyncResult._userCallback;
if (callback != null)
{
callback(asyncResult);
}
}
/// <summary>
/// Determine pipe read mode from Win32
/// </summary>
[SecurityCritical]
private void UpdateReadMode()
{
int flags;
if (!Interop.mincore.GetNamedPipeHandleState(SafePipeHandle, out flags, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero, IntPtr.Zero, 0))
{
WinIOError(Marshal.GetLastWin32Error());
}
if ((flags & Interop.mincore.PipeOptions.PIPE_READMODE_MESSAGE) != 0)
{
_readMode = PipeTransmissionMode.Message;
}
else
{
_readMode = PipeTransmissionMode.Byte;
}
}
/// <summary>
/// Filter out all pipe related errors and do some cleanup before calling __Error.WinIOError.
/// </summary>
/// <param name="errorCode"></param>
[SecurityCritical]
internal void WinIOError(int errorCode)
{
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED ||
errorCode == Interop.mincore.Errors.ERROR_NO_DATA
)
{
// Other side has broken the connection
_state = PipeState.Broken;
throw new IOException(SR.IO_PipeBroken, Win32Marshal.MakeHRFromErrorCode(errorCode));
}
else if (errorCode == Interop.mincore.Errors.ERROR_HANDLE_EOF)
{
throw __Error.GetEndOfFile();
}
else
{
// For invalid handles, detect the error and mark our handle
// as invalid to give slightly better error messages. Also
// help ensure we avoid handle recycling bugs.
if (errorCode == Interop.mincore.Errors.ERROR_INVALID_HANDLE)
{
_handle.SetHandleAsInvalid();
_state = PipeState.Broken;
}
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.ServiceModel;
using System.IO;
using System.ComponentModel;
using System.Globalization;
namespace Microsoft.Protocols.TestTools.StackSdk
{
/// <summary>
/// This class acts as an proxy to control a remote SUT.
/// It provides methods to start a process on the SUT, in both sync and async way.
/// It also provides methods to query or kill an SUT process.
/// Note:
/// 1. To make this proxy work, an SUT control service must has been
/// installed and started on the target remote SUT machine.
/// 2. No authentication is needed to control the remote SUT.
/// Any application on any machine that knows this service can manipulate
/// any process on the controlled machine. This unsafe service is designed
/// only for protocol test use, restricted in an isolated private network.
/// </summary>
public class SutControlProxy
{
#region constant variables
/// <summary>
/// SUT control service address has WCF net.tcp binding format:
/// "net.tcp://{address}:{port}/SutControlService/", for example
/// "net.tcp://sut01:8000/SutControlService/".
/// configured in address attribute of endpoint element in
/// SUT control service's App.config file.
/// </summary>
private const string ServiceAddressFormat = "net.tcp://{0}:{1}/SutControlService/";
/// <summary>
/// 8000 is the default value of SUT control service port,
/// configured in address attribute of endpoint element in
/// SUT control service's App.config file.
/// </summary>
private const uint DefaultServicePort = 8000;
#endregion
#region private variables
/// <summary>
/// The SUT control service's local stub.
/// </summary>
private ISutControlService service;
#endregion
#region constructors
/// <summary>
/// Constructor of SutControlProxy with default port 8000.
/// </summary>
/// <param name="sutAddress">the address of the SUT,
/// can be either IP address or computer name.
/// </param>
/// <exception cref="ArgumentNullException">sutAddress is null</exception>
public SutControlProxy(string sutAddress)
: this(sutAddress, DefaultServicePort)
{
}
/// <summary>
/// Constructor of SutControlProxy.
/// </summary>
/// <param name="sutAddress">the address of the SUT,
/// can be either IP address or computer name.
/// </param>
/// <param name="port">the port on SUT machine to provide SUT control service.</param>
/// <exception cref="ArgumentNullException">sutAddress is null</exception>
public SutControlProxy(string sutAddress, uint port)
{
AssertIsNotNull("sutAddress", sutAddress);
InitializeLogger();
#region logging
Info("Construct SutControlProxy, address={0}, port={1}.", sutAddress, port);
#endregion
// SUT control service address
string sutControlServiceAddress = string.Format(CultureInfo.InvariantCulture, ServiceAddressFormat, sutAddress, port);
EndpointAddress endpointAddress = new EndpointAddress(sutControlServiceAddress);
// channel factory
NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
ChannelFactory<ISutControlService> factory = new ChannelFactory<ISutControlService>(binding);
// create service channel
service = factory.CreateChannel(endpointAddress);
}
/// <summary>
/// Constructor of SutControlProxy, used in unit test
/// or in case caller has obtained an ISutControlService instance.
/// </summary>
/// <param name="service">service that implemented ISutControlService interface.</param>
/// <exception cref="ArgumentNullException">service is null</exception>
public SutControlProxy(ISutControlService service)
{
InitializeLogger();
#region assert
AssertIsNotNull("service", service);
#endregion
this.service = service;
}
#endregion
#region public methods
/// <summary>
/// Start a process on SUT.
/// This method executes asynchronously. After calling this method,
/// please wait and call <seealso cref="GetExecutionResults"/> method to check the status.
/// </summary>
/// <param name="command">the process's filename to start with.
/// The filename must be of executable file type.
/// The filename can use an absolute path, or relative path,
/// or without path if the path has been defined in SUT's "PATH" environment variable.
/// In any of above case, the ".exe" extension can be ignored.
/// <example>
/// "c:\windows\system32\cmd.exe";
/// "cmd.exe";
/// "cmd";
/// "..\myApp.exe"
/// "..\myApp"
/// </example>
/// </param>
/// <param name="arguments">process specified command-line arguments</param>
/// <returns>processId, the unique identifier for the process</returns>
/// <exception cref="ArgumentNullException">command is null</exception>
/// <exception cref="FileNotFoundException">command, as a file name, is not found on SUT machine.</exception>
public int StartProcess(
string command,
string arguments)
{
return StartProcessInternal(command, arguments, null, null, null);
}
/// <summary>
/// Start a process on SUT using specified domain\userName password.
/// This method executes asynchronously. After calling this method,
/// please wait and call <seealso cref="GetExecutionResults"/> method to check the status.
/// </summary>
/// <param name="command">the process's filename to start with.
/// The filename must be of executable file type.
/// The filename can use an absolute path, or relative path,
/// or without path if the path has been defined in SUT's "PATH" environment variable.
/// In any of above case, the ".exe" extension can be ignored.
/// <example>
/// "c:\windows\system32\cmd.exe";
/// "cmd.exe";
/// "cmd";
/// "..\myApp.exe"
/// "..\myApp"
/// </example>
/// </param>
/// <param name="arguments">process specified command-line arguments</param>
/// <param name="userName">user name to start process with.</param>
/// <param name="password">password to start process with.</param>
/// <param name="domain">domain to start process with.</param>
/// <returns>processId, the unique identifier for the process</returns>
/// <exception cref="ArgumentNullException">
/// command is null, or userName is null, or password is null, or domain is null.
/// </exception>
/// <exception cref="FileNotFoundException">command, as a file name, is not found on SUT machine.</exception>
public int StartProcess(
string command,
string arguments,
string userName,
string password,
string domain)
{
ValidateCredential(userName, password, domain);
return StartProcessInternal(command, arguments, userName, password, domain);
}
/// <summary>
/// Start a process on SUT, wait for the process exit and return its results.
/// This method executes synchronously, blocks current thread till process exits or timeouts.
/// </summary>
/// <param name="command">the process's filename to start with.
/// The filename must be of executable file type.
/// The filename can use an absolute path, or relative path,
/// or without path if the path has been defined in SUT's "PATH" environment variable.
/// In any of above case, the ".exe" extension can be ignored.
/// <example>
/// "c:\windows\system32\cmd.exe";
/// "cmd.exe";
/// "cmd";
/// "..\myApp.exe"
/// "..\myApp"
/// </example>
/// </param>
/// <param name="arguments">process specified command-line arguments</param>
/// <param name="timeout">if the process doesn't exit after waiting specified time span,
/// a TimeoutException is thrown.
/// timeout should either be
/// (1) TimeSpan.MaxValue which presents infinity, or
/// (2) its total milliseconds is greater than 0 and less than or equals to Int32.MaxValue. </param>
/// <param name="exitCode">exit code of the process</param>
/// <param name="standardOutput">
/// content that the process generates to the standard output stream.
/// Empty string returns if no content generated.</param>
/// <param name="standardError">
/// content that the process generates to the standard error stream.
/// Empty string returns if no content generated.</param>
/// <returns>processId, the unique identifier for the process</returns>
/// <exception cref="ArgumentNullException">command is null</exception>
/// <exception cref="FileNotFoundException">command, as a file name, is not found on SUT machine.</exception>
/// <exception cref="TimeoutException">
/// Process doesn't exit after waiting as long as timeout specified.
/// </exception>
public int StartProcessWaitForExit(
string command,
string arguments,
TimeSpan timeout,
out int exitCode,
out string standardOutput,
out string standardError)
{
return StartProcessWaitForExitInternal(command, arguments, null, null, null,
timeout, out exitCode, out standardOutput, out standardError);
}
/// <summary>
/// Start a process on SUT using specified domain\userName password,
/// wait for the process exit and return its results.
/// This method executes synchronously, blocks current thread till process exits or timeouts.
/// </summary>
/// <param name="command">the process's filename to start with.
/// The filename must be of executable file type.
/// The filename can use an absolute path, or relative path,
/// or without path if the path has been defined in SUT's "PATH" environment variable.
/// In any of above case, the ".exe" extension can be ignored.
/// <example>
/// "c:\windows\system32\cmd.exe";
/// "cmd.exe";
/// "cmd";
/// "..\myApp.exe"
/// "..\myApp"
/// </example>
/// </param>
/// <param name="arguments">process specified command-line arguments</param>
/// <param name="userName">user name to start process with.</param>
/// <param name="password">password to start process with.</param>
/// <param name="domain">domain to start process with.</param>
/// <param name="timeout">if the process doesn't exit after waiting specified time span,
/// a TimeoutException is thrown.
/// timeout should either be
/// (1) TimeSpan.MaxValue which presents infinity, or
/// (2) its total milliseconds is greater than 0 and less than or equals to Int32.MaxValue. </param>
/// <param name="exitCode">exit code of the process</param>
/// <param name="standardOutput">
/// content that the process generates to the standard output stream.
/// Empty string returns if no content generated.</param>
/// <param name="standardError">
/// content that the process generates to the standard error stream.
/// Empty string returns if no content generated.</param>
/// <returns>processId, the unique identifier for the process</returns>
/// <exception cref="ArgumentNullException">
/// command is null, or userName is null, or password is null, or domain is null.
/// </exception>
/// <exception cref="FileNotFoundException">command, as a file name, is not found on SUT machine.</exception>
/// <exception cref="TimeoutException">
/// Process doesn't exit after waiting as long as timeout specified.
/// </exception>
public int StartProcessWaitForExit(
string command,
string arguments,
string userName,
string password,
string domain,
TimeSpan timeout,
out int exitCode,
out string standardOutput,
out string standardError)
{
ValidateCredential(userName, password, domain);
return StartProcessWaitForExitInternal(command, arguments, userName, password, domain,
timeout, out exitCode, out standardOutput, out standardError);
}
/// <summary>
/// Get execution results of the process specified by processId
/// This method executes asynchronously.
/// If the process has exited, this method returns true, with valid exitCode.
/// If the process is still running, this method returns false.
/// standardOutput and standardError will always been output
/// as long as process outputs stream, no matter the process is running or exited.
/// </summary>
/// <param name="processId">the unique identifier for the process</param>
/// <param name="exitCode">exit code of the process if process has exited.
/// Note: if this method returns false, this parameter is assigned zero
/// which means process has not exited, thus has not provided exit code yet.</param>
/// <param name="standardOutput">
/// content that the process generates to the standard output stream,
/// since last query time.
/// Empty string returns if no content generated.</param>
/// <param name="standardError">
/// content that the process generates to the standard error stream,
/// since last query time.
/// Empty string returns if no content generated.</param>
/// <returns>true if process has exited, otherwise returns false.</returns>
/// <exception cref="FaultException" >
/// FaultException is thrown by SutControlService to indicate errors on SUT machine.
/// It encapsulate the details in ExceptionDetail, such as exception type, message and stack trace.
/// If you want to catch and analyze it, here's example:
///
/// catch (FaultException faultException)
/// {
/// if (faultException.Detail.Type == typeof(InvalidOperationException).FullName)
/// {
///
/// throw new InvalidOperationException();
/// }
/// }
/// </exception>
public bool GetExecutionResults(
int processId,
out int exitCode,
out string standardOutput,
out string standardError)
{
#region logging
Info("GetExecutionResults, processId={0}", processId);
#endregion
return service.GetExecutionResults(processId, out exitCode, out standardOutput, out standardError);
}
/// <summary>
/// Kill the process specified by processId.
/// Perform no action if the process has already exited.
/// This method executes synchronously, blocks current thread till process exits or timeouts.
/// </summary>
/// <param name="processId">the unique identifier for the process</param>
/// <param name="timeout">if the process doesn't exit after waiting specified time span,
/// a TimeoutException is thrown.
/// timeout should either be
/// (1) TimeSpan.MaxValue which presents infinity, or
/// (2) its total milliseconds is greater than 0 and less than or equals to Int32.MaxValue.
/// </param>
/// <exception cref="FaultException" >
/// FaultException is thrown by SutControlService to indicate errors on SUT machine.
/// It encapsulate the details in ExceptionDetail, such as exception type, message and stack trace.
/// If you want to catch and analyze it, here's example:
///
/// catch (FaultException faultException)
/// {
/// if (faultException.Detail.Type == typeof(InvalidOperationException).FullName)
/// {
///
/// throw new InvalidOperationException();
/// }
/// }
/// </exception>
public void KillProcess(int processId, TimeSpan timeout)
{
#region logging
Info("GetExecutionResults, processId={0}", processId);
#endregion
ValidateTimeout(timeout);
service.KillProcess(processId, timeout);
}
/// <summary>
/// Clear information proxy collected for process of specified processId,
/// so the unused memory can be recycled.
/// After calling this method, the processId is disposed and not valid to use any more.
/// It's safe to call this method more than once.
/// </summary>
/// <param name="processId">the unused process Id</param>
public void ClearProcess(int processId)
{
service.ClearProcess(processId);
}
#endregion
#region private methods
/// <summary>
/// Initialize Logger used in this proxy.
/// </summary>
private void InitializeLogger()
{
// to pass FxCop, initialize logger, set configId "stack".
//logger = new Logger(new LogConfig("SutControlProxyLog", "stack"));
}
/// <summary>
/// Write Debug level log.
/// </summary>
/// <param name="message">message to be logged, can be "xxx {0} {1} xxx" format.</param>
/// <param name="args">arguments formatted into message.</param>
private void Debug(string message, params object[] args)
{
// remain this interface for furture use.
// to avoid fxcop warning CA1801 (argument not used),
// add following line:
Console.WriteLine(message, args);
}
/// <summary>
/// Write Info level log.
/// </summary>
/// <param name="message">message to be logged, can be "xxx {0} {1} xxx" format.</param>
/// <param name="args">arguments formatted into message.</param>
private void Info(string message, params object[] args)
{
// remain this interface for furture use.
// to avoid fxcop warning CA1801 (argument not used),
// add following line:
Console.WriteLine(message, args);
}
/// <summary>
/// If object is null, throw ArgumentNullException.
/// </summary>
/// <param name="objectName">name of the checked object.</param>
/// <param name="value">object value to be checked.</param>
/// <exception cref="ArgumentNullException">object value is null.</exception>
private void AssertIsNotNull(string objectName, object value)
{
if (value == null)
{
throw new ArgumentNullException(objectName);
}
}
/// <summary>
/// Validate command, assert it is not null.
/// </summary>
/// <param name="command">command file name</param>
/// <exception cref="ArgumentNullException">command is null</exception>
private void ValidateCommand(string command)
{
#region assert
AssertIsNotNull("command", command);
#endregion
#region logging
Info("ValidateCommand, command={0}", command);
#endregion
}
/// <summary>
/// Validate userName, password and domain, assert any of them is not null.
/// </summary>
/// <param name="userName">userName on SUT machine</param>
/// <param name="password">password on SUT machine</param>
/// <param name="domain">domain on SUT machine</param>
/// <exception cref="ArgumentNullException">userName is null, or password is null, or domain is null.</exception>
private void ValidateCredential(string userName, string password, string domain)
{
#region assert
AssertIsNotNull("userName", userName);
AssertIsNotNull("password", password);
AssertIsNotNull("domain", domain);
#endregion
#region logging
// sensitive information must be output only in debug.
Debug("ValidateCredential, userName={0}, password={1}, domain={2}", userName, password, domain);
#endregion
}
/// <summary>
/// timeout should either be
/// (1) TimeSpan.MaxValue which presents infinity, or
/// (2) its total milliseconds is greater than 0 and less than or equals to or equals to Int32.MaxValue.
/// </summary>
/// <param name="timeout">timeout waiting for process exit.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// throw if timeout is less than zero
/// </exception>
private void ValidateTimeout(TimeSpan timeout)
{
if (timeout == TimeSpan.MaxValue)
{
#region logging
// TimeSpan.MaxValue is a special value which presents infinity,
// so we don't output its exact year, month, day, hour...
Info("ValidateTimeout timeout=TimeSpan.MaxValue");
#endregion
return;
}
#region logging
// TimeSpan.MaxValue is a special value, meaning infinite timeout.
// so we don't output its exact year, month, day, hour...
Info("ValidateTimeout timeout={0}", timeout);
#endregion
int timeoutMillis = (int)timeout.TotalMilliseconds;
#region assert
if (timeoutMillis < 0)
{
throw new ArgumentOutOfRangeException("timeout",
timeout,
"timeout should either be"
+ "(1) TimeSpan.MaxValue, or"
+ "(2) its total milliseconds is greater than 0 and less than or equals to Int32.MaxValue.");
}
#endregion
}
/// <summary>
/// Start a process on SUT using specified domain\userName password.
/// This method executes asynchronously. After calling this method,
/// please wait and call <seealso cref="GetExecutionResults"/> method to check the status.
/// </summary>
/// <param name="command">the process's filename to start with.
/// The filename must be of executable file type.
/// The filename can use an absolute path, or relative path,
/// or without path if the path has been defined in SUT's "PATH" environment variable.
/// In any of above case, the ".exe" extension can be ignored.
/// <example>
/// "c:\windows\system32\cmd.exe";
/// "cmd.exe";
/// "cmd";
/// "..\myApp.exe"
/// "..\myApp"
/// </example>
/// </param>
/// <param name="arguments">process specified command-line arguments</param>
/// <param name="userName">user name to start process with.</param>
/// <param name="password">password to start process with.</param>
/// <param name="domain">domain to start process with.</param>
/// <returns>processId, the unique identifier for the process</returns>
/// <exception cref="FaultException" >
/// FaultException is thrown by SutControlService to indicate errors on SUT machine.
/// It encapsulates the details in ExceptionDetail, such as exception type, message and stack trace.
/// If you want to catch and analyze it, here's example:
///
/// catch (FaultException faultException)
/// {
/// if (faultException.Detail.Type == typeof(InvalidOperationException).FullName)
/// {
/// throw new InvalidOperationException();
/// }
/// }
/// </exception>
private int StartProcessInternal(
string command,
string arguments,
string userName,
string password,
string domain)
{
ValidateCommand(command);
#region logging
Info("StartProcess, arguments='{0}'", (arguments == null ? "" : arguments));
#endregion
int processId = service.StartProcess(command, arguments, userName, password, domain);
#region logging
Info("StartProcess, returned processId={0}", processId);
#endregion
return processId;
}
/// <summary>
/// Start a process on SUT using specified domain\userName password,
/// wait for the process exit and return its results.
/// This method executes synchronously, blocks current thread till process exits or timeouts.
/// </summary>
/// <param name="command">the process's filename to start with.
/// The filename must be one of the executable file types.
/// The filename can use an absolute path, or relative path,
/// or without path if the path has been defined in SUT's "PATH" environment variable.
/// In any of above case, the ".exe" extension can be ignored.
/// <example>
/// "c:\windows\system32\cmd.exe";
/// "cmd.exe";
/// "cmd";
/// "..\myApp.exe"
/// "..\myApp"
/// </example>
/// </param>
/// <param name="arguments">process specified command-line arguments</param>
/// <param name="userName">user name to start process with.</param>
/// <param name="password">password to start process with.</param>
/// <param name="domain">domain to start process with.</param>
/// <param name="timeout">if the process doesn't exit after waiting specified time span,
/// a TimeoutException is thrown.
/// timeout should either be
/// (1) TimeSpan.MaxValue which presents infinity, or
/// (2) its total milliseconds is greater than 0 and less than or equals to Int32.MaxValue. </param>
/// <param name="exitCode">exit code of the process</param>
/// <param name="standardOutput">
/// content that the process generates to the standard output stream.
/// Empty string returns if no content generated.</param>
/// <param name="standardError">
/// content that the process generates to the standard error stream.
/// Empty string returns if no content generated.</param>
/// <returns>processId, the unique identifier for the process</returns>
/// <exception cref="FaultException" >
/// FaultException is thrown by SutControlService to indicate errors on SUT machine.
/// It encapsulate the details in ExceptionDetail, such as exception type, message and stack trace.
/// If you want to catch and analyze it, here's example:
///
/// catch (FaultException faultException)
/// {
/// if (faultException.Detail.Type == typeof(InvalidOperationException).FullName)
/// {
/// throw new InvalidOperationException();
/// }
/// }
/// </exception>
private int StartProcessWaitForExitInternal(
string command,
string arguments,
string userName,
string password,
string domain,
TimeSpan timeout,
out int exitCode,
out string standardOutput,
out string standardError)
{
ValidateCommand(command);
ValidateTimeout(timeout);
int processId = service.StartProcessWaitForExit(command, arguments, userName, password, domain, timeout,
out exitCode, out standardOutput, out standardError);
#region logging
Info("StartProcessWaitForExit, returned processId={0}", processId);
#endregion
return processId;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using SI.Mobile.RPMSGViewer.Lib;
using IOPath = System.IO.Path;
#if __ANDROID__
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using SI.Mobile.RPMSGViewer.android;
#endif
#if __IOS__
using Foundation;
using UIKit;
#endif
namespace SI.Mobile.RPMSGViewer.Lib
{
public static class AppUtils
{
private const string HTML_BODY_START_TAG = "<(?i)body.*?>";
private const string HTML_BODY_END_TAG = "</(?i)body>";
private const string HTML_HEAD_START_TAG = "<(?i)head.*?>";
#if __ANDROID__
static public Context ApplicationContext { get; set; }
#endif
#if __IOS__
public static NSUserDefaults GetSharedUserDefaults()
{
return new NSUserDefaults("group.com.secureislands.mobile.keyboard", NSUserDefaultsType.SuiteName);
}
#endif
static public bool IsTablet
{
get
{
#if __IOS__
string deviceModel = UIDevice.CurrentDevice.Model;
return deviceModel.StartsWith("iPad", StringComparison.InvariantCultureIgnoreCase);
#endif
#if __ANDROID__
return ApplicationContext.Resources.GetBoolean(Resource.Boolean.IsTablet);
#endif
}
}
public static string GetErrorPage(string title, string details)
{
return ReadResourceFile(SIConstants.ERROR_PAGE_FILE_PATH).Replace("#ERROR_TITLE#", title).
Replace("#ERROR_DETAILS#", details);
}
public static string GetDefaultPage(bool landscapeMode = false)
{
string welcomeImg;
if (IsTablet)
welcomeImg = landscapeMode ? "welcome_landscape" : "welcome_portrait";
else
welcomeImg = "welcome_phone";
return ReadResourceFile(SIConstants.DEFAULT_PAGE_FILE_PATH).Replace("[WELCOME_SCREEN]", welcomeImg);
}
#if __IOS__
public static string GetDefaultPage(UIInterfaceOrientation orientation)
{
bool landscapeMode = orientation == UIInterfaceOrientation.LandscapeLeft || orientation == UIInterfaceOrientation.LandscapeRight;
return GetDefaultPage(landscapeMode);
}
#endif
public static string GetLoadingPage()
{
return ReadResourceFile(SIConstants.LOADING_PAGE_FILE_PATH).Replace("#TITLE#", "Processing File");
}
public static string GetAboutPage()
{
return ReadResourceFile(SIConstants.ABOUT_PAGE_FILE_PATH);
}
public static string ReadResourceFile(string path)
{
#if __IOS__
return File.ReadAllText(path);
#endif
#if __ANDROID__
return ApplicationContext.Assets.Open(path).ToString(Encoding.UTF8);
#endif
}
public static string GeneratePermissionsHtml(string htmlContent, EndUserLicense eul)
{
List<string> permissions = new List<string>();
if (eul._Rights.Extract)
permissions.Add("Extract");
if (eul._Rights.Forward)
permissions.Add("Forward");
if (eul._Rights.Reply)
permissions.Add("Reply");
if (eul._Rights.ReplyAll)
permissions.Add("Reply All");
if (eul._Rights.Print)
permissions.Add("Print");
string permissionList = "";
foreach (string permission in permissions)
{
permissionList += "<li>" + permission + "</li>";
}
return htmlContent
.Replace("[TEMPLATE_NAME]", eul.TemplateName)
.Replace("[DESCRIPTION]", eul.Description)
.Replace("[ISSUED_TO]", eul.IssuedTo)
.Replace("[OWNER]", eul.Owner)
.Replace("[RMS_RIGHTS]", permissionList);
}
public static void LoadImagesInHtml(DRMContent data)
{
string result = data.HTMLBody;
List<RpmsgAttachment> notEmbeddedAttachments = new List<RpmsgAttachment>();
try
{
foreach (RpmsgAttachment attachment in data.Attachments)
{
if (attachment.ContentID == null || !result.Contains(attachment.ContentID))
{
notEmbeddedAttachments.Add(attachment);
continue;
}
string imgPath = IOPath.Combine(IOPath.GetTempPath(), Guid.NewGuid() + attachment.Name);
File.WriteAllBytes(imgPath, attachment.Content);
result = result.Replace("cid:" + attachment.ContentID, imgPath);
}
data.HTMLBody = result;
data.Attachments = notEmbeddedAttachments;
}
catch (Exception)
{
LogUtils.Log("Failed loading inline images for display");
}
}
public static string AddHtmlHeaderAndAttachments(DRMContent drmContent, EndUserLicense userLicense)
{
string html = EmbedHeadScriptsAndStyles(drmContent.HTMLBody, userLicense);
html = EmbedAttachments(html, drmContent, userLicense);
html = AddMailDetailsHeader(html, drmContent, userLicense);
return html;
}
private static string EmbedHeadScriptsAndStyles(string html, EndUserLicense userLicense)
{
string fixPositionScript = ReadResourceFile(IOPath.Combine(SIConstants.DEFAULT_RESOURCE_FOLDER, "MailHtml/FixPositionScript.txt"));
string restrictImagesWidthStyle = ReadResourceFile(IOPath.Combine(SIConstants.DEFAULT_RESOURCE_FOLDER, "MailHtml/RestrictImagesWidth.txt"));
string preventTextResize = ReadResourceFile(IOPath.Combine(SIConstants.DEFAULT_RESOURCE_FOLDER, "MailHtml/PreventTextResize.txt"));
string preventTextCopy = ReadResourceFile(IOPath.Combine(SIConstants.DEFAULT_RESOURCE_FOLDER, "MailHtml/PreventTextCopy.txt"));
string headStartTag = Regex.Match(html, HTML_HEAD_START_TAG).Value;
string styles = preventTextResize + restrictImagesWidthStyle;
if (userLicense._Rights.Extract == false)
styles += preventTextCopy;
string modifiedHtml = html.Replace(headStartTag, headStartTag + styles + fixPositionScript);
return modifiedHtml;
}
private static string EmbedAttachments(string html, DRMContent drmContent, EndUserLicense userLicense)
{
if (drmContent.Attachments == null)
return html;
string bodyEndTag = Regex.Match(html, HTML_BODY_END_TAG).Value;
string fixedDiv = "<div id=\"si_bottomFixed_10BF6356-9C77-4EE2-8A0F-B0F2BEFBC225\" style=\"position:relative; bottom:0px; left:0px\" >"; //the id of the div MUST be the same as the ID in the attachmentFixPositionScript
html = html.Replace(bodyEndTag, fixedDiv + bodyEndTag);
foreach (RpmsgAttachment att in drmContent.Attachments)
{
string base64AppIcon = null;
string base64ShareIcon = null;
#if __IOS__
UIImage appIcon = GetIconImageFromExtension(att.Extension);
base64AppIcon = appIcon.AsPNG().GetBase64EncodedString(NSDataBase64EncodingOptions.None);
UIImage shareIcon = UIImage.FromFile("MailHtml/Attachments/share.png");
base64ShareIcon = shareIcon.AsPNG().GetBase64EncodedString(NSDataBase64EncodingOptions.None);
#endif
#if __ANDROID__
Drawable appIcon = ApplicationContext.Resources.GetDrawable(Utils.GetIconIdFromExtension(att.Extension));
base64AppIcon = GetBase64EncodedFromDrawable(appIcon);
Drawable shareIcon = ApplicationContext.Resources.GetDrawable(Resource.Drawable.share);
base64ShareIcon = GetBase64EncodedFromDrawable(shareIcon);
#endif
html = html.Replace
(
bodyEndTag,
att.GetAttachmentHTML(base64AppIcon,base64ShareIcon) + bodyEndTag
);
}
return html.Replace(bodyEndTag, "</div>" + bodyEndTag);
}
#if __IOS__
static public UIImage GetIconImageFromExtension(string extension)
{
switch (extension)
{
case ".docx":
return UIImage.FromFile("MailHtml/Attachments/wordicon.png");
case ".pptx":
return UIImage.FromFile("MailHtml/Attachments/ppicon.png");
case ".xlsx":
return UIImage.FromFile("MailHtml/Attachments/excelicon.png");
case ".jpg":
return UIImage.FromFile("MailHtml/Attachments/jpgicon.png");
case ".png":
return UIImage.FromFile("MailHtml/Attachments/pngicon.png");
case ".pdf":
return UIImage.FromFile("MailHtml/Attachments/pdficon.png");
case ".txt":
return UIImage.FromFile("MailHtml/Attachments/txticon.png");
case ".zip":
return UIImage.FromFile("MailHtml/Attachments/zipicon.png");
case ".rpmsg":
return UIImage.FromFile("MailHtml/Attachments/rpmsgicon.png");
default:
return UIImage.FromFile("MailHtml/Attachments/defaulticon.png");
}
}
#endif
private static string AddMailDetailsHeader(string html, DRMContent drmContent, EndUserLicense userLicense)
{
if (userLicense._SIData == null)
return html;
string headerHtml = ReadResourceFile(IOPath.Combine(SIConstants.DEFAULT_RESOURCE_FOLDER, "MailHtml/Header/MailDetailsHeader.txt"));
string recipients = string.Join(", ", userLicense._SIData.ToNames);
if (userLicense._SIData.CCNames.Length > 0)
recipients += ", " + string.Join(", ", userLicense._SIData.CCNames);
bool noAttachments = drmContent.Attachments.Count == 0;
string base64AttachmentsIcon = null;
#if __IOS__
UIImage attachmentsIcon = UIImage.FromFile("MailHtml/Header/attachmentsIcon.png");
base64AttachmentsIcon = attachmentsIcon.AsPNG().GetBase64EncodedString(NSDataBase64EncodingOptions.None);
#endif
#if __ANDROID__
Drawable shareIcon = ApplicationContext.Resources.GetDrawable(Resource.Drawable.attachmentsIcon);
base64AttachmentsIcon = GetBase64EncodedFromDrawable(shareIcon);
#endif
string attachmentsHtml = noAttachments ? "" : drmContent.Attachments.Count +
"<img src=\"data:image/png;base64," + base64AttachmentsIcon + "\" alt=\"attachmentIcon\" style=\" height:0.9em; margin-top: 0.1em\" />";
headerHtml = headerHtml
.Replace("[MailSubject]", userLicense._SIData.Subject)
.Replace("[SenderName]", userLicense._SIData.SenderName)
.Replace("[SendTime]", userLicense._SIData.SendTime)
.Replace("[RecipientNames]", recipients)
.Replace("[AttachmentCount]", attachmentsHtml)
.Replace("[SenderInitial]", userLicense._SIData.SenderName.Trim().Substring(0, 1).ToUpper());
RpmsgClassification primaryClassification = userLicense._SIData.Classifications.Find(cls => cls.Color != null);
//there is no classification with color
if (primaryClassification == null && userLicense._SIData.Classifications.Count > 0)
{
//take the first dataclass
primaryClassification = userLicense._SIData.Classifications[0];
}
if (primaryClassification != null)
{
headerHtml = headerHtml.Replace ("<!--[ClassificationIndicator]-->", primaryClassification.GetClassificationHTML());
}
string bodyStartTag = Regex.Match(html, HTML_BODY_START_TAG).Value;
return html.Replace(bodyStartTag, bodyStartTag + headerHtml);
}
#if __ANDROID__
private static string GetBase64EncodedFromDrawable(Drawable drawable)
{
using (MemoryStream stream = new MemoryStream ())
{
((BitmapDrawable)drawable).Bitmap.Compress (Bitmap.CompressFormat.Png, 100, stream);
return Android.Util.Base64.EncodeToString (stream.ToArray (), Android.Util.Base64Flags.Default);
}
}
#endif
// workaround Xamarin bug https://bugzilla.xamarin.com/show_bug.cgi?id=30709
static Dictionary<Int32, Encoding> m_EncodingCache = new Dictionary<Int32, Encoding>();
public static Encoding GetEncoding(Int32 codepage)
{
if (m_EncodingCache.ContainsKey (codepage)) {
return m_EncodingCache [codepage];
}
Encoding encoding = Encoding.GetEncoding (codepage);
if (encoding == null)
encoding = Encoding.UTF8; // fallback to UTF8
m_EncodingCache [codepage] = encoding;
return encoding;
}
public static string GenerateClassificationLine(string dataclass)
{
return "<<Classification: \"" + dataclass + "\">>";
}
#if __IOS__
public static UIColor CreateColor(string hexColor)
{
try
{
hexColor = hexColor.Replace("#", "");
int red = Int32.Parse(hexColor.Substring(0, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
int green = Int32.Parse(hexColor.Substring(2, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
int blue = Int32.Parse(hexColor.Substring(4, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
return UIColor.FromRGB(red, green, blue);
}
catch
{
return UIColor.Gray;
}
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Newtonsoft.Json;
using NuGet.ContentModel;
using NuGet.Frameworks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class HarvestPackage : PackagingTask
{
/// <summary>
/// Package ID to harvest
/// </summary>
[Required]
public string PackageId { get; set; }
/// <summary>
/// Current package version.
/// </summary>
[Required]
public string PackageVersion { get; set; }
/// <summary>
/// Folder where packages have been restored
/// </summary>
[Required]
public string PackagesFolder { get; set; }
/// <summary>
/// Path to runtime.json that contains the runtime graph.
/// </summary>
[Required]
public string RuntimeFile { get; set; }
/// <summary>
/// Additional packages to consider for evaluating support but not harvesting assets.
/// Identity: Package ID
/// Version: Package version.
/// </summary>
public ITaskItem[] RuntimePackages { get; set; }
/// <summary>
/// Set to false to suppress harvesting of files and only harvest supported framework information.
/// </summary>
public bool HarvestAssets { get; set; }
/// <summary>
/// Set to partial paths to exclude from file harvesting.
/// </summary>
public string[] PathsToExclude { get; set; }
/// <summary>
/// Set to partial paths to suppress from both file and support harvesting.
/// </summary>
public string[] PathsToSuppress { get; set; }
/// <summary>
/// Frameworks to consider for support evaluation.
/// Identity: Framework
/// RuntimeIDs: Semi-colon seperated list of runtime IDs
/// </summary>
[Required]
public ITaskItem[] Frameworks { get; set; }
/// <summary>
/// Frameworks that were supported by previous package version.
/// Identity: Framework
/// Version: Assembly version if supported
/// </summary>
[Output]
public ITaskItem[] SupportedFrameworks { get; set; }
/// <summary>
/// Files harvested from previous package version.
/// Identity: path to file
/// AssemblyVersion: version of assembly
/// TargetFramework: target framework moniker to use for harvesting file's dependencies
/// TargetPath: path of file in package
/// IsReferenceAsset: true for files in Ref.
/// </summary>
[Output]
public ITaskItem[] Files { get; set; }
/// <summary>
/// Generates a table in markdown that lists the API version supported by
/// various packages at all levels of NETStandard.
/// </summary>
/// <returns></returns>
public override bool Execute()
{
if (!Directory.Exists(PackagesFolder))
{
Log.LogError($"PackagesFolder {PackagesFolder} does not exist.");
}
if (HasPackagesToHarvest())
{
if (HarvestAssets)
{
HarvestFilesFromPackage();
}
HarvestSupportedFrameworks();
}
return !Log.HasLoggedErrors;
}
private bool HasPackagesToHarvest()
{
bool result = true;
IEnumerable<string> packageDirs = new[] { Path.Combine(PackageId, PackageVersion) };
if (RuntimePackages != null)
{
packageDirs = packageDirs.Concat(
RuntimePackages.Select(p => Path.Combine(p.ItemSpec, p.GetMetadata("Version"))));
}
foreach (var packageDir in packageDirs)
{
var pathToPackage = Path.Combine(PackagesFolder, packageDir);
if (!Directory.Exists(pathToPackage))
{
Log.LogMessage($"Will not harvest files & support from package {packageDir} because {pathToPackage} does not exist.");
result = false;
}
}
return result;
}
private void HarvestSupportedFrameworks()
{
List<ITaskItem> supportedFrameworks = new List<ITaskItem>();
AggregateNuGetAssetResolver resolver = new AggregateNuGetAssetResolver(RuntimeFile);
string packagePath = Path.Combine(PackagesFolder, PackageId, PackageVersion);
// add the primary package
resolver.AddPackageItems(PackageId, GetPackageItems(packagePath));
if (RuntimePackages != null)
{
// add any split runtime packages
foreach (var runtimePackage in RuntimePackages)
{
var runtimePackageId = runtimePackage.ItemSpec;
var runtimePackageVersion = runtimePackage.GetMetadata("Version");
resolver.AddPackageItems(runtimePackageId, GetPackageItems(PackagesFolder, runtimePackageId, runtimePackageVersion));
}
}
// create a resolver that can be used to determine the API version for inbox assemblies
// since inbox assemblies are represented with placeholders we can remove the placeholders
// and use the netstandard reference assembly to determine the API version
var filesWithoutPlaceholders = GetPackageItems(packagePath)
.Where(f => !NuGetAssetResolver.IsPlaceholder(f));
NuGetAssetResolver resolverWithoutPlaceholders = new NuGetAssetResolver(RuntimeFile, filesWithoutPlaceholders);
string package = $"{PackageId}/{PackageVersion}";
foreach (var framework in Frameworks)
{
var runtimeIds = framework.GetMetadata("RuntimeIDs")?.Split(';');
NuGetFramework fx;
try
{
fx = FrameworkUtilities.ParseNormalized(framework.ItemSpec);
}
catch (Exception ex)
{
Log.LogError($"Could not parse Framework {framework.ItemSpec}. {ex}");
continue;
}
if (fx.Equals(NuGetFramework.UnsupportedFramework))
{
Log.LogError($"Did not recognize {framework.ItemSpec} as valid Framework.");
continue;
}
var compileAssets = resolver.ResolveCompileAssets(fx, PackageId);
bool hasCompileAsset, hasCompilePlaceHolder;
NuGetAssetResolver.ExamineAssets(Log, "Compile", package, fx.ToString(), compileAssets, out hasCompileAsset, out hasCompilePlaceHolder);
// start by making sure it has some asset available for compile
var isSupported = hasCompileAsset || hasCompilePlaceHolder;
if (!isSupported)
{
Log.LogMessage(LogImportance.Low, $"Skipping {fx} because it is not supported.");
continue;
}
foreach (var runtimeId in runtimeIds)
{
string target = String.IsNullOrEmpty(runtimeId) ? fx.ToString() : $"{fx}/{runtimeId}";
var runtimeAssets = resolver.ResolveRuntimeAssets(fx, runtimeId);
bool hasRuntimeAsset, hasRuntimePlaceHolder;
NuGetAssetResolver.ExamineAssets(Log, "Runtime", package, target, runtimeAssets, out hasRuntimeAsset, out hasRuntimePlaceHolder);
isSupported &= hasCompileAsset == hasRuntimeAsset;
isSupported &= hasCompilePlaceHolder == hasRuntimePlaceHolder;
if (!isSupported)
{
Log.LogMessage(LogImportance.Low, $"Skipping {fx} because it is not supported on {target}.");
break;
}
}
if (isSupported)
{
var supportedFramework = new TaskItem(framework.ItemSpec);
supportedFramework.SetMetadata("HarvestedFromPackage", package);
// set version
// first try the resolved compile asset for this package
var refAssm = compileAssets.FirstOrDefault(r => !NuGetAssetResolver.IsPlaceholder(r))?.Substring(PackageId.Length + 1);
if (refAssm == null)
{
// if we didn't have a compile asset it means this framework is supported inbox with a placeholder
// resolve the assets without placeholders to pick up the netstandard reference assembly.
compileAssets = resolverWithoutPlaceholders.ResolveCompileAssets(fx);
refAssm = compileAssets.FirstOrDefault(r => !NuGetAssetResolver.IsPlaceholder(r));
}
string version = "unknown";
if (refAssm != null)
{
version = VersionUtility.GetAssemblyVersion(Path.Combine(packagePath, refAssm))?.ToString() ?? version;
}
supportedFramework.SetMetadata("Version", version);
Log.LogMessage($"Validating version {version} for {supportedFramework.ItemSpec} because it was supported by {PackageId}/{PackageVersion}.");
supportedFrameworks.Add(supportedFramework);
}
}
SupportedFrameworks = supportedFrameworks.ToArray();
}
private static string[] includedExtensions = new[] { ".dll", ".xml", "._" };
public void HarvestFilesFromPackage()
{
string pathToPackage = Path.Combine(PackagesFolder, PackageId, PackageVersion);
if (!Directory.Exists(pathToPackage))
{
Log.LogError($"Cannot harvest from package {PackageId}/{PackageVersion} because {pathToPackage} does not exist.");
return;
}
var harvestedFiles = new List<ITaskItem>();
foreach (var extension in includedExtensions)
{
foreach (var packageFile in Directory.EnumerateFiles(pathToPackage, $"*{extension}", SearchOption.AllDirectories))
{
string packagePath = packageFile.Substring(pathToPackage.Length + 1).Replace('\\', '/');
if (ShouldExclude(packagePath))
{
Log.LogMessage($"Preferring live build of package path {packagePath} over the asset from last stable package.");
continue;
}
else
{
Log.LogMessage($"Including {packagePath} from last stable package {PackageId}/{PackageVersion}.");
}
var item = new TaskItem(packageFile);
var targetPath = Path.GetDirectoryName(packagePath).Replace('\\', '/');
item.SetMetadata("TargetPath", targetPath);
item.SetMetadata("TargetFramework", GetTargetFrameworkFromPackagePath(targetPath));
item.SetMetadata("HarvestDependencies", "true");
item.SetMetadata("IsReferenceAsset", IsReferencePackagePath(targetPath).ToString());
var assemblyVersion = VersionUtility.GetAssemblyVersion(packageFile);
if (assemblyVersion != null)
{
item.SetMetadata("AssemblyVersion", assemblyVersion.ToString());
}
harvestedFiles.Add(item);
}
}
Files = harvestedFiles.ToArray();
}
private string[] _pathsToExclude = null;
private bool ShouldExclude(string packagePath)
{
if (_pathsToExclude == null)
{
_pathsToExclude = PathsToExclude.NullAsEmpty().Select(EnsureDirectory).ToArray();
}
return ShouldSuppress(packagePath) ||
_pathsToExclude.Any(p => packagePath.StartsWith(p, StringComparison.OrdinalIgnoreCase));
}
private string[] _pathsToSuppress = null;
private bool ShouldSuppress(string packagePath)
{
if (_pathsToSuppress == null)
{
_pathsToSuppress = PathsToSuppress.NullAsEmpty().Select(EnsureDirectory).ToArray();
}
return _pathsToSuppress.Any(p => packagePath.StartsWith(p, StringComparison.OrdinalIgnoreCase));
}
private static string EnsureDirectory(string source)
{
string result;
if (source.Length < 1 || source[source.Length - 1] == '\\' || source[source.Length - 1] == '/')
{
// already have a directory
result = source;
}
else
{
// could be a directory or file
var extension = Path.GetExtension(source);
if (extension != null && extension.Length > 0 && includedExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
{
// it's a file, find the directory portion
var fileName = Path.GetFileName(source);
if (fileName.Length != source.Length)
{
result = source.Substring(0, source.Length - fileName.Length);
}
else
{
// no directory portion, just return as-is
result = source;
}
}
else
{
// it's a directory, add the slash
result = source + '/';
}
}
return result;
}
private static string GetTargetFrameworkFromPackagePath(string path)
{
var parts = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (parts.Length >= 2)
{
if (parts[0].Equals("lib", StringComparison.OrdinalIgnoreCase) ||
parts[0].Equals("ref", StringComparison.OrdinalIgnoreCase))
{
return parts[1];
}
if (parts.Length >= 4 &&
parts[0].Equals("runtimes", StringComparison.OrdinalIgnoreCase) &&
parts[2].Equals("lib", StringComparison.OrdinalIgnoreCase))
{
return parts[3];
}
}
return null;
}
private static bool IsReferencePackagePath(string path)
{
return path.StartsWith("ref", StringComparison.OrdinalIgnoreCase);
}
private IEnumerable<string> GetPackageItems(string packagesFolder, string packageId, string packageVersion)
{
string packageFolder = Path.Combine(packagesFolder, packageId, packageVersion);
return GetPackageItems(packageFolder);
}
private IEnumerable<string> GetPackageItems(string packageFolder)
{
return Directory.EnumerateFiles(packageFolder, "*", SearchOption.AllDirectories)
.Select(f => f.Substring(packageFolder.Length + 1).Replace('\\', '/'))
.Where(f => !ShouldSuppress(f));
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Xml.Serialization;
namespace SIL.Windows.Forms
{
/// ----------------------------------------------------------------------------------------
/// <summary>
/// Encapsulates a font object that can be serialized.
/// </summary>
/// ----------------------------------------------------------------------------------------
[XmlType("Font")]
public class SerializableFont
{
[XmlAttribute]
public string Name ;
[XmlAttribute]
public float Size = 10;
[XmlAttribute]
public bool Bold;
[XmlAttribute]
public bool Italic;
/// ------------------------------------------------------------------------------------
public SerializableFont()
{
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Intializes a new Serializable font object from the specified font.
/// </summary>
/// ------------------------------------------------------------------------------------
public SerializableFont(Font fnt)
{
Font = fnt;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets a font object based on the SerializableFont's settings or sets the
/// SerializableFont's settings.
/// </summary>
/// ------------------------------------------------------------------------------------
[XmlIgnore]
public Font Font
{
get
{
if (Name == null)
return null;
FontStyle style = FontStyle.Regular;
if (Bold)
style = FontStyle.Bold;
if (Italic)
style |= FontStyle.Italic;
return FontHelper.MakeFont(Name, (int)Size, style);
}
set
{
if (value == null)
Name = null;
else
{
Name = value.Name;
Size = value.SizeInPoints;
Bold = value.Bold;
Italic = value.Italic;
}
}
}
}
/// ----------------------------------------------------------------------------------------
/// <summary>
/// Misc. font helper methods.
/// </summary>
/// ----------------------------------------------------------------------------------------
public static class FontHelper
{
/// --------------------------------------------------------------------------------
static FontHelper()
{
ResetFonts();
}
/// ------------------------------------------------------------------------------------
public static void ResetFonts()
{
UIFont = (Font)SystemFonts.MenuFont.Clone();
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Determines if the specified font is installed on the computer.
/// </summary>
/// ------------------------------------------------------------------------------------
public static bool FontInstalled(string fontName)
{
fontName = fontName.ToLower();
using (var installedFonts = new InstalledFontCollection())
{
if (installedFonts.Families.Any(f => f.Name.ToLower() == fontName))
return true;
}
return false;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Creates a new font object that is a regualar style derivative of the specified
/// font, having the specified size.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Font MakeRegularFontDerivative(Font fnt, float size)
{
return MakeFont((fnt ?? UIFont).FontFamily.Name, size, FontStyle.Regular);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Creates a string containing three pieces of information about the specified font:
/// the name, size and style.
/// </summary>
/// ------------------------------------------------------------------------------------
public static string FontToString(Font fnt)
{
if (fnt == null)
return null;
return fnt.Name + ", " + fnt.SizeInPoints + ", " + fnt.Style;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Creates a font object with the specified properties. If an error occurs while
/// making the font (e.g. because the font doesn't support a particular style) a
/// fallback scheme is used.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Font MakeFont(string fontString)
{
if (fontString == null)
return SystemFonts.DefaultFont;
var name = SystemFonts.DefaultFont.FontFamily.Name;
var size = SystemFonts.DefaultFont.SizeInPoints;
var style = FontStyle.Regular;
var parts = fontString.Split(',');
if (parts.Length > 0)
name = parts[0];
if (parts.Length > 1)
float.TryParse(parts[1], out size);
if (parts.Length > 2)
{
try
{
style = (FontStyle)Enum.Parse(typeof(FontStyle), parts[2]);
}
catch { }
}
return MakeFont(name, size, style);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Creates a font object with the specified properties. If an error occurs while
/// making the font (e.g. because the font doesn't support a particular style) a
/// fallback scheme is used.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Font MakeFont(Font fnt, float size, FontStyle style)
{
return MakeFont(fnt.FontFamily.Name, size, style);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Creates a font object with the specified properties. If an error occurs while
/// making the font (e.g. because the font doesn't support a particular style) a
/// fallback scheme is used.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Font MakeFont(Font fnt, float size)
{
return MakeFont(fnt.FontFamily.Name, size, fnt.Style);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Creates a font object with the specified properties. If an error occurs while
/// making the font (e.g. because the font doesn't support a particular style) a
/// fallback scheme is used.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Font MakeFont(Font fnt, FontStyle style)
{
return MakeFont(fnt.FontFamily.Name, fnt.SizeInPoints, style);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Creates a font object with the specified properties. If an error occurs while
/// making the font (e.g. because the font doesn't support a particular style) a
/// fallback scheme is used.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Font MakeFont(string fontName, float size, FontStyle style)
{
// On Mono there is an 139 exit code if we pass a reference to the FontFamily
// to the Font constructor, but not if we pass the FontFamily.Name.
try
{
string familyName = null;
bool supportsStyle = false;
// on Linux it is possible to get multiple font families with the same name
foreach (var family in FontFamily.Families.Where(f => f.Name == fontName))
{
// if the font supports the requested style, use it now
if (family.IsStyleAvailable(style))
return new Font(family.Name, size, style, GraphicsUnit.Point);
// keep looking if the font has the correct name, but does not support the desired style
familyName = family.Name;
}
// if the requested font was not found, use the default font
if (string.IsNullOrEmpty(familyName))
{
familyName = UIFont.FontFamily.Name;
supportsStyle = UIFont.FontFamily.IsStyleAvailable(style);
}
return supportsStyle
? new Font(familyName, size, style, GraphicsUnit.Point)
: new Font(familyName, size, GraphicsUnit.Point);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
/// --------------------------------------------------------------------------------
public static bool GetSupportsRegular(string fontName)
{
return GetSupportsStyle(fontName, FontStyle.Regular);
}
/// --------------------------------------------------------------------------------
public static bool GetSupportsBold(string fontName)
{
return GetSupportsStyle(fontName, FontStyle.Bold);
}
/// --------------------------------------------------------------------------------
public static bool GetSupportsItalic(string fontName)
{
return GetSupportsStyle(fontName, FontStyle.Italic);
}
/// --------------------------------------------------------------------------------
public static bool GetSupportsStyle(string fontName, FontStyle style)
{
var family = FontFamily.Families.SingleOrDefault(f => f.Name == fontName);
return (family != null && family.IsStyleAvailable(style));
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Compares the font face name, size and style of two fonts.
/// </summary>
/// --------------------------------------------------------------------------------
public static bool AreFontsSame(Font x, Font y)
{
if (x == null || y == null)
return false;
return (x.Name == y.Name && x.Size.Equals(y.Size) && x.Style == y.Style);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the desired font for most UI elements.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Font UIFont { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.